diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 00000000..35049cbc --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +xtask = "run --package xtask --" diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 319dd7db..00000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,11 +0,0 @@ -version: 2 - -updates: - - package-ecosystem: "gomod" - directory: "/" - schedule: - interval: daily - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "weekly" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index b89e5b09..00000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,19 +0,0 @@ -## Related Issues - - -## Description - - -## Motivation and Context - - - -## How Has This Been Tested? - - - - -# Checklist -- [ ] Tests -- [ ] Documentation -- [ ] Linting \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/workflows/ISSUE_TEMPLATE/bug_report.md similarity index 86% rename from .github/ISSUE_TEMPLATE/bug_report.md rename to .github/workflows/ISSUE_TEMPLATE/bug_report.md index 1b12ab09..7768a8cd 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/workflows/ISSUE_TEMPLATE/bug_report.md @@ -1,28 +1,35 @@ --- name: Bug Report -about: Report a bug encountered +about: Report a bug encountered labels: bug --- ## Expected Behavior + ## Current Behavior + ## Possible Solution + ## Steps to Reproduce + + 1. 2. 3. 4. ## Context + ## Specifications - - Version: `$ teller version` - - Platform: \ No newline at end of file + +- Version: `$ teller version` +- Platform: diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/workflows/ISSUE_TEMPLATE/feature_request.md similarity index 99% rename from .github/ISSUE_TEMPLATE/feature_request.md rename to .github/workflows/ISSUE_TEMPLATE/feature_request.md index ed1f5da4..c4636146 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/workflows/ISSUE_TEMPLATE/feature_request.md @@ -7,10 +7,13 @@ labels: "enhancement" ## Feature Request **Is your feature request related to a problem? Please describe.** + **Describe the solution you'd like** + **Describe alternatives you've considered** + diff --git a/.github/workflows/ISSUE_TEMPLATE/general.md b/.github/workflows/ISSUE_TEMPLATE/general.md new file mode 100644 index 00000000..dbc7e6dc --- /dev/null +++ b/.github/workflows/ISSUE_TEMPLATE/general.md @@ -0,0 +1,5 @@ +contact_links: + +- name: Questions, unconfirmed bugs and ideas + url: https://github.com/tellerops/teller/discussions/new + about: Please post questions, unconfirmed bugs and ideas in discussions. diff --git a/.github/ISSUE_TEMPLATE/new_provider.md b/.github/workflows/ISSUE_TEMPLATE/new_provider.md similarity index 76% rename from .github/ISSUE_TEMPLATE/new_provider.md rename to .github/workflows/ISSUE_TEMPLATE/new_provider.md index 8bf3a44e..d71fc469 100644 --- a/.github/ISSUE_TEMPLATE/new_provider.md +++ b/.github/workflows/ISSUE_TEMPLATE/new_provider.md @@ -7,8 +7,9 @@ labels: "new-provider" ## New Provider Request ## Details -- Name: + +- Name: - URL: - Modes: (read/write/read+write) -- GitHub projects: -- API Documentation: +- GitHub projects: +- API Documentation: diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 00000000..538fbd22 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,106 @@ +name: Build +on: + pull_request: + push: + branches: + - master + tags-ignore: + - "v[0-9]+.[0-9]+.[0-9]+" + # you can enable a schedule to build + # schedule: + # - cron: '00 01 * * *' +jobs: + test: + name: Test Suite + strategy: + fail-fast: true + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + rust: [stable] + runs-on: ${{ matrix.os }} + steps: + - name: Checkout sources + uses: actions/checkout@v4 + + - name: Install stable toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: ${{ matrix.rust }} + override: true + + - uses: Swatinem/rust-cache@v2 + + - name: Run cargo test + uses: actions-rs/cargo@v1 + with: + command: test + args: --all-features --all + + coverage: + name: Coverage + strategy: + matrix: + os: [ubuntu-latest] + rust: [stable] + runs-on: ${{ matrix.os }} + steps: + - name: Checkout sources + uses: actions/checkout@v4 + + - name: Install stable toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: ${{ matrix.rust }} + override: true + components: llvm-tools-preview + + - uses: Swatinem/rust-cache@v2 + + - name: Download grcov + run: | + mkdir -p "${HOME}/.local/bin" + curl -sL https://github.com/mozilla/grcov/releases/download/v0.8.10/grcov-x86_64-unknown-linux-gnu.tar.bz2 | tar jxf - -C "${HOME}/.local/bin" + echo "$HOME/.local/bin" >> $GITHUB_PATH + + - name: Run xtask coverage + uses: actions-rs/cargo@v1 + with: + command: xtask + args: coverage + + - name: Upload to codecov.io + uses: codecov/codecov-action@v3 + with: + files: coverage/*.lcov + + lints: + name: Lints + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v4 + with: + submodules: true + + - name: Install stable toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + override: true + components: rustfmt, clippy + + - uses: Swatinem/rust-cache@v2 + + - name: Run cargo fmt + uses: actions-rs/cargo@v1 + with: + command: fmt + args: --all -- --check + + - name: Run cargo clippy + uses: actions-rs/cargo@v1 + with: + command: clippy + args: --all-features -- -D warnings -W clippy::pedantic -W clippy::nursery -W rust-2018-idioms diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml deleted file mode 100644 index aa5b99a3..00000000 --- a/.github/workflows/ci.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: CI - -on: - push: - branches: - - master - pull_request: - -jobs: - build: - name: Build - runs-on: ${{ matrix.os }} - strategy: - matrix: - os: [ubuntu-latest, macos-latest] - go: ['1.18'] - env: - VERBOSE: 1 - GOFLAGS: -mod=readonly - GOPROXY: https://proxy.golang.org - - steps: - - name: Set up Go - uses: actions/setup-go@v3 - with: - go-version: ${{ matrix.go }} - - - name: Checkout code - uses: actions/checkout@v3 - - - name: golangci-lint - uses: golangci/golangci-lint-action@v3 - with: - version: v1.45.0 - args: --timeout 5m0s - - - name: Test - run: make test - - - name: E2E - run: make e2e diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml deleted file mode 100644 index 71b55147..00000000 --- a/.github/workflows/release.yaml +++ /dev/null @@ -1,26 +0,0 @@ -name: Release -on: - push: - tags: - - 'v*.*.*' - - 'v*.*.*-rc*' -jobs: - goreleaser: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v3 - - - name: Set up Go - uses: actions/setup-go@v3 - with: - go-version: 1.18 - - - name: GoReleaser - uses: goreleaser/goreleaser-action@v2 - with: - version: v1.7.0 - args: release --rm-dist - env: - GITHUB_TOKEN: ${{ secrets.GORELEASER_GITHUB_TOKEN }} - GORELEASER_GITHUB_TOKEN: ${{ secrets.GORELEASER_GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..accb493c --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,212 @@ +name: Release +on: + # schedule: + # - cron: '0 0 * * *' # midnight UTC + + push: + tags: + - "v[0-9]+.[0-9]+.[0-9]+" + ## - release + +# 1. set up: +# secrets.COMMITTER_TOKEN - for pushing update to brew tap +# first placeholder formula in brew tap - for updating + +# 2. fill these in and you're done. +env: + BIN_NAME: teller + PROJECT_NAME: teller + REPO_NAME: tellerops/teller + +jobs: + test: + name: Test Suite + strategy: + fail-fast: true + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + rust: [stable] + runs-on: ${{ matrix.os }} + steps: + - name: Checkout sources + uses: actions/checkout@v4 + + - name: Install stable toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: ${{ matrix.rust }} + override: true + + - uses: Swatinem/rust-cache@v2 + + - name: Run cargo test + uses: actions-rs/cargo@v1 + with: + command: test + args: --all-features --all + dist: + name: Dist + runs-on: ${{ matrix.os }} + needs: test + strategy: + fail-fast: false # don't fail other jobs if one fails + matrix: + build: [x86_64-linux, aarch64-macos, x86_64-macos, x86_64-windows] #, x86_64-win-gnu, win32-msvc aarch64-linux, + include: + - build: x86_64-linux + os: ubuntu-20.04 + rust: stable + target: x86_64-unknown-linux-gnu + cross: false + + - build: x86_64-macos + os: macos-latest + rust: stable + target: x86_64-apple-darwin + + - build: aarch64-macos + os: macos-latest + rust: stable + target: aarch64-apple-darwin + + - build: x86_64-windows + os: windows-2019 + rust: stable + target: x86_64-pc-windows-msvc + + # - build: aarch64-macos + # os: macos-latest + # rust: stable + # target: aarch64-apple-darwin + # - build: x86_64-win-gnu + # os: windows-2019 + # rust: stable-x86_64-gnu + # target: x86_64-pc-windows-gnu + # - build: win32-msvc + # os: windows-2019 + # rust: stable + # target: i686-pc-windows-msvc + + steps: + - name: Checkout sources + uses: actions/checkout@v2 + with: + submodules: true + + - uses: actions/setup-node@v4 + with: + node-version: 18 + + - name: Install ${{ matrix.rust }} toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: ${{ matrix.rust }} + target: ${{ matrix.target }} + override: true + + - name: Install OpenSSL + if: matrix.build == 'aarch64-linux' + run: sudo apt-get install libssl-dev pkg-config + + - name: Build release binary + uses: actions-rs/cargo@v1 + with: + use-cross: ${{ matrix.cross }} + command: build + args: --release --locked --target ${{ matrix.target }} + + - name: Strip release binary (linux and macos) + if: matrix.build == 'x86_64-linux' || matrix.build == 'x86_64-macos' + run: strip "target/${{ matrix.target }}/release/$BIN_NAME" + + - name: Strip release binary (arm) + if: matrix.build == 'aarch64-linux' + run: | + docker run --rm -v \ + "$PWD/target:/target:Z" \ + rustembedded/cross:${{ matrix.target }} \ + aarch64-linux-gnu-strip \ + /target/${{ matrix.target }}/release/$BIN_NAME + + - name: Build archive + shell: bash + run: | + rm -rf dist + mkdir dist + if [ "${{ matrix.os }}" = "windows-2019" ]; then + cp "target/${{ matrix.target }}/release/$BIN_NAME.exe" "dist/" + else + cp "target/${{ matrix.target }}/release/$BIN_NAME" "dist/" + fi + + - uses: actions/upload-artifact@v2.2.4 + with: + name: bins-${{ matrix.build }} + path: dist + + publish: + name: Publish + needs: [dist] + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v2 + with: + submodules: false + + - uses: actions/download-artifact@v2 + # with: + # path: dist + # - run: ls -al ./dist + - run: ls -al bins-* + + - name: Calculate tag name + run: | + name=dev + if [[ $GITHUB_REF == refs/tags/v* ]]; then + name=${GITHUB_REF:10} + fi + echo ::set-output name=val::$name + echo TAG=$name >> $GITHUB_ENV + id: tagname + + - name: Build archive + shell: bash + run: | + set -ex + + rm -rf tmp + mkdir tmp + rm -rf dist + mkdir dist + + for dir in bins-* ; do + platform=${dir#"bins-"} + if [[ $platform =~ "windows" ]]; then + exe=".exe" + fi + pkgname=$PROJECT_NAME-$platform + mkdir tmp/$pkgname + # cp LICENSE README.md tmp/$pkgname + mv bins-$platform/$BIN_NAME$exe tmp/$pkgname + chmod +x tmp/$pkgname/$BIN_NAME$exe + + if [ "$exe" = "" ]; then + tar cJf dist/$pkgname.tar.xz -C tmp $pkgname + else + (cd tmp && 7z a -r ../dist/$pkgname.zip $pkgname) + fi + done + + - name: Upload binaries to release + uses: svenstaro/upload-release-action@v2 + with: + repo_token: ${{ secrets.GITHUB_TOKEN }} + file: dist/* + file_glob: true + tag: ${{ steps.tagname.outputs.val }} + overwrite: true + + # homebrew: see rustwrap.yaml diff --git a/.github/workflows/spectral.yaml b/.github/workflows/spectral.yaml deleted file mode 100644 index 59b6c3f9..00000000 --- a/.github/workflows/spectral.yaml +++ /dev/null @@ -1,15 +0,0 @@ -name: Spectral -on: [push] -env: - SPECTRAL_DSN: ${{ secrets.SPECTRAL_DSN }} -jobs: - scan: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - name: Install Spectral - uses: spectralops/spectral-github-action@v1 - with: - spectral-dsn: ${{ secrets.SPECTRAL_DSN }} - - name: Spectral Scan - run: spectral scan \ No newline at end of file diff --git a/.gitignore b/.gitignore index 4f61f898..1ce36153 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,8 @@ -autobrew -dist/ -teller -.vscode/ -node_modules/ +git-hidden-file +git-ignored-file todo.txt -.teller.writecase.yml -coverage.out -fixtures/sync/target.env +/target +notes/ +tmp/ dist/ -.idea \ No newline at end of file +.DS_Store diff --git a/.golangci.yml b/.golangci.yml deleted file mode 100644 index 6bcf4abc..00000000 --- a/.golangci.yml +++ /dev/null @@ -1,124 +0,0 @@ -run: - go: 1.18 - -linters-settings: - dupl: - threshold: 100 - funlen: - lines: 100 - statements: 50 - goconst: - min-len: 2 - min-occurrences: 2 - gocritic: - enabled-tags: - - diagnostic - - experimental - - opinionated - - performance - - style - disabled-checks: - - dupImport # https://github.com/go-critic/go-critic/issues/845 - - ifElseChain - - octalLiteral - - whyNoLint - - wrapperFunc - - hugeParam - gocyclo: - min-complexity: 20 - golint: - min-confidence: 0 - gomnd: - settings: - mnd: - # don't include the "operation" and "assign" - checks: argument,case,condition,return - govet: - check-shadowing: true - lll: - line-length: 140 - maligned: - suggest-new: true - misspell: - locale: US - nolintlint: - allow-leading-space: true # don't require machine-readable nolint directives (i.e. with no leading space) - allow-unused: false # report any unused nolint directives - require-explanation: false # don't require an explanation for nolint directives - require-specific: false # don't require nolint directives to be specific about which linter is being skipped - -linters: - # please, do not use `enable-all`: it's deprecated and will be removed soon. - # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint - disable-all: true - enable: - - bodyclose - - deadcode - - dogsled - - dupl - - errcheck - - exportloopref - - exhaustive - - funlen - - gochecknoinits - - goconst - - gocritic - - gocyclo - - gofmt - - goimports - - golint - - gomnd - - goprintffuncname - - gosec - - gosimple - - govet - - ineffassign - - misspell - - nakedret - - noctx - - nolintlint - - rowserrcheck - - staticcheck - - structcheck - - stylecheck - - typecheck - - unconvert - - unparam - - unused - - varcheck - - # don't enable: - # - asciicheck - # - scopelint - # - gochecknoglobals - # - gocognit - # - godot - # - godox - # - goerr113 - # - interfacer - # - maligned - # - nestif - # - prealloc - # - testpackage - # - revive - # - wsl - -issues: - # Excluding configuration per-path, per-linter, per-text and per-source - exclude: - - 'bad syntax for struct tag key' - - 'bad syntax for struct tag pair' - - exclude-rules: - - path: _test\.go - linters: - - gomnd - - goconst - - gocritic - - gosec - - # https://github.com/go-critic/go-critic/issues/926 - - linters: - - gocritic - text: "unnecessaryDefer:" - diff --git a/.goreleaser.yml b/.goreleaser.yml deleted file mode 100644 index f457beb9..00000000 --- a/.goreleaser.yml +++ /dev/null @@ -1,47 +0,0 @@ -# This is an example .goreleaser.yml file with some sane defaults. -# Make sure to check the documentation at http://goreleaser.com -builds: - - env: - - CGO_ENABLED=0 - goos: - - linux - - windows - - darwin - - ldflags: - - -s -w -X main.version={{.Version}} -X main.commit={{.Commit}} -X main.date={{.Date}} - -archives: - - replacements: - darwin: Darwin - linux: Linux - windows: Windows - 386: i386 - amd64: x86_64 - -brews: - - - name: teller - tap: - owner: spectralops - name: homebrew-tap - token: "{{ .Env.GORELEASER_GITHUB_TOKEN }}" - description: A secret manager for developers - never leave your terminal for secrets - homepage: https://github.com/spectralops/teller - license: "Apache 2.0" - install: | - bin.install "teller" - ln_s bin/"teller", bin/"tlr" - -checksum: - name_template: 'checksums.txt' - -snapshot: - name_template: "{{ .Tag }}-next" - -changelog: - sort: asc - filters: - exclude: - - '^docs:' - - '^test:' diff --git a/.spectral/spectral.yaml b/.spectral/spectral.yaml deleted file mode 100644 index ab9ae2a3..00000000 --- a/.spectral/spectral.yaml +++ /dev/null @@ -1,26 +0,0 @@ -# Spectral -# -# Here's a result run of the initial configuration, placed in '.spectral/' -# -# $ spectral -# -# [sample] ------------- summary ------------- -# [sample] AWS0001 - No AWS secrets in python files. -# sp -# - /../spectral/src/sp.py (AKIA223) -# [sample] total 8 byte(s), 1 file(s), 1 match(es) in 14ms -# -# - -match_ignores: - ignores: - - rule_id: SENF033 - path: pkg/providers/mock_providers/keypass.kdbx - - rule_id: SENF073 - path: fixtures/sync/source.env - - rule_id: SENF073 - path: fixtures/mirror-drift/source.env - - rule_id: SENF073 - path: fixtures/sync/target2.env - - rule_id: SENF073 - path: fixtures/mirror-drift/target.env diff --git a/.teller.example.yml b/.teller.example.yml deleted file mode 100644 index cc1752b1..00000000 --- a/.teller.example.yml +++ /dev/null @@ -1,141 +0,0 @@ -project: billing_development - -# carry owner process environment into child's env: -# carry_env: true - -opts: - region: env:AWS_REGION - stage: development - -confirm: Are you sure you want to run for {{stage}}? - -providers: - dotenv: - env_sync: - path: ~/my-dot-env.env - env: - FOO_BAR: - path: ~/my-dot-env.env - redact_with: "**FOOBAR**" # optional - - # # requires an API key in: HEROKU_API_KEY (you can fetch from ~/.netrc) - # heroku: - # env_sync: - # path: drakula-app - # # env: - # # JVM_OPTS: - # # path: drakula-app - - # hashicorp_vault: - # # configures client from environment: - # # https://github.com/hashicorp/vault/blob/api/v1.0.4/api/client.go#L28 - # env_sync: # this grabs all the mapping from the keystore itself, JSON format. - # path: secret/data/{{stage}}/billing/web/env - # env: # yaml/json spec: map[string]KeyPath - # SMTP_PASS: - # path: secret/data/{{stage}}/wordpress - # field: smtp - - # aws_secretsmanager: - # # configures client from environment: - # # https://docs.aws.amazon.com/sdk-for-go/api/service/secretsmanager/#SecretsManager.GetSecretValue - # env_sync: - # path: {{stage}}/billing/web/env - # env: - # MG_KEY: - # path: {{stage}}/billing/mg_key - - # aws_ssm: - # # configures client from environment: - # # https://docs.aws.amazon.com/sdk-for-go/api/service/secretsmanager/#SecretsManager.GetSecretValue - # env: - # FOO_BAR: - # path: /{{stage}}/billing - # decrypt: true - - # google_secretmanager: - # # configures client from environment: - # # GOOGLE_APPLICATION_CREDENTIALS=client-credentials.json - # # https://cloud.google.com/secret-manager/docs/reference/libraries#setting_up_authentication - # env: - # MG_KEY: - # # need to supply the relevant version (versions/1) - # path: projects/xx84744xxxxx/secrets/MG_KEY/versions/1 - - # etcd: - # # configures client from environment: - # # ETCDCTL_ENDPOINTS - # # tls: - # # ETCDCTL_CA_FILE - # # ETCDCTL_CERT_FILE - # # ETCDCTL_KEY_FILE - # env_sync: - # # when full sync, takes last segment as the var name - # path: /{{stage}}/billing - # env: - # MG_KEY: - # path: /{{stage}}/billing/mg - - # consul: - # # configures client from environment: - # # CONSUL_HTTP_ADDR - # env_sync: - # path: redis/config - # env: - # SAVE_TIME: - # # need to supply the relevant version (versions/1) - # path: redis/config/savetime - - # cyberark_conjur: - # # configures client from environment: - # # CONJUR_AUTHN_LOGIN - # # CONJUR_AUTHN_API_KEY - # # also, configures client from file: - # # FILENAME: ~/.conjurrc - # # appliance_url: https://conjur.cyberark.com - # # account: cyberarkdemo - # # cert_file: /root/conjur-cyberarkdemo.pem - # env: - # DB_USERNAME: - # path: secrets/database/username - # DB_PASSWORD: - # path: secrets/database/passwords - - # 1password: - # env_sync: - # path: # Key title - # source: # 1Password token gen include access to multiple vault. to get the secrets you must add and vaultUUID. the field is mandatory - # env: - # FOO_BAR: - # path: # Key title - # source: # 1Password token gen include access to multiple vault. to get the secrets you must add and vaultUUID. the field is mandatory - # field: # The secret field to get. notesPlain, {label key}, password etc. - - # lastpass: - # # Configure via environment variables: - # # LASTPASS_USERNAME - # # LASTPASS_PASSWORD - # env_sync: - # path: # LastPass item ID - # env: - # FOO_BAR: - # path: # LastPass item ID - # #field: by default taking password property. in case you want other property un-mark this line and set the LastPass property name - - - -# # Configure via environment variables for integration: -# # CLOUDFLARE_API_KEY: Your Cloudflare api key. -# # CLOUDFLARE_API_EMAIL: Your email associated with the api key. -# # CLOUDFLARE_ACCOUNT_ID: Your account ID. -# -# cloudflare_workers_secrets: -# env_sync: -# source: script-id -# env: -# foo-secret: -# path: foo-secret -# source: script-id -# foo-secret2: -# path: foo-secret -# source: script-id \ No newline at end of file diff --git a/.teller.yml b/.teller.yml deleted file mode 100644 index ea802f73..00000000 --- a/.teller.yml +++ /dev/null @@ -1,42 +0,0 @@ - -project: teller - -# Set this if you want to carry over parent process' environment variables -carry_env: true - - -# -# Variables -# -# Feel free to add options here to be used as a variable throughout -# paths. -# -opts: - region: env:AWS_REGION # you can get env variables with the 'env:' prefix, for default values if env not found use comma. Example: env:AWS_REGION,{DEFAULT_VALUE} - stage: development - - -# -# Providers -# -providers: - -# dotenv: -## env_sync: -## path: ~/teller-env.env -# env: -# ANSIBLE_VAULT_PASSPHRASE: -# path: ~/teller-env.env - - # Configure via environment variables for integration: - # ANSIBLE_VAULT_PASSPHRASE: Ansible Vault Password - - ansible_vault: - env_sync: - path: ansible/vars/vault_{{stage}}.yml - - env: - KEY1: - path: ansible/vars/vault_{{stage}}.yml - NONEXIST_KEY: - path: ansible/vars/vault_{{stage}}.yml diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 5774a392..d04234b1 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,3 +1,3 @@ # Community Code of Conduct -Teller follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md). \ No newline at end of file +Teller follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 60b1a948..a03f237d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ # Contributing to the teller -Teller is open source and we love to receive contributions from our community — you! +Teller is open source and we love to receive contributions from our community — you! There are many ways to contribute, from writing tutorials or blog posts, @@ -23,7 +23,6 @@ or that there are particular issues that you should know about before implementi Generally, we require that you test any code you are adding or modifying. Once your changes are ready , submit for review and we will make sure will review it , your effort is much appreciated! - ### Workflow All feature development and most bug fixes hit the master branch first. @@ -31,4 +30,3 @@ Pull requests should be reviewed by someone with commit access. Once approved, the author of the pull request, or reviewer if the author does not have commit access, should "Squash and merge". - diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..d15d2a7c --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,4214 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "addr2line" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "aho-corasick" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" +dependencies = [ + "memchr", +] + +[[package]] +name = "android-tzdata" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d96bd03f33fe50a863e394ee9718a706f988b9079b20c3784fb726e7678b62fb" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8901269c6307e8d93993578286ac0edf7f195079ffff5ebdeea6a59ffb7e36bc" + +[[package]] +name = "anstyle-parse" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7" +dependencies = [ + "anstyle", + "windows-sys 0.52.0", +] + +[[package]] +name = "anyhow" +version = "1.0.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519" + +[[package]] +name = "async-trait" +version = "0.1.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "atty" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" +dependencies = [ + "hermit-abi 0.1.19", + "libc", + "winapi", +] + +[[package]] +name = "autocfg" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80" + +[[package]] +name = "aws-config" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2a89e0000cde82447155d64eeb71720b933b4396a6fbbebad3f8b4f88ca7b54" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-sdk-sso", + "aws-sdk-ssooidc", + "aws-sdk-sts", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "hex", + "http 0.2.12", + "hyper", + "ring", + "time", + "tokio", + "tracing", + "url 2.5.0", + "zeroize", +] + +[[package]] +name = "aws-credential-types" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e16838e6c9e12125face1c1eff1343c75e3ff540de98ff7ebd61874a89bcfeb9" +dependencies = [ + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "zeroize", +] + +[[package]] +name = "aws-runtime" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4963ac9ff2d33a4231b3806c1c69f578f221a9cabb89ad2bde62ce2b442c8a7" +dependencies = [ + "aws-credential-types", + "aws-sigv4", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 0.2.12", + "http-body 0.4.6", + "percent-encoding 2.3.1", + "pin-project-lite", + "tracing", + "uuid", +] + +[[package]] +name = "aws-sdk-secretsmanager" +version = "1.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d16072a660b3af14e897b80c7cc60df757d856303c09c6c24de27ff16a3a57df" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 0.2.12", + "once_cell", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-ssm" +version = "1.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "069188fa54b42552351e228c29db2fcc9b82045d1c7499e8bf66f307cad42853" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http 0.2.12", + "once_cell", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-sso" +version = "1.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32fcc572fd5c58489ec205ec3e4e5f7d63018898a485cbf922a462af496bc300" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "http 0.2.12", + "once_cell", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-ssooidc" +version = "1.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b6275fa8684a1192754221173b1f7a7c1260d6b0571cc2b8af09468eb0cffe5" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-types", + "bytes", + "http 0.2.12", + "once_cell", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sdk-sts" +version = "1.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30acd58272fd567e4853c5075d838be1626b59057e0249c9be5a1a7eb13bf70f" +dependencies = [ + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-query", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-types", + "aws-smithy-xml", + "aws-types", + "http 0.2.12", + "once_cell", + "regex-lite", + "tracing", +] + +[[package]] +name = "aws-sigv4" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d6f29688a4be9895c0ba8bef861ad0c0dac5c15e9618b9b7a6c233990fc263" +dependencies = [ + "aws-credential-types", + "aws-smithy-http", + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "form_urlencoded", + "hex", + "hmac", + "http 0.2.12", + "http 1.1.0", + "once_cell", + "percent-encoding 2.3.1", + "sha2", + "time", + "tracing", +] + +[[package]] +name = "aws-smithy-async" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62220bc6e97f946ddd51b5f1361f78996e704677afc518a4ff66b7a72ea1378c" +dependencies = [ + "futures-util", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "aws-smithy-http" +version = "0.60.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a7de001a1b9a25601016d8057ea16e31a45fdca3751304c8edf4ad72e706c08" +dependencies = [ + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "bytes-utils", + "futures-core", + "http 0.2.12", + "http-body 0.4.6", + "once_cell", + "percent-encoding 2.3.1", + "pin-project-lite", + "pin-utils", + "tracing", +] + +[[package]] +name = "aws-smithy-json" +version = "0.60.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4683df9469ef09468dad3473d129960119a0d3593617542b7d52086c8486f2d6" +dependencies = [ + "aws-smithy-types", +] + +[[package]] +name = "aws-smithy-query" +version = "0.60.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2fbd61ceb3fe8a1cb7352e42689cec5335833cd9f94103a61e98f9bb61c64bb" +dependencies = [ + "aws-smithy-types", + "urlencoding", +] + +[[package]] +name = "aws-smithy-runtime" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44e7945379821074549168917e89e60630647e186a69243248f08c6d168b975a" +dependencies = [ + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-runtime-api", + "aws-smithy-types", + "bytes", + "fastrand", + "h2", + "http 0.2.12", + "http-body 0.4.6", + "http-body 1.0.0", + "hyper", + "hyper-rustls 0.24.2", + "once_cell", + "pin-project-lite", + "pin-utils", + "rustls 0.21.10", + "tokio", + "tracing", +] + +[[package]] +name = "aws-smithy-runtime-api" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cc56a5c96ec741de6c5e6bf1ce6948be969d6506dfa9c39cffc284e31e4979b" +dependencies = [ + "aws-smithy-async", + "aws-smithy-types", + "bytes", + "http 0.2.12", + "http 1.1.0", + "pin-project-lite", + "tokio", + "tracing", + "zeroize", +] + +[[package]] +name = "aws-smithy-types" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abe14dceea1e70101d38fbf2a99e6a34159477c0fb95e68e05c66bd7ae4c3729" +dependencies = [ + "base64-simd", + "bytes", + "bytes-utils", + "futures-core", + "http 0.2.12", + "http 1.1.0", + "http-body 0.4.6", + "http-body 1.0.0", + "http-body-util", + "itoa", + "num-integer", + "pin-project-lite", + "pin-utils", + "ryu", + "serde", + "time", + "tokio", + "tokio-util", +] + +[[package]] +name = "aws-smithy-xml" +version = "0.60.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d123fbc2a4adc3c301652ba8e149bf4bc1d1725affb9784eb20c953ace06bf55" +dependencies = [ + "xmlparser", +] + +[[package]] +name = "aws-types" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a43b56df2c529fe44cb4d92bd64d0479883fb9608ff62daede4df5405381814" +dependencies = [ + "aws-credential-types", + "aws-smithy-async", + "aws-smithy-runtime-api", + "aws-smithy-types", + "http 0.2.12", + "rustc_version", + "tracing", +] + +[[package]] +name = "backtrace" +version = "0.3.71" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", +] + +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9475866fec1451be56a3c2400fd081ff546538961565ccb5b7142cbd22bc7a51" + +[[package]] +name = "base64-simd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "339abbe78e73178762e23bea9dfd08e697eb3f3301cd4be981c0f78ba5859195" +dependencies = [ + "outref", + "vsimd", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bollard" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d82e7850583ead5f8bbef247e2a3c37a19bd576e8420cd262a6711921827e1e5" +dependencies = [ + "base64 0.13.1", + "bollard-stubs", + "bytes", + "futures-core", + "futures-util", + "hex", + "http 0.2.12", + "hyper", + "hyperlocal", + "log", + "pin-project-lite", + "serde", + "serde_derive", + "serde_json", + "serde_urlencoded", + "thiserror", + "tokio", + "tokio-util", + "url 2.5.0", + "winapi", +] + +[[package]] +name = "bollard-stubs" +version = "1.42.0-rc.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed59b5c00048f48d7af971b71f800fdf23e858844a6f9e4d32ca72e9399e7864" +dependencies = [ + "serde", + "serde_with 1.14.0", +] + +[[package]] +name = "bstr" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05efc5cfd9110c8416e471df0e96702d58690178e206e61b7173706673c93706" +dependencies = [ + "memchr", + "serde", +] + +[[package]] +name = "bumpalo" +version = "3.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" + +[[package]] +name = "bytes" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" + +[[package]] +name = "bytes-utils" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35" +dependencies = [ + "bytes", + "either", +] + +[[package]] +name = "cc" +version = "1.0.94" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17f6e324229dc011159fcc089755d1e2e216a90d43a7dea6853ca740b84f35e7" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chrono" +version = "0.4.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" +dependencies = [ + "android-tzdata", + "iana-time-zone", + "num-traits", + "serde", + "windows-targets 0.52.5", +] + +[[package]] +name = "chrono-tz" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d59ae0466b83e838b81a54256c39d5d7c20b9d7daa10510a242d9b75abd5936e" +dependencies = [ + "chrono", + "chrono-tz-build", + "phf", +] + +[[package]] +name = "chrono-tz-build" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "433e39f13c9a060046954e0592a8d0a4bcb1040125cbf91cb8ee58964cfb350f" +dependencies = [ + "parse-zoneinfo", + "phf", + "phf_codegen", +] + +[[package]] +name = "clap" +version = "3.2.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea181bf566f71cb9a5d17a59e1871af638180a18fb0035c92ae62b705207123" +dependencies = [ + "atty", + "bitflags 1.3.2", + "clap_lex 0.2.4", + "indexmap 1.9.3", + "strsim 0.10.0", + "termcolor", + "textwrap", +] + +[[package]] +name = "clap" +version = "4.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bc066a67923782aa8515dbaea16946c5bcc5addbd668bb80af688e53e548a0" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" +dependencies = [ + "anstream", + "anstyle", + "clap_lex 0.7.0", + "strsim 0.11.1", +] + +[[package]] +name = "clap_derive" +version = "4.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528131438037fd55894f62d6e9f068b8f45ac57ffa77517819645d10aed04f64" +dependencies = [ + "heck 0.5.0", + "proc-macro2", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "clap_lex" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5" +dependencies = [ + "os_str_bytes", +] + +[[package]] +name = "clap_lex" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98cc8fbded0c607b7ba9dd60cd98df59af97e84d24e49c8557331cfc26d301ce" + +[[package]] +name = "colorchoice" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" + +[[package]] +name = "comfy-table" +version = "7.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b34115915337defe99b2aff5c2ce6771e5fbc4079f4b506301f5cf394c8452f7" +dependencies = [ + "crossterm", + "strum 0.26.2", + "strum_macros 0.26.2", + "unicode-width", +] + +[[package]] +name = "console" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb" +dependencies = [ + "encode_unicode", + "lazy_static", + "libc", + "unicode-width", + "windows-sys 0.52.0", +] + +[[package]] +name = "consulrs" +version = "0.1.0" +source = "git+https://github.com/jmgilman/consulrs?rev=a14fddbdf3695e2e338145134c4b42f823e03370#a14fddbdf3695e2e338145134c4b42f823e03370" +dependencies = [ + "async-trait", + "base64 0.13.1", + "consulrs_derive", + "derive_builder 0.10.2", + "http 0.2.12", + "reqwest", + "rustify", + "rustify_derive", + "serde", + "serde_json", + "serde_with 1.14.0", + "thiserror", + "tracing", + "url 2.5.0", +] + +[[package]] +name = "consulrs_derive" +version = "0.1.0" +source = "git+https://github.com/jmgilman/consulrs?rev=a14fddbdf3695e2e338145134c4b42f823e03370#a14fddbdf3695e2e338145134c4b42f823e03370" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", + "synstructure", +] + +[[package]] +name = "content_inspector" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7bda66e858c683005a53a9a60c69a4aca7eeaa45d124526e389f7aec8e62f38" +dependencies = [ + "memchr", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" + +[[package]] +name = "cpufeatures" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32c" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89254598aa9b9fa608de44b3ae54c810f0f06d755e24c50177f1f8f31ff50ce2" +dependencies = [ + "rustc_version", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "248e3bacc7dc6baa3b21e405ee045c3047101a49145e7e9eca583ab4c2ca5345" + +[[package]] +name = "crossterm" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df" +dependencies = [ + "bitflags 2.5.0", + "crossterm_winapi", + "libc", + "parking_lot", + "winapi", +] + +[[package]] +name = "crossterm_winapi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b" +dependencies = [ + "winapi", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "csv" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac574ff4d437a7b5ad237ef331c17ccca63c46479e5b5453eb8e10bb99a759fe" +dependencies = [ + "csv-core", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "csv-core" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efa2b3d7902f4b634a20cae3c9c4e6209dc4779feb6863329607560143efa70" +dependencies = [ + "memchr", +] + +[[package]] +name = "darling" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f2c43f534ea4b0b049015d00269734195e6d3f0f6635cb692251aca6f9f8b3c" +dependencies = [ + "darling_core 0.12.4", + "darling_macro 0.12.4", +] + +[[package]] +name = "darling" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c" +dependencies = [ + "darling_core 0.13.4", + "darling_macro 0.13.4", +] + +[[package]] +name = "darling" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b750cb3417fd1b327431a470f388520309479ab0bf5e323505daf0290cd3850" +dependencies = [ + "darling_core 0.14.4", + "darling_macro 0.14.4", +] + +[[package]] +name = "darling" +version = "0.20.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54e36fcd13ed84ffdfda6f5be89b31287cbb80c439841fe69e04841435464391" +dependencies = [ + "darling_core 0.20.8", + "darling_macro 0.20.8", +] + +[[package]] +name = "darling_core" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e91455b86830a1c21799d94524df0845183fa55bafd9aa137b01c7d1065fa36" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim 0.10.0", + "syn 1.0.109", +] + +[[package]] +name = "darling_core" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim 0.10.0", + "syn 1.0.109", +] + +[[package]] +name = "darling_core" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "109c1ca6e6b7f82cc233a97004ea8ed7ca123a9af07a8230878fcfda9b158bf0" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim 0.10.0", + "syn 1.0.109", +] + +[[package]] +name = "darling_core" +version = "0.20.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c2cf1c23a687a1feeb728783b993c4e1ad83d99f351801977dd809b48d0a70f" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim 0.10.0", + "syn 2.0.59", +] + +[[package]] +name = "darling_macro" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29b5acf0dea37a7f66f7b25d2c5e93fd46f8f6968b1a5d7a3e02e97768afc95a" +dependencies = [ + "darling_core 0.12.4", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "darling_macro" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" +dependencies = [ + "darling_core 0.13.4", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "darling_macro" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4aab4dbc9f7611d8b55048a3a16d2d010c2c8334e46304b40ac1cc14bf3b48e" +dependencies = [ + "darling_core 0.14.4", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "darling_macro" +version = "0.20.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a668eda54683121533a393014d8692171709ff57a7d61f187b6e782719f8933f" +dependencies = [ + "darling_core 0.20.8", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "deranged" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", + "serde", +] + +[[package]] +name = "derive_builder" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d13202debe11181040ae9063d739fa32cfcaaebe2275fe387703460ae2365b30" +dependencies = [ + "derive_builder_macro 0.10.2", +] + +[[package]] +name = "derive_builder" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d07adf7be193b71cc36b193d0f5fe60b918a3a9db4dad0449f57bcfd519704a3" +dependencies = [ + "derive_builder_macro 0.11.2", +] + +[[package]] +name = "derive_builder" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d67778784b508018359cbc8696edb3db78160bab2c2a28ba7f56ef6932997f8" +dependencies = [ + "derive_builder_macro 0.12.0", +] + +[[package]] +name = "derive_builder_core" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66e616858f6187ed828df7c64a6d71720d83767a7f19740b2d1b6fe6327b36e5" +dependencies = [ + "darling 0.12.4", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_builder_core" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f91d4cfa921f1c05904dc3c57b4a32c38aed3340cce209f3a6fd1478babafc4" +dependencies = [ + "darling 0.14.4", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_builder_core" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c11bdc11a0c47bc7d37d582b5285da6849c96681023680b906673c5707af7b0f" +dependencies = [ + "darling 0.14.4", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "derive_builder_macro" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58a94ace95092c5acb1e97a7e846b310cfbd499652f72297da7493f618a98d73" +dependencies = [ + "derive_builder_core 0.10.2", + "syn 1.0.109", +] + +[[package]] +name = "derive_builder_macro" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f0314b72bed045f3a68671b3c86328386762c93f82d98c65c3cb5e5f573dd68" +dependencies = [ + "derive_builder_core 0.11.2", + "syn 1.0.109", +] + +[[package]] +name = "derive_builder_macro" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebcda35c7a396850a55ffeac740804b40ffec779b98fffbb1738f4033f0ee79e" +dependencies = [ + "derive_builder_core 0.12.0", + "syn 1.0.109", +] + +[[package]] +name = "deunicode" +version = "1.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "322ef0094744e63628e6f0eb2295517f79276a5b342a4c2ff3042566ca181d4e" + +[[package]] +name = "dialoguer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59c6f2989294b9a498d3ad5491a79c6deb604617378e1cdc4bfc1c1361fe2f87" +dependencies = [ + "console", + "shell-words", + "tempfile", + "zeroize", +] + +[[package]] +name = "dialoguer" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "658bce805d770f407bc62102fca7c2c64ceef2fbcb2b8bd19d2765ce093980de" +dependencies = [ + "console", + "shell-words", + "tempfile", + "thiserror", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "dockertest" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5e89cd7c59faf3cf0e31369fce2382807dd794d4fcce6380adcefdf5987796" +dependencies = [ + "anyhow", + "async-trait", + "base64 0.13.1", + "bollard", + "dyn-clone", + "futures", + "lazy_static", + "rand", + "secrecy", + "serde", + "serde_json", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "dockertest-server" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74f2753acbecdf22c035603b1f40eed1a1106ab994c57d6e739ad88ea58dd01" +dependencies = [ + "derive_builder 0.11.2", + "dockertest", + "futures", + "rand", + "tempfile", + "type-map", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "duct" +version = "0.13.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4ab5718d1224b63252cd0c6f74f6480f9ffeb117438a2e0f5cf6d9a4798929c" +dependencies = [ + "libc", + "once_cell", + "os_pipe", + "shared_child", +] + +[[package]] +name = "dunce" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56ce8c6da7551ec6c462cbaf3bfbc75131ebbfa1c944aeaa9dab51ca1c5f0c3b" + +[[package]] +name = "dyn-clone" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d6ef0072f8a535281e4876be788938b528e9a1d43900b82c2569af7da799125" + +[[package]] +name = "either" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a47c1c47d2f5964e29c61246e81db715514cd532db6b5116a25ea3c03d6780a2" + +[[package]] +name = "encode_unicode" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" + +[[package]] +name = "encoding_rs" +version = "0.8.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "errno" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "exitcode" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de853764b47027c2e862a995c34978ffa63c1501f2e15f987ba11bd4f9bba193" + +[[package]] +name = "eyre" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd915d99f24784cdc19fd37ef22b97e3ff0ae756c7e492e9fbfe897d61e2aec" +dependencies = [ + "indenter", + "once_cell", +] + +[[package]] +name = "fastrand" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "658bd65b1cf4c852a3cc96f18a8ce7b5640f6b703f905c7d74532294c2a63984" + +[[package]] +name = "filetime" +version = "0.2.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ee447700ac8aa0b2f2bd7bc4462ad686ba06baa6727ac149a2d6277f0d240fd" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "windows-sys 0.52.0", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +dependencies = [ + "percent-encoding 2.3.1", +] + +[[package]] +name = "fs-err" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a41f105fe1d5b6b34b2055e3dc59bb79b46b48b2040b9e6c7b4b5de097aa41" +dependencies = [ + "autocfg", +] + +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + +[[package]] +name = "futures" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" + +[[package]] +name = "futures-executor" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" + +[[package]] +name = "futures-macro" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "futures-sink" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" + +[[package]] +name = "futures-task" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" + +[[package]] +name = "futures-util" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94b22e06ecb0110981051723910cbf0b5f5e09a2062dd7663334ee79a9d1286c" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "gimli" +version = "0.28.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" + +[[package]] +name = "glob" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" + +[[package]] +name = "globset" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57da3b9b5b85bd66f31093f8c408b90a74431672542466497dcbdfdc02034be1" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata 0.4.6", + "regex-syntax 0.8.3", +] + +[[package]] +name = "globwalk" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e3af942408868f6934a7b85134a3230832b9977cf66125df2f9edcfce4ddcc" +dependencies = [ + "bitflags 1.3.2", + "ignore", + "walkdir", +] + +[[package]] +name = "google-apis-common" +version = "6.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78672323eaeeb181cadd4d07333f1bcc8c2840a55b58afa8ab052664cd4a54ad" +dependencies = [ + "base64 0.13.1", + "chrono", + "http 0.2.12", + "hyper", + "itertools 0.10.5", + "mime", + "serde", + "serde_json", + "serde_with 2.3.3", + "tokio", + "tower-service", + "url 1.7.2", + "yup-oauth2", +] + +[[package]] +name = "google-secretmanager1" +version = "5.0.4+20240223" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5b806517ba1ad137eb05b445ae04343a7b6469e7167084ec4e3ae4e4ba4002f" +dependencies = [ + "anyhow", + "google-apis-common", + "http 0.2.12", + "hyper", + "hyper-rustls 0.24.2", + "itertools 0.10.5", + "mime", + "serde", + "serde_json", + "tokio", + "tower-service", + "url 1.7.2", +] + +[[package]] +name = "h2" +version = "0.3.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81fe527a889e1532da5c525686d96d4c2e74cdd345badf8dfef9f6b39dd5f5e8" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http 0.2.12", + "indexmap 2.2.6", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hashbrown" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "home" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "http" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" +dependencies = [ + "bytes", + "http 0.2.12", + "pin-project-lite", +] + +[[package]] +name = "http-body" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" +dependencies = [ + "bytes", + "http 1.1.0", +] + +[[package]] +name = "http-body-util" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0475f8b2ac86659c21b64320d5d653f9efe42acd2a4e560073ec61a155a34f1d" +dependencies = [ + "bytes", + "futures-core", + "http 1.1.0", + "http-body 1.0.0", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "humansize" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6cb51c9a029ddc91b07a787f1d86b53ccfa49b0e86688c946ebe8d3555685dd7" +dependencies = [ + "libm", +] + +[[package]] +name = "humantime" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" + +[[package]] +name = "humantime-serde" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57a3db5ea5923d99402c94e9feb261dc5ee9b4efa158b0315f788cf549cc200c" +dependencies = [ + "humantime", + "serde", +] + +[[package]] +name = "hyper" +version = "0.14.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf96e135eb83a2a8ddf766e426a841d8ddd7449d5f00d34ea02b41d2f19eef80" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http 0.2.12", + "http-body 0.4.6", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.24.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" +dependencies = [ + "futures-util", + "http 0.2.12", + "hyper", + "log", + "rustls 0.21.10", + "rustls-native-certs 0.6.3", + "tokio", + "tokio-rustls 0.24.1", +] + +[[package]] +name = "hyper-rustls" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "399c78f9338483cb7e630c8474b07268983c6bd5acee012e4211f9f7bb21b070" +dependencies = [ + "futures-util", + "http 0.2.12", + "hyper", + "log", + "rustls 0.22.3", + "rustls-native-certs 0.7.0", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.25.0", +] + +[[package]] +name = "hyper-tls" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" +dependencies = [ + "bytes", + "hyper", + "native-tls", + "tokio", + "tokio-native-tls", +] + +[[package]] +name = "hyperlocal" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fafdf7b2b2de7c9784f76e02c0935e65a8117ec3b768644379983ab333ac98c" +dependencies = [ + "futures-util", + "hex", + "hyper", + "pin-project", + "tokio", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38f09e0f0b1fb55fdee1f17470ad800da77af5186a1a76c026b679358b7e844e" +dependencies = [ + "matches", + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "idna" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "ignore" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b46810df39e66e925525d6e38ce1e7f6e1d208f72dc39757880fcb66e2c58af1" +dependencies = [ + "crossbeam-deque", + "globset", + "log", + "memchr", + "regex-automata 0.4.6", + "same-file", + "walkdir", + "winapi-util", +] + +[[package]] +name = "indenter" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce23b50ad8242c51a442f3ff322d56b02f08852c77e4c0b4d3fd684abc89c683" + +[[package]] +name = "indexmap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" +dependencies = [ + "autocfg", + "hashbrown 0.12.3", + "serde", +] + +[[package]] +name = "indexmap" +version = "2.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" +dependencies = [ + "equivalent", + "hashbrown 0.14.3", +] + +[[package]] +name = "insta" +version = "1.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eab73f58e59ca6526037208f0e98851159ec1633cf17b6cd2e1f2c3fd5d53cc" +dependencies = [ + "console", + "lazy_static", + "linked-hash-map", + "pest", + "pest_derive", + "regex", + "serde", + "similar", +] + +[[package]] +name = "ipnet" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" + +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" + +[[package]] +name = "js-sys" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.153" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" + +[[package]] +name = "libm" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" + +[[package]] +name = "linked-hash-map" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" + +[[package]] +name = "linux-raw-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" + +[[package]] +name = "lock_api" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" + +[[package]] +name = "matchers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" +dependencies = [ + "regex-automata 0.1.10", +] + +[[package]] +name = "matches" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" + +[[package]] +name = "memchr" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "miniz_oxide" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7" +dependencies = [ + "adler", +] + +[[package]] +name = "mio" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.48.0", +] + +[[package]] +name = "native-tls" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" +dependencies = [ + "lazy_static", + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "nu-ansi-term" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" +dependencies = [ + "overload", + "winapi", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +dependencies = [ + "hermit-abi 0.3.9", + "libc", +] + +[[package]] +name = "num_threads" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" +dependencies = [ + "libc", +] + +[[package]] +name = "object" +version = "0.32.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" + +[[package]] +name = "openssl" +version = "0.10.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" +dependencies = [ + "bitflags 2.5.0", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "openssl-sys" +version = "0.9.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c597637d56fbc83893a35eb0dd04b2b8e7a50c91e64e9493e398b5df4fb45fa2" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "os_pipe" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57119c3b893986491ec9aa85056780d3a0f3cf4da7cc09dd3650dbd6c6738fb9" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "os_str_bytes" +version = "6.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2355d85b9a3786f481747ced0e0ff2ba35213a1f9bd406ed906554d7af805a1" + +[[package]] +name = "outref" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4030760ffd992bef45b0ae3f10ce1aba99e33464c90d14dd7c039884963ddc7a" + +[[package]] +name = "overload" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" + +[[package]] +name = "parking_lot" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-targets 0.48.5", +] + +[[package]] +name = "parse-zoneinfo" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c705f256449c60da65e11ff6626e0c16a0a0b96aaa348de61376b249bc340f41" +dependencies = [ + "regex", +] + +[[package]] +name = "percent-encoding" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831" + +[[package]] +name = "percent-encoding" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" + +[[package]] +name = "pest" +version = "2.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "311fb059dee1a7b802f036316d790138c613a4e8b180c822e3925a662e9f0c95" +dependencies = [ + "memchr", + "thiserror", + "ucd-trie", +] + +[[package]] +name = "pest_derive" +version = "2.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f73541b156d32197eecda1a4014d7f868fd2bcb3c550d5386087cfba442bf69c" +dependencies = [ + "pest", + "pest_generator", +] + +[[package]] +name = "pest_generator" +version = "2.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c35eeed0a3fab112f75165fdc026b3913f4183133f19b49be773ac9ea966e8bd" +dependencies = [ + "pest", + "pest_meta", + "proc-macro2", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "pest_meta" +version = "2.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2adbf29bb9776f28caece835398781ab24435585fe0d4dc1374a61db5accedca" +dependencies = [ + "once_cell", + "pest", + "sha2", +] + +[[package]] +name = "phf" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_shared" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" + +[[package]] +name = "proc-macro2" +version = "1.0.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rayon" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "regex" +version = "1.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata 0.4.6", + "regex-syntax 0.8.3", +] + +[[package]] +name = "regex-automata" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" +dependencies = [ + "regex-syntax 0.6.29", +] + +[[package]] +name = "regex-automata" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax 0.8.3", +] + +[[package]] +name = "regex-lite" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30b661b2f27137bdbc16f00eda72866a92bb28af1753ffbd56744fb6e2e9cd8e" + +[[package]] +name = "regex-syntax" +version = "0.6.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" + +[[package]] +name = "regex-syntax" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" + +[[package]] +name = "reqwest" +version = "0.11.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62" +dependencies = [ + "base64 0.21.7", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http 0.2.12", + "http-body 0.4.6", + "hyper", + "hyper-rustls 0.24.2", + "hyper-tls", + "ipnet", + "js-sys", + "log", + "mime", + "native-tls", + "once_cell", + "percent-encoding 2.3.1", + "pin-project-lite", + "rustls 0.21.10", + "rustls-pemfile 1.0.4", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "system-configuration", + "tokio", + "tokio-native-tls", + "tokio-rustls 0.24.1", + "tower-service", + "url 2.5.0", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", + "winreg", +] + +[[package]] +name = "ring" +version = "0.17.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" +dependencies = [ + "cc", + "cfg-if", + "getrandom", + "libc", + "spin", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver", +] + +[[package]] +name = "rustify" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9c02e25271068de581e03ac3bb44db60165ff1a10d92b9530192ccb898bc706" +dependencies = [ + "anyhow", + "async-trait", + "bytes", + "http 0.2.12", + "reqwest", + "rustify_derive", + "serde", + "serde_json", + "serde_urlencoded", + "thiserror", + "tracing", + "url 2.5.0", +] + +[[package]] +name = "rustify_derive" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58135536c18c04f4634bedad182a3f41baf33ef811cc38a3ec7b7061c57134c8" +dependencies = [ + "proc-macro2", + "quote", + "regex", + "serde_urlencoded", + "syn 1.0.109", + "synstructure", +] + +[[package]] +name = "rustix" +version = "0.38.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89" +dependencies = [ + "bitflags 2.5.0", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustls" +version = "0.21.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d5a6813c0759e4609cd494e8e725babae6a2ca7b62a5536a13daaec6fcb7ba" +dependencies = [ + "log", + "ring", + "rustls-webpki 0.101.7", + "sct", +] + +[[package]] +name = "rustls" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99008d7ad0bbbea527ec27bddbc0e432c5b87d8175178cee68d2eec9c4a1813c" +dependencies = [ + "log", + "ring", + "rustls-pki-types", + "rustls-webpki 0.102.2", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00" +dependencies = [ + "openssl-probe", + "rustls-pemfile 1.0.4", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-native-certs" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fb85efa936c42c6d5fc28d2629bb51e4b2f4b8a5211e297d599cc5a093792" +dependencies = [ + "openssl-probe", + "rustls-pemfile 2.1.2", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pemfile" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +dependencies = [ + "base64 0.21.7", +] + +[[package]] +name = "rustls-pemfile" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" +dependencies = [ + "base64 0.22.0", + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecd36cc4259e3e4514335c4a138c6b43171a8d61d8f5c9348f9fc7529416f247" + +[[package]] +name = "rustls-webpki" +version = "0.101.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "rustls-webpki" +version = "0.102.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faaa0a62740bedb9b2ef5afa303da42764c012f743917351dc9a237ea1663610" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80af6f9131f277a45a3fba6ce8e2258037bb0477a67e610d3c1fe046ab31de47" + +[[package]] +name = "ryu" +version = "1.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534" +dependencies = [ + "windows-sys 0.52.0", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sct" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "seahash" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" + +[[package]] +name = "secrecy" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bd1c54ea06cfd2f6b63219704de0b9b4f72dcc2b8fdef820be6cd799780e91e" +dependencies = [ + "zeroize", +] + +[[package]] +name = "security-framework" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "770452e37cad93e0a50d5abc3990d2bc351c36d0328f86cefec2f2fb206eaef6" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f3cc463c0ef97e11c3461a9d3787412d30e8e7eb907c79180c4a57bf7c04ef" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d43fe69e652f3df9bdc2b85b2854a0825b86e4fb76bc44d945137d053639ca" + +[[package]] +name = "serde" +version = "1.0.198" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9846a40c979031340571da2545a4e5b7c4163bdae79b301d5f86d03979451fcc" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.198" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e88edab869b01783ba905e7d0153f9fc1a6505a96e4ad3018011eedb838566d9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "serde_json" +version = "1.0.116" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_spanned" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb3622f419d1296904700073ea6cc23ad690adbd66f13ea683df73298736f0c1" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_variant" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a0068df419f9d9b6488fdded3f1c818522cdea328e02ce9d9f147380265a432" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_with" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "678b5a069e50bf00ecd22d0cd8ddf7c236f68581b03db652061ed5eb13a312ff" +dependencies = [ + "serde", + "serde_with_macros 1.5.2", +] + +[[package]] +name = "serde_with" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07ff71d2c147a7b57362cead5e22f772cd52f6ab31cfcd9edcd7f6aeb2a0afbe" +dependencies = [ + "base64 0.13.1", + "chrono", + "hex", + "indexmap 1.9.3", + "serde", + "serde_json", + "serde_with_macros 2.3.3", + "time", +] + +[[package]] +name = "serde_with_macros" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e182d6ec6f05393cc0e5ed1bf81ad6db3a8feedf8ee515ecdd369809bcce8082" +dependencies = [ + "darling 0.13.4", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "serde_with_macros" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "881b6f881b17d13214e5d494c939ebab463d01264ce1811e9d4ac3a882e7695f" +dependencies = [ + "darling 0.20.8", + "proc-macro2", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.2.6", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + +[[package]] +name = "sha2" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shared_child" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0d94659ad3c2137fef23ae75b03d5241d633f8acded53d672decfa0e6e0caef" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "shell-words" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24188a676b6ae68c3b2cb3a01be17fbf7240ce009799bb56d5b1409051e78fde" + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook-registry" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +dependencies = [ + "libc", +] + +[[package]] +name = "similar" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa42c91313f1d05da9b26f267f931cf178d4aba455b4c4622dd7355eb80c6640" + +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + +[[package]] +name = "slab" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" +dependencies = [ + "autocfg", +] + +[[package]] +name = "slug" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd94acec9c8da640005f8e135a39fc0372e74535e6b368b7a04b875f784c8c4" +dependencies = [ + "deunicode", + "wasm-bindgen", +] + +[[package]] +name = "smallvec" +version = "1.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" + +[[package]] +name = "snapbox" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b831b6e80fbcd2889efa75b185d24005f85981431495f995292b25836519d84" +dependencies = [ + "anstream", + "anstyle", + "content_inspector", + "dunce", + "filetime", + "libc", + "normalize-line-endings", + "os_pipe", + "similar", + "snapbox-macros", + "tempfile", + "wait-timeout", + "walkdir", + "windows-sys 0.52.0", +] + +[[package]] +name = "snapbox-macros" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c4b838b05d15ab22754068cb73500b2f3b07bf09d310e15b27f88160f1de40" +dependencies = [ + "anstream", +] + +[[package]] +name = "socket2" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05ffd9c0a93b7543e062e759284fcf5f5e3b098501104bfbdde4d404db792871" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + +[[package]] +name = "stringreader" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913e7b03d63752f6cdd2df77da36749d82669904798fe8944b9ec3d23f159905" + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "strum" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" +dependencies = [ + "strum_macros 0.25.3", +] + +[[package]] +name = "strum" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d8cec3501a5194c432b2b7976db6b7d10ec95c253208b45f83f7136aa985e29" + +[[package]] +name = "strum_macros" +version = "0.25.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.59", +] + +[[package]] +name = "strum_macros" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6cf59daf282c0a494ba14fd21610a0325f9f90ec9d1231dea26bcb1d696c946" +dependencies = [ + "heck 0.4.1", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.59", +] + +[[package]] +name = "subtle" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6531ffc7b071655e4ce2e04bd464c4830bb585a61cabb96cf808f05172615a" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" + +[[package]] +name = "synstructure" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", + "unicode-xid", +] + +[[package]] +name = "system-configuration" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "teller-cli" +version = "0.1.0" +dependencies = [ + "clap 4.5.4", + "comfy-table", + "console", + "dialoguer 0.11.0", + "dockertest-server", + "exitcode", + "eyre", + "fs-err", + "insta", + "proc-macro2", + "serde", + "serde_derive", + "serde_json", + "serde_yaml", + "strum 0.25.0", + "teller-core", + "teller-providers", + "thiserror", + "tokio", + "tracing", + "tracing-subscriber", + "tracing-tree", + "trycmd", +] + +[[package]] +name = "teller-core" +version = "0.1.0" +dependencies = [ + "aho-corasick", + "csv", + "duct", + "fs-err", + "ignore", + "insta", + "lazy_static", + "serde", + "serde_derive", + "serde_json", + "serde_variant", + "serde_yaml", + "shell-words", + "stringreader", + "strum 0.25.0", + "teller-providers", + "tera", + "thiserror", + "unicode-width", +] + +[[package]] +name = "teller-providers" +version = "0.1.0" +dependencies = [ + "async-trait", + "aws-config", + "aws-sdk-secretsmanager", + "aws-sdk-ssm", + "consulrs", + "crc32c", + "dockertest-server", + "dotenvy", + "fs-err", + "google-secretmanager1", + "home", + "insta", + "lazy_static", + "rustify", + "serde", + "serde_derive", + "serde_json", + "serde_variant", + "serde_yaml", + "strum 0.25.0", + "thiserror", + "tokio", + "vaultrs", +] + +[[package]] +name = "tempfile" +version = "3.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" +dependencies = [ + "cfg-if", + "fastrand", + "rustix", + "windows-sys 0.52.0", +] + +[[package]] +name = "tera" +version = "1.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "970dff17c11e884a4a09bc76e3a17ef71e01bb13447a11e85226e254fe6d10b8" +dependencies = [ + "chrono", + "chrono-tz", + "globwalk", + "humansize", + "lazy_static", + "percent-encoding 2.3.1", + "pest", + "pest_derive", + "rand", + "regex", + "serde", + "serde_json", + "slug", + "unic-segment", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "textwrap" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d434d3f8967a09480fb04132ebe0a3e088c173e6d0ee7897abbdf4eab0f8b9" + +[[package]] +name = "thiserror" +version = "1.0.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03468839009160513471e86a034bb2c5c0e4baae3b43f79ffc55c4a5427b3297" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "thread_local" +version = "1.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" +dependencies = [ + "cfg-if", + "once_cell", +] + +[[package]] +name = "time" +version = "0.3.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" +dependencies = [ + "deranged", + "itoa", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" + +[[package]] +name = "time-macros" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinyvec" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787" +dependencies = [ + "backtrace", + "bytes", + "libc", + "mio", + "num_cpus", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.48.0", +] + +[[package]] +name = "tokio-macros" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" +dependencies = [ + "rustls 0.21.10", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" +dependencies = [ + "rustls 0.22.3", + "rustls-pki-types", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5419f34732d9eb6ee4c3578b7989078579b7f039cbbb9ca2c4da015749371e15" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", + "tracing", +] + +[[package]] +name = "toml_datetime" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3550f4e9685620ac18a50ed434eb3aec30db8ba93b0287467bca5826ea25baf1" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e40bb779c5187258fd7aad0eb68cb8706a0a81fa712fbea808ab43c4b8374c4" +dependencies = [ + "indexmap 2.2.6", + "serde", + "serde_spanned", + "toml_datetime", + "winnow", +] + +[[package]] +name = "tower-service" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" + +[[package]] +name = "tracing" +version = "0.1.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.59", +] + +[[package]] +name = "tracing-core" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f751112709b4e791d8ce53e32c4ed2d353565a795ce84da2285393f41557bdf2" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log 0.2.0", +] + +[[package]] +name = "tracing-tree" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec6adcab41b1391b08a308cc6302b79f8095d1673f6947c2dc65ffb028b0b2d" +dependencies = [ + "nu-ansi-term", + "tracing-core", + "tracing-log 0.1.4", + "tracing-subscriber", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "trycmd" +version = "0.14.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d41014f614932fff67cd3b780e0eb0ecb14e698a831a0e555ef2a5137be968d5" +dependencies = [ + "glob", + "humantime", + "humantime-serde", + "rayon", + "serde", + "shlex", + "snapbox", + "toml_edit", +] + +[[package]] +name = "type-map" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "deb68604048ff8fa93347f02441e4487594adc20bb8a084f9e564d2b827a0a9f" +dependencies = [ + "rustc-hash", +] + +[[package]] +name = "typenum" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" + +[[package]] +name = "ucd-trie" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" + +[[package]] +name = "unic-char-property" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" +dependencies = [ + "unic-char-range", +] + +[[package]] +name = "unic-char-range" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" + +[[package]] +name = "unic-common" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" + +[[package]] +name = "unic-segment" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4ed5d26be57f84f176157270c112ef57b86debac9cd21daaabbe56db0f88f23" +dependencies = [ + "unic-ucd-segment", +] + +[[package]] +name = "unic-ucd-segment" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2079c122a62205b421f499da10f3ee0f7697f012f55b675e002483c73ea34700" +dependencies = [ + "unic-char-property", + "unic-char-range", + "unic-ucd-version", +] + +[[package]] +name = "unic-ucd-version" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" +dependencies = [ + "unic-common", +] + +[[package]] +name = "unicode-bidi" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "unicode-normalization" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-width" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" + +[[package]] +name = "unicode-xid" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f962df74c8c05a667b5ee8bcf162993134c104e96440b663c8daa176dc772d8c" + +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "1.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd4e7c0d531266369519a4aa4f399d748bd37043b00bde1e4ff1f60a120b355a" +dependencies = [ + "idna 0.1.5", + "matches", + "percent-encoding 1.0.1", +] + +[[package]] +name = "url" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" +dependencies = [ + "form_urlencoded", + "idna 0.5.0", + "percent-encoding 2.3.1", +] + +[[package]] +name = "urlencoding" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" + +[[package]] +name = "utf8parse" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" + +[[package]] +name = "uuid" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a183cf7feeba97b4dd1c0d46788634f6221d87fa961b305bed08c851829efcc0" + +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + +[[package]] +name = "vaultrs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb996bb053adadc767f8b0bda2a80bc2b67d24fe89f2b959ae919e200d79a19" +dependencies = [ + "async-trait", + "bytes", + "derive_builder 0.12.0", + "http 0.2.12", + "reqwest", + "rustify", + "rustify_derive", + "serde", + "serde_json", + "thiserror", + "tracing", + "url 2.5.0", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "vsimd" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" + +[[package]] +name = "wait-timeout" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f200f5b12eb75f8c1ed65abd4b2db8a6e1b138a20de009dacee265a2498f3f6" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.59", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.59", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" + +[[package]] +name = "web-sys" +version = "0.3.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets 0.52.5", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.5", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" +dependencies = [ + "windows_aarch64_gnullvm 0.52.5", + "windows_aarch64_msvc 0.52.5", + "windows_i686_gnu 0.52.5", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.5", + "windows_x86_64_gnu 0.52.5", + "windows_x86_64_gnullvm 0.52.5", + "windows_x86_64_msvc 0.52.5", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" + +[[package]] +name = "winnow" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0c976aaaa0e1f90dbb21e9587cdaf1d9679a1cde8875c0d6bd83ab96a208352" +dependencies = [ + "memchr", +] + +[[package]] +name = "winreg" +version = "0.50.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" +dependencies = [ + "cfg-if", + "windows-sys 0.48.0", +] + +[[package]] +name = "xmlparser" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fee0b777b0f5ac1c69bb06d361268faafa61cd4682ae064a171c16c433e9e4" + +[[package]] +name = "xtask" +version = "0.1.0" +dependencies = [ + "anyhow", + "xtaskops", +] + +[[package]] +name = "xtaskops" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "464ca5c2bac1d1fcdbef9da6c09c6a14f2c7ac6c8845f574ab12065a2b72bb8b" +dependencies = [ + "anyhow", + "clap 3.2.25", + "derive_builder 0.12.0", + "dialoguer 0.10.4", + "duct", + "fs_extra", + "glob", +] + +[[package]] +name = "yup-oauth2" +version = "8.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45b7ff561fdc7809a2adad8bce73e157d01129074098e6405d0d7dfa2d087782" +dependencies = [ + "anyhow", + "async-trait", + "base64 0.21.7", + "futures", + "http 0.2.12", + "hyper", + "hyper-rustls 0.25.0", + "itertools 0.12.1", + "log", + "percent-encoding 2.3.1", + "rustls 0.22.3", + "rustls-pemfile 1.0.4", + "seahash", + "serde", + "serde_json", + "time", + "tokio", + "tower-service", + "url 2.5.0", +] + +[[package]] +name = "zeroize" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..c5309fcb --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,25 @@ + +[workspace] +resolver = "2" +members = ["teller-cli", "teller-core", "teller-providers", "xtask"] +default-members = ["teller-cli"] + + +[workspace.dependencies] +serde = "1" +serde_json = "1" +serde_yaml = "0.9" +serde_derive = "1" +serde_variant = "0.1.2" +async-trait = "0.1.80" +lazy_static = "1.4.0" +strum = { version = "0.25", features = ["derive"] } +shell-words = "1" +duct = "0.13.6" +thiserror = "1.0.49" +aho-corasick = "1" +tokio = { version = "1", features = ["full"] } +tera = { version = "1" } + +# dev deps +insta = { version = "1.29.0", features = ["redactions", "yaml", "filters"] } diff --git a/LICENSE.txt b/LICENSE.txt index 6b84b80b..e1a96dba 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -198,4 +198,4 @@ 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. + limitations under the License. \ No newline at end of file diff --git a/MAINTAINERS.md b/MAINTAINERS.md index 123a41d3..86c13bdb 100644 --- a/MAINTAINERS.md +++ b/MAINTAINERS.md @@ -2,6 +2,5 @@ The current maintainers of the Teller project are: -* Dotan Nahum [jondot](https://github.com/jondot), , core maintainer -* Elad Kaplan [kaplanelad](https://github.com/kaplanelad), , core maintainer -* Lior Reuven [lreuven](https://github.com/lreuven), , project management +- Dotan Nahum [jondot](https://github.com/jondot), , core maintainer +- Elad Kaplan [kaplanelad](https://github.com/kaplanelad), , core maintainer diff --git a/Makefile b/Makefile deleted file mode 100644 index 09522042..00000000 --- a/Makefile +++ /dev/null @@ -1,51 +0,0 @@ -setup-mac: - brew install golangci-lint - go install github.com/golang/mock/mockgen@v1.5.0 -mocks: - mockgen -source pkg/providers/aws_secretsmanager.go -destination pkg/providers/mock_providers/aws_secretsmanager_mock.go - mockgen -source pkg/providers/aws_ssm.go -destination pkg/providers/mock_providers/aws_ssm_mock.go - mockgen -source pkg/providers/cloudflare_workers_kv.go -destination pkg/providers/mock_providers/cloudflare_workers_kv_mock.go - mockgen -source pkg/providers/cloudflare_workers_secrets.go -destination pkg/providers/mock_providers/cloudflare_workers_secrets_mock.go - mockgen -source pkg/providers/consul.go -destination pkg/providers/mock_providers/consul_mock.go - mockgen -source pkg/providers/dotenv.go -destination pkg/providers/mock_providers/dotenv_mock.go - mockgen -source pkg/providers/doppler.go -destination pkg/providers/mock_providers/doppler_mock.go - mockgen -source pkg/providers/etcd.go -destination pkg/providers/mock_providers/etcd_mock.go - mockgen -source pkg/providers/google_secretmanager.go -destination pkg/providers/mock_providers/google_secretmanager_mock.go - mockgen -source pkg/providers/hashicorp_vault.go -destination pkg/providers/mock_providers/hashicorp_vault_mock.go - mockgen -source pkg/providers/heroku.go -destination pkg/providers/mock_providers/heroku_mock.go - mockgen -source pkg/providers/vercel.go -destination pkg/providers/mock_providers/vercel_mock.go - mockgen -source pkg/providers/onepassword.go -destination pkg/providers/mock_providers/onepassword_mock.go - mockgen -source pkg/providers/gopass.go -destination pkg/providers/mock_providers/gopass_mock.go - mockgen -source pkg/providers/github.go -destination pkg/providers/mock_providers/github_mock.go - mockgen -source pkg/providers/azure_keyvault.go -destination pkg/providers/mock_providers/azure_keyvault_mock.go - mockgen -source pkg/providers/keeper_secretsmanager.go -destination pkg/providers/mock_providers/keeper_secretsmanager_mock.go -readme: - yarn readme -lint: - golangci-lint run -test: - go test -v ./pkg/... -cover - -integration: - go test -v ./pkg/integration_test -cover -tags=integration - -integration_api: - go test -v ./pkg/integration_test -cover -tags="integration_api integration" - -deps: - go mod tidy && go mod vendor - -release: - goreleaser --rm-dist - -build: - go build -ldflags "-s -w -X main.version=0.0.0 -X main.commit=0000000000000000000000000000000000000000 -X main.date=2022-01-01" - -e2e: build - BINARY_PATH="$(shell pwd)/teller" go test -v ./e2e - -coverage: - go test ./pkg/... -coverprofile=coverage.out - go tool cover -func=coverage.out - -.PHONY: deps setup-mac release readme lint mocks coverage diff --git a/README.md b/README.md index 70cf0279..c6ccfbf2 100644 --- a/README.md +++ b/README.md @@ -13,14 +13,11 @@ :pager: Create easy and clean workflows for working with cloud environments
:mag_right: Scan for secrets and fight secret sprawl -


- Teller - The open-source universal secret manager for developers | Product Hunt
-



- +

@@ -34,77 +31,69 @@ You can use Teller to tidy your own environment or for your team as a process an ![](media/providers.png) -## Quick Start with `teller` (or `tlr`) +## Quick Start with `teller` -You can install `teller` with homebrew: +**Download a binary** +Grab a binary from [releases](https://github.com/tellerops/teller/releases) -``` -$ brew tap spectralops/tap && brew install teller -``` - -You can now use `teller` or `tlr` (if you like shortcuts!) in your terminal. - -![](media/teller.gif) +**Build from source** +Using this method will allow you to eye-ball the source code, review it, and build a copy yourself. -`teller` will pull variables from your various cloud providers, vaults and others, and will populate your current working session (in various ways!, see more below) so you can work safely and much more productively. +This will install the binary locally on your machine: -`teller` needs a tellerfile. This is a `.teller.yml` file that lives in your repo, or one that you point teller to with `teller -c your-conf.yml`. - -## Using a Github Action +```bash +$ cd teller-cli +$ cargo install --path . +``` -For those using Github Action, you can have a 1-click experience of installing Teller in your CI: +**Create a new configuration** -```yaml -- name: Setup Teller - uses: spectralops/setup-teller@v1 -- name: Run a Teller task (show, scan, run, etc.) - run: teller run [args] +``` +$ teller new +? Select your secret providers › +⬚ hashicorp_consul +⬚ aws_secretsmanager +⬚ ssm +⬚ dotenv +⬚ hashicorp +⬚ google_secretmanager ``` -For more, check our [setup teller action](https://github.com/marketplace/actions/setup-teller) on the marketplace. +Then, edit the newly created `.teller.yml` to set the maps and keys that you need for your providers. -## Create your configuration +## A look at `teller.yml` +The teller YAML describes your providers and within each provider a `map` that describes: -Run `teller new` and follow the wizard, pick the providers you like and it will generate a `.teller.yml` for you. +* What is the root path to fetch key-values from +* For each such map, its unique `id` which will serve you for operations later +* For each map, an optional specific key name mapping - you can rename keys that you will fetch from the source provider -Alternatively, you can use the following minimal template or [view a full example](.teller.example.yml): +Here's an example configuration file. Note that it also include templating constructs -- such as fetching environment variables while loading the configuration: ```yaml -project: project_name -opts: - stage: development - -# remove if you don't like the prompt -confirm: Are you sure you want to run in {{stage}}? - providers: - # uses environment vars to configure - # https://github.com/hashicorp/vault/blob/api/v1.0.4/api/client.go#L28 - hashicorp_vault: - env_sync: - path: secret/data/{{stage}}/services/billing - - # this will fuse vars with the below .env file - # use if you'd like to grab secrets from outside of the project tree - dotenv: - env_sync: - path: ~/billing.env.{{stage}} -``` - -Now you can just run processes with: + hashi_1: + kind: hashicorp + maps: + - id: test-load + path: /{{ get_env(name="TEST_LOAD_1", default="test") }}/users/user1 + # if empty, map everything + # == means map to same key name + # otherwise key on left becomes right + # in the future: key_transform: camelize, snake_case for automapping the keys + keys: + GITHUB_TOKEN: == + mg: FOO_BAR + dot_1: + kind: dotenv + maps: + - id: stg + path: VAR_{{ get_env(name="STAGE", default="development") }} -``` -$ teller run node src/server.js -Service is up. -Loaded configuration: Mailgun, SMTP -Port: 5050 ``` -Behind the scenes: `teller` fetched the correct variables, placed those (and _just_ those) in `ENV` for the `node` process to use. +You can now address these providers as `hashi_1` or `dot_1`. Teller pulls the specified data from all providers by default. -# Best practices - -Go and have a look at a collection of our [best practices](./best-practices.md) # Features @@ -117,7 +106,7 @@ Got bitten by using `.env.production` and exposing it in the local project itsel Using `teller` and a `.teller.yml` file that exposes nothing to the prying eyes, you can work fluently and seamlessly with zero risk, also no need for quotes: ``` -$ teller run -- your-process arg1 arg2... --switch1 ... +$ teller run --reset --shell -- node index.js ``` ## :mag_right: Inspecting variables @@ -158,40 +147,24 @@ It can also integrate into your CI and serve as a shift-left security tool for y Look for your vault-kept secrets in your code by running: -``` +```bash $ teller scan ``` You can run it as a linter in your CI like so: -``` -run: teller scan --silent +```yaml +run: teller scan --error-if-found ``` It will break your build if it finds something (returns exit code `1`). -Use Teller for productively and securely running your processes and you get this for free -- nothing to configure. If you have data that you're bringing that you're sure isn't sensitive, flag it in your `teller.yml`: - -``` -dotenv: - env: - FOO: - path: ~/my-dot-env.env - severity: none # will skip scanning. possible values: high | medium | low | none -``` - -By default we treat all entries as sensitive, with value `high`. +You can also export results as JSON with `--json` and scan binary files with `-b`. ## :recycle: Redact secrets from process outputs, logs, and files You can use `teller` as a redaction tool across your infrastructure, and run processes while redacting their output as well as clean up logs and live tails of logs. -Run a process and redact its output in real time: - -``` -$ teller run --redact -- your-process arg1 arg2 -``` - Pipe any process output, tail or logs into teller to redact those, live: ``` @@ -206,102 +179,28 @@ $ tail -f /var/log/apache.log | teller redact Finally, if you've got some files you want to redact, you can do that too: -``` +```bash $ teller redact --in dirty.csv --out clean.csv ``` If you omit `--in` Teller will take `stdin`, and if you omit `--out` Teller will output to `stdout`. -## :beetle: Detect secrets and value drift -You can detect _secret drift_ by comparing values from different providers against each other. It might be that you want to pin a set of keys in different providers to always be the same value; when they aren't -- that means you have a drift. - -In most cases, keys in providers would be similar which we call _mirrored_ providers. Example: - -``` -Provider1: - MG_PASS=foo*** - -Provider2: - MG_PASS=foo*** # Both keys are called MG_PASS -``` +## :scroll: Populate templates -To detected mirror drifts, we use `teller mirror-drift`. +You can populate custom templates: ```bash -$ teller mirror-drift --source global-dotenv --target my-dotenv - -Drifts detected: 2 - -changed [] global-dotenv FOO_BAR "n***** != my-dotenv FOO_BAR ne***** -missing [] global-dotenv FB 3***** ?? +$ teller template --in config-templ.t ``` -Use `mirror-drift --sync ...` in order to declare that the two providers should represent a completely synchronized mirror (all keys, all values). - -As always, the specific provider definitions are in your `teller.yml` file. +Template format is [Tera](https://keats.github.io/tera) which is very similar to liquid or handlebars. -## :beetle: Detect secrets and value drift (graph links between providers) - -Some times you want to check drift between two providers, and two unrelated keys. For example: - -``` -Provider1: - MG_PASS=foo*** - -Provider2: - MAILGUN_PASS=foo*** -``` - -This poses a challenge. We need some way to "wire" the keys `MG_PASS` and `MAILGUN_PASS` and declare a relationship of source (`MG_PASS`) and destination, or sink (`MAILGUN_PASS`). - -For this, you can label mappings as `source` and couple with the appropriate sink as `sink`, effectively creating a graph of wirings. We call this `graph-drift` (use same label value for both to wire them together). Then, source values will be compared against sink values in your configuration: +Here is an example template: ```yaml -providers: - dotenv: - env_sync: - path: ~/my-dot-env.env - source: s1 - dotenv2: - kind: dotenv - env_sync: - path: ~/other-dot-env.env - sink: s1 -``` - -And run - -``` -$ teller graph-drift dotenv dotenv2 -c your-config.yml -``` - -![](https://user-images.githubusercontent.com/83390/117453797-07512380-af4e-11eb-949e-cc875e854fad.png) - -## :scroll: Populate templates - -Have a kickstarter project you want to populate quickly with some variables (not secrets though!)? - -Have a production project that just _has_ to have a file to read that contains your variables? - -You can use `teller` to inject variables into your own templates (based on [go templates](https://golang.org/pkg/text/template/)). - -With this template: - -```go -Hello, {{.Teller.EnvByKey "FOO_BAR" "default-value" }}! -``` - -Run: - -``` -$ teller template my-template.tmpl out.txt -``` - -Will get you, assuming `FOO_BAR=Spock`: - -``` -Hello, Spock! +production_var: {{ key(name="PRINT_NAME")}} +production_mood: {{ key(name="PRINT_MOOD")}} ``` ## :arrows_counterclockwise: Copy/sync data between providers @@ -310,30 +209,35 @@ In cases where you want to sync between providers, you can do that with `teller **Specific mapping key sync** +You can use the `/` format to copy a mapping from a provider to another provider: + ```bash -$ teller copy --from dotenv1 --to dotenv2,heroku1 +$ teller copy --from source/dev --to target/prod,<...> ``` -This will: +In this simplistic example, we use the following configuration file -1. Grab all mapped values from source (`dotenv1`) -2. For each target provider, find the matching mapped key, and copy the value from source into it - -**Full copy sync** - -```bash -$ teller copy --sync --from dotenv1 --to dotenv2,heroku1 +```yaml +providers: + dot1: + kind: dotenv + maps: + - id: one + path: one.env + dot2: + kind: dotenv + maps: + - id: two + path: two.env ``` This will: -1. Grab all mapped values from source (`dotenv1`) -2. For each target provider, perform a full copy of values from source into the mapped `env_sync` key +1. Grab all mapped values from source mapping +2. For each target provider, find the matching mapping, and copy the values from source into it -Notes: -- The mapping per provider is as configured in your `teller.yaml` file, in the `env_sync` or `env` properties. -- This sync will try to copy _all_ values from the source. +By default copying will **update** target mapping (upsert data), if you want to replace you can use `--replace`. ## :bike: Write and multi-write to providers @@ -342,86 +246,48 @@ Teller providers supporting _write_ use cases which allow writing values _into_ Remember, for this feature it still revolves around definitions in your `teller.yml` file: ```bash -$ teller put FOO_BAR=$MY_NEW_PASS --providers dotenv -c .teller.write.yml +$ teller put --providers new --map-id one NEW_VAR=s33kret ``` -A few notes: - -- Values are key-value pair in the format: `key=value` and you can specify multiple pairs at once -- When you're specifying a literal sensitive value, make sure to use an ENV variable so that nothing sensitive is recorded in your history -- The flag `--providers` lets you push to one or more providers at once -- `FOO_BAR` must be a mapped key in your configuration for each provider you want to update - -Sometimes you don't have a mapped key in your configuration file and want to perform an ad-hoc write, you can do that with `--path`: +In this example, this configuration is being used: -``` -$ teller put SMTP_PASS=newpass --path secret/data/foo --providers hashicorp_vault +```yaml +providers: + new: + kind: dotenv + maps: + - id: one + path: new.env ``` A few notes: -- The pair `SMTP_PASS=newpass` will be pushed to the specified path -- While you can push to multiple providers, please make sure the _path semantics_ are the same +- Values are key-value pair in the format: `key=value` and you can specify multiple pairs at once +- When you're specifying a literal sensitive value, make sure to use an ENV variable so that nothing sensitive is recorded in your history +- The flag `--providers` lets you push to one or more providers at once ## :x: Delete and multi-delete from providers Teller providers support _deleting_ values _from_ providers. -This feature revolves around definitions in your `teller.yml` file: - ```bash -$ teller delete FOO_BAR --providers dotenv -c .teller.yml +$ teller delete --providers new --map-id one DELETE_ME ``` A few notes: - You can specify multiple keys to delete, for example: - - ```bash - $ teller delete FOO BAR BAZ --providers dotenv - ``` - - The flag `--providers` lets you push to one or more providers at once -- All keys must be a mapped key in your configuration for each provider you want to delete from - -Sometimes you don't have a mapped key in your configuration file and want to perform an ad-hoc delete. You can do that with the `--path` flag: - -```bash -$ teller delete FOO BAR --path ~/my-env-file.env --providers dotenv -``` - -You can also delete all keys at once for a given path, without specifying them one by one: - -```bash -$ teller delete --all-keys --path ~/my-env-file.env --providers dotenv -``` -## :white_check_mark: Prompts and options - -There are a few options that you can use: - -- **carry_env** - carry the environment from the parent process into the child process. By default we isolate the child process from the parent process. (default: _false_) - -- **confirm** - an interactive question to prompt the user before taking action (such as running a process). (default: _empty_) - -- **opts** - a dict for our own variable/setting substitution mechanism. For example: - -``` -opts: - region: env:AWS_REGION - stage: qa -``` - -And now you can use paths like `/{{stage}}/{{region}}/billing-svc` where ever you want (this templating is available for the **confirm** question too). - -If you prefix a value with `env:` it will get pulled from your current environment. ## `YAML` Export in YAML format +XXX TODO: rewrite how the command export works + You can export in a YAML format, suitable for [GCloud](https://cloud.google.com/functions/docs/env-var): ``` -$ teller yaml +$ teller export yaml ``` Example format: @@ -433,10 +299,11 @@ KEY: VALUE ## `JSON` Export in JSON format + You can export in a JSON format, suitable for piping through `jq` or other workflows: ``` -$ teller json +$ teller export json ``` Example format: @@ -449,864 +316,23 @@ Example format: # Providers -For each provider, there are a few points to understand: - -- Sync - full sync support. Can we provide a path to a whole environment and have it synced (all keys, all values). Some of the providers support this and some don't. -- Key format - some of the providers expect a path-like key, some env-var like, and some don't care. We'll specify for each. - -## General provider configuration - -We use the following general structure to specify sync mapping for all providers: - -```yaml -# you can use either `env_sync` or `env` or both -env_sync: - path: ... # path to mapping - remap: - PROVIDER_VAR1: VAR3 # Maps PROVIDER_VAR1 to local env var VAR3 -env: - VAR1: - path: ... # path to value or mapping - field: # optional: use if path contains a k/v dict - decrypt: true | false # optional: use if provider supports encryption at the value side - severity: high | medium | low | none # optional: used for secret scanning, default is high. 'none' means not a secret - redact_with: "**XXX**" # optional: used as a placeholder swapping the secret with it. default is "**REDACTED**" - VAR2: - path: ... -``` - -### Remapping Provider Variables - -Providers which support syncing a list of keys and values can be remapped to different environment variable keys. Typically, when teller syncs paths from `env_sync`, the key returned from the provider is directly mapped to the environment variable key. In some cases it might be necessary to have the provider key mapped to a different variable without changing the provider settings. This can be useful when using `env_sync` for [Hashicorp Vault Dynamic Database credentials](https://www.vaultproject.io/docs/secrets/databases): - -```yaml -env_sync: - path: database/roles/my-role - remap: - username: PGUSER - password: PGPASSWORD -``` - -Additionally, you can remap key settings by using `remap_with` instead of `remap`: -```yaml -env_sync: - path: database/roles/my-role - remap_with: # Use either remap or remap_with, not both. - username: - field: PGUSER - severity: none - password: - field: PGPASSWORD - severity: high - redact_with: "**XXX**" -``` - -After remapping, the local environment variable `PGUSER` will contain the provider value for `username` and `PGPASSWORD` will contain the provider value for `password`. - -## Hashicorp Vault - -### Authentication - -If you have the Vault CLI configured and working, there's no special action to take. - -Configuration is environment based, as defined by client standard. See variables [here](https://github.com/hashicorp/vault/blob/api/v1.0.4/api/client.go#L28). - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read+write` -- Key format - path based, usually starts with `secret/data/`, and more generically `[engine name]/data` - -### Example Config - -```yaml -hashicorp_vault: - env_sync: - path: secret/data/demo/billing/web/env - env: - SMTP_PASS: - path: secret/data/demo/wordpress - field: smtp -``` - -## Consul - -### Authentication - -If you have the Consul CLI working and configured, there's no special action to take. - -Configuration is environment based, as defined by client standard. See variables [here](https://github.com/hashicorp/consul/blob/master/api/api.go#L28). - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read+write` -- Key format - - `env_sync` - path based, we use the last segment as the variable name - - `env` - any string, no special requirement - -### Example Config - -```yaml -consul: - env_sync: - path: ops/config - env: - SLACK_HOOK: - path: ops/config/slack -``` - -## Heroku - -### Authentication - -Requires an API key populated in your environment in: `HEROKU_API_KEY` (you can fetch it from your ~/.netrc). - -Generate new token with Heroku cli: `heroku authorizations:create` then use the TOKEN value. - -### Features +You can get a list of the providers and their described configuration values [in the documentation](https://docs.rs/teller). -- Sync - `yes` -- Mapping - `yes` -- Modes - `read+write` -- Key format - - `env_sync` - name of your Heroku app - - `env` - the actual env variable name in your Heroku settings +### Testing check list: -### Example Config +* [ ] **docker on windows**: if you have a container based test that uses Docker, make sure to exclude it on Windows using `#[cfg(not(windows))]` -```yaml -heroku: - env_sync: - path: my-app-dev - env: - MG_KEY: - path: my-app-dev -``` - -## Etcd - -### Authentication - -If you have `etcdctl` already working there's no special action to take. - -We follow how `etcdctl` takes its authentication settings. These environment variables need to be populated - -- `ETCDCTL_ENDPOINTS` - -For TLS: - -- `ETCDCTL_CA_FILE` -- `ETCDCTL_CERT_FILE` -- `ETCDCTL_KEY_FILE` - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read+write` -- Key format - - `env_sync` - path based - - `env` - path based - -### Example Config - -```yaml -etcd: - env_sync: - path: /prod/billing-svc - env: - MG_KEY: - path: /prod/billing-svc/vars/mg -``` - -## AWS Secrets Manager - -### Authentication - -Your standard `AWS_DEFAULT_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` need to be populated in your environment - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read+write+delete` -- Key format - - `env_sync` - path based - - `env` - path based -- Handles plain text secrets (rather than key/value pairs) via the `plaintext: true` property - -### Example Config - -```yaml -aws_secretsmanager: - env_sync: - path: /prod/billing-svc - env: - MG_KEY: - path: /prod/billing-svc/vars/mg -``` - -Plain text secrets are useful for files; instead of using the usual JSON encoded key/value pairs. This example shows how to get a plaintext secret: - -```yaml -aws_secretsmanager: - env_sync: - path: /prod/billing-svc - env: - MY_FILE: - path: /prod/billing-svc/some-file - plaintext: true -``` - - -## AWS Parameter store - -### Authentication - -Your standard `AWS_DEFAULT_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` need to be populated in your environment - -### Features - -- Sync - `no` -- Mapping - `no` -- Modes - `read+write+delete` -- Key format - - `env` - path based - - `decrypt` - available in this provider, will use KMS automatically - -### Example Config - -```yaml -aws_ssm: - env: - FOO_BAR: - path: /prod/billing-svc/vars - decrypt: true -``` - -## Google Secret Manager - -### Authentication - -You should populate `GOOGLE_APPLICATION_CREDENTIALS=account.json` in your environment to your relevant `account.json` that you get from Google. - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read+write+delete` -- Key format - - `env` - path based, needs to include a version - - `env_sync` - your project's path (gets the secrets latest version), when using --sync a new secret version will be created - - `decrypt` - available in this provider, will use KMS automatically - -### Example Config - -```yaml -google_secretmanager: - env_sync: - # secrets version is not relevant here since we are getting the latest version - path: projects/44882 - env: - MG_KEY: - # need to supply the relevant version (versions/1) - path: projects/44882/secrets/MG_KEY/versions/1 -``` - -if your secrets in google secret manager are stored as JSON or K:V you can add the field property to query the secret body -```yaml -google_secretmanager: - env_sync: - # secrets version is not relevant here since we are getting the latest version - path: projects/44882 - env: - MG_KEY: - # need to supply the relevant version (versions/1) - path: projects/44882/secrets/MG_KEY/versions/1 - field: MG_KEY -``` - -## .ENV (dotenv) - -### Authentication - -No need. You'll be pointing to a one or more `.env` files on your disk. - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read+write+delete` -- Key format - - `env` - env key like - -### Example Config - -You can mix and match any number of files, sitting anywhere on your drive. - -```yaml -dotenv: - env_sync: - path: ~/my-dot-env.env - env: - MG_KEY: - path: ~/my-dot-env.env -``` - -## Doppler - -### Authentication - -Install the [doppler cli][dopplercli] then run `doppler login`. You'll also need to configure your desired "project" for any given directory using `doppler configure`. Alternatively, you can set a global project by running `doppler configure set project ` from your home directory. - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read` -- Key format - - `env` - env key like - -### Example Config - -```yaml -doppler: - env_sync: - path: prd - env: - MG_KEY: - path: prd - field: OTHER_MG_KEY # (optional) -``` - -[dopplercli]: https://docs.doppler.com/docs/cli - -## Vercel - -### Authentication - -Requires an API key populated in your environment in: `VERCEL_TOKEN`. - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read`, [write: accepting PR](https://github.com/spectralops/teller) -- Key format - - `env_sync` - name of your Vercel app - - `env` - the actual env variable name in your Vercel settings - -### Example Config - -```yaml -vercel: - env_sync: - path: my-app-dev - env: - MG_KEY: - path: my-app-dev -``` - -## CyberArk Conjur - -### Authentication - -Requires a username and API key populated in your environment: - -- `CONJUR_AUTHN_LOGIN` -- `CONJUR_AUTHN_API_KEY` - -Requires a .conjurrc file in your User's home directory: - -```yaml ---- -account: conjurdemo -plugins: [] -appliance_url: https://conjur.example.com -cert_file: "" -``` - -- `account` is the organization account created during initial deployment -- `plugins` will be blank -- `appliance_url` should be the Base URI for the Conjur service -- `cert_file` should be the public key certificate if running in self-signed mode - -### Features - -- Sync - `no` [sync: accepting PR](https://github.com/spectralops/teller) -- Mapping - `yes` -- Modes - `read+write` -- Key format - - `env_sync` - not supported to comply with least-privilege model - - `env` - the secret variable path in Conjur Secrets Manager - -### Example Config - -```yaml -cyberark_conjur: - env: - DB_USERNAME: - path: /secrets/prod/pgsql/username - DB_PASSWORD: - path: /secrets/prod/pgsql/password -``` - -## Cloudflare Workers KV - -### Authentication - -requires the following environment variables to be set: - -`CLOUDFLARE_API_KEY`: Your Cloudflare api key. -`CLOUDFLARE_API_EMAIL`: Your email associated with the api key. -`CLOUDFLARE_ACCOUNT_ID`: Your account ID. - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read` (write coming soon) -- Key format - - `env_sync` - The KV namespace ID - - `field` - the actual key stored in the KV store - - `env` - the actual key stored in the KV store - -### Example Config - -```yaml -opts: - kv-namespace-id: - -providers: - cloudflare_workers_kv: - env_sync: - path: "{{kv-namespace-id}}" - remap: - # looks up the key `test_key` and maps it to `TEST`. - test_key: TEST - env: - SOME_SECRET: - path: "{{kv-namespace-id}}" - # Accesses the key `SOME_SECRET` in the KV namespace. - REMAPPED_KEY: - path: "{{kv-namespace-id}}" - # Accesses the field `SOME_KEY` in the KV namespace and maps it to REMAPPED_KEY. - field: SOME_KEY -``` - -## Cloudflare Workers Secrets - -### Usage: - -```sh -$ teller put foo-secret=000000 --providers cloudflare_workers_secrets -$ teller put foo-secret=123 foo-secret2=456 --providers cloudflare_workers_secrets --sync # take from env_sync for using the same source for multiple secrets -$ teller delete foo-secret foo-secret2 --providers cloudflare_workers_secrets -``` - -### Authentication - -requires the following environment variables to be set: - -`CLOUDFLARE_API_KEY`: Your Cloudflare api key. -`CLOUDFLARE_API_EMAIL`: Your email associated with the api key. -`CLOUDFLARE_ACCOUNT_ID`: Your account ID. - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `write` -- Key format - - `source` - The script name - - `path` - Name of the secret, when using `--sync` the path will overridden by the given parameters - -### Example Config - -```yaml -providers: - cloudflare_workers_secrets: - env_sync: - source: script-id - env: - foo-secret: - path: foo-secret - source: script-id - foo-secret2: - path: foo-secret - source: script-id -``` - -## 1Password - -### Authentication - -To integrate with the 1Password API, you should have system-to-system secret management running in your infrastructure/localhost [more details here](https://support.1password.com/connect-deploy-docker/). - -Requires the following environment variables to be set: -`OP_CONNECT_HOST` - The hostname of the 1Password Connect API -`OP_CONNECT_TOKEN` - The API token to be used to authenticate the client to a 1Password Connect API. - -### Features - -- Sync - `no` -- Mapping - `yes`, returns all fields on specific secret item -- Modes - `read+write` -- Key format - - `env_sync` - Will return all the fields under the secret item. - - `path` - Mandatory field: Secret item name. (expected unique secret item with the same name) - - `source` - Mandatory field: vaultUUID to query - - `env` - - `path` - Mandatory field: Secret item name. (expected unique secret item with the same name) - - `source` - Mandatory field: vaultUUID to query - - `field` - Mandatory field: the specific field name (notesPlain, {custom label name}, password, type etc). - -### Example Config - -```yaml -1password: - env_sync: - path: security-note - source: VAULT-ID - env: - SECURITY_NOTE_TITLE: - path: security-note-title - source: VAULT-ID - field: lable1 - NOTE_SECRET: - path: login-title - source: VAULT-ID - field: password - CREDIT_CARD: - path: credit-card-title - source: VAULT-ID - field: type -``` - -### Run Example: - -Example: - -```sh -OP_CONNECT_HOST="http://localhost:8080" OP_CONNECT_TOKEN="" teller yaml -``` - -## Gopass - -### Authentication - -If you have the Gopass working and configured, there's no special action to take. - -Configuration is environment based, as defined by client standard. See variables [here](https://github.com/gopasspw/gopass/blob/master/docs/config.md). - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read+write` -- Key format - - `env_sync` - path based, we use the last segment as the variable name - - `env` - any string, no special requirement - -### Example Config - -```yaml -gopass: - env_sync: - path: foo - env: - SLACK_HOOK: - path: path: foo/bar -``` - -## LastPass - -### Authentication - -Requires the following environment variables to be set: -`LASTPASS_USERNAME` - LastPass username -`LASTPASS_PASSWORD` - LastPass password - -### Features - -- Sync - `no` -- Mapping - `no` -- Modes - `read` -- Key format - - `env_sync` - Will return all the fields under the secret item. - - `path` - Mandatory field: Secret item ID. - - `env` - - `path` - Mandatory field: Secret item ID. - - `field` - Optional field: by default taking `password` property. in case you want other property un-mark this line and set the LastPass property name. - -## GitHub - -### Usage: - -```sh -$ teller put FROM_TELLER=00000 FROM_TELLER_2=00002 --providers github --sync # Add secrets with dynamic secrets name (take from env_sync) -$ teller put FROM_TELLER=1111 FROM_TELLER_2=222 --providers github # Add defined secrets name from env key (YAML key will be the name of the secret) -$ teller delete FROM_TELLER --providers github # Delete specific secret -$ teller delete FROM_TELLER FROM_TELLER_2 --providers github --all-keys --path={OWNER}/{REPO-NAME} # Delete all repo secrets, limited to 100 secrets per repository -``` - -### Authentication - -requires the following environment variables to be set: - -`GITHUB_AUTH_TOKEN`: GitHub token. - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `write` -- Key format - - `path` - Contain the repo owner and the repo name with `/` separator - -### Example Config - -```yaml -providers: - github: - env_sync: - path: owner/repo-name - env: - FROM_TELLER: - path: owner/repo-name - FROM_TELLER_2: - path: owner/repo-name -``` - -## KeyPass - -### Authentication - -requires the following environment variables to be set: - -`KEYPASS_PASSWORD`: Password database credentials -`KEYPASS_DB_PATH`: Database path - -### Features - -- Sync - `no` -- Mapping - `yes` -- Modes - `read` - -### Example Config - -```yaml -providers: - keypass: - env_sync: - path: redis/config - # source: Optional, all fields is the default. Supported fields: Notes, Title, Password, URL, UserName - env: - ETC_DSN: - path: redis/config/foobar - # source: Optional, Password is the default. Supported fields: Notes, Title, Password, URL, UserName -``` - -## FileSystem - -Allows to work against filesystem structure. for example: - -``` -. -└── /folder - ├── settings/ - │ ├── billing-svc - │ └── all/ - │ ├── foo - └── bar -``` - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read+write` - -### Example Config - -```yaml -providers: - filesystem: - env_sync: - path: /folder/settings - env: - ETC_DSN: - path: /folder/bar -``` - -## ProcessEnv - -Load the environment variables from the parent process as needed. - -### Authentication - -No need. - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read` -- Key format - - `env_sync` - Will return all the environment variables in the parent process - - `path` - Value isn't required or used - - `env` - - `field` - Optional field: specific environment variable in the parent process - -### Example Config - -```yaml -providers: - process_env: - env: - ETC_DSN: - # Optional: accesses the environment variable `SOME_KEY` and maps it to ETC_DSN - field: SOME_KEY -``` - -## Azure - -### Authentication - -Two options for getting Azure authentication are available: - -1. Standard Azure [environment variable](https://docs.microsoft.com/en-us/azure/developer/go/azure-sdk-authorization). (Enable by default) -2. For get credentials via [az client](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli) add `AZURE_CLI=1` to your environment variable - -Then set your vault-name by specific as environment variable: `KVAULT_NAME` - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read+write+delete` - -### Example Config - -```yaml -providers: - azure_keyvault: - env_sync: - path: azure - env: - FOO: - path: bar -``` - -## Keeper Secrets Manager - -### Authentication - -Configuration is environment based - you should populate `KSM_CONFIG=base64_config` or `KSM_CONFIG_FILE=ksm_config.json` in your environment with a valid [Secrets Manager Configuration](https://docs.keeper.io/secrets-manager/secrets-manager/about/secrets-manager-configuration#creating-a-secrets-manager-configuration). If both environment variables are set then `KSM_CONFIG` is used. - -Note: -- _Secrets Manager CLI configuration file format (INI) is different from KSM SDK configuration format (JSON) but the CLI [command](https://docs.keeper.io/secrets-manager/secrets-manager/secrets-manager-command-line-interface/profile-command#export) `ksm profile export profile_name` can be used to export some of the individual profiles into JSON config file compatible with the provider._ - -### Features - -- Sync - `yes` -- Mapping - `yes` -- Modes - `read` -- Key format - - `env_sync` - path is single record UID. Field labels (if empty -> field types) are used as keys, any duplicates will have a numeric suffix. - - `env` - any string, conforming to Keeper [Notation](https://docs.keeper.io/secrets-manager/secrets-manager/about/keeper-notation) _(`keeper://` prefix not required)_ - -### Example Config - -```yaml -keeper_secretsmanager: - env_sync: - path: ABCDEFGHIJKLMNOPQRSTUV - env: - PGUSER: - path: ABCDEFGHIJKLMNOPQRSTUV/field/login - CERT: - path: ABCDEFGHIJKLMNOPQRSTUV/custom_field/ssl_cert -``` - -# Semantics - -## Addressing - -- Stores that support key-value interfaces: `path` is the direct location of the value, no need for the `env` key or `field`. -- Stores that support key-valuemap interfaces: `path` is the location of the map, while the `env` key or `field` (if exists) will be used to do the additional final addressing. -- For env-sync (fetching value map out of a store), path will be a direct pointer at the key-valuemap - -## Errors - -- **Principle of non-recovery**: where possible an error is return when it is not recoverable (nothing to do), but when it is -- providers should attempt recovery (e.g. retry API call) -- **Missing key/value**: it's possible that when trying to fetch value in a provider - it's missing. This is not an error, rather an indication of a missing entry is returned (`EnvEntry#IsFound`) - -# Security Model - -## Project Practices - -- We `vendor` our dependencies and push them to the repo. This creates an immutable, independent build, that's also free from risks of fetching unknown code in CI/release time. - -## Providers - -For every provider, we are federating all authentication and authorization concern to the system of origin. In other words, if for example you connect to your organization's Hashicorp Vault, we assume you already have a secure way to do that, which is "blessed" by the organization. - -In addition, we don't offer any way to specify connection details to these systems in writing (in configuration files or other), and all connection details, to all providers, should be supplied via environment variables. - -That allows us to keep two important points: - -1. Don't undermine the user's security model and threat modeling for the sake of productivity (security AND productivity CAN be attained) -2. Don't encourage the user to do what we're here for -- save secrets and sensitive details from being forgotten in various places. - -## Developer Guide - -- [Add new provider](./doc/new-provider.md) -- Quick testing as you code: `make lint && make test` -- Checking your work before PR, run also integration tests: `make integration` +* [ ] **resource semantics**: while building providers, align with the semantics of _empty_ and _not found_ as two different semantics: if a provider supports an explicit "not found" semantic (404, NotFound, etc.), use `Error::NotFound`. Otherwise when a provider signals a "not found" semantic as an empty data bag, return an empty `KV[]` (i.e. do not translate a sematic of "empty" into "not found"). ### Testing -Testing is composed of _unit tests_ and _integration tests_. Integration tests are based on _testcontainers_ as well as live sandbox APIs (where containers are not available) - -- Unit tests are a mix of pure and mocks based tests, abstracting each provider's interface with a custom _client_ -- View [integration tests](/pkg/integration_test) - -To run all unit tests without integration: - -``` -$ make test -``` - -To run all unit tests including container-based integration: +Testing is done with: ``` -$ make integration +$ cargo test --all --all-features ``` -To run all unit tests including container and live API based integration (this is effectively **all integration tests**): - -``` -$ make integration_api -``` - -Running all tests: - -``` -$ make test -$ make integration_api -``` - -### Linting - -Linting is treated as a form of testing (using `golangci`, configuration [here](.golangci.yml)), to run: - -``` -$ make lint -``` +And requires Docker (or equivalent) on your machine. ### Thanks: @@ -1318,4 +344,4 @@ Teller follows [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/ma # Copyright -Copyright (c) 2021 [@jondot](http://twitter.com/jondot). See [LICENSE](LICENSE.txt) for further details. +Copyright (c) 2024 [@jondot](http://twitter.com/jondot). See [LICENSE](LICENSE.txt) for further details. diff --git a/ROADMAP.md b/ROADMAP.md deleted file mode 100644 index add1b20b..00000000 --- a/ROADMAP.md +++ /dev/null @@ -1,39 +0,0 @@ -# Teller Roadmap - -This document lists the new features being considered for the future and that are being experimented / worked on currently. We would like our contributors and users to know what features could come in the near future. We definitely welcome suggestions and ideas from everyone about the roadmap and features (feel free to open an [issue](https://github.com/SpectralOps/teller/issues)). - -## Currently worked on - -### Additional use cases - -* Secret value policy - allow for validating fetched secrets against a policy such as secret strength, raising a warning if policy is not met -* Secret enclave. Create a local secret engine to be stored co-located with code. This will become _just another provider_ to pick from -* Zero-trust / last-mile encryption. Have Teller perform the last-mile encryption at the point of fetching secrets allowing for zero-trust secret management. (this may share implementation details with the secret enclave) - - -## Planned Features - -### Additional use cases - -* Push-only providers, where only write is supported. Typically CI providers only allow for secrets to be written-in but not read-from. We want to allow for a "push" use case where users could sync secrets from vaults into operational platforms such as CI and production. That means creating the concept of _write only providers_. -* Kubernetes secrets sidecar. Enable a seamless way to have secrets fetched just-in-time for processes as a sidecar. -* Native Jenkins plugin as secrets engine. Have Jenkins point to a secret store that's actually backed by Teller - which delegates to your favorite vaults. - -### Additional Providers - -**Read/Write** - -* 1password (via local tooling) -* Lastpass (via local tooling) -* gopass - - - -**Write only** - -* Github -* Gitlab -* CircleCI -* Travis - - diff --git a/best-practices.md b/best-practices.md deleted file mode 100644 index 53e5a76c..00000000 --- a/best-practices.md +++ /dev/null @@ -1,12 +0,0 @@ -# Intro -This is a list of some of the best practices using this tool. Please contribute if you have any additions or changes to current or non existing best practices - -* [`Different envs`](#different-envs). - -# Different envs -We primarily use 2 methods: - -* A single file, where each environment is a parameter, see prompts and options, where you can populate one with an environment variable env:STAGE and STAGE=dev teller ... -* Keep a config file per environment, similar to what you would do with .env file (.env.example, .env.production, etc.) -- but with teller none of configuration files contain any sensitive information (as opposed to .env) so you're safe. - -The best practice really depends on the size of your team and how you prefer to work. We imagine if the team is small, and the use cases are not many, a single file would be great. If the team is large, or maybe you're enabling other teams -- keeping a file per environment would be better, and this way you can "distribute" your teller files per use case in a central way. \ No newline at end of file diff --git a/doc/new-provider.md b/doc/new-provider.md deleted file mode 100644 index cffcec75..00000000 --- a/doc/new-provider.md +++ /dev/null @@ -1,97 +0,0 @@ -# How to add a new provider - -Adding a new Teller provider is very easy, but you still need to know where to start. We summarize the steps very shortly to make your life easier - -## Provider implementation - -1. Copy the file [example.go](../examples/providers/example.go) from [examples/providers/example.go](../examples/providers/example.go) and make sure to implement all the required behaviors. The [example.go](../examples/providers/example.go) file is a skeleton for adding a new provider, it contains stubs for an interface which declares the required functionality that any provider must have. -2. After copying to the providers dir, remove the comment from the `init` function to register your provider - -```go - // func init() { -// metaInto := core.MetaInfo{ -// Description: "ProviderName", -// Name: "provider_name", -// Authentication: "If you have the Consul CLI working and configured, there's no special action to take.\nConfiguration is environment based, as defined by client standard. See variables [here](https://github.com/hashicorp/consul/blob/master/api/api.go#L28).", -// ConfigTemplate: ` -// provider: -// env: -// KEY_EAXMPLE: -// path: pathToKey -// `, -// Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true}, -// } -// RegisterProvider(metaInto, NewExample) -// } -``` - -Set `Description, Name, and Authentication`, as well as `OpMatrix` that descibes the action this provider supports, based on your implementation. - -3. Add a provider template configuration in path: [pkg/wizard_template.go](../pkg/wizard_template.go). This will be used to auto-generate a configuration. - -```go -{{- if index .ProviderKeys "example" }} - # Add here some authentication requirements, like a token that should be in the user's environment. - example: - env_sync: - path: redis/config - env: - ETC_DSN: - path: redis/config/foobar - -{{end}} -``` - -You're done! :rocket: - -### Verify your work: - -Run the command `go run main.go new` and run through the flow in the wizard. -Ensure that you see your provider in the `Select your secret providers` question. - -After the `teller.yml` file is created, run the command `go run main.go yaml`, you should see the message : - -```sh -FATA[0000] could not load all variables from the given existing providers error="provider \"Example\" does not implement write yet" -``` - -This means that you configured the provider successfully and are ready to implement the functions in it. - -### Notes - -- Since each provider uses some kind of system behind it (e.g. Hashicorp Vault provider connects to the Hashicorp Vault itself) try to wrap the access to the backend or system with your own abstract client-provider with an interface. It will help you to test your provider easier. -- Use provider logger for better visibility when an error occurs. -- Add the new provider to provider mapping in [README.md](../README.md#remapping-provider-variables). - -### Adding third-party packages - -We `vendor` our dependencies and push them to the repo. This creates an immutable, independent build, that's also free from risks of fetching unknown code in CI/release time. - -After adding your packages to import in your provider file, run the commands: - -```sh -$ go mod tidy -$ go mod vendor -``` - -## Adding tests - -Create an `example_test.go` file in [pkg/providers](../pkg/providers) folder. - -In case you warp the client-provider with an interface you can run a mock generator with the [mock](https://github.com/golang/mock) framework and add this command to the [Makefile](../Makefile) - -```sh -mockgen -source pkg/providers/example.go -destination pkg/providers/mock_providers/example_mock.go -``` - -Test guidelines: - -- Create a `TestExample` function and call [AssertProvider](../pkg/providers/helpers_test.go) for testing main functionality. -- Create a `TestExampleFailures` for testing error handling. -- You can also add more tests for testing private functions. -- Run `make lint` to validate linting. -- Run `make test` for make sure that all the test pass. - -``` - -``` diff --git a/e2e/README.md b/e2e/README.md deleted file mode 100644 index 07d1eacb..00000000 --- a/e2e/README.md +++ /dev/null @@ -1,38 +0,0 @@ -# End to End Tests - -This package contains integration tests. - -## Running -```sh -make e2e -``` - -## Create E2E test - -You have two different options to create an E2E test in Teller. - -### Simple -The simple and fast way is based on `yml` file configuration. All you need to do is create a *.yml file in [test folder](./tests/) with the following fields: - -| Field | Description | -|-------------------------------|------------------------------------ -| `name` | E2E name. -| `command` | Command to execute. You need to keep ``; this placeholder will replace with the `BINARY_PATH` binary value. -| `config_file_name` | Configuration file name. If empty, the configuration file will not be created. -| `config_content` | Configuration file content. -| `init_snapshot` | List of files that were going to create before Teller binary is executed. -| `init_snapshot.path` | Create file in path. -| `init_snapshot.file_name` | File name. -| `init_snapshot.content` | File content. -| `replace_stdout_content` | Replace dynamic stdout content to static. for example, replace current timestemp to static text. -| `expected_snapshot` | Compare the init_snapshot folder with the expected snapshot content. If empty, this compare check will be ignored. -| `expected_snapshot.path` | Create file in path. -| `expected_snapshot.file_name` | File name. -| `expected_snapshot.content` | File content. -| `expected_stdout` | Check if Teller stdout equals this value. If empty, this check will be ignored. -| `expected_stderr` | Check if Teller stderr equals this value. If empty, this check will be ignored. - -### Advanced -In case the E2E `yml`not flexible enough you have the option to create a `*.go` file in [test folder](./tests/). the go file most to: -1. Implement [TestCaseDescriber](./register/interface.go) interface -2. Must to user `init` function and register to [AddSuite](./register/register.go) \ No newline at end of file diff --git a/e2e/e2e_test.go b/e2e/e2e_test.go deleted file mode 100644 index 202158e0..00000000 --- a/e2e/e2e_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package e2e - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "regexp" - "strings" - - "testing" - - "github.com/spectralops/teller/e2e/register" - _ "github.com/spectralops/teller/e2e/tests" - "github.com/spectralops/teller/e2e/testutils" - "github.com/stretchr/testify/assert" -) - -const ( - replaceToStaticPath = "DYNAMIC-FULL-PATH" - replaceToShortStaticPath = "DYNAMIC-SHORT-PATH" - removeBinaryPlaceholder = "" - testsFolder = "tests" -) - -func TestE2E(t *testing.T) { //nolint - t.Parallel() - - // validate given binary path - binaryPath, err := getBinaryPath() - if err != nil { - assert.FailNow(t, err.Error()) - } - - snapshotSuites, err := testutils.GetYmlSnapshotSuites(testsFolder) - assert.Nil(t, err) - - // consider to replace `diff` command which is depended on OS to golang plugin. - // could't find something better - differ := testutils.NewExecDiffer() - // Loop on all test/*.yml files - for _, snapshot := range snapshotSuites { - - t.Run(snapshot.Name, func(t *testing.T) { - - // create a temp folder for the test - tempFolder, err := os.MkdirTemp(t.TempDir(), strings.ReplaceAll(snapshot.Name, " ", "")) - // descrive the base snapshot data of the test - snapshotFolder := filepath.Join(tempFolder, "snapshot") - assert.Nil(t, err, "could not create temp folder") - defer os.RemoveAll(tempFolder) - - if len(snapshot.InitSnapshot) > 0 { - err = snapshot.CreateSnapshotData(snapshot.InitSnapshot, snapshotFolder) - assert.Nil(t, err) - } - - if snapshot.ConfigFileName != "" { - err = snapshot.CrateConfig(snapshotFolder) - assert.Nil(t, err) - } - - flagsCommand := strings.TrimPrefix(snapshot.Command, removeBinaryPlaceholder) - stdout, stderr, err := testutils.ExecCmd(binaryPath, strings.Split(flagsCommand, " "), snapshotFolder) - if stdout == "" { - assert.Nil(t, err, stderr) - } - - // In case the stdout/stderr include the dynamic folder path, we want to replace with static-content for better snapshot text compare - stdout, stderr = replaceFolderName(stdout, stderr, snapshotFolder) - - if len(snapshot.ReplaceStdOutContent) > 0 { - for _, r := range snapshot.ReplaceStdOutContent { - var re = regexp.MustCompile(r.Search) - stdout = re.ReplaceAllString(stdout, r.Replace) - } - } - if len(snapshot.ReplaceStdErrContent) > 0 { - for _, r := range snapshot.ReplaceStdErrContent { - var re = regexp.MustCompile(r.Search) - stderr = re.ReplaceAllString(stderr, r.Replace) - } - } - - if snapshot.ExpectedStdOut != "" { - assert.Equal(t, snapshot.ExpectedStdOut, stdout) - } - - if snapshot.ExpectedStdErr != "" { - assert.Equal(t, snapshot.ExpectedStdErr, stderr) - } - - if len(snapshot.ExpectedSnapshot) > 0 { - destSnapshotFolder := filepath.Join(tempFolder, "dest") - err = snapshot.CreateSnapshotData(snapshot.ExpectedSnapshot, destSnapshotFolder) - assert.Nil(t, err) - - diffResult, err := testutils.FolderDiff(differ, destSnapshotFolder, snapshotFolder, []string{snapshot.ConfigFileName}) - if err != nil { - t.Fatalf("snapshot folder is not equal. results: %v", diffResult) - } - assert.Nil(t, err) - } - }) - } - // loop on register suites (from *.go files) - for name, suite := range register.GetSuites() { - t.Run(name, func(t *testing.T) { - - // creates temp dir for test path. - tempFolder, err := os.MkdirTemp(t.TempDir(), strings.ReplaceAll(name, " ", "")) - assert.Nil(t, err, "could not create temp folder") - defer os.RemoveAll(tempFolder) - - // initialized test case - testInstance := suite(tempFolder) - - err = testInstance.SetupTest() - assert.Nil(t, err) - - // get Teller flags command - flags := testInstance.GetFlags() - - stdout, stderr, err := testutils.ExecCmd(binaryPath, flags, tempFolder) - assert.Nil(t, err) - - stdout, stderr = replaceFolderName(stdout, stderr, tempFolder) - err = testInstance.Check(stdout, stderr) - assert.Nil(t, err) - }) - } -} - -func replaceFolderName(stdout, stderr, workingDirectory string) (string, string) { - stdout = strings.ReplaceAll(stdout, workingDirectory, replaceToStaticPath) - stderr = strings.ReplaceAll(stderr, workingDirectory, replaceToStaticPath) - shortFolderPath := workingDirectory[0:13] - stdout = strings.ReplaceAll(stdout, shortFolderPath, replaceToShortStaticPath) - stderr = strings.ReplaceAll(stderr, shortFolderPath, replaceToShortStaticPath) - - return stdout, stderr -} - -func getBinaryPath() (string, error) { - binaryPath, isExists := os.LookupEnv("BINARY_PATH") - if !isExists { - return "", errors.New("missing `BINARY_PATH`") - } - - info, err := os.Stat(binaryPath) - errors.Is(err, os.ErrNotExist) - - if err != nil || info.IsDir() { - return "", fmt.Errorf("%s not found", binaryPath) - } - return binaryPath, nil -} diff --git a/e2e/register/interface.go b/e2e/register/interface.go deleted file mode 100644 index 1b15d345..00000000 --- a/e2e/register/interface.go +++ /dev/null @@ -1,9 +0,0 @@ -package register - -type NewSuite func(tempFolderPath string) TestCaseDescriber - -type TestCaseDescriber interface { - SetupTest() error - GetFlags() []string - Check(stdOut, stderr string) error -} diff --git a/e2e/register/register.go b/e2e/register/register.go deleted file mode 100644 index f9053ff2..00000000 --- a/e2e/register/register.go +++ /dev/null @@ -1,11 +0,0 @@ -package register - -var suite = map[string]NewSuite{} - -func AddSuite(name string, test NewSuite) { - suite[name] = test -} - -func GetSuites() map[string]NewSuite { - return suite -} diff --git a/e2e/tests/custom-config-file.yml b/e2e/tests/custom-config-file.yml deleted file mode 100644 index bf47cd6b..00000000 --- a/e2e/tests/custom-config-file.yml +++ /dev/null @@ -1,23 +0,0 @@ ---- -name: Custom config name -command: show -c .custom-teller.yml -config_file_name: .custom-teller.yml -config_content: > - project: test - - providers: - filesystem: - env: - FOO: - path: {{.Folder}}/settings/test/foo -init_snapshot: - - path: settings/test - file_name: foo - content: shazam -expected_snapshot: -expected_stderr: | - -*- teller: loaded variables for test using .custom-teller.yml -*- - - [filesystem DYNAMIC-SHORT-PATH...tings/test/foo] FOO = sh***** - -expected_stdout: diff --git a/e2e/tests/delete.yml b/e2e/tests/delete.yml deleted file mode 100644 index dfdfdf51..00000000 --- a/e2e/tests/delete.yml +++ /dev/null @@ -1,48 +0,0 @@ ---- -name: Delete multiple entires -command: delete FOO BAR --providers filesystem -config_file_name: .teller.yml -config_content: > - project: test - - providers: - filesystem: - env_sync: - path: {{.Folder}}/settings/test/all - env: - FOO: - path: {{.Folder}}/settings/test/foo - BAR: - path: {{.Folder}}/settings/test/bar -init_snapshot: - - path: settings/test - file_name: foo - content: shazam - - path: settings/test - file_name: bar - content: shazam - - path: settings/test/all - file_name: secret-a - content: mailman - - path: settings/test/all - file_name: secret-b - content: shazam - - path: settings/test/all - file_name: secret-c - content: shazam-1 -expected_snapshot: - - path: settings/test/all - file_name: secret-a - content: mailman - - path: settings/test/all - file_name: secret-b - content: shazam - - path: settings/test/all - file_name: secret-c - content: shazam-1 - -expected_stderr: | - Delete FOO (DYNAMIC-FULL-PATH/settings/test/foo) in filesystem: OK. - Delete BAR (DYNAMIC-FULL-PATH/settings/test/bar) in filesystem: OK. - -expected_stdout: \ No newline at end of file diff --git a/e2e/tests/json.yml b/e2e/tests/json.yml deleted file mode 100644 index c5e56d39..00000000 --- a/e2e/tests/json.yml +++ /dev/null @@ -1,42 +0,0 @@ ---- -name: Show JSON entries -command: json -config_file_name: .teller.yml -config_content: > - project: test - - providers: - filesystem: - env_sync: - path: {{.Folder}}/settings/test/all - env: - FOO: - path: {{.Folder}}/settings/test/foo - BAR: - path: {{.Folder}}/settings/test/bar -init_snapshot: - - path: settings/test - file_name: foo - content: shazam - - path: settings/test - file_name: bar - content: shazam - - path: settings/test/all - file_name: secret-a - content: mailman - - path: settings/test/all - file_name: secret-b - content: shazam - - path: settings/test/all - file_name: secret-c - content: shazam-1 -expected_snapshot: -expected_stdout: >- - { - "BAR": "shazam", - "FOO": "shazam", - "secret-a": "mailman", - "secret-b": "shazam", - "secret-c": "shazam-1" - } -expected_stderr: \ No newline at end of file diff --git a/e2e/tests/put-sync.yml b/e2e/tests/put-sync.yml deleted file mode 100644 index 680fbacb..00000000 --- a/e2e/tests/put-sync.yml +++ /dev/null @@ -1,58 +0,0 @@ ---- -name: Put with --sync flag -command: put key-1=key-1-content key-2=key-2-content --providers filesystem --sync -config_file_name: .teller.yml -config_content: > - project: test - - providers: - filesystem: - env_sync: - path: {{.Folder}}/settings/test/all - env: - FOO: - path: {{.Folder}}/settings/test/foo - BAR: - path: {{.Folder}}/settings/test/bar -init_snapshot: - - path: settings/test - file_name: foo - content: shazam - - path: settings/test - file_name: bar - content: shazam - - path: settings/test/all - file_name: secret-a - content: mailman - - path: settings/test/all - file_name: secret-b - content: shazam - - path: settings/test/all - file_name: secret-c - content: shazam-1 -expected_snapshot: - - path: settings/test - file_name: foo - content: shazam - - path: settings/test - file_name: bar - content: shazam - - path: settings/test/all - file_name: secret-a - content: mailman - - path: settings/test/all - file_name: secret-b - content: shazam - - path: settings/test/all - file_name: secret-c - content: shazam-1 - - path: settings/test/all - file_name: key-1 - content: key-1-content - - path: settings/test/all - file_name: key-2 - content: key-2-content -expected_stderr: | - Synced filesystem (DYNAMIC-FULL-PATH/settings/test/all): OK. - -expected_stdout: \ No newline at end of file diff --git a/e2e/tests/put.yml b/e2e/tests/put.yml deleted file mode 100644 index ec3b400d..00000000 --- a/e2e/tests/put.yml +++ /dev/null @@ -1,53 +0,0 @@ ---- -name: Put multiple entires -command: put FOO=new-foo-value BAR=new-bar-value --providers filesystem -config_file_name: .teller.yml -config_content: > - project: test - - providers: - filesystem: - env_sync: - path: {{.Folder}}/settings/test/all - env: - FOO: - path: {{.Folder}}/settings/test/foo - BAR: - path: {{.Folder}}/settings/test/bar -init_snapshot: - - path: settings/test - file_name: foo - content: shazam - - path: settings/test - file_name: bar - content: shazam - - path: settings/test/all - file_name: secret-a - content: mailman - - path: settings/test/all - file_name: secret-b - content: shazam - - path: settings/test/all - file_name: secret-c - content: shazam-1 -expected_snapshot: - - path: settings/test - file_name: foo - content: new-foo-value - - path: settings/test - file_name: bar - content: new-bar-value - - path: settings/test/all - file_name: secret-a - content: mailman - - path: settings/test/all - file_name: secret-b - content: shazam - - path: settings/test/all - file_name: secret-c - content: shazam-1 -expected_stderr: | - Put BAR (DYNAMIC-FULL-PATH/settings/test/bar) in filesystem: OK. - Put FOO (DYNAMIC-FULL-PATH/settings/test/foo) in filesystem: OK. - -expected_stdout: \ No newline at end of file diff --git a/e2e/tests/redact.yml b/e2e/tests/redact.yml deleted file mode 100644 index 91630414..00000000 --- a/e2e/tests/redact.yml +++ /dev/null @@ -1,29 +0,0 @@ ---- -name: redact input -command: redact --in dirty -config_file_name: .teller.yml -config_content: > - project: redaction test - - providers: - filesystem: - env: - FOO: - path: {{.Folder}}/settings/test/foo -init_snapshot: - - path: settings/test - file_name: foo - content: secret - - path: - file_name: dirty - content: | - content - secret - content -expected_snapshot: -replace_stdout_content: -expected_stdout: | - content - **REDACTED** - content -expected_stderr: \ No newline at end of file diff --git a/e2e/tests/run-redact.yml b/e2e/tests/run-redact.yml deleted file mode 100644 index 5c6988e1..00000000 --- a/e2e/tests/run-redact.yml +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: Run with --redact flag -command: run --redact -- bash script -config_file_name: .teller.yml -config_content: > - project: redaction test - - providers: - filesystem: - env: - FOO: - path: {{.Folder}}/settings/test/foo -init_snapshot: - - path: settings/test - file_name: foo - content: secret - - path: - file_name: script - content: | - #!/usr/bin/env bash - for _ in {1..5}; - do - echo secret value; - done -expected_snapshot: -replace_stdout_content: -expected_stdout: | - **REDACTED** value - **REDACTED** value - **REDACTED** value - **REDACTED** value - **REDACTED** value -expected_stderr: \ No newline at end of file diff --git a/e2e/tests/scan.yml b/e2e/tests/scan.yml deleted file mode 100644 index 4f8bcb11..00000000 --- a/e2e/tests/scan.yml +++ /dev/null @@ -1,47 +0,0 @@ ---- -name: scan entries -command: scan -config_file_name: .teller.yml -config_content: > - project: test - - providers: - filesystem: - env_sync: - path: {{.Folder}}/files/all - env: - FOO: - path: {{.Folder}}/settings/test/foo - severity: low - BAR: - path: {{.Folder}}/settings/test/bar - severity: medium -init_snapshot: - - path: settings/test - file_name: foo - content: shazam - - path: settings/test - file_name: bar - content: shazam - - path: settings/test - file_name: file - content: content - - path: files/all - file_name: secret-a - content: mailman - - path: files/all - file_name: secret-b - content: 1111 -expected_snapshot: -replace_stdout_content: - - search: "matches in [0-9].[0-9]+(.*)" - replace: matches in 1.000ms -expected_stdout: | - [high] files/all/secret-a (1,0): found match for filesystem/secret-a (ma*****) - [high] files/all/secret-b (1,0): found match for filesystem/secret-b (11*****) - [low] settings/test/bar (1,0): found match for filesystem/FOO (sh*****) - [medium] settings/test/bar (1,0): found match for filesystem/BAR (sh*****) - [low] settings/test/foo (1,0): found match for filesystem/FOO (sh*****) - [medium] settings/test/foo (1,0): found match for filesystem/BAR (sh*****) - Scanning for 4 entries: found 6 matches in 1.000ms -expected_stderr: diff --git a/e2e/tests/sh.yml b/e2e/tests/sh.yml deleted file mode 100644 index dc19a76e..00000000 --- a/e2e/tests/sh.yml +++ /dev/null @@ -1,46 +0,0 @@ ---- -name: Sh print -command: sh -config_file_name: .teller.yml -config_content: > - project: test - - providers: - filesystem: - env_sync: - path: {{.Folder}}/settings/test/all - env: - FOO: - path: {{.Folder}}/settings/test/foo - BAR: - path: {{.Folder}}/settings/test/bar -init_snapshot: - - path: settings/test - file_name: foo - content: shazam - - path: settings/test - file_name: bar - content: shazam - - path: settings/test/all - file_name: secret-a - content: mailman - - path: settings/test/all - file_name: secret-b - content: shazam - - path: settings/test/all - file_name: secret-c - content: shazam-1 - - path: settings/test/all - file_name: secret-d - content: ()"';@ \(\)\"\'\;\@ - -expected_snapshot: -expected_stderr: -expected_stdout: | - #!/bin/sh - export secret-d='()"'"'"';@ \(\)\"\'"'"'\;\@' - export secret-c='shazam-1' - export secret-b='shazam' - export secret-a='mailman' - export FOO='shazam' - export BAR='shazam' diff --git a/e2e/tests/show.yml b/e2e/tests/show.yml deleted file mode 100644 index bbe49baa..00000000 --- a/e2e/tests/show.yml +++ /dev/null @@ -1,43 +0,0 @@ ---- -name: Show entries -command: show -config_file_name: .teller.yml -config_content: > - project: test - - providers: - filesystem: - env_sync: - path: {{.Folder}}/settings/test/all - env: - FOO: - path: {{.Folder}}/settings/test/foo - BAR: - path: {{.Folder}}/settings/test/bar -init_snapshot: - - path: settings/test - file_name: foo - content: shazam - - path: settings/test - file_name: bar - content: shazam - - path: settings/test/all - file_name: secret-a - content: mailman - - path: settings/test/all - file_name: secret-b - content: shazam - - path: settings/test/all - file_name: secret-c - content: shazam-1 -expected_snapshot: -expected_stderr: | - -*- teller: loaded variables for test using .teller.yml -*- - - [filesystem DYNAMIC-SHORT-PATH...tings/test/bar] BAR = sh***** - [filesystem DYNAMIC-SHORT-PATH...tings/test/foo] FOO = sh***** - [filesystem DYNAMIC-SHORT-PATH...tings/test/all] secret-a = ma***** - [filesystem DYNAMIC-SHORT-PATH...tings/test/all] secret-b = sh***** - [filesystem DYNAMIC-SHORT-PATH...tings/test/all] secret-c = sh***** - -expected_stdout: \ No newline at end of file diff --git a/e2e/tests/version.go b/e2e/tests/version.go deleted file mode 100644 index d08c9548..00000000 --- a/e2e/tests/version.go +++ /dev/null @@ -1,41 +0,0 @@ -package test - -import ( - "errors" - "regexp" - - "github.com/spectralops/teller/e2e/register" -) - -func init() { //nolint - register.AddSuite("version", NewSuiteVersionCommand) -} - -type SuiteVersionCommand struct { - tempFolderPath string -} - -func NewSuiteVersionCommand(tempFolderPath string) register.TestCaseDescriber { - return &SuiteVersionCommand{ - tempFolderPath: tempFolderPath, - } -} - -func (v *SuiteVersionCommand) SetupTest() error { - return nil -} - -func (v *SuiteVersionCommand) GetFlags() []string { - return []string{"version"} -} - -func (v *SuiteVersionCommand) Check(stdOut, stderr string) error { - var re = regexp.MustCompile(`(?m)Teller ([0-9]+)(\.[0-9]+)?(\.[0-9]+) -Revision [a-z0-9]{40}, date: [0-9]{4}-[0-9]{2}-[0-9]{2}`) - - if re.MatchString(stdOut) { - return nil - } - - return errors.New("invalid teller version") -} diff --git a/e2e/tests/yaml.yml b/e2e/tests/yaml.yml deleted file mode 100644 index 94c6b4e1..00000000 --- a/e2e/tests/yaml.yml +++ /dev/null @@ -1,41 +0,0 @@ ---- -name: yaml -command: yaml -config_content: > - project: test - - providers: - filesystem: - env_sync: - path: {{.Folder}}/settings/test/all - env: - FOO: - path: {{.Folder}}/settings/test/foo - BAR: - path: {{.Folder}}/settings/test/bar -config_file_name: .teller.yml -init_snapshot: - - path: settings/test - file_name: foo - content: shazam - - path: settings/test - file_name: bar - content: shazam - - path: settings/test/all - file_name: secret-a - content: mailman - - path: settings/test/all - file_name: secret-b - content: shazam - - path: settings/test/all - file_name: secret-c - content: shazam-1 -expected_snapshot: -expected_stdout: | - BAR: shazam - FOO: shazam - secret-a: mailman - secret-b: shazam - secret-c: shazam-1 - -expected_stderr: \ No newline at end of file diff --git a/e2e/testutils/config.go b/e2e/testutils/config.go deleted file mode 100644 index 791d4fbd..00000000 --- a/e2e/testutils/config.go +++ /dev/null @@ -1,117 +0,0 @@ -package testutils - -import ( - "os" - "path/filepath" - "strings" - "text/template" - - "github.com/karrick/godirwalk" - "gopkg.in/yaml.v2" -) - -type SnapshotSuite struct { - Name string `yaml:"name,omitempty"` - Command string `yaml:"command,omitempty"` - ConfigFileName string `yaml:"config_file_name,omitempty"` - Config string `yaml:"config_content,omitempty"` - InitSnapshot []SnapshotData `yaml:"init_snapshot,omitempty"` - ExpectedSnapshot []SnapshotData `yaml:"expected_snapshot,omitempty"` - ExpectedStdOut string `yaml:"expected_stdout,omitempty"` - ExpectedStdErr string `yaml:"expected_stderr,omitempty"` - ReplaceStdOutContent []ReplaceStdContent `yaml:"replace_stdout_content,omitempty"` - ReplaceStdErrContent []ReplaceStdContent `yaml:"replace_stderr_content,omitempty"` -} - -type SnapshotData struct { - Path string `yaml:"path"` - FileName string `yaml:"file_name"` - Content string `yaml:"content"` -} - -type ReplaceStdContent struct { - Search string `yaml:"search"` - Replace string `yaml:"replace"` -} - -// GetYmlSnapshotSuites returns list of snapshot suite from yml files -func GetYmlSnapshotSuites(folder string) ([]*SnapshotSuite, error) { - - SnapshotSuite := []*SnapshotSuite{} - err := godirwalk.Walk(folder, &godirwalk.Options{ - Callback: func(osPathname string, de *godirwalk.Dirent) error { - - if strings.HasSuffix(osPathname, "yml") { - snapshotSuite, err := loadSnapshotSuite(osPathname) - if err != nil { - return err - } - SnapshotSuite = append(SnapshotSuite, snapshotSuite) - } - - return nil - }, - Unsorted: true, - }) - - return SnapshotSuite, err -} - -// loadSnapshotSuite convert yml file to SnapshotSuite struct -func loadSnapshotSuite(file string) (*SnapshotSuite, error) { - ymlTestFile, err := os.ReadFile(file) - if err != nil { - return nil, err - } - snapshotSuite := &SnapshotSuite{} - err = yaml.Unmarshal(ymlTestFile, snapshotSuite) - if err != nil { - return nil, err - } - return snapshotSuite, nil -} - -func (s *SnapshotSuite) CrateConfig(dir string) error { - f, err := os.Create(filepath.Join(dir, s.ConfigFileName)) - - if err != nil { - return err - } - - defer f.Close() - - t, err := template.New("t").Parse(s.Config) - if err != nil { - return err - } - - type Data struct { - Folder string - } - - return t.Execute(f, Data{Folder: dir}) -} - -// CreateSnapshotData creates filesystem data from the given snapshotData. -// For example, SnapshotData struct descrive the filesystem structure -// └── /folder -// -// ├── settings/ -// │ ├── billing-svc -// │ └── all/ -// │ ├── foo -// └── bar -func (s *SnapshotSuite) CreateSnapshotData(snapshotData []SnapshotData, dir string) error { - - for _, data := range snapshotData { - err := os.MkdirAll(filepath.Join(dir, data.Path), os.ModePerm) - if err != nil { - return err - } - err = os.WriteFile(filepath.Join(dir, data.Path, data.FileName), []byte(data.Content), 0644) //nolint - if err != nil { - return err - } - } - return nil -} diff --git a/e2e/testutils/diff.go b/e2e/testutils/diff.go deleted file mode 100644 index 2786cf5b..00000000 --- a/e2e/testutils/diff.go +++ /dev/null @@ -1,9 +0,0 @@ -package testutils - -type Differ interface { - Diff(dir1, dir2 string, ignores []string) (string, error) -} - -func FolderDiff(d Differ, dir1, dir2 string, ignores []string) (string, error) { - return d.Diff(dir1, dir2, ignores) -} diff --git a/e2e/testutils/exec.go b/e2e/testutils/exec.go deleted file mode 100644 index 9018d71d..00000000 --- a/e2e/testutils/exec.go +++ /dev/null @@ -1,47 +0,0 @@ -package testutils - -import ( - "bytes" - "os/exec" -) - -type DifferExec struct { -} - -func ExecCmd(name string, arg []string, workingDirectory string) (stdout, stderr string, err error) { - - var r []string - for _, str := range arg { - if str != "" { - r = append(r, str) - } - } - cmd := exec.Command(name, r...) - var stdoutBuff bytes.Buffer - var stderrBuff bytes.Buffer - cmd.Dir = workingDirectory - cmd.Stdout = &stdoutBuff - cmd.Stderr = &stderrBuff - - err = cmd.Run() - - return stdoutBuff.String(), stderrBuff.String(), err -} - -func NewExecDiffer() Differ { - return &DifferExec{} -} - -func (de *DifferExec) Diff(dir1, dir2 string, ignores []string) (string, error) { - - flags := []string{"-qr"} - for _, ignore := range ignores { - flags = append(flags, "-x", ignore) - } - - flags = append(flags, dir1, dir2) - stdout, _, err := ExecCmd("diff", flags, "") - - return stdout, err - -} diff --git a/examples/providers/example.go b/examples/providers/example.go deleted file mode 100644 index a65189fe..00000000 --- a/examples/providers/example.go +++ /dev/null @@ -1,76 +0,0 @@ -package providers - -import ( - "fmt" - - "github.com/spectralops/teller/pkg/core" - - "github.com/spectralops/teller/pkg/logging" -) - -type Example struct { - logger logging.Logger -} - -//nolint - -// func init() { -// metaInto := core.MetaInfo{ -// Description: "ProviderName", -// Name: "provider_name", -// Authentication: "If you have the Consul CLI working and configured, there's no special action to take.\nConfiguration is environment based, as defined by client standard. See variables [here](https://github.com/hashicorp/consul/blob/master/api/api.go#L28).", -// ConfigTemplate: ` -// provider: -// env: -// KEY_EAXMPLE: -// path: pathToKey -// `, -// Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true}, -// } -// RegisterProvider(metaInto, NewExample) -// } - -// NewExample creates new provider instance -func NewExample(logger logging.Logger) (core.Provider, error) { - - return &Example{ - logger: logger, - }, nil -} - -// Name return the provider name -func (e *Example) Name() string { - return "Example" -} - -// Put will create a new single entry -func (e *Example) Put(p core.KeyPath, val string) error { - return fmt.Errorf("provider %q does not implement write yet", e.Name()) -} - -// PutMapping will create a multiple entries -func (e *Example) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %q does not implement write yet", e.Name()) -} - -// GetMapping returns a multiple entries -func (e *Example) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - - return []core.EnvEntry{}, fmt.Errorf("provider %q does not implement write yet", e.Name()) -} - -// Get returns a single entry -func (e *Example) Get(p core.KeyPath) (*core.EnvEntry, error) { - - return &core.EnvEntry{}, fmt.Errorf("provider %q does not implement write yet", e.Name()) -} - -// Delete will delete entry -func (e *Example) Delete(kp core.KeyPath) error { - return fmt.Errorf("provider %s does not implement delete yet", e.Name()) -} - -// DeleteMapping will delete the given path recessively -func (e *Example) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("provider %s does not implement delete yet", e.Name()) -} diff --git a/fixtures/mirror-drift/source.env b/fixtures/mirror-drift/source.env deleted file mode 100644 index 921268ad..00000000 --- a/fixtures/mirror-drift/source.env +++ /dev/null @@ -1,3 +0,0 @@ -ONE=1 -TWO=2 -THREE=3 \ No newline at end of file diff --git a/fixtures/mirror-drift/target.env b/fixtures/mirror-drift/target.env deleted file mode 100644 index 3ce551e3..00000000 --- a/fixtures/mirror-drift/target.env +++ /dev/null @@ -1,2 +0,0 @@ -ONE=5 -TWO=2 \ No newline at end of file diff --git a/fixtures/mirror-drift/teller.yml b/fixtures/mirror-drift/teller.yml deleted file mode 100644 index 7e30b543..00000000 --- a/fixtures/mirror-drift/teller.yml +++ /dev/null @@ -1,11 +0,0 @@ -project: mirror-drift - -providers: - source: - kind: dotenv - env_sync: - path: ../fixtures/mirror-drift/source.env - target: - kind: dotenv - env_sync: - path: ../fixtures/mirror-drift/target.env \ No newline at end of file diff --git a/fixtures/providers-export/providers-meta.json b/fixtures/providers-export/providers-meta.json deleted file mode 100644 index 91020bc9..00000000 --- a/fixtures/providers-export/providers-meta.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "version": "1.1", - "providers": { - "Provider_1": { - "Description": "Description of Provider 1", - "Name": "Provider_1", - "Authentication": "Provider 1 authentication instructions", - "ConfigTemplate": "Provider 1 config template", - "Ops": { - "Delete": false, - "DeleteMapping": false, - "Put": true, - "PutMapping": true, - "Get": true, - "GetMapping": true - } - }, - "Provider_2": { - "Description": "Description of Provider 2", - "Name": "Provider_2", - "Authentication": "Provider 2 authentication instructions", - "ConfigTemplate": "Provider 2 config template", - "Ops": { - "Delete": false, - "DeleteMapping": false, - "Put": true, - "PutMapping": true, - "Get": true, - "GetMapping": true - } - } - } -} \ No newline at end of file diff --git a/fixtures/sync/source.env b/fixtures/sync/source.env deleted file mode 100644 index 921268ad..00000000 --- a/fixtures/sync/source.env +++ /dev/null @@ -1,3 +0,0 @@ -ONE=1 -TWO=2 -THREE=3 \ No newline at end of file diff --git a/fixtures/sync/target2.env b/fixtures/sync/target2.env deleted file mode 100644 index 3b11c4ed..00000000 --- a/fixtures/sync/target2.env +++ /dev/null @@ -1,4 +0,0 @@ -FOO="2" -ONE="1" -THREE="3" -TWO="2" \ No newline at end of file diff --git a/fixtures/sync/teller.yml b/fixtures/sync/teller.yml deleted file mode 100644 index a142059b..00000000 --- a/fixtures/sync/teller.yml +++ /dev/null @@ -1,15 +0,0 @@ -project: sync - -providers: - source: - kind: dotenv - env_sync: - path: ../fixtures/sync/source.env - target: - kind: dotenv - env_sync: - path: ../fixtures/sync/target.env - target2: - kind: dotenv - env_sync: - path: ../fixtures/sync/target2.env \ No newline at end of file diff --git a/go.mod b/go.mod deleted file mode 100644 index 16e19fb1..00000000 --- a/go.mod +++ /dev/null @@ -1,175 +0,0 @@ -module github.com/spectralops/teller - -go 1.18 - -require ( - cloud.google.com/go v0.78.0 - github.com/1Password/connect-sdk-go v1.2.0 - github.com/AlecAivazis/survey/v2 v2.2.8 - github.com/Azure/azure-sdk-for-go v52.5.0+incompatible - github.com/Azure/go-autorest/autorest v0.11.18 - github.com/DopplerHQ/cli v0.0.0-20210309042056-414bede8a50e - github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38 - github.com/alecthomas/kong v0.2.15 - github.com/aws/aws-sdk-go-v2 v1.24.1 - github.com/aws/aws-sdk-go-v2/config v1.26.5 - github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.26.2 - github.com/aws/aws-sdk-go-v2/service/ssm v1.44.7 - github.com/cloudflare/cloudflare-go v0.25.0 - github.com/cyberark/conjur-api-go v0.7.1 - github.com/dghubble/sling v1.3.0 - github.com/fatih/color v1.14.1 - github.com/golang/mock v1.6.0 - github.com/google/go-github/v43 v43.0.0 - github.com/googleapis/gax-go/v2 v2.0.5 - github.com/gopasspw/gopass v1.15.4 - github.com/hashicorp/consul/api v1.8.1 - github.com/hashicorp/vault/api v1.0.4 - github.com/heroku/heroku-go/v5 v5.2.1 - github.com/jftuga/ellipsis v1.0.0 - github.com/joho/godotenv v1.3.0 - github.com/karrick/godirwalk v1.16.1 - github.com/mattn/lastpass-go v0.0.0-20160926001517-82bef8502f75 - github.com/mitchellh/go-homedir v1.1.0 - github.com/samber/lo v1.11.0 - github.com/sirupsen/logrus v1.7.0 - github.com/sosedoff/ansible-vault-go v0.2.0 - github.com/stretchr/testify v1.8.1 - github.com/testcontainers/testcontainers-go v0.10.1-0.20210331130832-54854fb15ccb - github.com/tobischo/gokeepasslib/v3 v3.2.5 - go.etcd.io/etcd/api/v3 v3.5.0-alpha.0 - go.etcd.io/etcd/client/v3 v3.5.0-alpha.0 - go.etcd.io/etcd/pkg/v3 v3.5.0-alpha.0 - golang.org/x/crypto v0.8.0 - golang.org/x/oauth2 v0.5.0 - google.golang.org/api v0.40.0 - google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c - gopkg.in/yaml.v2 v2.4.0 - gopkg.in/yaml.v3 v3.0.1 -) - -require github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.10.4 // indirect - -require ( - filippo.io/age v1.1.1 // indirect - filippo.io/edwards25519 v1.0.0 // indirect - github.com/Azure/go-autorest v14.2.0+incompatible // indirect - github.com/Azure/go-autorest/autorest/adal v0.9.13 // indirect - github.com/Azure/go-autorest/autorest/azure/auth v0.5.7 // indirect - github.com/Azure/go-autorest/autorest/azure/cli v0.4.2 // indirect - github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect - github.com/Azure/go-autorest/autorest/to v0.4.0 // indirect - github.com/Azure/go-autorest/autorest/validation v0.3.1 // indirect - github.com/Azure/go-autorest/logger v0.2.1 // indirect - github.com/Azure/go-autorest/tracing v0.6.0 // indirect - github.com/Microsoft/go-winio v0.4.17-0.20210211115548-6eac466e5fa3 // indirect - github.com/Microsoft/hcsshim v0.8.15 // indirect - github.com/ProtonMail/go-crypto v0.0.0-20230201104953-d1d05f4e2bfb // indirect - github.com/aead/argon2 v0.0.0-20180111183520-a87724528b07 // indirect - github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da // indirect - github.com/alecthomas/colour v0.1.0 // indirect - github.com/alecthomas/repr v0.0.0-20201120212035-bb82daffcca2 // indirect - github.com/alessio/shellescape v1.4.1 // indirect - github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da // indirect - github.com/atotto/clipboard v0.1.4 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.16.16 // indirect - github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.11 // indirect - github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.10 // indirect - github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.10 // indirect - github.com/aws/aws-sdk-go-v2/internal/ini v1.7.2 // indirect - github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.10.10 // indirect - github.com/aws/aws-sdk-go-v2/service/sso v1.18.7 // indirect - github.com/aws/aws-sdk-go-v2/service/ssooidc v1.21.7 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.26.7 // indirect - github.com/aws/smithy-go v1.19.0 // indirect - github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect - github.com/blang/semver/v4 v4.0.0 // indirect - github.com/caspr-io/yamlpath v0.0.0-20200722075116-502e8d113a9b // indirect - github.com/cenkalti/backoff v2.2.1+incompatible // indirect - github.com/cloudflare/circl v1.3.2 // indirect - github.com/containerd/cgroups v0.0.0-20200824123100-0b889c03f102 // indirect - github.com/containerd/containerd v1.5.0-beta.1 // indirect - github.com/containerd/continuity v0.0.0-20201208142359-180525291bb7 // indirect - github.com/coreos/go-semver v0.3.0 // indirect - github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect - github.com/danieljoos/wincred v1.1.2 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect - github.com/dimchansky/utfbom v1.1.1 // indirect - github.com/docker/distribution v2.7.1+incompatible // indirect - github.com/docker/docker v20.10.5+incompatible // indirect - github.com/docker/go-connections v0.4.0 // indirect - github.com/docker/go-units v0.4.0 // indirect - github.com/dustin/go-humanize v1.0.1 // indirect - github.com/form3tech-oss/jwt-go v3.2.2+incompatible // indirect - github.com/godbus/dbus/v5 v5.1.0 // indirect - github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e // indirect - github.com/golang/protobuf v1.5.2 // indirect - github.com/golang/snappy v0.0.1 // indirect - github.com/google/go-cmp v0.5.9 // indirect - github.com/google/go-github v17.0.0+incompatible // indirect - github.com/google/go-querystring v1.1.0 // indirect - github.com/google/uuid v1.2.0 // indirect - github.com/hashicorp/errwrap v1.1.0 // indirect - github.com/hashicorp/go-cleanhttp v0.5.1 // indirect - github.com/hashicorp/go-hclog v0.12.0 // indirect - github.com/hashicorp/go-immutable-radix v1.0.0 // indirect - github.com/hashicorp/go-multierror v1.1.1 // indirect - github.com/hashicorp/go-retryablehttp v0.5.4 // indirect - github.com/hashicorp/go-rootcerts v1.0.2 // indirect - github.com/hashicorp/go-sockaddr v1.0.2 // indirect - github.com/hashicorp/golang-lru v0.5.4 // indirect - github.com/hashicorp/hcl v1.0.0 // indirect - github.com/hashicorp/serf v0.9.5 // indirect - github.com/hashicorp/vault/sdk v0.1.13 // indirect - github.com/inconshreveable/mousetrap v1.0.0 // indirect - github.com/jmespath/go-jmespath v0.4.0 // indirect - github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect - github.com/keeper-security/secrets-manager-go/core v1.6.2 - github.com/mattn/go-colorable v0.1.13 // indirect - github.com/mattn/go-isatty v0.0.17 // indirect - github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect - github.com/miekg/dns v1.1.35 // indirect - github.com/mitchellh/mapstructure v1.1.2 // indirect - github.com/moby/sys/mount v0.2.0 // indirect - github.com/moby/sys/mountinfo v0.4.0 // indirect - github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354 // indirect - github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/opencontainers/image-spec v1.0.1 // indirect - github.com/opencontainers/runc v1.0.0-rc93 // indirect - github.com/opentracing/opentracing-go v1.2.0 // indirect - github.com/pborman/uuid v1.2.0 // indirect - github.com/pierrec/lz4 v2.0.5+incompatible // indirect - github.com/pkg/errors v0.9.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/rogpeppe/go-internal v1.9.0 // indirect - github.com/rs/zerolog v1.29.0 // indirect - github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/ryanuber/go-glob v1.0.0 // indirect - github.com/sergi/go-diff v1.1.0 // indirect - github.com/spf13/cobra v0.0.5 // indirect - github.com/spf13/pflag v1.0.5 // indirect - github.com/twpayne/go-pinentry v0.2.0 // indirect - github.com/uber/jaeger-client-go v2.25.0+incompatible // indirect - github.com/uber/jaeger-lib v2.4.0+incompatible // indirect - github.com/urfave/cli/v2 v2.24.3 // indirect - github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect - github.com/zalando/go-keyring v0.2.2 // indirect - go.opencensus.io v0.22.5 // indirect - go.uber.org/atomic v1.10.0 // indirect - go.uber.org/multierr v1.9.0 // indirect - go.uber.org/zap v1.16.0 // indirect - golang.org/x/exp v0.0.0-20230212135524-a684f29349b6 // indirect - golang.org/x/net v0.9.0 // indirect - golang.org/x/sync v0.1.0 // indirect - golang.org/x/sys v0.7.0 // indirect - golang.org/x/term v0.7.0 // indirect - golang.org/x/text v0.9.0 // indirect - golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 // indirect - google.golang.org/appengine v1.6.7 // indirect - google.golang.org/grpc v1.35.0 // indirect - google.golang.org/protobuf v1.28.1 // indirect - gopkg.in/gookit/color.v1 v1.1.6 // indirect - gopkg.in/square/go-jose.v2 v2.3.1 // indirect -) diff --git a/go.sum b/go.sum deleted file mode 100644 index d4bc7073..00000000 --- a/go.sum +++ /dev/null @@ -1,1414 +0,0 @@ -bazil.org/fuse v0.0.0-20160811212531-371fbbdaa898/go.mod h1:Xbm+BRKSBEpa4q4hTSxohYNQpsxXPbPry4JJWOB3LB8= -cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= -cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= -cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= -cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= -cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= -cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= -cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= -cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= -cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= -cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= -cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= -cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= -cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= -cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= -cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= -cloud.google.com/go v0.78.0 h1:oKpsiyKMfVpwR3zSAkQixGzlVE5ovitBuO0qSmCf0bI= -cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= -cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= -cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= -cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= -cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= -cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= -cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= -cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= -cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= -cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= -cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= -cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= -cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= -cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= -cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= -cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= -cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= -cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= -dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= -filippo.io/age v1.1.1 h1:pIpO7l151hCnQ4BdyBujnGP2YlUo0uj6sAVNHGBvXHg= -filippo.io/age v1.1.1/go.mod h1:l03SrzDUrBkdBx8+IILdnn2KZysqQdbEBUQ4p3sqEQE= -filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= -filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= -github.com/1Password/connect-sdk-go v1.2.0 h1:WbIvmbDUpA89nyH0l3LF2iRSFJAv86d2D7IjVNjw6iw= -github.com/1Password/connect-sdk-go v1.2.0/go.mod h1:qK2bF/GweAq812xj+HGfbauaE6cKX1MXfKhpAvoHEq8= -github.com/AlecAivazis/survey/v2 v2.0.8/go.mod h1:9FJRdMdDm8rnT+zHVbvQT2RTSTLq0Ttd6q3Vl2fahjk= -github.com/AlecAivazis/survey/v2 v2.2.8 h1:TgxCwybKdBckmC+/P9/5h49rw/nAHe/itZL0dgHs+Q0= -github.com/AlecAivazis/survey/v2 v2.2.8/go.mod h1:9DYvHgXtiXm6nCn+jXnOXLKbH+Yo9u8fAS/SduGdoPk= -github.com/Azure/azure-sdk-for-go v16.2.1+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= -github.com/Azure/azure-sdk-for-go v52.5.0+incompatible h1:/NLBWHCnIHtZyLPc1P7WIqi4Te4CC23kIQyK3Ep/7lA= -github.com/Azure/azure-sdk-for-go v52.5.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= -github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 h1:w+iIsaOQNcT7OZ575w+acHgRric5iCyQh+xv+KJ4HB8= -github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= -github.com/Azure/go-autorest v10.8.1+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= -github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= -github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= -github.com/Azure/go-autorest/autorest v0.11.1/go.mod h1:JFgpikqFJ/MleTTxwepExTKnFUKKszPS8UavbQYUMuw= -github.com/Azure/go-autorest/autorest v0.11.17/go.mod h1:eipySxLmqSyC5s5k1CLupqet0PSENBEDP93LQ9a8QYw= -github.com/Azure/go-autorest/autorest v0.11.18 h1:90Y4srNYrwOtAgVo3ndrQkTYn6kf1Eg/AjTFJ8Is2aM= -github.com/Azure/go-autorest/autorest v0.11.18/go.mod h1:dSiJPy22c3u0OtOKDNttNgqpNFY/GeWa7GH/Pz56QRA= -github.com/Azure/go-autorest/autorest/adal v0.9.0/go.mod h1:/c022QCutn2P7uY+/oQWWNcK9YU+MH96NgK+jErpbcg= -github.com/Azure/go-autorest/autorest/adal v0.9.5/go.mod h1:B7KF7jKIeC9Mct5spmyCB/A8CG/sEz1vwIRGv/bbw7A= -github.com/Azure/go-autorest/autorest/adal v0.9.11/go.mod h1:nBKAnTomx8gDtl+3ZCJv2v0KACFHWTB2drffI1B68Pk= -github.com/Azure/go-autorest/autorest/adal v0.9.13 h1:Mp5hbtOePIzM8pJVRa3YLrWWmZtoxRXqUEzCfJt3+/Q= -github.com/Azure/go-autorest/autorest/adal v0.9.13/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M= -github.com/Azure/go-autorest/autorest/azure/auth v0.5.7 h1:8DQB8yl7aLQuP+nuR5e2RO6454OvFlSTXXaNHshc16s= -github.com/Azure/go-autorest/autorest/azure/auth v0.5.7/go.mod h1:AkzUsqkrdmNhfP2i54HqINVQopw0CLDnvHpJ88Zz1eI= -github.com/Azure/go-autorest/autorest/azure/cli v0.4.2 h1:dMOmEJfkLKW/7JsokJqkyoYSgmR08hi9KrhjZb+JALY= -github.com/Azure/go-autorest/autorest/azure/cli v0.4.2/go.mod h1:7qkJkT+j6b+hIpzMOwPChJhTqS8VbsqqgULzMNRugoM= -github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= -github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= -github.com/Azure/go-autorest/autorest/mocks v0.4.0/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= -github.com/Azure/go-autorest/autorest/mocks v0.4.1 h1:K0laFcLE6VLTOwNgSxaGbUcLPuGXlNkbVvq4cW4nIHk= -github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= -github.com/Azure/go-autorest/autorest/to v0.4.0 h1:oXVqrxakqqV1UZdSazDOPOLvOIz+XA683u8EctwboHk= -github.com/Azure/go-autorest/autorest/to v0.4.0/go.mod h1:fE8iZBn7LQR7zH/9XU2NcPR4o9jEImooCeWJcYV/zLE= -github.com/Azure/go-autorest/autorest/validation v0.3.1 h1:AgyqjAd94fwNAoTjl/WQXg4VvFeRFpO+UhNyRXqF1ac= -github.com/Azure/go-autorest/autorest/validation v0.3.1/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E= -github.com/Azure/go-autorest/logger v0.2.0/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= -github.com/Azure/go-autorest/logger v0.2.1 h1:IG7i4p/mDa2Ce4TRyAO8IHnVhAVF3RFU+ZtXWSmf4Tg= -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/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak= -github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/DopplerHQ/cli v0.0.0-20210309042056-414bede8a50e h1:X5yHJzv4R12/zF9PR6OlroESbv6Bbz+L5LlZWY+qGkw= -github.com/DopplerHQ/cli v0.0.0-20210309042056-414bede8a50e/go.mod h1:BYiWQL3TJGl8TjMYVeWYxJJK46arOR4J/2urnIJE/jE= -github.com/HdrHistogram/hdrhistogram-go v1.0.1 h1:GX8GAYDuhlFQnI2fRDHQhTlkHMz8bEn0jTI6LJU0mpw= -github.com/HdrHistogram/hdrhistogram-go v1.0.1/go.mod h1:BWJ+nMSHY3L41Zj7CA3uXnloDp7xxV0YvstAE7nKTaM= -github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA= -github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= -github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5/go.mod h1:tTuCMEN+UleMWgg9dVx4Hu52b1bJo+59jBh3ajtinzw= -github.com/Microsoft/go-winio v0.4.16-0.20201130162521-d1ffc52c7331/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0= -github.com/Microsoft/go-winio v0.4.16/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0= -github.com/Microsoft/go-winio v0.4.17-0.20210211115548-6eac466e5fa3 h1:mw6pDQqv38/WGF1cO/jF5t/jyAJ2yi7CmtFLLO5tGFI= -github.com/Microsoft/go-winio v0.4.17-0.20210211115548-6eac466e5fa3/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84= -github.com/Microsoft/hcsshim v0.8.6/go.mod h1:Op3hHsoHPAvb6lceZHDtd9OkTew38wNoXnJs8iY7rUg= -github.com/Microsoft/hcsshim v0.8.7-0.20190325164909-8abdbb8205e4/go.mod h1:Op3hHsoHPAvb6lceZHDtd9OkTew38wNoXnJs8iY7rUg= -github.com/Microsoft/hcsshim v0.8.7/go.mod h1:OHd7sQqRFrYd3RmSgbgji+ctCwkbq2wbEYNSzOYtcBQ= -github.com/Microsoft/hcsshim v0.8.9/go.mod h1:5692vkUqntj1idxauYlpoINNKeqCiG6Sg38RRsjT5y8= -github.com/Microsoft/hcsshim v0.8.14/go.mod h1:NtVKoYxQuTLx6gEq0L96c9Ju4JbRJ4nY2ow3VK6a9Lg= -github.com/Microsoft/hcsshim v0.8.15 h1:Aof83YILRs2Vx3GhHqlvvfyx1asRJKMFIMeVlHsZKtI= -github.com/Microsoft/hcsshim v0.8.15/go.mod h1:x38A4YbHbdxJtc0sF6oIz+RG0npwSCAvn69iY6URG00= -github.com/Microsoft/hcsshim/test v0.0.0-20201218223536-d3e5debf77da/go.mod h1:5hlzMzRKMLyo42nCZ9oml8AdTlq/0cvIaBv6tK1RehU= -github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ= -github.com/Netflix/go-expect v0.0.0-20180615182759-c93bf25de8e8 h1:xzYJEypr/85nBpB11F9br+3HUrpgb+fcm5iADzXXYEw= -github.com/Netflix/go-expect v0.0.0-20180615182759-c93bf25de8e8/go.mod h1:oX5x61PbNXchhh0oikYAH+4Pcfw5LKv21+Jnpr6r6Pc= -github.com/ProtonMail/go-crypto v0.0.0-20230201104953-d1d05f4e2bfb h1:Vx1Bw/nGULx+FuY7Sw+8ZDpOx9XOdA+mOfo678SqkbU= -github.com/ProtonMail/go-crypto v0.0.0-20230201104953-d1d05f4e2bfb/go.mod h1:I0gYDMZ6Z5GRU7l58bNFSkPTFN6Yl12dsUlAZ8xy98g= -github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0= -github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE= -github.com/Shopify/logrus-bugsnag v0.0.0-20171204204709-577dee27f20d/go.mod h1:HI8ITrYtUY+O+ZhtlqUnD8+KwNPOyugEhfP9fdUIaEQ= -github.com/aead/argon2 v0.0.0-20180111183520-a87724528b07 h1:i9/M2RadeVsPBMNwXFiaYkXQi9lY9VuZeI4Onavd3pA= -github.com/aead/argon2 v0.0.0-20180111183520-a87724528b07/go.mod h1:Tnm/osX+XXr9R+S71o5/F0E60sRkPVALdhWw25qPImQ= -github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da h1:KjTM2ks9d14ZYCvmHS9iAKVt9AyzRSqNU1qabPih5BY= -github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da/go.mod h1:eHEWzANqSiWQsof+nXEI9bUVUyV6F53Fp89EuCh2EAA= -github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38 h1:smF2tmSOzy2Mm+0dGI2AIUHY+w0BUc+4tn40djz7+6U= -github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38/go.mod h1:r7bzyVFMNntcxPZXK3/+KdruV1H5KSlyVY0gc+NgInI= -github.com/alecthomas/colour v0.1.0 h1:nOE9rJm6dsZ66RGWYSFrXw461ZIt9A6+nHgL7FRrDUk= -github.com/alecthomas/colour v0.1.0/go.mod h1:QO9JBoKquHd+jz9nshCh40fOfO+JzsoXy8qTHF68zU0= -github.com/alecthomas/kong v0.2.15 h1:HP3K1XuFn0wGSWFGVW67V+65tXw/Ht8FDYiLNAuX2Ug= -github.com/alecthomas/kong v0.2.15/go.mod h1:kQOmtJgV+Lb4aj+I2LEn40cbtawdWJ9Y8QLq+lElKxE= -github.com/alecthomas/repr v0.0.0-20201120212035-bb82daffcca2 h1:G5TeG64Ox4OWq2YwlsxS7nOedU8vbGgNRTRDAjGvDCk= -github.com/alecthomas/repr v0.0.0-20201120212035-bb82daffcca2/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8= -github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= -github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/alessio/shellescape v1.4.1 h1:V7yhSDDn8LP4lc4jS8pFkt0zCnzVJlG5JXy9BVKJUX0= -github.com/alessio/shellescape v1.4.1/go.mod h1:PZAiSCk0LJaZkiCSkPv8qIobYglO3FPpyFjDCtHLS30= -github.com/alexflint/go-filemutex v0.0.0-20171022225611-72bdc8eae2ae/go.mod h1:CgnQgUtFrFz9mxFNtED3jI5tLDjKlOM+oUF/sTk6ps0= -github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= -github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= -github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da h1:8GUt8eRujhVEGZFFEjBj46YV4rDjvGrNxb0KMWYkL2I= -github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= -github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= -github.com/atotto/clipboard v0.1.2/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= -github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= -github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= -github.com/aws/aws-sdk-go v1.15.11/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0= -github.com/aws/aws-sdk-go-v2 v1.24.1 h1:xAojnj+ktS95YZlDf0zxWBkbFtymPeDP+rvUQIH3uAU= -github.com/aws/aws-sdk-go-v2 v1.24.1/go.mod h1:LNh45Br1YAkEKaAqvmE1m8FUx6a5b/V0oAKV7of29b4= -github.com/aws/aws-sdk-go-v2/config v1.26.5 h1:lodGSevz7d+kkFJodfauThRxK9mdJbyutUxGq1NNhvw= -github.com/aws/aws-sdk-go-v2/config v1.26.5/go.mod h1:DxHrz6diQJOc9EwDslVRh84VjjrE17g+pVZXUeSxaDU= -github.com/aws/aws-sdk-go-v2/credentials v1.16.16 h1:8q6Rliyv0aUFAVtzaldUEcS+T5gbadPbWdV1WcAddK8= -github.com/aws/aws-sdk-go-v2/credentials v1.16.16/go.mod h1:UHVZrdUsv63hPXFo1H7c5fEneoVo9UXiz36QG1GEPi0= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.11 h1:c5I5iH+DZcH3xOIMlz3/tCKJDaHFwYEmxvlh2fAcFo8= -github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.11/go.mod h1:cRrYDYAMUohBJUtUnOhydaMHtiK/1NZ0Otc9lIb6O0Y= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.10 h1:vF+Zgd9s+H4vOXd5BMaPWykta2a6Ih0AKLq/X6NYKn4= -github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.10/go.mod h1:6BkRjejp/GR4411UGqkX8+wFMbFbqsUIimfK4XjOKR4= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.10 h1:nYPe006ktcqUji8S2mqXf9c/7NdiKriOwMvWQHgYztw= -github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.10/go.mod h1:6UV4SZkVvmODfXKql4LCbaZUpF7HO2BX38FgBf9ZOLw= -github.com/aws/aws-sdk-go-v2/internal/ini v1.7.2 h1:GrSw8s0Gs/5zZ0SX+gX4zQjRnRsMJDJ2sLur1gRBhEM= -github.com/aws/aws-sdk-go-v2/internal/ini v1.7.2/go.mod h1:6fQQgfuGmw8Al/3M2IgIllycxV7ZW7WCdVSqfBeUiCY= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.10.4 h1:/b31bi3YVNlkzkBrm9LfpaKoaYZUxIAj4sHfOTmLfqw= -github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.10.4/go.mod h1:2aGXHFmbInwgP9ZfpmdIfOELL79zhdNYNmReK8qDfdQ= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.10.10 h1:DBYTXwIGQSGs9w4jKm60F5dmCQ3EEruxdc0MFh+3EY4= -github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.10.10/go.mod h1:wohMUQiFdzo0NtxbBg0mSRGZ4vL3n0dKjLTINdcIino= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.26.2 h1:A5sGOT/mukuU+4At1vkSIWAN8tPwPCoYZBp7aruR540= -github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.26.2/go.mod h1:qutL00aW8GSo2D0I6UEOqMvRS3ZyuBrOC1BLe5D2jPc= -github.com/aws/aws-sdk-go-v2/service/ssm v1.44.7 h1:a8HvP/+ew3tKwSXqL3BCSjiuicr+XTU2eFYeogV9GJE= -github.com/aws/aws-sdk-go-v2/service/ssm v1.44.7/go.mod h1:Q7XIWsMo0JcMpI/6TGD6XXcXcV1DbTj6e9BKNntIMIM= -github.com/aws/aws-sdk-go-v2/service/sso v1.18.7 h1:eajuO3nykDPdYicLlP3AGgOyVN3MOlFmZv7WGTuJPow= -github.com/aws/aws-sdk-go-v2/service/sso v1.18.7/go.mod h1:+mJNDdF+qiUlNKNC3fxn74WWNN+sOiGOEImje+3ScPM= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.21.7 h1:QPMJf+Jw8E1l7zqhZmMlFw6w1NmfkfiSK8mS4zOx3BA= -github.com/aws/aws-sdk-go-v2/service/ssooidc v1.21.7/go.mod h1:ykf3COxYI0UJmxcfcxcVuz7b6uADi1FkiUz6Eb7AgM8= -github.com/aws/aws-sdk-go-v2/service/sts v1.26.7 h1:NzO4Vrau795RkUdSHKEwiR01FaGzGOH1EETJ+5QHnm0= -github.com/aws/aws-sdk-go-v2/service/sts v1.26.7/go.mod h1:6h2YuIoxaMSCFf5fi1EgZAwdfkGMgDY+DVfa61uLe4U= -github.com/aws/smithy-go v1.19.0 h1:KWFKQV80DpP3vJrrA9sVAHQ5gc2z8i4EzrLhLlWXcBM= -github.com/aws/smithy-go v1.19.0/go.mod h1:NukqUGpCZIILqqiV0NIjeFh24kd/FAa4beRb6nbIUPE= -github.com/axw/gocov v1.0.0/go.mod h1:LvQpEYiwwIb2nYkXY2fDWhg9/AsYqkhmrCshjlUJECE= -github.com/beorn7/perks v0.0.0-20160804104726-4c0e84591b9a/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= -github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= -github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= -github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d/go.mod h1:6QX/PXZ00z/TKoufEY6K/a0k6AhaJrQKdFe6OfVXsa4= -github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= -github.com/bitly/go-simplejson v0.5.0/go.mod h1:cXHtHw4XUPsvGaxgjIAn8PhEWG9NfngEKAMDJEczWVA= -github.com/blang/semver v3.1.0+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= -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/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4= -github.com/bshuster-repo/logrus-logstash-hook v0.4.1/go.mod h1:zsTqEiSzDgAa/8GZR7E1qaXrhYNDKBYy5/dWPTIflbk= -github.com/buger/jsonparser v0.0.0-20180808090653-f4dd9f5a6b44/go.mod h1:bbYlZJ7hK1yFx9hf58LP0zeX7UjIGs20ufpu3evjr+s= -github.com/bugsnag/bugsnag-go v0.0.0-20141110184014-b1d153021fcd/go.mod h1:2oa8nejYd4cQ/b0hMIopN0lCRxU0bueqREvZLWFrtK8= -github.com/bugsnag/osext v0.0.0-20130617224835-0dd3f918b21b/go.mod h1:obH5gd0BsqsP2LwDJ9aOkm/6J86V6lyAXCoQWGw3K50= -github.com/bugsnag/panicwrap v0.0.0-20151223152923-e2c28503fcd0/go.mod h1:D/8v3kj0zr8ZAKg1AQ6crr+5VwKN5eIywRkfhyM/+dE= -github.com/bwesterb/go-ristretto v1.2.0/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= -github.com/caspr-io/yamlpath v0.0.0-20200722075116-502e8d113a9b h1:2K3B6Xm7/lnhOugeGB3nIk50bZ9zhuJvXCEfUuL68ik= -github.com/caspr-io/yamlpath v0.0.0-20200722075116-502e8d113a9b/go.mod h1:4rP9T6iHCuPAIDKdNaZfTuuqSIoQQvFctNWIAUI1rlg= -github.com/cenkalti/backoff v2.1.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= -github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= -github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= -github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/checkpoint-restore/go-criu/v4 v4.1.0/go.mod h1:xUQBLp4RLc5zJtWY++yjOoMoB5lihDt7fai+75m+rGw= -github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= -github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= -github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= -github.com/cilium/ebpf v0.0.0-20200110133405-4032b1d8aae3/go.mod h1:MA5e5Lr8slmEg9bt0VpxxWqJlO4iwu3FBdHUzV7wQVg= -github.com/cilium/ebpf v0.0.0-20200702112145-1c8d4c9ef775/go.mod h1:7cR51M8ViRLIdUjrmSXlK9pkrsDlLHbO8jiB8X8JnOc= -github.com/cilium/ebpf v0.2.0/go.mod h1:To2CFviqOWL/M0gIMsvSMlqe7em/l1ALkX1PyjrX2Qs= -github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= -github.com/cloudflare/circl v1.1.0/go.mod h1:prBCrKB9DV4poKZY1l9zBXg2QJY7mvgRvtMxxK7fi4I= -github.com/cloudflare/circl v1.3.2 h1:VWp8dY3yH69fdM7lM6A1+NhhVoDu9vqK0jOgmkQHFWk= -github.com/cloudflare/circl v1.3.2/go.mod h1:+CauBF6R70Jqcyl8N2hC8pAXYbWkGIezuSbuGLtRhnw= -github.com/cloudflare/cloudflare-go v0.25.0 h1:GwyKwGq8ciGNjKiTpjj6RvU3+uJNuPBNjlUkeQRx0yU= -github.com/cloudflare/cloudflare-go v0.25.0/go.mod h1:sPWL/lIC6biLEdyGZwBQ1rGQKF1FhM7N60fuNiFdYTI= -github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= -github.com/containerd/aufs v0.0.0-20200908144142-dab0cbea06f4/go.mod h1:nukgQABAEopAHvB6j7cnP5zJ+/3aVcE7hCYqvIwAHyE= -github.com/containerd/btrfs v0.0.0-20201111183144-404b9149801e/go.mod h1:jg2QkJcsabfHugurUvvPhS3E08Oxiuh5W/g1ybB4e0E= -github.com/containerd/cgroups v0.0.0-20190717030353-c4b9ac5c7601/go.mod h1:X9rLEHIqSf/wfK8NsPqxJmeZgW4pcfzdXITDrUSJ6uI= -github.com/containerd/cgroups v0.0.0-20190919134610-bf292b21730f/go.mod h1:OApqhQ4XNSNC13gXIwDjhOQxjWa/NxkwZXJ1EvqT0ko= -github.com/containerd/cgroups v0.0.0-20200531161412-0dbf7f05ba59/go.mod h1:pA0z1pT8KYB3TCXK/ocprsh7MAkoW8bZVzPdih9snmM= -github.com/containerd/cgroups v0.0.0-20200710171044-318312a37340/go.mod h1:s5q4SojHctfxANBDvMeIaIovkq29IP48TKAxnhYRxvo= -github.com/containerd/cgroups v0.0.0-20200824123100-0b889c03f102 h1:Qf4HiqfvmB7zS6scsmNgTLmByHbq8n9RTF39v+TzP7A= -github.com/containerd/cgroups v0.0.0-20200824123100-0b889c03f102/go.mod h1:s5q4SojHctfxANBDvMeIaIovkq29IP48TKAxnhYRxvo= -github.com/containerd/console v0.0.0-20180822173158-c12b1e7919c1/go.mod h1:Tj/on1eG8kiEhd0+fhSDzsPAFESxzBBvdyEgyryXffw= -github.com/containerd/console v0.0.0-20181022165439-0650fd9eeb50/go.mod h1:Tj/on1eG8kiEhd0+fhSDzsPAFESxzBBvdyEgyryXffw= -github.com/containerd/console v0.0.0-20191206165004-02ecf6a7291e/go.mod h1:8Pf4gM6VEbTNRIT26AyyU7hxdQU3MvAvxVI0sc00XBE= -github.com/containerd/console v1.0.1/go.mod h1:XUsP6YE/mKtz6bxc+I8UiKKTP04qjQL4qcS3XoQ5xkw= -github.com/containerd/containerd v1.2.10/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= -github.com/containerd/containerd v1.3.0-beta.2.0.20190828155532-0293cbd26c69/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= -github.com/containerd/containerd v1.3.0/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= -github.com/containerd/containerd v1.3.1-0.20191213020239-082f7e3aed57/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= -github.com/containerd/containerd v1.3.2/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= -github.com/containerd/containerd v1.4.0-beta.2.0.20200729163537-40b22ef07410/go.mod h1:bC6axHOhabU15QhwfG7w5PipXdVtMXFTttgp+kVtyUA= -github.com/containerd/containerd v1.5.0-beta.1 h1:IK6yirB4X7wpKyFSikWiT++nZsyIxGAAgNEv3fEGuls= -github.com/containerd/containerd v1.5.0-beta.1/go.mod h1:5HfvG1V2FsKesEGQ17k5/T7V960Tmcumvqn8Mc+pCYQ= -github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= -github.com/containerd/continuity v0.0.0-20190815185530-f2a389ac0a02/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= -github.com/containerd/continuity v0.0.0-20191127005431-f65d91d395eb/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= -github.com/containerd/continuity v0.0.0-20200710164510-efbc4488d8fe/go.mod h1:cECdGN1O8G9bgKTlLhuPJimka6Xb/Gg7vYzCTNVxhvo= -github.com/containerd/continuity v0.0.0-20201208142359-180525291bb7 h1:6ejg6Lkk8dskcM7wQ28gONkukbQkM4qpj4RnYbpFzrI= -github.com/containerd/continuity v0.0.0-20201208142359-180525291bb7/go.mod h1:kR3BEg7bDFaEddKm54WSmrol1fKWDU1nKYkgrcgZT7Y= -github.com/containerd/fifo v0.0.0-20180307165137-3d5202aec260/go.mod h1:ODA38xgv3Kuk8dQz2ZQXpnv/UZZUHUCL7pnLehbXgQI= -github.com/containerd/fifo v0.0.0-20190226154929-a9fb20d87448/go.mod h1:ODA38xgv3Kuk8dQz2ZQXpnv/UZZUHUCL7pnLehbXgQI= -github.com/containerd/fifo v0.0.0-20200410184934-f15a3290365b/go.mod h1:jPQ2IAeZRCYxpS/Cm1495vGFww6ecHmMk1YJH2Q5ln0= -github.com/containerd/fifo v0.0.0-20201026212402-0724c46b320c/go.mod h1:jPQ2IAeZRCYxpS/Cm1495vGFww6ecHmMk1YJH2Q5ln0= -github.com/containerd/go-cni v1.0.1/go.mod h1:+vUpYxKvAF72G9i1WoDOiPGRtQpqsNW/ZHtSlv++smU= -github.com/containerd/go-runc v0.0.0-20180907222934-5a6d9f37cfa3/go.mod h1:IV7qH3hrUgRmyYrtgEeGWJfWbgcHL9CSRruz2Vqcph0= -github.com/containerd/go-runc v0.0.0-20190911050354-e029b79d8cda/go.mod h1:IV7qH3hrUgRmyYrtgEeGWJfWbgcHL9CSRruz2Vqcph0= -github.com/containerd/go-runc v0.0.0-20200220073739-7016d3ce2328/go.mod h1:PpyHrqVs8FTi9vpyHwPwiNEGaACDxT/N/pLcvMSRA9g= -github.com/containerd/imgcrypt v1.0.1/go.mod h1:mdd8cEPW7TPgNG4FpuP3sGBiQ7Yi/zak9TYCG3juvb0= -github.com/containerd/nri v0.0.0-20201007170849-eb1350a75164/go.mod h1:+2wGSDGFYfE5+So4M5syatU0N0f0LbWpuqyMi4/BE8c= -github.com/containerd/ttrpc v0.0.0-20190828154514-0e0f228740de/go.mod h1:PvCDdDGpgqzQIzDW1TphrGLssLDZp2GuS+X5DkEJB8o= -github.com/containerd/ttrpc v0.0.0-20190828172938-92c8520ef9f8/go.mod h1:PvCDdDGpgqzQIzDW1TphrGLssLDZp2GuS+X5DkEJB8o= -github.com/containerd/ttrpc v0.0.0-20191028202541-4f1b8fe65a5c/go.mod h1:LPm1u0xBw8r8NOKoOdNMeVHSawSsltak+Ihv+etqsE8= -github.com/containerd/ttrpc v1.0.1/go.mod h1:UAxOpgT9ziI0gJrmKvgcZivgxOp8iFPSk8httJEt98Y= -github.com/containerd/ttrpc v1.0.2/go.mod h1:UAxOpgT9ziI0gJrmKvgcZivgxOp8iFPSk8httJEt98Y= -github.com/containerd/typeurl v0.0.0-20180627222232-a93fcdb778cd/go.mod h1:Cm3kwCdlkCfMSHURc+r6fwoGH6/F1hH3S4sg0rLFWPc= -github.com/containerd/typeurl v0.0.0-20190911142611-5eb25027c9fd/go.mod h1:GeKYzf2pQcqv7tJ0AoCuuhtnqhva5LNU3U+OyKxxJpk= -github.com/containerd/typeurl v1.0.1/go.mod h1:TB1hUtrpaiO88KEK56ijojHS1+NeF0izUACaJW2mdXg= -github.com/containerd/zfs v0.0.0-20200918131355-0a33824f23a2/go.mod h1:8IgZOBdv8fAgXddBT4dBXJPtxyRsejFIpXoklgxgEjw= -github.com/containernetworking/cni v0.7.1/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY= -github.com/containernetworking/cni v0.8.0/go.mod h1:LGwApLUm2FpoOfxTDEeq8T9ipbpZ61X79hmU3w8FmsY= -github.com/containernetworking/plugins v0.8.6/go.mod h1:qnw5mN19D8fIwkqW7oHHYDHVlzhJpcY6TQxn/fUyDDM= -github.com/containers/ocicrypt v1.0.1/go.mod h1:MeJDzk1RJHv89LjsH0Sp5KTY3ZYkjXO/C+bKAeWFIrc= -github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= -github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= -github.com/coreos/go-iptables v0.4.5/go.mod h1:/mVI274lEDI2ns62jHCDnCyBF9Iwsmekav8Dbxlm1MU= -github.com/coreos/go-oidc v2.1.0+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc= -github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-semver v0.3.0 h1:wkHLiw0WNATZnSG7epLsujiMCgPAc9xhjJ4tgnAxmfM= -github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= -github.com/coreos/go-systemd v0.0.0-20161114122254-48702e0da86b/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/coreos/go-systemd/v22 v22.0.0/go.mod h1:xO0FLkIi5MaZafQlIrOotqXZ90ih+1atmu1JpKERPPk= -github.com/coreos/go-systemd/v22 v22.1.0/go.mod h1:xO0FLkIi5MaZafQlIrOotqXZ90ih+1atmu1JpKERPPk= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534 h1:rtAn27wIbmOGUs7RIbVgPEjb31ehTVniDwPGXyMxm5U= -github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= -github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= -github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= -github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= -github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/cyberark/conjur-api-go v0.7.1 h1:nMWB1s0d8a8fGTeAkQIb8KLY9kTFwevgNg6tE2lMcao= -github.com/cyberark/conjur-api-go v0.7.1/go.mod h1:HZ5RoBhAB2KwnxyXbQ29DwpviRVg7SMRq7QhwtFjN3Q= -github.com/cyphar/filepath-securejoin v0.2.2/go.mod h1:FpkQEhXnPnOthhzymB7CGsFk2G9VLXONKD9G7QGMM+4= -github.com/d2g/dhcp4 v0.0.0-20170904100407-a1d1b6c41b1c/go.mod h1:Ct2BUK8SB0YC1SMSibvLzxjeJLnrYEVLULFNiHY9YfQ= -github.com/d2g/dhcp4client v1.0.0/go.mod h1:j0hNfjhrt2SxUOw55nL0ATM/z4Yt3t2Kd1mW34z5W5s= -github.com/d2g/dhcp4server v0.0.0-20181031114812-7d4a0a7f59a5/go.mod h1:Eo87+Kg/IX2hfWJfwxMzLyuSZyxSoAug2nGa1G2QAi8= -github.com/d2g/hardwareaddr v0.0.0-20190221164911-e7d9fbe030e4/go.mod h1:bMl4RjIciD2oAxI7DmWRx6gbeqrkoLqv3MV0vzNad+I= -github.com/danieljoos/wincred v1.1.0/go.mod h1:XYlo+eRTsVA9aHGp7NGjFkPla4m+DCL7hqDjlFjiygg= -github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0= -github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/denverdino/aliyungo v0.0.0-20190125010748-a747050bb1ba/go.mod h1:dV8lFg6daOBZbT6/BDGIz6Y3WFGn8juu6G+CQ6LHtl0= -github.com/dghubble/sling v1.3.0 h1:pZHjCJq4zJvc6qVQ5wN1jo5oNZlNE0+8T/h0XeXBUKU= -github.com/dghubble/sling v1.3.0/go.mod h1:XXShWaBWKzNLhu2OxikSNFrlsvowtz4kyRuXUG7oQKY= -github.com/dgrijalva/jwt-go v0.0.0-20170104182250-a601269ab70c/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= -github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= -github.com/dimchansky/utfbom v1.1.1 h1:vV6w1AhK4VMnhBno/TPVCoK9U/LP0PkLCS9tbxHdi/U= -github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE= -github.com/dnaeon/go-vcr v1.0.1/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= -github.com/docker/distribution v0.0.0-20190905152932-14b96e55d84c/go.mod h1:0+TTO4EOBfRPhZXAeF1Vu+W3hHZ8eLp8PgKVZlcvtFY= -github.com/docker/distribution v2.7.1-0.20190205005809-0d3efadf0154+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/distribution v2.7.1+incompatible h1:a5mlkVzth6W5A4fOsS3D2EO5BUmsJpcB+cRlLU7cSug= -github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v20.10.5+incompatible h1:o5WL5onN4awYGwrW7+oTn5x9AF2prw7V0Ox8ZEkoCdg= -github.com/docker/docker v20.10.5+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= -github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= -github.com/docker/go-events v0.0.0-20170721190031-9461782956ad/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= -github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c/go.mod h1:Uw6UezgYA44ePAFQYUehOuCzmy5zmg/+nl2ZfMWGkpA= -github.com/docker/go-metrics v0.0.0-20180209012529-399ea8c73916/go.mod h1:/u0gXw0Gay3ceNrsHubL3BtdOL2fHf93USgMTe0W5dI= -github.com/docker/go-metrics v0.0.1/go.mod h1:cG1hvH2utMXtqgqqYE9plW6lDxS3/5ayHzueweSI3Vw= -github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw= -github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= -github.com/docker/libtrust v0.0.0-20150114040149-fa567046d9b1/go.mod h1:cyGadeNEkKy96OOhEzfZl+yxihPEzKnqJwvfuSUqbZE= -github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM= -github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= -github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= -github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= -github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= -github.com/emicklei/go-restful v2.9.5+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs= -github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= -github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= -github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= -github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= -github.com/fatih/color v1.14.1 h1:qfhVLaG5s+nCROl1zJsZRxFeYrHLqWroPOQ8BWiNb4w= -github.com/fatih/color v1.14.1/go.mod h1:2oHN61fhTpgcxD3TSWCgKDiH1+x4OiDVVGH8WlgGZGg= -github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= -github.com/form3tech-oss/jwt-go v3.2.2+incompatible h1:TcekIExNqud5crz4xD2pavyTgWiPvpYe4Xau31I0PRk= -github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= -github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= -github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa/go.mod h1:KnogPXtdwXqoenmZCw6S+25EAm2MkxbG0deNDu4cbSA= -github.com/garyburd/redigo v0.0.0-20150301180006-535138d7bcd7/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY= -github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= -github.com/go-ini/ini v1.25.4/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= -github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= -github.com/go-ldap/ldap v3.0.2+incompatible/go.mod h1:qfd9rJvER9Q0/D/Sqn1DfHRoBp40uXYvFoEVrNEPqRc= -github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= -github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= -github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= -github.com/go-openapi/errors v0.19.2/go.mod h1:qX0BLWsyaKfvhluLejVpVNwNRdXZhEbTA4kxxpKBC94= -github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg= -github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonreference v0.19.2/go.mod h1:jMjeRr2HHw6nAVajTXJ4eiUwohSTlpa0o73RUL1owJc= -github.com/go-openapi/jsonreference v0.19.3/go.mod h1:rjx6GuL8TTa9VaixXglHmQmIL98+wF9xc8zWvFonSJ8= -github.com/go-openapi/spec v0.19.3/go.mod h1:FpwSN1ksY1eteniUU7X0N/BgJ7a4WvBFVA8Lj9mJglo= -github.com/go-openapi/strfmt v0.19.3/go.mod h1:0yX7dbo8mKIvc3XSKp7MNfxw4JytCfCD6+bY1AVL9LU= -github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= -github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= -github.com/go-redis/redis v6.15.9+incompatible h1:K0pv1D7EQUjfyoMql+r/jZqCLizCGKFlFgcHWWmHQjg= -github.com/go-redis/redis v6.15.9+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= -github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= -github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= -github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= -github.com/go-test/deep v1.0.2-0.20181118220953-042da051cf31/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= -github.com/godbus/dbus v0.0.0-20151105175453-c7fdd8b5cd55/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= -github.com/godbus/dbus v0.0.0-20180201030542-885f9cc04c9c/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= -github.com/godbus/dbus v0.0.0-20190422162347-ade71ed3457e/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= -github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= -github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/gogo/googleapis v1.2.0/go.mod h1:Njal3psf3qN6dwBtQfUmBZh2ybovJ0tlu3o/AC7HYjU= -github.com/gogo/googleapis v1.4.0/go.mod h1:5YRNX2z1oM5gXdAkurHa942MDgEJyk02w4OecKY87+c= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= -github.com/gogo/protobuf v1.2.2-0.20190723190241-65acae22fc9d/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= -github.com/gogo/protobuf v1.3.0/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= -github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= -github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= -github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= -github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY= -github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= -github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= -github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= -github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= -github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= -github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= -github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= -github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= -github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= -github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.1/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.4/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.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= -github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY= -github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= -github.com/google/go-github/v43 v43.0.0 h1:y+GL7LIsAIF2NZlJ46ZoC/D1W1ivZasT0lnWHMYPZ+U= -github.com/google/go-github/v43 v43.0.0/go.mod h1:ZkTvvmCXBvsfPpTHXnH/d2hP9Y0cTbvN9kr5xqyXOIc= -github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= -github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= -github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= -github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= -github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= -github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs= -github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= -github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= -github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/googleapis/gnostic v0.4.1/go.mod h1:LRhVm6pbyptWbWbuZ38d1eyptfvIytN3ir6b65WBswg= -github.com/gopasspw/gopass v1.15.4 h1:ebs6oQgtxrpvM9IaXmG67fd69+kczuF37PBcUutWzaw= -github.com/gopasspw/gopass v1.15.4/go.mod h1:u98G2rOj5h92lLq9ltKUfZOHpjgQoS7ZgG6kqIcmQvQ= -github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00 h1:l5lAOZEym3oK3SQ2HBHWsJUfbNBiTXJDeW2QDxw9AQ0= -github.com/gopherjs/gopherjs v0.0.0-20200217142428-fce0ec30dd00/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= -github.com/gorilla/handlers v0.0.0-20150720190736-60c7bfde3e33/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= -github.com/gorilla/mux v1.7.2 h1:zoNxOV7WjqXptQOVngLmcSQgXmgk4NMz1HibBchjl/I= -github.com/gorilla/mux v1.7.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= -github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= -github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= -github.com/grpc-ecosystem/grpc-gateway v1.14.6/go.mod h1:zdiPV4Yse/1gnckTHtghG4GkDEdKCRJduHpTxT3/jcw= -github.com/hashicorp/consul/api v1.8.1 h1:BOEQaMWoGMhmQ29fC26bi0qb7/rId9JzZP2V0Xmx7m8= -github.com/hashicorp/consul/api v1.8.1/go.mod h1:sDjTOq0yUyv5G4h+BqSea7Fn6BU+XbolEz1952UB+mk= -github.com/hashicorp/consul/sdk v0.7.0 h1:H6R9d008jDcHPQPAqPNuydAshJ4v5/8URdFnUvK/+sc= -github.com/hashicorp/consul/sdk v0.7.0/go.mod h1:fY08Y9z5SvJqevyZNy6WWPXiG3KwBPAvlcdx16zZ0fM= -github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= -github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= -github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-hclog v0.0.0-20180709165350-ff2cf002a8dd/go.mod h1:9bjs9uLqI8l75knNv3lV1kA55veR+WUPSiKIWcQHudI= -github.com/hashicorp/go-hclog v0.8.0/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= -github.com/hashicorp/go-hclog v0.12.0 h1:d4QkX8FRTYaKaCZBoXYY8zJX2BXjWxurN/GA2tkrmZM= -github.com/hashicorp/go-hclog v0.12.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ= -github.com/hashicorp/go-immutable-radix v1.0.0 h1:AKDB1HM5PWEA7i4nhcpwOrO2byshxBjXVn/J/3+z5/0= -github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= -github.com/hashicorp/go-msgpack v0.5.3 h1:zKjpN5BK/P5lMYrLmBHdBULWbJ0XpYR+7NGzqkZzoD4= -github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= -github.com/hashicorp/go-multierror v0.0.0-20161216184304-ed905158d874/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= -github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= -github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA= -github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= -github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/hashicorp/go-plugin v1.0.1/go.mod h1:++UyYGoz3o5w9ZzAdZxtQKrWWP+iqPBn3cQptSMzBuY= -github.com/hashicorp/go-retryablehttp v0.5.4 h1:1BZvpawXoJCWX6pNtow9+rpEj+3itIlutiqnntI6jOE= -github.com/hashicorp/go-retryablehttp v0.5.4/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= -github.com/hashicorp/go-rootcerts v1.0.1/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= -github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5Oi2viEzc= -github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= -github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= -github.com/hashicorp/go-sockaddr v1.0.2 h1:ztczhD1jLxIRjVejw8gFomI1BQZOe2WoVOu0SyteCQc= -github.com/hashicorp/go-sockaddr v1.0.2/go.mod h1:rB4wwRAUzs07qva3c5SdrY/NEtAUjGlgmH/UkBUC97A= -github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= -github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-uuid v1.0.1 h1:fv1ep09latC32wFoVwnqcnKJGnMSdBanPczbHAYm1BE= -github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= -github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= -github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= -github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= -github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= -github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= -github.com/hashicorp/mdns v1.0.1/go.mod h1:4gW7WsVCke5TE7EPeYliwHlRUyBtfCwuFwuMg2DmyNY= -github.com/hashicorp/memberlist v0.2.2 h1:5+RffWKwqJ71YPu9mWsF7ZOscZmwfasdA8kbdC7AO2g= -github.com/hashicorp/memberlist v0.2.2/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE= -github.com/hashicorp/serf v0.9.5 h1:EBWvyu9tcRszt3Bxp3KNssBMP1KuHWyO51lz9+786iM= -github.com/hashicorp/serf v0.9.5/go.mod h1:UWDWwZeL5cuWDJdl0C6wrvrUwEqtQ4ZKBKKENpqIUyk= -github.com/hashicorp/vault/api v1.0.4 h1:j08Or/wryXT4AcHj1oCbMd7IijXcKzYUGw59LGu9onU= -github.com/hashicorp/vault/api v1.0.4/go.mod h1:gDcqh3WGcR1cpF5AJz/B1UFheUEneMoIospckxBxk6Q= -github.com/hashicorp/vault/sdk v0.1.13 h1:mOEPeOhT7jl0J4AMl1E705+BcmeRs1VmKNb9F0sMLy8= -github.com/hashicorp/vault/sdk v0.1.13/go.mod h1:B+hVj7TpuQY1Y/GPbCpffmgd+tSEwvhkWnjtSYCaS2M= -github.com/hashicorp/yamux v0.0.0-20180604194846-3520598351bb/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= -github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM= -github.com/heroku/heroku-go/v5 v5.2.1 h1:5g379GyHuOI3qhb1ujFwQ13Kjt96M+KMkV8s7omg+do= -github.com/heroku/heroku-go/v5 v5.2.1/go.mod h1:d+1QrZyjbnQJG1f8xIoVvMQRFLt3XRVZOdlm26Sr73U= -github.com/hinshun/vt10x v0.0.0-20180616224451-1954e6464174 h1:WlZsjVhE8Af9IcZDGgJGQpNflI3+MJSBhsgT5PCtzBQ= -github.com/hinshun/vt10x v0.0.0-20180616224451-1954e6464174/go.mod h1:DqJ97dSdRW1W22yXSB90986pcOyQ7r45iio1KN2ez1A= -github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= -github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= -github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= -github.com/imdario/mergo v0.3.10/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= -github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= -github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/interagent/schematic v0.0.0-20180830170528-b5e8ba7aa570/go.mod h1:4X9u5iNUePRrRDdwjok6skjlQBXTcNfWa4C3uS1+5SQ= -github.com/j-keck/arping v0.0.0-20160618110441-2cf9dc699c56/go.mod h1:ymszkNOg6tORTn+6F6j+Jc8TOr5osrynvN6ivFWZ2GA= -github.com/jedib0t/go-pretty v4.3.0+incompatible/go.mod h1:XemHduiw8R651AF9Pt4FwCTKeG3oo7hrHJAoznj9nag= -github.com/jftuga/ellipsis v1.0.0 h1:ERi1XBFERM2YpadkvM1P9bxQKgOC40Hr6TCKkvLBDtY= -github.com/jftuga/ellipsis v1.0.0/go.mod h1:phJ3vQPi8MPrtRKdo0aESNJdw56f09SLVX0k/FY+jr0= -github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jmespath/go-jmespath v0.0.0-20160803190731-bd40a432e4c7/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= -github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= -github.com/jmespath/go-jmespath v0.4.0/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/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc= -github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= -github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= -github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= -github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= -github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= -github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= -github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= -github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/karrick/godirwalk v1.16.1 h1:DynhcF+bztK8gooS0+NDJFrdNZjJ3gzVzC545UNA9iw= -github.com/karrick/godirwalk v1.16.1/go.mod h1:j4mkqPuvaLI8mp1DroR3P6ad7cyYd4c1qeJ3RV7ULlk= -github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= -github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= -github.com/keeper-security/secrets-manager-go/core v1.6.2 h1:bRZUJI/s5WwVbceSNlKyKqYuBNKkZCyNPH4lU2GYiF0= -github.com/keeper-security/secrets-manager-go/core v1.6.2/go.mod h1:dtlaeeds9+SZsbDAZnQRsDSqEAK9a62SYtqhNql+VgQ= -github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= -github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= -github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.11.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/pty v1.1.4/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/pty v1.1.5 h1:hyz3dwM5QLc1Rfoz4FuWJQG5BN7tc6K1MndAUnGpQr4= -github.com/kr/pty v1.1.5/go.mod h1:9r2w37qlBe7rQ6e1fg1S/9xpWHSnaqNdHD3WcMdbPDA= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= -github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs= -github.com/marstr/guid v1.1.0/go.mod h1:74gB1z2wpxxInTG6yaqA7KrtM0NZ+RbrcqDvYHefzho= -github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= -github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= -github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= -github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= -github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= -github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= -github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= -github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= -github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= -github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= -github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= -github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= -github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= -github.com/mattn/go-runewidth v0.0.5/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= -github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= -github.com/mattn/go-shellwords v1.0.3/go.mod h1:3xCvwCdWdlDJUrvuMn7Wuy9eWs4pE8vqg+NOMyg4B2o= -github.com/mattn/lastpass-go v0.0.0-20160926001517-82bef8502f75 h1:zeHg49NDkgehebyDdIxz8fqUgG/rmuVs1A0lOInmRJg= -github.com/mattn/lastpass-go v0.0.0-20160926001517-82bef8502f75/go.mod h1:QuMpIepjU37tLzqJ6/kNGOr8x9obTTL5gNi1DPUSY3o= -github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= -github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= -github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4= -github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE= -github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= -github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso= -github.com/miekg/dns v1.1.35 h1:oTfOaDH+mZkdcgdIjH6yBajRGtIwcwcaR+rt23ZSrJs= -github.com/miekg/dns v1.1.35/go.mod h1:KNUDUusw/aVsxyTYZM1oqvCicbwhgbNgztCETuNZ7xM= -github.com/mistifyio/go-zfs v2.1.2-0.20190413222219-f784269be439+incompatible/go.mod h1:8AuVvqP/mXw1px98n46wfvcGfQ4ci2FwoAjKYxuo3Z4= -github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= -github.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI= -github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= -github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-testing-interface v0.0.0-20171004221916-a61a99592b77/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/go-testing-interface v1.0.0 h1:fzU/JVNcaqHQEcVFAKeR41fkiLdIPrefOvVG1VZ96U0= -github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= -github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= -github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= -github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/osext v0.0.0-20151018003038-5e2d6d41470f/go.mod h1:OkQIRizQZAeMln+1tSwduZz7+Af5oFlKirV/MSYes2A= -github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/moby/sys/mount v0.2.0 h1:WhCW5B355jtxndN5ovugJlMFJawbUODuW8fSnEH6SSM= -github.com/moby/sys/mount v0.2.0/go.mod h1:aAivFE2LB3W4bACsUXChRHQ0qKWsetY4Y9V7sxOougM= -github.com/moby/sys/mountinfo v0.4.0 h1:1KInV3Huv18akCu58V7lzNlt+jFmqlu1EaErnEHE/VM= -github.com/moby/sys/mountinfo v0.4.0/go.mod h1:rEr8tzG/lsIZHBtN/JjGG+LMYx9eXgW2JI+6q0qou+A= -github.com/moby/sys/symlink v0.1.0/go.mod h1:GGDODQmbFOjFsXvfLVn3+ZRxkch54RkSiGqsZeMYowQ= -github.com/moby/term v0.0.0-20200312100748-672ec06f55cd h1:aY7OQNf2XqY/JQ6qREWamhI/81os/agb2BAGpcx5yWI= -github.com/moby/term v0.0.0-20200312100748-672ec06f55cd/go.mod h1:DdlQx2hp0Ss5/fLikoLlEeIYiATotOjgB//nb973jeo= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c h1:nXxl5PrvVm2L/wCy8dQu6DMTwH4oIuGN8GJDAlqDdVE= -github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= -github.com/mrunalp/fileutils v0.5.0/go.mod h1:M1WthSahJixYnrXQl/DFQuteStB1weuxD2QJNHXfbSQ= -github.com/munnerz/goautoneg v0.0.0-20120707110453-a547fc61f48d/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= -github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354 h1:4kuARK6Y6FxaNu/BnU2OAaLF86eTVhP2hjTB6iMvItA= -github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354/go.mod h1:KSVJerMDfblTH7p5MZaTt+8zaT2iEk3AkVb9PQdZuE8= -github.com/ncw/swift v1.0.47/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= -github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= -github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= -github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= -github.com/onsi/ginkgo v0.0.0-20151202141238-7f8ab55aaf3b/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v0.0.0-20170829012221-11459a886d9c/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.11.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= -github.com/onsi/gomega v0.0.0-20151007035656-2152b45fa28a/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= -github.com/onsi/gomega v0.0.0-20170829124025-dcabb60a477c/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= -github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= -github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= -github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA= -github.com/opencontainers/go-digest v0.0.0-20170106003457-a6d0ee40d420/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= -github.com/opencontainers/go-digest v0.0.0-20180430190053-c9281466c8b2/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= -github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= -github.com/opencontainers/go-digest v1.0.0-rc1.0.20180430190053-c9281466c8b2/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= -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.0.0/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= -github.com/opencontainers/image-spec v1.0.1 h1:JMemWkRwHx4Zj+fVxWoMCFm/8sYGGrUVojFA6h/TRcI= -github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= -github.com/opencontainers/runc v0.0.0-20190115041553-12f6a991201f/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= -github.com/opencontainers/runc v0.1.1/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= -github.com/opencontainers/runc v1.0.0-rc8.0.20190926000215-3e425f80a8c9/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= -github.com/opencontainers/runc v1.0.0-rc9/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= -github.com/opencontainers/runc v1.0.0-rc93 h1:x2UMpOOVf3kQ8arv/EsDGwim8PTNqzL1/EYDr/+scOM= -github.com/opencontainers/runc v1.0.0-rc93/go.mod h1:3NOsor4w32B2tC0Zbl8Knk4Wg84SM2ImC1fxBuqJ/H0= -github.com/opencontainers/runtime-spec v0.1.2-0.20190507144316-5b71a03e2700/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= -github.com/opencontainers/runtime-spec v1.0.1/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= -github.com/opencontainers/runtime-spec v1.0.2-0.20190207185410-29686dbc5559/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= -github.com/opencontainers/runtime-spec v1.0.2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= -github.com/opencontainers/runtime-spec v1.0.3-0.20200929063507-e6143ca7d51d/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= -github.com/opencontainers/runtime-tools v0.0.0-20181011054405-1d69bd0f9c39/go.mod h1:r3f7wjNzSs2extwzU3Y+6pKfobzPh+kKFJ3ofN+3nfs= -github.com/opencontainers/selinux v1.6.0/go.mod h1:VVGKuOLlE7v4PJyT6h7mNWvq1rzqiriPsEqVhc+svHE= -github.com/opencontainers/selinux v1.8.0/go.mod h1:RScLhm78qiWa2gbVCcGkC7tCGdgk3ogry1nUQF8Evvo= -github.com/opentracing/opentracing-go v1.2.0 h1:uEJPy/1a5RIPAJ0Ov+OIO8OxWu77jEv+1B0VhjKrZUs= -github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= -github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= -github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= -github.com/pborman/uuid v1.2.0 h1:J7Q5mO4ysT1dv8hyrUGHb9+ooztCXu1D8MY8DZYsu3g= -github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= -github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= -github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= -github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= -github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.8.1-0.20171018195549-f15c970de5b7/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= -github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= -github.com/pquerna/cachecontrol v0.0.0-20171018203845-0dec1b30a021/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA= -github.com/prometheus/client_golang v0.0.0-20180209125602-c332b6f63c06/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= -github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= -github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= -github.com/prometheus/client_golang v1.5.1/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= -github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= -github.com/prometheus/client_model v0.0.0-20171117100541-99fa1f4be8e5/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= -github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/common v0.0.0-20180110214958-89604d197083/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= -github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= -github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= -github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= -github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= -github.com/prometheus/procfs v0.0.0-20180125133057-cb4147076ac7/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/prometheus/procfs v0.0.0-20190522114515-bc1a522cf7b1/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= -github.com/prometheus/procfs v0.0.5/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= -github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= -github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/prometheus/procfs v0.2.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= -github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= -github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= -github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= -github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= -github.com/rs/zerolog v1.29.0 h1:Zes4hju04hjbvkVkOhdl2HpZa+0PmVwigmo8XoORE5w= -github.com/rs/zerolog v1.29.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= -github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= -github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -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/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= -github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= -github.com/safchain/ethtool v0.0.0-20190326074333-42ed695e3de8/go.mod h1:Z0q5wiBQGYcxhMZ6gUqHn6pYNLypFAvaL3UvgZLR0U4= -github.com/samber/lo v1.11.0 h1:JfeYozXL1xfkhRUFOfH13ociyeiLSC/GRJjGKI668xM= -github.com/samber/lo v1.11.0/go.mod h1:2I7tgIv8Q1SG2xEIkRq0F2i2zgxVpnyPOP0d3Gj2r+A= -github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= -github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I= -github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/seccomp/libseccomp-golang v0.9.1/go.mod h1:GbW5+tmTXfcxTToHLXlScSlAvWlF4P2Ca7zGrPiEpWo= -github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= -github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= -github.com/sirupsen/logrus v1.0.4-0.20170822132746-89742aefa4b2/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= -github.com/sirupsen/logrus v1.0.5/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= -github.com/sirupsen/logrus v1.0.6/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc= -github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= -github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM= -github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/skratchdot/open-golang v0.0.0-20190402232053-79abb63cd66e/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog= -github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= -github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= -github.com/smartystreets/assertions v1.2.0/go.mod h1:tcbTF8ujkAEcZ8TElKY+i30BzYlVhC/LOxJk7iOWnoo= -github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= -github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= -github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= -github.com/sosedoff/ansible-vault-go v0.2.0 h1:XqkBdqbXgTuFQ++NdrZvSdUTNozeb6S3V5x7FVs17vg= -github.com/sosedoff/ansible-vault-go v0.2.0/go.mod h1:wMU54HNJfY0n0KIgbpA9m15NBfaUDlJrAsaZp0FwzkI= -github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= -github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= -github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cobra v0.0.2-0.20171109065643-2da4a54c5cee/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/cobra v0.0.5 h1:f0B+LkLX6DtmRH1isoNA9VTtNUK9K8xYd28JNNfOv/s= -github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= -github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= -github.com/spf13/pflag v0.0.0-20170130214245-9ff6c6923cff/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/pflag v1.0.1-0.20171106142849-4c012f6dcd95/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= -github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= -github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= -github.com/stretchr/objx v0.0.0-20180129172003-8a3f7159479f/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/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 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v0.0.0-20180303142811-b89eecf5ca5d/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.1.4/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -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= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= -github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/syndtr/gocapability v0.0.0-20170704070218-db04d3cc01c8/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= -github.com/syndtr/gocapability v0.0.0-20180916011248-d98352740cb2/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= -github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= -github.com/tchap/go-patricia v2.2.6+incompatible/go.mod h1:bmLyhP68RS6kStMGxByiQ23RP/odRBOTVjwp2cDyi6I= -github.com/testcontainers/testcontainers-go v0.10.1-0.20210331130832-54854fb15ccb h1:IK+y9L4aToxLHSy0na5lIGr9lP51Zip/si8lgauVo/E= -github.com/testcontainers/testcontainers-go v0.10.1-0.20210331130832-54854fb15ccb/go.mod h1:zFYk0JndthnMHEwtVRHCpLwIP/Ik1G7mvIAQ2MdZ+Ig= -github.com/thoas/go-funk v0.9.1 h1:O549iLZqPpTUQ10ykd26sZhzD+rmR5pWhuElrhbC20M= -github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= -github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/tobischo/gokeepasslib/v3 v3.2.5 h1:BW0HorAp/Eo5XsjA3pgyrLaRzn9J5tGq8NBOADpE39g= -github.com/tobischo/gokeepasslib/v3 v3.2.5/go.mod h1:iwxOzUuk/ccA0mitrFC4MovT1p0IRY8EA35L4u1x/ug= -github.com/twpayne/go-pinentry v0.2.0 h1:hS5NEJiilop9xP9pBX/1NYduzDlGGMdg1KamTBTrOWw= -github.com/twpayne/go-pinentry v0.2.0/go.mod h1:r6buhMwARxnnL0VRBqfd1tE6Fadk1kfP00GRMutEspY= -github.com/uber/jaeger-client-go v2.25.0+incompatible h1:IxcNZ7WRY1Y3G4poYlx24szfsn/3LvK9QHCq9oQw8+U= -github.com/uber/jaeger-client-go v2.25.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk= -github.com/uber/jaeger-lib v2.4.0+incompatible h1:fY7QsGQWiCt8pajv4r7JEvmATdCVaWxXbjwyYwsNaLQ= -github.com/uber/jaeger-lib v2.4.0+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U= -github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= -github.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= -github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= -github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/urfave/cli v1.22.2/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= -github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= -github.com/urfave/cli/v2 v2.24.3 h1:7Q1w8VN8yE0MJEHP06bv89PjYsN4IHWED2s1v/Zlfm0= -github.com/urfave/cli/v2 v2.24.3/go.mod h1:GHupkWPMM0M/sj1a2b4wUrWBPzazNrIjouW6fmdJLxc= -github.com/vishvananda/netlink v0.0.0-20181108222139-023a6dafdcdf/go.mod h1:+SR5DhBJrl6ZM7CoCKvpw5BKroDKQ+PJqOg65H/2ktk= -github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= -github.com/vishvananda/netns v0.0.0-20180720170159-13995c7128cc/go.mod h1:ZjcWmFBXmLKZu9Nxj3WKYEafiSqer2rnvPr0en9UNpI= -github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU= -github.com/willf/bitset v1.1.11-0.20200630133818-d5bec3311243/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= -github.com/willf/bitset v1.1.11/go.mod h1:83CECat5yLh5zVOf4P1ErAgKA5UDvKtgyUABdr3+MjI= -github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= -github.com/xeipuuv/gojsonschema v0.0.0-20180618132009-1d523034197f/go.mod h1:5yf86TLmAcydyeJq5YvxkGPE2fm/u4myDekKRoLuqhs= -github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= -github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= -github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= -github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= -github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= -github.com/yvasiyarov/go-metrics v0.0.0-20140926110328-57bccd1ccd43/go.mod h1:aX5oPXxHm3bOH+xeAttToC8pqch2ScQN/JoXYupl6xs= -github.com/yvasiyarov/gorelic v0.0.0-20141212073537-a9bba5b9ab50/go.mod h1:NUSPSUX/bi6SeDMUh6brw0nXpxHnc96TguQh0+r/ssA= -github.com/yvasiyarov/newrelic_platform_go v0.0.0-20140908184405-b21fdbd4370f/go.mod h1:GlGEuHIJweS1mbCqG+7vt2nvWLzLLnRHbXz5JKd/Qbg= -github.com/zalando/go-keyring v0.1.1-0.20210112083600-4d37811583ad/go.mod h1:OIC+OZ28XbmwFxU/Rp9V7eKzZjamBJwRzC8UFJH9+L8= -github.com/zalando/go-keyring v0.2.2 h1:f0xmpYiSrHtSNAVgwip93Cg8tuF45HJM6rHq/A5RI/4= -github.com/zalando/go-keyring v0.2.2/go.mod h1:sI3evg9Wvpw3+n4SqplGSJUMwtDeROfD4nsFz4z9PG0= -go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= -go.etcd.io/bbolt v1.3.5/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= -go.etcd.io/etcd v0.5.0-alpha.5.0.20200910180754-dd1b699fc489/go.mod h1:yVHk9ub3CSBatqGNg7GRmsnfLWtoW60w4eDYfh7vHDg= -go.etcd.io/etcd/api/v3 v3.5.0-alpha.0 h1:+e5nrluATIy3GP53znpkHMFzPTHGYyzvJGFCbuI6ZLc= -go.etcd.io/etcd/api/v3 v3.5.0-alpha.0/go.mod h1:mPcW6aZJukV6Aa81LSKpBjQXTWlXB5r74ymPoSWa3Sw= -go.etcd.io/etcd/client/v3 v3.5.0-alpha.0 h1:dr1EOILak2pu4Nf5XbRIOCNIBjcz6UmkQd7hHRXwxaM= -go.etcd.io/etcd/client/v3 v3.5.0-alpha.0/go.mod h1:wKt7jgDgf/OfKiYmCq5WFGxOFAkVMLxiiXgLDFhECr8= -go.etcd.io/etcd/pkg/v3 v3.5.0-alpha.0 h1:3yLUEC0nFCxw/RArImOyRUI4OAFbg4PFpBbAhSNzKNY= -go.etcd.io/etcd/pkg/v3 v3.5.0-alpha.0/go.mod h1:tV31atvwzcybuqejDoY3oaNRTtlD2l/Ot78Pc9w7DMY= -go.mongodb.org/mongo-driver v1.0.3/go.mod h1:u7ryQJ+DOzQmeO7zB6MHyr8jkEQvC8vH7qLUO4lqsUM= -go.mongodb.org/mongo-driver v1.1.2/go.mod h1:u7ryQJ+DOzQmeO7zB6MHyr8jkEQvC8vH7qLUO4lqsUM= -go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= -go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= -go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= -go.opencensus.io v0.22.5 h1:dntmOdLpSpHlVqbW5Eay97DelsZHe+55D+xC6i0dDS0= -go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= -go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= -go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= -go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= -go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= -go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= -go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI= -go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ= -go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= -go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= -go.uber.org/zap v1.16.0 h1:uFRZXykJGK9lLY4HtgSw44DnIcAM+kRBP7x5m+NpAOM= -go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= -golang.org/x/crypto v0.0.0-20171113213409-9f005a07e0d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181009213950-7c1a557ab941/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190530122614-20be4c3c3ed5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190611184440-5c40567a22f8/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= -golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.8.0 h1:pd9TJtTueMTVQXzk8E2XESSMQDj/U7OUu0PqJqPXQjQ= -golang.org/x/crypto v0.8.0/go.mod h1:mRqEX+O9/h5TFCrQhkgjo2yKi0yYA+9ecGkdQoHrywE= -golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= -golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= -golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= -golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= -golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= -golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= -golang.org/x/exp v0.0.0-20230212135524-a684f29349b6 h1:Ic9KukPQ7PegFzHckNiMTQXGgEszA7mY2Fn4ZMtnMbw= -golang.org/x/exp v0.0.0-20230212135524-a684f29349b6/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= -golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= -golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= -golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= -golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= -golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5 h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI= -golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= -golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= -golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= -golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= -golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= -golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181011144130-49bb7cea24b1/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= -golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= -golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190619014844-b5b0513f8c1b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190827160401-ba9fcec4b297/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191002035440-2ec189313ef0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191004110552-13f9640d40b9/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= -golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.9.0 h1:aWJ/m6xSmxWBx+V0XRHTlrYrPG56jKsLdTFmsSsCzOM= -golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= -golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= -golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= -golang.org/x/oauth2 v0.5.0 h1:HuArIo48skDwlrvM3sEdHXElYslAMsf3KwRkkW4MC4s= -golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I= -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-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= -golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190129075346-302c3dd5f1cc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190514135907-3a4b5fb9f71f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190522044717-8097e1b27ff5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190530182044-ad28b68e88f1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190602015325-4c4f7f33c9ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190812073006-9eafafc0a87e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190922100055-0a153f010e69/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190924154521-2837fb4f24fe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191115151921-52ab43148777/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191210023423-ac6580df4449/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200120151820-655fe14d7479/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200513112337-417ce2331b5c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200728102440-3e129f6d46b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200916030750-2334cc1a136f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200922070232-aee5d888a860/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201009025420-dfb3f7c4e634/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201112073958-5cba982894dd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201202213521-69691e467435/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210819135213-f52c844e1c1c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU= -golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ= -golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= -golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.1-0.20181227161524-e6919f6577db/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= -golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 h1:Hir2P/De0WpUhtrKGGjvSb2YxUgyZ7EFOSLIcSSpiwE= -golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/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= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190614205625-5aca471b1d59/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190617190820-da514acc4774/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190907020128-2ca718005c18/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20191216052735-49a3e744a425/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= -golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= -golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= -golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= -golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= -golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= -golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= -golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/api v0.0.0-20160322025152-9bf6e6e569ff/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0= -google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= -google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= -google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= -google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= -google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= -google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= -google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= -google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= -google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= -google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= -google.golang.org/api v0.40.0 h1:uWrpz12dpVPn7cojP82mk02XDgTJLDPc2KbVTxrWb4A= -google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= -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/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= -google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= -google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= -google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= -google.golang.org/cloud v0.0.0-20151119220103-975617b05ea8/go.mod h1:0H1ncTHf11KCFhTc/+EFRbzSCOZx+VUbRMk55Yv5MYk= -google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= -google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= -google.golang.org/genproto v0.0.0-20190522204451-c2c4e71fbf69/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s= -google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= -google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200117163144-32f20d992d24/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= -google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= -google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= -google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= -google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201110150050-8816d57aaa9a/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c h1:7A9LQhrZmuCPI79/sYSbscFqBp4XFYf6oaIQuV1xji4= -google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/grpc v0.0.0-20160317175043-d3ddb4469d5a/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= -google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw= -google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= -google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= -google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.22.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.24.0/go.mod h1:XDChyiUovWa60DnaeDeZmSW86xtLtjtZbwvSiRnRtcA= -google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= -google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= -google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= -google.golang.org/grpc v1.35.0 h1:TwIQcH3es+MojMVojxxfQ3l3OF2KzlRxML2xZq0kRo8= -google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= -google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= -gopkg.in/airbrake/gobrake.v2 v2.0.9/go.mod h1:/h5ZAUhDkGaJfjzjKLSjv6zCL6O0LLBxU4K+aSYdM/U= -gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= -gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d/go.mod h1:cuepJuh7vyXfUyUwEgHQXw849cJrilpS5NeIjOWESAw= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20141024133853-64131543e789/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= -gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2/go.mod h1:Xk6kEKp8OKb+X14hQBKWaSkCsqBpgog8nAV2xsGOxlo= -gopkg.in/gookit/color.v1 v1.1.6 h1:5fB10p6AUFjhd2ayq9JgmJWr9WlTrguFdw3qlYtKNHk= -gopkg.in/gookit/color.v1 v1.1.6/go.mod h1:IcEkFGaveVShJ+j8ew+jwe9epHyGpJ9IrptHmW3laVY= -gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= -gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= -gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= -gopkg.in/square/go-jose.v2 v2.2.2/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= -gopkg.in/square/go-jose.v2 v2.3.1 h1:SK5KegNXmKmqE342YYN2qPHEnUYeoMiXXl1poUlI+o4= -gopkg.in/square/go-jose.v2 v2.3.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= -gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= -gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20191026110619-0b21df46bc1d/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20200121175148-a6ecf24a6d71/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -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 v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= -gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= -gotest.tools/v3 v3.0.2 h1:kG1BFyqVHuQoVQiR1bWGnfz/fmHvvuiSPIV7rvl360E= -gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= -honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -honnef.co/go/tools v0.0.1-2020.1.4 h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8= -honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -k8s.io/api v0.20.1/go.mod h1:KqwcCVogGxQY3nBlRpwt+wpAMF/KjaCc7RpywacvqUo= -k8s.io/apimachinery v0.20.1/go.mod h1:WlLqWAHZGg07AeltaI0MV5uk1Omp8xaN0JGLY6gkRpU= -k8s.io/apiserver v0.20.1/go.mod h1:ro5QHeQkgMS7ZGpvf4tSMx6bBOgPfE+f52KwvXfScaU= -k8s.io/client-go v0.20.1/go.mod h1:/zcHdt1TeWSd5HoUe6elJmHSQ6uLLgp4bIJHVEuy+/Y= -k8s.io/component-base v0.20.1/go.mod h1:guxkoJnNoh8LNrbtiQOlyp2Y2XFCZQmrcg2n/DeYNLk= -k8s.io/cri-api v0.17.3/go.mod h1:X1sbHmuXhwaHs9xxYffLqJogVsnI+f6cPRcgPel7ywM= -k8s.io/cri-api v0.20.1/go.mod h1:2JRbKt+BFLTjtrILYVqQK5jqhI+XNdF6UiGMgczeBCI= -k8s.io/gengo v0.0.0-20200413195148-3a45101e95ac/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= -k8s.io/klog/v2 v2.0.0/go.mod h1:PBfzABfn139FHAV07az/IF9Wp1bkk3vpT2XSJ76fSDE= -k8s.io/klog/v2 v2.4.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= -k8s.io/kube-openapi v0.0.0-20201113171705-d219536bb9fd/go.mod h1:WOJ3KddDSol4tAGcJo0Tvi+dK12EcqSLqcWsryKMpfM= -k8s.io/kubernetes v1.13.0/go.mod h1:ocZa8+6APFNC2tX1DZASIbocyYT5jHzqFVsY5aoB7Jk= -k8s.io/utils v0.0.0-20201110183641-67b214c5f920/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= -rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= -sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.0.14/go.mod h1:LEScyzhFmoF5pso/YSeBstl57mOzx9xlU9n85RGrDQg= -sigs.k8s.io/structured-merge-diff/v4 v4.0.2/go.mod h1:bJZC9H9iH24zzfZ/41RGcq60oK1F7G282QMXDPYydCw= -sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= -sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= diff --git a/install.ps1 b/install.ps1 new file mode 100644 index 00000000..284377e4 --- /dev/null +++ b/install.ps1 @@ -0,0 +1,55 @@ +#!/usr/bin/env pwsh +# Copyright 2018 the Deno authors. All rights reserved. MIT license. +# TODO(everyone): Keep this script simple and easily auditable. + +$ErrorActionPreference = 'Stop' + +$Project = "teller" +$Repo = "tellerops/teller" + +if ($v) { + $Version = "v${v}" +} +if ($args.Length -eq 1) { + $Version = $args.Get(0) +} + +$Install = $env:BP_INSTALL +$BinDir = if ($Install) { + "$Install" +} else { + "$Home\.$Project-bin" +} + +$Zip = "$BinDir\$Project.zip" +$Exe = "$BinDir\$Project.exe" +$Target = 'x86_64-windows' + +# GitHub requires TLS 1.2 +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + +$Uri = if (!$Version) { + "https://github.com/$Repo/releases/latest/download/${Project}-${Target}.zip" +} else { + "https://github.com/$Repo/releases/download/${Version}/$Project-${Target}.zip" +} + +if (!(Test-Path $BinDir)) { + New-Item $BinDir -ItemType Directory | Out-Null +} + +curl.exe -Lo $Zip $Uri + +tar.exe xf $Zip -C $BinDir --strip-components 1 + +Remove-Item $Zip + +$User = [EnvironmentVariableTarget]::User +$Path = [Environment]::GetEnvironmentVariable('Path', $User) +if (!(";$Path;".ToLower() -like "*;$BinDir;*".ToLower())) { + [Environment]::SetEnvironmentVariable('Path', "$Path;$BinDir", $User) + $Env:Path += ";$BinDir" +} + +Write-Output "$Project was installed successfully to $Exe" +Write-Output "Run with '--help' to get started" diff --git a/install.sh b/install.sh new file mode 100644 index 00000000..cf22ea0f --- /dev/null +++ b/install.sh @@ -0,0 +1,54 @@ +#!/bin/sh +# Copyright 2019 the Deno authors. All rights reserved. MIT license. +# Copyright 2022 the Backpack authors. All rights reserved. MIT license. +# TODO(everyone): Keep this script simple and easily auditable. + +set -e + +# assumes bin name same as project name +project="teller" +bin_name="teller" +repo="tellerops/teller" + +if [ "$OS" = "Windows_NT" ]; then + target="x86_64-windows" +else + case $(uname -sm) in + "Darwin x86_64") target="x86_64-macos" ;; + "Darwin arm64") target="aarch64-macos" ;; + *) target="x86_64-linux" ;; + esac +fi + +if [ $# -eq 0 ]; then + uri="https://github.com/${repo}/releases/latest/download/${project}-${target}.tar.xz" +else + uri="https://github.com/${repo}/releases/download/${1}/${project}-${target}.tar.xz" +fi + +install="${PROJ_INSTALL:-$HOME/.$project-bin}" +bin_dir="$install" +exe="$bin_dir/$bin_name" + +if [ ! -d "$bin_dir" ]; then + mkdir -p "$bin_dir" +fi + +curl --fail --location --progress-bar --output "$exe.tar.xz" "$uri" +tar zxf "$exe.tar.xz" -C "$bin_dir" --strip-components 1 +chmod +x "$exe" +rm "$exe.tar.xz" + +echo "$project was installed successfully to $exe" +if command -v $exe >/dev/null; then + echo "Run '$exe --help' to get started" +else + case $SHELL in + /bin/zsh) shell_profile=".zshrc" ;; + *) shell_profile=".bashrc" ;; + esac + echo "Manually add the directory to your \$HOME/$shell_profile (or similar)" + echo " export PROJ_INSTALL=\"$install\"" + echo " export PATH=\"\$PROJ_INSTALL:\$PATH\"" + echo "Run '$exe --help' to get started" +fi diff --git a/main.go b/main.go deleted file mode 100644 index 8d2ca618..00000000 --- a/main.go +++ /dev/null @@ -1,330 +0,0 @@ -package main - -import ( - "errors" - "fmt" - "io" - "io/fs" - "os" - - "github.com/alecthomas/kong" - "github.com/spectralops/teller/pkg" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/providers" - "github.com/spectralops/teller/pkg/utils" -) - -var CLI struct { - Config string `short:"c" help:"Path to teller YAML file"` - LogLevel string `short:"l" help:"Application log level"` - - Run struct { - Redact bool `optional name:"redact" help:"Redact output of the child process"` - Cmd []string `arg name:"cmd" help:"Command to execute"` - } `cmd help:"Run a command"` - - Version struct { - } `cmd aliases:"v" help:"Teller version"` - - New struct { - } `cmd help:"Create a new teller configuration file"` - - Show struct { - } `cmd help:"Print in a human friendly, secure format"` - - Providers struct { - Path string `optional name:"path" help:"Path for saving providers JSON file"` - } `cmd help:"Export providers metadata to a local JSON file" hidden: ""` - - Yaml struct { - } `cmd help:"Print values in a YAML format (suitable for GCloud)"` - - JSON struct { - } `cmd help:"Print values in a JSON format"` - - Sh struct { - } `cmd help:"Print ready to be eval'd exports for your shell"` - - Env struct { - } `cmd help:"Print in a .env format for Docker and others"` - - Template struct { - TemplatePath string `arg name:"template_path" help:"Path to the template source (Go template format)"` - Out string `arg name:"out" help:"Output file"` - } `cmd help:"Inject vars from a template by given source path (single file or folder)"` - - Redact struct { - In string `optional name:"in" help:"Input file"` - Out string `optional name:"out" help:"Output file"` - } `cmd help:"Redacts secrets from a process output"` - - Scan struct { - Path string `arg optional name:"path" help:"Scan root, default: '.'"` - Silent bool `optional name:"silent" help:"No text, just exit code"` - } `cmd help:"Scans your codebase for sensitive keys"` - - GraphDrift struct { - Providers []string `arg optional name:"providers" help:"A list of providers to check for drift"` - } `cmd help:"Detect secret and value drift between providers"` - - Put struct { - Kvs map[string]string `arg name:"kvs" help:"A list of key/value pairs, where key is from your tellerfile mapping"` - Providers []string `name:"providers" help:"A list of providers to put the new value into"` - Sync bool `optional name:"sync" help:"Sync all given k/vs to the env_sync key"` - Path string `optional name:"path" help:"Take literal path and not from config"` - } `cmd help:"Put a new value"` - - Copy struct { - From string `name:"from" help:"A provider name to sync from"` - To []string `name:"to" help:"A list of provider names to copy values from the source provider to"` - Sync bool `optional name:"sync" help:"Sync all given k/vs to the env_sync key"` - } `cmd help:"Sync data from a source provider directly to multiple target providers"` - - MirrorDrift struct { - Source string `name:"source" help:"A source to check drift against"` - Target string `name:"target" help:"A target to check against source"` - } `cmd help:"Check same-key (mirror) value drift between source and target"` - - Delete struct { - Keys []string `arg optional name:"keys" help:"A list of keys, where key is from your tellerfile mapping"` - Providers []string `name:"providers" help:"A list of providers to delete the key from"` - Path string `optional name:"path" help:"Take literal path and not from config"` - AllKeys bool `optional name:"all-keys" help:"Deletes all keys for a given path. Applicable only when used together with the 'path' flag"` - } `cmd help:"Delete a secret"` -} - -var ( - version = "dev" - commit = "none" - date = "unknown" - defaultLogLevel = "error" -) - -//nolint -func main() { - //print help if no command given - if len(os.Args) < 2 { - os.Args = append(os.Args, "--help") - } - ctx := kong.Parse(&CLI) - - logger := logging.GetRoot() - if CLI.LogLevel != "" { - defaultLogLevel = CLI.LogLevel - } - logger.SetLevel(defaultLogLevel) - - // below commands don't require a tellerfile - //nolint - switch ctx.Command() { - case "version": - fmt.Printf("Teller %v\n", version) - fmt.Printf("Revision %v, date: %v\n", commit, date) - os.Exit(0) - case "providers": - providersMetaList := providers.GetAllProvidersMeta() - providersMetaJSON, err := providers.GenerateProvidersMetaJSON(version, providersMetaList) - if err != nil { - logger.WithError(err).Fatal("could not get providers meta, %s", err) - } - - saveErr := utils.WriteFileInPath("providers-meta.json", CLI.Providers.Path, []byte(providersMetaJSON)) - if saveErr != nil { - logger.WithError(err).Fatal("could not save providers meta to a local file, %s", saveErr) - } - fmt.Printf("Providers meta has been exported successfully\n") - - os.Exit(0) - } - - // - // load or create new file - // - const ( - defaultTellerFile = ".teller.yml" - // Alternative default teller file, it uses official YAML extension - // See https://github.com/tellerops/teller/issues/162 - secondDefaultTellerFile = ".teller.yaml" - ) - - telleryml := defaultTellerFile - if CLI.Config != "" { - telleryml = CLI.Config - } - - if ctx.Command() == "new" { - teller := pkg.Teller{ - Porcelain: &pkg.Porcelain{Out: os.Stderr}, - Logger: logger, - } - if _, err := os.Stat(telleryml); err == nil && !teller.Porcelain.AskForConfirmation(fmt.Sprintf("The file %s already exists. Do you want to override the configuration with new settings?", telleryml)) { - os.Exit(0) - } - - err := teller.SetupNewProject(telleryml) - if err != nil { - logger.WithError(err).Fatal("could not create configuration") - } - os.Exit(0) - } - - tlrfile, err := pkg.NewTellerFile(telleryml) - if isDefaultFilePathErr(CLI.Config, err) { - tlrfile, err = pkg.NewTellerFile(secondDefaultTellerFile) - } - if err != nil { - logger.WithError(err).WithField("file", telleryml).Fatal("could not read file") - } - - teller := pkg.NewTeller(tlrfile, CLI.Run.Cmd, CLI.Run.Redact, logger) - - // below commands don't require collecting - //nolint - switch ctx.Command() { - case "put ": - err := teller.Put(CLI.Put.Kvs, CLI.Put.Providers, CLI.Put.Sync, CLI.Put.Path) - if err != nil { - logger.WithError(err).Fatal("put command field") - } - os.Exit(0) - case "copy": - err := teller.Sync(CLI.Copy.From, CLI.Copy.To, CLI.Copy.Sync) - if err != nil { - logger.WithError(err).WithFields(map[string]interface{}{ - "from": CLI.Copy.From, - "to": CLI.Copy.To, - "sync_flag": CLI.Copy.Sync, - }).Fatal("could not copy data between providers") - } - os.Exit(0) - case "mirror-drift": - drifts, err := teller.MirrorDrift(CLI.MirrorDrift.Source, CLI.MirrorDrift.Target) - if err != nil { - logger.WithError(err).Fatal("mirror-drift command field") - } - if len(drifts) > 0 { - teller.Porcelain.PrintDrift(drifts) - os.Exit(1) - } - os.Exit(0) - case "delete": - err := teller.Delete(CLI.Delete.Keys, CLI.Delete.Providers, CLI.Delete.Path, CLI.Delete.AllKeys) - if err != nil { - logger.WithError(err).Fatal("could not delete key") - } - os.Exit(0) - case "delete ": - err := teller.Delete(CLI.Delete.Keys, CLI.Delete.Providers, CLI.Delete.Path, CLI.Delete.AllKeys) - if err != nil { - logger.WithError(err).Fatal("could not delete keys") - } - os.Exit(0) - } - // collecting - - err = teller.Collect() - if err != nil { - logger.WithError(err).Fatal("could not load all variables from the given existing providers") - } - - // all of the below require a tellerfile - switch ctx.Command() { - case "run ": - if len(CLI.Run.Cmd) < 1 { - logger.Fatal("Error: No command given") - } - teller.Exec() - - case "graph-drift ": - fallthrough - case "graph-drift": - drifts := teller.Drift(CLI.GraphDrift.Providers) - if len(drifts) > 0 { - teller.Porcelain.PrintDrift(drifts) - os.Exit(1) - } - - case "redact": - // redact (stdin) - // redact --in FILE --out FOUT - // redact --in FILE (stdout) - var fin io.Reader = os.Stdin - var fout io.Writer = os.Stdout - - if CLI.Redact.In != "" { - f, err := os.Open(CLI.Redact.In) - if err != nil { - logger.WithError(err).Fatal("could not open file") - } - fin = f - } - - if CLI.Redact.Out != "" { - f, err := os.Create(CLI.Redact.Out) - if err != nil { - logger.WithError(err).Fatal("could not create file") - } - - fout = f - } - - if err := teller.RedactLines(fin, fout); err != nil { - logger.WithError(err).Fatal("could not redact lines") - } - - case "sh": - fmt.Print(teller.ExportEnv()) - - case "env": - fmt.Print(teller.ExportDotenv()) - - case "yaml": - out, err := teller.ExportYAML() - if err != nil { - logger.WithError(err).Fatal("could not export to YAML") - } - fmt.Print(out) - - case "json": - out, err := teller.ExportJSON() - if err != nil { - logger.WithError(err).Fatal("could not export to JSON") - } - fmt.Print(out) - - case "show": - teller.PrintEnvKeys() - - case "scan": - findings, err := teller.Scan(CLI.Scan.Path, CLI.Scan.Silent) - - if err != nil { - logger.WithError(err).WithField("path", CLI.Scan.Path).Fatal("scan error") - } - num := len(findings) - if num > 0 { - os.Exit(1) - } - - case "template ": - err := teller.Template(CLI.Template.TemplatePath, CLI.Template.Out) - if err != nil { - logger.WithError(err).WithFields(map[string]interface{}{ - "template_path": CLI.Template.TemplatePath, - "template_output": CLI.Template.Out, - }).Fatal("could not populate template") - } - - default: - println(ctx.Command()) - teller.PrintEnvKeys() - } -} - -func isDefaultFilePathErr(config string, err error) bool { - // Ignore if explicitly set to '.teller.yml'. - if config != "" { - return false - } - return errors.Is(err, fs.ErrNotExist) -} diff --git a/media/cover.png b/media/cover.png deleted file mode 100644 index c37617d2..00000000 Binary files a/media/cover.png and /dev/null differ diff --git a/media/teller.gif b/media/teller.gif deleted file mode 100644 index 1183a9f9..00000000 Binary files a/media/teller.gif and /dev/null differ diff --git a/package.json b/package.json deleted file mode 100644 index e0e0f0ff..00000000 --- a/package.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "private": true, - "name": "teller", - "version": "1.0.0", - "main": "index.js", - "license": "MIT", - "scripts": { - "readme": "doctoc --maxlevel 2 README.md" - }, - "devDependencies": { - "doctoc": "^2.0.0" - } -} \ No newline at end of file diff --git a/pkg/core/populate.go b/pkg/core/populate.go deleted file mode 100644 index c5123807..00000000 --- a/pkg/core/populate.go +++ /dev/null @@ -1,62 +0,0 @@ -package core - -import ( - "fmt" - "os" - "strings" -) - -const ( - populateFromEnvironment = "env:" - populateWithDefault = "," -) - -type Opts map[string]string -type Populate struct { - rules map[string]string -} - -func NewPopulate(opts Opts) *Populate { - rules := make(map[string]string) - for k, v := range opts { - val := v - if strings.HasPrefix(v, populateFromEnvironment) { - evar := strings.TrimPrefix(v, populateFromEnvironment) - evar, defaultValue := parseDefaultValue(evar) - val = os.Getenv(evar) - if val == "" { - val = defaultValue - } - } - rules[fmt.Sprintf("{{%s}}", k)] = val - } - - return &Populate{ - rules: rules, - } -} - -func (p *Populate) FindAndReplace(path string) string { - populated := path - for k, v := range p.rules { - populated = strings.ReplaceAll(populated, k, v) - } - return populated -} - -func (p *Populate) KeyPath(kp KeyPath) KeyPath { - return kp.SwitchPath(p.FindAndReplace(kp.Path)) -} - -// parseDefaultValue returns that field name and the default value if `populateWithDefault` was found -// Example 1: FOO,BAR -> the function return FOO, BAR -// Example 2: FOO -> the function return FOO, "" (empty value) -func parseDefaultValue(evar string) (key, defaultValue string) { - if strings.Contains(evar, populateWithDefault) { - data := strings.SplitN(evar, populateWithDefault, 2) //nolint - if len(data) == 2 { //nolint - return data[0], strings.TrimSpace(data[1]) - } - } - return evar, "" -} diff --git a/pkg/core/populate_test.go b/pkg/core/populate_test.go deleted file mode 100644 index 7362c721..00000000 --- a/pkg/core/populate_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package core - -import ( - "os" - "testing" - - "github.com/alecthomas/assert" -) - -func TestPopulatePath(t *testing.T) { - os.Setenv("TELLER_TEST_FOO", "test-foo") - - p := NewPopulate(map[string]string{ - "foo": "bar", - "teller-env": "env:TELLER_TEST_FOO", - "teller-env-default": "env:TELLER_TEST_DEFAULT,default-value", - }) - - assert.Equal(t, p.FindAndReplace("foo/{{foo}}/qux/{{foo}}"), "foo/bar/qux/bar") - assert.Equal(t, p.FindAndReplace("foo/qux"), "foo/qux") - assert.Equal(t, p.FindAndReplace("foo/{{none}}"), "foo/{{none}}") - assert.Equal(t, p.FindAndReplace("foo/{{teller-env}}"), "foo/test-foo") - assert.Equal(t, p.FindAndReplace("foo/{{teller-env-default}}"), "foo/default-value") - assert.Equal(t, p.FindAndReplace(""), "") - - kp := KeyPath{ - Path: "{{foo}}/hey", - Env: "env", - Decrypt: true, - Optional: true, - } - assert.Equal(t, p.KeyPath(kp), KeyPath{ - Path: "bar/hey", - Env: "env", - Decrypt: true, - Optional: true, - }) - kp = KeyPath{ - Path: "{{teller-env}}/hey", - Env: "env", - Decrypt: true, - Optional: true, - } - assert.Equal(t, p.KeyPath(kp), KeyPath{ - Path: "test-foo/hey", - Env: "env", - Decrypt: true, - Optional: true, - }) - kp = KeyPath{ - Path: "{{teller-env-default}}/hey", - Env: "env", - Decrypt: true, - Optional: true, - } - assert.Equal(t, p.KeyPath(kp), KeyPath{ - Path: "default-value/hey", - Env: "env", - Decrypt: true, - Optional: true, - }) -} - -func TestPopulateDefaultValue(t *testing.T) { - key, value := parseDefaultValue("TELLER_TEST_FOO") - assert.Equal(t, key, "TELLER_TEST_FOO") - assert.Equal(t, value, "") - - key, value = parseDefaultValue("TELLER_TEST_FOO, default,,value") - assert.Equal(t, key, "TELLER_TEST_FOO") - assert.Equal(t, value, "default,,value") -} diff --git a/pkg/core/types.go b/pkg/core/types.go deleted file mode 100644 index 42296892..00000000 --- a/pkg/core/types.go +++ /dev/null @@ -1,260 +0,0 @@ -package core - -import ( - "strings" - - "github.com/spectralops/teller/pkg/logging" -) - -type Severity string - -const ( - High Severity = "high" - Medium Severity = "medium" - Low Severity = "low" - None Severity = "none" - - // PlainTextKey the key used for plaintext secrets - PlainTextKey = "plaintext" -) - -type RemapKeyPath struct { - Field string `yaml:"field,omitempty"` - Severity Severity `yaml:"severity,omitempty"` - RedactWith string `yaml:"redact_with,omitempty"` -} - -type KeyPath struct { - Env string `yaml:"env,omitempty"` - Path string `yaml:"path"` - Field string `yaml:"field,omitempty"` - Remap *map[string]string `yaml:"remap,omitempty"` - RemapWith *map[string]RemapKeyPath `yaml:"remap_with,omitempty"` - Decrypt bool `yaml:"decrypt,omitempty"` - Optional bool `yaml:"optional,omitempty"` - Plaintext bool `yaml:"plaintext,omitempty"` - Severity Severity `yaml:"severity,omitempty" default:"high"` - RedactWith string `yaml:"redact_with,omitempty" default:"**REDACTED**"` - Source string `yaml:"source,omitempty"` - Sink string `yaml:"sink,omitempty"` -} - -type WizardAnswers struct { - Project string - Providers []string - ProviderKeys map[string]bool - Confirm bool -} - -func (k *KeyPath) EffectiveKey() string { - if k.Plaintext { - return PlainTextKey - } - key := k.Env - if k.Field != "" { - key = k.Field - } - return key -} - -func (k *KeyPath) EffectiveRemap() map[string]RemapKeyPath { - remap := make(map[string]RemapKeyPath) - if k.Remap != nil { - for k, v := range *k.Remap { - remap[k] = RemapKeyPath{Field: v} - } - } else if k.RemapWith != nil { - remap = *k.RemapWith - } - return remap -} - -func (k *KeyPath) Missing() EnvEntry { - return EnvEntry{ - IsFound: false, - Key: k.Env, - Field: k.Field, - ResolvedPath: k.Path, - } -} - -func (k *KeyPath) Found(v string) EnvEntry { - return EnvEntry{ - IsFound: true, - Key: k.Env, - Field: k.Field, - Value: v, - ResolvedPath: k.Path, - } -} - -// NOTE: consider doing what 'updateParams' does in these builders -func (k *KeyPath) FoundWithKey(key, v string) EnvEntry { - return EnvEntry{ - IsFound: true, - Key: key, - Field: k.Field, - Value: v, - ResolvedPath: k.Path, - } -} - -func (k *KeyPath) WithEnv(env string) KeyPath { - return KeyPath{ - Env: env, - Path: k.Path, - Field: k.Field, - Decrypt: k.Decrypt, - Optional: k.Optional, - Source: k.Source, - Sink: k.Sink, - Plaintext: k.Plaintext, - } -} -func (k *KeyPath) SwitchPath(path string) KeyPath { - return KeyPath{ - Path: path, - Field: k.Field, - Env: k.Env, - Decrypt: k.Decrypt, - Optional: k.Optional, - Source: k.Source, - Sink: k.Sink, - Plaintext: k.Plaintext, - } -} - -type DriftedEntriesBySource []DriftedEntry - -func (a DriftedEntriesBySource) Len() int { return len(a) } -func (a DriftedEntriesBySource) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a DriftedEntriesBySource) Less(i, j int) bool { return a[i].Source.Source < a[j].Source.Source } - -type EntriesByProvider []EnvEntry - -func (a EntriesByProvider) Len() int { return len(a) } -func (a EntriesByProvider) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a EntriesByProvider) Less(i, j int) bool { - firstProviderName := strings.ToLower(a[i].ProviderName) - secondProviderName := strings.ToLower(a[j].ProviderName) - if firstProviderName != secondProviderName { - return firstProviderName < secondProviderName - } - return a[i].Key < a[j].Key -} - -type EntriesByKey []EnvEntry - -func (a EntriesByKey) Len() int { return len(a) } -func (a EntriesByKey) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a EntriesByKey) Less(i, j int) bool { return a[i].Key > a[j].Key } - -type EntriesByValueSize []EnvEntry - -func (a EntriesByValueSize) Len() int { return len(a) } -func (a EntriesByValueSize) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a EntriesByValueSize) Less(i, j int) bool { return len(a[i].Value) > len(a[j].Value) } - -type EnvEntry struct { - Key string - Field string - Value string - ProviderName string - ResolvedPath string - Severity Severity - RedactWith string - Source string - Sink string - IsFound bool -} - -func (ee *EnvEntry) AddressingKeyPath() *KeyPath { - return &KeyPath{ - Env: ee.Key, - Field: ee.Field, - Path: ee.ResolvedPath, - } -} - -type DriftedEntry struct { - Diff string - Source EnvEntry - Target EnvEntry -} -type EnvEntryLookup struct { - Entries []EnvEntry -} - -func (ee *EnvEntryLookup) EnvBy(key, provider, path, dflt string) string { - for i := range ee.Entries { - e := ee.Entries[i] - if e.Key == key && e.ProviderName == provider && e.ResolvedPath == path { - return e.Value - } - } - return dflt -} -func (ee *EnvEntryLookup) EnvByKey(key, dflt string) string { - for i := range ee.Entries { - e := ee.Entries[i] - if e.Key == key { - return e.Value - } - - } - return dflt -} - -func (ee *EnvEntryLookup) EnvByKeyAndProvider(key, provider, dflt string) string { - for i := range ee.Entries { - e := ee.Entries[i] - if e.Key == key && e.ProviderName == provider { - return e.Value - } - - } - return dflt -} - -type Provider interface { - // in this case 'env' is empty, but EnvEntries are the value - GetMapping(p KeyPath) ([]EnvEntry, error) - - // in this case env is filled - Get(p KeyPath) (*EnvEntry, error) - - Put(p KeyPath, val string) error - PutMapping(p KeyPath, m map[string]string) error - - Delete(p KeyPath) error - DeleteMapping(p KeyPath) error -} - -type MetaInfo struct { - Description string - Name string - Authentication string - ConfigTemplate string - Ops OpMatrix -} -type OpMatrix struct { - Delete bool - DeleteMapping bool - Put bool - PutMapping bool - Get bool - GetMapping bool -} - -type Match struct { - Path string - Line string - LineNumber int - MatchIndex int - Entry EnvEntry -} - -type RegisteredProvider struct { - Meta MetaInfo - Builder func(logger logging.Logger) (Provider, error) -} diff --git a/pkg/integration_test/consul_test.go b/pkg/integration_test/consul_test.go deleted file mode 100644 index 85fa9795..00000000 --- a/pkg/integration_test/consul_test.go +++ /dev/null @@ -1,89 +0,0 @@ -//go:build integration -// +build integration - -package integration_test - -import ( - "context" - "fmt" - "testing" - "time" - - "github.com/hashicorp/consul/api" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/providers" - "github.com/stretchr/testify/assert" - "github.com/testcontainers/testcontainers-go" - "github.com/testcontainers/testcontainers-go/wait" -) - -type ConsulData = map[string]interface{} - -func TestGetConsul(t *testing.T) { - ctx := context.Background() - const testToken = "vault-token" - - req := testcontainers.GenericContainerRequest{ - ContainerRequest: testcontainers.ContainerRequest{ - AlwaysPullImage: false, - Image: "consul:1.9.5", - ExposedPorts: []string{"8500/tcp"}, - Env: map[string]string{}, - WaitingFor: wait.ForLog("Started gRPC server").WithStartupTimeout(20 * time.Second)}, - - Started: true, - } - - vaultContainer, err := testcontainers.GenericContainer(ctx, req) - assert.NoError(t, err) - defer vaultContainer.Terminate(ctx) //nolint - - ip, err := vaultContainer.Host(ctx) - assert.NoError(t, err) - port, err := vaultContainer.MappedPort(ctx, "8500") - assert.NoError(t, err) - host := fmt.Sprintf("http://%s:%s", ip, port.Port()) - - // - // pre-insert data w/API - // - config := &api.Config{Address: host} - client, err := api.NewClient(config) - assert.NoError(t, err) - _, err = client.KV().Put(&api.KVPair{Key: "path/to/svc/MG_KEY", Value: []byte("value1")}, &api.WriteOptions{}) - assert.NoError(t, err) - - // - // use provider to read data - // - t.Setenv("CONSUL_HTTP_ADDR", host) - p, err := providers.NewConsul(logging.New()) - assert.NoError(t, err) - kvp := core.KeyPath{Env: "MG_KEY", Path: "path/to/svc/MG_KEY"} - res, err := p.Get(kvp) - - assert.NoError(t, err) - assert.Equal(t, "MG_KEY", res.Key) - assert.Equal(t, "value1", res.Value) - assert.Equal(t, "path/to/svc/MG_KEY", res.ResolvedPath) - - err = p.Put(kvp, "changed-secret") - assert.NoError(t, err) - - res, err = p.Get(kvp) - assert.NoError(t, err) - assert.Equal(t, "MG_KEY", res.Key) - assert.Equal(t, "changed-secret", res.Value) - assert.Equal(t, "path/to/svc/MG_KEY", res.ResolvedPath) - - err = p.PutMapping(kvp.SwitchPath("path/to/allmap"), map[string]string{"K1": "v1", "K2": "v2"}) - assert.NoError(t, err) - ents, err := p.GetMapping(kvp.SwitchPath("path/to/allmap")) - assert.NoError(t, err) - assert.Equal(t, 2, len(ents)) - assert.Equal(t, "K1", ents[1].Key) - assert.Equal(t, "K2", ents[0].Key) - assert.Equal(t, "v1", ents[1].Value) - assert.Equal(t, "v2", ents[0].Value) -} diff --git a/pkg/integration_test/dotenv_test.go b/pkg/integration_test/dotenv_test.go deleted file mode 100644 index 0c438bb6..00000000 --- a/pkg/integration_test/dotenv_test.go +++ /dev/null @@ -1,69 +0,0 @@ -//go:build integration -// +build integration - -package integration_test - -import ( - "os" - "testing" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/providers" - "github.com/stretchr/testify/assert" -) - -func TestGetDotEnv(t *testing.T) { - // - // pre-insert data - // - f, err := os.CreateTemp(t.TempDir(), "dotenv-*") - assert.NoError(t, err) - f.WriteString("MG_KEY=123\n") - f.Close() - - // - // use provider to read data - // - p, err := providers.NewDotenv(logging.New()) - assert.NoError(t, err) - kvp := core.KeyPath{Env: "MG_KEY", Path: f.Name()} - res, err := p.Get(kvp) - - assert.NoError(t, err) - assert.Equal(t, "MG_KEY", res.Key) - assert.Equal(t, "123", res.Value) - assert.Equal(t, f.Name(), res.ResolvedPath) - - err = p.Put(kvp, "changed-secret") - assert.NoError(t, err) - - res, err = p.Get(kvp) - assert.NoError(t, err) - assert.Equal(t, "MG_KEY", res.Key) - assert.Equal(t, "changed-secret", res.Value) - assert.Equal(t, f.Name(), res.ResolvedPath) - - err = p.PutMapping(kvp, map[string]string{"K1": "val1", "K2": "val2"}) - assert.NoError(t, err) - - res, err = p.Get(core.KeyPath{Env: "K1", Path: f.Name()}) - assert.NoError(t, err) - assert.Equal(t, "K1", res.Key) - assert.Equal(t, "val1", res.Value) - - err = p.Delete(core.KeyPath{Env: "MG_KEY", Path: f.Name()}) - assert.NoError(t, err) - - entries, err := p.GetMapping(core.KeyPath{Path: f.Name()}) - for _, entry := range entries { - assert.NotEqual(t, "MG_KEY", entry.Key) - } - assert.NoError(t, err) - - err = p.DeleteMapping(kvp) - assert.NoError(t, err) - - _, err = os.Stat(f.Name()) - assert.True(t, os.IsNotExist(err)) -} diff --git a/pkg/integration_test/etcd_test.go b/pkg/integration_test/etcd_test.go deleted file mode 100644 index ace91749..00000000 --- a/pkg/integration_test/etcd_test.go +++ /dev/null @@ -1,93 +0,0 @@ -//go:build integration -// +build integration - -package integration_test - -import ( - "context" - "fmt" - "testing" - "time" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/providers" - "github.com/stretchr/testify/assert" - "github.com/testcontainers/testcontainers-go" - "github.com/testcontainers/testcontainers-go/wait" - clientv3 "go.etcd.io/etcd/client/v3" -) - -func TestGetEtcd(t *testing.T) { - ctx := context.Background() - const testToken = "vault-token" - - req := testcontainers.GenericContainerRequest{ - ContainerRequest: testcontainers.ContainerRequest{ - AlwaysPullImage: false, - Image: "gcr.io/etcd-development/etcd:v3.3", - ExposedPorts: []string{"2379/tcp"}, - Cmd: []string{ - "etcd", - "--name", "etcd0", - "--advertise-client-urls", "http://0.0.0.0:2379", - "--listen-client-urls", "http://0.0.0.0:2379", - }, - Env: map[string]string{}, - WaitingFor: wait.ForLog("ready to serve client requests").WithStartupTimeout(20 * time.Second)}, - Started: true, - } - - vaultContainer, err := testcontainers.GenericContainer(ctx, req) - assert.NoError(t, err) - defer vaultContainer.Terminate(ctx) //nolint - - ip, err := vaultContainer.Host(ctx) - assert.NoError(t, err) - port, err := vaultContainer.MappedPort(ctx, "2379/tcp") - assert.NoError(t, err) - host := fmt.Sprintf("http://%s:%s", ip, port.Port()) - - // - // pre-insert data w/API - // - cfg := clientv3.Config{ - Endpoints: []string{host}, - } - client, err := clientv3.New(cfg) - assert.NoError(t, err) - _, err = client.Put(context.TODO(), "path/to/svc/MG_KEY", "value1") - assert.NoError(t, err) - // - // use provider to read data - // - t.Setenv("ETCDCTL_ENDPOINTS", host) - p, err := providers.NewEtcd(logging.New()) - assert.NoError(t, err) - kvp := core.KeyPath{Env: "MG_KEY", Path: "path/to/svc/MG_KEY"} - res, err := p.Get(kvp) - - assert.NoError(t, err) - assert.Equal(t, "MG_KEY", res.Key) - assert.Equal(t, "value1", res.Value) - assert.Equal(t, "path/to/svc/MG_KEY", res.ResolvedPath) - - err = p.Put(kvp, "changed-secret") - assert.NoError(t, err) - - res, err = p.Get(kvp) - assert.NoError(t, err) - assert.Equal(t, "MG_KEY", res.Key) - assert.Equal(t, "changed-secret", res.Value) - assert.Equal(t, "path/to/svc/MG_KEY", res.ResolvedPath) - - err = p.PutMapping(kvp.SwitchPath("path/to/allmap"), map[string]string{"K1": "v1", "K2": "v2"}) - assert.NoError(t, err) - ents, err := p.GetMapping(kvp.SwitchPath("path/to/allmap")) - assert.NoError(t, err) - assert.Equal(t, 2, len(ents)) - assert.Equal(t, "K1", ents[1].Key) - assert.Equal(t, "K2", ents[0].Key) - assert.Equal(t, "v1", ents[1].Value) - assert.Equal(t, "v2", ents[0].Value) -} diff --git a/pkg/integration_test/heroku_test.go b/pkg/integration_test/heroku_test.go deleted file mode 100644 index 50d8b03c..00000000 --- a/pkg/integration_test/heroku_test.go +++ /dev/null @@ -1,70 +0,0 @@ -//go:build integration_api -// +build integration_api - -package integration_test - -import ( - "context" - "os" - "testing" - - heroku "github.com/heroku/heroku-go/v5" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/providers" - "github.com/stretchr/testify/assert" -) - -func TestGetHeroku(t *testing.T) { - - // - // TEST PRECONDITION: - // - // HEROKU_API_KEY populated - // 'teller-heroku-integration' app exists - // - - // - // pre-insert data w/API - // - heroku.DefaultTransport.BearerToken = os.Getenv("HEROKU_API_KEY") - svc := heroku.NewService(heroku.DefaultClient) - - v := "value1" - _, err := svc.ConfigVarUpdate(context.TODO(), "teller-heroku-integration", map[string]*string{"MG_KEY": &v, "K1": nil, "K2": nil}) - assert.NoError(t, err) - - // - // use provider to read data - // - p, err := providers.NewHeroku(logging.New()) - assert.NoError(t, err) - kvp := core.KeyPath{Env: "MG_KEY", Path: "teller-heroku-integration"} - res, err := p.Get(kvp) - - assert.NoError(t, err) - assert.Equal(t, "MG_KEY", res.Key) - assert.Equal(t, "value1", res.Value) - assert.Equal(t, "teller-heroku-integration", res.ResolvedPath) - - err = p.Put(kvp, "changed-secret") - assert.NoError(t, err) - - res, err = p.Get(kvp) - assert.NoError(t, err) - assert.Equal(t, "MG_KEY", res.Key) - assert.Equal(t, "changed-secret", res.Value) - assert.Equal(t, "teller-heroku-integration", res.ResolvedPath) - - err = p.PutMapping(kvp, map[string]string{"K1": "v1", "K2": "v2"}) - assert.NoError(t, err) - ents, err := p.GetMapping(kvp) - assert.NoError(t, err) - assert.Equal(t, 3, len(ents)) - assert.Equal(t, "MG_KEY", ents[0].Key) - assert.Equal(t, "changed-secret", ents[0].Value) - assert.Equal(t, "K1", ents[2].Key) - assert.Equal(t, "v1", ents[2].Value) - assert.Equal(t, "K2", ents[1].Key) - assert.Equal(t, "v2", ents[1].Value) -} diff --git a/pkg/integration_test/vault_test.go b/pkg/integration_test/vault_test.go deleted file mode 100644 index 962f4bda..00000000 --- a/pkg/integration_test/vault_test.go +++ /dev/null @@ -1,84 +0,0 @@ -//go:build integration -// +build integration - -package integration_test - -import ( - "context" - "fmt" - "testing" - "time" - - "github.com/hashicorp/vault/api" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/providers" - "github.com/stretchr/testify/assert" - "github.com/testcontainers/testcontainers-go" - "github.com/testcontainers/testcontainers-go/wait" -) - -type SecretData = map[string]interface{} - -func TestGetVaultSecret(t *testing.T) { - ctx := context.Background() - const testToken = "vault-token" - - req := testcontainers.GenericContainerRequest{ - ContainerRequest: testcontainers.ContainerRequest{ - AlwaysPullImage: false, - Image: "vault:1.6.3", - ExposedPorts: []string{"8200/tcp"}, - Env: map[string]string{"VAULT_DEV_ROOT_TOKEN_ID": testToken}, - WaitingFor: wait.ForLog("Vault server started!").WithStartupTimeout(20 * time.Second)}, - - Started: true, - } - - vaultContainer, err := testcontainers.GenericContainer(ctx, req) - assert.NoError(t, err) - defer vaultContainer.Terminate(ctx) //nolint - - ip, err := vaultContainer.Host(ctx) - assert.NoError(t, err) - port, err := vaultContainer.MappedPort(ctx, "8200") - assert.NoError(t, err) - host := fmt.Sprintf("http://%s:%s", ip, port.Port()) - - // - // pre-insert data w/API - // - config := &api.Config{Address: host} - client, err := api.NewClient(config) - assert.NoError(t, err) - client.SetToken(testToken) - secretData := SecretData{ - "MG_KEY": "value1", - } - _, err = client.Logical().Write("secret/data/settings/prod/billing-svc", SecretData{"data": secretData}) - assert.NoError(t, err) - - // - // use provider to read data - // - t.Setenv("VAULT_ADDR", host) - t.Setenv("VAULT_TOKEN", testToken) - p, err := providers.NewHashicorpVault(logging.New()) - assert.NoError(t, err) - kvp := core.KeyPath{Env: "MG_KEY", Path: "secret/data/settings/prod/billing-svc"} - res, err := p.Get(kvp) - - assert.NoError(t, err) - assert.Equal(t, "MG_KEY", res.Key) - assert.Equal(t, "value1", res.Value) - assert.Equal(t, "secret/data/settings/prod/billing-svc", res.ResolvedPath) - - err = (p.(*providers.HashicorpVault)).Put(kvp, "changed-secret") - assert.NoError(t, err) - - res, err = p.Get(kvp) - assert.NoError(t, err) - assert.Equal(t, "MG_KEY", res.Key) - assert.Equal(t, "changed-secret", res.Value) - assert.Equal(t, "secret/data/settings/prod/billing-svc", res.ResolvedPath) -} diff --git a/pkg/logging/logging.go b/pkg/logging/logging.go deleted file mode 100644 index 9a621e8c..00000000 --- a/pkg/logging/logging.go +++ /dev/null @@ -1,173 +0,0 @@ -package logging - -import ( - "io" - "strings" - - "github.com/sirupsen/logrus" -) - -var ( - defaultLogger = New() -) - -type Logger interface { - Panic(fmt string, a ...interface{}) - Fatal(fmt string, a ...interface{}) - Error(fmt string, a ...interface{}) - Warn(fmt string, a ...interface{}) - Info(fmt string, a ...interface{}) - Debug(fmt string, a ...interface{}) - Trace(fmt string, a ...interface{}) - - WithFields(map[string]interface{}) Logger - WithField(string, interface{}) Logger - WithError(err error) Logger - - GetLevel() string - SetLevel(string) - - SetOutputFormat(format string) - SetCallerReporter() -} - -type StandardLogger struct { - logger *logrus.Logger - fields map[string]interface{} -} - -// New returns a new application logger. -func New() *StandardLogger { - return &StandardLogger{ - logger: logrus.New(), - } -} - -// GetRoot returns the root logger application. -func GetRoot() *StandardLogger { - return defaultLogger -} - -// SetOutput sets the underlying logrus output. -func (l *StandardLogger) SetOutput(w io.Writer) { - l.logger.SetOutput(w) -} - -// SetOutputFormat change the logger format. -// available formats: text/json -func (l *StandardLogger) SetOutputFormat(format string) { - var formatter logrus.Formatter - - switch strings.ToLower(format) { - case "text": - formatter = &logrus.TextFormatter{ - FullTimestamp: true, - DisableLevelTruncation: true, - PadLevelText: true, - QuoteEmptyFields: true, - } - case "json": - formatter = &logrus.JSONFormatter{ - PrettyPrint: false, - } - default: - return // using default logger format - } - - l.logger.SetFormatter(formatter) -} - -// SetCallerReporter add calling method as a field. -func (l *StandardLogger) SetCallerReporter() { - l.logger.SetReportCaller(true) -} - -// WithFields create new logger instance with the given default fields. -// -// Example: -// logger :=log.WithFields(map[string]interface{}{"test": 2222}) -// logger.Info("Teller message") -> `INFO[0000] Teller message test=2222` -func (l *StandardLogger) WithFields(fields map[string]interface{}) Logger { - cp := *l - cp.fields = make(map[string]interface{}) - for k, v := range l.fields { - cp.fields[k] = v - } - for k, v := range fields { - cp.fields[k] = v - } - return &cp -} - -// WithField create new logger instance with singe field. -func (l *StandardLogger) WithField(name string, value interface{}) Logger { - return l.WithFields(map[string]interface{}{name: value}) -} - -// WithError add an error as single field to the logger. -func (l *StandardLogger) WithError(err error) Logger { - return l.WithField("error", err) -} - -// GetLevel return the current logging level. -func (l *StandardLogger) GetLevel() string { - return l.logger.GetLevel().String() -} - -// SetLevel sets the logger level. -func (l *StandardLogger) SetLevel(level string) { - - switch level { - case "panic'": - l.logger.SetLevel(logrus.PanicLevel) - case "fatal": - l.logger.SetLevel(logrus.FatalLevel) - case "error": - l.logger.SetLevel(logrus.ErrorLevel) - case "warn", "warning": - l.logger.SetLevel(logrus.WarnLevel) - case "info": - l.logger.SetLevel(logrus.InfoLevel) - case "debug": - l.logger.SetLevel(logrus.DebugLevel) - case "trace": - l.logger.SetLevel(logrus.TraceLevel) - case "null", "none": - l.logger.SetOutput(io.Discard) - default: - l.Warn("unknown log level %v", level) - l.logger.SetLevel(logrus.ErrorLevel) - } -} - -func (l *StandardLogger) Panic(fmt string, a ...interface{}) { - l.logger.WithFields(l.getFields()).Panicf(fmt, a...) -} - -func (l *StandardLogger) Fatal(fmt string, a ...interface{}) { - l.logger.WithFields(l.getFields()).Fatalf(fmt, a...) -} - -func (l *StandardLogger) Error(fmt string, a ...interface{}) { - l.logger.WithFields(l.getFields()).Errorf(fmt, a...) -} - -func (l *StandardLogger) Warn(fmt string, a ...interface{}) { - l.logger.WithFields(l.getFields()).Errorf(fmt, a...) -} - -func (l *StandardLogger) Info(fmt string, a ...interface{}) { - l.logger.WithFields(l.getFields()).Infof(fmt, a...) -} - -func (l *StandardLogger) Debug(fmt string, a ...interface{}) { - l.logger.WithFields(l.getFields()).Debugf(fmt, a...) -} - -func (l *StandardLogger) Trace(fmt string, a ...interface{}) { - l.logger.WithFields(l.getFields()).Tracef(fmt, a...) -} - -func (l *StandardLogger) getFields() map[string]interface{} { - return l.fields -} diff --git a/pkg/logging/logging_test.go b/pkg/logging/logging_test.go deleted file mode 100644 index 518ae17a..00000000 --- a/pkg/logging/logging_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package logging - -import ( - "bytes" - "encoding/json" - "errors" - "testing" - - "github.com/alecthomas/assert" -) - -func TestSetOutput(t *testing.T) { - - buf := new(bytes.Buffer) - logger := New() - - logger.SetOutput(buf) - logger.Error("error message") - - assert.NotEmpty(t, buf.String()) - -} - -func TestJSONFormat(t *testing.T) { - - buf := new(bytes.Buffer) - logger := New() - - logger.SetOutput(buf) - logger.SetOutputFormat("json") - logger.Error("error message") - - var js interface{} - assert.True(t, json.Unmarshal(buf.Bytes(), &js) == nil) - -} - -func TestTextFormat(t *testing.T) { - - buf := new(bytes.Buffer) - logger := New() - - logger.SetOutput(buf) - logger.SetOutputFormat("text") - logger.Error("error message") - - assert.Contains(t, buf.String(), "level=error") - assert.Contains(t, buf.String(), "msg=\"error message\"") - -} - -func TestWithFields(t *testing.T) { - - buf := new(bytes.Buffer) - logger := New() - - logger.SetOutput(buf) - logger.SetOutputFormat("text") - logger.WithFields(map[string]interface{}{"field-a": "test", "field-b": "test"}).Error("error message") - - assert.Contains(t, buf.String(), "field-a=test") - assert.Contains(t, buf.String(), "field-b=test") - -} - -func TestWithField(t *testing.T) { - - buf := new(bytes.Buffer) - logger := New() - - logger.SetOutput(buf) - logger.SetOutputFormat("text") - logger.WithField("field-a", "test").Error("error message") - - assert.Contains(t, buf.String(), "field-a=test") - -} - -func TestWithError(t *testing.T) { - - buf := new(bytes.Buffer) - logger := New() - - logger.SetOutput(buf) - logger.SetOutputFormat("text") - logger.WithError(errors.New("some-error")).Error("error message") - - assert.Contains(t, buf.String(), "error=some-error") - -} - -func TestLevelSetter(t *testing.T) { - - logger := New() - logger.SetLevel("debug") - assert.Equal(t, "debug", logger.GetLevel()) - -} diff --git a/pkg/porcelain.go b/pkg/porcelain.go deleted file mode 100644 index 40a935a5..00000000 --- a/pkg/porcelain.go +++ /dev/null @@ -1,216 +0,0 @@ -package pkg - -import ( - "bytes" - "fmt" - "io" - "math" - "os" - "sort" - "strings" - "time" - - survey "github.com/AlecAivazis/survey/v2" - "github.com/samber/lo" - - "github.com/fatih/color" - "github.com/jftuga/ellipsis" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/utils" -) - -type Porcelain struct { - Out io.Writer -} - -func (p *Porcelain) StartWizard() (*core.WizardAnswers, error) { - wd, _ := os.Getwd() - workingfolder := utils.LastSegment(wd) - - providers := BuiltinProviders{} - providerNames := providers.ProviderHumanToMachine() - displayProviders := lo.Keys(providerNames) - sort.Strings(displayProviders) - // the questions to ask - var qs = []*survey.Question{ - { - Name: "project", - Prompt: &survey.Input{ - Message: "Project name?", - Default: workingfolder, - }, - Validate: survey.Required, - }, - { - Name: "providers", - Prompt: &survey.MultiSelect{ - Message: "Select your secret providers", - PageSize: 10, - Options: displayProviders, - }, - }, - { - Name: "confirm", - Prompt: &survey.Confirm{ - Message: "Would you like extra confirmation before accessing secrets?", - }, - }, - } - - answers := core.WizardAnswers{} - // perform the questions - err := survey.Ask(qs, &answers) - if err != nil { - return nil, err - } - - if len(answers.Providers) == 0 { - return nil, fmt.Errorf("you need to select at least one provider") - } - - answers.ProviderKeys = map[string]bool{} - for _, plabel := range answers.Providers { - answers.ProviderKeys[providerNames[plabel]] = true - } - - return &answers, nil -} - -func (p *Porcelain) DidCreateNewFile(fname string) { - green := color.New(color.FgGreen).SprintFunc() - fmt.Fprintf(p.Out, "Created file: %v\n", green(fname)) -} - -func (p *Porcelain) AskForConfirmation(msg string) bool { - yesno := false - prompt := &survey.Confirm{ - Message: msg, - } - _ = survey.AskOne(prompt, &yesno) - return yesno -} - -func (p *Porcelain) VSpace(size int) { - fmt.Fprint(p.Out, strings.Repeat("\n", size)) -} - -func (p *Porcelain) PrintContext(projectName, loadedFrom string) { - green := color.New(color.FgGreen).SprintFunc() - white := color.New(color.FgWhite).SprintFunc() - - fmt.Fprintf(p.Out, "-*- %s: loaded variables for %s using %s -*-\n", white("teller"), green(projectName), green(loadedFrom)) -} - -func (p *Porcelain) PrintEntries(entries []core.EnvEntry) { - var buf bytes.Buffer - yellow := color.New(color.FgYellow).SprintFunc() - gray := color.New(color.FgHiBlack).SprintFunc() - green := color.New(color.FgGreen).SprintFunc() - red := color.New(color.FgRed).SprintFunc() - - for i := range entries { - v := entries[i] - ep := ellipsis.Shorten(v.ResolvedPath, 30) //nolint: gomnd - if !v.IsFound { - fmt.Fprintf(&buf, "[%s %s %s] %s\n", yellow(v.ProviderName), gray(ep), red("missing"), green(v.Key)) - } else { - fmt.Fprintf(&buf, "[%s %s] %s %s %s\n", yellow(v.ProviderName), gray(ep), green(v.Key), gray("="), maskedValue(v.Value)) - } - } - - out := buf.String() - - fmt.Fprint(p.Out, out) -} -func maskedValue(v string) string { - return fmt.Sprintf("%s*****", v[:int(math.Min(float64(len(v)), 2))]) //nolint: gomnd -} - -func (p *Porcelain) PrintMatches(matches []core.Match) { - yellow := color.New(color.FgYellow).SprintFunc() - gray := color.New(color.FgHiBlack).SprintFunc() - green := color.New(color.FgGreen).SprintFunc() - white := color.New(color.FgWhite).SprintFunc() - red := color.New(color.FgRed).SprintFunc() - - sort.Slice(matches, func(i, j int) bool { - return matches[i].Path < matches[j].Path - }) - - for _, m := range matches { //nolint - sevcolor := white - if m.Entry.Severity == core.High { - sevcolor = red - } - if m.Entry.Severity == core.Medium { - sevcolor = yellow - } - fmt.Printf("[%s] %s (%s,%s): found match for %s/%s (%s)\n", sevcolor(m.Entry.Severity), green(m.Path), yellow(m.LineNumber), yellow(m.MatchIndex), gray(m.Entry.ProviderName), red(m.Entry.Key), gray(maskedValue(m.Entry.Value))) - } -} - -func (p *Porcelain) PrintMatchSummary(findings []core.Match, entries []core.EnvEntry, elapsed time.Duration) { - yellow := color.New(color.FgYellow).SprintFunc() - goodbad := color.New(color.FgGreen).SprintFunc() - if len(findings) > 0 { - goodbad = color.New(color.FgRed).SprintFunc() - } - - fmt.Printf("Scanning for %v entries: found %v matches in %v\n", yellow(len(entries)), goodbad(len(findings)), goodbad(elapsed)) -} - -func (p *Porcelain) PrintDrift(drifts []core.DriftedEntry) { - green := color.New(color.FgGreen).SprintFunc() - gray := color.New(color.FgHiBlack).SprintFunc() - red := color.New(color.FgRed).SprintFunc() - - if len(drifts) > 0 { - fmt.Fprintf(p.Out, "Drifts detected: %v\n\n", len(drifts)) - - for i := range drifts { - d := drifts[i] - if d.Diff == "changed" { - fmt.Fprintf(p.Out, "%v [%v] %v %v %v != %v %v %v\n", d.Diff, d.Source.Source, green(d.Source.ProviderName), green(d.Source.Key), gray(maskedValue(d.Source.Value)), red(d.Target.ProviderName), red(d.Target.Key), gray(maskedValue(d.Target.Value))) - } else { - fmt.Fprintf(p.Out, "%v [%v] %v %v %v ??\n", d.Diff, d.Source.Source, green(d.Source.ProviderName), green(d.Source.Key), gray(maskedValue(d.Source.Value))) - } - } - } - -} - -func (p *Porcelain) DidPutKVP(kvp core.KeyPath, pname string, sync bool) { - green := color.New(color.FgGreen).SprintFunc() - yellow := color.New(color.FgYellow).SprintFunc() - gray := color.New(color.FgHiBlack).SprintFunc() - if sync { - fmt.Fprintf(p.Out, "Synced %v (%v): OK.\n", green(pname), gray(kvp.Path)) - } else { - fmt.Fprintf(p.Out, "Put %v (%v) in %v: OK.\n", yellow(kvp.Env), gray(kvp.Path), green(pname)) - } -} - -func (p *Porcelain) NoPutKVP(k, pname string) { - green := color.New(color.FgGreen).SprintFunc() - yellow := color.New(color.FgYellow).SprintFunc() - fmt.Fprintf(p.Out, "Put %v in %v: no such key '%v' in mapping\n", yellow(k), green(pname), yellow(k)) -} - -func (p *Porcelain) DidDeleteKP(kp core.KeyPath, pname string) { - green := color.New(color.FgGreen).SprintFunc() - yellow := color.New(color.FgYellow).SprintFunc() - gray := color.New(color.FgHiBlack).SprintFunc() - fmt.Fprintf(p.Out, "Delete %v (%v) in %v: OK.\n", yellow(kp.Env), gray(kp.Path), green(pname)) -} - -func (p *Porcelain) NoDeleteKP(k, pname string) { - green := color.New(color.FgGreen).SprintFunc() - yellow := color.New(color.FgYellow).SprintFunc() - fmt.Fprintf(p.Out, "Delete %v in %v: no such key '%v' in mapping\n", yellow(k), green(pname), yellow(k)) -} - -func (p *Porcelain) DidDeleteP(path, pname string) { - green := color.New(color.FgGreen).SprintFunc() - gray := color.New(color.FgHiBlack).SprintFunc() - fmt.Fprintf(p.Out, "Delete mapping in path %v in %v: OK.\n", gray(path), green(pname)) -} diff --git a/pkg/porcelain_test.go b/pkg/porcelain_test.go deleted file mode 100644 index 66bdda38..00000000 --- a/pkg/porcelain_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package pkg - -import ( - "bytes" - "testing" - - "github.com/alecthomas/assert" - "github.com/spectralops/teller/pkg/core" -) - -func TestPorcelainNonInteractive(t *testing.T) { - var b bytes.Buffer - p := Porcelain{ - Out: &b, - } - p.DidCreateNewFile("myfile.yaml") - assert.Equal(t, b.String(), "Created file: myfile.yaml\n") - b.Reset() - - p.PrintContext("project", "place") - assert.Equal(t, b.String(), "-*- teller: loaded variables for project using place -*-\n") - b.Reset() - - p.PrintEntries([]core.EnvEntry{ - {IsFound: true, Key: "k", Value: "v", ProviderName: "test-provider", ResolvedPath: "path/kv"}, - }) - assert.Equal(t, b.String(), "[test-provider path/kv] k = v*****\n") - b.Reset() -} - -func TestPorcelainPrintDrift(t *testing.T) { - var b bytes.Buffer - p := Porcelain{ - Out: &b, - } - p.PrintDrift([]core.DriftedEntry{ - { - Diff: "changed", - Source: core.EnvEntry{ - - Source: "s1", Key: "k", Value: "v", ProviderName: "test-provider", ResolvedPath: "path/kv", - }, - - Target: core.EnvEntry{ - - Sink: "s1", Key: "k", Value: "x", ProviderName: "test-provider", ResolvedPath: "path/kv", - }, - }, - { - Diff: "changed", - Source: core.EnvEntry{ - Source: "s2", Key: "k2", Value: "1", ProviderName: "test-provider", ResolvedPath: "path/kv", - }, - - Target: core.EnvEntry{ - Sink: "s2", Key: "k2", Value: "2", ProviderName: "test-provider", ResolvedPath: "path/kv", - }, - }, - }) - assert.Equal(t, b.String(), `Drifts detected: 2 - -changed [s1] test-provider k v***** != test-provider k x***** -changed [s2] test-provider k2 1***** != test-provider k2 2***** -`) -} diff --git a/pkg/provider_test.go b/pkg/provider_test.go deleted file mode 100644 index 8e133813..00000000 --- a/pkg/provider_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package pkg - -import ( - "fmt" - "testing" - - "github.com/alecthomas/assert" -) - -func TestGetProvider(t *testing.T) { - providers := &BuiltinProviders{} - p, err := providers.GetProvider("missing") - assert.Nil(t, p) - assert.NotNil(t, err) - assert.Contains(t, err.Error(), "provider 'missing' does not exist") - - for _, v := range providers.ProviderHumanToMachine() { - _, err := providers.GetProvider(v) - if err != nil { - assert.NotContains(t, err.Error(), fmt.Sprintf("provider %s does not exist", v)) - } - } -} diff --git a/pkg/providers.go b/pkg/providers.go deleted file mode 100644 index 50411e20..00000000 --- a/pkg/providers.go +++ /dev/null @@ -1,27 +0,0 @@ -package pkg - -import ( - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers" -) - -type Providers interface { - GetProvider(name string) (core.Provider, error) - ProviderHumanToMachine() map[string]string -} - -type BuiltinProviders struct { -} - -func (p *BuiltinProviders) ProviderHumanToMachine() map[string]string { - providersMeta := providers.GetAllProvidersMeta() - descriptionToNameMap := make(map[string]string) - for _, meta := range providersMeta { - descriptionToNameMap[meta.Description] = meta.Name - } - return descriptionToNameMap -} - -func (p *BuiltinProviders) GetProvider(name string) (core.Provider, error) { - return providers.ResolveProvider(name) -} diff --git a/pkg/providers/ansible_vault.go b/pkg/providers/ansible_vault.go deleted file mode 100644 index 22d3549c..00000000 --- a/pkg/providers/ansible_vault.go +++ /dev/null @@ -1,133 +0,0 @@ -package providers - -import ( - "fmt" - "os" - "sort" - - "github.com/joho/godotenv" - vault "github.com/sosedoff/ansible-vault-go" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -type AnsibleVaultClient interface { - Read(p string) (map[string]string, error) -} - -type AnsibleVaultReader struct { - passPhrase string -} - -func (a AnsibleVaultReader) Read(p string) (map[string]string, error) { - content, err := vault.DecryptFile(p, a.passPhrase) - if err != nil { - return nil, err - } - return godotenv.Unmarshal(content) -} - -type AnsibleVault struct { - logger logging.Logger - client AnsibleVaultClient -} - -//nolint -func init() { - metaInto := core.MetaInfo{ - Description: "Ansible Vault", - Name: "ansible_vault", - Authentication: "ANSIBLE_VAULT_PASSPHRASE.", - ConfigTemplate: ` - # Configure via environment variables for integration: - # ANSIBLE_VAULT_PASSPHRASE: Ansible Vault Password - - ansible_vault: - env_sync: - path: ansible/vars/vault_{{stage}}.yml - - env: - KEY1: - path: ansible/vars/vault_{{stage}}.yml - NONEXIST_KEY: - path: ansible/vars/vault_{{stage}}.yml -`, - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: false, PutMapping: false}, - } - RegisterProvider(metaInto, NewAnsibleVault) -} - -// NewAnsibleVault creates new provider instance -func NewAnsibleVault(logger logging.Logger) (core.Provider, error) { - ansibleVaultPassphrase := os.Getenv("ANSIBLE_VAULT_PASSPHRASE") - return &AnsibleVault{ - logger: logger, - client: &AnsibleVaultReader{ - passPhrase: ansibleVaultPassphrase, - }, - }, nil -} - -// Name return the provider name -func (a *AnsibleVault) Name() string { - return "AnsibleVault" -} - -// Put will create a new single entry -func (a *AnsibleVault) Put(p core.KeyPath, val string) error { - return fmt.Errorf("provider %q does not implement write yet", a.Name()) -} - -// PutMapping will create a multiple entries -func (a *AnsibleVault) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %q does not implement write yet", a.Name()) -} - -// GetMapping returns a multiple entries -func (a *AnsibleVault) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - // Read existing secret - a.logger.WithField("path", p.Path).Debug("read secret") - kvs, err := a.client.Read(p.Path) - if err != nil { - return nil, err - } - - var entries []core.EnvEntry - for k, v := range kvs { - entries = append(entries, p.FoundWithKey(k, v)) - } - sort.Sort(core.EntriesByKey(entries)) - - return entries, nil -} - -// Get returns a single entry -func (a *AnsibleVault) Get(p core.KeyPath) (*core.EnvEntry, error) { //nolint:dupl - a.logger.WithField("path", p.Path).Debug("read secret") - - kvs, err := a.client.Read(p.Path) - if err != nil { - return nil, err - } - - k := p.EffectiveKey() - val, ok := kvs[k] - if !ok { - a.logger.WithFields(map[string]interface{}{"path": p.Path, "key": k}).Debug("key not found") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(val) - return &ent, nil -} - -// Delete will delete entry -func (a *AnsibleVault) Delete(kp core.KeyPath) error { - return fmt.Errorf("provider %s does not implement delete yet", a.Name()) -} - -// DeleteMapping will delete the given path recessively -func (a *AnsibleVault) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("provider %s does not implement delete yet", a.Name()) -} diff --git a/pkg/providers/ansible_vault_test.go b/pkg/providers/ansible_vault_test.go deleted file mode 100644 index 1e89d90e..00000000 --- a/pkg/providers/ansible_vault_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package providers - -import ( - "testing" - - "github.com/golang/mock/gomock" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestAnsibleVault(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockAnsibleVaultClient(ctrl) - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - out := map[string]string{ - "MG_KEY": "shazam", - "SMTP_PASS": "mailman", - } - client.EXPECT().Read(gomock.Eq(path)).Return(out, nil).AnyTimes() - client.EXPECT().Read(gomock.Eq(pathmap)).Return(out, nil).AnyTimes() - - s := AnsibleVault{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) -} diff --git a/pkg/providers/aws_secretsmanager.go b/pkg/providers/aws_secretsmanager.go deleted file mode 100644 index 1b6f1bf9..00000000 --- a/pkg/providers/aws_secretsmanager.go +++ /dev/null @@ -1,284 +0,0 @@ -package providers - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "os" - "sort" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/config" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager" - smtypes "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/utils" -) - -type AWSSecretsManagerClient interface { - GetSecretValue(ctx context.Context, params *secretsmanager.GetSecretValueInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.GetSecretValueOutput, error) - CreateSecret(ctx context.Context, params *secretsmanager.CreateSecretInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.CreateSecretOutput, error) - PutSecretValue(ctx context.Context, params *secretsmanager.PutSecretValueInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.PutSecretValueOutput, error) - DescribeSecret(ctx context.Context, params *secretsmanager.DescribeSecretInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.DescribeSecretOutput, error) - DeleteSecret(ctx context.Context, params *secretsmanager.DeleteSecretInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.DeleteSecretOutput, error) -} - -type AWSSecretsManager struct { - client AWSSecretsManagerClient - logger logging.Logger - deletionDisableRecoveryWindow bool - treatSecretMarkedForDeletionAsNonExisting bool - deletionRecoveryWindowInDays int64 -} - -var defaultDeletionRecoveryWindowInDays int64 = 7 - -const versionSplit = "," - -// nolint -func init() { - metaInfo := core.MetaInfo{ - Name: "aws_secretsmanager", - Description: "AWS Secrets Manager", - Authentication: "Your standard `AWS_DEFAULT_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` need to be populated in your environment. `AWS_ENDPOINT` is used to allow usage of localstack", - ConfigTemplate: ` - # configure only from environment - aws_secretsmanager: - env_sync: - path: prod/foo/bar - env: - FOO_BAR: - path: prod/foo/bar - field: SOME_KEY -`, - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true, Delete: true, DeleteMapping: true}, - } - RegisterProvider(metaInfo, NewAWSSecretsManager) -} - -func NewAWSSecretsManager(logger logging.Logger) (core.Provider, error) { - customResolver := aws.EndpointResolverFunc(func(service, region string) (aws.Endpoint, error) { - awsEndpointOverride := os.Getenv("AWS_ENDPOINT") - if awsEndpointOverride != "" { - return aws.Endpoint{ - PartitionID: "aws", - URL: awsEndpointOverride, - SigningRegion: region, - }, nil - } - - // returning EndpointNotFoundError will allow the service to fallback to its default resolution - return aws.Endpoint{}, &aws.EndpointNotFoundError{} - }) - - cfg, err := config.LoadDefaultConfig(context.Background(), config.WithEndpointResolver(customResolver)) - if err != nil { - return nil, err - } - - client := secretsmanager.NewFromConfig(cfg) - - return &AWSSecretsManager{ - client: client, - logger: logger, - deletionRecoveryWindowInDays: defaultDeletionRecoveryWindowInDays, - deletionDisableRecoveryWindow: false, - treatSecretMarkedForDeletionAsNonExisting: true, - }, nil -} - -func (a *AWSSecretsManager) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - kvs, err := a.getSecret(p) - if err != nil { - return nil, err - } - - var entries []core.EnvEntry - for k, v := range kvs { - entries = append(entries, p.FoundWithKey(k, v)) - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -func (a *AWSSecretsManager) Put(kp core.KeyPath, val string) error { - k := kp.EffectiveKey() - return a.PutMapping(kp, map[string]string{k: val}) -} - -func (a *AWSSecretsManager) PutMapping(kp core.KeyPath, m map[string]string) error { - secrets, err := a.getSecret(kp) - if err != nil { - return err - } - - secretAlreadyExist := len(secrets) != 0 - - secrets = utils.Merge(secrets, m) - secretBytes, err := json.Marshal(secrets) - if err != nil { - return err - } - - secretString := string(secretBytes) - ctx := context.Background() - if secretAlreadyExist { - // secret already exist - put new value - a.logger.WithField("path", kp.Path).Debug("secret already exists, update the existing one") - _, err = a.client.PutSecretValue(ctx, &secretsmanager.PutSecretValueInput{SecretId: &kp.Path, SecretString: &secretString}) - return err - } - - // create secret - a.logger.WithField("path", kp.Path).Debug("create secret") - _, err = a.client.CreateSecret(ctx, &secretsmanager.CreateSecretInput{Name: &kp.Path, SecretString: &secretString}) - if err != nil { - return err - } - - return nil -} - -func (a *AWSSecretsManager) Get(kp core.KeyPath) (*core.EnvEntry, error) { - kvs, err := a.getSecret(kp) - if err != nil { - return nil, err - } - - k := kp.EffectiveKey() - val, ok := kvs[k] - if !ok { - a.logger.WithField("key", k).Debug("key not found in kvs secrets") - ent := kp.Missing() - return &ent, nil - } - - ent := kp.Found(val) - return &ent, nil -} - -func (a *AWSSecretsManager) Delete(kp core.KeyPath) error { - kvs, err := a.getSecret(kp) - if err != nil { - return err - } - - k := kp.EffectiveKey() - delete(kvs, k) - - if len(kvs) == 0 { - return a.DeleteMapping(kp) - } - - secretBytes, err := json.Marshal(kvs) - if err != nil { - return err - } - - secretString := string(secretBytes) - ctx := context.Background() - a.logger.WithField("path", kp.Path).Debug("put secret value") - _, err = a.client.PutSecretValue(ctx, &secretsmanager.PutSecretValueInput{SecretId: &kp.Path, SecretString: &secretString}) - return err -} - -func (a *AWSSecretsManager) DeleteMapping(kp core.KeyPath) error { - kvs, err := a.getSecret(kp) - if err != nil { - return err - } - - if kvs == nil { - // already deleted - a.logger.WithField("path", kp.Path).Debug("already deleted") - return nil - } - - ctx := context.Background() - a.logger.WithField("path", kp.Path).Debug("delete secret") - _, err = a.client.DeleteSecret(ctx, &secretsmanager.DeleteSecretInput{ - SecretId: &kp.Path, - RecoveryWindowInDays: &a.deletionRecoveryWindowInDays, - ForceDeleteWithoutRecovery: &a.deletionDisableRecoveryWindow, - }) - - return err -} - -func (a *AWSSecretsManager) getSecret(kp core.KeyPath) (map[string]string, error) { - a.logger.WithField("path", kp.Path).Debug("get secret value") - valueInput := secretsmanager.GetSecretValueInput{SecretId: &kp.Path} - - splitVersion := strings.Split(kp.Path, versionSplit) - //nolint:gomnd - if len(splitVersion) == 2 { - a.logger.WithFields(map[string]interface{}{ - "path": splitVersion[0], - "version": splitVersion[1], - }).Debug("add version") - valueInput.SecretId = &splitVersion[0] - valueInput.VersionId = &splitVersion[1] - } - - res, err := a.client.GetSecretValue(context.Background(), &valueInput) - - var ( - resNotFoundErr *smtypes.ResourceNotFoundException - invalidReqErr *smtypes.InvalidRequestException - ) - - switch { - case err == nil: - if res == nil || res.SecretString == nil { - return nil, fmt.Errorf("data not found at %q", kp.Path) - } - if kp.Plaintext { - return map[string]string{ - core.PlainTextKey: *res.SecretString, - }, nil - } - - var secret map[string]interface{} - err = json.Unmarshal([]byte(*res.SecretString), &secret) - if err != nil { - return nil, err - } - - stringParse := map[string]string{} - for k, v := range secret { - stringParse[k] = fmt.Sprintf("%v", v) - } - return stringParse, nil - case errors.As(err, &resNotFoundErr): - // doesn't exist - do not treat as an error - return nil, nil - case a.treatSecretMarkedForDeletionAsNonExisting && errors.As(err, &invalidReqErr): - // see whether it is marked for deletion - markedForDeletion, markedForDeletionErr := a.isSecretMarkedForDeletion(kp) - if err != nil { - return nil, markedForDeletionErr - } - - if markedForDeletion { - // doesn't exist anymore - do not treat as an error - return nil, nil - } - - return nil, nil - } - - return nil, err - -} - -func (a *AWSSecretsManager) isSecretMarkedForDeletion(kp core.KeyPath) (bool, error) { - data, err := a.client.DescribeSecret(context.Background(), &secretsmanager.DescribeSecretInput{SecretId: &kp.Path}) - if err != nil { - return false, err - } - - return data.DeletedDate != nil, nil -} diff --git a/pkg/providers/aws_secretsmanager_test.go b/pkg/providers/aws_secretsmanager_test.go deleted file mode 100644 index ac880622..00000000 --- a/pkg/providers/aws_secretsmanager_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/alecthomas/assert" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager" - "github.com/golang/mock/gomock" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestAWSSecretsManager(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockAWSSecretsManagerClient(ctrl) - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - in := secretsmanager.GetSecretValueInput{SecretId: &path} - inmap := secretsmanager.GetSecretValueInput{SecretId: &pathmap} - data := `{"MG_KEY":"shazam", "SMTP_PASS":"mailman"}` - out := secretsmanager.GetSecretValueOutput{ - SecretString: &data, - } - client.EXPECT().GetSecretValue(gomock.Any(), gomock.Eq(&in)).Return(&out, nil).AnyTimes() - client.EXPECT().GetSecretValue(gomock.Any(), gomock.Eq(&inmap)).Return(&out, nil).AnyTimes() - s := AWSSecretsManager{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) -} - -func TestAWSSecretsManagerPlainText(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockAWSSecretsManagerClient(ctrl) - path := "settings/prod/billing-svc" - in := secretsmanager.GetSecretValueInput{SecretId: &path} - data := `hello-world` - out := secretsmanager.GetSecretValueOutput{ - SecretString: &data, - } - client.EXPECT().GetSecretValue(gomock.Any(), gomock.Eq(&in)).Return(&out, nil).AnyTimes() - s := AWSSecretsManager{ - client: client, - logger: GetTestLogger(), - } - AssertProviderPlainText(t, &s, data) -} - -func TestAWSSecretsManagerFailures(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockAWSSecretsManagerClient(ctrl) - client.EXPECT().GetSecretValue(gomock.Any(), gomock.Any()).Return(nil, errors.New("error")).AnyTimes() - s := AWSSecretsManager{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/aws_ssm.go b/pkg/providers/aws_ssm.go deleted file mode 100644 index 2a793fce..00000000 --- a/pkg/providers/aws_ssm.go +++ /dev/null @@ -1,140 +0,0 @@ -package providers - -import ( - "context" - "fmt" - "os" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/config" - "github.com/aws/aws-sdk-go-v2/service/ssm" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -type AWSSSMClient interface { - GetParameter(ctx context.Context, params *ssm.GetParameterInput, optFns ...func(*ssm.Options)) (*ssm.GetParameterOutput, error) - PutParameter(ctx context.Context, params *ssm.PutParameterInput, optFns ...func(*ssm.Options)) (*ssm.PutParameterOutput, error) - DeleteParameter(ctx context.Context, params *ssm.DeleteParameterInput, optFns ...func(*ssm.Options)) (*ssm.DeleteParameterOutput, error) -} -type AWSSSM struct { - client AWSSSMClient - logger logging.Logger -} - -const awsssmName = "aws_ssm" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "AWS SSM (aka paramstore)", - Name: awsssmName, - Authentication: "Your standard `AWS_DEFAULT_REGION`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` need to be populated in your environment. `AWS_ENDPOINT` is used to allow usage of localstack", - ConfigTemplate: ` - # configure only from environment - aws_ssm: - env: - FOO_BAR: - path: /prod/foobar - decrypt: true - `, - Ops: core.OpMatrix{Get: true, Put: true, Delete: true}, - } - RegisterProvider(metaInfo, NewAWSSSM) -} - -func NewAWSSSM(logger logging.Logger) (core.Provider, error) { - customResolver := aws.EndpointResolverFunc(func(service, region string) (aws.Endpoint, error) { - awsEndpointOverride := os.Getenv("AWS_ENDPOINT") - if awsEndpointOverride != "" { - return aws.Endpoint{ - PartitionID: "aws", - URL: awsEndpointOverride, - SigningRegion: region, - }, nil - } - - // returning EndpointNotFoundError will allow the service to fallback to its default resolution - return aws.Endpoint{}, &aws.EndpointNotFoundError{} - }) - - cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithEndpointResolver(customResolver)) - if err != nil { - return nil, err - } - - client := ssm.NewFromConfig(cfg) - - return &AWSSSM{client: client, logger: logger}, nil -} - -func (a *AWSSSM) Put(kp core.KeyPath, val string) error { - - _, err := a.client.PutParameter(context.TODO(), &ssm.PutParameterInput{ - Name: &kp.Path, - Value: &val, - Overwrite: aws.Bool(true), - Type: types.ParameterTypeString, - }) - if err != nil { - return err - } - - return nil -} - -func (a *AWSSSM) PutMapping(kp core.KeyPath, m map[string]string) error { - for k, v := range m { - ap := kp.SwitchPath(k) - err := a.Put(ap, v) - if err != nil { - return err - } - } - - return nil -} - -func (a *AWSSSM) GetMapping(kp core.KeyPath) ([]core.EnvEntry, error) { - return nil, fmt.Errorf("does not support full env sync (path: %s)", kp.Path) -} - -func (a *AWSSSM) Delete(kp core.KeyPath) error { - _, err := a.client.DeleteParameter(context.TODO(), &ssm.DeleteParameterInput{Name: &kp.Path}) - return err -} - -func (a *AWSSSM) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("does not support full env sync (path: %s)", kp.Path) -} - -func (a *AWSSSM) Get(p core.KeyPath) (*core.EnvEntry, error) { - secret, err := a.getSecret(p) - if err != nil { - return nil, err - } - - if secret == nil { - a.logger.WithField("path", p.Path).Debug("secret is empty") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(*secret) - return &ent, nil -} - -func (a *AWSSSM) getSecret(kp core.KeyPath) (*string, error) { - a.logger.WithField("path", kp.Path).Debug("get entry") - res, err := a.client.GetParameter(context.TODO(), &ssm.GetParameterInput{Name: &kp.Path, WithDecryption: &kp.Decrypt}) - if err != nil { - return nil, err - } - - if res == nil || res.Parameter.Value == nil { - return nil, nil - } - - return res.Parameter.Value, nil -} diff --git a/pkg/providers/aws_ssm_test.go b/pkg/providers/aws_ssm_test.go deleted file mode 100644 index bcb1d2bd..00000000 --- a/pkg/providers/aws_ssm_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/aws/aws-sdk-go-v2/aws" - - "github.com/alecthomas/assert" - "github.com/aws/aws-sdk-go-v2/service/ssm" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/golang/mock/gomock" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestAWSSSM(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockAWSSSMClient(ctrl) - path := "settings/prod/billing-svc" - val := "shazam" - - in := ssm.GetParameterInput{Name: &path, WithDecryption: aws.Bool(true)} - out := ssm.GetParameterOutput{ - Parameter: &types.Parameter{ - Value: &val, - }, - } - client.EXPECT().GetParameter(gomock.Any(), gomock.Eq(&in)).Return(&out, nil).AnyTimes() - s := AWSSSM{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, false) -} - -func TestAWSSSMFailures(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockAWSSSMClient(ctrl) - client.EXPECT().GetParameter(gomock.Any(), gomock.Any()).Return(nil, errors.New("error")).AnyTimes() - s := AWSSSM{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/azure_keyvault.go b/pkg/providers/azure_keyvault.go deleted file mode 100644 index facfb589..00000000 --- a/pkg/providers/azure_keyvault.go +++ /dev/null @@ -1,164 +0,0 @@ -package providers - -import ( - "context" - "fmt" - "os" - "path" - - "github.com/Azure/azure-sdk-for-go/profiles/latest/keyvault/keyvault" - kvauth "github.com/Azure/azure-sdk-for-go/services/keyvault/auth" - "github.com/Azure/go-autorest/autorest" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -const AzureVaultDomain = "vault.azure.net" - -type AzureKeyVaultClient interface { - SetSecret(ctx context.Context, vaultBaseURL string, secretName string, parameters keyvault.SecretSetParameters) (result keyvault.SecretBundle, err error) - GetSecret(ctx context.Context, vaultBaseURL string, secretName string, secretVersion string) (result keyvault.SecretBundle, err error) - GetSecrets(ctx context.Context, vaultBaseURL string, maxresults *int32) (result keyvault.SecretListResultPage, err error) - DeleteSecret(ctx context.Context, vaultBaseURL string, secretName string) (result keyvault.DeletedSecretBundle, err error) -} - -type AzureKeyVault struct { - client AzureKeyVaultClient - logger logging.Logger - vaultName string - vaultBaseURL string -} - -const azureName = "azure_keyvault" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Azure Key Vault", - Name: azureName, - Authentication: "TODO(XXX)", - ConfigTemplate: ` - # you can mix and match many files - azure_keyvault: - env_sync: - path: azure - env: - FOO_BAR: - path: foobar - `, - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true, Delete: true}, - } - RegisterProvider(metaInfo, NewAzureKeyVault) -} - -func NewAzureKeyVault(logger logging.Logger) (core.Provider, error) { - vaultName := os.Getenv("KVAULT_NAME") - if vaultName == "" { - return nil, fmt.Errorf("cannot find KVAULT_NAME for azure key vault") - } - - var authorizer autorest.Authorizer - var err error - - if _, ok := os.LookupEnv("AZURE_CLI"); ok { - authorizer, err = kvauth.NewAuthorizerFromCLI() - } else { - authorizer, err = kvauth.NewAuthorizerFromEnvironment() - } - - if err != nil { - return nil, err - } - - basicClient := keyvault.New() - basicClient.Authorizer = authorizer - return &AzureKeyVault{client: &basicClient, - vaultName: vaultName, - logger: logger, - vaultBaseURL: "https://" + vaultName + "." + AzureVaultDomain, - }, nil -} - -func (a *AzureKeyVault) Name() string { - return "azure_keyvault" -} - -func (a *AzureKeyVault) Put(p core.KeyPath, val string) error { - a.logger.WithField("path", p.Path).Debug("set secret") - _, err := a.client.SetSecret(context.TODO(), a.vaultBaseURL, p.Path, keyvault.SecretSetParameters{ - Value: &val, - }) - return err -} - -func (a *AzureKeyVault) PutMapping(p core.KeyPath, m map[string]string) error { - for k, v := range m { - ap := p.SwitchPath(k) - err := a.Put(ap, v) - if err != nil { - return err - } - } - return nil -} - -func (a *AzureKeyVault) GetMapping(kp core.KeyPath) ([]core.EnvEntry, error) { - r := []core.EnvEntry{} - ctx := context.Background() - a.logger.WithField("vault_base_url", a.vaultBaseURL).Debug("get secrets") - secretList, err := a.client.GetSecrets(ctx, a.vaultBaseURL, nil) - if err != nil { - return nil, err - } - - for secretList.NotDone() { - for _, secret := range secretList.Values() { - value, err := a.getSecret(core.KeyPath{Path: path.Base(*secret.ID)}) - if err != nil { - return nil, err - } - if value.Value != nil { - ent := kp.FoundWithKey(path.Base(*secret.ID), *value.Value) - r = append(r, ent) - } - } - - err := secretList.NextWithContext(ctx) - if err != nil { - return nil, err - } - } - return r, nil -} - -func (a *AzureKeyVault) Get(p core.KeyPath) (*core.EnvEntry, error) { - secretResp, err := a.getSecret(p) - if err != nil { - return nil, err - } - if secretResp.Value == nil { - a.logger.WithField("path", p.Path).Debug("secret is empty") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(*secretResp.Value) - return &ent, nil -} - -func (a *AzureKeyVault) Delete(kp core.KeyPath) error { - _, err := a.client.DeleteSecret(context.TODO(), a.vaultBaseURL, kp.Path) - return err -} - -func (a *AzureKeyVault) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", azureName) -} - -func (a *AzureKeyVault) getSecret(kp core.KeyPath) (keyvault.SecretBundle, error) { - a.logger.WithFields(map[string]interface{}{ - "vault_base_url": a.vaultBaseURL, - "secret_name": kp.Path, - }).Debug("get secret") - return a.client.GetSecret(context.Background(), a.vaultBaseURL, kp.Path, "") -} diff --git a/pkg/providers/azure_keyvault_test.go b/pkg/providers/azure_keyvault_test.go deleted file mode 100644 index 8b504f8a..00000000 --- a/pkg/providers/azure_keyvault_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package providers - -import ( - "context" - "errors" - "testing" - - "github.com/Azure/azure-sdk-for-go/profiles/latest/keyvault/keyvault" - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func String(v string) *string { return &v } - -func TestAzureKeyVault(t *testing.T) { - - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockAzureKeyVaultClient(ctrl) - - a := AzureKeyVault{ - client: client, - logger: GetTestLogger(), - vaultName: "test", - vaultBaseURL: "https://test/", - } - - path := "settings/prod/billing-svc" - shazam := "shazam" - - secretList := keyvault.SecretListResult{ - Value: &[]keyvault.SecretItem{ - {ID: String("all")}, - {ID: String("all-1")}, - }, - } - - stopNext := func(context.Context, keyvault.SecretListResult) (keyvault.SecretListResult, error) { - return keyvault.SecretListResult{}, nil - } - returnSecrets := keyvault.NewSecretListResultPage(secretList, stopNext) - client.EXPECT().GetSecret(gomock.Any(), a.vaultBaseURL, path, "").Return(keyvault.SecretBundle{Value: &shazam}, nil).AnyTimes() - client.EXPECT().GetSecret(gomock.Any(), a.vaultBaseURL, "all", "").Return(keyvault.SecretBundle{Value: String("mailman")}, nil).AnyTimes() - client.EXPECT().GetSecret(gomock.Any(), a.vaultBaseURL, "all-1", "").Return(keyvault.SecretBundle{Value: String("shazam")}, nil).AnyTimes() - client.EXPECT().GetSecrets(gomock.Any(), a.vaultBaseURL, nil).Return(returnSecrets, nil).AnyTimes() - - AssertProvider(t, &a, true) - -} - -func TestAzureKeyVaultFailures(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockAzureKeyVaultClient(ctrl) - a := AzureKeyVault{ - client: client, - logger: GetTestLogger(), - vaultName: "test", - vaultBaseURL: "https://test/", - } - - client.EXPECT().GetSecret(gomock.Any(), a.vaultBaseURL, "settings/{{stage}}/billing-svc", "").Return(keyvault.SecretBundle{}, errors.New("error")).AnyTimes() - - _, err := a.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/cloudflare_workers_kv.go b/pkg/providers/cloudflare_workers_kv.go deleted file mode 100644 index a2b0e51e..00000000 --- a/pkg/providers/cloudflare_workers_kv.go +++ /dev/null @@ -1,125 +0,0 @@ -package providers - -import ( - "context" - "fmt" - "os" - "sort" - - cloudflare "github.com/cloudflare/cloudflare-go" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -type CloudflareClient interface { - WriteWorkersKV(ctx context.Context, namespaceID, key string, value []byte) (cloudflare.Response, error) - WriteWorkersKVBulk(ctx context.Context, namespaceID string, kvs cloudflare.WorkersKVBulkWriteRequest) (cloudflare.Response, error) - ReadWorkersKV(ctx context.Context, namespaceID string, key string) ([]byte, error) - ListWorkersKVs(ctx context.Context, namespaceID string) (cloudflare.ListStorageKeysResponse, error) -} - -type Cloudflare struct { - client CloudflareClient - logger logging.Logger -} - -const cloudFlareWorkersKVName = "cloudflare_workers_kv" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Cloudflare Workers K/V", - Name: cloudFlareWorkersKVName, - Authentication: "requires the following environment variables to be set:\n`CLOUDFLARE_API_KEY`: Your Cloudflare api key.\n`CLOUDFLARE_API_EMAIL`: Your email associated with the api key.\n`CLOUDFLARE_ACCOUNT_ID`: Your account ID.\n", - ConfigTemplate: ` - TODO(XXX): Missing -`, - Ops: core.OpMatrix{Get: true, GetMapping: true}, - } - RegisterProvider(metaInfo, NewCloudflareClient) -} - -func NewCloudflareClient(logger logging.Logger) (core.Provider, error) { - api, err := cloudflare.New( - os.Getenv("CLOUDFLARE_API_KEY"), - os.Getenv("CLOUDFLARE_API_EMAIL"), - ) - - if err != nil { - return nil, err - } - - cloudflare.UsingAccount(os.Getenv("CLOUDFLARE_ACCOUNT_ID"))(api) //nolint - - return &Cloudflare{client: api, logger: logger}, nil -} - -func (c *Cloudflare) Put(p core.KeyPath, val string) error { - return fmt.Errorf("provider %q does not implement write yet", cloudFlareWorkersKVName) -} - -func (c *Cloudflare) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %q does not implement write yet", cloudFlareWorkersKVName) -} - -func (c *Cloudflare) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - entries, err := c.getSecrets(p) - if err != nil { - return nil, err - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -func (c *Cloudflare) Get(p core.KeyPath) (*core.EnvEntry, error) { - secret, err := c.getSecret(p) - if err != nil { - return nil, err - } - ent := p.Found(string(secret)) - return &ent, nil -} - -func (c *Cloudflare) Delete(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", cloudFlareWorkersKVName) -} - -func (c *Cloudflare) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", cloudFlareWorkersKVName) -} - -func (c *Cloudflare) getSecrets(p core.KeyPath) ([]core.EnvEntry, error) { - c.logger.WithField("namespace_id", p.Path).Debug("get workers KVs") - secrets, err := c.client.ListWorkersKVs(context.TODO(), p.Path) - if err != nil { - return nil, err - } - - entries := []core.EnvEntry{} - for _, k := range secrets.Result { - p.Field = k.Name - secret, err := c.getSecret(p) - if err != nil { - entries = append(entries, p.Missing()) - } - entries = append(entries, p.FoundWithKey(k.Name, string(secret))) - } - - return entries, nil -} - -func (c *Cloudflare) getSecret(p core.KeyPath) ([]byte, error) { - k := p.Field - if k == "" { - c.logger.WithField("field", p.Field).Debug("`field` attribute not configured. trying to get `env` attribute") - k = p.Env - } - if k == "" { - return nil, fmt.Errorf("Key required for fetching secrets. Received \"\"") //nolint - } - c.logger.WithFields(map[string]interface{}{ - "namespace_id": p.Path, - "name": k, - }).Debug("read worker kv") - return c.client.ReadWorkersKV(context.TODO(), p.Path, k) -} diff --git a/pkg/providers/cloudflare_workers_kv_test.go b/pkg/providers/cloudflare_workers_kv_test.go deleted file mode 100644 index 0c725267..00000000 --- a/pkg/providers/cloudflare_workers_kv_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/alecthomas/assert" - cloudflare "github.com/cloudflare/cloudflare-go" - "github.com/golang/mock/gomock" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestCloudflareWorkersKV(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockCloudflareClient(ctrl) - - // In CloudflareWorkersKV this isn't the path name, but a Workers KV namespace ID. - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - shazam := []byte("shazam") - mailman := []byte("mailman") - - listOut := cloudflare.ListStorageKeysResponse{ //nolint - cloudflare.Response{}, - []cloudflare.StorageKey{{Name: "MG_KEY"}, {Name: "SMTP_PASS"}}, - cloudflare.ResultInfo{}, - } - - client.EXPECT().ReadWorkersKV(gomock.Any(), path, gomock.Eq("MG_KEY")).Return(shazam, nil).AnyTimes() - client.EXPECT().ReadWorkersKV(gomock.Any(), pathmap, gomock.Eq("MG_KEY")).Return(shazam, nil).AnyTimes() - client.EXPECT().ReadWorkersKV(gomock.Any(), pathmap, gomock.Eq("SMTP_PASS")).Return(mailman, nil).AnyTimes() - client.EXPECT().ListWorkersKVs(gomock.Any(), pathmap).Return(listOut, nil).AnyTimes() - - s := Cloudflare{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) -} - -func TestCloudflareReadWorkersKVFailures(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockCloudflareClient(ctrl) - client.EXPECT().ReadWorkersKV(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, errors.New("error")).AnyTimes() - s := Cloudflare{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - _, missingLookupKeyError := s.Get(core.KeyPath{Field: "", Env: "", Path: "settings/{{stage}}/billing-svc"}) - - assert.NotNil(t, err) - assert.Equal(t, missingLookupKeyError.Error(), "Key required for fetching secrets. Received \"\"") -} - -func TestCloudflareListWorkersKVsFailures(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockCloudflareClient(ctrl) - client.EXPECT().ListWorkersKVs(gomock.Any(), gomock.Any()).Return(cloudflare.ListStorageKeysResponse{}, errors.New("error")).AnyTimes() - s := Cloudflare{ - client: client, - logger: GetTestLogger(), - } - _, err := s.GetMapping(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/cloudflare_workers_secrets.go b/pkg/providers/cloudflare_workers_secrets.go deleted file mode 100644 index 86156967..00000000 --- a/pkg/providers/cloudflare_workers_secrets.go +++ /dev/null @@ -1,154 +0,0 @@ -package providers - -import ( - "context" - "errors" - "fmt" - "os" - - cloudflare "github.com/cloudflare/cloudflare-go" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -var ( - ErrCloudFlareSourceFieldIsMissing = errors.New("`source` field is missing") -) - -type CloudflareSecretsClient interface { - SetWorkersSecret(ctx context.Context, script string, req *cloudflare.WorkersPutSecretRequest) (cloudflare.WorkersPutSecretResponse, error) - DeleteWorkersSecret(ctx context.Context, script, secretName string) (cloudflare.Response, error) -} - -type CloudflareSecrets struct { - client CloudflareSecretsClient - logger logging.Logger -} - -const CloudflareWorkersSecretName = "cloudflare_workers_secret" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Cloudflare Workers Secrets", - Name: CloudflareWorkersSecretName, - Authentication: "requires the following environment variables to be set:\n`CLOUDFLARE_API_KEY`: Your Cloudflare api key.\n`CLOUDFLARE_API_EMAIL`: Your email associated with the api key.\n`CLOUDFLARE_ACCOUNT_ID`: Your account ID.\n", - ConfigTemplate: ` - # Configure via environment variables for integration: - # CLOUDFLARE_API_KEY: Your Cloudflare api key. - # CLOUDFLARE_API_EMAIL: Your email associated with the api key. - # CLOUDFLARE_ACCOUNT_ID: Your account ID. - - cloudflare_workers_secrets: - env_sync: - source: # Mandatory: script field - env: - script-value: - path: foo-secret - source: # Mandatory: script field - `, - Ops: core.OpMatrix{Put: true, PutMapping: true, Delete: true}, - } - RegisterProvider(metaInfo, NewCloudflareSecretsClient) -} - -func NewCloudflareSecretsClient(logger logging.Logger) (core.Provider, error) { - api, err := cloudflare.New( - os.Getenv("CLOUDFLARE_API_KEY"), - os.Getenv("CLOUDFLARE_API_EMAIL"), - ) - - if err != nil { - return nil, err - } - - cloudflare.UsingAccount(os.Getenv("CLOUDFLARE_ACCOUNT_ID"))(api) //nolint - return &CloudflareSecrets{client: api, logger: logger}, nil -} - -func (c *CloudflareSecrets) Put(p core.KeyPath, val string) error { - - if p.Source == "" { - return ErrCloudFlareSourceFieldIsMissing - } - - secretName, err := c.getSecretName(p) - if err != nil { - return err - } - - secretRequest := cloudflare.WorkersPutSecretRequest{ - Name: secretName, - Text: val, - Type: cloudflare.WorkerSecretTextBindingType, - } - - c.logger.WithFields(map[string]interface{}{ - "script": p.Source, - "name": secretRequest.Name, - }).Debug("set workers secret") - _, err = c.client.SetWorkersSecret(context.TODO(), p.Source, &secretRequest) - - return err -} - -func (c *CloudflareSecrets) PutMapping(p core.KeyPath, m map[string]string) error { - if p.Source == "" { - return ErrCloudFlareSourceFieldIsMissing - } - - for k, v := range m { - ap := p.WithEnv(fmt.Sprintf("%v/%v", p.Path, k)) - - err := c.Put(ap, v) - if err != nil { - return err - } - } - return nil -} - -func (c *CloudflareSecrets) Delete(p core.KeyPath) error { - - if p.Source == "" { - return ErrCloudFlareSourceFieldIsMissing - } - - secretName, err := c.getSecretName(p) - if err != nil { - return err - } - - c.logger.WithFields(map[string]interface{}{ - "script": p.Source, - "name": secretName, - }).Debug("delete workers secret") - _, err = c.client.DeleteWorkersSecret(context.TODO(), p.Source, secretName) - return err -} - -func (c *CloudflareSecrets) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - return nil, fmt.Errorf("%s does not support read functionality", CloudflareWorkersSecretName) -} - -func (c *CloudflareSecrets) Get(p core.KeyPath) (*core.EnvEntry, error) { - return nil, fmt.Errorf("%s does not support read functionality", CloudflareWorkersSecretName) -} - -func (c *CloudflareSecrets) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement deleteMapping yet", CloudflareWorkersSecretName) -} - -func (c *CloudflareSecrets) getSecretName(p core.KeyPath) (string, error) { - - k := p.Field - if k == "" { - c.logger.WithField("field", p.Field).Debug("`field` attribute not configured. trying to get `env` attribute") - k = p.Env - } - if k == "" { - return "", fmt.Errorf("key required for fetching secrets. Received \"\"") - } - return k, nil - -} diff --git a/pkg/providers/cloudflare_workers_secrets_test.go b/pkg/providers/cloudflare_workers_secrets_test.go deleted file mode 100644 index 18dd879d..00000000 --- a/pkg/providers/cloudflare_workers_secrets_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package providers - -import ( - "testing" - - "github.com/alecthomas/assert" - cloudflare "github.com/cloudflare/cloudflare-go" - "github.com/golang/mock/gomock" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestCloudflareWorkersSecretsPut(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockCloudflareSecretsClient(ctrl) - - expectedWorkerPutRequest := cloudflare.WorkersPutSecretRequest{ - Name: "MG_KEY", - Text: "put-secret", - Type: "secret_text", - } - client.EXPECT().SetWorkersSecret(gomock.Any(), "script-key", &expectedWorkerPutRequest).Return(cloudflare.WorkersPutSecretResponse{}, nil).AnyTimes() - - c := CloudflareSecrets{ - client: client, - logger: GetTestLogger(), - } - assert.Nil(t, c.Put(core.KeyPath{Field: "MG_KEY", Source: "script-key"}, "put-secret")) - assert.Nil(t, c.Put(core.KeyPath{Env: "MG_KEY", Source: "script-key"}, "put-secret")) - assert.NotNil(t, c.Put(core.KeyPath{Path: "script-key"}, "put-secret")) - assert.EqualError(t, c.Delete(core.KeyPath{Field: "MG_KEY"}), ErrCloudFlareSourceFieldIsMissing.Error()) -} - -func TestCloudflareWorkersSecretsDelete(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockCloudflareSecretsClient(ctrl) - - client.EXPECT().DeleteWorkersSecret(gomock.Any(), "script-key", "MG_KEY").Return(cloudflare.Response{}, nil).AnyTimes() - - c := CloudflareSecrets{ - client: client, - logger: GetTestLogger(), - } - - assert.Nil(t, c.Delete(core.KeyPath{Field: "MG_KEY", Source: "script-key"})) - assert.EqualError(t, c.Delete(core.KeyPath{Field: "MG_KEY"}), ErrCloudFlareSourceFieldIsMissing.Error()) - assert.NotNil(t, c.Delete(core.KeyPath{Path: "script-key"})) - -} diff --git a/pkg/providers/consul.go b/pkg/providers/consul.go deleted file mode 100644 index d1cd994e..00000000 --- a/pkg/providers/consul.go +++ /dev/null @@ -1,132 +0,0 @@ -package providers - -import ( - "fmt" - "sort" - - "github.com/hashicorp/consul/api" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/utils" -) - -type ConsulClient interface { - Get(key string, q *api.QueryOptions) (*api.KVPair, *api.QueryMeta, error) - List(prefix string, q *api.QueryOptions) (api.KVPairs, *api.QueryMeta, error) - Put(p *api.KVPair, q *api.WriteOptions) (*api.WriteMeta, error) -} - -type Consul struct { - client ConsulClient - logger logging.Logger -} - -const consulName = "consul" - -//nolint -func init() { - metaInto := core.MetaInfo{ - Description: "Consul", - Name: consulName, - Authentication: "If you have the Consul CLI working and configured, there's no special action to take.\nConfiguration is environment based, as defined by client standard. See variables [here](https://github.com/hashicorp/consul/blob/master/api/api.go#L28).", - ConfigTemplate: ` - # Configure via environment: - # CONSUL_HTTP_ADDR - consul: - env_sync: - path: redis/config - env: - ETC_DSN: - path: redis/config/foobar -`, - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true}, - } - RegisterProvider(metaInto, NewConsul) -} - -func NewConsul(logger logging.Logger) (core.Provider, error) { - df := api.DefaultConfig() - client, err := api.NewClient(df) - if err != nil { - return nil, err - } - kv := client.KV() - return &Consul{client: kv, logger: logger}, nil -} - -func (a *Consul) Put(p core.KeyPath, val string) error { - a.logger.WithField("path", p.Path).Debug("put value") - _, err := a.client.Put(&api.KVPair{ - Key: p.Path, - Value: []byte(val), - }, &api.WriteOptions{}) - - return err -} - -func (a *Consul) PutMapping(p core.KeyPath, m map[string]string) error { - for k, v := range m { - ap := p.SwitchPath(fmt.Sprintf("%v/%v", p.Path, k)) - err := a.Put(ap, v) - if err != nil { - return err - } - } - return nil -} - -func (a *Consul) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - kvs, err := a.getSecrets(p) - if err != nil { - return nil, err - } - entries := []core.EnvEntry{} - for _, kv := range kvs { - k := kv.Key - v := string(kv.Value) - seg := utils.LastSegment(k) - entries = append(entries, p.FoundWithKey(seg, v)) - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -func (a *Consul) Get(p core.KeyPath) (*core.EnvEntry, error) { - kv, err := a.getSecret(p) - if err != nil { - return nil, fmt.Errorf("%v cannot get value: %v", consulName, err) - } - - if kv == nil { - a.logger.WithField("path", p.Path).Debug("kv is empty") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(string(kv.Value)) - return &ent, nil -} - -func (a *Consul) Delete(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", consulName) -} - -func (a *Consul) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", consulName) -} - -func (a *Consul) getSecrets(kp core.KeyPath) (api.KVPairs, error) { - a.logger.WithField("path", kp.Path).Debug("get all keys under a prefix") - kvs, _, err := a.client.List(kp.Path, nil) - return kvs, err -} - -func (a *Consul) getSecret(kp core.KeyPath) (*api.KVPair, error) { - a.logger.WithField("path", kp.Path).Debug("get value") - kv, _, err := a.client.Get(kp.Path, nil) - if err != nil { - return nil, err - } - return kv, nil -} diff --git a/pkg/providers/consul_test.go b/pkg/providers/consul_test.go deleted file mode 100644 index 93b3fd84..00000000 --- a/pkg/providers/consul_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - "github.com/hashicorp/consul/api" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestConsul(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockConsulClient(ctrl) - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - out := api.KVPair{ - Key: "MG_KEY", - Value: []byte("shazam"), - } - outlist := api.KVPairs{ - { - Key: "SMTP_PASS", - Value: []byte("mailman"), - }, - { - Key: "MG_KEY", - Value: []byte("shazam"), - }, - } - client.EXPECT().Get(gomock.Eq(path), gomock.Any()).Return(&out, nil, nil).AnyTimes() - client.EXPECT().List(gomock.Eq(pathmap), gomock.Any()).Return(outlist, nil, nil).AnyTimes() - s := Consul{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) -} - -func TestConsulFailures(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockConsulClient(ctrl) - client.EXPECT().Get(gomock.Any(), gomock.Any()).Return(nil, nil, errors.New("error")).AnyTimes() - s := Consul{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/cyberark_conjur.go b/pkg/providers/cyberark_conjur.go deleted file mode 100644 index 36315b98..00000000 --- a/pkg/providers/cyberark_conjur.go +++ /dev/null @@ -1,115 +0,0 @@ -package providers - -import ( - "fmt" - "os" - - "github.com/cyberark/conjur-api-go/conjurapi" - "github.com/cyberark/conjur-api-go/conjurapi/authn" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -type ResourceFilter struct { - Kind string - Search string - Limit int - Offset int -} - -type ConjurClient interface { - AddSecret(variableID string, secretValue string) error - RetrieveSecret(variableID string) ([]byte, error) -} - -type CyberArkConjur struct { - client ConjurClient - logger logging.Logger -} - -const ConjurName = "cyberark_conjur" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "CyberArk Conjure", - Name: ConjurName, - Authentication: "Requires a username and API key populated in your environment:\n* `CONJUR_AUTHN_LOGIN`\n* `CONJUR_AUTHN_API_KEY`", - ConfigTemplate: ` - # https://conjur.org - # set CONJUR_AUTHN_LOGIN and CONJUR_AUTHN_API_KEY env vars - # set .conjurrc file in user's home directory - cyberark_conjur: - env: - FOO_BAR: - path: /secrets/foo/bar -`, - Ops: core.OpMatrix{Get: true, Put: true}, - } - RegisterProvider(metaInfo, NewConjurClient) -} - -func NewConjurClient(logger logging.Logger) (core.Provider, error) { - config, err := conjurapi.LoadConfig() - if err != nil { - return nil, err - } - - conjur, err := conjurapi.NewClientFromKey(config, - authn.LoginPair{ - Login: os.Getenv("CONJUR_AUTHN_LOGIN"), - APIKey: os.Getenv("CONJUR_AUTHN_API_KEY"), - }, - ) - if err != nil { - return nil, err - } - - return &CyberArkConjur{client: conjur, logger: logger}, nil -} - -func (c *CyberArkConjur) Put(p core.KeyPath, val string) error { - err := c.putSecret(p, val) - - return err -} -func (c *CyberArkConjur) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %q does not implement put mapping yet", ConjurName) -} - -func (c *CyberArkConjur) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - return nil, fmt.Errorf("provider %q does not implement get mapping yet", ConjurName) -} - -func (c *CyberArkConjur) Get(p core.KeyPath) (*core.EnvEntry, error) { - secret, err := c.getSecret(p) - if err != nil { - return nil, err - } - if secret == nil { - c.logger.WithField("path", p.Path).Debug("secret is empty") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(string(secret)) - return &ent, nil -} - -func (c *CyberArkConjur) Delete(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", ConjurName) -} - -func (c *CyberArkConjur) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", ConjurName) -} - -func (c *CyberArkConjur) getSecret(kp core.KeyPath) ([]byte, error) { - c.logger.WithField("path", kp.Path).Debug("get a secret from the path") - return c.client.RetrieveSecret(kp.Path) -} - -func (c *CyberArkConjur) putSecret(kp core.KeyPath, val string) error { - c.logger.WithField("path", kp.Path).Debug("create secret") - return c.client.AddSecret(kp.Path, val) -} diff --git a/pkg/providers/doppler.go b/pkg/providers/doppler.go deleted file mode 100644 index f9a8ca3a..00000000 --- a/pkg/providers/doppler.go +++ /dev/null @@ -1,124 +0,0 @@ -package providers - -// TODO(XXX): remove this provider, no support/specialty - -import ( - "fmt" - "sort" - - "github.com/DopplerHQ/cli/pkg/configuration" - "github.com/DopplerHQ/cli/pkg/http" - "github.com/DopplerHQ/cli/pkg/models" - "github.com/DopplerHQ/cli/pkg/utils" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -type DopplerClient interface { - GetSecrets(host string, verifyTLS bool, apiKey string, project string, config string) ([]byte, http.Error) -} - -type dopplerClient struct{} - -func (dopplerClient) GetSecrets(host string, verifyTLS bool, apiKey, project, config string) ([]byte, http.Error) { - return http.GetSecrets(host, verifyTLS, apiKey, project, config) -} - -type Doppler struct { - client DopplerClient - logger logging.Logger - config models.ScopedOptions -} - -const DopplerName = "doppler" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Doppler", - Name: DopplerName, - Ops: core.OpMatrix{Get: true}, - } - - RegisterProvider(metaInfo, NewDoppler) -} - -func NewDoppler(logger logging.Logger) (core.Provider, error) { - configuration.Setup() - configuration.LoadConfig() - - return &Doppler{ - client: dopplerClient{}, - logger: logger, - config: configuration.Get(configuration.Scope), - }, nil -} - -func (h *Doppler) Put(p core.KeyPath, val string) error { - return fmt.Errorf("provider %q does not implement write yet", DopplerName) -} -func (h *Doppler) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %q does not implement write yet", DopplerName) -} - -func (h *Doppler) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - s, err := h.getConfig(p.Path) - if err != nil { - return nil, err - } - - entries := []core.EnvEntry{} - for k, v := range s { - entries = append(entries, p.FoundWithKey(k, v.ComputedValue)) - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -func (h *Doppler) Get(p core.KeyPath) (*core.EnvEntry, error) { - s, err := h.getConfig(p.Path) - if err != nil { - return nil, err - } - - key := p.Env - if p.Field != "" { - h.logger.WithField("path", p.Path).Debug("`env` attribute not configured. take `field` attribute") - key = p.Field - } - - v, ok := s[key] - if !ok { - h.logger.WithFields(map[string]interface{}{"key": key, "path": p.Path}).Debug("the given key not exists") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(v.ComputedValue) - - return &ent, nil -} - -func (h *Doppler) Delete(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", DopplerName) -} - -func (h *Doppler) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", DopplerName) -} - -func (h *Doppler) getConfig(config string) (map[string]models.ComputedSecret, error) { - h.logger.Debug("get secrets") - r, herr := h.client.GetSecrets( - h.config.APIHost.Value, - utils.GetBool(h.config.VerifyTLS.Value, true), - h.config.Token.Value, - h.config.EnclaveProject.Value, - config, - ) - if !herr.IsNil() { - return nil, herr.Err - } - - return models.ParseSecrets(r) -} diff --git a/pkg/providers/doppler_test.go b/pkg/providers/doppler_test.go deleted file mode 100644 index b349f773..00000000 --- a/pkg/providers/doppler_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package providers - -import ( - "testing" - - "github.com/DopplerHQ/cli/pkg/http" - "github.com/DopplerHQ/cli/pkg/models" - "github.com/golang/mock/gomock" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestDoppler(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockDopplerClient(ctrl) - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - out := []byte(`{ - "secrets": { - "MG_KEY": { - "computed": "shazam" - }, - "SMTP_PASS": { - "computed": "mailman" - } - } - }`) - - client.EXPECT().GetSecrets(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Eq(path)).Return(out, http.Error{}).AnyTimes() - client.EXPECT().GetSecrets(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Eq(pathmap)).Return(out, http.Error{}).AnyTimes() - - s := Doppler{ - client: client, - config: models.ScopedOptions{}, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) -} diff --git a/pkg/providers/dotenv.go b/pkg/providers/dotenv.go deleted file mode 100644 index 290bc895..00000000 --- a/pkg/providers/dotenv.go +++ /dev/null @@ -1,226 +0,0 @@ -package providers - -import ( - "os" - "path" - "sort" - - "github.com/joho/godotenv" - "github.com/mitchellh/go-homedir" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/utils" -) - -const ( - filePerm = 0644 - dirPerm = 0755 -) - -type DotEnvClient interface { - Read(p string) (map[string]string, error) - Write(p string, kvs map[string]string) error - Exists(p string) (bool, error) - Delete(p string) error -} -type DotEnvReader struct { -} - -func (d *DotEnvReader) Read(p string) (map[string]string, error) { - p, err := homedir.Expand(p) - if err != nil { - return nil, err - } - - content, err := os.ReadFile(p) - if err != nil { - if os.IsNotExist(err) { - return nil, nil - } - - return nil, err - } - - return godotenv.Unmarshal(string(content)) -} - -func (d *DotEnvReader) Write(p string, kvs map[string]string) error { - content, err := godotenv.Marshal(kvs) - if err != nil { - return err - } - - p, err = homedir.Expand(p) - if err != nil { - return err - } - - // ensure all subdirectories exist - err = os.MkdirAll(path.Dir(p), dirPerm) - if err != nil { - return err - } - - return os.WriteFile(p, []byte(content), filePerm) -} - -func (d *DotEnvReader) Exists(p string) (bool, error) { - p, err := homedir.Expand(p) - if err != nil { - return false, err - } - - _, err = os.Stat(p) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - - return false, err - } - - return true, nil -} - -func (d *DotEnvReader) Delete(p string) error { - p, err := homedir.Expand(p) - if err != nil { - return err - } - - return os.Remove(p) -} - -type Dotenv struct { - client DotEnvClient - logger logging.Logger -} - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: ".env", - Authentication: "", - Name: "dotenv", - ConfigTemplate: ` - # you can mix and match many files - dotenv: - env_sync: - path: ~/my-dot-env.env - env: - FOO_BAR: - path: ~/my-dot-env.env -`, - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true, Delete: true, DeleteMapping: true}, - } - - RegisterProvider(metaInfo, NewDotenv) -} - -func NewDotenv(logger logging.Logger) (core.Provider, error) { - return &Dotenv{ - client: &DotEnvReader{}, - logger: logger, - }, nil -} - -func (a *Dotenv) Put(p core.KeyPath, val string) error { - k := p.EffectiveKey() - return a.PutMapping(p, map[string]string{k: val}) -} - -func (a *Dotenv) PutMapping(kp core.KeyPath, m map[string]string) error { - exists, err := a.client.Exists(kp.Path) - if err != nil { - a.logger.WithField("path", kp.Path).Debug("secret path not exists") - return err - } - - if !exists { - a.logger.WithField("path", kp.Path).Debug("set secret") - return a.client.Write(kp.Path, m) - } - - a.logger.WithField("path", kp.Path).Debug("read secret") - // get a fresh copy of a hash - secrets, err := a.client.Read(kp.Path) - if err != nil { - return err - } - - secrets = utils.Merge(secrets, m) - a.logger.WithField("path", kp.Path).Debug("merge and write secrets to path") - return a.client.Write(kp.Path, secrets) -} - -func (a *Dotenv) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - a.logger.WithField("path", p.Path).Debug("read secret") - kvs, err := a.client.Read(p.Path) - if err != nil { - return nil, err - } - var entries []core.EnvEntry - for k, v := range kvs { - entries = append(entries, p.FoundWithKey(k, v)) - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -func (a *Dotenv) Get(p core.KeyPath) (*core.EnvEntry, error) { //nolint:dupl - a.logger.WithField("path", p.Path).Debug("read secret") - kvs, err := a.client.Read(p.Path) - if err != nil { - return nil, err - } - - k := p.EffectiveKey() - val, ok := kvs[k] - if !ok { - a.logger.WithFields(map[string]interface{}{"path": p.Path, "key": k}).Debug("key not found") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(val) - return &ent, nil -} - -func (a *Dotenv) Delete(kp core.KeyPath) error { - a.logger.WithField("path", kp.Path).Debug("read secret") - kvs, err := a.client.Read(kp.Path) - if err != nil { - return err - } - - k := kp.EffectiveKey() - delete(kvs, k) - - if len(kvs) == 0 { - return a.DeleteMapping(kp) - } - - p, err := homedir.Expand(kp.Path) - if err != nil { - return err - } - - return a.client.Write(p, kvs) -} - -func (a *Dotenv) DeleteMapping(kp core.KeyPath) error { - exists, err := a.client.Exists(kp.Path) - if err != nil { - a.logger.WithField("path", kp.Path).Debug("secret path not exists") - return err - } - - if !exists { - // already deleted - a.logger.WithField("path", kp.Path).Debug("secret already deleted") - return nil - } - - a.logger.WithField("path", kp.Path).Debug("delete key") - return a.client.Delete(kp.Path) -} diff --git a/pkg/providers/dotenv_test.go b/pkg/providers/dotenv_test.go deleted file mode 100644 index e0f27a49..00000000 --- a/pkg/providers/dotenv_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestDotenv(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockDotEnvClient(ctrl) - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - out := map[string]string{ - "MG_KEY": "shazam", - "SMTP_PASS": "mailman", - } - client.EXPECT().Read(gomock.Eq(path)).Return(out, nil).AnyTimes() - client.EXPECT().Read(gomock.Eq(pathmap)).Return(out, nil).AnyTimes() - client.EXPECT().Read(gomock.Eq(pathmap)).Return(out, nil).AnyTimes() - s := Dotenv{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) -} - -func TestDotenvFailures(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockDotEnvClient(ctrl) - client.EXPECT().Read(gomock.Any()).Return(nil, errors.New("error")).AnyTimes() - s := Dotenv{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/etcd.go b/pkg/providers/etcd.go deleted file mode 100644 index f8d8e6f2..00000000 --- a/pkg/providers/etcd.go +++ /dev/null @@ -1,166 +0,0 @@ -package providers - -import ( - "context" - "crypto/tls" - "fmt" - "sort" - - "os" - "strings" - - spb "go.etcd.io/etcd/api/v3/mvccpb" - clientv3 "go.etcd.io/etcd/client/v3" - - "go.etcd.io/etcd/pkg/v3/transport" - - "github.com/samber/lo" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/utils" -) - -type EtcdClient interface { - Get(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.GetResponse, error) - Put(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) -} -type Etcd struct { - client EtcdClient - logger logging.Logger -} - -const EtcdName = "etcd" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Etcd", - Name: EtcdName, - Authentication: "These environment variables need to be populated\n* `ETCDCTL_ENDPOINTS`\nFor TLS:\n* `ETCDCTL_CA_FILE`\n* `ETCDCTL_CERT_FILE`\n* `ETCDCTL_KEY_FILE`", - ConfigTemplate: ` - # Configure via environment: - # ETCDCTL_ENDPOINTS - # tls: - # ETCDCTL_CA_FILE - # ETCDCTL_CERT_FILE - # ETCDCTL_KEY_FILE - etcd: - env_sync: - path: /prod/foo - env: - ETC_DSN: - path: /prod/foo/bar -`, - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true}, - } - RegisterProvider(metaInfo, NewEtcd) -} - -func NewEtcd(logger logging.Logger) (core.Provider, error) { - epstring := os.Getenv("ETCDCTL_ENDPOINTS") - if epstring == "" { - return nil, fmt.Errorf("cannot find ETCDCTL_ENDPOINTS for etcd") - } - - eps := lo.Map(strings.Split(epstring, ","), func(s string, _ int) string { return strings.Trim(s, " ") }) - client, err := newClient(eps) - if err != nil { - return nil, err - } - return &Etcd{client: client, logger: logger}, nil -} - -func (a *Etcd) Put(p core.KeyPath, val string) error { - a.logger.WithField("path", p.Path).Debug("create key") - _, err := a.client.Put(context.TODO(), p.Path, val) - return err -} -func (a *Etcd) PutMapping(p core.KeyPath, m map[string]string) error { - for k, v := range m { - ap := p.SwitchPath(fmt.Sprintf("%v/%v", p.Path, k)) - err := a.Put(ap, v) - if err != nil { - return err - } - } - return nil -} - -func (a *Etcd) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - kvs, err := a.getSecret(p, clientv3.WithPrefix()) - if err != nil { - return nil, err - } - entries := []core.EnvEntry{} - for _, kv := range kvs { - k := string(kv.Key) - v := string(kv.Value) - seg := utils.LastSegment(k) - entries = append(entries, p.FoundWithKey(seg, v)) - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -func (a *Etcd) Get(p core.KeyPath) (*core.EnvEntry, error) { - kvs, err := a.getSecret(p) - if err != nil { - return nil, err - } - for _, kv := range kvs { - k := string(kv.Key) - v := string(kv.Value) - if k == p.Path { - ent := p.Found(v) - return &ent, nil - } - } - - ent := p.Missing() - return &ent, nil -} - -func (a *Etcd) Delete(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", EtcdName) -} - -func (a *Etcd) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", EtcdName) -} - -func (a *Etcd) getSecret(kp core.KeyPath, opts ...clientv3.OpOption) ([]*spb.KeyValue, error) { - a.logger.WithField("path", kp.Path).Debug("get key") - res, err := a.client.Get(context.TODO(), kp.Path, opts...) - if err != nil { - return nil, err - } - return res.Kvs, nil -} - -func newClient(eps []string) (*clientv3.Client, error) { - tr, err := getTransport() - if err != nil { - return nil, err - } - - cfg := clientv3.Config{ - TLS: tr, - Endpoints: eps, - } - return clientv3.New(cfg) -} -func getTransport() (*tls.Config, error) { - cafile := os.Getenv("ETCDCTL_CA_FILE") - certfile := os.Getenv("ETCDCTL_CERT_FILE") - keyfile := os.Getenv("ETCDCTL_KEY_FILE") - if cafile == "" || certfile == "" || keyfile == "" { - return nil, nil - } - - tlsinfo := &transport.TLSInfo{ - CertFile: certfile, - KeyFile: keyfile, - TrustedCAFile: cafile, - } - return tlsinfo.ClientConfig() -} diff --git a/pkg/providers/etcd_test.go b/pkg/providers/etcd_test.go deleted file mode 100644 index ca409b95..00000000 --- a/pkg/providers/etcd_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" - spb "go.etcd.io/etcd/api/v3/mvccpb" - clientv3 "go.etcd.io/etcd/client/v3" -) - -func TestEtcd(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockEtcdClient(ctrl) - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - - kv1 := &spb.KeyValue{ - Key: []byte("settings/prod/billing-svc"), - Value: []byte("shazam"), - } - kv2 := &spb.KeyValue{ - Key: []byte("settings/prod/billing-svc"), - Value: []byte("mailman"), - } - out := clientv3.GetResponse{ - Kvs: []*spb.KeyValue{kv1}, - } - outmap := clientv3.GetResponse{ - Kvs: []*spb.KeyValue{kv2, kv1}, - } - client.EXPECT().Get(gomock.Any(), gomock.Eq(path)).Return(&out, nil).AnyTimes() - client.EXPECT().Get(gomock.Any(), gomock.Eq(pathmap), gomock.Any()).Return(&outmap, nil).AnyTimes() - s := Etcd{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) -} - -func TestEtcdFailures(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockEtcdClient(ctrl) - client.EXPECT().Get(gomock.Any(), gomock.Any()).Return(nil, errors.New("error")).AnyTimes() - s := Etcd{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/export.go b/pkg/providers/export.go deleted file mode 100644 index c49eec13..00000000 --- a/pkg/providers/export.go +++ /dev/null @@ -1,32 +0,0 @@ -package providers - -import ( - "encoding/json" - - "github.com/spectralops/teller/pkg/core" -) - -type TellerExport struct { - Version string `json:"version"` - Providers map[string]core.MetaInfo `json:"providers"` -} - -func GenerateProvidersMetaJSON(version string, providersMetaList []core.MetaInfo) (string, error) { - providersMetaMap := make(map[string]core.MetaInfo) - for _, provider := range providersMetaList { - providersMetaMap[provider.Name] = provider - } - - tellerObject := TellerExport{ - Version: version, - Providers: providersMetaMap, - } - - jsonOutput, err := json.MarshalIndent(tellerObject, "", " ") - - if err != nil { - return "", err - } - - return string(jsonOutput), nil -} diff --git a/pkg/providers/export_test.go b/pkg/providers/export_test.go deleted file mode 100644 index 7b7245fb..00000000 --- a/pkg/providers/export_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package providers - -import ( - "encoding/json" - "os" - "testing" - - "github.com/alecthomas/assert" - "github.com/spectralops/teller/pkg/core" -) - -func TestGenerateProvidersMetaJSON(t *testing.T) { - var providersData = []core.MetaInfo{ - { - Name: "Provider_1", - Description: "Description of Provider 1", - Authentication: "Provider 1 authentication instructions", - ConfigTemplate: "Provider 1 config template", - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true}, - }, - { - Name: "Provider_2", - Description: "Description of Provider 2", - Authentication: "Provider 2 authentication instructions", - ConfigTemplate: "Provider 2 config template", - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true}, - }, - } - - providersMetaJSON, _ := GenerateProvidersMetaJSON("1.1", providersData) - providersFileContent, _ := os.ReadFile("../../fixtures/providers-export/providers-meta.json") - - actualProvidersJSON, _ := json.Marshal(providersMetaJSON) - expectedProvidersJSON, _ := json.Marshal(string(providersFileContent)) - - assert.Equal(t, string(actualProvidersJSON), string(expectedProvidersJSON)) -} diff --git a/pkg/providers/filesystem.go b/pkg/providers/filesystem.go deleted file mode 100644 index 6f3f8837..00000000 --- a/pkg/providers/filesystem.go +++ /dev/null @@ -1,175 +0,0 @@ -package providers - -import ( - "bytes" - "errors" - "fmt" - "os" - "path" - "path/filepath" - "strings" - "unicode/utf8" - - "github.com/karrick/godirwalk" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -type FileSystem struct { - logger logging.Logger - rootDirectory string -} - -const FileSystemName = "FileSystem" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "File system", - Name: FileSystemName, - Authentication: "", - ConfigTemplate: ` - filesystem: - env_sync: - path: redis/config - env: - ETC_DSN: - path: redis/config/foobar -`, - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true, Delete: true}, - } - - RegisterProvider(metaInfo, NewFileSystem) -} - -// NewFileSystem creates new provider instance -func NewFileSystem(logger logging.Logger) (core.Provider, error) { - return &FileSystem{ - logger: logger, - rootDirectory: "", - }, nil -} - -// Put will create a new single entry -func (f *FileSystem) Put(p core.KeyPath, val string) error { - return f.writeFile(f.getFilePath(p.Path), val) -} - -// PutMapping will create a multiple entries -func (f *FileSystem) PutMapping(p core.KeyPath, m map[string]string) error { - for k, v := range m { - ap := p.SwitchPath(fmt.Sprintf("%v/%v", f.getFilePath(p.Path), k)) - err := f.Put(ap, v) - if err != nil { - return err - } - } - return nil -} - -// GetMapping returns a multiple entries -func (f *FileSystem) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - - findings := []core.EnvEntry{} - err := godirwalk.Walk(f.getFilePath(p.Path), &godirwalk.Options{ - Callback: func(osPathname string, de *godirwalk.Dirent) error { - - if !de.IsRegular() || strings.HasPrefix(de.Name(), ".") { - return nil - } - content, err := f.readFile(osPathname) - if err != nil { - f.logger.WithError(err).WithField("path", p.Path).Debug("file not found in path") - return nil - } - - if !f.IsText(content) { - return nil - } - findings = append(findings, p.FoundWithKey(strings.Replace(path.Clean(osPathname), fmt.Sprintf("%s/", p.Path), "", 1), string(content))) - - return nil - }, - Unsorted: true, - }) - - return findings, err -} - -// Get returns a single entry -func (f *FileSystem) Get(p core.KeyPath) (*core.EnvEntry, error) { - content, err := f.readFile(f.getFilePath(p.Path)) - if err != nil { - f.logger.WithError(err).WithField("path", p.Path).Debug("file not found in path") - return nil, err - } - ent := p.Found(string(content)) - return &ent, nil -} - -// Delete will delete entry -func (f *FileSystem) Delete(kp core.KeyPath) error { - deletePath := f.getFilePath(kp.Path) - fileInfo, err := os.Stat(deletePath) - if err != nil { - return err - } - // to make the delete safely, we allow deleting a single file only - if fileInfo.IsDir() { - return errors.New("delete folder is not supported") - } - - return os.Remove(deletePath) -} - -// DeleteMapping will delete the given path -func (f *FileSystem) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("provider mapping %s does not implement delete yet", FileSystemName) -} - -func (f *FileSystem) getFilePath(p string) string { - if f.rootDirectory == "" { - return p - } - return filepath.Join(f.rootDirectory, p) -} - -func (f *FileSystem) writeFile(to, val string) error { - f.logger.WithField("path", to).Info("put entry value") - dir, _ := path.Split(to) - if _, err := os.Stat(dir); os.IsNotExist(err) { - f.logger.WithField("dir", dir).Debug("create folder path") - err = os.MkdirAll(dir, os.ModePerm) - if err != nil { - return err - } - } - return os.WriteFile(to, []byte(val), 0600) //nolint -} - -func (f *FileSystem) readFile(filePath string) ([]byte, error) { - - content, err := os.ReadFile(filePath) - if err != nil { - return nil, err - } - content = bytes.TrimSuffix(content, []byte("\n")) - content = bytes.TrimSuffix(content, []byte("\r\n")) - return content, nil -} - -func (f *FileSystem) IsText(s []byte) bool { - const max = 1024 - if len(s) > max { - s = s[0:max] - } - for i, c := range string(s) { - if i+utf8.UTFMax > len(s) { - break - } - if c == 0xFFFD || c < ' ' && c != '\n' && c != '\t' && c != '\f' { - return false - } - } - return true -} diff --git a/pkg/providers/filesystem_test.go b/pkg/providers/filesystem_test.go deleted file mode 100644 index ba46ee46..00000000 --- a/pkg/providers/filesystem_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package providers - -import ( - "os" - "path/filepath" - "testing" - - "github.com/alecthomas/assert" - "github.com/spectralops/teller/pkg/core" -) - -func createMockDirectoryStructure(f *FileSystem) error { - createFileSystemData := []struct { - path string - fileName string - value string - }{ - {"settings/prod", "billing-svc", "shazam"}, - {"settings/prod/billing/all", "secret-a", "mailman"}, - {"settings/prod/billing/all", "secret-b", "shazam"}, - {"settings/prod/billing/all/folder", "secret-c", "shazam-1"}, - } - - for _, filePath := range createFileSystemData { - err := os.MkdirAll(filepath.Join(f.rootDirectory, filePath.path), os.ModePerm) - if err != nil { - return err - } - err = os.WriteFile(filepath.Join(f.rootDirectory, filePath.path, filePath.fileName), []byte(filePath.value), 0644) - if err != nil { - return err - } - - } - return nil -} - -func TestFileSystem(t *testing.T) { - - tempFolder, err := os.MkdirTemp(os.TempDir(), "teller-filesystem") - assert.Nil(t, err) - defer os.RemoveAll(tempFolder) - - f := &FileSystem{ - logger: GetTestLogger(), - rootDirectory: tempFolder, - } - - err = createMockDirectoryStructure(f) - assert.NoError(t, err) - - AssertProvider(t, f, false) - ents, err := f.GetMapping(core.KeyPath{Path: "settings/prod/billing/all", Decrypt: true}) - assert.Nil(t, err) - assert.Equal(t, len(ents), 3) -} - -func TestFileSystemSetEntry(t *testing.T) { - - tempFolder, err := os.MkdirTemp(os.TempDir(), "teller-filesystem") - assert.Nil(t, err) - defer os.RemoveAll(tempFolder) - - f := &FileSystem{ - logger: GetTestLogger(), - rootDirectory: tempFolder, - } - err = createMockDirectoryStructure(f) - assert.NoError(t, err) - - destFile := "create/newfolder/foo" - _, err = f.Get(core.KeyPath{Path: destFile, Decrypt: true}) - assert.NotEmpty(t, err) - - err = f.Put(core.KeyPath{Path: destFile}, "new-val") - assert.Nil(t, err) - - results, err := f.Get(core.KeyPath{Path: destFile, Decrypt: true}) - assert.Nil(t, err) - assert.NotEmpty(t, results) - -} - -func TestFileSystemDeleteEntry(t *testing.T) { - - tempFolder, err := os.MkdirTemp(os.TempDir(), "teller-filesystem") - assert.Nil(t, err) - defer os.RemoveAll(tempFolder) - - f := &FileSystem{ - logger: GetTestLogger(), - rootDirectory: tempFolder, - } - err = createMockDirectoryStructure(f) - assert.NoError(t, err) - - destFile := "settings/prod/billing-svc" - _, err = f.Get(core.KeyPath{Path: destFile, Decrypt: true}) - assert.Nil(t, err) - - err = f.Delete(core.KeyPath{Path: destFile, Decrypt: true}) - assert.Nil(t, err) - - _, err = f.Get(core.KeyPath{Path: destFile, Decrypt: true}) - assert.NotNil(t, err) - -} diff --git a/pkg/providers/github.go b/pkg/providers/github.go deleted file mode 100644 index 32dd2e99..00000000 --- a/pkg/providers/github.go +++ /dev/null @@ -1,217 +0,0 @@ -package providers - -import ( - "context" - crypto_rand "crypto/rand" - "encoding/base64" - "errors" - "fmt" - "os" - "strings" - - "github.com/google/go-github/v43/github" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "golang.org/x/crypto/nacl/box" - "golang.org/x/oauth2" -) - -const ( - gitHubSplitPathCount = 2 -) - -// GitHubActionClient describe the GitHub action client -type GitHubActionClient interface { - GetRepoPublicKey(ctx context.Context, owner, repo string) (*github.PublicKey, *github.Response, error) - CreateOrUpdateRepoSecret(ctx context.Context, owner, repo string, eSecret *github.EncryptedSecret) (*github.Response, error) - DeleteRepoSecret(ctx context.Context, owner, repo, name string) (*github.Response, error) - ListRepoSecrets(ctx context.Context, owner, repo string, opts *github.ListOptions) (*github.Secrets, *github.Response, error) -} - -type GitHub struct { - clientActions GitHubActionClient - logger logging.Logger -} - -// NewGitHub create new GitHub provider -const GithubName = "GitHub" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Github", - Authentication: "Requires `GITHUB_AUTH_TOKEN`", - Name: GithubName, - ConfigTemplate: ` - # Configure via environment variables for integration: - # GITHUB_AUTH_TOKEN: GitHub token - - github: - env_sync: - path: owner/github-repo - env: - script-value: - path: owner/github-repo -`, - Ops: core.OpMatrix{Put: true, PutMapping: true, Delete: true, DeleteMapping: true}, - } - - RegisterProvider(metaInfo, NewGitHub) -} - -func NewGitHub(logger logging.Logger) (core.Provider, error) { - token := os.Getenv("GITHUB_AUTH_TOKEN") - if token == "" { - return nil, errors.New("missing `GITHUB_AUTH_TOKEN`") - } - - ts := oauth2.StaticTokenSource( - &oauth2.Token{AccessToken: token}, - ) - tc := oauth2.NewClient(context.TODO(), ts) - client := github.NewClient(tc) - - return &GitHub{clientActions: client.Actions, logger: logger}, nil -} - -func (g *GitHub) Put(p core.KeyPath, val string) error { - - owner, repoName, err := g.parsePathToOwnerAndRepo(p) - if err != nil { - return err - } - - publicKey, _, err := g.getRepoPublicKey(owner, repoName) - if err != nil { - return err - } - - encryptedSecret, err := g.encryptSecretWithPublicKey(publicKey, p.Env, val) - if err != nil { - return err - } - - _, err = g.createOrUpdateRepoSecret(context.TODO(), owner, repoName, encryptedSecret) - - return err -} - -func (g *GitHub) PutMapping(p core.KeyPath, m map[string]string) error { - for k, v := range m { - ap := p.WithEnv(k) - err := g.Put(ap, v) - if err != nil { - return err - } - } - return nil -} - -func (g *GitHub) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - return nil, fmt.Errorf("does not supported by the %s provider", GithubName) -} - -func (g *GitHub) Get(p core.KeyPath) (*core.EnvEntry, error) { - return nil, fmt.Errorf("does not supported by the %s provider", GithubName) -} - -func (g *GitHub) Delete(p core.KeyPath) error { - owner, repoName, err := g.parsePathToOwnerAndRepo(p) - if err != nil { - return err - } - - _, err = g.deleteRepoSecret(context.TODO(), owner, repoName, p.Env) - return err -} - -func (g *GitHub) DeleteMapping(p core.KeyPath) error { - - owner, repoName, err := g.parsePathToOwnerAndRepo(p) - if err != nil { - return err - } - - opt := github.ListOptions{PerPage: 100} - g.logger.WithFields(map[string]interface{}{ - "owner": owner, - "repository_name": repoName, - }).Debug("get repo secrets") - secrets, _, err := g.clientActions.ListRepoSecrets(context.TODO(), owner, repoName, &opt) - if err != nil { - return err - } - - for _, secret := range secrets.Secrets { - err := g.Delete(p.WithEnv(secret.Name)) - if err != nil { - return err - } - - } - - return nil -} - -// parsePathToOwnerAndRepo parse the key path to the owner and repo name -func (g *GitHub) parsePathToOwnerAndRepo(p core.KeyPath) (string, string, error) { //nolint - - splitData := strings.SplitN(p.Path, "/", 2) //nolint - if len(splitData) != gitHubSplitPathCount { - return "", "", fmt.Errorf("invalid %s path, expected owner/repo got: %s", GithubName, p.Path) - } - return splitData[0], splitData[1], nil -} - -// GetRepoPublicKey gets a public key that should be used for secret encryption. -func (g *GitHub) getRepoPublicKey(owner, repo string) (*github.PublicKey, *github.Response, error) { - return g.clientActions.GetRepoPublicKey(context.TODO(), owner, repo) - -} - -// CreateOrUpdateRepoSecret creates or updates a repository secret with an encrypted value. -func (g *GitHub) createOrUpdateRepoSecret(ctx context.Context, owner, repo string, eSecret *github.EncryptedSecret) (*github.Response, error) { - g.logger.WithFields(map[string]interface{}{ - "owner": owner, - "repository_name": repo, - "name": eSecret.Name, - }).Debug("put repo secret") - return g.clientActions.CreateOrUpdateRepoSecret(ctx, owner, repo, eSecret) -} - -// DeleteRepoSecret deletes a secret in a repository using the secret name. -func (g *GitHub) deleteRepoSecret(ctx context.Context, owner, repo, name string) (*github.Response, error) { - g.logger.WithFields(map[string]interface{}{ - "owner": owner, - "repository_name": repo, - "name": name, - }).Debug("delete repo secret") - return g.clientActions.DeleteRepoSecret(ctx, owner, repo, name) -} - -// encryptSecretWithPublicKey secret secret name and value by the given GitHub public key -func (g *GitHub) encryptSecretWithPublicKey(publicKey *github.PublicKey, secretName, secretValue string) (*github.EncryptedSecret, error) { - - decodedPublicKey, err := base64.StdEncoding.DecodeString(publicKey.GetKey()) - if err != nil { - return nil, fmt.Errorf("base64.StdEncoding.DecodeString was unable to decode public key: %v", err) - } - - var boxKey [32]byte - copy(boxKey[:], decodedPublicKey) - secretBytes := []byte(secretValue) - encryptedBytes, err := box.SealAnonymous([]byte{}, secretBytes, &boxKey, crypto_rand.Reader) - if err != nil { - return nil, fmt.Errorf("box.SealAnonymous failed with error %w", err) - } - - encryptedString := base64.StdEncoding.EncodeToString(encryptedBytes) - - keyID := publicKey.GetKeyID() - encryptedSecret := &github.EncryptedSecret{ - Name: secretName, - KeyID: keyID, - EncryptedValue: encryptedString, - } - return encryptedSecret, nil -} diff --git a/pkg/providers/github_test.go b/pkg/providers/github_test.go deleted file mode 100644 index 1ac5375b..00000000 --- a/pkg/providers/github_test.go +++ /dev/null @@ -1,167 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - "github.com/google/go-github/v43/github" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestGitHubPut(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockGitHubActionClient(ctrl) - - keyID := "1234" - key := "2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvv1234" - publicKey := github.PublicKey{ - KeyID: &keyID, - Key: &key, - } - - client.EXPECT().GetRepoPublicKey(gomock.Any(), "owner-name", "error").Return(&publicKey, nil, errors.New("some error")).AnyTimes() - client.EXPECT().GetRepoPublicKey(gomock.Any(), "owner-name", "repo-name").Return(&publicKey, nil, nil).AnyTimes() - client.EXPECT().CreateOrUpdateRepoSecret(gomock.Any(), "owner-name", "repo-name", gomock.Any()).Return(nil, nil).AnyTimes() - - client.EXPECT().GetRepoPublicKey(gomock.Any(), "owner-name", "create-error").Return(&publicKey, nil, nil).AnyTimes() - client.EXPECT().CreateOrUpdateRepoSecret(gomock.Any(), "owner-name", "create-error", gomock.Any()).Return(nil, errors.New("some error")).AnyTimes() - - c := GitHub{ - clientActions: client, - logger: GetTestLogger(), - } - - assert.NotNil(t, c.Put(core.KeyPath{Path: "owner-name", Field: "MG_KEY"}, "put-secret"), "owner or repo name should be invalid") - assert.NotNil(t, c.Put(core.KeyPath{Path: "owner-name/error", Field: "MG_KEY"}, "put-secret"), "repo public key should return an error") - assert.Nil(t, c.Put(core.KeyPath{Path: "owner-name/repo-name", Field: "MG_KEY"}, "put-secret"), "can put a new secret") - assert.NotNil(t, c.Put(core.KeyPath{Path: "owner-name/create-error", Field: "MG_KEY"}, "put-secret"), "create or update secret should be fails") - -} - -func TestGitHubPutMapping(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockGitHubActionClient(ctrl) - - keyID := "1234" - key := "2Sg8iYjAxxmI2LvUXpJjkYrMxURPc8r+dB7TJyvv1234" - publicKey := github.PublicKey{ - KeyID: &keyID, - Key: &key, - } - - client.EXPECT().GetRepoPublicKey(gomock.Any(), "owner-name", "error").Return(&publicKey, nil, errors.New("some error")).AnyTimes() - client.EXPECT().GetRepoPublicKey(gomock.Any(), "owner-name", "repo-name").Return(&publicKey, nil, nil).AnyTimes() - client.EXPECT().CreateOrUpdateRepoSecret(gomock.Any(), "owner-name", "repo-name", gomock.Any()).Return(nil, nil).AnyTimes() - - client.EXPECT().GetRepoPublicKey(gomock.Any(), "owner-name", "create-error").Return(&publicKey, nil, nil).AnyTimes() - client.EXPECT().CreateOrUpdateRepoSecret(gomock.Any(), "owner-name", "create-error", gomock.Any()).Return(nil, errors.New("some error")).AnyTimes() - - c := GitHub{ - clientActions: client, - logger: GetTestLogger(), - } - - data := map[string]string{ - "key-1": "value-1", - } - assert.NotNil(t, c.PutMapping(core.KeyPath{Path: "owner-name", Field: "MG_KEY"}, data), "owner or repo name should be invalid") - assert.NotNil(t, c.PutMapping(core.KeyPath{Path: "owner-name/error", Field: "MG_KEY"}, data), "repo public key should return an error") - assert.Nil(t, c.PutMapping(core.KeyPath{Path: "owner-name/repo-name", Field: "MG_KEY"}, data), "can put a new secret") - assert.NotNil(t, c.PutMapping(core.KeyPath{Path: "owner-name/create-error", Field: "MG_KEY"}, data), "create or update secret should be fails") - -} - -func TestGitHubDelete(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockGitHubActionClient(ctrl) - - client.EXPECT().DeleteRepoSecret(gomock.Any(), "owner-name", "repo-name", "MG_KEY").Return(nil, nil).AnyTimes() - client.EXPECT().DeleteRepoSecret(gomock.Any(), "owner-name", "repo-name", "MG_KEY_ERROR").Return(nil, errors.New("some error")).AnyTimes() - - c := GitHub{ - clientActions: client, - logger: GetTestLogger(), - } - - assert.NotNil(t, c.Delete(core.KeyPath{Path: "owner-name", Field: "MG_KEY"}), "owner or repo name should be invalid") - assert.Nil(t, c.Delete(core.KeyPath{Path: "owner-name/repo-name", Env: "MG_KEY"}), "delete action should pass") - assert.NotNil(t, c.Delete(core.KeyPath{Path: "owner-name/repo-name", Env: "MG_KEY_ERROR"}), "delete action should return an error") - -} - -func TestGitHubDeleteMaping(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockGitHubActionClient(ctrl) - - secretsResponse := github.Secrets{ - TotalCount: 2, - Secrets: []*github.Secret{ - {Name: "MG_KEY-1"}, - {Name: "MG_KEY-2"}, - }, - } - client.EXPECT().ListRepoSecrets(gomock.Any(), "owner-name", "repo-name", gomock.Any()).Return(&secretsResponse, nil, nil).AnyTimes() - client.EXPECT().DeleteRepoSecret(gomock.Any(), "owner-name", "repo-name", "MG_KEY-1").Return(nil, nil).AnyTimes() - client.EXPECT().DeleteRepoSecret(gomock.Any(), "owner-name", "repo-name", "MG_KEY-2").Return(nil, nil).AnyTimes() - - c := GitHub{ - clientActions: client, - logger: GetTestLogger(), - } - - assert.Nil(t, c.DeleteMapping(core.KeyPath{Path: "owner-name/repo-name", Env: "MG_KEY"}), "delete action should pass") - -} - -func TestGitHubDeleteMapingWithError(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockGitHubActionClient(ctrl) - - secretsResponse := github.Secrets{ - TotalCount: 2, - Secrets: []*github.Secret{ - {Name: "MG_KEY-1"}, - {Name: "MG_KEY-2"}, - }, - } - client.EXPECT().ListRepoSecrets(gomock.Any(), "owner-name", "repo-name", gomock.Any()).Return(&secretsResponse, nil, nil).AnyTimes() - client.EXPECT().DeleteRepoSecret(gomock.Any(), "owner-name", "repo-name", "MG_KEY-1").Return(nil, nil).AnyTimes() - client.EXPECT().DeleteRepoSecret(gomock.Any(), "owner-name", "repo-name", "MG_KEY-2").Return(nil, errors.New("some error")).AnyTimes() - - c := GitHub{ - clientActions: client, - logger: GetTestLogger(), - } - - assert.NotNil(t, c.DeleteMapping(core.KeyPath{Path: "owner-name/repo-name", Env: "MG_KEY"}), "delete action should pass") - -} - -func TestParsePathToOwnerAndRepo(t *testing.T) { - - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockGitHubActionClient(ctrl) - - c := GitHub{ - clientActions: client, - logger: GetTestLogger(), - } - - owner, repo, err := c.parsePathToOwnerAndRepo(core.KeyPath{Path: "owner-name/repo-name", Env: "MG_KEY"}) - assert.Equal(t, owner, "owner-name", "unexpected owner name from path key") - assert.Equal(t, repo, "repo-name", "unexpected repo name from path key") - assert.Nil(t, err) - - _, _, err = c.parsePathToOwnerAndRepo(core.KeyPath{Path: "owner-name", Env: "MG_KEY"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/google_secretmanager.go b/pkg/providers/google_secretmanager.go deleted file mode 100644 index 352a8ab4..00000000 --- a/pkg/providers/google_secretmanager.go +++ /dev/null @@ -1,181 +0,0 @@ -package providers - -import ( - "context" - "encoding/json" - "fmt" - "regexp" - "sort" - "strings" - - secretmanager "cloud.google.com/go/secretmanager/apiv1" - secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - - "github.com/googleapis/gax-go/v2" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "google.golang.org/api/iterator" -) - -type GoogleSMClient interface { - AccessSecretVersion(ctx context.Context, req *secretmanagerpb.AccessSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error) - DestroySecretVersion(ctx context.Context, req *secretmanagerpb.DestroySecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) - ListSecrets(ctx context.Context, in *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) *secretmanager.SecretIterator - AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) -} -type GoogleSecretManager struct { - client GoogleSMClient - logger logging.Logger -} - -const GoogleSecretManagerName = "google_secretmanager" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Google Secret Manager", - Name: GoogleSecretManagerName, - Authentication: "You should populate `GOOGLE_APPLICATION_CREDENTIALS=account.json` in your environment to your relevant `account.json` that you get from Google.", - ConfigTemplate: ` - # GOOGLE_APPLICATION_CREDENTIALS=foobar.json - # https://cloud.google.com/secret-manager/docs/reference/libraries#setting_up_authentication - google_secretmanager: - env: - FOO_GOOG: - # need to supply the relevant version (versions/1) - path: projects/123/secrets/FOO_GOOG/versions/1 -`, - Ops: core.OpMatrix{Get: true, Put: true, Delete: true}, - } - - RegisterProvider(metaInfo, NewGoogleSecretManager) -} - -func NewGoogleSecretManager(logger logging.Logger) (core.Provider, error) { - client, err := secretmanager.NewClient(context.TODO()) - if err != nil { - return nil, err - } - return &GoogleSecretManager{client: client, logger: logger}, nil -} - -func (a *GoogleSecretManager) Put(p core.KeyPath, val string) error { - reg := regexp.MustCompile(`(?i)/versions/\d+$`) - res := reg.ReplaceAllString(p.Path, "") - return a.addSecret(res, val) -} -func (a *GoogleSecretManager) PutMapping(p core.KeyPath, m map[string]string) error { - for k, v := range m { - path := fmt.Sprintf("%v/secrets/%v", p.Path, k) - err := a.addSecret(path, v) - if err != nil { - return err - } - } - - return nil -} - -func (a *GoogleSecretManager) GetMapping(kp core.KeyPath) ([]core.EnvEntry, error) { - secrets, err := a.getSecrets(kp.Path) - if err != nil { - return nil, err - } - - entries := []core.EnvEntry{} - - for _, val := range secrets { - path := fmt.Sprintf("%s/%s", val, "versions/latest") - secretVal, err := a.getSecret(path) - if err != nil { - return nil, err - } - key := strings.TrimPrefix(val, kp.Path) - entries = append(entries, kp.FoundWithKey(key, secretVal)) - } - sort.Sort(core.EntriesByKey(entries)) - - return entries, nil -} - -func (a *GoogleSecretManager) Get(p core.KeyPath) (*core.EnvEntry, error) { - secret, err := a.getSecret(p.Path) - if err != nil { - return nil, err - } - - ent := p.Found(secret) - - if ent.Field != "" { - var valueSecrets map[string]interface{} - err = json.Unmarshal([]byte(ent.Value), &valueSecrets) - if err != nil { - return nil, err - } - fieldValue := valueSecrets[ent.Field].(string) - ent.Value = fieldValue - } - return &ent, nil -} - -func (a *GoogleSecretManager) Delete(kp core.KeyPath) error { - return a.deleteSecret(kp.Path) -} - -func (a *GoogleSecretManager) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", GoogleSecretManagerName) -} - -func (a *GoogleSecretManager) getSecret(path string) (string, error) { - r := secretmanagerpb.AccessSecretVersionRequest{ - Name: path, - } - a.logger.WithField("path", r.Name).Debug("get secret") - - secret, err := a.client.AccessSecretVersion(context.TODO(), &r) - if err != nil { - return "", err - } - return string(secret.Payload.Data), nil -} - -func (a *GoogleSecretManager) deleteSecret(path string) error { - req := &secretmanagerpb.DestroySecretVersionRequest{ - Name: path, - } - _, err := a.client.DestroySecretVersion(context.TODO(), req) - return err -} - -func (a *GoogleSecretManager) addSecret(path, val string) error { - req := &secretmanagerpb.AddSecretVersionRequest{ - Parent: path, - Payload: &secretmanagerpb.SecretPayload{ - Data: []byte(val), - }, - } - - _, err := a.client.AddSecretVersion(context.TODO(), req) - return err -} - -func (a *GoogleSecretManager) getSecrets(path string) ([]string, error) { - req := &secretmanagerpb.ListSecretsRequest{ - Parent: path, - } - entries := []string{} - - it := a.client.ListSecrets(context.TODO(), req) - for { - resp, err := it.Next() - if err == iterator.Done { - break - } - - if err != nil { - return nil, err - } - entries = append(entries, resp.Name) - } - return entries, nil -} diff --git a/pkg/providers/google_secretmanager_test.go b/pkg/providers/google_secretmanager_test.go deleted file mode 100644 index bacda83a..00000000 --- a/pkg/providers/google_secretmanager_test.go +++ /dev/null @@ -1,124 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - secretmanager "cloud.google.com/go/secretmanager/apiv1" - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestGoogleSM(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockGoogleSMClient(ctrl) - path := "settings/prod/billing-svc" - sec := &secretmanagerpb.SecretPayload{ - Data: []byte("shazam"), - } - out := &secretmanagerpb.AccessSecretVersionResponse{ - Payload: sec, - } - outDelete := &secretmanagerpb.SecretVersion{ - Name: string(sec.Data), - } - outAdd := &secretmanagerpb.SecretVersion{ - Name: string(sec.Data), - } - outList := &secretmanager.SecretIterator{ - Response: string(sec.Data), - } - in := secretmanagerpb.AccessSecretVersionRequest{ - Name: path, - } - inDelete := secretmanagerpb.DestroySecretVersionRequest{ - Name: path, - } - inList := secretmanagerpb.ListSecretsRequest{ - Parent: path, - } - inAdd := secretmanagerpb.AddSecretVersionRequest{ - Parent: path, - Payload: &secretmanagerpb.SecretPayload{ - Data: []byte("some value"), - }, - } - client.EXPECT().AccessSecretVersion(gomock.Any(), gomock.Eq(&in)).Return(out, nil).AnyTimes() - client.EXPECT().DestroySecretVersion(gomock.Any(), gomock.Eq(&inDelete)).Return(outDelete, nil).AnyTimes() - client.EXPECT().ListSecrets(gomock.Any(), gomock.Eq(&inList)).Return(outList).AnyTimes() - client.EXPECT().AddSecretVersion(gomock.Any(), gomock.Eq(&inAdd)).Return(outAdd, nil).AnyTimes() - s := GoogleSecretManager{ - client: client, - logger: GetTestLogger(), - } - ConfigurableAssertProvider(t, &s, false, false) -} - -func TestGoogleSMWithField(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockGoogleSMClient(ctrl) - path := "settings/prod/billing-svc" - - data := `{"MG_KEY":"shazam", "SMTP_PASS":"mailman"}` - sec := &secretmanagerpb.SecretPayload{ - Data: []byte(data), - } - out := &secretmanagerpb.AccessSecretVersionResponse{ - Payload: sec, - } - outDelete := &secretmanagerpb.SecretVersion{ - Name: string(sec.Data), - } - outAdd := &secretmanagerpb.SecretVersion{ - Name: string(sec.Data), - } - outList := &secretmanager.SecretIterator{ - Response: string(sec.Data), - } - in := secretmanagerpb.AccessSecretVersionRequest{ - Name: path, - } - inDelete := secretmanagerpb.DestroySecretVersionRequest{ - Name: path, - } - inList := secretmanagerpb.ListSecretsRequest{ - Parent: path, - } - inAdd := secretmanagerpb.AddSecretVersionRequest{ - Parent: path, - Payload: &secretmanagerpb.SecretPayload{ - Data: []byte("some value"), - }, - } - client.EXPECT().AccessSecretVersion(gomock.Any(), gomock.Eq(&in)).Return(out, nil).AnyTimes() - client.EXPECT().DestroySecretVersion(gomock.Any(), gomock.Eq(&inDelete)).Return(outDelete, nil).AnyTimes() - client.EXPECT().ListSecrets(gomock.Any(), gomock.Eq(&inList)).Return(outList).AnyTimes() - client.EXPECT().AddSecretVersion(gomock.Any(), gomock.Eq(&inAdd)).Return(outAdd, nil).AnyTimes() - s := GoogleSecretManager{ - client: client, - logger: GetTestLogger(), - } - ConfigurableAssertProvider(t, &s, false, true) -} - -func TestGoogleSMFailures(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockGoogleSMClient(ctrl) - client.EXPECT().AccessSecretVersion(gomock.Any(), gomock.Any()).Return(nil, errors.New("error")).AnyTimes() - s := GoogleSecretManager{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/gopass.go b/pkg/providers/gopass.go deleted file mode 100644 index 4ebc3eb6..00000000 --- a/pkg/providers/gopass.go +++ /dev/null @@ -1,141 +0,0 @@ -package providers - -import ( - "context" - "fmt" - "sort" - "strings" - - "github.com/gopasspw/gopass/pkg/gopass" - "github.com/gopasspw/gopass/pkg/gopass/api" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/utils" -) - -type GopassClient interface { - List(ctx context.Context) ([]string, error) - Get(ctx context.Context, name, revision string) (gopass.Secret, error) - Set(ctx context.Context, name string, sec gopass.Byter) error -} - -type Gopass struct { - client GopassClient - logger logging.Logger -} - -const GoPassName = "gopass" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Gopass", - Name: GoPassName, - Authentication: "Configuration is environment based, as defined by client standard. See variables [here](https://github.com/gopasspw/gopass/blob/master/docs/config.md).", - ConfigTemplate: ` - # Override default configuration: https://github.com/gopasspw/gopass/blob/master/docs/config.md - gopass: - env_sync: - path: foo - env: - ETC_DSN: - path: foo/bar -`, - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true}, - } - - RegisterProvider(metaInfo, NewGopass) -} -func NewGopass(logger logging.Logger) (core.Provider, error) { - ctx := context.Background() - gp, err := api.New(ctx) - if err != nil { - return nil, err - } - return &Gopass{client: gp, logger: logger}, nil -} - -func (g *Gopass) Put(p core.KeyPath, val string) error { - secret, err := g.getSecret(p.Path) - if err != nil { - return fmt.Errorf("%v cannot get value: %v", GoPassName, err) - } - - secret.SetPassword(val) - g.logger.WithField("path", p.Path).Debug("set secret") - return g.client.Set(context.TODO(), p.Path, secret) -} - -func (g *Gopass) PutMapping(p core.KeyPath, m map[string]string) error { - for k, v := range m { - ap := p.SwitchPath(fmt.Sprintf("%v/%v", p.Path, k)) - secret, err := g.getSecret(ap.Path) - if err != nil { - return fmt.Errorf("%v cannot get value: %v", GoPassName, err) - } - - secret.SetPassword(v) - g.logger.WithField("path", ap.Path).Debug("set secret") - err = g.client.Set(context.TODO(), ap.Path, secret) - if err != nil { - return fmt.Errorf("%v cannot update value: %v", GoPassName, err) - } - - } - return nil -} - -func (g *Gopass) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - g.logger.Debug("get all secrets") - secretsPath, err := g.client.List(context.TODO()) - if err != nil { - return nil, err - } - entries := []core.EnvEntry{} - for _, secretPath := range secretsPath { - if strings.HasPrefix(secretPath, p.Path) { - secret, err := g.getSecret(secretPath) - if err != nil { - return nil, err - } - seg := utils.LastSegment(secretPath) - entries = append(entries, p.FoundWithKey(seg, secret.Password())) - } - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -func (g *Gopass) Get(p core.KeyPath) (*core.EnvEntry, error) { - - secret, err := g.getSecret(p.Path) - if err != nil { - return nil, fmt.Errorf("%v cannot get value: %v", GoPassName, err) - } - - if secret == nil { - g.logger.WithField("path", p.Path).Debug("secret is empty") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(secret.Password()) - return &ent, nil -} - -func (g *Gopass) Delete(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", GoPassName) -} - -func (g *Gopass) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", GoPassName) -} - -func (g *Gopass) getSecret(path string) (gopass.Secret, error) { - g.logger.WithField("path", path).Debug("get secret") - secret, err := g.client.Get(context.TODO(), path, "") - if err != nil { - return nil, err - } - return secret, nil -} diff --git a/pkg/providers/gopass_test.go b/pkg/providers/gopass_test.go deleted file mode 100644 index 4ade102b..00000000 --- a/pkg/providers/gopass_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package providers - -import ( - "context" - "errors" - "testing" - - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - "github.com/gopasspw/gopass/pkg/gopass/secrets/secparse" - - // "github.com/gopasspw/gopass/pkg/gopass/secrets/secparse" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestGopass(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockGopassClient(ctrl) - path := "settings/prod/billing-svc" - - secretShazamVal := `shazam -settings / prod / billing-svc -` - secretMailmanVal := `mailman -settings / prod / billing-svc -` - secretShazam, _ := secparse.Parse([]byte(secretShazamVal)) - secretMailman, _ := secparse.Parse([]byte(secretMailmanVal)) - outlist := []string{ - "settings/prod/billing-svc/all/1", - "settings/prod/billing-svc/all/2", - } - - client.EXPECT().Get(context.TODO(), gomock.Eq(path), gomock.Any()).Return(secretShazam, nil).AnyTimes() - client.EXPECT().Get(context.TODO(), gomock.Eq("settings/prod/billing-svc/all/1"), gomock.Any()).Return(secretShazam, nil).AnyTimes() - client.EXPECT().Get(context.TODO(), gomock.Eq("settings/prod/billing-svc/all/2"), gomock.Any()).Return(secretMailman, nil).AnyTimes() - client.EXPECT().List(context.TODO()).Return(outlist, nil).AnyTimes() - s := Gopass{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) -} - -func TestGopassFailures(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockGopassClient(ctrl) - client.EXPECT().Get(context.TODO(), gomock.Any(), gomock.Any()).Return(nil, errors.New("error")).AnyTimes() - s := Gopass{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - client.EXPECT().List(context.TODO()).Return([]string{"a"}, errors.New("error")).AnyTimes() - assert.NotNil(t, err) - _, err = s.GetMapping(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/hashicorp_vault.go b/pkg/providers/hashicorp_vault.go deleted file mode 100644 index 2e6ef499..00000000 --- a/pkg/providers/hashicorp_vault.go +++ /dev/null @@ -1,162 +0,0 @@ -package providers - -import ( - "fmt" - "sort" - - "github.com/hashicorp/vault/api" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -type HashicorpClient interface { - Read(path string) (*api.Secret, error) - Write(path string, data map[string]interface{}) (*api.Secret, error) -} -type HashicorpVault struct { - client HashicorpClient - logger logging.Logger -} - -const HashicorpVaultName = "hashicorp_vault" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Hashicorp Vault", - Name: HashicorpVaultName, - Authentication: "Configuration is environment based, as defined by client standard. See variables [here](https://github.com/hashicorp/vault/blob/api/v1.0.4/api/client.go#L28).", - ConfigTemplate: ` - # configure only from environment - # https://github.com/hashicorp/vault/blob/api/v1.0.4/api/client.go#L28 - # this vars should not go through to the executing cmd - hashicorp_vault: - env_sync: - path: secret/data/{{"{{stage}}"}}/billing/web/env - env: - SMTP_PASS: - path: secret/data/{{"{{stage}}"}}/wordpress - field: smtp -`, - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: true, PutMapping: true}, - } - - RegisterProvider(metaInfo, NewHashicorpVault) -} - -func NewHashicorpVault(logger logging.Logger) (core.Provider, error) { - conf := api.DefaultConfig() - err := conf.ReadEnvironment() - if err != nil { - return nil, err - } - - client, err := api.NewClient(conf) - - if err != nil { - return nil, err - } - - return &HashicorpVault{client: client.Logical(), logger: logger}, nil -} - -func (h *HashicorpVault) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - secret, err := h.getSecret(p) - if err != nil { - return nil, err - } - - // vault returns a secret kv struct as either data{} or data.data{} depending on engine - var k map[string]interface{} - if val, ok := secret.Data["data"]; ok { - k = val.(map[string]interface{}) - } else { - k = secret.Data - } - - entries := []core.EnvEntry{} - for k, v := range k { - entries = append(entries, p.FoundWithKey(k, v.(string))) - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -func (h *HashicorpVault) Get(p core.KeyPath) (*core.EnvEntry, error) { - secret, err := h.getSecret(p) - if err != nil { - return nil, err - } - - if secret == nil { - h.logger.WithField("path", p.Path).Debug("secret is empty") - ent := p.Missing() - return &ent, nil - } - - // vault returns a secret kv struct as either data{} or data.data{} depending on engine - var data map[string]interface{} - if val, ok := secret.Data["data"]; ok { - data = val.(map[string]interface{}) - } else { - data = secret.Data - } - - k := data[p.Env] - if p.Field != "" { - h.logger.WithField("path", p.Path).Debug("`env` attribute not found in returned data. take `field` attribute") - k = data[p.Field] - } - - if k == nil { - h.logger.WithField("path", p.Path).Debug("key not found") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(k.(string)) - return &ent, nil -} - -func (h *HashicorpVault) Put(p core.KeyPath, val string) error { - k := p.Env - if p.Field != "" { - h.logger.WithField("path", p.Path).Debug("`env` attribute not configured. take `field` attribute") - k = p.Field - } - m := map[string]string{k: val} - h.logger.WithField("path", p.Path).Debug("write secret") - _, err := h.client.Write(p.Path, map[string]interface{}{"data": m}) - return err -} -func (h *HashicorpVault) PutMapping(p core.KeyPath, m map[string]string) error { - h.logger.WithField("path", p.Path).Debug("write secret") - _, err := h.client.Write(p.Path, map[string]interface{}{"data": m}) - return err -} - -func (h *HashicorpVault) Delete(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", HashicorpVaultName) -} - -func (h *HashicorpVault) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", HashicorpVaultName) -} - -func (h *HashicorpVault) getSecret(kp core.KeyPath) (*api.Secret, error) { - h.logger.WithField("path", kp.Path).Debug("read secret") - secret, err := h.client.Read(kp.Path) - if err != nil { - return nil, err - } - - if secret == nil || len(secret.Data) == 0 { - return nil, fmt.Errorf("secret not found in path: %s", kp.Path) - } - - if len(secret.Warnings) > 0 { - fmt.Println(secret.Warnings) - } - - return secret, nil -} diff --git a/pkg/providers/hashicorp_vault_test.go b/pkg/providers/hashicorp_vault_test.go deleted file mode 100644 index 016d8068..00000000 --- a/pkg/providers/hashicorp_vault_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - - "github.com/hashicorp/vault/api" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestHashicorpVault(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockHashicorpClient(ctrl) - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - - tests := map[string]struct { - out api.Secret - }{ - "data.data": { - out: api.Secret{ - Data: map[string]interface{}{ - "data": map[string]interface{}{ - "MG_KEY": "shazam", - "SMTP_PASS": "mailman", - }, - }, - }, - }, - "data": { - out: api.Secret{ - Data: map[string]interface{}{ - "MG_KEY": "shazam", - "SMTP_PASS": "mailman", - }, - }, - }, - } - - for name, tc := range tests { - t.Run(name, func(t *testing.T) { - client.EXPECT().Read(gomock.Eq(path)).Return(&tc.out, nil).AnyTimes() - client.EXPECT().Read(gomock.Eq(pathmap)).Return(&tc.out, nil).AnyTimes() - s := HashicorpVault{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) - }) - } -} - -func TestHashicorpVaultFailures(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockHashicorpClient(ctrl) - client.EXPECT().Read(gomock.Any()).Return(nil, errors.New("error")).AnyTimes() - s := HashicorpVault{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/helpers_test.go b/pkg/providers/helpers_test.go deleted file mode 100644 index c52e9d87..00000000 --- a/pkg/providers/helpers_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package providers - -import ( - "testing" - - "github.com/alecthomas/assert" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -func AssertProvider(t *testing.T, s core.Provider, sync bool) { - p := core.NewPopulate(map[string]string{"stage": "prod"}) - - kpmap := p.KeyPath(core.KeyPath{Field: "MG_KEY", Path: "settings/{{stage}}/billing-svc/all", Decrypt: true}) - kp := p.KeyPath(core.KeyPath{Field: "MG_KEY", Path: "settings/{{stage}}/billing-svc", Decrypt: true}) - kpenv := p.KeyPath(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc", Decrypt: true}) - - ent, err := s.Get(kp) - assert.Nil(t, err) - assert.Equal(t, ent.Value, "shazam") - - ent, err = s.Get(kpenv) - assert.Nil(t, err) - assert.Equal(t, ent.Value, "shazam") - - if sync { - ents, err := s.GetMapping(kpmap) - assert.Nil(t, err) - assert.Equal(t, len(ents), 2) - assert.Equal(t, ents[0].Value, "mailman") - assert.Equal(t, ents[1].Value, "shazam") - } -} - -func AssertProviderPlainText(t *testing.T, s core.Provider, expected string) { - p := core.NewPopulate(map[string]string{"stage": "prod"}) - - kp := p.KeyPath(core.KeyPath{Field: "MG_KEY", Path: "settings/{{stage}}/billing-svc", Decrypt: true, Plaintext: true}) - kpenv := p.KeyPath(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc", Decrypt: true, Plaintext: true}) - - ent, err := s.Get(kp) - assert.Nil(t, err) - assert.Equal(t, ent.Value, expected) - - ent, err = s.Get(kpenv) - assert.Nil(t, err) - assert.Equal(t, ent.Value, expected) -} - -func ConfigurableAssertProvider(t *testing.T, s core.Provider, sync bool, setField bool) { - p := core.NewPopulate(map[string]string{"stage": "prod"}) - - fieldValue := "" - if setField == true { - fieldValue = "MG_KEY" - } - - kpmap := p.KeyPath(core.KeyPath{Field: fieldValue, Path: "settings/{{stage}}/billing-svc/all", Decrypt: true}) - kp := p.KeyPath(core.KeyPath{Field: fieldValue, Path: "settings/{{stage}}/billing-svc", Decrypt: true}) - kpenv := p.KeyPath(core.KeyPath{Field: fieldValue, Env: fieldValue, Path: "settings/{{stage}}/billing-svc", Decrypt: true}) - - ent, err := s.Get(kp) - assert.Nil(t, err) - assert.Equal(t, ent.Value, "shazam") - - ent, err = s.Get(kpenv) - assert.Nil(t, err) - assert.Equal(t, ent.Value, "shazam") - - if sync { - ents, err := s.GetMapping(kpmap) - assert.Nil(t, err) - assert.Equal(t, len(ents), 2) - assert.Equal(t, ents[0].Value, "mailman") - assert.Equal(t, ents[1].Value, "shazam") - } -} - -func GetTestLogger() logging.Logger { - logger := logging.New() - logger.SetLevel("null") - return logger -} diff --git a/pkg/providers/heroku.go b/pkg/providers/heroku.go deleted file mode 100644 index a6dc8dc8..00000000 --- a/pkg/providers/heroku.go +++ /dev/null @@ -1,127 +0,0 @@ -package providers - -import ( - "context" - "fmt" - "os" - "sort" - - heroku "github.com/heroku/heroku-go/v5" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -type HerokuClient interface { - ConfigVarInfoForApp(ctx context.Context, appIdentity string) (heroku.ConfigVarInfoForAppResult, error) - ConfigVarUpdate(ctx context.Context, appIdentity string, o map[string]*string) (heroku.ConfigVarUpdateResult, error) -} -type Heroku struct { - client HerokuClient - logger logging.Logger -} - -const HerokuName = "heroku" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Heroku", - Name: HerokuName, - Authentication: "Requires an API key populated in your environment in: `HEROKU_API_KEY` (you can fetch it from your ~/.netrc).", - ConfigTemplate: ` - # requires an API key in: HEROKU_API_KEY (you can fetch yours from ~/.netrc) - heroku: - # sync a complete environment - env_sync: - path: drakula-demo - - # # pick and choose variables - # env: - # JVM_OPTS: - # path: drakula-demo -`, - Ops: core.OpMatrix{GetMapping: true, Get: true, Put: true, PutMapping: true}, - } - - RegisterProvider(metaInfo, NewHeroku) -} - -func NewHeroku(logger logging.Logger) (core.Provider, error) { - heroku.DefaultTransport.BearerToken = os.Getenv("HEROKU_API_KEY") - - svc := heroku.NewService(heroku.DefaultClient) - return &Heroku{client: svc, logger: logger}, nil -} - -func (h *Heroku) Put(p core.KeyPath, val string) error { - k := p.EffectiveKey() - h.logger.WithField("path", p.Path).Debug("put variable") - _, err := h.client.ConfigVarUpdate(context.TODO(), p.Path, map[string]*string{k: &val}) - return err -} -func (h *Heroku) PutMapping(p core.KeyPath, m map[string]string) error { - vars := map[string]*string{} - for k := range m { - v := m[k] - vars[k] = &v - } - h.logger.WithField("path", p.Path).Debug("put multiple values") - _, err := h.client.ConfigVarUpdate(context.TODO(), p.Path, vars) - return err -} - -func (h *Heroku) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - secret, err := h.getSecret(p) - if err != nil { - return nil, err - } - - k := secret - - entries := []core.EnvEntry{} - for k, v := range k { - val := "" - if v != nil { - val = *v - } - entries = append(entries, p.FoundWithKey(k, val)) - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -func (h *Heroku) Get(p core.KeyPath) (*core.EnvEntry, error) { //nolint:dupl - secret, err := h.getSecret(p) - if err != nil { - return nil, err - } - - data := secret - k := data[p.Env] - if p.Field != "" { - h.logger.WithField("path", p.Path).Debug("`env` attribute not found in returned data. take `field` attribute") - k = data[p.Field] - } - - if k == nil { - h.logger.WithField("path", p.Path).Debug("requested entry not found") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(*k) - return &ent, nil -} - -func (h *Heroku) Delete(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", HerokuName) -} - -func (h *Heroku) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", HerokuName) -} - -func (h *Heroku) getSecret(kp core.KeyPath) (heroku.ConfigVarInfoForAppResult, error) { - h.logger.WithField("path", kp.Path).Debug("get field") - return h.client.ConfigVarInfoForApp(context.TODO(), kp.Path) -} diff --git a/pkg/providers/heroku_test.go b/pkg/providers/heroku_test.go deleted file mode 100644 index 64d4187c..00000000 --- a/pkg/providers/heroku_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestHeroku(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockHerokuClient(ctrl) - // in heroku this isn't the path name, but an app name, - // but for testing it doesn't matter - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - shazam := "shazam" - mailman := "mailman" - out := map[string]*string{ - "MG_KEY": &shazam, - "SMTP_PASS": &mailman, - } - client.EXPECT().ConfigVarInfoForApp(gomock.Any(), gomock.Eq(path)).Return(out, nil).AnyTimes() - client.EXPECT().ConfigVarInfoForApp(gomock.Any(), gomock.Eq(pathmap)).Return(out, nil).AnyTimes() - s := Heroku{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) -} - -func TestHerokuFailures(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockHerokuClient(ctrl) - client.EXPECT().ConfigVarInfoForApp(gomock.Any(), gomock.Any()).Return(nil, errors.New("error")).AnyTimes() - s := Heroku{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/keeper_secretsmanager.go b/pkg/providers/keeper_secretsmanager.go deleted file mode 100644 index 6f4f4ee6..00000000 --- a/pkg/providers/keeper_secretsmanager.go +++ /dev/null @@ -1,234 +0,0 @@ -package providers - -import ( - "encoding/json" - "fmt" - "os" - "strconv" - "strings" - - ksm "github.com/keeper-security/secrets-manager-go/core" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -type KsmClient interface { - GetSecret(p core.KeyPath) (*core.EnvEntry, error) - GetSecrets(p core.KeyPath) ([]core.EnvEntry, error) -} - -type KeeperSecretsManager struct { - client KsmClient - logger logging.Logger -} - -const keeperName = "keeper_secretsmanager" - -//nolint -func init() { - metaInto := core.MetaInfo{ - Description: "Keeper Secrets Manager", - Name: keeperName, - Authentication: "You should populate `KSM_CONFIG=Base64ConfigString or KSM_CONFIG_FILE=ksm_config.json` in your environment.", - ConfigTemplate: ` - keeper_secretsmanager: - env_sync: - path: record_uid - env: - FOO_BAR: - path: UID/custom_field/foo_bar - # use Keeper Notation to pull data from typed records -`, - Ops: core.OpMatrix{Get: true, GetMapping: true}, - } - RegisterProvider(metaInto, NewKeeperSecretsManager) -} - -type SecretsManagerClient struct { - sm *ksm.SecretsManager -} - -func (c SecretsManagerClient) GetSecret(p core.KeyPath) (*core.EnvEntry, error) { - nr, err := c.sm.GetNotationResults(p.Path) - if err != nil { - return nil, err - } - - ent := core.EnvEntry{} - if len(nr) > 0 { - ent = p.Found(nr[0]) - } else { - ent = p.Missing() - } - - return &ent, nil -} - -func (c SecretsManagerClient) GetSecrets(p core.KeyPath) ([]core.EnvEntry, error) { - // p.Path must be a record UID - // TODO: Add Path = folderUID... expect too many dulpicates, prefix key name with RUID? - type KeyValuePair struct { - key, value string - } - - r := []core.EnvEntry{} - - recs, err := c.sm.GetSecrets([]string{p.Path}) - if err != nil { - return nil, err - } - if len(recs) < 1 { - return r, nil - } - - entries := []KeyValuePair{} - rec := recs[0] - fields := rec.GetFieldsBySection(ksm.FieldSectionBoth) - for _, field := range fields { - fmap, ok := field.(map[string]interface{}) - if !ok { - continue - } - - iValues, ok := fmap["value"].([]interface{}) - if !ok || len(iValues) < 1 { - continue - } - - value := extractValue(iValues) - if value == "" { - continue - } - - key := extractKey(fmap) - entries = append(entries, KeyValuePair{key: key, value: value}) - } - - // avoid duplicate key names - keymap := map[string]struct{}{} - for _, e := range entries { - key := e.key - if _, found := keymap[e.key]; found { - n := 1 - for { - n++ - mkey := key + "_" + strconv.Itoa(n) - if _, found := keymap[mkey]; !found { - key = mkey - break - } - } - } - keymap[key] = struct{}{} - ent := p.FoundWithKey(key, e.value) - r = append(r, ent) - } - - return r, nil -} - -func extractKey(fieldMap map[string]interface{}) string { - key := "" - if fLabel, ok := fieldMap["label"].(string); ok { - key = strings.TrimSpace(fLabel) - } - if key == "" { - if fType, ok := fieldMap["type"].(string); ok { - key = strings.TrimSpace(fType) - } - } - key = strings.ReplaceAll(key, " ", "_") - return key -} - -func extractValue(iValues []interface{}) string { - value := "" - _, isArray := iValues[0].([]interface{}) - _, isObject := iValues[0].(map[string]interface{}) - isJSON := len(iValues) > 1 || isArray || isObject - if isJSON { - if len(iValues) == 1 { - if val, err := json.Marshal(iValues[0]); err == nil { - value = string(val) - } - } else if val, err := json.Marshal(iValues); err == nil { - value = string(val) - } - } else { - val := iValues[0] - // JavaScript number type, IEEE754 double precision float - if fval, ok := val.(float64); ok && fval == float64(int(fval)) { - val = int(fval) // convert to int - } - value = fmt.Sprintf("%v", val) - } - return value -} - -func NewKsmClient() (KsmClient, error) { - config := os.Getenv("KSM_CONFIG") - configPath := os.Getenv("KSM_CONFIG_FILE") - if config == "" && configPath == "" { - return nil, fmt.Errorf("cannot find KSM_CONFIG or KSM_CONFIG_FILE for %s", keeperName) - } - - // with both options present KSM_CONFIG overrides KSM_CONFIG_FILE - var options *ksm.ClientOptions = nil - if config != "" { - options = &ksm.ClientOptions{Config: ksm.NewMemoryKeyValueStorage(config)} - } else if stat, err := os.Stat(configPath); err == nil && stat.Size() > 2 { - options = &ksm.ClientOptions{Config: ksm.NewFileKeyValueStorage(configPath)} - } - - if options == nil { - return nil, fmt.Errorf("failed to initialize KSM Client Options") - } - - sm := ksm.NewSecretsManager(options) - if sm == nil { - return nil, fmt.Errorf("failed to initialize KSM Client") - } - - return SecretsManagerClient{ - sm: sm, - }, nil -} - -func NewKeeperSecretsManager(logger logging.Logger) (core.Provider, error) { - ksmClient, err := NewKsmClient() - if err != nil { - return nil, err - } - return &KeeperSecretsManager{ - client: ksmClient, - logger: logger, - }, nil -} - -func (k *KeeperSecretsManager) Name() string { - return keeperName -} - -func (k *KeeperSecretsManager) Get(p core.KeyPath) (*core.EnvEntry, error) { - return k.client.GetSecret(p) -} - -func (k *KeeperSecretsManager) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - return k.client.GetSecrets(p) -} - -func (k *KeeperSecretsManager) Put(p core.KeyPath, val string) error { - return fmt.Errorf("provider %q does not implement write yet", k.Name()) -} - -func (k *KeeperSecretsManager) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %q does not implement write mapping yet", k.Name()) -} - -func (k *KeeperSecretsManager) Delete(kp core.KeyPath) error { - return fmt.Errorf("provider %s does not implement delete yet", k.Name()) -} - -func (k *KeeperSecretsManager) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("provider %s does not implement delete mapping yet", k.Name()) -} diff --git a/pkg/providers/keeper_secretsmanager_test.go b/pkg/providers/keeper_secretsmanager_test.go deleted file mode 100644 index dbbfbd79..00000000 --- a/pkg/providers/keeper_secretsmanager_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestKeeperSecretsManager(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockKsmClient(ctrl) - - a := KeeperSecretsManager{ - client: client, - logger: GetTestLogger(), - } - - path := core.KeyPath{Path: "settings/prod/billing-svc/all", Field: "MG_KEY", Decrypt: true} - key1 := core.KeyPath{Path: "settings/prod/billing-svc", Field: "MG_KEY", Decrypt: true} - key2 := core.KeyPath{Path: "settings/prod/billing-svc", Env: "MG_KEY", Decrypt: true} - - returnSecrets := []core.EnvEntry{ - {Key: "MM_KEY", Value: "mailman"}, - {Key: "MG_KEY", Value: "shazam"}, - } - client.EXPECT().GetSecret(key1).Return(&core.EnvEntry{Value: "shazam"}, nil).AnyTimes() - client.EXPECT().GetSecret(key2).Return(&core.EnvEntry{Value: "shazam"}, nil).AnyTimes() - client.EXPECT().GetSecrets(path).Return(returnSecrets, nil).AnyTimes() - client.EXPECT().GetSecrets(nil).Return(returnSecrets, nil).AnyTimes() - - AssertProvider(t, &a, true) -} - -func TestKeeperSecretsManagerFailures(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockKsmClient(ctrl) - - a := KeeperSecretsManager{ - client: client, - logger: GetTestLogger(), - } - - path := core.KeyPath{Path: "settings/{{stage}}/billing-svc/all"} - key1 := core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"} - client.EXPECT().GetSecret(key1).Return(&core.EnvEntry{}, errors.New("error")).AnyTimes() - client.EXPECT().GetSecrets(path).Return([]core.EnvEntry{}, errors.New("error")).AnyTimes() - - _, err := a.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) - - _, err = a.GetMapping(core.KeyPath{Path: "settings/{{stage}}/billing-svc/all"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/keypass.go b/pkg/providers/keypass.go deleted file mode 100644 index d82e5b12..00000000 --- a/pkg/providers/keypass.go +++ /dev/null @@ -1,194 +0,0 @@ -package providers - -import ( - "errors" - "fmt" - "os" - "strings" - - "github.com/spectralops/teller/pkg/core" - - "github.com/spectralops/teller/pkg/logging" - "github.com/tobischo/gokeepasslib/v3" -) - -var ( - // keyPathFields describe all the available fields in KeyPass entry - keyPathFields = []string{"Notes", "Password", "URL", "UserName"} -) - -type KeyPass struct { - logger logging.Logger - data map[string]gokeepasslib.Entry -} - -const KeyPassName = "KeyPass" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Keypass", - Name: KeyPassName, - Authentication: "Set the following env vars:\n`KEYPASS_PASSWORD`: Password database credentials\n`KEYPASS_DB_PATH`: Database path", - ConfigTemplate: ` - # Configure via environment variables for integration: - # KEYPASS_PASSWORD: KeyPass password - # KEYPASS_DB_PATH: Path to DB file - - keypass: - env_sync: - path: redis/config - # source: Optional, all fields is the default. Supported fields: Notes, Title, Password, URL, UserName - env: - ETC_DSN: - path: redis/config/foobar - # source: Optional, Password is the default. Supported fields: Notes, Title, Password, URL, UserName -`, - Ops: core.OpMatrix{GetMapping: true, Get: true}, - } - - RegisterProvider(metaInfo, NewKeyPass) -} - -// NewKeyPass creates new provider instance -func NewKeyPass(logger logging.Logger) (core.Provider, error) { - password := os.Getenv("KEYPASS_PASSWORD") - if password == "" { - return nil, errors.New("missing `KEYPASS_PASSWORD`") - } - dbPath := os.Getenv("KEYPASS_DB_PATH") - if dbPath == "" { - return nil, errors.New("missing `KEYPASS_DB_PATH`") - } - - file, err := os.Open(dbPath) - if err != nil { - return nil, err - } - defer file.Close() - - db := gokeepasslib.NewDatabase() - db.Credentials = gokeepasslib.NewPasswordCredentials(password) - err = gokeepasslib.NewDecoder(file).Decode(db) - - if err != nil { - return nil, err - } - - err = db.UnlockProtectedEntries() - if err != nil { - return nil, err - } - keyPass := &KeyPass{ - logger: logger, - } - keyPass.data = keyPass.prepareGroups("", db.Content.Root.Groups, nil) - return keyPass, nil -} - -// Put will create a new single entry -func (k *KeyPass) Put(p core.KeyPath, val string) error { - return fmt.Errorf("provider %q does not implement write yet", KeyPassName) -} - -// PutMapping will create a multiple entries -func (k *KeyPass) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %q does not implement write yet", KeyPassName) -} - -// GetMapping returns a multiple entries -func (k *KeyPass) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - - results := []core.EnvEntry{} - for path, entry := range k.data { //nolint - // get entries that start with the given path - if strings.HasPrefix(path, p.Path) { - if p.Source == "" { - // getting all entries fields - for _, field := range keyPathFields { - val := entry.Get(field).Value.Content - // skip on empty field - if val == "" { - k.logger.WithFields(map[string]interface{}{ - "field": field, - "path": path, - }).Debug("empty field") - continue - } - results = append(results, p.FoundWithKey(fmt.Sprintf("%s/%s", path, strings.ToLower(field)), val)) - } - } else { - fieldContent := entry.Get(p.Source) - if fieldContent == nil { - k.logger.WithFields(map[string]interface{}{ - "source": p.Source, - "path": path, - }).Debug("field not found") - continue - } - val := fieldContent.Value.Content - if val != "" { - results = append(results, p.FoundWithKey(path, val)) - } - } - } - } - return results, nil -} - -// Get returns a single entry -func (k *KeyPass) Get(p core.KeyPath) (*core.EnvEntry, error) { - ent := p.Missing() - entry, found := k.data[p.Path] - if !found { - k.logger.WithField("path", p.Path).Debug("secret not found in path") - return nil, fmt.Errorf("%v path: %s not exists", KeyPassName, p.Path) - } - source := p.Source - if source == "" { - k.logger.WithField("path", p.Path).Debug("source attribute is empty, setting default field") - source = "Password" - } - k.logger.WithFields(map[string]interface{}{ - "path": p.Path, - "source": source, - }).Debug("get keypass field") - ent = p.Found(entry.Get(source).Value.Content) - - return &ent, nil -} - -// Delete will delete entry -func (k *KeyPass) Delete(kp core.KeyPath) error { - return fmt.Errorf("provider %s does not implement delete yet", KeyPassName) -} - -// DeleteMapping will delete the given path recessively -func (k *KeyPass) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("provider %s does not implement delete yet", KeyPassName) -} - -// prepareGroups all KeyPass entries for easy seearch -func (k *KeyPass) prepareGroups(path string, groups []gokeepasslib.Group, mapData map[string]gokeepasslib.Entry) map[string]gokeepasslib.Entry { - if mapData == nil { - mapData = map[string]gokeepasslib.Entry{} - } - for _, group := range groups { //nolint - // if entries found, adding the entry data fo the list - if len(group.Entries) > 0 { - for _, entry := range group.Entries { //nolint - if path == "" { // prevent unexpected leading slash for entries in root - mapData[fmt.Sprintf("%s/%s", group.Name, entry.GetTitle())] = entry - } else { - mapData[fmt.Sprintf("%s/%s/%s", path, group.Name, entry.GetTitle())] = entry - } - - } - } - if len(group.Groups) > 0 { - // call recursively prepareGroups function get collect entries - return k.prepareGroups(strings.TrimPrefix(fmt.Sprintf("%s/%s", path, group.Name), "/"), group.Groups, mapData) - } - } - return mapData -} diff --git a/pkg/providers/keypass_test.go b/pkg/providers/keypass_test.go deleted file mode 100644 index 7cd69c1c..00000000 --- a/pkg/providers/keypass_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package providers - -import ( - "os" - "path" - "runtime" - "testing" - - "github.com/alecthomas/assert" - "github.com/spectralops/teller/pkg/core" -) - -func TestKetPass(t *testing.T) { - - _, filename, _, _ := runtime.Caller(0) //nolint - os.Setenv("KEYPASS_PASSWORD", "1234") - - os.Setenv("KEYPASS_DB_PATH", path.Join(path.Dir(filename), "mock_providers", "keypass.kdbx")) - - k, err := NewKeyPass(GetTestLogger()) - assert.Nil(t, err) - AssertProvider(t, k, false) - p := core.NewPopulate(map[string]string{"stage": "prod"}) - kpmap := p.KeyPath(core.KeyPath{Field: "MG_KEY", Path: "settings/{{stage}}/billing-svc/all", Decrypt: true}) - ents, err := k.GetMapping(kpmap) - assert.Nil(t, err) - assert.Equal(t, len(ents), 4) -} - -func TestKeypassFailures(t *testing.T) { - - _, filename, _, _ := runtime.Caller(0) //nolint - os.Setenv("KEYPASS_PASSWORD", "1234") - - os.Setenv("KEYPASS_DB_PATH", path.Join(path.Dir(filename), "mock_providers", "keypass.kdbx")) - - k, _ := NewKeyPass(GetTestLogger()) - _, err := k.Get(core.KeyPath{Env: "NOT_EXISTS", Path: "settings"}) - assert.NotNil(t, err) - -} diff --git a/pkg/providers/lastpass.go b/pkg/providers/lastpass.go deleted file mode 100644 index 63afafde..00000000 --- a/pkg/providers/lastpass.go +++ /dev/null @@ -1,173 +0,0 @@ -package providers - -import ( - "bufio" - "errors" - "fmt" - "os" - "strings" - - "github.com/spectralops/teller/pkg/core" - - "github.com/mattn/lastpass-go" - "github.com/spectralops/teller/pkg/logging" -) - -const ( - findingNoteCount = 2 -) - -type LastPass struct { - accounts map[string]*lastpass.Account - logger logging.Logger -} - -const LastPassName = "lastpass" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "Lastpass", - Authentication: "TODO(XXX)", - Name: LastPassName, - ConfigTemplate: ` - # Configure via environment variables: - # LASTPASS_USERNAME - # LASTPASS_PASSWORD - - lastpass: - env_sync: - path: # LastPass item ID - env: - ETC_DSN: - path: # Lastpass item ID - # field: by default taking password property. in case you want other property un-mark this line and set the lastpass property name. -`, - Ops: core.OpMatrix{GetMapping: true, Get: true}, - } - - RegisterProvider(metaInfo, NewLastPass) -} - -func NewLastPass(logger logging.Logger) (core.Provider, error) { - username := os.Getenv("LASTPASS_USERNAME") - masterPassword := os.Getenv("LASTPASS_PASSWORD") - - vault, err := lastpass.CreateVault(username, masterPassword) - if err != nil { - return nil, err - } - - accountsMap := map[string]*lastpass.Account{} - for _, account := range vault.Accounts { - accountsMap[account.Id] = account - } - - return &LastPass{accounts: accountsMap, logger: logger}, nil -} - -func (l *LastPass) Put(p core.KeyPath, val string) error { - return fmt.Errorf("provider %q does not implement write yet", LastPassName) -} - -func (l *LastPass) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %q does not implement write yet", LastPassName) -} - -func (l *LastPass) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - - item, err := l.getSecretByID(p.Path) - if err != nil { - return nil, err - } - - entries := []core.EnvEntry{} - entries = append(entries, p.FoundWithKey("Name", item.Name), p.FoundWithKey("Password", item.Password), p.FoundWithKey("Url", item.Url)) - - for k, v := range l.notesToMap(item.Notes) { - entries = append(entries, p.FoundWithKey(strings.ReplaceAll(k, " ", "_"), v)) - } - - return entries, nil -} - -func (l *LastPass) Get(p core.KeyPath) (*core.EnvEntry, error) { - - item, err := l.getSecretByID(p.Path) - if err != nil { - return nil, err - } - - var ent = p.Missing() - // if field not defined, password field returned - if p.Field == "" { - l.logger.WithField("path", p.Path).Debug("field attribute is empty, return item password attribute") - ent = p.Found(item.Password) - } else { - l.logger.WithFields(map[string]interface{}{ - "path": p.Path, - "field": p.Field, - }).Debug("field attribute present, search filed name in notes list") - key, err := l.getNodeByKeyName(p.Field, item.Notes) - if err == nil { - ent = p.Found(key) - } - } - - return &ent, nil -} - -func (l *LastPass) Delete(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", LastPassName) -} - -func (l *LastPass) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", LastPassName) -} - -func (l *LastPass) getSecretByID(id string) (*lastpass.Account, error) { - - if item, found := l.accounts[id]; found { - return item, nil - } - return nil, errors.New("item ID not found") - -} - -// notesToMap parse LastPass note convention to map string -// -// Example: -// ` -// card:a -// Type:b -// ` -// TO: -// {"card": "a", "Type": "b"} -func (l *LastPass) notesToMap(notes string) map[string]string { - - results := map[string]string{} - scanner := bufio.NewScanner(strings.NewReader(notes)) - for scanner.Scan() { - findings := strings.SplitN(scanner.Text(), ":", 2) //nolint: gomnd - if len(findings) == findingNoteCount { - results[strings.TrimSpace(findings[0])] = strings.TrimSpace(findings[1]) - } - } - return results -} - -// getNodeByKeyName parse LastPass note convention and search if one of the note equal to the given key -func (l *LastPass) getNodeByKeyName(key, notes string) (string, error) { - - scanner := bufio.NewScanner(strings.NewReader(notes)) - for scanner.Scan() { - findings := strings.SplitN(scanner.Text(), ":", 2) //nolint: gomnd - if len(findings) == findingNoteCount && findings[0] == key { - return strings.TrimSpace(findings[1]), nil - } - } - l.logger.WithFields(map[string]interface{}{ - "field": key, - }).Debug("field attribute not found in notes list") - return "", errors.New("key not found") -} diff --git a/pkg/providers/lastpass_test.go b/pkg/providers/lastpass_test.go deleted file mode 100644 index c4db94e3..00000000 --- a/pkg/providers/lastpass_test.go +++ /dev/null @@ -1,74 +0,0 @@ -package providers - -import ( - "testing" - - "github.com/alecthomas/assert" - "github.com/mattn/lastpass-go" - "github.com/spectralops/teller/pkg/core" -) - -func TestLastPass(t *testing.T) { - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - - notes := `MG_KEY: shazam -Sec key: secret-from-note -` - lastPassProvider := LastPass{ - accounts: map[string]*lastpass.Account{ - path: { - Id: "id", - Name: "secret-name", - Username: "username", - Password: "shazam", - Url: "http://test.com", - Group: "", - Notes: notes, - }, - pathmap: { - Id: "id-2", - Name: "secret-name-2", - Username: "shazam", - Password: "username-2", - Url: "http://test.com", - Group: "", - Notes: notes, - }, - }, - logger: GetTestLogger(), - } - AssertProvider(t, &lastPassProvider, false) - - p := core.NewPopulate(map[string]string{"stage": "prod"}) - kpmap := p.KeyPath(core.KeyPath{Field: "MG_KEY", Path: "settings/{{stage}}/billing-svc/all", Decrypt: true}) - - ents, err := lastPassProvider.GetMapping(kpmap) - assert.Nil(t, err) - assert.Equal(t, len(ents), 5) - - // collect all the fields that returned from GetMapping - allValues := []string{} - for _, f := range ents { - allValues = append(allValues, f.Value) - } - - assert.Contains(t, allValues, "secret-name-2") - assert.Contains(t, allValues, "username-2") - assert.Contains(t, allValues, "http://test.com") - assert.Contains(t, allValues, "shazam") - assert.Contains(t, allValues, "secret-from-note") - -} - -func TestLastPassFailures(t *testing.T) { - lastPassProvider := LastPass{ - accounts: map[string]*lastpass.Account{}, - logger: GetTestLogger(), - } - - _, err := lastPassProvider.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) - _, err = lastPassProvider.GetMapping(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/mock_providers/ansible_vault_mock.go b/pkg/providers/mock_providers/ansible_vault_mock.go deleted file mode 100644 index 7fd71ba8..00000000 --- a/pkg/providers/mock_providers/ansible_vault_mock.go +++ /dev/null @@ -1,49 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/ansible_vault.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" -) - -// MockAnsibleVaultClient is a mock of AnsibleVaultClient interface. -type MockAnsibleVaultClient struct { - ctrl *gomock.Controller - recorder *MockAnsibleVaultClientMockRecorder -} - -// MockAnsibleVaultClientMockRecorder is the mock recorder for MockAnsibleVaultClient. -type MockAnsibleVaultClientMockRecorder struct { - mock *MockAnsibleVaultClient -} - -// NewMockAnsibleVaultClient creates a new mock instance. -func NewMockAnsibleVaultClient(ctrl *gomock.Controller) *MockAnsibleVaultClient { - mock := &MockAnsibleVaultClient{ctrl: ctrl} - mock.recorder = &MockAnsibleVaultClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAnsibleVaultClient) EXPECT() *MockAnsibleVaultClientMockRecorder { - return m.recorder -} - -// Read mocks base method. -func (m *MockAnsibleVaultClient) Read(p string) (map[string]string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Read", p) - ret0, _ := ret[0].(map[string]string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Read indicates an expected call of Read. -func (mr *MockAnsibleVaultClientMockRecorder) Read(p interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockAnsibleVaultClient)(nil).Read), p) -} diff --git a/pkg/providers/mock_providers/aws_secretsmanager_mock.go b/pkg/providers/mock_providers/aws_secretsmanager_mock.go deleted file mode 100644 index c3d25077..00000000 --- a/pkg/providers/mock_providers/aws_secretsmanager_mock.go +++ /dev/null @@ -1,136 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/aws_secretsmanager.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - context "context" - reflect "reflect" - - secretsmanager "github.com/aws/aws-sdk-go-v2/service/secretsmanager" - gomock "github.com/golang/mock/gomock" -) - -// MockAWSSecretsManagerClient is a mock of AWSSecretsManagerClient interface. -type MockAWSSecretsManagerClient struct { - ctrl *gomock.Controller - recorder *MockAWSSecretsManagerClientMockRecorder -} - -// MockAWSSecretsManagerClientMockRecorder is the mock recorder for MockAWSSecretsManagerClient. -type MockAWSSecretsManagerClientMockRecorder struct { - mock *MockAWSSecretsManagerClient -} - -// NewMockAWSSecretsManagerClient creates a new mock instance. -func NewMockAWSSecretsManagerClient(ctrl *gomock.Controller) *MockAWSSecretsManagerClient { - mock := &MockAWSSecretsManagerClient{ctrl: ctrl} - mock.recorder = &MockAWSSecretsManagerClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAWSSecretsManagerClient) EXPECT() *MockAWSSecretsManagerClientMockRecorder { - return m.recorder -} - -// CreateSecret mocks base method. -func (m *MockAWSSecretsManagerClient) CreateSecret(ctx context.Context, params *secretsmanager.CreateSecretInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.CreateSecretOutput, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, params} - for _, a := range optFns { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "CreateSecret", varargs...) - ret0, _ := ret[0].(*secretsmanager.CreateSecretOutput) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateSecret indicates an expected call of CreateSecret. -func (mr *MockAWSSecretsManagerClientMockRecorder) CreateSecret(ctx, params interface{}, optFns ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, params}, optFns...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateSecret", reflect.TypeOf((*MockAWSSecretsManagerClient)(nil).CreateSecret), varargs...) -} - -// DeleteSecret mocks base method. -func (m *MockAWSSecretsManagerClient) DeleteSecret(ctx context.Context, params *secretsmanager.DeleteSecretInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.DeleteSecretOutput, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, params} - for _, a := range optFns { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "DeleteSecret", varargs...) - ret0, _ := ret[0].(*secretsmanager.DeleteSecretOutput) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DeleteSecret indicates an expected call of DeleteSecret. -func (mr *MockAWSSecretsManagerClientMockRecorder) DeleteSecret(ctx, params interface{}, optFns ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, params}, optFns...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteSecret", reflect.TypeOf((*MockAWSSecretsManagerClient)(nil).DeleteSecret), varargs...) -} - -// DescribeSecret mocks base method. -func (m *MockAWSSecretsManagerClient) DescribeSecret(ctx context.Context, params *secretsmanager.DescribeSecretInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.DescribeSecretOutput, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, params} - for _, a := range optFns { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "DescribeSecret", varargs...) - ret0, _ := ret[0].(*secretsmanager.DescribeSecretOutput) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DescribeSecret indicates an expected call of DescribeSecret. -func (mr *MockAWSSecretsManagerClientMockRecorder) DescribeSecret(ctx, params interface{}, optFns ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, params}, optFns...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeSecret", reflect.TypeOf((*MockAWSSecretsManagerClient)(nil).DescribeSecret), varargs...) -} - -// GetSecretValue mocks base method. -func (m *MockAWSSecretsManagerClient) GetSecretValue(ctx context.Context, params *secretsmanager.GetSecretValueInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.GetSecretValueOutput, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, params} - for _, a := range optFns { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "GetSecretValue", varargs...) - ret0, _ := ret[0].(*secretsmanager.GetSecretValueOutput) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSecretValue indicates an expected call of GetSecretValue. -func (mr *MockAWSSecretsManagerClientMockRecorder) GetSecretValue(ctx, params interface{}, optFns ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, params}, optFns...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSecretValue", reflect.TypeOf((*MockAWSSecretsManagerClient)(nil).GetSecretValue), varargs...) -} - -// PutSecretValue mocks base method. -func (m *MockAWSSecretsManagerClient) PutSecretValue(ctx context.Context, params *secretsmanager.PutSecretValueInput, optFns ...func(*secretsmanager.Options)) (*secretsmanager.PutSecretValueOutput, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, params} - for _, a := range optFns { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "PutSecretValue", varargs...) - ret0, _ := ret[0].(*secretsmanager.PutSecretValueOutput) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PutSecretValue indicates an expected call of PutSecretValue. -func (mr *MockAWSSecretsManagerClientMockRecorder) PutSecretValue(ctx, params interface{}, optFns ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, params}, optFns...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutSecretValue", reflect.TypeOf((*MockAWSSecretsManagerClient)(nil).PutSecretValue), varargs...) -} diff --git a/pkg/providers/mock_providers/aws_ssm_mock.go b/pkg/providers/mock_providers/aws_ssm_mock.go deleted file mode 100644 index 9e7d17d7..00000000 --- a/pkg/providers/mock_providers/aws_ssm_mock.go +++ /dev/null @@ -1,96 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/aws_ssm.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - context "context" - reflect "reflect" - - ssm "github.com/aws/aws-sdk-go-v2/service/ssm" - gomock "github.com/golang/mock/gomock" -) - -// MockAWSSSMClient is a mock of AWSSSMClient interface. -type MockAWSSSMClient struct { - ctrl *gomock.Controller - recorder *MockAWSSSMClientMockRecorder -} - -// MockAWSSSMClientMockRecorder is the mock recorder for MockAWSSSMClient. -type MockAWSSSMClientMockRecorder struct { - mock *MockAWSSSMClient -} - -// NewMockAWSSSMClient creates a new mock instance. -func NewMockAWSSSMClient(ctrl *gomock.Controller) *MockAWSSSMClient { - mock := &MockAWSSSMClient{ctrl: ctrl} - mock.recorder = &MockAWSSSMClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAWSSSMClient) EXPECT() *MockAWSSSMClientMockRecorder { - return m.recorder -} - -// DeleteParameter mocks base method. -func (m *MockAWSSSMClient) DeleteParameter(ctx context.Context, params *ssm.DeleteParameterInput, optFns ...func(*ssm.Options)) (*ssm.DeleteParameterOutput, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, params} - for _, a := range optFns { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "DeleteParameter", varargs...) - ret0, _ := ret[0].(*ssm.DeleteParameterOutput) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DeleteParameter indicates an expected call of DeleteParameter. -func (mr *MockAWSSSMClientMockRecorder) DeleteParameter(ctx, params interface{}, optFns ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, params}, optFns...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteParameter", reflect.TypeOf((*MockAWSSSMClient)(nil).DeleteParameter), varargs...) -} - -// GetParameter mocks base method. -func (m *MockAWSSSMClient) GetParameter(ctx context.Context, params *ssm.GetParameterInput, optFns ...func(*ssm.Options)) (*ssm.GetParameterOutput, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, params} - for _, a := range optFns { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "GetParameter", varargs...) - ret0, _ := ret[0].(*ssm.GetParameterOutput) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetParameter indicates an expected call of GetParameter. -func (mr *MockAWSSSMClientMockRecorder) GetParameter(ctx, params interface{}, optFns ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, params}, optFns...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetParameter", reflect.TypeOf((*MockAWSSSMClient)(nil).GetParameter), varargs...) -} - -// PutParameter mocks base method. -func (m *MockAWSSSMClient) PutParameter(ctx context.Context, params *ssm.PutParameterInput, optFns ...func(*ssm.Options)) (*ssm.PutParameterOutput, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, params} - for _, a := range optFns { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "PutParameter", varargs...) - ret0, _ := ret[0].(*ssm.PutParameterOutput) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PutParameter indicates an expected call of PutParameter. -func (mr *MockAWSSSMClientMockRecorder) PutParameter(ctx, params interface{}, optFns ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, params}, optFns...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutParameter", reflect.TypeOf((*MockAWSSSMClient)(nil).PutParameter), varargs...) -} diff --git a/pkg/providers/mock_providers/azure_keyvault_mock.go b/pkg/providers/mock_providers/azure_keyvault_mock.go deleted file mode 100644 index 9b763579..00000000 --- a/pkg/providers/mock_providers/azure_keyvault_mock.go +++ /dev/null @@ -1,96 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/azure_keyvault.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - context "context" - reflect "reflect" - - keyvault "github.com/Azure/azure-sdk-for-go/profiles/latest/keyvault/keyvault" - gomock "github.com/golang/mock/gomock" -) - -// MockAzureKeyVaultClient is a mock of AzureKeyVaultClient interface. -type MockAzureKeyVaultClient struct { - ctrl *gomock.Controller - recorder *MockAzureKeyVaultClientMockRecorder -} - -// MockAzureKeyVaultClientMockRecorder is the mock recorder for MockAzureKeyVaultClient. -type MockAzureKeyVaultClientMockRecorder struct { - mock *MockAzureKeyVaultClient -} - -// NewMockAzureKeyVaultClient creates a new mock instance. -func NewMockAzureKeyVaultClient(ctrl *gomock.Controller) *MockAzureKeyVaultClient { - mock := &MockAzureKeyVaultClient{ctrl: ctrl} - mock.recorder = &MockAzureKeyVaultClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockAzureKeyVaultClient) EXPECT() *MockAzureKeyVaultClientMockRecorder { - return m.recorder -} - -// DeleteSecret mocks base method. -func (m *MockAzureKeyVaultClient) DeleteSecret(ctx context.Context, vaultBaseURL, secretName string) (keyvault.DeletedSecretBundle, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteSecret", ctx, vaultBaseURL, secretName) - ret0, _ := ret[0].(keyvault.DeletedSecretBundle) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DeleteSecret indicates an expected call of DeleteSecret. -func (mr *MockAzureKeyVaultClientMockRecorder) DeleteSecret(ctx, vaultBaseURL, secretName interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteSecret", reflect.TypeOf((*MockAzureKeyVaultClient)(nil).DeleteSecret), ctx, vaultBaseURL, secretName) -} - -// GetSecret mocks base method. -func (m *MockAzureKeyVaultClient) GetSecret(ctx context.Context, vaultBaseURL, secretName, secretVersion string) (keyvault.SecretBundle, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSecret", ctx, vaultBaseURL, secretName, secretVersion) - ret0, _ := ret[0].(keyvault.SecretBundle) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSecret indicates an expected call of GetSecret. -func (mr *MockAzureKeyVaultClientMockRecorder) GetSecret(ctx, vaultBaseURL, secretName, secretVersion interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSecret", reflect.TypeOf((*MockAzureKeyVaultClient)(nil).GetSecret), ctx, vaultBaseURL, secretName, secretVersion) -} - -// GetSecrets mocks base method. -func (m *MockAzureKeyVaultClient) GetSecrets(ctx context.Context, vaultBaseURL string, maxresults *int32) (keyvault.SecretListResultPage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSecrets", ctx, vaultBaseURL, maxresults) - ret0, _ := ret[0].(keyvault.SecretListResultPage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSecrets indicates an expected call of GetSecrets. -func (mr *MockAzureKeyVaultClientMockRecorder) GetSecrets(ctx, vaultBaseURL, maxresults interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSecrets", reflect.TypeOf((*MockAzureKeyVaultClient)(nil).GetSecrets), ctx, vaultBaseURL, maxresults) -} - -// SetSecret mocks base method. -func (m *MockAzureKeyVaultClient) SetSecret(ctx context.Context, vaultBaseURL, secretName string, parameters keyvault.SecretSetParameters) (keyvault.SecretBundle, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetSecret", ctx, vaultBaseURL, secretName, parameters) - ret0, _ := ret[0].(keyvault.SecretBundle) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// SetSecret indicates an expected call of SetSecret. -func (mr *MockAzureKeyVaultClientMockRecorder) SetSecret(ctx, vaultBaseURL, secretName, parameters interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSecret", reflect.TypeOf((*MockAzureKeyVaultClient)(nil).SetSecret), ctx, vaultBaseURL, secretName, parameters) -} diff --git a/pkg/providers/mock_providers/cloudflare_workers_kv_mock.go b/pkg/providers/mock_providers/cloudflare_workers_kv_mock.go deleted file mode 100644 index 951774f5..00000000 --- a/pkg/providers/mock_providers/cloudflare_workers_kv_mock.go +++ /dev/null @@ -1,96 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/cloudflare_workers_kv.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - context "context" - reflect "reflect" - - cloudflare "github.com/cloudflare/cloudflare-go" - gomock "github.com/golang/mock/gomock" -) - -// MockCloudflareClient is a mock of CloudflareClient interface. -type MockCloudflareClient struct { - ctrl *gomock.Controller - recorder *MockCloudflareClientMockRecorder -} - -// MockCloudflareClientMockRecorder is the mock recorder for MockCloudflareClient. -type MockCloudflareClientMockRecorder struct { - mock *MockCloudflareClient -} - -// NewMockCloudflareClient creates a new mock instance. -func NewMockCloudflareClient(ctrl *gomock.Controller) *MockCloudflareClient { - mock := &MockCloudflareClient{ctrl: ctrl} - mock.recorder = &MockCloudflareClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockCloudflareClient) EXPECT() *MockCloudflareClientMockRecorder { - return m.recorder -} - -// ListWorkersKVs mocks base method. -func (m *MockCloudflareClient) ListWorkersKVs(ctx context.Context, namespaceID string) (cloudflare.ListStorageKeysResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListWorkersKVs", ctx, namespaceID) - ret0, _ := ret[0].(cloudflare.ListStorageKeysResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListWorkersKVs indicates an expected call of ListWorkersKVs. -func (mr *MockCloudflareClientMockRecorder) ListWorkersKVs(ctx, namespaceID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListWorkersKVs", reflect.TypeOf((*MockCloudflareClient)(nil).ListWorkersKVs), ctx, namespaceID) -} - -// ReadWorkersKV mocks base method. -func (m *MockCloudflareClient) ReadWorkersKV(ctx context.Context, namespaceID, key string) ([]byte, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ReadWorkersKV", ctx, namespaceID, key) - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ReadWorkersKV indicates an expected call of ReadWorkersKV. -func (mr *MockCloudflareClientMockRecorder) ReadWorkersKV(ctx, namespaceID, key interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadWorkersKV", reflect.TypeOf((*MockCloudflareClient)(nil).ReadWorkersKV), ctx, namespaceID, key) -} - -// WriteWorkersKV mocks base method. -func (m *MockCloudflareClient) WriteWorkersKV(ctx context.Context, namespaceID, key string, value []byte) (cloudflare.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WriteWorkersKV", ctx, namespaceID, key, value) - ret0, _ := ret[0].(cloudflare.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WriteWorkersKV indicates an expected call of WriteWorkersKV. -func (mr *MockCloudflareClientMockRecorder) WriteWorkersKV(ctx, namespaceID, key, value interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteWorkersKV", reflect.TypeOf((*MockCloudflareClient)(nil).WriteWorkersKV), ctx, namespaceID, key, value) -} - -// WriteWorkersKVBulk mocks base method. -func (m *MockCloudflareClient) WriteWorkersKVBulk(ctx context.Context, namespaceID string, kvs cloudflare.WorkersKVBulkWriteRequest) (cloudflare.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "WriteWorkersKVBulk", ctx, namespaceID, kvs) - ret0, _ := ret[0].(cloudflare.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// WriteWorkersKVBulk indicates an expected call of WriteWorkersKVBulk. -func (mr *MockCloudflareClientMockRecorder) WriteWorkersKVBulk(ctx, namespaceID, kvs interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WriteWorkersKVBulk", reflect.TypeOf((*MockCloudflareClient)(nil).WriteWorkersKVBulk), ctx, namespaceID, kvs) -} diff --git a/pkg/providers/mock_providers/cloudflare_workers_secrets_mock.go b/pkg/providers/mock_providers/cloudflare_workers_secrets_mock.go deleted file mode 100644 index 3a15cb4a..00000000 --- a/pkg/providers/mock_providers/cloudflare_workers_secrets_mock.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/cloudflare_workers_secrets.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - context "context" - reflect "reflect" - - cloudflare "github.com/cloudflare/cloudflare-go" - gomock "github.com/golang/mock/gomock" -) - -// MockCloudflareSecretsClient is a mock of CloudflareSecretsClient interface. -type MockCloudflareSecretsClient struct { - ctrl *gomock.Controller - recorder *MockCloudflareSecretsClientMockRecorder -} - -// MockCloudflareSecretsClientMockRecorder is the mock recorder for MockCloudflareSecretsClient. -type MockCloudflareSecretsClientMockRecorder struct { - mock *MockCloudflareSecretsClient -} - -// NewMockCloudflareSecretsClient creates a new mock instance. -func NewMockCloudflareSecretsClient(ctrl *gomock.Controller) *MockCloudflareSecretsClient { - mock := &MockCloudflareSecretsClient{ctrl: ctrl} - mock.recorder = &MockCloudflareSecretsClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockCloudflareSecretsClient) EXPECT() *MockCloudflareSecretsClientMockRecorder { - return m.recorder -} - -// DeleteWorkersSecret mocks base method. -func (m *MockCloudflareSecretsClient) DeleteWorkersSecret(ctx context.Context, script, secretName string) (cloudflare.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteWorkersSecret", ctx, script, secretName) - ret0, _ := ret[0].(cloudflare.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DeleteWorkersSecret indicates an expected call of DeleteWorkersSecret. -func (mr *MockCloudflareSecretsClientMockRecorder) DeleteWorkersSecret(ctx, script, secretName interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteWorkersSecret", reflect.TypeOf((*MockCloudflareSecretsClient)(nil).DeleteWorkersSecret), ctx, script, secretName) -} - -// SetWorkersSecret mocks base method. -func (m *MockCloudflareSecretsClient) SetWorkersSecret(ctx context.Context, script string, req *cloudflare.WorkersPutSecretRequest) (cloudflare.WorkersPutSecretResponse, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetWorkersSecret", ctx, script, req) - ret0, _ := ret[0].(cloudflare.WorkersPutSecretResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// SetWorkersSecret indicates an expected call of SetWorkersSecret. -func (mr *MockCloudflareSecretsClientMockRecorder) SetWorkersSecret(ctx, script, req interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetWorkersSecret", reflect.TypeOf((*MockCloudflareSecretsClient)(nil).SetWorkersSecret), ctx, script, req) -} diff --git a/pkg/providers/mock_providers/consul_mock.go b/pkg/providers/mock_providers/consul_mock.go deleted file mode 100644 index 9b5c93fd..00000000 --- a/pkg/providers/mock_providers/consul_mock.go +++ /dev/null @@ -1,82 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/consul.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - api "github.com/hashicorp/consul/api" -) - -// MockConsulClient is a mock of ConsulClient interface. -type MockConsulClient struct { - ctrl *gomock.Controller - recorder *MockConsulClientMockRecorder -} - -// MockConsulClientMockRecorder is the mock recorder for MockConsulClient. -type MockConsulClientMockRecorder struct { - mock *MockConsulClient -} - -// NewMockConsulClient creates a new mock instance. -func NewMockConsulClient(ctrl *gomock.Controller) *MockConsulClient { - mock := &MockConsulClient{ctrl: ctrl} - mock.recorder = &MockConsulClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockConsulClient) EXPECT() *MockConsulClientMockRecorder { - return m.recorder -} - -// Get mocks base method. -func (m *MockConsulClient) Get(key string, q *api.QueryOptions) (*api.KVPair, *api.QueryMeta, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", key, q) - ret0, _ := ret[0].(*api.KVPair) - ret1, _ := ret[1].(*api.QueryMeta) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// Get indicates an expected call of Get. -func (mr *MockConsulClientMockRecorder) Get(key, q interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockConsulClient)(nil).Get), key, q) -} - -// List mocks base method. -func (m *MockConsulClient) List(prefix string, q *api.QueryOptions) (api.KVPairs, *api.QueryMeta, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "List", prefix, q) - ret0, _ := ret[0].(api.KVPairs) - ret1, _ := ret[1].(*api.QueryMeta) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// List indicates an expected call of List. -func (mr *MockConsulClientMockRecorder) List(prefix, q interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockConsulClient)(nil).List), prefix, q) -} - -// Put mocks base method. -func (m *MockConsulClient) Put(p *api.KVPair, q *api.WriteOptions) (*api.WriteMeta, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Put", p, q) - ret0, _ := ret[0].(*api.WriteMeta) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Put indicates an expected call of Put. -func (mr *MockConsulClientMockRecorder) Put(p, q interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Put", reflect.TypeOf((*MockConsulClient)(nil).Put), p, q) -} diff --git a/pkg/providers/mock_providers/cyberark_conjur_mock.go b/pkg/providers/mock_providers/cyberark_conjur_mock.go deleted file mode 100644 index 7ffe59ea..00000000 --- a/pkg/providers/mock_providers/cyberark_conjur_mock.go +++ /dev/null @@ -1,63 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/cyberark_conjur.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" -) - -// MockConjurClient is a mock of ConjurClient interface. -type MockConjurClient struct { - ctrl *gomock.Controller - recorder *MockConjurClientMockRecorder -} - -// MockConjurClientMockRecorder is the mock recorder for MockConjurClient. -type MockConjurClientMockRecorder struct { - mock *MockConjurClient -} - -// NewMockConjurClient creates a new mock instance. -func NewMockConjurClient(ctrl *gomock.Controller) *MockConjurClient { - mock := &MockConjurClient{ctrl: ctrl} - mock.recorder = &MockConjurClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockConjurClient) EXPECT() *MockConjurClientMockRecorder { - return m.recorder -} - -// AddSecret mocks base method. -func (m *MockConjurClient) AddSecret(variableId, secretValue string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AddSecret", variableId, secretValue) - ret0, _ := ret[0].(error) - return ret0 -} - -// AddSecret indicates an expected call of AddSecret. -func (mr *MockConjurClientMockRecorder) AddSecret(variableId, secretValue interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSecret", reflect.TypeOf((*MockConjurClient)(nil).AddSecret), variableId, secretValue) -} - -// RetrieveSecret mocks base method. -func (m *MockConjurClient) RetrieveSecret(variableId string) ([]byte, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RetrieveSecret", variableId) - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// RetrieveSecret indicates an expected call of RetrieveSecret. -func (mr *MockConjurClientMockRecorder) RetrieveSecret(variableId interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RetrieveSecret", reflect.TypeOf((*MockConjurClient)(nil).RetrieveSecret), variableId) -} diff --git a/pkg/providers/mock_providers/doppler_mock.go b/pkg/providers/mock_providers/doppler_mock.go deleted file mode 100644 index dec6c87a..00000000 --- a/pkg/providers/mock_providers/doppler_mock.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/doppler.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - reflect "reflect" - - http "github.com/DopplerHQ/cli/pkg/http" - gomock "github.com/golang/mock/gomock" -) - -// MockDopplerClient is a mock of DopplerClient interface. -type MockDopplerClient struct { - ctrl *gomock.Controller - recorder *MockDopplerClientMockRecorder -} - -// MockDopplerClientMockRecorder is the mock recorder for MockDopplerClient. -type MockDopplerClientMockRecorder struct { - mock *MockDopplerClient -} - -// NewMockDopplerClient creates a new mock instance. -func NewMockDopplerClient(ctrl *gomock.Controller) *MockDopplerClient { - mock := &MockDopplerClient{ctrl: ctrl} - mock.recorder = &MockDopplerClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockDopplerClient) EXPECT() *MockDopplerClientMockRecorder { - return m.recorder -} - -// GetSecrets mocks base method. -func (m *MockDopplerClient) GetSecrets(host string, verifyTLS bool, apiKey, project, config string) ([]byte, http.Error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSecrets", host, verifyTLS, apiKey, project, config) - ret0, _ := ret[0].([]byte) - ret1, _ := ret[1].(http.Error) - return ret0, ret1 -} - -// GetSecrets indicates an expected call of GetSecrets. -func (mr *MockDopplerClientMockRecorder) GetSecrets(host, verifyTLS, apiKey, project, config interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSecrets", reflect.TypeOf((*MockDopplerClient)(nil).GetSecrets), host, verifyTLS, apiKey, project, config) -} diff --git a/pkg/providers/mock_providers/dotenv_mock.go b/pkg/providers/mock_providers/dotenv_mock.go deleted file mode 100644 index c11e1ddb..00000000 --- a/pkg/providers/mock_providers/dotenv_mock.go +++ /dev/null @@ -1,92 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/dotenv.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" -) - -// MockDotEnvClient is a mock of DotEnvClient interface. -type MockDotEnvClient struct { - ctrl *gomock.Controller - recorder *MockDotEnvClientMockRecorder -} - -// MockDotEnvClientMockRecorder is the mock recorder for MockDotEnvClient. -type MockDotEnvClientMockRecorder struct { - mock *MockDotEnvClient -} - -// NewMockDotEnvClient creates a new mock instance. -func NewMockDotEnvClient(ctrl *gomock.Controller) *MockDotEnvClient { - mock := &MockDotEnvClient{ctrl: ctrl} - mock.recorder = &MockDotEnvClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockDotEnvClient) EXPECT() *MockDotEnvClientMockRecorder { - return m.recorder -} - -// Delete mocks base method. -func (m *MockDotEnvClient) Delete(p string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delete", p) - ret0, _ := ret[0].(error) - return ret0 -} - -// Delete indicates an expected call of Delete. -func (mr *MockDotEnvClientMockRecorder) Delete(p interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockDotEnvClient)(nil).Delete), p) -} - -// Exists mocks base method. -func (m *MockDotEnvClient) Exists(p string) (bool, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Exists", p) - ret0, _ := ret[0].(bool) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Exists indicates an expected call of Exists. -func (mr *MockDotEnvClientMockRecorder) Exists(p interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Exists", reflect.TypeOf((*MockDotEnvClient)(nil).Exists), p) -} - -// Read mocks base method. -func (m *MockDotEnvClient) Read(p string) (map[string]string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Read", p) - ret0, _ := ret[0].(map[string]string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Read indicates an expected call of Read. -func (mr *MockDotEnvClientMockRecorder) Read(p interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockDotEnvClient)(nil).Read), p) -} - -// Write mocks base method. -func (m *MockDotEnvClient) Write(p string, kvs map[string]string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Write", p, kvs) - ret0, _ := ret[0].(error) - return ret0 -} - -// Write indicates an expected call of Write. -func (mr *MockDotEnvClientMockRecorder) Write(p, kvs interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockDotEnvClient)(nil).Write), p, kvs) -} diff --git a/pkg/providers/mock_providers/etcd_mock.go b/pkg/providers/mock_providers/etcd_mock.go deleted file mode 100644 index 3bdcfaff..00000000 --- a/pkg/providers/mock_providers/etcd_mock.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/etcd.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - context "context" - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - clientv3 "go.etcd.io/etcd/client/v3" -) - -// MockEtcdClient is a mock of EtcdClient interface. -type MockEtcdClient struct { - ctrl *gomock.Controller - recorder *MockEtcdClientMockRecorder -} - -// MockEtcdClientMockRecorder is the mock recorder for MockEtcdClient. -type MockEtcdClientMockRecorder struct { - mock *MockEtcdClient -} - -// NewMockEtcdClient creates a new mock instance. -func NewMockEtcdClient(ctrl *gomock.Controller) *MockEtcdClient { - mock := &MockEtcdClient{ctrl: ctrl} - mock.recorder = &MockEtcdClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockEtcdClient) EXPECT() *MockEtcdClientMockRecorder { - return m.recorder -} - -// Get mocks base method. -func (m *MockEtcdClient) Get(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.GetResponse, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, key} - for _, a := range opts { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "Get", varargs...) - ret0, _ := ret[0].(*clientv3.GetResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockEtcdClientMockRecorder) Get(ctx, key interface{}, opts ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, key}, opts...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockEtcdClient)(nil).Get), varargs...) -} - -// Put mocks base method. -func (m *MockEtcdClient) Put(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, key, val} - for _, a := range opts { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "Put", varargs...) - ret0, _ := ret[0].(*clientv3.PutResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Put indicates an expected call of Put. -func (mr *MockEtcdClientMockRecorder) Put(ctx, key, val interface{}, opts ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, key, val}, opts...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Put", reflect.TypeOf((*MockEtcdClient)(nil).Put), varargs...) -} diff --git a/pkg/providers/mock_providers/github_mock.go b/pkg/providers/mock_providers/github_mock.go deleted file mode 100644 index 2fffe082..00000000 --- a/pkg/providers/mock_providers/github_mock.go +++ /dev/null @@ -1,98 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/github.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - context "context" - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - github "github.com/google/go-github/v43/github" -) - -// MockGitHubActionClient is a mock of GitHubActionClient interface. -type MockGitHubActionClient struct { - ctrl *gomock.Controller - recorder *MockGitHubActionClientMockRecorder -} - -// MockGitHubActionClientMockRecorder is the mock recorder for MockGitHubActionClient. -type MockGitHubActionClientMockRecorder struct { - mock *MockGitHubActionClient -} - -// NewMockGitHubActionClient creates a new mock instance. -func NewMockGitHubActionClient(ctrl *gomock.Controller) *MockGitHubActionClient { - mock := &MockGitHubActionClient{ctrl: ctrl} - mock.recorder = &MockGitHubActionClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGitHubActionClient) EXPECT() *MockGitHubActionClientMockRecorder { - return m.recorder -} - -// CreateOrUpdateRepoSecret mocks base method. -func (m *MockGitHubActionClient) CreateOrUpdateRepoSecret(ctx context.Context, owner, repo string, eSecret *github.EncryptedSecret) (*github.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOrUpdateRepoSecret", ctx, owner, repo, eSecret) - ret0, _ := ret[0].(*github.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateOrUpdateRepoSecret indicates an expected call of CreateOrUpdateRepoSecret. -func (mr *MockGitHubActionClientMockRecorder) CreateOrUpdateRepoSecret(ctx, owner, repo, eSecret interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOrUpdateRepoSecret", reflect.TypeOf((*MockGitHubActionClient)(nil).CreateOrUpdateRepoSecret), ctx, owner, repo, eSecret) -} - -// DeleteRepoSecret mocks base method. -func (m *MockGitHubActionClient) DeleteRepoSecret(ctx context.Context, owner, repo, name string) (*github.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "DeleteRepoSecret", ctx, owner, repo, name) - ret0, _ := ret[0].(*github.Response) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DeleteRepoSecret indicates an expected call of DeleteRepoSecret. -func (mr *MockGitHubActionClientMockRecorder) DeleteRepoSecret(ctx, owner, repo, name interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteRepoSecret", reflect.TypeOf((*MockGitHubActionClient)(nil).DeleteRepoSecret), ctx, owner, repo, name) -} - -// GetRepoPublicKey mocks base method. -func (m *MockGitHubActionClient) GetRepoPublicKey(ctx context.Context, owner, repo string) (*github.PublicKey, *github.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetRepoPublicKey", ctx, owner, repo) - ret0, _ := ret[0].(*github.PublicKey) - ret1, _ := ret[1].(*github.Response) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// GetRepoPublicKey indicates an expected call of GetRepoPublicKey. -func (mr *MockGitHubActionClientMockRecorder) GetRepoPublicKey(ctx, owner, repo interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRepoPublicKey", reflect.TypeOf((*MockGitHubActionClient)(nil).GetRepoPublicKey), ctx, owner, repo) -} - -// ListRepoSecrets mocks base method. -func (m *MockGitHubActionClient) ListRepoSecrets(ctx context.Context, owner, repo string, opts *github.ListOptions) (*github.Secrets, *github.Response, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListRepoSecrets", ctx, owner, repo, opts) - ret0, _ := ret[0].(*github.Secrets) - ret1, _ := ret[1].(*github.Response) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// ListRepoSecrets indicates an expected call of ListRepoSecrets. -func (mr *MockGitHubActionClientMockRecorder) ListRepoSecrets(ctx, owner, repo, opts interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListRepoSecrets", reflect.TypeOf((*MockGitHubActionClient)(nil).ListRepoSecrets), ctx, owner, repo, opts) -} diff --git a/pkg/providers/mock_providers/google_secretmanager_mock.go b/pkg/providers/mock_providers/google_secretmanager_mock.go deleted file mode 100644 index a78b3c56..00000000 --- a/pkg/providers/mock_providers/google_secretmanager_mock.go +++ /dev/null @@ -1,117 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/google_secretmanager.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - context "context" - reflect "reflect" - - secretmanager "cloud.google.com/go/secretmanager/apiv1" - gomock "github.com/golang/mock/gomock" - gax "github.com/googleapis/gax-go/v2" - secretmanager0 "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" -) - -// MockGoogleSMClient is a mock of GoogleSMClient interface. -type MockGoogleSMClient struct { - ctrl *gomock.Controller - recorder *MockGoogleSMClientMockRecorder -} - -// MockGoogleSMClientMockRecorder is the mock recorder for MockGoogleSMClient. -type MockGoogleSMClientMockRecorder struct { - mock *MockGoogleSMClient -} - -// NewMockGoogleSMClient creates a new mock instance. -func NewMockGoogleSMClient(ctrl *gomock.Controller) *MockGoogleSMClient { - mock := &MockGoogleSMClient{ctrl: ctrl} - mock.recorder = &MockGoogleSMClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGoogleSMClient) EXPECT() *MockGoogleSMClientMockRecorder { - return m.recorder -} - -// AccessSecretVersion mocks base method. -func (m *MockGoogleSMClient) AccessSecretVersion(ctx context.Context, req *secretmanager0.AccessSecretVersionRequest, opts ...gax.CallOption) (*secretmanager0.AccessSecretVersionResponse, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, req} - for _, a := range opts { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "AccessSecretVersion", varargs...) - ret0, _ := ret[0].(*secretmanager0.AccessSecretVersionResponse) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AccessSecretVersion indicates an expected call of AccessSecretVersion. -func (mr *MockGoogleSMClientMockRecorder) AccessSecretVersion(ctx, req interface{}, opts ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, req}, opts...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AccessSecretVersion", reflect.TypeOf((*MockGoogleSMClient)(nil).AccessSecretVersion), varargs...) -} - -// AddSecretVersion mocks base method. -func (m *MockGoogleSMClient) AddSecretVersion(ctx context.Context, req *secretmanager0.AddSecretVersionRequest, opts ...gax.CallOption) (*secretmanager0.SecretVersion, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, req} - for _, a := range opts { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "AddSecretVersion", varargs...) - ret0, _ := ret[0].(*secretmanager0.SecretVersion) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AddSecretVersion indicates an expected call of AddSecretVersion. -func (mr *MockGoogleSMClientMockRecorder) AddSecretVersion(ctx, req interface{}, opts ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, req}, opts...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSecretVersion", reflect.TypeOf((*MockGoogleSMClient)(nil).AddSecretVersion), varargs...) -} - -// DestroySecretVersion mocks base method. -func (m *MockGoogleSMClient) DestroySecretVersion(ctx context.Context, req *secretmanager0.DestroySecretVersionRequest, opts ...gax.CallOption) (*secretmanager0.SecretVersion, error) { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, req} - for _, a := range opts { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "DestroySecretVersion", varargs...) - ret0, _ := ret[0].(*secretmanager0.SecretVersion) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// DestroySecretVersion indicates an expected call of DestroySecretVersion. -func (mr *MockGoogleSMClientMockRecorder) DestroySecretVersion(ctx, req interface{}, opts ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, req}, opts...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DestroySecretVersion", reflect.TypeOf((*MockGoogleSMClient)(nil).DestroySecretVersion), varargs...) -} - -// ListSecrets mocks base method. -func (m *MockGoogleSMClient) ListSecrets(ctx context.Context, in *secretmanager0.ListSecretsRequest, opts ...gax.CallOption) *secretmanager.SecretIterator { - m.ctrl.T.Helper() - varargs := []interface{}{ctx, in} - for _, a := range opts { - varargs = append(varargs, a) - } - ret := m.ctrl.Call(m, "ListSecrets", varargs...) - ret0, _ := ret[0].(*secretmanager.SecretIterator) - return ret0 -} - -// ListSecrets indicates an expected call of ListSecrets. -func (mr *MockGoogleSMClientMockRecorder) ListSecrets(ctx, in interface{}, opts ...interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - varargs := append([]interface{}{ctx, in}, opts...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListSecrets", reflect.TypeOf((*MockGoogleSMClient)(nil).ListSecrets), varargs...) -} diff --git a/pkg/providers/mock_providers/gopass_mock.go b/pkg/providers/mock_providers/gopass_mock.go deleted file mode 100644 index a0f8b564..00000000 --- a/pkg/providers/mock_providers/gopass_mock.go +++ /dev/null @@ -1,80 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/gopass.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - context "context" - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - gopass "github.com/gopasspw/gopass/pkg/gopass" -) - -// MockGopassClient is a mock of GopassClient interface. -type MockGopassClient struct { - ctrl *gomock.Controller - recorder *MockGopassClientMockRecorder -} - -// MockGopassClientMockRecorder is the mock recorder for MockGopassClient. -type MockGopassClientMockRecorder struct { - mock *MockGopassClient -} - -// NewMockGopassClient creates a new mock instance. -func NewMockGopassClient(ctrl *gomock.Controller) *MockGopassClient { - mock := &MockGopassClient{ctrl: ctrl} - mock.recorder = &MockGopassClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockGopassClient) EXPECT() *MockGopassClientMockRecorder { - return m.recorder -} - -// Get mocks base method. -func (m *MockGopassClient) Get(ctx context.Context, name, revision string) (gopass.Secret, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", ctx, name, revision) - ret0, _ := ret[0].(gopass.Secret) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockGopassClientMockRecorder) Get(ctx, name, revision interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockGopassClient)(nil).Get), ctx, name, revision) -} - -// List mocks base method. -func (m *MockGopassClient) List(ctx context.Context) ([]string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "List", ctx) - ret0, _ := ret[0].([]string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// List indicates an expected call of List. -func (mr *MockGopassClientMockRecorder) List(ctx interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockGopassClient)(nil).List), ctx) -} - -// Set mocks base method. -func (m *MockGopassClient) Set(ctx context.Context, name string, sec gopass.Byter) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Set", ctx, name, sec) - ret0, _ := ret[0].(error) - return ret0 -} - -// Set indicates an expected call of Set. -func (mr *MockGopassClientMockRecorder) Set(ctx, name, sec interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Set", reflect.TypeOf((*MockGopassClient)(nil).Set), ctx, name, sec) -} diff --git a/pkg/providers/mock_providers/hashicorp_vault_mock.go b/pkg/providers/mock_providers/hashicorp_vault_mock.go deleted file mode 100644 index dc3e9992..00000000 --- a/pkg/providers/mock_providers/hashicorp_vault_mock.go +++ /dev/null @@ -1,65 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/hashicorp_vault.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - api "github.com/hashicorp/vault/api" -) - -// MockHashicorpClient is a mock of HashicorpClient interface. -type MockHashicorpClient struct { - ctrl *gomock.Controller - recorder *MockHashicorpClientMockRecorder -} - -// MockHashicorpClientMockRecorder is the mock recorder for MockHashicorpClient. -type MockHashicorpClientMockRecorder struct { - mock *MockHashicorpClient -} - -// NewMockHashicorpClient creates a new mock instance. -func NewMockHashicorpClient(ctrl *gomock.Controller) *MockHashicorpClient { - mock := &MockHashicorpClient{ctrl: ctrl} - mock.recorder = &MockHashicorpClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHashicorpClient) EXPECT() *MockHashicorpClientMockRecorder { - return m.recorder -} - -// Read mocks base method. -func (m *MockHashicorpClient) Read(path string) (*api.Secret, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Read", path) - ret0, _ := ret[0].(*api.Secret) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Read indicates an expected call of Read. -func (mr *MockHashicorpClientMockRecorder) Read(path interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Read", reflect.TypeOf((*MockHashicorpClient)(nil).Read), path) -} - -// Write mocks base method. -func (m *MockHashicorpClient) Write(path string, data map[string]interface{}) (*api.Secret, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Write", path, data) - ret0, _ := ret[0].(*api.Secret) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Write indicates an expected call of Write. -func (mr *MockHashicorpClientMockRecorder) Write(path, data interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockHashicorpClient)(nil).Write), path, data) -} diff --git a/pkg/providers/mock_providers/heroku_mock.go b/pkg/providers/mock_providers/heroku_mock.go deleted file mode 100644 index c6c05901..00000000 --- a/pkg/providers/mock_providers/heroku_mock.go +++ /dev/null @@ -1,66 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/heroku.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - context "context" - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - v5 "github.com/heroku/heroku-go/v5" -) - -// MockHerokuClient is a mock of HerokuClient interface. -type MockHerokuClient struct { - ctrl *gomock.Controller - recorder *MockHerokuClientMockRecorder -} - -// MockHerokuClientMockRecorder is the mock recorder for MockHerokuClient. -type MockHerokuClientMockRecorder struct { - mock *MockHerokuClient -} - -// NewMockHerokuClient creates a new mock instance. -func NewMockHerokuClient(ctrl *gomock.Controller) *MockHerokuClient { - mock := &MockHerokuClient{ctrl: ctrl} - mock.recorder = &MockHerokuClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHerokuClient) EXPECT() *MockHerokuClientMockRecorder { - return m.recorder -} - -// ConfigVarInfoForApp mocks base method. -func (m *MockHerokuClient) ConfigVarInfoForApp(ctx context.Context, appIdentity string) (v5.ConfigVarInfoForAppResult, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ConfigVarInfoForApp", ctx, appIdentity) - ret0, _ := ret[0].(v5.ConfigVarInfoForAppResult) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ConfigVarInfoForApp indicates an expected call of ConfigVarInfoForApp. -func (mr *MockHerokuClientMockRecorder) ConfigVarInfoForApp(ctx, appIdentity interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigVarInfoForApp", reflect.TypeOf((*MockHerokuClient)(nil).ConfigVarInfoForApp), ctx, appIdentity) -} - -// ConfigVarUpdate mocks base method. -func (m *MockHerokuClient) ConfigVarUpdate(ctx context.Context, appIdentity string, o map[string]*string) (v5.ConfigVarUpdateResult, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ConfigVarUpdate", ctx, appIdentity, o) - ret0, _ := ret[0].(v5.ConfigVarUpdateResult) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ConfigVarUpdate indicates an expected call of ConfigVarUpdate. -func (mr *MockHerokuClientMockRecorder) ConfigVarUpdate(ctx, appIdentity, o interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConfigVarUpdate", reflect.TypeOf((*MockHerokuClient)(nil).ConfigVarUpdate), ctx, appIdentity, o) -} diff --git a/pkg/providers/mock_providers/keeper_secretsmanager_mock.go b/pkg/providers/mock_providers/keeper_secretsmanager_mock.go deleted file mode 100644 index 4fb634f8..00000000 --- a/pkg/providers/mock_providers/keeper_secretsmanager_mock.go +++ /dev/null @@ -1,65 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/keeper_secretsmanager.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - core "github.com/spectralops/teller/pkg/core" -) - -// MockKsmClient is a mock of KsmClient interface. -type MockKsmClient struct { - ctrl *gomock.Controller - recorder *MockKsmClientMockRecorder -} - -// MockKsmClientMockRecorder is the mock recorder for MockKsmClient. -type MockKsmClientMockRecorder struct { - mock *MockKsmClient -} - -// NewMockKsmClient creates a new mock instance. -func NewMockKsmClient(ctrl *gomock.Controller) *MockKsmClient { - mock := &MockKsmClient{ctrl: ctrl} - mock.recorder = &MockKsmClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockKsmClient) EXPECT() *MockKsmClientMockRecorder { - return m.recorder -} - -// GetSecret mocks base method. -func (m *MockKsmClient) GetSecret(p core.KeyPath) (*core.EnvEntry, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSecret", p) - ret0, _ := ret[0].(*core.EnvEntry) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSecret indicates an expected call of GetSecret. -func (mr *MockKsmClientMockRecorder) GetSecret(p interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSecret", reflect.TypeOf((*MockKsmClient)(nil).GetSecret), p) -} - -// GetSecrets mocks base method. -func (m *MockKsmClient) GetSecrets(p core.KeyPath) ([]core.EnvEntry, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSecrets", p) - ret0, _ := ret[0].([]core.EnvEntry) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSecrets indicates an expected call of GetSecrets. -func (mr *MockKsmClientMockRecorder) GetSecrets(p interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSecrets", reflect.TypeOf((*MockKsmClient)(nil).GetSecrets), p) -} diff --git a/pkg/providers/mock_providers/keypass.kdbx b/pkg/providers/mock_providers/keypass.kdbx deleted file mode 100644 index 589fb155..00000000 Binary files a/pkg/providers/mock_providers/keypass.kdbx and /dev/null differ diff --git a/pkg/providers/mock_providers/onepassword_mock.go b/pkg/providers/mock_providers/onepassword_mock.go deleted file mode 100644 index 1787eb86..00000000 --- a/pkg/providers/mock_providers/onepassword_mock.go +++ /dev/null @@ -1,65 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/onepassword.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - reflect "reflect" - - onepassword "github.com/1Password/connect-sdk-go/onepassword" - gomock "github.com/golang/mock/gomock" -) - -// MockOnePasswordClient is a mock of OnePasswordClient interface. -type MockOnePasswordClient struct { - ctrl *gomock.Controller - recorder *MockOnePasswordClientMockRecorder -} - -// MockOnePasswordClientMockRecorder is the mock recorder for MockOnePasswordClient. -type MockOnePasswordClientMockRecorder struct { - mock *MockOnePasswordClient -} - -// NewMockOnePasswordClient creates a new mock instance. -func NewMockOnePasswordClient(ctrl *gomock.Controller) *MockOnePasswordClient { - mock := &MockOnePasswordClient{ctrl: ctrl} - mock.recorder = &MockOnePasswordClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOnePasswordClient) EXPECT() *MockOnePasswordClientMockRecorder { - return m.recorder -} - -// GetItemByTitle mocks base method. -func (m *MockOnePasswordClient) GetItemByTitle(title, vaultUUID string) (*onepassword.Item, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetItemByTitle", title, vaultUUID) - ret0, _ := ret[0].(*onepassword.Item) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetItemByTitle indicates an expected call of GetItemByTitle. -func (mr *MockOnePasswordClientMockRecorder) GetItemByTitle(title, vaultUUID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetItemByTitle", reflect.TypeOf((*MockOnePasswordClient)(nil).GetItemByTitle), title, vaultUUID) -} - -// UpdateItem mocks base method. -func (m *MockOnePasswordClient) UpdateItem(item *onepassword.Item, vaultUUID string) (*onepassword.Item, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UpdateItem", item, vaultUUID) - ret0, _ := ret[0].(*onepassword.Item) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UpdateItem indicates an expected call of UpdateItem. -func (mr *MockOnePasswordClientMockRecorder) UpdateItem(item, vaultUUID interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateItem", reflect.TypeOf((*MockOnePasswordClient)(nil).UpdateItem), item, vaultUUID) -} diff --git a/pkg/providers/mock_providers/vercel_mock.go b/pkg/providers/mock_providers/vercel_mock.go deleted file mode 100644 index 82382fc3..00000000 --- a/pkg/providers/mock_providers/vercel_mock.go +++ /dev/null @@ -1,49 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: pkg/providers/vercel.go - -// Package mock_providers is a generated GoMock package. -package mock_providers - -import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" -) - -// MockVercelClient is a mock of VercelClient interface. -type MockVercelClient struct { - ctrl *gomock.Controller - recorder *MockVercelClientMockRecorder -} - -// MockVercelClientMockRecorder is the mock recorder for MockVercelClient. -type MockVercelClientMockRecorder struct { - mock *MockVercelClient -} - -// NewMockVercelClient creates a new mock instance. -func NewMockVercelClient(ctrl *gomock.Controller) *MockVercelClient { - mock := &MockVercelClient{ctrl: ctrl} - mock.recorder = &MockVercelClientMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockVercelClient) EXPECT() *MockVercelClientMockRecorder { - return m.recorder -} - -// GetProject mocks base method. -func (m *MockVercelClient) GetProject(path string) (map[string]*string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetProject", path) - ret0, _ := ret[0].(map[string]*string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetProject indicates an expected call of GetProject. -func (mr *MockVercelClientMockRecorder) GetProject(path interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetProject", reflect.TypeOf((*MockVercelClient)(nil).GetProject), path) -} diff --git a/pkg/providers/onepassword.go b/pkg/providers/onepassword.go deleted file mode 100644 index c4aa28d8..00000000 --- a/pkg/providers/onepassword.go +++ /dev/null @@ -1,152 +0,0 @@ -package providers - -import ( - "fmt" - - "github.com/1Password/connect-sdk-go/connect" - "github.com/1Password/connect-sdk-go/onepassword" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -type OnePasswordClient interface { - GetItemByTitle(title, vaultUUID string) (*onepassword.Item, error) - UpdateItem(item *onepassword.Item, vaultUUID string) (*onepassword.Item, error) -} - -type OnePassword struct { - client OnePasswordClient - logger logging.Logger -} - -const OnePasswordName = "1password" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Description: "1Password", - Name: OnePasswordName, - Authentication: ` -To integrate with the 1Password API, you should have system-to-system secret management running in your infrastructure/localhost [more details here](https://support.1password.com/connect-deploy-docker/). - -Requires the following environment variables to be set: -` + "`OP_CONNECT_HOST`" + ` - The hostname of the 1Password Connect API -` + "`OP_CONNECT_TOKEN`" + ` - The API token to be used to authenticate the client to a 1Password Connect API. -`, - ConfigTemplate: `, - # Configure via environment variables: - # OP_CONNECT_HOST - # OP_CONNECT_TOKEN - 1password: - env_sync: - path: # Key title - source: # 1Password token gen include access to multiple vault. to get the secrets you must add and vaultUUID. the field is mandatory - env: - FOO_BAR: - path: # Key title - source: # 1Password token gen include access to multiple vault. to get the secrets you must add and vaultUUID. the field is mandatory - field: # The secret field to get. notesPlain, {label key}, password etc. -`, - Ops: core.OpMatrix{ - Put: true, - GetMapping: true, - Get: true, - }, - } - - RegisterProvider(metaInfo, NewOnePassword) -} - -func NewOnePassword(logger logging.Logger) (core.Provider, error) { - client, err := connect.NewClientFromEnvironment() - if err != nil { - return nil, err - } - return &OnePassword{client: client, logger: logger}, nil -} - -func (o *OnePassword) Put(p core.KeyPath, val string) error { - - item, err := o.getItemByTitle(p) - if err != nil { - return err - } - - for _, field := range item.Fields { - if field.Label == p.Field { - field.Value = val - o.logger.WithFields(map[string]interface{}{ - "item_id": item.ID, - "vault_id": p.Source, - }).Debug("update item") - _, err := o.client.UpdateItem(item, p.Source) - return err - } - } - - return fmt.Errorf("label %v not found", p.Field) -} - -func (o *OnePassword) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %q does not implement write multiple keys", OnePasswordName) -} - -func (o *OnePassword) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - - item, err := o.getItemByTitle(p) - if err != nil { - return nil, err - } - - entries := []core.EnvEntry{} - for _, field := range item.Fields { - entries = append(entries, p.FoundWithKey(field.Label, field.Value)) - } - - return entries, nil -} - -func (o *OnePassword) Get(p core.KeyPath) (*core.EnvEntry, error) { - - item, err := o.getItemByTitle(p) - if err != nil { - return nil, err - } - - var ent = p.Missing() - for _, field := range item.Fields { - if field.Label == p.Field || field.Label == p.Env { - ent = p.Found(field.Value) - break - } - o.logger.WithFields(map[string]interface{}{ - "field": p.Field, - "env": p.Env, - "label": field.Label, - }).Debug("item not found from list") - } - - return &ent, nil -} - -func (o *OnePassword) Delete(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", OnePasswordName) -} - -func (o *OnePassword) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", OnePasswordName) -} - -func (o *OnePassword) getItemByTitle(p core.KeyPath) (*onepassword.Item, error) { - - o.logger.WithFields(map[string]interface{}{ - "item_id": p.Path, - "vault_id": p.Source, - }).Debug("get item by title") - item, err := o.client.GetItemByTitle(p.Path, p.Source) - if err != nil { - return nil, fmt.Errorf("key %s not found in vaultUUID %s, error: %v", p.Path, p.Source, err) - } - - return item, nil -} diff --git a/pkg/providers/onepassword_test.go b/pkg/providers/onepassword_test.go deleted file mode 100644 index f869ffc9..00000000 --- a/pkg/providers/onepassword_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - - "github.com/1Password/connect-sdk-go/onepassword" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestOnePassword(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockOnePasswordClient(ctrl) - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - - out := onepassword.Item{ - Fields: []*onepassword.ItemField{ - {Label: "MG_KEY", Value: "shazam"}, - }, - } - outlist := onepassword.Item{ - Fields: []*onepassword.ItemField{ - {Label: "MG_KEY_1", Value: "mailman"}, - {Label: "MG_KEY", Value: "shazam"}, - }, - } - client.EXPECT().GetItemByTitle(gomock.Eq(path), gomock.Any()).Return(&out, nil).AnyTimes() - client.EXPECT().GetItemByTitle(gomock.Eq(pathmap), gomock.Any()).Return(&outlist, nil).AnyTimes() - s := OnePassword{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) -} - -func TestOnePasswordFailures(t *testing.T) { - ctrl := gomock.NewController(t) - defer ctrl.Finish() - client := mock_providers.NewMockOnePasswordClient(ctrl) - client.EXPECT().GetItemByTitle(gomock.Any(), gomock.Any()).Return(nil, errors.New("error")).AnyTimes() - s := OnePassword{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) - _, err = s.GetMapping(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/providers/process_env.go b/pkg/providers/process_env.go deleted file mode 100644 index 66a57475..00000000 --- a/pkg/providers/process_env.go +++ /dev/null @@ -1,100 +0,0 @@ -package providers - -import ( - "fmt" - "os" - "sort" - "strings" - - "github.com/spectralops/teller/pkg/core" - - "github.com/spectralops/teller/pkg/logging" -) - -type ProcessEnv struct { - logger logging.Logger -} - -//nolint -func init() { - metaInto := core.MetaInfo{ - Description: "ProcessEnv", - Name: "process_env", - Authentication: "No Authentication needed", - ConfigTemplate: ` - # Configure via environment: - process_env: - env: - ETC_DSN: - # Optional: accesses the environment variable 'SOME_KEY' and maps it to ETC_DSN - field: SOME_KEY -`, - Ops: core.OpMatrix{Get: true, GetMapping: true, Put: false, PutMapping: false}, - } - RegisterProvider(metaInto, NewProcessEnv) -} - -// NewProcessEnv creates new provider instance -func NewProcessEnv(logger logging.Logger) (core.Provider, error) { - return &ProcessEnv{ - logger: logger, - }, nil -} - -// Name return the provider name -func (a *ProcessEnv) Name() string { - return "process_env" -} - -// GetMapping returns a multiple entries -func (a *ProcessEnv) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - a.logger.Debug("read secret") - - kvs := make(map[string]string) - for _, envs := range os.Environ() { - pair := strings.SplitN(envs, "=", 2) //nolint: gomnd - kvs[pair[0]] = pair[1] - } - var entries []core.EnvEntry - for k, v := range kvs { - entries = append(entries, p.FoundWithKey(k, v)) - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -// Get returns a single entry -func (a *ProcessEnv) Get(p core.KeyPath) (*core.EnvEntry, error) { - a.logger.Debug("read secret") - - k := p.EffectiveKey() - val, ok := os.LookupEnv(k) - if !ok { - a.logger.WithFields(map[string]interface{}{"key": k}).Debug("key not found") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(val) - return &ent, nil -} - -// Delete will delete entry -func (a *ProcessEnv) Delete(kp core.KeyPath) error { - return fmt.Errorf("provider %s does not implement delete yet", a.Name()) -} - -// DeleteMapping will delete the given path recessively -func (a *ProcessEnv) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("provider %s does not implement deleteMapping yet", a.Name()) -} - -// Put will create a new single entry -func (a *ProcessEnv) Put(p core.KeyPath, val string) error { - return fmt.Errorf("provider %s does not implement put yet", a.Name()) -} - -// PutMapping will create a multiple entries -func (a *ProcessEnv) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %s does not implement putMapping yet", a.Name()) -} diff --git a/pkg/providers/process_env_test.go b/pkg/providers/process_env_test.go deleted file mode 100644 index cf2a3bad..00000000 --- a/pkg/providers/process_env_test.go +++ /dev/null @@ -1 +0,0 @@ -package providers diff --git a/pkg/providers/register.go b/pkg/providers/register.go deleted file mode 100644 index e38b1101..00000000 --- a/pkg/providers/register.go +++ /dev/null @@ -1,45 +0,0 @@ -package providers - -import ( - "fmt" - "strings" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -var providersMap = map[string]core.RegisteredProvider{} - -func RegisterProvider(metaInfo core.MetaInfo, builder func(logger logging.Logger) (core.Provider, error)) { - loweredProviderName := strings.ToLower(metaInfo.Name) - if _, ok := providersMap[loweredProviderName]; ok { - panic(fmt.Sprintf("provider '%s' already exists", loweredProviderName)) - } - providersMap[loweredProviderName] = core.RegisteredProvider{Meta: metaInfo, Builder: builder} -} - -func ResolveProvider(providerName string) (core.Provider, error) { - loweredProviderName := strings.ToLower(providerName) - if registeredProvider, ok := providersMap[loweredProviderName]; ok { - logger := logging.GetRoot().WithField("provider_name", loweredProviderName) - return registeredProvider.Builder(logger) - } - return nil, fmt.Errorf("provider '%s' does not exist", providerName) - -} - -func ResolveProviderMeta(providerName string) (core.MetaInfo, error) { - loweredProviderName := strings.ToLower(providerName) - if registeredProvider, ok := providersMap[loweredProviderName]; ok { - return registeredProvider.Meta, nil - } - return core.MetaInfo{}, fmt.Errorf("provider '%s' does not exist", providerName) -} - -func GetAllProvidersMeta() []core.MetaInfo { - metaInfoList := []core.MetaInfo{} - for _, value := range providersMap { - metaInfoList = append(metaInfoList, value.Meta) - } - return metaInfoList -} diff --git a/pkg/providers/vercel.go b/pkg/providers/vercel.go deleted file mode 100644 index 80b80291..00000000 --- a/pkg/providers/vercel.go +++ /dev/null @@ -1,169 +0,0 @@ -package providers - -import ( - "fmt" - "os" - "sort" - - "github.com/dghubble/sling" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" -) - -type VercelClient interface { - GetProject(path string) (map[string]*string, error) -} -type VercelAPI struct { - http *sling.Sling -} - -func NewVercelAPI(token string) *VercelAPI { - bearer := "Bearer " + token - httpClient := sling.New().Base(VercelAPIBase).Set("Authorization", bearer) - return &VercelAPI{http: httpClient} -} - -func (v *VercelAPI) GetProject(path string) (map[string]*string, error) { - projectsPath := "/v1" + ProjectEndPoint + "/" + path - project := new(VercelProject) - _, err := v.http.Get(projectsPath).ReceiveSuccess(project) - return project.envMap(), err -} - -type Vercel struct { - client VercelClient - logger logging.Logger -} - -type VercelProject struct { - Env []struct { - Key string `json:"key"` - Value string `json:"value"` - Type string `json:"type"` - } `json:"env"` -} - -func (vp *VercelProject) envMap() map[string]*string { - val := make(map[string]*string) - for i := 0; i < len(vp.Env); i++ { - // pick only plain type variables (ignore secrets) - cur := vp.Env[i] - if cur.Type == "plain" { - val[cur.Key] = &cur.Value - } - } - return val -} - -/* -https://vercel.com/docs/api#endpoints/secrets -*/ - -const VercelAPIBase = "https://api.vercel.com/" - -const ProjectEndPoint = "/projects" - -const VercelName = "vercel" - -//nolint -func init() { - metaInfo := core.MetaInfo{ - Name: "vercel", - Description: "Vercel", - Authentication: "Requires an API key populated in your environment in: `VERCEL_TOKEN`.", - ConfigTemplate: ` - # requires an API token in: VERCEL_TOKEN - vercel: - # sync a complete environment - env_sync: - path: drakula-demo - - # # pick and choose variables - # env: - # JVM_OPTS: - # path: drakula-demo -`, - Ops: core.OpMatrix{ - Get: true, - GetMapping: true, - }, - } - - RegisterProvider(metaInfo, NewVercel) -} - -func NewVercel(logger logging.Logger) (core.Provider, error) { - vercelToken := os.Getenv("VERCEL_TOKEN") - if vercelToken == "" { - return nil, fmt.Errorf("please set VERCEL_TOKEN") - } - return &Vercel{client: NewVercelAPI(vercelToken), logger: logger}, nil -} - -func (ve *Vercel) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - secret, err := ve.getSecret(p) - if err != nil { - return nil, err - } - - k := secret - entries := []core.EnvEntry{} - for k, v := range k { - val := "" - if v != nil { - val = *v - } - entries = append(entries, p.FoundWithKey(k, val)) - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -func (ve *Vercel) Get(p core.KeyPath) (*core.EnvEntry, error) { //nolint:dupl - secret, err := ve.getSecret(p) - if err != nil { - return nil, err - } - - data := secret - k := data[p.Env] - if p.Field != "" { - ve.logger.WithField("path", p.Path).Debug("`env` attribute not found in returned data. take `field` attribute") - k = data[p.Field] - } - - if k == nil { - ve.logger.WithField("path", p.Path).Debug("requested entry not found") - ent := p.Missing() - return &ent, nil - } - - ent := p.Found(*k) - return &ent, nil -} - -func (ve *Vercel) Put(p core.KeyPath, val string) error { - return fmt.Errorf("provider %q does not implement write yet", VercelName) -} -func (ve *Vercel) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %q does not implement write yet", VercelName) -} - -func (ve *Vercel) Delete(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", VercelName) -} - -func (ve *Vercel) DeleteMapping(kp core.KeyPath) error { - return fmt.Errorf("%s does not implement delete yet", VercelName) -} - -func (ve *Vercel) getSecret(kp core.KeyPath) (map[string]*string, error) { - /* https://vercel.com/docs/api#endpoints/projects/get-a-single-project */ - ve.logger.WithField("path", kp.Path).Debug("get secret") - project, err := ve.client.GetProject(kp.Path) - if err != nil { - return nil, err - } - - return project, nil -} diff --git a/pkg/providers/vercel_test.go b/pkg/providers/vercel_test.go deleted file mode 100644 index ad9d8399..00000000 --- a/pkg/providers/vercel_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package providers - -import ( - "errors" - "testing" - - "github.com/alecthomas/assert" - "github.com/golang/mock/gomock" - - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/providers/mock_providers" -) - -func TestVercel(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockVercelClient(ctrl) - // in heroku this isn't the path name, but an app name, - // but for testing it doesn't matter - path := "settings/prod/billing-svc" - pathmap := "settings/prod/billing-svc/all" - shazam := "shazam" - mailman := "mailman" - out := map[string]*string{ - "MG_KEY": &shazam, - "SMTP_PASS": &mailman, - } - client.EXPECT().GetProject(gomock.Eq(path)).Return(out, nil).AnyTimes() - client.EXPECT().GetProject(gomock.Eq(pathmap)).Return(out, nil).AnyTimes() - s := Vercel{ - client: client, - logger: GetTestLogger(), - } - AssertProvider(t, &s, true) -} - -func TestVercelFailures(t *testing.T) { - ctrl := gomock.NewController(t) - // Assert that Bar() is invoked. - defer ctrl.Finish() - client := mock_providers.NewMockVercelClient(ctrl) - client.EXPECT().GetProject(gomock.Any()).Return(nil, errors.New("error")).AnyTimes() - s := Vercel{ - client: client, - logger: GetTestLogger(), - } - _, err := s.Get(core.KeyPath{Env: "MG_KEY", Path: "settings/{{stage}}/billing-svc"}) - assert.NotNil(t, err) -} diff --git a/pkg/redactor.go b/pkg/redactor.go deleted file mode 100644 index 17835bf5..00000000 --- a/pkg/redactor.go +++ /dev/null @@ -1,60 +0,0 @@ -package pkg - -import ( - "bufio" - "fmt" - "io" - "sort" - "strings" - - "github.com/spectralops/teller/pkg/core" -) - -const ( - bufferSize = 64 * 1024 - maxBufferSize = 10 * 1024 * 1024 -) - -type Redactor struct { - io.WriteCloser - err <-chan error -} - -func NewRedactor(dist io.Writer, entries []core.EnvEntry) *Redactor { - entries = append([]core.EnvEntry(nil), entries...) - sort.Sort(core.EntriesByValueSize(entries)) - - r, w := io.Pipe() - ch := make(chan error) - go func() { - defer close(ch) - - s := bufio.NewScanner(r) - buf := make([]byte, 0, bufferSize) - s.Buffer(buf, maxBufferSize) // 10MB lines correlating to 10MB files max (bundles?) - - for s.Scan() { - line := s.Text() - for i := range entries { - line = strings.ReplaceAll(line, entries[i].Value, entries[i].RedactWith) - } - if _, err := fmt.Fprintln(dist, line); err != nil { - ch <- r.CloseWithError(err) - return - } - } - ch <- s.Err() - }() - - return &Redactor{ - WriteCloser: w, - err: ch, - } -} - -func (r *Redactor) Close() error { - err := r.WriteCloser.Close() - <-r.err - - return err -} diff --git a/pkg/redactor_test.go b/pkg/redactor_test.go deleted file mode 100644 index 1aec073a..00000000 --- a/pkg/redactor_test.go +++ /dev/null @@ -1,188 +0,0 @@ -package pkg - -import ( - "bytes" - "io" - "testing" - - "github.com/alecthomas/assert" - "github.com/spectralops/teller/pkg/core" -) - -func TestRedactorOverlap(t *testing.T) { - cases := []struct { - name string - entries []core.EnvEntry - s string - sr string - }{ - { - name: "overlap", - // in this case we don't want '123' to appear in the clear after all redactions are made. - // it can happen if the smaller secret get replaced first because both - // secrets overlap. we need to ensure the wider secrets always get - // replaced first. - entries: []core.EnvEntry{ - { - ProviderName: "test", - ResolvedPath: "/some/path", - Key: "OTHER_KEY", - Value: "hello", - RedactWith: "**OTHER_KEY**", - }, - { - ProviderName: "test", - ResolvedPath: "/some/path", - Key: "SOME_KEY", - Value: "hello123", - RedactWith: "**SOME_KEY**", - }, - }, - s: ` -func Foobar(){ - secret := "hello" - callService(secret, "hello123") - // hello, hello123 -} -`, - sr: ` -func Foobar(){ - secret := "**OTHER_KEY**" - callService(secret, "**SOME_KEY**") - // **OTHER_KEY**, **SOME_KEY** -} -`, - }, - { - name: "multiple", - entries: []core.EnvEntry{ - { - ProviderName: "test", - ResolvedPath: "/some/path", - Key: "SOME_KEY", - Value: "shazam", - RedactWith: "**SOME_KEY**", - }, - { - ProviderName: "test", - ResolvedPath: "/some/path", - Key: "OTHER_KEY", - Value: "loot", - RedactWith: "**OTHER_KEY**", - }, - }, - s: ` -func Foobar(){ - secret := "loot" - callService(secret, "shazam") -} -`, - sr: ` -func Foobar(){ - secret := "**OTHER_KEY**" - callService(secret, "**SOME_KEY**") -} -`, - }, - } - - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - buf := bytes.NewBuffer(nil) - redactor := NewRedactor(buf, c.entries) - - _, err := io.WriteString(redactor, c.s) - assert.NoError(t, err) - - err = redactor.Close() - assert.NoError(t, err) - - assert.Equal(t, buf.String(), c.sr) - }) - } -} -func TestRedactorMultiple(t *testing.T) { - entries := []core.EnvEntry{ - { - ProviderName: "test", - ResolvedPath: "/some/path", - Key: "SOME_KEY", - Value: "shazam", - RedactWith: "**SOME_KEY**", - }, - { - ProviderName: "test", - ResolvedPath: "/some/path", - Key: "OTHER_KEY", - Value: "loot", - RedactWith: "**OTHER_KEY**", - }, - } - s := ` -func Foobar(){ - secret := "loot" - callService(secret, "shazam") -} -` - sr := ` -func Foobar(){ - secret := "**OTHER_KEY**" - callService(secret, "**SOME_KEY**") -} -` - - buf := bytes.NewBuffer(nil) - redactor := NewRedactor(buf, entries) - - _, err := io.WriteString(redactor, s) - assert.NoError(t, err) - - err = redactor.Close() - assert.NoError(t, err) - - assert.Equal(t, buf.String(), sr) -} - -func TestRedactor(t *testing.T) { - entries := []core.EnvEntry{ - { - ProviderName: "test", - ResolvedPath: "/some/path", - Key: "SOME_KEY", - Value: "shazam", - RedactWith: "**NOPE**", - }, - } - s := ` -func Foobar(){ - secret := "shazam" - callService(secret, "shazam") -} -` - sr := ` -func Foobar(){ - secret := "**NOPE**" - callService(secret, "**NOPE**") -} -` - - buf := bytes.NewBuffer(nil) - redactor := NewRedactor(buf, entries) - - _, err := io.WriteString(redactor, s) - assert.NoError(t, err) - - err = redactor.Close() - assert.NoError(t, err) - - assert.Equal(t, buf.String(), sr) -} - -func TestRedactor_Close(t *testing.T) { - buf := bytes.NewBuffer(nil) - redactor := NewRedactor(buf, nil) - - assert.NoError(t, redactor.Close()) - // can be close more than once. - assert.NoError(t, redactor.Close()) -} diff --git a/pkg/teller.go b/pkg/teller.go deleted file mode 100644 index 1acaff32..00000000 --- a/pkg/teller.go +++ /dev/null @@ -1,737 +0,0 @@ -package pkg - -import ( - "bufio" - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "os" - "os/exec" - "path/filepath" - "sort" - "strings" - "text/template" - "time" - - "github.com/karrick/godirwalk" - "github.com/samber/lo" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/providers" - "gopkg.in/yaml.v3" -) - -// Teller -// Cmd - command to execute if any given. -// Porcelain - wrapping teller in a nice porcelain; in other words the textual UI for teller. -// Providers - the available providers to use. -// Entries - when loaded, these contains the mapped entries. Load them with Collect() -// Templating - Teller's templating options. -type Teller struct { - Redact bool - Cmd []string - Config *TellerFile - Porcelain *Porcelain - Populate *core.Populate - Providers Providers - Entries []core.EnvEntry - Templating *Templating - Logger logging.Logger -} - -// Create a new Teller instance, using a tellerfile, and a command to execute (if any) -func NewTeller(tlrfile *TellerFile, cmd []string, redact bool, logger logging.Logger) *Teller { - opts := core.Opts{"project": tlrfile.Project} - for k, v := range tlrfile.Opts { - opts[k] = v - } - return &Teller{ - Redact: redact, - Config: tlrfile, - Cmd: cmd, - Providers: &BuiltinProviders{}, - Populate: core.NewPopulate(opts), - Porcelain: &Porcelain{Out: os.Stderr}, - Templating: &Templating{}, - Logger: logger, - } -} - -// execute a command, and take care to sanitize the child process environment (conditionally) -func (tl *Teller) execCmd(cmd string, cmdArgs []string, withRedaction bool) error { - command := exec.Command(cmd, cmdArgs...) - if !tl.Config.CarryEnv { - command.Env = lo.Map(tl.Entries, func(ent core.EnvEntry, _ int) string { - return fmt.Sprintf("%s=%s", ent.Key, ent.Value) - }) - - command.Env = append(command.Env, lo.Map([]string{"USER", "HOME", "PATH"}, func(k string, _ int) string { return fmt.Sprintf("%s=%s", k, os.Getenv(k)) })...) - - } else { - for i := range tl.Entries { - b := tl.Entries[i] - os.Setenv(b.Key, b.Value) - } - } - - command.Stdin = os.Stdin - command.Stdout = os.Stdout - command.Stderr = os.Stderr - if withRedaction { - o := NewRedactor(command.Stdout, tl.Entries) - defer o.Close() - command.Stdout = o - - e := NewRedactor(command.Stderr, tl.Entries) - defer e.Close() - command.Stderr = e - } - - return command.Run() -} - -func (tl *Teller) PrintEnvKeys() { - tl.sortByProviderName() - tl.Porcelain.PrintContext(tl.Config.Project, tl.Config.LoadedFrom) - tl.Porcelain.VSpace(1) - tl.Porcelain.PrintEntries(tl.Entries) -} - -// Export variables into a shell sourceable format -func (tl *Teller) ExportEnv() string { - var b bytes.Buffer - - fmt.Fprintf(&b, "#!/bin/sh\n") - for i := range tl.Entries { - v := tl.Entries[i] - value := strings.ReplaceAll(v.Value, "'", "'\"'\"'") - fmt.Fprintf(&b, "export %s='%s'\n", v.Key, value) - } - return b.String() -} - -// Export variables into a .env format (basically a KEY=VAL format, that's also compatible with Docker) -func (tl *Teller) ExportDotenv() string { - var b bytes.Buffer - - for i := range tl.Entries { - v := tl.Entries[i] - fmt.Fprintf(&b, "%s=%s\n", v.Key, v.Value) - } - return b.String() -} - -func (tl *Teller) ExportYAML() (out string, err error) { - valmap := map[string]string{} - - for i := range tl.Entries { - v := tl.Entries[i] - valmap[v.Key] = v.Value - } - content, err := yaml.Marshal(valmap) - if err != nil { - return "", err - } - return string(content), nil -} - -func (tl *Teller) ExportJSON() (out string, err error) { - valmap := map[string]string{} - - for i := range tl.Entries { - v := tl.Entries[i] - valmap[v.Key] = v.Value - } - content, err := json.MarshalIndent(valmap, "", " ") - if err != nil { - return "", err - } - return string(content), nil -} - -func renderWizardTemplate(fname string, answers *core.WizardAnswers) error { - t, err := template.New("t").Parse(TellerFileTemplate) - if err != nil { - return err - } - f, err := os.Create(fname) - if err != nil { - return err - } - err = t.Execute(f, answers) - if err != nil { - return err - } - return nil -} - -// Start an interactive wizard, that will create a file when completed. -func (tl *Teller) SetupNewProject(fname string) error { - answers, err := tl.Porcelain.StartWizard() - if err != nil { - return err - } - err = renderWizardTemplate(fname, answers) - if err != nil { - return err - } - - tl.Porcelain.DidCreateNewFile(fname) - return nil -} - -// Execute a command with teller. This requires all entries to be loaded beforehand with Collect() -func (tl *Teller) RedactLines(r io.Reader, w io.Writer) error { - o := NewRedactor(w, tl.Entries) - defer o.Close() - - _, err := io.Copy(o, r) - return err -} - -// Execute a command with teller. This requires all entries to be loaded beforehand with Collect() -func (tl *Teller) Exec() { - tl.Porcelain.PrintContext(tl.Config.Project, tl.Config.LoadedFrom) - if tl.Config.Confirm != "" { - tl.Porcelain.VSpace(1) - tl.Porcelain.PrintEntries(tl.Entries) - tl.Porcelain.VSpace(1) - if !tl.Porcelain.AskForConfirmation(tl.Populate.FindAndReplace(tl.Config.Confirm)) { - return - } - } - - err := tl.execCmd(tl.Cmd[0], tl.Cmd[1:], tl.Redact) - if err != nil { - tl.Logger.WithError(err).Fatal("could not execute command") - } -} - -func hasBindata(line []byte) bool { - for _, el := range line { - if el == 0 { - return true - } - } - return false -} -func checkForMatches(path string, entries []core.EnvEntry) ([]core.Match, error) { - file, err := os.Open(path) - if err != nil { - return nil, err - } - defer file.Close() - - retval := []core.Match{} - - scanner := bufio.NewScanner(file) - //nolint - buf := make([]byte, 0, 64*1024) - //nolint - scanner.Buffer(buf, 10*1024*1024) // 10MB lines correlating to 10MB files max (bundles?) - - var lineNumber = 0 - for scanner.Scan() { - lineNumber++ - line := scanner.Bytes() - if hasBindata(line) { - // This is a binary file. Skip it! - return retval, nil - } - - linestr := string(line) - for i := range entries { - ent := entries[i] - if !ent.IsFound || ent.Value == "" || ent.Severity == core.None { - continue - } - if matchIndex := strings.Index(linestr, ent.Value); matchIndex != -1 { - m := core.Match{ - Path: path, Line: linestr, LineNumber: lineNumber, MatchIndex: matchIndex, Entry: ent} - retval = append(retval, m) - } - } - } - - if err := scanner.Err(); err != nil { - return nil, err - } - return retval, nil -} - -// Scan for entries. Each of the mapped entries is considered highly sensitive unless stated other wise (with sensitive: high|medium|low|none) -// as such, we can offer a security scan to locate those in the current codebase (if the entries are sensitive and are placed inside a vault or -// similar store, what's the purpose of hardcoding these? let's help ourselves and locate throughout all the files in the path given) -func (tl *Teller) Scan(path string, silent bool) ([]core.Match, error) { - if path == "" { - path = "." - } - - start := time.Now() - findings := []core.Match{} - err := godirwalk.Walk(path, &godirwalk.Options{ - Callback: func(osPathname string, de *godirwalk.Dirent) error { - // Following string operation is not most performant way - // of doing this, but common enough to warrant a simple - // example here: - if strings.Contains(osPathname, ".git") { - return godirwalk.SkipThis - } - if de.IsRegular() { - ms, err := checkForMatches(osPathname, tl.Entries) - if err == nil { - findings = append(findings, ms...) - } - // else { - // can't open, can't scan - // fmt.Println("error: %v", err) - // } - } - return nil - }, - Unsorted: true, // (optional) set true for faster yet non-deterministic enumeration (see godoc) - }) - - elapsed := time.Since(start) - if len(findings) > 0 && !silent { - tl.Porcelain.PrintMatches(findings) - tl.Porcelain.VSpace(1) - } - - if !silent { - tl.Porcelain.PrintMatchSummary(findings, tl.Entries, elapsed) - } - return findings, err -} - -// Template Teller vars from a given path (can be file or folder) -func (tl *Teller) Template(from, to string) error { - - fileInfo, err := os.Stat(from) - if err != nil { - return fmt.Errorf("invald path. err: %v", err) - } - - if fileInfo.IsDir() { - return tl.templateFolder(from, to) - } - - return tl.templateFile(from, to) -} - -// templateFolder scan given folder and inject Teller vars for each search file -func (tl *Teller) templateFolder(from, to string) error { - - err := godirwalk.Walk(from, &godirwalk.Options{ - Callback: func(osPathname string, de *godirwalk.Dirent) error { - if de.IsDir() { - return nil - } - copyTo := filepath.Join(to, strings.Replace(osPathname, from, "", 1)) - return tl.templateFile(osPathname, copyTo) - }, - Unsorted: true, - }) - - return err -} - -// templateFile inject Teller vars into a single file -func (tl *Teller) templateFile(from, to string) error { - tfile, err := os.ReadFile(from) - if err != nil { - return fmt.Errorf("cannot read template '%v': %v", from, err) - } - - res, err := tl.Templating.ForTemplate(string(tfile), tl.Entries) - if err != nil { - return fmt.Errorf("cannot render template '%v': %v", from, err) - } - - info, _ := os.Stat(from) - - // crate destination path if not exists - toFolder := filepath.Dir(to) - if _, err = os.Stat(toFolder); os.IsNotExist(err) { - err = os.MkdirAll(toFolder, os.ModePerm) - if err != nil { - return fmt.Errorf("cannot create folder '%v': %v", to, err) - } - } - - err = os.WriteFile(to, []byte(res), info.Mode()) - if err != nil { - return fmt.Errorf("cannot save to '%v': %v", to, err) - } - return nil -} - -func updateParams(ent *core.EnvEntry, from *core.KeyPath, pname string) { - ent.ProviderName = pname - ent.Source = from.Source - ent.Sink = from.Sink - - if from.Severity == "" { - ent.Severity = core.High - } else { - ent.Severity = from.Severity - } - - if from.RedactWith == "" { - ent.RedactWith = "**REDACTED**" - } else { - ent.RedactWith = from.RedactWith - } -} - -func (tl *Teller) CollectFromProvider(pname string) ([]core.EnvEntry, error) { - - entries := []core.EnvEntry{} - conf, ok := tl.Config.Providers[pname] - p, err := tl.Providers.GetProvider(pname) - m, _ := providers.ResolveProviderMeta(pname) - if err != nil && ok && conf.Kind != "" { - // ok, maybe same provider, with 'kind'? - p, err = tl.Providers.GetProvider(conf.Kind) - } - - // still no provider? bail. - if err != nil { - tl.Logger.Debug("provider not found in providers list with the name: %s or config kind: %s", pname, conf.Kind) - return nil, err - } - logger := tl.Logger.WithField("provider_name", m.Name) - if conf.EnvMapping != nil { - es, err := p.GetMapping(tl.Populate.KeyPath(*conf.EnvMapping)) - if err != nil { - return nil, err - } - - logger.Debug("found %d entries from env mapping", len(es)) - //nolint - for k, v := range es { - updateParams(&es[k], conf.EnvMapping, pname) - // optionally remap environment variables synced from the provider - remap := conf.EnvMapping.EffectiveRemap() - if val, ok := remap[v.Key]; ok { - if val.Field != "" { - logger.Debug("rename entry from %s to %s", v.Key, val.Field) - es[k].Key = val.Field - } - if val.Severity != "" { - es[k].Severity = val.Severity - } - if val.RedactWith != "" { - es[k].RedactWith = val.RedactWith - } - } - } - - entries = append(entries, es...) - } else { - logger.Debug("config EnvMapping not configure") - } - - logger.Debug("total fetch entries from mapping %d", len(entries)) - if conf.Env != nil { - //nolint - for k, v := range *conf.Env { - logger.Debug("get value from path: %s", k) - ent, err := p.Get(tl.Populate.KeyPath(v.WithEnv(k))) - if err != nil { - if v.Optional { - logger.Debug("optional field is set to path: %s", k) - continue - } else { - return nil, err - } - } else { - //nolint - updateParams(ent, &v, pname) - entries = append(entries, *ent) - } - } - } else { - logger.Debug("config env not configure") - } - logger.Debug("total fetch entries %d", len(entries)) - return entries, nil -} - -func (tl *Teller) CollectFromProviderMap(ps *ProvidersMap) ([]core.EnvEntry, error) { - entries := []core.EnvEntry{} - for pname := range *ps { - pents, err := tl.CollectFromProvider(pname) - if err != nil { - return nil, err - } - entries = append(entries, pents...) - } - - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} - -// The main "load all variables from all providers" logic. Walks over all definitions in the tellerfile -// and then: fetches, converts, creates a new EnvEntry. We're also mapping the sensitivity aspects of it. -// Note that for a similarly named entry - last one wins. -func (tl *Teller) Collect() error { - t := tl.Config - entries, err := tl.CollectFromProviderMap(&t.Providers) - if err != nil { - return err - } - - tl.Entries = entries - return nil -} - -func (tl *Teller) sortByProviderName() { - sort.Sort(core.EntriesByProvider(tl.Entries)) -} - -func (tl *Teller) Drift(providerNames []string) []core.DriftedEntry { - sources := map[string]core.EnvEntry{} - targets := map[string][]core.EnvEntry{} - filtering := len(providerNames) > 0 - for i := range tl.Entries { - ent := tl.Entries[i] - if filtering && !lo.Contains(providerNames, ent.ProviderName) { - continue - } - if ent.Source != "" { - sources[ent.Source+":"+ent.Key] = ent - } else if ent.Sink != "" { - k := ent.Sink + ":" + ent.Key - ents := targets[k] - if ents == nil { - targets[k] = []core.EnvEntry{ent} - } else { - targets[k] = append(ents, ent) - } - } - } - - drifts := []core.DriftedEntry{} - - //nolint - for sk, source := range sources { - ents := targets[sk] - if ents == nil { - drifts = append(drifts, core.DriftedEntry{Diff: "missing", Source: source}) - } - - for _, e := range ents { - if e.Value != source.Value { - drifts = append(drifts, core.DriftedEntry{Diff: "changed", Source: source, Target: e}) - } - } - } - - sort.Sort(core.DriftedEntriesBySource(drifts)) - return drifts -} - -func (tl *Teller) GetProviderByName(pname string) (*MappingConfig, core.Provider, error) { - pcfg, ok := tl.Config.Providers[pname] - if !ok { - return nil, nil, fmt.Errorf("provider %v not found", pname) - } - p := pname - if pcfg.Kind != "" { - p = pcfg.Kind - } - provider, err := tl.Providers.GetProvider(p) - return &pcfg, provider, err -} - -func (tl *Teller) Put(kvmap map[string]string, providerNames []string, sync bool, directPath string) error { - for _, pname := range providerNames { - pcfg, provider, err := tl.GetProviderByName(pname) - if err != nil { - return fmt.Errorf("cannot create provider %v: %v", pname, err) - } - logger := tl.Logger.WithFields(map[string]interface{}{ - "provider_name": pname, - "flag_sync": sync, - "direct_path": directPath, - }) - logger.Debug("put secret") - - useDirectPath := directPath != "" - - // XXXWIP design - decide porcelain or not, errors? - if sync { - var kvp core.KeyPath - if useDirectPath { - kvp = core.KeyPath{Path: directPath} - } else { - if pcfg.EnvMapping == nil { - return fmt.Errorf("there is no env sync mapping for provider '%v'", pname) - } - kvp = *pcfg.EnvMapping - } - kvpResolved := tl.Populate.KeyPath(kvp) - logger.Trace("calling PutMapping provider function") - err := provider.PutMapping(kvpResolved, kvmap) - if err != nil { - return fmt.Errorf("cannot put (sync) %v in provider %v: %v", kvpResolved.Path, pname, err) - } - tl.Porcelain.DidPutKVP(kvpResolved, pname, true) - } else { - if pcfg.Env == nil { - return fmt.Errorf("there is no specific key mapping to map to for provider '%v'", pname) - } - - keys := make([]string, 0, len(kvmap)) - for k := range kvmap { - keys = append(keys, k) - } - sort.Strings(keys) - for _, k := range keys { - // get the kvp for specific mapping - ok := false - var kvp core.KeyPath - - if useDirectPath { - kvp = core.KeyPath{Path: directPath} - ok = true - } else { - kvp, ok = (*pcfg.Env)[k] - } - - if ok { - kvpResolved := tl.Populate.KeyPath(kvp.WithEnv(k)) - logger.Trace("calling Put provider function") - err := provider.Put(kvpResolved, kvmap[k]) - if err != nil { - return fmt.Errorf("cannot put %v in provider %v: %v", k, pname, err) - } - tl.Porcelain.DidPutKVP(kvpResolved, pname, false) - } else { - tl.Porcelain.NoPutKVP(k, pname) - } - } - } - } - - return nil -} - -func (tl *Teller) Sync(from string, to []string, sync bool) error { - entries, err := tl.CollectFromProvider(from) - if err != nil { - return err - } - kvmap := map[string]string{} - for i := range entries { - ent := entries[i] - kvmap[ent.Key] = ent.Value - } - - err = tl.Put(kvmap, to, sync, "") - return err -} - -func (tl *Teller) MirrorDrift(source, target string) ([]core.DriftedEntry, error) { - drifts := []core.DriftedEntry{} - sourceEntries, err := tl.CollectFromProvider(source) - if err != nil { - return nil, err - } - - targetEntries, err := tl.CollectFromProvider(target) - if err != nil { - return nil, err - } - - for i := range sourceEntries { - sent := sourceEntries[i] - tentry, ok := lo.Find(targetEntries, func(ent core.EnvEntry) bool { - return sent.Key == ent.Key - }) - - if !ok { - drifts = append(drifts, core.DriftedEntry{Diff: "missing", Source: sent}) - continue - } - - if sent.Value != tentry.Value { - drifts = append(drifts, core.DriftedEntry{Diff: "changed", Source: sent, Target: tentry}) - } - } - - return drifts, nil -} - -func (tl *Teller) Delete(keys, providerNames []string, directPath string, allKeys bool) error { - if len(providerNames) == 0 { - return errors.New("at least one provider has to be specified") - } - - logger := tl.Logger.WithFields(map[string]interface{}{ - "providers": providerNames, - "allKeys": allKeys, - "direct_path": directPath, - }) - logger.Debug("delete keys") - - if len(keys) == 0 && (!allKeys || directPath == "") { - return errors.New("at least one key is expected") - } - - useDirectPath := directPath != "" - for _, pname := range providerNames { - pcfg, provider, err := tl.GetProviderByName(pname) - if err != nil { - return fmt.Errorf("cannot get provider %v: %v", pname, err) - } - - if pcfg.Env == nil { - return fmt.Errorf("there is no specific key mapping to map to for provider '%v'", pname) - } - - if allKeys && useDirectPath { - logger.WithField("path", directPath).Debug("calling DeleteMapping provider function") - err := provider.DeleteMapping(core.KeyPath{Path: directPath}) - if err != nil { - return fmt.Errorf("cannot delete path %q in provider %q: %v", directPath, pname, err) - } - - tl.Porcelain.DidDeleteP(directPath, pname) - return nil - } - - for _, key := range keys { - // get the kp for specific mapping - var ( - kp core.KeyPath - ok bool - ) - - if useDirectPath { - kp = core.KeyPath{Path: directPath} - ok = true - } else { - kp, ok = (*pcfg.Env)[key] - } - - if !ok { - tl.Porcelain.NoDeleteKP(key, pname) - continue - } - - kpResolved := tl.Populate.KeyPath(kp.WithEnv(key)) - err := provider.Delete(kpResolved) - if err != nil { - return fmt.Errorf("cannot delete %v in provider %q: %v", key, pname, err) - } - - tl.Porcelain.DidDeleteKP(kpResolved, pname) - } - } - - return nil -} diff --git a/pkg/teller_test.go b/pkg/teller_test.go deleted file mode 100644 index 33073e4f..00000000 --- a/pkg/teller_test.go +++ /dev/null @@ -1,794 +0,0 @@ -package pkg - -import ( - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "sort" - "strings" - "testing" - - "github.com/alecthomas/assert" - "github.com/spectralops/teller/pkg/core" - "github.com/spectralops/teller/pkg/logging" - "github.com/spectralops/teller/pkg/providers" -) - -// implements both Providers and Provider interface, for testing return only itself. -type InMemProvider struct { - inmem map[string]string - alwaysError bool -} - -func (im *InMemProvider) Put(p core.KeyPath, val string) error { - return fmt.Errorf("provider %q does not implement write yet", im.Name()) -} -func (im *InMemProvider) PutMapping(p core.KeyPath, m map[string]string) error { - return fmt.Errorf("provider %q does not implement write yet", im.Name()) -} - -func (im *InMemProvider) Delete(kp core.KeyPath) error { - if im.alwaysError { - return errors.New("error") - } - - k := kp.EffectiveKey() - - delete(im.inmem, fmt.Sprintf("%s/%s", kp.Path, k)) - return nil -} - -func (im *InMemProvider) DeleteMapping(kp core.KeyPath) error { - if im.alwaysError { - return errors.New("error") - } - - for key := range im.inmem { - if !strings.HasPrefix(key, kp.Path) { - continue - } - - delete(im.inmem, key) - } - - return nil -} - -func (im *InMemProvider) GetProvider(name string) (core.Provider, error) { - return im, nil //hardcode to return self -} -func (im *InMemProvider) ProviderHumanToMachine() map[string]string { - return map[string]string{ - "Inmem": "inmem", - } -} - -func (im *InMemProvider) Name() string { - return "inmem" -} - -func (im *InMemProvider) Meta() core.MetaInfo { - return core.MetaInfo{} -} - -//nolint -func init() { - inmemProviderMeta := core.MetaInfo{ - Name: "inmem-provider", - Description: "test-provider", - } - - inmemProviderErrorMeta := core.MetaInfo{ - Name: "inmem-provider-error", - Description: "test-provider-error", - } - - providers.RegisterProvider(inmemProviderMeta, NewInMemProvider) - providers.RegisterProvider(inmemProviderErrorMeta, NewInMemErrorProvider) -} - -func NewInMemProvider(logger logging.Logger) (core.Provider, error) { - return &InMemProvider{ - inmem: map[string]string{ - "prod/billing/FOO": "foo_shazam", - "prod/billing/MG_KEY": "mg_shazam", - "prod/billing/BEFORE_REMAP": "test_env_remap", - }, - alwaysError: false, - }, nil - -} - -func NewInMemErrorProvider(logger logging.Logger) (core.Provider, error) { - return &InMemProvider{ - inmem: map[string]string{ - "prod/billing/FOO": "foo_shazam", - "prod/billing/MG_KEY": "mg_shazam", - "prod/billing/BEFORE_REMAP": "test_env_remap", - }, - alwaysError: true, - }, nil - -} - -func (im *InMemProvider) GetMapping(p core.KeyPath) ([]core.EnvEntry, error) { - if im.alwaysError { - return nil, errors.New("error") - } - - var entries []core.EnvEntry - - for k, v := range im.inmem { - entries = append(entries, core.EnvEntry{ - Key: k, - Value: v, - ResolvedPath: p.Path, - ProviderName: im.Name(), - }) - } - sort.Sort(core.EntriesByKey(entries)) - return entries, nil -} -func (im *InMemProvider) Get(p core.KeyPath) (*core.EnvEntry, error) { - if im.alwaysError { - return nil, errors.New("error") - } - s := im.inmem[p.Path] - return &core.EnvEntry{ - Key: p.Env, - Value: s, - ResolvedPath: p.Path, - ProviderName: im.Name(), - }, nil -} - -func getLogger() logging.Logger { - logger := logging.New() - logger.SetLevel("null") - return logger -} - -func TestNewTeller(t *testing.T) { - tlrfile := &TellerFile{ - Project: "teller", - Opts: map[string]string{ - "foo": "bar", - }, - } - cmd := []string{"teller", "show"} - logger := getLogger() - - tl := NewTeller(tlrfile, cmd, true, logger) - - assert.True(t, tl.Redact) - assert.Equal(t, tl.Config, tlrfile) - assert.Equal(t, tl.Cmd, cmd) - assert.Equal(t, tl.Populate, core.NewPopulate(map[string]string{ - "project": "teller", - "foo": "bar", - })) - assert.Equal(t, tl.Logger, logger) -} - -func TestTellerExports(t *testing.T) { - tl := Teller{ - Logger: getLogger(), - Entries: []core.EnvEntry{}, - Providers: &BuiltinProviders{}, - } - - b := tl.ExportEnv() - assert.Equal(t, b, "#!/bin/sh\n") - - tl = Teller{ - Logger: getLogger(), - Entries: []core.EnvEntry{ - {Key: "k", Value: "v", ProviderName: "test-provider", ResolvedPath: "path/kv"}, - }, - } - - b = tl.ExportEnv() - assert.Equal(t, b, "#!/bin/sh\nexport k='v'\n") - - b, err := tl.ExportYAML() - assert.NoError(t, err) - assert.Equal(t, b, "k: v\n") - b, err = tl.ExportJSON() - assert.NoError(t, err) - assert.Equal(t, b, "{\n \"k\": \"v\"\n}") -} - -func TestTellerShExportEscaped(t *testing.T) { - tl := Teller{ - Logger: getLogger(), - Entries: []core.EnvEntry{}, - Providers: &BuiltinProviders{}, - } - - b := tl.ExportEnv() - assert.Equal(t, b, "#!/bin/sh\n") - - tl = Teller{ - Logger: getLogger(), - Entries: []core.EnvEntry{ - {Key: "k", Value: `()"';@ \(\)\"\'\;\@`, ProviderName: "test-provider", ResolvedPath: "path/kv"}, - }, - } - - b = tl.ExportEnv() - assert.Equal(t, b, "#!/bin/sh\nexport k='()\"'\"'\"';@ \\(\\)\\\"\\'\"'\"'\\;\\@'\n") -} - -func TestTellerCollect(t *testing.T) { - var b bytes.Buffer - tl := Teller{ - Logger: getLogger(), - Providers: &BuiltinProviders{}, - Porcelain: &Porcelain{ - Out: &b, - }, - Populate: core.NewPopulate(map[string]string{"stage": "prod"}), - Config: &TellerFile{ - Project: "test-project", - LoadedFrom: "nowhere", - Providers: map[string]MappingConfig{ - "inmem-provider": { - Env: &map[string]core.KeyPath{ - "MG_KEY": { - Path: "{{stage}}/billing/MG_KEY", - }, - "FOO_BAR": { - Path: "{{stage}}/billing/FOO", - }, - }, - }, - }, - }, - } - err := tl.Collect() - assert.Nil(t, err) - assert.Equal(t, len(tl.Entries), 2) - assert.Equal(t, tl.Entries[0].Key, "MG_KEY") - assert.Equal(t, tl.Entries[0].Value, "mg_shazam") - assert.Equal(t, tl.Entries[0].ResolvedPath, "prod/billing/MG_KEY") - assert.Equal(t, tl.Entries[0].ProviderName, "inmem-provider") - - assert.Equal(t, tl.Entries[1].Key, "FOO_BAR") - assert.Equal(t, tl.Entries[1].Value, "foo_shazam") - assert.Equal(t, tl.Entries[1].ResolvedPath, "prod/billing/FOO") - assert.Equal(t, tl.Entries[1].ProviderName, "inmem-provider") -} - -func TestTellerCollectWithSync(t *testing.T) { - var b bytes.Buffer - tl := Teller{ - Logger: getLogger(), - Providers: &BuiltinProviders{}, - Porcelain: &Porcelain{ - Out: &b, - }, - Populate: core.NewPopulate(map[string]string{"stage": "prod"}), - Config: &TellerFile{ - Project: "test-project", - LoadedFrom: "nowhere", - Providers: map[string]MappingConfig{ - "inmem-provider": { - EnvMapping: &core.KeyPath{ - Path: "{{stage}}/billing", - Remap: &map[string]string{ - "prod/billing/BEFORE_REMAP": "prod/billing/REMAPED", - }, - }, - }, - }, - }, - } - err := tl.Collect() - assert.Nil(t, err) - assert.Equal(t, len(tl.Entries), 3) - assert.Equal(t, tl.Entries[0].Key, "prod/billing/REMAPED") - assert.Equal(t, tl.Entries[0].Value, "test_env_remap") - assert.Equal(t, tl.Entries[0].ResolvedPath, "prod/billing") - assert.Equal(t, tl.Entries[0].ProviderName, "inmem-provider") - - assert.Equal(t, tl.Entries[1].Key, "prod/billing/MG_KEY") - assert.Equal(t, tl.Entries[1].Value, "mg_shazam") - assert.Equal(t, tl.Entries[1].ResolvedPath, "prod/billing") - assert.Equal(t, tl.Entries[1].ProviderName, "inmem-provider") - - assert.Equal(t, tl.Entries[2].Key, "prod/billing/FOO") - assert.Equal(t, tl.Entries[2].Value, "foo_shazam") - assert.Equal(t, tl.Entries[2].ResolvedPath, "prod/billing") - assert.Equal(t, tl.Entries[2].ProviderName, "inmem-provider") -} - -func TestTellerCollectWithSyncRemapWith(t *testing.T) { - var b bytes.Buffer - tl := Teller{ - Logger: getLogger(), - Providers: &BuiltinProviders{}, - Porcelain: &Porcelain{ - Out: &b, - }, - Populate: core.NewPopulate(map[string]string{"stage": "prod"}), - Config: &TellerFile{ - Project: "test-project", - LoadedFrom: "nowhere", - Providers: map[string]MappingConfig{ - "inmem-provider": { - EnvMapping: &core.KeyPath{ - Path: "{{stage}}/billing", - RemapWith: &map[string]core.RemapKeyPath{ - "prod/billing/BEFORE_REMAP": { - Field: "prod/billing/REMAPED", - Severity: core.None, - RedactWith: "-", - }, - }, - }, - }, - }, - }, - } - err := tl.Collect() - assert.Nil(t, err) - assert.Equal(t, len(tl.Entries), 3) - assert.Equal(t, tl.Entries[0].Key, "prod/billing/REMAPED") - assert.Equal(t, tl.Entries[0].Severity, core.None) - assert.Equal(t, tl.Entries[0].RedactWith, "-") - assert.Equal(t, tl.Entries[0].Value, "test_env_remap") - assert.Equal(t, tl.Entries[0].ResolvedPath, "prod/billing") - assert.Equal(t, tl.Entries[0].ProviderName, "inmem-provider") - - assert.Equal(t, tl.Entries[1].Key, "prod/billing/MG_KEY") - assert.Equal(t, tl.Entries[1].Value, "mg_shazam") - assert.Equal(t, tl.Entries[1].ResolvedPath, "prod/billing") - assert.Equal(t, tl.Entries[1].ProviderName, "inmem-provider") - - assert.Equal(t, tl.Entries[2].Key, "prod/billing/FOO") - assert.Equal(t, tl.Entries[2].Value, "foo_shazam") - assert.Equal(t, tl.Entries[2].ResolvedPath, "prod/billing") - assert.Equal(t, tl.Entries[2].ProviderName, "inmem-provider") -} - -func TestTellerCollectWithErrors(t *testing.T) { - var b bytes.Buffer - tl := Teller{ - Logger: getLogger(), - Providers: &BuiltinProviders{}, - Porcelain: &Porcelain{ - Out: &b, - }, - Populate: core.NewPopulate(map[string]string{"stage": "prod"}), - Config: &TellerFile{ - Project: "test-project", - LoadedFrom: "nowhere", - Providers: map[string]MappingConfig{ - "inmem-provider-error": { - EnvMapping: &core.KeyPath{ - Path: "{{stage}}/billing", - }, - }, - }, - }, - } - err := tl.Collect() - assert.NotNil(t, err) -} -func TestTellerPorcelainNonInteractive(t *testing.T) { - var b bytes.Buffer - - entries := []core.EnvEntry{} - - tl := Teller{ - Logger: getLogger(), - Entries: entries, - Porcelain: &Porcelain{ - Out: &b, - }, - Config: &TellerFile{ - Project: "test-project", - LoadedFrom: "nowhere", - }, - } - - tl.PrintEnvKeys() - assert.Equal(t, b.String(), "-*- teller: loaded variables for test-project using nowhere -*-\n\n") - b.Reset() - - tl.Entries = append(tl.Entries, core.EnvEntry{ - IsFound: true, - Key: "k", Value: "v", ProviderName: "test-provider", ResolvedPath: "path/kv", - }) - - tl.PrintEnvKeys() - assert.Equal(t, b.String(), "-*- teller: loaded variables for test-project using nowhere -*-\n\n[test-provider path/kv] k = v*****\n") - -} - -func TestTellerEntriesOutputSort(t *testing.T) { - var b bytes.Buffer - - entries := []core.EnvEntry{} - - tl := Teller{ - Logger: getLogger(), - Entries: entries, - Porcelain: &Porcelain{ - Out: &b, - }, - Config: &TellerFile{ - Project: "test-project", - LoadedFrom: "nowhere", - }, - } - - tl.Entries = append(tl.Entries, core.EnvEntry{ - IsFound: true, - Key: "c", Value: "c", ProviderName: "test-provider", ResolvedPath: "path/kv", - }) - tl.Entries = append(tl.Entries, core.EnvEntry{ - IsFound: true, - Key: "a", Value: "a", ProviderName: "test-provider", ResolvedPath: "path/kv", - }) - tl.Entries = append(tl.Entries, core.EnvEntry{ - IsFound: true, - Key: "b", Value: "b", ProviderName: "test-provider", ResolvedPath: "path/kv", - }) - tl.Entries = append(tl.Entries, core.EnvEntry{ - IsFound: true, - Key: "k", Value: "v", ProviderName: "alpha", ResolvedPath: "path/kv", - }) - tl.Entries = append(tl.Entries, core.EnvEntry{ - IsFound: true, - Key: "k", Value: "v", ProviderName: "BETA", ResolvedPath: "path/kv", - }) - - tl.PrintEnvKeys() - assert.Equal(t, b.String(), "-*- teller: loaded variables for test-project using nowhere -*-\n\n[alpha path/kv] k = v*****\n[BETA path/kv] k = v*****\n[test-provider path/kv] a = a*****\n[test-provider path/kv] b = b*****\n[test-provider path/kv] c = c*****\n") -} - -func TestTellerDrift(t *testing.T) { - tl := Teller{ - Logger: getLogger(), - Entries: []core.EnvEntry{ - {Key: "k", Value: "v", Source: "s1", ProviderName: "test-provider", ResolvedPath: "path/kv"}, - {Key: "k", Value: "v", Sink: "s1", ProviderName: "test-provider2", ResolvedPath: "path/kv"}, - {Key: "kX", Value: "vx", Source: "s1", ProviderName: "test-provider", ResolvedPath: "path/kv"}, - {Key: "kX", Value: "CHANGED", Sink: "s1", ProviderName: "test-provider2", ResolvedPath: "path/kv"}, - - // these do not have sink/source - {Key: "k--", Value: "00", ProviderName: "test-provider", ResolvedPath: "path/kv"}, - {Key: "k--", Value: "11", ProviderName: "test-provider2", ResolvedPath: "path/kv"}, - }, - } - - drifts := tl.Drift([]string{}) - - assert.Equal(t, len(drifts), 1) - d := drifts[0] - assert.Equal(t, d.Source.Value, "vx") - assert.Equal(t, d.Target.Value, "CHANGED") -} - -func TestTellerMirrorDrift(t *testing.T) { - tlrfile, err := NewTellerFile("../fixtures/mirror-drift/teller.yml") - if err != nil { - fmt.Printf("Error: %v", err) - os.Exit(1) - } - - tl := NewTeller(tlrfile, []string{}, false, getLogger()) - - drifts, err := tl.MirrorDrift("source", "target") - assert.NoError(t, err) - - assert.Equal(t, len(drifts), 2) - d := drifts[0] - assert.Equal(t, d.Source.Key, "THREE") - assert.Equal(t, d.Source.Value, "3") - assert.Equal(t, d.Diff, "missing") - assert.Equal(t, d.Target.Value, "") - - d = drifts[1] - assert.Equal(t, d.Source.Key, "ONE") - assert.Equal(t, d.Source.Value, "1") - assert.Equal(t, d.Diff, "changed") - assert.Equal(t, d.Target.Value, "5") -} - -func TestTellerSync(t *testing.T) { - tlrfile, err := NewTellerFile("../fixtures/sync/teller.yml") - if err != nil { - fmt.Printf("Error: %v", err) - os.Exit(1) - } - - tl := NewTeller(tlrfile, []string{}, false, getLogger()) - - err = os.WriteFile("../fixtures/sync/target.env", []byte(` -FOO=1 -`), 0644) - assert.NoError(t, err) - - err = os.WriteFile("../fixtures/sync/target2.env", []byte(` -FOO=2 -`), 0644) - - assert.NoError(t, err) - - err = tl.Sync("source", []string{"target", "target2"}, true) - - assert.NoError(t, err) - - content, err := os.ReadFile("../fixtures/sync/target.env") - assert.NoError(t, err) - - assert.Equal(t, string(content), `FOO="1" -ONE="1" -THREE="3" -TWO="2"`) - - content, err = os.ReadFile("../fixtures/sync/target2.env") - assert.NoError(t, err) - - assert.Equal(t, string(content), `FOO="2" -ONE="1" -THREE="3" -TWO="2"`) -} - -func TestTemplateFile(t *testing.T) { - - tlrfile, err := NewTellerFile("../fixtures/sync/teller.yml") - if err != nil { - fmt.Printf("Error: %v", err) - os.Exit(1) - } - - tl := NewTeller(tlrfile, []string{}, false, getLogger()) - tl.Entries = append(tl.Entries, core.EnvEntry{Key: "TEST-PLACEHOLDER", Value: "secret-here"}) - - tempFolder, _ := os.MkdirTemp(os.TempDir(), "test-template") - defer os.RemoveAll(tempFolder) - - templatePath := filepath.Join(tempFolder, "target.tpl") // prepare template file path - destinationPath := filepath.Join(tempFolder, "starget.envs") // prepare destination file path - - err = os.WriteFile(templatePath, []byte(`Hello, {{.Teller.EnvByKey "TEST-PLACEHOLDER" "default-value" }}!`), 0644) - assert.NoError(t, err) - - err = tl.templateFile(templatePath, destinationPath) - assert.NoError(t, err) - - txt, err := ioutil.ReadFile(destinationPath) - assert.NoError(t, err) - assert.Equal(t, string(txt), "Hello, secret-here!") - -} - -func TestTemplateFolder(t *testing.T) { - - tlrfile, err := NewTellerFile("../fixtures/sync/teller.yml") - if err != nil { - fmt.Printf("Error: %v", err) - os.Exit(1) - } - - tl := NewTeller(tlrfile, []string{}, false, getLogger()) - tl.Entries = append(tl.Entries, core.EnvEntry{Key: "TEST-PLACEHOLDER", Value: "secret-here"}) - tl.Entries = append(tl.Entries, core.EnvEntry{Key: "TEST-PLACEHOLDER-2", Value: "secret2-here"}) - - rootTempDir := os.TempDir() - tempFolder, _ := os.MkdirTemp(rootTempDir, "test-template") // create temp root folder - // Create template folders structure - templateFolder := filepath.Join(tempFolder, "from") - err = os.MkdirAll(templateFolder, os.ModePerm) - assert.NoError(t, err) - err = os.MkdirAll(filepath.Join(templateFolder, "folder1", "folder2"), os.ModePerm) - assert.NoError(t, err) - - // copy to: - copyToFolder := filepath.Join(tempFolder, "to") - - err = os.MkdirAll(copyToFolder, os.ModePerm) - assert.NoError(t, err) - - defer os.RemoveAll(tempFolder) - - err = os.WriteFile(filepath.Join(templateFolder, "target.tpl"), []byte(`Hello, {{.Teller.EnvByKey "TEST-PLACEHOLDER" "default-value" }}!`), 0644) - assert.NoError(t, err) - err = os.WriteFile(filepath.Join(templateFolder, "folder1", "folder2", "target2.tpl"), []byte(`Hello, {{.Teller.EnvByKey "TEST-PLACEHOLDER-2" "default-value" }}!`), 0644) - assert.NoError(t, err) - - err = tl.templateFolder(templateFolder, copyToFolder) - assert.NoError(t, err) - fmt.Println(copyToFolder) - - txt, err := ioutil.ReadFile(filepath.Join(copyToFolder, "target.tpl")) - assert.NoError(t, err) - assert.Equal(t, string(txt), "Hello, secret-here!") - - txt, err = ioutil.ReadFile(filepath.Join(copyToFolder, "folder1", "folder2", "target2.tpl")) - assert.NoError(t, err) - assert.Equal(t, string(txt), "Hello, secret2-here!") - -} - -func TestTellerDelete(t *testing.T) { - fooPath := "/sample/path/FOO" - p := &InMemProvider{ - inmem: map[string]string{ - fooPath: "foo", - "/sample/path/BAR": "bar", - }, - alwaysError: false, - } - tl := Teller{ - Logger: getLogger(), - Providers: p, - Porcelain: &Porcelain{ - Out: ioutil.Discard, - }, - Populate: core.NewPopulate(map[string]string{"stage": "prod"}), - Config: &TellerFile{ - Project: "test-project", - LoadedFrom: "nowhere", - Providers: map[string]MappingConfig{ - "inmem-provider": { - Env: &map[string]core.KeyPath{ - "FOO": { - Path: "/sample/path", - Env: "FOO", - }, - "BAR": { - Path: "/sample/path", - Env: "BAR", - }, - }, - }, - }, - }, - } - - keysToDelete := []string{"FOO"} - err := tl.Delete(keysToDelete, []string{"inmem-provider"}, "", false) - assert.NoError(t, err) - - assert.Equal(t, len(p.inmem), 1) - _, ok := p.inmem[fooPath] - assert.False(t, ok) - - keysToDelete = []string{"BAR"} - err = tl.Delete(keysToDelete, []string{"inmem-provider"}, "/sample/path", false) - assert.NoError(t, err) - - assert.Equal(t, len(p.inmem), 0) -} - -func TestTellerDeleteAll(t *testing.T) { - p := &InMemProvider{ - inmem: map[string]string{ - "/sample/path/FOO": "foo", - "/sample/path/BAR": "bar", - }, - alwaysError: false, - } - tl := Teller{ - Logger: getLogger(), - Providers: p, - Porcelain: &Porcelain{ - Out: ioutil.Discard, - }, - Populate: core.NewPopulate(map[string]string{"stage": "prod"}), - Config: &TellerFile{ - Project: "test-project", - LoadedFrom: "nowhere", - Providers: map[string]MappingConfig{ - "inmem-provider": { - Env: &map[string]core.KeyPath{ - "FOO": { - Path: "/sample/path", - Env: "FOO", - }, - "BAR": { - Path: "/sample/path", - Env: "BAR", - }, - }, - }, - }, - }, - } - - err := tl.Delete([]string{}, []string{"inmem-provider"}, "/sample/path", true) - assert.NoError(t, err) - - assert.Equal(t, len(p.inmem), 0) -} - -func TestTeller_execCmd(t *testing.T) { - cmd := "bash" - cmdArgs := []string{"-c", "for i in {1..3}; do echo $SOME_KEY; echo $OTHER_KEY 1>&2; done"} - entries := []core.EnvEntry{ - { - ProviderName: "test", - ResolvedPath: "/some/path", - Key: "OTHER_KEY", - Value: "hello", - RedactWith: "**OTHER_KEY**", - }, - { - ProviderName: "test", - ResolvedPath: "/some/path", - Key: "SOME_KEY", - Value: "hello123", - RedactWith: "**SOME_KEY**", - }, - } - - tests := []struct { - name string - carryEnv bool - withRedaction bool - }{ - { - name: "CarryEnv: false, withRedaction: false", - carryEnv: false, - withRedaction: false, - }, - { - name: "CarryEnv: true, withRedaction: false", - carryEnv: true, - withRedaction: false, - }, - { - name: "CarryEnv: false, withRedaction: true", - carryEnv: false, - withRedaction: true, - }, - { - name: "CarryEnv: true, withRedaction: true", - carryEnv: true, - withRedaction: true, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - oldStdout, oldStderr := os.Stdout, os.Stderr - t.Cleanup(func() { - os.Stdout, os.Stderr = oldStdout, oldStderr - }) - - var err error - os.Stdout, err = os.CreateTemp(t.TempDir(), "stdout") - assert.NoError(t, err) - os.Stderr, err = os.CreateTemp(t.TempDir(), "stderr") - assert.NoError(t, err) - - tl := &Teller{ - Config: &TellerFile{ - CarryEnv: tt.carryEnv, - }, - Entries: entries, - } - assert.NoError(t, tl.execCmd(cmd, cmdArgs, tt.withRedaction)) - - os.Stdout.Seek(0, io.SeekStart) - o, _ := io.ReadAll(os.Stdout) - os.Stderr.Seek(0, io.SeekStart) - e, _ := io.ReadAll(os.Stderr) - if tt.withRedaction { - assert.Equal(t, "**SOME_KEY**\n**SOME_KEY**\n**SOME_KEY**\n", string(o)) - assert.Equal(t, "**OTHER_KEY**\n**OTHER_KEY**\n**OTHER_KEY**\n", string(e)) - } else { - assert.Equal(t, "hello123\nhello123\nhello123\n", string(o)) - assert.Equal(t, "hello\nhello\nhello\n", string(e)) - } - }) - } -} diff --git a/pkg/tellerfile.go b/pkg/tellerfile.go deleted file mode 100644 index bf66879d..00000000 --- a/pkg/tellerfile.go +++ /dev/null @@ -1,38 +0,0 @@ -package pkg - -import ( - "os" - - "github.com/spectralops/teller/pkg/core" - "gopkg.in/yaml.v2" -) - -type ProvidersMap map[string]MappingConfig -type TellerFile struct { - Opts map[string]string `yaml:"opts,omitempty"` - Confirm string `yaml:"confirm,omitempty"` - Project string `yaml:"project,omitempty"` - CarryEnv bool `yaml:"carry_env,omitempty"` - Providers ProvidersMap `yaml:"providers,omitempty"` - LoadedFrom string -} - -type MappingConfig struct { - Kind string `yaml:"kind,omitempty"` - EnvMapping *core.KeyPath `yaml:"env_sync,omitempty"` - Env *map[string]core.KeyPath `yaml:"env,omitempty"` -} - -func NewTellerFile(s string) (*TellerFile, error) { - yamlFile, err := os.ReadFile(s) - if err != nil { - return nil, err - } - t := &TellerFile{} - err = yaml.Unmarshal(yamlFile, t) - if err != nil { - return nil, err - } - t.LoadedFrom = s - return t, nil -} diff --git a/pkg/templating.go b/pkg/templating.go deleted file mode 100644 index c1167db5..00000000 --- a/pkg/templating.go +++ /dev/null @@ -1,42 +0,0 @@ -package pkg - -import ( - "bytes" - "text/template" - - "github.com/spectralops/teller/pkg/core" -) - -type Templating struct { -} -type viewmodel struct { - Teller *core.EnvEntryLookup -} - -func (t *Templating) New() *Templating { - return &Templating{} -} - -func (t *Templating) ForTemplate(tmpl string, entries []core.EnvEntry) (string, error) { - lookup := core.EnvEntryLookup{ - Entries: entries, - } - - tt, err := template.New("t").Parse(tmpl) - if err != nil { - return "", err - } - - var output bytes.Buffer - - err = tt.Execute(&output, viewmodel{Teller: &lookup}) - if err != nil { - return "", err - } - - return output.String(), nil -} - -func (t *Templating) ForGlob() *Templating { - return &Templating{} -} diff --git a/pkg/templating_test.go b/pkg/templating_test.go deleted file mode 100644 index 3c3113e4..00000000 --- a/pkg/templating_test.go +++ /dev/null @@ -1,9 +0,0 @@ -package pkg - -import ( - "testing" -) - -func TestTemplating(t *testing.T) { - //assert.Fail(t) -} diff --git a/pkg/utils/files.go b/pkg/utils/files.go deleted file mode 100644 index 5c66be1a..00000000 --- a/pkg/utils/files.go +++ /dev/null @@ -1,28 +0,0 @@ -package utils - -import ( - "os" - "path/filepath" -) - -const ( - filePermission = 0600 -) - -func WriteFileInPath(filename, to string, content []byte) error { - if to != "" { - if _, err := os.Stat(to); os.IsNotExist(err) { - err = os.MkdirAll(to, os.ModePerm) - if err != nil { - return err - } - } - } - err := os.WriteFile(filepath.Join(to, filename), content, filePermission) - - if err != nil { - return err - } - - return nil -} diff --git a/pkg/utils/strings.go b/pkg/utils/strings.go deleted file mode 100644 index eb8bb507..00000000 --- a/pkg/utils/strings.go +++ /dev/null @@ -1,20 +0,0 @@ -package utils - -import "strings" - -func LastSegment(s string) string { - segs := strings.Split(s, "/") - return segs[len(segs)-1] -} - -func Merge(first, second map[string]string) map[string]string { - target := make(map[string]string) - for k, v := range first { - target[k] = v - } - for k, v := range second { - target[k] = v - } - - return target -} diff --git a/pkg/wizard_template.go b/pkg/wizard_template.go deleted file mode 100644 index cc5bd54f..00000000 --- a/pkg/wizard_template.go +++ /dev/null @@ -1,303 +0,0 @@ -package pkg - -var TellerFileTemplate = ` -project: {{.Project}} -{{- if .Confirm }} -confirm: Are you sure you want to run on {{"{{stage}}"}}? -{{ end }} - -# Set this if you want to carry over parent process' environment variables -# carry_env: true - - -# -# Variables -# -# Feel free to add options here to be used as a variable throughout -# paths. -# -opts: - region: env:AWS_REGION # you can get env variables with the 'env:' prefix, for default values if env not found use comma. Example: env:AWS_REGION,{DEFAULT_VALUE} - stage: development - - -# -# Providers -# -providers: - -{{- if index .ProviderKeys "heroku" }} - # requires an API key in: HEROKU_API_KEY (you can fetch yours from ~/.netrc) - heroku: - # sync a complete environment - env_sync: - path: drakula-demo - - # # pick and choose variables - # env: - # JVM_OPTS: - # path: drakula-demo -{{end}} - -{{- if index .ProviderKeys "vercel" }} - # requires an API token in: VERCEL_TOKEN - vercel: - # sync a complete environment - env_sync: - path: drakula-demo - - # # pick and choose variables - # env: - # JVM_OPTS: - # path: drakula-demo -{{end}} - -{{- if index .ProviderKeys "hashicorp_vault" }} - # configure only from environment - # https://github.com/hashicorp/vault/blob/api/v1.0.4/api/client.go#L28 - # this vars should not go through to the executing cmd - hashicorp_vault: - env_sync: - path: secret/data/{{"{{stage}}"}}/billing/web/env - env: - SMTP_PASS: - path: secret/data/{{"{{stage}}"}}/wordpress - field: smtp -{{end}} - -{{- if index .ProviderKeys "aws_secretsmanager" }} - # configure only from environment - # filter secret versioning by adding comma separating in path value (path: prod/foo/bar,). - aws_secretsmanager: - env_sync: - path: prod/foo/bar - env: - FOO_BAR: - path: prod/foo/bar - field: SOME_KEY -{{end}} - -{{- if index .ProviderKeys "aws_ssm" }} - # configure only from environment - aws_ssm: - env: - FOO_BAR: - path: /prod/foobar - decrypt: true -{{end}} - -{{- if index .ProviderKeys "google_secretmanager" }} - # GOOGLE_APPLICATION_CREDENTIALS=foobar.json - # https://cloud.google.com/secret-manager/docs/reference/libraries#setting_up_authentication - google_secretmanager: - env: - FOO_GOOG: - # need to supply the relevant version (versions/1) - path: projects/123/secrets/FOO_GOOG/versions/1 -{{end}} - -{{- if index .ProviderKeys "etcd" }} - # Configure via environment: - # ETCDCTL_ENDPOINTS - # tls: - # ETCDCTL_CA_FILE - # ETCDCTL_CERT_FILE - # ETCDCTL_KEY_FILE - etcd: - env_sync: - path: /prod/foo - env: - ETC_DSN: - path: /prod/foo/bar -{{end}} - -{{- if index .ProviderKeys "consul" }} - # Configure via environment: - # CONSUL_HTTP_ADDR - consul: - env_sync: - path: redis/config - env: - ETC_DSN: - path: redis/config/foobar -{{end}} - -{{- if index .ProviderKeys "dotenv" }} - # you can mix and match many files - dotenv: - env_sync: - path: ~/my-dot-env.env - env: - FOO_BAR: - path: ~/my-dot-env.env -{{end}} - -{{- if index .ProviderKeys "azure_keyvault" }} - # you can mix and match many files - azure_keyvault: - env_sync: - path: azure - env: - FOO_BAR: - path: foobar -{{end}} - -{{- if index .ProviderKeys "doppler" }} - # set your doppler project with "doppler configure set project " - doppler: - env_sync: - path: prd - env: - FOO_BAR: - path: prd -{{end}} - -{{- if index .ProviderKeys "cyberark_conjur" }} - # https://conjur.org - # set CONJUR_AUTHN_LOGIN and CONJUR_AUTHN_API_KEY env vars - # set .conjurrc file in user's home directory - cyberark_conjur: - env: - FOO_BAR: - path: /secrets/foo/bar -{{end}} - -{{- if index .ProviderKeys "1password" }} - # Configure via environment variables: - # OP_CONNECT_HOST - # OP_CONNECT_TOKEN - 1password: - env_sync: - path: # Key title - source: # 1Password token gen include access to multiple vault. to get the secrets you must add and vaultUUID. the field is mandatory - env: - FOO_BAR: - path: # Key title - source: # 1Password token gen include access to multiple vault. to get the secrets you must add and vaultUUID. the field is mandatory - field: # The secret field to get. notesPlain, {label key}, password etc. -{{end}} - -{{- if index .ProviderKeys "gopass" }} - # Override default configuration: https://github.com/gopasspw/gopass/blob/master/docs/config.md - gopass: - env_sync: - path: foo - env: - ETC_DSN: - path: foo/bar -{{end}} - -{{- if index .ProviderKeys "lastpass" }} - # Configure via environment variables: - # LASTPASS_USERNAME - # LASTPASS_PASSWORD - - lastpass: - env_sync: - path: # LastPass item ID - env: - ETC_DSN: - path: # Lastpass item ID - # field: by default taking password property. in case you want other property un-mark this line and set the lastpass property name. -{{end}} - -{{- if index .ProviderKeys "cloudflare_workers_secrets" }} - - # Configure via environment variables for integration: - # CLOUDFLARE_API_KEY: Your Cloudflare api key. - # CLOUDFLARE_API_EMAIL: Your email associated with the api key. - # CLOUDFLARE_ACCOUNT_ID: Your account ID. - - cloudflare_workers_secrets: - env_sync: - source: # Mandatory: script field - env: - script-value: - path: foo-secret - source: # Mandatory: script field -{{end}} - -{{- if index .ProviderKeys "github" }} - - # Configure via environment variables for integration: - # GITHUB_AUTH_TOKEN: GitHub token - - github: - env_sync: - path: owner/github-repo - env: - script-value: - path: owner/github-repo - -{{end}} - -{{- if index .ProviderKeys "keypass" }} - - # Configure via environment variables for integration: - # KEYPASS_PASSWORD: KeyPass password - # KEYPASS_DB_PATH: Path to DB file - - keypass: - env_sync: - path: redis/config - # source: Optional, all fields is the default. Supported fields: Notes, Title, Password, URL, UserName - env: - ETC_DSN: - path: redis/config/foobar - # source: Optional, Password is the default. Supported fields: Notes, Title, Password, URL, UserName - -{{end}} - -{{- if index .ProviderKeys "filesystem" }} - - filesystem: - env_sync: - path: redis/config - env: - ETC_DSN: - path: redis/config/foobar - -{{end}} - -{{- if index .ProviderKeys "process_env" }} - - process_env: - env: - ETC_DSN: - field: SOME_KEY # Optional, accesses the environment variable SOME_KEY and maps it to ETC_DSN - -{{end}} - -{{- if index .ProviderKeys "ansible_vault" }} - - # Configure via environment variables for integration: - # ANSIBLE_VAULT_PASSPHRASE: Ansible Vault Password - - ansible_vault: - env_sync: - path: ansible/vars/vault_{{stage}}.yml - - env: - KEY1: - path: ansible/vars/vault_{{stage}}.yml - NONEXIST_KEY: - path: ansible/vars/vault_{{stage}}.yml - -{{end}} - -{{- if index .ProviderKeys "keeper_secretsmanager" }} - - # requires a configuration in: KSM_CONFIG=base64_config or file path KSM_CONFIG_FILE=ksm_config.json - keeper_secretsmanager: - env_sync: - path: RECORD_UID - # all non-empty fields are mapped by their labels, if empty then by field type, and index 1,2,...,N - - env: - USER: - path: RECORD_UID/field/login - # use Keeper Notation to select individual field values - # https://docs.keeper.io/secrets-manager/secrets-manager/about/keeper-notation - -{{end}} -` diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 00000000..5d56faf9 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "nightly" diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..2d9cafa5 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,3 @@ +unstable_features = true +group_imports = "StdExternalCrate" +format_strings = true diff --git a/rustwrap.yaml b/rustwrap.yaml new file mode 100644 index 00000000..2c4ec9ed --- /dev/null +++ b/rustwrap.yaml @@ -0,0 +1,33 @@ +# replace everything that starts with __V_ + +targets: + - platform: win32 + arch: x64 + url_template: https://github.com/tellerops/teller/releases/download/v__VERSION__/teller-x86_64-windows.zip + archive: dist/releases/teller-x86_64-windows.zip + - platform: linux + arch: x64 + url_template: https://github.com/tellerops/teller/releases/download/v__VERSION__/teller-x86_64-linux.tar.xz + archive: dist/releases/teller-x86_64-linux.tar.xz + - platform: darwin + arch: arm64 + url_template: https://github.com/tellerops/teller/releases/download/v__VERSION__/teller-aarch64-macos.tar.xz + archive: dist/releases/teller-aarch64-macos.tar.xz + +brew: + name: teller + publish: false +s/homebrew-tap + recipe_fname: teller.rb + recipe_template: | + class Teller < Formula + desc "desc" + homepage "http://github.com/tellerops/teller" + url "__URL__[arm64]" + version "__VERSION__" + sha256 "__SHA__[arm64]" + + def install + bin.install "teller" + end + end diff --git a/teller-cli/Cargo.toml b/teller-cli/Cargo.toml new file mode 100644 index 00000000..05694271 --- /dev/null +++ b/teller-cli/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "teller-cli" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +serde_yaml = { workspace = true } +serde_derive = { workspace = true } +fs-err = "2.9.0" +eyre = "0.6.8" +thiserror = { workspace = true } +tokio = { workspace = true } +# async-trait = "*" +tracing = "^0.1.34" +tracing-tree = { version = "0.2.1" } +tracing-subscriber = { version = "^0.3.11", features = ["env-filter"] } +strum = { workspace = true } +proc-macro2 = "1.0.63" # Remove once https://github.com/rust-lang/rust/issues/113152 is fixed. +clap = { version = "4.3.0", features = ["cargo", "derive"] } +exitcode = { version = "^1.1.2" } +console = { version = "*" } +comfy-table = { version = "*" } +dialoguer = { version = "0.11.0" } +teller-providers = { version = "*", path = "../teller-providers" } +teller-core = { version = "*", path = "../teller-core" } + +[dev-dependencies] +insta = { workspace = true } +dockertest-server = { version = "0.1.7", features = ["hashi", "cloud"] } +trycmd = "0.14.10" + +[[bin]] +name = "teller" diff --git a/teller-cli/fixtures/config.yml b/teller-cli/fixtures/config.yml new file mode 100644 index 00000000..79d6c0f7 --- /dev/null +++ b/teller-cli/fixtures/config.yml @@ -0,0 +1,18 @@ +providers: + hashi_1: + kind: hashicorp # name is = kind if empty + maps: + - id: test + path: /{{ get_env(name="TEST_LOAD_1", default="test") }}/users/user1 + # if empty, map everything + # == means map to same key name + # otherwise key on left becomes right + # in the future: key_transform: camelize, snake_case for automapping the keys + keys: + GITHUB_TOKEN: == + mg: FOO_BAR + dot_1: + kind: dotenv # name is = kind if empty + maps: + - id: test + path: VAR_{{ get_env(name="STAGE", default="development") }} diff --git a/teller-cli/fixtures/dotenv.yml b/teller-cli/fixtures/dotenv.yml new file mode 100644 index 00000000..7b5f2d18 --- /dev/null +++ b/teller-cli/fixtures/dotenv.yml @@ -0,0 +1,6 @@ +providers: + dot_1: + kind: dotenv + maps: + - id: test + path: fixtures/vars.env diff --git a/teller-cli/fixtures/flow.env b/teller-cli/fixtures/flow.env new file mode 100644 index 00000000..1d7b8023 --- /dev/null +++ b/teller-cli/fixtures/flow.env @@ -0,0 +1,3 @@ + +FOO=bar +HELLO=world diff --git a/teller-cli/fixtures/flow_test.yml b/teller-cli/fixtures/flow_test.yml new file mode 100644 index 00000000..8dfff147 --- /dev/null +++ b/teller-cli/fixtures/flow_test.yml @@ -0,0 +1,39 @@ +providers: + hashi_1: + kind: hashicorp + options: + address: {{ address }} + token: {{ token }} + maps: + - id: pg-dev + path: secret/dev/postgres + protocol: kv2 + sm_1: + kind: aws_secretsmanager + options: + region: us-east-1 + access_key_id: stub + secret_access_key: stub + provider_name: faked + endpoint_url: {{ endpoint_url }} + maps: + - id: pg-dev + path: /dev/postgres + ssm_1: + kind: ssm + options: + region: us-east-1 + access_key_id: stub + secret_access_key: stub + provider_name: faked + endpoint_url: {{ endpoint_url }} + maps: + - id: pg-dev + path: /dev/postgres + keys: + USER: USER_NAME + dot_1: + kind: dotenv + maps: + - id: tvars + path: fixtures/flow_test_vars.env diff --git a/teller-cli/fixtures/flow_test_vars.env b/teller-cli/fixtures/flow_test_vars.env new file mode 100644 index 00000000..8a9b809a --- /dev/null +++ b/teller-cli/fixtures/flow_test_vars.env @@ -0,0 +1 @@ +USER_NAME=linus diff --git a/teller-cli/fixtures/google_sm_integration.yml b/teller-cli/fixtures/google_sm_integration.yml new file mode 100644 index 00000000..d741ed4a --- /dev/null +++ b/teller-cli/fixtures/google_sm_integration.yml @@ -0,0 +1,12 @@ +providers: + gsm1: + kind: google_secretmanager + maps: + - id: test + path: projects/{{ get_env(name="TEST_PROVIDER_GSM_PROJECT", default="test") }} + # if empty, map everything + # == means map to same key name + # otherwise key on left becomes right + # in the future: key_transform: camelize, snake_case for automapping the keys + keys: + TLR_TEST_SKRT: == diff --git a/teller-cli/fixtures/hashi.yml b/teller-cli/fixtures/hashi.yml new file mode 100644 index 00000000..eea66ff2 --- /dev/null +++ b/teller-cli/fixtures/hashi.yml @@ -0,0 +1,14 @@ +providers: + hashi_1: + kind: hashicorp # name is = kind if empty + maps: + - id: test + path: data1/mysecret + protocol: kv1 + # if empty, map everything + # == means map to same key name + # otherwise key on left becomes right + # in the future: key_transform: camelize, snake_case for automapping the keys + keys: + GITHUB_TOKEN: == + a: == diff --git a/teller-cli/fixtures/scan/content.bin b/teller-cli/fixtures/scan/content.bin new file mode 100644 index 00000000..bd812fcc Binary files /dev/null and b/teller-cli/fixtures/scan/content.bin differ diff --git a/teller-cli/fixtures/scan/has-matches.txt b/teller-cli/fixtures/scan/has-matches.txt new file mode 100644 index 00000000..cac8fb16 --- /dev/null +++ b/teller-cli/fixtures/scan/has-matches.txt @@ -0,0 +1,5 @@ +hello world, + +this should match: trooper123. + +done. diff --git a/teller-cli/fixtures/scan/multiple.txt b/teller-cli/fixtures/scan/multiple.txt new file mode 100644 index 00000000..2652c63c --- /dev/null +++ b/teller-cli/fixtures/scan/multiple.txt @@ -0,0 +1,6 @@ +all of these should match: + this: pass1 + and that: pass1 + and also, + pass1 + \ No newline at end of file diff --git a/teller-cli/fixtures/scan/nested/nested-match.txt b/teller-cli/fixtures/scan/nested/nested-match.txt new file mode 100644 index 00000000..129cb721 --- /dev/null +++ b/teller-cli/fixtures/scan/nested/nested-match.txt @@ -0,0 +1,5 @@ +hello world, + +this should match: nested111. + +done. diff --git a/teller-cli/fixtures/scan/no-matches.txt b/teller-cli/fixtures/scan/no-matches.txt new file mode 100644 index 00000000..e5f1ae98 --- /dev/null +++ b/teller-cli/fixtures/scan/no-matches.txt @@ -0,0 +1 @@ +this should not match diff --git a/teller-cli/fixtures/smoke.yml b/teller-cli/fixtures/smoke.yml new file mode 100644 index 00000000..b6fc32fd --- /dev/null +++ b/teller-cli/fixtures/smoke.yml @@ -0,0 +1,22 @@ +providers: + ssm_1: + kind: ssm + maps: + - id: ssm-prod + path: /ssm/prod + keys: + GITHUB_TOKEN: == + mg: FOO_BAR + hashi_1: + kind: hashicorp + maps: + - id: hashi-stg + path: /hashi/staging + keys: + GITHUB_TOKEN: == + mg: FOO_BAR + dot_1: + kind: dotenv # name is = kind if empty + maps: + - id: dotvars + path: fixtures/vars.env diff --git a/teller-cli/fixtures/vars.env b/teller-cli/fixtures/vars.env new file mode 100644 index 00000000..35d61703 --- /dev/null +++ b/teller-cli/fixtures/vars.env @@ -0,0 +1,2 @@ +HELLO=world +foo=bar diff --git a/teller-cli/src/bin/teller.rs b/teller-cli/src/bin/teller.rs new file mode 100644 index 00000000..eab7883d --- /dev/null +++ b/teller-cli/src/bin/teller.rs @@ -0,0 +1,19 @@ +use std::process::exit; + +use clap::Parser; +use eyre::Result; +use teller_cli::{cli, tracing}; + +#[tokio::main] +async fn main() -> Result<()> { + let args = cli::Cli::parse(); + + tracing(args.verbose); + + let resp = cli::run(&args).await?; + + if let Some(msg) = resp.message { + println!("{msg}"); + } + exit(resp.code); +} diff --git a/teller-cli/src/cli.rs b/teller-cli/src/cli.rs new file mode 100644 index 00000000..5ad042f6 --- /dev/null +++ b/teller-cli/src/cli.rs @@ -0,0 +1,334 @@ +use std::path::{Path, PathBuf}; + +use clap::{Args, Parser, Subcommand, ValueEnum}; +use eyre::eyre; +use teller_core::{exec, export, teller::Teller}; +use teller_providers::{config::KV, providers::ProviderKind}; + +use crate::{ + io::{self, or_stdin, or_stdout}, + new, scan, Response, +}; + +#[derive(Debug, Clone, Parser)] // requires `derive` feature +#[command(name = "teller")] +#[command(about = "A multi provider secret management tool", long_about = None)] +pub struct Cli { + /// Path to your teller.yml config + #[arg(short, long)] + pub config: Option, + + /// Path to your teller.yml config + #[arg(long)] + pub verbose: bool, + + /// A teller command + #[command(subcommand)] + pub command: Commands, +} +#[derive(Debug, Clone, Subcommand)] +pub enum Commands { + /// Run a command + Run { + /// Reset environment variables before running + #[arg(short, long)] + reset: bool, + /// Run command as shell command + #[arg(short, long)] + shell: bool, + /// The command to run + #[arg(value_name = "COMMAND", raw = true)] + command: Vec, + }, + + /// Scan files + Scan(ScanArgs), + /// Export key-secret pairs to a specified format + Export { + /// The format to export to + #[arg(value_enum, index = 1)] + format: Format, + }, + /// Redact text using fetched secrets + Redact { + /// Input file (stdin if none given) + #[arg(name = "in", short, long)] + in_file: Option, + /// Output file (stdout if none given) + #[arg(short, long)] + out: Option, + }, + + /// Render a key-value aware template + Template { + /// Input template (stdin if none given) + #[arg(name = "in", short, long)] + in_file: Option, + /// Output destination (stdout if none given) + #[arg(short, long)] + out: Option, + }, + + /// Export compatible with ENV + Env {}, + + /// Print all currently accessible data + Show {}, + + /// Export as source-able shell script + Sh {}, + + /// Create a new Teller configuration + New(NewArgs), + + /// Put new key-values onto a list of providers on a specified path + Put { + #[arg(long, short)] + map_id: String, + + #[arg(long, value_delimiter = ',')] + providers: Vec, + + #[clap(value_parser = parse_key_val::)] + kvs: Vec<(String, String)>, + }, + + /// Delete specific keys or complete paths + Delete { + #[arg(long, short)] + map_id: String, + + #[arg(long, value_delimiter = ',')] + providers: Vec, + + keys: Vec, + }, + Copy { + #[arg(long, short)] + from: String, + + #[arg(long, short, value_delimiter = ',')] + to: Vec, + + #[arg(long, short)] + replace: bool, + }, +} + +fn parse_key_val( + s: &str, +) -> std::result::Result<(T, U), Box> +where + T: std::str::FromStr, + T::Err: std::error::Error + Send + Sync + 'static, + U: std::str::FromStr, + U::Err: std::error::Error + Send + Sync + 'static, +{ + let pos = s + .find('=') + .ok_or_else(|| format!("invalid KEY=value: no `=` found in `{s}`"))?; + Ok((s[..pos].parse()?, s[pos + 1..].parse()?)) +} + +#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum)] +pub enum Format { + /// Export as CSV + CSV, + /// Export as YAML + YAML, + /// Export as JSON + JSON, + /// Export as env variables + ENV, +} + +#[allow(clippy::struct_excessive_bools)] +#[derive(Debug, Clone, Args)] // requires `derive` feature +pub struct ScanArgs { + /// Root folder to scan recursively + #[arg(short, long, default_value = ".")] + pub root: String, + /// Include hidden and ignored files + #[arg(short, long)] + pub all: bool, + /// Returns exit code 1 if has finding + #[arg(long)] + pub error_if_found: bool, + /// Include binary files + #[arg(short, long)] + pub binary: bool, + /// Output matches as JSON + #[arg(short, long)] + pub json: bool, +} + +const DEFAULT_FILE_PATH: &str = ".teller.yml"; + +#[derive(Debug, Clone, Args)] +pub struct NewArgs { + /// Stuff to add + #[arg(short, long, conflicts_with = "std", default_value=DEFAULT_FILE_PATH)] + pub filename: PathBuf, + + /// Print configuration to the STDOUT + #[arg(long)] + pub std: bool, + + /// Force teller configuration file if exists + #[arg(long)] + pub force: bool, + + #[arg(long, value_delimiter = ',')] + pub providers: Vec, +} + +async fn load_teller(config: Option) -> eyre::Result { + let config_arg = config.unwrap_or_else(|| "teller.yml".to_string()); + let config_path = Path::new(&config_arg); + let teller = Teller::from_yaml(config_path).await?; + Ok(teller) +} + +/// Run the CLI logic +/// +/// # Errors +/// +/// This function will return an error if operation fails +#[allow(clippy::future_not_send)] +#[allow(clippy::too_many_lines)] +pub async fn run(args: &Cli) -> eyre::Result { + match args.command.clone() { + Commands::Run { + reset, + shell, + command, + } => { + let teller = load_teller(args.config.clone()).await?; + let pwd = std::env::current_dir()?; + let opts = exec::Opts { + pwd: pwd.as_path(), + sh: shell, + reset_env: reset, + capture: false, + }; + teller + .run( + command + .iter() + .map(String::as_str) + .collect::>() + .as_slice(), + &opts, + ) + .await?; + Response::ok() + } + Commands::Scan(cmdargs) => { + let teller = load_teller(args.config.clone()).await?; + scan::run(&teller, &cmdargs).await + } + Commands::Export { format } => { + let teller_format = match format { + Format::CSV => export::Format::CSV, + Format::YAML => export::Format::YAML, + Format::JSON => export::Format::JSON, + Format::ENV => export::Format::ENV, + }; + let teller = load_teller(args.config.clone()).await?; + let out = teller.export(&teller_format).await?; + Response::ok_with_message(out) + } + Commands::Redact { in_file, out } => { + let teller = load_teller(args.config.clone()).await?; + teller + .redact(&mut or_stdin(in_file)?, &mut or_stdout(out)?) + .await?; + Response::ok() + } + Commands::Template { in_file, out } => { + let mut input = String::new(); + or_stdin(in_file)?.read_to_string(&mut input)?; + let teller = load_teller(args.config.clone()).await?; + let rendered = teller.template(&input).await?; + let mut out = or_stdout(out)?; + out.write_all(rendered.as_bytes())?; + out.flush()?; + Response::ok() + } + Commands::Env {} => { + let teller = load_teller(args.config.clone()).await?; + let out = teller.export(&export::Format::ENV).await?; + Response::ok_with_message(out) + } + Commands::New(new_args) => new::run(&new_args), + Commands::Show {} => { + let teller = load_teller(args.config.clone()).await?; + let kvs = teller.collect().await?; + io::print_kvs(&kvs); + Response::ok() + } + Commands::Sh {} => { + let teller = load_teller(args.config.clone()).await?; + let out = teller.export(&export::Format::Shell).await?; + Response::ok_with_message(out) + } + Commands::Put { + kvs, + map_id, + providers, + } => { + let kvs = kvs + .iter() + .map(|(k, v)| KV::from_kv(k, v)) + .collect::>(); + let teller = load_teller(args.config.clone()).await?; + teller + .put(kvs.as_slice(), map_id.as_str(), providers.as_slice()) + .await?; + Response::ok() + } + Commands::Delete { + map_id, + providers, + keys, + } => { + let teller = load_teller(args.config.clone()).await?; + teller + .delete(keys.as_slice(), &map_id, providers.as_slice()) + .await?; + Response::ok() + } + Commands::Copy { from, to, replace } => { + // a copy report should state how many keys were copied and to where. + // invent a new kvrl (key-value resource location) format: kvurl://dotenv/?meta + // / like server/resource-path + // ?path=varbatim/path/to/location request specific path overriding resource routing + // + // dotenv/map-id -> foo/map-id: copied 4 key(s). + // dotenv/map-id -> f/map-id: copied 4 key(s). + // copied 4 key(s) [in replace mode] from `dotenv:path-id` to `foo:path-id`, `bar:path-id` + let teller = load_teller(args.config.clone()).await?; + let (from_provider, from_map_id) = from.split_once('/').ok_or_else(|| { + eyre!( + "cannot parse '--from': '{}', did you format it as: '/' ?", + from + ) + })?; + for to_provider in to { + let (to_provider, to_map_id) = to_provider.split_once('/').ok_or_else(|| { + eyre!( + "cannot parse '--to': '{}', did you format it as: '/' ?", + to_provider + ) + })?; + teller + .copy(from_provider, from_map_id, to_provider, to_map_id, replace) + .await?; + } + + Response::ok() + } + } +} diff --git a/teller-cli/src/io.rs b/teller-cli/src/io.rs new file mode 100644 index 00000000..8a46050d --- /dev/null +++ b/teller-cli/src/io.rs @@ -0,0 +1,45 @@ +use std::io::{self, BufRead, BufReader, BufWriter, Write}; + +use eyre::Result; +use fs_err::File; +use teller_providers::config::KV; + +/// Read from a file or stdin +/// +/// # Errors +/// +/// This function will return an error if IO fails +pub fn or_stdin(file: Option) -> Result> { + let out: Box = file.map_or_else( + || Ok(Box::new(BufReader::new(io::stdin())) as Box), + |file_path| File::open(file_path).map(|f| Box::new(BufReader::new(f)) as Box), + )?; + + Ok(out) +} + +/// Write to a file or stdout +/// +/// # Errors +/// +/// This function will return an error if IO fails +pub fn or_stdout(file: Option) -> Result> { + let out = file.map_or_else( + || Ok(Box::new(BufWriter::new(std::io::stdout())) as Box), + |file_path| File::open(file_path).map(|f| Box::new(BufWriter::new(f)) as Box), + )?; + Ok(out) +} + +pub fn print_kvs(kvs: &[KV]) { + for kv in kvs { + println!( + "[{}]: {} = {}***", + kv.provider + .as_ref() + .map_or_else(|| "n/a".to_string(), |p| format!("{} ({})", p.name, p.kind)), + kv.key, + kv.value.get(0..2).unwrap_or_default() + ); + } +} diff --git a/teller-cli/src/lib.rs b/teller-cli/src/lib.rs new file mode 100644 index 00000000..ad1ff388 --- /dev/null +++ b/teller-cli/src/lib.rs @@ -0,0 +1,57 @@ +pub mod cli; +pub mod io; +pub mod new; +pub mod scan; +pub mod wizard; +use eyre::Result; +use tracing::level_filters::LevelFilter; +use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Registry}; +#[allow(clippy::module_name_repetitions)] +pub struct Response { + pub code: exitcode::ExitCode, + pub message: Option, +} +impl Response { + #[allow(clippy::missing_const_for_fn)] + #[allow(clippy::unnecessary_wraps)] + fn fail() -> Result { + Ok(Self { + code: 1, + message: None, + }) + } + #[allow(clippy::missing_const_for_fn)] + #[allow(clippy::unnecessary_wraps)] + fn ok() -> Result { + Ok(Self { + code: exitcode::OK, + message: None, + }) + } + + #[allow(clippy::missing_const_for_fn)] + #[allow(clippy::unnecessary_wraps)] + fn ok_with_message(message: String) -> Result { + Ok(Self { + code: exitcode::OK, + message: Some(message), + }) + } +} + +pub fn tracing(verbose: bool) { + let level = if verbose { + LevelFilter::INFO + } else { + LevelFilter::OFF + }; + Registry::default() + .with(tracing_tree::HierarchicalLayer::new(2)) + .with( + EnvFilter::builder() + .with_default_directive(level.into()) + .with_env_var("LOG") + .from_env_lossy(), + ) + .init(); +} diff --git a/teller-cli/src/new.rs b/teller-cli/src/new.rs new file mode 100644 index 00000000..92b15e6b --- /dev/null +++ b/teller-cli/src/new.rs @@ -0,0 +1,70 @@ +use std::fs; + +use eyre::Result; +use teller_core::config::{Config, RenderTemplate}; +use teller_providers::providers; + +use super::Response; +use crate::{cli::NewArgs, wizard}; + +pub const CMD_NAME: &str = "new"; + +/// Create a new teller configuration +/// +/// # Errors +/// +/// This function will return an error if operation fails +#[allow(clippy::future_not_send)] +pub fn run(args: &NewArgs) -> Result { + let providers: Vec = args.providers.clone(); + + let file = { + let mut file_path = args.filename.clone(); + let ext = file_path + .extension() + .and_then(std::ffi::OsStr::to_str) + .unwrap_or(""); + + if ext != "yaml" || ext != "yml" { + file_path.set_extension("yml"); + } + + file_path + }; + + let w = { + let mut wizard = wizard::AppConfig::new(args.force); + + if !args.std { + wizard.with_file_validation(file.as_path()); + } + + if !providers.is_empty() { + wizard.with_providers(providers); + } + wizard + }; + let results = match w.start() { + Ok(r) => r, + Err(e) => match e { + wizard::Error::ProviderNotFound(_) + | wizard::Error::Prompt(_) + | wizard::Error::InvalidSelection => return Err(eyre::Error::new(e)), + wizard::Error::ConfigurationAlreadyExists => return Response::ok(), + }, + }; + + let template = Config::render_template(&RenderTemplate { + providers: results.providers, + })?; + + if args.std { + Response::ok_with_message(template) + } else { + if let Some(folder) = &file.parent() { + fs::create_dir_all(folder)?; + } + fs::write(&file, template)?; + Response::ok_with_message(format!("Configuration saved in: {:?}", file.display())) + } +} diff --git a/teller-cli/src/scan.rs b/teller-cli/src/scan.rs new file mode 100644 index 00000000..889060b6 --- /dev/null +++ b/teller-cli/src/scan.rs @@ -0,0 +1,63 @@ +use comfy_table::presets::NOTHING; +use comfy_table::{Cell, Table}; +use eyre::Result; +use teller_core::{scan, teller::Teller}; + +use crate::cli::ScanArgs; +use crate::Response; + +fn hide_chars(s: &str) -> String { + let mut result = String::new(); + let chars_to_display = s.chars().take(2).collect::(); + let asterisks = "*".repeat(3); + result.push_str(&chars_to_display); + result.push_str(&asterisks); + result +} + +/// Scan a folder for secrets fetched from providers +/// +/// # Errors +/// +/// This function will return an error if the operation fails +#[allow(clippy::future_not_send)] +pub async fn run(teller: &Teller, args: &ScanArgs) -> Result { + let opts = scan::Opts { + include_all: args.all, + include_binary: args.binary, + }; + + let kvs = teller.collect().await?; + let res = teller.scan(&args.root, &kvs, &opts)?; + let count = res.len(); + eprintln!("scanning for {} item(s) in {}", kvs.len(), args.root); + if args.json { + println!("{}", serde_json::to_string_pretty(&res)?); + } else { + let mut table = Table::new(); + table.load_preset(NOTHING); + for m in res { + let pos = m.position.unwrap_or((0, 0)); + table.add_row(vec![ + Cell::new(format!("{}:{}", pos.0, pos.1)), + Cell::new(m.path.to_string_lossy()), + Cell::new(hide_chars(&m.query.value)), + Cell::new( + m.query + .provider + .map_or_else(|| "n/a".to_string(), |p| p.kind.to_string()) + .to_string(), + ), + Cell::new(m.query.path.map_or_else(|| "n/a".to_string(), |p| p.path)), + ]); + } + println!("{table}"); + } + eprintln!("found {count} result(s)"); + + if args.error_if_found && count > 0 { + Response::fail() + } else { + Response::ok() + } +} diff --git a/teller-cli/src/wizard.rs b/teller-cli/src/wizard.rs new file mode 100644 index 00000000..e0166ebd --- /dev/null +++ b/teller-cli/src/wizard.rs @@ -0,0 +1,121 @@ +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use dialoguer::{theme::ColorfulTheme, Confirm, MultiSelect}; +use strum::IntoEnumIterator; +use teller_providers::providers::ProviderKind; + +pub type Result = std::result::Result; + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error("Provider: {0} not exists")] + ProviderNotFound(String), + + #[error(transparent)] + Prompt(#[from] dialoguer::Error), + + #[error("Config file already exists")] + ConfigurationAlreadyExists, + + #[error("Invalid prompt selection")] + InvalidSelection, +} + +pub struct AppConfig { + file_path: Option, + providers: Option>, + pub override_file: bool, +} + +pub struct Results { + pub providers: Vec, +} + +/// Creating wizard flow for crating Teller configuration file +impl AppConfig { + #[must_use] + pub const fn new(override_file: bool) -> Self { + Self { + file_path: None, + providers: None, + override_file, + } + } + + pub fn with_file_validation(&mut self, file_path: &Path) -> &mut Self { + self.file_path = Some(file_path.to_path_buf()); + self + } + + pub fn with_providers(&mut self, providers: Vec) -> &mut Self { + self.providers = Some(providers); + self + } + + /// Start wizard flow + /// + /// # Errors + /// this function return an errors when from `Error` options + pub fn start(&self) -> Result { + if let Some(file_path) = &self.file_path { + if file_path.exists() + && !self.override_file + && !Self::confirm_override_file(file_path.as_path())? + { + return Err(Error::ConfigurationAlreadyExists {}); + } + } + + let providers = match &self.providers { + Some(providers) => providers.clone(), + None => Self::select_providers()?, + }; + Ok(Results { providers }) + } + + fn confirm_override_file(file_path: &Path) -> Result { + Ok(Confirm::with_theme(&ColorfulTheme::default()) + .with_prompt(format!( + "Teller config {:?} already exists. Do you want to override the configuration \ + with new settings", + file_path.display() + )) + .interact()?) + } + + /// Prompt provider selection + /// + /// # Errors + /// When has a problem with prompt selection + fn select_providers() -> Result> { + let providers = ProviderKind::iter() + .map(|provider| (provider.to_string(), provider)) + .collect::>(); + + let names = &providers + .keys() + .map(std::string::String::as_str) + .collect::>(); + + let selected_providers = MultiSelect::with_theme(&ColorfulTheme::default()) + .with_prompt("Select your secret providers") + .items(names) + .report(false) + .interact()?; + + let mut selected = vec![]; + for selection in selected_providers { + let Some(provider_name) = names.get(selection) else { + return Err(Error::InvalidSelection); + }; + + match providers.get(*provider_name) { + Some(p) => selected.push(p.clone()), + _ => return Err(Error::ProviderNotFound((*provider_name).to_string())), + }; + } + + Ok(selected) + } +} diff --git a/teller-cli/tests/cli_tests.rs b/teller-cli/tests/cli_tests.rs new file mode 100644 index 00000000..be10b16f --- /dev/null +++ b/teller-cli/tests/cli_tests.rs @@ -0,0 +1,25 @@ +use std::fs; + +fn prep_data_for_mutating_tests() { + fs::write("tests/cmd/put.in/new.env", "EMPTY=true\n").expect("writing a fixture file"); + fs::write( + "tests/cmd/delete.in/new.env", + "EMPTY=true\nDELETE_ME=true\n", + ) + .expect("writing a fixture file"); + fs::write("tests/cmd/copy.in/target.env", "TARGET_ONLY=true\n") + .expect("writing a fixture file"); +} +#[test] +fn cli_tests() { + fs::write("tests/cmd/scan.in/git-hidden-file", "happy").expect("writing a fixture file"); + prep_data_for_mutating_tests(); + + let c = trycmd::TestCases::new(); + c.case("tests/cmd/*.trycmd"); + #[cfg(windows)] + c.skip("tests/cmd/run.trycmd"); + + c.run(); + prep_data_for_mutating_tests(); +} diff --git a/teller-cli/tests/cmd/copy.in/source.env b/teller-cli/tests/cmd/copy.in/source.env new file mode 100644 index 00000000..242f94a2 --- /dev/null +++ b/teller-cli/tests/cmd/copy.in/source.env @@ -0,0 +1,2 @@ +EMPTY=true +DEV_DB=magic diff --git a/teller-cli/tests/cmd/copy.in/target.env b/teller-cli/tests/cmd/copy.in/target.env new file mode 100644 index 00000000..80f6149b --- /dev/null +++ b/teller-cli/tests/cmd/copy.in/target.env @@ -0,0 +1 @@ +TARGET_ONLY=true diff --git a/teller-cli/tests/cmd/copy.in/teller.yml b/teller-cli/tests/cmd/copy.in/teller.yml new file mode 100644 index 00000000..d2799f24 --- /dev/null +++ b/teller-cli/tests/cmd/copy.in/teller.yml @@ -0,0 +1,11 @@ +providers: + source: + kind: dotenv + maps: + - id: dev + path: source.env + target: + kind: dotenv + maps: + - id: prod + path: target.env diff --git a/teller-cli/tests/cmd/copy.trycmd b/teller-cli/tests/cmd/copy.trycmd new file mode 100644 index 00000000..f276706e --- /dev/null +++ b/teller-cli/tests/cmd/copy.trycmd @@ -0,0 +1,24 @@ +```console +$ teller show +[source (dotenv)]: DEV_DB = ma*** +[source (dotenv)]: EMPTY = tr*** +[target (dotenv)]: TARGET_ONLY = tr*** + +$ teller copy --from source/dev --to target/prod + +$ teller show +[source (dotenv)]: DEV_DB = ma*** +[source (dotenv)]: EMPTY = tr*** +[target (dotenv)]: DEV_DB = ma*** +[target (dotenv)]: EMPTY = tr*** +[target (dotenv)]: TARGET_ONLY = tr*** + +$ teller copy --from source/dev --to target/prod --replace + +$ teller show +[source (dotenv)]: DEV_DB = ma*** +[source (dotenv)]: EMPTY = tr*** +[target (dotenv)]: DEV_DB = ma*** +[target (dotenv)]: EMPTY = tr*** + +``` diff --git a/teller-cli/tests/cmd/delete.in/new.env b/teller-cli/tests/cmd/delete.in/new.env new file mode 100644 index 00000000..af0a9111 --- /dev/null +++ b/teller-cli/tests/cmd/delete.in/new.env @@ -0,0 +1,2 @@ +EMPTY=true +DELETE_ME=true diff --git a/teller-cli/tests/cmd/delete.in/teller.yml b/teller-cli/tests/cmd/delete.in/teller.yml new file mode 100644 index 00000000..e02abce0 --- /dev/null +++ b/teller-cli/tests/cmd/delete.in/teller.yml @@ -0,0 +1,6 @@ +providers: + new: + kind: dotenv + maps: + - id: one + path: new.env diff --git a/teller-cli/tests/cmd/delete.trycmd b/teller-cli/tests/cmd/delete.trycmd new file mode 100644 index 00000000..b0a140da --- /dev/null +++ b/teller-cli/tests/cmd/delete.trycmd @@ -0,0 +1,20 @@ +```console +$ teller show +[new (dotenv)]: DELETE_ME = tr*** +[new (dotenv)]: EMPTY = tr*** + +$ teller delete --providers new --map-id one DELETE_ME + +$ teller show +[new (dotenv)]: EMPTY = tr*** + +$ teller delete --providers new --map-id one + +$ teller show +? 1 +Error: NOT FOUND "new.env": file is empty + +Location: + [..] + +``` diff --git a/teller-cli/tests/cmd/export.in/one.env b/teller-cli/tests/cmd/export.in/one.env new file mode 100644 index 00000000..96d17208 --- /dev/null +++ b/teller-cli/tests/cmd/export.in/one.env @@ -0,0 +1,2 @@ +PRINT_NAME=linus +FOO_BAR=foo diff --git a/teller-cli/tests/cmd/export.in/teller.yml b/teller-cli/tests/cmd/export.in/teller.yml new file mode 100644 index 00000000..719d24a0 --- /dev/null +++ b/teller-cli/tests/cmd/export.in/teller.yml @@ -0,0 +1,11 @@ +providers: + dot1: + kind: dotenv + maps: + - id: one + path: one.env + dot2: + kind: dotenv + maps: + - id: two + path: two.env diff --git a/teller-cli/tests/cmd/export.in/two.env b/teller-cli/tests/cmd/export.in/two.env new file mode 100644 index 00000000..18b198b4 --- /dev/null +++ b/teller-cli/tests/cmd/export.in/two.env @@ -0,0 +1,2 @@ +PRINT_MOOD=happy +FOO_BAZ=baz diff --git a/teller-cli/tests/cmd/export.trycmd b/teller-cli/tests/cmd/export.trycmd new file mode 100644 index 00000000..6190e5b6 --- /dev/null +++ b/teller-cli/tests/cmd/export.trycmd @@ -0,0 +1,41 @@ +```console +$ teller -c teller.yml export yaml +FOO_BAR: foo +FOO_BAZ: baz +PRINT_MOOD: happy +PRINT_NAME: linus + + +$ teller -c teller.yml export csv +FOO_BAR,foo +PRINT_NAME,linus +FOO_BAZ,baz +PRINT_MOOD,happy + + +$ teller -c teller.yml export json +{"FOO_BAR":"foo","FOO_BAZ":"baz","PRINT_MOOD":"happy","PRINT_NAME":"linus"} + +$ teller -c teller.yml export env +FOO_BAR=foo +PRINT_NAME=linus +FOO_BAZ=baz +PRINT_MOOD=happy + + +$ teller -c teller.yml sh +#!/bin/sh +export FOO_BAR='foo' +export PRINT_NAME='linus' +export FOO_BAZ='baz' +export PRINT_MOOD='happy' + + +$ teller -c teller.yml env +FOO_BAR=foo +PRINT_NAME=linus +FOO_BAZ=baz +PRINT_MOOD=happy + + +``` diff --git a/teller-cli/tests/cmd/new.trycmd b/teller-cli/tests/cmd/new.trycmd new file mode 100644 index 00000000..48d75e76 --- /dev/null +++ b/teller-cli/tests/cmd/new.trycmd @@ -0,0 +1,19 @@ +```console +$ teller new --providers inmem,dotenv --force --filename tmp/.test.teller.yml +Configuration saved in: "tmp/.test.teller.yml" + +$ teller new --providers inmem,dotenv --std +providers: + dotenv_1: + kind: dotenv + maps: + - id: '' + path: example/dev + inmem_1: + kind: inmem + maps: + - id: '' + path: example/dev + + +``` diff --git a/teller-cli/tests/cmd/put.in/new.env b/teller-cli/tests/cmd/put.in/new.env new file mode 100644 index 00000000..0d685322 --- /dev/null +++ b/teller-cli/tests/cmd/put.in/new.env @@ -0,0 +1 @@ +EMPTY=true diff --git a/teller-cli/tests/cmd/put.in/teller.yml b/teller-cli/tests/cmd/put.in/teller.yml new file mode 100644 index 00000000..e02abce0 --- /dev/null +++ b/teller-cli/tests/cmd/put.in/teller.yml @@ -0,0 +1,6 @@ +providers: + new: + kind: dotenv + maps: + - id: one + path: new.env diff --git a/teller-cli/tests/cmd/put.trycmd b/teller-cli/tests/cmd/put.trycmd new file mode 100644 index 00000000..2b150718 --- /dev/null +++ b/teller-cli/tests/cmd/put.trycmd @@ -0,0 +1,11 @@ +```console +$ teller show +[new (dotenv)]: EMPTY = tr*** + +$ teller put --providers new --map-id one NEW_VAR=s33kret + +$ teller show +[new (dotenv)]: EMPTY = tr*** +[new (dotenv)]: NEW_VAR = s3*** + +``` diff --git a/teller-cli/tests/cmd/run.in/index.js b/teller-cli/tests/cmd/run.in/index.js new file mode 100644 index 00000000..3be8e3c4 --- /dev/null +++ b/teller-cli/tests/cmd/run.in/index.js @@ -0,0 +1,6 @@ + +console.log('hello from nodejs') +console.log(process.env['PRINT_NAME']) +console.log(process.env['PRINT_MOOD']) +console.log(process.env['FOO_BAR']) +console.log(process.env['FOO_BAZ']) diff --git a/teller-cli/tests/cmd/run.in/one.env b/teller-cli/tests/cmd/run.in/one.env new file mode 100644 index 00000000..96d17208 --- /dev/null +++ b/teller-cli/tests/cmd/run.in/one.env @@ -0,0 +1,2 @@ +PRINT_NAME=linus +FOO_BAR=foo diff --git a/teller-cli/tests/cmd/run.in/teller.yml b/teller-cli/tests/cmd/run.in/teller.yml new file mode 100644 index 00000000..719d24a0 --- /dev/null +++ b/teller-cli/tests/cmd/run.in/teller.yml @@ -0,0 +1,11 @@ +providers: + dot1: + kind: dotenv + maps: + - id: one + path: one.env + dot2: + kind: dotenv + maps: + - id: two + path: two.env diff --git a/teller-cli/tests/cmd/run.in/two.env b/teller-cli/tests/cmd/run.in/two.env new file mode 100644 index 00000000..18b198b4 --- /dev/null +++ b/teller-cli/tests/cmd/run.in/two.env @@ -0,0 +1,2 @@ +PRINT_MOOD=happy +FOO_BAZ=baz diff --git a/teller-cli/tests/cmd/run.trycmd b/teller-cli/tests/cmd/run.trycmd new file mode 100644 index 00000000..cbfabddb --- /dev/null +++ b/teller-cli/tests/cmd/run.trycmd @@ -0,0 +1,9 @@ +```console +$ teller -c teller.yml run --reset --shell -- node index.js +hello from nodejs +linus +happy +foo +baz + +``` diff --git a/teller-cli/tests/cmd/scan.in/content.bin b/teller-cli/tests/cmd/scan.in/content.bin new file mode 100644 index 00000000..995f844c Binary files /dev/null and b/teller-cli/tests/cmd/scan.in/content.bin differ diff --git a/teller-cli/tests/cmd/scan.in/one.env b/teller-cli/tests/cmd/scan.in/one.env new file mode 100644 index 00000000..96d17208 --- /dev/null +++ b/teller-cli/tests/cmd/scan.in/one.env @@ -0,0 +1,2 @@ +PRINT_NAME=linus +FOO_BAR=foo diff --git a/teller-cli/tests/cmd/scan.in/teller.yml b/teller-cli/tests/cmd/scan.in/teller.yml new file mode 100644 index 00000000..719d24a0 --- /dev/null +++ b/teller-cli/tests/cmd/scan.in/teller.yml @@ -0,0 +1,11 @@ +providers: + dot1: + kind: dotenv + maps: + - id: one + path: one.env + dot2: + kind: dotenv + maps: + - id: two + path: two.env diff --git a/teller-cli/tests/cmd/scan.in/two.env b/teller-cli/tests/cmd/scan.in/two.env new file mode 100644 index 00000000..18b198b4 --- /dev/null +++ b/teller-cli/tests/cmd/scan.in/two.env @@ -0,0 +1,2 @@ +PRINT_MOOD=happy +FOO_BAZ=baz diff --git a/teller-cli/tests/cmd/scan.trycmd b/teller-cli/tests/cmd/scan.trycmd new file mode 100644 index 00000000..8d471e7f --- /dev/null +++ b/teller-cli/tests/cmd/scan.trycmd @@ -0,0 +1,28 @@ +```console +$ teller -c teller.yml scan +scanning for 4 item(s) in . + 2:9 ./one.env fo*** dotenv one.env + 2:9 ./two.env ba*** dotenv two.env + 1:12 ./two.env ha*** dotenv two.env + 1:12 ./one.env li*** dotenv one.env +found 4 result(s) + +$ teller -c teller.yml scan -a +scanning for 4 item(s) in . + 2:9 ./one.env fo*** dotenv one.env + 2:9 ./two.env ba*** dotenv two.env + 1:1 ./git-hidden-file ha*** dotenv two.env + 1:12 ./two.env ha*** dotenv two.env + 1:12 ./one.env li*** dotenv one.env +found 5 result(s) + +$ teller -c teller.yml scan -b +scanning for 4 item(s) in . + 2:9 ./one.env fo*** dotenv one.env + 2:9 ./two.env ba*** dotenv two.env + 2:1 ./content.bin ha*** dotenv two.env + 1:12 ./two.env ha*** dotenv two.env + 1:12 ./one.env li*** dotenv one.env +found 5 result(s) + +``` diff --git a/teller-cli/tests/cmd/template.in/config-templ.t b/teller-cli/tests/cmd/template.in/config-templ.t new file mode 100644 index 00000000..2e839adf --- /dev/null +++ b/teller-cli/tests/cmd/template.in/config-templ.t @@ -0,0 +1,2 @@ +production_var: {{ key(name="PRINT_NAME")}} +production_mood: {{ key(name="PRINT_MOOD")}} diff --git a/teller-cli/tests/cmd/template.in/one.env b/teller-cli/tests/cmd/template.in/one.env new file mode 100644 index 00000000..96d17208 --- /dev/null +++ b/teller-cli/tests/cmd/template.in/one.env @@ -0,0 +1,2 @@ +PRINT_NAME=linus +FOO_BAR=foo diff --git a/teller-cli/tests/cmd/template.in/teller.yml b/teller-cli/tests/cmd/template.in/teller.yml new file mode 100644 index 00000000..719d24a0 --- /dev/null +++ b/teller-cli/tests/cmd/template.in/teller.yml @@ -0,0 +1,11 @@ +providers: + dot1: + kind: dotenv + maps: + - id: one + path: one.env + dot2: + kind: dotenv + maps: + - id: two + path: two.env diff --git a/teller-cli/tests/cmd/template.in/two.env b/teller-cli/tests/cmd/template.in/two.env new file mode 100644 index 00000000..18b198b4 --- /dev/null +++ b/teller-cli/tests/cmd/template.in/two.env @@ -0,0 +1,2 @@ +PRINT_MOOD=happy +FOO_BAZ=baz diff --git a/teller-cli/tests/cmd/template.trycmd b/teller-cli/tests/cmd/template.trycmd new file mode 100644 index 00000000..7ba16b92 --- /dev/null +++ b/teller-cli/tests/cmd/template.trycmd @@ -0,0 +1,6 @@ +```console +$ teller -c teller.yml template --in config-templ.t +production_var: linus +production_mood: happy + +``` diff --git a/teller-cli/tests/flow_test.rs b/teller-cli/tests/flow_test.rs new file mode 100644 index 00000000..981c9b24 --- /dev/null +++ b/teller-cli/tests/flow_test.rs @@ -0,0 +1,145 @@ +use std::collections::HashMap; + +use dockertest_server::{ + servers::{ + cloud::{LocalStackServer, LocalStackServerConfig}, + hashi::{VaultServer, VaultServerConfig}, + }, + Test, +}; +use fs_err as fs; +use insta::assert_debug_snapshot; +use teller_core::config::Config; +use teller_providers::{ + config::{ProviderInfo, KV}, + providers::ProviderKind, + registry::Registry, +}; + +fn build_providers() -> Test { + let mut test = Test::new(); + test.register( + VaultServerConfig::builder() + .port(9200) + .version("1.8.2".into()) + .build() + .unwrap(), + ); + test.register( + LocalStackServerConfig::builder() + .env( + vec![( + "SERVICES".to_string(), + "iam,sts,ssm,kms,secretsmanager".to_string(), + )] + .into_iter() + .collect(), + ) + .port(4561) + .version("2.0.2".into()) + .build() + .unwrap(), + ); + test +} + +#[test] +#[cfg(not(windows))] +fn providers_smoke_test() { + use std::env; + + if env::var("RUNNER_OS").unwrap_or_default() == "macOS" { + return; + } + + let test = build_providers(); + + test.run(|instance| async move { + let user = "linus"; + let password = "torvalds123"; + let vault_server: VaultServer = instance.server(); + let localstack_server: LocalStackServer = instance.server(); + + fs::write( + "fixtures/flow.env", + r" +FOO=bar +HELLO=world +", + ) + .unwrap(); + let mut vars = HashMap::new(); + vars.insert("address".to_string(), vault_server.external_url()); + vars.insert("token".to_string(), vault_server.token); + vars.insert("endpoint_url".to_string(), localstack_server.external_url()); + + let config = Config::with_vars( + &fs::read_to_string("fixtures/flow_test.yml").unwrap(), + &vars, + ) + .unwrap(); + let registry = Registry::new(&config.providers).await.unwrap(); + + // (1) start: put on hashi + let hashi = registry.get("hashi_1").unwrap(); + let hashi_pm0 = &config.providers.get("hashi_1").unwrap().maps[0]; + hashi + .put( + hashi_pm0, + &[ + KV::from_value( + user, + "USER", + "USER", + hashi_pm0, + ProviderInfo { + kind: ProviderKind::Hashicorp, + name: "test".to_string(), + }, + ), + KV::from_value( + password, + "PASSWORD", + "PASSWORD", + hashi_pm0, + ProviderInfo { + kind: ProviderKind::Hashicorp, + name: "test".to_string(), + }, + ), + ], + ) + .await + .unwrap(); + let res = hashi.get(hashi_pm0).await; + assert_debug_snapshot!("flow-test-hashi-0", res); + + // (2) push results into secretsmanager + let kvs = res.unwrap(); + + let smgr = registry.get("sm_1").unwrap(); + let smgr_pm0 = &config.providers.get("sm_1").unwrap().maps[0]; + smgr.put(smgr_pm0, &kvs[..]).await.unwrap(); + let res = smgr.get(smgr_pm0).await; + assert_debug_snapshot!("flow-test-smgr-0", res); + + // (3) push results into ssm - remember it has custom key mapping so + // check that in snapshots (USER -> USER_NAME, and drops the pass) + let kvs = res.unwrap(); + + let ssm = registry.get("ssm_1").unwrap(); + let ssm_pm0 = &config.providers.get("ssm_1").unwrap().maps[0]; + ssm.put(ssm_pm0, &kvs[..]).await.unwrap(); + let res = ssm.get(ssm_pm0).await; + assert_debug_snapshot!("flow-test-ssm-0", res); + + // (4) lastly, write it into dotenv file, read it back, and snapshot it + let kvs = res.unwrap(); + + let dot = registry.get("dot_1").unwrap(); + let dot_pm0 = &config.providers.get("dot_1").unwrap().maps[0]; + dot.put(dot_pm0, &kvs[..]).await.unwrap(); + let res = dot.get(dot_pm0).await; + assert_debug_snapshot!("flow-test-dot-0", res); + }); +} diff --git a/teller-cli/tests/snapshots/flow_test__flow-test-dot-0.snap b/teller-cli/tests/snapshots/flow_test__flow-test-dot-0.snap new file mode 100644 index 00000000..25f1859a --- /dev/null +++ b/teller-cli/tests/snapshots/flow_test__flow-test-dot-0.snap @@ -0,0 +1,33 @@ +--- +source: teller-cli/tests/flow_test.rs +expression: res +--- +Ok( + [ + KV { + value: "linus", + key: "USER_NAME", + from_key: "USER_NAME", + path: Some( + PathInfo { + id: "tvars", + path: "fixtures/flow_test_vars.env", + }, + ), + provider: Some( + ProviderInfo { + kind: Dotenv, + name: "dot_1", + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, + ], +) diff --git a/teller-cli/tests/snapshots/flow_test__flow-test-hashi-0.snap b/teller-cli/tests/snapshots/flow_test__flow-test-hashi-0.snap new file mode 100644 index 00000000..0e76f0e3 --- /dev/null +++ b/teller-cli/tests/snapshots/flow_test__flow-test-hashi-0.snap @@ -0,0 +1,58 @@ +--- +source: teller-cli/tests/flow_test.rs +expression: res +--- +Ok( + [ + KV { + value: "torvalds123", + key: "PASSWORD", + from_key: "PASSWORD", + path: Some( + PathInfo { + id: "pg-dev", + path: "secret/dev/postgres", + }, + ), + provider: Some( + ProviderInfo { + kind: Hashicorp, + name: "hashi_1", + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, + KV { + value: "linus", + key: "USER", + from_key: "USER", + path: Some( + PathInfo { + id: "pg-dev", + path: "secret/dev/postgres", + }, + ), + provider: Some( + ProviderInfo { + kind: Hashicorp, + name: "hashi_1", + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, + ], +) diff --git a/teller-cli/tests/snapshots/flow_test__flow-test-smgr-0.snap b/teller-cli/tests/snapshots/flow_test__flow-test-smgr-0.snap new file mode 100644 index 00000000..959d9746 --- /dev/null +++ b/teller-cli/tests/snapshots/flow_test__flow-test-smgr-0.snap @@ -0,0 +1,58 @@ +--- +source: teller-cli/tests/flow_test.rs +expression: res +--- +Ok( + [ + KV { + value: "torvalds123", + key: "PASSWORD", + from_key: "PASSWORD", + path: Some( + PathInfo { + id: "pg-dev", + path: "/dev/postgres", + }, + ), + provider: Some( + ProviderInfo { + kind: AWSSecretsManager, + name: "sm_1", + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, + KV { + value: "linus", + key: "USER", + from_key: "USER", + path: Some( + PathInfo { + id: "pg-dev", + path: "/dev/postgres", + }, + ), + provider: Some( + ProviderInfo { + kind: AWSSecretsManager, + name: "sm_1", + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, + ], +) diff --git a/teller-cli/tests/snapshots/flow_test__flow-test-ssm-0.snap b/teller-cli/tests/snapshots/flow_test__flow-test-ssm-0.snap new file mode 100644 index 00000000..8d244a06 --- /dev/null +++ b/teller-cli/tests/snapshots/flow_test__flow-test-ssm-0.snap @@ -0,0 +1,33 @@ +--- +source: teller-cli/tests/flow_test.rs +expression: res +--- +Ok( + [ + KV { + value: "linus", + key: "USER_NAME", + from_key: "USER", + path: Some( + PathInfo { + id: "pg-dev", + path: "/dev/postgres", + }, + ), + provider: Some( + ProviderInfo { + kind: SSM, + name: "ssm_1", + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, + ], +) diff --git a/teller-core/.gitattributes b/teller-core/.gitattributes new file mode 100644 index 00000000..5b61fd39 --- /dev/null +++ b/teller-core/.gitattributes @@ -0,0 +1 @@ +fixtures/* -text diff --git a/teller-core/Cargo.toml b/teller-core/Cargo.toml new file mode 100644 index 00000000..59171d2d --- /dev/null +++ b/teller-core/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "teller-core" +version = "0.1.0" +edition = "2021" + +[dependencies] +serde = { workspace = true } +serde_json = { workspace = true } +serde_yaml = { workspace = true } +serde_derive = { workspace = true } +serde_variant = { workspace = true } +lazy_static = { workspace = true } +strum = { workspace = true } +shell-words = "1" +duct = "0.13.6" +thiserror = { workspace = true } +fs-err = "2.9.0" +ignore = "*" +unicode-width = "*" +aho-corasick = { workspace = true } +tera = { workspace = true } +csv = "1.2.1" +teller-providers = { version = "*", path = "../teller-providers" } + +[dev-dependencies] +insta = { workspace = true } +stringreader = "*" diff --git a/teller-core/fixtures/config.yml b/teller-core/fixtures/config.yml new file mode 100644 index 00000000..dcaf5fc7 --- /dev/null +++ b/teller-core/fixtures/config.yml @@ -0,0 +1,18 @@ +providers: + hashi_1: + kind: hashicorp # name is = kind if empty + maps: + - id: test-load + path: /{{ get_env(name="TEST_LOAD_1", default="test") }}/users/user1 + # if empty, map everything + # == means map to same key name + # otherwise key on left becomes right + # in the future: key_transform: camelize, snake_case for automapping the keys + keys: + GITHUB_TOKEN: == + mg: FOO_BAR + dot_1: + kind: dotenv # name is = kind if empty + maps: + - id: stg + path: VAR_{{ get_env(name="STAGE", default="development") }} diff --git a/teller-core/src/config.rs b/teller-core/src/config.rs new file mode 100644 index 00000000..b2ff00d9 --- /dev/null +++ b/teller-core/src/config.rs @@ -0,0 +1,149 @@ +use std::cmp::Ordering; +use std::path::PathBuf; +use std::{ + collections::{BTreeMap, HashMap}, + path::Path, +}; + +use fs_err as fs; +use serde_derive::{Deserialize, Serialize}; +use teller_providers::config::{PathMap, ProviderCfg, KV}; +use teller_providers::providers::ProviderKind; +use tera::{Context, Tera}; + +use crate::Result; + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub struct Config { + pub providers: BTreeMap, +} + +#[derive(Serialize)] +pub struct RenderTemplate { + pub providers: Vec, +} + +fn apply_eqeq(config: &mut Config) { + config.providers.iter_mut().for_each(|(_name, provider)| { + provider.maps.iter_mut().for_each(|pm| { + pm.keys.iter_mut().for_each(|(k, v)| { + // THINK: replace with: + // 1. templating: {{id}} (identity), {{snake_case}} (snake case it) + // 2. other symbols: == id, ^^ capitalize, snake case __ lower snake case + if v == "==" { + v.clone_from(k); + } + }); + }); + }); +} + +impl Config { + /// Config from text + /// + /// # Errors + /// + /// This function will return an error if serialization fails + pub fn with_vars(text: &str, vars: &HashMap) -> Result { + let rendered_text = Tera::one_off(text, &Context::from_serialize(vars)?, false)?; + let mut config: Self = serde_yaml::from_str(&rendered_text)?; + + apply_eqeq(&mut config); + + Ok(config) + } + + /// Config from text + /// + /// # Errors + /// + /// This function will return an error if serialization fails + pub fn from_text(text: &str) -> Result { + Self::with_vars(text, &HashMap::new()) + } + + /// Config from file + /// + /// # Errors + /// + /// This function will return an error if IO fails + pub fn from_path(path: &Path) -> Result { + Self::from_text(&fs::read_to_string(path)?) + } + + /// Create configuration template file + /// + /// # Errors + /// When could not convert config to string + pub fn render_template(data: &RenderTemplate) -> Result { + let res: BTreeMap = data + .providers + .iter() + .map(|p| { + ( + format!("{p}_1"), + ProviderCfg { + kind: p.clone(), + maps: vec![PathMap::from_path("example/dev")], + ..ProviderCfg::default() + }, + ) + }) + .collect(); + + let config = Self { providers: res }; + + let a: String = serde_yaml::to_string(&config)?; + Ok(a) + } +} + +#[derive(Debug, Clone, Serialize, Eq, PartialEq)] +pub struct Match { + pub path: PathBuf, + pub position: Option<(usize, usize)>, + pub offset: usize, + pub query: KV, +} + +impl PartialOrd for Match { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Match { + fn cmp(&self, other: &Self) -> Ordering { + let query_cmp = self.query.cmp(&other.query); + + if query_cmp != Ordering::Equal { + return query_cmp; + } + + self.offset.cmp(&other.offset) + } +} + +#[cfg(test)] +mod tests { + use insta::assert_yaml_snapshot; + + use super::*; + #[test] + fn load_config() { + std::env::set_var("TEST_LOAD_1", "DEV"); + let config = Config::from_path(Path::new("fixtures/config.yml")).unwrap(); + assert_eq!(config.providers.len(), 2); + assert_yaml_snapshot!(config); + } + + #[test] + fn can_render_template_config() { + let data = RenderTemplate { + providers: vec![ProviderKind::Inmem, ProviderKind::Dotenv], + }; + + let config = Config::render_template(&data).unwrap(); + assert_yaml_snapshot!(config); + } +} diff --git a/teller-core/src/exec.rs b/teller-core/src/exec.rs new file mode 100644 index 00000000..a16d966a --- /dev/null +++ b/teller-core/src/exec.rs @@ -0,0 +1,193 @@ +use std::{collections::HashMap, path::Path, process::Output}; + +// use crate::{Error, Result}; +// use teller_providers::errors::{Error, Result}; +use crate::{Error, Result}; +pub struct Opts<'a> { + pub pwd: &'a Path, + pub capture: bool, + pub sh: bool, + pub reset_env: bool, +} + +const ENV_OK: &[&str] = &[ + "USER", + "HOME", + "PATH", + "TMPDIR", + "SHELL", + "SSH_AUTH_SOCK", + "LANG", + "LC_ALL", + "TEMPDIR", + "TERM", + "COLORTERM", + "LOGNAME", +]; + +/// Run a command +/// +/// # Errors +/// +/// This function will return an error if running command fails +pub fn cmd(cmdstr: &str, env_kvs: &[(String, String)], opts: &Opts<'_>) -> Result { + let words = if opts.sh { + shell_command_argv(cmdstr.into()) + } else { + shell_words::split(cmdstr)?.iter().map(Into::into).collect() + }; + cmd_slice( + words + .iter() + .map(String::as_str) + .collect::>() + .as_slice(), + env_kvs, + opts, + ) +} + +fn cmd_slice(words: &[&str], env_kvs: &[(String, String)], opts: &Opts<'_>) -> Result { + // env handling + let mut env_map: HashMap<_, _> = if opts.reset_env { + std::env::vars() + .filter(|(k, _)| ENV_OK.contains(&k.as_str())) + .collect() + } else { + std::env::vars().collect() + }; + + for (k, v) in env_kvs { + env_map.insert(k.clone(), v.clone()); + } + + // no shell + let (first, rest) = words + .split_first() + .ok_or_else(|| Error::Message("command has not enough arguments".to_string()))?; + + let mut expr = duct::cmd(Path::new(first), rest) + .dir(opts.pwd) + .full_env(&env_map); + + if opts.capture { + expr = expr.stdout_capture(); + } + + Ok(expr.run()?) +} + +#[cfg(unix)] +fn shell_command_argv(command: String) -> Vec { + use std::env; + + let shell = env::var("SHELL").unwrap_or_else(|_| "/bin/sh".into()); + vec![shell, "-c".into(), command] +} + +#[cfg(windows)] +fn shell_command_argv(command: String) -> Vec { + let comspec = std::env::var_os("COMSPEC") + .and_then(|s| s.into_string().ok()) + .unwrap_or_else(|| "cmd.exe".into()); + vec![comspec, "/C".into(), command] +} + +#[cfg(test)] +mod tests { + use std::path::Path; + + use insta::assert_debug_snapshot; + use teller_providers::config::ProviderInfo; + use teller_providers::config::KV; + use teller_providers::providers::ProviderKind; + + use super::cmd; + use super::Opts; + + #[test] + #[cfg(not(windows))] + fn run_echo() { + let out = cmd( + "echo $MY_VAR", + &std::iter::once(&KV::from_literal( + "/foo/bar", + "MY_VAR", + "shazam", + ProviderInfo { + kind: ProviderKind::Inmem, + name: "test".to_string(), + }, + )) + .map(|kv| (kv.key.clone(), kv.value.clone())) + .collect::>(), + &Opts { + pwd: Path::new("."), + capture: true, + reset_env: true, + sh: true, + }, + ) + .unwrap(); + let s = String::from_utf8_lossy(&out.stdout[..]); + assert_debug_snapshot!(s); + } + + #[ignore] + #[test] + fn env_reset() { + let out = cmd( + "/usr/bin/env", + &std::iter::once(&KV::from_literal( + "/foo/bar", + "MY_VAR", + "shazam", + ProviderInfo { + kind: ProviderKind::Inmem, + name: "test".to_string(), + }, + )) + .map(|kv| (kv.key.clone(), kv.value.clone())) + .collect::>(), + &Opts { + pwd: Path::new("."), + capture: true, + reset_env: false, // <-- notice this! + sh: false, + }, + ) + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout[..]).to_string(); + + // dirty secret here + assert!(stdout.contains("GITHUB_TOKEN=")); + + let out = cmd( + "/usr/bin/env", + &std::iter::once(&KV::from_literal( + "/foo/bar", + "MY_VAR", + "shazam", + ProviderInfo { + kind: ProviderKind::Inmem, + name: "test".to_string(), + }, + )) + .map(|kv| (kv.key.clone(), kv.value.clone())) + .collect::>(), + &Opts { + pwd: Path::new("."), + capture: true, + reset_env: true, // <-- reset env + sh: false, + }, + ) + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout[..]).to_string(); + + assert!(stdout.contains("USER=")); + assert!(stdout.contains("PATH=")); + // no secret here! + assert!(!stdout.contains("GITHUB_TOKEN=")); + } +} diff --git a/teller-core/src/export.rs b/teller-core/src/export.rs new file mode 100644 index 00000000..71bbe39b --- /dev/null +++ b/teller-core/src/export.rs @@ -0,0 +1,102 @@ +use std::collections::BTreeMap; +use std::str::FromStr; + +use csv::WriterBuilder; +use lazy_static::lazy_static; +use serde_derive::{Deserialize, Serialize}; +use serde_variant::to_variant_name; +use strum::EnumIter; +use strum::IntoEnumIterator; +use teller_providers::config::KV; + +use crate::{Error, Result}; + +lazy_static! { + pub static ref POSSIBLE_VALUES: String = { + let providers: Vec = Format::iter() + .map(|provider| provider.to_string()) + .collect(); + providers.join(", ") + }; +} + +#[derive(Serialize, Deserialize, Debug, Clone, EnumIter)] +pub enum Format { + #[serde(rename = "csv")] + CSV, + #[serde(rename = "yaml")] + YAML, + #[serde(rename = "json")] + JSON, + #[serde(rename = "env")] + ENV, + #[serde(rename = "shell")] + Shell, +} + +impl std::fmt::Display for Format { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + to_variant_name(self).expect("only enum supported").fmt(f) + } +} + +impl FromStr for Format { + type Err = &'static str; + + fn from_str(input: &str) -> Result { + let providers = Self::iter() + .map(|provider| (provider.to_string(), provider)) + .collect::>(); + + providers.get(input).map_or_else( + || Err(&POSSIBLE_VALUES as &'static str), + |provider| Ok(provider.clone()), + ) + } +} + +impl Format { + /// Export current format type to string + /// + /// # Errors + /// + pub fn export(&self, kvs: &[KV]) -> Result { + match self { + Self::YAML => Ok(serde_yaml::to_string(&KV::to_data(kvs))?), + Self::JSON => Ok(serde_json::to_string(&KV::to_data(kvs))?), + Self::CSV => Self::export_csv(kvs), + Self::ENV => Ok(Self::export_env(kvs)), + Self::Shell => Ok(Self::export_shell(kvs)), + } + } + + fn export_shell(kvs: &[KV]) -> String { + let mut out = String::new(); + out.push_str("#!/bin/sh\n"); + + for kv in kvs { + out.push_str(&format!("export {}='{}'\n", kv.key, kv.value)); + } + out + } + + fn export_env(kvs: &[KV]) -> String { + let mut out = String::new(); + for kv in kvs { + out.push_str(&format!("{}={}\n", kv.key, kv.value)); + } + out + } + + fn export_csv(kvs: &[KV]) -> Result { + let mut wtr = WriterBuilder::new().from_writer(vec![]); + for kv in kvs { + wtr.write_record(&[kv.key.clone(), kv.value.clone()])?; + } + Ok(String::from_utf8( + wtr.into_inner() + .map_err(Box::from) + .map_err(Error::CSVInner)?, + )?) + } +} diff --git a/teller-core/src/io.rs b/teller-core/src/io.rs new file mode 100644 index 00000000..7ade64cc --- /dev/null +++ b/teller-core/src/io.rs @@ -0,0 +1,20 @@ +use std::{ + io::{self, Read}, + path::Path, +}; + +use fs_err::File; + +pub fn is_binary_file(path: &Path) -> io::Result { + let mut file = File::open(path)?; + let mut buffer = [0; 1024]; // Read the first 1024 bytes of the file + + let bytes_read = file.read(&mut buffer)?; + for item in buffer.iter().take(bytes_read) { + if *item == 0 { + return Ok(true); // Found a null byte, indicating a binary file + } + } + + Ok(false) // No null byte found, likely a text file. +} diff --git a/teller-core/src/lib.rs b/teller-core/src/lib.rs new file mode 100644 index 00000000..df33951d --- /dev/null +++ b/teller-core/src/lib.rs @@ -0,0 +1,47 @@ +pub mod config; +pub mod exec; +pub mod export; +mod io; +pub mod redact; +pub mod scan; +pub mod teller; +pub mod template; + +use std::string::FromUtf8Error; + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error("{0}")] + Message(String), + + #[error(transparent)] + Shellwords(#[from] shell_words::ParseError), + + #[error(transparent)] + IO(#[from] std::io::Error), + + #[error(transparent)] + Provider(#[from] teller_providers::Error), + + #[error(transparent)] + Handlebars(Box), + + #[error(transparent)] + Json(#[from] serde_json::Error), + + #[error(transparent)] + YAML(#[from] serde_yaml::Error), + + #[error(transparent)] + CSV(#[from] csv::Error), + + #[error(transparent)] + CSVInner(Box), + + #[error(transparent)] + Tera(#[from] tera::Error), + + #[error(transparent)] + Utf(#[from] FromUtf8Error), +} +pub type Result = std::result::Result; diff --git a/teller-core/src/redact.rs b/teller-core/src/redact.rs new file mode 100644 index 00000000..d057c1f0 --- /dev/null +++ b/teller-core/src/redact.rs @@ -0,0 +1,114 @@ +use std::{ + borrow::Cow, + io::{BufRead, Write}, +}; + +// use crate::{Result, KV}; +use teller_providers::config::KV; + +pub struct Redactor {} + +impl Redactor { + #[must_use] + pub const fn new() -> Self { + Self {} + } + + /// Redact a reader into writer + /// + /// # Errors + /// + /// This function will return an error if IO fails + pub fn redact( + &self, + reader: R, + mut writer: W, + kvs: &[KV], + ) -> std::io::Result<()> { + for line in reader.lines().map_while(Result::ok) { + let redacted = self.redact_string(line.as_str(), kvs); + writer.write_all(redacted.as_bytes())?; + writer.write_all(&[b'\n'])?; // TODO: support crlf for windows + writer.flush()?; + } + Ok(()) + } + + #[must_use] + pub fn redact_string<'a>(&'a self, message: &'a str, kvs: &[KV]) -> Cow<'_, str> { + if self.has_match(message, kvs) { + let mut redacted = message.to_string(); + for kv in kvs { + redacted = redacted.replace( + &kv.value, + kv.meta + .as_ref() + .and_then(|m| m.redact_with.as_ref()) + .map_or("[REDACTED]", |s| s.as_str()), + ); + } + Cow::Owned(redacted) + } else { + Cow::Borrowed(message) + } + } + + #[must_use] + pub fn has_match<'a>(&'a self, message: &'a str, kvs: &[KV]) -> bool { + kvs.iter().any(|kv| message.contains(&kv.value)) + } +} + +impl Default for Redactor { + fn default() -> Self { + Self::new() + } +} + +#[cfg(test)] +mod tests { + use std::io::{BufReader, BufWriter}; + + use stringreader::StringReader; + use teller_providers::{config::ProviderInfo, providers::ProviderKind}; + + use super::*; + + #[test] + fn redact_none() { + let data = "foobar\nfoobaz\n"; + let mut reader = BufReader::new(StringReader::new(data)); + let mut writer = BufWriter::new(Vec::new()); + let redactor = Redactor {}; + + redactor.redact(&mut reader, &mut writer, &[]).unwrap(); + let s = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert_eq!(s, "foobar\nfoobaz\n"); + } + + #[test] + fn redact_some() { + let data = "foobar\nfoobaz\n"; + let mut reader = BufReader::new(StringReader::new(data)); + let mut writer = BufWriter::new(Vec::new()); + let redactor = Redactor {}; + + redactor + .redact( + &mut reader, + &mut writer, + &[KV::from_literal( + "some/path", + "k", + "foobaz", + ProviderInfo { + kind: ProviderKind::Inmem, + name: "test".to_string(), + }, + )], + ) + .unwrap(); + let s = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert_eq!(s, "foobar\n[REDACTED]\n"); + } +} diff --git a/teller-core/src/scan.rs b/teller-core/src/scan.rs new file mode 100644 index 00000000..923b8aa4 --- /dev/null +++ b/teller-core/src/scan.rs @@ -0,0 +1,182 @@ +use std::fs; + +use aho_corasick::AhoCorasick; +use ignore::WalkBuilder; +use teller_providers::config::KV; +use unicode_width::UnicodeWidthStr; + +use crate::{config::Match, io::is_binary_file, Error, Result}; + +#[derive(Debug, Clone, Default)] +pub struct Opts { + pub include_all: bool, + pub include_binary: bool, +} + +/// (ln, col), 1 based (not zero based) +fn get_visual_position(text: &[u8], byte_position: usize) -> Option<(usize, usize)> { + if byte_position >= text.len() || text.is_empty() { + return None; + } + + let lines = text + .iter() + .take(byte_position) + .filter(|c| **c == b'\n') + .count(); + let last_ln_start = text + .iter() + .take(byte_position) + .rposition(|c| *c == b'\n') + .unwrap_or(0); + + let len = UnicodeWidthStr::width( + String::from_utf8_lossy(&text[last_ln_start..byte_position]).as_ref(), + ); + + // index starts from 1 for both + Some((lines + 1, len + 1)) +} + +// aho +// offset into row/col visual https://github.com/zkat/miette/blob/f4d056e1ffeb9a0bf36e2a6501365bd7e00db22d/src/handlers/graphical.rs#L619 +// match repr +/// +/// # Errors +/// +/// TODO +#[allow(clippy::module_name_repetitions)] +pub fn scan_root(root: &str, kvs: &[KV], opts: &Opts) -> Result> { + let patterns = kvs.iter().map(|kv| kv.value.as_str()).collect::>(); + let finder = AhoCorasick::new(patterns).map_err(|e| Error::Message(e.to_string()))?; + + let mut wb = WalkBuilder::new(root); + + let mut matches = vec![]; + for entry in wb + .ignore(!opts.include_all) + .git_ignore(!opts.include_all) + .hidden(opts.include_all) + .build() + .filter_map(Result::ok) + .filter(|ent| ent.path().is_file()) + { + let path = entry.path(); + if is_binary_file(path)? && !opts.include_binary { + continue; + } + + let content = String::from_utf8_lossy(&fs::read(path)?).to_string(); + let bytes = content.as_bytes(); + + finder.find_iter(&content).for_each(|aho_match| { + matches.push(Match { + path: path.to_path_buf(), + query: kvs[aho_match.pattern()].clone(), + position: get_visual_position(bytes, aho_match.start()), + offset: aho_match.start(), + }); + }); + } + + matches.sort(); + Ok(matches) +} + +#[cfg(test)] +mod tests { + use std::{ + fs, + path::{Path, PathBuf}, + }; + + use insta::assert_debug_snapshot; + use teller_providers::{ + config::{ProviderInfo, KV}, + providers::ProviderKind, + }; + + use super::*; + use crate::scan; + + fn normalize_path_separators(path: &Path) -> PathBuf { + let path_str = path.to_string_lossy().replace('\\', "/"); + PathBuf::from(path_str) + } + fn normalize_matches(ms: &[Match]) -> Vec { + ms.iter() + .map(|m| Match { + path: normalize_path_separators(&m.path), + ..m.clone() + }) + .collect::>() + } + + #[test] + fn test_position() { + assert_eq!(get_visual_position(b"", 4), None); + assert_eq!(get_visual_position(b"", 1), None); + assert_eq!(get_visual_position(b"", 0), None); + assert_eq!(get_visual_position(b"a", 1), None); + + assert_eq!(get_visual_position(b"abcde\nfghi", 8), Some((2, 3))); + assert_eq!(get_visual_position(b"abcde\r\nfghi", 8), Some((2, 2))); + + let text = r#" 100% ❯ j teller-rs + /Users/jondot/spikes/teller-rs + (base) + ~/spikes/teller-rs on  master [!?] via 🦀 v1.73.0-nightly +  100% ❯ code . + (base) + ~/spikes/teller-rs on  master [!?] via 🦀 v1.73.0-nightly +  100% ❯ [WARN] - (starship::utils): Executing command "/opt/homebrew/bin/git" timed out. + (base) + ~/spikes/teller-rs on  master [!?] via 🦀 v1.73.0-nightly +  100% ❯ open /Users/jondot/Movies + (base) + ~/spikes/teller-rs on  master [!?] via 🦀 v1.73.0-nightly +  100% ❯"#; + let position = get_visual_position(text.as_bytes(), 438); + assert_eq!(position, Some((11, 19))); + } + + #[test] + fn test_scan() { + let provider = ProviderInfo { + kind: ProviderKind::Inmem, + name: "test".to_string(), + }; + let kvs = vec![ + KV::from_literal("/some/path", "key1", "hashicorp", provider.clone()), + KV::from_literal("/some/path", "key1", "dont-find-me", provider.clone()), + KV::from_literal("/some/path", "key1", "trooper123", provider.clone()), + KV::from_literal("/some/path", "key1", "pass1", provider.clone()), + KV::from_literal("/some/path", "key1", "nested111", provider), + ]; + + let res = scan_root("fixtures", &kvs[..], &scan::Opts::default()); + assert_debug_snapshot!(normalize_matches(&res.unwrap())); + + let res = scan_root( + "fixtures", + &kvs[..], + &scan::Opts { + include_binary: true, + include_all: false, + }, + ); + assert_debug_snapshot!(normalize_matches(&res.unwrap())); + + fs::write("fixtures/git-ignored-file", "trooper123").expect("cannot write file"); + + let res = scan_root( + "fixtures", + &kvs[..], + &scan::Opts { + include_binary: false, + include_all: true, + }, + ); + assert_debug_snapshot!(normalize_matches(&res.unwrap())); + } +} diff --git a/teller-core/src/snapshots/teller_core__config__tests__can_render_template_config.snap b/teller-core/src/snapshots/teller_core__config__tests__can_render_template_config.snap new file mode 100644 index 00000000..8398068c --- /dev/null +++ b/teller-core/src/snapshots/teller_core__config__tests__can_render_template_config.snap @@ -0,0 +1,5 @@ +--- +source: teller-core/src/config.rs +expression: config +--- +"providers:\n dotenv_1:\n kind: dotenv\n maps:\n - id: ''\n path: example/dev\n inmem_1:\n kind: inmem\n maps:\n - id: ''\n path: example/dev\n" diff --git a/teller-core/src/snapshots/teller_core__config__tests__load_config.snap b/teller-core/src/snapshots/teller_core__config__tests__load_config.snap new file mode 100644 index 00000000..add5a9e7 --- /dev/null +++ b/teller-core/src/snapshots/teller_core__config__tests__load_config.snap @@ -0,0 +1,18 @@ +--- +source: teller-core/src/config.rs +expression: config +--- +providers: + dot_1: + kind: dotenv + maps: + - id: stg + path: VAR_development + hashi_1: + kind: hashicorp + maps: + - id: test-load + path: /DEV/users/user1 + keys: + GITHUB_TOKEN: GITHUB_TOKEN + mg: FOO_BAR diff --git a/teller-core/src/snapshots/teller_core__exec__tests__run_echo.snap b/teller-core/src/snapshots/teller_core__exec__tests__run_echo.snap new file mode 100644 index 00000000..c2ac7ba7 --- /dev/null +++ b/teller-core/src/snapshots/teller_core__exec__tests__run_echo.snap @@ -0,0 +1,5 @@ +--- +source: src/exec.rs +expression: s +--- +"shazam\n" diff --git a/teller-core/src/snapshots/teller_core__scan__tests__scan-2.snap b/teller-core/src/snapshots/teller_core__scan__tests__scan-2.snap new file mode 100644 index 00000000..627f8937 --- /dev/null +++ b/teller-core/src/snapshots/teller_core__scan__tests__scan-2.snap @@ -0,0 +1,34 @@ +--- +source: teller-core/src/scan.rs +expression: normalize_matches(res.unwrap()) +--- +[ + Match { + path: "fixtures/config.yml", + position: Some( + ( + 3, + 11, + ), + ), + offset: 32, + query: KV { + value: "hashicorp", + key: "key1", + from_key: "key1", + path: Some( + PathInfo { + id: "/some/path", + path: "/some/path", + }, + ), + provider: Some( + ProviderInfo { + kind: Inmem, + name: "test", + }, + ), + meta: None, + }, + }, +] diff --git a/teller-core/src/snapshots/teller_core__scan__tests__scan-3.snap b/teller-core/src/snapshots/teller_core__scan__tests__scan-3.snap new file mode 100644 index 00000000..fd059e74 --- /dev/null +++ b/teller-core/src/snapshots/teller_core__scan__tests__scan-3.snap @@ -0,0 +1,62 @@ +--- +source: teller-core/src/scan.rs +expression: normalize_matches(res.unwrap()) +--- +[ + Match { + path: "fixtures/git-ignored-file", + position: Some( + ( + 1, + 1, + ), + ), + offset: 0, + query: KV { + value: "trooper123", + key: "key1", + from_key: "key1", + path: Some( + PathInfo { + id: "/some/path", + path: "/some/path", + }, + ), + provider: Some( + ProviderInfo { + kind: Inmem, + name: "test", + }, + ), + meta: None, + }, + }, + Match { + path: "fixtures/config.yml", + position: Some( + ( + 3, + 11, + ), + ), + offset: 32, + query: KV { + value: "hashicorp", + key: "key1", + from_key: "key1", + path: Some( + PathInfo { + id: "/some/path", + path: "/some/path", + }, + ), + provider: Some( + ProviderInfo { + kind: Inmem, + name: "test", + }, + ), + meta: None, + }, + }, +] diff --git a/teller-core/src/snapshots/teller_core__scan__tests__scan.snap b/teller-core/src/snapshots/teller_core__scan__tests__scan.snap new file mode 100644 index 00000000..627f8937 --- /dev/null +++ b/teller-core/src/snapshots/teller_core__scan__tests__scan.snap @@ -0,0 +1,34 @@ +--- +source: teller-core/src/scan.rs +expression: normalize_matches(res.unwrap()) +--- +[ + Match { + path: "fixtures/config.yml", + position: Some( + ( + 3, + 11, + ), + ), + offset: 32, + query: KV { + value: "hashicorp", + key: "key1", + from_key: "key1", + path: Some( + PathInfo { + id: "/some/path", + path: "/some/path", + }, + ), + provider: Some( + ProviderInfo { + kind: Inmem, + name: "test", + }, + ), + meta: None, + }, + }, +] diff --git a/teller-core/src/snapshots/teller_core__template__tests__render_template.snap b/teller-core/src/snapshots/teller_core__template__tests__render_template.snap new file mode 100644 index 00000000..e76a9f28 --- /dev/null +++ b/teller-core/src/snapshots/teller_core__template__tests__render_template.snap @@ -0,0 +1,7 @@ +--- +source: teller-core/src/template.rs +expression: "render(\"hello {{ key(name='k') }}\", kvs)" +--- +Ok( + "hello foobaz", +) diff --git a/teller-core/src/teller.rs b/teller-core/src/teller.rs new file mode 100644 index 00000000..f9e648fd --- /dev/null +++ b/teller-core/src/teller.rs @@ -0,0 +1,217 @@ +use std::collections::BTreeMap; +use std::io::{BufRead, Write}; +use std::path::Path; +use std::process::Output; + +use teller_providers::config::PathMap; +use teller_providers::Provider; +// use csv::WriterBuilder; +use teller_providers::{config::KV, registry::Registry, Result as ProviderResult}; + +use crate::redact::Redactor; +use crate::template; +use crate::{ + config::{Config, Match}, + exec, export, scan, Error, Result, +}; + +pub struct Teller { + registry: Registry, + config: Config, +} + +impl Teller { + /// Build from config + /// + /// # Errors + /// + /// This function will return an error if loading fails + pub async fn from_config(config: &Config) -> teller_providers::Result { + let registry = Registry::new(&config.providers).await?; + Ok(Self { + registry, + config: config.clone(), + }) + } + + /// Build from YAML + /// + /// # Errors + /// + /// This function will return an error if loading fails + pub async fn from_yaml(file: &Path) -> Result { + let config = Config::from_path(file)?; + Self::from_config(&config).await.map_err(Error::Provider) + } + /// Collects kvs from all provider maps in the current configuration + /// + /// # Errors + /// + /// This function will return an error if IO fails + pub async fn collect(&self) -> ProviderResult> { + let mut res = Vec::new(); + for (name, providercfg) in &self.config.providers { + if let Some(provider) = self.registry.get(name) { + for pm in &providercfg.maps { + let kvs = provider.get(pm).await?; + res.push(kvs); + } + } + } + Ok(res.into_iter().flatten().collect::>()) + } + /// Put a list of KVs into a list of providers, on a specified path + /// + /// # Errors + /// + /// This function will return an error if put fails + pub async fn put(&self, kvs: &[KV], map_id: &str, providers: &[String]) -> Result<()> { + // a target provider has to have the specified path id + for provider_name in providers { + let (provider, pm) = self.get_pathmap_on_provider(map_id, provider_name)?; + provider.put(pm, kvs).await?; + } + Ok(()) + } + + /// Delete a list of keys or a complete path for every provider in the list + /// + /// # Errors + /// + /// This function will return an error if delete fails + pub async fn delete(&self, keys: &[String], map_id: &str, providers: &[String]) -> Result<()> { + // a target provider has to have the specified path id + for provider_name in providers { + let (provider, pm) = self.get_pathmap_on_provider(map_id, provider_name)?; + // 1. if keys is empty, use the default pathmap + // 2. otherwise, create a new pathmap, with a subset of keys + if keys.is_empty() { + provider.del(pm).await?; + } else { + let mut subset_keys = BTreeMap::new(); + for key in keys { + subset_keys.insert(key.clone(), key.clone()); + } + let mut new_pm = pm.clone(); + new_pm.keys = subset_keys; + provider.del(&new_pm).await?; + } + } + Ok(()) + } + /// Get a provider and pathmap from configuration and registry + /// + /// # Errors + /// + /// This function will return an error if operation fails + #[allow(clippy::borrowed_box)] + pub fn get_pathmap_on_provider( + &self, + map_id: &str, + provider_name: &String, + ) -> Result<(&Box, &PathMap)> { + let pconf = self.config.providers.get(provider_name).ok_or_else(|| { + Error::Message(format!( + "cannot find provider '{provider_name}' path configuration" + )) + })?; + let pm = pconf.maps.iter().find(|m| m.id == map_id).ok_or_else(|| { + Error::Message(format!( + "cannot find path id '{map_id}' in provider '{provider_name}'" + )) + })?; + let provider = self.registry.get(provider_name).ok_or_else(|| { + Error::Message(format!("cannot get initialized provider '{provider_name}'")) + })?; + Ok((provider, pm)) + } + /// Run an external command with provider based environment variables + /// + /// # Errors + /// + /// This function will return an error if command fails + pub async fn run<'a>(&self, cmd: &[&str], opts: &exec::Opts<'a>) -> Result { + let cmd = shell_words::join(cmd); + let kvs = self.collect().await?; + let res = exec::cmd( + cmd.as_str(), + &kvs.iter() + .map(|kv| (kv.key.clone(), kv.value.clone())) + .collect::>()[..], + opts, + )?; + Ok(res) + } + + /// Redact streams + /// + /// # Errors + /// + /// This function will return an error if Is or collecting keys fails + #[allow(clippy::future_not_send)] + pub async fn redact(&self, reader: R, writer: W) -> Result<()> { + let kvs = self.collect().await?; + let redactor = Redactor::new(); + redactor.redact(reader, writer, kvs.as_slice())?; + Ok(()) + } + + /// Populate a custom template with KVs + /// + /// # Errors + /// + /// This function will return an error if template rendering fails + pub async fn template(&self, template: &str) -> Result { + let kvs = self.collect().await?; + let out = template::render(template, kvs)?; // consumes kvs + Ok(out) + } + + /// Export KV data + /// + /// # Errors + /// + /// This function will return an error if export fails + pub async fn export<'a>(&self, format: &export::Format) -> Result { + let kvs = self.collect().await?; + format.export(&kvs) + } + + /// Scan a folder recursively for secrets or values + /// + /// # Errors + /// + /// This function will return an error if IO fails + pub fn scan(&self, root: &str, kvs: &[KV], opts: &scan::Opts) -> Result> { + scan::scan_root(root, kvs, opts) + } + + /// Copy from provider to target provider. + /// Note: `replace` will first delete data at target, then copy. + /// + /// # Errors + /// + /// This function will return an error if copy fails + pub async fn copy( + &self, + from_provider: &str, + from_map_id: &str, + to_provider: &str, + to_map_id: &str, + replace: bool, + ) -> Result<()> { + // XXX fix &str, &String params + let (from_provider, from_pm) = + self.get_pathmap_on_provider(from_map_id, &from_provider.to_string())?; + let data = from_provider.get(from_pm).await?; + + let (to_provider, to_pm) = + self.get_pathmap_on_provider(to_map_id, &to_provider.to_string())?; + + if replace { + to_provider.del(to_pm).await?; + } + to_provider.put(to_pm, &data).await?; + Ok(()) + } +} diff --git a/teller-core/src/template.rs b/teller-core/src/template.rs new file mode 100644 index 00000000..229c29b6 --- /dev/null +++ b/teller-core/src/template.rs @@ -0,0 +1,62 @@ +use teller_providers::config::KV; +use tera::{from_value, to_value, Context, Result, Tera}; + +struct KeyFn { + kvs: Vec, +} +impl tera::Function for KeyFn { + fn call( + &self, + args: &std::collections::HashMap, + ) -> tera::Result { + args.get("name").map_or_else( + || Err("cannot get parameter 'name'".into()), + |val| { + from_value::(val.clone()).map_or_else( + |_| Err("cannot get parameter 'name'".into()), + |v| { + self.kvs + .iter() + .find(|kv| kv.key == v) + .and_then(|kv| to_value(&kv.value).ok()) + .ok_or_else(|| "not found".into()) + }, + ) + }, + ) + } +} + +/// Render a template with access to KVs +/// +/// # Errors +/// +/// This function will return an error if rendering fails +pub fn render(template: &str, kvs: Vec) -> Result { + let mut tera = Tera::default(); + tera.register_function("key", KeyFn { kvs }); + let res = tera.render_str(template, &Context::new())?; + Ok(res) +} + +#[cfg(test)] +mod tests { + use insta::assert_debug_snapshot; + use teller_providers::{config::ProviderInfo, providers::ProviderKind}; + + use super::*; + + #[test] + fn render_template() { + let kvs = &[KV::from_literal( + "some/path", + "k", + "foobaz", + ProviderInfo { + kind: ProviderKind::Inmem, + name: "test".to_string(), + }, + )]; + assert_debug_snapshot!(render("hello {{ key(name='k') }}", kvs.to_vec())); + } +} diff --git a/teller-providers/Cargo.toml b/teller-providers/Cargo.toml new file mode 100644 index 00000000..ae8f6ea2 --- /dev/null +++ b/teller-providers/Cargo.toml @@ -0,0 +1,59 @@ +[package] +name = "teller-providers" +version = "0.1.0" +edition = "2021" + +# [lib] +# name = "teller-providers" + +[features] +default = [ + "hashicorp_vault", + "dotenv", + "ssm", + "aws_secretsmanager", + "google_secretmanager", + "hashicorp_consul", +] + +ssm = ["aws", "dep:aws-sdk-ssm"] +aws_secretsmanager = ["aws", "dep:aws-sdk-secretsmanager"] +google_secretmanager = ["dep:google-secretmanager1", "dep:crc32c"] +hashicorp_vault = ["dep:vaultrs", "dep:rustify"] +dotenv = ["dep:dotenvy"] +hashicorp_consul = ["dep:consulrs"] +aws = ["dep:aws-config"] + +[dependencies] +async-trait = { workspace = true } +lazy_static = { workspace = true } +serde_variant = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +serde_yaml = { workspace = true } +serde_derive = { workspace = true } +strum = { workspace = true } +thiserror = { workspace = true } +fs-err = "2.9.0" +home = "0.5.5" +# gcp +google-secretmanager1 = { version = "5.0.2", optional = true } +crc32c = { version = "0.6", optional = true } +# aws +aws-config = { version = "1.2.0", optional = true } +# aws-ssm +aws-sdk-ssm = { version = "1.22.0", optional = true } +# aws-secretsmanager +aws-sdk-secretsmanager = { version = "1.22.0", optional = true } +# dotenv +dotenvy = { version = "0.15.7", optional = true } +# hashivault +vaultrs = { version = "0.7.2", optional = true } +rustify = { version = "0.5.3", optional = true } +# HashiCorp Consul +consulrs = { git = "https://github.com/jmgilman/consulrs", optional = true, rev = "a14fddbdf3695e2e338145134c4b42f823e03370" } + +[dev-dependencies] +insta = { workspace = true } +dockertest-server = { version = "0.1.7", features = ["hashi", "cloud"] } +tokio = { workspace = true } diff --git a/teller-providers/src/config.rs b/teller-providers/src/config.rs new file mode 100644 index 00000000..bec92c49 --- /dev/null +++ b/teller-providers/src/config.rs @@ -0,0 +1,202 @@ +use std::cmp::Ordering; +use std::collections::BTreeMap; + +use serde_derive::{Deserialize, Serialize}; + +use crate::providers::ProviderKind; + +fn is_default(t: &T) -> bool { + t == &T::default() +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub struct ProviderCfg { + #[serde(rename = "kind")] + pub kind: ProviderKind, + #[serde(rename = "options", skip_serializing_if = "Option::is_none")] + pub options: Option, + #[serde(rename = "name", skip_serializing_if = "Option::is_none")] + pub name: Option, + pub maps: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default, Eq, PartialEq)] +pub enum Sensitivity { + #[default] + None, + Low, + Medium, + High, + Critical, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default, Eq, PartialEq)] +pub struct ProviderInfo { + pub kind: ProviderKind, + pub name: String, +} +#[derive(Serialize, Deserialize, Debug, Clone, Default, Eq, PartialEq)] +pub struct PathInfo { + pub id: String, + pub path: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default, Eq, PartialEq)] +pub struct MetaInfo { + pub sensitivity: Sensitivity, + pub redact_with: Option, + pub source: Option, + pub sink: Option, +} +#[derive(Serialize, Deserialize, Debug, Clone, Default, Eq, PartialEq)] +pub struct KV { + pub value: String, + pub key: String, // mapped-to key + pub from_key: String, + pub path: Option, // always toplevel + pub provider: Option, + pub meta: Option, +} + +impl PartialOrd for KV { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for KV { + fn cmp(&self, other: &Self) -> Ordering { + if let (Some(provider), Some(other_provider)) = (&self.provider, &other.provider) { + let provider_cmp = provider.kind.cmp(&other_provider.kind); + if provider_cmp != Ordering::Equal { + return provider_cmp; + } + } + + self.key.cmp(&other.key) + } +} + +impl KV { + #[must_use] + pub fn to_data(kvs: &[Self]) -> BTreeMap { + let mut data = BTreeMap::new(); + for kv in kvs { + data.insert(kv.key.clone(), kv.value.clone()); + } + data + } + + #[must_use] + pub fn from_data( + data: &BTreeMap, + pm: &PathMap, + provider: &ProviderInfo, + ) -> Vec { + // map all of the data found + if pm.keys.is_empty() { + data.iter() + .map(|(k, v)| Self::from_value(v, k, k, pm, provider.clone())) + .collect::>() + } else { + // selectively map only keys from pathmap + pm.keys + .iter() + .filter_map(|(from_key, to_key)| { + data.get(from_key).map(|found_val| { + Self::from_value(found_val, from_key, to_key, pm, provider.clone()) + }) + }) + .collect::>() + } + } + #[must_use] + pub fn from_value( + found_val: &str, + from_key: &str, + to_key: &str, + pm: &PathMap, + provider: ProviderInfo, + ) -> Self { + Self { + value: found_val.to_string(), + key: to_key.to_string(), + from_key: from_key.to_string(), + path: Some(PathInfo { + path: pm.path.clone(), + id: pm.id.to_string(), + }), + provider: Some(provider), + meta: Some(MetaInfo { + sensitivity: pm.sensitivity.clone(), + redact_with: pm.redact_with.clone(), + source: pm.source.clone(), + sink: pm.sink.clone(), + }), + } + } + #[must_use] + pub fn from_literal(path: &str, key: &str, value: &str, provider: ProviderInfo) -> Self { + Self { + value: value.to_string(), + key: key.to_string(), + from_key: key.to_string(), + path: Some(PathInfo { + id: path.to_string(), + path: path.to_string(), + }), + provider: Some(provider), + ..Default::default() + } + } + + /// represents a KV without any source (e.g. created manually by a user, pending insert to + /// one of the providers) + #[must_use] + pub fn from_kv(key: &str, value: &str) -> Self { + Self { + value: value.to_string(), + key: key.to_string(), + from_key: key.to_string(), + ..Default::default() + } + } +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub struct PathMap { + pub id: String, + #[serde(rename = "protocol", skip_serializing_if = "Option::is_none")] + pub protocol: Option, + #[serde(rename = "path")] + pub path: String, + #[serde(default, rename = "keys", skip_serializing_if = "is_default")] + pub keys: BTreeMap, + #[serde(default, rename = "decrypt", skip_serializing_if = "is_default")] + pub decrypt: bool, + #[serde(default, rename = "sensitivity", skip_serializing_if = "is_default")] + pub sensitivity: Sensitivity, + #[serde( + default, + rename = "redact_with", + skip_serializing_if = "Option::is_none" + )] + pub redact_with: Option, + #[serde(default, rename = "source", skip_serializing_if = "Option::is_none")] + pub source: Option, + #[serde(default, rename = "sink", skip_serializing_if = "Option::is_none")] + pub sink: Option, + // ignore population if optional + we got error + #[serde(default, rename = "optional", skip_serializing_if = "is_default")] + pub optional: bool, +} + +impl PathMap { + #[must_use] + pub fn from_path(path: &str) -> Self { + Self { + path: path.to_string(), + ..Default::default() + } + } +} diff --git a/teller-providers/src/lib.rs b/teller-providers/src/lib.rs new file mode 100644 index 00000000..1f86f642 --- /dev/null +++ b/teller-providers/src/lib.rs @@ -0,0 +1,70 @@ +pub mod config; +pub mod providers; +pub mod registry; + +use async_trait::async_trait; + +use crate::config::{PathMap, ProviderInfo, KV}; + +#[async_trait] +pub trait Provider { + fn kind(&self) -> ProviderInfo; + /// Get a mapping + /// + /// # Errors + /// + /// ... + async fn get(&self, pm: &PathMap) -> Result>; + /// Put a mapping + /// + /// # Errors + /// + /// ... + async fn put(&self, pm: &PathMap, kvs: &[KV]) -> Result<()>; + /// Delete a mapping + /// + /// # Errors + /// + /// ... + async fn del(&self, pm: &PathMap) -> Result<()>; +} +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error("{0}")] + Message(String), + + #[error("{0}: {1}")] + PathError(String, String), + + #[error(transparent)] + IO(#[from] std::io::Error), + + #[error(transparent)] + Env(#[from] std::env::VarError), + + #[error(transparent)] + Any(#[from] Box), + + #[error(transparent)] + Json(#[from] serde_json::Error), + + #[error(transparent)] + YAML(#[from] serde_yaml::Error), + + #[error("NOT FOUND {path}: {msg}")] + NotFound { path: String, msg: String }, + + #[error("GET {path}: {msg}")] + GetError { path: String, msg: String }, + + #[error("DEL {path}: {msg}")] + DeleteError { path: String, msg: String }, + + #[error("PUT {path}: {msg}")] + PutError { path: String, msg: String }, + + #[error("LIST {path}: {msg}")] + ListError { path: String, msg: String }, +} + +pub type Result = std::result::Result; diff --git a/teller-providers/src/providers/aws_secretsmanager.rs b/teller-providers/src/providers/aws_secretsmanager.rs new file mode 100644 index 00000000..9055c737 --- /dev/null +++ b/teller-providers/src/providers/aws_secretsmanager.rs @@ -0,0 +1,318 @@ +//! AWS Secret Manager +//! +//! +//! ## Example configuration +//! +//! ```yaml +//! providers: +//! aws1: +//! kind: aws_secretsmanager +//! # options: ... +//! ``` +//! ## Options +//! +//! See [`AWSSecretsManagerOptions`] +//! +//! +#![allow(clippy::borrowed_box)] + +use std::collections::BTreeMap; + +use async_trait::async_trait; +use aws_config::{self, BehaviorVersion}; +use aws_sdk_secretsmanager as secretsmanager; +use secretsmanager::config::{Credentials, Region}; +use secretsmanager::operation::get_secret_value::GetSecretValueError; +use secretsmanager::{error::SdkError, operation::delete_secret::DeleteSecretError}; +use serde_derive::{Deserialize, Serialize}; + +use super::ProviderKind; +use crate::config::ProviderInfo; +use crate::{ + config::{PathMap, KV}, + Error, Provider, Result, +}; + +fn handle_get_err( + mode: &Mode, + e: SdkError, + pm: &PathMap, +) -> Result> { + match e.into_service_error() { + GetSecretValueError::ResourceNotFoundException(_) => { + if mode == &Mode::Get { + Err(Error::NotFound { + path: pm.path.to_string(), + msg: "not found".to_string(), + }) + } else { + // we're ok + Ok(None) + } + } + e => { + if e.to_string().contains("marked deleted") { + Err(Error::NotFound { + path: pm.path.to_string(), + msg: "not found".to_string(), + }) + } else { + Err(Error::GetError { + path: pm.path.to_string(), + msg: e.to_string(), + }) + } + } + } +} + +fn handle_del_err(e: SdkError, pm: &PathMap) -> Result<()> { + match e.into_service_error() { + DeleteSecretError::ResourceNotFoundException(_) => { + // we're ok + Ok(()) + } + e => Err(Error::DeleteError { + path: pm.path.to_string(), + msg: e.to_string(), + }), + } +} + +#[derive(PartialEq)] +enum Mode { + Get, + Put, + Del, +} + +/// +/// # AWS provider configuration +/// +/// This holds the most commonly used and simplified configuration options for this provider. These +/// paramters can be used in the Teller YAML configuration. +/// +/// For indepth description of each parameter see: [AWS SDK config](https://docs.rs/aws-config/latest/aws_config/struct.SdkConfig.html) +/// +/// If you need an additional parameter from the AWS SDK included in our simplified configuration, +/// open an issue in Teller and request to add it. +/// +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct AWSSecretsManagerOptions { + pub region: Option, + pub access_key_id: Option, + pub secret_access_key: Option, + pub endpoint_url: Option, +} + +pub struct AWSSecretsManager { + pub client: secretsmanager::Client, + pub name: String, +} + +impl AWSSecretsManager { + #[must_use] + pub fn with_client(name: &str, client: secretsmanager::Client) -> Self { + Self { + client, + name: name.to_string(), + } + } + /// Create a new secretsmanager provider + /// + /// # Errors + /// + /// This function will return an error if cannot create a provider + pub async fn new(name: &str, opts: Option) -> Result { + let client = if let Some(opts) = opts { + let mut config = aws_config::defaults(BehaviorVersion::v2023_11_09()); + if let (Some(key), Some(secret)) = (opts.access_key_id, opts.secret_access_key) { + config = config + .credentials_provider(Credentials::new(key, secret, None, None, "teller")); + } + if let Some(endpoint_url) = opts.endpoint_url { + config = config.endpoint_url(endpoint_url); + } + if let Some(region) = opts.region { + config = config.region(Region::new(region)); + } + let ssmconf = secretsmanager::config::Builder::from(&config.load().await).build(); + secretsmanager::Client::from_conf(ssmconf) + } else { + let config = aws_config::load_defaults(BehaviorVersion::v2023_11_09()).await; + let ssmconf = secretsmanager::config::Builder::from(&config).build(); + secretsmanager::Client::from_conf(ssmconf) + }; + Ok(Self { + client, + name: name.to_string(), + }) + } +} + +async fn get_data( + mode: &Mode, + client: &secretsmanager::Client, + pm: &PathMap, +) -> Result>> { + let resp = client + .get_secret_value() + .secret_id(&pm.path) + .send() + .await + .map_or_else( + |e| handle_get_err(mode, e, pm), + |res| Ok(res.secret_string().map(std::string::ToString::to_string)), + )?; + + if let Some(raw_string) = resp { + Ok(Some(serde_json::from_str::>( + &raw_string, + )?)) + } else { + Ok(None) + } +} + +async fn put_data( + client: &secretsmanager::Client, + pm: &PathMap, + data: &BTreeMap, +) -> Result<()> { + if client + .get_secret_value() + .secret_id(&pm.path) + .send() + .await + .is_ok() + { + client + .put_secret_value() + .set_secret_id(Some(pm.path.clone())) + .secret_string(serde_json::to_string(&data)?) + .send() + .await + .map_err(|e| Error::PutError { + msg: e.to_string(), + path: pm.path.clone(), + })?; + } else { + client + .create_secret() + .set_name(Some(pm.path.clone())) + .secret_string(serde_json::to_string(&data)?) + .send() + .await + .map_err(|e| Error::PutError { + msg: e.to_string(), + path: pm.path.clone(), + })?; + }; + + Ok(()) +} + +#[async_trait] +impl Provider for AWSSecretsManager { + fn kind(&self) -> ProviderInfo { + ProviderInfo { + kind: ProviderKind::AWSSecretsManager, + name: self.name.clone(), + } + } + + async fn get(&self, pm: &PathMap) -> Result> { + get_data(&Mode::Get, &self.client, pm).await?.map_or_else( + || Ok(vec![]), + |data| Ok(KV::from_data(&data, pm, &self.kind())), + ) + } + + async fn put(&self, pm: &PathMap, kvs: &[KV]) -> Result<()> { + let mut data = get_data(&Mode::Put, &self.client, pm) + .await? + .unwrap_or_default(); + for kv in kvs { + data.insert(kv.key.clone(), kv.value.clone()); + } + put_data(&self.client, pm, &data).await + } + + async fn del(&self, pm: &PathMap) -> Result<()> { + if pm.keys.is_empty() { + self.client + .delete_secret() + .secret_id(&pm.path) + .send() + .await + .map_or_else(|e| handle_del_err(e, pm), |_| Ok(()))?; + } else { + let mut data = get_data(&Mode::Del, &self.client, pm) + .await? + .unwrap_or_default(); + for k in pm.keys.keys() { + data.remove(k); + } + put_data(&self.client, pm, &data).await?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::env; + + use dockertest_server::servers::cloud::LocalStackServer; + use dockertest_server::servers::cloud::LocalStackServerConfig; + use dockertest_server::Test; + + use crate::{providers::test_utils, Provider}; + + #[test] + #[cfg(not(windows))] + fn sanity_test() { + if env::var("RUNNER_OS").unwrap_or_default() == "macOS" { + return; + } + + let env: HashMap<_, _> = vec![( + "SERVICES".to_string(), + "iam,sts,ssm,kms,secretsmanager".to_string(), + )] + .into_iter() + .collect(); + let config = LocalStackServerConfig::builder() + .env(env) + .port(4561) + .version("2.0.2".into()) + .build() + .unwrap(); + let mut test = Test::new(); + test.register(config); + + test.run(|instance| async move { + let server: LocalStackServer = instance.server(); + + let data = serde_json::json!({ + "region": "us-east-1", + "access_key_id": "stub", + "secret_access_key": "stub", + "provider_name": "faked", + "endpoint_url": server.external_url() + }); + + let p = Box::new( + super::AWSSecretsManager::new( + "aws_secretsmanager", + Some(serde_json::from_value(data).unwrap()), + ) + .await + .unwrap(), + ) as Box; + + test_utils::ProviderTest::new(p).run().await; + }); + } +} diff --git a/teller-providers/src/providers/dotenv.rs b/teller-providers/src/providers/dotenv.rs new file mode 100644 index 00000000..ac4fcbdc --- /dev/null +++ b/teller-providers/src/providers/dotenv.rs @@ -0,0 +1,218 @@ +//! `dotenv` Provider +//! +//! +//! ## Example configuration +//! +//! ```yaml +//! providers: +//! dotenv1: +//! kind: dotenv +//! # options: ... +//! ``` +//! ## Options +//! +//! See [`DotEnvOptions`] +//! +//! +#![allow(clippy::borrowed_box)] +use std::fs::File; +use std::io::prelude::*; +use std::{ + collections::{BTreeMap, HashMap}, + io, + path::Path, +}; + +use async_trait::async_trait; +use dotenvy::{self}; +use fs_err as fs; +use serde_derive::{Deserialize, Serialize}; + +use super::ProviderKind; +use crate::config::ProviderInfo; +use crate::{ + config::{PathMap, KV}, + Error, Provider, Result, +}; + +#[derive(PartialEq)] +enum Mode { + Get, + Put, + Del, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub struct DotEnvOptions { + /// create a file if did not exist, when writing new data to provider + pub create_on_put: bool, +} + +pub struct Dotenv { + pub name: String, + opts: DotEnvOptions, +} +impl Dotenv { + /// Create a new provider + /// + /// # Errors + /// + /// This function will return an error if cannot create a provider + pub fn new(name: &str, opts: Option) -> Result { + let opts = opts.unwrap_or_default(); + + Ok(Self { + name: name.to_string(), + opts, + }) + } +} + +fn load(path: &Path, mode: &Mode) -> Result> { + let content = fs::File::open(path)?; + let mut env = BTreeMap::new(); + + if mode == &Mode::Get { + let metadata = content.metadata().map_err(|e| Error::GetError { + path: format!("{path:?}"), + msg: format!("could not get file metadata. err: {e:?}"), + })?; + + if metadata.len() == 0 { + return Err(Error::NotFound { + path: format!("{path:?}"), + msg: "file is empty".to_string(), + }); + } + } + + for res in dotenvy::Iter::new(&content) { + let (k, v) = res.map_err(|e| Error::GetError { + path: format!("{path:?}"), + msg: e.to_string(), + })?; + env.insert(k, v); + } + + Ok(env) +} +// poor man's serialization, loses original comments and formatting +fn save(path: &Path, data: &BTreeMap) -> Result { + let mut out = String::new(); + for (k, v) in data { + let maybe_json: serde_json::Result> = + serde_json::from_str(v); + + let json_value = if maybe_json.is_ok() { + serde_json::to_string(&v).map(Some).unwrap_or_default() + } else { + None + }; + + let value = json_value.unwrap_or_else(|| v.to_string()); + out.push_str(&format!("{k}={value}\n")); + } + + fs::write(path, &out)?; + Ok(out) +} + +#[async_trait] +impl Provider for Dotenv { + fn kind(&self) -> ProviderInfo { + ProviderInfo { + kind: ProviderKind::Dotenv, + name: self.name.clone(), + } + } + + async fn get(&self, pm: &PathMap) -> Result> { + let data = load(Path::new(&pm.path), &Mode::Get)?; + Ok(KV::from_data(&data, pm, &self.kind())) + } + + async fn put(&self, pm: &PathMap, kvs: &[KV]) -> Result<()> { + // Create file if not exists + add the option to set is as false + self.load_modify_save( + pm, + |data| { + for kv in kvs { + data.insert(kv.key.to_string(), kv.value.to_string()); + } + }, + &Mode::Put, + )?; + Ok(()) + } + + async fn del(&self, pm: &PathMap) -> Result<()> { + self.load_modify_save( + pm, + |data| { + if pm.keys.is_empty() { + data.clear(); + } else { + for k in pm.keys.keys() { + if data.contains_key(k) { + data.remove(k); + } + } + } + }, + &Mode::Del, + )?; + Ok(()) + } +} +impl Dotenv { + fn load_modify_save(&self, pm: &PathMap, modify: F, mode: &Mode) -> Result<()> + where + F: Fn(&mut BTreeMap), + { + if mode == &Mode::Put && self.opts.create_on_put { + Self::create_empty_file(&pm.path).map_err(|e| Error::GetError { + path: format!("{:?}", pm.path), + msg: format!("could not create file: {:?}. err: {e:?}", pm.path), + })?; + } + let file = Path::new(&pm.path); + let mut data = load(file, mode)?; + modify(&mut data); + save(file, &data)?; + Ok(()) + } + + fn create_empty_file(path: &str) -> io::Result<()> { + if let Some(parent_dir) = Path::new(path).parent() { + std::fs::create_dir_all(parent_dir)?; + } + let mut file = File::create(path)?; + file.write_all(b"")?; + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use tokio::test; + + use super::*; + use crate::providers::test_utils; + + #[test] + async fn sanity_test() { + let opts = serde_json::json!({ + "create_on_put": true, + }); + + let p: Box = Box::new( + super::Dotenv::new("dotenv", Some(serde_json::from_value(opts).unwrap())).unwrap(), + ) as Box; + + test_utils::ProviderTest::new(p) + .with_root_prefix("tmp/dotenv/") + .run() + .await; + } +} diff --git a/teller-providers/src/providers/google_secretmanager.rs b/teller-providers/src/providers/google_secretmanager.rs new file mode 100644 index 00000000..a7b9d0a5 --- /dev/null +++ b/teller-providers/src/providers/google_secretmanager.rs @@ -0,0 +1,417 @@ +//! Google Secret Manager +//! +//! +//! ## Example configuration +//! +//! ```yaml +//! providers: +//! gsm1: +//! kind: google_secretmanager +//! # options: ... +//! ``` +//! ## Options +//! +//! Uses default GSM options location strategy (by order): +//! +//! * Use `GOOGLE_APPLICATION_CREDENTIALS` +//! * Try `$HOME/.config/gcloud/application_default_credentials.json` +//! +//! If you need specific configuration options for this provider, please request via opening an issue. +//! +use async_trait::async_trait; +use google_secretmanager1::{ + api::{AddSecretVersionRequest, Automatic, Replication, Secret, SecretPayload}, + hyper::{self, client::HttpConnector}, + hyper_rustls::{self, HttpsConnector}, + oauth2::{ + self, + authenticator::{ApplicationDefaultCredentialsTypes, Authenticator}, + ApplicationDefaultCredentialsAuthenticator, ApplicationDefaultCredentialsFlowOpts, + }, + SecretManager, +}; + +use super::ProviderKind; +use crate::{ + config::{PathMap, ProviderInfo, KV}, + Error, Provider, Result, +}; + +#[async_trait] +pub trait GSM { + fn get_hub(&self) -> Option<&SecretManager>>; + async fn list(&self, name: &str) -> Result>; + async fn get(&self, name: &str) -> Result>; + async fn put(&self, name: &str, value: &str) -> Result<()>; + async fn del(&self, name: &str) -> Result<()>; +} + +pub struct GSMClient { + hub: SecretManager>, +} + +impl GSMClient { + /// Create a GSM client + /// + /// # Errors + /// Fails if cannot create the client + pub async fn new() -> Result { + let authenticator = resolve_auth().await.map_err(Box::from)?; + + let hub = SecretManager::new( + hyper::Client::builder().build( + hyper_rustls::HttpsConnectorBuilder::new() + .with_native_roots() + .https_or_http() + .enable_http1() + .enable_http2() + .build(), + ), + authenticator, + ); + Ok(Self { hub }) + } +} + +#[async_trait] +impl GSM for GSMClient { + fn get_hub(&self) -> Option<&SecretManager>> { + Some(&self.hub) + } + + async fn list(&self, name: &str) -> Result> { + let hub = self.get_hub().expect("hub"); + + let (_, secret) = hub + .projects() + .secrets_list(name) + .doit() + .await + .map_err(|e| Error::ListError { + path: name.to_string(), + msg: e.to_string(), + })?; + + let mut out = Vec::new(); + if let Some(secrets) = secret.secrets { + for secret in &secrets { + let secret_name = secret + .name + .as_ref() + .expect("secretmanager API should output a secret resource name"); + + if let Some(value) = self.get(secret_name).await? { + out.push((secret_name.clone(), value)); + } + } + } + Ok(out) + } + + async fn get(&self, name: &str) -> Result> { + let hub = self.get_hub().expect("hub"); + let resource = if name.contains("/versions") { + name.to_string() + } else { + format!("{name}/versions/latest") + }; + + let maybe_secret = hub + .projects() + .secrets_versions_access(&resource) + .doit() + .await + .ok(); + + if let Some((_, secret)) = maybe_secret { + let payload = secret + .payload + .ok_or_else(|| Error::Message(format!("no secret payload found in {resource}")))?; + + Ok(payload + .data + .map(|d| String::from_utf8_lossy(&d).to_string())) + } else { + Ok(None) + } + } + + async fn put(&self, name: &str, value: &str) -> Result<()> { + let hub = self.get_hub().expect("hub"); + + let res = hub.projects().secrets_get(name).doit().await; + + // attempt adding a secret if missing + if let Err(err) = res { + let repr = err.to_string(); + + // F-you google cloud. resorting to checking a + // string representation of the error instead of navigating + // the horrible error story you give us. + if repr.contains("\"NOT_FOUND\"") { + if let Some((project, secret_id)) = name.split_once("/secrets/") { + hub.projects() + .secrets_create( + Secret { + replication: Some(Replication { + automatic: Some(Automatic::default()), + user_managed: None, + }), + ..Secret::default() + }, + project, + ) + .secret_id(secret_id) + .doit() + .await + .map_err(|e| Error::PutError { + path: name.to_string(), + msg: e.to_string(), + })?; + } + } + } + + // add value under a secret version + hub.projects() + .secrets_add_version( + AddSecretVersionRequest { + payload: Some(SecretPayload { + data: Some(value.as_bytes().to_vec()), + data_crc32c: Some(i64::from(crc32c::crc32c(value.as_bytes()))), + }), + }, + name, + ) + .doit() + .await + .map_err(|e| Error::PutError { + path: name.to_string(), + msg: e.to_string(), + })?; + + Ok(()) + } + + async fn del(&self, name: &str) -> Result<()> { + let hub = self.get_hub().expect("hub"); + + // only delete if exists + if let Ok(Some(_)) = self.get(name).await { + hub.projects() + .secrets_delete(name) + .doit() + .await + .map_err(|e| Error::DeleteError { + path: name.to_string(), + msg: e.to_string(), + })?; + } + + Ok(()) + } +} + +async fn resolve_auth() -> Result>> +{ + // + // try SA creds (via env, GOOGLE_APPLICATION_CREDENTIALS) + // + let service_auth = match ApplicationDefaultCredentialsAuthenticator::builder( + ApplicationDefaultCredentialsFlowOpts::default(), + ) + .await + { + ApplicationDefaultCredentialsTypes::ServiceAccount(auth) => { + Ok(auth.build().await.map_err(Box::from)?) + } + ApplicationDefaultCredentialsTypes::InstanceMetadata(_) => Err(Error::Message( + "expected sa detail, found instance metadata".to_string(), + )), + }; + if service_auth.is_ok() { + return service_auth; + } + + // + // try user creds + // + let creds = home::home_dir() + .ok_or_else(|| Error::Message("cannot find home dir".to_string()))? + .join(".config/gcloud/application_default_credentials.json"); + + let user_secret = oauth2::read_authorized_user_secret(creds) + .await + .map_err(Box::from)?; + + Ok(oauth2::AuthorizedUserAuthenticator::builder(user_secret) + .build() + .await + .map_err(Box::from)?) +} + +pub struct GoogleSecretManager { + client: Box, + pub name: String, +} + +impl GoogleSecretManager { + #[must_use] + pub fn new(name: &str, client: Box) -> Self { + Self { + client, + name: name.to_string(), + } + } +} + +#[async_trait] +impl Provider for GoogleSecretManager { + fn kind(&self) -> ProviderInfo { + ProviderInfo { + kind: ProviderKind::GoogleSecretManager, + name: self.name.clone(), + } + } + + async fn get(&self, pm: &PathMap) -> Result> { + let mut out = Vec::new(); + if pm.keys.is_empty() { + // get parameters by path + // ("projects/1xxx34/secrets/DSN4", "foobar") + let values = self.client.list(&pm.path).await?; + + for (resource, v) in values { + // projects/123/secrets/FOOBAR -> FOOBAR + // ^-<--<--< rsplit + if let Some((_, key)) = resource.rsplit_once('/') { + out.push(KV::from_value(&v, key, key, pm, self.kind())); + } + } + } else { + for (k, v) in &pm.keys { + let resp = self + .client + .get(&format!("{}/secrets/{}", pm.path, k)) + .await?; + if let Some(val) = resp { + out.push(KV::from_value(&val, k, v, pm, self.kind())); + } + } + } + + if out.is_empty() { + return Err(Error::NotFound { + path: pm.path.to_string(), + msg: "path not found".to_string(), + }); + } + Ok(out) + } + + async fn put(&self, pm: &PathMap, kvs: &[KV]) -> Result<()> { + for kv in kvs { + self.client + .put(&format!("{}/secrets/{}", pm.path, kv.key), &kv.value) + .await?; + } + Ok(()) + } + + async fn del(&self, pm: &PathMap) -> Result<()> { + if pm.keys.is_empty() { + let values = self.client.list(&pm.path).await?; + + for (resource, _) in values { + self.client.del(&resource).await?; + } + } else { + for k in pm.keys.keys() { + self.client + .del(&format!("{}/secrets/{}", pm.path, k)) + .await?; + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::{ + collections::BTreeMap, + sync::{Arc, Mutex}, + }; + + use async_trait::async_trait; + use google_secretmanager1::hyper::client::HttpConnector; + use google_secretmanager1::hyper_rustls::HttpsConnector; + use google_secretmanager1::SecretManager; + + use crate::{ + providers::{google_secretmanager::GSM, test_utils}, + Provider, Result, + }; + + struct MockClient { + data: Arc>>, + } + + impl MockClient { + /// Create a GSM client + /// + /// # Errors + /// Fails if cannot create the client + pub fn new() -> Self { + Self { + data: Arc::new(Mutex::new(BTreeMap::new())), + } + } + } + + #[async_trait] + impl GSM for MockClient { + fn get_hub(&self) -> Option<&SecretManager>> { + None + } + + async fn list(&self, name: &str) -> Result> { + Ok(self + .data + .lock() + .unwrap() + .iter() + .filter(|(k, _)| k.starts_with(name)) + .map(|(k, v)| (k.clone(), v.clone())) + .collect::>()) + } + + async fn get(&self, name: &str) -> Result> { + Ok(self.data.lock().unwrap().get(name).cloned()) + } + + async fn put(&self, name: &str, value: &str) -> Result<()> { + self.data + .lock() + .unwrap() + .insert(name.to_string(), value.to_string()); + Ok(()) + } + + async fn del(&self, name: &str) -> Result<()> { + self.data.lock().unwrap().remove(name); + Ok(()) + } + } + + #[tokio::test] + async fn sanity_test() { + let mock_client = MockClient::new(); + let p = Box::new(super::GoogleSecretManager::new( + "test", + Box::new(mock_client) as Box, + )) as Box; + + test_utils::ProviderTest::new(p).run().await; + } +} diff --git a/teller-providers/src/providers/hashicorp_consul.rs b/teller-providers/src/providers/hashicorp_consul.rs new file mode 100644 index 00000000..9fdafe8e --- /dev/null +++ b/teller-providers/src/providers/hashicorp_consul.rs @@ -0,0 +1,318 @@ +//! Hashicorp Consul +//! +//! +//! ## Example configuration +//! +//! ```yaml +//! providers: +//! consul1: +//! kind: hashicorp_consul +//! # options: ... +//! ``` +//! ## Options +//! +//! See [`HashiCorpConsulOptions`] for more. +//! +#![allow(clippy::borrowed_box)] +use std::env; + +use async_trait::async_trait; +use consulrs::{ + api::kv::requests::{ + DeleteKeyRequestBuilder, ReadKeyRequestBuilder, ReadKeysRequestBuilder, + SetKeyRequestBuilder, + }, + client::{ConsulClient, ConsulClientSettingsBuilder}, + error::ClientError, + kv as ConsulKV, +}; +use serde_derive::{Deserialize, Serialize}; + +use super::ProviderKind; +use crate::{ + config::{PathMap, ProviderInfo, KV}, + Error, Provider, Result, +}; + +#[derive(Default, Serialize, Deserialize, Debug, Clone)] +pub struct HashiCorpConsulOptions { + /// Consul address. if is None, search address from `CONSUL_HTTP_ADDR` + pub address: Option, + /// Consul token. if is None, search address from `CONSUL_HTTP_TOKEN` + pub token: Option, + /// Specifies the datacenter to query. + pub dc: Option, +} + +fn xerr(pm: &PathMap, e: ClientError) -> Error { + match e { + ClientError::RestClientError { source } => match source { + rustify::errors::ClientError::ServerResponseError { code, content } => { + match (code, content.clone()) { + (404, Some(content)) + if content.contains("Invalid path for a versioned K/V secrets") => + { + Error::PathError( + pm.path.clone(), + "missing or incompatible protocol version".to_string(), + ) + } + (404, _) => Error::NotFound { + path: pm.path.clone(), + msg: "not found".to_string(), + }, + _ => Error::Message(format!("code: {code}, {content:?}")), + } + } + _ => Error::Any(Box::from(source)), + }, + ClientError::APIError { + code: 404, + message: _, + } => Error::NotFound { + path: pm.path.clone(), + msg: "not found".to_string(), + }, + _ => Error::Any(Box::from(e)), + } +} + +pub struct HashiCorpConsul { + pub client: ConsulClient, + opts: HashiCorpConsulOptions, + pub name: String, +} + +impl HashiCorpConsul { + #[must_use] + pub fn with_client(name: &str, client: ConsulClient) -> Self { + Self { + client, + opts: HashiCorpConsulOptions::default(), + name: name.to_string(), + } + } + + /// Create a new hashicorp Consul + /// + /// # Errors + /// + /// This function will return an error if cannot create a provider + pub fn new(name: &str, opts: Option) -> Result { + let opts = opts.unwrap_or_default(); + + let address = opts + .address + .as_ref() + .map_or_else( + || env::var("CONSUL_HTTP_ADDR"), + |address| Ok(address.to_string()), + ) + .map_err(|_| Error::Message("Consul address not present.".to_string()))?; + + let token = opts + .token + .as_ref() + .map_or_else( + || env::var("CONSUL_HTTP_TOKEN"), + |token| Ok(token.to_string()), + ) + .unwrap_or_default(); + + let settings = ConsulClientSettingsBuilder::default() + .address(address) + .token(token) + .build() + .map_err(Box::from)?; + + let client = ConsulClient::new(settings).map_err(Box::from)?; + + Ok(Self { + client, + opts, + name: name.to_string(), + }) + } +} + +impl HashiCorpConsul { + fn prepare_get_builder_request(&self) -> ReadKeyRequestBuilder { + let mut opts: ReadKeyRequestBuilder = ReadKeyRequestBuilder::default(); + if let Some(dc) = self.opts.dc.as_ref() { + opts.dc(dc.to_string()); + } + opts.recurse(true); + opts + } + + fn prepare_put_builder_request(&self) -> SetKeyRequestBuilder { + let mut opts: SetKeyRequestBuilder = SetKeyRequestBuilder::default(); + if let Some(dc) = self.opts.dc.as_ref() { + opts.dc(dc.to_string()); + } + opts + } + + fn prepare_delete_builder_request(&self) -> DeleteKeyRequestBuilder { + let mut opts: DeleteKeyRequestBuilder = DeleteKeyRequestBuilder::default(); + if let Some(dc) = self.opts.dc.as_ref() { + opts.dc(dc.to_string()); + } + opts.recurse(false); + opts + } + + fn prepare_keys_builder_request(&self) -> ReadKeysRequestBuilder { + let mut opts: ReadKeysRequestBuilder = ReadKeysRequestBuilder::default(); + if let Some(dc) = self.opts.dc.as_ref() { + opts.dc(dc.to_string()); + } + opts.recurse(false); + opts + } +} +#[async_trait] +impl Provider for HashiCorpConsul { + fn kind(&self) -> ProviderInfo { + ProviderInfo { + kind: ProviderKind::HashiCorpConsul, + name: self.name.clone(), + } + } + + async fn get(&self, pm: &PathMap) -> Result> { + let res = ConsulKV::read( + &self.client, + &pm.path, + Some(&mut self.prepare_get_builder_request()), + ) + .await + .map_err(|e| xerr(pm, e))?; + + let mut results = vec![]; + for kv_pair in res.response { + let kv_value = kv_pair.value.ok_or_else(|| Error::NotFound { + path: pm.path.to_string(), + msg: "value not found".to_string(), + })?; + + let val: String = kv_value.try_into().map_err(|e| Error::GetError { + path: pm.path.to_string(), + msg: format!("could not decode Base64 value. err: {e:?}"), + })?; + + let (_, key) = kv_pair.key.rsplit_once('/').unwrap_or(("", &kv_pair.key)); + + results.push(KV::from_value(&val, key, key, pm, self.kind())); + } + + Ok(results) + } + + async fn put(&self, pm: &PathMap, kvs: &[KV]) -> Result<()> { + for kv in kvs { + ConsulKV::set( + &self.client, + &format!("{}/{}", pm.path, kv.key), + kv.value.as_bytes(), + Some(&mut self.prepare_put_builder_request()), + ) + .await + .map_err(|e| Error::PutError { + path: pm.path.to_string(), + msg: format!( + "could not put value in key {}. err: {:?}", + kv.key.as_str(), + e + ), + })?; + } + Ok(()) + } + + async fn del(&self, pm: &PathMap) -> Result<()> { + let keys = if pm.keys.is_empty() { + ConsulKV::keys( + &self.client, + pm.path.as_str(), + Some(&mut self.prepare_keys_builder_request()), + ) + .await + .map_err(|e| Error::DeleteError { + path: pm.path.to_string(), + msg: format!( + "could not get keys in path: {}. err: {:?}", + pm.path.as_str(), + e + ), + })? + .response + } else { + pm.keys + .keys() + .map(|kv| format!("{}/{kv}", &pm.path)) + .collect::>() + }; + + for key in keys { + ConsulKV::delete( + &self.client, + key.as_str(), + Some(&mut self.prepare_delete_builder_request()), + ) + .await + .map_err(|e| Error::DeleteError { + path: pm.path.to_string(), + msg: format!("could not delete key: {}. err: {:?}", pm.path.as_str(), e), + })?; + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + + use dockertest_server::servers::hashi::{ConsulServer, ConsulServerConfig}; + use dockertest_server::Test; + + use super::*; + use crate::providers::test_utils; + + const PORT: u32 = 8501; + + #[test] + #[cfg(not(windows))] + fn sanity_test() { + if env::var("RUNNER_OS").unwrap_or_default() == "macOS" { + return; + } + + let config = ConsulServerConfig::builder() + .port(PORT) + .version("1.15.4".into()) + .build() + .unwrap(); + let mut test = Test::new(); + test.register(config); + + test.run(|instance| async move { + let server: ConsulServer = instance.server(); + + let data = serde_json::json!({ + "address": server.external_url(), + }); + + let p = Box::new( + super::HashiCorpConsul::new( + "hashicorp_consul", + Some(serde_json::from_value(data).unwrap()), + ) + .unwrap(), + ) as Box; + + test_utils::ProviderTest::new(p).run().await; + }); + } +} diff --git a/teller-providers/src/providers/hashicorp_vault.rs b/teller-providers/src/providers/hashicorp_vault.rs new file mode 100644 index 00000000..c1d90fc3 --- /dev/null +++ b/teller-providers/src/providers/hashicorp_vault.rs @@ -0,0 +1,314 @@ +//! Hashicorp Vault +//! +//! +//! ## Example configuration +//! +//! ```yaml +//! providers: +//! vault1: +//! kind: hashicorp_vault +//! # options: ... +//! ``` +//! ## Options +//! +//! See [`HashivaultOptions`] for more. +//! +#![allow(clippy::borrowed_box)] +use std::{ + collections::{BTreeMap, HashMap}, + env, +}; + +use async_trait::async_trait; +use serde_derive::{Deserialize, Serialize}; +use vaultrs::{ + client::{VaultClient, VaultClientSettingsBuilder}, + error::ClientError, + kv1, kv2, +}; + +use super::ProviderKind; +use crate::{ + config::{PathMap, ProviderInfo, KV}, + Error, Provider, Result, +}; + +/// # Hashicorp options +/// +/// If no options provided at all, will take `VAULT_ADDR` and `VAULT_TOKEN` env variables. +/// If partial options provided, will only take what's provided. +/// +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct HashivaultOptions { + /// Vault address + pub address: Option, + /// Vault token + pub token: Option, +} + +pub struct Hashivault { + pub client: VaultClient, + pub name: String, +} + +impl Hashivault { + /// Create a new hashicorp vault + /// + /// # Errors + /// + /// This function will return an error if cannot create a provider + pub fn new(name: &str, opts: Option) -> Result { + let settings = if let Some(opts) = opts { + let mut settings = VaultClientSettingsBuilder::default(); + + if let Some(address) = opts.address { + settings.address(address); + } + + if let Some(token) = opts.token { + settings.token(token); + } + + settings.build().map_err(Box::from)? + } else { + VaultClientSettingsBuilder::default() + .address(env::var("VAULT_ADDR")?) + .token(env::var("VAULT_TOKEN")?) + .build() + .map_err(Box::from)? + }; + + let client = VaultClient::new(settings).map_err(Box::from)?; + + Ok(Self { + client, + name: name.to_string(), + }) + } +} + +fn parse_path(pm: &PathMap) -> Result<(&str, &str, &str)> { + let (engine, full_path) = (pm.protocol.as_deref().unwrap_or("kv2"), pm.path.as_str()); + let (mount, path) = full_path.split_once('/').ok_or_else(|| { + Error::Message( + "path must have initial mount seperated by '/', e.g. `secret/foo`".to_string(), + ) + })?; + Ok((engine, mount, path)) +} + +fn xerr(pm: &PathMap, e: ClientError) -> Error { + match e { + ClientError::RestClientError { source } => match source { + rustify::errors::ClientError::ServerResponseError { code, content } => { + match (code, content.clone()) { + (404, Some(content)) + if content.contains("Invalid path for a versioned K/V secrets") => + { + Error::PathError( + pm.path.clone(), + "missing or incompatible protocol version".to_string(), + ) + } + (404, _) => Error::NotFound { + path: pm.path.clone(), + msg: "not found".to_string(), + }, + _ => Error::Message(format!("code: {code}, {content:?}")), + } + } + _ => Error::Any(Box::from(source)), + }, + ClientError::APIError { + code: 404, + errors: _, + } => Error::NotFound { + path: pm.path.clone(), + msg: "not found".to_string(), + }, + _ => Error::Any(Box::from(e)), + } +} + +async fn get_data(client: &VaultClient, pm: &PathMap) -> Result> { + let (engine, mount, path) = parse_path(pm)?; + let data = if engine == "kv2" { + kv2::read(client, mount, path).await + } else { + kv1::get(client, mount, path).await + } + .map_err(|e| xerr(pm, e))?; + + Ok(data) +} + +async fn get_data_or_empty(client: &VaultClient, pm: &PathMap) -> Result> { + let data = match get_data(client, pm).await { + Ok(data) => data, + Err(Error::NotFound { path: _, msg: _ }) => BTreeMap::new(), + Err(e) => return Err(e), + }; + Ok(data) +} + +async fn put_data( + client: &VaultClient, + pm: &PathMap, + data: &BTreeMap, +) -> Result<()> { + let (engine, mount, path) = parse_path(pm)?; + if engine == "kv2" { + kv2::set(client, mount, path, data) + .await + .map_err(|e| xerr(pm, e))?; + } else { + kv1::set( + client, + mount, + path, + &data + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .collect::>(), + ) + .await + .map_err(|e| xerr(pm, e))?; + }; + Ok(()) +} + +#[async_trait] +impl Provider for Hashivault { + fn kind(&self) -> ProviderInfo { + ProviderInfo { + kind: ProviderKind::Hashicorp, + name: self.name.clone(), + } + } + + async fn get(&self, pm: &PathMap) -> Result> { + Ok(KV::from_data( + &get_data(&self.client, pm).await.map_err(|e| match e { + Error::NotFound { path, msg } => Error::NotFound { path, msg }, + _ => Error::GetError { + path: pm.path.to_string(), + msg: e.to_string(), + }, + })?, + pm, + &self.kind(), + )) + } + + async fn put(&self, pm: &PathMap, kvs: &[KV]) -> Result<()> { + let mut data = get_data_or_empty(&self.client, pm) + .await + .map_err(|e| Error::PutError { + path: pm.path.to_string(), + msg: e.to_string(), + })?; + for kv in kvs { + data.insert(kv.key.clone(), kv.value.clone()); + } + put_data(&self.client, pm, &data) + .await + .map_err(|e| Error::PutError { + path: pm.path.to_string(), + msg: e.to_string(), + })?; + Ok(()) + } + + async fn del(&self, pm: &PathMap) -> Result<()> { + // if pm contains specific keys, we cannot delete the path, + // deleting a complete path may drop everything under it (a path stores a dictionary of k/v) + // we want to remove the keys from the secret object and re-write it into its path. + if !pm.keys.is_empty() { + let mut data = + get_data_or_empty(&self.client, pm) + .await + .map_err(|e| Error::DeleteError { + path: pm.path.to_string(), + msg: e.to_string(), + })?; + for key in pm.keys.keys() { + data.remove(key); + } + put_data(&self.client, pm, &data) + .await + .map_err(|e| Error::DeleteError { + path: pm.path.to_string(), + msg: e.to_string(), + })?; + return Ok(()); + } + + // otherwise, delete the whole path + let (engine, mount, path) = parse_path(pm)?; + if engine == "kv2" { + kv2::delete_latest(&self.client, mount, path) + .await + .map_err(|e| xerr(pm, e)) + .map_err(|e| Error::DeleteError { + path: pm.path.to_string(), + msg: e.to_string(), + })?; + } else { + kv1::delete(&self.client, mount, path) + .await + .map_err(|e| xerr(pm, e)) + .map_err(|e| Error::DeleteError { + path: pm.path.to_string(), + msg: e.to_string(), + })?; + }; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + + use dockertest_server::servers::hashi::{VaultServer, VaultServerConfig}; + use dockertest_server::Test; + + use super::*; + use crate::providers::test_utils; + + const PORT: u32 = 9200; + + #[test] + #[cfg(not(windows))] + fn sanity_test() { + if env::var("RUNNER_OS").unwrap_or_default() == "macOS" { + return; + } + + let config = VaultServerConfig::builder() + .port(PORT) + .version("1.8.2".into()) + .build() + .unwrap(); + let mut test = Test::new(); + test.register(config); + + test.run(|instance| async move { + let server: VaultServer = instance.server(); + + let data = serde_json::json!({ + "address": server.external_url(), + "token": server.token + }); + + let p = Box::new( + super::Hashivault::new( + "hashicorp_vault", + Some(serde_json::from_value(data).unwrap()), + ) + .unwrap(), + ) as Box; + + test_utils::ProviderTest::new(p).run().await; + }); + } +} diff --git a/teller-providers/src/providers/inmem.rs b/teller-providers/src/providers/inmem.rs new file mode 100644 index 00000000..b025df81 --- /dev/null +++ b/teller-providers/src/providers/inmem.rs @@ -0,0 +1,147 @@ +//! In-memory Store +//! +//! +//! ## Example configuration +//! +//! ```yaml +//! providers: +//! inmem1: +//! kind: inmem +//! options: +//! key1: value +//! key1: value +//! ``` +//! ## Options +//! +//! The options to the inmem store are actually its initial data +//! representation and can be any `serde_json::Value` that can convert to +//! a `BTreeMap` (hashmap) +//! +use std::{collections::BTreeMap, sync::Mutex}; + +use async_trait::async_trait; + +use super::ProviderKind; +use crate::{ + config::{PathMap, ProviderInfo, KV}, + Error, Provider, Result, +}; + +pub struct Inmem { + store: Mutex>>, + name: String, +} + +impl Inmem { + /// Build from YAML + /// + /// # Errors + /// + /// This function will return an error if serialization fails + pub fn from_yaml(name: &str, yaml: &str) -> Result { + Ok(Self { + store: Mutex::new(serde_yaml::from_str(yaml)?), + name: name.to_string(), + }) + } + + /// Create an inmem provider. + /// `opts` is the memory map of the provider, which is a `BTreeMap>`, + /// or in YAML: + /// + /// ```yaml + /// production/foo/bar: + /// key: v + /// baz: bar + /// ``` + /// + /// # Errors + /// + /// This function will return an error if creation fails + pub fn new(name: &str, opts: Option) -> Result { + Ok(if let Some(opts) = opts { + Self { + store: Mutex::new(serde_json::from_value(opts)?), + name: name.to_string(), + } + } else { + Self { + store: Mutex::new(BTreeMap::default()), + name: name.to_string(), + } + }) + } + + /// Returns the get state of this [`Inmem`]. + /// + /// # Panics + /// + /// Panics if lock cannot be acquired + pub fn get_state(&self) -> BTreeMap> { + self.store + .lock() + .expect("inmem store failed getting a lock") + .clone() + } +} + +#[async_trait] +impl Provider for Inmem { + fn kind(&self) -> ProviderInfo { + ProviderInfo { + kind: ProviderKind::Inmem, + name: self.name.clone(), + } + } + + #[allow(clippy::significant_drop_tightening)] + async fn get(&self, pm: &PathMap) -> Result> { + let store = self.store.lock().unwrap(); + let data = store.get(&pm.path).ok_or_else(|| Error::NotFound { + path: pm.path.to_string(), + msg: "not found".to_string(), + })?; + Ok(KV::from_data(data, pm, &self.kind())) + } + #[allow(clippy::significant_drop_tightening)] + async fn put(&self, pm: &PathMap, kvs: &[KV]) -> Result<()> { + let mut store = self.store.lock().unwrap(); + let mut data = store.get(&pm.path).cloned().unwrap_or_default(); + for kv in kvs { + data.insert(kv.key.clone(), kv.value.clone()); + } + store.insert(pm.path.clone(), data); + Ok(()) + } + + async fn del(&self, pm: &PathMap) -> Result<()> { + if pm.keys.is_empty() { + self.store.lock().unwrap().remove(&pm.path); + } else { + let mut store = self.store.lock().unwrap(); + let mut data = store.get(&pm.path).cloned().unwrap_or_default(); + for key in pm.keys.keys() { + data.remove(key); + } + store.insert(pm.path.clone(), data); + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use tokio::test; + + use crate::providers::test_utils; + use crate::Provider; + + #[test] + async fn sanity_test() { + let p = + Box::new(super::Inmem::new("test", None).unwrap()) as Box; + + test_utils::ProviderTest::new(p).run().await; + } +} diff --git a/teller-providers/src/providers/mod.rs b/teller-providers/src/providers/mod.rs new file mode 100644 index 00000000..6d46b181 --- /dev/null +++ b/teller-providers/src/providers/mod.rs @@ -0,0 +1,90 @@ +use std::{collections::HashMap, str::FromStr}; + +use lazy_static::lazy_static; +use serde::{Deserialize, Serialize}; +use serde_variant::to_variant_name; +use strum::{EnumIter, IntoEnumIterator}; + +#[cfg(test)] +mod test_utils; + +#[cfg(feature = "dotenv")] +pub mod dotenv; +pub mod inmem; + +#[cfg(feature = "hashicorp_vault")] +pub mod hashicorp_vault; + +#[cfg(feature = "ssm")] +pub mod ssm; + +#[cfg(feature = "aws_secretsmanager")] +pub mod aws_secretsmanager; + +#[cfg(feature = "google_secretmanager")] +pub mod google_secretmanager; + +#[cfg(feature = "hashicorp_consul")] +pub mod hashicorp_consul; + +lazy_static! { + pub static ref PROVIDER_KINDS: String = { + let providers: Vec = ProviderKind::iter() + .map(|provider| provider.to_string()) + .collect(); + providers.join(", ") + }; +} +#[derive( + Serialize, Deserialize, Debug, Clone, Default, PartialOrd, Ord, PartialEq, Eq, EnumIter, +)] +pub enum ProviderKind { + #[serde(rename = "inmem")] + Inmem, + + #[default] + #[cfg(feature = "dotenv")] + #[serde(rename = "dotenv")] + Dotenv, + + #[cfg(feature = "hashicorp_vault")] + #[serde(rename = "hashicorp")] + Hashicorp, + + #[cfg(feature = "hashicorp_consul")] + #[serde(rename = "hashicorp_consul")] + HashiCorpConsul, + + #[cfg(feature = "ssm")] + #[serde(rename = "ssm")] + SSM, + + #[cfg(feature = "aws_secretsmanager")] + #[serde(rename = "aws_secretsmanager")] + AWSSecretsManager, + + #[cfg(feature = "google_secretmanager")] + #[serde(rename = "google_secretmanager")] + GoogleSecretManager, +} + +impl std::fmt::Display for ProviderKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + to_variant_name(self).expect("only enum supported").fmt(f) + } +} + +impl FromStr for ProviderKind { + type Err = &'static str; + + fn from_str(input: &str) -> Result { + let providers = Self::iter() + .map(|provider| (provider.to_string(), provider)) + .collect::>(); + + providers.get(input).map_or_else( + || Err(&PROVIDER_KINDS as &'static str), + |provider| Ok(provider.clone()), + ) + } +} diff --git a/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[del-keys-secret_development].snap b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[del-keys-secret_development].snap new file mode 100644 index 00000000..b9a67bda --- /dev/null +++ b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[del-keys-secret_development].snap @@ -0,0 +1,7 @@ +--- +source: src/providers/test_utils.rs +expression: delete_res +--- +Ok( + (), +) diff --git a/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[del-secret_multiple_app-1].snap b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[del-secret_multiple_app-1].snap new file mode 100644 index 00000000..b9a67bda --- /dev/null +++ b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[del-secret_multiple_app-1].snap @@ -0,0 +1,7 @@ +--- +source: src/providers/test_utils.rs +expression: delete_res +--- +Ok( + (), +) diff --git a/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-after-update-secret_multiple_app-2].snap b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-after-update-secret_multiple_app-2].snap new file mode 100644 index 00000000..83a00f6c --- /dev/null +++ b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-after-update-secret_multiple_app-2].snap @@ -0,0 +1,33 @@ +--- +source: teller-providers/src/providers/test_utils.rs +expression: read_after_update_res +--- +Ok( + [ + KV { + value: "baz", + key: "foo", + from_key: "foo", + path: Some( + PathInfo { + id: "", + path: "secret/multiple/app-2", + }, + ), + provider: Some( + ProviderInfo { + kind: PROVIDER_KIND, + name: PROVIDER_NAME, + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, + ], +) diff --git a/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-del-keys-secret_development].snap b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-del-keys-secret_development].snap new file mode 100644 index 00000000..143f8a69 --- /dev/null +++ b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-del-keys-secret_development].snap @@ -0,0 +1,33 @@ +--- +source: teller-providers/src/providers/test_utils.rs +expression: get_del_res +--- +Ok( + [ + KV { + value: "{\"DB_PASS\": \"1234\",\"DB_NAME\": \"FOO\"}", + key: "db", + from_key: "db", + path: Some( + PathInfo { + id: "", + path: "secret/development", + }, + ), + provider: Some( + ProviderInfo { + kind: PROVIDER_KIND, + name: PROVIDER_NAME, + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, + ], +) diff --git a/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-secret_development].snap b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-secret_development].snap new file mode 100644 index 00000000..44b168bf --- /dev/null +++ b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-secret_development].snap @@ -0,0 +1,81 @@ +--- +source: teller-providers/src/providers/test_utils.rs +expression: res +--- +[ + KV { + value: "DEBUG", + key: "log_level", + from_key: "log_level", + path: Some( + PathInfo { + id: "", + path: "secret/development", + }, + ), + provider: Some( + ProviderInfo { + kind: PROVIDER_KIND, + name: PROVIDER_NAME, + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, + KV { + value: "Teller", + key: "app", + from_key: "app", + path: Some( + PathInfo { + id: "", + path: "secret/development", + }, + ), + provider: Some( + ProviderInfo { + kind: PROVIDER_KIND, + name: PROVIDER_NAME, + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, + KV { + value: "{\"DB_PASS\": \"1234\",\"DB_NAME\": \"FOO\"}", + key: "db", + from_key: "db", + path: Some( + PathInfo { + id: "", + path: "secret/development", + }, + ), + provider: Some( + ProviderInfo { + kind: PROVIDER_KIND, + name: PROVIDER_NAME, + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, +] diff --git a/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-secret_multiple_app-1].snap b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-secret_multiple_app-1].snap new file mode 100644 index 00000000..4fef6a5d --- /dev/null +++ b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-secret_multiple_app-1].snap @@ -0,0 +1,31 @@ +--- +source: teller-providers/src/providers/test_utils.rs +expression: res +--- +[ + KV { + value: "DEBUG", + key: "log_level", + from_key: "log_level", + path: Some( + PathInfo { + id: "", + path: "secret/multiple/app-1", + }, + ), + provider: Some( + ProviderInfo { + kind: PROVIDER_KIND, + name: PROVIDER_NAME, + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, +] diff --git a/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-secret_multiple_app-2].snap b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-secret_multiple_app-2].snap new file mode 100644 index 00000000..6aed024e --- /dev/null +++ b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[get-secret_multiple_app-2].snap @@ -0,0 +1,31 @@ +--- +source: teller-providers/src/providers/test_utils.rs +expression: res +--- +[ + KV { + value: "bar", + key: "foo", + from_key: "foo", + path: Some( + PathInfo { + id: "", + path: "secret/multiple/app-2", + }, + ), + provider: Some( + ProviderInfo { + kind: PROVIDER_KIND, + name: PROVIDER_NAME, + }, + ), + meta: Some( + MetaInfo { + sensitivity: None, + redact_with: None, + source: None, + sink: None, + }, + ), + }, +] diff --git a/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-secret_development].snap b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-secret_development].snap new file mode 100644 index 00000000..ce029a19 --- /dev/null +++ b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-secret_development].snap @@ -0,0 +1,7 @@ +--- +source: src/providers/test_utils.rs +expression: res +--- +Ok( + (), +) diff --git a/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-secret_multiple_app-1].snap b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-secret_multiple_app-1].snap new file mode 100644 index 00000000..ce029a19 --- /dev/null +++ b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-secret_multiple_app-1].snap @@ -0,0 +1,7 @@ +--- +source: src/providers/test_utils.rs +expression: res +--- +Ok( + (), +) diff --git a/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-secret_multiple_app-2].snap b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-secret_multiple_app-2].snap new file mode 100644 index 00000000..ce029a19 --- /dev/null +++ b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-secret_multiple_app-2].snap @@ -0,0 +1,7 @@ +--- +source: src/providers/test_utils.rs +expression: res +--- +Ok( + (), +) diff --git a/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-update-secret_multiple_app-2].snap b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-update-secret_multiple_app-2].snap new file mode 100644 index 00000000..014217e5 --- /dev/null +++ b/teller-providers/src/providers/snapshots/teller_providers__providers__test_utils__[put-update-secret_multiple_app-2].snap @@ -0,0 +1,7 @@ +--- +source: src/providers/test_utils.rs +expression: update_res +--- +Ok( + (), +) diff --git a/teller-providers/src/providers/ssm.rs b/teller-providers/src/providers/ssm.rs new file mode 100644 index 00000000..be720d0d --- /dev/null +++ b/teller-providers/src/providers/ssm.rs @@ -0,0 +1,292 @@ +//! AWS SSM +//! +//! +//! ## Example configuration +//! +//! ```yaml +//! providers: +//! ssm1: +//! kind: ssm +//! # options: ... +//! ``` +//! ## Options +//! +//! See [`SSMOptions`] +//! +//! +#![allow(clippy::borrowed_box)] +use async_trait::async_trait; +use aws_config::{self, BehaviorVersion}; +use aws_sdk_ssm as ssm; +use serde_derive::{Deserialize, Serialize}; +use ssm::config::{Credentials, Region}; +use ssm::{ + error::SdkError, operation::delete_parameter::DeleteParameterError, types::ParameterType, +}; + +use super::ProviderKind; +use crate::config::{PathMap, ProviderInfo, KV}; +use crate::Provider; +use crate::{Error, Result}; + +fn handle_delete(e: SdkError, pm: &PathMap) -> Result<()> { + match e.into_service_error() { + DeleteParameterError::ParameterNotFound(_) => { + // we're ok + Ok(()) + } + e => Err(Error::DeleteError { + path: pm.path.to_string(), + msg: e.to_string(), + }), + } +} + +fn join_path(left: &str, right: &str) -> String { + format!( + "{}/{}", + left.trim_end_matches('/'), + right.trim_start_matches('/') + ) +} +/// # AWS SSM configuration +/// +/// This holds the most commonly used and simplified configuration options for this provider. These +/// paramters can be used in the Teller YAML configuration. +/// +/// For indepth description of each parameter see: [AWS SDK config](https://docs.rs/aws-config/latest/aws_config/struct.SdkConfig.html) +/// +/// If you need an additional parameter from the AWS SDK included in our simplified configuration, +/// open an issue in Teller and request to add it. +/// +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct SSMOptions { + pub region: Option, + pub access_key_id: Option, + pub secret_access_key: Option, + pub endpoint_url: Option, +} + +pub struct SSM { + pub name: String, + pub client: ssm::Client, +} +impl SSM { + #[must_use] + pub fn with_client(name: &str, client: ssm::Client) -> Self { + Self { + name: name.to_string(), + client, + } + } + + /// Create a new ssm provider + /// + /// # Errors + /// + /// This function will return an error if cannot create a provider + pub async fn new(name: &str, opts: Option) -> Result { + let client = if let Some(opts) = opts { + let opts: SSMOptions = serde_json::from_value(opts)?; + + let mut config = aws_config::defaults(BehaviorVersion::v2023_11_09()); + if let (Some(key), Some(secret)) = (opts.access_key_id, opts.secret_access_key) { + config = config + .credentials_provider(Credentials::new(key, secret, None, None, "teller")); + } + if let Some(endpoint_url) = opts.endpoint_url { + config = config.endpoint_url(endpoint_url); + } + if let Some(region) = opts.region { + config = config.region(Region::new(region)); + } + let ssmconf = ssm::config::Builder::from(&config.load().await).build(); + ssm::Client::from_conf(ssmconf) + } else { + let config = aws_config::load_defaults(BehaviorVersion::v2023_11_09()).await; + let ssmconf = ssm::config::Builder::from(&config).build(); + ssm::Client::from_conf(ssmconf) + }; + Ok(Self { + client, + name: name.to_string(), + }) + } +} + +#[async_trait] +impl Provider for SSM { + fn kind(&self) -> ProviderInfo { + ProviderInfo { + kind: ProviderKind::SSM, + name: self.name.clone(), + } + } + + async fn get(&self, pm: &PathMap) -> Result> { + let mut out = Vec::new(); + if pm.keys.is_empty() { + // get parameters by path + let resp = self + .client + .get_parameters_by_path() + .path(&pm.path) + .with_decryption(pm.decrypt) + .send() + .await + .map_err(|e| Error::GetError { + msg: e.to_string(), + path: pm.path.clone(), + })?; + + let params = resp.parameters(); + if params.is_empty() { + return Err(Error::NotFound { + msg: "not found".to_string(), + path: pm.path.clone(), + }); + } + for p in params { + let ssm_key = p.name().unwrap_or_default(); + if !ssm_key.starts_with(&pm.path) { + return Err(Error::GetError { + path: pm.path.clone(), + msg: format!("{ssm_key} is not contained in root path"), + }); + } + + let relative_key = ssm_key + .strip_prefix(&pm.path) + .map(|k| k.trim_start_matches('/')) + .unwrap_or_default(); + + out.push(KV::from_value( + p.value().unwrap_or_default(), + relative_key, + relative_key, + pm, + self.kind(), + )); + } + } else { + for (k, v) in &pm.keys { + let resp = self + .client + .get_parameter() + .name(join_path(&pm.path, k)) + .with_decryption(pm.decrypt) + .send() + .await + .map_err(|e| Error::GetError { + msg: e.to_string(), + path: pm.path.clone(), + })?; + let param = resp.parameter(); + if let Some(p) = param { + out.push(KV::from_value( + p.value().unwrap_or_default(), + k, + v, + pm, + self.kind(), + )); + } + } + } + + Ok(out) + } + + async fn put(&self, pm: &PathMap, kvs: &[KV]) -> Result<()> { + for kv in kvs { + // proper separator sensitive concat + let path = format!("{}/{}", pm.path, kv.key); + self.client + .put_parameter() + .name(&path) + .value(&kv.value) + .overwrite(true) + .r#type(ParameterType::String) + .send() + .await + .map_err(|e| Error::PutError { + msg: e.to_string(), + path, + })?; + } + Ok(()) + } + + async fn del(&self, pm: &PathMap) -> Result<()> { + let paths = if pm.keys.is_empty() { + let kvs = self.get(pm).await?; + kvs.iter() + .map(|kv| join_path(&pm.path, &kv.key)) + .collect::>() + } else { + pm.keys + .keys() + .map(|k| join_path(&pm.path, k)) + .collect::>() + }; + + for path in paths { + let res = self.client.delete_parameter().name(path).send().await; + res.map_or_else(|e| handle_delete(e, pm), |_| Ok(()))?; + } + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + use std::env; + + use dockertest_server::servers::cloud::LocalStackServer; + use dockertest_server::servers::cloud::LocalStackServerConfig; + use dockertest_server::Test; + + use super::*; + use crate::providers::test_utils; + + #[test] + #[cfg(not(windows))] + fn sanity_test() { + if env::var("RUNNER_OS").unwrap_or_default() == "macOS" { + return; + } + + let env: HashMap<_, _> = vec![("SERVICES".to_string(), "iam,sts,ssm,kms".to_string())] + .into_iter() + .collect(); + let config = LocalStackServerConfig::builder() + .env(env) + .port(4551) + .version("2.0.2".into()) + .build() + .unwrap(); + let mut test = Test::new(); + test.register(config); + + test.run(|instance| async move { + let server: LocalStackServer = instance.server(); + let data = serde_json::json!({ + "region": "us-east-1", + "access_key_id": "stub", + "secret_access_key": "stub", + "provider_name": "faked", + "endpoint_url": server.external_url(), + }); + + let p = Box::new(super::SSM::new("ssm", Some(data)).await.unwrap()) + as Box; + + test_utils::ProviderTest::new(p) + .with_root_prefix("/") + .run() + .await; + }); + } +} diff --git a/teller-providers/src/providers/test_utils.rs b/teller-providers/src/providers/test_utils.rs new file mode 100644 index 00000000..83e92556 --- /dev/null +++ b/teller-providers/src/providers/test_utils.rs @@ -0,0 +1,316 @@ +use std::collections::{BTreeMap, HashMap}; + +use insta::{assert_debug_snapshot, with_settings}; + +use crate::config::{PathMap, KV}; +use crate::{Error, Provider}; + +pub const ROOT_PATH_A: &str = "secret/development"; +pub const ROOT_PATH_B: &str = "secret/multiple/app-1"; +pub const ROOT_PATH_C: &str = "secret/multiple/app-2"; +const PATH_A_KEY_1: &str = "db"; +const PATH_A_KEY_2: &str = "log_level"; +const PATH_A_KEY_3: &str = "app"; +const PATH_A_VALUE_1: &str = "{\"DB_PASS\": \"1234\",\"DB_NAME\": \"FOO\"}"; +const PATH_A_VALUE_2: &str = "DEBUG"; +const PATH_A_VALUE_3: &str = "Teller"; +const PATH_B_KEY_1: &str = "log_level"; +const PATH_B_VALUE_1: &str = "DEBUG"; +const PATH_C_KEY_1: &str = "foo"; +const PATH_C_VALUE_1: &str = "bar"; +const PATH_C_VALUE_1_UPDATE: &str = "baz"; + +pub struct ProviderTest { + /// Adding the given prefix to all root path keys. you should use in case you want to change the root path key + /// in case your provider is required a different path from the test case. + /// In the all snapshots tests, the give value wan clean and you will not see it to aliment all the providers returns the sane response + pub root_prefix: Option, + + pub provider: Box, +} + +/// A struct representing a test suite for validating a Teller provider's functionality. +/// +/// This struct encapsulates a set of test functions designed to validate the behavior of a Teller provider. It provides +/// methods for inserting, retrieving, updating, and deleting key-value pairs from the provider, allowing you to verify +/// the correctness of the provider's implementation. +/// +/// # Example +/// ``` +/// use tokio::test; +/// use crate::providers::test_utils; +/// use crate::Provider; +/// +/// +/// async fn sanity_test() { +/// let p = Box::new(super::Inmem::new(None).unwrap()) as Box; +/// +/// test_utils::ProviderTestBuilder::default().run(&p).await; +/// } +/// ``` +impl ProviderTest { + pub fn new(provider: Box) -> Self { + Self { + root_prefix: None, + provider, + } + } + + pub fn with_root_prefix(mut self, root_prefix: &str) -> Self { + self.root_prefix = Some(root_prefix.to_string()); + self + } + + pub async fn run(&self) { + let path_tree = self.get_tree(); + + self.validate_get_unexisting_key().await; + self.validate_put(&path_tree).await; + self.validate_get(&path_tree).await; + self.validate_update().await; + self.validate_delete().await; + self.validate_delete_keys().await; + } + + /// Returns a tree structure of test paths with associated key-value pairs. + /// + /// This function constructs a tree structure of test paths, where each path is associated with a vector of key-value pairs. + /// The tree is represented as a `HashMap` where the keys are root paths, and the associated values are vectors of `KV` pairs. + /// + fn get_tree(&self) -> HashMap<&str, Vec> { + HashMap::from([ + ( + ROOT_PATH_A, + vec![ + KV::from_literal( + "", + PATH_A_KEY_1, + PATH_A_VALUE_1, + self.provider.as_ref().kind(), + ), + KV::from_literal( + "", + PATH_A_KEY_2, + PATH_A_VALUE_2, + self.provider.as_ref().kind(), + ), + KV::from_literal( + "", + PATH_A_KEY_3, + PATH_A_VALUE_3, + self.provider.as_ref().kind(), + ), + ], + ), + ( + ROOT_PATH_B, + vec![KV::from_literal( + "", + PATH_B_KEY_1, + PATH_B_VALUE_1, + self.provider.as_ref().kind(), + )], + ), + ( + ROOT_PATH_C, + vec![KV::from_literal( + "", + PATH_C_KEY_1, + PATH_C_VALUE_1, + self.provider.as_ref().kind(), + )], + ), + ]) + } + + fn get_key_path(&self, root_path: &str) -> String { + self.root_prefix.as_ref().map_or_else( + || root_path.to_string(), + |prefix| format!("{prefix}{root_path}"), + ) + } + + /// Validates that a Teller provider implementation returns an error when attempting to retrieve a non-existent key path. + /// + /// This function checks the behavior of the provided `Provider` implementation when trying to access an invalid key path + /// by constructing a key path from a given root path and an invalid path segment. It then awaits the result and asserts + /// that it is an error. + async fn validate_get_unexisting_key(&self) { + let res = self + .provider + .as_ref() + .get(&PathMap::from_path(&format!("{ROOT_PATH_A}/invalid-path"))) + .await; + assert!(res.is_err()); + } + + /// Validate that Teller provider successfully put all the tests tree map into the provider. + async fn validate_put(&self, path_tree: &HashMap<&str, Vec>) { + for (root_path, keys) in path_tree { + let path_map = PathMap::from_path(&self.get_key_path(root_path)); + let res = self.provider.as_ref().put(&path_map, keys).await; + assert!(res.is_ok()); + assert_debug_snapshot!(format!("[put-{}]", root_path.replace('/', "_"),), res); + } + } + + /// Validates that a Teller provider successfully stores a tree map of key-value pairs. + /// + /// This function tests the behavior of a Teller provider by attempting to put a collection of key-value + /// into the provider and the function returns successfully response. + /// Each put response function snapshot the function response struct + async fn validate_get(&self, path_tree: &HashMap<&str, Vec>) { + for root_path in path_tree.keys() { + let res = self + .provider + .as_ref() + .get(&PathMap::from_path(&self.get_key_path(root_path))) + .await; + assert!(res.is_ok()); + + let mut res = res.unwrap(); + res.sort_by(|a: &KV, b| a.value.cmp(&b.value)); + + with_settings!({filters => vec![ + (format!("{:?}", self.provider.as_ref().kind().kind).as_str(), "PROVIDER_KIND"), + (format!("{:?}", self.provider.as_ref().kind().name).as_str(), "PROVIDER_NAME"), + (format!("\".*{ROOT_PATH_A}").as_str(), format!("\"{ROOT_PATH_A}").as_str()), + (format!("\".*{ROOT_PATH_B}").as_str(), format!("\"{ROOT_PATH_B}").as_str()), + (format!("\".*{ROOT_PATH_C}").as_str(), format!("\"{ROOT_PATH_C}").as_str()), + ]}, { + assert_debug_snapshot!( + format!("[get-{}]", root_path.replace('/', "_"),), + res + ); + }); + } + } + + /// Validates the update operation on a Teller provider after inserting a tree structure. + /// + /// This function is intended to be executed after running the `validate_get` function to insert a tree structure into the + /// Teller provider. It performs the following steps: + /// + /// 1. Updates a specific key-value pair with new values and expects a successful response from the provider. + /// 2. Verifies that the updated value is reflected correctly in the provider. + /// + /// The function utilizes the provided `provider` to perform the update operation and snapshots the results for verification. + async fn validate_update(&self) { + // ** Update value and expected success response. + let update_keys = vec![KV::from_literal( + "", + PATH_C_KEY_1, + PATH_C_VALUE_1_UPDATE, + self.provider.as_ref().kind(), + )]; + let update_res = self + .provider + .as_ref() + .put( + &PathMap::from_path(&self.get_key_path(ROOT_PATH_C)), + &update_keys, + ) + .await; + assert!(update_res.is_ok()); + assert_debug_snapshot!( + format!("[put-update-{}]", ROOT_PATH_C.replace('/', "_"),), + update_res + ); + + // ** Read the updated value and make sure that the value is updated. + let read_after_update_res = self + .provider + .as_ref() + .get(&PathMap::from_path(&self.get_key_path(ROOT_PATH_C))) + .await; + assert!(read_after_update_res.is_ok()); + + with_settings!({filters => vec![ + (format!("{:?}", self.provider.as_ref().kind().kind).as_str(), "PROVIDER_KIND"), + (format!("{:?}", self.provider.as_ref().kind().name).as_str(), "PROVIDER_NAME"), + (format!("\".*{ROOT_PATH_A}").as_str(), format!("\"{ROOT_PATH_A}").as_str()), + (format!("\".*{ROOT_PATH_B}").as_str(), format!("\"{ROOT_PATH_B}").as_str()), + (format!("\".*{ROOT_PATH_C}").as_str(), format!("\"{ROOT_PATH_C}").as_str()), + ]}, { + assert_debug_snapshot!( + format!("[get-after-update-{}]", ROOT_PATH_C.replace('/', "_"),), + read_after_update_res + ); + }); + } + + /// Validates the deletion of a key from a Teller provider. + /// + /// This function tests the behavior of a Teller provider by performing the following steps: + /// + /// 1. Deletes a specific key from the provider using the `del` method. + /// 2. Verifies that the deletion operation is successful by checking the result for success. + /// 3. Attempts to retrieve the deleted key and confirms that it returns an error, indicating that the key no longer exists. + async fn validate_delete(&self) { + let delete_res = self + .provider + .as_ref() + .del(&PathMap::from_path(&self.get_key_path(ROOT_PATH_B))) + .await; + assert!(delete_res.is_ok()); + assert_debug_snapshot!( + format!("[del-{}]", ROOT_PATH_B.replace('/', "_"),), + delete_res + ); + + // ** Validate deletion key. + + let get_del_res = self + .provider + .as_ref() + .get(&PathMap::from_path(&self.get_key_path(ROOT_PATH_B))) + .await; + + assert!(matches!( + get_del_res, + Err(Error::NotFound { path: _, msg: _ }) + )); + assert!(get_del_res.is_err()); + } + + /// Validates deletion specifics key from a Teller provider. + /// + /// This function tests the behavior of a Teller provider by performing the following steps: + /// + /// 1. Delete specifics keys from a path by using adding keys list. + /// 2. Verifies that the deletion operation is successful by run `get` again on the same path and expecting that + /// not see the deletion keys + async fn validate_delete_keys(&self) { + let mut path_path = PathMap::from_path(&self.get_key_path(ROOT_PATH_A)); + + path_path.keys = BTreeMap::from([ + (PATH_A_KEY_2.to_string(), String::new()), + (PATH_A_KEY_3.to_string(), String::new()), + ]); + + let delete_keys_res = self.provider.as_ref().del(&path_path).await; + println!("{delete_keys_res:#?}"); + assert!(delete_keys_res.is_ok()); + assert_debug_snapshot!( + format!("[del-keys-{}]", ROOT_PATH_A.replace('/', "_")), + delete_keys_res + ); + + let get_del_res = self + .provider + .as_ref() + .get(&PathMap::from_path(&self.get_key_path(ROOT_PATH_A))) + .await; + + with_settings!({filters => vec![ + (format!("{:?}", self.provider.as_ref().kind().kind).as_str(), "PROVIDER_KIND"), + (format!("{:?}", self.provider.as_ref().kind().name).as_str(), "PROVIDER_NAME"), + (format!("\".*{ROOT_PATH_A}").as_str(), format!("\"{ROOT_PATH_A}").as_str()), + ]}, { + assert_debug_snapshot!( + format!("[get-del-keys-{}]", ROOT_PATH_A.replace('/', "_")), + get_del_res + ); + }); + } +} diff --git a/teller-providers/src/registry.rs b/teller-providers/src/registry.rs new file mode 100644 index 00000000..9f81f06e --- /dev/null +++ b/teller-providers/src/registry.rs @@ -0,0 +1,93 @@ +use std::collections::{BTreeMap, HashMap}; + +use crate::providers::ProviderKind; +use crate::Result; +use crate::{config::ProviderCfg, Provider}; + +pub struct Registry { + providers: HashMap>, +} + +impl Registry { + /// Create a registry from config + /// + /// # Errors + /// + /// This function will return an error if any provider loading failed + pub async fn new(providers: &BTreeMap) -> Result { + let mut loaded_providers = HashMap::new(); + for (k, provider) in providers { + let provider: Box = match provider.kind { + ProviderKind::Inmem => Box::new(crate::providers::inmem::Inmem::new( + k, + provider.options.clone(), + )?), + + #[cfg(feature = "dotenv")] + ProviderKind::Dotenv => Box::new(crate::providers::dotenv::Dotenv::new( + k, + provider + .options + .clone() + .map(serde_json::from_value) + .transpose()?, + )?), + #[cfg(feature = "hashicorp_vault")] + ProviderKind::Hashicorp => { + Box::new(crate::providers::hashicorp_vault::Hashivault::new( + k, + provider + .options + .clone() + .map(serde_json::from_value) + .transpose()?, + )?) + } + #[cfg(feature = "ssm")] + ProviderKind::SSM => { + Box::new(crate::providers::ssm::SSM::new(k, provider.options.clone()).await?) + } + #[cfg(feature = "aws_secretsmanager")] + ProviderKind::AWSSecretsManager => Box::new( + crate::providers::aws_secretsmanager::AWSSecretsManager::new( + k, + provider + .options + .clone() + .map(serde_json::from_value) + .transpose()?, + ) + .await?, + ), + #[cfg(feature = "google_secretmanager")] + ProviderKind::GoogleSecretManager => Box::new( + crate::providers::google_secretmanager::GoogleSecretManager::new( + k, + Box::new(crate::providers::google_secretmanager::GSMClient::new().await?) + as Box, + ), + ), + #[cfg(feature = "hashicorp_consul")] + ProviderKind::HashiCorpConsul => { + Box::new(crate::providers::hashicorp_consul::HashiCorpConsul::new( + k, + provider + .options + .clone() + .map(serde_json::from_value) + .transpose()?, + )?) + } + }; + loaded_providers.insert(k.clone(), provider); + } + Ok(Self { + providers: loaded_providers, + }) + } + #[must_use] + #[allow(clippy::borrowed_box)] + pub fn get(&self, name: &str) -> Option<&Box> { + self.providers.get(name) + } +} diff --git a/vendor/cloud.google.com/go/LICENSE b/vendor/cloud.google.com/go/LICENSE deleted file mode 100644 index d6456956..00000000 --- a/vendor/cloud.google.com/go/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/cloud.google.com/go/compute/metadata/metadata.go b/vendor/cloud.google.com/go/compute/metadata/metadata.go deleted file mode 100644 index 545bd9d3..00000000 --- a/vendor/cloud.google.com/go/compute/metadata/metadata.go +++ /dev/null @@ -1,519 +0,0 @@ -// Copyright 2014 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 metadata provides access to Google Compute Engine (GCE) -// metadata and API service accounts. -// -// This package is a wrapper around the GCE metadata service, -// as documented at https://developers.google.com/compute/docs/metadata. -package metadata // import "cloud.google.com/go/compute/metadata" - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "runtime" - "strings" - "sync" - "time" -) - -const ( - // metadataIP is the documented metadata server IP address. - metadataIP = "169.254.169.254" - - // metadataHostEnv is the environment variable specifying the - // GCE metadata hostname. If empty, the default value of - // metadataIP ("169.254.169.254") is used instead. - // This is variable name is not defined by any spec, as far as - // I know; it was made up for the Go package. - metadataHostEnv = "GCE_METADATA_HOST" - - userAgent = "gcloud-golang/0.1" -) - -type cachedValue struct { - k string - trim bool - mu sync.Mutex - v string -} - -var ( - projID = &cachedValue{k: "project/project-id", trim: true} - projNum = &cachedValue{k: "project/numeric-project-id", trim: true} - instID = &cachedValue{k: "instance/id", trim: true} -) - -var defaultClient = &Client{hc: &http.Client{ - Transport: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 2 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - }, -}} - -// NotDefinedError is returned when requested metadata is not defined. -// -// The underlying string is the suffix after "/computeMetadata/v1/". -// -// This error is not returned if the value is defined to be the empty -// string. -type NotDefinedError string - -func (suffix NotDefinedError) Error() string { - return fmt.Sprintf("metadata: GCE metadata %q not defined", string(suffix)) -} - -func (c *cachedValue) get(cl *Client) (v string, err error) { - defer c.mu.Unlock() - c.mu.Lock() - if c.v != "" { - return c.v, nil - } - if c.trim { - v, err = cl.getTrimmed(c.k) - } else { - v, err = cl.Get(c.k) - } - if err == nil { - c.v = v - } - return -} - -var ( - onGCEOnce sync.Once - onGCE bool -) - -// OnGCE reports whether this process is running on Google Compute Engine. -func OnGCE() bool { - onGCEOnce.Do(initOnGCE) - return onGCE -} - -func initOnGCE() { - onGCE = testOnGCE() -} - -func testOnGCE() bool { - // The user explicitly said they're on GCE, so trust them. - if os.Getenv(metadataHostEnv) != "" { - return true - } - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - resc := make(chan bool, 2) - - // Try two strategies in parallel. - // See https://github.com/googleapis/google-cloud-go/issues/194 - go func() { - req, _ := http.NewRequest("GET", "http://"+metadataIP, nil) - req.Header.Set("User-Agent", userAgent) - res, err := defaultClient.hc.Do(req.WithContext(ctx)) - if err != nil { - resc <- false - return - } - defer res.Body.Close() - resc <- res.Header.Get("Metadata-Flavor") == "Google" - }() - - go func() { - addrs, err := net.DefaultResolver.LookupHost(ctx, "metadata.google.internal") - if err != nil || len(addrs) == 0 { - resc <- false - return - } - resc <- strsContains(addrs, metadataIP) - }() - - tryHarder := systemInfoSuggestsGCE() - if tryHarder { - res := <-resc - if res { - // The first strategy succeeded, so let's use it. - return true - } - // Wait for either the DNS or metadata server probe to - // contradict the other one and say we are running on - // GCE. Give it a lot of time to do so, since the system - // info already suggests we're running on a GCE BIOS. - timer := time.NewTimer(5 * time.Second) - defer timer.Stop() - select { - case res = <-resc: - return res - case <-timer.C: - // Too slow. Who knows what this system is. - return false - } - } - - // There's no hint from the system info that we're running on - // GCE, so use the first probe's result as truth, whether it's - // true or false. The goal here is to optimize for speed for - // users who are NOT running on GCE. We can't assume that - // either a DNS lookup or an HTTP request to a blackholed IP - // address is fast. Worst case this should return when the - // metaClient's Transport.ResponseHeaderTimeout or - // Transport.Dial.Timeout fires (in two seconds). - return <-resc -} - -// systemInfoSuggestsGCE reports whether the local system (without -// doing network requests) suggests that we're running on GCE. If this -// returns true, testOnGCE tries a bit harder to reach its metadata -// server. -func systemInfoSuggestsGCE() bool { - if runtime.GOOS != "linux" { - // We don't have any non-Linux clues available, at least yet. - return false - } - slurp, _ := ioutil.ReadFile("/sys/class/dmi/id/product_name") - name := strings.TrimSpace(string(slurp)) - return name == "Google" || name == "Google Compute Engine" -} - -// Subscribe calls Client.Subscribe on the default client. -func Subscribe(suffix string, fn func(v string, ok bool) error) error { - return defaultClient.Subscribe(suffix, fn) -} - -// Get calls Client.Get on the default client. -func Get(suffix string) (string, error) { return defaultClient.Get(suffix) } - -// ProjectID returns the current instance's project ID string. -func ProjectID() (string, error) { return defaultClient.ProjectID() } - -// NumericProjectID returns the current instance's numeric project ID. -func NumericProjectID() (string, error) { return defaultClient.NumericProjectID() } - -// InternalIP returns the instance's primary internal IP address. -func InternalIP() (string, error) { return defaultClient.InternalIP() } - -// ExternalIP returns the instance's primary external (public) IP address. -func ExternalIP() (string, error) { return defaultClient.ExternalIP() } - -// Email calls Client.Email on the default client. -func Email(serviceAccount string) (string, error) { return defaultClient.Email(serviceAccount) } - -// Hostname returns the instance's hostname. This will be of the form -// ".c..internal". -func Hostname() (string, error) { return defaultClient.Hostname() } - -// InstanceTags returns the list of user-defined instance tags, -// assigned when initially creating a GCE instance. -func InstanceTags() ([]string, error) { return defaultClient.InstanceTags() } - -// InstanceID returns the current VM's numeric instance ID. -func InstanceID() (string, error) { return defaultClient.InstanceID() } - -// InstanceName returns the current VM's instance ID string. -func InstanceName() (string, error) { return defaultClient.InstanceName() } - -// Zone returns the current VM's zone, such as "us-central1-b". -func Zone() (string, error) { return defaultClient.Zone() } - -// InstanceAttributes calls Client.InstanceAttributes on the default client. -func InstanceAttributes() ([]string, error) { return defaultClient.InstanceAttributes() } - -// ProjectAttributes calls Client.ProjectAttributes on the default client. -func ProjectAttributes() ([]string, error) { return defaultClient.ProjectAttributes() } - -// InstanceAttributeValue calls Client.InstanceAttributeValue on the default client. -func InstanceAttributeValue(attr string) (string, error) { - return defaultClient.InstanceAttributeValue(attr) -} - -// ProjectAttributeValue calls Client.ProjectAttributeValue on the default client. -func ProjectAttributeValue(attr string) (string, error) { - return defaultClient.ProjectAttributeValue(attr) -} - -// Scopes calls Client.Scopes on the default client. -func Scopes(serviceAccount string) ([]string, error) { return defaultClient.Scopes(serviceAccount) } - -func strsContains(ss []string, s string) bool { - for _, v := range ss { - if v == s { - return true - } - } - return false -} - -// A Client provides metadata. -type Client struct { - hc *http.Client -} - -// NewClient returns a Client that can be used to fetch metadata. -// Returns the client that uses the specified http.Client for HTTP requests. -// If nil is specified, returns the default client. -func NewClient(c *http.Client) *Client { - if c == nil { - return defaultClient - } - - return &Client{hc: c} -} - -// getETag returns a value from the metadata service as well as the associated ETag. -// This func is otherwise equivalent to Get. -func (c *Client) getETag(suffix string) (value, etag string, err error) { - // Using a fixed IP makes it very difficult to spoof the metadata service in - // a container, which is an important use-case for local testing of cloud - // deployments. To enable spoofing of the metadata service, the environment - // variable GCE_METADATA_HOST is first inspected to decide where metadata - // requests shall go. - host := os.Getenv(metadataHostEnv) - if host == "" { - // Using 169.254.169.254 instead of "metadata" here because Go - // binaries built with the "netgo" tag and without cgo won't - // know the search suffix for "metadata" is - // ".google.internal", and this IP address is documented as - // being stable anyway. - host = metadataIP - } - suffix = strings.TrimLeft(suffix, "/") - u := "http://" + host + "/computeMetadata/v1/" + suffix - req, err := http.NewRequest("GET", u, nil) - if err != nil { - return "", "", err - } - req.Header.Set("Metadata-Flavor", "Google") - req.Header.Set("User-Agent", userAgent) - res, err := c.hc.Do(req) - if err != nil { - return "", "", err - } - defer res.Body.Close() - if res.StatusCode == http.StatusNotFound { - return "", "", NotDefinedError(suffix) - } - all, err := ioutil.ReadAll(res.Body) - if err != nil { - return "", "", err - } - if res.StatusCode != 200 { - return "", "", &Error{Code: res.StatusCode, Message: string(all)} - } - return string(all), res.Header.Get("Etag"), nil -} - -// Get returns a value from the metadata service. -// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/". -// -// If the GCE_METADATA_HOST environment variable is not defined, a default of -// 169.254.169.254 will be used instead. -// -// If the requested metadata is not defined, the returned error will -// be of type NotDefinedError. -func (c *Client) Get(suffix string) (string, error) { - val, _, err := c.getETag(suffix) - return val, err -} - -func (c *Client) getTrimmed(suffix string) (s string, err error) { - s, err = c.Get(suffix) - s = strings.TrimSpace(s) - return -} - -func (c *Client) lines(suffix string) ([]string, error) { - j, err := c.Get(suffix) - if err != nil { - return nil, err - } - s := strings.Split(strings.TrimSpace(j), "\n") - for i := range s { - s[i] = strings.TrimSpace(s[i]) - } - return s, nil -} - -// ProjectID returns the current instance's project ID string. -func (c *Client) ProjectID() (string, error) { return projID.get(c) } - -// NumericProjectID returns the current instance's numeric project ID. -func (c *Client) NumericProjectID() (string, error) { return projNum.get(c) } - -// InstanceID returns the current VM's numeric instance ID. -func (c *Client) InstanceID() (string, error) { return instID.get(c) } - -// InternalIP returns the instance's primary internal IP address. -func (c *Client) InternalIP() (string, error) { - return c.getTrimmed("instance/network-interfaces/0/ip") -} - -// Email returns the email address associated with the service account. -// The account may be empty or the string "default" to use the instance's -// main account. -func (c *Client) Email(serviceAccount string) (string, error) { - if serviceAccount == "" { - serviceAccount = "default" - } - return c.getTrimmed("instance/service-accounts/" + serviceAccount + "/email") -} - -// ExternalIP returns the instance's primary external (public) IP address. -func (c *Client) ExternalIP() (string, error) { - return c.getTrimmed("instance/network-interfaces/0/access-configs/0/external-ip") -} - -// Hostname returns the instance's hostname. This will be of the form -// ".c..internal". -func (c *Client) Hostname() (string, error) { - return c.getTrimmed("instance/hostname") -} - -// InstanceTags returns the list of user-defined instance tags, -// assigned when initially creating a GCE instance. -func (c *Client) InstanceTags() ([]string, error) { - var s []string - j, err := c.Get("instance/tags") - if err != nil { - return nil, err - } - if err := json.NewDecoder(strings.NewReader(j)).Decode(&s); err != nil { - return nil, err - } - return s, nil -} - -// InstanceName returns the current VM's instance ID string. -func (c *Client) InstanceName() (string, error) { - return c.getTrimmed("instance/name") -} - -// Zone returns the current VM's zone, such as "us-central1-b". -func (c *Client) Zone() (string, error) { - zone, err := c.getTrimmed("instance/zone") - // zone is of the form "projects//zones/". - if err != nil { - return "", err - } - return zone[strings.LastIndex(zone, "/")+1:], nil -} - -// InstanceAttributes returns the list of user-defined attributes, -// assigned when initially creating a GCE VM instance. The value of an -// attribute can be obtained with InstanceAttributeValue. -func (c *Client) InstanceAttributes() ([]string, error) { return c.lines("instance/attributes/") } - -// ProjectAttributes returns the list of user-defined attributes -// applying to the project as a whole, not just this VM. The value of -// an attribute can be obtained with ProjectAttributeValue. -func (c *Client) ProjectAttributes() ([]string, error) { return c.lines("project/attributes/") } - -// InstanceAttributeValue returns the value of the provided VM -// instance attribute. -// -// If the requested attribute is not defined, the returned error will -// be of type NotDefinedError. -// -// InstanceAttributeValue may return ("", nil) if the attribute was -// defined to be the empty string. -func (c *Client) InstanceAttributeValue(attr string) (string, error) { - return c.Get("instance/attributes/" + attr) -} - -// ProjectAttributeValue returns the value of the provided -// project attribute. -// -// If the requested attribute is not defined, the returned error will -// be of type NotDefinedError. -// -// ProjectAttributeValue may return ("", nil) if the attribute was -// defined to be the empty string. -func (c *Client) ProjectAttributeValue(attr string) (string, error) { - return c.Get("project/attributes/" + attr) -} - -// Scopes returns the service account scopes for the given account. -// The account may be empty or the string "default" to use the instance's -// main account. -func (c *Client) Scopes(serviceAccount string) ([]string, error) { - if serviceAccount == "" { - serviceAccount = "default" - } - return c.lines("instance/service-accounts/" + serviceAccount + "/scopes") -} - -// Subscribe subscribes to a value from the metadata service. -// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/". -// The suffix may contain query parameters. -// -// Subscribe calls fn with the latest metadata value indicated by the provided -// suffix. If the metadata value is deleted, fn is called with the empty string -// and ok false. Subscribe blocks until fn returns a non-nil error or the value -// is deleted. Subscribe returns the error value returned from the last call to -// fn, which may be nil when ok == false. -func (c *Client) Subscribe(suffix string, fn func(v string, ok bool) error) error { - const failedSubscribeSleep = time.Second * 5 - - // First check to see if the metadata value exists at all. - val, lastETag, err := c.getETag(suffix) - if err != nil { - return err - } - - if err := fn(val, true); err != nil { - return err - } - - ok := true - if strings.ContainsRune(suffix, '?') { - suffix += "&wait_for_change=true&last_etag=" - } else { - suffix += "?wait_for_change=true&last_etag=" - } - for { - val, etag, err := c.getETag(suffix + url.QueryEscape(lastETag)) - if err != nil { - if _, deleted := err.(NotDefinedError); !deleted { - time.Sleep(failedSubscribeSleep) - continue // Retry on other errors. - } - ok = false - } - lastETag = etag - - if err := fn(val, ok); err != nil || !ok { - return err - } - } -} - -// Error contains an error response from the server. -type Error struct { - // Code is the HTTP response status code. - Code int - // Message is the server response message. - Message string -} - -func (e *Error) Error() string { - return fmt.Sprintf("compute: Received %d `%s`", e.Code, e.Message) -} diff --git a/vendor/cloud.google.com/go/iam/iam.go b/vendor/cloud.google.com/go/iam/iam.go deleted file mode 100644 index 0a06ea2e..00000000 --- a/vendor/cloud.google.com/go/iam/iam.go +++ /dev/null @@ -1,387 +0,0 @@ -// Copyright 2016 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 iam supports the resource-specific operations of Google Cloud -// IAM (Identity and Access Management) for the Google Cloud Libraries. -// See https://cloud.google.com/iam for more about IAM. -// -// Users of the Google Cloud Libraries will typically not use this package -// directly. Instead they will begin with some resource that supports IAM, like -// a pubsub topic, and call its IAM method to get a Handle for that resource. -package iam - -import ( - "context" - "fmt" - "time" - - gax "github.com/googleapis/gax-go/v2" - pb "google.golang.org/genproto/googleapis/iam/v1" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" -) - -// client abstracts the IAMPolicy API to allow multiple implementations. -type client interface { - Get(ctx context.Context, resource string) (*pb.Policy, error) - Set(ctx context.Context, resource string, p *pb.Policy) error - Test(ctx context.Context, resource string, perms []string) ([]string, error) - GetWithVersion(ctx context.Context, resource string, requestedPolicyVersion int32) (*pb.Policy, error) -} - -// grpcClient implements client for the standard gRPC-based IAMPolicy service. -type grpcClient struct { - c pb.IAMPolicyClient -} - -var withRetry = gax.WithRetry(func() gax.Retryer { - return gax.OnCodes([]codes.Code{ - codes.DeadlineExceeded, - codes.Unavailable, - }, gax.Backoff{ - Initial: 100 * time.Millisecond, - Max: 60 * time.Second, - Multiplier: 1.3, - }) -}) - -func (g *grpcClient) Get(ctx context.Context, resource string) (*pb.Policy, error) { - return g.GetWithVersion(ctx, resource, 1) -} - -func (g *grpcClient) GetWithVersion(ctx context.Context, resource string, requestedPolicyVersion int32) (*pb.Policy, error) { - var proto *pb.Policy - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource)) - ctx = insertMetadata(ctx, md) - - err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error { - var err error - proto, err = g.c.GetIamPolicy(ctx, &pb.GetIamPolicyRequest{ - Resource: resource, - Options: &pb.GetPolicyOptions{ - RequestedPolicyVersion: requestedPolicyVersion, - }, - }) - return err - }, withRetry) - if err != nil { - return nil, err - } - return proto, nil -} - -func (g *grpcClient) Set(ctx context.Context, resource string, p *pb.Policy) error { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource)) - ctx = insertMetadata(ctx, md) - - return gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error { - _, err := g.c.SetIamPolicy(ctx, &pb.SetIamPolicyRequest{ - Resource: resource, - Policy: p, - }) - return err - }, withRetry) -} - -func (g *grpcClient) Test(ctx context.Context, resource string, perms []string) ([]string, error) { - var res *pb.TestIamPermissionsResponse - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", resource)) - ctx = insertMetadata(ctx, md) - - err := gax.Invoke(ctx, func(ctx context.Context, _ gax.CallSettings) error { - var err error - res, err = g.c.TestIamPermissions(ctx, &pb.TestIamPermissionsRequest{ - Resource: resource, - Permissions: perms, - }) - return err - }, withRetry) - if err != nil { - return nil, err - } - return res.Permissions, nil -} - -// A Handle provides IAM operations for a resource. -type Handle struct { - c client - resource string -} - -// A Handle3 provides IAM operations for a resource. It is similar to a Handle, but provides access to newer IAM features (e.g., conditions). -type Handle3 struct { - c client - resource string - version int32 -} - -// InternalNewHandle is for use by the Google Cloud Libraries only. -// -// InternalNewHandle returns a Handle for resource. -// The conn parameter refers to a server that must support the IAMPolicy service. -func InternalNewHandle(conn grpc.ClientConnInterface, resource string) *Handle { - return InternalNewHandleGRPCClient(pb.NewIAMPolicyClient(conn), resource) -} - -// InternalNewHandleGRPCClient is for use by the Google Cloud Libraries only. -// -// InternalNewHandleClient returns a Handle for resource using the given -// grpc service that implements IAM as a mixin -func InternalNewHandleGRPCClient(c pb.IAMPolicyClient, resource string) *Handle { - return InternalNewHandleClient(&grpcClient{c: c}, resource) -} - -// InternalNewHandleClient is for use by the Google Cloud Libraries only. -// -// InternalNewHandleClient returns a Handle for resource using the given -// client implementation. -func InternalNewHandleClient(c client, resource string) *Handle { - return &Handle{ - c: c, - resource: resource, - } -} - -// V3 returns a Handle3, which is like Handle except it sets -// requestedPolicyVersion to 3 when retrieving a policy and policy.version to 3 -// when storing a policy. -func (h *Handle) V3() *Handle3 { - return &Handle3{ - c: h.c, - resource: h.resource, - version: 3, - } -} - -// Policy retrieves the IAM policy for the resource. -func (h *Handle) Policy(ctx context.Context) (*Policy, error) { - proto, err := h.c.Get(ctx, h.resource) - if err != nil { - return nil, err - } - return &Policy{InternalProto: proto}, nil -} - -// SetPolicy replaces the resource's current policy with the supplied Policy. -// -// If policy was created from a prior call to Get, then the modification will -// only succeed if the policy has not changed since the Get. -func (h *Handle) SetPolicy(ctx context.Context, policy *Policy) error { - return h.c.Set(ctx, h.resource, policy.InternalProto) -} - -// TestPermissions returns the subset of permissions that the caller has on the resource. -func (h *Handle) TestPermissions(ctx context.Context, permissions []string) ([]string, error) { - return h.c.Test(ctx, h.resource, permissions) -} - -// A RoleName is a name representing a collection of permissions. -type RoleName string - -// Common role names. -const ( - Owner RoleName = "roles/owner" - Editor RoleName = "roles/editor" - Viewer RoleName = "roles/viewer" -) - -const ( - // AllUsers is a special member that denotes all users, even unauthenticated ones. - AllUsers = "allUsers" - - // AllAuthenticatedUsers is a special member that denotes all authenticated users. - AllAuthenticatedUsers = "allAuthenticatedUsers" -) - -// A Policy is a list of Bindings representing roles -// granted to members. -// -// The zero Policy is a valid policy with no bindings. -type Policy struct { - // TODO(jba): when type aliases are available, put Policy into an internal package - // and provide an exported alias here. - - // This field is exported for use by the Google Cloud Libraries only. - // It may become unexported in a future release. - InternalProto *pb.Policy -} - -// Members returns the list of members with the supplied role. -// The return value should not be modified. Use Add and Remove -// to modify the members of a role. -func (p *Policy) Members(r RoleName) []string { - b := p.binding(r) - if b == nil { - return nil - } - return b.Members -} - -// HasRole reports whether member has role r. -func (p *Policy) HasRole(member string, r RoleName) bool { - return memberIndex(member, p.binding(r)) >= 0 -} - -// Add adds member member to role r if it is not already present. -// A new binding is created if there is no binding for the role. -func (p *Policy) Add(member string, r RoleName) { - b := p.binding(r) - if b == nil { - if p.InternalProto == nil { - p.InternalProto = &pb.Policy{} - } - p.InternalProto.Bindings = append(p.InternalProto.Bindings, &pb.Binding{ - Role: string(r), - Members: []string{member}, - }) - return - } - if memberIndex(member, b) < 0 { - b.Members = append(b.Members, member) - return - } -} - -// Remove removes member from role r if it is present. -func (p *Policy) Remove(member string, r RoleName) { - bi := p.bindingIndex(r) - if bi < 0 { - return - } - bindings := p.InternalProto.Bindings - b := bindings[bi] - mi := memberIndex(member, b) - if mi < 0 { - return - } - // Order doesn't matter for bindings or members, so to remove, move the last item - // into the removed spot and shrink the slice. - if len(b.Members) == 1 { - // Remove binding. - last := len(bindings) - 1 - bindings[bi] = bindings[last] - bindings[last] = nil - p.InternalProto.Bindings = bindings[:last] - return - } - // Remove member. - // TODO(jba): worry about multiple copies of m? - last := len(b.Members) - 1 - b.Members[mi] = b.Members[last] - b.Members[last] = "" - b.Members = b.Members[:last] -} - -// Roles returns the names of all the roles that appear in the Policy. -func (p *Policy) Roles() []RoleName { - if p.InternalProto == nil { - return nil - } - var rns []RoleName - for _, b := range p.InternalProto.Bindings { - rns = append(rns, RoleName(b.Role)) - } - return rns -} - -// binding returns the Binding for the suppied role, or nil if there isn't one. -func (p *Policy) binding(r RoleName) *pb.Binding { - i := p.bindingIndex(r) - if i < 0 { - return nil - } - return p.InternalProto.Bindings[i] -} - -func (p *Policy) bindingIndex(r RoleName) int { - if p.InternalProto == nil { - return -1 - } - for i, b := range p.InternalProto.Bindings { - if b.Role == string(r) { - return i - } - } - return -1 -} - -// memberIndex returns the index of m in b's Members, or -1 if not found. -func memberIndex(m string, b *pb.Binding) int { - if b == nil { - return -1 - } - for i, mm := range b.Members { - if mm == m { - return i - } - } - return -1 -} - -// insertMetadata inserts metadata into the given context -func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { - out, _ := metadata.FromOutgoingContext(ctx) - out = out.Copy() - for _, md := range mds { - for k, v := range md { - out[k] = append(out[k], v...) - } - } - return metadata.NewOutgoingContext(ctx, out) -} - -// A Policy3 is a list of Bindings representing roles granted to members. -// -// The zero Policy3 is a valid policy with no bindings. -// -// It is similar to a Policy, except a Policy3 provides direct access to the -// list of Bindings. -// -// The policy version is always set to 3. -type Policy3 struct { - etag []byte - Bindings []*pb.Binding -} - -// Policy retrieves the IAM policy for the resource. -// -// requestedPolicyVersion is always set to 3. -func (h *Handle3) Policy(ctx context.Context) (*Policy3, error) { - proto, err := h.c.GetWithVersion(ctx, h.resource, h.version) - if err != nil { - return nil, err - } - return &Policy3{ - Bindings: proto.Bindings, - etag: proto.Etag, - }, nil -} - -// SetPolicy replaces the resource's current policy with the supplied Policy. -// -// If policy was created from a prior call to Get, then the modification will -// only succeed if the policy has not changed since the Get. -func (h *Handle3) SetPolicy(ctx context.Context, policy *Policy3) error { - return h.c.Set(ctx, h.resource, &pb.Policy{ - Bindings: policy.Bindings, - Etag: policy.etag, - Version: h.version, - }) -} - -// TestPermissions returns the subset of permissions that the caller has on the resource. -func (h *Handle3) TestPermissions(ctx context.Context, permissions []string) ([]string, error) { - return h.c.Test(ctx, h.resource, permissions) -} diff --git a/vendor/cloud.google.com/go/secretmanager/apiv1/doc.go b/vendor/cloud.google.com/go/secretmanager/apiv1/doc.go deleted file mode 100644 index b034fb73..00000000 --- a/vendor/cloud.google.com/go/secretmanager/apiv1/doc.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2021 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 -// -// 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. - -// Code generated by protoc-gen-go_gapic. DO NOT EDIT. - -// Package secretmanager is an auto-generated package for the -// Secret Manager API. -// -// Stores sensitive data such as API keys, passwords, and certificates. -// Provides convenience while improving security. -// -// Use of Context -// -// The ctx passed to NewClient is used for authentication requests and -// for creating the underlying connection, but is not used for subsequent calls. -// Individual methods on the client use the ctx given to them. -// -// To close the open connection, use the Close() method. -// -// For information about setting deadlines, reusing contexts, and more -// please visit pkg.go.dev/cloud.google.com/go. -package secretmanager // import "cloud.google.com/go/secretmanager/apiv1" - -import ( - "context" - "os" - "runtime" - "strconv" - "strings" - "unicode" - - "google.golang.org/api/option" - "google.golang.org/grpc/metadata" -) - -// For more information on implementing a client constructor hook, see -// https://github.com/googleapis/google-cloud-go/wiki/Customizing-constructors. -type clientHookParams struct{} -type clientHook func(context.Context, clientHookParams) ([]option.ClientOption, error) - -const versionClient = "20210222" - -func insertMetadata(ctx context.Context, mds ...metadata.MD) context.Context { - out, _ := metadata.FromOutgoingContext(ctx) - out = out.Copy() - for _, md := range mds { - for k, v := range md { - out[k] = append(out[k], v...) - } - } - return metadata.NewOutgoingContext(ctx, out) -} - -func checkDisableDeadlines() (bool, error) { - raw, ok := os.LookupEnv("GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE") - if !ok { - return false, nil - } - - b, err := strconv.ParseBool(raw) - return b, err -} - -// DefaultAuthScopes reports the default set of authentication scopes to use with this package. -func DefaultAuthScopes() []string { - return []string{ - "https://www.googleapis.com/auth/cloud-platform", - } -} - -// versionGo returns the Go runtime version. The returned string -// has no whitespace, suitable for reporting in header. -func versionGo() string { - const develPrefix = "devel +" - - s := runtime.Version() - if strings.HasPrefix(s, develPrefix) { - s = s[len(develPrefix):] - if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 { - s = s[:p] - } - return s - } - - notSemverRune := func(r rune) bool { - return !strings.ContainsRune("0123456789.", r) - } - - if strings.HasPrefix(s, "go1") { - s = s[2:] - var prerelease string - if p := strings.IndexFunc(s, notSemverRune); p >= 0 { - s, prerelease = s[:p], s[p:] - } - if strings.HasSuffix(s, ".") { - s += "0" - } else if strings.Count(s, ".") < 2 { - s += ".0" - } - if prerelease != "" { - s += "-" + prerelease - } - return s - } - return "UNKNOWN" -} diff --git a/vendor/cloud.google.com/go/secretmanager/apiv1/gapic_metadata.json b/vendor/cloud.google.com/go/secretmanager/apiv1/gapic_metadata.json deleted file mode 100644 index a5049c72..00000000 --- a/vendor/cloud.google.com/go/secretmanager/apiv1/gapic_metadata.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "schema": "1.0", - "comment": "This file maps proto services/RPCs to the corresponding library clients/methods.", - "language": "go", - "protoPackage": "google.cloud.secretmanager.v1", - "libraryPackage": "cloud.google.com/go/secretmanager/apiv1", - "services": { - "SecretManagerService": { - "clients": { - "grpc": { - "libraryClient": "Client", - "rpcs": { - "AccessSecretVersion": { - "methods": [ - "AccessSecretVersion" - ] - }, - "AddSecretVersion": { - "methods": [ - "AddSecretVersion" - ] - }, - "CreateSecret": { - "methods": [ - "CreateSecret" - ] - }, - "DeleteSecret": { - "methods": [ - "DeleteSecret" - ] - }, - "DestroySecretVersion": { - "methods": [ - "DestroySecretVersion" - ] - }, - "DisableSecretVersion": { - "methods": [ - "DisableSecretVersion" - ] - }, - "EnableSecretVersion": { - "methods": [ - "EnableSecretVersion" - ] - }, - "GetIamPolicy": { - "methods": [ - "GetIamPolicy" - ] - }, - "GetSecret": { - "methods": [ - "GetSecret" - ] - }, - "GetSecretVersion": { - "methods": [ - "GetSecretVersion" - ] - }, - "ListSecretVersions": { - "methods": [ - "ListSecretVersions" - ] - }, - "ListSecrets": { - "methods": [ - "ListSecrets" - ] - }, - "SetIamPolicy": { - "methods": [ - "SetIamPolicy" - ] - }, - "TestIamPermissions": { - "methods": [ - "TestIamPermissions" - ] - }, - "UpdateSecret": { - "methods": [ - "UpdateSecret" - ] - } - } - } - } - } - } -} diff --git a/vendor/cloud.google.com/go/secretmanager/apiv1/iam.go b/vendor/cloud.google.com/go/secretmanager/apiv1/iam.go deleted file mode 100644 index e3d78a54..00000000 --- a/vendor/cloud.google.com/go/secretmanager/apiv1/iam.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2020 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 -// -// 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 secretmanager - -import ( - "cloud.google.com/go/iam" -) - -// IAM returns a handle to inspect and change permissions of the resource -// indicated by the given resource path. Name should be of the format -// `projects/my-project/secrets/my-secret`. -func (c *Client) IAM(name string) *iam.Handle { - return iam.InternalNewHandleGRPCClient(c.client, name) -} diff --git a/vendor/cloud.google.com/go/secretmanager/apiv1/secret_manager_client.go b/vendor/cloud.google.com/go/secretmanager/apiv1/secret_manager_client.go deleted file mode 100644 index fdb22d22..00000000 --- a/vendor/cloud.google.com/go/secretmanager/apiv1/secret_manager_client.go +++ /dev/null @@ -1,672 +0,0 @@ -// Copyright 2021 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 -// -// 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. - -// Code generated by protoc-gen-go_gapic. DO NOT EDIT. - -package secretmanager - -import ( - "context" - "fmt" - "math" - "net/url" - "time" - - "github.com/golang/protobuf/proto" - gax "github.com/googleapis/gax-go/v2" - "google.golang.org/api/iterator" - "google.golang.org/api/option" - "google.golang.org/api/option/internaloption" - gtransport "google.golang.org/api/transport/grpc" - secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1" - iampb "google.golang.org/genproto/googleapis/iam/v1" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" -) - -var newClientHook clientHook - -// CallOptions contains the retry settings for each method of Client. -type CallOptions struct { - ListSecrets []gax.CallOption - CreateSecret []gax.CallOption - AddSecretVersion []gax.CallOption - GetSecret []gax.CallOption - UpdateSecret []gax.CallOption - DeleteSecret []gax.CallOption - ListSecretVersions []gax.CallOption - GetSecretVersion []gax.CallOption - AccessSecretVersion []gax.CallOption - DisableSecretVersion []gax.CallOption - EnableSecretVersion []gax.CallOption - DestroySecretVersion []gax.CallOption - SetIamPolicy []gax.CallOption - GetIamPolicy []gax.CallOption - TestIamPermissions []gax.CallOption -} - -func defaultClientOptions() []option.ClientOption { - return []option.ClientOption{ - internaloption.WithDefaultEndpoint("secretmanager.googleapis.com:443"), - internaloption.WithDefaultMTLSEndpoint("secretmanager.mtls.googleapis.com:443"), - internaloption.WithDefaultAudience("https://secretmanager.googleapis.com/"), - internaloption.WithDefaultScopes(DefaultAuthScopes()...), - option.WithGRPCDialOption(grpc.WithDisableServiceConfig()), - option.WithGRPCDialOption(grpc.WithDefaultCallOptions( - grpc.MaxCallRecvMsgSize(math.MaxInt32))), - } -} - -func defaultCallOptions() *CallOptions { - return &CallOptions{ - ListSecrets: []gax.CallOption{}, - CreateSecret: []gax.CallOption{}, - AddSecretVersion: []gax.CallOption{}, - GetSecret: []gax.CallOption{}, - UpdateSecret: []gax.CallOption{}, - DeleteSecret: []gax.CallOption{}, - ListSecretVersions: []gax.CallOption{}, - GetSecretVersion: []gax.CallOption{}, - AccessSecretVersion: []gax.CallOption{ - gax.WithRetry(func() gax.Retryer { - return gax.OnCodes([]codes.Code{ - codes.Unavailable, - codes.Unknown, - }, gax.Backoff{ - Initial: 1000 * time.Millisecond, - Max: 60000 * time.Millisecond, - Multiplier: 1.30, - }) - }), - }, - DisableSecretVersion: []gax.CallOption{}, - EnableSecretVersion: []gax.CallOption{}, - DestroySecretVersion: []gax.CallOption{}, - SetIamPolicy: []gax.CallOption{}, - GetIamPolicy: []gax.CallOption{}, - TestIamPermissions: []gax.CallOption{}, - } -} - -// Client is a client for interacting with Secret Manager API. -// -// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls. -type Client struct { - // Connection pool of gRPC connections to the service. - connPool gtransport.ConnPool - - // flag to opt out of default deadlines via GOOGLE_API_GO_EXPERIMENTAL_DISABLE_DEFAULT_DEADLINE - disableDeadlines bool - - // The gRPC API client. - client secretmanagerpb.SecretManagerServiceClient - - // The call options for this service. - CallOptions *CallOptions - - // The x-goog-* metadata to be sent with each request. - xGoogMetadata metadata.MD -} - -// NewClient creates a new secret manager service client. -// -// Secret Manager Service -// -// Manages secrets and operations using those secrets. Implements a REST -// model with the following objects: -// -// Secret -// -// SecretVersion -func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) { - clientOpts := defaultClientOptions() - - if newClientHook != nil { - hookOpts, err := newClientHook(ctx, clientHookParams{}) - if err != nil { - return nil, err - } - clientOpts = append(clientOpts, hookOpts...) - } - - disableDeadlines, err := checkDisableDeadlines() - if err != nil { - return nil, err - } - - connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...) - if err != nil { - return nil, err - } - c := &Client{ - connPool: connPool, - disableDeadlines: disableDeadlines, - CallOptions: defaultCallOptions(), - - client: secretmanagerpb.NewSecretManagerServiceClient(connPool), - } - c.setGoogleClientInfo() - - return c, nil -} - -// Connection returns a connection to the API service. -// -// Deprecated. -func (c *Client) Connection() *grpc.ClientConn { - return c.connPool.Conn() -} - -// Close closes the connection to the API service. The user should invoke this when -// the client is no longer required. -func (c *Client) Close() error { - return c.connPool.Close() -} - -// setGoogleClientInfo sets the name and version of the application in -// the `x-goog-api-client` header passed on each request. Intended for -// use by Google-written clients. -func (c *Client) setGoogleClientInfo(keyval ...string) { - kv := append([]string{"gl-go", versionGo()}, keyval...) - kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version) - c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...)) -} - -// ListSecrets lists Secrets. -func (c *Client) ListSecrets(ctx context.Context, req *secretmanagerpb.ListSecretsRequest, opts ...gax.CallOption) *SecretIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSecrets[0:len(c.CallOptions.ListSecrets):len(c.CallOptions.ListSecrets)], opts...) - it := &SecretIterator{} - req = proto.Clone(req).(*secretmanagerpb.ListSecretsRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*secretmanagerpb.Secret, string, error) { - var resp *secretmanagerpb.ListSecretsResponse - req.PageToken = pageToken - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.ListSecrets(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, "", err - } - - it.Response = resp - return resp.GetSecrets(), resp.GetNextPageToken(), nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) - if err != nil { - return "", err - } - it.items = append(it.items, items...) - return nextPageToken, nil - } - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - it.pageInfo.MaxSize = int(req.GetPageSize()) - it.pageInfo.Token = req.GetPageToken() - return it -} - -// CreateSecret creates a new Secret containing no SecretVersions. -func (c *Client) CreateSecret(ctx context.Context, req *secretmanagerpb.CreateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.CreateSecret[0:len(c.CallOptions.CreateSecret):len(c.CallOptions.CreateSecret)], opts...) - var resp *secretmanagerpb.Secret - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.CreateSecret(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// AddSecretVersion creates a new SecretVersion containing secret data and attaches -// it to an existing Secret. -func (c *Client) AddSecretVersion(ctx context.Context, req *secretmanagerpb.AddSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AddSecretVersion[0:len(c.CallOptions.AddSecretVersion):len(c.CallOptions.AddSecretVersion)], opts...) - var resp *secretmanagerpb.SecretVersion - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.AddSecretVersion(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// GetSecret gets metadata for a given Secret. -func (c *Client) GetSecret(ctx context.Context, req *secretmanagerpb.GetSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSecret[0:len(c.CallOptions.GetSecret):len(c.CallOptions.GetSecret)], opts...) - var resp *secretmanagerpb.Secret - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.GetSecret(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// UpdateSecret updates metadata of an existing Secret. -func (c *Client) UpdateSecret(ctx context.Context, req *secretmanagerpb.UpdateSecretRequest, opts ...gax.CallOption) (*secretmanagerpb.Secret, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "secret.name", url.QueryEscape(req.GetSecret().GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.UpdateSecret[0:len(c.CallOptions.UpdateSecret):len(c.CallOptions.UpdateSecret)], opts...) - var resp *secretmanagerpb.Secret - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.UpdateSecret(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// DeleteSecret deletes a Secret. -func (c *Client) DeleteSecret(ctx context.Context, req *secretmanagerpb.DeleteSecretRequest, opts ...gax.CallOption) error { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DeleteSecret[0:len(c.CallOptions.DeleteSecret):len(c.CallOptions.DeleteSecret)], opts...) - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - _, err = c.client.DeleteSecret(ctx, req, settings.GRPC...) - return err - }, opts...) - return err -} - -// ListSecretVersions lists SecretVersions. This call does not return secret -// data. -func (c *Client) ListSecretVersions(ctx context.Context, req *secretmanagerpb.ListSecretVersionsRequest, opts ...gax.CallOption) *SecretVersionIterator { - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.ListSecretVersions[0:len(c.CallOptions.ListSecretVersions):len(c.CallOptions.ListSecretVersions)], opts...) - it := &SecretVersionIterator{} - req = proto.Clone(req).(*secretmanagerpb.ListSecretVersionsRequest) - it.InternalFetch = func(pageSize int, pageToken string) ([]*secretmanagerpb.SecretVersion, string, error) { - var resp *secretmanagerpb.ListSecretVersionsResponse - req.PageToken = pageToken - if pageSize > math.MaxInt32 { - req.PageSize = math.MaxInt32 - } else { - req.PageSize = int32(pageSize) - } - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.ListSecretVersions(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, "", err - } - - it.Response = resp - return resp.GetVersions(), resp.GetNextPageToken(), nil - } - fetch := func(pageSize int, pageToken string) (string, error) { - items, nextPageToken, err := it.InternalFetch(pageSize, pageToken) - if err != nil { - return "", err - } - it.items = append(it.items, items...) - return nextPageToken, nil - } - it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf) - it.pageInfo.MaxSize = int(req.GetPageSize()) - it.pageInfo.Token = req.GetPageToken() - return it -} - -// GetSecretVersion gets metadata for a SecretVersion. -// -// projects/*/secrets/*/versions/latest is an alias to the latest -// SecretVersion. -func (c *Client) GetSecretVersion(ctx context.Context, req *secretmanagerpb.GetSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetSecretVersion[0:len(c.CallOptions.GetSecretVersion):len(c.CallOptions.GetSecretVersion)], opts...) - var resp *secretmanagerpb.SecretVersion - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.GetSecretVersion(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// AccessSecretVersion accesses a SecretVersion. This call returns the secret data. -// -// projects/*/secrets/*/versions/latest is an alias to the latest -// SecretVersion. -func (c *Client) AccessSecretVersion(ctx context.Context, req *secretmanagerpb.AccessSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.AccessSecretVersionResponse, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.AccessSecretVersion[0:len(c.CallOptions.AccessSecretVersion):len(c.CallOptions.AccessSecretVersion)], opts...) - var resp *secretmanagerpb.AccessSecretVersionResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.AccessSecretVersion(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// DisableSecretVersion disables a SecretVersion. -// -// Sets the state of the SecretVersion to -// DISABLED. -func (c *Client) DisableSecretVersion(ctx context.Context, req *secretmanagerpb.DisableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DisableSecretVersion[0:len(c.CallOptions.DisableSecretVersion):len(c.CallOptions.DisableSecretVersion)], opts...) - var resp *secretmanagerpb.SecretVersion - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.DisableSecretVersion(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// EnableSecretVersion enables a SecretVersion. -// -// Sets the state of the SecretVersion to -// ENABLED. -func (c *Client) EnableSecretVersion(ctx context.Context, req *secretmanagerpb.EnableSecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.EnableSecretVersion[0:len(c.CallOptions.EnableSecretVersion):len(c.CallOptions.EnableSecretVersion)], opts...) - var resp *secretmanagerpb.SecretVersion - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.EnableSecretVersion(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// DestroySecretVersion destroys a SecretVersion. -// -// Sets the state of the SecretVersion to -// DESTROYED and irrevocably destroys the -// secret data. -func (c *Client) DestroySecretVersion(ctx context.Context, req *secretmanagerpb.DestroySecretVersionRequest, opts ...gax.CallOption) (*secretmanagerpb.SecretVersion, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.DestroySecretVersion[0:len(c.CallOptions.DestroySecretVersion):len(c.CallOptions.DestroySecretVersion)], opts...) - var resp *secretmanagerpb.SecretVersion - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.DestroySecretVersion(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// SetIamPolicy sets the access control policy on the specified secret. Replaces any -// existing policy. -// -// Permissions on SecretVersions are enforced according -// to the policy set on the associated Secret. -func (c *Client) SetIamPolicy(ctx context.Context, req *iampb.SetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.SetIamPolicy[0:len(c.CallOptions.SetIamPolicy):len(c.CallOptions.SetIamPolicy)], opts...) - var resp *iampb.Policy - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.SetIamPolicy(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// GetIamPolicy gets the access control policy for a secret. -// Returns empty policy if the secret exists and does not have a policy set. -func (c *Client) GetIamPolicy(ctx context.Context, req *iampb.GetIamPolicyRequest, opts ...gax.CallOption) (*iampb.Policy, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.GetIamPolicy[0:len(c.CallOptions.GetIamPolicy):len(c.CallOptions.GetIamPolicy)], opts...) - var resp *iampb.Policy - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.GetIamPolicy(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// TestIamPermissions returns permissions that a caller has for the specified secret. -// If the secret does not exist, this call returns an empty set of -// permissions, not a NOT_FOUND error. -// -// Note: This operation is designed to be used for building permission-aware -// UIs and command-line tools, not for authorization checking. This operation -// may “fail open” without warning. -func (c *Client) TestIamPermissions(ctx context.Context, req *iampb.TestIamPermissionsRequest, opts ...gax.CallOption) (*iampb.TestIamPermissionsResponse, error) { - if _, ok := ctx.Deadline(); !ok && !c.disableDeadlines { - cctx, cancel := context.WithTimeout(ctx, 60000*time.Millisecond) - defer cancel() - ctx = cctx - } - md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "resource", url.QueryEscape(req.GetResource()))) - ctx = insertMetadata(ctx, c.xGoogMetadata, md) - opts = append(c.CallOptions.TestIamPermissions[0:len(c.CallOptions.TestIamPermissions):len(c.CallOptions.TestIamPermissions)], opts...) - var resp *iampb.TestIamPermissionsResponse - err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error { - var err error - resp, err = c.client.TestIamPermissions(ctx, req, settings.GRPC...) - return err - }, opts...) - if err != nil { - return nil, err - } - return resp, nil -} - -// SecretIterator manages a stream of *secretmanagerpb.Secret. -type SecretIterator struct { - items []*secretmanagerpb.Secret - pageInfo *iterator.PageInfo - nextFunc func() error - - // Response is the raw response for the current page. - // It must be cast to the RPC response type. - // Calling Next() or InternalFetch() updates this value. - Response interface{} - - // InternalFetch is for use by the Google Cloud Libraries only. - // It is not part of the stable interface of this package. - // - // InternalFetch returns results from a single call to the underlying RPC. - // The number of results is no greater than pageSize. - // If there are no more results, nextPageToken is empty and err is nil. - InternalFetch func(pageSize int, pageToken string) (results []*secretmanagerpb.Secret, nextPageToken string, err error) -} - -// PageInfo supports pagination. See the google.golang.org/api/iterator package for details. -func (it *SecretIterator) PageInfo() *iterator.PageInfo { - return it.pageInfo -} - -// Next returns the next result. Its second return value is iterator.Done if there are no more -// results. Once Next returns Done, all subsequent calls will return Done. -func (it *SecretIterator) Next() (*secretmanagerpb.Secret, error) { - var item *secretmanagerpb.Secret - if err := it.nextFunc(); err != nil { - return item, err - } - item = it.items[0] - it.items = it.items[1:] - return item, nil -} - -func (it *SecretIterator) bufLen() int { - return len(it.items) -} - -func (it *SecretIterator) takeBuf() interface{} { - b := it.items - it.items = nil - return b -} - -// SecretVersionIterator manages a stream of *secretmanagerpb.SecretVersion. -type SecretVersionIterator struct { - items []*secretmanagerpb.SecretVersion - pageInfo *iterator.PageInfo - nextFunc func() error - - // Response is the raw response for the current page. - // It must be cast to the RPC response type. - // Calling Next() or InternalFetch() updates this value. - Response interface{} - - // InternalFetch is for use by the Google Cloud Libraries only. - // It is not part of the stable interface of this package. - // - // InternalFetch returns results from a single call to the underlying RPC. - // The number of results is no greater than pageSize. - // If there are no more results, nextPageToken is empty and err is nil. - InternalFetch func(pageSize int, pageToken string) (results []*secretmanagerpb.SecretVersion, nextPageToken string, err error) -} - -// PageInfo supports pagination. See the google.golang.org/api/iterator package for details. -func (it *SecretVersionIterator) PageInfo() *iterator.PageInfo { - return it.pageInfo -} - -// Next returns the next result. Its second return value is iterator.Done if there are no more -// results. Once Next returns Done, all subsequent calls will return Done. -func (it *SecretVersionIterator) Next() (*secretmanagerpb.SecretVersion, error) { - var item *secretmanagerpb.SecretVersion - if err := it.nextFunc(); err != nil { - return item, err - } - item = it.items[0] - it.items = it.items[1:] - return item, nil -} - -func (it *SecretVersionIterator) bufLen() int { - return len(it.items) -} - -func (it *SecretVersionIterator) takeBuf() interface{} { - b := it.items - it.items = nil - return b -} diff --git a/vendor/filippo.io/age/.gitattributes b/vendor/filippo.io/age/.gitattributes deleted file mode 100644 index bb7ec5ec..00000000 --- a/vendor/filippo.io/age/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -*.age binary -testdata/testkit/* binary diff --git a/vendor/filippo.io/age/AUTHORS b/vendor/filippo.io/age/AUTHORS deleted file mode 100644 index 1fbcfc4c..00000000 --- a/vendor/filippo.io/age/AUTHORS +++ /dev/null @@ -1,6 +0,0 @@ -# This is the official list of age authors for copyright purposes. -# To be included, send a change adding the individual or company -# who owns a contribution's copyright. - -Google LLC -Filippo Valsorda diff --git a/vendor/filippo.io/age/LICENSE b/vendor/filippo.io/age/LICENSE deleted file mode 100644 index 3b50c989..00000000 --- a/vendor/filippo.io/age/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright 2019 The age Authors - -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 the age project 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/filippo.io/age/README.md b/vendor/filippo.io/age/README.md deleted file mode 100644 index d6302877..00000000 --- a/vendor/filippo.io/age/README.md +++ /dev/null @@ -1,251 +0,0 @@ -

The age logo, an wireframe of St. Peters dome in Rome, with the text: age, file encryption

- -[![Go Reference](https://pkg.go.dev/badge/filippo.io/age.svg)](https://pkg.go.dev/filippo.io/age) -[![man page]()](https://filippo.io/age/age.1) -[![C2SP specification](https://img.shields.io/badge/%C2%A7%23-specification-blueviolet)](https://age-encryption.org/v1) - -age is a simple, modern and secure file encryption tool, format, and Go library. - -It features small explicit keys, no config options, and UNIX-style composability. - -``` -$ age-keygen -o key.txt -Public key: age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p -$ tar cvz ~/data | age -r age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p > data.tar.gz.age -$ age --decrypt -i key.txt data.tar.gz.age > data.tar.gz -``` - -📜 The format specification is at [age-encryption.org/v1](https://age-encryption.org/v1). age was designed by [@Benjojo12](https://twitter.com/Benjojo12) and [@FiloSottile](https://twitter.com/FiloSottile). - -📬 Follow the maintenance of this project by subscribing to [Maintainer Dispatches](https://filippo.io/newsletter)! - -🦀 An alternative interoperable Rust implementation is available at [github.com/str4d/rage](https://github.com/str4d/rage). - -🔑 Hardware PIV tokens such as YubiKeys are supported through the [age-plugin-yubikey](https://github.com/str4d/age-plugin-yubikey) plugin. - -💬 The author pronounces it `[aɡe̞]`, like the Italian [“aghe”](https://translate.google.com/?sl=it&text=aghe). - -## Installation - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Homebrew (macOS or Linux) - brew install age -
MacPorts - port install age -
Alpine Linux v3.15+ - apk add age -
Arch Linux - pacman -S age -
Debian 11+ (Bullseye) - apt install age/bullseye-backports - (enable backports for age v1.0.0+) -
Fedora 33+ - dnf install age -
Gentoo Linux - emerge app-crypt/age -
NixOS / Nix - nix-env -i age -
openSUSE Tumbleweed - zypper install age -
Ubuntu 22.04+ - apt install age -
Void Linux - xbps-install age -
FreeBSD - pkg install age (security/age) -
OpenBSD 6.7+ - pkg_add age (security/age) -
Chocolatey (Windows) - choco install age.portable -
Scoop (Windows) - scoop bucket add extras; scoop install age -
- -On Windows, Linux, macOS, and FreeBSD you can use the pre-built binaries. - -``` -https://dl.filippo.io/age/latest?for=linux/amd64 -https://dl.filippo.io/age/v1.0.0-rc.1?for=darwin/arm64 -... -``` - -If your system has [a supported version of Go](https://go.dev/dl/), you can build from source. - -``` -go install filippo.io/age/cmd/...@latest -``` - -Help from new packagers is very welcome. - -## Usage - -For the full documentation, read [the age(1) man page](https://filippo.io/age/age.1). - -``` -Usage: - age [--encrypt] (-r RECIPIENT | -R PATH)... [--armor] [-o OUTPUT] [INPUT] - age [--encrypt] --passphrase [--armor] [-o OUTPUT] [INPUT] - age --decrypt [-i PATH]... [-o OUTPUT] [INPUT] - -Options: - -e, --encrypt Encrypt the input to the output. Default if omitted. - -d, --decrypt Decrypt the input to the output. - -o, --output OUTPUT Write the result to the file at path OUTPUT. - -a, --armor Encrypt to a PEM encoded format. - -p, --passphrase Encrypt with a passphrase. - -r, --recipient RECIPIENT Encrypt to the specified RECIPIENT. Can be repeated. - -R, --recipients-file PATH Encrypt to recipients listed at PATH. Can be repeated. - -i, --identity PATH Use the identity file at PATH. Can be repeated. - -INPUT defaults to standard input, and OUTPUT defaults to standard output. -If OUTPUT exists, it will be overwritten. - -RECIPIENT can be an age public key generated by age-keygen ("age1...") -or an SSH public key ("ssh-ed25519 AAAA...", "ssh-rsa AAAA..."). - -Recipient files contain one or more recipients, one per line. Empty lines -and lines starting with "#" are ignored as comments. "-" may be used to -read recipients from standard input. - -Identity files contain one or more secret keys ("AGE-SECRET-KEY-1..."), -one per line, or an SSH key. Empty lines and lines starting with "#" are -ignored as comments. Passphrase encrypted age files can be used as -identity files. Multiple key files can be provided, and any unused ones -will be ignored. "-" may be used to read identities from standard input. - -When --encrypt is specified explicitly, -i can also be used to encrypt to an -identity file symmetrically, instead or in addition to normal recipients. -``` - -### Multiple recipients - -Files can be encrypted to multiple recipients by repeating `-r/--recipient`. Every recipient will be able to decrypt the file. - -``` -$ age -o example.jpg.age -r age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p \ - -r age1lggyhqrw2nlhcxprm67z43rta597azn8gknawjehu9d9dl0jq3yqqvfafg example.jpg -``` - -#### Recipient files - -Multiple recipients can also be listed one per line in one or more files passed with the `-R/--recipients-file` flag. - -``` -$ cat recipients.txt -# Alice -age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p -# Bob -age1lggyhqrw2nlhcxprm67z43rta597azn8gknawjehu9d9dl0jq3yqqvfafg -$ age -R recipients.txt example.jpg > example.jpg.age -``` - -If the argument to `-R` (or `-i`) is `-`, the file is read from standard input. - -### Passphrases - -Files can be encrypted with a passphrase by using `-p/--passphrase`. By default age will automatically generate a secure passphrase. Passphrase protected files are automatically detected at decrypt time. - -``` -$ age -p secrets.txt > secrets.txt.age -Enter passphrase (leave empty to autogenerate a secure one): -Using the autogenerated passphrase "release-response-step-brand-wrap-ankle-pair-unusual-sword-train". -$ age -d secrets.txt.age > secrets.txt -Enter passphrase: -``` - -### Passphrase-protected key files - -If an identity file passed to `-i` is a passphrase encrypted age file, it will be automatically decrypted. - -``` -$ age-keygen | age -p > key.age -Public key: age1yhm4gctwfmrpz87tdslm550wrx6m79y9f2hdzt0lndjnehwj0ukqrjpyx5 -Enter passphrase (leave empty to autogenerate a secure one): -Using the autogenerated passphrase "hip-roast-boring-snake-mention-east-wasp-honey-input-actress". -$ age -r age1yhm4gctwfmrpz87tdslm550wrx6m79y9f2hdzt0lndjnehwj0ukqrjpyx5 secrets.txt > secrets.txt.age -$ age -d -i key.age secrets.txt.age > secrets.txt -Enter passphrase for identity file "key.age": -``` - -Passphrase-protected identity files are not necessary for most use cases, where access to the encrypted identity file implies access to the whole system. However, they can be useful if the identity file is stored remotely. - -### SSH keys - -As a convenience feature, age also supports encrypting to `ssh-rsa` and `ssh-ed25519` SSH public keys, and decrypting with the respective private key file. (`ssh-agent` is not supported.) - -``` -$ age -R ~/.ssh/id_ed25519.pub example.jpg > example.jpg.age -$ age -d -i ~/.ssh/id_ed25519 example.jpg.age > example.jpg -``` - -Note that SSH key support employs more complex cryptography, and embeds a public key tag in the encrypted file, making it possible to track files that are encrypted to a specific public key. - -#### Encrypting to a GitHub user - -Combining SSH key support and `-R`, you can easily encrypt a file to the SSH keys listed on a GitHub profile. - -``` -$ curl https://github.com/benjojo.keys | age -R - example.jpg > example.jpg.age -``` - -Keep in mind that people might not protect SSH keys long-term, since they are revokable when used only for authentication, and that SSH keys held on YubiKeys can't be used to decrypt files. diff --git a/vendor/filippo.io/age/age.go b/vendor/filippo.io/age/age.go deleted file mode 100644 index a0ef0bb7..00000000 --- a/vendor/filippo.io/age/age.go +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright 2019 The age 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 age implements file encryption according to the age-encryption.org/v1 -// specification. -// -// For most use cases, use the Encrypt and Decrypt functions with -// X25519Recipient and X25519Identity. If passphrase encryption is required, use -// ScryptRecipient and ScryptIdentity. For compatibility with existing SSH keys -// use the filippo.io/age/agessh package. -// -// age encrypted files are binary and not malleable. For encoding them as text, -// use the filippo.io/age/armor package. -// -// Key management -// -// age does not have a global keyring. Instead, since age keys are small, -// textual, and cheap, you are encouraged to generate dedicated keys for each -// task and application. -// -// Recipient public keys can be passed around as command line flags and in -// config files, while secret keys should be stored in dedicated files, through -// secret management systems, or as environment variables. -// -// There is no default path for age keys. Instead, they should be stored at -// application-specific paths. The CLI supports files where private keys are -// listed one per line, ignoring empty lines and lines starting with "#". These -// files can be parsed with ParseIdentities. -// -// When integrating age into a new system, it's recommended that you only -// support X25519 keys, and not SSH keys. The latter are supported for manual -// encryption operations. If you need to tie into existing key management -// infrastructure, you might want to consider implementing your own Recipient -// and Identity. -// -// Backwards compatibility -// -// Files encrypted with a stable version (not alpha, beta, or release candidate) -// of age, or with any v1.0.0 beta or release candidate, will decrypt with any -// later versions of the v1 API. This might change in v2, in which case v1 will -// be maintained with security fixes for compatibility with older files. -// -// If decrypting an older file poses a security risk, doing so might require an -// explicit opt-in in the API. -package age - -import ( - "crypto/hmac" - "crypto/rand" - "errors" - "fmt" - "io" - - "filippo.io/age/internal/format" - "filippo.io/age/internal/stream" -) - -// An Identity is passed to Decrypt to unwrap an opaque file key from a -// recipient stanza. It can be for example a secret key like X25519Identity, a -// plugin, or a custom implementation. -// -// Unwrap must return an error wrapping ErrIncorrectIdentity if none of the -// recipient stanzas match the identity, any other error will be considered -// fatal. -// -// Most age API users won't need to interact with this directly, and should -// instead pass Recipient implementations to Encrypt and Identity -// implementations to Decrypt. -type Identity interface { - Unwrap(stanzas []*Stanza) (fileKey []byte, err error) -} - -var ErrIncorrectIdentity = errors.New("incorrect identity for recipient block") - -// A Recipient is passed to Encrypt to wrap an opaque file key to one or more -// recipient stanza(s). It can be for example a public key like X25519Recipient, -// a plugin, or a custom implementation. -// -// Most age API users won't need to interact with this directly, and should -// instead pass Recipient implementations to Encrypt and Identity -// implementations to Decrypt. -type Recipient interface { - Wrap(fileKey []byte) ([]*Stanza, error) -} - -// A Stanza is a section of the age header that encapsulates the file key as -// encrypted to a specific recipient. -// -// Most age API users won't need to interact with this directly, and should -// instead pass Recipient implementations to Encrypt and Identity -// implementations to Decrypt. -type Stanza struct { - Type string - Args []string - Body []byte -} - -const fileKeySize = 16 -const streamNonceSize = 16 - -// Encrypt encrypts a file to one or more recipients. -// -// Writes to the returned WriteCloser are encrypted and written to dst as an age -// file. Every recipient will be able to decrypt the file. -// -// The caller must call Close on the WriteCloser when done for the last chunk to -// be encrypted and flushed to dst. -func Encrypt(dst io.Writer, recipients ...Recipient) (io.WriteCloser, error) { - if len(recipients) == 0 { - return nil, errors.New("no recipients specified") - } - - // As a best effort, prevent an API user from generating a file that the - // ScryptIdentity will refuse to decrypt. This check can't unfortunately be - // implemented as part of the Recipient interface, so it lives as a special - // case in Encrypt. - for _, r := range recipients { - if _, ok := r.(*ScryptRecipient); ok && len(recipients) != 1 { - return nil, errors.New("an ScryptRecipient must be the only one for the file") - } - } - - fileKey := make([]byte, fileKeySize) - if _, err := rand.Read(fileKey); err != nil { - return nil, err - } - - hdr := &format.Header{} - for i, r := range recipients { - stanzas, err := r.Wrap(fileKey) - if err != nil { - return nil, fmt.Errorf("failed to wrap key for recipient #%d: %v", i, err) - } - for _, s := range stanzas { - hdr.Recipients = append(hdr.Recipients, (*format.Stanza)(s)) - } - } - if mac, err := headerMAC(fileKey, hdr); err != nil { - return nil, fmt.Errorf("failed to compute header MAC: %v", err) - } else { - hdr.MAC = mac - } - if err := hdr.Marshal(dst); err != nil { - return nil, fmt.Errorf("failed to write header: %v", err) - } - - nonce := make([]byte, streamNonceSize) - if _, err := rand.Read(nonce); err != nil { - return nil, err - } - if _, err := dst.Write(nonce); err != nil { - return nil, fmt.Errorf("failed to write nonce: %v", err) - } - - return stream.NewWriter(streamKey(fileKey, nonce), dst) -} - -// NoIdentityMatchError is returned by Decrypt when none of the supplied -// identities match the encrypted file. -type NoIdentityMatchError struct { - // Errors is a slice of all the errors returned to Decrypt by the Unwrap - // calls it made. They all wrap ErrIncorrectIdentity. - Errors []error -} - -func (*NoIdentityMatchError) Error() string { - return "no identity matched any of the recipients" -} - -// Decrypt decrypts a file encrypted to one or more identities. -// -// It returns a Reader reading the decrypted plaintext of the age file read -// from src. All identities will be tried until one successfully decrypts the file. -func Decrypt(src io.Reader, identities ...Identity) (io.Reader, error) { - if len(identities) == 0 { - return nil, errors.New("no identities specified") - } - - hdr, payload, err := format.Parse(src) - if err != nil { - return nil, fmt.Errorf("failed to read header: %w", err) - } - - stanzas := make([]*Stanza, 0, len(hdr.Recipients)) - for _, s := range hdr.Recipients { - stanzas = append(stanzas, (*Stanza)(s)) - } - errNoMatch := &NoIdentityMatchError{} - var fileKey []byte - for _, id := range identities { - fileKey, err = id.Unwrap(stanzas) - if errors.Is(err, ErrIncorrectIdentity) { - errNoMatch.Errors = append(errNoMatch.Errors, err) - continue - } - if err != nil { - return nil, err - } - - break - } - if fileKey == nil { - return nil, errNoMatch - } - - if mac, err := headerMAC(fileKey, hdr); err != nil { - return nil, fmt.Errorf("failed to compute header MAC: %v", err) - } else if !hmac.Equal(mac, hdr.MAC) { - return nil, errors.New("bad header MAC") - } - - nonce := make([]byte, streamNonceSize) - if _, err := io.ReadFull(payload, nonce); err != nil { - return nil, fmt.Errorf("failed to read nonce: %w", err) - } - - return stream.NewReader(streamKey(fileKey, nonce), payload) -} - -// multiUnwrap is a helper that implements Identity.Unwrap in terms of a -// function that unwraps a single recipient stanza. -func multiUnwrap(unwrap func(*Stanza) ([]byte, error), stanzas []*Stanza) ([]byte, error) { - for _, s := range stanzas { - fileKey, err := unwrap(s) - if errors.Is(err, ErrIncorrectIdentity) { - // If we ever start returning something interesting wrapping - // ErrIncorrectIdentity, we should let it make its way up through - // Decrypt into NoIdentityMatchError.Errors. - continue - } - if err != nil { - return nil, err - } - return fileKey, nil - } - return nil, ErrIncorrectIdentity -} diff --git a/vendor/filippo.io/age/agessh/agessh.go b/vendor/filippo.io/age/agessh/agessh.go deleted file mode 100644 index ec2ccdda..00000000 --- a/vendor/filippo.io/age/agessh/agessh.go +++ /dev/null @@ -1,396 +0,0 @@ -// Copyright 2019 The age 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 agessh provides age.Identity and age.Recipient implementations of -// types "ssh-rsa" and "ssh-ed25519", which allow reusing existing SSH keys for -// encryption with age-encryption.org/v1. -// -// These recipient types should only be used for compatibility with existing -// keys, and native X25519 keys should be preferred otherwise. -// -// Note that these recipient types are not anonymous: the encrypted message will -// include a short 32-bit ID of the public key. -package agessh - -import ( - "crypto/ed25519" - "crypto/rand" - "crypto/rsa" - "crypto/sha256" - "crypto/sha512" - "errors" - "fmt" - "io" - - "filippo.io/age" - "filippo.io/age/internal/format" - "filippo.io/edwards25519" - "golang.org/x/crypto/chacha20poly1305" - "golang.org/x/crypto/curve25519" - "golang.org/x/crypto/hkdf" - "golang.org/x/crypto/ssh" -) - -func sshFingerprint(pk ssh.PublicKey) string { - h := sha256.Sum256(pk.Marshal()) - return format.EncodeToString(h[:4]) -} - -const oaepLabel = "age-encryption.org/v1/ssh-rsa" - -type RSARecipient struct { - sshKey ssh.PublicKey - pubKey *rsa.PublicKey -} - -var _ age.Recipient = &RSARecipient{} - -func NewRSARecipient(pk ssh.PublicKey) (*RSARecipient, error) { - if pk.Type() != "ssh-rsa" { - return nil, errors.New("SSH public key is not an RSA key") - } - r := &RSARecipient{ - sshKey: pk, - } - - if pk, ok := pk.(ssh.CryptoPublicKey); ok { - if pk, ok := pk.CryptoPublicKey().(*rsa.PublicKey); ok { - r.pubKey = pk - } else { - return nil, errors.New("unexpected public key type") - } - } else { - return nil, errors.New("pk does not implement ssh.CryptoPublicKey") - } - if r.pubKey.Size() < 2048/8 { - return nil, errors.New("RSA key size is too small") - } - return r, nil -} - -func (r *RSARecipient) Wrap(fileKey []byte) ([]*age.Stanza, error) { - l := &age.Stanza{ - Type: "ssh-rsa", - Args: []string{sshFingerprint(r.sshKey)}, - } - - wrappedKey, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, - r.pubKey, fileKey, []byte(oaepLabel)) - if err != nil { - return nil, err - } - l.Body = wrappedKey - - return []*age.Stanza{l}, nil -} - -type RSAIdentity struct { - k *rsa.PrivateKey - sshKey ssh.PublicKey -} - -var _ age.Identity = &RSAIdentity{} - -func NewRSAIdentity(key *rsa.PrivateKey) (*RSAIdentity, error) { - s, err := ssh.NewSignerFromKey(key) - if err != nil { - return nil, err - } - i := &RSAIdentity{ - k: key, sshKey: s.PublicKey(), - } - return i, nil -} - -func (i *RSAIdentity) Recipient() *RSARecipient { - return &RSARecipient{ - sshKey: i.sshKey, - pubKey: &i.k.PublicKey, - } -} - -func (i *RSAIdentity) Unwrap(stanzas []*age.Stanza) ([]byte, error) { - return multiUnwrap(i.unwrap, stanzas) -} - -func (i *RSAIdentity) unwrap(block *age.Stanza) ([]byte, error) { - if block.Type != "ssh-rsa" { - return nil, age.ErrIncorrectIdentity - } - if len(block.Args) != 1 { - return nil, errors.New("invalid ssh-rsa recipient block") - } - - if block.Args[0] != sshFingerprint(i.sshKey) { - return nil, age.ErrIncorrectIdentity - } - - fileKey, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, i.k, - block.Body, []byte(oaepLabel)) - if err != nil { - return nil, fmt.Errorf("failed to decrypt file key: %v", err) - } - return fileKey, nil -} - -type Ed25519Recipient struct { - sshKey ssh.PublicKey - theirPublicKey []byte -} - -var _ age.Recipient = &Ed25519Recipient{} - -func NewEd25519Recipient(pk ssh.PublicKey) (*Ed25519Recipient, error) { - if pk.Type() != "ssh-ed25519" { - return nil, errors.New("SSH public key is not an Ed25519 key") - } - - cpk, ok := pk.(ssh.CryptoPublicKey) - if !ok { - return nil, errors.New("pk does not implement ssh.CryptoPublicKey") - } - epk, ok := cpk.CryptoPublicKey().(ed25519.PublicKey) - if !ok { - return nil, errors.New("unexpected public key type") - } - mpk, err := ed25519PublicKeyToCurve25519(epk) - if err != nil { - return nil, fmt.Errorf("invalid Ed25519 public key: %v", err) - } - - return &Ed25519Recipient{ - sshKey: pk, - theirPublicKey: mpk, - }, nil -} - -func ParseRecipient(s string) (age.Recipient, error) { - pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(s)) - if err != nil { - return nil, fmt.Errorf("malformed SSH recipient: %q: %v", s, err) - } - - var r age.Recipient - switch t := pubKey.Type(); t { - case "ssh-rsa": - r, err = NewRSARecipient(pubKey) - case "ssh-ed25519": - r, err = NewEd25519Recipient(pubKey) - default: - return nil, fmt.Errorf("unknown SSH recipient type: %q", t) - } - if err != nil { - return nil, fmt.Errorf("malformed SSH recipient: %q: %v", s, err) - } - - return r, nil -} - -func ed25519PublicKeyToCurve25519(pk ed25519.PublicKey) ([]byte, error) { - // See https://blog.filippo.io/using-ed25519-keys-for-encryption and - // https://pkg.go.dev/filippo.io/edwards25519#Point.BytesMontgomery. - p, err := new(edwards25519.Point).SetBytes(pk) - if err != nil { - return nil, err - } - return p.BytesMontgomery(), nil -} - -const ed25519Label = "age-encryption.org/v1/ssh-ed25519" - -func (r *Ed25519Recipient) Wrap(fileKey []byte) ([]*age.Stanza, error) { - ephemeral := make([]byte, curve25519.ScalarSize) - if _, err := rand.Read(ephemeral); err != nil { - return nil, err - } - ourPublicKey, err := curve25519.X25519(ephemeral, curve25519.Basepoint) - if err != nil { - return nil, err - } - - sharedSecret, err := curve25519.X25519(ephemeral, r.theirPublicKey) - if err != nil { - return nil, err - } - - tweak := make([]byte, curve25519.ScalarSize) - tH := hkdf.New(sha256.New, nil, r.sshKey.Marshal(), []byte(ed25519Label)) - if _, err := io.ReadFull(tH, tweak); err != nil { - return nil, err - } - sharedSecret, _ = curve25519.X25519(tweak, sharedSecret) - - l := &age.Stanza{ - Type: "ssh-ed25519", - Args: []string{sshFingerprint(r.sshKey), - format.EncodeToString(ourPublicKey[:])}, - } - - salt := make([]byte, 0, len(ourPublicKey)+len(r.theirPublicKey)) - salt = append(salt, ourPublicKey...) - salt = append(salt, r.theirPublicKey...) - h := hkdf.New(sha256.New, sharedSecret, salt, []byte(ed25519Label)) - wrappingKey := make([]byte, chacha20poly1305.KeySize) - if _, err := io.ReadFull(h, wrappingKey); err != nil { - return nil, err - } - - wrappedKey, err := aeadEncrypt(wrappingKey, fileKey) - if err != nil { - return nil, err - } - l.Body = wrappedKey - - return []*age.Stanza{l}, nil -} - -type Ed25519Identity struct { - secretKey, ourPublicKey []byte - sshKey ssh.PublicKey -} - -var _ age.Identity = &Ed25519Identity{} - -func NewEd25519Identity(key ed25519.PrivateKey) (*Ed25519Identity, error) { - s, err := ssh.NewSignerFromKey(key) - if err != nil { - return nil, err - } - i := &Ed25519Identity{ - sshKey: s.PublicKey(), - secretKey: ed25519PrivateKeyToCurve25519(key), - } - i.ourPublicKey, _ = curve25519.X25519(i.secretKey, curve25519.Basepoint) - return i, nil -} - -func ParseIdentity(pemBytes []byte) (age.Identity, error) { - k, err := ssh.ParseRawPrivateKey(pemBytes) - if err != nil { - return nil, err - } - - switch k := k.(type) { - case *ed25519.PrivateKey: - return NewEd25519Identity(*k) - // ParseRawPrivateKey returns inconsistent types. See Issue 429. - case ed25519.PrivateKey: - return NewEd25519Identity(k) - case *rsa.PrivateKey: - return NewRSAIdentity(k) - } - - return nil, fmt.Errorf("unsupported SSH identity type: %T", k) -} - -func ed25519PrivateKeyToCurve25519(pk ed25519.PrivateKey) []byte { - h := sha512.New() - h.Write(pk.Seed()) - out := h.Sum(nil) - return out[:curve25519.ScalarSize] -} - -func (i *Ed25519Identity) Recipient() *Ed25519Recipient { - return &Ed25519Recipient{ - sshKey: i.sshKey, - theirPublicKey: i.ourPublicKey, - } -} - -func (i *Ed25519Identity) Unwrap(stanzas []*age.Stanza) ([]byte, error) { - return multiUnwrap(i.unwrap, stanzas) -} - -func (i *Ed25519Identity) unwrap(block *age.Stanza) ([]byte, error) { - if block.Type != "ssh-ed25519" { - return nil, age.ErrIncorrectIdentity - } - if len(block.Args) != 2 { - return nil, errors.New("invalid ssh-ed25519 recipient block") - } - publicKey, err := format.DecodeString(block.Args[1]) - if err != nil { - return nil, fmt.Errorf("failed to parse ssh-ed25519 recipient: %v", err) - } - if len(publicKey) != curve25519.PointSize { - return nil, errors.New("invalid ssh-ed25519 recipient block") - } - - if block.Args[0] != sshFingerprint(i.sshKey) { - return nil, age.ErrIncorrectIdentity - } - - sharedSecret, err := curve25519.X25519(i.secretKey, publicKey) - if err != nil { - return nil, fmt.Errorf("invalid X25519 recipient: %v", err) - } - - tweak := make([]byte, curve25519.ScalarSize) - tH := hkdf.New(sha256.New, nil, i.sshKey.Marshal(), []byte(ed25519Label)) - if _, err := io.ReadFull(tH, tweak); err != nil { - return nil, err - } - sharedSecret, _ = curve25519.X25519(tweak, sharedSecret) - - salt := make([]byte, 0, len(publicKey)+len(i.ourPublicKey)) - salt = append(salt, publicKey...) - salt = append(salt, i.ourPublicKey...) - h := hkdf.New(sha256.New, sharedSecret, salt, []byte(ed25519Label)) - wrappingKey := make([]byte, chacha20poly1305.KeySize) - if _, err := io.ReadFull(h, wrappingKey); err != nil { - return nil, err - } - - fileKey, err := aeadDecrypt(wrappingKey, block.Body) - if err != nil { - return nil, fmt.Errorf("failed to decrypt file key: %v", err) - } - return fileKey, nil -} - -// multiUnwrap is copied from package age. It's a helper that implements -// Identity.Unwrap in terms of a function that unwraps a single recipient -// stanza. -func multiUnwrap(unwrap func(*age.Stanza) ([]byte, error), stanzas []*age.Stanza) ([]byte, error) { - for _, s := range stanzas { - fileKey, err := unwrap(s) - if errors.Is(err, age.ErrIncorrectIdentity) { - // If we ever start returning something interesting wrapping - // ErrIncorrectIdentity, we should let it make its way up through - // Decrypt into NoIdentityMatchError.Errors. - continue - } - if err != nil { - return nil, err - } - return fileKey, nil - } - return nil, age.ErrIncorrectIdentity -} - -// aeadEncrypt and aeadDecrypt are copied from package age. -// -// They don't limit the file key size because multi-key attacks are irrelevant -// against the ssh-ed25519 recipient. Being an asymmetric recipient, it would -// only allow a more efficient search for accepted public keys against a -// decryption oracle, but the ssh-X recipients are not anonymous (they have a -// short recipient hash). - -func aeadEncrypt(key, plaintext []byte) ([]byte, error) { - aead, err := chacha20poly1305.New(key) - if err != nil { - return nil, err - } - nonce := make([]byte, chacha20poly1305.NonceSize) - return aead.Seal(nil, nonce, plaintext, nil), nil -} - -func aeadDecrypt(key, ciphertext []byte) ([]byte, error) { - aead, err := chacha20poly1305.New(key) - if err != nil { - return nil, err - } - nonce := make([]byte, chacha20poly1305.NonceSize) - return aead.Open(nil, nonce, ciphertext, nil) -} diff --git a/vendor/filippo.io/age/agessh/encrypted_keys.go b/vendor/filippo.io/age/agessh/encrypted_keys.go deleted file mode 100644 index 9414bcf4..00000000 --- a/vendor/filippo.io/age/agessh/encrypted_keys.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2019 The age 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 agessh - -import ( - "crypto" - "crypto/ed25519" - "crypto/rsa" - "fmt" - - "filippo.io/age" - "golang.org/x/crypto/ssh" -) - -// EncryptedSSHIdentity is an age.Identity implementation based on a passphrase -// encrypted SSH private key. -// -// It requests the passphrase only if the public key matches a recipient stanza. -// If the application knows it will always have to decrypt the private key, it -// would be simpler to use ssh.ParseRawPrivateKeyWithPassphrase directly and -// pass the result to NewEd25519Identity or NewRSAIdentity. -type EncryptedSSHIdentity struct { - pubKey ssh.PublicKey - recipient age.Recipient - pemBytes []byte - passphrase func() ([]byte, error) - - decrypted age.Identity -} - -// NewEncryptedSSHIdentity returns a new EncryptedSSHIdentity. -// -// pubKey must be the public key associated with the encrypted private key, and -// it must have type "ssh-ed25519" or "ssh-rsa". For OpenSSH encrypted files it -// can be extracted from an ssh.PassphraseMissingError, otherwise it can often -// be found in ".pub" files. -// -// pemBytes must be a valid input to ssh.ParseRawPrivateKeyWithPassphrase. -// passphrase is a callback that will be invoked by Unwrap when the passphrase -// is necessary. -func NewEncryptedSSHIdentity(pubKey ssh.PublicKey, pemBytes []byte, passphrase func() ([]byte, error)) (*EncryptedSSHIdentity, error) { - i := &EncryptedSSHIdentity{ - pubKey: pubKey, - pemBytes: pemBytes, - passphrase: passphrase, - } - switch t := pubKey.Type(); t { - case "ssh-ed25519": - r, err := NewEd25519Recipient(pubKey) - if err != nil { - return nil, err - } - i.recipient = r - case "ssh-rsa": - r, err := NewRSARecipient(pubKey) - if err != nil { - return nil, err - } - i.recipient = r - default: - return nil, fmt.Errorf("unsupported SSH key type: %v", t) - } - return i, nil -} - -var _ age.Identity = &EncryptedSSHIdentity{} - -func (i *EncryptedSSHIdentity) Recipient() age.Recipient { - return i.recipient -} - -// Unwrap implements age.Identity. If the private key is still encrypted, and -// any of the stanzas match the public key, it will request the passphrase. The -// decrypted private key will be cached after the first successful invocation. -func (i *EncryptedSSHIdentity) Unwrap(stanzas []*age.Stanza) (fileKey []byte, err error) { - if i.decrypted != nil { - return i.decrypted.Unwrap(stanzas) - } - - var match bool - for _, s := range stanzas { - if s.Type != i.pubKey.Type() { - continue - } - if len(s.Args) < 1 { - return nil, fmt.Errorf("invalid %v recipient block", i.pubKey.Type()) - } - if s.Args[0] != sshFingerprint(i.pubKey) { - continue - } - match = true - break - } - if !match { - return nil, age.ErrIncorrectIdentity - } - - passphrase, err := i.passphrase() - if err != nil { - return nil, fmt.Errorf("failed to obtain passphrase: %v", err) - } - k, err := ssh.ParseRawPrivateKeyWithPassphrase(i.pemBytes, passphrase) - if err != nil { - return nil, fmt.Errorf("failed to decrypt SSH key file: %v", err) - } - - var pubKey interface { - Equal(x crypto.PublicKey) bool - } - switch k := k.(type) { - case *ed25519.PrivateKey: - i.decrypted, err = NewEd25519Identity(*k) - pubKey = k.Public().(ed25519.PublicKey) - // ParseRawPrivateKey returns inconsistent types. See Issue 429. - case ed25519.PrivateKey: - i.decrypted, err = NewEd25519Identity(k) - pubKey = k.Public().(ed25519.PublicKey) - case *rsa.PrivateKey: - i.decrypted, err = NewRSAIdentity(k) - pubKey = &k.PublicKey - default: - return nil, fmt.Errorf("unexpected SSH key type: %T", k) - } - if err != nil { - return nil, fmt.Errorf("invalid SSH key: %v", err) - } - - if exp := i.pubKey.(ssh.CryptoPublicKey).CryptoPublicKey(); !pubKey.Equal(exp) { - return nil, fmt.Errorf("mismatched private and public SSH key") - } - - return i.decrypted.Unwrap(stanzas) -} diff --git a/vendor/filippo.io/age/internal/bech32/bech32.go b/vendor/filippo.io/age/internal/bech32/bech32.go deleted file mode 100644 index 6f8a48cd..00000000 --- a/vendor/filippo.io/age/internal/bech32/bech32.go +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) 2017 Takatoshi Nakagawa -// Copyright (c) 2019 The age Authors -// -// 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. - -// Package bech32 is a modified version of the reference implementation of BIP173. -package bech32 - -import ( - "fmt" - "strings" -) - -var charset = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" - -var generator = []uint32{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3} - -func polymod(values []byte) uint32 { - chk := uint32(1) - for _, v := range values { - top := chk >> 25 - chk = (chk & 0x1ffffff) << 5 - chk = chk ^ uint32(v) - for i := 0; i < 5; i++ { - bit := top >> i & 1 - if bit == 1 { - chk ^= generator[i] - } - } - } - return chk -} - -func hrpExpand(hrp string) []byte { - h := []byte(strings.ToLower(hrp)) - var ret []byte - for _, c := range h { - ret = append(ret, c>>5) - } - ret = append(ret, 0) - for _, c := range h { - ret = append(ret, c&31) - } - return ret -} - -func verifyChecksum(hrp string, data []byte) bool { - return polymod(append(hrpExpand(hrp), data...)) == 1 -} - -func createChecksum(hrp string, data []byte) []byte { - values := append(hrpExpand(hrp), data...) - values = append(values, []byte{0, 0, 0, 0, 0, 0}...) - mod := polymod(values) ^ 1 - ret := make([]byte, 6) - for p := range ret { - shift := 5 * (5 - p) - ret[p] = byte(mod>>shift) & 31 - } - return ret -} - -func convertBits(data []byte, frombits, tobits byte, pad bool) ([]byte, error) { - var ret []byte - acc := uint32(0) - bits := byte(0) - maxv := byte(1<>frombits != 0 { - return nil, fmt.Errorf("invalid data range: data[%d]=%d (frombits=%d)", idx, value, frombits) - } - acc = acc<= tobits { - bits -= tobits - ret = append(ret, byte(acc>>bits)&maxv) - } - } - if pad { - if bits > 0 { - ret = append(ret, byte(acc<<(tobits-bits))&maxv) - } - } else if bits >= frombits { - return nil, fmt.Errorf("illegal zero padding") - } else if byte(acc<<(tobits-bits))&maxv != 0 { - return nil, fmt.Errorf("non-zero padding") - } - return ret, nil -} - -// Encode encodes the HRP and a bytes slice to Bech32. If the HRP is uppercase, -// the output will be uppercase. -func Encode(hrp string, data []byte) (string, error) { - values, err := convertBits(data, 8, 5, true) - if err != nil { - return "", err - } - if len(hrp) < 1 { - return "", fmt.Errorf("invalid HRP: %q", hrp) - } - for p, c := range hrp { - if c < 33 || c > 126 { - return "", fmt.Errorf("invalid HRP character: hrp[%d]=%d", p, c) - } - } - if strings.ToUpper(hrp) != hrp && strings.ToLower(hrp) != hrp { - return "", fmt.Errorf("mixed case HRP: %q", hrp) - } - lower := strings.ToLower(hrp) == hrp - hrp = strings.ToLower(hrp) - var ret strings.Builder - ret.WriteString(hrp) - ret.WriteString("1") - for _, p := range values { - ret.WriteByte(charset[p]) - } - for _, p := range createChecksum(hrp, values) { - ret.WriteByte(charset[p]) - } - if lower { - return ret.String(), nil - } - return strings.ToUpper(ret.String()), nil -} - -// Decode decodes a Bech32 string. If the string is uppercase, the HRP will be uppercase. -func Decode(s string) (hrp string, data []byte, err error) { - if strings.ToLower(s) != s && strings.ToUpper(s) != s { - return "", nil, fmt.Errorf("mixed case") - } - pos := strings.LastIndex(s, "1") - if pos < 1 || pos+7 > len(s) { - return "", nil, fmt.Errorf("separator '1' at invalid position: pos=%d, len=%d", pos, len(s)) - } - hrp = s[:pos] - for p, c := range hrp { - if c < 33 || c > 126 { - return "", nil, fmt.Errorf("invalid character human-readable part: s[%d]=%d", p, c) - } - } - s = strings.ToLower(s) - for p, c := range s[pos+1:] { - d := strings.IndexRune(charset, c) - if d == -1 { - return "", nil, fmt.Errorf("invalid character data part: s[%d]=%v", p, c) - } - data = append(data, byte(d)) - } - if !verifyChecksum(hrp, data) { - return "", nil, fmt.Errorf("invalid checksum") - } - data, err = convertBits(data[:len(data)-6], 5, 8, false) - if err != nil { - return "", nil, err - } - return hrp, data, nil -} diff --git a/vendor/filippo.io/age/internal/format/format.go b/vendor/filippo.io/age/internal/format/format.go deleted file mode 100644 index aa77b756..00000000 --- a/vendor/filippo.io/age/internal/format/format.go +++ /dev/null @@ -1,311 +0,0 @@ -// Copyright 2019 The age 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 format implements the age file format. -package format - -import ( - "bufio" - "bytes" - "encoding/base64" - "errors" - "fmt" - "io" - "strings" -) - -type Header struct { - Recipients []*Stanza - MAC []byte -} - -// Stanza is assignable to age.Stanza, and if this package is made public, -// age.Stanza can be made a type alias of this type. -type Stanza struct { - Type string - Args []string - Body []byte -} - -var b64 = base64.RawStdEncoding.Strict() - -func DecodeString(s string) ([]byte, error) { - // CR and LF are ignored by DecodeString, but we don't want any malleability. - if strings.ContainsAny(s, "\n\r") { - return nil, errors.New(`unexpected newline character`) - } - return b64.DecodeString(s) -} - -var EncodeToString = b64.EncodeToString - -const ColumnsPerLine = 64 - -const BytesPerLine = ColumnsPerLine / 4 * 3 - -// NewWrappedBase64Encoder returns a WrappedBase64Encoder that writes to dst. -func NewWrappedBase64Encoder(enc *base64.Encoding, dst io.Writer) *WrappedBase64Encoder { - w := &WrappedBase64Encoder{dst: dst} - w.enc = base64.NewEncoder(enc, WriterFunc(w.writeWrapped)) - return w -} - -type WriterFunc func(p []byte) (int, error) - -func (f WriterFunc) Write(p []byte) (int, error) { return f(p) } - -// WrappedBase64Encoder is a standard base64 encoder that inserts an LF -// character every ColumnsPerLine bytes. It does not insert a newline neither at -// the beginning nor at the end of the stream, but it ensures the last line is -// shorter than ColumnsPerLine, which means it might be empty. -type WrappedBase64Encoder struct { - enc io.WriteCloser - dst io.Writer - written int - buf bytes.Buffer -} - -func (w *WrappedBase64Encoder) Write(p []byte) (int, error) { return w.enc.Write(p) } - -func (w *WrappedBase64Encoder) Close() error { - return w.enc.Close() -} - -func (w *WrappedBase64Encoder) writeWrapped(p []byte) (int, error) { - if w.buf.Len() != 0 { - panic("age: internal error: non-empty WrappedBase64Encoder.buf") - } - for len(p) > 0 { - toWrite := ColumnsPerLine - (w.written % ColumnsPerLine) - if toWrite > len(p) { - toWrite = len(p) - } - n, _ := w.buf.Write(p[:toWrite]) - w.written += n - p = p[n:] - if w.written%ColumnsPerLine == 0 { - w.buf.Write([]byte("\n")) - } - } - if _, err := w.buf.WriteTo(w.dst); err != nil { - // We always return n = 0 on error because it's hard to work back to the - // input length that ended up written out. Not ideal, but Write errors - // are not recoverable anyway. - return 0, err - } - return len(p), nil -} - -// LastLineIsEmpty returns whether the last output line was empty, either -// because no input was written, or because a multiple of BytesPerLine was. -// -// Calling LastLineIsEmpty before Close is meaningless. -func (w *WrappedBase64Encoder) LastLineIsEmpty() bool { - return w.written%ColumnsPerLine == 0 -} - -const intro = "age-encryption.org/v1\n" - -var stanzaPrefix = []byte("->") -var footerPrefix = []byte("---") - -func (r *Stanza) Marshal(w io.Writer) error { - if _, err := w.Write(stanzaPrefix); err != nil { - return err - } - for _, a := range append([]string{r.Type}, r.Args...) { - if _, err := io.WriteString(w, " "+a); err != nil { - return err - } - } - if _, err := io.WriteString(w, "\n"); err != nil { - return err - } - ww := NewWrappedBase64Encoder(b64, w) - if _, err := ww.Write(r.Body); err != nil { - return err - } - if err := ww.Close(); err != nil { - return err - } - _, err := io.WriteString(w, "\n") - return err -} - -func (h *Header) MarshalWithoutMAC(w io.Writer) error { - if _, err := io.WriteString(w, intro); err != nil { - return err - } - for _, r := range h.Recipients { - if err := r.Marshal(w); err != nil { - return err - } - } - _, err := fmt.Fprintf(w, "%s", footerPrefix) - return err -} - -func (h *Header) Marshal(w io.Writer) error { - if err := h.MarshalWithoutMAC(w); err != nil { - return err - } - mac := b64.EncodeToString(h.MAC) - _, err := fmt.Fprintf(w, " %s\n", mac) - return err -} - -type StanzaReader struct { - r *bufio.Reader - err error -} - -func NewStanzaReader(r *bufio.Reader) *StanzaReader { - return &StanzaReader{r: r} -} - -func (r *StanzaReader) ReadStanza() (s *Stanza, err error) { - // Read errors are unrecoverable. - if r.err != nil { - return nil, r.err - } - defer func() { r.err = err }() - - s = &Stanza{} - - line, err := r.r.ReadBytes('\n') - if err != nil { - return nil, fmt.Errorf("failed to read line: %w", err) - } - if !bytes.HasPrefix(line, stanzaPrefix) { - return nil, fmt.Errorf("malformed stanza opening line: %q", line) - } - prefix, args := splitArgs(line) - if prefix != string(stanzaPrefix) || len(args) < 1 { - return nil, fmt.Errorf("malformed stanza: %q", line) - } - for _, a := range args { - if !isValidString(a) { - return nil, fmt.Errorf("malformed stanza: %q", line) - } - } - s.Type = args[0] - s.Args = args[1:] - - for { - line, err := r.r.ReadBytes('\n') - if err != nil { - return nil, fmt.Errorf("failed to read line: %w", err) - } - - b, err := DecodeString(strings.TrimSuffix(string(line), "\n")) - if err != nil { - if bytes.HasPrefix(line, footerPrefix) || bytes.HasPrefix(line, stanzaPrefix) { - return nil, fmt.Errorf("malformed body line %q: stanza ended without a short line\nNote: this might be a file encrypted with an old beta version of age or rage. Use age v1.0.0-beta6 or rage to decrypt it.", line) - } - return nil, errorf("malformed body line %q: %v", line, err) - } - if len(b) > BytesPerLine { - return nil, errorf("malformed body line %q: too long", line) - } - s.Body = append(s.Body, b...) - if len(b) < BytesPerLine { - // A stanza body always ends with a short line. - return s, nil - } - } -} - -type ParseError struct { - err error -} - -func (e *ParseError) Error() string { - return "parsing age header: " + e.err.Error() -} - -func (e *ParseError) Unwrap() error { - return e.err -} - -func errorf(format string, a ...interface{}) error { - return &ParseError{fmt.Errorf(format, a...)} -} - -// Parse returns the header and a Reader that begins at the start of the -// payload. -func Parse(input io.Reader) (*Header, io.Reader, error) { - h := &Header{} - rr := bufio.NewReader(input) - - line, err := rr.ReadString('\n') - if err != nil { - return nil, nil, errorf("failed to read intro: %w", err) - } - if line != intro { - return nil, nil, errorf("unexpected intro: %q", line) - } - - sr := NewStanzaReader(rr) - for { - peek, err := rr.Peek(len(footerPrefix)) - if err != nil { - return nil, nil, errorf("failed to read header: %w", err) - } - - if bytes.Equal(peek, footerPrefix) { - line, err := rr.ReadBytes('\n') - if err != nil { - return nil, nil, fmt.Errorf("failed to read header: %w", err) - } - - prefix, args := splitArgs(line) - if prefix != string(footerPrefix) || len(args) != 1 { - return nil, nil, errorf("malformed closing line: %q", line) - } - h.MAC, err = DecodeString(args[0]) - if err != nil || len(h.MAC) != 32 { - return nil, nil, errorf("malformed closing line %q: %v", line, err) - } - break - } - - s, err := sr.ReadStanza() - if err != nil { - return nil, nil, fmt.Errorf("failed to parse header: %w", err) - } - h.Recipients = append(h.Recipients, s) - } - - // If input is a bufio.Reader, rr might be equal to input because - // bufio.NewReader short-circuits. In this case we can just return it (and - // we would end up reading the buffer twice if we prepended the peek below). - if rr == input { - return h, rr, nil - } - // Otherwise, unwind the bufio overread and return the unbuffered input. - buf, err := rr.Peek(rr.Buffered()) - if err != nil { - return nil, nil, errorf("internal error: %v", err) - } - payload := io.MultiReader(bytes.NewReader(buf), input) - return h, payload, nil -} - -func splitArgs(line []byte) (string, []string) { - l := strings.TrimSuffix(string(line), "\n") - parts := strings.Split(l, " ") - return parts[0], parts[1:] -} - -func isValidString(s string) bool { - if len(s) == 0 { - return false - } - for _, c := range s { - if c < 33 || c > 126 { - return false - } - } - return true -} diff --git a/vendor/filippo.io/age/internal/stream/stream.go b/vendor/filippo.io/age/internal/stream/stream.go deleted file mode 100644 index 7cf02c47..00000000 --- a/vendor/filippo.io/age/internal/stream/stream.go +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright 2019 The age 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 stream implements a variant of the STREAM chunked encryption scheme. -package stream - -import ( - "crypto/cipher" - "errors" - "fmt" - "io" - - "golang.org/x/crypto/chacha20poly1305" - "golang.org/x/crypto/poly1305" -) - -const ChunkSize = 64 * 1024 - -type Reader struct { - a cipher.AEAD - src io.Reader - - unread []byte // decrypted but unread data, backed by buf - buf [encChunkSize]byte - - err error - nonce [chacha20poly1305.NonceSize]byte -} - -const ( - encChunkSize = ChunkSize + poly1305.TagSize - lastChunkFlag = 0x01 -) - -func NewReader(key []byte, src io.Reader) (*Reader, error) { - aead, err := chacha20poly1305.New(key) - if err != nil { - return nil, err - } - return &Reader{ - a: aead, - src: src, - }, nil -} - -func (r *Reader) Read(p []byte) (int, error) { - if len(r.unread) > 0 { - n := copy(p, r.unread) - r.unread = r.unread[n:] - return n, nil - } - if r.err != nil { - return 0, r.err - } - if len(p) == 0 { - return 0, nil - } - - last, err := r.readChunk() - if err != nil { - r.err = err - return 0, err - } - - n := copy(p, r.unread) - r.unread = r.unread[n:] - - if last { - // Ensure there is an EOF after the last chunk as expected. In other - // words, check for trailing data after a full-length final chunk. - // Hopefully, the underlying reader supports returning EOF even if it - // had previously returned an EOF to ReadFull. - if _, err := r.src.Read(make([]byte, 1)); err == nil { - r.err = errors.New("trailing data after end of encrypted file") - } else if err != io.EOF { - r.err = fmt.Errorf("non-EOF error reading after end of encrypted file: %w", err) - } else { - r.err = io.EOF - } - } - - return n, nil -} - -// readChunk reads the next chunk of ciphertext from r.src and makes it available -// in r.unread. last is true if the chunk was marked as the end of the message. -// readChunk must not be called again after returning a last chunk or an error. -func (r *Reader) readChunk() (last bool, err error) { - if len(r.unread) != 0 { - panic("stream: internal error: readChunk called with dirty buffer") - } - - in := r.buf[:] - n, err := io.ReadFull(r.src, in) - switch { - case err == io.EOF: - // A message can't end without a marked chunk. This message is truncated. - return false, io.ErrUnexpectedEOF - case err == io.ErrUnexpectedEOF: - // The last chunk can be short, but not empty unless it's the first and - // only chunk. - if !nonceIsZero(&r.nonce) && n == r.a.Overhead() { - return false, errors.New("last chunk is empty, try age v1.0.0, and please consider reporting this") - } - in = in[:n] - last = true - setLastChunkFlag(&r.nonce) - case err != nil: - return false, err - } - - outBuf := make([]byte, 0, ChunkSize) - out, err := r.a.Open(outBuf, r.nonce[:], in, nil) - if err != nil && !last { - // Check if this was a full-length final chunk. - last = true - setLastChunkFlag(&r.nonce) - out, err = r.a.Open(outBuf, r.nonce[:], in, nil) - } - if err != nil { - return false, errors.New("failed to decrypt and authenticate payload chunk") - } - - incNonce(&r.nonce) - r.unread = r.buf[:copy(r.buf[:], out)] - return last, nil -} - -func incNonce(nonce *[chacha20poly1305.NonceSize]byte) { - for i := len(nonce) - 2; i >= 0; i-- { - nonce[i]++ - if nonce[i] != 0 { - break - } else if i == 0 { - // The counter is 88 bits, this is unreachable. - panic("stream: chunk counter wrapped around") - } - } -} - -func setLastChunkFlag(nonce *[chacha20poly1305.NonceSize]byte) { - nonce[len(nonce)-1] = lastChunkFlag -} - -func nonceIsZero(nonce *[chacha20poly1305.NonceSize]byte) bool { - return *nonce == [chacha20poly1305.NonceSize]byte{} -} - -type Writer struct { - a cipher.AEAD - dst io.Writer - unwritten []byte // backed by buf - buf [encChunkSize]byte - nonce [chacha20poly1305.NonceSize]byte - err error -} - -func NewWriter(key []byte, dst io.Writer) (*Writer, error) { - aead, err := chacha20poly1305.New(key) - if err != nil { - return nil, err - } - w := &Writer{ - a: aead, - dst: dst, - } - w.unwritten = w.buf[:0] - return w, nil -} - -func (w *Writer) Write(p []byte) (n int, err error) { - // TODO: consider refactoring with a bytes.Buffer. - if w.err != nil { - return 0, w.err - } - if len(p) == 0 { - return 0, nil - } - - total := len(p) - for len(p) > 0 { - freeBuf := w.buf[len(w.unwritten):ChunkSize] - n := copy(freeBuf, p) - p = p[n:] - w.unwritten = w.unwritten[:len(w.unwritten)+n] - - if len(w.unwritten) == ChunkSize && len(p) > 0 { - if err := w.flushChunk(notLastChunk); err != nil { - w.err = err - return 0, err - } - } - } - return total, nil -} - -// Close flushes the last chunk. It does not close the underlying Writer. -func (w *Writer) Close() error { - if w.err != nil { - return w.err - } - - w.err = w.flushChunk(lastChunk) - if w.err != nil { - return w.err - } - - w.err = errors.New("stream.Writer is already closed") - return nil -} - -const ( - lastChunk = true - notLastChunk = false -) - -func (w *Writer) flushChunk(last bool) error { - if !last && len(w.unwritten) != ChunkSize { - panic("stream: internal error: flush called with partial chunk") - } - - if last { - setLastChunkFlag(&w.nonce) - } - buf := w.a.Seal(w.buf[:0], w.nonce[:], w.unwritten, nil) - _, err := w.dst.Write(buf) - w.unwritten = w.buf[:0] - incNonce(&w.nonce) - return err -} diff --git a/vendor/filippo.io/age/parse.go b/vendor/filippo.io/age/parse.go deleted file mode 100644 index 373d1a89..00000000 --- a/vendor/filippo.io/age/parse.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2021 The age 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 age - -import ( - "bufio" - "fmt" - "io" - "strings" -) - -// ParseIdentities parses a file with one or more private key encodings, one per -// line. Empty lines and lines starting with "#" are ignored. -// -// This is the same syntax as the private key files accepted by the CLI, except -// the CLI also accepts SSH private keys, which are not recommended for the -// average application. -// -// Currently, all returned values are of type *X25519Identity, but different -// types might be returned in the future. -func ParseIdentities(f io.Reader) ([]Identity, error) { - const privateKeySizeLimit = 1 << 24 // 16 MiB - var ids []Identity - scanner := bufio.NewScanner(io.LimitReader(f, privateKeySizeLimit)) - var n int - for scanner.Scan() { - n++ - line := scanner.Text() - if strings.HasPrefix(line, "#") || line == "" { - continue - } - i, err := ParseX25519Identity(line) - if err != nil { - return nil, fmt.Errorf("error at line %d: %v", n, err) - } - ids = append(ids, i) - } - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("failed to read secret keys file: %v", err) - } - if len(ids) == 0 { - return nil, fmt.Errorf("no secret keys found") - } - return ids, nil -} - -// ParseRecipients parses a file with one or more public key encodings, one per -// line. Empty lines and lines starting with "#" are ignored. -// -// This is the same syntax as the recipients files accepted by the CLI, except -// the CLI also accepts SSH recipients, which are not recommended for the -// average application. -// -// Currently, all returned values are of type *X25519Recipient, but different -// types might be returned in the future. -func ParseRecipients(f io.Reader) ([]Recipient, error) { - const recipientFileSizeLimit = 1 << 24 // 16 MiB - var recs []Recipient - scanner := bufio.NewScanner(io.LimitReader(f, recipientFileSizeLimit)) - var n int - for scanner.Scan() { - n++ - line := scanner.Text() - if strings.HasPrefix(line, "#") || line == "" { - continue - } - r, err := ParseX25519Recipient(line) - if err != nil { - // Hide the error since it might unintentionally leak the contents - // of confidential files. - return nil, fmt.Errorf("malformed recipient at line %d", n) - } - recs = append(recs, r) - } - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("failed to read recipients file: %v", err) - } - if len(recs) == 0 { - return nil, fmt.Errorf("no recipients found") - } - return recs, nil -} diff --git a/vendor/filippo.io/age/primitives.go b/vendor/filippo.io/age/primitives.go deleted file mode 100644 index 804b0193..00000000 --- a/vendor/filippo.io/age/primitives.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2019 The age 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 age - -import ( - "crypto/hmac" - "crypto/sha256" - "errors" - "io" - - "filippo.io/age/internal/format" - "golang.org/x/crypto/chacha20poly1305" - "golang.org/x/crypto/hkdf" -) - -// aeadEncrypt encrypts a message with a one-time key. -func aeadEncrypt(key, plaintext []byte) ([]byte, error) { - aead, err := chacha20poly1305.New(key) - if err != nil { - return nil, err - } - // The nonce is fixed because this function is only used in places where the - // spec guarantees each key is only used once (by deriving it from values - // that include fresh randomness), allowing us to save the overhead. - // For the code that encrypts the actual payload, look at the - // filippo.io/age/internal/stream package. - nonce := make([]byte, chacha20poly1305.NonceSize) - return aead.Seal(nil, nonce, plaintext, nil), nil -} - -var errIncorrectCiphertextSize = errors.New("encrypted value has unexpected length") - -// aeadDecrypt decrypts a message of an expected fixed size. -// -// The message size is limited to mitigate multi-key attacks, where a ciphertext -// can be crafted that decrypts successfully under multiple keys. Short -// ciphertexts can only target two keys, which has limited impact. -func aeadDecrypt(key []byte, size int, ciphertext []byte) ([]byte, error) { - aead, err := chacha20poly1305.New(key) - if err != nil { - return nil, err - } - if len(ciphertext) != size+aead.Overhead() { - return nil, errIncorrectCiphertextSize - } - nonce := make([]byte, chacha20poly1305.NonceSize) - return aead.Open(nil, nonce, ciphertext, nil) -} - -func headerMAC(fileKey []byte, hdr *format.Header) ([]byte, error) { - h := hkdf.New(sha256.New, fileKey, nil, []byte("header")) - hmacKey := make([]byte, 32) - if _, err := io.ReadFull(h, hmacKey); err != nil { - return nil, err - } - hh := hmac.New(sha256.New, hmacKey) - if err := hdr.MarshalWithoutMAC(hh); err != nil { - return nil, err - } - return hh.Sum(nil), nil -} - -func streamKey(fileKey, nonce []byte) []byte { - h := hkdf.New(sha256.New, fileKey, nonce, []byte("payload")) - streamKey := make([]byte, chacha20poly1305.KeySize) - if _, err := io.ReadFull(h, streamKey); err != nil { - panic("age: internal error: failed to read from HKDF: " + err.Error()) - } - return streamKey -} diff --git a/vendor/filippo.io/age/scrypt.go b/vendor/filippo.io/age/scrypt.go deleted file mode 100644 index 1346ad13..00000000 --- a/vendor/filippo.io/age/scrypt.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2019 The age 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 age - -import ( - "crypto/rand" - "errors" - "fmt" - "regexp" - "strconv" - - "filippo.io/age/internal/format" - "golang.org/x/crypto/chacha20poly1305" - "golang.org/x/crypto/scrypt" -) - -const scryptLabel = "age-encryption.org/v1/scrypt" - -// ScryptRecipient is a password-based recipient. Anyone with the password can -// decrypt the message. -// -// If a ScryptRecipient is used, it must be the only recipient for the file: it -// can't be mixed with other recipient types and can't be used multiple times -// for the same file. -// -// Its use is not recommended for automated systems, which should prefer -// X25519Recipient. -type ScryptRecipient struct { - password []byte - workFactor int -} - -var _ Recipient = &ScryptRecipient{} - -// NewScryptRecipient returns a new ScryptRecipient with the provided password. -func NewScryptRecipient(password string) (*ScryptRecipient, error) { - if len(password) == 0 { - return nil, errors.New("passphrase can't be empty") - } - r := &ScryptRecipient{ - password: []byte(password), - // TODO: automatically scale this to 1s (with a min) in the CLI. - workFactor: 18, // 1s on a modern machine - } - return r, nil -} - -// SetWorkFactor sets the scrypt work factor to 2^logN. -// It must be called before Wrap. -// -// If SetWorkFactor is not called, a reasonable default is used. -func (r *ScryptRecipient) SetWorkFactor(logN int) { - if logN > 30 || logN < 1 { - panic("age: SetWorkFactor called with illegal value") - } - r.workFactor = logN -} - -const scryptSaltSize = 16 - -func (r *ScryptRecipient) Wrap(fileKey []byte) ([]*Stanza, error) { - salt := make([]byte, scryptSaltSize) - if _, err := rand.Read(salt[:]); err != nil { - return nil, err - } - - logN := r.workFactor - l := &Stanza{ - Type: "scrypt", - Args: []string{format.EncodeToString(salt), strconv.Itoa(logN)}, - } - - salt = append([]byte(scryptLabel), salt...) - k, err := scrypt.Key(r.password, salt, 1< 30 || logN < 1 { - panic("age: SetMaxWorkFactor called with illegal value") - } - i.maxWorkFactor = logN -} - -func (i *ScryptIdentity) Unwrap(stanzas []*Stanza) ([]byte, error) { - for _, s := range stanzas { - if s.Type == "scrypt" && len(stanzas) != 1 { - return nil, errors.New("an scrypt recipient must be the only one") - } - } - return multiUnwrap(i.unwrap, stanzas) -} - -var digitsRe = regexp.MustCompile(`^[1-9][0-9]*$`) - -func (i *ScryptIdentity) unwrap(block *Stanza) ([]byte, error) { - if block.Type != "scrypt" { - return nil, ErrIncorrectIdentity - } - if len(block.Args) != 2 { - return nil, errors.New("invalid scrypt recipient block") - } - salt, err := format.DecodeString(block.Args[0]) - if err != nil { - return nil, fmt.Errorf("failed to parse scrypt salt: %v", err) - } - if len(salt) != scryptSaltSize { - return nil, errors.New("invalid scrypt recipient block") - } - if w := block.Args[1]; !digitsRe.MatchString(w) { - return nil, fmt.Errorf("scrypt work factor encoding invalid: %q", w) - } - logN, err := strconv.Atoi(block.Args[1]) - if err != nil { - return nil, fmt.Errorf("failed to parse scrypt work factor: %v", err) - } - if logN > i.maxWorkFactor { - return nil, fmt.Errorf("scrypt work factor too large: %v", logN) - } - if logN <= 0 { // unreachable - return nil, fmt.Errorf("invalid scrypt work factor: %v", logN) - } - - salt = append([]byte(scryptLabel), salt...) - k, err := scrypt.Key(i.password, salt, 1<>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 f5e59080..00000000 --- a/vendor/filippo.io/edwards25519/extra.go +++ /dev/null @@ -1,343 +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/ed25519/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. -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**7, 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 5518ef2b..00000000 --- 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 44dc8e8c..00000000 --- a/vendor/filippo.io/edwards25519/field/fe_amd64.go +++ /dev/null @@ -1,13 +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. - -// +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 0aa1e86d..00000000 --- a/vendor/filippo.io/edwards25519/field/fe_amd64.s +++ /dev/null @@ -1,378 +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. - -// +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 ddb6c9b8..00000000 --- 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 af459ef5..00000000 --- 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 751ab2ad..00000000 --- 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. - -// +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 234a5b2e..00000000 --- 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 699238e9..00000000 --- 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/internal/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 d6667b27..00000000 --- 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 a 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() -} - -// carryPropagate 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 3df2fb93..00000000 --- a/vendor/filippo.io/edwards25519/scalar.go +++ /dev/null @@ -1,1030 +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 ( - "crypto/subtle" - "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 value in little-endian. The value is always reduced - // modulo l between operations. - s [32]byte -} - -var ( - scZero = Scalar{[32]byte{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, 0}} - - scOne = Scalar{[32]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}} - - scMinusOne = Scalar{[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}} -) - -// NewScalar returns a new zero Scalar. -func NewScalar() *Scalar { - return &Scalar{} -} - -// MultiplyAdd sets s = x * y + z mod l, and returns s. -func (s *Scalar) MultiplyAdd(x, y, z *Scalar) *Scalar { - scMulAdd(&s.s, &x.s, &y.s, &z.s) - return s -} - -// Add sets s = x + y mod l, and returns s. -func (s *Scalar) Add(x, y *Scalar) *Scalar { - // s = 1 * x + y mod l - scMulAdd(&s.s, &scOne.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 - scMulAdd(&s.s, &scMinusOne.s, &y.s, &x.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 - scMulAdd(&s.s, &scMinusOne.s, &x.s, &scZero.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 - scMulAdd(&s.s, &x.s, &y.s, &scZero.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 an 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") - } - var wideBytes [64]byte - copy(wideBytes[:], x[:]) - scReduce(&s.s, &wideBytes) - return s, nil -} - -// 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") - } - ss := &Scalar{} - copy(ss.s[:], x) - if !isReduced(ss) { - return nil, errors.New("invalid scalar encoding") - } - s.s = ss.s - return s, nil -} - -// isReduced returns whether the given scalar is reduced modulo l. -func isReduced(s *Scalar) bool { - for i := len(s.s) - 1; i >= 0; i-- { - switch { - case s.s[i] > scMinusOne.s[i]: - return false - case s.s[i] < scMinusOne.s[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") - } - var wideBytes [64]byte - copy(wideBytes[:], x[:]) - wideBytes[0] &= 248 - wideBytes[31] &= 63 - wideBytes[31] |= 64 - scReduce(&s.s, &wideBytes) - return s, nil -} - -// Bytes returns the canonical 32-byte little-endian encoding of s. -func (s *Scalar) Bytes() []byte { - buf := make([]byte, 32) - copy(buf, s.s[:]) - return buf -} - -// Equal returns 1 if s and t are equal, and 0 otherwise. -func (s *Scalar) Equal(t *Scalar) int { - return subtle.ConstantTimeCompare(s.s[:], t.s[:]) -} - -// scMulAdd and scReduce are ported from the public domain, “ref10” -// implementation of ed25519 from SUPERCOP. - -func load3(in []byte) int64 { - r := int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - return r -} - -func load4(in []byte) int64 { - r := int64(in[0]) - r |= int64(in[1]) << 8 - r |= int64(in[2]) << 16 - r |= int64(in[3]) << 24 - return r -} - -// Input: -// a[0]+256*a[1]+...+256^31*a[31] = a -// b[0]+256*b[1]+...+256^31*b[31] = b -// c[0]+256*c[1]+...+256^31*c[31] = c -// -// Output: -// s[0]+256*s[1]+...+256^31*s[31] = (ab+c) mod l -// where l = 2^252 + 27742317777372353535851937790883648493. -func scMulAdd(s, a, b, c *[32]byte) { - a0 := 2097151 & load3(a[:]) - a1 := 2097151 & (load4(a[2:]) >> 5) - a2 := 2097151 & (load3(a[5:]) >> 2) - a3 := 2097151 & (load4(a[7:]) >> 7) - a4 := 2097151 & (load4(a[10:]) >> 4) - a5 := 2097151 & (load3(a[13:]) >> 1) - a6 := 2097151 & (load4(a[15:]) >> 6) - a7 := 2097151 & (load3(a[18:]) >> 3) - a8 := 2097151 & load3(a[21:]) - a9 := 2097151 & (load4(a[23:]) >> 5) - a10 := 2097151 & (load3(a[26:]) >> 2) - a11 := (load4(a[28:]) >> 7) - b0 := 2097151 & load3(b[:]) - b1 := 2097151 & (load4(b[2:]) >> 5) - b2 := 2097151 & (load3(b[5:]) >> 2) - b3 := 2097151 & (load4(b[7:]) >> 7) - b4 := 2097151 & (load4(b[10:]) >> 4) - b5 := 2097151 & (load3(b[13:]) >> 1) - b6 := 2097151 & (load4(b[15:]) >> 6) - b7 := 2097151 & (load3(b[18:]) >> 3) - b8 := 2097151 & load3(b[21:]) - b9 := 2097151 & (load4(b[23:]) >> 5) - b10 := 2097151 & (load3(b[26:]) >> 2) - b11 := (load4(b[28:]) >> 7) - c0 := 2097151 & load3(c[:]) - c1 := 2097151 & (load4(c[2:]) >> 5) - c2 := 2097151 & (load3(c[5:]) >> 2) - c3 := 2097151 & (load4(c[7:]) >> 7) - c4 := 2097151 & (load4(c[10:]) >> 4) - c5 := 2097151 & (load3(c[13:]) >> 1) - c6 := 2097151 & (load4(c[15:]) >> 6) - c7 := 2097151 & (load3(c[18:]) >> 3) - c8 := 2097151 & load3(c[21:]) - c9 := 2097151 & (load4(c[23:]) >> 5) - c10 := 2097151 & (load3(c[26:]) >> 2) - c11 := (load4(c[28:]) >> 7) - var carry [23]int64 - - s0 := c0 + a0*b0 - s1 := c1 + a0*b1 + a1*b0 - s2 := c2 + a0*b2 + a1*b1 + a2*b0 - s3 := c3 + a0*b3 + a1*b2 + a2*b1 + a3*b0 - s4 := c4 + a0*b4 + a1*b3 + a2*b2 + a3*b1 + a4*b0 - s5 := c5 + a0*b5 + a1*b4 + a2*b3 + a3*b2 + a4*b1 + a5*b0 - s6 := c6 + a0*b6 + a1*b5 + a2*b4 + a3*b3 + a4*b2 + a5*b1 + a6*b0 - s7 := c7 + a0*b7 + a1*b6 + a2*b5 + a3*b4 + a4*b3 + a5*b2 + a6*b1 + a7*b0 - s8 := c8 + a0*b8 + a1*b7 + a2*b6 + a3*b5 + a4*b4 + a5*b3 + a6*b2 + a7*b1 + a8*b0 - s9 := c9 + a0*b9 + a1*b8 + a2*b7 + a3*b6 + a4*b5 + a5*b4 + a6*b3 + a7*b2 + a8*b1 + a9*b0 - s10 := c10 + a0*b10 + a1*b9 + a2*b8 + a3*b7 + a4*b6 + a5*b5 + a6*b4 + a7*b3 + a8*b2 + a9*b1 + a10*b0 - s11 := c11 + a0*b11 + a1*b10 + a2*b9 + a3*b8 + a4*b7 + a5*b6 + a6*b5 + a7*b4 + a8*b3 + a9*b2 + a10*b1 + a11*b0 - s12 := a1*b11 + a2*b10 + a3*b9 + a4*b8 + a5*b7 + a6*b6 + a7*b5 + a8*b4 + a9*b3 + a10*b2 + a11*b1 - s13 := a2*b11 + a3*b10 + a4*b9 + a5*b8 + a6*b7 + a7*b6 + a8*b5 + a9*b4 + a10*b3 + a11*b2 - s14 := a3*b11 + a4*b10 + a5*b9 + a6*b8 + a7*b7 + a8*b6 + a9*b5 + a10*b4 + a11*b3 - s15 := a4*b11 + a5*b10 + a6*b9 + a7*b8 + a8*b7 + a9*b6 + a10*b5 + a11*b4 - s16 := a5*b11 + a6*b10 + a7*b9 + a8*b8 + a9*b7 + a10*b6 + a11*b5 - s17 := a6*b11 + a7*b10 + a8*b9 + a9*b8 + a10*b7 + a11*b6 - s18 := a7*b11 + a8*b10 + a9*b9 + a10*b8 + a11*b7 - s19 := a8*b11 + a9*b10 + a10*b9 + a11*b8 - s20 := a9*b11 + a10*b10 + a11*b9 - s21 := a10*b11 + a11*b10 - s22 := a11 * b11 - s23 := int64(0) - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - carry[18] = (s18 + (1 << 20)) >> 21 - s19 += carry[18] - s18 -= carry[18] << 21 - carry[20] = (s20 + (1 << 20)) >> 21 - s21 += carry[20] - s20 -= carry[20] << 21 - carry[22] = (s22 + (1 << 20)) >> 21 - s23 += carry[22] - s22 -= carry[22] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - carry[17] = (s17 + (1 << 20)) >> 21 - s18 += carry[17] - s17 -= carry[17] << 21 - carry[19] = (s19 + (1 << 20)) >> 21 - s20 += carry[19] - s19 -= carry[19] << 21 - carry[21] = (s21 + (1 << 20)) >> 21 - s22 += carry[21] - s21 -= carry[21] << 21 - - s11 += s23 * 666643 - s12 += s23 * 470296 - s13 += s23 * 654183 - s14 -= s23 * 997805 - s15 += s23 * 136657 - s16 -= s23 * 683901 - s23 = 0 - - s10 += s22 * 666643 - s11 += s22 * 470296 - s12 += s22 * 654183 - s13 -= s22 * 997805 - s14 += s22 * 136657 - s15 -= s22 * 683901 - s22 = 0 - - s9 += s21 * 666643 - s10 += s21 * 470296 - s11 += s21 * 654183 - s12 -= s21 * 997805 - s13 += s21 * 136657 - s14 -= s21 * 683901 - s21 = 0 - - s8 += s20 * 666643 - s9 += s20 * 470296 - s10 += s20 * 654183 - s11 -= s20 * 997805 - s12 += s20 * 136657 - s13 -= s20 * 683901 - s20 = 0 - - s7 += s19 * 666643 - s8 += s19 * 470296 - s9 += s19 * 654183 - s10 -= s19 * 997805 - s11 += s19 * 136657 - s12 -= s19 * 683901 - s19 = 0 - - s6 += s18 * 666643 - s7 += s18 * 470296 - s8 += s18 * 654183 - s9 -= s18 * 997805 - s10 += s18 * 136657 - s11 -= s18 * 683901 - s18 = 0 - - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - - s5 += s17 * 666643 - s6 += s17 * 470296 - s7 += s17 * 654183 - s8 -= s17 * 997805 - s9 += s17 * 136657 - s10 -= s17 * 683901 - s17 = 0 - - s4 += s16 * 666643 - s5 += s16 * 470296 - s6 += s16 * 654183 - s7 -= s16 * 997805 - s8 += s16 * 136657 - s9 -= s16 * 683901 - s16 = 0 - - s3 += s15 * 666643 - s4 += s15 * 470296 - s5 += s15 * 654183 - s6 -= s15 * 997805 - s7 += s15 * 136657 - s8 -= s15 * 683901 - s15 = 0 - - s2 += s14 * 666643 - s3 += s14 * 470296 - s4 += s14 * 654183 - s5 -= s14 * 997805 - s6 += s14 * 136657 - s7 -= s14 * 683901 - s14 = 0 - - s1 += s13 * 666643 - s2 += s13 * 470296 - s3 += s13 * 654183 - s4 -= s13 * 997805 - s5 += s13 * 136657 - s6 -= s13 * 683901 - s13 = 0 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[11] = s11 >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - s[0] = byte(s0 >> 0) - s[1] = byte(s0 >> 8) - s[2] = byte((s0 >> 16) | (s1 << 5)) - s[3] = byte(s1 >> 3) - s[4] = byte(s1 >> 11) - s[5] = byte((s1 >> 19) | (s2 << 2)) - s[6] = byte(s2 >> 6) - s[7] = byte((s2 >> 14) | (s3 << 7)) - s[8] = byte(s3 >> 1) - s[9] = byte(s3 >> 9) - s[10] = byte((s3 >> 17) | (s4 << 4)) - s[11] = byte(s4 >> 4) - s[12] = byte(s4 >> 12) - s[13] = byte((s4 >> 20) | (s5 << 1)) - s[14] = byte(s5 >> 7) - s[15] = byte((s5 >> 15) | (s6 << 6)) - s[16] = byte(s6 >> 2) - s[17] = byte(s6 >> 10) - s[18] = byte((s6 >> 18) | (s7 << 3)) - s[19] = byte(s7 >> 5) - s[20] = byte(s7 >> 13) - s[21] = byte(s8 >> 0) - s[22] = byte(s8 >> 8) - s[23] = byte((s8 >> 16) | (s9 << 5)) - s[24] = byte(s9 >> 3) - s[25] = byte(s9 >> 11) - s[26] = byte((s9 >> 19) | (s10 << 2)) - s[27] = byte(s10 >> 6) - s[28] = byte((s10 >> 14) | (s11 << 7)) - s[29] = byte(s11 >> 1) - s[30] = byte(s11 >> 9) - s[31] = byte(s11 >> 17) -} - -// Input: -// s[0]+256*s[1]+...+256^63*s[63] = s -// -// Output: -// s[0]+256*s[1]+...+256^31*s[31] = s mod l -// where l = 2^252 + 27742317777372353535851937790883648493. -func scReduce(out *[32]byte, s *[64]byte) { - s0 := 2097151 & load3(s[:]) - s1 := 2097151 & (load4(s[2:]) >> 5) - s2 := 2097151 & (load3(s[5:]) >> 2) - s3 := 2097151 & (load4(s[7:]) >> 7) - s4 := 2097151 & (load4(s[10:]) >> 4) - s5 := 2097151 & (load3(s[13:]) >> 1) - s6 := 2097151 & (load4(s[15:]) >> 6) - s7 := 2097151 & (load3(s[18:]) >> 3) - s8 := 2097151 & load3(s[21:]) - s9 := 2097151 & (load4(s[23:]) >> 5) - s10 := 2097151 & (load3(s[26:]) >> 2) - s11 := 2097151 & (load4(s[28:]) >> 7) - s12 := 2097151 & (load4(s[31:]) >> 4) - s13 := 2097151 & (load3(s[34:]) >> 1) - s14 := 2097151 & (load4(s[36:]) >> 6) - s15 := 2097151 & (load3(s[39:]) >> 3) - s16 := 2097151 & load3(s[42:]) - s17 := 2097151 & (load4(s[44:]) >> 5) - s18 := 2097151 & (load3(s[47:]) >> 2) - s19 := 2097151 & (load4(s[49:]) >> 7) - s20 := 2097151 & (load4(s[52:]) >> 4) - s21 := 2097151 & (load3(s[55:]) >> 1) - s22 := 2097151 & (load4(s[57:]) >> 6) - s23 := (load4(s[60:]) >> 3) - - s11 += s23 * 666643 - s12 += s23 * 470296 - s13 += s23 * 654183 - s14 -= s23 * 997805 - s15 += s23 * 136657 - s16 -= s23 * 683901 - s23 = 0 - - s10 += s22 * 666643 - s11 += s22 * 470296 - s12 += s22 * 654183 - s13 -= s22 * 997805 - s14 += s22 * 136657 - s15 -= s22 * 683901 - s22 = 0 - - s9 += s21 * 666643 - s10 += s21 * 470296 - s11 += s21 * 654183 - s12 -= s21 * 997805 - s13 += s21 * 136657 - s14 -= s21 * 683901 - s21 = 0 - - s8 += s20 * 666643 - s9 += s20 * 470296 - s10 += s20 * 654183 - s11 -= s20 * 997805 - s12 += s20 * 136657 - s13 -= s20 * 683901 - s20 = 0 - - s7 += s19 * 666643 - s8 += s19 * 470296 - s9 += s19 * 654183 - s10 -= s19 * 997805 - s11 += s19 * 136657 - s12 -= s19 * 683901 - s19 = 0 - - s6 += s18 * 666643 - s7 += s18 * 470296 - s8 += s18 * 654183 - s9 -= s18 * 997805 - s10 += s18 * 136657 - s11 -= s18 * 683901 - s18 = 0 - - var carry [17]int64 - - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[12] = (s12 + (1 << 20)) >> 21 - s13 += carry[12] - s12 -= carry[12] << 21 - carry[14] = (s14 + (1 << 20)) >> 21 - s15 += carry[14] - s14 -= carry[14] << 21 - carry[16] = (s16 + (1 << 20)) >> 21 - s17 += carry[16] - s16 -= carry[16] << 21 - - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - carry[13] = (s13 + (1 << 20)) >> 21 - s14 += carry[13] - s13 -= carry[13] << 21 - carry[15] = (s15 + (1 << 20)) >> 21 - s16 += carry[15] - s15 -= carry[15] << 21 - - s5 += s17 * 666643 - s6 += s17 * 470296 - s7 += s17 * 654183 - s8 -= s17 * 997805 - s9 += s17 * 136657 - s10 -= s17 * 683901 - s17 = 0 - - s4 += s16 * 666643 - s5 += s16 * 470296 - s6 += s16 * 654183 - s7 -= s16 * 997805 - s8 += s16 * 136657 - s9 -= s16 * 683901 - s16 = 0 - - s3 += s15 * 666643 - s4 += s15 * 470296 - s5 += s15 * 654183 - s6 -= s15 * 997805 - s7 += s15 * 136657 - s8 -= s15 * 683901 - s15 = 0 - - s2 += s14 * 666643 - s3 += s14 * 470296 - s4 += s14 * 654183 - s5 -= s14 * 997805 - s6 += s14 * 136657 - s7 -= s14 * 683901 - s14 = 0 - - s1 += s13 * 666643 - s2 += s13 * 470296 - s3 += s13 * 654183 - s4 -= s13 * 997805 - s5 += s13 * 136657 - s6 -= s13 * 683901 - s13 = 0 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = (s0 + (1 << 20)) >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[2] = (s2 + (1 << 20)) >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[4] = (s4 + (1 << 20)) >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[6] = (s6 + (1 << 20)) >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[8] = (s8 + (1 << 20)) >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[10] = (s10 + (1 << 20)) >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - carry[1] = (s1 + (1 << 20)) >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[3] = (s3 + (1 << 20)) >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[5] = (s5 + (1 << 20)) >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[7] = (s7 + (1 << 20)) >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[9] = (s9 + (1 << 20)) >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[11] = (s11 + (1 << 20)) >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - carry[11] = s11 >> 21 - s12 += carry[11] - s11 -= carry[11] << 21 - - s0 += s12 * 666643 - s1 += s12 * 470296 - s2 += s12 * 654183 - s3 -= s12 * 997805 - s4 += s12 * 136657 - s5 -= s12 * 683901 - s12 = 0 - - carry[0] = s0 >> 21 - s1 += carry[0] - s0 -= carry[0] << 21 - carry[1] = s1 >> 21 - s2 += carry[1] - s1 -= carry[1] << 21 - carry[2] = s2 >> 21 - s3 += carry[2] - s2 -= carry[2] << 21 - carry[3] = s3 >> 21 - s4 += carry[3] - s3 -= carry[3] << 21 - carry[4] = s4 >> 21 - s5 += carry[4] - s4 -= carry[4] << 21 - carry[5] = s5 >> 21 - s6 += carry[5] - s5 -= carry[5] << 21 - carry[6] = s6 >> 21 - s7 += carry[6] - s6 -= carry[6] << 21 - carry[7] = s7 >> 21 - s8 += carry[7] - s7 -= carry[7] << 21 - carry[8] = s8 >> 21 - s9 += carry[8] - s8 -= carry[8] << 21 - carry[9] = s9 >> 21 - s10 += carry[9] - s9 -= carry[9] << 21 - carry[10] = s10 >> 21 - s11 += carry[10] - s10 -= carry[10] << 21 - - out[0] = byte(s0 >> 0) - out[1] = byte(s0 >> 8) - out[2] = byte((s0 >> 16) | (s1 << 5)) - out[3] = byte(s1 >> 3) - out[4] = byte(s1 >> 11) - out[5] = byte((s1 >> 19) | (s2 << 2)) - out[6] = byte(s2 >> 6) - out[7] = byte((s2 >> 14) | (s3 << 7)) - out[8] = byte(s3 >> 1) - out[9] = byte(s3 >> 9) - out[10] = byte((s3 >> 17) | (s4 << 4)) - out[11] = byte(s4 >> 4) - out[12] = byte(s4 >> 12) - out[13] = byte((s4 >> 20) | (s5 << 1)) - out[14] = byte(s5 >> 7) - out[15] = byte((s5 >> 15) | (s6 << 6)) - out[16] = byte(s6 >> 2) - out[17] = byte(s6 >> 10) - out[18] = byte((s6 >> 18) | (s7 << 3)) - out[19] = byte(s7 >> 5) - out[20] = byte(s7 >> 13) - out[21] = byte(s8 >> 0) - out[22] = byte(s8 >> 8) - out[23] = byte((s8 >> 16) | (s9 << 5)) - out[24] = byte(s9 >> 3) - out[25] = byte(s9 >> 11) - out[26] = byte((s9 >> 19) | (s10 << 2)) - out[27] = byte(s10 >> 6) - out[28] = byte((s10 >> 14) | (s11 << 7)) - out[29] = byte(s11 >> 1) - out[30] = byte(s11 >> 9) - out[31] = byte(s11 >> 17) -} - -// 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 - if s.s[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(s.s[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 { - if s.s[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(s.s[i] & 15) - digits[2*i+1] = int8((s.s[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/scalarmult.go b/vendor/filippo.io/edwards25519/scalarmult.go deleted file mode 100644 index f7ca3cef..00000000 --- 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 beec956b..00000000 --- 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 - // recievers 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/1Password/connect-sdk-go/LICENSE b/vendor/github.com/1Password/connect-sdk-go/LICENSE deleted file mode 100644 index 340215c6..00000000 --- a/vendor/github.com/1Password/connect-sdk-go/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021 1Password - -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/github.com/1Password/connect-sdk-go/connect/client.go b/vendor/github.com/1Password/connect-sdk-go/connect/client.go deleted file mode 100644 index 16b1832e..00000000 --- a/vendor/github.com/1Password/connect-sdk-go/connect/client.go +++ /dev/null @@ -1,453 +0,0 @@ -package connect - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - - opentracing "github.com/opentracing/opentracing-go" - "github.com/opentracing/opentracing-go/ext" - jaegerClientConfig "github.com/uber/jaeger-client-go/config" - "github.com/uber/jaeger-client-go/zipkin" - - "github.com/1Password/connect-sdk-go/onepassword" -) - -const ( - defaultUserAgent = "connect-sdk-go/%s" -) - -// Client Represents an available 1Password Connect API to connect to -type Client interface { - GetVaults() ([]onepassword.Vault, error) - GetVault(uuid string) (*onepassword.Vault, error) - GetVaultsByTitle(uuid string) ([]onepassword.Vault, error) - GetItem(uuid string, vaultUUID string) (*onepassword.Item, error) - GetItems(vaultUUID string) ([]onepassword.Item, error) - GetItemsByTitle(title string, vaultUUID string) ([]onepassword.Item, error) - GetItemByTitle(title string, vaultUUID string) (*onepassword.Item, error) - CreateItem(item *onepassword.Item, vaultUUID string) (*onepassword.Item, error) - UpdateItem(item *onepassword.Item, vaultUUID string) (*onepassword.Item, error) - DeleteItem(item *onepassword.Item, vaultUUID string) error - GetFile(fileUUID string, itemUUID string, vaultUUID string) (*onepassword.File, error) - GetFileContent(file *onepassword.File) ([]byte, error) -} - -type httpClient interface { - Do(req *http.Request) (*http.Response, error) -} - -const ( - envHostVariable = "OP_CONNECT_HOST" - envTokenVariable = "OP_CONNECT_TOKEN" -) - -// NewClientFromEnvironment Returns a Secret Service client assuming that your -// jwt is set in the OP_TOKEN environment variable -func NewClientFromEnvironment() (Client, error) { - host, found := os.LookupEnv(envHostVariable) - if !found { - return nil, fmt.Errorf("There is no hostname available in the %q variable", envHostVariable) - } - - token, found := os.LookupEnv(envTokenVariable) - if !found { - return nil, fmt.Errorf("There is no token available in the %q variable", envTokenVariable) - } - - return NewClient(host, token), nil -} - -// NewClient Returns a Secret Service client for a given url and jwt -func NewClient(url string, token string) Client { - return NewClientWithUserAgent(url, token, fmt.Sprintf(defaultUserAgent, SDKVersion)) -} - -// NewClientWithUserAgent Returns a Secret Service client for a given url and jwt and identifies with userAgent -func NewClientWithUserAgent(url string, token string, userAgent string) Client { - if !opentracing.IsGlobalTracerRegistered() { - cfg := jaegerClientConfig.Configuration{} - zipkinPropagator := zipkin.NewZipkinB3HTTPHeaderPropagator() - cfg.InitGlobalTracer( - userAgent, - jaegerClientConfig.Injector(opentracing.HTTPHeaders, zipkinPropagator), - jaegerClientConfig.Extractor(opentracing.HTTPHeaders, zipkinPropagator), - jaegerClientConfig.ZipkinSharedRPCSpan(true), - ) - } - - return &restClient{ - URL: url, - Token: token, - - userAgent: userAgent, - tracer: opentracing.GlobalTracer(), - - client: http.DefaultClient, - } -} - -type restClient struct { - URL string - Token string - userAgent string - tracer opentracing.Tracer - client httpClient -} - -// GetVaults Get a list of all available vaults -func (rs *restClient) GetVaults() ([]onepassword.Vault, error) { - span := rs.tracer.StartSpan("GetVaults") - defer span.Finish() - - vaultURL := fmt.Sprintf("/v1/vaults") - request, err := rs.buildRequest(http.MethodGet, vaultURL, http.NoBody, span) - if err != nil { - return nil, err - } - - response, err := rs.client.Do(request) - if err != nil { - return nil, err - } - - var vaults []onepassword.Vault - if err := parseResponse(response, http.StatusOK, &vaults); err != nil { - return nil, err - } - - return vaults, nil -} - -// GetVaults Get a list of all available vaults -func (rs *restClient) GetVault(uuid string) (*onepassword.Vault, error) { - if uuid == "" { - return nil, errors.New("no uuid provided") - } - - span := rs.tracer.StartSpan("GetVault") - defer span.Finish() - - vaultURL := fmt.Sprintf("/v1/vaults/%s", uuid) - request, err := rs.buildRequest(http.MethodGet, vaultURL, http.NoBody, span) - if err != nil { - return nil, err - } - - response, err := rs.client.Do(request) - if err != nil { - return nil, err - } - var vault onepassword.Vault - if err := parseResponse(response, http.StatusOK, &vault); err != nil { - return nil, err - } - - return &vault, nil -} - -func (rs *restClient) GetVaultsByTitle(title string) ([]onepassword.Vault, error) { - span := rs.tracer.StartSpan("GetVaultsByTitle") - defer span.Finish() - - filter := url.QueryEscape(fmt.Sprintf("title eq \"%s\"", title)) - itemURL := fmt.Sprintf("/v1/vaults?filter=%s", filter) - request, err := rs.buildRequest(http.MethodGet, itemURL, http.NoBody, span) - if err != nil { - return nil, err - } - - response, err := rs.client.Do(request) - if err != nil { - return nil, err - } - - var vaults []onepassword.Vault - if err := parseResponse(response, http.StatusOK, &vaults); err != nil { - return nil, err - } - - return vaults, nil -} - -// GetItem Get a specific Item from the 1Password Connect API -func (rs *restClient) GetItem(uuid string, vaultUUID string) (*onepassword.Item, error) { - span := rs.tracer.StartSpan("GetItem") - defer span.Finish() - - itemURL := fmt.Sprintf("/v1/vaults/%s/items/%s", vaultUUID, uuid) - request, err := rs.buildRequest(http.MethodGet, itemURL, http.NoBody, span) - if err != nil { - return nil, err - } - - response, err := rs.client.Do(request) - if err != nil { - return nil, err - } - var item onepassword.Item - if err := parseResponse(response, http.StatusOK, &item); err != nil { - return nil, err - } - - return &item, nil -} - -func (rs *restClient) GetItemByTitle(title string, vaultUUID string) (*onepassword.Item, error) { - span := rs.tracer.StartSpan("GetItemByTitle") - defer span.Finish() - items, err := rs.GetItemsByTitle(title, vaultUUID) - if err != nil { - return nil, err - } - - if len(items) != 1 { - return nil, fmt.Errorf("Found %d item(s) in vault %q with title %q", len(items), vaultUUID, title) - } - - return rs.GetItem(items[0].ID, items[0].Vault.ID) -} - -func (rs *restClient) GetItemsByTitle(title string, vaultUUID string) ([]onepassword.Item, error) { - span := rs.tracer.StartSpan("GetItemsByTitle") - defer span.Finish() - - filter := url.QueryEscape(fmt.Sprintf("title eq \"%s\"", title)) - itemURL := fmt.Sprintf("/v1/vaults/%s/items?filter=%s", vaultUUID, filter) - request, err := rs.buildRequest(http.MethodGet, itemURL, http.NoBody, span) - if err != nil { - return nil, err - } - - response, err := rs.client.Do(request) - if err != nil { - return nil, err - } - - var items []onepassword.Item - if err := parseResponse(response, http.StatusOK, &items); err != nil { - return nil, err - } - - return items, nil -} - -func (rs *restClient) GetItems(vaultUUID string) ([]onepassword.Item, error) { - span := rs.tracer.StartSpan("GetItems") - defer span.Finish() - - itemURL := fmt.Sprintf("/v1/vaults/%s/items", vaultUUID) - request, err := rs.buildRequest(http.MethodGet, itemURL, http.NoBody, span) - if err != nil { - return nil, err - } - - response, err := rs.client.Do(request) - if err != nil { - return nil, err - } - - var items []onepassword.Item - if err := parseResponse(response, http.StatusOK, &items); err != nil { - return nil, err - } - - return items, nil -} - -// CreateItem Create a new item in a specified vault -func (rs *restClient) CreateItem(item *onepassword.Item, vaultUUID string) (*onepassword.Item, error) { - span := rs.tracer.StartSpan("CreateItem") - defer span.Finish() - - itemURL := fmt.Sprintf("/v1/vaults/%s/items", vaultUUID) - itemBody, err := json.Marshal(item) - if err != nil { - return nil, err - } - - request, err := rs.buildRequest(http.MethodPost, itemURL, bytes.NewBuffer(itemBody), span) - if err != nil { - return nil, err - } - - response, err := rs.client.Do(request) - if err != nil { - return nil, err - } - - var newItem onepassword.Item - if err := parseResponse(response, http.StatusOK, &newItem); err != nil { - return nil, err - } - - return &newItem, nil -} - -// UpdateItem Update a new item in a specified vault -func (rs *restClient) UpdateItem(item *onepassword.Item, vaultUUID string) (*onepassword.Item, error) { - span := rs.tracer.StartSpan("UpdateItem") - defer span.Finish() - - itemURL := fmt.Sprintf("/v1/vaults/%s/items/%s", item.Vault.ID, item.ID) - itemBody, err := json.Marshal(item) - if err != nil { - return nil, err - } - - request, err := rs.buildRequest(http.MethodPut, itemURL, bytes.NewBuffer(itemBody), span) - if err != nil { - return nil, err - } - - response, err := rs.client.Do(request) - if err != nil { - return nil, err - } - - var newItem onepassword.Item - if err := parseResponse(response, http.StatusOK, &newItem); err != nil { - return nil, err - } - - return &newItem, nil -} - -// DeleteItem Delete a new item in a specified vault -func (rs *restClient) DeleteItem(item *onepassword.Item, vaultUUID string) error { - span := rs.tracer.StartSpan("DeleteItem") - defer span.Finish() - - itemURL := fmt.Sprintf("/v1/vaults/%s/items/%s", item.Vault.ID, item.ID) - request, err := rs.buildRequest(http.MethodDelete, itemURL, http.NoBody, span) - if err != nil { - return err - } - - response, err := rs.client.Do(request) - if err != nil { - return err - } - - if err := parseResponse(response, http.StatusNoContent, nil); err != nil { - return err - } - - return nil -} - -// GetFile Get a specific File in a specified item. -// This does not include the file contents. Call GetFileContent() to load the file's content. -func (rs *restClient) GetFile(uuid string, itemUUID string, vaultUUID string) (*onepassword.File, error) { - span := rs.tracer.StartSpan("GetFile") - defer span.Finish() - - itemURL := fmt.Sprintf("/v1/vaults/%s/items/%s/files/%s", vaultUUID, itemUUID, uuid) - request, err := rs.buildRequest(http.MethodGet, itemURL, http.NoBody, span) - if err != nil { - return nil, err - } - - response, err := rs.client.Do(request) - if err != nil { - return nil, err - } - if err := expectMinimumConnectVersion(response, version{1, 3, 0}); err != nil { - return nil, err - } - - var file onepassword.File - if err := parseResponse(response, http.StatusOK, &file); err != nil { - return nil, err - } - - return &file, nil -} - -// GetFileContent retrieves the file's content. -// If the file's content have previously been fetched, those contents are returned without making another request. -func (rs *restClient) GetFileContent(file *onepassword.File) ([]byte, error) { - if content, err := file.Content(); err == nil { - return content, nil - } - - span := rs.tracer.StartSpan("GetFileContent") - defer span.Finish() - - request, err := rs.buildRequest(http.MethodGet, file.ContentPath, http.NoBody, span) - if err != nil { - return nil, err - } - - response, err := rs.client.Do(request) - if err != nil { - return nil, err - } - if err := expectMinimumConnectVersion(response, version{1, 3, 0}); err != nil { - return nil, err - } - - content, err := readResponseBody(response, http.StatusOK) - if err != nil { - return nil, err - } - - file.SetContent(content) - return content, nil -} - -func (rs *restClient) buildRequest(method string, path string, body io.Reader, span opentracing.Span) (*http.Request, error) { - url := fmt.Sprintf("%s%s", rs.URL, path) - - request, err := http.NewRequest(method, url, body) - if err != nil { - return nil, err - } - - request.Header.Set("Content-Type", "application/json") - request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", rs.Token)) - request.Header.Set("User-Agent", rs.userAgent) - - ext.SpanKindRPCClient.Set(span) - ext.HTTPUrl.Set(span, path) - ext.HTTPMethod.Set(span, method) - - rs.tracer.Inject(span.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(request.Header)) - - return request, nil -} - -func parseResponse(resp *http.Response, expectedStatusCode int, result interface{}) error { - body, err := readResponseBody(resp, expectedStatusCode) - if err != nil { - return err - } - if result != nil { - if err := json.Unmarshal(body, result); err != nil { - return fmt.Errorf("decoding response: %s", err) - } - } - return nil -} - -func readResponseBody(resp *http.Response, expectedStatusCode int) ([]byte, error) { - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - if resp.StatusCode != expectedStatusCode { - var errResp *onepassword.Error - if err := json.Unmarshal(body, &errResp); err != nil { - return nil, fmt.Errorf("decoding error response: %s", err) - } - return nil, errResp - } - return body, nil -} diff --git a/vendor/github.com/1Password/connect-sdk-go/connect/config.go b/vendor/github.com/1Password/connect-sdk-go/connect/config.go deleted file mode 100644 index 2812b3fa..00000000 --- a/vendor/github.com/1Password/connect-sdk-go/connect/config.go +++ /dev/null @@ -1,172 +0,0 @@ -package connect - -import ( - "fmt" - "os" - "reflect" - "strconv" - "strings" - - "github.com/1Password/connect-sdk-go/onepassword" -) - -const ( - vaultTag = "opvault" - itemTag = "opitem" - fieldTag = "opfield" - - envVaultVar = "OP_VAULT" -) - -type parsedItem struct { - vaultUUID string - itemTitle string - fields []*reflect.StructField - values []*reflect.Value -} - -// Load Load configuration values based on strcut tag -func Load(client Client, i interface{}) error { - configP := reflect.ValueOf(i) - if configP.Kind() != reflect.Ptr { - return fmt.Errorf("You must pass a pointer to Config struct") - } - - config := configP.Elem() - if config.Kind() != reflect.Struct { - return fmt.Errorf("Config values can only be loaded into a struct") - } - - t := config.Type() - - // Multiple fields may be from a single item so we will collect them - items := map[string]parsedItem{} - - // Fetch the Vault from the environment - vaultUUID, envVarFound := os.LookupEnv(envVaultVar) - - for i := 0; i < t.NumField(); i++ { - value := config.Field(i) - field := t.Field(i) - tag := field.Tag.Get(itemTag) - - if tag == "" { - continue - } - - if !value.CanSet() { - return fmt.Errorf("Cannot load config into private fields") - } - - itemVault, err := vaultUUIDForField(&field, vaultUUID, envVarFound) - if err != nil { - return err - } - - key := fmt.Sprintf("%s/%s", itemVault, tag) - parsed := items[key] - parsed.vaultUUID = itemVault - parsed.itemTitle = tag - parsed.fields = append(parsed.fields, &field) - parsed.values = append(parsed.values, &value) - items[key] = parsed - } - - for _, item := range items { - if err := setValuesForTag(client, &item); err != nil { - return err - } - } - - return nil -} - -func vaultUUIDForField(field *reflect.StructField, vaultUUID string, envVaultFound bool) (string, error) { - // Check to see if a specific vault has been specified on the field - // If the env vault id has not been found and item doesn't have a vault - // return an error - if vaultUUIDTag := field.Tag.Get(vaultTag); vaultUUIDTag == "" { - if !envVaultFound { - return "", fmt.Errorf("There is no vault for %q field", field.Name) - } - } else { - return vaultUUIDTag, nil - } - - return vaultUUID, nil -} - -func setValuesForTag(client Client, parsedItem *parsedItem) error { - item, err := client.GetItemByTitle(parsedItem.itemTitle, parsedItem.vaultUUID) - if err != nil { - return err - } - - for i, field := range parsedItem.fields { - value := parsedItem.values[i] - path := field.Tag.Get(fieldTag) - if path == "" { - if field.Type == reflect.TypeOf(onepassword.Item{}) { - value.Set(reflect.ValueOf(*item)) - return nil - } - return fmt.Errorf("There is no %q specified for %q", fieldTag, field.Name) - } - - pathParts := strings.Split(path, ".") - - if len(pathParts) != 2 { - return fmt.Errorf("Invalid field path format for %q", field.Name) - } - - sectionID := sectionIDForName(pathParts[0], item.Sections) - label := pathParts[1] - - for _, f := range item.Fields { - fieldSectionID := "" - if f.Section != nil { - fieldSectionID = f.Section.ID - } - - if fieldSectionID == sectionID && f.Label == label { - if err := setValue(value, f.Value); err != nil { - return err - } - break - } - } - } - - return nil -} - -func setValue(value *reflect.Value, toSet string) error { - switch value.Kind() { - case reflect.String: - value.SetString(toSet) - case reflect.Int: - v, err := strconv.Atoi(toSet) - if err != nil { - return err - } - value.SetInt(int64(v)) - default: - return fmt.Errorf("Unsupported type %q. Only string, int64, and onepassword.Item are supported", value.Kind()) - } - - return nil -} - -func sectionIDForName(name string, sections []*onepassword.ItemSection) string { - if sections == nil { - return "" - } - - for _, s := range sections { - if name == strings.ToLower(s.Label) { - return s.ID - } - } - - return "" -} diff --git a/vendor/github.com/1Password/connect-sdk-go/connect/version.go b/vendor/github.com/1Password/connect-sdk-go/connect/version.go deleted file mode 100644 index b654f8bb..00000000 --- a/vendor/github.com/1Password/connect-sdk-go/connect/version.go +++ /dev/null @@ -1,104 +0,0 @@ -package connect - -import ( - "errors" - "fmt" - "net/http" - "strconv" - "strings" -) - -// SDKVersion is the latest Semantic Version of the library -// Do not rename this variable without changing the regex in the Makefile -const SDKVersion = "1.2.0" - -const VersionHeaderKey = "1Password-Connect-Version" - -// expectMinimumConnectVersion returns an error if the provided minimum version for Connect is lower than the version -// reported in the response from Connect. -func expectMinimumConnectVersion(resp *http.Response, minimumVersion version) error { - serverVersion, err := getServerVersion(resp) - if err != nil { - // Return gracefully if server version cannot be determined reliably - return nil - } - if !serverVersion.IsGreaterOrEqualThan(minimumVersion) { - return fmt.Errorf("need at least version %s of Connect for this function, detected version %s. Please update your Connect server", minimumVersion, serverVersion) - } - return nil -} - -func getServerVersion(resp *http.Response) (serverVersion, error) { - versionHeader := resp.Header.Get(VersionHeaderKey) - if versionHeader == "" { - // The last version without the version header was v1.2.0 - return serverVersion{ - version: version{1, 2, 0}, - orEarlier: true, - }, nil - } - return parseServerVersion(versionHeader) -} - -type version struct { - major int - minor int - patch int -} - -// serverVersion describes the version reported by the server. -type serverVersion struct { - version - // orEarlier is true if the version is derived from the lack of a version header from the server. - orEarlier bool -} - -func (v version) String() string { - return fmt.Sprintf("%d.%d.%d", v.major, v.minor, v.patch) -} - -func (v serverVersion) String() string { - if v.orEarlier { - return v.version.String() + " (or earlier)" - } - return v.version.String() -} - -// IsGreaterOrEqualThan returns true if the lefthand-side version is equal to or or a higher version than the provided -// minimum according to the semantic versioning rules. -func (v version) IsGreaterOrEqualThan(min version) bool { - if v.major != min.major { - // Different major version - return v.major > min.major - } - - if v.minor != min.minor { - // Same major, but different minor version - return v.minor > min.minor - } - - // Same major and minor version - return v.patch >= min.patch -} - -func parseServerVersion(v string) (serverVersion, error) { - spl := strings.Split(v, ".") - if len(spl) != 3 { - return serverVersion{}, errors.New("wrong length") - } - var res [3]int - for i := range res { - tmp, err := strconv.Atoi(spl[i]) - if err != nil { - return serverVersion{}, err - } - res[i] = tmp - } - return serverVersion{ - version: version{ - major: res[0], - minor: res[1], - patch: res[2], - }, - }, nil -} diff --git a/vendor/github.com/1Password/connect-sdk-go/onepassword/errors.go b/vendor/github.com/1Password/connect-sdk-go/onepassword/errors.go deleted file mode 100644 index 329a0b33..00000000 --- a/vendor/github.com/1Password/connect-sdk-go/onepassword/errors.go +++ /dev/null @@ -1,21 +0,0 @@ -package onepassword - -import "fmt" - -// Error is an error returned by the Connect API. -type Error struct { - StatusCode int `json:"status"` - Message string `json:"message"` -} - -func (e *Error) Error() string { - return fmt.Sprintf("status %d: %s", e.StatusCode, e.Message) -} - -func (e *Error) Is(target error) bool { - t, ok := target.(*Error) - if !ok { - return false - } - return t.Message == e.Message && t.StatusCode == e.StatusCode -} diff --git a/vendor/github.com/1Password/connect-sdk-go/onepassword/files.go b/vendor/github.com/1Password/connect-sdk-go/onepassword/files.go deleted file mode 100644 index a34692fc..00000000 --- a/vendor/github.com/1Password/connect-sdk-go/onepassword/files.go +++ /dev/null @@ -1,49 +0,0 @@ -package onepassword - -import ( - "encoding/json" - "errors" -) - -type File struct { - ID string `json:"id"` - Name string `json:"name"` - Section *ItemSection `json:"section,omitempty"` - Size int `json:"size"` - ContentPath string `json:"content_path"` - content []byte -} - -func (f *File) UnmarshalJSON(data []byte) error { - var jsonFile struct { - ID string `json:"id"` - Name string `json:"name"` - Section *ItemSection `json:"section,omitempty"` - Size int `json:"size"` - ContentPath string `json:"content_path"` - Content []byte `json:"content,omitempty"` - } - if err := json.Unmarshal(data, &jsonFile); err != nil { - return err - } - f.ID = jsonFile.ID - f.Name = jsonFile.Name - f.Section = jsonFile.Section - f.Size = jsonFile.Size - f.ContentPath = jsonFile.ContentPath - f.content = jsonFile.Content - return nil -} - -// Content returns the content of the file if they have been loaded and returns an error if they have not been loaded. -// Use `client.GetFileContent(file *File)` instead to make sure the content is fetched automatically if not present. -func (f *File) Content() ([]byte, error) { - if f.content == nil { - return nil, errors.New("file content not loaded") - } - return f.content, nil -} - -func (f *File) SetContent(content []byte) { - f.content = content -} diff --git a/vendor/github.com/1Password/connect-sdk-go/onepassword/items.go b/vendor/github.com/1Password/connect-sdk-go/onepassword/items.go deleted file mode 100644 index 783ca8ea..00000000 --- a/vendor/github.com/1Password/connect-sdk-go/onepassword/items.go +++ /dev/null @@ -1,160 +0,0 @@ -package onepassword - -import ( - "encoding/json" - "strings" - "time" -) - -// ItemCategory Represents the template of the Item -type ItemCategory string - -const ( - Login ItemCategory = "LOGIN" - Password ItemCategory = "PASSWORD" - Server ItemCategory = "SERVER" - Database ItemCategory = "DATABASE" - CreditCard ItemCategory = "CREDIT_CARD" - Membership ItemCategory = "MEMBERSHIP" - Passport ItemCategory = "PASSPORT" - SoftwareLicense ItemCategory = "SOFTWARE_LICENSE" - OutdoorLicense ItemCategory = "OUTDOOR_LICENSE" - SecureNote ItemCategory = "SECURE_NOTE" - WirelessRouter ItemCategory = "WIRELESS_ROUTER" - BankAccount ItemCategory = "BANK_ACCOUNT" - DriverLicense ItemCategory = "DRIVER_LICENSE" - Identity ItemCategory = "IDENTITY" - RewardProgram ItemCategory = "REWARD_PROGRAM" - Document ItemCategory = "DOCUMENT" - EmailAccount ItemCategory = "EMAIL_ACCOUNT" - SocialSecurityNumber ItemCategory = "SOCIAL_SECURITY_NUMBER" - ApiCredential ItemCategory = "API_CREDENTIAL" - Custom ItemCategory = "CUSTOM" -) - -// UnmarshalJSON Unmarshall Item Category enum strings to Go string enums -func (ic *ItemCategory) UnmarshalJSON(b []byte) error { - var s string - json.Unmarshal(b, &s) - category := ItemCategory(s) - switch category { - case Login, Password, Server, Database, CreditCard, Membership, Passport, SoftwareLicense, - OutdoorLicense, SecureNote, WirelessRouter, BankAccount, DriverLicense, Identity, RewardProgram, - Document, EmailAccount, SocialSecurityNumber, ApiCredential: - *ic = category - default: - *ic = Custom - } - - return nil -} - -// Item represents an item returned to the consumer -type Item struct { - ID string `json:"id"` - Title string `json:"title"` - - URLs []ItemURL `json:"urls,omitempty"` - Favorite bool `json:"favorite,omitempty"` - Tags []string `json:"tags,omitempty"` - Version int `json:"version,omitempty"` - Trashed bool `json:"trashed,omitempty"` - - Vault ItemVault `json:"vault"` - Category ItemCategory `json:"category,omitempty"` // TODO: switch this to `category` - - Sections []*ItemSection `json:"sections,omitempty"` - Fields []*ItemField `json:"fields,omitempty"` - Files []*File `json:"files,omitempty"` - - LastEditedBy string `json:"lastEditedBy,omitempty"` - CreatedAt time.Time `json:"createdAt,omitempty"` - UpdatedAt time.Time `json:"updatedAt,omitempty"` -} - -// ItemVault represents the Vault the Item is found in -type ItemVault struct { - ID string `json:"id"` -} - -// ItemURL is a simplified item URL -type ItemURL struct { - Primary bool `json:"primary,omitempty"` - URL string `json:"href"` -} - -// ItemSection Representation of a Section on an item -type ItemSection struct { - ID string `json:"id,omitempty"` - Label string `json:"label,omitempty"` -} - -// GeneratorRecipe Representation of a "recipe" used to generate a field -type GeneratorRecipe struct { - Length int `json:"length,omitempty"` - CharacterSets []string `json:"characterSets,omitempty"` -} - -// ItemField Representation of a single field on an Item -type ItemField struct { - ID string `json:"id"` - Section *ItemSection `json:"section,omitempty"` - Type string `json:"type"` - Purpose string `json:"purpose,omitempty"` - Label string `json:"label,omitempty"` - Value string `json:"value,omitempty"` - Generate bool `json:"generate,omitempty"` - Recipe *GeneratorRecipe `json:"recipe,omitempty"` - Entropy float64 `json:"entropy,omitempty"` -} - -// Get Retrieve the value of a field on the item by its label. To specify a -// field from a specific section pass in
.. If -// no field matching the selector is found return "". -func (i *Item) GetValue(field string) string { - if i == nil || len(i.Fields) == 0 { - return "" - } - - sectionFilter := false - sectionLabel := "" - fieldLabel := field - if strings.Contains(field, ".") { - parts := strings.Split(field, ".") - - // Test to make sure the . isn't the last character - if len(parts) == 2 { - sectionFilter = true - sectionLabel = parts[0] - fieldLabel = parts[1] - } - } - - for _, f := range i.Fields { - if sectionFilter { - if f.Section != nil { - if sectionLabel != i.SectionLabelForID(f.Section.ID) { - continue - } - } - } - - if fieldLabel == f.Label { - return f.Value - } - } - - return "" -} - -func (i *Item) SectionLabelForID(id string) string { - if i != nil || len(i.Sections) > 0 { - for _, s := range i.Sections { - if s.ID == id { - return s.Label - } - } - } - - return "" -} diff --git a/vendor/github.com/1Password/connect-sdk-go/onepassword/vaults.go b/vendor/github.com/1Password/connect-sdk-go/onepassword/vaults.go deleted file mode 100644 index 03844adf..00000000 --- a/vendor/github.com/1Password/connect-sdk-go/onepassword/vaults.go +++ /dev/null @@ -1,46 +0,0 @@ -package onepassword - -import ( - "encoding/json" - "time" -) - -// Vault represents a 1password Vault -type Vault struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - - AttrVersion int `json:"attributeVersion,omitempty"` - ContentVersoin int `json:"contentVersion,omitempty"` - Items int `json:"items,omitempty"` - Type VaultType `json:"type,omitempty"` - - CreatedAt time.Time `json:"createdAt,omitempty"` - UpdatedAt time.Time `json:"updatedAt,omitempty"` -} - -// VaultType Representation of what the Vault Type is -type VaultType string - -const ( - PersonalVault VaultType = "PERSONAL" - EveryoneVault VaultType = "EVERYONE" - TransferVault VaultType = "TRANSFER" - UserCreatedVault VaultType = "USER_CREATED" - UnknownVault VaultType = "UNKNOWN" -) - -// UnmarshalJSON Unmarshall Vault Type enum strings to Go string enums -func (vt *VaultType) UnmarshalJSON(b []byte) error { - var s string - json.Unmarshal(b, &s) - vaultType := VaultType(s) - switch vaultType { - case PersonalVault, EveryoneVault, TransferVault, UserCreatedVault: - *vt = vaultType - default: - *vt = UnknownVault - } - return nil -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/.travis.yml b/vendor/github.com/AlecAivazis/survey/v2/.travis.yml deleted file mode 100644 index f96db1ac..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -language: go - -go: - - 1.12 - -os: - - linux - - linux-ppc64le - - osx - - windows - -go_import_path: github.com/AlecAivazis/survey/v2 - -before_install: - - go get github.com/alecaivazis/run - -install: - - run install-deps - -script: - - run tests - # - run autoplay-tests diff --git a/vendor/github.com/AlecAivazis/survey/v2/CONTRIBUTING.md b/vendor/github.com/AlecAivazis/survey/v2/CONTRIBUTING.md deleted file mode 100644 index a84e0606..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/CONTRIBUTING.md +++ /dev/null @@ -1,77 +0,0 @@ -# Contributing to Survey - -🎉🎉 First off, thanks for the interest in contributing to `survey`! 🎉🎉 - -The following is a set of guidelines to follow when contributing to this package. These are not hard rules, please use common sense and feel free to propose changes to this document in a pull request. - -## Table of Contents - -1. [Code of Conduct](#code-of-conduct) -1. [Getting Help](#getting-help) -1. [Filing a Bug Report](#how-to-file-a-bug-report) -1. [Suggesting an API change](#suggesting-an-api-change) -1. [Submitting a Contribution](#submitting-a-contribution) -1. [Writing and Running Tests](#writing-and-running-tests) - -## Code of Conduct - -This project and its contibutors are expected to uphold the [Go Community Code of Conduct](https://golang.org/conduct). By participating, you are expected to follow these guidelines. - -## Getting help - -Feel free to [open up an issue](https://github.com/AlecAivazis/survey/v2/issues/new) on GitHub when asking a question so others will be able to find it. Please remember to tag the issue with the `Question` label so the maintainers can get to your question as soon as possible. If the question is urgent, feel free to reach out to `@AlecAivazis` directly in the gophers slack channel. - -## How to file a bug report - -Bugs are tracked using the Github Issue tracker. When filing a bug, please remember to label the issue as a `Bug` and answer/provide the following: - -1. What operating system and terminal are you using? -1. An example that showcases the bug. -1. What did you expect to see? -1. What did you see instead? - -## Suggesting an API change - -If you have an idea, I'm more than happy to discuss it. Please open an issue and we can work through it. In order to maintain some sense of stability, additions to the top-level API are taken just as seriously as changes that break it. Adding stuff is much easier than removing it. - -## Submitting a contribution - -In order to maintain stability, most features get fully integrated in more than one PR. This allows for more opportunity to think through each API change without amassing large amounts of tech debt and API changes at once. If your feature can be broken into separate chunks, it will be able to be reviewed much quicker. For example, if the PR that implemented the `Validate` field was submitted in a PR separately from one that included `survey.Required`, it would be able to get merge without having to decide how many different `Validators` we want to provide as part of `survey`'s API. - -When submitting a contribution, - -- Provide a description of the feature or change -- Reference the ticket addressed by the PR if there is one -- Following community standards, add comments for all exported members so that all necessary information is available on godocs -- Remember to update the project README.md with changes to the high-level API -- Include both positive and negative unit tests (when applicable) -- Contributions with visual ramifications or interaction changes should be accompanied with the appropriate `go-expect` tests. For more information on writing these tests, see [Writing and Running Tests](#writing-and-running-tests) - -## Writing and running tests - -When submitting features, please add as many units tests as necessary to test both positive and negative cases. - -Integration tests for survey uses [go-expect](https://github.com/Netflix/go-expect) to expect a match on stdout and respond on stdin. Since `os.Stdout` in a `go test` process is not a TTY, you need a way to interpret terminal / ANSI escape sequences for things like `CursorLocation`. The stdin/stdout handled by `go-expect` is also multiplexed to a [virtual terminal](https://github.com/hinshun/vt10x). - -For example, you can extend the tests for Input by specifying the following test case: - -```go -{ - "Test Input prompt interaction", // Name of the test. - &Input{ // An implementation of the survey.Prompt interface. - Message: "What is your name?", - }, - func(c *expect.Console) { // An expect procedure. You can expect strings / regexps and - c.ExpectString("What is your name?") // write back strings / bytes to its psuedoterminal for survey. - c.SendLine("Johnny Appleseed") - c.ExpectEOF() // Nothing is read from the tty without an expect, and once an - // expectation is met, no further bytes are read. End your - // procedure with `c.ExpectEOF()` to read until survey finishes. - }, - "Johnny Appleseed", // The expected result. -} -``` - -If you want to write your own `go-expect` test from scratch, you'll need to instantiate a virtual terminal, -multiplex it into an `*expect.Console`, and hook up its tty with survey's optional stdio. Please see `go-expect` -[documentation](https://godoc.org/github.com/Netflix/go-expect) for more detail. diff --git a/vendor/github.com/AlecAivazis/survey/v2/Gopkg.lock b/vendor/github.com/AlecAivazis/survey/v2/Gopkg.lock deleted file mode 100644 index b764f308..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/Gopkg.lock +++ /dev/null @@ -1,78 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - branch = "master" - name = "github.com/Netflix/go-expect" - packages = ["."] - revision = "c93bf25de8e869da25cf26bcd2932b36141f61ae" - -[[projects]] - name = "github.com/davecgh/go-spew" - packages = ["spew"] - revision = "346938d642f2ec3594ed81d874461961cd0faa76" - version = "v1.1.0" - -[[projects]] - branch = "master" - name = "github.com/hinshun/vt10x" - packages = ["."] - revision = "1954e646417484a2a687ea344edade2c2b6523c8" - -[[projects]] - branch = "master" - name = "github.com/kballard/go-shellquote" - packages = ["."] - revision = "95032a82bc518f77982ea72343cc1ade730072f0" - -[[projects]] - name = "github.com/kr/pty" - packages = ["."] - revision = "282ce0e5322c82529687d609ee670fac7c7d917c" - version = "v1.1.1" - -[[projects]] - name = "github.com/mattn/go-colorable" - packages = ["."] - revision = "167de6bfdfba052fa6b2d3664c8f5272e23c9072" - version = "v0.0.9" - -[[projects]] - name = "github.com/mattn/go-isatty" - packages = ["."] - revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39" - version = "v0.0.3" - -[[projects]] - branch = "master" - name = "github.com/mgutz/ansi" - packages = ["."] - revision = "9520e82c474b0a04dd04f8a40959027271bab992" - -[[projects]] - name = "github.com/pmezard/go-difflib" - packages = ["difflib"] - revision = "792786c7400a136282c1664665ae0a8db921c6c2" - version = "v1.0.0" - -[[projects]] - name = "github.com/stretchr/testify" - packages = [ - "assert", - "require" - ] - revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71" - version = "v1.2.1" - -[[projects]] - branch = "master" - name = "golang.org/x/sys" - packages = ["unix"] - revision = "9527bec2660bd847c050fda93a0f0c6dee0800bb" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - inputs-digest = "371508ebad4798adc38a118f858b5c17a65b58594203548f9feb74cb781dd907" - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/AlecAivazis/survey/v2/Gopkg.toml b/vendor/github.com/AlecAivazis/survey/v2/Gopkg.toml deleted file mode 100644 index 8acb825a..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/Gopkg.toml +++ /dev/null @@ -1,54 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - - -[[constraint]] - branch = "master" - name = "github.com/Netflix/go-expect" - -[[constraint]] - branch = "master" - name = "github.com/hinshun/vt10x" - -[[constraint]] - name = "github.com/mattn/go-isatty" - version = "0.0.3" - -[[constraint]] - branch = "master" - name = "github.com/mgutz/ansi" - -[[constraint]] - name = "github.com/stretchr/testify" - version = "1.2.1" - -[prune] - go-tests = true - unused-packages = true - -[[constraint]] - branch = "master" - name = "github.com/kballard/go-shellquote" diff --git a/vendor/github.com/AlecAivazis/survey/v2/LICENSE b/vendor/github.com/AlecAivazis/survey/v2/LICENSE deleted file mode 100644 index 07a709ae..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Alec Aivazis - -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/github.com/AlecAivazis/survey/v2/README.md b/vendor/github.com/AlecAivazis/survey/v2/README.md deleted file mode 100644 index 4569ad7d..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/README.md +++ /dev/null @@ -1,472 +0,0 @@ -# Survey - -[![Build Status](https://travis-ci.org/AlecAivazis/survey.svg?branch=feature%2Fpretty)](https://travis-ci.org/AlecAivazis/survey) -[![GoDoc](http://img.shields.io/badge/godoc-reference-5272B4.svg)](https://pkg.go.dev/github.com/AlecAivazis/survey/v2) - -A library for building interactive prompts. - - - -```go -package main - -import ( - "fmt" - "github.com/AlecAivazis/survey/v2" -) - -// the questions to ask -var qs = []*survey.Question{ - { - Name: "name", - Prompt: &survey.Input{Message: "What is your name?"}, - Validate: survey.Required, - Transform: survey.Title, - }, - { - Name: "color", - Prompt: &survey.Select{ - Message: "Choose a color:", - Options: []string{"red", "blue", "green"}, - Default: "red", - }, - }, - { - Name: "age", - Prompt: &survey.Input{Message: "How old are you?"}, - }, -} - -func main() { - // the answers will be written to this struct - answers := struct { - Name string // survey will match the question and field names - FavoriteColor string `survey:"color"` // or you can tag fields to match a specific name - Age int // if the types don't match, survey will convert it - }{} - - // perform the questions - err := survey.Ask(qs, &answers) - if err != nil { - fmt.Println(err.Error()) - return - } - - fmt.Printf("%s chose %s.", answers.Name, answers.FavoriteColor) -} -``` - -## Table of Contents - -1. [Examples](#examples) -1. [Running the Prompts](#running-the-prompts) -1. [Prompts](#prompts) - 1. [Input](#input) - 1. [Suggestion Options](#suggestion-options) - 1. [Multiline](#multiline) - 1. [Password](#password) - 1. [Confirm](#confirm) - 1. [Select](#select) - 1. [MultiSelect](#multiselect) - 1. [Editor](#editor) -1. [Filtering Options](#filtering-options) -1. [Validation](#validation) - 1. [Built-in Validators](#built-in-validators) -1. [Help Text](#help-text) - 1. [Changing the input rune](#changing-the-input-rune) -1. [Changing the Icons ](#changing-the-icons) -1. [Custom Types](#custom-types) -1. [Testing](#testing) -1. [FAQ](#faq) - -## Examples - -Examples can be found in the `examples/` directory. Run them -to see basic behavior: - -```bash -go get github.com/AlecAivazis/survey/v2 - -cd $GOPATH/src/github.com/AlecAivazis/survey - -go run examples/simple.go -go run examples/validation.go -``` - -## Running the Prompts - -There are two primary ways to execute prompts and start collecting information from your users: `Ask` and -`AskOne`. The primary difference is whether you are interested in collecting a single piece of information -or if you have a list of questions to ask whose answers should be collected in a single struct. -For most basic usecases, `Ask` should be enough. However, for surveys with complicated branching logic, -we recommend that you break out your questions into multiple calls to both of these functions to fit your needs. - -### Configuring the Prompts - -Most prompts take fine-grained configuration through fields on the structs you instantiate. It is also -possible to change survey's default behaviors by passing `AskOpts` to either `Ask` or `AskOne`. Examples -in this document will do both interchangeably: - -```golang -prompt := &Select{ - Message: "Choose a color:", - Options: []string{"red", "blue", "green"}, - // can pass a validator directly - Validate: survey.Required, -} - -// or define a default for the single call to `AskOne` -// the answer will get written to the color variable -survey.AskOne(prompt, &color, survey.WithValidator(survey.Required)) - -// or define a default for every entry in a list of questions -// the answer will get copied into the matching field of the struct as shown above -survey.Ask(questions, &answers, survey.WithValidator(survey.Required)) -``` - -## Prompts - -### Input - - - -```golang -name := "" -prompt := &survey.Input{ - Message: "ping", -} -survey.AskOne(prompt, &name) -``` - -#### Suggestion Options - - - -```golang -file := "" -prompt := &survey.Input{ - Message: "inform a file to save:", - Suggest: func (toComplete string) []string { - files, _ := filepath.Glob(toComplete + "*") - return files - }, -} -} -survey.AskOne(prompt, &file) -``` - -### Multiline - - - -```golang -text := "" -prompt := &survey.Multiline{ - Message: "ping", -} -survey.AskOne(prompt, &text) -``` - -### Password - - - -```golang -password := "" -prompt := &survey.Password{ - Message: "Please type your password", -} -survey.AskOne(prompt, &password) -``` - -### Confirm - - - -```golang -name := false -prompt := &survey.Confirm{ - Message: "Do you like pie?", -} -survey.AskOne(prompt, &name) -``` - -### Select - - - -```golang -color := "" -prompt := &survey.Select{ - Message: "Choose a color:", - Options: []string{"red", "blue", "green"}, -} -survey.AskOne(prompt, &color) -``` - -Fields and values that come from a `Select` prompt can be one of two different things. If you pass an `int` -the field will have the value of the selected index. If you instead pass a string, the string value selected -will be written to the field. - -The user can also press `esc` to toggle the ability cycle through the options with the j and k keys to do down and up respectively. - -By default, the select prompt is limited to showing 7 options at a time -and will paginate lists of options longer than that. This can be changed a number of ways: - -```golang -// as a field on a single select -prompt := &survey.MultiSelect{..., PageSize: 10} - -// or as an option to Ask or AskOne -survey.AskOne(prompt, &days, survey.WithPageSize(10)) -``` - -### MultiSelect - -![Example](img/multi-select-all-none.gif) - -```golang -days := []string{} -prompt := &survey.MultiSelect{ - Message: "What days do you prefer:", - Options: []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}, -} -survey.AskOne(prompt, &days) -``` - -Fields and values that come from a `MultiSelect` prompt can be one of two different things. If you pass an `int` -the field will have a slice of the selected indices. If you instead pass a string, a slice of the string values -selected will be written to the field. - -The user can also press `esc` to toggle the ability cycle through the options with the j and k keys to do down and up respectively. - -By default, the MultiSelect prompt is limited to showing 7 options at a time -and will paginate lists of options longer than that. This can be changed a number of ways: - -```golang -// as a field on a single select -prompt := &survey.MultiSelect{..., PageSize: 10} - -// or as an option to Ask or AskOne -survey.AskOne(prompt, &days, survey.WithPageSize(10)) -``` - -### Editor - -Launches the user's preferred editor (defined by the \$VISUAL or \$EDITOR environment variables) on a -temporary file. Once the user exits their editor, the contents of the temporary file are read in as -the result. If neither of those are present, notepad (on Windows) or vim (Linux or Mac) is used. - -You can also specify a [pattern](https://golang.org/pkg/io/ioutil/#TempFile) for the name of the temporary file. This -can be useful for ensuring syntax highlighting matches your usecase. - -```golang -prompt := &survey.Editor{ - Message: "Shell code snippet", - FileName: "*.sh", -} - -survey.AskOne(prompt, &content) -``` - -## Filtering Options - -By default, the user can filter for options in Select and MultiSelects by typing while the prompt -is active. This will filter out all options that don't contain the typed string anywhere in their name, ignoring case. - -A custom filter function can also be provided to change this behavior: - -```golang -func myFilter(filterValue string, optValue string, optIndex int) bool { - // only include the option if it includes the filter and has length greater than 5 - return strings.Contains(optValue, filterValue) && len(optValue) >= 5 -} - -// configure it for a specific prompt -&Select{ - Message: "Choose a color:", - Options: []string{"red", "blue", "green"}, - Filter: myFilter, -} - -// or define a default for all of the questions -survey.AskOne(prompt, &color, survey.WithFilter(myFilter)) -``` - -## Keeping the filter active - -By default the filter will disappear if the user selects one of the filtered elements. Once the user selects one element the filter setting is gone. - -However the user can prevent this from happening and keep the filter active for multiple selections in a e.g. MultiSelect: - -```golang -// configure it for a specific prompt -&Select{ - Message: "Choose a color:", - Options: []string{"light-green", "green", "dark-green", "red"}, - KeepFilter: true, -} - -// or define a default for all of the questions -survey.AskOne(prompt, &color, survey.WithKeepFilter(true)) -``` - -## Validation - -Validating individual responses for a particular question can be done by defining a -`Validate` field on the `survey.Question` to be validated. This function takes an -`interface{}` type and returns an error to show to the user, prompting them for another -response. Like usual, validators can be provided directly to the prompt or with `survey.WithValidator`: - -```golang -q := &survey.Question{ - Prompt: &survey.Input{Message: "Hello world validation"}, - Validate: func (val interface{}) error { - // since we are validating an Input, the assertion will always succeed - if str, ok := val.(string) ; !ok || len(str) > 10 { - return errors.New("This response cannot be longer than 10 characters.") - } - return nil - }, -} - -color := "" -prompt := &survey.Input{ Message: "Whats your name?" } - -// you can pass multiple validators here and survey will make sure each one passes -survey.AskOne(prompt, &color, survey.WithValidator(survey.Required)) -``` - -### Built-in Validators - -`survey` comes prepackaged with a few validators to fit common situations. Currently these -validators include: - -| name | valid types | description | notes | -| ------------ | ----------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------- | -| Required | any | Rejects zero values of the response type | Boolean values pass straight through since the zero value (false) is a valid response | -| MinLength(n) | string | Enforces that a response is at least the given length | | -| MaxLength(n) | string | Enforces that a response is no longer than the given length | | - -## Help Text - -All of the prompts have a `Help` field which can be defined to provide more information to your users: - - - -```golang -&survey.Input{ - Message: "What is your phone number:", - Help: "Phone number should include the area code", -} -``` - -### Changing the input rune - -In some situations, `?` is a perfectly valid response. To handle this, you can change the rune that survey -looks for with `WithHelpInput`: - -```golang -import ( - "github.com/AlecAivazis/survey/v2" -) - -number := "" -prompt := &survey.Input{ - Message: "If you have this need, please give me a reasonable message.", - Help: "I couldn't come up with one.", -} - -survey.AskOne(prompt, &number, survey.WithHelpInput('^')) -``` - -## Changing the Icons - -Changing the icons and their color/format can be done by passing the `WithIcons` option. The format -follows the patterns outlined [here](https://github.com/mgutz/ansi#style-format). For example: - -```golang -import ( - "github.com/AlecAivazis/survey/v2" -) - -number := "" -prompt := &survey.Input{ - Message: "If you have this need, please give me a reasonable message.", - Help: "I couldn't come up with one.", -} - -survey.AskOne(prompt, &number, survey.WithIcons(func(icons *survey.IconSet) { - // you can set any icons - icons.Question.Text = "⁇" - // for more information on formatting the icons, see here: https://github.com/mgutz/ansi#style-format - icons.Question.Format = "yellow+hb" -})) -``` - -The icons and their default text and format are summarized below: - -| name | text | format | description | -| -------------- | ---- | ---------- | ------------------------------------------------------------- | -| Error | X | red | Before an error | -| Help | i | cyan | Before help text | -| Question | ? | green+hb | Before the message of a prompt | -| SelectFocus | > | green | Marks the current focus in `Select` and `MultiSelect` prompts | -| UnmarkedOption | [ ] | default+hb | Marks an unselected option in a `MultiSelect` prompt | -| MarkedOption | [x] | cyan+b | Marks a chosen selection in a `MultiSelect` prompt | - -## Custom Types - -survey will assign prompt answers to your custom types if they implement this interface: - -```golang -type Settable interface { - WriteAnswer(field string, value interface{}) error -} -``` - -Here is an example how to use them: - -```golang -type MyValue struct { - value string -} -func (my *MyValue) WriteAnswer(name string, value interface{}) error { - my.value = value.(string) -} - -myval := MyValue{} -survey.AskOne( - &survey.Input{ - Message: "Enter something:", - }, - &myval -) -``` - -## Testing - -You can test your program's interactive prompts using [go-expect](https://github.com/Netflix/go-expect). The library -can be used to expect a match on stdout and respond on stdin. Since `os.Stdout` in a `go test` process is not a TTY, -if you are manipulating the cursor or using `survey`, you will need a way to interpret terminal / ANSI escape sequences -for things like `CursorLocation`. `vt10x.NewVT10XConsole` will create a `go-expect` console that also multiplexes -stdio to an in-memory [virtual terminal](https://github.com/hinshun/vt10x). - -For some examples, you can see any of the tests in this repo. - -## FAQ - -### Why isn't sending a SIGINT (aka. CTRL-C) signal working? - -When you send an interrupt signal to the process, it only interrupts the current prompt instead of the entire process. This manifests in a `github.com/AlecAivazis/survey/v2/terminal.InterruptErr` being returned from `Ask` and `AskOne`. If you want to stop the process, handle the returned error in your code: - -```go -err := survey.AskOne(prompt, &myVar) -if err == terminal.InterruptErr { - fmt.Println("interrupted") - - os.Exit(0) -} else if err != nil { - panic(err) -} -``` diff --git a/vendor/github.com/AlecAivazis/survey/v2/_tasks.hcl b/vendor/github.com/AlecAivazis/survey/v2/_tasks.hcl deleted file mode 100644 index ae970f33..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/_tasks.hcl +++ /dev/null @@ -1,19 +0,0 @@ -task "install-deps" { - description = "Install all of package dependencies" - pipeline = [ - "go get {{.files}}", - ] -} - -task "tests" { - description = "Run the test suite" - command = "go test {{.files}}" - environment { - GOFLAGS = "-mod=vendor" - } -} - -variables { - files = "$(go list -v ./... | grep -iEv \"tests|examples\")" -} - diff --git a/vendor/github.com/AlecAivazis/survey/v2/confirm.go b/vendor/github.com/AlecAivazis/survey/v2/confirm.go deleted file mode 100644 index 8e5d7efa..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/confirm.go +++ /dev/null @@ -1,153 +0,0 @@ -package survey - -import ( - "fmt" - "regexp" -) - -// Confirm is a regular text input that accept yes/no answers. Response type is a bool. -type Confirm struct { - Renderer - Message string - Default bool - Help string -} - -// data available to the templates when processing -type ConfirmTemplateData struct { - Confirm - Answer string - ShowHelp bool - Config *PromptConfig -} - -// Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format -var ConfirmQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }} {{color "reset"}} -{{- if .Answer}} - {{- color "cyan"}}{{.Answer}}{{color "reset"}}{{"\n"}} -{{- else }} - {{- if and .Help (not .ShowHelp)}}{{color "cyan"}}[{{ .Config.HelpInput }} for help]{{color "reset"}} {{end}} - {{- color "white"}}{{if .Default}}(Y/n) {{else}}(y/N) {{end}}{{color "reset"}} -{{- end}}` - -// the regex for answers -var ( - yesRx = regexp.MustCompile("^(?i:y(?:es)?)$") - noRx = regexp.MustCompile("^(?i:n(?:o)?)$") -) - -func yesNo(t bool) string { - if t { - return "Yes" - } - return "No" -} - -func (c *Confirm) getBool(showHelp bool, config *PromptConfig) (bool, error) { - cursor := c.NewCursor() - rr := c.NewRuneReader() - rr.SetTermMode() - defer rr.RestoreTermMode() - - // start waiting for input - for { - line, err := rr.ReadLine(0) - if err != nil { - return false, err - } - // move back up a line to compensate for the \n echoed from terminal - cursor.PreviousLine(1) - val := string(line) - - // get the answer that matches the - var answer bool - switch { - case yesRx.Match([]byte(val)): - answer = true - case noRx.Match([]byte(val)): - answer = false - case val == "": - answer = c.Default - case val == config.HelpInput && c.Help != "": - err := c.Render( - ConfirmQuestionTemplate, - ConfirmTemplateData{ - Confirm: *c, - ShowHelp: true, - Config: config, - }, - ) - if err != nil { - // use the default value and bubble up - return c.Default, err - } - showHelp = true - continue - default: - // we didnt get a valid answer, so print error and prompt again - if err := c.Error(config, fmt.Errorf("%q is not a valid answer, please try again.", val)); err != nil { - return c.Default, err - } - err := c.Render( - ConfirmQuestionTemplate, - ConfirmTemplateData{ - Confirm: *c, - ShowHelp: showHelp, - Config: config, - }, - ) - if err != nil { - // use the default value and bubble up - return c.Default, err - } - continue - } - return answer, nil - } - // should not get here - return c.Default, nil -} - -/* -Prompt prompts the user with a simple text field and expects a reply followed -by a carriage return. - - likesPie := false - prompt := &survey.Confirm{ Message: "What is your name?" } - survey.AskOne(prompt, &likesPie) -*/ -func (c *Confirm) Prompt(config *PromptConfig) (interface{}, error) { - // render the question template - err := c.Render( - ConfirmQuestionTemplate, - ConfirmTemplateData{ - Confirm: *c, - Config: config, - }, - ) - if err != nil { - return "", err - } - - // get input and return - return c.getBool(false, config) -} - -// Cleanup overwrite the line with the finalized formatted version -func (c *Confirm) Cleanup(config *PromptConfig, val interface{}) error { - // if the value was previously true - ans := yesNo(val.(bool)) - - // render the template - return c.Render( - ConfirmQuestionTemplate, - ConfirmTemplateData{ - Confirm: *c, - Answer: ans, - Config: config, - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/core/template.go b/vendor/github.com/AlecAivazis/survey/v2/core/template.go deleted file mode 100644 index 24dade33..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/core/template.go +++ /dev/null @@ -1,91 +0,0 @@ -package core - -import ( - "bytes" - "sync" - "text/template" - - "github.com/mgutz/ansi" -) - -// DisableColor can be used to make testing reliable -var DisableColor = false - -var TemplateFuncsWithColor = map[string]interface{}{ - // Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format - "color": ansi.ColorCode, -} - -var TemplateFuncsNoColor = map[string]interface{}{ - // Templates without Color formatting. For layout/ testing. - "color": func(color string) string { - return "" - }, -} - -//RunTemplate returns two formatted strings given a template and -//the data it requires. The first string returned is generated for -//user-facing output and may or may not contain ANSI escape codes -//for colored output. The second string does not contain escape codes -//and can be used by the renderer for layout purposes. -func RunTemplate(tmpl string, data interface{}) (string, string, error) { - tPair, err := getTemplatePair(tmpl) - if err != nil { - return "", "", err - } - userBuf := bytes.NewBufferString("") - err = tPair[0].Execute(userBuf, data) - if err != nil { - return "", "", err - } - layoutBuf := bytes.NewBufferString("") - err = tPair[1].Execute(layoutBuf, data) - if err != nil { - return userBuf.String(), "", err - } - return userBuf.String(), layoutBuf.String(), err -} - -var ( - memoizedGetTemplate = map[string][2]*template.Template{} - - memoMutex = &sync.RWMutex{} -) - -//getTemplatePair returns a pair of compiled templates where the -//first template is generated for user-facing output and the -//second is generated for use by the renderer. The second -//template does not contain any color escape codes, whereas -//the first template may or may not depending on DisableColor. -func getTemplatePair(tmpl string) ([2]*template.Template, error) { - memoMutex.RLock() - if t, ok := memoizedGetTemplate[tmpl]; ok { - memoMutex.RUnlock() - return t, nil - } - memoMutex.RUnlock() - - templatePair := [2]*template.Template{nil, nil} - - templateNoColor, err := template.New("prompt").Funcs(TemplateFuncsNoColor).Parse(tmpl) - if err != nil { - return [2]*template.Template{}, err - } - - templatePair[1] = templateNoColor - - if DisableColor { - templatePair[0] = templatePair[1] - } else { - templateWithColor, err := template.New("prompt").Funcs(TemplateFuncsWithColor).Parse(tmpl) - templatePair[0] = templateWithColor - if err != nil { - return [2]*template.Template{}, err - } - } - - memoMutex.Lock() - memoizedGetTemplate[tmpl] = templatePair - memoMutex.Unlock() - return templatePair, nil -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/core/write.go b/vendor/github.com/AlecAivazis/survey/v2/core/write.go deleted file mode 100644 index 47d0e498..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/core/write.go +++ /dev/null @@ -1,356 +0,0 @@ -package core - -import ( - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "time" -) - -// the tag used to denote the name of the question -const tagName = "survey" - -// Settable allow for configuration when assigning answers -type Settable interface { - WriteAnswer(field string, value interface{}) error -} - -// OptionAnswer is the return type of Selects/MultiSelects that lets the appropriate information -// get copied to the user's struct -type OptionAnswer struct { - Value string - Index int -} - -func OptionAnswerList(incoming []string) []OptionAnswer { - list := []OptionAnswer{} - for i, opt := range incoming { - list = append(list, OptionAnswer{Value: opt, Index: i}) - } - return list -} - -func WriteAnswer(t interface{}, name string, v interface{}) (err error) { - // if the field is a custom type - if s, ok := t.(Settable); ok { - // use the interface method - return s.WriteAnswer(name, v) - } - - // the target to write to - target := reflect.ValueOf(t) - // the value to write from - value := reflect.ValueOf(v) - - // make sure we are writing to a pointer - if target.Kind() != reflect.Ptr { - return errors.New("you must pass a pointer as the target of a Write operation") - } - // the object "inside" of the target pointer - elem := target.Elem() - - // handle the special types - switch elem.Kind() { - // if we are writing to a struct - case reflect.Struct: - // if we are writing to an option answer than we want to treat - // it like a single thing and not a place to deposit answers - if elem.Type().Name() == "OptionAnswer" { - // copy the value over to the normal struct - return copy(elem, value) - } - - // get the name of the field that matches the string we were given - fieldIndex, err := findFieldIndex(elem, name) - // if something went wrong - if err != nil { - // bubble up - return err - } - field := elem.Field(fieldIndex) - // handle references to the Settable interface aswell - if s, ok := field.Interface().(Settable); ok { - // use the interface method - return s.WriteAnswer(name, v) - } - if field.CanAddr() { - if s, ok := field.Addr().Interface().(Settable); ok { - // use the interface method - return s.WriteAnswer(name, v) - } - } - - // copy the value over to the normal struct - return copy(field, value) - case reflect.Map: - mapType := reflect.TypeOf(t).Elem() - if mapType.Key().Kind() != reflect.String { - return errors.New("answer maps key must be of type string") - } - - // copy only string value/index value to map if, - // map is not of type interface and is 'OptionAnswer' - if value.Type().Name() == "OptionAnswer" { - if kval := mapType.Elem().Kind(); kval == reflect.String { - mt := *t.(*map[string]string) - mt[name] = value.FieldByName("Value").String() - return nil - } else if kval == reflect.Int { - mt := *t.(*map[string]int) - mt[name] = int(value.FieldByName("Index").Int()) - return nil - } - } - - if mapType.Elem().Kind() != reflect.Interface { - return errors.New("answer maps must be of type map[string]interface") - } - mt := *t.(*map[string]interface{}) - mt[name] = value.Interface() - return nil - } - // otherwise just copy the value to the target - return copy(elem, value) -} - -type errFieldNotMatch struct { - questionName string -} - -func (err errFieldNotMatch) Error() string { - return fmt.Sprintf("could not find field matching %v", err.questionName) -} - -func (err errFieldNotMatch) Is(target error) bool { // implements the dynamic errors.Is interface. - if target != nil { - if name, ok := IsFieldNotMatch(target); ok { - // if have a filled questionName then perform "deeper" comparison. - return name == "" || err.questionName == "" || name == err.questionName - } - } - - return false -} - -// IsFieldNotMatch reports whether an "err" is caused by a non matching field. -// It returns the Question.Name that couldn't be matched with a destination field. -// -// Usage: -// err := survey.Ask(qs, &v); -// if err != nil { -// if name, ok := core.IsFieldNotMatch(err); ok { -// [...name is the not matched question name] -// } -// } -func IsFieldNotMatch(err error) (string, bool) { - if err != nil { - if v, ok := err.(errFieldNotMatch); ok { - return v.questionName, true - } - } - - return "", false -} - -// BUG(AlecAivazis): the current implementation might cause weird conflicts if there are -// two fields with same name that only differ by casing. -func findFieldIndex(s reflect.Value, name string) (int, error) { - // the type of the value - sType := s.Type() - - // first look for matching tags so we can overwrite matching field names - for i := 0; i < sType.NumField(); i++ { - // the field we are current scanning - field := sType.Field(i) - - // the value of the survey tag - tag := field.Tag.Get(tagName) - // if the tag matches the name we are looking for - if tag != "" && tag == name { - // then we found our index - return i, nil - } - } - - // then look for matching names - for i := 0; i < sType.NumField(); i++ { - // the field we are current scanning - field := sType.Field(i) - - // if the name of the field matches what we're looking for - if strings.ToLower(field.Name) == strings.ToLower(name) { - return i, nil - } - } - - // we didn't find the field - return -1, errFieldNotMatch{name} -} - -// isList returns true if the element is something we can Len() -func isList(v reflect.Value) bool { - switch v.Type().Kind() { - case reflect.Array, reflect.Slice: - return true - default: - return false - } -} - -// Write takes a value and copies it to the target -func copy(t reflect.Value, v reflect.Value) (err error) { - // if something ends up panicing we need to catch it in a deferred func - defer func() { - if r := recover(); r != nil { - // if we paniced with an error - if _, ok := r.(error); ok { - // cast the result to an error object - err = r.(error) - } else if _, ok := r.(string); ok { - // otherwise we could have paniced with a string so wrap it in an error - err = errors.New(r.(string)) - } - } - }() - - // if we are copying from a string result to something else - if v.Kind() == reflect.String && v.Type() != t.Type() { - var castVal interface{} - var casterr error - vString := v.Interface().(string) - - switch t.Kind() { - case reflect.Bool: - castVal, casterr = strconv.ParseBool(vString) - case reflect.Int: - castVal, casterr = strconv.Atoi(vString) - case reflect.Int8: - var val64 int64 - val64, casterr = strconv.ParseInt(vString, 10, 8) - if casterr == nil { - castVal = int8(val64) - } - case reflect.Int16: - var val64 int64 - val64, casterr = strconv.ParseInt(vString, 10, 16) - if casterr == nil { - castVal = int16(val64) - } - case reflect.Int32: - var val64 int64 - val64, casterr = strconv.ParseInt(vString, 10, 32) - if casterr == nil { - castVal = int32(val64) - } - case reflect.Int64: - if t.Type() == reflect.TypeOf(time.Duration(0)) { - castVal, casterr = time.ParseDuration(vString) - } else { - castVal, casterr = strconv.ParseInt(vString, 10, 64) - } - case reflect.Uint: - var val64 uint64 - val64, casterr = strconv.ParseUint(vString, 10, 8) - if casterr == nil { - castVal = uint(val64) - } - case reflect.Uint8: - var val64 uint64 - val64, casterr = strconv.ParseUint(vString, 10, 8) - if casterr == nil { - castVal = uint8(val64) - } - case reflect.Uint16: - var val64 uint64 - val64, casterr = strconv.ParseUint(vString, 10, 16) - if casterr == nil { - castVal = uint16(val64) - } - case reflect.Uint32: - var val64 uint64 - val64, casterr = strconv.ParseUint(vString, 10, 32) - if casterr == nil { - castVal = uint32(val64) - } - case reflect.Uint64: - castVal, casterr = strconv.ParseUint(vString, 10, 64) - case reflect.Float32: - var val64 float64 - val64, casterr = strconv.ParseFloat(vString, 32) - if casterr == nil { - castVal = float32(val64) - } - case reflect.Float64: - castVal, casterr = strconv.ParseFloat(vString, 64) - default: - return fmt.Errorf("Unable to convert from string to type %s", t.Kind()) - } - - if casterr != nil { - return casterr - } - - t.Set(reflect.ValueOf(castVal)) - return - } - - // if we are copying from an OptionAnswer to something - if v.Type().Name() == "OptionAnswer" { - // copying an option answer to a string - if t.Kind() == reflect.String { - // copies the Value field of the struct - t.Set(reflect.ValueOf(v.FieldByName("Value").Interface())) - return - } - - // copying an option answer to an int - if t.Kind() == reflect.Int { - // copies the Index field of the struct - t.Set(reflect.ValueOf(v.FieldByName("Index").Interface())) - return - } - - // copying an OptionAnswer to an OptionAnswer - if t.Type().Name() == "OptionAnswer" { - t.Set(v) - return - } - - // we're copying an option answer to an incorrect type - return fmt.Errorf("Unable to convert from OptionAnswer to type %s", t.Kind()) - } - - // if we are copying from one slice or array to another - if isList(v) && isList(t) { - // loop over every item in the desired value - for i := 0; i < v.Len(); i++ { - // write to the target given its kind - switch t.Kind() { - // if its a slice - case reflect.Slice: - // an object of the correct type - obj := reflect.Indirect(reflect.New(t.Type().Elem())) - - // write the appropriate value to the obj and catch any errors - if err := copy(obj, v.Index(i)); err != nil { - return err - } - - // just append the value to the end - t.Set(reflect.Append(t, obj)) - // otherwise it could be an array - case reflect.Array: - // set the index to the appropriate value - copy(t.Slice(i, i+1).Index(0), v.Index(i)) - } - } - } else { - // set the value to the target - t.Set(v) - } - - // we're done - return -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/editor.go b/vendor/github.com/AlecAivazis/survey/v2/editor.go deleted file mode 100644 index ec6a1417..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/editor.go +++ /dev/null @@ -1,222 +0,0 @@ -package survey - -import ( - "bytes" - "io/ioutil" - "os" - "os/exec" - "runtime" - - "github.com/AlecAivazis/survey/v2/terminal" - shellquote "github.com/kballard/go-shellquote" -) - -/* -Editor launches an instance of the users preferred editor on a temporary file. -The editor to use is determined by reading the $VISUAL or $EDITOR environment -variables. If neither of those are present, notepad (on Windows) or vim -(others) is used. -The launch of the editor is triggered by the enter key. Since the response may -be long, it will not be echoed as Input does, instead, it print . -Response type is a string. - - message := "" - prompt := &survey.Editor{ Message: "What is your commit message?" } - survey.AskOne(prompt, &message) -*/ -type Editor struct { - Renderer - Message string - Default string - Help string - Editor string - HideDefault bool - AppendDefault bool - FileName string -} - -// data available to the templates when processing -type EditorTemplateData struct { - Editor - Answer string - ShowAnswer bool - ShowHelp bool - Config *PromptConfig -} - -// Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format -var EditorQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }} {{color "reset"}} -{{- if .ShowAnswer}} - {{- color "cyan"}}{{.Answer}}{{color "reset"}}{{"\n"}} -{{- else }} - {{- if and .Help (not .ShowHelp)}}{{color "cyan"}}[{{ .Config.HelpInput }} for help]{{color "reset"}} {{end}} - {{- if and .Default (not .HideDefault)}}{{color "white"}}({{.Default}}) {{color "reset"}}{{end}} - {{- color "cyan"}}[Enter to launch editor] {{color "reset"}} -{{- end}}` - -var ( - bom = []byte{0xef, 0xbb, 0xbf} - editor = "vim" -) - -func init() { - if runtime.GOOS == "windows" { - editor = "notepad" - } - if v := os.Getenv("VISUAL"); v != "" { - editor = v - } else if e := os.Getenv("EDITOR"); e != "" { - editor = e - } -} - -func (e *Editor) PromptAgain(config *PromptConfig, invalid interface{}, err error) (interface{}, error) { - initialValue := invalid.(string) - return e.prompt(initialValue, config) -} - -func (e *Editor) Prompt(config *PromptConfig) (interface{}, error) { - initialValue := "" - if e.Default != "" && e.AppendDefault { - initialValue = e.Default - } - return e.prompt(initialValue, config) -} - -func (e *Editor) prompt(initialValue string, config *PromptConfig) (interface{}, error) { - // render the template - err := e.Render( - EditorQuestionTemplate, - EditorTemplateData{ - Editor: *e, - Config: config, - }, - ) - if err != nil { - return "", err - } - - // start reading runes from the standard in - rr := e.NewRuneReader() - rr.SetTermMode() - defer rr.RestoreTermMode() - - cursor := e.NewCursor() - cursor.Hide() - defer cursor.Show() - - for { - r, _, err := rr.ReadRune() - if err != nil { - return "", err - } - if r == '\r' || r == '\n' { - break - } - if r == terminal.KeyInterrupt { - return "", terminal.InterruptErr - } - if r == terminal.KeyEndTransmission { - break - } - if string(r) == config.HelpInput && e.Help != "" { - err = e.Render( - EditorQuestionTemplate, - EditorTemplateData{ - Editor: *e, - ShowHelp: true, - Config: config, - }, - ) - if err != nil { - return "", err - } - } - continue - } - - // prepare the temp file - pattern := e.FileName - if pattern == "" { - pattern = "survey*.txt" - } - f, err := ioutil.TempFile("", pattern) - if err != nil { - return "", err - } - defer os.Remove(f.Name()) - - // write utf8 BOM header - // The reason why we do this is because notepad.exe on Windows determines the - // encoding of an "empty" text file by the locale, for example, GBK in China, - // while golang string only handles utf8 well. However, a text file with utf8 - // BOM header is not considered "empty" on Windows, and the encoding will then - // be determined utf8 by notepad.exe, instead of GBK or other encodings. - if _, err := f.Write(bom); err != nil { - return "", err - } - - // write initial value - if _, err := f.WriteString(initialValue); err != nil { - return "", err - } - - // close the fd to prevent the editor unable to save file - if err := f.Close(); err != nil { - return "", err - } - - // check is input editor exist - if e.Editor != "" { - editor = e.Editor - } - - stdio := e.Stdio() - - args, err := shellquote.Split(editor) - if err != nil { - return "", err - } - args = append(args, f.Name()) - - // open the editor - cmd := exec.Command(args[0], args[1:]...) - cmd.Stdin = stdio.In - cmd.Stdout = stdio.Out - cmd.Stderr = stdio.Err - cursor.Show() - if err := cmd.Run(); err != nil { - return "", err - } - - // raw is a BOM-unstripped UTF8 byte slice - raw, err := ioutil.ReadFile(f.Name()) - if err != nil { - return "", err - } - - // strip BOM header - text := string(bytes.TrimPrefix(raw, bom)) - - // check length, return default value on empty - if len(text) == 0 && !e.AppendDefault { - return e.Default, nil - } - - return text, nil -} - -func (e *Editor) Cleanup(config *PromptConfig, val interface{}) error { - return e.Render( - EditorQuestionTemplate, - EditorTemplateData{ - Editor: *e, - Answer: "", - ShowAnswer: true, - Config: config, - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/filter.go b/vendor/github.com/AlecAivazis/survey/v2/filter.go deleted file mode 100644 index 56f70267..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/filter.go +++ /dev/null @@ -1 +0,0 @@ -package survey diff --git a/vendor/github.com/AlecAivazis/survey/v2/input.go b/vendor/github.com/AlecAivazis/survey/v2/input.go deleted file mode 100644 index 2e9ad3ce..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/input.go +++ /dev/null @@ -1,210 +0,0 @@ -package survey - -import ( - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" -) - -/* -Input is a regular text input that prints each character the user types on the screen -and accepts the input with the enter key. Response type is a string. - - name := "" - prompt := &survey.Input{ Message: "What is your name?" } - survey.AskOne(prompt, &name) -*/ -type Input struct { - Renderer - Message string - Default string - Help string - Suggest func(toComplete string) []string - typedAnswer string - answer string - options []core.OptionAnswer - selectedIndex int - showingHelp bool -} - -// data available to the templates when processing -type InputTemplateData struct { - Input - ShowAnswer bool - ShowHelp bool - Answer string - PageEntries []core.OptionAnswer - SelectedIndex int - Config *PromptConfig -} - -// Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format -var InputQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }} {{color "reset"}} -{{- if .ShowAnswer}} - {{- color "cyan"}}{{.Answer}}{{color "reset"}}{{"\n"}} -{{- else if .PageEntries -}} - {{- .Answer}} [Use arrows to move, enter to select, type to continue] - {{- "\n"}} - {{- range $ix, $choice := .PageEntries}} - {{- if eq $ix $.SelectedIndex }}{{color $.Config.Icons.SelectFocus.Format }}{{ $.Config.Icons.SelectFocus.Text }} {{else}}{{color "default"}} {{end}} - {{- $choice.Value}} - {{- color "reset"}}{{"\n"}} - {{- end}} -{{- else }} - {{- if or (and .Help (not .ShowHelp)) .Suggest }}{{color "cyan"}}[ - {{- if and .Help (not .ShowHelp)}}{{ print .Config.HelpInput }} for help {{- if and .Suggest}}, {{end}}{{end -}} - {{- if and .Suggest }}{{color "cyan"}}{{ print .Config.SuggestInput }} for suggestions{{end -}} - ]{{color "reset"}} {{end}} - {{- if .Default}}{{color "white"}}({{.Default}}) {{color "reset"}}{{end}} - {{- .Answer -}} -{{- end}}` - -func (i *Input) OnChange(key rune, config *PromptConfig) (bool, error) { - if key == terminal.KeyEnter || key == '\n' { - if i.answer != config.HelpInput || i.Help == "" { - // we're done - return true, nil - } else { - i.answer = "" - i.showingHelp = true - } - } else if key == terminal.KeyDeleteWord || key == terminal.KeyDeleteLine { - i.answer = "" - } else if key == terminal.KeyEscape && i.Suggest != nil { - if len(i.options) > 0 { - i.answer = i.typedAnswer - } - i.options = nil - } else if key == terminal.KeyArrowUp && len(i.options) > 0 { - if i.selectedIndex == 0 { - i.selectedIndex = len(i.options) - 1 - } else { - i.selectedIndex-- - } - i.answer = i.options[i.selectedIndex].Value - } else if (key == terminal.KeyArrowDown || key == terminal.KeyTab) && len(i.options) > 0 { - if i.selectedIndex == len(i.options)-1 { - i.selectedIndex = 0 - } else { - i.selectedIndex++ - } - i.answer = i.options[i.selectedIndex].Value - } else if key == terminal.KeyTab && i.Suggest != nil { - options := i.Suggest(i.answer) - i.selectedIndex = 0 - i.typedAnswer = i.answer - if len(options) > 0 { - i.answer = options[0] - if len(options) == 1 { - i.options = nil - } else { - i.options = core.OptionAnswerList(options) - } - } - } else if key == terminal.KeyDelete || key == terminal.KeyBackspace { - if i.answer != "" { - runeAnswer := []rune(i.answer) - i.answer = string(runeAnswer[0 : len(runeAnswer)-1]) - } - } else if key >= terminal.KeySpace { - i.answer += string(key) - i.typedAnswer = i.answer - i.options = nil - } - - pageSize := config.PageSize - opts, idx := paginate(pageSize, i.options, i.selectedIndex) - err := i.Render( - InputQuestionTemplate, - InputTemplateData{ - Input: *i, - Answer: i.answer, - ShowHelp: i.showingHelp, - SelectedIndex: idx, - PageEntries: opts, - Config: config, - }, - ) - - return err != nil, err -} - -func (i *Input) Prompt(config *PromptConfig) (interface{}, error) { - // render the template - err := i.Render( - InputQuestionTemplate, - InputTemplateData{ - Input: *i, - Config: config, - }, - ) - if err != nil { - return "", err - } - - // start reading runes from the standard in - rr := i.NewRuneReader() - rr.SetTermMode() - defer rr.RestoreTermMode() - - cursor := i.NewCursor() - cursor.Hide() // hide the cursor - defer cursor.Show() // show the cursor when we're done - - // start waiting for input - for { - r, _, err := rr.ReadRune() - if err != nil { - return "", err - } - if r == terminal.KeyInterrupt { - return "", terminal.InterruptErr - } - if r == terminal.KeyEndTransmission { - break - } - - b, err := i.OnChange(r, config) - if err != nil { - return "", err - } - - if b { - break - } - } - - // if the line is empty - if len(i.answer) == 0 { - // use the default value - return i.Default, err - } - - lineStr := i.answer - - i.AppendRenderedText(lineStr) - - // we're done - return lineStr, err -} - -func (i *Input) Cleanup(config *PromptConfig, val interface{}) error { - // use the default answer when cleaning up the prompt if necessary - ans := i.answer - if ans == "" && i.Default != "" { - ans = i.Default - } - - // render the cleanup - return i.Render( - InputQuestionTemplate, - InputTemplateData{ - Input: *i, - ShowAnswer: true, - Config: config, - Answer: ans, - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/multiline.go b/vendor/github.com/AlecAivazis/survey/v2/multiline.go deleted file mode 100644 index d0523b7e..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/multiline.go +++ /dev/null @@ -1,110 +0,0 @@ -package survey - -import ( - "strings" - - "github.com/AlecAivazis/survey/v2/terminal" -) - -type Multiline struct { - Renderer - Message string - Default string - Help string -} - -// data available to the templates when processing -type MultilineTemplateData struct { - Multiline - Answer string - ShowAnswer bool - ShowHelp bool - Config *PromptConfig -} - -// Templates with Color formatting. See Documentation: https://github.com/mgutz/ansi#style-format -var MultilineQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }} {{color "reset"}} -{{- if .ShowAnswer}} - {{- "\n"}}{{color "cyan"}}{{.Answer}}{{color "reset"}} - {{- if .Answer }}{{ "\n" }}{{ end }} -{{- else }} - {{- if .Default}}{{color "white"}}({{.Default}}) {{color "reset"}}{{end}} - {{- color "cyan"}}[Enter 2 empty lines to finish]{{color "reset"}} -{{- end}}` - -func (i *Multiline) Prompt(config *PromptConfig) (interface{}, error) { - // render the template - err := i.Render( - MultilineQuestionTemplate, - MultilineTemplateData{ - Multiline: *i, - Config: config, - }, - ) - if err != nil { - return "", err - } - - // start reading runes from the standard in - rr := i.NewRuneReader() - rr.SetTermMode() - defer rr.RestoreTermMode() - - cursor := i.NewCursor() - - multiline := make([]string, 0) - - emptyOnce := false - // get the next line - for { - line := []rune{} - line, err = rr.ReadLine(0) - if err != nil { - return string(line), err - } - - if string(line) == "" { - if emptyOnce { - numLines := len(multiline) + 2 - cursor.PreviousLine(numLines) - for j := 0; j < numLines; j++ { - terminal.EraseLine(i.Stdio().Out, terminal.ERASE_LINE_ALL) - cursor.NextLine(1) - } - cursor.PreviousLine(numLines) - break - } - emptyOnce = true - } else { - emptyOnce = false - } - multiline = append(multiline, string(line)) - } - - val := strings.Join(multiline, "\n") - val = strings.TrimSpace(val) - - // if the line is empty - if len(val) == 0 { - // use the default value - return i.Default, err - } - - i.AppendRenderedText(val) - return val, err -} - -func (i *Multiline) Cleanup(config *PromptConfig, val interface{}) error { - return i.Render( - MultilineQuestionTemplate, - MultilineTemplateData{ - Multiline: *i, - Answer: val.(string), - ShowAnswer: true, - Config: config, - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/multiselect.go b/vendor/github.com/AlecAivazis/survey/v2/multiselect.go deleted file mode 100644 index 3d4f95b9..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/multiselect.go +++ /dev/null @@ -1,331 +0,0 @@ -package survey - -import ( - "errors" - "fmt" - - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" -) - -/* -MultiSelect is a prompt that presents a list of various options to the user -for them to select using the arrow keys and enter. Response type is a slice of strings. - - days := []string{} - prompt := &survey.MultiSelect{ - Message: "What days do you prefer:", - Options: []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}, - } - survey.AskOne(prompt, &days) -*/ -type MultiSelect struct { - Renderer - Message string - Options []string - Default interface{} - Help string - PageSize int - VimMode bool - FilterMessage string - Filter func(filter string, value string, index int) bool - filter string - selectedIndex int - checked map[int]bool - showingHelp bool -} - -// data available to the templates when processing -type MultiSelectTemplateData struct { - MultiSelect - Answer string - ShowAnswer bool - Checked map[int]bool - SelectedIndex int - ShowHelp bool - PageEntries []core.OptionAnswer - Config *PromptConfig -} - -var MultiSelectQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }}{{ .FilterMessage }}{{color "reset"}} -{{- if .ShowAnswer}}{{color "cyan"}} {{.Answer}}{{color "reset"}}{{"\n"}} -{{- else }} - {{- " "}}{{- color "cyan"}}[Use arrows to move, space to select, to all, to none, type to filter{{- if and .Help (not .ShowHelp)}}, {{ .Config.HelpInput }} for more help{{end}}]{{color "reset"}} - {{- "\n"}} - {{- range $ix, $option := .PageEntries}} - {{- if eq $ix $.SelectedIndex }}{{color $.Config.Icons.SelectFocus.Format }}{{ $.Config.Icons.SelectFocus.Text }}{{color "reset"}}{{else}} {{end}} - {{- if index $.Checked $option.Index }}{{color $.Config.Icons.MarkedOption.Format }} {{ $.Config.Icons.MarkedOption.Text }} {{else}}{{color $.Config.Icons.UnmarkedOption.Format }} {{ $.Config.Icons.UnmarkedOption.Text }} {{end}} - {{- color "reset"}} - {{- " "}}{{$option.Value}}{{"\n"}} - {{- end}} -{{- end}}` - -// OnChange is called on every keypress. -func (m *MultiSelect) OnChange(key rune, config *PromptConfig) { - options := m.filterOptions(config) - oldFilter := m.filter - - if key == terminal.KeyArrowUp || (m.VimMode && key == 'k') { - // if we are at the top of the list - if m.selectedIndex == 0 { - // go to the bottom - m.selectedIndex = len(options) - 1 - } else { - // decrement the selected index - m.selectedIndex-- - } - } else if key == terminal.KeyTab || key == terminal.KeyArrowDown || (m.VimMode && key == 'j') { - // if we are at the bottom of the list - if m.selectedIndex == len(options)-1 { - // start at the top - m.selectedIndex = 0 - } else { - // increment the selected index - m.selectedIndex++ - } - // if the user pressed down and there is room to move - } else if key == terminal.KeySpace { - // the option they have selected - if m.selectedIndex < len(options) { - selectedOpt := options[m.selectedIndex] - - // if we haven't seen this index before - if old, ok := m.checked[selectedOpt.Index]; !ok { - // set the value to true - m.checked[selectedOpt.Index] = true - } else { - // otherwise just invert the current value - m.checked[selectedOpt.Index] = !old - } - if !config.KeepFilter { - m.filter = "" - } - } - // only show the help message if we have one to show - } else if string(key) == config.HelpInput && m.Help != "" { - m.showingHelp = true - } else if key == terminal.KeyEscape { - m.VimMode = !m.VimMode - } else if key == terminal.KeyDeleteWord || key == terminal.KeyDeleteLine { - m.filter = "" - } else if key == terminal.KeyDelete || key == terminal.KeyBackspace { - if m.filter != "" { - runeFilter := []rune(m.filter) - m.filter = string(runeFilter[0 : len(runeFilter)-1]) - } - } else if key >= terminal.KeySpace { - m.filter += string(key) - m.VimMode = false - } else if key == terminal.KeyArrowRight { - for _, v := range options { - m.checked[v.Index] = true - } - if !config.KeepFilter { - m.filter = "" - } - } else if key == terminal.KeyArrowLeft { - for _, v := range options { - m.checked[v.Index] = false - } - if !config.KeepFilter { - m.filter = "" - } - } - - m.FilterMessage = "" - if m.filter != "" { - m.FilterMessage = " " + m.filter - } - if oldFilter != m.filter { - // filter changed - options = m.filterOptions(config) - if len(options) > 0 && len(options) <= m.selectedIndex { - m.selectedIndex = len(options) - 1 - } - } - // paginate the options - // figure out the page size - pageSize := m.PageSize - // if we dont have a specific one - if pageSize == 0 { - // grab the global value - pageSize = config.PageSize - } - - // TODO if we have started filtering and were looking at the end of a list - // and we have modified the filter then we should move the page back! - opts, idx := paginate(pageSize, options, m.selectedIndex) - - // render the options - m.Render( - MultiSelectQuestionTemplate, - MultiSelectTemplateData{ - MultiSelect: *m, - SelectedIndex: idx, - Checked: m.checked, - ShowHelp: m.showingHelp, - PageEntries: opts, - Config: config, - }, - ) -} - -func (m *MultiSelect) filterOptions(config *PromptConfig) []core.OptionAnswer { - // the filtered list - answers := []core.OptionAnswer{} - - // if there is no filter applied - if m.filter == "" { - // return all of the options - return core.OptionAnswerList(m.Options) - } - - // the filter to apply - filter := m.Filter - if filter == nil { - filter = config.Filter - } - - // apply the filter to each option - for i, opt := range m.Options { - // i the filter says to include the option - if filter(m.filter, opt, i) { - answers = append(answers, core.OptionAnswer{ - Index: i, - Value: opt, - }) - } - } - - // we're done here - return answers -} - -func (m *MultiSelect) Prompt(config *PromptConfig) (interface{}, error) { - // compute the default state - m.checked = make(map[int]bool) - // if there is a default - if m.Default != nil { - // if the default is string values - if defaultValues, ok := m.Default.([]string); ok { - for _, dflt := range defaultValues { - for i, opt := range m.Options { - // if the option corresponds to the default - if opt == dflt { - // we found our initial value - m.checked[i] = true - // stop looking - break - } - } - } - // if the default value is index values - } else if defaultIndices, ok := m.Default.([]int); ok { - // go over every index we need to enable by default - for _, idx := range defaultIndices { - // and enable it - m.checked[idx] = true - } - } - } - - // if there are no options to render - if len(m.Options) == 0 { - // we failed - return "", errors.New("please provide options to select from") - } - - // figure out the page size - pageSize := m.PageSize - // if we dont have a specific one - if pageSize == 0 { - // grab the global value - pageSize = config.PageSize - } - // paginate the options - // build up a list of option answers - opts, idx := paginate(pageSize, core.OptionAnswerList(m.Options), m.selectedIndex) - - cursor := m.NewCursor() - cursor.Hide() // hide the cursor - defer cursor.Show() // show the cursor when we're done - - // ask the question - err := m.Render( - MultiSelectQuestionTemplate, - MultiSelectTemplateData{ - MultiSelect: *m, - SelectedIndex: idx, - Checked: m.checked, - PageEntries: opts, - Config: config, - }, - ) - if err != nil { - return "", err - } - - rr := m.NewRuneReader() - rr.SetTermMode() - defer rr.RestoreTermMode() - - // start waiting for input - for { - r, _, err := rr.ReadRune() - if err != nil { - return "", err - } - if r == '\r' || r == '\n' { - break - } - if r == terminal.KeyInterrupt { - return "", terminal.InterruptErr - } - if r == terminal.KeyEndTransmission { - break - } - m.OnChange(r, config) - } - m.filter = "" - m.FilterMessage = "" - - answers := []core.OptionAnswer{} - for i, option := range m.Options { - if val, ok := m.checked[i]; ok && val { - answers = append(answers, core.OptionAnswer{Value: option, Index: i}) - } - } - - return answers, nil -} - -// Cleanup removes the options section, and renders the ask like a normal question. -func (m *MultiSelect) Cleanup(config *PromptConfig, val interface{}) error { - // the answer to show - answer := "" - for _, ans := range val.([]core.OptionAnswer) { - answer = fmt.Sprintf("%s, %s", answer, ans.Value) - } - - // if we answered anything - if len(answer) > 2 { - // remove the precending commas - answer = answer[2:] - } - - // execute the output summary template with the answer - return m.Render( - MultiSelectQuestionTemplate, - MultiSelectTemplateData{ - MultiSelect: *m, - SelectedIndex: m.selectedIndex, - Checked: m.checked, - Answer: answer, - ShowAnswer: true, - Config: config, - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/password.go b/vendor/github.com/AlecAivazis/survey/v2/password.go deleted file mode 100644 index 285bff5e..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/password.go +++ /dev/null @@ -1,101 +0,0 @@ -package survey - -import ( - "fmt" - "strings" - - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" -) - -/* -Password is like a normal Input but the text shows up as *'s and there is no default. Response -type is a string. - - password := "" - prompt := &survey.Password{ Message: "Please type your password" } - survey.AskOne(prompt, &password) -*/ -type Password struct { - Renderer - Message string - Help string -} - -type PasswordTemplateData struct { - Password - ShowHelp bool - Config *PromptConfig -} - -// PasswordQuestionTemplate is a template with color formatting. See Documentation: https://github.com/mgutz/ansi#style-format -var PasswordQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }} {{color "reset"}} -{{- if and .Help (not .ShowHelp)}}{{color "cyan"}}[{{ .Config.HelpInput }} for help]{{color "reset"}} {{end}}` - -func (p *Password) Prompt(config *PromptConfig) (interface{}, error) { - // render the question template - userOut, _, err := core.RunTemplate( - PasswordQuestionTemplate, - PasswordTemplateData{ - Password: *p, - Config: config, - }, - ) - fmt.Fprint(terminal.NewAnsiStdout(p.Stdio().Out), userOut) - if err != nil { - return "", err - } - - rr := p.NewRuneReader() - rr.SetTermMode() - defer rr.RestoreTermMode() - - // no help msg? Just return any response - if p.Help == "" { - line, err := rr.ReadLine('*') - return string(line), err - } - - cursor := p.NewCursor() - - line := []rune{} - // process answers looking for help prompt answer - for { - line, err = rr.ReadLine('*') - if err != nil { - return string(line), err - } - - if string(line) == config.HelpInput { - // terminal will echo the \n so we need to jump back up one row - cursor.PreviousLine(1) - - err = p.Render( - PasswordQuestionTemplate, - PasswordTemplateData{ - Password: *p, - ShowHelp: true, - Config: config, - }, - ) - if err != nil { - return "", err - } - continue - } - - break - } - - lineStr := string(line) - p.AppendRenderedText(strings.Repeat("*", len(lineStr))) - return lineStr, err -} - -// Cleanup hides the string with a fixed number of characters. -func (prompt *Password) Cleanup(config *PromptConfig, val interface{}) error { - return nil -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/renderer.go b/vendor/github.com/AlecAivazis/survey/v2/renderer.go deleted file mode 100644 index 54251213..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/renderer.go +++ /dev/null @@ -1,164 +0,0 @@ -package survey - -import ( - "bytes" - "fmt" - "unicode/utf8" - - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" - goterm "golang.org/x/crypto/ssh/terminal" -) - -type Renderer struct { - stdio terminal.Stdio - renderedErrors bytes.Buffer - renderedText bytes.Buffer -} - -type ErrorTemplateData struct { - Error error - Icon Icon -} - -var ErrorTemplate = `{{color .Icon.Format }}{{ .Icon.Text }} Sorry, your reply was invalid: {{ .Error.Error }}{{color "reset"}} -` - -func (r *Renderer) WithStdio(stdio terminal.Stdio) { - r.stdio = stdio -} - -func (r *Renderer) Stdio() terminal.Stdio { - return r.stdio -} - -func (r *Renderer) NewRuneReader() *terminal.RuneReader { - return terminal.NewRuneReader(r.stdio) -} - -func (r *Renderer) NewCursor() *terminal.Cursor { - return &terminal.Cursor{ - In: r.stdio.In, - Out: r.stdio.Out, - } -} - -func (r *Renderer) Error(config *PromptConfig, invalid error) error { - // cleanup the currently rendered errors - r.resetPrompt(r.countLines(r.renderedErrors)) - r.renderedErrors.Reset() - - // cleanup the rest of the prompt - r.resetPrompt(r.countLines(r.renderedText)) - r.renderedText.Reset() - - userOut, layoutOut, err := core.RunTemplate(ErrorTemplate, &ErrorTemplateData{ - Error: invalid, - Icon: config.Icons.Error, - }) - if err != nil { - return err - } - - // send the message to the user - fmt.Fprint(terminal.NewAnsiStdout(r.stdio.Out), userOut) - - // add the printed text to the rendered error buffer so we can cleanup later - r.appendRenderedError(layoutOut) - - return nil -} - -func (r *Renderer) Render(tmpl string, data interface{}) error { - // cleanup the currently rendered text - lineCount := r.countLines(r.renderedText) - r.resetPrompt(lineCount) - r.renderedText.Reset() - - // render the template summarizing the current state - userOut, layoutOut, err := core.RunTemplate(tmpl, data) - if err != nil { - return err - } - - // print the summary - fmt.Fprint(terminal.NewAnsiStdout(r.stdio.Out), userOut) - - // add the printed text to the rendered text buffer so we can cleanup later - r.AppendRenderedText(layoutOut) - - // nothing went wrong - return nil -} - -// appendRenderedError appends text to the renderer's error buffer -// which is used to track what has been printed. It is not exported -// as errors should only be displayed via Error(config, error). -func (r *Renderer) appendRenderedError(text string) { - r.renderedErrors.WriteString(text) -} - -// AppendRenderedText appends text to the renderer's text buffer -// which is used to track of what has been printed. The buffer is used -// to calculate how many lines to erase before updating the prompt. -func (r *Renderer) AppendRenderedText(text string) { - r.renderedText.WriteString(text) -} - -func (r *Renderer) resetPrompt(lines int) { - // clean out current line in case tmpl didnt end in newline - cursor := r.NewCursor() - cursor.HorizontalAbsolute(0) - terminal.EraseLine(r.stdio.Out, terminal.ERASE_LINE_ALL) - // clean up what we left behind last time - for i := 0; i < lines; i++ { - cursor.PreviousLine(1) - terminal.EraseLine(r.stdio.Out, terminal.ERASE_LINE_ALL) - } -} - -func (r *Renderer) termWidth() (int, error) { - fd := int(r.stdio.Out.Fd()) - termWidth, _, err := goterm.GetSize(fd) - return termWidth, err -} - -// countLines will return the count of `\n` with the addition of any -// lines that have wrapped due to narrow terminal width -func (r *Renderer) countLines(buf bytes.Buffer) int { - w, err := r.termWidth() - if err != nil || w == 0 { - // if we got an error due to terminal.GetSize not being supported - // on current platform then just assume a very wide terminal - w = 10000 - } - - bufBytes := buf.Bytes() - - count := 0 - curr := 0 - delim := -1 - for curr < len(bufBytes) { - // read until the next newline or the end of the string - relDelim := bytes.IndexRune(bufBytes[curr:], '\n') - if relDelim != -1 { - count += 1 // new line found, add it to the count - delim = curr + relDelim - } else { - delim = len(bufBytes) // no new line found, read rest of text - } - - if lineWidth := utf8.RuneCount(bufBytes[curr:delim]); lineWidth > w { - // account for word wrapping - count += lineWidth / w - if (lineWidth % w) == 0 { - // content whose width is exactly a multiplier of available width should not - // count as having wrapped on the last line - count -= 1 - } - } - curr = delim + 1 - } - - return count -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/select.go b/vendor/github.com/AlecAivazis/survey/v2/select.go deleted file mode 100644 index fdce0381..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/select.go +++ /dev/null @@ -1,329 +0,0 @@ -package survey - -import ( - "errors" - - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" -) - -/* -Select is a prompt that presents a list of various options to the user -for them to select using the arrow keys and enter. Response type is a string. - - color := "" - prompt := &survey.Select{ - Message: "Choose a color:", - Options: []string{"red", "blue", "green"}, - } - survey.AskOne(prompt, &color) -*/ -type Select struct { - Renderer - Message string - Options []string - Default interface{} - Help string - PageSize int - VimMode bool - FilterMessage string - Filter func(filter string, value string, index int) bool - filter string - selectedIndex int - useDefault bool - showingHelp bool -} - -// SelectTemplateData is the data available to the templates when processing -type SelectTemplateData struct { - Select - PageEntries []core.OptionAnswer - SelectedIndex int - Answer string - ShowAnswer bool - ShowHelp bool - Config *PromptConfig -} - -var SelectQuestionTemplate = ` -{{- if .ShowHelp }}{{- color .Config.Icons.Help.Format }}{{ .Config.Icons.Help.Text }} {{ .Help }}{{color "reset"}}{{"\n"}}{{end}} -{{- color .Config.Icons.Question.Format }}{{ .Config.Icons.Question.Text }} {{color "reset"}} -{{- color "default+hb"}}{{ .Message }}{{ .FilterMessage }}{{color "reset"}} -{{- if .ShowAnswer}}{{color "cyan"}} {{.Answer}}{{color "reset"}}{{"\n"}} -{{- else}} - {{- " "}}{{- color "cyan"}}[Use arrows to move, type to filter{{- if and .Help (not .ShowHelp)}}, {{ .Config.HelpInput }} for more help{{end}}]{{color "reset"}} - {{- "\n"}} - {{- range $ix, $choice := .PageEntries}} - {{- if eq $ix $.SelectedIndex }}{{color $.Config.Icons.SelectFocus.Format }}{{ $.Config.Icons.SelectFocus.Text }} {{else}}{{color "default"}} {{end}} - {{- $choice.Value}} - {{- color "reset"}}{{"\n"}} - {{- end}} -{{- end}}` - -// OnChange is called on every keypress. -func (s *Select) OnChange(key rune, config *PromptConfig) bool { - options := s.filterOptions(config) - oldFilter := s.filter - - // if the user pressed the enter key and the index is a valid option - if key == terminal.KeyEnter || key == '\n' { - // if the selected index is a valid option - if len(options) > 0 && s.selectedIndex < len(options) { - - // we're done (stop prompting the user) - return true - } - - // we're not done (keep prompting) - return false - - // if the user pressed the up arrow or 'k' to emulate vim - } else if (key == terminal.KeyArrowUp || (s.VimMode && key == 'k')) && len(options) > 0 { - s.useDefault = false - - // if we are at the top of the list - if s.selectedIndex == 0 { - // start from the button - s.selectedIndex = len(options) - 1 - } else { - // otherwise we are not at the top of the list so decrement the selected index - s.selectedIndex-- - } - - // if the user pressed down or 'j' to emulate vim - } else if (key == terminal.KeyTab || key == terminal.KeyArrowDown || (s.VimMode && key == 'j')) && len(options) > 0 { - s.useDefault = false - // if we are at the bottom of the list - if s.selectedIndex == len(options)-1 { - // start from the top - s.selectedIndex = 0 - } else { - // increment the selected index - s.selectedIndex++ - } - // only show the help message if we have one - } else if string(key) == config.HelpInput && s.Help != "" { - s.showingHelp = true - // if the user wants to toggle vim mode on/off - } else if key == terminal.KeyEscape { - s.VimMode = !s.VimMode - // if the user hits any of the keys that clear the filter - } else if key == terminal.KeyDeleteWord || key == terminal.KeyDeleteLine { - s.filter = "" - // if the user is deleting a character in the filter - } else if key == terminal.KeyDelete || key == terminal.KeyBackspace { - // if there is content in the filter to delete - if s.filter != "" { - runeFilter := []rune(s.filter) - // subtract a line from the current filter - s.filter = string(runeFilter[0 : len(runeFilter)-1]) - // we removed the last value in the filter - } - } else if key >= terminal.KeySpace { - s.filter += string(key) - // make sure vim mode is disabled - s.VimMode = false - // make sure that we use the current value in the filtered list - s.useDefault = false - } - - s.FilterMessage = "" - if s.filter != "" { - s.FilterMessage = " " + s.filter - } - if oldFilter != s.filter { - // filter changed - options = s.filterOptions(config) - if len(options) > 0 && len(options) <= s.selectedIndex { - s.selectedIndex = len(options) - 1 - } - } - - // figure out the options and index to render - // figure out the page size - pageSize := s.PageSize - // if we dont have a specific one - if pageSize == 0 { - // grab the global value - pageSize = config.PageSize - } - - // TODO if we have started filtering and were looking at the end of a list - // and we have modified the filter then we should move the page back! - opts, idx := paginate(pageSize, options, s.selectedIndex) - - // render the options - s.Render( - SelectQuestionTemplate, - SelectTemplateData{ - Select: *s, - SelectedIndex: idx, - ShowHelp: s.showingHelp, - PageEntries: opts, - Config: config, - }, - ) - - // keep prompting - return false -} - -func (s *Select) filterOptions(config *PromptConfig) []core.OptionAnswer { - // the filtered list - answers := []core.OptionAnswer{} - - // if there is no filter applied - if s.filter == "" { - return core.OptionAnswerList(s.Options) - } - - // the filter to apply - filter := s.Filter - if filter == nil { - filter = config.Filter - } - - // - for i, opt := range s.Options { - // i the filter says to include the option - if filter(s.filter, opt, i) { - answers = append(answers, core.OptionAnswer{ - Index: i, - Value: opt, - }) - } - } - - // return the list of answers - return answers -} - -func (s *Select) Prompt(config *PromptConfig) (interface{}, error) { - // if there are no options to render - if len(s.Options) == 0 { - // we failed - return "", errors.New("please provide options to select from") - } - - // start off with the first option selected - sel := 0 - // if there is a default - if s.Default != "" { - // find the choice - for i, opt := range s.Options { - // if the option corresponds to the default - if opt == s.Default { - // we found our initial value - sel = i - // stop looking - break - } - } - } - // save the selected index - s.selectedIndex = sel - - // figure out the page size - pageSize := s.PageSize - // if we dont have a specific one - if pageSize == 0 { - // grab the global value - pageSize = config.PageSize - } - - // figure out the options and index to render - opts, idx := paginate(pageSize, core.OptionAnswerList(s.Options), sel) - - // ask the question - err := s.Render( - SelectQuestionTemplate, - SelectTemplateData{ - Select: *s, - PageEntries: opts, - SelectedIndex: idx, - Config: config, - }, - ) - if err != nil { - return "", err - } - - // by default, use the default value - s.useDefault = true - - rr := s.NewRuneReader() - rr.SetTermMode() - defer rr.RestoreTermMode() - - cursor := s.NewCursor() - cursor.Hide() // hide the cursor - defer cursor.Show() // show the cursor when we're done - - // start waiting for input - for { - r, _, err := rr.ReadRune() - if err != nil { - return "", err - } - if r == terminal.KeyInterrupt { - return "", terminal.InterruptErr - } - if r == terminal.KeyEndTransmission { - break - } - if s.OnChange(r, config) { - break - } - } - options := s.filterOptions(config) - s.filter = "" - s.FilterMessage = "" - - // the index to report - var val string - // if we are supposed to use the default value - if s.useDefault || s.selectedIndex >= len(options) { - // if there is a default value - if s.Default != nil { - // if the default is a string - if defaultString, ok := s.Default.(string); ok { - // use the default value - val = defaultString - // the default value could also be an interpret which is interpretted as the index - } else if defaultIndex, ok := s.Default.(int); ok { - val = s.Options[defaultIndex] - } else { - return val, errors.New("default value of select must be an int or string") - } - } else if len(options) > 0 { - // there is no default value so use the first - val = options[0].Value - } - // otherwise the selected index points to the value - } else if s.selectedIndex < len(options) { - // the - val = options[s.selectedIndex].Value - } - - // now that we have the value lets go hunt down the right index to return - idx = -1 - for i, optionValue := range s.Options { - if optionValue == val { - idx = i - } - } - - return core.OptionAnswer{Value: val, Index: idx}, err -} - -func (s *Select) Cleanup(config *PromptConfig, val interface{}) error { - return s.Render( - SelectQuestionTemplate, - SelectTemplateData{ - Select: *s, - Answer: val.(core.OptionAnswer).Value, - ShowAnswer: true, - Config: config, - }, - ) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/survey.go b/vendor/github.com/AlecAivazis/survey/v2/survey.go deleted file mode 100644 index e004cf30..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/survey.go +++ /dev/null @@ -1,400 +0,0 @@ -package survey - -import ( - "errors" - "io" - "os" - "strings" - - "github.com/AlecAivazis/survey/v2/core" - "github.com/AlecAivazis/survey/v2/terminal" -) - -// DefaultAskOptions is the default options on ask, using the OS stdio. -func defaultAskOptions() *AskOptions { - return &AskOptions{ - Stdio: terminal.Stdio{ - In: os.Stdin, - Out: os.Stdout, - Err: os.Stderr, - }, - PromptConfig: PromptConfig{ - PageSize: 7, - HelpInput: "?", - SuggestInput: "tab", - Icons: IconSet{ - Error: Icon{ - Text: "X", - Format: "red", - }, - Help: Icon{ - Text: "?", - Format: "cyan", - }, - Question: Icon{ - Text: "?", - Format: "green+hb", - }, - MarkedOption: Icon{ - Text: "[x]", - Format: "green", - }, - UnmarkedOption: Icon{ - Text: "[ ]", - Format: "default+hb", - }, - SelectFocus: Icon{ - Text: ">", - Format: "cyan+b", - }, - }, - Filter: func(filter string, value string, index int) (include bool) { - filter = strings.ToLower(filter) - - // include this option if it matches - return strings.Contains(strings.ToLower(value), filter) - }, - KeepFilter: false, - }, - } -} -func defaultPromptConfig() *PromptConfig { - return &defaultAskOptions().PromptConfig -} - -func defaultIcons() *IconSet { - return &defaultPromptConfig().Icons -} - -// OptionAnswer is an ergonomic alias for core.OptionAnswer -type OptionAnswer = core.OptionAnswer - -// Icon holds the text and format to show for a particular icon -type Icon struct { - Text string - Format string -} - -// IconSet holds the icons to use for various prompts -type IconSet struct { - HelpInput Icon - Error Icon - Help Icon - Question Icon - MarkedOption Icon - UnmarkedOption Icon - SelectFocus Icon -} - -// Validator is a function passed to a Question after a user has provided a response. -// If the function returns an error, then the user will be prompted again for another -// response. -type Validator func(ans interface{}) error - -// Transformer is a function passed to a Question after a user has provided a response. -// The function can be used to implement a custom logic that will result to return -// a different representation of the given answer. -// -// Look `TransformString`, `ToLower` `Title` and `ComposeTransformers` for more. -type Transformer func(ans interface{}) (newAns interface{}) - -// Question is the core data structure for a survey questionnaire. -type Question struct { - Name string - Prompt Prompt - Validate Validator - Transform Transformer -} - -// PromptConfig holds the global configuration for a prompt -type PromptConfig struct { - PageSize int - Icons IconSet - HelpInput string - SuggestInput string - Filter func(filter string, option string, index int) bool - KeepFilter bool -} - -// Prompt is the primary interface for the objects that can take user input -// and return a response. -type Prompt interface { - Prompt(config *PromptConfig) (interface{}, error) - Cleanup(*PromptConfig, interface{}) error - Error(*PromptConfig, error) error -} - -// PromptAgainer Interface for Prompts that support prompting again after invalid input -type PromptAgainer interface { - PromptAgain(config *PromptConfig, invalid interface{}, err error) (interface{}, error) -} - -// AskOpt allows setting optional ask options. -type AskOpt func(options *AskOptions) error - -// AskOptions provides additional options on ask. -type AskOptions struct { - Stdio terminal.Stdio - Validators []Validator - PromptConfig PromptConfig -} - -// WithStdio specifies the standard input, output and error files survey -// interacts with. By default, these are os.Stdin, os.Stdout, and os.Stderr. -func WithStdio(in terminal.FileReader, out terminal.FileWriter, err io.Writer) AskOpt { - return func(options *AskOptions) error { - options.Stdio.In = in - options.Stdio.Out = out - options.Stdio.Err = err - return nil - } -} - -// WithFilter specifies the default filter to use when asking questions. -func WithFilter(filter func(filter string, value string, index int) (include bool)) AskOpt { - return func(options *AskOptions) error { - // save the filter internally - options.PromptConfig.Filter = filter - - return nil - } -} - -// WithKeepFilter sets the if the filter is kept after selections -func WithKeepFilter(KeepFilter bool) AskOpt { - return func(options *AskOptions) error { - // set the page size - options.PromptConfig.KeepFilter = KeepFilter - - // nothing went wrong - return nil - } -} - -// WithValidator specifies a validator to use while prompting the user -func WithValidator(v Validator) AskOpt { - return func(options *AskOptions) error { - // add the provided validator to the list - options.Validators = append(options.Validators, v) - - // nothing went wrong - return nil - } -} - -type wantsStdio interface { - WithStdio(terminal.Stdio) -} - -// WithPageSize sets the default page size used by prompts -func WithPageSize(pageSize int) AskOpt { - return func(options *AskOptions) error { - // set the page size - options.PromptConfig.PageSize = pageSize - - // nothing went wrong - return nil - } -} - -// WithHelpInput changes the character that prompts look for to give the user helpful information. -func WithHelpInput(r rune) AskOpt { - return func(options *AskOptions) error { - // set the input character - options.PromptConfig.HelpInput = string(r) - - // nothing went wrong - return nil - } -} - -// WithIcons sets the icons that will be used when prompting the user -func WithIcons(setIcons func(*IconSet)) AskOpt { - return func(options *AskOptions) error { - // update the default icons with whatever the user says - setIcons(&options.PromptConfig.Icons) - - // nothing went wrong - return nil - } -} - -/* -AskOne performs the prompt for a single prompt and asks for validation if required. -Response types should be something that can be casted from the response type designated -in the documentation. For example: - - name := "" - prompt := &survey.Input{ - Message: "name", - } - - survey.AskOne(prompt, &name) - -*/ -func AskOne(p Prompt, response interface{}, opts ...AskOpt) error { - err := Ask([]*Question{{Prompt: p}}, response, opts...) - if err != nil { - return err - } - - return nil -} - -/* -Ask performs the prompt loop, asking for validation when appropriate. The response -type can be one of two options. If a struct is passed, the answer will be written to -the field whose name matches the Name field on the corresponding question. Field types -should be something that can be casted from the response type designated in the -documentation. Note, a survey tag can also be used to identify a Otherwise, a -map[string]interface{} can be passed, responses will be written to the key with the -matching name. For example: - - qs := []*survey.Question{ - { - Name: "name", - Prompt: &survey.Input{Message: "What is your name?"}, - Validate: survey.Required, - Transform: survey.Title, - }, - } - - answers := struct{ Name string }{} - - - err := survey.Ask(qs, &answers) -*/ -func Ask(qs []*Question, response interface{}, opts ...AskOpt) error { - // build up the configuration options - options := defaultAskOptions() - for _, opt := range opts { - if opt == nil { - continue - } - if err := opt(options); err != nil { - return err - } - } - - // if we weren't passed a place to record the answers - if response == nil { - // we can't go any further - return errors.New("cannot call Ask() with a nil reference to record the answers") - } - - // go over every question - for _, q := range qs { - // If Prompt implements controllable stdio, pass in specified stdio. - if p, ok := q.Prompt.(wantsStdio); ok { - p.WithStdio(options.Stdio) - } - - // grab the user input and save it - ans, err := q.Prompt.Prompt(&options.PromptConfig) - // if there was a problem - if err != nil { - return err - } - - // build up a list of validators that we have to apply to this question - validators := []Validator{} - - // make sure to include the question specific one - if q.Validate != nil { - validators = append(validators, q.Validate) - } - // add any "global" validators - for _, validator := range options.Validators { - validators = append(validators, validator) - } - - // apply every validator to thte response - for _, validator := range validators { - // wait for a valid response - for invalid := validator(ans); invalid != nil; invalid = validator(ans) { - err := q.Prompt.Error(&options.PromptConfig, invalid) - // if there was a problem - if err != nil { - return err - } - - // ask for more input - if promptAgainer, ok := q.Prompt.(PromptAgainer); ok { - ans, err = promptAgainer.PromptAgain(&options.PromptConfig, ans, invalid) - } else { - ans, err = q.Prompt.Prompt(&options.PromptConfig) - } - // if there was a problem - if err != nil { - return err - } - } - } - - if q.Transform != nil { - // check if we have a transformer available, if so - // then try to acquire the new representation of the - // answer, if the resulting answer is not nil. - if newAns := q.Transform(ans); newAns != nil { - ans = newAns - } - } - - // tell the prompt to cleanup with the validated value - q.Prompt.Cleanup(&options.PromptConfig, ans) - - // if something went wrong - if err != nil { - // stop listening - return err - } - - // add it to the map - err = core.WriteAnswer(response, q.Name, ans) - // if something went wrong - if err != nil { - return err - } - - } - - // return the response - return nil -} - -// paginate returns a single page of choices given the page size, the total list of -// possible choices, and the current selected index in the total list. -func paginate(pageSize int, choices []core.OptionAnswer, sel int) ([]core.OptionAnswer, int) { - var start, end, cursor int - - if len(choices) < pageSize { - // if we dont have enough options to fill a page - start = 0 - end = len(choices) - cursor = sel - - } else if sel < pageSize/2 { - // if we are in the first half page - start = 0 - end = pageSize - cursor = sel - - } else if len(choices)-sel-1 < pageSize/2 { - // if we are in the last half page - start = len(choices) - pageSize - end = len(choices) - cursor = sel - start - - } else { - // somewhere in the middle - above := pageSize / 2 - below := pageSize - above - - cursor = pageSize / 2 - start = sel - above - end = sel + below - } - - // return the subset we care about and the index - return choices[start:end], cursor -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/LICENSE.txt b/vendor/github.com/AlecAivazis/survey/v2/terminal/LICENSE.txt deleted file mode 100644 index ade5fef6..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2014 Takashi Kokubun - -MIT License - -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/github.com/AlecAivazis/survey/v2/terminal/README.md b/vendor/github.com/AlecAivazis/survey/v2/terminal/README.md deleted file mode 100644 index d0b9db0f..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# survey/terminal - -This package started as a copy of [kokuban/go-ansi](http://github.com/k0kubun/go-ansi) but has since been modified to fit survey's specific needs. diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/buffered_reader.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/buffered_reader.go deleted file mode 100644 index 55eac152..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/buffered_reader.go +++ /dev/null @@ -1,22 +0,0 @@ -package terminal - -import ( - "bytes" - "io" -) - -type BufferedReader struct { - In io.Reader - Buffer *bytes.Buffer -} - -func (br *BufferedReader) Read(p []byte) (int, error) { - n, err := br.Buffer.Read(p) - if err != nil && err != io.EOF { - return n, err - } else if err == nil { - return n, nil - } - - return br.In.Read(p[n:]) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor.go deleted file mode 100644 index c294ca4c..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor.go +++ /dev/null @@ -1,190 +0,0 @@ -// +build !windows - -package terminal - -import ( - "bufio" - "bytes" - "fmt" - "io" - "regexp" - "strconv" -) - -var COORDINATE_SYSTEM_BEGIN Short = 1 - -var dsrPattern = regexp.MustCompile(`\x1b\[(\d+);(\d+)R$`) - -type Cursor struct { - In FileReader - Out FileWriter -} - -// Up moves the cursor n cells to up. -func (c *Cursor) Up(n int) { - fmt.Fprintf(c.Out, "\x1b[%dA", n) -} - -// Down moves the cursor n cells to down. -func (c *Cursor) Down(n int) { - fmt.Fprintf(c.Out, "\x1b[%dB", n) -} - -// Forward moves the cursor n cells to right. -func (c *Cursor) Forward(n int) { - fmt.Fprintf(c.Out, "\x1b[%dC", n) -} - -// Back moves the cursor n cells to left. -func (c *Cursor) Back(n int) { - fmt.Fprintf(c.Out, "\x1b[%dD", n) -} - -// NextLine moves cursor to beginning of the line n lines down. -func (c *Cursor) NextLine(n int) { - c.Down(1) -} - -// PreviousLine moves cursor to beginning of the line n lines up. -func (c *Cursor) PreviousLine(n int) { - c.Up(1) -} - -// HorizontalAbsolute moves cursor horizontally to x. -func (c *Cursor) HorizontalAbsolute(x int) { - fmt.Fprintf(c.Out, "\x1b[%dG", x) -} - -// Show shows the cursor. -func (c *Cursor) Show() { - fmt.Fprint(c.Out, "\x1b[?25h") -} - -// Hide hide the cursor. -func (c *Cursor) Hide() { - fmt.Fprint(c.Out, "\x1b[?25l") -} - -// Move moves the cursor to a specific x,y location. -func (c *Cursor) Move(x int, y int) { - fmt.Fprintf(c.Out, "\x1b[%d;%df", x, y) -} - -// Save saves the current position -func (c *Cursor) Save() { - fmt.Fprint(c.Out, "\x1b7") -} - -// Restore restores the saved position of the cursor -func (c *Cursor) Restore() { - fmt.Fprint(c.Out, "\x1b8") -} - -// for comparability purposes between windows -// in unix we need to print out a new line on some terminals -func (c *Cursor) MoveNextLine(cur *Coord, terminalSize *Coord) { - if cur.Y == terminalSize.Y { - fmt.Fprintln(c.Out) - } - c.NextLine(1) -} - -// Location returns the current location of the cursor in the terminal -func (c *Cursor) Location(buf *bytes.Buffer) (*Coord, error) { - // ANSI escape sequence for DSR - Device Status Report - // https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences - fmt.Fprint(c.Out, "\x1b[6n") - - // There may be input in Stdin prior to CursorLocation so make sure we don't - // drop those bytes. - var loc []int - var match string - for loc == nil { - // Reports the cursor position (CPR) to the application as (as though typed at - // the keyboard) ESC[n;mR, where n is the row and m is the column. - reader := bufio.NewReader(c.In) - text, err := reader.ReadSlice(byte('R')) - if err != nil { - return nil, err - } - - loc = dsrPattern.FindStringIndex(string(text)) - if loc == nil { - // After reading slice to byte 'R', the bufio Reader may have read more - // bytes into its internal buffer which will be discarded on next ReadSlice. - // We create a temporary buffer to read the remaining buffered slice and - // write them to output buffer. - buffered := make([]byte, reader.Buffered()) - _, err = io.ReadFull(reader, buffered) - if err != nil { - return nil, err - } - - // Stdin contains R that doesn't match DSR, so pass the bytes along to - // output buffer. - buf.Write(text) - buf.Write(buffered) - } else { - // Write the non-matching leading bytes to output buffer. - buf.Write(text[:loc[0]]) - - // Save the matching bytes to extract the row and column of the cursor. - match = string(text[loc[0]:loc[1]]) - } - } - - matches := dsrPattern.FindStringSubmatch(string(match)) - if len(matches) != 3 { - return nil, fmt.Errorf("incorrect number of matches: %d", len(matches)) - } - - col, err := strconv.Atoi(matches[2]) - if err != nil { - return nil, err - } - - row, err := strconv.Atoi(matches[1]) - if err != nil { - return nil, err - } - - return &Coord{Short(col), Short(row)}, nil -} - -func (cur Coord) CursorIsAtLineEnd(size *Coord) bool { - return cur.X == size.X -} - -func (cur Coord) CursorIsAtLineBegin() bool { - return cur.X == COORDINATE_SYSTEM_BEGIN -} - -// Size returns the height and width of the terminal. -func (c *Cursor) Size(buf *bytes.Buffer) (*Coord, error) { - // the general approach here is to move the cursor to the very bottom - // of the terminal, ask for the current location and then move the - // cursor back where we started - - // hide the cursor (so it doesn't blink when getting the size of the terminal) - c.Hide() - // save the current location of the cursor - c.Save() - - // move the cursor to the very bottom of the terminal - c.Move(999, 999) - - // ask for the current location - bottom, err := c.Location(buf) - if err != nil { - return nil, err - } - - // move back where we began - c.Restore() - - // show the cursor - c.Show() - // since the bottom was calculated in the lower right corner, it - // is the dimensions we are looking for - return bottom, nil -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor_windows.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor_windows.go deleted file mode 100644 index e24440e7..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/cursor_windows.go +++ /dev/null @@ -1,138 +0,0 @@ -package terminal - -import ( - "bytes" - "syscall" - "unsafe" -) - -var COORDINATE_SYSTEM_BEGIN Short = 0 - -// shared variable to save the cursor location from CursorSave() -var cursorLoc Coord - -type Cursor struct { - In FileReader - Out FileWriter -} - -func (c *Cursor) Up(n int) { - c.cursorMove(0, n) -} - -func (c *Cursor) Down(n int) { - c.cursorMove(0, -1*n) -} - -func (c *Cursor) Forward(n int) { - c.cursorMove(n, 0) -} - -func (c *Cursor) Back(n int) { - c.cursorMove(-1*n, 0) -} - -// save the cursor location -func (c *Cursor) Save() { - cursorLoc, _ = c.Location(nil) -} - -func (c *Cursor) Restore() { - handle := syscall.Handle(c.Out.Fd()) - // restore it to the original position - procSetConsoleCursorPosition.Call(uintptr(handle), uintptr(*(*int32)(unsafe.Pointer(&cursorLoc)))) -} - -func (cur Coord) CursorIsAtLineEnd(size *Coord) bool { - return cur.X == size.X -} - -func (cur Coord) CursorIsAtLineBegin() bool { - return cur.X == 0 -} - -func (c *Cursor) cursorMove(x int, y int) { - handle := syscall.Handle(c.Out.Fd()) - - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - - var cursor Coord - cursor.X = csbi.cursorPosition.X + Short(x) - cursor.Y = csbi.cursorPosition.Y + Short(y) - - procSetConsoleCursorPosition.Call(uintptr(handle), uintptr(*(*int32)(unsafe.Pointer(&cursor)))) -} - -func (c *Cursor) NextLine(n int) { - c.Up(n) - c.HorizontalAbsolute(0) -} - -func (c *Cursor) PreviousLine(n int) { - c.Down(n) - c.HorizontalAbsolute(0) -} - -// for comparability purposes between windows -// in windows we don't have to print out a new line -func (c *Cursor) MoveNextLine(cur Coord, terminalSize *Coord) { - c.NextLine(1) -} - -func (c *Cursor) HorizontalAbsolute(x int) { - handle := syscall.Handle(c.Out.Fd()) - - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - - var cursor Coord - cursor.X = Short(x) - cursor.Y = csbi.cursorPosition.Y - - if csbi.size.X < cursor.X { - cursor.X = csbi.size.X - } - - procSetConsoleCursorPosition.Call(uintptr(handle), uintptr(*(*int32)(unsafe.Pointer(&cursor)))) -} - -func (c *Cursor) Show() { - handle := syscall.Handle(c.Out.Fd()) - - var cci consoleCursorInfo - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&cci))) - cci.visible = 1 - - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&cci))) -} - -func (c *Cursor) Hide() { - handle := syscall.Handle(c.Out.Fd()) - - var cci consoleCursorInfo - procGetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&cci))) - cci.visible = 0 - - procSetConsoleCursorInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&cci))) -} - -func (c *Cursor) Location(buf *bytes.Buffer) (Coord, error) { - handle := syscall.Handle(c.Out.Fd()) - - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - - return csbi.cursorPosition, nil -} - -func (c *Cursor) Size(buf *bytes.Buffer) (*Coord, error) { - handle := syscall.Handle(c.Out.Fd()) - - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - // windows' coordinate system begins at (0, 0) - csbi.size.X-- - csbi.size.Y-- - return &csbi.size, nil -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/display.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/display.go deleted file mode 100644 index 0f014b13..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/display.go +++ /dev/null @@ -1,9 +0,0 @@ -package terminal - -type EraseLineMode int - -const ( - ERASE_LINE_END EraseLineMode = iota - ERASE_LINE_START - ERASE_LINE_ALL -) diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/display_posix.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/display_posix.go deleted file mode 100644 index 838dd664..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/display_posix.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !windows - -package terminal - -import ( - "fmt" -) - -func EraseLine(out FileWriter, mode EraseLineMode) { - fmt.Fprintf(out, "\x1b[%dK", mode) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/display_windows.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/display_windows.go deleted file mode 100644 index 0adc1ded..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/display_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -package terminal - -import ( - "syscall" - "unsafe" -) - -func EraseLine(out FileWriter, mode EraseLineMode) { - handle := syscall.Handle(out.Fd()) - - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - - var w uint32 - var x Short - cursor := csbi.cursorPosition - switch mode { - case ERASE_LINE_END: - x = csbi.size.X - case ERASE_LINE_START: - x = 0 - case ERASE_LINE_ALL: - cursor.X = 0 - x = csbi.size.X - } - procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(x), uintptr(*(*int32)(unsafe.Pointer(&cursor))), uintptr(unsafe.Pointer(&w))) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/error.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/error.go deleted file mode 100644 index 710c3614..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/error.go +++ /dev/null @@ -1,9 +0,0 @@ -package terminal - -import ( - "errors" -) - -var ( - InterruptErr = errors.New("interrupt") -) diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/output.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/output.go deleted file mode 100644 index 6fe11c08..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/output.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build !windows - -package terminal - -import ( - "io" -) - -// NewAnsiStdout returns special stdout, which converts escape sequences to Windows API calls -// on Windows environment. -func NewAnsiStdout(out FileWriter) io.Writer { - return out -} - -// NewAnsiStderr returns special stderr, which converts escape sequences to Windows API calls -// on Windows environment. -func NewAnsiStderr(out FileWriter) io.Writer { - return out -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/output_windows.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/output_windows.go deleted file mode 100644 index 6622690f..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/output_windows.go +++ /dev/null @@ -1,227 +0,0 @@ -package terminal - -import ( - "bytes" - "fmt" - "io" - "strconv" - "strings" - "syscall" - "unsafe" - - "github.com/mattn/go-isatty" -) - -var ( - cursorFunctions = map[rune]func(c *Cursor) func(int){ - 'A': func(c *Cursor) func(int) { return c.Up }, - 'B': func(c *Cursor) func(int) { return c.Down }, - 'C': func(c *Cursor) func(int) { return c.Forward }, - 'D': func(c *Cursor) func(int) { return c.Back }, - 'E': func(c *Cursor) func(int) { return c.NextLine }, - 'F': func(c *Cursor) func(int) { return c.PreviousLine }, - 'G': func(c *Cursor) func(int) { return c.HorizontalAbsolute }, - } -) - -const ( - foregroundBlue = 0x1 - foregroundGreen = 0x2 - foregroundRed = 0x4 - foregroundIntensity = 0x8 - foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) - backgroundBlue = 0x10 - backgroundGreen = 0x20 - backgroundRed = 0x40 - backgroundIntensity = 0x80 - backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) -) - -type Writer struct { - out FileWriter - handle syscall.Handle - orgAttr word -} - -func NewAnsiStdout(out FileWriter) io.Writer { - var csbi consoleScreenBufferInfo - if !isatty.IsTerminal(out.Fd()) { - return out - } - handle := syscall.Handle(out.Fd()) - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - return &Writer{out: out, handle: handle, orgAttr: csbi.attributes} -} - -func NewAnsiStderr(out FileWriter) io.Writer { - var csbi consoleScreenBufferInfo - if !isatty.IsTerminal(out.Fd()) { - return out - } - handle := syscall.Handle(out.Fd()) - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - return &Writer{out: out, handle: handle, orgAttr: csbi.attributes} -} - -func (w *Writer) Write(data []byte) (n int, err error) { - r := bytes.NewReader(data) - - for { - ch, size, err := r.ReadRune() - if err != nil { - break - } - n += size - - switch ch { - case '\x1b': - size, err = w.handleEscape(r) - n += size - if err != nil { - break - } - default: - fmt.Fprint(w.out, string(ch)) - } - } - return -} - -func (w *Writer) handleEscape(r *bytes.Reader) (n int, err error) { - buf := make([]byte, 0, 10) - buf = append(buf, "\x1b"...) - - // Check '[' continues after \x1b - ch, size, err := r.ReadRune() - if err != nil { - fmt.Fprint(w.out, string(buf)) - return - } - n += size - if ch != '[' { - fmt.Fprint(w.out, string(buf)) - return - } - - // Parse escape code - var code rune - argBuf := make([]byte, 0, 10) - for { - ch, size, err = r.ReadRune() - if err != nil { - fmt.Fprint(w.out, string(buf)) - return - } - n += size - if ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') { - code = ch - break - } - argBuf = append(argBuf, string(ch)...) - } - - w.applyEscapeCode(buf, string(argBuf), code) - return -} - -func (w *Writer) applyEscapeCode(buf []byte, arg string, code rune) { - c := &Cursor{Out: w.out} - - switch arg + string(code) { - case "?25h": - c.Show() - return - case "?25l": - c.Hide() - return - } - - if f, ok := cursorFunctions[code]; ok { - if n, err := strconv.Atoi(arg); err == nil { - f(c)(n) - return - } - } - - switch code { - case 'm': - w.applySelectGraphicRendition(arg) - default: - buf = append(buf, string(code)...) - fmt.Fprint(w.out, string(buf)) - } -} - -// Original implementation: https://github.com/mattn/go-colorable -func (w *Writer) applySelectGraphicRendition(arg string) { - if arg == "" { - procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.orgAttr)) - return - } - - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - attr := csbi.attributes - - for _, param := range strings.Split(arg, ";") { - n, err := strconv.Atoi(param) - if err != nil { - continue - } - - switch { - case n == 0 || n == 100: - attr = w.orgAttr - case 1 <= n && n <= 5: - attr |= foregroundIntensity - case 30 <= n && n <= 37: - attr = (attr & backgroundMask) - if (n-30)&1 != 0 { - attr |= foregroundRed - } - if (n-30)&2 != 0 { - attr |= foregroundGreen - } - if (n-30)&4 != 0 { - attr |= foregroundBlue - } - case 40 <= n && n <= 47: - attr = (attr & foregroundMask) - if (n-40)&1 != 0 { - attr |= backgroundRed - } - if (n-40)&2 != 0 { - attr |= backgroundGreen - } - if (n-40)&4 != 0 { - attr |= backgroundBlue - } - case 90 <= n && n <= 97: - attr = (attr & backgroundMask) - attr |= foregroundIntensity - if (n-90)&1 != 0 { - attr |= foregroundRed - } - if (n-90)&2 != 0 { - attr |= foregroundGreen - } - if (n-90)&4 != 0 { - attr |= foregroundBlue - } - case 100 <= n && n <= 107: - attr = (attr & foregroundMask) - attr |= backgroundIntensity - if (n-100)&1 != 0 { - attr |= backgroundRed - } - if (n-100)&2 != 0 { - attr |= backgroundGreen - } - if (n-100)&4 != 0 { - attr |= backgroundBlue - } - } - } - - procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr)) -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader.go deleted file mode 100644 index 05e91014..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader.go +++ /dev/null @@ -1,330 +0,0 @@ -package terminal - -import ( - "fmt" - "unicode" - - "golang.org/x/text/width" -) - -type RuneReader struct { - stdio Stdio - cursor *Cursor - state runeReaderState -} - -func NewRuneReader(stdio Stdio) *RuneReader { - return &RuneReader{ - stdio: stdio, - state: newRuneReaderState(stdio.In), - } -} - -func (rr *RuneReader) printChar(char rune, mask rune) { - // if we don't need to mask the input - if mask == 0 { - // just print the character the user pressed - fmt.Fprintf(rr.stdio.Out, "%c", char) - } else { - // otherwise print the mask we were given - fmt.Fprintf(rr.stdio.Out, "%c", mask) - } -} - -func (rr *RuneReader) ReadLine(mask rune) ([]rune, error) { - line := []rune{} - // we only care about horizontal displacements from the origin so start counting at 0 - index := 0 - - cursor := &Cursor{ - In: rr.stdio.In, - Out: rr.stdio.Out, - } - - // we get the terminal width and height (if resized after this point the property might become invalid) - terminalSize, _ := cursor.Size(rr.Buffer()) - // we set the current location of the cursor once - cursorCurrent, _ := cursor.Location(rr.Buffer()) - - for { - // wait for some input - r, _, err := rr.ReadRune() - if err != nil { - return line, err - } - // increment cursor location - cursorCurrent.X++ - - // if the user pressed enter or some other newline/termination like ctrl+d - if r == '\r' || r == '\n' || r == KeyEndTransmission { - // delete what's printed out on the console screen (cleanup) - for index > 0 { - if cursorCurrent.CursorIsAtLineBegin() { - EraseLine(rr.stdio.Out, ERASE_LINE_END) - cursor.PreviousLine(1) - cursor.Forward(int(terminalSize.X)) - cursorCurrent.X = terminalSize.X - cursorCurrent.Y-- - - } else { - cursor.Back(1) - cursorCurrent.X-- - } - index-- - } - // move the cursor the a new line - cursor.MoveNextLine(cursorCurrent, terminalSize) - - // we're done processing the input - return line, nil - } - // if the user interrupts (ie with ctrl+c) - if r == KeyInterrupt { - // go to the beginning of the next line - fmt.Fprint(rr.stdio.Out, "\r\n") - - // we're done processing the input, and treat interrupt like an error - return line, InterruptErr - } - - // allow for backspace/delete editing of inputs - if r == KeyBackspace || r == KeyDelete { - // and we're not at the beginning of the line - if index > 0 && len(line) > 0 { - // if we are at the end of the word - if index == len(line) { - // just remove the last letter from the internal representation - // also count the number of cells the rune before the cursor occupied - cells := runeWidth(line[len(line)-1]) - line = line[:len(line)-1] - // go back one - if cursorCurrent.X == 1 { - cursor.PreviousLine(1) - cursor.Forward(int(terminalSize.X)) - } else { - cursor.Back(cells) - } - - // clear the rest of the line - EraseLine(rr.stdio.Out, ERASE_LINE_END) - } else { - // we need to remove a character from the middle of the word - - cells := runeWidth(line[index-1]) - - // remove the current index from the list - line = append(line[:index-1], line[index:]...) - - // save the current position of the cursor, as we have to move the cursor one back to erase the current symbol - // and then move the cursor for each symbol in line[index-1:] to print it out, afterwards we want to restore - // the cursor to its previous location. - cursor.Save() - - // clear the rest of the line - cursor.Back(cells) - - // print what comes after - for _, char := range line[index-1:] { - //Erase symbols which are left over from older print - EraseLine(rr.stdio.Out, ERASE_LINE_END) - // print characters to the new line appropriately - rr.printChar(char, mask) - - } - // erase what's left over from last print - if cursorCurrent.Y < terminalSize.Y { - cursor.NextLine(1) - EraseLine(rr.stdio.Out, ERASE_LINE_END) - } - // restore cursor - cursor.Restore() - if cursorCurrent.CursorIsAtLineBegin() { - cursor.PreviousLine(1) - cursor.Forward(int(terminalSize.X)) - } else { - cursor.Back(cells) - } - } - - // decrement the index - index-- - } else { - // otherwise the user pressed backspace while at the beginning of the line - soundBell(rr.stdio.Out) - } - - // we're done processing this key - continue - } - - // if the left arrow is pressed - if r == KeyArrowLeft { - // if we have space to the left - if index > 0 { - //move the cursor to the prev line if necessary - if cursorCurrent.CursorIsAtLineBegin() { - cursor.PreviousLine(1) - cursor.Forward(int(terminalSize.X)) - } else { - cursor.Back(runeWidth(line[index-1])) - } - //decrement the index - index-- - - } else { - // otherwise we are at the beginning of where we started reading lines - // sound the bell - soundBell(rr.stdio.Out) - } - - // we're done processing this key press - continue - } - - // if the right arrow is pressed - if r == KeyArrowRight { - // if we have space to the right - if index < len(line) { - // move the cursor to the next line if necessary - if cursorCurrent.CursorIsAtLineEnd(terminalSize) { - cursor.NextLine(1) - } else { - cursor.Forward(runeWidth(line[index])) - } - index++ - - } else { - // otherwise we are at the end of the word and can't go past - // sound the bell - soundBell(rr.stdio.Out) - } - - // we're done processing this key press - continue - } - // the user pressed one of the special keys - if r == SpecialKeyHome { - for index > 0 { - if cursorCurrent.CursorIsAtLineBegin() { - cursor.PreviousLine(1) - cursor.Forward(int(terminalSize.X)) - cursorCurrent.X = terminalSize.X - cursorCurrent.Y-- - - } else { - cursor.Back(runeWidth(line[index-1])) - cursorCurrent.X-- - } - index-- - } - continue - // user pressed end - } else if r == SpecialKeyEnd { - for index != len(line) { - if cursorCurrent.CursorIsAtLineEnd(terminalSize) { - cursor.NextLine(1) - cursorCurrent.X = COORDINATE_SYSTEM_BEGIN - cursorCurrent.Y++ - - } else { - cursor.Forward(runeWidth(line[index])) - cursorCurrent.X++ - } - index++ - } - continue - // user pressed forward delete key - } else if r == SpecialKeyDelete { - // if index at the end of the line nothing to delete - if index != len(line) { - // save the current position of the cursor, as we have to erase the current symbol - // and then move the cursor for each symbol in line[index:] to print it out, afterwards we want to restore - // the cursor to its previous location. - cursor.Save() - // remove the symbol after the cursor - line = append(line[:index], line[index+1:]...) - // print the updated line - for _, char := range line[index:] { - EraseLine(rr.stdio.Out, ERASE_LINE_END) - // print out the character - rr.printChar(char, mask) - } - // erase what's left on last line - if cursorCurrent.Y < terminalSize.Y { - cursor.NextLine(1) - EraseLine(rr.stdio.Out, ERASE_LINE_END) - } - // restore cursor - cursor.Restore() - if len(line) == 0 || index == len(line) { - EraseLine(rr.stdio.Out, ERASE_LINE_END) - } - } - continue - } - - // if the letter is another escape sequence - if unicode.IsControl(r) || r == IgnoreKey { - // ignore it - continue - } - - // the user pressed a regular key - - // if we are at the end of the line - if index == len(line) { - // just append the character at the end of the line - line = append(line, r) - // save the location of the cursor - index++ - // print out the character - rr.printChar(r, mask) - } else { - // we are in the middle of the word so we need to insert the character the user pressed - line = append(line[:index], append([]rune{r}, line[index:]...)...) - // save the current position of the cursor, as we have to move the cursor back to erase the current symbol - // and then move for each symbol in line[index:] to print it out, afterwards we want to restore - // cursor's location to its previous one. - cursor.Save() - EraseLine(rr.stdio.Out, ERASE_LINE_END) - // remove the symbol after the cursor - // print the updated line - for _, char := range line[index:] { - EraseLine(rr.stdio.Out, ERASE_LINE_END) - // print out the character - rr.printChar(char, mask) - cursorCurrent.X++ - } - // if we are at the last line, we want to visually insert a new line and append to it. - if cursorCurrent.CursorIsAtLineEnd(terminalSize) && cursorCurrent.Y == terminalSize.Y { - // add a new line to the terminal - fmt.Fprintln(rr.stdio.Out) - // restore the position of the cursor horizontally - cursor.Restore() - // restore the position of the cursor vertically - cursor.PreviousLine(1) - } else { - // restore cursor - cursor.Restore() - } - // check if cursor needs to move to next line - cursorCurrent, _ = cursor.Location(rr.Buffer()) - if cursorCurrent.CursorIsAtLineEnd(terminalSize) { - cursor.NextLine(1) - } else { - cursor.Forward(runeWidth(r)) - } - // increment the index - index++ - - } - } -} - -func runeWidth(r rune) int { - switch width.LookupRune(r).Kind() { - case width.EastAsianWide, width.EastAsianFullwidth: - return 2 - } - return 1 -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_bsd.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_bsd.go deleted file mode 100644 index 6ea34092..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_bsd.go +++ /dev/null @@ -1,13 +0,0 @@ -// copied from: https://github.com/golang/crypto/blob/master/ssh/terminal/util_bsd.go -// Copyright 2013 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. - -// +build darwin dragonfly freebsd netbsd openbsd - -package terminal - -import "syscall" - -const ioctlReadTermios = syscall.TIOCGETA -const ioctlWriteTermios = syscall.TIOCSETA diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_linux.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_linux.go deleted file mode 100644 index 6dd60ea6..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_linux.go +++ /dev/null @@ -1,13 +0,0 @@ -// copied from https://github.com/golang/crypto/blob/master/ssh/terminal/util_linux.go -// Copyright 2013 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. -// +build linux,!ppc64le - -package terminal - -// These constants are declared here, rather than importing -// them from the syscall package as some syscall packages, even -// on linux, for example gccgo, do not declare them. -const ioctlReadTermios = 0x5401 // syscall.TCGETS -const ioctlWriteTermios = 0x5402 // syscall.TCSETS diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_posix.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_posix.go deleted file mode 100644 index a7e38425..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_posix.go +++ /dev/null @@ -1,111 +0,0 @@ -// +build !windows - -// The terminal mode manipulation code is derived heavily from: -// https://github.com/golang/crypto/blob/master/ssh/terminal/util.go: -// Copyright 2011 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 terminal - -import ( - "bufio" - "bytes" - "fmt" - "syscall" - "unsafe" -) - -type runeReaderState struct { - term syscall.Termios - reader *bufio.Reader - buf *bytes.Buffer -} - -func newRuneReaderState(input FileReader) runeReaderState { - buf := new(bytes.Buffer) - return runeReaderState{ - reader: bufio.NewReader(&BufferedReader{ - In: input, - Buffer: buf, - }), - buf: buf, - } -} - -func (rr *RuneReader) Buffer() *bytes.Buffer { - return rr.state.buf -} - -// For reading runes we just want to disable echo. -func (rr *RuneReader) SetTermMode() error { - if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlReadTermios, uintptr(unsafe.Pointer(&rr.state.term)), 0, 0, 0); err != 0 { - return err - } - - newState := rr.state.term - newState.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG - - if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlWriteTermios, uintptr(unsafe.Pointer(&newState)), 0, 0, 0); err != 0 { - return err - } - - return nil -} - -func (rr *RuneReader) RestoreTermMode() error { - if _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(rr.stdio.In.Fd()), ioctlWriteTermios, uintptr(unsafe.Pointer(&rr.state.term)), 0, 0, 0); err != 0 { - return err - } - return nil -} - -func (rr *RuneReader) ReadRune() (rune, int, error) { - r, size, err := rr.state.reader.ReadRune() - if err != nil { - return r, size, err - } - - // parse ^[ sequences to look for arrow keys - if r == '\033' { - if rr.state.reader.Buffered() == 0 { - // no more characters so must be `Esc` key - return KeyEscape, 1, nil - } - r, size, err = rr.state.reader.ReadRune() - if err != nil { - return r, size, err - } - if r != '[' { - return r, size, fmt.Errorf("Unexpected Escape Sequence: %q", []rune{'\033', r}) - } - r, size, err = rr.state.reader.ReadRune() - if err != nil { - return r, size, err - } - switch r { - case 'D': - return KeyArrowLeft, 1, nil - case 'C': - return KeyArrowRight, 1, nil - case 'A': - return KeyArrowUp, 1, nil - case 'B': - return KeyArrowDown, 1, nil - case 'H': // Home button - return SpecialKeyHome, 1, nil - case 'F': // End button - return SpecialKeyEnd, 1, nil - case '3': // Delete Button - // discard the following '~' key from buffer - rr.state.reader.Discard(1) - return SpecialKeyDelete, 1, nil - default: - // discard the following '~' key from buffer - rr.state.reader.Discard(1) - return IgnoreKey, 1, nil - } - return r, size, fmt.Errorf("Unknown Escape Sequence: %q", []rune{'\033', '[', r}) - } - return r, size, err -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_ppc64le.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_ppc64le.go deleted file mode 100644 index ae4eb097..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_ppc64le.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build ppc64le,linux - -package terminal - -// Used syscall numbers from https://github.com/golang/go/blob/master/src/syscall/ztypes_linux_ppc64le.go -const ioctlReadTermios = 0x402c7413 // syscall.TCGETS -const ioctlWriteTermios = 0x802c7414 // syscall.TCSETS diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_windows.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_windows.go deleted file mode 100644 index 791092f5..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/runereader_windows.go +++ /dev/null @@ -1,142 +0,0 @@ -package terminal - -import ( - "bytes" - "syscall" - "unsafe" -) - -var ( - dll = syscall.NewLazyDLL("kernel32.dll") - setConsoleMode = dll.NewProc("SetConsoleMode") - getConsoleMode = dll.NewProc("GetConsoleMode") - readConsoleInput = dll.NewProc("ReadConsoleInputW") -) - -const ( - EVENT_KEY = 0x0001 - - // key codes for arrow keys - // https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx - VK_DELETE = 0x2E - VK_END = 0x23 - VK_HOME = 0x24 - VK_LEFT = 0x25 - VK_UP = 0x26 - VK_RIGHT = 0x27 - VK_DOWN = 0x28 - - RIGHT_CTRL_PRESSED = 0x0004 - LEFT_CTRL_PRESSED = 0x0008 - - ENABLE_ECHO_INPUT uint32 = 0x0004 - ENABLE_LINE_INPUT uint32 = 0x0002 - ENABLE_PROCESSED_INPUT uint32 = 0x0001 -) - -type inputRecord struct { - eventType uint16 - padding uint16 - event [16]byte -} - -type keyEventRecord struct { - bKeyDown int32 - wRepeatCount uint16 - wVirtualKeyCode uint16 - wVirtualScanCode uint16 - unicodeChar uint16 - wdControlKeyState uint32 -} - -type runeReaderState struct { - term uint32 -} - -func newRuneReaderState(input FileReader) runeReaderState { - return runeReaderState{} -} - -func (rr *RuneReader) Buffer() *bytes.Buffer { - return nil -} - -func (rr *RuneReader) SetTermMode() error { - r, _, err := getConsoleMode.Call(uintptr(rr.stdio.In.Fd()), uintptr(unsafe.Pointer(&rr.state.term))) - // windows return 0 on error - if r == 0 { - return err - } - - newState := rr.state.term - newState &^= ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT - r, _, err = setConsoleMode.Call(uintptr(rr.stdio.In.Fd()), uintptr(newState)) - // windows return 0 on error - if r == 0 { - return err - } - return nil -} - -func (rr *RuneReader) RestoreTermMode() error { - r, _, err := setConsoleMode.Call(uintptr(rr.stdio.In.Fd()), uintptr(rr.state.term)) - // windows return 0 on error - if r == 0 { - return err - } - return nil -} - -func (rr *RuneReader) ReadRune() (rune, int, error) { - ir := &inputRecord{} - bytesRead := 0 - for { - rv, _, e := readConsoleInput.Call(rr.stdio.In.Fd(), uintptr(unsafe.Pointer(ir)), 1, uintptr(unsafe.Pointer(&bytesRead))) - // windows returns non-zero to indicate success - if rv == 0 && e != nil { - return 0, 0, e - } - - if ir.eventType != EVENT_KEY { - continue - } - - // the event data is really a c struct union, so here we have to do an usafe - // cast to put the data into the keyEventRecord (since we have already verified - // above that this event does correspond to a key event - key := (*keyEventRecord)(unsafe.Pointer(&ir.event[0])) - // we only care about key down events - if key.bKeyDown == 0 { - continue - } - if key.wdControlKeyState&(LEFT_CTRL_PRESSED|RIGHT_CTRL_PRESSED) != 0 && key.unicodeChar == 'C' { - return KeyInterrupt, bytesRead, nil - } - // not a normal character so look up the input sequence from the - // virtual key code mappings (VK_*) - if key.unicodeChar == 0 { - switch key.wVirtualKeyCode { - case VK_DOWN: - return KeyArrowDown, bytesRead, nil - case VK_LEFT: - return KeyArrowLeft, bytesRead, nil - case VK_RIGHT: - return KeyArrowRight, bytesRead, nil - case VK_UP: - return KeyArrowUp, bytesRead, nil - case VK_DELETE: - return SpecialKeyDelete, bytesRead, nil - case VK_HOME: - return SpecialKeyHome, bytesRead, nil - case VK_END: - return SpecialKeyEnd, bytesRead, nil - default: - // not a virtual key that we care about so just continue on to - // the next input key - continue - } - } - r := rune(key.unicodeChar) - return r, bytesRead, nil - } -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/sequences.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/sequences.go deleted file mode 100644 index 6d9e8775..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/sequences.go +++ /dev/null @@ -1,31 +0,0 @@ -package terminal - -import ( - "fmt" - "io" -) - -const ( - KeyArrowLeft = '\x02' - KeyArrowRight = '\x06' - KeyArrowUp = '\x10' - KeyArrowDown = '\x0e' - KeySpace = ' ' - KeyEnter = '\r' - KeyBackspace = '\b' - KeyDelete = '\x7f' - KeyInterrupt = '\x03' - KeyEndTransmission = '\x04' - KeyEscape = '\x1b' - KeyDeleteWord = '\x17' // Ctrl+W - KeyDeleteLine = '\x18' // Ctrl+X - SpecialKeyHome = '\x01' - SpecialKeyEnd = '\x11' - SpecialKeyDelete = '\x12' - IgnoreKey = '\000' - KeyTab = '\t' -) - -func soundBell(out io.Writer) { - fmt.Fprint(out, "\a") -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/stdio.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/stdio.go deleted file mode 100644 index 88bf7c4e..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/stdio.go +++ /dev/null @@ -1,24 +0,0 @@ -package terminal - -import ( - "io" -) - -// Stdio is the standard input/output the terminal reads/writes with. -type Stdio struct { - In FileReader - Out FileWriter - Err io.Writer -} - -// FileWriter provides a minimal interface for Stdin. -type FileWriter interface { - io.Writer - Fd() uintptr -} - -// FileReader provides a minimal interface for Stdout. -type FileReader interface { - io.Reader - Fd() uintptr -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/syscall_windows.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/syscall_windows.go deleted file mode 100644 index 63b85d4c..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/syscall_windows.go +++ /dev/null @@ -1,39 +0,0 @@ -package terminal - -import ( - "syscall" -) - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") - procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") - procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") - procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") - procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") - procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") -) - -type wchar uint16 -type dword uint32 -type word uint16 - -type smallRect struct { - left Short - top Short - right Short - bottom Short -} - -type consoleScreenBufferInfo struct { - size Coord - cursorPosition Coord - attributes word - window smallRect - maximumWindowSize Coord -} - -type consoleCursorInfo struct { - size dword - visible int32 -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/terminal/terminal.go b/vendor/github.com/AlecAivazis/survey/v2/terminal/terminal.go deleted file mode 100644 index 4b59062c..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/terminal/terminal.go +++ /dev/null @@ -1,8 +0,0 @@ -package terminal - -type Short int16 - -type Coord struct { - X Short - Y Short -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/transform.go b/vendor/github.com/AlecAivazis/survey/v2/transform.go deleted file mode 100644 index 58d5193b..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/transform.go +++ /dev/null @@ -1,79 +0,0 @@ -package survey - -import ( - "reflect" - "strings" -) - -// TransformString returns a `Transformer` based on the "f" -// function which accepts a string representation of the answer -// and returns a new one, transformed, answer. -// Take for example the functions inside the std `strings` package, -// they can be converted to a compatible `Transformer` by using this function, -// i.e: `TransformString(strings.Title)`, `TransformString(strings.ToUpper)`. -// -// Note that `TransformString` is just a helper, `Transformer` can be used -// to transform any type of answer. -func TransformString(f func(s string) string) Transformer { - return func(ans interface{}) interface{} { - // if the answer value passed in is the zero value of the appropriate type - if isZero(reflect.ValueOf(ans)) { - // skip this `Transformer` by returning a zero value of string. - // The original answer will be not affected, - // see survey.go#L125. - // A zero value of string should be returned to be handled by - // next Transformer in a composed Tranformer, - // see tranform.go#L75 - return "" - } - - // "ans" is never nil here, so we don't have to check that - // see survey.go#L338 for more. - // Make sure that the the answer's value was a typeof string. - s, ok := ans.(string) - if !ok { - return "" - } - - return f(s) - } -} - -// ToLower is a `Transformer`. -// It receives an answer value -// and returns a copy of the "ans" -// with all Unicode letters mapped to their lower case. -// -// Note that if "ans" is not a string then it will -// return a nil value, meaning that the above answer -// will not be affected by this call at all. -func ToLower(ans interface{}) interface{} { - transformer := TransformString(strings.ToLower) - return transformer(ans) -} - -// Title is a `Transformer`. -// It receives an answer value -// and returns a copy of the "ans" -// with all Unicode letters that begin words -// mapped to their title case. -// -// Note that if "ans" is not a string then it will -// return a nil value, meaning that the above answer -// will not be affected by this call at all. -func Title(ans interface{}) interface{} { - transformer := TransformString(strings.Title) - return transformer(ans) -} - -// ComposeTransformers is a variadic function used to create one transformer from many. -func ComposeTransformers(transformers ...Transformer) Transformer { - // return a transformer that calls each one sequentially - return func(ans interface{}) interface{} { - // execute each transformer - for _, t := range transformers { - ans = t(ans) - } - return ans - } -} diff --git a/vendor/github.com/AlecAivazis/survey/v2/validate.go b/vendor/github.com/AlecAivazis/survey/v2/validate.go deleted file mode 100644 index ba7e1278..00000000 --- a/vendor/github.com/AlecAivazis/survey/v2/validate.go +++ /dev/null @@ -1,87 +0,0 @@ -package survey - -import ( - "errors" - "fmt" - "reflect" -) - -// Required does not allow an empty value -func Required(val interface{}) error { - // the reflect value of the result - value := reflect.ValueOf(val) - - // if the value passed in is the zero value of the appropriate type - if isZero(value) && value.Kind() != reflect.Bool { - return errors.New("Value is required") - } - return nil -} - -// MaxLength requires that the string is no longer than the specified value -func MaxLength(length int) Validator { - // return a validator that checks the length of the string - return func(val interface{}) error { - if str, ok := val.(string); ok { - // if the string is longer than the given value - if len([]rune(str)) > length { - // yell loudly - return fmt.Errorf("value is too long. Max length is %v", length) - } - } else { - // otherwise we cannot convert the value into a string and cannot enforce length - return fmt.Errorf("cannot enforce length on response of type %v", reflect.TypeOf(val).Name()) - } - - // the input is fine - return nil - } -} - -// MinLength requires that the string is longer or equal in length to the specified value -func MinLength(length int) Validator { - // return a validator that checks the length of the string - return func(val interface{}) error { - if str, ok := val.(string); ok { - // if the string is shorter than the given value - if len([]rune(str)) < length { - // yell loudly - return fmt.Errorf("value is too short. Min length is %v", length) - } - } else { - // otherwise we cannot convert the value into a string and cannot enforce length - return fmt.Errorf("cannot enforce length on response of type %v", reflect.TypeOf(val).Name()) - } - - // the input is fine - return nil - } -} - -// ComposeValidators is a variadic function used to create one validator from many. -func ComposeValidators(validators ...Validator) Validator { - // return a validator that calls each one sequentially - return func(val interface{}) error { - // execute each validator - for _, validator := range validators { - // if the answer's value is not valid - if err := validator(val); err != nil { - // return the error - return err - } - } - // we passed all validators, the answer is valid - return nil - } -} - -// isZero returns true if the passed value is the zero object -func isZero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Slice, reflect.Map: - return v.Len() == 0 - } - - // compare the types directly with more general coverage - return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/LICENSE b/vendor/github.com/Azure/azure-sdk-for-go/LICENSE deleted file mode 100644 index 047555ec..00000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/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 2020 Microsoft Corporation - - 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/Azure/azure-sdk-for-go/NOTICE b/vendor/github.com/Azure/azure-sdk-for-go/NOTICE deleted file mode 100644 index 2d1d7260..00000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -Microsoft Azure-SDK-for-Go -Copyright 2014-2017 Microsoft - -This product includes software developed at -the Microsoft Corporation (https://www.microsoft.com). diff --git a/vendor/github.com/Azure/azure-sdk-for-go/profiles/latest/keyvault/keyvault/models.go b/vendor/github.com/Azure/azure-sdk-for-go/profiles/latest/keyvault/keyvault/models.go deleted file mode 100644 index 3756079a..00000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/profiles/latest/keyvault/keyvault/models.go +++ /dev/null @@ -1,300 +0,0 @@ -// +build go1.9 - -// Copyright 2021 Microsoft Corporation -// -// 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. - -// This code was auto-generated by: -// github.com/Azure/azure-sdk-for-go/tools/profileBuilder - -package keyvault - -import ( - "context" - - original "github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault" -) - -type ActionType = original.ActionType - -const ( - AutoRenew ActionType = original.AutoRenew - EmailContacts ActionType = original.EmailContacts -) - -type DeletionRecoveryLevel = original.DeletionRecoveryLevel - -const ( - Purgeable DeletionRecoveryLevel = original.Purgeable - Recoverable DeletionRecoveryLevel = original.Recoverable - RecoverableProtectedSubscription DeletionRecoveryLevel = original.RecoverableProtectedSubscription - RecoverablePurgeable DeletionRecoveryLevel = original.RecoverablePurgeable -) - -type JSONWebKeyCurveName = original.JSONWebKeyCurveName - -const ( - P256 JSONWebKeyCurveName = original.P256 - P384 JSONWebKeyCurveName = original.P384 - P521 JSONWebKeyCurveName = original.P521 - SECP256K1 JSONWebKeyCurveName = original.SECP256K1 -) - -type JSONWebKeyEncryptionAlgorithm = original.JSONWebKeyEncryptionAlgorithm - -const ( - RSA15 JSONWebKeyEncryptionAlgorithm = original.RSA15 - RSAOAEP JSONWebKeyEncryptionAlgorithm = original.RSAOAEP - RSAOAEP256 JSONWebKeyEncryptionAlgorithm = original.RSAOAEP256 -) - -type JSONWebKeyOperation = original.JSONWebKeyOperation - -const ( - Decrypt JSONWebKeyOperation = original.Decrypt - Encrypt JSONWebKeyOperation = original.Encrypt - Sign JSONWebKeyOperation = original.Sign - UnwrapKey JSONWebKeyOperation = original.UnwrapKey - Verify JSONWebKeyOperation = original.Verify - WrapKey JSONWebKeyOperation = original.WrapKey -) - -type JSONWebKeySignatureAlgorithm = original.JSONWebKeySignatureAlgorithm - -const ( - ECDSA256 JSONWebKeySignatureAlgorithm = original.ECDSA256 - ES256 JSONWebKeySignatureAlgorithm = original.ES256 - ES384 JSONWebKeySignatureAlgorithm = original.ES384 - ES512 JSONWebKeySignatureAlgorithm = original.ES512 - PS256 JSONWebKeySignatureAlgorithm = original.PS256 - PS384 JSONWebKeySignatureAlgorithm = original.PS384 - PS512 JSONWebKeySignatureAlgorithm = original.PS512 - RS256 JSONWebKeySignatureAlgorithm = original.RS256 - RS384 JSONWebKeySignatureAlgorithm = original.RS384 - RS512 JSONWebKeySignatureAlgorithm = original.RS512 - RSNULL JSONWebKeySignatureAlgorithm = original.RSNULL -) - -type JSONWebKeyType = original.JSONWebKeyType - -const ( - EC JSONWebKeyType = original.EC - ECHSM JSONWebKeyType = original.ECHSM - Oct JSONWebKeyType = original.Oct - RSA JSONWebKeyType = original.RSA - RSAHSM JSONWebKeyType = original.RSAHSM -) - -type KeyUsageType = original.KeyUsageType - -const ( - CRLSign KeyUsageType = original.CRLSign - DataEncipherment KeyUsageType = original.DataEncipherment - DecipherOnly KeyUsageType = original.DecipherOnly - DigitalSignature KeyUsageType = original.DigitalSignature - EncipherOnly KeyUsageType = original.EncipherOnly - KeyAgreement KeyUsageType = original.KeyAgreement - KeyCertSign KeyUsageType = original.KeyCertSign - KeyEncipherment KeyUsageType = original.KeyEncipherment - NonRepudiation KeyUsageType = original.NonRepudiation -) - -type Action = original.Action -type AdministratorDetails = original.AdministratorDetails -type Attributes = original.Attributes -type BackupKeyResult = original.BackupKeyResult -type BackupSecretResult = original.BackupSecretResult -type BaseClient = original.BaseClient -type CertificateAttributes = original.CertificateAttributes -type CertificateBundle = original.CertificateBundle -type CertificateCreateParameters = original.CertificateCreateParameters -type CertificateImportParameters = original.CertificateImportParameters -type CertificateIssuerItem = original.CertificateIssuerItem -type CertificateIssuerListResult = original.CertificateIssuerListResult -type CertificateIssuerListResultIterator = original.CertificateIssuerListResultIterator -type CertificateIssuerListResultPage = original.CertificateIssuerListResultPage -type CertificateIssuerSetParameters = original.CertificateIssuerSetParameters -type CertificateIssuerUpdateParameters = original.CertificateIssuerUpdateParameters -type CertificateItem = original.CertificateItem -type CertificateListResult = original.CertificateListResult -type CertificateListResultIterator = original.CertificateListResultIterator -type CertificateListResultPage = original.CertificateListResultPage -type CertificateMergeParameters = original.CertificateMergeParameters -type CertificateOperation = original.CertificateOperation -type CertificateOperationUpdateParameter = original.CertificateOperationUpdateParameter -type CertificatePolicy = original.CertificatePolicy -type CertificateUpdateParameters = original.CertificateUpdateParameters -type Contact = original.Contact -type Contacts = original.Contacts -type DeletedCertificateBundle = original.DeletedCertificateBundle -type DeletedCertificateItem = original.DeletedCertificateItem -type DeletedCertificateListResult = original.DeletedCertificateListResult -type DeletedCertificateListResultIterator = original.DeletedCertificateListResultIterator -type DeletedCertificateListResultPage = original.DeletedCertificateListResultPage -type DeletedKeyBundle = original.DeletedKeyBundle -type DeletedKeyItem = original.DeletedKeyItem -type DeletedKeyListResult = original.DeletedKeyListResult -type DeletedKeyListResultIterator = original.DeletedKeyListResultIterator -type DeletedKeyListResultPage = original.DeletedKeyListResultPage -type DeletedSecretBundle = original.DeletedSecretBundle -type DeletedSecretItem = original.DeletedSecretItem -type DeletedSecretListResult = original.DeletedSecretListResult -type DeletedSecretListResultIterator = original.DeletedSecretListResultIterator -type DeletedSecretListResultPage = original.DeletedSecretListResultPage -type Error = original.Error -type ErrorType = original.ErrorType -type IssuerAttributes = original.IssuerAttributes -type IssuerBundle = original.IssuerBundle -type IssuerCredentials = original.IssuerCredentials -type IssuerParameters = original.IssuerParameters -type JSONWebKey = original.JSONWebKey -type KeyAttributes = original.KeyAttributes -type KeyBundle = original.KeyBundle -type KeyCreateParameters = original.KeyCreateParameters -type KeyImportParameters = original.KeyImportParameters -type KeyItem = original.KeyItem -type KeyListResult = original.KeyListResult -type KeyListResultIterator = original.KeyListResultIterator -type KeyListResultPage = original.KeyListResultPage -type KeyOperationResult = original.KeyOperationResult -type KeyOperationsParameters = original.KeyOperationsParameters -type KeyProperties = original.KeyProperties -type KeyRestoreParameters = original.KeyRestoreParameters -type KeySignParameters = original.KeySignParameters -type KeyUpdateParameters = original.KeyUpdateParameters -type KeyVerifyParameters = original.KeyVerifyParameters -type KeyVerifyResult = original.KeyVerifyResult -type LifetimeAction = original.LifetimeAction -type OrganizationDetails = original.OrganizationDetails -type PendingCertificateSigningRequestResult = original.PendingCertificateSigningRequestResult -type SasDefinitionAttributes = original.SasDefinitionAttributes -type SasDefinitionBundle = original.SasDefinitionBundle -type SasDefinitionCreateParameters = original.SasDefinitionCreateParameters -type SasDefinitionItem = original.SasDefinitionItem -type SasDefinitionListResult = original.SasDefinitionListResult -type SasDefinitionListResultIterator = original.SasDefinitionListResultIterator -type SasDefinitionListResultPage = original.SasDefinitionListResultPage -type SasDefinitionUpdateParameters = original.SasDefinitionUpdateParameters -type SecretAttributes = original.SecretAttributes -type SecretBundle = original.SecretBundle -type SecretItem = original.SecretItem -type SecretListResult = original.SecretListResult -type SecretListResultIterator = original.SecretListResultIterator -type SecretListResultPage = original.SecretListResultPage -type SecretProperties = original.SecretProperties -type SecretRestoreParameters = original.SecretRestoreParameters -type SecretSetParameters = original.SecretSetParameters -type SecretUpdateParameters = original.SecretUpdateParameters -type StorageAccountAttributes = original.StorageAccountAttributes -type StorageAccountCreateParameters = original.StorageAccountCreateParameters -type StorageAccountItem = original.StorageAccountItem -type StorageAccountRegenerteKeyParameters = original.StorageAccountRegenerteKeyParameters -type StorageAccountUpdateParameters = original.StorageAccountUpdateParameters -type StorageBundle = original.StorageBundle -type StorageListResult = original.StorageListResult -type StorageListResultIterator = original.StorageListResultIterator -type StorageListResultPage = original.StorageListResultPage -type SubjectAlternativeNames = original.SubjectAlternativeNames -type Trigger = original.Trigger -type X509CertificateProperties = original.X509CertificateProperties - -func New() BaseClient { - return original.New() -} -func NewCertificateIssuerListResultIterator(page CertificateIssuerListResultPage) CertificateIssuerListResultIterator { - return original.NewCertificateIssuerListResultIterator(page) -} -func NewCertificateIssuerListResultPage(cur CertificateIssuerListResult, getNextPage func(context.Context, CertificateIssuerListResult) (CertificateIssuerListResult, error)) CertificateIssuerListResultPage { - return original.NewCertificateIssuerListResultPage(cur, getNextPage) -} -func NewCertificateListResultIterator(page CertificateListResultPage) CertificateListResultIterator { - return original.NewCertificateListResultIterator(page) -} -func NewCertificateListResultPage(cur CertificateListResult, getNextPage func(context.Context, CertificateListResult) (CertificateListResult, error)) CertificateListResultPage { - return original.NewCertificateListResultPage(cur, getNextPage) -} -func NewDeletedCertificateListResultIterator(page DeletedCertificateListResultPage) DeletedCertificateListResultIterator { - return original.NewDeletedCertificateListResultIterator(page) -} -func NewDeletedCertificateListResultPage(cur DeletedCertificateListResult, getNextPage func(context.Context, DeletedCertificateListResult) (DeletedCertificateListResult, error)) DeletedCertificateListResultPage { - return original.NewDeletedCertificateListResultPage(cur, getNextPage) -} -func NewDeletedKeyListResultIterator(page DeletedKeyListResultPage) DeletedKeyListResultIterator { - return original.NewDeletedKeyListResultIterator(page) -} -func NewDeletedKeyListResultPage(cur DeletedKeyListResult, getNextPage func(context.Context, DeletedKeyListResult) (DeletedKeyListResult, error)) DeletedKeyListResultPage { - return original.NewDeletedKeyListResultPage(cur, getNextPage) -} -func NewDeletedSecretListResultIterator(page DeletedSecretListResultPage) DeletedSecretListResultIterator { - return original.NewDeletedSecretListResultIterator(page) -} -func NewDeletedSecretListResultPage(cur DeletedSecretListResult, getNextPage func(context.Context, DeletedSecretListResult) (DeletedSecretListResult, error)) DeletedSecretListResultPage { - return original.NewDeletedSecretListResultPage(cur, getNextPage) -} -func NewKeyListResultIterator(page KeyListResultPage) KeyListResultIterator { - return original.NewKeyListResultIterator(page) -} -func NewKeyListResultPage(cur KeyListResult, getNextPage func(context.Context, KeyListResult) (KeyListResult, error)) KeyListResultPage { - return original.NewKeyListResultPage(cur, getNextPage) -} -func NewSasDefinitionListResultIterator(page SasDefinitionListResultPage) SasDefinitionListResultIterator { - return original.NewSasDefinitionListResultIterator(page) -} -func NewSasDefinitionListResultPage(cur SasDefinitionListResult, getNextPage func(context.Context, SasDefinitionListResult) (SasDefinitionListResult, error)) SasDefinitionListResultPage { - return original.NewSasDefinitionListResultPage(cur, getNextPage) -} -func NewSecretListResultIterator(page SecretListResultPage) SecretListResultIterator { - return original.NewSecretListResultIterator(page) -} -func NewSecretListResultPage(cur SecretListResult, getNextPage func(context.Context, SecretListResult) (SecretListResult, error)) SecretListResultPage { - return original.NewSecretListResultPage(cur, getNextPage) -} -func NewStorageListResultIterator(page StorageListResultPage) StorageListResultIterator { - return original.NewStorageListResultIterator(page) -} -func NewStorageListResultPage(cur StorageListResult, getNextPage func(context.Context, StorageListResult) (StorageListResult, error)) StorageListResultPage { - return original.NewStorageListResultPage(cur, getNextPage) -} -func NewWithoutDefaults() BaseClient { - return original.NewWithoutDefaults() -} -func PossibleActionTypeValues() []ActionType { - return original.PossibleActionTypeValues() -} -func PossibleDeletionRecoveryLevelValues() []DeletionRecoveryLevel { - return original.PossibleDeletionRecoveryLevelValues() -} -func PossibleJSONWebKeyCurveNameValues() []JSONWebKeyCurveName { - return original.PossibleJSONWebKeyCurveNameValues() -} -func PossibleJSONWebKeyEncryptionAlgorithmValues() []JSONWebKeyEncryptionAlgorithm { - return original.PossibleJSONWebKeyEncryptionAlgorithmValues() -} -func PossibleJSONWebKeyOperationValues() []JSONWebKeyOperation { - return original.PossibleJSONWebKeyOperationValues() -} -func PossibleJSONWebKeySignatureAlgorithmValues() []JSONWebKeySignatureAlgorithm { - return original.PossibleJSONWebKeySignatureAlgorithmValues() -} -func PossibleJSONWebKeyTypeValues() []JSONWebKeyType { - return original.PossibleJSONWebKeyTypeValues() -} -func PossibleKeyUsageTypeValues() []KeyUsageType { - return original.PossibleKeyUsageTypeValues() -} -func UserAgent() string { - return original.UserAgent() + " profiles/latest" -} -func Version() string { - return original.Version() -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/CHANGELOG.md b/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/CHANGELOG.md deleted file mode 100644 index cfd13d67..00000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/CHANGELOG.md +++ /dev/null @@ -1,5 +0,0 @@ -Generated from https://github.com/Azure/azure-rest-api-specs/tree/3c764635e7d442b3e74caf593029fcd440b3ef82//specification/keyvault/data-plane/readme.md tag: `package-2016-10` - -Code generator @microsoft.azure/autorest.go@2.1.175 - - diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/client.go deleted file mode 100644 index 0d8f5964..00000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/client.go +++ /dev/null @@ -1,6288 +0,0 @@ -// Package keyvault implements the Azure ARM Keyvault service API version 2016-10-01. -// -// The key vault client performs cryptographic key operations and vault operations against the Key Vault service. -package keyvault - -// Copyright (c) Microsoft and contributors. 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. -// 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 Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// BaseClient is the base client for Keyvault. -type BaseClient struct { - autorest.Client -} - -// New creates an instance of the BaseClient client. -func New() BaseClient { - return NewWithoutDefaults() -} - -// NewWithoutDefaults creates an instance of the BaseClient client. -func NewWithoutDefaults() BaseClient { - return BaseClient{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - } -} - -// BackupKey the Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation -// does NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key -// material is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is -// to allow a client to GENERATE a key in one Azure Key Vault instance, BACKUP the key, and then RESTORE it into -// another Azure Key Vault instance. The BACKUP operation may be used to export, in protected form, any key type from -// Azure Key Vault. Individual versions of a key cannot be backed up. BACKUP / RESTORE can be performed within -// geographical boundaries only; meaning that a BACKUP from one geographical area cannot be restored to another -// geographical area. For example, a backup from the US geographical area cannot be restored in an EU geographical -// area. This operation requires the key/backup permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key. -func (client BaseClient) BackupKey(ctx context.Context, vaultBaseURL string, keyName string) (result BackupKeyResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.BackupKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.BackupKeyPreparer(ctx, vaultBaseURL, keyName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "BackupKey", nil, "Failure preparing request") - return - } - - resp, err := client.BackupKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "BackupKey", resp, "Failure sending request") - return - } - - result, err = client.BackupKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "BackupKey", resp, "Failure responding to request") - return - } - - return -} - -// BackupKeyPreparer prepares the BackupKey request. -func (client BaseClient) BackupKeyPreparer(ctx context.Context, vaultBaseURL string, keyName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}/backup", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// BackupKeySender sends the BackupKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) BackupKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// BackupKeyResponder handles the response to the BackupKey request. The method always -// closes the http.Response Body. -func (client BaseClient) BackupKeyResponder(resp *http.Response) (result BackupKeyResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// BackupSecret requests that a backup of the specified secret be downloaded to the client. All versions of the secret -// will be downloaded. This operation requires the secrets/backup permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// secretName - the name of the secret. -func (client BaseClient) BackupSecret(ctx context.Context, vaultBaseURL string, secretName string) (result BackupSecretResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.BackupSecret") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.BackupSecretPreparer(ctx, vaultBaseURL, secretName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "BackupSecret", nil, "Failure preparing request") - return - } - - resp, err := client.BackupSecretSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "BackupSecret", resp, "Failure sending request") - return - } - - result, err = client.BackupSecretResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "BackupSecret", resp, "Failure responding to request") - return - } - - return -} - -// BackupSecretPreparer prepares the BackupSecret request. -func (client BaseClient) BackupSecretPreparer(ctx context.Context, vaultBaseURL string, secretName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "secret-name": autorest.Encode("path", secretName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/secrets/{secret-name}/backup", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// BackupSecretSender sends the BackupSecret request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) BackupSecretSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// BackupSecretResponder handles the response to the BackupSecret request. The method always -// closes the http.Response Body. -func (client BaseClient) BackupSecretResponder(resp *http.Response) (result BackupSecretResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateCertificate if this is the first version, the certificate resource is created. This operation requires the -// certificates/create permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate. -// parameters - the parameters to create a certificate. -func (client BaseClient) CreateCertificate(ctx context.Context, vaultBaseURL string, certificateName string, parameters CertificateCreateParameters) (result CertificateOperation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.CreateCertificate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: certificateName, - Constraints: []validation.Constraint{{Target: "certificateName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z-]+$`, Chain: nil}}}, - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.CertificatePolicy", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.CertificatePolicy.X509CertificateProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.CertificatePolicy.X509CertificateProperties.ValidityInMonths", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.CertificatePolicy.X509CertificateProperties.ValidityInMonths", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}, - }}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "CreateCertificate", err.Error()) - } - - req, err := client.CreateCertificatePreparer(ctx, vaultBaseURL, certificateName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "CreateCertificate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateCertificateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "CreateCertificate", resp, "Failure sending request") - return - } - - result, err = client.CreateCertificateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "CreateCertificate", resp, "Failure responding to request") - return - } - - return -} - -// CreateCertificatePreparer prepares the CreateCertificate request. -func (client BaseClient) CreateCertificatePreparer(ctx context.Context, vaultBaseURL string, certificateName string, parameters CertificateCreateParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}/create", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateCertificateSender sends the CreateCertificate request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) CreateCertificateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateCertificateResponder handles the response to the CreateCertificate request. The method always -// closes the http.Response Body. -func (client BaseClient) CreateCertificateResponder(resp *http.Response) (result CertificateOperation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// CreateKey the create key operation can be used to create any key type in Azure Key Vault. If the named key already -// exists, Azure Key Vault creates a new version of the key. It requires the keys/create permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name for the new key. The system will generate the version name for the new key. -// parameters - the parameters to create a key. -func (client BaseClient) CreateKey(ctx context.Context, vaultBaseURL string, keyName string, parameters KeyCreateParameters) (result KeyBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.CreateKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: keyName, - Constraints: []validation.Constraint{{Target: "keyName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z-]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "CreateKey", err.Error()) - } - - req, err := client.CreateKeyPreparer(ctx, vaultBaseURL, keyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "CreateKey", nil, "Failure preparing request") - return - } - - resp, err := client.CreateKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "CreateKey", resp, "Failure sending request") - return - } - - result, err = client.CreateKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "CreateKey", resp, "Failure responding to request") - return - } - - return -} - -// CreateKeyPreparer prepares the CreateKey request. -func (client BaseClient) CreateKeyPreparer(ctx context.Context, vaultBaseURL string, keyName string, parameters KeyCreateParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}/create", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateKeySender sends the CreateKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) CreateKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// CreateKeyResponder handles the response to the CreateKey request. The method always -// closes the http.Response Body. -func (client BaseClient) CreateKeyResponder(resp *http.Response) (result KeyBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Decrypt the DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and -// specified algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be -// decrypted, the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation -// applies to asymmetric and symmetric keys stored in Azure Key Vault since it uses the private portion of the key. -// This operation requires the keys/decrypt permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key. -// keyVersion - the version of the key. -// parameters - the parameters for the decryption operation. -func (client BaseClient) Decrypt(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyOperationsParameters) (result KeyOperationResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.Decrypt") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Value", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "Decrypt", err.Error()) - } - - req, err := client.DecryptPreparer(ctx, vaultBaseURL, keyName, keyVersion, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Decrypt", nil, "Failure preparing request") - return - } - - resp, err := client.DecryptSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Decrypt", resp, "Failure sending request") - return - } - - result, err = client.DecryptResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Decrypt", resp, "Failure responding to request") - return - } - - return -} - -// DecryptPreparer prepares the Decrypt request. -func (client BaseClient) DecryptPreparer(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyOperationsParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - "key-version": autorest.Encode("path", keyVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}/{key-version}/decrypt", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DecryptSender sends the Decrypt request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) DecryptSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DecryptResponder handles the response to the Decrypt request. The method always -// closes the http.Response Body. -func (client BaseClient) DecryptResponder(resp *http.Response) (result KeyOperationResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteCertificate deletes all versions of a certificate object along with its associated policy. Delete certificate -// cannot be used to remove individual versions of a certificate object. This operation requires the -// certificates/delete permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate. -func (client BaseClient) DeleteCertificate(ctx context.Context, vaultBaseURL string, certificateName string) (result DeletedCertificateBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.DeleteCertificate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeleteCertificatePreparer(ctx, vaultBaseURL, certificateName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificate", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteCertificateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificate", resp, "Failure sending request") - return - } - - result, err = client.DeleteCertificateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificate", resp, "Failure responding to request") - return - } - - return -} - -// DeleteCertificatePreparer prepares the DeleteCertificate request. -func (client BaseClient) DeleteCertificatePreparer(ctx context.Context, vaultBaseURL string, certificateName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteCertificateSender sends the DeleteCertificate request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) DeleteCertificateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteCertificateResponder handles the response to the DeleteCertificate request. The method always -// closes the http.Response Body. -func (client BaseClient) DeleteCertificateResponder(resp *http.Response) (result DeletedCertificateBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteCertificateContacts deletes the certificate contacts for a specified key vault certificate. This operation -// requires the certificates/managecontacts permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -func (client BaseClient) DeleteCertificateContacts(ctx context.Context, vaultBaseURL string) (result Contacts, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.DeleteCertificateContacts") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeleteCertificateContactsPreparer(ctx, vaultBaseURL) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificateContacts", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteCertificateContactsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificateContacts", resp, "Failure sending request") - return - } - - result, err = client.DeleteCertificateContactsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificateContacts", resp, "Failure responding to request") - return - } - - return -} - -// DeleteCertificateContactsPreparer prepares the DeleteCertificateContacts request. -func (client BaseClient) DeleteCertificateContactsPreparer(ctx context.Context, vaultBaseURL string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/certificates/contacts"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteCertificateContactsSender sends the DeleteCertificateContacts request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) DeleteCertificateContactsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteCertificateContactsResponder handles the response to the DeleteCertificateContacts request. The method always -// closes the http.Response Body. -func (client BaseClient) DeleteCertificateContactsResponder(resp *http.Response) (result Contacts, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteCertificateIssuer the DeleteCertificateIssuer operation permanently removes the specified certificate issuer -// from the vault. This operation requires the certificates/manageissuers/deleteissuers permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// issuerName - the name of the issuer. -func (client BaseClient) DeleteCertificateIssuer(ctx context.Context, vaultBaseURL string, issuerName string) (result IssuerBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.DeleteCertificateIssuer") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeleteCertificateIssuerPreparer(ctx, vaultBaseURL, issuerName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificateIssuer", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteCertificateIssuerSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificateIssuer", resp, "Failure sending request") - return - } - - result, err = client.DeleteCertificateIssuerResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificateIssuer", resp, "Failure responding to request") - return - } - - return -} - -// DeleteCertificateIssuerPreparer prepares the DeleteCertificateIssuer request. -func (client BaseClient) DeleteCertificateIssuerPreparer(ctx context.Context, vaultBaseURL string, issuerName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "issuer-name": autorest.Encode("path", issuerName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/issuers/{issuer-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteCertificateIssuerSender sends the DeleteCertificateIssuer request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) DeleteCertificateIssuerSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteCertificateIssuerResponder handles the response to the DeleteCertificateIssuer request. The method always -// closes the http.Response Body. -func (client BaseClient) DeleteCertificateIssuerResponder(resp *http.Response) (result IssuerBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteCertificateOperation deletes the creation operation for a specified certificate that is in the process of -// being created. The certificate is no longer created. This operation requires the certificates/update permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate. -func (client BaseClient) DeleteCertificateOperation(ctx context.Context, vaultBaseURL string, certificateName string) (result CertificateOperation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.DeleteCertificateOperation") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeleteCertificateOperationPreparer(ctx, vaultBaseURL, certificateName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificateOperation", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteCertificateOperationSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificateOperation", resp, "Failure sending request") - return - } - - result, err = client.DeleteCertificateOperationResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteCertificateOperation", resp, "Failure responding to request") - return - } - - return -} - -// DeleteCertificateOperationPreparer prepares the DeleteCertificateOperation request. -func (client BaseClient) DeleteCertificateOperationPreparer(ctx context.Context, vaultBaseURL string, certificateName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}/pending", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteCertificateOperationSender sends the DeleteCertificateOperation request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) DeleteCertificateOperationSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteCertificateOperationResponder handles the response to the DeleteCertificateOperation request. The method always -// closes the http.Response Body. -func (client BaseClient) DeleteCertificateOperationResponder(resp *http.Response) (result CertificateOperation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteKey the delete key operation cannot be used to remove individual versions of a key. This operation removes the -// cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or -// Encrypt/Decrypt operations. This operation requires the keys/delete permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key to delete. -func (client BaseClient) DeleteKey(ctx context.Context, vaultBaseURL string, keyName string) (result DeletedKeyBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.DeleteKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeleteKeyPreparer(ctx, vaultBaseURL, keyName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteKey", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteKey", resp, "Failure sending request") - return - } - - result, err = client.DeleteKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteKey", resp, "Failure responding to request") - return - } - - return -} - -// DeleteKeyPreparer prepares the DeleteKey request. -func (client BaseClient) DeleteKeyPreparer(ctx context.Context, vaultBaseURL string, keyName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteKeySender sends the DeleteKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) DeleteKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteKeyResponder handles the response to the DeleteKey request. The method always -// closes the http.Response Body. -func (client BaseClient) DeleteKeyResponder(resp *http.Response) (result DeletedKeyBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteSasDefinition deletes a SAS definition from a specified storage account. This operation requires the -// storage/deletesas permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// storageAccountName - the name of the storage account. -// sasDefinitionName - the name of the SAS definition. -func (client BaseClient) DeleteSasDefinition(ctx context.Context, vaultBaseURL string, storageAccountName string, sasDefinitionName string) (result SasDefinitionBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.DeleteSasDefinition") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: storageAccountName, - Constraints: []validation.Constraint{{Target: "storageAccountName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}, - {TargetValue: sasDefinitionName, - Constraints: []validation.Constraint{{Target: "sasDefinitionName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "DeleteSasDefinition", err.Error()) - } - - req, err := client.DeleteSasDefinitionPreparer(ctx, vaultBaseURL, storageAccountName, sasDefinitionName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteSasDefinition", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSasDefinitionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteSasDefinition", resp, "Failure sending request") - return - } - - result, err = client.DeleteSasDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteSasDefinition", resp, "Failure responding to request") - return - } - - return -} - -// DeleteSasDefinitionPreparer prepares the DeleteSasDefinition request. -func (client BaseClient) DeleteSasDefinitionPreparer(ctx context.Context, vaultBaseURL string, storageAccountName string, sasDefinitionName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "sas-definition-name": autorest.Encode("path", sasDefinitionName), - "storage-account-name": autorest.Encode("path", storageAccountName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/storage/{storage-account-name}/sas/{sas-definition-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSasDefinitionSender sends the DeleteSasDefinition request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) DeleteSasDefinitionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteSasDefinitionResponder handles the response to the DeleteSasDefinition request. The method always -// closes the http.Response Body. -func (client BaseClient) DeleteSasDefinitionResponder(resp *http.Response) (result SasDefinitionBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteSecret the DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an -// individual version of a secret. This operation requires the secrets/delete permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// secretName - the name of the secret. -func (client BaseClient) DeleteSecret(ctx context.Context, vaultBaseURL string, secretName string) (result DeletedSecretBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.DeleteSecret") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.DeleteSecretPreparer(ctx, vaultBaseURL, secretName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteSecret", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSecretSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteSecret", resp, "Failure sending request") - return - } - - result, err = client.DeleteSecretResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteSecret", resp, "Failure responding to request") - return - } - - return -} - -// DeleteSecretPreparer prepares the DeleteSecret request. -func (client BaseClient) DeleteSecretPreparer(ctx context.Context, vaultBaseURL string, secretName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "secret-name": autorest.Encode("path", secretName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/secrets/{secret-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSecretSender sends the DeleteSecret request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) DeleteSecretSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteSecretResponder handles the response to the DeleteSecret request. The method always -// closes the http.Response Body. -func (client BaseClient) DeleteSecretResponder(resp *http.Response) (result DeletedSecretBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// DeleteStorageAccount deletes a storage account. This operation requires the storage/delete permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// storageAccountName - the name of the storage account. -func (client BaseClient) DeleteStorageAccount(ctx context.Context, vaultBaseURL string, storageAccountName string) (result StorageBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.DeleteStorageAccount") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: storageAccountName, - Constraints: []validation.Constraint{{Target: "storageAccountName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "DeleteStorageAccount", err.Error()) - } - - req, err := client.DeleteStorageAccountPreparer(ctx, vaultBaseURL, storageAccountName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteStorageAccount", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteStorageAccountSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteStorageAccount", resp, "Failure sending request") - return - } - - result, err = client.DeleteStorageAccountResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "DeleteStorageAccount", resp, "Failure responding to request") - return - } - - return -} - -// DeleteStorageAccountPreparer prepares the DeleteStorageAccount request. -func (client BaseClient) DeleteStorageAccountPreparer(ctx context.Context, vaultBaseURL string, storageAccountName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "storage-account-name": autorest.Encode("path", storageAccountName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/storage/{storage-account-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteStorageAccountSender sends the DeleteStorageAccount request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) DeleteStorageAccountSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// DeleteStorageAccountResponder handles the response to the DeleteStorageAccount request. The method always -// closes the http.Response Body. -func (client BaseClient) DeleteStorageAccountResponder(resp *http.Response) (result StorageBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Encrypt the ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in -// Azure Key Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is -// dependent on the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly -// necessary for symmetric keys stored in Azure Key Vault since protection with an asymmetric key can be performed -// using public portion of the key. This operation is supported for asymmetric keys as a convenience for callers that -// have a key-reference but do not have access to the public key material. This operation requires the keys/encrypt -// permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key. -// keyVersion - the version of the key. -// parameters - the parameters for the encryption operation. -func (client BaseClient) Encrypt(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyOperationsParameters) (result KeyOperationResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.Encrypt") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Value", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "Encrypt", err.Error()) - } - - req, err := client.EncryptPreparer(ctx, vaultBaseURL, keyName, keyVersion, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Encrypt", nil, "Failure preparing request") - return - } - - resp, err := client.EncryptSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Encrypt", resp, "Failure sending request") - return - } - - result, err = client.EncryptResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Encrypt", resp, "Failure responding to request") - return - } - - return -} - -// EncryptPreparer prepares the Encrypt request. -func (client BaseClient) EncryptPreparer(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyOperationsParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - "key-version": autorest.Encode("path", keyVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}/{key-version}/encrypt", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// EncryptSender sends the Encrypt request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) EncryptSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// EncryptResponder handles the response to the Encrypt request. The method always -// closes the http.Response Body. -func (client BaseClient) EncryptResponder(resp *http.Response) (result KeyOperationResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetCertificate gets information about a specific certificate. This operation requires the certificates/get -// permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate in the given vault. -// certificateVersion - the version of the certificate. -func (client BaseClient) GetCertificate(ctx context.Context, vaultBaseURL string, certificateName string, certificateVersion string) (result CertificateBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetCertificatePreparer(ctx, vaultBaseURL, certificateName, certificateVersion) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificate", nil, "Failure preparing request") - return - } - - resp, err := client.GetCertificateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificate", resp, "Failure sending request") - return - } - - result, err = client.GetCertificateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificate", resp, "Failure responding to request") - return - } - - return -} - -// GetCertificatePreparer prepares the GetCertificate request. -func (client BaseClient) GetCertificatePreparer(ctx context.Context, vaultBaseURL string, certificateName string, certificateVersion string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - "certificate-version": autorest.Encode("path", certificateVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}/{certificate-version}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetCertificateSender sends the GetCertificate request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetCertificateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetCertificateResponder handles the response to the GetCertificate request. The method always -// closes the http.Response Body. -func (client BaseClient) GetCertificateResponder(resp *http.Response) (result CertificateBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetCertificateContacts the GetCertificateContacts operation returns the set of certificate contact resources in the -// specified key vault. This operation requires the certificates/managecontacts permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -func (client BaseClient) GetCertificateContacts(ctx context.Context, vaultBaseURL string) (result Contacts, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificateContacts") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetCertificateContactsPreparer(ctx, vaultBaseURL) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateContacts", nil, "Failure preparing request") - return - } - - resp, err := client.GetCertificateContactsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateContacts", resp, "Failure sending request") - return - } - - result, err = client.GetCertificateContactsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateContacts", resp, "Failure responding to request") - return - } - - return -} - -// GetCertificateContactsPreparer prepares the GetCertificateContacts request. -func (client BaseClient) GetCertificateContactsPreparer(ctx context.Context, vaultBaseURL string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/certificates/contacts"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetCertificateContactsSender sends the GetCertificateContacts request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetCertificateContactsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetCertificateContactsResponder handles the response to the GetCertificateContacts request. The method always -// closes the http.Response Body. -func (client BaseClient) GetCertificateContactsResponder(resp *http.Response) (result Contacts, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetCertificateIssuer the GetCertificateIssuer operation returns the specified certificate issuer resources in the -// specified key vault. This operation requires the certificates/manageissuers/getissuers permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// issuerName - the name of the issuer. -func (client BaseClient) GetCertificateIssuer(ctx context.Context, vaultBaseURL string, issuerName string) (result IssuerBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificateIssuer") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetCertificateIssuerPreparer(ctx, vaultBaseURL, issuerName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateIssuer", nil, "Failure preparing request") - return - } - - resp, err := client.GetCertificateIssuerSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateIssuer", resp, "Failure sending request") - return - } - - result, err = client.GetCertificateIssuerResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateIssuer", resp, "Failure responding to request") - return - } - - return -} - -// GetCertificateIssuerPreparer prepares the GetCertificateIssuer request. -func (client BaseClient) GetCertificateIssuerPreparer(ctx context.Context, vaultBaseURL string, issuerName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "issuer-name": autorest.Encode("path", issuerName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/issuers/{issuer-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetCertificateIssuerSender sends the GetCertificateIssuer request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetCertificateIssuerSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetCertificateIssuerResponder handles the response to the GetCertificateIssuer request. The method always -// closes the http.Response Body. -func (client BaseClient) GetCertificateIssuerResponder(resp *http.Response) (result IssuerBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetCertificateIssuers the GetCertificateIssuers operation returns the set of certificate issuer resources in the -// specified key vault. This operation requires the certificates/manageissuers/getissuers permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// maxresults - maximum number of results to return in a page. If not specified the service will return up to -// 25 results. -func (client BaseClient) GetCertificateIssuers(ctx context.Context, vaultBaseURL string, maxresults *int32) (result CertificateIssuerListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificateIssuers") - defer func() { - sc := -1 - if result.cilr.Response.Response != nil { - sc = result.cilr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetCertificateIssuers", err.Error()) - } - - result.fn = client.getCertificateIssuersNextResults - req, err := client.GetCertificateIssuersPreparer(ctx, vaultBaseURL, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateIssuers", nil, "Failure preparing request") - return - } - - resp, err := client.GetCertificateIssuersSender(req) - if err != nil { - result.cilr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateIssuers", resp, "Failure sending request") - return - } - - result.cilr, err = client.GetCertificateIssuersResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateIssuers", resp, "Failure responding to request") - return - } - if result.cilr.hasNextLink() && result.cilr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetCertificateIssuersPreparer prepares the GetCertificateIssuers request. -func (client BaseClient) GetCertificateIssuersPreparer(ctx context.Context, vaultBaseURL string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/certificates/issuers"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetCertificateIssuersSender sends the GetCertificateIssuers request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetCertificateIssuersSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetCertificateIssuersResponder handles the response to the GetCertificateIssuers request. The method always -// closes the http.Response Body. -func (client BaseClient) GetCertificateIssuersResponder(resp *http.Response) (result CertificateIssuerListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getCertificateIssuersNextResults retrieves the next set of results, if any. -func (client BaseClient) getCertificateIssuersNextResults(ctx context.Context, lastResults CertificateIssuerListResult) (result CertificateIssuerListResult, err error) { - req, err := lastResults.certificateIssuerListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getCertificateIssuersNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetCertificateIssuersSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getCertificateIssuersNextResults", resp, "Failure sending next results request") - } - result, err = client.GetCertificateIssuersResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getCertificateIssuersNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetCertificateIssuersComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetCertificateIssuersComplete(ctx context.Context, vaultBaseURL string, maxresults *int32) (result CertificateIssuerListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificateIssuers") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetCertificateIssuers(ctx, vaultBaseURL, maxresults) - return -} - -// GetCertificateOperation gets the creation operation associated with a specified certificate. This operation requires -// the certificates/get permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate. -func (client BaseClient) GetCertificateOperation(ctx context.Context, vaultBaseURL string, certificateName string) (result CertificateOperation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificateOperation") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetCertificateOperationPreparer(ctx, vaultBaseURL, certificateName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateOperation", nil, "Failure preparing request") - return - } - - resp, err := client.GetCertificateOperationSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateOperation", resp, "Failure sending request") - return - } - - result, err = client.GetCertificateOperationResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateOperation", resp, "Failure responding to request") - return - } - - return -} - -// GetCertificateOperationPreparer prepares the GetCertificateOperation request. -func (client BaseClient) GetCertificateOperationPreparer(ctx context.Context, vaultBaseURL string, certificateName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}/pending", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetCertificateOperationSender sends the GetCertificateOperation request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetCertificateOperationSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetCertificateOperationResponder handles the response to the GetCertificateOperation request. The method always -// closes the http.Response Body. -func (client BaseClient) GetCertificateOperationResponder(resp *http.Response) (result CertificateOperation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetCertificatePolicy the GetCertificatePolicy operation returns the specified certificate policy resources in the -// specified key vault. This operation requires the certificates/get permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate in a given key vault. -func (client BaseClient) GetCertificatePolicy(ctx context.Context, vaultBaseURL string, certificateName string) (result CertificatePolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificatePolicy") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetCertificatePolicyPreparer(ctx, vaultBaseURL, certificateName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificatePolicy", nil, "Failure preparing request") - return - } - - resp, err := client.GetCertificatePolicySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificatePolicy", resp, "Failure sending request") - return - } - - result, err = client.GetCertificatePolicyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificatePolicy", resp, "Failure responding to request") - return - } - - return -} - -// GetCertificatePolicyPreparer prepares the GetCertificatePolicy request. -func (client BaseClient) GetCertificatePolicyPreparer(ctx context.Context, vaultBaseURL string, certificateName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}/policy", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetCertificatePolicySender sends the GetCertificatePolicy request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetCertificatePolicySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetCertificatePolicyResponder handles the response to the GetCertificatePolicy request. The method always -// closes the http.Response Body. -func (client BaseClient) GetCertificatePolicyResponder(resp *http.Response) (result CertificatePolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetCertificates the GetCertificates operation returns the set of certificates resources in the specified key vault. -// This operation requires the certificates/list permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// maxresults - maximum number of results to return in a page. If not specified the service will return up to -// 25 results. -func (client BaseClient) GetCertificates(ctx context.Context, vaultBaseURL string, maxresults *int32) (result CertificateListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificates") - defer func() { - sc := -1 - if result.clr.Response.Response != nil { - sc = result.clr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetCertificates", err.Error()) - } - - result.fn = client.getCertificatesNextResults - req, err := client.GetCertificatesPreparer(ctx, vaultBaseURL, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificates", nil, "Failure preparing request") - return - } - - resp, err := client.GetCertificatesSender(req) - if err != nil { - result.clr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificates", resp, "Failure sending request") - return - } - - result.clr, err = client.GetCertificatesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificates", resp, "Failure responding to request") - return - } - if result.clr.hasNextLink() && result.clr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetCertificatesPreparer prepares the GetCertificates request. -func (client BaseClient) GetCertificatesPreparer(ctx context.Context, vaultBaseURL string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/certificates"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetCertificatesSender sends the GetCertificates request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetCertificatesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetCertificatesResponder handles the response to the GetCertificates request. The method always -// closes the http.Response Body. -func (client BaseClient) GetCertificatesResponder(resp *http.Response) (result CertificateListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getCertificatesNextResults retrieves the next set of results, if any. -func (client BaseClient) getCertificatesNextResults(ctx context.Context, lastResults CertificateListResult) (result CertificateListResult, err error) { - req, err := lastResults.certificateListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getCertificatesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetCertificatesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getCertificatesNextResults", resp, "Failure sending next results request") - } - result, err = client.GetCertificatesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getCertificatesNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetCertificatesComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetCertificatesComplete(ctx context.Context, vaultBaseURL string, maxresults *int32) (result CertificateListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificates") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetCertificates(ctx, vaultBaseURL, maxresults) - return -} - -// GetCertificateVersions the GetCertificateVersions operation returns the versions of a certificate in the specified -// key vault. This operation requires the certificates/list permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate. -// maxresults - maximum number of results to return in a page. If not specified the service will return up to -// 25 results. -func (client BaseClient) GetCertificateVersions(ctx context.Context, vaultBaseURL string, certificateName string, maxresults *int32) (result CertificateListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificateVersions") - defer func() { - sc := -1 - if result.clr.Response.Response != nil { - sc = result.clr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetCertificateVersions", err.Error()) - } - - result.fn = client.getCertificateVersionsNextResults - req, err := client.GetCertificateVersionsPreparer(ctx, vaultBaseURL, certificateName, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateVersions", nil, "Failure preparing request") - return - } - - resp, err := client.GetCertificateVersionsSender(req) - if err != nil { - result.clr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateVersions", resp, "Failure sending request") - return - } - - result.clr, err = client.GetCertificateVersionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetCertificateVersions", resp, "Failure responding to request") - return - } - if result.clr.hasNextLink() && result.clr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetCertificateVersionsPreparer prepares the GetCertificateVersions request. -func (client BaseClient) GetCertificateVersionsPreparer(ctx context.Context, vaultBaseURL string, certificateName string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}/versions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetCertificateVersionsSender sends the GetCertificateVersions request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetCertificateVersionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetCertificateVersionsResponder handles the response to the GetCertificateVersions request. The method always -// closes the http.Response Body. -func (client BaseClient) GetCertificateVersionsResponder(resp *http.Response) (result CertificateListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getCertificateVersionsNextResults retrieves the next set of results, if any. -func (client BaseClient) getCertificateVersionsNextResults(ctx context.Context, lastResults CertificateListResult) (result CertificateListResult, err error) { - req, err := lastResults.certificateListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getCertificateVersionsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetCertificateVersionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getCertificateVersionsNextResults", resp, "Failure sending next results request") - } - result, err = client.GetCertificateVersionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getCertificateVersionsNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetCertificateVersionsComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetCertificateVersionsComplete(ctx context.Context, vaultBaseURL string, certificateName string, maxresults *int32) (result CertificateListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetCertificateVersions") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetCertificateVersions(ctx, vaultBaseURL, certificateName, maxresults) - return -} - -// GetDeletedCertificate the GetDeletedCertificate operation retrieves the deleted certificate information plus its -// attributes, such as retention interval, scheduled permanent deletion and the current deletion recovery level. This -// operation requires the certificates/get permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate -func (client BaseClient) GetDeletedCertificate(ctx context.Context, vaultBaseURL string, certificateName string) (result DeletedCertificateBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetDeletedCertificate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetDeletedCertificatePreparer(ctx, vaultBaseURL, certificateName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedCertificate", nil, "Failure preparing request") - return - } - - resp, err := client.GetDeletedCertificateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedCertificate", resp, "Failure sending request") - return - } - - result, err = client.GetDeletedCertificateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedCertificate", resp, "Failure responding to request") - return - } - - return -} - -// GetDeletedCertificatePreparer prepares the GetDeletedCertificate request. -func (client BaseClient) GetDeletedCertificatePreparer(ctx context.Context, vaultBaseURL string, certificateName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/deletedcertificates/{certificate-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetDeletedCertificateSender sends the GetDeletedCertificate request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetDeletedCertificateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetDeletedCertificateResponder handles the response to the GetDeletedCertificate request. The method always -// closes the http.Response Body. -func (client BaseClient) GetDeletedCertificateResponder(resp *http.Response) (result DeletedCertificateBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetDeletedCertificates the GetDeletedCertificates operation retrieves the certificates in the current vault which -// are in a deleted state and ready for recovery or purging. This operation includes deletion-specific information. -// This operation requires the certificates/get/list permission. This operation can only be enabled on soft-delete -// enabled vaults. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// maxresults - maximum number of results to return in a page. If not specified the service will return up to -// 25 results. -func (client BaseClient) GetDeletedCertificates(ctx context.Context, vaultBaseURL string, maxresults *int32) (result DeletedCertificateListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetDeletedCertificates") - defer func() { - sc := -1 - if result.dclr.Response.Response != nil { - sc = result.dclr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetDeletedCertificates", err.Error()) - } - - result.fn = client.getDeletedCertificatesNextResults - req, err := client.GetDeletedCertificatesPreparer(ctx, vaultBaseURL, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedCertificates", nil, "Failure preparing request") - return - } - - resp, err := client.GetDeletedCertificatesSender(req) - if err != nil { - result.dclr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedCertificates", resp, "Failure sending request") - return - } - - result.dclr, err = client.GetDeletedCertificatesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedCertificates", resp, "Failure responding to request") - return - } - if result.dclr.hasNextLink() && result.dclr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetDeletedCertificatesPreparer prepares the GetDeletedCertificates request. -func (client BaseClient) GetDeletedCertificatesPreparer(ctx context.Context, vaultBaseURL string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/deletedcertificates"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetDeletedCertificatesSender sends the GetDeletedCertificates request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetDeletedCertificatesSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetDeletedCertificatesResponder handles the response to the GetDeletedCertificates request. The method always -// closes the http.Response Body. -func (client BaseClient) GetDeletedCertificatesResponder(resp *http.Response) (result DeletedCertificateListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getDeletedCertificatesNextResults retrieves the next set of results, if any. -func (client BaseClient) getDeletedCertificatesNextResults(ctx context.Context, lastResults DeletedCertificateListResult) (result DeletedCertificateListResult, err error) { - req, err := lastResults.deletedCertificateListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getDeletedCertificatesNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetDeletedCertificatesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getDeletedCertificatesNextResults", resp, "Failure sending next results request") - } - result, err = client.GetDeletedCertificatesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getDeletedCertificatesNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetDeletedCertificatesComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetDeletedCertificatesComplete(ctx context.Context, vaultBaseURL string, maxresults *int32) (result DeletedCertificateListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetDeletedCertificates") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetDeletedCertificates(ctx, vaultBaseURL, maxresults) - return -} - -// GetDeletedKey the Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be -// invoked on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires -// the keys/get permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key. -func (client BaseClient) GetDeletedKey(ctx context.Context, vaultBaseURL string, keyName string) (result DeletedKeyBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetDeletedKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetDeletedKeyPreparer(ctx, vaultBaseURL, keyName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedKey", nil, "Failure preparing request") - return - } - - resp, err := client.GetDeletedKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedKey", resp, "Failure sending request") - return - } - - result, err = client.GetDeletedKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedKey", resp, "Failure responding to request") - return - } - - return -} - -// GetDeletedKeyPreparer prepares the GetDeletedKey request. -func (client BaseClient) GetDeletedKeyPreparer(ctx context.Context, vaultBaseURL string, keyName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/deletedkeys/{key-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetDeletedKeySender sends the GetDeletedKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetDeletedKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetDeletedKeyResponder handles the response to the GetDeletedKey request. The method always -// closes the http.Response Body. -func (client BaseClient) GetDeletedKeyResponder(resp *http.Response) (result DeletedKeyBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetDeletedKeys retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part -// of a deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is -// applicable for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an -// error if invoked on a non soft-delete enabled vault. This operation requires the keys/list permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// maxresults - maximum number of results to return in a page. If not specified the service will return up to -// 25 results. -func (client BaseClient) GetDeletedKeys(ctx context.Context, vaultBaseURL string, maxresults *int32) (result DeletedKeyListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetDeletedKeys") - defer func() { - sc := -1 - if result.dklr.Response.Response != nil { - sc = result.dklr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetDeletedKeys", err.Error()) - } - - result.fn = client.getDeletedKeysNextResults - req, err := client.GetDeletedKeysPreparer(ctx, vaultBaseURL, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedKeys", nil, "Failure preparing request") - return - } - - resp, err := client.GetDeletedKeysSender(req) - if err != nil { - result.dklr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedKeys", resp, "Failure sending request") - return - } - - result.dklr, err = client.GetDeletedKeysResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedKeys", resp, "Failure responding to request") - return - } - if result.dklr.hasNextLink() && result.dklr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetDeletedKeysPreparer prepares the GetDeletedKeys request. -func (client BaseClient) GetDeletedKeysPreparer(ctx context.Context, vaultBaseURL string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/deletedkeys"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetDeletedKeysSender sends the GetDeletedKeys request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetDeletedKeysSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetDeletedKeysResponder handles the response to the GetDeletedKeys request. The method always -// closes the http.Response Body. -func (client BaseClient) GetDeletedKeysResponder(resp *http.Response) (result DeletedKeyListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getDeletedKeysNextResults retrieves the next set of results, if any. -func (client BaseClient) getDeletedKeysNextResults(ctx context.Context, lastResults DeletedKeyListResult) (result DeletedKeyListResult, err error) { - req, err := lastResults.deletedKeyListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getDeletedKeysNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetDeletedKeysSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getDeletedKeysNextResults", resp, "Failure sending next results request") - } - result, err = client.GetDeletedKeysResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getDeletedKeysNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetDeletedKeysComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetDeletedKeysComplete(ctx context.Context, vaultBaseURL string, maxresults *int32) (result DeletedKeyListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetDeletedKeys") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetDeletedKeys(ctx, vaultBaseURL, maxresults) - return -} - -// GetDeletedSecret the Get Deleted Secret operation returns the specified deleted secret along with its attributes. -// This operation requires the secrets/get permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// secretName - the name of the secret. -func (client BaseClient) GetDeletedSecret(ctx context.Context, vaultBaseURL string, secretName string) (result DeletedSecretBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetDeletedSecret") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetDeletedSecretPreparer(ctx, vaultBaseURL, secretName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedSecret", nil, "Failure preparing request") - return - } - - resp, err := client.GetDeletedSecretSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedSecret", resp, "Failure sending request") - return - } - - result, err = client.GetDeletedSecretResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedSecret", resp, "Failure responding to request") - return - } - - return -} - -// GetDeletedSecretPreparer prepares the GetDeletedSecret request. -func (client BaseClient) GetDeletedSecretPreparer(ctx context.Context, vaultBaseURL string, secretName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "secret-name": autorest.Encode("path", secretName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/deletedsecrets/{secret-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetDeletedSecretSender sends the GetDeletedSecret request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetDeletedSecretSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetDeletedSecretResponder handles the response to the GetDeletedSecret request. The method always -// closes the http.Response Body. -func (client BaseClient) GetDeletedSecretResponder(resp *http.Response) (result DeletedSecretBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetDeletedSecrets the Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled -// for soft-delete. This operation requires the secrets/list permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// maxresults - maximum number of results to return in a page. If not specified the service will return up to -// 25 results. -func (client BaseClient) GetDeletedSecrets(ctx context.Context, vaultBaseURL string, maxresults *int32) (result DeletedSecretListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetDeletedSecrets") - defer func() { - sc := -1 - if result.dslr.Response.Response != nil { - sc = result.dslr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetDeletedSecrets", err.Error()) - } - - result.fn = client.getDeletedSecretsNextResults - req, err := client.GetDeletedSecretsPreparer(ctx, vaultBaseURL, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedSecrets", nil, "Failure preparing request") - return - } - - resp, err := client.GetDeletedSecretsSender(req) - if err != nil { - result.dslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedSecrets", resp, "Failure sending request") - return - } - - result.dslr, err = client.GetDeletedSecretsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetDeletedSecrets", resp, "Failure responding to request") - return - } - if result.dslr.hasNextLink() && result.dslr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetDeletedSecretsPreparer prepares the GetDeletedSecrets request. -func (client BaseClient) GetDeletedSecretsPreparer(ctx context.Context, vaultBaseURL string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/deletedsecrets"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetDeletedSecretsSender sends the GetDeletedSecrets request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetDeletedSecretsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetDeletedSecretsResponder handles the response to the GetDeletedSecrets request. The method always -// closes the http.Response Body. -func (client BaseClient) GetDeletedSecretsResponder(resp *http.Response) (result DeletedSecretListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getDeletedSecretsNextResults retrieves the next set of results, if any. -func (client BaseClient) getDeletedSecretsNextResults(ctx context.Context, lastResults DeletedSecretListResult) (result DeletedSecretListResult, err error) { - req, err := lastResults.deletedSecretListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getDeletedSecretsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetDeletedSecretsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getDeletedSecretsNextResults", resp, "Failure sending next results request") - } - result, err = client.GetDeletedSecretsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getDeletedSecretsNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetDeletedSecretsComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetDeletedSecretsComplete(ctx context.Context, vaultBaseURL string, maxresults *int32) (result DeletedSecretListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetDeletedSecrets") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetDeletedSecrets(ctx, vaultBaseURL, maxresults) - return -} - -// GetKey the get key operation is applicable to all key types. If the requested key is symmetric, then no key material -// is released in the response. This operation requires the keys/get permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key to get. -// keyVersion - adding the version parameter retrieves a specific version of a key. -func (client BaseClient) GetKey(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string) (result KeyBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetKeyPreparer(ctx, vaultBaseURL, keyName, keyVersion) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetKey", nil, "Failure preparing request") - return - } - - resp, err := client.GetKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetKey", resp, "Failure sending request") - return - } - - result, err = client.GetKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetKey", resp, "Failure responding to request") - return - } - - return -} - -// GetKeyPreparer prepares the GetKey request. -func (client BaseClient) GetKeyPreparer(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - "key-version": autorest.Encode("path", keyVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}/{key-version}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetKeySender sends the GetKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetKeyResponder handles the response to the GetKey request. The method always -// closes the http.Response Body. -func (client BaseClient) GetKeyResponder(resp *http.Response) (result KeyBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetKeys retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a -// stored key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and -// tags are provided in the response. Individual versions of a key are not listed in the response. This operation -// requires the keys/list permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// maxresults - maximum number of results to return in a page. If not specified the service will return up to -// 25 results. -func (client BaseClient) GetKeys(ctx context.Context, vaultBaseURL string, maxresults *int32) (result KeyListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetKeys") - defer func() { - sc := -1 - if result.klr.Response.Response != nil { - sc = result.klr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetKeys", err.Error()) - } - - result.fn = client.getKeysNextResults - req, err := client.GetKeysPreparer(ctx, vaultBaseURL, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetKeys", nil, "Failure preparing request") - return - } - - resp, err := client.GetKeysSender(req) - if err != nil { - result.klr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetKeys", resp, "Failure sending request") - return - } - - result.klr, err = client.GetKeysResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetKeys", resp, "Failure responding to request") - return - } - if result.klr.hasNextLink() && result.klr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetKeysPreparer prepares the GetKeys request. -func (client BaseClient) GetKeysPreparer(ctx context.Context, vaultBaseURL string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/keys"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetKeysSender sends the GetKeys request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetKeysSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetKeysResponder handles the response to the GetKeys request. The method always -// closes the http.Response Body. -func (client BaseClient) GetKeysResponder(resp *http.Response) (result KeyListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getKeysNextResults retrieves the next set of results, if any. -func (client BaseClient) getKeysNextResults(ctx context.Context, lastResults KeyListResult) (result KeyListResult, err error) { - req, err := lastResults.keyListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getKeysNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetKeysSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getKeysNextResults", resp, "Failure sending next results request") - } - result, err = client.GetKeysResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getKeysNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetKeysComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetKeysComplete(ctx context.Context, vaultBaseURL string, maxresults *int32) (result KeyListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetKeys") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetKeys(ctx, vaultBaseURL, maxresults) - return -} - -// GetKeyVersions the full key identifier, attributes, and tags are provided in the response. This operation requires -// the keys/list permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key. -// maxresults - maximum number of results to return in a page. If not specified the service will return up to -// 25 results. -func (client BaseClient) GetKeyVersions(ctx context.Context, vaultBaseURL string, keyName string, maxresults *int32) (result KeyListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetKeyVersions") - defer func() { - sc := -1 - if result.klr.Response.Response != nil { - sc = result.klr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetKeyVersions", err.Error()) - } - - result.fn = client.getKeyVersionsNextResults - req, err := client.GetKeyVersionsPreparer(ctx, vaultBaseURL, keyName, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetKeyVersions", nil, "Failure preparing request") - return - } - - resp, err := client.GetKeyVersionsSender(req) - if err != nil { - result.klr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetKeyVersions", resp, "Failure sending request") - return - } - - result.klr, err = client.GetKeyVersionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetKeyVersions", resp, "Failure responding to request") - return - } - if result.klr.hasNextLink() && result.klr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetKeyVersionsPreparer prepares the GetKeyVersions request. -func (client BaseClient) GetKeyVersionsPreparer(ctx context.Context, vaultBaseURL string, keyName string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}/versions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetKeyVersionsSender sends the GetKeyVersions request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetKeyVersionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetKeyVersionsResponder handles the response to the GetKeyVersions request. The method always -// closes the http.Response Body. -func (client BaseClient) GetKeyVersionsResponder(resp *http.Response) (result KeyListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getKeyVersionsNextResults retrieves the next set of results, if any. -func (client BaseClient) getKeyVersionsNextResults(ctx context.Context, lastResults KeyListResult) (result KeyListResult, err error) { - req, err := lastResults.keyListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getKeyVersionsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetKeyVersionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getKeyVersionsNextResults", resp, "Failure sending next results request") - } - result, err = client.GetKeyVersionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getKeyVersionsNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetKeyVersionsComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetKeyVersionsComplete(ctx context.Context, vaultBaseURL string, keyName string, maxresults *int32) (result KeyListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetKeyVersions") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetKeyVersions(ctx, vaultBaseURL, keyName, maxresults) - return -} - -// GetSasDefinition gets information about a SAS definition for the specified storage account. This operation requires -// the storage/getsas permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// storageAccountName - the name of the storage account. -// sasDefinitionName - the name of the SAS definition. -func (client BaseClient) GetSasDefinition(ctx context.Context, vaultBaseURL string, storageAccountName string, sasDefinitionName string) (result SasDefinitionBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetSasDefinition") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: storageAccountName, - Constraints: []validation.Constraint{{Target: "storageAccountName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}, - {TargetValue: sasDefinitionName, - Constraints: []validation.Constraint{{Target: "sasDefinitionName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetSasDefinition", err.Error()) - } - - req, err := client.GetSasDefinitionPreparer(ctx, vaultBaseURL, storageAccountName, sasDefinitionName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSasDefinition", nil, "Failure preparing request") - return - } - - resp, err := client.GetSasDefinitionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSasDefinition", resp, "Failure sending request") - return - } - - result, err = client.GetSasDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSasDefinition", resp, "Failure responding to request") - return - } - - return -} - -// GetSasDefinitionPreparer prepares the GetSasDefinition request. -func (client BaseClient) GetSasDefinitionPreparer(ctx context.Context, vaultBaseURL string, storageAccountName string, sasDefinitionName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "sas-definition-name": autorest.Encode("path", sasDefinitionName), - "storage-account-name": autorest.Encode("path", storageAccountName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/storage/{storage-account-name}/sas/{sas-definition-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSasDefinitionSender sends the GetSasDefinition request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetSasDefinitionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetSasDefinitionResponder handles the response to the GetSasDefinition request. The method always -// closes the http.Response Body. -func (client BaseClient) GetSasDefinitionResponder(resp *http.Response) (result SasDefinitionBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetSasDefinitions list storage SAS definitions for the given storage account. This operation requires the -// storage/listsas permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// storageAccountName - the name of the storage account. -// maxresults - maximum number of results to return in a page. If not specified the service will return up to -// 25 results. -func (client BaseClient) GetSasDefinitions(ctx context.Context, vaultBaseURL string, storageAccountName string, maxresults *int32) (result SasDefinitionListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetSasDefinitions") - defer func() { - sc := -1 - if result.sdlr.Response.Response != nil { - sc = result.sdlr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: storageAccountName, - Constraints: []validation.Constraint{{Target: "storageAccountName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}, - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetSasDefinitions", err.Error()) - } - - result.fn = client.getSasDefinitionsNextResults - req, err := client.GetSasDefinitionsPreparer(ctx, vaultBaseURL, storageAccountName, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSasDefinitions", nil, "Failure preparing request") - return - } - - resp, err := client.GetSasDefinitionsSender(req) - if err != nil { - result.sdlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSasDefinitions", resp, "Failure sending request") - return - } - - result.sdlr, err = client.GetSasDefinitionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSasDefinitions", resp, "Failure responding to request") - return - } - if result.sdlr.hasNextLink() && result.sdlr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetSasDefinitionsPreparer prepares the GetSasDefinitions request. -func (client BaseClient) GetSasDefinitionsPreparer(ctx context.Context, vaultBaseURL string, storageAccountName string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "storage-account-name": autorest.Encode("path", storageAccountName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/storage/{storage-account-name}/sas", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSasDefinitionsSender sends the GetSasDefinitions request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetSasDefinitionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetSasDefinitionsResponder handles the response to the GetSasDefinitions request. The method always -// closes the http.Response Body. -func (client BaseClient) GetSasDefinitionsResponder(resp *http.Response) (result SasDefinitionListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getSasDefinitionsNextResults retrieves the next set of results, if any. -func (client BaseClient) getSasDefinitionsNextResults(ctx context.Context, lastResults SasDefinitionListResult) (result SasDefinitionListResult, err error) { - req, err := lastResults.sasDefinitionListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getSasDefinitionsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetSasDefinitionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getSasDefinitionsNextResults", resp, "Failure sending next results request") - } - result, err = client.GetSasDefinitionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getSasDefinitionsNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetSasDefinitionsComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetSasDefinitionsComplete(ctx context.Context, vaultBaseURL string, storageAccountName string, maxresults *int32) (result SasDefinitionListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetSasDefinitions") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetSasDefinitions(ctx, vaultBaseURL, storageAccountName, maxresults) - return -} - -// GetSecret the GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the -// secrets/get permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// secretName - the name of the secret. -// secretVersion - the version of the secret. -func (client BaseClient) GetSecret(ctx context.Context, vaultBaseURL string, secretName string, secretVersion string) (result SecretBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetSecret") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.GetSecretPreparer(ctx, vaultBaseURL, secretName, secretVersion) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSecret", nil, "Failure preparing request") - return - } - - resp, err := client.GetSecretSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSecret", resp, "Failure sending request") - return - } - - result, err = client.GetSecretResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSecret", resp, "Failure responding to request") - return - } - - return -} - -// GetSecretPreparer prepares the GetSecret request. -func (client BaseClient) GetSecretPreparer(ctx context.Context, vaultBaseURL string, secretName string, secretVersion string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "secret-name": autorest.Encode("path", secretName), - "secret-version": autorest.Encode("path", secretVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/secrets/{secret-name}/{secret-version}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSecretSender sends the GetSecret request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetSecretSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetSecretResponder handles the response to the GetSecret request. The method always -// closes the http.Response Body. -func (client BaseClient) GetSecretResponder(resp *http.Response) (result SecretBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetSecrets the Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and -// its attributes are provided in the response. Individual secret versions are not listed in the response. This -// operation requires the secrets/list permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// maxresults - maximum number of results to return in a page. If not specified, the service will return up to -// 25 results. -func (client BaseClient) GetSecrets(ctx context.Context, vaultBaseURL string, maxresults *int32) (result SecretListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetSecrets") - defer func() { - sc := -1 - if result.slr.Response.Response != nil { - sc = result.slr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetSecrets", err.Error()) - } - - result.fn = client.getSecretsNextResults - req, err := client.GetSecretsPreparer(ctx, vaultBaseURL, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSecrets", nil, "Failure preparing request") - return - } - - resp, err := client.GetSecretsSender(req) - if err != nil { - result.slr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSecrets", resp, "Failure sending request") - return - } - - result.slr, err = client.GetSecretsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSecrets", resp, "Failure responding to request") - return - } - if result.slr.hasNextLink() && result.slr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetSecretsPreparer prepares the GetSecrets request. -func (client BaseClient) GetSecretsPreparer(ctx context.Context, vaultBaseURL string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/secrets"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSecretsSender sends the GetSecrets request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetSecretsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetSecretsResponder handles the response to the GetSecrets request. The method always -// closes the http.Response Body. -func (client BaseClient) GetSecretsResponder(resp *http.Response) (result SecretListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getSecretsNextResults retrieves the next set of results, if any. -func (client BaseClient) getSecretsNextResults(ctx context.Context, lastResults SecretListResult) (result SecretListResult, err error) { - req, err := lastResults.secretListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getSecretsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetSecretsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getSecretsNextResults", resp, "Failure sending next results request") - } - result, err = client.GetSecretsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getSecretsNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetSecretsComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetSecretsComplete(ctx context.Context, vaultBaseURL string, maxresults *int32) (result SecretListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetSecrets") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetSecrets(ctx, vaultBaseURL, maxresults) - return -} - -// GetSecretVersions the full secret identifier and attributes are provided in the response. No values are returned for -// the secrets. This operations requires the secrets/list permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// secretName - the name of the secret. -// maxresults - maximum number of results to return in a page. If not specified, the service will return up to -// 25 results. -func (client BaseClient) GetSecretVersions(ctx context.Context, vaultBaseURL string, secretName string, maxresults *int32) (result SecretListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetSecretVersions") - defer func() { - sc := -1 - if result.slr.Response.Response != nil { - sc = result.slr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetSecretVersions", err.Error()) - } - - result.fn = client.getSecretVersionsNextResults - req, err := client.GetSecretVersionsPreparer(ctx, vaultBaseURL, secretName, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSecretVersions", nil, "Failure preparing request") - return - } - - resp, err := client.GetSecretVersionsSender(req) - if err != nil { - result.slr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSecretVersions", resp, "Failure sending request") - return - } - - result.slr, err = client.GetSecretVersionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetSecretVersions", resp, "Failure responding to request") - return - } - if result.slr.hasNextLink() && result.slr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetSecretVersionsPreparer prepares the GetSecretVersions request. -func (client BaseClient) GetSecretVersionsPreparer(ctx context.Context, vaultBaseURL string, secretName string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "secret-name": autorest.Encode("path", secretName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/secrets/{secret-name}/versions", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSecretVersionsSender sends the GetSecretVersions request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetSecretVersionsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetSecretVersionsResponder handles the response to the GetSecretVersions request. The method always -// closes the http.Response Body. -func (client BaseClient) GetSecretVersionsResponder(resp *http.Response) (result SecretListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getSecretVersionsNextResults retrieves the next set of results, if any. -func (client BaseClient) getSecretVersionsNextResults(ctx context.Context, lastResults SecretListResult) (result SecretListResult, err error) { - req, err := lastResults.secretListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getSecretVersionsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetSecretVersionsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getSecretVersionsNextResults", resp, "Failure sending next results request") - } - result, err = client.GetSecretVersionsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getSecretVersionsNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetSecretVersionsComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetSecretVersionsComplete(ctx context.Context, vaultBaseURL string, secretName string, maxresults *int32) (result SecretListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetSecretVersions") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetSecretVersions(ctx, vaultBaseURL, secretName, maxresults) - return -} - -// GetStorageAccount gets information about a specified storage account. This operation requires the storage/get -// permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// storageAccountName - the name of the storage account. -func (client BaseClient) GetStorageAccount(ctx context.Context, vaultBaseURL string, storageAccountName string) (result StorageBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetStorageAccount") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: storageAccountName, - Constraints: []validation.Constraint{{Target: "storageAccountName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetStorageAccount", err.Error()) - } - - req, err := client.GetStorageAccountPreparer(ctx, vaultBaseURL, storageAccountName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetStorageAccount", nil, "Failure preparing request") - return - } - - resp, err := client.GetStorageAccountSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetStorageAccount", resp, "Failure sending request") - return - } - - result, err = client.GetStorageAccountResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetStorageAccount", resp, "Failure responding to request") - return - } - - return -} - -// GetStorageAccountPreparer prepares the GetStorageAccount request. -func (client BaseClient) GetStorageAccountPreparer(ctx context.Context, vaultBaseURL string, storageAccountName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "storage-account-name": autorest.Encode("path", storageAccountName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/storage/{storage-account-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetStorageAccountSender sends the GetStorageAccount request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetStorageAccountSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetStorageAccountResponder handles the response to the GetStorageAccount request. The method always -// closes the http.Response Body. -func (client BaseClient) GetStorageAccountResponder(resp *http.Response) (result StorageBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// GetStorageAccounts list storage accounts managed by the specified key vault. This operation requires the -// storage/list permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// maxresults - maximum number of results to return in a page. If not specified the service will return up to -// 25 results. -func (client BaseClient) GetStorageAccounts(ctx context.Context, vaultBaseURL string, maxresults *int32) (result StorageListResultPage, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetStorageAccounts") - defer func() { - sc := -1 - if result.slr.Response.Response != nil { - sc = result.slr.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: maxresults, - Constraints: []validation.Constraint{{Target: "maxresults", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "maxresults", Name: validation.InclusiveMaximum, Rule: int64(25), Chain: nil}, - {Target: "maxresults", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "GetStorageAccounts", err.Error()) - } - - result.fn = client.getStorageAccountsNextResults - req, err := client.GetStorageAccountsPreparer(ctx, vaultBaseURL, maxresults) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetStorageAccounts", nil, "Failure preparing request") - return - } - - resp, err := client.GetStorageAccountsSender(req) - if err != nil { - result.slr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetStorageAccounts", resp, "Failure sending request") - return - } - - result.slr, err = client.GetStorageAccountsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "GetStorageAccounts", resp, "Failure responding to request") - return - } - if result.slr.hasNextLink() && result.slr.IsEmpty() { - err = result.NextWithContext(ctx) - return - } - - return -} - -// GetStorageAccountsPreparer prepares the GetStorageAccounts request. -func (client BaseClient) GetStorageAccountsPreparer(ctx context.Context, vaultBaseURL string, maxresults *int32) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if maxresults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *maxresults) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/storage"), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetStorageAccountsSender sends the GetStorageAccounts request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) GetStorageAccountsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// GetStorageAccountsResponder handles the response to the GetStorageAccounts request. The method always -// closes the http.Response Body. -func (client BaseClient) GetStorageAccountsResponder(resp *http.Response) (result StorageListResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// getStorageAccountsNextResults retrieves the next set of results, if any. -func (client BaseClient) getStorageAccountsNextResults(ctx context.Context, lastResults StorageListResult) (result StorageListResult, err error) { - req, err := lastResults.storageListResultPreparer(ctx) - if err != nil { - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getStorageAccountsNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.GetStorageAccountsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "keyvault.BaseClient", "getStorageAccountsNextResults", resp, "Failure sending next results request") - } - result, err = client.GetStorageAccountsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "getStorageAccountsNextResults", resp, "Failure responding to next results request") - } - return -} - -// GetStorageAccountsComplete enumerates all values, automatically crossing page boundaries as required. -func (client BaseClient) GetStorageAccountsComplete(ctx context.Context, vaultBaseURL string, maxresults *int32) (result StorageListResultIterator, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.GetStorageAccounts") - defer func() { - sc := -1 - if result.Response().Response.Response != nil { - sc = result.page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - result.page, err = client.GetStorageAccounts(ctx, vaultBaseURL, maxresults) - return -} - -// ImportCertificate imports an existing valid certificate, containing a private key, into Azure Key Vault. The -// certificate to be imported can be in either PFX or PEM format. If the certificate is in PEM format the PEM file must -// contain the key as well as x509 certificates. This operation requires the certificates/import permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate. -// parameters - the parameters to import the certificate. -func (client BaseClient) ImportCertificate(ctx context.Context, vaultBaseURL string, certificateName string, parameters CertificateImportParameters) (result CertificateBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.ImportCertificate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: certificateName, - Constraints: []validation.Constraint{{Target: "certificateName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z-]+$`, Chain: nil}}}, - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Base64EncodedCertificate", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.CertificatePolicy", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.CertificatePolicy.X509CertificateProperties", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.CertificatePolicy.X509CertificateProperties.ValidityInMonths", Name: validation.Null, Rule: false, - Chain: []validation.Constraint{{Target: "parameters.CertificatePolicy.X509CertificateProperties.ValidityInMonths", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}, - }}, - }}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "ImportCertificate", err.Error()) - } - - req, err := client.ImportCertificatePreparer(ctx, vaultBaseURL, certificateName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "ImportCertificate", nil, "Failure preparing request") - return - } - - resp, err := client.ImportCertificateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "ImportCertificate", resp, "Failure sending request") - return - } - - result, err = client.ImportCertificateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "ImportCertificate", resp, "Failure responding to request") - return - } - - return -} - -// ImportCertificatePreparer prepares the ImportCertificate request. -func (client BaseClient) ImportCertificatePreparer(ctx context.Context, vaultBaseURL string, certificateName string, parameters CertificateImportParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}/import", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ImportCertificateSender sends the ImportCertificate request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) ImportCertificateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ImportCertificateResponder handles the response to the ImportCertificate request. The method always -// closes the http.Response Body. -func (client BaseClient) ImportCertificateResponder(resp *http.Response) (result CertificateBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ImportKey the import key operation may be used to import any key type into an Azure Key Vault. If the named key -// already exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import -// permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - name for the imported key. -// parameters - the parameters to import a key. -func (client BaseClient) ImportKey(ctx context.Context, vaultBaseURL string, keyName string, parameters KeyImportParameters) (result KeyBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.ImportKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: keyName, - Constraints: []validation.Constraint{{Target: "keyName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z-]+$`, Chain: nil}}}, - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Key", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "ImportKey", err.Error()) - } - - req, err := client.ImportKeyPreparer(ctx, vaultBaseURL, keyName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "ImportKey", nil, "Failure preparing request") - return - } - - resp, err := client.ImportKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "ImportKey", resp, "Failure sending request") - return - } - - result, err = client.ImportKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "ImportKey", resp, "Failure responding to request") - return - } - - return -} - -// ImportKeyPreparer prepares the ImportKey request. -func (client BaseClient) ImportKeyPreparer(ctx context.Context, vaultBaseURL string, keyName string, parameters KeyImportParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ImportKeySender sends the ImportKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) ImportKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// ImportKeyResponder handles the response to the ImportKey request. The method always -// closes the http.Response Body. -func (client BaseClient) ImportKeyResponder(resp *http.Response) (result KeyBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// MergeCertificate the MergeCertificate operation performs the merging of a certificate or certificate chain with a -// key pair currently available in the service. This operation requires the certificates/create permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate. -// parameters - the parameters to merge certificate. -func (client BaseClient) MergeCertificate(ctx context.Context, vaultBaseURL string, certificateName string, parameters CertificateMergeParameters) (result CertificateBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.MergeCertificate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.X509Certificates", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "MergeCertificate", err.Error()) - } - - req, err := client.MergeCertificatePreparer(ctx, vaultBaseURL, certificateName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "MergeCertificate", nil, "Failure preparing request") - return - } - - resp, err := client.MergeCertificateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "MergeCertificate", resp, "Failure sending request") - return - } - - result, err = client.MergeCertificateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "MergeCertificate", resp, "Failure responding to request") - return - } - - return -} - -// MergeCertificatePreparer prepares the MergeCertificate request. -func (client BaseClient) MergeCertificatePreparer(ctx context.Context, vaultBaseURL string, certificateName string, parameters CertificateMergeParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}/pending/merge", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// MergeCertificateSender sends the MergeCertificate request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) MergeCertificateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// MergeCertificateResponder handles the response to the MergeCertificate request. The method always -// closes the http.Response Body. -func (client BaseClient) MergeCertificateResponder(resp *http.Response) (result CertificateBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// PurgeDeletedCertificate the PurgeDeletedCertificate operation performs an irreversible deletion of the specified -// certificate, without possibility for recovery. The operation is not available if the recovery level does not specify -// 'Purgeable'. This operation requires the certificate/purge permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate -func (client BaseClient) PurgeDeletedCertificate(ctx context.Context, vaultBaseURL string, certificateName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.PurgeDeletedCertificate") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PurgeDeletedCertificatePreparer(ctx, vaultBaseURL, certificateName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "PurgeDeletedCertificate", nil, "Failure preparing request") - return - } - - resp, err := client.PurgeDeletedCertificateSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "PurgeDeletedCertificate", resp, "Failure sending request") - return - } - - result, err = client.PurgeDeletedCertificateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "PurgeDeletedCertificate", resp, "Failure responding to request") - return - } - - return -} - -// PurgeDeletedCertificatePreparer prepares the PurgeDeletedCertificate request. -func (client BaseClient) PurgeDeletedCertificatePreparer(ctx context.Context, vaultBaseURL string, certificateName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/deletedcertificates/{certificate-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PurgeDeletedCertificateSender sends the PurgeDeletedCertificate request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) PurgeDeletedCertificateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// PurgeDeletedCertificateResponder handles the response to the PurgeDeletedCertificate request. The method always -// closes the http.Response Body. -func (client BaseClient) PurgeDeletedCertificateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// PurgeDeletedKey the Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation -// can be invoked on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation -// requires the keys/purge permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key -func (client BaseClient) PurgeDeletedKey(ctx context.Context, vaultBaseURL string, keyName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.PurgeDeletedKey") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PurgeDeletedKeyPreparer(ctx, vaultBaseURL, keyName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "PurgeDeletedKey", nil, "Failure preparing request") - return - } - - resp, err := client.PurgeDeletedKeySender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "PurgeDeletedKey", resp, "Failure sending request") - return - } - - result, err = client.PurgeDeletedKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "PurgeDeletedKey", resp, "Failure responding to request") - return - } - - return -} - -// PurgeDeletedKeyPreparer prepares the PurgeDeletedKey request. -func (client BaseClient) PurgeDeletedKeyPreparer(ctx context.Context, vaultBaseURL string, keyName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/deletedkeys/{key-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PurgeDeletedKeySender sends the PurgeDeletedKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) PurgeDeletedKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// PurgeDeletedKeyResponder handles the response to the PurgeDeletedKey request. The method always -// closes the http.Response Body. -func (client BaseClient) PurgeDeletedKeyResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// PurgeDeletedSecret the purge deleted secret operation removes the secret permanently, without the possibility of -// recovery. This operation can only be enabled on a soft-delete enabled vault. This operation requires the -// secrets/purge permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// secretName - the name of the secret. -func (client BaseClient) PurgeDeletedSecret(ctx context.Context, vaultBaseURL string, secretName string) (result autorest.Response, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.PurgeDeletedSecret") - defer func() { - sc := -1 - if result.Response != nil { - sc = result.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.PurgeDeletedSecretPreparer(ctx, vaultBaseURL, secretName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "PurgeDeletedSecret", nil, "Failure preparing request") - return - } - - resp, err := client.PurgeDeletedSecretSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "PurgeDeletedSecret", resp, "Failure sending request") - return - } - - result, err = client.PurgeDeletedSecretResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "PurgeDeletedSecret", resp, "Failure responding to request") - return - } - - return -} - -// PurgeDeletedSecretPreparer prepares the PurgeDeletedSecret request. -func (client BaseClient) PurgeDeletedSecretPreparer(ctx context.Context, vaultBaseURL string, secretName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "secret-name": autorest.Encode("path", secretName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/deletedsecrets/{secret-name}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// PurgeDeletedSecretSender sends the PurgeDeletedSecret request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) PurgeDeletedSecretSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// PurgeDeletedSecretResponder handles the response to the PurgeDeletedSecret request. The method always -// closes the http.Response Body. -func (client BaseClient) PurgeDeletedSecretResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// RecoverDeletedCertificate the RecoverDeletedCertificate operation performs the reversal of the Delete operation. The -// operation is applicable in vaults enabled for soft-delete, and must be issued during the retention interval -// (available in the deleted certificate's attributes). This operation requires the certificates/recover permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the deleted certificate -func (client BaseClient) RecoverDeletedCertificate(ctx context.Context, vaultBaseURL string, certificateName string) (result CertificateBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.RecoverDeletedCertificate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RecoverDeletedCertificatePreparer(ctx, vaultBaseURL, certificateName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RecoverDeletedCertificate", nil, "Failure preparing request") - return - } - - resp, err := client.RecoverDeletedCertificateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RecoverDeletedCertificate", resp, "Failure sending request") - return - } - - result, err = client.RecoverDeletedCertificateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RecoverDeletedCertificate", resp, "Failure responding to request") - return - } - - return -} - -// RecoverDeletedCertificatePreparer prepares the RecoverDeletedCertificate request. -func (client BaseClient) RecoverDeletedCertificatePreparer(ctx context.Context, vaultBaseURL string, certificateName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/deletedcertificates/{certificate-name}/recover", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RecoverDeletedCertificateSender sends the RecoverDeletedCertificate request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) RecoverDeletedCertificateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// RecoverDeletedCertificateResponder handles the response to the RecoverDeletedCertificate request. The method always -// closes the http.Response Body. -func (client BaseClient) RecoverDeletedCertificateResponder(resp *http.Response) (result CertificateBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// RecoverDeletedKey the Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It -// recovers the deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will -// return an error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation -// requires the keys/recover permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the deleted key. -func (client BaseClient) RecoverDeletedKey(ctx context.Context, vaultBaseURL string, keyName string) (result KeyBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.RecoverDeletedKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RecoverDeletedKeyPreparer(ctx, vaultBaseURL, keyName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RecoverDeletedKey", nil, "Failure preparing request") - return - } - - resp, err := client.RecoverDeletedKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RecoverDeletedKey", resp, "Failure sending request") - return - } - - result, err = client.RecoverDeletedKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RecoverDeletedKey", resp, "Failure responding to request") - return - } - - return -} - -// RecoverDeletedKeyPreparer prepares the RecoverDeletedKey request. -func (client BaseClient) RecoverDeletedKeyPreparer(ctx context.Context, vaultBaseURL string, keyName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/deletedkeys/{key-name}/recover", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RecoverDeletedKeySender sends the RecoverDeletedKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) RecoverDeletedKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// RecoverDeletedKeyResponder handles the response to the RecoverDeletedKey request. The method always -// closes the http.Response Body. -func (client BaseClient) RecoverDeletedKeyResponder(resp *http.Response) (result KeyBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// RecoverDeletedSecret recovers the deleted secret in the specified vault. This operation can only be performed on a -// soft-delete enabled vault. This operation requires the secrets/recover permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// secretName - the name of the deleted secret. -func (client BaseClient) RecoverDeletedSecret(ctx context.Context, vaultBaseURL string, secretName string) (result SecretBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.RecoverDeletedSecret") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.RecoverDeletedSecretPreparer(ctx, vaultBaseURL, secretName) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RecoverDeletedSecret", nil, "Failure preparing request") - return - } - - resp, err := client.RecoverDeletedSecretSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RecoverDeletedSecret", resp, "Failure sending request") - return - } - - result, err = client.RecoverDeletedSecretResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RecoverDeletedSecret", resp, "Failure responding to request") - return - } - - return -} - -// RecoverDeletedSecretPreparer prepares the RecoverDeletedSecret request. -func (client BaseClient) RecoverDeletedSecretPreparer(ctx context.Context, vaultBaseURL string, secretName string) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "secret-name": autorest.Encode("path", secretName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/deletedsecrets/{secret-name}/recover", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RecoverDeletedSecretSender sends the RecoverDeletedSecret request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) RecoverDeletedSecretSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// RecoverDeletedSecretResponder handles the response to the RecoverDeletedSecret request. The method always -// closes the http.Response Body. -func (client BaseClient) RecoverDeletedSecretResponder(resp *http.Response) (result SecretBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// RegenerateStorageAccountKey regenerates the specified key value for the given storage account. This operation -// requires the storage/regeneratekey permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// storageAccountName - the name of the storage account. -// parameters - the parameters to regenerate storage account key. -func (client BaseClient) RegenerateStorageAccountKey(ctx context.Context, vaultBaseURL string, storageAccountName string, parameters StorageAccountRegenerteKeyParameters) (result StorageBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.RegenerateStorageAccountKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: storageAccountName, - Constraints: []validation.Constraint{{Target: "storageAccountName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}, - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.KeyName", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "RegenerateStorageAccountKey", err.Error()) - } - - req, err := client.RegenerateStorageAccountKeyPreparer(ctx, vaultBaseURL, storageAccountName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RegenerateStorageAccountKey", nil, "Failure preparing request") - return - } - - resp, err := client.RegenerateStorageAccountKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RegenerateStorageAccountKey", resp, "Failure sending request") - return - } - - result, err = client.RegenerateStorageAccountKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RegenerateStorageAccountKey", resp, "Failure responding to request") - return - } - - return -} - -// RegenerateStorageAccountKeyPreparer prepares the RegenerateStorageAccountKey request. -func (client BaseClient) RegenerateStorageAccountKeyPreparer(ctx context.Context, vaultBaseURL string, storageAccountName string, parameters StorageAccountRegenerteKeyParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "storage-account-name": autorest.Encode("path", storageAccountName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/storage/{storage-account-name}/regeneratekey", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RegenerateStorageAccountKeySender sends the RegenerateStorageAccountKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) RegenerateStorageAccountKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// RegenerateStorageAccountKeyResponder handles the response to the RegenerateStorageAccountKey request. The method always -// closes the http.Response Body. -func (client BaseClient) RegenerateStorageAccountKeyResponder(resp *http.Response) (result StorageBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// RestoreKey imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, -// attributes and access control policies. The RESTORE operation may be used to import a previously backed up key. -// Individual versions of a key cannot be restored. The key is restored in its entirety with the same key name as it -// had when it was backed up. If the key name is not available in the target Key Vault, the RESTORE operation will be -// rejected. While the key name is retained during restore, the final key identifier will change if the key is restored -// to a different vault. Restore will restore all versions and preserve version identifiers. The RESTORE operation is -// subject to security constraints: The target Key Vault must be owned by the same Microsoft Azure Subscription as the -// source Key Vault The user must have RESTORE permission in the target Key Vault. This operation requires the -// keys/restore permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// parameters - the parameters to restore the key. -func (client BaseClient) RestoreKey(ctx context.Context, vaultBaseURL string, parameters KeyRestoreParameters) (result KeyBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.RestoreKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.KeyBundleBackup", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "RestoreKey", err.Error()) - } - - req, err := client.RestoreKeyPreparer(ctx, vaultBaseURL, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RestoreKey", nil, "Failure preparing request") - return - } - - resp, err := client.RestoreKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RestoreKey", resp, "Failure sending request") - return - } - - result, err = client.RestoreKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RestoreKey", resp, "Failure responding to request") - return - } - - return -} - -// RestoreKeyPreparer prepares the RestoreKey request. -func (client BaseClient) RestoreKeyPreparer(ctx context.Context, vaultBaseURL string, parameters KeyRestoreParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/keys/restore"), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RestoreKeySender sends the RestoreKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) RestoreKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// RestoreKeyResponder handles the response to the RestoreKey request. The method always -// closes the http.Response Body. -func (client BaseClient) RestoreKeyResponder(resp *http.Response) (result KeyBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// RestoreSecret restores a backed up secret, and all its versions, to a vault. This operation requires the -// secrets/restore permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// parameters - the parameters to restore the secret. -func (client BaseClient) RestoreSecret(ctx context.Context, vaultBaseURL string, parameters SecretRestoreParameters) (result SecretBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.RestoreSecret") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.SecretBundleBackup", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "RestoreSecret", err.Error()) - } - - req, err := client.RestoreSecretPreparer(ctx, vaultBaseURL, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RestoreSecret", nil, "Failure preparing request") - return - } - - resp, err := client.RestoreSecretSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RestoreSecret", resp, "Failure sending request") - return - } - - result, err = client.RestoreSecretResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "RestoreSecret", resp, "Failure responding to request") - return - } - - return -} - -// RestoreSecretPreparer prepares the RestoreSecret request. -func (client BaseClient) RestoreSecretPreparer(ctx context.Context, vaultBaseURL string, parameters SecretRestoreParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/secrets/restore"), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// RestoreSecretSender sends the RestoreSecret request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) RestoreSecretSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// RestoreSecretResponder handles the response to the RestoreSecret request. The method always -// closes the http.Response Body. -func (client BaseClient) RestoreSecretResponder(resp *http.Response) (result SecretBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SetCertificateContacts sets the certificate contacts for the specified key vault. This operation requires the -// certificates/managecontacts permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// contacts - the contacts for the key vault certificate. -func (client BaseClient) SetCertificateContacts(ctx context.Context, vaultBaseURL string, contacts Contacts) (result Contacts, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.SetCertificateContacts") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.SetCertificateContactsPreparer(ctx, vaultBaseURL, contacts) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetCertificateContacts", nil, "Failure preparing request") - return - } - - resp, err := client.SetCertificateContactsSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetCertificateContacts", resp, "Failure sending request") - return - } - - result, err = client.SetCertificateContactsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetCertificateContacts", resp, "Failure responding to request") - return - } - - return -} - -// SetCertificateContactsPreparer prepares the SetCertificateContacts request. -func (client BaseClient) SetCertificateContactsPreparer(ctx context.Context, vaultBaseURL string, contacts Contacts) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - contacts.ID = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPath("/certificates/contacts"), - autorest.WithJSON(contacts), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetCertificateContactsSender sends the SetCertificateContacts request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) SetCertificateContactsSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// SetCertificateContactsResponder handles the response to the SetCertificateContacts request. The method always -// closes the http.Response Body. -func (client BaseClient) SetCertificateContactsResponder(resp *http.Response) (result Contacts, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SetCertificateIssuer the SetCertificateIssuer operation adds or updates the specified certificate issuer. This -// operation requires the certificates/setissuers permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// issuerName - the name of the issuer. -// parameter - certificate issuer set parameter. -func (client BaseClient) SetCertificateIssuer(ctx context.Context, vaultBaseURL string, issuerName string, parameter CertificateIssuerSetParameters) (result IssuerBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.SetCertificateIssuer") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameter, - Constraints: []validation.Constraint{{Target: "parameter.Provider", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "SetCertificateIssuer", err.Error()) - } - - req, err := client.SetCertificateIssuerPreparer(ctx, vaultBaseURL, issuerName, parameter) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetCertificateIssuer", nil, "Failure preparing request") - return - } - - resp, err := client.SetCertificateIssuerSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetCertificateIssuer", resp, "Failure sending request") - return - } - - result, err = client.SetCertificateIssuerResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetCertificateIssuer", resp, "Failure responding to request") - return - } - - return -} - -// SetCertificateIssuerPreparer prepares the SetCertificateIssuer request. -func (client BaseClient) SetCertificateIssuerPreparer(ctx context.Context, vaultBaseURL string, issuerName string, parameter CertificateIssuerSetParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "issuer-name": autorest.Encode("path", issuerName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/issuers/{issuer-name}", pathParameters), - autorest.WithJSON(parameter), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetCertificateIssuerSender sends the SetCertificateIssuer request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) SetCertificateIssuerSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// SetCertificateIssuerResponder handles the response to the SetCertificateIssuer request. The method always -// closes the http.Response Body. -func (client BaseClient) SetCertificateIssuerResponder(resp *http.Response) (result IssuerBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SetSasDefinition creates or updates a new SAS definition for the specified storage account. This operation requires -// the storage/setsas permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// storageAccountName - the name of the storage account. -// sasDefinitionName - the name of the SAS definition. -// parameters - the parameters to create a SAS definition. -func (client BaseClient) SetSasDefinition(ctx context.Context, vaultBaseURL string, storageAccountName string, sasDefinitionName string, parameters SasDefinitionCreateParameters) (result SasDefinitionBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.SetSasDefinition") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: storageAccountName, - Constraints: []validation.Constraint{{Target: "storageAccountName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}, - {TargetValue: sasDefinitionName, - Constraints: []validation.Constraint{{Target: "sasDefinitionName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}, - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Parameters", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "SetSasDefinition", err.Error()) - } - - req, err := client.SetSasDefinitionPreparer(ctx, vaultBaseURL, storageAccountName, sasDefinitionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetSasDefinition", nil, "Failure preparing request") - return - } - - resp, err := client.SetSasDefinitionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetSasDefinition", resp, "Failure sending request") - return - } - - result, err = client.SetSasDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetSasDefinition", resp, "Failure responding to request") - return - } - - return -} - -// SetSasDefinitionPreparer prepares the SetSasDefinition request. -func (client BaseClient) SetSasDefinitionPreparer(ctx context.Context, vaultBaseURL string, storageAccountName string, sasDefinitionName string, parameters SasDefinitionCreateParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "sas-definition-name": autorest.Encode("path", sasDefinitionName), - "storage-account-name": autorest.Encode("path", storageAccountName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/storage/{storage-account-name}/sas/{sas-definition-name}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetSasDefinitionSender sends the SetSasDefinition request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) SetSasDefinitionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// SetSasDefinitionResponder handles the response to the SetSasDefinition request. The method always -// closes the http.Response Body. -func (client BaseClient) SetSasDefinitionResponder(resp *http.Response) (result SasDefinitionBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SetSecret the SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key -// Vault creates a new version of that secret. This operation requires the secrets/set permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// secretName - the name of the secret. -// parameters - the parameters for setting the secret. -func (client BaseClient) SetSecret(ctx context.Context, vaultBaseURL string, secretName string, parameters SecretSetParameters) (result SecretBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.SetSecret") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: secretName, - Constraints: []validation.Constraint{{Target: "secretName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z-]+$`, Chain: nil}}}, - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Value", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "SetSecret", err.Error()) - } - - req, err := client.SetSecretPreparer(ctx, vaultBaseURL, secretName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetSecret", nil, "Failure preparing request") - return - } - - resp, err := client.SetSecretSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetSecret", resp, "Failure sending request") - return - } - - result, err = client.SetSecretResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetSecret", resp, "Failure responding to request") - return - } - - return -} - -// SetSecretPreparer prepares the SetSecret request. -func (client BaseClient) SetSecretPreparer(ctx context.Context, vaultBaseURL string, secretName string, parameters SecretSetParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "secret-name": autorest.Encode("path", secretName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/secrets/{secret-name}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetSecretSender sends the SetSecret request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) SetSecretSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// SetSecretResponder handles the response to the SetSecret request. The method always -// closes the http.Response Body. -func (client BaseClient) SetSecretResponder(resp *http.Response) (result SecretBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// SetStorageAccount creates or updates a new storage account. This operation requires the storage/set permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// storageAccountName - the name of the storage account. -// parameters - the parameters to create a storage account. -func (client BaseClient) SetStorageAccount(ctx context.Context, vaultBaseURL string, storageAccountName string, parameters StorageAccountCreateParameters) (result StorageBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.SetStorageAccount") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: storageAccountName, - Constraints: []validation.Constraint{{Target: "storageAccountName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}, - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.ResourceID", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.ActiveKeyName", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.AutoRegenerateKey", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "SetStorageAccount", err.Error()) - } - - req, err := client.SetStorageAccountPreparer(ctx, vaultBaseURL, storageAccountName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetStorageAccount", nil, "Failure preparing request") - return - } - - resp, err := client.SetStorageAccountSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetStorageAccount", resp, "Failure sending request") - return - } - - result, err = client.SetStorageAccountResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "SetStorageAccount", resp, "Failure responding to request") - return - } - - return -} - -// SetStorageAccountPreparer prepares the SetStorageAccount request. -func (client BaseClient) SetStorageAccountPreparer(ctx context.Context, vaultBaseURL string, storageAccountName string, parameters StorageAccountCreateParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "storage-account-name": autorest.Encode("path", storageAccountName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/storage/{storage-account-name}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetStorageAccountSender sends the SetStorageAccount request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) SetStorageAccountSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// SetStorageAccountResponder handles the response to the SetStorageAccount request. The method always -// closes the http.Response Body. -func (client BaseClient) SetStorageAccountResponder(resp *http.Response) (result StorageBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Sign the SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this -// operation uses the private portion of the key. This operation requires the keys/sign permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key. -// keyVersion - the version of the key. -// parameters - the parameters for the signing operation. -func (client BaseClient) Sign(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeySignParameters) (result KeyOperationResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.Sign") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Value", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "Sign", err.Error()) - } - - req, err := client.SignPreparer(ctx, vaultBaseURL, keyName, keyVersion, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Sign", nil, "Failure preparing request") - return - } - - resp, err := client.SignSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Sign", resp, "Failure sending request") - return - } - - result, err = client.SignResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Sign", resp, "Failure responding to request") - return - } - - return -} - -// SignPreparer prepares the Sign request. -func (client BaseClient) SignPreparer(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeySignParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - "key-version": autorest.Encode("path", keyVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}/{key-version}/sign", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SignSender sends the Sign request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) SignSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// SignResponder handles the response to the Sign request. The method always -// closes the http.Response Body. -func (client BaseClient) SignResponder(resp *http.Response) (result KeyOperationResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UnwrapKey the UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This -// operation is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored -// in Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey -// permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key. -// keyVersion - the version of the key. -// parameters - the parameters for the key operation. -func (client BaseClient) UnwrapKey(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyOperationsParameters) (result KeyOperationResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.UnwrapKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Value", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "UnwrapKey", err.Error()) - } - - req, err := client.UnwrapKeyPreparer(ctx, vaultBaseURL, keyName, keyVersion, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UnwrapKey", nil, "Failure preparing request") - return - } - - resp, err := client.UnwrapKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UnwrapKey", resp, "Failure sending request") - return - } - - result, err = client.UnwrapKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UnwrapKey", resp, "Failure responding to request") - return - } - - return -} - -// UnwrapKeyPreparer prepares the UnwrapKey request. -func (client BaseClient) UnwrapKeyPreparer(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyOperationsParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - "key-version": autorest.Encode("path", keyVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}/{key-version}/unwrapkey", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UnwrapKeySender sends the UnwrapKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) UnwrapKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// UnwrapKeyResponder handles the response to the UnwrapKey request. The method always -// closes the http.Response Body. -func (client BaseClient) UnwrapKeyResponder(resp *http.Response) (result KeyOperationResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateCertificate the UpdateCertificate operation applies the specified update on the given certificate; the only -// elements updated are the certificate's attributes. This operation requires the certificates/update permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate in the given key vault. -// certificateVersion - the version of the certificate. -// parameters - the parameters for certificate update. -func (client BaseClient) UpdateCertificate(ctx context.Context, vaultBaseURL string, certificateName string, certificateVersion string, parameters CertificateUpdateParameters) (result CertificateBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.UpdateCertificate") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateCertificatePreparer(ctx, vaultBaseURL, certificateName, certificateVersion, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificate", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateCertificateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificate", resp, "Failure sending request") - return - } - - result, err = client.UpdateCertificateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificate", resp, "Failure responding to request") - return - } - - return -} - -// UpdateCertificatePreparer prepares the UpdateCertificate request. -func (client BaseClient) UpdateCertificatePreparer(ctx context.Context, vaultBaseURL string, certificateName string, certificateVersion string, parameters CertificateUpdateParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - "certificate-version": autorest.Encode("path", certificateVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}/{certificate-version}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateCertificateSender sends the UpdateCertificate request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) UpdateCertificateSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// UpdateCertificateResponder handles the response to the UpdateCertificate request. The method always -// closes the http.Response Body. -func (client BaseClient) UpdateCertificateResponder(resp *http.Response) (result CertificateBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateCertificateIssuer the UpdateCertificateIssuer operation performs an update on the specified certificate issuer -// entity. This operation requires the certificates/setissuers permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// issuerName - the name of the issuer. -// parameter - certificate issuer update parameter. -func (client BaseClient) UpdateCertificateIssuer(ctx context.Context, vaultBaseURL string, issuerName string, parameter CertificateIssuerUpdateParameters) (result IssuerBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.UpdateCertificateIssuer") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateCertificateIssuerPreparer(ctx, vaultBaseURL, issuerName, parameter) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificateIssuer", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateCertificateIssuerSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificateIssuer", resp, "Failure sending request") - return - } - - result, err = client.UpdateCertificateIssuerResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificateIssuer", resp, "Failure responding to request") - return - } - - return -} - -// UpdateCertificateIssuerPreparer prepares the UpdateCertificateIssuer request. -func (client BaseClient) UpdateCertificateIssuerPreparer(ctx context.Context, vaultBaseURL string, issuerName string, parameter CertificateIssuerUpdateParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "issuer-name": autorest.Encode("path", issuerName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/issuers/{issuer-name}", pathParameters), - autorest.WithJSON(parameter), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateCertificateIssuerSender sends the UpdateCertificateIssuer request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) UpdateCertificateIssuerSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// UpdateCertificateIssuerResponder handles the response to the UpdateCertificateIssuer request. The method always -// closes the http.Response Body. -func (client BaseClient) UpdateCertificateIssuerResponder(resp *http.Response) (result IssuerBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateCertificateOperation updates a certificate creation operation that is already in progress. This operation -// requires the certificates/update permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate. -// certificateOperation - the certificate operation response. -func (client BaseClient) UpdateCertificateOperation(ctx context.Context, vaultBaseURL string, certificateName string, certificateOperation CertificateOperationUpdateParameter) (result CertificateOperation, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.UpdateCertificateOperation") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateCertificateOperationPreparer(ctx, vaultBaseURL, certificateName, certificateOperation) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificateOperation", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateCertificateOperationSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificateOperation", resp, "Failure sending request") - return - } - - result, err = client.UpdateCertificateOperationResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificateOperation", resp, "Failure responding to request") - return - } - - return -} - -// UpdateCertificateOperationPreparer prepares the UpdateCertificateOperation request. -func (client BaseClient) UpdateCertificateOperationPreparer(ctx context.Context, vaultBaseURL string, certificateName string, certificateOperation CertificateOperationUpdateParameter) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}/pending", pathParameters), - autorest.WithJSON(certificateOperation), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateCertificateOperationSender sends the UpdateCertificateOperation request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) UpdateCertificateOperationSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// UpdateCertificateOperationResponder handles the response to the UpdateCertificateOperation request. The method always -// closes the http.Response Body. -func (client BaseClient) UpdateCertificateOperationResponder(resp *http.Response) (result CertificateOperation, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateCertificatePolicy set specified members in the certificate policy. Leave others as null. This operation -// requires the certificates/update permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// certificateName - the name of the certificate in the given vault. -// certificatePolicy - the policy for the certificate. -func (client BaseClient) UpdateCertificatePolicy(ctx context.Context, vaultBaseURL string, certificateName string, certificatePolicy CertificatePolicy) (result CertificatePolicy, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.UpdateCertificatePolicy") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateCertificatePolicyPreparer(ctx, vaultBaseURL, certificateName, certificatePolicy) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificatePolicy", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateCertificatePolicySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificatePolicy", resp, "Failure sending request") - return - } - - result, err = client.UpdateCertificatePolicyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateCertificatePolicy", resp, "Failure responding to request") - return - } - - return -} - -// UpdateCertificatePolicyPreparer prepares the UpdateCertificatePolicy request. -func (client BaseClient) UpdateCertificatePolicyPreparer(ctx context.Context, vaultBaseURL string, certificateName string, certificatePolicy CertificatePolicy) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "certificate-name": autorest.Encode("path", certificateName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - certificatePolicy.ID = nil - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/certificates/{certificate-name}/policy", pathParameters), - autorest.WithJSON(certificatePolicy), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateCertificatePolicySender sends the UpdateCertificatePolicy request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) UpdateCertificatePolicySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// UpdateCertificatePolicyResponder handles the response to the UpdateCertificatePolicy request. The method always -// closes the http.Response Body. -func (client BaseClient) UpdateCertificatePolicyResponder(resp *http.Response) (result CertificatePolicy, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateKey in order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic -// material of a key itself cannot be changed. This operation requires the keys/update permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of key to update. -// keyVersion - the version of the key to update. -// parameters - the parameters of the key to update. -func (client BaseClient) UpdateKey(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyUpdateParameters) (result KeyBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.UpdateKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateKeyPreparer(ctx, vaultBaseURL, keyName, keyVersion, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateKey", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateKey", resp, "Failure sending request") - return - } - - result, err = client.UpdateKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateKey", resp, "Failure responding to request") - return - } - - return -} - -// UpdateKeyPreparer prepares the UpdateKey request. -func (client BaseClient) UpdateKeyPreparer(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyUpdateParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - "key-version": autorest.Encode("path", keyVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}/{key-version}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateKeySender sends the UpdateKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) UpdateKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// UpdateKeyResponder handles the response to the UpdateKey request. The method always -// closes the http.Response Body. -func (client BaseClient) UpdateKeyResponder(resp *http.Response) (result KeyBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateSasDefinition updates the specified attributes associated with the given SAS definition. This operation -// requires the storage/setsas permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// storageAccountName - the name of the storage account. -// sasDefinitionName - the name of the SAS definition. -// parameters - the parameters to update a SAS definition. -func (client BaseClient) UpdateSasDefinition(ctx context.Context, vaultBaseURL string, storageAccountName string, sasDefinitionName string, parameters SasDefinitionUpdateParameters) (result SasDefinitionBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.UpdateSasDefinition") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: storageAccountName, - Constraints: []validation.Constraint{{Target: "storageAccountName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}, - {TargetValue: sasDefinitionName, - Constraints: []validation.Constraint{{Target: "sasDefinitionName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "UpdateSasDefinition", err.Error()) - } - - req, err := client.UpdateSasDefinitionPreparer(ctx, vaultBaseURL, storageAccountName, sasDefinitionName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateSasDefinition", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateSasDefinitionSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateSasDefinition", resp, "Failure sending request") - return - } - - result, err = client.UpdateSasDefinitionResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateSasDefinition", resp, "Failure responding to request") - return - } - - return -} - -// UpdateSasDefinitionPreparer prepares the UpdateSasDefinition request. -func (client BaseClient) UpdateSasDefinitionPreparer(ctx context.Context, vaultBaseURL string, storageAccountName string, sasDefinitionName string, parameters SasDefinitionUpdateParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "sas-definition-name": autorest.Encode("path", sasDefinitionName), - "storage-account-name": autorest.Encode("path", storageAccountName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/storage/{storage-account-name}/sas/{sas-definition-name}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSasDefinitionSender sends the UpdateSasDefinition request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) UpdateSasDefinitionSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// UpdateSasDefinitionResponder handles the response to the UpdateSasDefinition request. The method always -// closes the http.Response Body. -func (client BaseClient) UpdateSasDefinitionResponder(resp *http.Response) (result SasDefinitionBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateSecret the UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not -// specified in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires -// the secrets/set permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// secretName - the name of the secret. -// secretVersion - the version of the secret. -// parameters - the parameters for update secret operation. -func (client BaseClient) UpdateSecret(ctx context.Context, vaultBaseURL string, secretName string, secretVersion string, parameters SecretUpdateParameters) (result SecretBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.UpdateSecret") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - req, err := client.UpdateSecretPreparer(ctx, vaultBaseURL, secretName, secretVersion, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateSecret", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateSecretSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateSecret", resp, "Failure sending request") - return - } - - result, err = client.UpdateSecretResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateSecret", resp, "Failure responding to request") - return - } - - return -} - -// UpdateSecretPreparer prepares the UpdateSecret request. -func (client BaseClient) UpdateSecretPreparer(ctx context.Context, vaultBaseURL string, secretName string, secretVersion string, parameters SecretUpdateParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "secret-name": autorest.Encode("path", secretName), - "secret-version": autorest.Encode("path", secretVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/secrets/{secret-name}/{secret-version}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSecretSender sends the UpdateSecret request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) UpdateSecretSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// UpdateSecretResponder handles the response to the UpdateSecret request. The method always -// closes the http.Response Body. -func (client BaseClient) UpdateSecretResponder(resp *http.Response) (result SecretBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// UpdateStorageAccount updates the specified attributes associated with the given storage account. This operation -// requires the storage/set/update permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// storageAccountName - the name of the storage account. -// parameters - the parameters to update a storage account. -func (client BaseClient) UpdateStorageAccount(ctx context.Context, vaultBaseURL string, storageAccountName string, parameters StorageAccountUpdateParameters) (result StorageBundle, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.UpdateStorageAccount") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: storageAccountName, - Constraints: []validation.Constraint{{Target: "storageAccountName", Name: validation.Pattern, Rule: `^[0-9a-zA-Z]+$`, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "UpdateStorageAccount", err.Error()) - } - - req, err := client.UpdateStorageAccountPreparer(ctx, vaultBaseURL, storageAccountName, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateStorageAccount", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateStorageAccountSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateStorageAccount", resp, "Failure sending request") - return - } - - result, err = client.UpdateStorageAccountResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "UpdateStorageAccount", resp, "Failure responding to request") - return - } - - return -} - -// UpdateStorageAccountPreparer prepares the UpdateStorageAccount request. -func (client BaseClient) UpdateStorageAccountPreparer(ctx context.Context, vaultBaseURL string, storageAccountName string, parameters StorageAccountUpdateParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "storage-account-name": autorest.Encode("path", storageAccountName), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/storage/{storage-account-name}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateStorageAccountSender sends the UpdateStorageAccount request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) UpdateStorageAccountSender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// UpdateStorageAccountResponder handles the response to the UpdateStorageAccount request. The method always -// closes the http.Response Body. -func (client BaseClient) UpdateStorageAccountResponder(resp *http.Response) (result StorageBundle, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Verify the VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly -// necessary for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the -// public portion of the key but this operation is supported as a convenience for callers that only have a -// key-reference and not the public portion of the key. This operation requires the keys/verify permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key. -// keyVersion - the version of the key. -// parameters - the parameters for verify operations. -func (client BaseClient) Verify(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyVerifyParameters) (result KeyVerifyResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.Verify") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Digest", Name: validation.Null, Rule: true, Chain: nil}, - {Target: "parameters.Signature", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "Verify", err.Error()) - } - - req, err := client.VerifyPreparer(ctx, vaultBaseURL, keyName, keyVersion, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Verify", nil, "Failure preparing request") - return - } - - resp, err := client.VerifySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Verify", resp, "Failure sending request") - return - } - - result, err = client.VerifyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "Verify", resp, "Failure responding to request") - return - } - - return -} - -// VerifyPreparer prepares the Verify request. -func (client BaseClient) VerifyPreparer(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyVerifyParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - "key-version": autorest.Encode("path", keyVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}/{key-version}/verify", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// VerifySender sends the Verify request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) VerifySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// VerifyResponder handles the response to the Verify request. The method always -// closes the http.Response Body. -func (client BaseClient) VerifyResponder(resp *http.Response) (result KeyVerifyResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// WrapKey the WRAP operation supports encryption of a symmetric key using a key encryption key that has previously -// been stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure -// Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This -// operation is supported for asymmetric keys as a convenience for callers that have a key-reference but do not have -// access to the public key material. This operation requires the keys/wrapKey permission. -// Parameters: -// vaultBaseURL - the vault name, for example https://myvault.vault.azure.net. -// keyName - the name of the key. -// keyVersion - the version of the key. -// parameters - the parameters for wrap operation. -func (client BaseClient) WrapKey(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyOperationsParameters) (result KeyOperationResult, err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.WrapKey") - defer func() { - sc := -1 - if result.Response.Response != nil { - sc = result.Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - if err := validation.Validate([]validation.Validation{ - {TargetValue: parameters, - Constraints: []validation.Constraint{{Target: "parameters.Value", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil { - return result, validation.NewError("keyvault.BaseClient", "WrapKey", err.Error()) - } - - req, err := client.WrapKeyPreparer(ctx, vaultBaseURL, keyName, keyVersion, parameters) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "WrapKey", nil, "Failure preparing request") - return - } - - resp, err := client.WrapKeySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "WrapKey", resp, "Failure sending request") - return - } - - result, err = client.WrapKeyResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "keyvault.BaseClient", "WrapKey", resp, "Failure responding to request") - return - } - - return -} - -// WrapKeyPreparer prepares the WrapKey request. -func (client BaseClient) WrapKeyPreparer(ctx context.Context, vaultBaseURL string, keyName string, keyVersion string, parameters KeyOperationsParameters) (*http.Request, error) { - urlParameters := map[string]interface{}{ - "vaultBaseUrl": vaultBaseURL, - } - - pathParameters := map[string]interface{}{ - "key-name": autorest.Encode("path", keyName), - "key-version": autorest.Encode("path", keyVersion), - } - - const APIVersion = "2016-10-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPost(), - autorest.WithCustomBaseURL("{vaultBaseUrl}", urlParameters), - autorest.WithPathParameters("/keys/{key-name}/{key-version}/wrapkey", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// WrapKeySender sends the WrapKey request. The method will close the -// http.Response Body if it receives an error. -func (client BaseClient) WrapKeySender(req *http.Request) (*http.Response, error) { - return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) -} - -// WrapKeyResponder handles the response to the WrapKey request. The method always -// closes the http.Response Body. -func (client BaseClient) WrapKeyResponder(resp *http.Response) (result KeyOperationResult, err error) { - err = autorest.Respond( - resp, - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/enums.go b/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/enums.go deleted file mode 100644 index 91b3bf86..00000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/enums.go +++ /dev/null @@ -1,198 +0,0 @@ -package keyvault - -// Copyright (c) Microsoft and contributors. 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. -// 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 Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// ActionType enumerates the values for action type. -type ActionType string - -const ( - // AutoRenew ... - AutoRenew ActionType = "AutoRenew" - // EmailContacts ... - EmailContacts ActionType = "EmailContacts" -) - -// PossibleActionTypeValues returns an array of possible values for the ActionType const type. -func PossibleActionTypeValues() []ActionType { - return []ActionType{AutoRenew, EmailContacts} -} - -// DeletionRecoveryLevel enumerates the values for deletion recovery level. -type DeletionRecoveryLevel string - -const ( - // Purgeable Soft-delete is not enabled for this vault. A DELETE operation results in immediate and - // irreversible data loss. - Purgeable DeletionRecoveryLevel = "Purgeable" - // Recoverable Soft-delete is enabled for this vault and purge has been disabled. A deleted entity will - // remain in this state until recovered, or the end of the retention interval. - Recoverable DeletionRecoveryLevel = "Recoverable" - // RecoverableProtectedSubscription Soft-delete is enabled for this vault, and the subscription is - // protected against immediate deletion. - RecoverableProtectedSubscription DeletionRecoveryLevel = "Recoverable+ProtectedSubscription" - // RecoverablePurgeable Soft-delete is enabled for this vault; A privileged user may trigger an immediate, - // irreversible deletion(purge) of a deleted entity. - RecoverablePurgeable DeletionRecoveryLevel = "Recoverable+Purgeable" -) - -// PossibleDeletionRecoveryLevelValues returns an array of possible values for the DeletionRecoveryLevel const type. -func PossibleDeletionRecoveryLevelValues() []DeletionRecoveryLevel { - return []DeletionRecoveryLevel{Purgeable, Recoverable, RecoverableProtectedSubscription, RecoverablePurgeable} -} - -// JSONWebKeyCurveName enumerates the values for json web key curve name. -type JSONWebKeyCurveName string - -const ( - // P256 The NIST P-256 elliptic curve, AKA SECG curve SECP256R1. - P256 JSONWebKeyCurveName = "P-256" - // P384 The NIST P-384 elliptic curve, AKA SECG curve SECP384R1. - P384 JSONWebKeyCurveName = "P-384" - // P521 The NIST P-521 elliptic curve, AKA SECG curve SECP521R1. - P521 JSONWebKeyCurveName = "P-521" - // SECP256K1 The SECG SECP256K1 elliptic curve. - SECP256K1 JSONWebKeyCurveName = "SECP256K1" -) - -// PossibleJSONWebKeyCurveNameValues returns an array of possible values for the JSONWebKeyCurveName const type. -func PossibleJSONWebKeyCurveNameValues() []JSONWebKeyCurveName { - return []JSONWebKeyCurveName{P256, P384, P521, SECP256K1} -} - -// JSONWebKeyEncryptionAlgorithm enumerates the values for json web key encryption algorithm. -type JSONWebKeyEncryptionAlgorithm string - -const ( - // RSA15 ... - RSA15 JSONWebKeyEncryptionAlgorithm = "RSA1_5" - // RSAOAEP ... - RSAOAEP JSONWebKeyEncryptionAlgorithm = "RSA-OAEP" - // RSAOAEP256 ... - RSAOAEP256 JSONWebKeyEncryptionAlgorithm = "RSA-OAEP-256" -) - -// PossibleJSONWebKeyEncryptionAlgorithmValues returns an array of possible values for the JSONWebKeyEncryptionAlgorithm const type. -func PossibleJSONWebKeyEncryptionAlgorithmValues() []JSONWebKeyEncryptionAlgorithm { - return []JSONWebKeyEncryptionAlgorithm{RSA15, RSAOAEP, RSAOAEP256} -} - -// JSONWebKeyOperation enumerates the values for json web key operation. -type JSONWebKeyOperation string - -const ( - // Decrypt ... - Decrypt JSONWebKeyOperation = "decrypt" - // Encrypt ... - Encrypt JSONWebKeyOperation = "encrypt" - // Sign ... - Sign JSONWebKeyOperation = "sign" - // UnwrapKey ... - UnwrapKey JSONWebKeyOperation = "unwrapKey" - // Verify ... - Verify JSONWebKeyOperation = "verify" - // WrapKey ... - WrapKey JSONWebKeyOperation = "wrapKey" -) - -// PossibleJSONWebKeyOperationValues returns an array of possible values for the JSONWebKeyOperation const type. -func PossibleJSONWebKeyOperationValues() []JSONWebKeyOperation { - return []JSONWebKeyOperation{Decrypt, Encrypt, Sign, UnwrapKey, Verify, WrapKey} -} - -// JSONWebKeySignatureAlgorithm enumerates the values for json web key signature algorithm. -type JSONWebKeySignatureAlgorithm string - -const ( - // ECDSA256 ... - ECDSA256 JSONWebKeySignatureAlgorithm = "ECDSA256" - // ES256 ... - ES256 JSONWebKeySignatureAlgorithm = "ES256" - // ES384 ... - ES384 JSONWebKeySignatureAlgorithm = "ES384" - // ES512 ... - ES512 JSONWebKeySignatureAlgorithm = "ES512" - // PS256 ... - PS256 JSONWebKeySignatureAlgorithm = "PS256" - // PS384 ... - PS384 JSONWebKeySignatureAlgorithm = "PS384" - // PS512 ... - PS512 JSONWebKeySignatureAlgorithm = "PS512" - // RS256 ... - RS256 JSONWebKeySignatureAlgorithm = "RS256" - // RS384 ... - RS384 JSONWebKeySignatureAlgorithm = "RS384" - // RS512 ... - RS512 JSONWebKeySignatureAlgorithm = "RS512" - // RSNULL ... - RSNULL JSONWebKeySignatureAlgorithm = "RSNULL" -) - -// PossibleJSONWebKeySignatureAlgorithmValues returns an array of possible values for the JSONWebKeySignatureAlgorithm const type. -func PossibleJSONWebKeySignatureAlgorithmValues() []JSONWebKeySignatureAlgorithm { - return []JSONWebKeySignatureAlgorithm{ECDSA256, ES256, ES384, ES512, PS256, PS384, PS512, RS256, RS384, RS512, RSNULL} -} - -// JSONWebKeyType enumerates the values for json web key type. -type JSONWebKeyType string - -const ( - // EC ... - EC JSONWebKeyType = "EC" - // ECHSM ... - ECHSM JSONWebKeyType = "EC-HSM" - // Oct ... - Oct JSONWebKeyType = "oct" - // RSA ... - RSA JSONWebKeyType = "RSA" - // RSAHSM ... - RSAHSM JSONWebKeyType = "RSA-HSM" -) - -// PossibleJSONWebKeyTypeValues returns an array of possible values for the JSONWebKeyType const type. -func PossibleJSONWebKeyTypeValues() []JSONWebKeyType { - return []JSONWebKeyType{EC, ECHSM, Oct, RSA, RSAHSM} -} - -// KeyUsageType enumerates the values for key usage type. -type KeyUsageType string - -const ( - // CRLSign ... - CRLSign KeyUsageType = "cRLSign" - // DataEncipherment ... - DataEncipherment KeyUsageType = "dataEncipherment" - // DecipherOnly ... - DecipherOnly KeyUsageType = "decipherOnly" - // DigitalSignature ... - DigitalSignature KeyUsageType = "digitalSignature" - // EncipherOnly ... - EncipherOnly KeyUsageType = "encipherOnly" - // KeyAgreement ... - KeyAgreement KeyUsageType = "keyAgreement" - // KeyCertSign ... - KeyCertSign KeyUsageType = "keyCertSign" - // KeyEncipherment ... - KeyEncipherment KeyUsageType = "keyEncipherment" - // NonRepudiation ... - NonRepudiation KeyUsageType = "nonRepudiation" -) - -// PossibleKeyUsageTypeValues returns an array of possible values for the KeyUsageType const type. -func PossibleKeyUsageTypeValues() []KeyUsageType { - return []KeyUsageType{CRLSign, DataEncipherment, DecipherOnly, DigitalSignature, EncipherOnly, KeyAgreement, KeyCertSign, KeyEncipherment, NonRepudiation} -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/models.go deleted file mode 100644 index 32130333..00000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/models.go +++ /dev/null @@ -1,2988 +0,0 @@ -package keyvault - -// Copyright (c) Microsoft and contributors. 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. -// 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 Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "encoding/json" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/autorest/to" - "github.com/Azure/go-autorest/tracing" - "net/http" -) - -// The package's fully qualified name. -const fqdn = "github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault" - -// Action the action that will be executed. -type Action struct { - // ActionType - The type of the action. Possible values include: 'EmailContacts', 'AutoRenew' - ActionType ActionType `json:"action_type,omitempty"` -} - -// AdministratorDetails details of the organization administrator of the certificate issuer. -type AdministratorDetails struct { - // FirstName - First name. - FirstName *string `json:"first_name,omitempty"` - // LastName - Last name. - LastName *string `json:"last_name,omitempty"` - // EmailAddress - Email address. - EmailAddress *string `json:"email,omitempty"` - // Phone - Phone number. - Phone *string `json:"phone,omitempty"` -} - -// Attributes the object attributes managed by the KeyVault service. -type Attributes struct { - // Enabled - Determines whether the object is enabled. - Enabled *bool `json:"enabled,omitempty"` - // NotBefore - Not before date in UTC. - NotBefore *date.UnixTime `json:"nbf,omitempty"` - // Expires - Expiry date in UTC. - Expires *date.UnixTime `json:"exp,omitempty"` - // Created - READ-ONLY; Creation time in UTC. - Created *date.UnixTime `json:"created,omitempty"` - // Updated - READ-ONLY; Last updated time in UTC. - Updated *date.UnixTime `json:"updated,omitempty"` -} - -// MarshalJSON is the custom marshaler for Attributes. -func (a Attributes) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if a.Enabled != nil { - objectMap["enabled"] = a.Enabled - } - if a.NotBefore != nil { - objectMap["nbf"] = a.NotBefore - } - if a.Expires != nil { - objectMap["exp"] = a.Expires - } - return json.Marshal(objectMap) -} - -// BackupKeyResult the backup key result, containing the backup blob. -type BackupKeyResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; The backup blob containing the backed up key. (a URL-encoded base64 string) - Value *string `json:"value,omitempty"` -} - -// BackupSecretResult the backup secret result, containing the backup blob. -type BackupSecretResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; The backup blob containing the backed up secret. (a URL-encoded base64 string) - Value *string `json:"value,omitempty"` -} - -// CertificateAttributes the certificate management attributes. -type CertificateAttributes struct { - // RecoveryLevel - READ-ONLY; Reflects the deletion recovery level currently in effect for certificates in the current vault. If it contains 'Purgeable', the certificate can be permanently deleted by a privileged user; otherwise, only the system can purge the certificate, at the end of the retention interval. Possible values include: 'Purgeable', 'RecoverablePurgeable', 'Recoverable', 'RecoverableProtectedSubscription' - RecoveryLevel DeletionRecoveryLevel `json:"recoveryLevel,omitempty"` - // Enabled - Determines whether the object is enabled. - Enabled *bool `json:"enabled,omitempty"` - // NotBefore - Not before date in UTC. - NotBefore *date.UnixTime `json:"nbf,omitempty"` - // Expires - Expiry date in UTC. - Expires *date.UnixTime `json:"exp,omitempty"` - // Created - READ-ONLY; Creation time in UTC. - Created *date.UnixTime `json:"created,omitempty"` - // Updated - READ-ONLY; Last updated time in UTC. - Updated *date.UnixTime `json:"updated,omitempty"` -} - -// MarshalJSON is the custom marshaler for CertificateAttributes. -func (ca CertificateAttributes) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ca.Enabled != nil { - objectMap["enabled"] = ca.Enabled - } - if ca.NotBefore != nil { - objectMap["nbf"] = ca.NotBefore - } - if ca.Expires != nil { - objectMap["exp"] = ca.Expires - } - return json.Marshal(objectMap) -} - -// CertificateBundle a certificate bundle consists of a certificate (X509) plus its attributes. -type CertificateBundle struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; The certificate id. - ID *string `json:"id,omitempty"` - // Kid - READ-ONLY; The key id. - Kid *string `json:"kid,omitempty"` - // Sid - READ-ONLY; The secret id. - Sid *string `json:"sid,omitempty"` - // X509Thumbprint - READ-ONLY; Thumbprint of the certificate. (a URL-encoded base64 string) - X509Thumbprint *string `json:"x5t,omitempty"` - // Policy - READ-ONLY; The management policy. - Policy *CertificatePolicy `json:"policy,omitempty"` - // Cer - CER contents of x509 certificate. - Cer *[]byte `json:"cer,omitempty"` - // ContentType - The content type of the secret. - ContentType *string `json:"contentType,omitempty"` - // Attributes - The certificate attributes. - Attributes *CertificateAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for CertificateBundle. -func (cb CertificateBundle) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cb.Cer != nil { - objectMap["cer"] = cb.Cer - } - if cb.ContentType != nil { - objectMap["contentType"] = cb.ContentType - } - if cb.Attributes != nil { - objectMap["attributes"] = cb.Attributes - } - if cb.Tags != nil { - objectMap["tags"] = cb.Tags - } - return json.Marshal(objectMap) -} - -// CertificateCreateParameters the certificate create parameters. -type CertificateCreateParameters struct { - // CertificatePolicy - The management policy for the certificate. - CertificatePolicy *CertificatePolicy `json:"policy,omitempty"` - // CertificateAttributes - The attributes of the certificate (optional). - CertificateAttributes *CertificateAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for CertificateCreateParameters. -func (ccp CertificateCreateParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ccp.CertificatePolicy != nil { - objectMap["policy"] = ccp.CertificatePolicy - } - if ccp.CertificateAttributes != nil { - objectMap["attributes"] = ccp.CertificateAttributes - } - if ccp.Tags != nil { - objectMap["tags"] = ccp.Tags - } - return json.Marshal(objectMap) -} - -// CertificateImportParameters the certificate import parameters. -type CertificateImportParameters struct { - // Base64EncodedCertificate - Base64 encoded representation of the certificate object to import. This certificate needs to contain the private key. - Base64EncodedCertificate *string `json:"value,omitempty"` - // Password - If the private key in base64EncodedCertificate is encrypted, the password used for encryption. - Password *string `json:"pwd,omitempty"` - // CertificatePolicy - The management policy for the certificate. - CertificatePolicy *CertificatePolicy `json:"policy,omitempty"` - // CertificateAttributes - The attributes of the certificate (optional). - CertificateAttributes *CertificateAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for CertificateImportParameters. -func (cip CertificateImportParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cip.Base64EncodedCertificate != nil { - objectMap["value"] = cip.Base64EncodedCertificate - } - if cip.Password != nil { - objectMap["pwd"] = cip.Password - } - if cip.CertificatePolicy != nil { - objectMap["policy"] = cip.CertificatePolicy - } - if cip.CertificateAttributes != nil { - objectMap["attributes"] = cip.CertificateAttributes - } - if cip.Tags != nil { - objectMap["tags"] = cip.Tags - } - return json.Marshal(objectMap) -} - -// CertificateIssuerItem the certificate issuer item containing certificate issuer metadata. -type CertificateIssuerItem struct { - // ID - Certificate Identifier. - ID *string `json:"id,omitempty"` - // Provider - The issuer provider. - Provider *string `json:"provider,omitempty"` -} - -// CertificateIssuerListResult the certificate issuer list result. -type CertificateIssuerListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; A response message containing a list of certificate issuers in the key vault along with a link to the next page of certificate issuers. - Value *[]CertificateIssuerItem `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of certificate issuers. - NextLink *string `json:"nextLink,omitempty"` -} - -// CertificateIssuerListResultIterator provides access to a complete listing of CertificateIssuerItem -// values. -type CertificateIssuerListResultIterator struct { - i int - page CertificateIssuerListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *CertificateIssuerListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CertificateIssuerListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *CertificateIssuerListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter CertificateIssuerListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter CertificateIssuerListResultIterator) Response() CertificateIssuerListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter CertificateIssuerListResultIterator) Value() CertificateIssuerItem { - if !iter.page.NotDone() { - return CertificateIssuerItem{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the CertificateIssuerListResultIterator type. -func NewCertificateIssuerListResultIterator(page CertificateIssuerListResultPage) CertificateIssuerListResultIterator { - return CertificateIssuerListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (cilr CertificateIssuerListResult) IsEmpty() bool { - return cilr.Value == nil || len(*cilr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (cilr CertificateIssuerListResult) hasNextLink() bool { - return cilr.NextLink != nil && len(*cilr.NextLink) != 0 -} - -// certificateIssuerListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (cilr CertificateIssuerListResult) certificateIssuerListResultPreparer(ctx context.Context) (*http.Request, error) { - if !cilr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(cilr.NextLink))) -} - -// CertificateIssuerListResultPage contains a page of CertificateIssuerItem values. -type CertificateIssuerListResultPage struct { - fn func(context.Context, CertificateIssuerListResult) (CertificateIssuerListResult, error) - cilr CertificateIssuerListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *CertificateIssuerListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CertificateIssuerListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.cilr) - if err != nil { - return err - } - page.cilr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *CertificateIssuerListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page CertificateIssuerListResultPage) NotDone() bool { - return !page.cilr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page CertificateIssuerListResultPage) Response() CertificateIssuerListResult { - return page.cilr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page CertificateIssuerListResultPage) Values() []CertificateIssuerItem { - if page.cilr.IsEmpty() { - return nil - } - return *page.cilr.Value -} - -// Creates a new instance of the CertificateIssuerListResultPage type. -func NewCertificateIssuerListResultPage(cur CertificateIssuerListResult, getNextPage func(context.Context, CertificateIssuerListResult) (CertificateIssuerListResult, error)) CertificateIssuerListResultPage { - return CertificateIssuerListResultPage{ - fn: getNextPage, - cilr: cur, - } -} - -// CertificateIssuerSetParameters the certificate issuer set parameters. -type CertificateIssuerSetParameters struct { - // Provider - The issuer provider. - Provider *string `json:"provider,omitempty"` - // Credentials - The credentials to be used for the issuer. - Credentials *IssuerCredentials `json:"credentials,omitempty"` - // OrganizationDetails - Details of the organization as provided to the issuer. - OrganizationDetails *OrganizationDetails `json:"org_details,omitempty"` - // Attributes - Attributes of the issuer object. - Attributes *IssuerAttributes `json:"attributes,omitempty"` -} - -// CertificateIssuerUpdateParameters the certificate issuer update parameters. -type CertificateIssuerUpdateParameters struct { - // Provider - The issuer provider. - Provider *string `json:"provider,omitempty"` - // Credentials - The credentials to be used for the issuer. - Credentials *IssuerCredentials `json:"credentials,omitempty"` - // OrganizationDetails - Details of the organization as provided to the issuer. - OrganizationDetails *OrganizationDetails `json:"org_details,omitempty"` - // Attributes - Attributes of the issuer object. - Attributes *IssuerAttributes `json:"attributes,omitempty"` -} - -// CertificateItem the certificate item containing certificate metadata. -type CertificateItem struct { - // ID - Certificate identifier. - ID *string `json:"id,omitempty"` - // Attributes - The certificate management attributes. - Attributes *CertificateAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // X509Thumbprint - Thumbprint of the certificate. (a URL-encoded base64 string) - X509Thumbprint *string `json:"x5t,omitempty"` -} - -// MarshalJSON is the custom marshaler for CertificateItem. -func (ci CertificateItem) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ci.ID != nil { - objectMap["id"] = ci.ID - } - if ci.Attributes != nil { - objectMap["attributes"] = ci.Attributes - } - if ci.Tags != nil { - objectMap["tags"] = ci.Tags - } - if ci.X509Thumbprint != nil { - objectMap["x5t"] = ci.X509Thumbprint - } - return json.Marshal(objectMap) -} - -// CertificateListResult the certificate list result. -type CertificateListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; A response message containing a list of certificates in the key vault along with a link to the next page of certificates. - Value *[]CertificateItem `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of certificates. - NextLink *string `json:"nextLink,omitempty"` -} - -// CertificateListResultIterator provides access to a complete listing of CertificateItem values. -type CertificateListResultIterator struct { - i int - page CertificateListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *CertificateListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CertificateListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *CertificateListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter CertificateListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter CertificateListResultIterator) Response() CertificateListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter CertificateListResultIterator) Value() CertificateItem { - if !iter.page.NotDone() { - return CertificateItem{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the CertificateListResultIterator type. -func NewCertificateListResultIterator(page CertificateListResultPage) CertificateListResultIterator { - return CertificateListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (clr CertificateListResult) IsEmpty() bool { - return clr.Value == nil || len(*clr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (clr CertificateListResult) hasNextLink() bool { - return clr.NextLink != nil && len(*clr.NextLink) != 0 -} - -// certificateListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (clr CertificateListResult) certificateListResultPreparer(ctx context.Context) (*http.Request, error) { - if !clr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(clr.NextLink))) -} - -// CertificateListResultPage contains a page of CertificateItem values. -type CertificateListResultPage struct { - fn func(context.Context, CertificateListResult) (CertificateListResult, error) - clr CertificateListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *CertificateListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/CertificateListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.clr) - if err != nil { - return err - } - page.clr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *CertificateListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page CertificateListResultPage) NotDone() bool { - return !page.clr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page CertificateListResultPage) Response() CertificateListResult { - return page.clr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page CertificateListResultPage) Values() []CertificateItem { - if page.clr.IsEmpty() { - return nil - } - return *page.clr.Value -} - -// Creates a new instance of the CertificateListResultPage type. -func NewCertificateListResultPage(cur CertificateListResult, getNextPage func(context.Context, CertificateListResult) (CertificateListResult, error)) CertificateListResultPage { - return CertificateListResultPage{ - fn: getNextPage, - clr: cur, - } -} - -// CertificateMergeParameters the certificate merge parameters -type CertificateMergeParameters struct { - // X509Certificates - The certificate or the certificate chain to merge. - X509Certificates *[][]byte `json:"x5c,omitempty"` - // CertificateAttributes - The attributes of the certificate (optional). - CertificateAttributes *CertificateAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for CertificateMergeParameters. -func (cmp CertificateMergeParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cmp.X509Certificates != nil { - objectMap["x5c"] = cmp.X509Certificates - } - if cmp.CertificateAttributes != nil { - objectMap["attributes"] = cmp.CertificateAttributes - } - if cmp.Tags != nil { - objectMap["tags"] = cmp.Tags - } - return json.Marshal(objectMap) -} - -// CertificateOperation a certificate operation is returned in case of asynchronous requests. -type CertificateOperation struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; The certificate id. - ID *string `json:"id,omitempty"` - // IssuerParameters - Parameters for the issuer of the X509 component of a certificate. - IssuerParameters *IssuerParameters `json:"issuer,omitempty"` - // Csr - The certificate signing request (CSR) that is being used in the certificate operation. - Csr *[]byte `json:"csr,omitempty"` - // CancellationRequested - Indicates if cancellation was requested on the certificate operation. - CancellationRequested *bool `json:"cancellation_requested,omitempty"` - // Status - Status of the certificate operation. - Status *string `json:"status,omitempty"` - // StatusDetails - The status details of the certificate operation. - StatusDetails *string `json:"status_details,omitempty"` - // Error - Error encountered, if any, during the certificate operation. - Error *Error `json:"error,omitempty"` - // Target - Location which contains the result of the certificate operation. - Target *string `json:"target,omitempty"` - // RequestID - Identifier for the certificate operation. - RequestID *string `json:"request_id,omitempty"` -} - -// MarshalJSON is the custom marshaler for CertificateOperation. -func (co CertificateOperation) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if co.IssuerParameters != nil { - objectMap["issuer"] = co.IssuerParameters - } - if co.Csr != nil { - objectMap["csr"] = co.Csr - } - if co.CancellationRequested != nil { - objectMap["cancellation_requested"] = co.CancellationRequested - } - if co.Status != nil { - objectMap["status"] = co.Status - } - if co.StatusDetails != nil { - objectMap["status_details"] = co.StatusDetails - } - if co.Error != nil { - objectMap["error"] = co.Error - } - if co.Target != nil { - objectMap["target"] = co.Target - } - if co.RequestID != nil { - objectMap["request_id"] = co.RequestID - } - return json.Marshal(objectMap) -} - -// CertificateOperationUpdateParameter the certificate operation update parameters. -type CertificateOperationUpdateParameter struct { - // CancellationRequested - Indicates if cancellation was requested on the certificate operation. - CancellationRequested *bool `json:"cancellation_requested,omitempty"` -} - -// CertificatePolicy management policy for a certificate. -type CertificatePolicy struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; The certificate id. - ID *string `json:"id,omitempty"` - // KeyProperties - Properties of the key backing a certificate. - KeyProperties *KeyProperties `json:"key_props,omitempty"` - // SecretProperties - Properties of the secret backing a certificate. - SecretProperties *SecretProperties `json:"secret_props,omitempty"` - // X509CertificateProperties - Properties of the X509 component of a certificate. - X509CertificateProperties *X509CertificateProperties `json:"x509_props,omitempty"` - // LifetimeActions - Actions that will be performed by Key Vault over the lifetime of a certificate. - LifetimeActions *[]LifetimeAction `json:"lifetime_actions,omitempty"` - // IssuerParameters - Parameters for the issuer of the X509 component of a certificate. - IssuerParameters *IssuerParameters `json:"issuer,omitempty"` - // Attributes - The certificate attributes. - Attributes *CertificateAttributes `json:"attributes,omitempty"` -} - -// MarshalJSON is the custom marshaler for CertificatePolicy. -func (cp CertificatePolicy) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cp.KeyProperties != nil { - objectMap["key_props"] = cp.KeyProperties - } - if cp.SecretProperties != nil { - objectMap["secret_props"] = cp.SecretProperties - } - if cp.X509CertificateProperties != nil { - objectMap["x509_props"] = cp.X509CertificateProperties - } - if cp.LifetimeActions != nil { - objectMap["lifetime_actions"] = cp.LifetimeActions - } - if cp.IssuerParameters != nil { - objectMap["issuer"] = cp.IssuerParameters - } - if cp.Attributes != nil { - objectMap["attributes"] = cp.Attributes - } - return json.Marshal(objectMap) -} - -// CertificateUpdateParameters the certificate update parameters. -type CertificateUpdateParameters struct { - // CertificatePolicy - The management policy for the certificate. - CertificatePolicy *CertificatePolicy `json:"policy,omitempty"` - // CertificateAttributes - The attributes of the certificate (optional). - CertificateAttributes *CertificateAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for CertificateUpdateParameters. -func (cup CertificateUpdateParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if cup.CertificatePolicy != nil { - objectMap["policy"] = cup.CertificatePolicy - } - if cup.CertificateAttributes != nil { - objectMap["attributes"] = cup.CertificateAttributes - } - if cup.Tags != nil { - objectMap["tags"] = cup.Tags - } - return json.Marshal(objectMap) -} - -// Contact the contact information for the vault certificates. -type Contact struct { - // EmailAddress - Email address. - EmailAddress *string `json:"email,omitempty"` - // Name - Name. - Name *string `json:"name,omitempty"` - // Phone - Phone number. - Phone *string `json:"phone,omitempty"` -} - -// Contacts the contacts for the vault certificates. -type Contacts struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; Identifier for the contacts collection. - ID *string `json:"id,omitempty"` - // ContactList - The contact list for the vault certificates. - ContactList *[]Contact `json:"contacts,omitempty"` -} - -// MarshalJSON is the custom marshaler for Contacts. -func (c Contacts) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if c.ContactList != nil { - objectMap["contacts"] = c.ContactList - } - return json.Marshal(objectMap) -} - -// DeletedCertificateBundle a Deleted Certificate consisting of its previous id, attributes and its tags, -// as well as information on when it will be purged. -type DeletedCertificateBundle struct { - autorest.Response `json:"-"` - // RecoveryID - The url of the recovery object, used to identify and recover the deleted certificate. - RecoveryID *string `json:"recoveryId,omitempty"` - // ScheduledPurgeDate - READ-ONLY; The time when the certificate is scheduled to be purged, in UTC - ScheduledPurgeDate *date.UnixTime `json:"scheduledPurgeDate,omitempty"` - // DeletedDate - READ-ONLY; The time when the certificate was deleted, in UTC - DeletedDate *date.UnixTime `json:"deletedDate,omitempty"` - // ID - READ-ONLY; The certificate id. - ID *string `json:"id,omitempty"` - // Kid - READ-ONLY; The key id. - Kid *string `json:"kid,omitempty"` - // Sid - READ-ONLY; The secret id. - Sid *string `json:"sid,omitempty"` - // X509Thumbprint - READ-ONLY; Thumbprint of the certificate. (a URL-encoded base64 string) - X509Thumbprint *string `json:"x5t,omitempty"` - // Policy - READ-ONLY; The management policy. - Policy *CertificatePolicy `json:"policy,omitempty"` - // Cer - CER contents of x509 certificate. - Cer *[]byte `json:"cer,omitempty"` - // ContentType - The content type of the secret. - ContentType *string `json:"contentType,omitempty"` - // Attributes - The certificate attributes. - Attributes *CertificateAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for DeletedCertificateBundle. -func (dcb DeletedCertificateBundle) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dcb.RecoveryID != nil { - objectMap["recoveryId"] = dcb.RecoveryID - } - if dcb.Cer != nil { - objectMap["cer"] = dcb.Cer - } - if dcb.ContentType != nil { - objectMap["contentType"] = dcb.ContentType - } - if dcb.Attributes != nil { - objectMap["attributes"] = dcb.Attributes - } - if dcb.Tags != nil { - objectMap["tags"] = dcb.Tags - } - return json.Marshal(objectMap) -} - -// DeletedCertificateItem the deleted certificate item containing metadata about the deleted certificate. -type DeletedCertificateItem struct { - // RecoveryID - The url of the recovery object, used to identify and recover the deleted certificate. - RecoveryID *string `json:"recoveryId,omitempty"` - // ScheduledPurgeDate - READ-ONLY; The time when the certificate is scheduled to be purged, in UTC - ScheduledPurgeDate *date.UnixTime `json:"scheduledPurgeDate,omitempty"` - // DeletedDate - READ-ONLY; The time when the certificate was deleted, in UTC - DeletedDate *date.UnixTime `json:"deletedDate,omitempty"` - // ID - Certificate identifier. - ID *string `json:"id,omitempty"` - // Attributes - The certificate management attributes. - Attributes *CertificateAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // X509Thumbprint - Thumbprint of the certificate. (a URL-encoded base64 string) - X509Thumbprint *string `json:"x5t,omitempty"` -} - -// MarshalJSON is the custom marshaler for DeletedCertificateItem. -func (dci DeletedCertificateItem) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dci.RecoveryID != nil { - objectMap["recoveryId"] = dci.RecoveryID - } - if dci.ID != nil { - objectMap["id"] = dci.ID - } - if dci.Attributes != nil { - objectMap["attributes"] = dci.Attributes - } - if dci.Tags != nil { - objectMap["tags"] = dci.Tags - } - if dci.X509Thumbprint != nil { - objectMap["x5t"] = dci.X509Thumbprint - } - return json.Marshal(objectMap) -} - -// DeletedCertificateListResult a list of certificates that have been deleted in this vault. -type DeletedCertificateListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; A response message containing a list of deleted certificates in the vault along with a link to the next page of deleted certificates - Value *[]DeletedCertificateItem `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of deleted certificates. - NextLink *string `json:"nextLink,omitempty"` -} - -// DeletedCertificateListResultIterator provides access to a complete listing of DeletedCertificateItem -// values. -type DeletedCertificateListResultIterator struct { - i int - page DeletedCertificateListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *DeletedCertificateListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeletedCertificateListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *DeletedCertificateListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter DeletedCertificateListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter DeletedCertificateListResultIterator) Response() DeletedCertificateListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter DeletedCertificateListResultIterator) Value() DeletedCertificateItem { - if !iter.page.NotDone() { - return DeletedCertificateItem{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the DeletedCertificateListResultIterator type. -func NewDeletedCertificateListResultIterator(page DeletedCertificateListResultPage) DeletedCertificateListResultIterator { - return DeletedCertificateListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (dclr DeletedCertificateListResult) IsEmpty() bool { - return dclr.Value == nil || len(*dclr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (dclr DeletedCertificateListResult) hasNextLink() bool { - return dclr.NextLink != nil && len(*dclr.NextLink) != 0 -} - -// deletedCertificateListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (dclr DeletedCertificateListResult) deletedCertificateListResultPreparer(ctx context.Context) (*http.Request, error) { - if !dclr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(dclr.NextLink))) -} - -// DeletedCertificateListResultPage contains a page of DeletedCertificateItem values. -type DeletedCertificateListResultPage struct { - fn func(context.Context, DeletedCertificateListResult) (DeletedCertificateListResult, error) - dclr DeletedCertificateListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *DeletedCertificateListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeletedCertificateListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.dclr) - if err != nil { - return err - } - page.dclr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *DeletedCertificateListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page DeletedCertificateListResultPage) NotDone() bool { - return !page.dclr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page DeletedCertificateListResultPage) Response() DeletedCertificateListResult { - return page.dclr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page DeletedCertificateListResultPage) Values() []DeletedCertificateItem { - if page.dclr.IsEmpty() { - return nil - } - return *page.dclr.Value -} - -// Creates a new instance of the DeletedCertificateListResultPage type. -func NewDeletedCertificateListResultPage(cur DeletedCertificateListResult, getNextPage func(context.Context, DeletedCertificateListResult) (DeletedCertificateListResult, error)) DeletedCertificateListResultPage { - return DeletedCertificateListResultPage{ - fn: getNextPage, - dclr: cur, - } -} - -// DeletedKeyBundle a DeletedKeyBundle consisting of a WebKey plus its Attributes and deletion info -type DeletedKeyBundle struct { - autorest.Response `json:"-"` - // RecoveryID - The url of the recovery object, used to identify and recover the deleted key. - RecoveryID *string `json:"recoveryId,omitempty"` - // ScheduledPurgeDate - READ-ONLY; The time when the key is scheduled to be purged, in UTC - ScheduledPurgeDate *date.UnixTime `json:"scheduledPurgeDate,omitempty"` - // DeletedDate - READ-ONLY; The time when the key was deleted, in UTC - DeletedDate *date.UnixTime `json:"deletedDate,omitempty"` - // Key - The Json web key. - Key *JSONWebKey `json:"key,omitempty"` - // Attributes - The key management attributes. - Attributes *KeyAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // Managed - READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. - Managed *bool `json:"managed,omitempty"` -} - -// MarshalJSON is the custom marshaler for DeletedKeyBundle. -func (dkb DeletedKeyBundle) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dkb.RecoveryID != nil { - objectMap["recoveryId"] = dkb.RecoveryID - } - if dkb.Key != nil { - objectMap["key"] = dkb.Key - } - if dkb.Attributes != nil { - objectMap["attributes"] = dkb.Attributes - } - if dkb.Tags != nil { - objectMap["tags"] = dkb.Tags - } - return json.Marshal(objectMap) -} - -// DeletedKeyItem the deleted key item containing the deleted key metadata and information about deletion. -type DeletedKeyItem struct { - // RecoveryID - The url of the recovery object, used to identify and recover the deleted key. - RecoveryID *string `json:"recoveryId,omitempty"` - // ScheduledPurgeDate - READ-ONLY; The time when the key is scheduled to be purged, in UTC - ScheduledPurgeDate *date.UnixTime `json:"scheduledPurgeDate,omitempty"` - // DeletedDate - READ-ONLY; The time when the key was deleted, in UTC - DeletedDate *date.UnixTime `json:"deletedDate,omitempty"` - // Kid - Key identifier. - Kid *string `json:"kid,omitempty"` - // Attributes - The key management attributes. - Attributes *KeyAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // Managed - READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. - Managed *bool `json:"managed,omitempty"` -} - -// MarshalJSON is the custom marshaler for DeletedKeyItem. -func (dki DeletedKeyItem) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dki.RecoveryID != nil { - objectMap["recoveryId"] = dki.RecoveryID - } - if dki.Kid != nil { - objectMap["kid"] = dki.Kid - } - if dki.Attributes != nil { - objectMap["attributes"] = dki.Attributes - } - if dki.Tags != nil { - objectMap["tags"] = dki.Tags - } - return json.Marshal(objectMap) -} - -// DeletedKeyListResult a list of keys that have been deleted in this vault. -type DeletedKeyListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; A response message containing a list of deleted keys in the vault along with a link to the next page of deleted keys - Value *[]DeletedKeyItem `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of deleted keys. - NextLink *string `json:"nextLink,omitempty"` -} - -// DeletedKeyListResultIterator provides access to a complete listing of DeletedKeyItem values. -type DeletedKeyListResultIterator struct { - i int - page DeletedKeyListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *DeletedKeyListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeletedKeyListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *DeletedKeyListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter DeletedKeyListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter DeletedKeyListResultIterator) Response() DeletedKeyListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter DeletedKeyListResultIterator) Value() DeletedKeyItem { - if !iter.page.NotDone() { - return DeletedKeyItem{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the DeletedKeyListResultIterator type. -func NewDeletedKeyListResultIterator(page DeletedKeyListResultPage) DeletedKeyListResultIterator { - return DeletedKeyListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (dklr DeletedKeyListResult) IsEmpty() bool { - return dklr.Value == nil || len(*dklr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (dklr DeletedKeyListResult) hasNextLink() bool { - return dklr.NextLink != nil && len(*dklr.NextLink) != 0 -} - -// deletedKeyListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (dklr DeletedKeyListResult) deletedKeyListResultPreparer(ctx context.Context) (*http.Request, error) { - if !dklr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(dklr.NextLink))) -} - -// DeletedKeyListResultPage contains a page of DeletedKeyItem values. -type DeletedKeyListResultPage struct { - fn func(context.Context, DeletedKeyListResult) (DeletedKeyListResult, error) - dklr DeletedKeyListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *DeletedKeyListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeletedKeyListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.dklr) - if err != nil { - return err - } - page.dklr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *DeletedKeyListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page DeletedKeyListResultPage) NotDone() bool { - return !page.dklr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page DeletedKeyListResultPage) Response() DeletedKeyListResult { - return page.dklr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page DeletedKeyListResultPage) Values() []DeletedKeyItem { - if page.dklr.IsEmpty() { - return nil - } - return *page.dklr.Value -} - -// Creates a new instance of the DeletedKeyListResultPage type. -func NewDeletedKeyListResultPage(cur DeletedKeyListResult, getNextPage func(context.Context, DeletedKeyListResult) (DeletedKeyListResult, error)) DeletedKeyListResultPage { - return DeletedKeyListResultPage{ - fn: getNextPage, - dklr: cur, - } -} - -// DeletedSecretBundle a Deleted Secret consisting of its previous id, attributes and its tags, as well as -// information on when it will be purged. -type DeletedSecretBundle struct { - autorest.Response `json:"-"` - // RecoveryID - The url of the recovery object, used to identify and recover the deleted secret. - RecoveryID *string `json:"recoveryId,omitempty"` - // ScheduledPurgeDate - READ-ONLY; The time when the secret is scheduled to be purged, in UTC - ScheduledPurgeDate *date.UnixTime `json:"scheduledPurgeDate,omitempty"` - // DeletedDate - READ-ONLY; The time when the secret was deleted, in UTC - DeletedDate *date.UnixTime `json:"deletedDate,omitempty"` - // Value - The secret value. - Value *string `json:"value,omitempty"` - // ID - The secret id. - ID *string `json:"id,omitempty"` - // ContentType - The content type of the secret. - ContentType *string `json:"contentType,omitempty"` - // Attributes - The secret management attributes. - Attributes *SecretAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // Kid - READ-ONLY; If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV certificate. - Kid *string `json:"kid,omitempty"` - // Managed - READ-ONLY; True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed will be true. - Managed *bool `json:"managed,omitempty"` -} - -// MarshalJSON is the custom marshaler for DeletedSecretBundle. -func (dsb DeletedSecretBundle) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dsb.RecoveryID != nil { - objectMap["recoveryId"] = dsb.RecoveryID - } - if dsb.Value != nil { - objectMap["value"] = dsb.Value - } - if dsb.ID != nil { - objectMap["id"] = dsb.ID - } - if dsb.ContentType != nil { - objectMap["contentType"] = dsb.ContentType - } - if dsb.Attributes != nil { - objectMap["attributes"] = dsb.Attributes - } - if dsb.Tags != nil { - objectMap["tags"] = dsb.Tags - } - return json.Marshal(objectMap) -} - -// DeletedSecretItem the deleted secret item containing metadata about the deleted secret. -type DeletedSecretItem struct { - // RecoveryID - The url of the recovery object, used to identify and recover the deleted secret. - RecoveryID *string `json:"recoveryId,omitempty"` - // ScheduledPurgeDate - READ-ONLY; The time when the secret is scheduled to be purged, in UTC - ScheduledPurgeDate *date.UnixTime `json:"scheduledPurgeDate,omitempty"` - // DeletedDate - READ-ONLY; The time when the secret was deleted, in UTC - DeletedDate *date.UnixTime `json:"deletedDate,omitempty"` - // ID - Secret identifier. - ID *string `json:"id,omitempty"` - // Attributes - The secret management attributes. - Attributes *SecretAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // ContentType - Type of the secret value such as a password. - ContentType *string `json:"contentType,omitempty"` - // Managed - READ-ONLY; True if the secret's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. - Managed *bool `json:"managed,omitempty"` -} - -// MarshalJSON is the custom marshaler for DeletedSecretItem. -func (dsi DeletedSecretItem) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if dsi.RecoveryID != nil { - objectMap["recoveryId"] = dsi.RecoveryID - } - if dsi.ID != nil { - objectMap["id"] = dsi.ID - } - if dsi.Attributes != nil { - objectMap["attributes"] = dsi.Attributes - } - if dsi.Tags != nil { - objectMap["tags"] = dsi.Tags - } - if dsi.ContentType != nil { - objectMap["contentType"] = dsi.ContentType - } - return json.Marshal(objectMap) -} - -// DeletedSecretListResult the deleted secret list result -type DeletedSecretListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; A response message containing a list of the deleted secrets in the vault along with a link to the next page of deleted secrets - Value *[]DeletedSecretItem `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of deleted secrets. - NextLink *string `json:"nextLink,omitempty"` -} - -// DeletedSecretListResultIterator provides access to a complete listing of DeletedSecretItem values. -type DeletedSecretListResultIterator struct { - i int - page DeletedSecretListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *DeletedSecretListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeletedSecretListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *DeletedSecretListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter DeletedSecretListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter DeletedSecretListResultIterator) Response() DeletedSecretListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter DeletedSecretListResultIterator) Value() DeletedSecretItem { - if !iter.page.NotDone() { - return DeletedSecretItem{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the DeletedSecretListResultIterator type. -func NewDeletedSecretListResultIterator(page DeletedSecretListResultPage) DeletedSecretListResultIterator { - return DeletedSecretListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (dslr DeletedSecretListResult) IsEmpty() bool { - return dslr.Value == nil || len(*dslr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (dslr DeletedSecretListResult) hasNextLink() bool { - return dslr.NextLink != nil && len(*dslr.NextLink) != 0 -} - -// deletedSecretListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (dslr DeletedSecretListResult) deletedSecretListResultPreparer(ctx context.Context) (*http.Request, error) { - if !dslr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(dslr.NextLink))) -} - -// DeletedSecretListResultPage contains a page of DeletedSecretItem values. -type DeletedSecretListResultPage struct { - fn func(context.Context, DeletedSecretListResult) (DeletedSecretListResult, error) - dslr DeletedSecretListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *DeletedSecretListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/DeletedSecretListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.dslr) - if err != nil { - return err - } - page.dslr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *DeletedSecretListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page DeletedSecretListResultPage) NotDone() bool { - return !page.dslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page DeletedSecretListResultPage) Response() DeletedSecretListResult { - return page.dslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page DeletedSecretListResultPage) Values() []DeletedSecretItem { - if page.dslr.IsEmpty() { - return nil - } - return *page.dslr.Value -} - -// Creates a new instance of the DeletedSecretListResultPage type. -func NewDeletedSecretListResultPage(cur DeletedSecretListResult, getNextPage func(context.Context, DeletedSecretListResult) (DeletedSecretListResult, error)) DeletedSecretListResultPage { - return DeletedSecretListResultPage{ - fn: getNextPage, - dslr: cur, - } -} - -// Error the key vault server error. -type Error struct { - // Code - READ-ONLY; The error code. - Code *string `json:"code,omitempty"` - // Message - READ-ONLY; The error message. - Message *string `json:"message,omitempty"` - // InnerError - READ-ONLY - InnerError *Error `json:"innererror,omitempty"` -} - -// ErrorType the key vault error exception. -type ErrorType struct { - // Error - READ-ONLY - Error *Error `json:"error,omitempty"` -} - -// IssuerAttributes the attributes of an issuer managed by the Key Vault service. -type IssuerAttributes struct { - // Enabled - Determines whether the issuer is enabled. - Enabled *bool `json:"enabled,omitempty"` - // Created - READ-ONLY; Creation time in UTC. - Created *date.UnixTime `json:"created,omitempty"` - // Updated - READ-ONLY; Last updated time in UTC. - Updated *date.UnixTime `json:"updated,omitempty"` -} - -// MarshalJSON is the custom marshaler for IssuerAttributes. -func (ia IssuerAttributes) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ia.Enabled != nil { - objectMap["enabled"] = ia.Enabled - } - return json.Marshal(objectMap) -} - -// IssuerBundle the issuer for Key Vault certificate. -type IssuerBundle struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; Identifier for the issuer object. - ID *string `json:"id,omitempty"` - // Provider - The issuer provider. - Provider *string `json:"provider,omitempty"` - // Credentials - The credentials to be used for the issuer. - Credentials *IssuerCredentials `json:"credentials,omitempty"` - // OrganizationDetails - Details of the organization as provided to the issuer. - OrganizationDetails *OrganizationDetails `json:"org_details,omitempty"` - // Attributes - Attributes of the issuer object. - Attributes *IssuerAttributes `json:"attributes,omitempty"` -} - -// MarshalJSON is the custom marshaler for IssuerBundle. -func (ib IssuerBundle) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ib.Provider != nil { - objectMap["provider"] = ib.Provider - } - if ib.Credentials != nil { - objectMap["credentials"] = ib.Credentials - } - if ib.OrganizationDetails != nil { - objectMap["org_details"] = ib.OrganizationDetails - } - if ib.Attributes != nil { - objectMap["attributes"] = ib.Attributes - } - return json.Marshal(objectMap) -} - -// IssuerCredentials the credentials to be used for the certificate issuer. -type IssuerCredentials struct { - // AccountID - The user name/account name/account id. - AccountID *string `json:"account_id,omitempty"` - // Password - The password/secret/account key. - Password *string `json:"pwd,omitempty"` -} - -// IssuerParameters parameters for the issuer of the X509 component of a certificate. -type IssuerParameters struct { - // Name - Name of the referenced issuer object or reserved names; for example, 'Self' or 'Unknown'. - Name *string `json:"name,omitempty"` - // CertificateType - Type of certificate to be requested from the issuer provider. - CertificateType *string `json:"cty,omitempty"` -} - -// JSONWebKey as of http://tools.ietf.org/html/draft-ietf-jose-json-web-key-18 -type JSONWebKey struct { - // Kid - Key identifier. - Kid *string `json:"kid,omitempty"` - // Kty - JsonWebKey key type (kty). Possible values include: 'EC', 'ECHSM', 'RSA', 'RSAHSM', 'Oct' - Kty JSONWebKeyType `json:"kty,omitempty"` - KeyOps *[]string `json:"key_ops,omitempty"` - // N - RSA modulus. (a URL-encoded base64 string) - N *string `json:"n,omitempty"` - // E - RSA public exponent. (a URL-encoded base64 string) - E *string `json:"e,omitempty"` - // D - RSA private exponent, or the D component of an EC private key. (a URL-encoded base64 string) - D *string `json:"d,omitempty"` - // DP - RSA private key parameter. (a URL-encoded base64 string) - DP *string `json:"dp,omitempty"` - // DQ - RSA private key parameter. (a URL-encoded base64 string) - DQ *string `json:"dq,omitempty"` - // QI - RSA private key parameter. (a URL-encoded base64 string) - QI *string `json:"qi,omitempty"` - // P - RSA secret prime. (a URL-encoded base64 string) - P *string `json:"p,omitempty"` - // Q - RSA secret prime, with p < q. (a URL-encoded base64 string) - Q *string `json:"q,omitempty"` - // K - Symmetric key. (a URL-encoded base64 string) - K *string `json:"k,omitempty"` - // T - HSM Token, used with 'Bring Your Own Key'. (a URL-encoded base64 string) - T *string `json:"key_hsm,omitempty"` - // Crv - Elliptic curve name. For valid values, see JsonWebKeyCurveName. Possible values include: 'P256', 'P384', 'P521', 'SECP256K1' - Crv JSONWebKeyCurveName `json:"crv,omitempty"` - // X - X component of an EC public key. (a URL-encoded base64 string) - X *string `json:"x,omitempty"` - // Y - Y component of an EC public key. (a URL-encoded base64 string) - Y *string `json:"y,omitempty"` -} - -// KeyAttributes the attributes of a key managed by the key vault service. -type KeyAttributes struct { - // RecoveryLevel - READ-ONLY; Reflects the deletion recovery level currently in effect for keys in the current vault. If it contains 'Purgeable' the key can be permanently deleted by a privileged user; otherwise, only the system can purge the key, at the end of the retention interval. Possible values include: 'Purgeable', 'RecoverablePurgeable', 'Recoverable', 'RecoverableProtectedSubscription' - RecoveryLevel DeletionRecoveryLevel `json:"recoveryLevel,omitempty"` - // Enabled - Determines whether the object is enabled. - Enabled *bool `json:"enabled,omitempty"` - // NotBefore - Not before date in UTC. - NotBefore *date.UnixTime `json:"nbf,omitempty"` - // Expires - Expiry date in UTC. - Expires *date.UnixTime `json:"exp,omitempty"` - // Created - READ-ONLY; Creation time in UTC. - Created *date.UnixTime `json:"created,omitempty"` - // Updated - READ-ONLY; Last updated time in UTC. - Updated *date.UnixTime `json:"updated,omitempty"` -} - -// MarshalJSON is the custom marshaler for KeyAttributes. -func (ka KeyAttributes) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ka.Enabled != nil { - objectMap["enabled"] = ka.Enabled - } - if ka.NotBefore != nil { - objectMap["nbf"] = ka.NotBefore - } - if ka.Expires != nil { - objectMap["exp"] = ka.Expires - } - return json.Marshal(objectMap) -} - -// KeyBundle a KeyBundle consisting of a WebKey plus its attributes. -type KeyBundle struct { - autorest.Response `json:"-"` - // Key - The Json web key. - Key *JSONWebKey `json:"key,omitempty"` - // Attributes - The key management attributes. - Attributes *KeyAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // Managed - READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. - Managed *bool `json:"managed,omitempty"` -} - -// MarshalJSON is the custom marshaler for KeyBundle. -func (kb KeyBundle) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if kb.Key != nil { - objectMap["key"] = kb.Key - } - if kb.Attributes != nil { - objectMap["attributes"] = kb.Attributes - } - if kb.Tags != nil { - objectMap["tags"] = kb.Tags - } - return json.Marshal(objectMap) -} - -// KeyCreateParameters the key create parameters. -type KeyCreateParameters struct { - // Kty - The type of key to create. For valid values, see JsonWebKeyType. Possible values include: 'EC', 'ECHSM', 'RSA', 'RSAHSM', 'Oct' - Kty JSONWebKeyType `json:"kty,omitempty"` - // KeySize - The key size in bits. For example: 2048, 3072, or 4096 for RSA. - KeySize *int32 `json:"key_size,omitempty"` - KeyOps *[]JSONWebKeyOperation `json:"key_ops,omitempty"` - KeyAttributes *KeyAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // Curve - Elliptic curve name. For valid values, see JsonWebKeyCurveName. Possible values include: 'P256', 'P384', 'P521', 'SECP256K1' - Curve JSONWebKeyCurveName `json:"crv,omitempty"` -} - -// MarshalJSON is the custom marshaler for KeyCreateParameters. -func (kcp KeyCreateParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if kcp.Kty != "" { - objectMap["kty"] = kcp.Kty - } - if kcp.KeySize != nil { - objectMap["key_size"] = kcp.KeySize - } - if kcp.KeyOps != nil { - objectMap["key_ops"] = kcp.KeyOps - } - if kcp.KeyAttributes != nil { - objectMap["attributes"] = kcp.KeyAttributes - } - if kcp.Tags != nil { - objectMap["tags"] = kcp.Tags - } - if kcp.Curve != "" { - objectMap["crv"] = kcp.Curve - } - return json.Marshal(objectMap) -} - -// KeyImportParameters the key import parameters. -type KeyImportParameters struct { - // Hsm - Whether to import as a hardware key (HSM) or software key. - Hsm *bool `json:"Hsm,omitempty"` - // Key - The Json web key - Key *JSONWebKey `json:"key,omitempty"` - // KeyAttributes - The key management attributes. - KeyAttributes *KeyAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for KeyImportParameters. -func (kip KeyImportParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if kip.Hsm != nil { - objectMap["Hsm"] = kip.Hsm - } - if kip.Key != nil { - objectMap["key"] = kip.Key - } - if kip.KeyAttributes != nil { - objectMap["attributes"] = kip.KeyAttributes - } - if kip.Tags != nil { - objectMap["tags"] = kip.Tags - } - return json.Marshal(objectMap) -} - -// KeyItem the key item containing key metadata. -type KeyItem struct { - // Kid - Key identifier. - Kid *string `json:"kid,omitempty"` - // Attributes - The key management attributes. - Attributes *KeyAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // Managed - READ-ONLY; True if the key's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. - Managed *bool `json:"managed,omitempty"` -} - -// MarshalJSON is the custom marshaler for KeyItem. -func (ki KeyItem) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ki.Kid != nil { - objectMap["kid"] = ki.Kid - } - if ki.Attributes != nil { - objectMap["attributes"] = ki.Attributes - } - if ki.Tags != nil { - objectMap["tags"] = ki.Tags - } - return json.Marshal(objectMap) -} - -// KeyListResult the key list result. -type KeyListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; A response message containing a list of keys in the key vault along with a link to the next page of keys. - Value *[]KeyItem `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of keys. - NextLink *string `json:"nextLink,omitempty"` -} - -// KeyListResultIterator provides access to a complete listing of KeyItem values. -type KeyListResultIterator struct { - i int - page KeyListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *KeyListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/KeyListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *KeyListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter KeyListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter KeyListResultIterator) Response() KeyListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter KeyListResultIterator) Value() KeyItem { - if !iter.page.NotDone() { - return KeyItem{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the KeyListResultIterator type. -func NewKeyListResultIterator(page KeyListResultPage) KeyListResultIterator { - return KeyListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (klr KeyListResult) IsEmpty() bool { - return klr.Value == nil || len(*klr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (klr KeyListResult) hasNextLink() bool { - return klr.NextLink != nil && len(*klr.NextLink) != 0 -} - -// keyListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (klr KeyListResult) keyListResultPreparer(ctx context.Context) (*http.Request, error) { - if !klr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(klr.NextLink))) -} - -// KeyListResultPage contains a page of KeyItem values. -type KeyListResultPage struct { - fn func(context.Context, KeyListResult) (KeyListResult, error) - klr KeyListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *KeyListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/KeyListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.klr) - if err != nil { - return err - } - page.klr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *KeyListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page KeyListResultPage) NotDone() bool { - return !page.klr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page KeyListResultPage) Response() KeyListResult { - return page.klr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page KeyListResultPage) Values() []KeyItem { - if page.klr.IsEmpty() { - return nil - } - return *page.klr.Value -} - -// Creates a new instance of the KeyListResultPage type. -func NewKeyListResultPage(cur KeyListResult, getNextPage func(context.Context, KeyListResult) (KeyListResult, error)) KeyListResultPage { - return KeyListResultPage{ - fn: getNextPage, - klr: cur, - } -} - -// KeyOperationResult the key operation result. -type KeyOperationResult struct { - autorest.Response `json:"-"` - // Kid - READ-ONLY; Key identifier - Kid *string `json:"kid,omitempty"` - // Result - READ-ONLY; a URL-encoded base64 string - Result *string `json:"value,omitempty"` -} - -// KeyOperationsParameters the key operations parameters. -type KeyOperationsParameters struct { - // Algorithm - algorithm identifier. Possible values include: 'RSAOAEP', 'RSAOAEP256', 'RSA15' - Algorithm JSONWebKeyEncryptionAlgorithm `json:"alg,omitempty"` - // Value - a URL-encoded base64 string - Value *string `json:"value,omitempty"` -} - -// KeyProperties properties of the key pair backing a certificate. -type KeyProperties struct { - // Exportable - Indicates if the private key can be exported. - Exportable *bool `json:"exportable,omitempty"` - // KeyType - The key type. - KeyType *string `json:"kty,omitempty"` - // KeySize - The key size in bits. For example: 2048, 3072, or 4096 for RSA. - KeySize *int32 `json:"key_size,omitempty"` - // ReuseKey - Indicates if the same key pair will be used on certificate renewal. - ReuseKey *bool `json:"reuse_key,omitempty"` -} - -// KeyRestoreParameters the key restore parameters. -type KeyRestoreParameters struct { - // KeyBundleBackup - The backup blob associated with a key bundle. (a URL-encoded base64 string) - KeyBundleBackup *string `json:"value,omitempty"` -} - -// KeySignParameters the key operations parameters. -type KeySignParameters struct { - // Algorithm - The signing/verification algorithm identifier. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible values include: 'PS256', 'PS384', 'PS512', 'RS256', 'RS384', 'RS512', 'RSNULL', 'ES256', 'ES384', 'ES512', 'ECDSA256' - Algorithm JSONWebKeySignatureAlgorithm `json:"alg,omitempty"` - // Value - a URL-encoded base64 string - Value *string `json:"value,omitempty"` -} - -// KeyUpdateParameters the key update parameters. -type KeyUpdateParameters struct { - // KeyOps - Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. - KeyOps *[]JSONWebKeyOperation `json:"key_ops,omitempty"` - KeyAttributes *KeyAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for KeyUpdateParameters. -func (kup KeyUpdateParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if kup.KeyOps != nil { - objectMap["key_ops"] = kup.KeyOps - } - if kup.KeyAttributes != nil { - objectMap["attributes"] = kup.KeyAttributes - } - if kup.Tags != nil { - objectMap["tags"] = kup.Tags - } - return json.Marshal(objectMap) -} - -// KeyVerifyParameters the key verify parameters. -type KeyVerifyParameters struct { - // Algorithm - The signing/verification algorithm. For more information on possible algorithm types, see JsonWebKeySignatureAlgorithm. Possible values include: 'PS256', 'PS384', 'PS512', 'RS256', 'RS384', 'RS512', 'RSNULL', 'ES256', 'ES384', 'ES512', 'ECDSA256' - Algorithm JSONWebKeySignatureAlgorithm `json:"alg,omitempty"` - // Digest - The digest used for signing. (a URL-encoded base64 string) - Digest *string `json:"digest,omitempty"` - // Signature - The signature to be verified. (a URL-encoded base64 string) - Signature *string `json:"value,omitempty"` -} - -// KeyVerifyResult the key verify result. -type KeyVerifyResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; True if the signature is verified, otherwise false. - Value *bool `json:"value,omitempty"` -} - -// LifetimeAction action and its trigger that will be performed by Key Vault over the lifetime of a -// certificate. -type LifetimeAction struct { - // Trigger - The condition that will execute the action. - Trigger *Trigger `json:"trigger,omitempty"` - // Action - The action that will be executed. - Action *Action `json:"action,omitempty"` -} - -// OrganizationDetails details of the organization of the certificate issuer. -type OrganizationDetails struct { - // ID - Id of the organization. - ID *string `json:"id,omitempty"` - // AdminDetails - Details of the organization administrator. - AdminDetails *[]AdministratorDetails `json:"admin_details,omitempty"` -} - -// PendingCertificateSigningRequestResult the pending certificate signing request result. -type PendingCertificateSigningRequestResult struct { - // Value - READ-ONLY; The pending certificate signing request as Base64 encoded string. - Value *string `json:"value,omitempty"` -} - -// SasDefinitionAttributes the SAS definition management attributes. -type SasDefinitionAttributes struct { - // Enabled - the enabled state of the object. - Enabled *bool `json:"enabled,omitempty"` - // Created - READ-ONLY; Creation time in UTC. - Created *date.UnixTime `json:"created,omitempty"` - // Updated - READ-ONLY; Last updated time in UTC. - Updated *date.UnixTime `json:"updated,omitempty"` -} - -// MarshalJSON is the custom marshaler for SasDefinitionAttributes. -func (sda SasDefinitionAttributes) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sda.Enabled != nil { - objectMap["enabled"] = sda.Enabled - } - return json.Marshal(objectMap) -} - -// SasDefinitionBundle a SAS definition bundle consists of key vault SAS definition details plus its -// attributes. -type SasDefinitionBundle struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; The SAS definition id. - ID *string `json:"id,omitempty"` - // SecretID - READ-ONLY; Storage account SAS definition secret id. - SecretID *string `json:"sid,omitempty"` - // Parameters - READ-ONLY; The SAS definition metadata in the form of key-value pairs. - Parameters map[string]*string `json:"parameters"` - // Attributes - READ-ONLY; The SAS definition attributes. - Attributes *SasDefinitionAttributes `json:"attributes,omitempty"` - // Tags - READ-ONLY; Application specific metadata in the form of key-value pairs - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for SasDefinitionBundle. -func (sdb SasDefinitionBundle) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// SasDefinitionCreateParameters the SAS definition create parameters. -type SasDefinitionCreateParameters struct { - // Parameters - Sas definition creation metadata in the form of key-value pairs. - Parameters map[string]*string `json:"parameters"` - // SasDefinitionAttributes - The attributes of the SAS definition. - SasDefinitionAttributes *SasDefinitionAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for SasDefinitionCreateParameters. -func (sdcp SasDefinitionCreateParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sdcp.Parameters != nil { - objectMap["parameters"] = sdcp.Parameters - } - if sdcp.SasDefinitionAttributes != nil { - objectMap["attributes"] = sdcp.SasDefinitionAttributes - } - if sdcp.Tags != nil { - objectMap["tags"] = sdcp.Tags - } - return json.Marshal(objectMap) -} - -// SasDefinitionItem the SAS definition item containing storage SAS definition metadata. -type SasDefinitionItem struct { - // ID - READ-ONLY; The storage SAS identifier. - ID *string `json:"id,omitempty"` - // SecretID - READ-ONLY; The storage account SAS definition secret id. - SecretID *string `json:"sid,omitempty"` - // Attributes - READ-ONLY; The SAS definition management attributes. - Attributes *SasDefinitionAttributes `json:"attributes,omitempty"` - // Tags - READ-ONLY; Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for SasDefinitionItem. -func (sdi SasDefinitionItem) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// SasDefinitionListResult the storage account SAS definition list result. -type SasDefinitionListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; A response message containing a list of SAS definitions along with a link to the next page of SAS definitions. - Value *[]SasDefinitionItem `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of SAS definitions. - NextLink *string `json:"nextLink,omitempty"` -} - -// SasDefinitionListResultIterator provides access to a complete listing of SasDefinitionItem values. -type SasDefinitionListResultIterator struct { - i int - page SasDefinitionListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *SasDefinitionListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SasDefinitionListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SasDefinitionListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SasDefinitionListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter SasDefinitionListResultIterator) Response() SasDefinitionListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter SasDefinitionListResultIterator) Value() SasDefinitionItem { - if !iter.page.NotDone() { - return SasDefinitionItem{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SasDefinitionListResultIterator type. -func NewSasDefinitionListResultIterator(page SasDefinitionListResultPage) SasDefinitionListResultIterator { - return SasDefinitionListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (sdlr SasDefinitionListResult) IsEmpty() bool { - return sdlr.Value == nil || len(*sdlr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (sdlr SasDefinitionListResult) hasNextLink() bool { - return sdlr.NextLink != nil && len(*sdlr.NextLink) != 0 -} - -// sasDefinitionListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (sdlr SasDefinitionListResult) sasDefinitionListResultPreparer(ctx context.Context) (*http.Request, error) { - if !sdlr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(sdlr.NextLink))) -} - -// SasDefinitionListResultPage contains a page of SasDefinitionItem values. -type SasDefinitionListResultPage struct { - fn func(context.Context, SasDefinitionListResult) (SasDefinitionListResult, error) - sdlr SasDefinitionListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SasDefinitionListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SasDefinitionListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.sdlr) - if err != nil { - return err - } - page.sdlr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SasDefinitionListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SasDefinitionListResultPage) NotDone() bool { - return !page.sdlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SasDefinitionListResultPage) Response() SasDefinitionListResult { - return page.sdlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SasDefinitionListResultPage) Values() []SasDefinitionItem { - if page.sdlr.IsEmpty() { - return nil - } - return *page.sdlr.Value -} - -// Creates a new instance of the SasDefinitionListResultPage type. -func NewSasDefinitionListResultPage(cur SasDefinitionListResult, getNextPage func(context.Context, SasDefinitionListResult) (SasDefinitionListResult, error)) SasDefinitionListResultPage { - return SasDefinitionListResultPage{ - fn: getNextPage, - sdlr: cur, - } -} - -// SasDefinitionUpdateParameters the SAS definition update parameters. -type SasDefinitionUpdateParameters struct { - // Parameters - Sas definition update metadata in the form of key-value pairs. - Parameters map[string]*string `json:"parameters"` - // SasDefinitionAttributes - The attributes of the SAS definition. - SasDefinitionAttributes *SasDefinitionAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for SasDefinitionUpdateParameters. -func (sdup SasDefinitionUpdateParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sdup.Parameters != nil { - objectMap["parameters"] = sdup.Parameters - } - if sdup.SasDefinitionAttributes != nil { - objectMap["attributes"] = sdup.SasDefinitionAttributes - } - if sdup.Tags != nil { - objectMap["tags"] = sdup.Tags - } - return json.Marshal(objectMap) -} - -// SecretAttributes the secret management attributes. -type SecretAttributes struct { - // RecoveryLevel - READ-ONLY; Reflects the deletion recovery level currently in effect for secrets in the current vault. If it contains 'Purgeable', the secret can be permanently deleted by a privileged user; otherwise, only the system can purge the secret, at the end of the retention interval. Possible values include: 'Purgeable', 'RecoverablePurgeable', 'Recoverable', 'RecoverableProtectedSubscription' - RecoveryLevel DeletionRecoveryLevel `json:"recoveryLevel,omitempty"` - // Enabled - Determines whether the object is enabled. - Enabled *bool `json:"enabled,omitempty"` - // NotBefore - Not before date in UTC. - NotBefore *date.UnixTime `json:"nbf,omitempty"` - // Expires - Expiry date in UTC. - Expires *date.UnixTime `json:"exp,omitempty"` - // Created - READ-ONLY; Creation time in UTC. - Created *date.UnixTime `json:"created,omitempty"` - // Updated - READ-ONLY; Last updated time in UTC. - Updated *date.UnixTime `json:"updated,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecretAttributes. -func (sa SecretAttributes) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sa.Enabled != nil { - objectMap["enabled"] = sa.Enabled - } - if sa.NotBefore != nil { - objectMap["nbf"] = sa.NotBefore - } - if sa.Expires != nil { - objectMap["exp"] = sa.Expires - } - return json.Marshal(objectMap) -} - -// SecretBundle a secret consisting of a value, id and its attributes. -type SecretBundle struct { - autorest.Response `json:"-"` - // Value - The secret value. - Value *string `json:"value,omitempty"` - // ID - The secret id. - ID *string `json:"id,omitempty"` - // ContentType - The content type of the secret. - ContentType *string `json:"contentType,omitempty"` - // Attributes - The secret management attributes. - Attributes *SecretAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // Kid - READ-ONLY; If this is a secret backing a KV certificate, then this field specifies the corresponding key backing the KV certificate. - Kid *string `json:"kid,omitempty"` - // Managed - READ-ONLY; True if the secret's lifetime is managed by key vault. If this is a secret backing a certificate, then managed will be true. - Managed *bool `json:"managed,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecretBundle. -func (sb SecretBundle) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sb.Value != nil { - objectMap["value"] = sb.Value - } - if sb.ID != nil { - objectMap["id"] = sb.ID - } - if sb.ContentType != nil { - objectMap["contentType"] = sb.ContentType - } - if sb.Attributes != nil { - objectMap["attributes"] = sb.Attributes - } - if sb.Tags != nil { - objectMap["tags"] = sb.Tags - } - return json.Marshal(objectMap) -} - -// SecretItem the secret item containing secret metadata. -type SecretItem struct { - // ID - Secret identifier. - ID *string `json:"id,omitempty"` - // Attributes - The secret management attributes. - Attributes *SecretAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // ContentType - Type of the secret value such as a password. - ContentType *string `json:"contentType,omitempty"` - // Managed - READ-ONLY; True if the secret's lifetime is managed by key vault. If this is a key backing a certificate, then managed will be true. - Managed *bool `json:"managed,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecretItem. -func (si SecretItem) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if si.ID != nil { - objectMap["id"] = si.ID - } - if si.Attributes != nil { - objectMap["attributes"] = si.Attributes - } - if si.Tags != nil { - objectMap["tags"] = si.Tags - } - if si.ContentType != nil { - objectMap["contentType"] = si.ContentType - } - return json.Marshal(objectMap) -} - -// SecretListResult the secret list result. -type SecretListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; A response message containing a list of secrets in the key vault along with a link to the next page of secrets. - Value *[]SecretItem `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of secrets. - NextLink *string `json:"nextLink,omitempty"` -} - -// SecretListResultIterator provides access to a complete listing of SecretItem values. -type SecretListResultIterator struct { - i int - page SecretListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *SecretListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecretListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *SecretListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter SecretListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter SecretListResultIterator) Response() SecretListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter SecretListResultIterator) Value() SecretItem { - if !iter.page.NotDone() { - return SecretItem{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the SecretListResultIterator type. -func NewSecretListResultIterator(page SecretListResultPage) SecretListResultIterator { - return SecretListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (slr SecretListResult) IsEmpty() bool { - return slr.Value == nil || len(*slr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (slr SecretListResult) hasNextLink() bool { - return slr.NextLink != nil && len(*slr.NextLink) != 0 -} - -// secretListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (slr SecretListResult) secretListResultPreparer(ctx context.Context) (*http.Request, error) { - if !slr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(slr.NextLink))) -} - -// SecretListResultPage contains a page of SecretItem values. -type SecretListResultPage struct { - fn func(context.Context, SecretListResult) (SecretListResult, error) - slr SecretListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *SecretListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/SecretListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.slr) - if err != nil { - return err - } - page.slr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *SecretListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page SecretListResultPage) NotDone() bool { - return !page.slr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page SecretListResultPage) Response() SecretListResult { - return page.slr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page SecretListResultPage) Values() []SecretItem { - if page.slr.IsEmpty() { - return nil - } - return *page.slr.Value -} - -// Creates a new instance of the SecretListResultPage type. -func NewSecretListResultPage(cur SecretListResult, getNextPage func(context.Context, SecretListResult) (SecretListResult, error)) SecretListResultPage { - return SecretListResultPage{ - fn: getNextPage, - slr: cur, - } -} - -// SecretProperties properties of the key backing a certificate. -type SecretProperties struct { - // ContentType - The media type (MIME type). - ContentType *string `json:"contentType,omitempty"` -} - -// SecretRestoreParameters the secret restore parameters. -type SecretRestoreParameters struct { - // SecretBundleBackup - The backup blob associated with a secret bundle. (a URL-encoded base64 string) - SecretBundleBackup *string `json:"value,omitempty"` -} - -// SecretSetParameters the secret set parameters. -type SecretSetParameters struct { - // Value - The value of the secret. - Value *string `json:"value,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` - // ContentType - Type of the secret value such as a password. - ContentType *string `json:"contentType,omitempty"` - // SecretAttributes - The secret management attributes. - SecretAttributes *SecretAttributes `json:"attributes,omitempty"` -} - -// MarshalJSON is the custom marshaler for SecretSetParameters. -func (ssp SecretSetParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if ssp.Value != nil { - objectMap["value"] = ssp.Value - } - if ssp.Tags != nil { - objectMap["tags"] = ssp.Tags - } - if ssp.ContentType != nil { - objectMap["contentType"] = ssp.ContentType - } - if ssp.SecretAttributes != nil { - objectMap["attributes"] = ssp.SecretAttributes - } - return json.Marshal(objectMap) -} - -// SecretUpdateParameters the secret update parameters. -type SecretUpdateParameters struct { - // ContentType - Type of the secret value such as a password. - ContentType *string `json:"contentType,omitempty"` - // SecretAttributes - The secret management attributes. - SecretAttributes *SecretAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for SecretUpdateParameters. -func (sup SecretUpdateParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sup.ContentType != nil { - objectMap["contentType"] = sup.ContentType - } - if sup.SecretAttributes != nil { - objectMap["attributes"] = sup.SecretAttributes - } - if sup.Tags != nil { - objectMap["tags"] = sup.Tags - } - return json.Marshal(objectMap) -} - -// StorageAccountAttributes the storage account management attributes. -type StorageAccountAttributes struct { - // Enabled - the enabled state of the object. - Enabled *bool `json:"enabled,omitempty"` - // Created - READ-ONLY; Creation time in UTC. - Created *date.UnixTime `json:"created,omitempty"` - // Updated - READ-ONLY; Last updated time in UTC. - Updated *date.UnixTime `json:"updated,omitempty"` -} - -// MarshalJSON is the custom marshaler for StorageAccountAttributes. -func (saa StorageAccountAttributes) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if saa.Enabled != nil { - objectMap["enabled"] = saa.Enabled - } - return json.Marshal(objectMap) -} - -// StorageAccountCreateParameters the storage account create parameters. -type StorageAccountCreateParameters struct { - // ResourceID - Storage account resource id. - ResourceID *string `json:"resourceId,omitempty"` - // ActiveKeyName - Current active storage account key name. - ActiveKeyName *string `json:"activeKeyName,omitempty"` - // AutoRegenerateKey - whether keyvault should manage the storage account for the user. - AutoRegenerateKey *bool `json:"autoRegenerateKey,omitempty"` - // RegenerationPeriod - The key regeneration time duration specified in ISO-8601 format. - RegenerationPeriod *string `json:"regenerationPeriod,omitempty"` - // StorageAccountAttributes - The attributes of the storage account. - StorageAccountAttributes *StorageAccountAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for StorageAccountCreateParameters. -func (sacp StorageAccountCreateParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if sacp.ResourceID != nil { - objectMap["resourceId"] = sacp.ResourceID - } - if sacp.ActiveKeyName != nil { - objectMap["activeKeyName"] = sacp.ActiveKeyName - } - if sacp.AutoRegenerateKey != nil { - objectMap["autoRegenerateKey"] = sacp.AutoRegenerateKey - } - if sacp.RegenerationPeriod != nil { - objectMap["regenerationPeriod"] = sacp.RegenerationPeriod - } - if sacp.StorageAccountAttributes != nil { - objectMap["attributes"] = sacp.StorageAccountAttributes - } - if sacp.Tags != nil { - objectMap["tags"] = sacp.Tags - } - return json.Marshal(objectMap) -} - -// StorageAccountItem the storage account item containing storage account metadata. -type StorageAccountItem struct { - // ID - READ-ONLY; Storage identifier. - ID *string `json:"id,omitempty"` - // ResourceID - READ-ONLY; Storage account resource Id. - ResourceID *string `json:"resourceId,omitempty"` - // Attributes - READ-ONLY; The storage account management attributes. - Attributes *StorageAccountAttributes `json:"attributes,omitempty"` - // Tags - READ-ONLY; Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for StorageAccountItem. -func (sai StorageAccountItem) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// StorageAccountRegenerteKeyParameters the storage account key regenerate parameters. -type StorageAccountRegenerteKeyParameters struct { - // KeyName - The storage account key name. - KeyName *string `json:"keyName,omitempty"` -} - -// StorageAccountUpdateParameters the storage account update parameters. -type StorageAccountUpdateParameters struct { - // ActiveKeyName - The current active storage account key name. - ActiveKeyName *string `json:"activeKeyName,omitempty"` - // AutoRegenerateKey - whether keyvault should manage the storage account for the user. - AutoRegenerateKey *bool `json:"autoRegenerateKey,omitempty"` - // RegenerationPeriod - The key regeneration time duration specified in ISO-8601 format. - RegenerationPeriod *string `json:"regenerationPeriod,omitempty"` - // StorageAccountAttributes - The attributes of the storage account. - StorageAccountAttributes *StorageAccountAttributes `json:"attributes,omitempty"` - // Tags - Application specific metadata in the form of key-value pairs. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for StorageAccountUpdateParameters. -func (saup StorageAccountUpdateParameters) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if saup.ActiveKeyName != nil { - objectMap["activeKeyName"] = saup.ActiveKeyName - } - if saup.AutoRegenerateKey != nil { - objectMap["autoRegenerateKey"] = saup.AutoRegenerateKey - } - if saup.RegenerationPeriod != nil { - objectMap["regenerationPeriod"] = saup.RegenerationPeriod - } - if saup.StorageAccountAttributes != nil { - objectMap["attributes"] = saup.StorageAccountAttributes - } - if saup.Tags != nil { - objectMap["tags"] = saup.Tags - } - return json.Marshal(objectMap) -} - -// StorageBundle a Storage account bundle consists of key vault storage account details plus its -// attributes. -type StorageBundle struct { - autorest.Response `json:"-"` - // ID - READ-ONLY; The storage account id. - ID *string `json:"id,omitempty"` - // ResourceID - READ-ONLY; The storage account resource id. - ResourceID *string `json:"resourceId,omitempty"` - // ActiveKeyName - READ-ONLY; The current active storage account key name. - ActiveKeyName *string `json:"activeKeyName,omitempty"` - // AutoRegenerateKey - READ-ONLY; whether keyvault should manage the storage account for the user. - AutoRegenerateKey *bool `json:"autoRegenerateKey,omitempty"` - // RegenerationPeriod - READ-ONLY; The key regeneration time duration specified in ISO-8601 format. - RegenerationPeriod *string `json:"regenerationPeriod,omitempty"` - // Attributes - READ-ONLY; The storage account attributes. - Attributes *StorageAccountAttributes `json:"attributes,omitempty"` - // Tags - READ-ONLY; Application specific metadata in the form of key-value pairs - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for StorageBundle. -func (sb StorageBundle) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - return json.Marshal(objectMap) -} - -// StorageListResult the storage accounts list result. -type StorageListResult struct { - autorest.Response `json:"-"` - // Value - READ-ONLY; A response message containing a list of storage accounts in the key vault along with a link to the next page of storage accounts. - Value *[]StorageAccountItem `json:"value,omitempty"` - // NextLink - READ-ONLY; The URL to get the next set of storage accounts. - NextLink *string `json:"nextLink,omitempty"` -} - -// StorageListResultIterator provides access to a complete listing of StorageAccountItem values. -type StorageListResultIterator struct { - i int - page StorageListResultPage -} - -// NextWithContext advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *StorageListResultIterator) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StorageListResultIterator.NextWithContext") - defer func() { - sc := -1 - if iter.Response().Response.Response != nil { - sc = iter.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err = iter.page.NextWithContext(ctx) - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (iter *StorageListResultIterator) Next() error { - return iter.NextWithContext(context.Background()) -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter StorageListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter StorageListResultIterator) Response() StorageListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter StorageListResultIterator) Value() StorageAccountItem { - if !iter.page.NotDone() { - return StorageAccountItem{} - } - return iter.page.Values()[iter.i] -} - -// Creates a new instance of the StorageListResultIterator type. -func NewStorageListResultIterator(page StorageListResultPage) StorageListResultIterator { - return StorageListResultIterator{page: page} -} - -// IsEmpty returns true if the ListResult contains no values. -func (slr StorageListResult) IsEmpty() bool { - return slr.Value == nil || len(*slr.Value) == 0 -} - -// hasNextLink returns true if the NextLink is not empty. -func (slr StorageListResult) hasNextLink() bool { - return slr.NextLink != nil && len(*slr.NextLink) != 0 -} - -// storageListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (slr StorageListResult) storageListResultPreparer(ctx context.Context) (*http.Request, error) { - if !slr.hasNextLink() { - return nil, nil - } - return autorest.Prepare((&http.Request{}).WithContext(ctx), - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(slr.NextLink))) -} - -// StorageListResultPage contains a page of StorageAccountItem values. -type StorageListResultPage struct { - fn func(context.Context, StorageListResult) (StorageListResult, error) - slr StorageListResult -} - -// NextWithContext advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *StorageListResultPage) NextWithContext(ctx context.Context) (err error) { - if tracing.IsEnabled() { - ctx = tracing.StartSpan(ctx, fqdn+"/StorageListResultPage.NextWithContext") - defer func() { - sc := -1 - if page.Response().Response.Response != nil { - sc = page.Response().Response.Response.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - } - for { - next, err := page.fn(ctx, page.slr) - if err != nil { - return err - } - page.slr = next - if !next.hasNextLink() || !next.IsEmpty() { - break - } - } - return nil -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -// Deprecated: Use NextWithContext() instead. -func (page *StorageListResultPage) Next() error { - return page.NextWithContext(context.Background()) -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page StorageListResultPage) NotDone() bool { - return !page.slr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page StorageListResultPage) Response() StorageListResult { - return page.slr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page StorageListResultPage) Values() []StorageAccountItem { - if page.slr.IsEmpty() { - return nil - } - return *page.slr.Value -} - -// Creates a new instance of the StorageListResultPage type. -func NewStorageListResultPage(cur StorageListResult, getNextPage func(context.Context, StorageListResult) (StorageListResult, error)) StorageListResultPage { - return StorageListResultPage{ - fn: getNextPage, - slr: cur, - } -} - -// SubjectAlternativeNames the subject alternate names of a X509 object. -type SubjectAlternativeNames struct { - // Emails - Email addresses. - Emails *[]string `json:"emails,omitempty"` - // DNSNames - Domain names. - DNSNames *[]string `json:"dns_names,omitempty"` - // Upns - User principal names. - Upns *[]string `json:"upns,omitempty"` -} - -// Trigger a condition to be satisfied for an action to be executed. -type Trigger struct { - // LifetimePercentage - Percentage of lifetime at which to trigger. Value should be between 1 and 99. - LifetimePercentage *int32 `json:"lifetime_percentage,omitempty"` - // DaysBeforeExpiry - Days before expiry to attempt renewal. Value should be between 1 and validity_in_months multiplied by 27. If validity_in_months is 36, then value should be between 1 and 972 (36 * 27). - DaysBeforeExpiry *int32 `json:"days_before_expiry,omitempty"` -} - -// X509CertificateProperties properties of the X509 component of a certificate. -type X509CertificateProperties struct { - // Subject - The subject name. Should be a valid X509 distinguished Name. - Subject *string `json:"subject,omitempty"` - // Ekus - The enhanced key usage. - Ekus *[]string `json:"ekus,omitempty"` - // SubjectAlternativeNames - The subject alternative names. - SubjectAlternativeNames *SubjectAlternativeNames `json:"sans,omitempty"` - // KeyUsage - List of key usages. - KeyUsage *[]KeyUsageType `json:"key_usage,omitempty"` - // ValidityInMonths - The duration that the certificate is valid in months. - ValidityInMonths *int32 `json:"validity_months,omitempty"` -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/version.go deleted file mode 100644 index b63082f3..00000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/2016-10-01/keyvault/version.go +++ /dev/null @@ -1,30 +0,0 @@ -package keyvault - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft and contributors. 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. -// 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 Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// UserAgent returns the UserAgent string to use when sending http.Requests. -func UserAgent() string { - return "Azure-SDK-For-Go/" + Version() + " keyvault/2016-10-01" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/auth/auth.go b/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/auth/auth.go deleted file mode 100644 index d87f0084..00000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/keyvault/auth/auth.go +++ /dev/null @@ -1,76 +0,0 @@ -package auth - -// Copyright (c) Microsoft and contributors. 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. -// 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. - -import ( - "os" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/azure/auth" -) - -// NewAuthorizerFromEnvironment creates a keyvault dataplane Authorizer configured from environment variables in the order: -// 1. Client credentials -// 2. Client certificate -// 3. Username password -// 4. MSI -func NewAuthorizerFromEnvironment() (autorest.Authorizer, error) { - res, err := getResource() - if err != nil { - return nil, err - } - return auth.NewAuthorizerFromEnvironmentWithResource(res) -} - -// NewAuthorizerFromFile creates a keyvault dataplane Authorizer configured from a configuration file. -// The path to the configuration file must be specified in the AZURE_AUTH_LOCATION environment variable. -func NewAuthorizerFromFile() (autorest.Authorizer, error) { - res, err := getResource() - if err != nil { - return nil, err - } - return auth.NewAuthorizerFromFileWithResource(res) -} - -// NewAuthorizerFromCLI creates a keyvault dataplane Authorizer configured from Azure CLI 2.0 for local development scenarios. -func NewAuthorizerFromCLI() (autorest.Authorizer, error) { - res, err := getResource() - if err != nil { - return nil, err - } - return auth.NewAuthorizerFromCLIWithResource(res) -} - -func getResource() (string, error) { - var env azure.Environment - - if envName := os.Getenv("AZURE_ENVIRONMENT"); envName == "" { - env = azure.PublicCloud - } else { - var err error - env, err = azure.EnvironmentFromName(envName) - if err != nil { - return "", err - } - } - - resource := os.Getenv("AZURE_KEYVAULT_RESOURCE") - if resource == "" { - resource = env.ResourceIdentifiers.KeyVault - } - - return resource, nil -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/version/version.go b/vendor/github.com/Azure/azure-sdk-for-go/version/version.go deleted file mode 100644 index baf3c436..00000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/version/version.go +++ /dev/null @@ -1,21 +0,0 @@ -package version - -// Copyright (c) Microsoft and contributors. 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. -// 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 Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// Number contains the semantic version of this SDK. -const Number = "v52.5.0" diff --git a/vendor/github.com/Azure/go-autorest/.gitignore b/vendor/github.com/Azure/go-autorest/.gitignore deleted file mode 100644 index 3350aaf7..00000000 --- a/vendor/github.com/Azure/go-autorest/.gitignore +++ /dev/null @@ -1,32 +0,0 @@ -# The standard Go .gitignore file follows. (Sourced from: github.com/github/gitignore/master/Go.gitignore) -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test -.DS_Store -.idea/ -.vscode/ - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -# go-autorest specific -vendor/ -autorest/azure/example/example diff --git a/vendor/github.com/Azure/go-autorest/CHANGELOG.md b/vendor/github.com/Azure/go-autorest/CHANGELOG.md deleted file mode 100644 index d1f596bf..00000000 --- a/vendor/github.com/Azure/go-autorest/CHANGELOG.md +++ /dev/null @@ -1,1004 +0,0 @@ -# CHANGELOG - -## v14.2.0 - -- Added package comment to make `github.com/Azure/go-autorest` importable. - -## v14.1.1 - -### Bug Fixes - -- Change `x-ms-authorization-auxiliary` header value separator to comma. - -## v14.1.0 - -### New Features - -- Added `azure.SetEnvironment()` that will update the global environments map with the specified values. - -## v14.0.1 - -### Bug Fixes - -- Fix race condition when refreshing token. -- Fixed some tests to work with Go 1.14. - -## v14.0.0 - -## Breaking Changes - -- By default, the `DoRetryForStatusCodes` functions will no longer infinitely retry a request when the response returns an HTTP status code of 429 (StatusTooManyRequests). To opt in to the old behavior set `autorest.Count429AsRetry` to `false`. - -## New Features - -- Variable `autorest.Max429Delay` can be used to control the maximum delay between retries when a 429 is received with no `Retry-After` header. The default is zero which means there is no cap. - -## v13.4.0 - -## New Features - -- Added field `SendDecorators` to the `Client` type. This can be used to specify a custom chain of SendDecorators per client. -- Added method `Client.Send()` which includes logic for selecting the preferred chain of SendDecorators. - -## v13.3.3 - -### Bug Fixes - -- Fixed connection leak when retrying requests. -- Enabled exponential back-off with a 2-minute cap when retrying on 429. -- Fixed some cases where errors were inadvertently dropped. - -## v13.3.2 - -### Bug Fixes - -- Updated `autorest.AsStringSlice()` to convert slice elements to their string representation. - -## v13.3.1 - -- Updated external dependencies. - -### Bug Fixes - -## v13.3.0 - -### New Features - -- Added support for shared key and shared access signature token authorization. - - `autorest.NewSharedKeyAuthorizer()` and dependent types. - - `autorest.NewSASTokenAuthorizer()` and dependent types. -- Added `ServicePrincipalToken.SetCustomRefresh()` so a custom refresh function can be invoked when a token has expired. - -### Bug Fixes - -- Fixed `cli.AccessTokensPath()` to respect `AZURE_CONFIG_DIR` when set. -- Support parsing error messages in XML responses. - -## v13.2.0 - -### New Features - -- Added the following functions to replace their versions that don't take a context. - - `adal.InitiateDeviceAuthWithContext()` - - `adal.CheckForUserCompletionWithContext()` - - `adal.WaitForUserCompletionWithContext()` - -## v13.1.0 - -### New Features - -- Added support for MSI authentication on Azure App Service and Azure Functions. - -## v13.0.2 - -### Bug Fixes - -- Always retry a request even if the sender returns a non-nil error. - -## v13.0.1 - -## Bug Fixes - -- Fixed `autorest.WithQueryParameters()` so that it properly encodes multi-value query parameters. - -## v13.0.0 - -## Breaking Changes - -The `tracing` package has been rewritten to provide a common interface for consumers to wire in the tracing package of their choice. -What this means is that by default no tracing provider will be compiled into your program and setting the `AZURE_SDK_TRACING_ENABLED` -environment variable will have no effect. To enable this previous behavior you must now add the following import to your source file. -```go - import _ "github.com/Azure/go-autorest/tracing/opencensus" -``` -The APIs required by autorest-generated code have remained but some APIs have been removed and new ones added. -The following APIs and variables have been removed (the majority of them were moved to the `opencensus` package). -- tracing.Transport -- tracing.Enable() -- tracing.EnableWithAIForwarding() -- tracing.Disable() - -The following APIs and types have been added -- tracing.Tracer -- tracing.Register() - -To hook up a tracer simply call `tracing.Register()` passing in a type that satisfies the `tracing.Tracer` interface. - -## v12.4.3 - -### Bug Fixes - -- `autorest.MultiTenantServicePrincipalTokenAuthorizer` will now properly add its auxiliary bearer tokens. - -## v12.4.2 - -### Bug Fixes - -- Improvements to the fixes made in v12.4.1. - - Remove `override` stanza from Gopkg.toml and `replace` directive from go.mod as they don't apply when being consumed as a dependency. - - Switched to latest version of `ocagent` that still depends on protobuf v1.2. - - Add indirect dependencies to the `required` clause with matching `constraint` stanzas so that `dep` dependencies match go.sum. - -## v12.4.1 - -### Bug Fixes - -- Updated OpenCensus and OCAgent versions to versions that don't depend on v1.3+ of protobuf as it was breaking kubernetes. -- Pinned opencensus-proto to a version that's compatible with our versions of OpenCensus and OCAgent. - -## v12.4.0 - -### New Features - -- Added `autorest.WithPrepareDecorators` and `autorest.GetPrepareDecorators` for adding and retrieving a custom chain of PrepareDecorators to the provided context. - -## v12.3.0 - -### New Features - -- Support for multi-tenant via x-ms-authorization-auxiliary header has been added for client credentials with - secret scenario; this basically bundles multiple OAuthConfig and ServicePrincipalToken types into corresponding - MultiTenant* types along with a new authorizer that adds the primary and auxiliary token headers to the reqest. - The authenticaion helpers have been updated to support this scenario; if environment var AZURE_AUXILIARY_TENANT_IDS - is set with a semicolon delimited list of tenants the multi-tenant codepath will kick in to create the appropriate authorizer. - See `adal.NewMultiTenantOAuthConfig`, `adal.NewMultiTenantServicePrincipalToken` and `autorest.NewMultiTenantServicePrincipalTokenAuthorizer` - along with their supporting types and methods. -- Added `autorest.WithSendDecorators` and `autorest.GetSendDecorators` for adding and retrieving a custom chain of SendDecorators to the provided context. -- Added `autorest.DoRetryForStatusCodesWithCap` and `autorest.DelayForBackoffWithCap` to enforce an upper bound on the duration between retries. - -## v12.2.0 - -### New Features - -- Added `autorest.WithXML`, `autorest.AsMerge`, `autorest.WithBytes` preparer decorators. -- Added `autorest.ByUnmarshallingBytes` response decorator. -- Added `Response.IsHTTPStatus` and `Response.HasHTTPStatus` helper methods for inspecting HTTP status code in `autorest.Response` types. - -### Bug Fixes - -- `autorest.DelayWithRetryAfter` now supports HTTP-Dates in the `Retry-After` header and is not limited to just 429 status codes. - -## v12.1.0 - -### New Features - -- Added `to.ByteSlicePtr()`. -- Added blob/queue storage resource ID to `azure.ResourceIdentifier`. - -## v12.0.0 - -### Breaking Changes - -In preparation for modules the following deprecated content has been removed. - - - async.NewFuture() - - async.Future.Done() - - async.Future.WaitForCompletion() - - async.DoPollForAsynchronous() - - The `utils` package - - validation.NewErrorWithValidationError() - - The `version` package - -## v11.9.0 - -### New Features - -- Add `ResourceIdentifiers` field to `azure.Environment` containing resource IDs for public and sovereign clouds. - -## v11.8.0 - -### New Features - -- Added `autorest.NewClientWithOptions()` to support endpoints that require free renegotiation. - -## v11.7.1 - -### Bug Fixes - -- Fix missing support for http(s) proxy when using the default sender. - -## v11.7.0 - -### New Features - -- Added methods to obtain a ServicePrincipalToken on the various credential configuration types in the `auth` package. - -## v11.6.1 - -### Bug Fixes - -- Fix ACR DNS endpoint for government clouds. -- Add Cosmos DB DNS endpoints. -- Update dependencies to resolve build breaks in OpenCensus. - -## v11.6.0 - -### New Features - -- Added type `autorest.BasicAuthorizer` to support Basic authentication. - -## v11.5.2 - -### Bug Fixes - -- Fixed `GetTokenFromCLI` did not work with zsh. - -## v11.5.1 - -### Bug Fixes - -- In `Client.sender()` set the minimum TLS version on HTTP clients to 1.2. - -## v11.5.0 - -### New Features - -- The `auth` package has been refactored so that the environment and file settings are now available. -- The methods used in `auth.NewAuthorizerFromEnvironment()` are now exported so that custom authorization chains can be created. -- Added support for certificate authorization for file-based config. - -## v11.4.0 - -### New Features - -- Added `adal.AddToUserAgent()` so callers can append custom data to the user-agent header used for ADAL requests. -- Exported `adal.UserAgent()` for parity with `autorest.Client`. - -## v11.3.2 - -### Bug Fixes - -- In `Future.WaitForCompletionRef()` if the provided context has a deadline don't add the default deadline. - -## v11.3.1 - -### Bug Fixes - -- For an LRO PUT operation the final GET URL was incorrectly set to the Location polling header in some cases. - -## v11.3.0 - -### New Features - -- Added method `ServicePrincipalToken()` to `DeviceFlowConfig` type. - -## v11.2.8 - -### Bug Fixes - -- Deprecate content in the `version` package. The functionality has been superseded by content in the `autorest` package. - -## v11.2.7 - -### Bug Fixes - -- Fix environment variable name for enabling tracing from `AZURE_SDK_TRACING_ENABELD` to `AZURE_SDK_TRACING_ENABLED`. - Note that for backward compatibility reasons, both will work until the next major version release of the package. - -## v11.2.6 - -### Bug Fixes - -- If zero bytes are read from a polling response body don't attempt to unmarshal them. - -## v11.2.5 - -### Bug Fixes - -- Removed race condition in `autorest.DoRetryForStatusCodes`. - -## v11.2.4 - -### Bug Fixes - -- Function `cli.ProfilePath` now respects environment `AZURE_CONFIG_DIR` if available. - -## v11.2.1 - -NOTE: Versions of Go prior to 1.10 have been removed from CI as they no -longer work with golint. - -### Bug Fixes - -- Method `MSIConfig.Authorizer` now supports user-assigned identities. -- The adal package now reports its own user-agent string. - -## v11.2.0 - -### New Features - -- Added `tracing` package that enables instrumentation of HTTP and API calls. - Setting the env variable `AZURE_SDK_TRACING_ENABLED` or calling `tracing.Enable` - will start instrumenting the code for metrics and traces. - Additionally, setting the env variable `OCAGENT_TRACE_EXPORTER_ENDPOINT` or - calling `tracing.EnableWithAIForwarding` will start the instrumentation and connect to an - App Insights Local Forwarder that is needs to be running. Note that if the - AI Local Forwarder is not running tracking will still be enabled. - By default, instrumentation is disabled. Once enabled, instrumentation can also - be programatically disabled by calling `Disable`. -- Added `DoneWithContext` call for checking LRO status. `Done` has been deprecated. - -### Bug Fixes - -- Don't use the initial request's context for LRO polling. -- Don't override the `refreshLock` and the `http.Client` when unmarshalling `ServicePrincipalToken` if - it is already set. - -## v11.1.1 - -### Bug Fixes - -- When creating a future always include the polling tracker even if there's a failure; this allows the underlying response to be obtained by the caller. - -## v11.1.0 - -### New Features - -- Added `auth.NewAuthorizerFromCLI` to create an authorizer configured from the Azure 2.0 CLI. -- Added `adal.NewOAuthConfigWithAPIVersion` to create an OAuthConfig with the specified API version. - -## v11.0.1 - -### New Features - -- Added `x5c` header to client assertion for certificate Issuer+Subject Name authentication. - -## v11.0.0 - -### Breaking Changes - -- To handle differences between ADFS and AAD the following fields have had their types changed from `string` to `json.Number` - - ExpiresIn - - ExpiresOn - - NotBefore - -### New Features - -- Added `auth.NewAuthorizerFromFileWithResource` to create an authorizer from the config file with the specified resource. -- Setting a client's `PollingDuration` to zero will use the provided context to control a LRO's polling duration. - -## v10.15.5 - -### Bug Fixes - -- In `DoRetryForStatusCodes`, if a request's context is cancelled return the last response. - -## v10.15.4 - -### Bug Fixes - -- If a polling operation returns a failure status code return the associated error. - -## v10.15.3 - -### Bug Fixes - -- Initialize the polling URL and method for an LRO tracker on each iteration, favoring the Azure-AsyncOperation header. - -## v10.15.2 - -### Bug Fixes - -- Use fmt.Fprint when printing request/response so that any escape sequences aren't treated as format specifiers. - -## v10.15.1 - -### Bug Fixes - -- If an LRO API returns a `Failed` provisioning state in the initial response return an error at that point so the caller doesn't have to poll. -- For failed LROs without an OData v4 error include the response body in the error's `AdditionalInfo` field to aid in diagnosing the failure. - -## v10.15.0 - -### New Features - -- Add initial support for request/response logging via setting environment variables. - Setting `AZURE_GO_SDK_LOG_LEVEL` to `LogInfo` will log request/response - without their bodies. To include the bodies set the log level to `LogDebug`. - By default the logger writes to strerr, however it can also write to stdout or a file - if specified in `AZURE_GO_SDK_LOG_FILE`. Note that if the specified file - already exists it will be truncated. - IMPORTANT: by default the logger will redact the Authorization and Ocp-Apim-Subscription-Key - headers. Any other secrets will _not_ be redacted. - -## v10.14.0 - -### New Features - -- Added package version that contains version constants and user-agent data. - -### Bug Fixes - -- Add the user-agent to token requests. - -## v10.13.0 - -- Added support for additionalInfo in ServiceError type. - -## v10.12.0 - -### New Features - -- Added field ServicePrincipalToken.MaxMSIRefreshAttempts to configure the maximun number of attempts to refresh an MSI token. - -## v10.11.4 - -### Bug Fixes - -- If an LRO returns http.StatusOK on the initial response with no async headers return the response body from Future.GetResult(). -- If there is no "final GET URL" return an error from Future.GetResult(). - -## v10.11.3 - -### Bug Fixes - -- In IMDS retry logic, if we don't receive a response don't retry. - - Renamed the retry function so it's clear it's meant for IMDS only. -- For error response bodies that aren't OData-v4 compliant stick the raw JSON in the ServiceError.Details field so the information isn't lost. - - Also add the raw HTTP response to the DetailedResponse. -- Removed superfluous wrapping of response error in azure.DoRetryWithRegistration(). - -## v10.11.2 - -### Bug Fixes - -- Validation for integers handles int and int64 types. - -## v10.11.1 - -### Bug Fixes - -- Adding User information to authorization config as parsed from CLI cache. - -## v10.11.0 - -### New Features - -- Added NewServicePrincipalTokenFromManualTokenSecret for creating a new SPT using a manual token and secret -- Added method ServicePrincipalToken.MarshalTokenJSON() to marshall the inner Token - -## v10.10.0 - -### New Features - -- Most ServicePrincipalTokens can now be marshalled/unmarshall to/from JSON (ServicePrincipalCertificateSecret and ServicePrincipalMSISecret are not supported). -- Added method ServicePrincipalToken.SetRefreshCallbacks(). - -## v10.9.2 - -### Bug Fixes - -- Refreshing a refresh token obtained from a web app authorization code now works. - -## v10.9.1 - -### Bug Fixes - -- The retry logic for MSI token requests now uses exponential backoff per the guidelines. -- IsTemporaryNetworkError() will return true for errors that don't implement the net.Error interface. - -## v10.9.0 - -### Deprecated Methods - -| Old Method | New Method | -| -------------------------: | :---------------------------: | -| azure.NewFuture() | azure.NewFutureFromResponse() | -| Future.WaitForCompletion() | Future.WaitForCompletionRef() | - -### New Features - -- Added azure.NewFutureFromResponse() for creating a Future from the initial response from an async operation. -- Added Future.GetResult() for making the final GET call to retrieve the result from an async operation. - -### Bug Fixes - -- Some futures failed to return their results, this should now be fixed. - -## v10.8.2 - -### Bug Fixes - -- Add nil-gaurd to token retry logic. - -## v10.8.1 - -### Bug Fixes - -- Return a TokenRefreshError if the sender fails on the initial request. -- Don't retry on non-temporary network errors. - -## v10.8.0 - -- Added NewAuthorizerFromEnvironmentWithResource() helper function. - -## v10.7.0 - -### New Features - -- Added \*WithContext() methods to ADAL token refresh operations. - -## v10.6.2 - -- Fixed a bug on device authentication. - -## v10.6.1 - -- Added retries to MSI token get request. - -## v10.6.0 - -- Changed MSI token implementation. Now, the token endpoint is the IMDS endpoint. - -## v10.5.1 - -### Bug Fixes - -- `DeviceFlowConfig.Authorizer()` now prints the device code message when running `go test`. `-v` flag is required. - -## v10.5.0 - -### New Features - -- Added NewPollingRequestWithContext() for use with polling asynchronous operations. - -### Bug Fixes - -- Make retry logic use the request's context instead of the deprecated Cancel object. - -## v10.4.0 - -### New Features - -- Added helper for parsing Azure Resource ID's. -- Added deprecation message to utils.GetEnvVarOrExit() - -## v10.3.0 - -### New Features - -- Added EnvironmentFromURL method to load an Environment from a given URL. This function is particularly useful in the private and hybrid Cloud model, where one may define their own endpoints -- Added TokenAudience endpoint to Environment structure. This is useful in private and hybrid cloud models where TokenAudience endpoint can be different from ResourceManagerEndpoint - -## v10.2.0 - -### New Features - -- Added endpoints for batch management. - -## v10.1.3 - -### Bug Fixes - -- In Client.Do() invoke WithInspection() last so that it will inspect WithAuthorization(). -- Fixed authorization methods to invoke p.Prepare() first, aligning them with the other preparers. - -## v10.1.2 - -- Corrected comment for auth.NewAuthorizerFromFile() function. - -## v10.1.1 - -- Updated version number to match current release. - -## v10.1.0 - -### New Features - -- Expose the polling URL for futures. - -### Bug Fixes - -- Add validation.NewErrorWithValidationError back to prevent breaking changes (it is deprecated). - -## v10.0.0 - -### New Features - -- Added target and innererror fields to ServiceError to comply with OData v4 spec. -- The Done() method on futures will now return a ServiceError object when available (it used to return a partial value of such errors). -- Added helper methods for obtaining authorizers. -- Expose the polling URL for futures. - -### Bug Fixes - -- Switched from glide to dep for dependency management. -- Fixed unmarshaling of ServiceError for JSON bodies that don't conform to the OData spec. -- Fixed a race condition in token refresh. - -### Breaking Changes - -- The ServiceError.Details field type has been changed to match the OData v4 spec. -- Go v1.7 has been dropped from CI. -- API parameter validation failures will now return a unique error type validation.Error. -- The adal.Token type has been decomposed from adal.ServicePrincipalToken (this was necessary in order to fix the token refresh race). - -## v9.10.0 - -- Fix the Service Bus suffix in Azure public env -- Add Service Bus Endpoint (AAD ResourceURI) for use in [Azure Service Bus RBAC Preview](https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-role-based-access-control) - -## v9.9.0 - -### New Features - -- Added EventGridKeyAuthorizer for key authorization with event grid topics. - -### Bug Fixes - -- Fixed race condition when auto-refreshing service principal tokens. - -## v9.8.1 - -### Bug Fixes - -- Added http.StatusNoContent (204) to the list of expected status codes for long-running operations. -- Updated runtime version info so it's current. - -## v9.8.0 - -### New Features - -- Added type azure.AsyncOpIncompleteError to be returned from a future's Result() method when the operation has not completed. - -## v9.7.1 - -### Bug Fixes - -- Use correct AAD and Graph endpoints for US Gov environment. - -## v9.7.0 - -### New Features - -- Added support for application/octet-stream MIME types. - -## v9.6.1 - -### Bug Fixes - -- Ensure Authorization header is added to request when polling for registration status. - -## v9.6.0 - -### New Features - -- Added support for acquiring tokens via MSI with a user assigned identity. - -## v9.5.3 - -### Bug Fixes - -- Don't remove encoding of existing URL Query parameters when calling autorest.WithQueryParameters. -- Set correct Content Type when using autorest.WithFormData. - -## v9.5.2 - -### Bug Fixes - -- Check for nil \*http.Response before dereferencing it. - -## v9.5.1 - -### Bug Fixes - -- Don't count http.StatusTooManyRequests (429) against the retry cap. -- Use retry logic when SkipResourceProviderRegistration is set to true. - -## v9.5.0 - -### New Features - -- Added support for username + password, API key, authoriazation code and cognitive services authentication. -- Added field SkipResourceProviderRegistration to clients to provide a way to skip auto-registration of RPs. -- Added utility function AsStringSlice() to convert its parameters to a string slice. - -### Bug Fixes - -- When checking for authentication failures look at the error type not the status code as it could vary. - -## v9.4.2 - -### Bug Fixes - -- Validate parameters when creating credentials. -- Don't retry requests if the returned status is a 401 (http.StatusUnauthorized) as it will never succeed. - -## v9.4.1 - -### Bug Fixes - -- Update the AccessTokensPath() to read access tokens path through AZURE_ACCESS_TOKEN_FILE. If this - environment variable is not set, it will fall back to use default path set by Azure CLI. -- Use case-insensitive string comparison for polling states. - -## v9.4.0 - -### New Features - -- Added WaitForCompletion() to Future as a default polling implementation. - -### Bug Fixes - -- Method Future.Done() shouldn't update polling status for unexpected HTTP status codes. - -## v9.3.1 - -### Bug Fixes - -- DoRetryForStatusCodes will retry if sender.Do returns a non-nil error. - -## v9.3.0 - -### New Features - -- Added PollingMethod() to Future so callers know what kind of polling mechanism is used. -- Added azure.ChangeToGet() which transforms an http.Request into a GET (to be used with LROs). - -## v9.2.0 - -### New Features - -- Added support for custom Azure Stack endpoints. -- Added type azure.Future used to track the status of long-running operations. - -### Bug Fixes - -- Preserve the original error in DoRetryWithRegistration when registration fails. - -## v9.1.1 - -- Fixes a bug regarding the cookie jar on `autorest.Client.Sender`. - -## v9.1.0 - -### New Features - -- In cases where there is a non-empty error from the service, attempt to unmarshal it instead of uniformly calling it an "Unknown" error. -- Support for loading Azure CLI Authentication files. -- Automatically register your subscription with the Azure Resource Provider if it hadn't been previously. - -### Bug Fixes - -- RetriableRequest can now tolerate a ReadSeekable body being read but not reset. -- Adding missing Apache Headers - -## v9.0.0 - -> **IMPORTANT:** This release was intially labeled incorrectly as `v8.4.0`. From the time it was released, it should have been marked `v9.0.0` because it contains breaking changes to the MSI packages. We appologize for any inconvenience this causes. - -Adding MSI Endpoint Support and CLI token rehydration. - -## v8.3.1 - -Pick up bug fix in adal for MSI support. - -## v8.3.0 - -Updates to Error string formats for clarity. Also, adding a copy of the http.Response to errors for an improved debugging experience. - -## v8.2.0 - -### New Features - -- Add support for bearer authentication callbacks -- Support 429 response codes that include "Retry-After" header -- Support validation constraint "Pattern" for map keys - -### Bug Fixes - -- Make RetriableRequest work with multiple versions of Go - -## v8.1.1 - -Updates the RetriableRequest to take advantage of GetBody() added in Go 1.8. - -## v8.1.0 - -Adds RetriableRequest type for more efficient handling of retrying HTTP requests. - -## v8.0.0 - -ADAL refactored into its own package. -Support for UNIX time. - -## v7.3.1 - -- Version Testing now removed from production bits that are shipped with the library. - -## v7.3.0 - -- Exposing new `RespondDecorator`, `ByDiscardingBody`. This allows operations - to acknowledge that they do not need either the entire or a trailing portion - of accepts response body. In doing so, Go's http library can reuse HTTP - connections more readily. -- Adding `PrepareDecorator` to target custom BaseURLs. -- Adding ACR suffix to public cloud environment. -- Updating Glide dependencies. - -## v7.2.5 - -- Fixed the Active Directory endpoint for the China cloud. -- Removes UTF-8 BOM if present in response payload. -- Added telemetry. - -## v7.2.3 - -- Fixing bug in calls to `DelayForBackoff` that caused doubling of delay - duration. - -## v7.2.2 - -- autorest/azure: added ASM and ARM VM DNS suffixes. - -## v7.2.1 - -- fixed parsing of UTC times that are not RFC3339 conformant. - -## v7.2.0 - -- autorest/validation: Reformat validation error for better error message. - -## v7.1.0 - -- preparer: Added support for multipart formdata - WithMultiPartFormdata() -- preparer: Added support for sending file in request body - WithFile -- client: Added RetryDuration parameter. -- autorest/validation: new package for validation code for Azure Go SDK. - -## v7.0.7 - -- Add trailing / to endpoint -- azure: add EnvironmentFromName - -## v7.0.6 - -- Add retry logic for 408, 500, 502, 503 and 504 status codes. -- Change url path and query encoding logic. -- Fix DelayForBackoff for proper exponential delay. -- Add CookieJar in Client. - -## v7.0.5 - -- Add check to start polling only when status is in [200,201,202]. -- Refactoring for unchecked errors. -- azure/persist changes. -- Fix 'file in use' issue in renewing token in deviceflow. -- Store header RetryAfter for subsequent requests in polling. -- Add attribute details in service error. - -## v7.0.4 - -- Better error messages for long running operation failures - -## v7.0.3 - -- Corrected DoPollForAsynchronous to properly handle the initial response - -## v7.0.2 - -- Corrected DoPollForAsynchronous to continue using the polling method first discovered - -## v7.0.1 - -- Fixed empty JSON input error in ByUnmarshallingJSON -- Fixed polling support for GET calls -- Changed format name from TimeRfc1123 to TimeRFC1123 - -## v7.0.0 - -- Added ByCopying responder with supporting TeeReadCloser -- Rewrote Azure asynchronous handling -- Reverted to only unmarshalling JSON -- Corrected handling of RFC3339 time strings and added support for Rfc1123 time format - -The `json.Decoder` does not catch bad data as thoroughly as `json.Unmarshal`. Since -`encoding/json` successfully deserializes all core types, and extended types normally provide -their custom JSON serialization handlers, the code has been reverted back to using -`json.Unmarshal`. The original change to use `json.Decode` was made to reduce duplicate -code; there is no loss of function, and there is a gain in accuracy, by reverting. - -Additionally, Azure services indicate requests to be polled by multiple means. The existing code -only checked for one of those (that is, the presence of the `Azure-AsyncOperation` header). -The new code correctly covers all cases and aligns with the other Azure SDKs. - -## v6.1.0 - -- Introduced `date.ByUnmarshallingJSONDate` and `date.ByUnmarshallingJSONTime` to enable JSON encoded values. - -## v6.0.0 - -- Completely reworked the handling of polled and asynchronous requests -- Removed unnecessary routines -- Reworked `mocks.Sender` to replay a series of `http.Response` objects -- Added `PrepareDecorators` for primitive types (e.g., bool, int32) - -Handling polled and asynchronous requests is no longer part of `Client#Send`. Instead new -`SendDecorators` implement different styles of polled behavior. See`autorest.DoPollForStatusCodes` -and `azure.DoPollForAsynchronous` for examples. - -## v5.0.0 - -- Added new RespondDecorators unmarshalling primitive types -- Corrected application of inspection and authorization PrependDecorators - -## v4.0.0 - -- Added support for Azure long-running operations. -- Added cancelation support to all decorators and functions that may delay. -- Breaking: `DelayForBackoff` now accepts a channel, which may be nil. - -## v3.1.0 - -- Add support for OAuth Device Flow authorization. -- Add support for ServicePrincipalTokens that are backed by an existing token, rather than other secret material. -- Add helpers for persisting and restoring Tokens. -- Increased code coverage in the github.com/Azure/autorest/azure package - -## v3.0.0 - -- Breaking: `NewErrorWithError` no longer takes `statusCode int`. -- Breaking: `NewErrorWithStatusCode` is replaced with `NewErrorWithResponse`. -- Breaking: `Client#Send()` no longer takes `codes ...int` argument. -- Add: XML unmarshaling support with `ByUnmarshallingXML()` -- Stopped vending dependencies locally and switched to [Glide](https://github.com/Masterminds/glide). - Applications using this library should either use Glide or vendor dependencies locally some other way. -- Add: `azure.WithErrorUnlessStatusCode()` decorator to handle Azure errors. -- Fix: use `net/http.DefaultClient` as base client. -- Fix: Missing inspection for polling responses added. -- Add: CopyAndDecode helpers. -- Improved `./autorest/to` with `[]string` helpers. -- Removed golint suppressions in .travis.yml. - -## v2.1.0 - -- Added `StatusCode` to `Error` for more easily obtaining the HTTP Reponse StatusCode (if any) - -## v2.0.0 - -- Changed `to.StringMapPtr` method signature to return a pointer -- Changed `ServicePrincipalCertificateSecret` and `NewServicePrincipalTokenFromCertificate` to support generic certificate and private keys - -## v1.0.0 - -- Added Logging inspectors to trace http.Request / Response -- Added support for User-Agent header -- Changed WithHeader PrepareDecorator to use set vs. add -- Added JSON to error when unmarshalling fails -- Added Client#Send method -- Corrected case of "Azure" in package paths -- Added "to" helpers, Azure helpers, and improved ease-of-use -- Corrected golint issues - -## v1.0.1 - -- Added CHANGELOG.md - -## v1.1.0 - -- Added mechanism to retrieve a ServicePrincipalToken using a certificate-signed JWT -- Added an example of creating a certificate-based ServicePrincipal and retrieving an OAuth token using the certificate - -## v1.1.1 - -- Introduce godeps and vendor dependencies introduced in v1.1.1 diff --git a/vendor/github.com/Azure/go-autorest/GNUmakefile b/vendor/github.com/Azure/go-autorest/GNUmakefile deleted file mode 100644 index a434e73a..00000000 --- a/vendor/github.com/Azure/go-autorest/GNUmakefile +++ /dev/null @@ -1,23 +0,0 @@ -DIR?=./autorest/ - -default: build - -build: fmt - go install $(DIR) - -test: - go test $(DIR) || exit 1 - -vet: - @echo "go vet ." - @go vet $(DIR)... ; if [ $$? -eq 1 ]; then \ - echo ""; \ - echo "Vet found suspicious constructs. Please check the reported constructs"; \ - echo "and fix them if necessary before submitting the code for review."; \ - exit 1; \ - fi - -fmt: - gofmt -w $(DIR) - -.PHONY: build test vet fmt diff --git a/vendor/github.com/Azure/go-autorest/Gopkg.lock b/vendor/github.com/Azure/go-autorest/Gopkg.lock deleted file mode 100644 index dc6e3e63..00000000 --- a/vendor/github.com/Azure/go-autorest/Gopkg.lock +++ /dev/null @@ -1,324 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:892e39e5c083d0943f1e80ab8351690f183c6a5ab24e1d280adcad424c26255e" - name = "contrib.go.opencensus.io/exporter/ocagent" - packages = ["."] - pruneopts = "UT" - revision = "a8a6f458bbc1d5042322ad1f9b65eeb0b69be9ea" - version = "v0.6.0" - -[[projects]] - digest = "1:8f5acd4d4462b5136af644d25101f0968a7a94ee90fcb2059cec5b7cc42e0b20" - name = "github.com/census-instrumentation/opencensus-proto" - packages = [ - "gen-go/agent/common/v1", - "gen-go/agent/metrics/v1", - "gen-go/agent/trace/v1", - "gen-go/metrics/v1", - "gen-go/resource/v1", - "gen-go/trace/v1", - ] - pruneopts = "UT" - revision = "d89fa54de508111353cb0b06403c00569be780d8" - version = "v0.2.1" - -[[projects]] - digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec" - name = "github.com/davecgh/go-spew" - packages = ["spew"] - pruneopts = "UT" - revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73" - version = "v1.1.1" - -[[projects]] - digest = "1:76dc72490af7174349349838f2fe118996381b31ea83243812a97e5a0fd5ed55" - name = "github.com/dgrijalva/jwt-go" - packages = ["."] - pruneopts = "UT" - revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" - version = "v3.2.0" - -[[projects]] - digest = "1:cf0d2e435fd4ce45b789e93ef24b5f08e86be0e9807a16beb3694e2d8c9af965" - name = "github.com/dimchansky/utfbom" - packages = ["."] - pruneopts = "UT" - revision = "d2133a1ce379ef6fa992b0514a77146c60db9d1c" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:b7cb6054d3dff43b38ad2e92492f220f57ae6087ee797dca298139776749ace8" - name = "github.com/golang/groupcache" - packages = ["lru"] - pruneopts = "UT" - revision = "611e8accdfc92c4187d399e95ce826046d4c8d73" - -[[projects]] - digest = "1:e3839df32927e8d3403cd5aa7253d966e8ff80fc8f10e2e35d146461cd83fcfa" - name = "github.com/golang/protobuf" - packages = [ - "descriptor", - "jsonpb", - "proto", - "protoc-gen-go/descriptor", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/struct", - "ptypes/timestamp", - "ptypes/wrappers", - ] - pruneopts = "UT" - revision = "6c65a5562fc06764971b7c5d05c76c75e84bdbf7" - version = "v1.3.2" - -[[projects]] - digest = "1:c560cd79300fac84f124b96225181a637a70b60155919a3c36db50b7cca6b806" - name = "github.com/grpc-ecosystem/grpc-gateway" - packages = [ - "internal", - "runtime", - "utilities", - ] - pruneopts = "UT" - revision = "f7120437bb4f6c71f7f5076ad65a45310de2c009" - version = "v1.12.1" - -[[projects]] - digest = "1:5d231480e1c64a726869bc4142d270184c419749d34f167646baa21008eb0a79" - name = "github.com/mitchellh/go-homedir" - packages = ["."] - pruneopts = "UT" - revision = "af06845cf3004701891bf4fdb884bfe4920b3727" - version = "v1.1.0" - -[[projects]] - digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" - name = "github.com/pmezard/go-difflib" - packages = ["difflib"] - pruneopts = "UT" - revision = "792786c7400a136282c1664665ae0a8db921c6c2" - version = "v1.0.0" - -[[projects]] - digest = "1:99d32780e5238c2621fff621123997c3e3cca96db8be13179013aea77dfab551" - name = "github.com/stretchr/testify" - packages = [ - "assert", - "require", - ] - pruneopts = "UT" - revision = "221dbe5ed46703ee255b1da0dec05086f5035f62" - version = "v1.4.0" - -[[projects]] - digest = "1:7c5e00383399fe13de0b4b65c9fdde16275407ce8ac02d867eafeaa916edcc71" - name = "go.opencensus.io" - packages = [ - ".", - "internal", - "internal/tagencoding", - "metric/metricdata", - "metric/metricproducer", - "plugin/ocgrpc", - "plugin/ochttp", - "plugin/ochttp/propagation/b3", - "plugin/ochttp/propagation/tracecontext", - "resource", - "stats", - "stats/internal", - "stats/view", - "tag", - "trace", - "trace/internal", - "trace/propagation", - "trace/tracestate", - ] - pruneopts = "UT" - revision = "aad2c527c5defcf89b5afab7f37274304195a6b2" - version = "v0.22.2" - -[[projects]] - branch = "master" - digest = "1:f604f5e2ee721b6757d962dfe7bab4f28aae50c456e39cfb2f3819762a44a6ae" - name = "golang.org/x/crypto" - packages = [ - "pkcs12", - "pkcs12/internal/rc2", - ] - pruneopts = "UT" - revision = "e9b2fee46413994441b28dfca259d911d963dfed" - -[[projects]] - branch = "master" - digest = "1:334b27eac455cb6567ea28cd424230b07b1a64334a2f861a8075ac26ce10af43" - name = "golang.org/x/lint" - packages = [ - ".", - "golint", - ] - pruneopts = "UT" - revision = "fdd1cda4f05fd1fd86124f0ef9ce31a0b72c8448" - -[[projects]] - branch = "master" - digest = "1:257a75d024975428ab9192bfc334c3490882f8cb21322ea5784ca8eca000a910" - name = "golang.org/x/net" - packages = [ - "http/httpguts", - "http2", - "http2/hpack", - "idna", - "internal/timeseries", - "trace", - ] - pruneopts = "UT" - revision = "1ddd1de85cb0337b623b740a609d35817d516a8d" - -[[projects]] - branch = "master" - digest = "1:382bb5a7fb4034db3b6a2d19e5a4a6bcf52f4750530603c01ca18a172fa3089b" - name = "golang.org/x/sync" - packages = ["semaphore"] - pruneopts = "UT" - revision = "cd5d95a43a6e21273425c7ae415d3df9ea832eeb" - -[[projects]] - branch = "master" - digest = "1:4da420ceda5f68e8d748aa2169d0ed44ffadb1bbd6537cf778a49563104189b8" - name = "golang.org/x/sys" - packages = ["unix"] - pruneopts = "UT" - revision = "ce4227a45e2eb77e5c847278dcc6a626742e2945" - -[[projects]] - digest = "1:8d8faad6b12a3a4c819a3f9618cb6ee1fa1cfc33253abeeea8b55336721e3405" - name = "golang.org/x/text" - packages = [ - "collate", - "collate/build", - "internal/colltab", - "internal/gen", - "internal/language", - "internal/language/compact", - "internal/tag", - "internal/triegen", - "internal/ucd", - "language", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "UT" - revision = "342b2e1fbaa52c93f31447ad2c6abc048c63e475" - version = "v0.3.2" - -[[projects]] - branch = "master" - digest = "1:4eb5ea8395fb60212dd58b92c9db80bab59d5e99c7435f9a6a0a528c373b60e7" - name = "golang.org/x/tools" - packages = [ - "go/ast/astutil", - "go/gcexportdata", - "go/internal/gcimporter", - "go/types/typeutil", - ] - pruneopts = "UT" - revision = "259af5ff87bdcd4abf2ecda8edc3f13f04f26a42" - -[[projects]] - digest = "1:964bb30febc27fabfbec4759fa530c6ec35e77a7c85fed90b9317ea39a054877" - name = "google.golang.org/api" - packages = ["support/bundler"] - pruneopts = "UT" - revision = "8a410c21381766a810817fd6200fce8838ecb277" - version = "v0.14.0" - -[[projects]] - branch = "master" - digest = "1:a8d5c2c6e746b3485e36908ab2a9e3d77b86b81f8156d88403c7d2b462431dfd" - name = "google.golang.org/genproto" - packages = [ - "googleapis/api/httpbody", - "googleapis/rpc/status", - "protobuf/field_mask", - ] - pruneopts = "UT" - revision = "51378566eb590fa106d1025ea12835a4416dda84" - -[[projects]] - digest = "1:b59ce3ddb11daeeccccc9cb3183b58ebf8e9a779f1c853308cd91612e817a301" - name = "google.golang.org/grpc" - packages = [ - ".", - "backoff", - "balancer", - "balancer/base", - "balancer/roundrobin", - "binarylog/grpc_binarylog_v1", - "codes", - "connectivity", - "credentials", - "credentials/internal", - "encoding", - "encoding/proto", - "grpclog", - "internal", - "internal/backoff", - "internal/balancerload", - "internal/binarylog", - "internal/buffer", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/grpcsync", - "internal/resolver/dns", - "internal/resolver/passthrough", - "internal/syscall", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "serviceconfig", - "stats", - "status", - "tap", - ] - pruneopts = "UT" - revision = "1a3960e4bd028ac0cec0a2afd27d7d8e67c11514" - version = "v1.25.1" - -[[projects]] - digest = "1:b75b3deb2bce8bc079e16bb2aecfe01eb80098f5650f9e93e5643ca8b7b73737" - name = "gopkg.in/yaml.v2" - packages = ["."] - pruneopts = "UT" - revision = "1f64d6156d11335c3f22d9330b0ad14fc1e789ce" - version = "v2.2.7" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "contrib.go.opencensus.io/exporter/ocagent", - "github.com/dgrijalva/jwt-go", - "github.com/dimchansky/utfbom", - "github.com/mitchellh/go-homedir", - "github.com/stretchr/testify/require", - "go.opencensus.io/plugin/ochttp", - "go.opencensus.io/plugin/ochttp/propagation/tracecontext", - "go.opencensus.io/stats/view", - "go.opencensus.io/trace", - "golang.org/x/crypto/pkcs12", - "golang.org/x/lint/golint", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/Azure/go-autorest/Gopkg.toml b/vendor/github.com/Azure/go-autorest/Gopkg.toml deleted file mode 100644 index 1fc28659..00000000 --- a/vendor/github.com/Azure/go-autorest/Gopkg.toml +++ /dev/null @@ -1,59 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" -# -# [prune] -# non-go = false -# go-tests = true -# unused-packages = true - -required = ["golang.org/x/lint/golint"] - -[prune] - go-tests = true - unused-packages = true - -[[constraint]] - name = "contrib.go.opencensus.io/exporter/ocagent" - version = "0.6.0" - -[[constraint]] - name = "github.com/dgrijalva/jwt-go" - version = "3.2.0" - -[[constraint]] - name = "github.com/dimchansky/utfbom" - version = "1.1.0" - -[[constraint]] - name = "github.com/mitchellh/go-homedir" - version = "1.1.0" - -[[constraint]] - name = "github.com/stretchr/testify" - version = "1.3.0" - -[[constraint]] - name = "go.opencensus.io" - version = "0.22.0" - -[[constraint]] - branch = "master" - name = "golang.org/x/crypto" diff --git a/vendor/github.com/Azure/go-autorest/LICENSE b/vendor/github.com/Azure/go-autorest/LICENSE deleted file mode 100644 index b9d6a27e..00000000 --- a/vendor/github.com/Azure/go-autorest/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2015 Microsoft Corporation - - 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/Azure/go-autorest/README.md b/vendor/github.com/Azure/go-autorest/README.md deleted file mode 100644 index de1e19a4..00000000 --- a/vendor/github.com/Azure/go-autorest/README.md +++ /dev/null @@ -1,165 +0,0 @@ -# go-autorest - -[![GoDoc](https://godoc.org/github.com/Azure/go-autorest/autorest?status.png)](https://godoc.org/github.com/Azure/go-autorest/autorest) -[![Build Status](https://dev.azure.com/azure-sdk/public/_apis/build/status/go/Azure.go-autorest?branchName=master)](https://dev.azure.com/azure-sdk/public/_build/latest?definitionId=625&branchName=master) -[![Go Report Card](https://goreportcard.com/badge/Azure/go-autorest)](https://goreportcard.com/report/Azure/go-autorest) - -Package go-autorest provides an HTTP request client for use with [Autorest](https://github.com/Azure/autorest.go)-generated API client packages. - -An authentication client tested with Azure Active Directory (AAD) is also -provided in this repo in the package -`github.com/Azure/go-autorest/autorest/adal`. Despite its name, this package -is maintained only as part of the Azure Go SDK and is not related to other -"ADAL" libraries in [github.com/AzureAD](https://github.com/AzureAD). - -## Overview - -Package go-autorest implements an HTTP request pipeline suitable for use across -multiple goroutines and provides the shared routines used by packages generated -by [Autorest](https://github.com/Azure/autorest.go). - -The package breaks sending and responding to HTTP requests into three phases: Preparing, Sending, -and Responding. A typical pattern is: - -```go - req, err := Prepare(&http.Request{}, - token.WithAuthorization()) - - resp, err := Send(req, - WithLogging(logger), - DoErrorIfStatusCode(http.StatusInternalServerError), - DoCloseIfError(), - DoRetryForAttempts(5, time.Second)) - - err = Respond(resp, - ByDiscardingBody(), - ByClosing()) -``` - -Each phase relies on decorators to modify and / or manage processing. Decorators may first modify -and then pass the data along, pass the data first and then modify the result, or wrap themselves -around passing the data (such as a logger might do). Decorators run in the order provided. For -example, the following: - -```go - req, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPath("a"), - WithPath("b"), - WithPath("c")) -``` - -will set the URL to: - -``` - https://microsoft.com/a/b/c -``` - -Preparers and Responders may be shared and re-used (assuming the underlying decorators support -sharing and re-use). Performant use is obtained by creating one or more Preparers and Responders -shared among multiple go-routines, and a single Sender shared among multiple sending go-routines, -all bound together by means of input / output channels. - -Decorators hold their passed state within a closure (such as the path components in the example -above). Be careful to share Preparers and Responders only in a context where such held state -applies. For example, it may not make sense to share a Preparer that applies a query string from a -fixed set of values. Similarly, sharing a Responder that reads the response body into a passed -struct (e.g., `ByUnmarshallingJson`) is likely incorrect. - -Errors raised by autorest objects and methods will conform to the `autorest.Error` interface. - -See the included examples for more detail. For details on the suggested use of this package by -generated clients, see the Client described below. - -## Helpers - -### Handling Swagger Dates - -The Swagger specification (https://swagger.io) that drives AutoRest -(https://github.com/Azure/autorest/) precisely defines two date forms: date and date-time. The -github.com/Azure/go-autorest/autorest/date package provides time.Time derivations to ensure correct -parsing and formatting. - -### Handling Empty Values - -In JSON, missing values have different semantics than empty values. This is especially true for -services using the HTTP PATCH verb. The JSON submitted with a PATCH request generally contains -only those values to modify. Missing values are to be left unchanged. Developers, then, require a -means to both specify an empty value and to leave the value out of the submitted JSON. - -The Go JSON package (`encoding/json`) supports the `omitempty` tag. When specified, it omits -empty values from the rendered JSON. Since Go defines default values for all base types (such as "" -for string and 0 for int) and provides no means to mark a value as actually empty, the JSON package -treats default values as meaning empty, omitting them from the rendered JSON. This means that, using -the Go base types encoded through the default JSON package, it is not possible to create JSON to -clear a value at the server. - -The workaround within the Go community is to use pointers to base types in lieu of base types within -structures that map to JSON. For example, instead of a value of type `string`, the workaround uses -`*string`. While this enables distinguishing empty values from those to be unchanged, creating -pointers to a base type (notably constant, in-line values) requires additional variables. This, for -example, - -```go - s := struct { - S *string - }{ S: &"foo" } -``` -fails, while, this - -```go - v := "foo" - s := struct { - S *string - }{ S: &v } -``` -succeeds. - -To ease using pointers, the subpackage `to` contains helpers that convert to and from pointers for -Go base types which have Swagger analogs. It also provides a helper that converts between -`map[string]string` and `map[string]*string`, enabling the JSON to specify that the value -associated with a key should be cleared. With the helpers, the previous example becomes - -```go - s := struct { - S *string - }{ S: to.StringPtr("foo") } -``` - -## Install - -```bash -go get github.com/Azure/go-autorest/autorest -go get github.com/Azure/go-autorest/autorest/azure -go get github.com/Azure/go-autorest/autorest/date -go get github.com/Azure/go-autorest/autorest/to -``` - -### Using with Go Modules -In [v12.0.1](https://github.com/Azure/go-autorest/pull/386), this repository introduced the following modules. - -- autorest/adal -- autorest/azure/auth -- autorest/azure/cli -- autorest/date -- autorest/mocks -- autorest/to -- autorest/validation -- autorest -- logger -- tracing - -Tagging cumulative SDK releases as a whole (e.g. `v12.3.0`) is still enabled to support consumers of this repo that have not yet migrated to modules. - -## License - -See LICENSE file. - ------ - -This project has adopted the [Microsoft Open Source Code of -Conduct](https://opensource.microsoft.com/codeofconduct/). For more information -see the [Code of Conduct -FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact -[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional -questions or comments. diff --git a/vendor/github.com/Azure/go-autorest/autorest/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/LICENSE deleted file mode 100644 index b9d6a27e..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2015 Microsoft Corporation - - 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/Azure/go-autorest/autorest/adal/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/adal/LICENSE deleted file mode 100644 index b9d6a27e..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2015 Microsoft Corporation - - 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/Azure/go-autorest/autorest/adal/README.md b/vendor/github.com/Azure/go-autorest/autorest/adal/README.md deleted file mode 100644 index fec416a9..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/README.md +++ /dev/null @@ -1,292 +0,0 @@ -# Azure Active Directory authentication for Go - -This is a standalone package for authenticating with Azure Active -Directory from other Go libraries and applications, in particular the [Azure SDK -for Go](https://github.com/Azure/azure-sdk-for-go). - -Note: Despite the package's name it is not related to other "ADAL" libraries -maintained in the [github.com/AzureAD](https://github.com/AzureAD) org. Issues -should be opened in [this repo's](https://github.com/Azure/go-autorest/issues) -or [the SDK's](https://github.com/Azure/azure-sdk-for-go/issues) issue -trackers. - -## Install - -```bash -go get -u github.com/Azure/go-autorest/autorest/adal -``` - -## Usage - -An Active Directory application is required in order to use this library. An application can be registered in the [Azure Portal](https://portal.azure.com/) by following these [guidelines](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-integrating-applications) or using the [Azure CLI](https://github.com/Azure/azure-cli). - -### Register an Azure AD Application with secret - - -1. Register a new application with a `secret` credential - - ``` - az ad app create \ - --display-name example-app \ - --homepage https://example-app/home \ - --identifier-uris https://example-app/app \ - --password secret - ``` - -2. Create a service principal using the `Application ID` from previous step - - ``` - az ad sp create --id "Application ID" - ``` - - * Replace `Application ID` with `appId` from step 1. - -### Register an Azure AD Application with certificate - -1. Create a private key - - ``` - openssl genrsa -out "example-app.key" 2048 - ``` - -2. Create the certificate - - ``` - openssl req -new -key "example-app.key" -subj "/CN=example-app" -out "example-app.csr" - openssl x509 -req -in "example-app.csr" -signkey "example-app.key" -out "example-app.crt" -days 10000 - ``` - -3. Create the PKCS12 version of the certificate containing also the private key - - ``` - openssl pkcs12 -export -out "example-app.pfx" -inkey "example-app.key" -in "example-app.crt" -passout pass: - - ``` - -4. Register a new application with the certificate content form `example-app.crt` - - ``` - certificateContents="$(tail -n+2 "example-app.crt" | head -n-1)" - - az ad app create \ - --display-name example-app \ - --homepage https://example-app/home \ - --identifier-uris https://example-app/app \ - --key-usage Verify --end-date 2018-01-01 \ - --key-value "${certificateContents}" - ``` - -5. Create a service principal using the `Application ID` from previous step - - ``` - az ad sp create --id "APPLICATION_ID" - ``` - - * Replace `APPLICATION_ID` with `appId` from step 4. - - -### Grant the necessary permissions - -Azure relies on a Role-Based Access Control (RBAC) model to manage the access to resources at a fine-grained -level. There is a set of [pre-defined roles](https://docs.microsoft.com/en-us/azure/active-directory/role-based-access-built-in-roles) -which can be assigned to a service principal of an Azure AD application depending of your needs. - -``` -az role assignment create --assigner "SERVICE_PRINCIPAL_ID" --role "ROLE_NAME" -``` - -* Replace the `SERVICE_PRINCIPAL_ID` with the `appId` from previous step. -* Replace the `ROLE_NAME` with a role name of your choice. - -It is also possible to define custom role definitions. - -``` -az role definition create --role-definition role-definition.json -``` - -* Check [custom roles](https://docs.microsoft.com/en-us/azure/active-directory/role-based-access-control-custom-roles) for more details regarding the content of `role-definition.json` file. - - -### Acquire Access Token - -The common configuration used by all flows: - -```Go -const activeDirectoryEndpoint = "https://login.microsoftonline.com/" -tenantID := "TENANT_ID" -oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, tenantID) - -applicationID := "APPLICATION_ID" - -callback := func(token adal.Token) error { - // This is called after the token is acquired -} - -// The resource for which the token is acquired -resource := "https://management.core.windows.net/" -``` - -* Replace the `TENANT_ID` with your tenant ID. -* Replace the `APPLICATION_ID` with the value from previous section. - -#### Client Credentials - -```Go -applicationSecret := "APPLICATION_SECRET" - -spt, err := adal.NewServicePrincipalToken( - *oauthConfig, - appliationID, - applicationSecret, - resource, - callbacks...) -if err != nil { - return nil, err -} - -// Acquire a new access token -err = spt.Refresh() -if (err == nil) { - token := spt.Token -} -``` - -* Replace the `APPLICATION_SECRET` with the `password` value from previous section. - -#### Client Certificate - -```Go -certificatePath := "./example-app.pfx" - -certData, err := ioutil.ReadFile(certificatePath) -if err != nil { - return nil, fmt.Errorf("failed to read the certificate file (%s): %v", certificatePath, err) -} - -// Get the certificate and private key from pfx file -certificate, rsaPrivateKey, err := decodePkcs12(certData, "") -if err != nil { - return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err) -} - -spt, err := adal.NewServicePrincipalTokenFromCertificate( - *oauthConfig, - applicationID, - certificate, - rsaPrivateKey, - resource, - callbacks...) - -// Acquire a new access token -err = spt.Refresh() -if (err == nil) { - token := spt.Token -} -``` - -* Update the certificate path to point to the example-app.pfx file which was created in previous section. - - -#### Device Code - -```Go -oauthClient := &http.Client{} - -// Acquire the device code -deviceCode, err := adal.InitiateDeviceAuth( - oauthClient, - *oauthConfig, - applicationID, - resource) -if err != nil { - return nil, fmt.Errorf("Failed to start device auth flow: %s", err) -} - -// Display the authentication message -fmt.Println(*deviceCode.Message) - -// Wait here until the user is authenticated -token, err := adal.WaitForUserCompletion(oauthClient, deviceCode) -if err != nil { - return nil, fmt.Errorf("Failed to finish device auth flow: %s", err) -} - -spt, err := adal.NewServicePrincipalTokenFromManualToken( - *oauthConfig, - applicationID, - resource, - *token, - callbacks...) - -if (err == nil) { - token := spt.Token -} -``` - -#### Username password authenticate - -```Go -spt, err := adal.NewServicePrincipalTokenFromUsernamePassword( - *oauthConfig, - applicationID, - username, - password, - resource, - callbacks...) - -if (err == nil) { - token := spt.Token -} -``` - -#### Authorization code authenticate - -``` Go -spt, err := adal.NewServicePrincipalTokenFromAuthorizationCode( - *oauthConfig, - applicationID, - clientSecret, - authorizationCode, - redirectURI, - resource, - callbacks...) - -err = spt.Refresh() -if (err == nil) { - token := spt.Token -} -``` - -### Command Line Tool - -A command line tool is available in `cmd/adal.go` that can acquire a token for a given resource. It supports all flows mentioned above. - -``` -adal -h - -Usage of ./adal: - -applicationId string - application id - -certificatePath string - path to pk12/PFC application certificate - -mode string - authentication mode (device, secret, cert, refresh) (default "device") - -resource string - resource for which the token is requested - -secret string - application secret - -tenantId string - tenant id - -tokenCachePath string - location of oath token cache (default "/home/cgc/.adal/accessToken.json") -``` - -Example acquire a token for `https://management.core.windows.net/` using device code flow: - -``` -adal -mode device \ - -applicationId "APPLICATION_ID" \ - -tenantId "TENANT_ID" \ - -resource https://management.core.windows.net/ - -``` diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/config.go b/vendor/github.com/Azure/go-autorest/autorest/adal/config.go deleted file mode 100644 index fa596474..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/config.go +++ /dev/null @@ -1,151 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "errors" - "fmt" - "net/url" -) - -const ( - activeDirectoryEndpointTemplate = "%s/oauth2/%s%s" -) - -// OAuthConfig represents the endpoints needed -// in OAuth operations -type OAuthConfig struct { - AuthorityEndpoint url.URL `json:"authorityEndpoint"` - AuthorizeEndpoint url.URL `json:"authorizeEndpoint"` - TokenEndpoint url.URL `json:"tokenEndpoint"` - DeviceCodeEndpoint url.URL `json:"deviceCodeEndpoint"` -} - -// IsZero returns true if the OAuthConfig object is zero-initialized. -func (oac OAuthConfig) IsZero() bool { - return oac == OAuthConfig{} -} - -func validateStringParam(param, name string) error { - if len(param) == 0 { - return fmt.Errorf("parameter '" + name + "' cannot be empty") - } - return nil -} - -// NewOAuthConfig returns an OAuthConfig with tenant specific urls -func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) { - apiVer := "1.0" - return NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID, &apiVer) -} - -// NewOAuthConfigWithAPIVersion returns an OAuthConfig with tenant specific urls. -// If apiVersion is not nil the "api-version" query parameter will be appended to the endpoint URLs with the specified value. -func NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID string, apiVersion *string) (*OAuthConfig, error) { - if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil { - return nil, err - } - api := "" - // it's legal for tenantID to be empty so don't validate it - if apiVersion != nil { - if err := validateStringParam(*apiVersion, "apiVersion"); err != nil { - return nil, err - } - api = fmt.Sprintf("?api-version=%s", *apiVersion) - } - u, err := url.Parse(activeDirectoryEndpoint) - if err != nil { - return nil, err - } - authorityURL, err := u.Parse(tenantID) - if err != nil { - return nil, err - } - authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", api)) - if err != nil { - return nil, err - } - tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", api)) - if err != nil { - return nil, err - } - deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", api)) - if err != nil { - return nil, err - } - - return &OAuthConfig{ - AuthorityEndpoint: *authorityURL, - AuthorizeEndpoint: *authorizeURL, - TokenEndpoint: *tokenURL, - DeviceCodeEndpoint: *deviceCodeURL, - }, nil -} - -// MultiTenantOAuthConfig provides endpoints for primary and aulixiary tenant IDs. -type MultiTenantOAuthConfig interface { - PrimaryTenant() *OAuthConfig - AuxiliaryTenants() []*OAuthConfig -} - -// OAuthOptions contains optional OAuthConfig creation arguments. -type OAuthOptions struct { - APIVersion string -} - -func (c OAuthOptions) apiVersion() string { - if c.APIVersion != "" { - return fmt.Sprintf("?api-version=%s", c.APIVersion) - } - return "1.0" -} - -// NewMultiTenantOAuthConfig creates an object that support multitenant OAuth configuration. -// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/authenticate-multi-tenant for more information. -func NewMultiTenantOAuthConfig(activeDirectoryEndpoint, primaryTenantID string, auxiliaryTenantIDs []string, options OAuthOptions) (MultiTenantOAuthConfig, error) { - if len(auxiliaryTenantIDs) == 0 || len(auxiliaryTenantIDs) > 3 { - return nil, errors.New("must specify one to three auxiliary tenants") - } - mtCfg := multiTenantOAuthConfig{ - cfgs: make([]*OAuthConfig, len(auxiliaryTenantIDs)+1), - } - apiVer := options.apiVersion() - pri, err := NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, primaryTenantID, &apiVer) - if err != nil { - return nil, fmt.Errorf("failed to create OAuthConfig for primary tenant: %v", err) - } - mtCfg.cfgs[0] = pri - for i := range auxiliaryTenantIDs { - aux, err := NewOAuthConfig(activeDirectoryEndpoint, auxiliaryTenantIDs[i]) - if err != nil { - return nil, fmt.Errorf("failed to create OAuthConfig for tenant '%s': %v", auxiliaryTenantIDs[i], err) - } - mtCfg.cfgs[i+1] = aux - } - return mtCfg, nil -} - -type multiTenantOAuthConfig struct { - // first config in the slice is the primary tenant - cfgs []*OAuthConfig -} - -func (m multiTenantOAuthConfig) PrimaryTenant() *OAuthConfig { - return m.cfgs[0] -} - -func (m multiTenantOAuthConfig) AuxiliaryTenants() []*OAuthConfig { - return m.cfgs[1:] -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go b/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go deleted file mode 100644 index 9daa4b58..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go +++ /dev/null @@ -1,273 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// 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. - -/* - This file is largely based on rjw57/oauth2device's code, with the follow differences: - * scope -> resource, and only allow a single one - * receive "Message" in the DeviceCode struct and show it to users as the prompt - * azure-xplat-cli has the following behavior that this emulates: - - does not send client_secret during the token exchange - - sends resource again in the token exchange request -*/ - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" -) - -const ( - logPrefix = "autorest/adal/devicetoken:" -) - -var ( - // ErrDeviceGeneric represents an unknown error from the token endpoint when using device flow - ErrDeviceGeneric = fmt.Errorf("%s Error while retrieving OAuth token: Unknown Error", logPrefix) - - // ErrDeviceAccessDenied represents an access denied error from the token endpoint when using device flow - ErrDeviceAccessDenied = fmt.Errorf("%s Error while retrieving OAuth token: Access Denied", logPrefix) - - // ErrDeviceAuthorizationPending represents the server waiting on the user to complete the device flow - ErrDeviceAuthorizationPending = fmt.Errorf("%s Error while retrieving OAuth token: Authorization Pending", logPrefix) - - // ErrDeviceCodeExpired represents the server timing out and expiring the code during device flow - ErrDeviceCodeExpired = fmt.Errorf("%s Error while retrieving OAuth token: Code Expired", logPrefix) - - // ErrDeviceSlowDown represents the service telling us we're polling too often during device flow - ErrDeviceSlowDown = fmt.Errorf("%s Error while retrieving OAuth token: Slow Down", logPrefix) - - // ErrDeviceCodeEmpty represents an empty device code from the device endpoint while using device flow - ErrDeviceCodeEmpty = fmt.Errorf("%s Error while retrieving device code: Device Code Empty", logPrefix) - - // ErrOAuthTokenEmpty represents an empty OAuth token from the token endpoint when using device flow - ErrOAuthTokenEmpty = fmt.Errorf("%s Error while retrieving OAuth token: Token Empty", logPrefix) - - errCodeSendingFails = "Error occurred while sending request for Device Authorization Code" - errCodeHandlingFails = "Error occurred while handling response from the Device Endpoint" - errTokenSendingFails = "Error occurred while sending request with device code for a token" - errTokenHandlingFails = "Error occurred while handling response from the Token Endpoint (during device flow)" - errStatusNotOK = "Error HTTP status != 200" -) - -// DeviceCode is the object returned by the device auth endpoint -// It contains information to instruct the user to complete the auth flow -type DeviceCode struct { - DeviceCode *string `json:"device_code,omitempty"` - UserCode *string `json:"user_code,omitempty"` - VerificationURL *string `json:"verification_url,omitempty"` - ExpiresIn *int64 `json:"expires_in,string,omitempty"` - Interval *int64 `json:"interval,string,omitempty"` - - Message *string `json:"message"` // Azure specific - Resource string // store the following, stored when initiating, used when exchanging - OAuthConfig OAuthConfig - ClientID string -} - -// TokenError is the object returned by the token exchange endpoint -// when something is amiss -type TokenError struct { - Error *string `json:"error,omitempty"` - ErrorCodes []int `json:"error_codes,omitempty"` - ErrorDescription *string `json:"error_description,omitempty"` - Timestamp *string `json:"timestamp,omitempty"` - TraceID *string `json:"trace_id,omitempty"` -} - -// DeviceToken is the object return by the token exchange endpoint -// It can either look like a Token or an ErrorToken, so put both here -// and check for presence of "Error" to know if we are in error state -type deviceToken struct { - Token - TokenError -} - -// InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode -// that can be used with CheckForUserCompletion or WaitForUserCompletion. -// Deprecated: use InitiateDeviceAuthWithContext() instead. -func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { - return InitiateDeviceAuthWithContext(context.Background(), sender, oauthConfig, clientID, resource) -} - -// InitiateDeviceAuthWithContext initiates a device auth flow. It returns a DeviceCode -// that can be used with CheckForUserCompletion or WaitForUserCompletion. -func InitiateDeviceAuthWithContext(ctx context.Context, sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { - v := url.Values{ - "client_id": []string{clientID}, - "resource": []string{resource}, - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - - req, err := http.NewRequest(http.MethodPost, oauthConfig.DeviceCodeEndpoint.String(), body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) - } - - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - resp, err := sender.Do(req.WithContext(ctx)) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) - } - defer resp.Body.Close() - - rb, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) - } - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, errStatusNotOK) - } - - if len(strings.Trim(string(rb), " ")) == 0 { - return nil, ErrDeviceCodeEmpty - } - - var code DeviceCode - err = json.Unmarshal(rb, &code) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) - } - - code.ClientID = clientID - code.Resource = resource - code.OAuthConfig = oauthConfig - - return &code, nil -} - -// CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint -// to see if the device flow has: been completed, timed out, or otherwise failed -// Deprecated: use CheckForUserCompletionWithContext() instead. -func CheckForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { - return CheckForUserCompletionWithContext(context.Background(), sender, code) -} - -// CheckForUserCompletionWithContext takes a DeviceCode and checks with the Azure AD OAuth endpoint -// to see if the device flow has: been completed, timed out, or otherwise failed -func CheckForUserCompletionWithContext(ctx context.Context, sender Sender, code *DeviceCode) (*Token, error) { - v := url.Values{ - "client_id": []string{code.ClientID}, - "code": []string{*code.DeviceCode}, - "grant_type": []string{OAuthGrantTypeDeviceCode}, - "resource": []string{code.Resource}, - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - - req, err := http.NewRequest(http.MethodPost, code.OAuthConfig.TokenEndpoint.String(), body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err.Error()) - } - - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - resp, err := sender.Do(req.WithContext(ctx)) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err.Error()) - } - defer resp.Body.Close() - - rb, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err.Error()) - } - - if resp.StatusCode != http.StatusOK && len(strings.Trim(string(rb), " ")) == 0 { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, errStatusNotOK) - } - if len(strings.Trim(string(rb), " ")) == 0 { - return nil, ErrOAuthTokenEmpty - } - - var token deviceToken - err = json.Unmarshal(rb, &token) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err.Error()) - } - - if token.Error == nil { - return &token.Token, nil - } - - switch *token.Error { - case "authorization_pending": - return nil, ErrDeviceAuthorizationPending - case "slow_down": - return nil, ErrDeviceSlowDown - case "access_denied": - return nil, ErrDeviceAccessDenied - case "code_expired": - return nil, ErrDeviceCodeExpired - default: - // return a more meaningful error message if available - if token.ErrorDescription != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, *token.Error, *token.ErrorDescription) - } - return nil, ErrDeviceGeneric - } -} - -// WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs. -// This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'. -// Deprecated: use WaitForUserCompletionWithContext() instead. -func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { - return WaitForUserCompletionWithContext(context.Background(), sender, code) -} - -// WaitForUserCompletionWithContext calls CheckForUserCompletion repeatedly until a token is granted or an error -// state occurs. This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'. -func WaitForUserCompletionWithContext(ctx context.Context, sender Sender, code *DeviceCode) (*Token, error) { - intervalDuration := time.Duration(*code.Interval) * time.Second - waitDuration := intervalDuration - - for { - token, err := CheckForUserCompletionWithContext(ctx, sender, code) - - if err == nil { - return token, nil - } - - switch err { - case ErrDeviceSlowDown: - waitDuration += waitDuration - case ErrDeviceAuthorizationPending: - // noop - default: // everything else is "fatal" to us - return nil, err - } - - if waitDuration > (intervalDuration * 3) { - return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix) - } - - select { - case <-time.After(waitDuration): - // noop - case <-ctx.Done(): - return nil, ctx.Err() - } - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/adal/go_mod_tidy_hack.go deleted file mode 100644 index 7551b792..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package adal - -// Copyright 2017 Microsoft Corporation -// -// 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. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go b/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go deleted file mode 100644 index 2a974a39..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go +++ /dev/null @@ -1,135 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "golang.org/x/crypto/pkcs12" -) - -var ( - // ErrMissingCertificate is returned when no local certificate is found in the provided PFX data. - ErrMissingCertificate = errors.New("adal: certificate missing") - - // ErrMissingPrivateKey is returned when no private key is found in the provided PFX data. - ErrMissingPrivateKey = errors.New("adal: private key missing") -) - -// LoadToken restores a Token object from a file located at 'path'. -func LoadToken(path string) (*Token, error) { - file, err := os.Open(path) - if err != nil { - return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) - } - defer file.Close() - - var token Token - - dec := json.NewDecoder(file) - if err = dec.Decode(&token); err != nil { - return nil, fmt.Errorf("failed to decode contents of file (%s) into Token representation: %v", path, err) - } - return &token, nil -} - -// SaveToken persists an oauth token at the given location on disk. -// It moves the new file into place so it can safely be used to replace an existing file -// that maybe accessed by multiple processes. -func SaveToken(path string, mode os.FileMode, token Token) error { - dir := filepath.Dir(path) - err := os.MkdirAll(dir, os.ModePerm) - if err != nil { - return fmt.Errorf("failed to create directory (%s) to store token in: %v", dir, err) - } - - newFile, err := ioutil.TempFile(dir, "token") - if err != nil { - return fmt.Errorf("failed to create the temp file to write the token: %v", err) - } - tempPath := newFile.Name() - - if err := json.NewEncoder(newFile).Encode(token); err != nil { - return fmt.Errorf("failed to encode token to file (%s) while saving token: %v", tempPath, err) - } - if err := newFile.Close(); err != nil { - return fmt.Errorf("failed to close temp file %s: %v", tempPath, err) - } - - // Atomic replace to avoid multi-writer file corruptions - if err := os.Rename(tempPath, path); err != nil { - return fmt.Errorf("failed to move temporary token to desired output location. src=%s dst=%s: %v", tempPath, path, err) - } - if err := os.Chmod(path, mode); err != nil { - return fmt.Errorf("failed to chmod the token file %s: %v", path, err) - } - return nil -} - -// DecodePfxCertificateData extracts the x509 certificate and RSA private key from the provided PFX data. -// The PFX data must contain a private key along with a certificate whose public key matches that of the -// private key or an error is returned. -// If the private key is not password protected pass the empty string for password. -func DecodePfxCertificateData(pfxData []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error) { - blocks, err := pkcs12.ToPEM(pfxData, password) - if err != nil { - return nil, nil, err - } - // first extract the private key - var priv *rsa.PrivateKey - for _, block := range blocks { - if block.Type == "PRIVATE KEY" { - priv, err = x509.ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - return nil, nil, err - } - break - } - } - if priv == nil { - return nil, nil, ErrMissingPrivateKey - } - // now find the certificate with the matching public key of our private key - var cert *x509.Certificate - for _, block := range blocks { - if block.Type == "CERTIFICATE" { - pcert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, nil, err - } - certKey, ok := pcert.PublicKey.(*rsa.PublicKey) - if !ok { - // keep looking - continue - } - if priv.E == certKey.E && priv.N.Cmp(certKey.N) == 0 { - // found a match - cert = pcert - break - } - } - } - if cert == nil { - return nil, nil, ErrMissingCertificate - } - return cert, priv, nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go b/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go deleted file mode 100644 index 1826a68d..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go +++ /dev/null @@ -1,96 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "crypto/tls" - "net/http" - "net/http/cookiejar" - "sync" - - "github.com/Azure/go-autorest/tracing" -) - -const ( - contentType = "Content-Type" - mimeTypeFormPost = "application/x-www-form-urlencoded" -) - -// DO NOT ACCESS THIS DIRECTLY. go through sender() -var defaultSender Sender -var defaultSenderInit = &sync.Once{} - -// Sender is the interface that wraps the Do method to send HTTP requests. -// -// The standard http.Client conforms to this interface. -type Sender interface { - Do(*http.Request) (*http.Response, error) -} - -// SenderFunc is a method that implements the Sender interface. -type SenderFunc func(*http.Request) (*http.Response, error) - -// Do implements the Sender interface on SenderFunc. -func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { - return sf(r) -} - -// SendDecorator takes and possibly decorates, by wrapping, a Sender. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then react to the -// http.Response result. -type SendDecorator func(Sender) Sender - -// CreateSender creates, decorates, and returns, as a Sender, the default http.Client. -func CreateSender(decorators ...SendDecorator) Sender { - return DecorateSender(sender(), decorators...) -} - -// DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to -// the Sender. Decorators are applied in the order received, but their affect upon the request -// depends on whether they are a pre-decorator (change the http.Request and then pass it along) or a -// post-decorator (pass the http.Request along and react to the results in http.Response). -func DecorateSender(s Sender, decorators ...SendDecorator) Sender { - for _, decorate := range decorators { - s = decorate(s) - } - return s -} - -func sender() Sender { - // note that we can't init defaultSender in init() since it will - // execute before calling code has had a chance to enable tracing - defaultSenderInit.Do(func() { - // Use behaviour compatible with DefaultTransport, but require TLS minimum version. - defaultTransport := http.DefaultTransport.(*http.Transport) - transport := &http.Transport{ - Proxy: defaultTransport.Proxy, - DialContext: defaultTransport.DialContext, - MaxIdleConns: defaultTransport.MaxIdleConns, - IdleConnTimeout: defaultTransport.IdleConnTimeout, - TLSHandshakeTimeout: defaultTransport.TLSHandshakeTimeout, - ExpectContinueTimeout: defaultTransport.ExpectContinueTimeout, - TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS12, - }, - } - var roundTripper http.RoundTripper = transport - if tracing.IsEnabled() { - roundTripper = tracing.NewTransport(transport) - } - j, _ := cookiejar.New(nil) - defaultSender = &http.Client{Jar: j, Transport: roundTripper} - }) - return defaultSender -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/token.go b/vendor/github.com/Azure/go-autorest/autorest/adal/token.go deleted file mode 100644 index c870ef4e..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/token.go +++ /dev/null @@ -1,1336 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "context" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "math" - "net/http" - "net/url" - "os" - "strconv" - "strings" - "sync" - "time" - - "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/logger" - "github.com/form3tech-oss/jwt-go" -) - -const ( - defaultRefresh = 5 * time.Minute - - // OAuthGrantTypeDeviceCode is the "grant_type" identifier used in device flow - OAuthGrantTypeDeviceCode = "device_code" - - // OAuthGrantTypeClientCredentials is the "grant_type" identifier used in credential flows - OAuthGrantTypeClientCredentials = "client_credentials" - - // OAuthGrantTypeUserPass is the "grant_type" identifier used in username and password auth flows - OAuthGrantTypeUserPass = "password" - - // OAuthGrantTypeRefreshToken is the "grant_type" identifier used in refresh token flows - OAuthGrantTypeRefreshToken = "refresh_token" - - // OAuthGrantTypeAuthorizationCode is the "grant_type" identifier used in authorization code flows - OAuthGrantTypeAuthorizationCode = "authorization_code" - - // metadataHeader is the header required by MSI extension - metadataHeader = "Metadata" - - // msiEndpoint is the well known endpoint for getting MSI authentications tokens - msiEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token" - - // the API version to use for the MSI endpoint - msiAPIVersion = "2018-02-01" - - // the default number of attempts to refresh an MSI authentication token - defaultMaxMSIRefreshAttempts = 5 - - // asMSIEndpointEnv is the environment variable used to store the endpoint on App Service and Functions - msiEndpointEnv = "MSI_ENDPOINT" - - // asMSISecretEnv is the environment variable used to store the request secret on App Service and Functions - msiSecretEnv = "MSI_SECRET" - - // the API version to use for the legacy App Service MSI endpoint - appServiceAPIVersion2017 = "2017-09-01" - - // secret header used when authenticating against app service MSI endpoint - secretHeader = "Secret" - - // the format for expires_on in UTC with AM/PM - expiresOnDateFormatPM = "1/2/2006 15:04:05 PM +00:00" - - // the format for expires_on in UTC without AM/PM - expiresOnDateFormat = "1/2/2006 15:04:05 +00:00" -) - -// OAuthTokenProvider is an interface which should be implemented by an access token retriever -type OAuthTokenProvider interface { - OAuthToken() string -} - -// MultitenantOAuthTokenProvider provides tokens used for multi-tenant authorization. -type MultitenantOAuthTokenProvider interface { - PrimaryOAuthToken() string - AuxiliaryOAuthTokens() []string -} - -// TokenRefreshError is an interface used by errors returned during token refresh. -type TokenRefreshError interface { - error - Response() *http.Response -} - -// Refresher is an interface for token refresh functionality -type Refresher interface { - Refresh() error - RefreshExchange(resource string) error - EnsureFresh() error -} - -// RefresherWithContext is an interface for token refresh functionality -type RefresherWithContext interface { - RefreshWithContext(ctx context.Context) error - RefreshExchangeWithContext(ctx context.Context, resource string) error - EnsureFreshWithContext(ctx context.Context) error -} - -// TokenRefreshCallback is the type representing callbacks that will be called after -// a successful token refresh -type TokenRefreshCallback func(Token) error - -// TokenRefresh is a type representing a custom callback to refresh a token -type TokenRefresh func(ctx context.Context, resource string) (*Token, error) - -// Token encapsulates the access token used to authorize Azure requests. -// https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-oauth2-client-creds-grant-flow#service-to-service-access-token-response -type Token struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - - ExpiresIn json.Number `json:"expires_in"` - ExpiresOn json.Number `json:"expires_on"` - NotBefore json.Number `json:"not_before"` - - Resource string `json:"resource"` - Type string `json:"token_type"` -} - -func newToken() Token { - return Token{ - ExpiresIn: "0", - ExpiresOn: "0", - NotBefore: "0", - } -} - -// IsZero returns true if the token object is zero-initialized. -func (t Token) IsZero() bool { - return t == Token{} -} - -// Expires returns the time.Time when the Token expires. -func (t Token) Expires() time.Time { - s, err := t.ExpiresOn.Float64() - if err != nil { - s = -3600 - } - - expiration := date.NewUnixTimeFromSeconds(s) - - return time.Time(expiration).UTC() -} - -// IsExpired returns true if the Token is expired, false otherwise. -func (t Token) IsExpired() bool { - return t.WillExpireIn(0) -} - -// WillExpireIn returns true if the Token will expire after the passed time.Duration interval -// from now, false otherwise. -func (t Token) WillExpireIn(d time.Duration) bool { - return !t.Expires().After(time.Now().Add(d)) -} - -//OAuthToken return the current access token -func (t *Token) OAuthToken() string { - return t.AccessToken -} - -// ServicePrincipalSecret is an interface that allows various secret mechanism to fill the form -// that is submitted when acquiring an oAuth token. -type ServicePrincipalSecret interface { - SetAuthenticationValues(spt *ServicePrincipalToken, values *url.Values) error -} - -// ServicePrincipalNoSecret represents a secret type that contains no secret -// meaning it is not valid for fetching a fresh token. This is used by Manual -type ServicePrincipalNoSecret struct { -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret -// It only returns an error for the ServicePrincipalNoSecret type -func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - return fmt.Errorf("Manually created ServicePrincipalToken does not contain secret material to retrieve a new access token") -} - -// MarshalJSON implements the json.Marshaler interface. -func (noSecret ServicePrincipalNoSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalNoSecret", - }) -} - -// ServicePrincipalTokenSecret implements ServicePrincipalSecret for client_secret type authorization. -type ServicePrincipalTokenSecret struct { - ClientSecret string `json:"value"` -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -// It will populate the form submitted during oAuth Token Acquisition using the client_secret. -func (tokenSecret *ServicePrincipalTokenSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("client_secret", tokenSecret.ClientSecret) - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (tokenSecret ServicePrincipalTokenSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - Value string `json:"value"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalTokenSecret", - Value: tokenSecret.ClientSecret, - }) -} - -// ServicePrincipalCertificateSecret implements ServicePrincipalSecret for generic RSA cert auth with signed JWTs. -type ServicePrincipalCertificateSecret struct { - Certificate *x509.Certificate - PrivateKey *rsa.PrivateKey -} - -// SignJwt returns the JWT signed with the certificate's private key. -func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) { - hasher := sha1.New() - _, err := hasher.Write(secret.Certificate.Raw) - if err != nil { - return "", err - } - - thumbprint := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) - - // The jti (JWT ID) claim provides a unique identifier for the JWT. - jti := make([]byte, 20) - _, err = rand.Read(jti) - if err != nil { - return "", err - } - - token := jwt.New(jwt.SigningMethodRS256) - token.Header["x5t"] = thumbprint - x5c := []string{base64.StdEncoding.EncodeToString(secret.Certificate.Raw)} - token.Header["x5c"] = x5c - token.Claims = jwt.MapClaims{ - "aud": spt.inner.OauthConfig.TokenEndpoint.String(), - "iss": spt.inner.ClientID, - "sub": spt.inner.ClientID, - "jti": base64.URLEncoding.EncodeToString(jti), - "nbf": time.Now().Unix(), - "exp": time.Now().Add(24 * time.Hour).Unix(), - } - - signedString, err := token.SignedString(secret.PrivateKey) - return signedString, err -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -// It will populate the form submitted during oAuth Token Acquisition using a JWT signed with a certificate. -func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - jwt, err := secret.SignJwt(spt) - if err != nil { - return err - } - - v.Set("client_assertion", jwt) - v.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (secret ServicePrincipalCertificateSecret) MarshalJSON() ([]byte, error) { - return nil, errors.New("marshalling ServicePrincipalCertificateSecret is not supported") -} - -// ServicePrincipalMSISecret implements ServicePrincipalSecret for machines running the MSI Extension. -type ServicePrincipalMSISecret struct { - msiType msiType - clientResourceID string -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (msiSecret *ServicePrincipalMSISecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (msiSecret ServicePrincipalMSISecret) MarshalJSON() ([]byte, error) { - return nil, errors.New("marshalling ServicePrincipalMSISecret is not supported") -} - -// ServicePrincipalUsernamePasswordSecret implements ServicePrincipalSecret for username and password auth. -type ServicePrincipalUsernamePasswordSecret struct { - Username string `json:"username"` - Password string `json:"password"` -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (secret *ServicePrincipalUsernamePasswordSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("username", secret.Username) - v.Set("password", secret.Password) - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (secret ServicePrincipalUsernamePasswordSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - Username string `json:"username"` - Password string `json:"password"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalUsernamePasswordSecret", - Username: secret.Username, - Password: secret.Password, - }) -} - -// ServicePrincipalAuthorizationCodeSecret implements ServicePrincipalSecret for authorization code auth. -type ServicePrincipalAuthorizationCodeSecret struct { - ClientSecret string `json:"value"` - AuthorizationCode string `json:"authCode"` - RedirectURI string `json:"redirect"` -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (secret *ServicePrincipalAuthorizationCodeSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("code", secret.AuthorizationCode) - v.Set("client_secret", secret.ClientSecret) - v.Set("redirect_uri", secret.RedirectURI) - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (secret ServicePrincipalAuthorizationCodeSecret) MarshalJSON() ([]byte, error) { - type tokenType struct { - Type string `json:"type"` - Value string `json:"value"` - AuthCode string `json:"authCode"` - Redirect string `json:"redirect"` - } - return json.Marshal(tokenType{ - Type: "ServicePrincipalAuthorizationCodeSecret", - Value: secret.ClientSecret, - AuthCode: secret.AuthorizationCode, - Redirect: secret.RedirectURI, - }) -} - -// ServicePrincipalToken encapsulates a Token created for a Service Principal. -type ServicePrincipalToken struct { - inner servicePrincipalToken - refreshLock *sync.RWMutex - sender Sender - customRefreshFunc TokenRefresh - refreshCallbacks []TokenRefreshCallback - // MaxMSIRefreshAttempts is the maximum number of attempts to refresh an MSI token. - // Settings this to a value less than 1 will use the default value. - MaxMSIRefreshAttempts int -} - -// MarshalTokenJSON returns the marshalled inner token. -func (spt ServicePrincipalToken) MarshalTokenJSON() ([]byte, error) { - return json.Marshal(spt.inner.Token) -} - -// SetRefreshCallbacks replaces any existing refresh callbacks with the specified callbacks. -func (spt *ServicePrincipalToken) SetRefreshCallbacks(callbacks []TokenRefreshCallback) { - spt.refreshCallbacks = callbacks -} - -// SetCustomRefreshFunc sets a custom refresh function used to refresh the token. -func (spt *ServicePrincipalToken) SetCustomRefreshFunc(customRefreshFunc TokenRefresh) { - spt.customRefreshFunc = customRefreshFunc -} - -// MarshalJSON implements the json.Marshaler interface. -func (spt ServicePrincipalToken) MarshalJSON() ([]byte, error) { - return json.Marshal(spt.inner) -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -func (spt *ServicePrincipalToken) UnmarshalJSON(data []byte) error { - // need to determine the token type - raw := map[string]interface{}{} - err := json.Unmarshal(data, &raw) - if err != nil { - return err - } - secret := raw["secret"].(map[string]interface{}) - switch secret["type"] { - case "ServicePrincipalNoSecret": - spt.inner.Secret = &ServicePrincipalNoSecret{} - case "ServicePrincipalTokenSecret": - spt.inner.Secret = &ServicePrincipalTokenSecret{} - case "ServicePrincipalCertificateSecret": - return errors.New("unmarshalling ServicePrincipalCertificateSecret is not supported") - case "ServicePrincipalMSISecret": - return errors.New("unmarshalling ServicePrincipalMSISecret is not supported") - case "ServicePrincipalUsernamePasswordSecret": - spt.inner.Secret = &ServicePrincipalUsernamePasswordSecret{} - case "ServicePrincipalAuthorizationCodeSecret": - spt.inner.Secret = &ServicePrincipalAuthorizationCodeSecret{} - default: - return fmt.Errorf("unrecognized token type '%s'", secret["type"]) - } - err = json.Unmarshal(data, &spt.inner) - if err != nil { - return err - } - // Don't override the refreshLock or the sender if those have been already set. - if spt.refreshLock == nil { - spt.refreshLock = &sync.RWMutex{} - } - if spt.sender == nil { - spt.sender = sender() - } - return nil -} - -// internal type used for marshalling/unmarshalling -type servicePrincipalToken struct { - Token Token `json:"token"` - Secret ServicePrincipalSecret `json:"secret"` - OauthConfig OAuthConfig `json:"oauth"` - ClientID string `json:"clientID"` - Resource string `json:"resource"` - AutoRefresh bool `json:"autoRefresh"` - RefreshWithin time.Duration `json:"refreshWithin"` -} - -func validateOAuthConfig(oac OAuthConfig) error { - if oac.IsZero() { - return fmt.Errorf("parameter 'oauthConfig' cannot be zero-initialized") - } - return nil -} - -// NewServicePrincipalTokenWithSecret create a ServicePrincipalToken using the supplied ServicePrincipalSecret implementation. -func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, resource string, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(id, "id"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("parameter 'secret' cannot be nil") - } - spt := &ServicePrincipalToken{ - inner: servicePrincipalToken{ - Token: newToken(), - OauthConfig: oauthConfig, - Secret: secret, - ClientID: id, - Resource: resource, - AutoRefresh: true, - RefreshWithin: defaultRefresh, - }, - refreshLock: &sync.RWMutex{}, - sender: sender(), - refreshCallbacks: callbacks, - } - return spt, nil -} - -// NewServicePrincipalTokenFromManualToken creates a ServicePrincipalToken using the supplied token -func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if token.IsZero() { - return nil, fmt.Errorf("parameter 'token' cannot be zero-initialized") - } - spt, err := NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalNoSecret{}, - callbacks...) - if err != nil { - return nil, err - } - - spt.inner.Token = token - - return spt, nil -} - -// NewServicePrincipalTokenFromManualTokenSecret creates a ServicePrincipalToken using the supplied token and secret -func NewServicePrincipalTokenFromManualTokenSecret(oauthConfig OAuthConfig, clientID string, resource string, token Token, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("parameter 'secret' cannot be nil") - } - if token.IsZero() { - return nil, fmt.Errorf("parameter 'token' cannot be zero-initialized") - } - spt, err := NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - secret, - callbacks...) - if err != nil { - return nil, err - } - - spt.inner.Token = token - - return spt, nil -} - -// NewServicePrincipalToken creates a ServicePrincipalToken from the supplied Service Principal -// credentials scoped to the named resource. -func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(secret, "secret"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalTokenSecret{ - ClientSecret: secret, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromCertificate creates a ServicePrincipalToken from the supplied pkcs12 bytes. -func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if certificate == nil { - return nil, fmt.Errorf("parameter 'certificate' cannot be nil") - } - if privateKey == nil { - return nil, fmt.Errorf("parameter 'privateKey' cannot be nil") - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalCertificateSecret{ - PrivateKey: privateKey, - Certificate: certificate, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromUsernamePassword creates a ServicePrincipalToken from the username and password. -func NewServicePrincipalTokenFromUsernamePassword(oauthConfig OAuthConfig, clientID string, username string, password string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(username, "username"); err != nil { - return nil, err - } - if err := validateStringParam(password, "password"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalUsernamePasswordSecret{ - Username: username, - Password: password, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromAuthorizationCode creates a ServicePrincipalToken from the -func NewServicePrincipalTokenFromAuthorizationCode(oauthConfig OAuthConfig, clientID string, clientSecret string, authorizationCode string, redirectURI string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(clientSecret, "clientSecret"); err != nil { - return nil, err - } - if err := validateStringParam(authorizationCode, "authorizationCode"); err != nil { - return nil, err - } - if err := validateStringParam(redirectURI, "redirectURI"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalAuthorizationCodeSecret{ - ClientSecret: clientSecret, - AuthorizationCode: authorizationCode, - RedirectURI: redirectURI, - }, - callbacks..., - ) -} - -type msiType int - -const ( - msiTypeUnavailable msiType = iota - msiTypeAppServiceV20170901 - msiTypeCloudShell - msiTypeIMDS -) - -func (m msiType) String() string { - switch m { - case msiTypeUnavailable: - return "unavailable" - case msiTypeAppServiceV20170901: - return "AppServiceV20170901" - case msiTypeCloudShell: - return "CloudShell" - case msiTypeIMDS: - return "IMDS" - default: - return fmt.Sprintf("unhandled MSI type %d", m) - } -} - -// returns the MSI type and endpoint, or an error -func getMSIType() (msiType, string, error) { - if endpointEnvVar := os.Getenv(msiEndpointEnv); endpointEnvVar != "" { - // if the env var MSI_ENDPOINT is set - if secretEnvVar := os.Getenv(msiSecretEnv); secretEnvVar != "" { - // if BOTH the env vars MSI_ENDPOINT and MSI_SECRET are set the msiType is AppService - return msiTypeAppServiceV20170901, endpointEnvVar, nil - } - // if ONLY the env var MSI_ENDPOINT is set the msiType is CloudShell - return msiTypeCloudShell, endpointEnvVar, nil - } else if msiAvailableHook(context.Background(), sender()) { - // if MSI_ENDPOINT is NOT set AND the IMDS endpoint is available the msiType is IMDS. This will timeout after 500 milliseconds - return msiTypeIMDS, msiEndpoint, nil - } else { - // if MSI_ENDPOINT is NOT set and IMDS endpoint is not available Managed Identity is not available - return msiTypeUnavailable, "", errors.New("MSI not available") - } -} - -// GetMSIVMEndpoint gets the MSI endpoint on Virtual Machines. -// NOTE: this always returns the IMDS endpoint, it does not work for app services or cloud shell. -// Deprecated: NewServicePrincipalTokenFromMSI() and variants will automatically detect the endpoint. -func GetMSIVMEndpoint() (string, error) { - return msiEndpoint, nil -} - -// GetMSIAppServiceEndpoint get the MSI endpoint for App Service and Functions. -// It will return an error when not running in an app service/functions environment. -// Deprecated: NewServicePrincipalTokenFromMSI() and variants will automatically detect the endpoint. -func GetMSIAppServiceEndpoint() (string, error) { - msiType, endpoint, err := getMSIType() - if err != nil { - return "", err - } - switch msiType { - case msiTypeAppServiceV20170901: - return endpoint, nil - default: - return "", fmt.Errorf("%s is not app service environment", msiType) - } -} - -// GetMSIEndpoint get the appropriate MSI endpoint depending on the runtime environment -// Deprecated: NewServicePrincipalTokenFromMSI() and variants will automatically detect the endpoint. -func GetMSIEndpoint() (string, error) { - _, endpoint, err := getMSIType() - return endpoint, err -} - -// NewServicePrincipalTokenFromMSI creates a ServicePrincipalToken via the MSI VM Extension. -// It will use the system assigned identity when creating the token. -// msiEndpoint - empty string, or pass a non-empty string to override the default value. -// Deprecated: use NewServicePrincipalTokenFromManagedIdentity() instead. -func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - return newServicePrincipalTokenFromMSI(msiEndpoint, resource, "", "", callbacks...) -} - -// NewServicePrincipalTokenFromMSIWithUserAssignedID creates a ServicePrincipalToken via the MSI VM Extension. -// It will use the clientID of specified user assigned identity when creating the token. -// msiEndpoint - empty string, or pass a non-empty string to override the default value. -// Deprecated: use NewServicePrincipalTokenFromManagedIdentity() instead. -func NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, resource string, userAssignedID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateStringParam(userAssignedID, "userAssignedID"); err != nil { - return nil, err - } - return newServicePrincipalTokenFromMSI(msiEndpoint, resource, userAssignedID, "", callbacks...) -} - -// NewServicePrincipalTokenFromMSIWithIdentityResourceID creates a ServicePrincipalToken via the MSI VM Extension. -// It will use the azure resource id of user assigned identity when creating the token. -// msiEndpoint - empty string, or pass a non-empty string to override the default value. -// Deprecated: use NewServicePrincipalTokenFromManagedIdentity() instead. -func NewServicePrincipalTokenFromMSIWithIdentityResourceID(msiEndpoint, resource string, identityResourceID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateStringParam(identityResourceID, "identityResourceID"); err != nil { - return nil, err - } - return newServicePrincipalTokenFromMSI(msiEndpoint, resource, "", identityResourceID, callbacks...) -} - -// ManagedIdentityOptions contains optional values for configuring managed identity authentication. -type ManagedIdentityOptions struct { - // ClientID is the user-assigned identity to use during authentication. - // It is mutually exclusive with IdentityResourceID. - ClientID string - - // IdentityResourceID is the resource ID of the user-assigned identity to use during authentication. - // It is mutually exclusive with ClientID. - IdentityResourceID string -} - -// NewServicePrincipalTokenFromManagedIdentity creates a ServicePrincipalToken using a managed identity. -// It supports the following managed identity environments. -// - App Service Environment (API version 2017-09-01 only) -// - Cloud shell -// - IMDS with a system or user assigned identity -func NewServicePrincipalTokenFromManagedIdentity(resource string, options *ManagedIdentityOptions, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if options == nil { - options = &ManagedIdentityOptions{} - } - return newServicePrincipalTokenFromMSI("", resource, options.ClientID, options.IdentityResourceID, callbacks...) -} - -func newServicePrincipalTokenFromMSI(msiEndpoint, resource, userAssignedID, identityResourceID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if userAssignedID != "" && identityResourceID != "" { - return nil, errors.New("cannot specify userAssignedID and identityResourceID") - } - msiType, endpoint, err := getMSIType() - if err != nil { - logger.Instance.Writef(logger.LogError, "Error determining managed identity environment: %v", err) - return nil, err - } - logger.Instance.Writef(logger.LogInfo, "Managed identity environment is %s, endpoint is %s", msiType, endpoint) - if msiEndpoint != "" { - endpoint = msiEndpoint - logger.Instance.Writef(logger.LogInfo, "Managed identity custom endpoint is %s", endpoint) - } - msiEndpointURL, err := url.Parse(endpoint) - if err != nil { - return nil, err - } - // cloud shell sends its data in the request body - if msiType != msiTypeCloudShell { - v := url.Values{} - v.Set("resource", resource) - clientIDParam := "client_id" - switch msiType { - case msiTypeAppServiceV20170901: - clientIDParam = "clientid" - v.Set("api-version", appServiceAPIVersion2017) - break - case msiTypeIMDS: - v.Set("api-version", msiAPIVersion) - } - if userAssignedID != "" { - v.Set(clientIDParam, userAssignedID) - } else if identityResourceID != "" { - v.Set("mi_res_id", identityResourceID) - } - msiEndpointURL.RawQuery = v.Encode() - } - - spt := &ServicePrincipalToken{ - inner: servicePrincipalToken{ - Token: newToken(), - OauthConfig: OAuthConfig{ - TokenEndpoint: *msiEndpointURL, - }, - Secret: &ServicePrincipalMSISecret{ - msiType: msiType, - clientResourceID: identityResourceID, - }, - Resource: resource, - AutoRefresh: true, - RefreshWithin: defaultRefresh, - ClientID: userAssignedID, - }, - refreshLock: &sync.RWMutex{}, - sender: sender(), - refreshCallbacks: callbacks, - MaxMSIRefreshAttempts: defaultMaxMSIRefreshAttempts, - } - - return spt, nil -} - -// internal type that implements TokenRefreshError -type tokenRefreshError struct { - message string - resp *http.Response -} - -// Error implements the error interface which is part of the TokenRefreshError interface. -func (tre tokenRefreshError) Error() string { - return tre.message -} - -// Response implements the TokenRefreshError interface, it returns the raw HTTP response from the refresh operation. -func (tre tokenRefreshError) Response() *http.Response { - return tre.resp -} - -func newTokenRefreshError(message string, resp *http.Response) TokenRefreshError { - return tokenRefreshError{message: message, resp: resp} -} - -// EnsureFresh will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. -func (spt *ServicePrincipalToken) EnsureFresh() error { - return spt.EnsureFreshWithContext(context.Background()) -} - -// EnsureFreshWithContext will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. -func (spt *ServicePrincipalToken) EnsureFreshWithContext(ctx context.Context) error { - // must take the read lock when initially checking the token's expiration - if spt.inner.AutoRefresh && spt.Token().WillExpireIn(spt.inner.RefreshWithin) { - // take the write lock then check again to see if the token was already refreshed - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - if spt.inner.Token.WillExpireIn(spt.inner.RefreshWithin) { - return spt.refreshInternal(ctx, spt.inner.Resource) - } - } - return nil -} - -// InvokeRefreshCallbacks calls any TokenRefreshCallbacks that were added to the SPT during initialization -func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error { - if spt.refreshCallbacks != nil { - for _, callback := range spt.refreshCallbacks { - err := callback(spt.inner.Token) - if err != nil { - return fmt.Errorf("adal: TokenRefreshCallback handler failed. Error = '%v'", err) - } - } - } - return nil -} - -// Refresh obtains a fresh token for the Service Principal. -// This method is safe for concurrent use. -func (spt *ServicePrincipalToken) Refresh() error { - return spt.RefreshWithContext(context.Background()) -} - -// RefreshWithContext obtains a fresh token for the Service Principal. -// This method is safe for concurrent use. -func (spt *ServicePrincipalToken) RefreshWithContext(ctx context.Context) error { - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - return spt.refreshInternal(ctx, spt.inner.Resource) -} - -// RefreshExchange refreshes the token, but for a different resource. -// This method is safe for concurrent use. -func (spt *ServicePrincipalToken) RefreshExchange(resource string) error { - return spt.RefreshExchangeWithContext(context.Background(), resource) -} - -// RefreshExchangeWithContext refreshes the token, but for a different resource. -// This method is safe for concurrent use. -func (spt *ServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error { - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - return spt.refreshInternal(ctx, resource) -} - -func (spt *ServicePrincipalToken) getGrantType() string { - switch spt.inner.Secret.(type) { - case *ServicePrincipalUsernamePasswordSecret: - return OAuthGrantTypeUserPass - case *ServicePrincipalAuthorizationCodeSecret: - return OAuthGrantTypeAuthorizationCode - default: - return OAuthGrantTypeClientCredentials - } -} - -func (spt *ServicePrincipalToken) refreshInternal(ctx context.Context, resource string) error { - if spt.customRefreshFunc != nil { - token, err := spt.customRefreshFunc(ctx, resource) - if err != nil { - return err - } - spt.inner.Token = *token - return spt.InvokeRefreshCallbacks(spt.inner.Token) - } - req, err := http.NewRequest(http.MethodPost, spt.inner.OauthConfig.TokenEndpoint.String(), nil) - if err != nil { - return fmt.Errorf("adal: Failed to build the refresh request. Error = '%v'", err) - } - req.Header.Add("User-Agent", UserAgent()) - req = req.WithContext(ctx) - var resp *http.Response - authBodyFilter := func(b []byte) []byte { - if logger.Level() != logger.LogAuth { - return []byte("**REDACTED** authentication body") - } - return b - } - if msiSecret, ok := spt.inner.Secret.(*ServicePrincipalMSISecret); ok { - switch msiSecret.msiType { - case msiTypeAppServiceV20170901: - req.Method = http.MethodGet - req.Header.Set("secret", os.Getenv(msiSecretEnv)) - break - case msiTypeCloudShell: - req.Header.Set("Metadata", "true") - data := url.Values{} - data.Set("resource", spt.inner.Resource) - if spt.inner.ClientID != "" { - data.Set("client_id", spt.inner.ClientID) - } else if msiSecret.clientResourceID != "" { - data.Set("msi_res_id", msiSecret.clientResourceID) - } - req.Body = ioutil.NopCloser(strings.NewReader(data.Encode())) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - break - case msiTypeIMDS: - req.Method = http.MethodGet - req.Header.Set("Metadata", "true") - break - } - logger.Instance.WriteRequest(req, logger.Filter{Body: authBodyFilter}) - resp, err = retryForIMDS(spt.sender, req, spt.MaxMSIRefreshAttempts) - } else { - v := url.Values{} - v.Set("client_id", spt.inner.ClientID) - v.Set("resource", resource) - - if spt.inner.Token.RefreshToken != "" { - v.Set("grant_type", OAuthGrantTypeRefreshToken) - v.Set("refresh_token", spt.inner.Token.RefreshToken) - // web apps must specify client_secret when refreshing tokens - // see https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code#refreshing-the-access-tokens - if spt.getGrantType() == OAuthGrantTypeAuthorizationCode { - err := spt.inner.Secret.SetAuthenticationValues(spt, &v) - if err != nil { - return err - } - } - } else { - v.Set("grant_type", spt.getGrantType()) - err := spt.inner.Secret.SetAuthenticationValues(spt, &v) - if err != nil { - return err - } - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - req.Body = body - logger.Instance.WriteRequest(req, logger.Filter{Body: authBodyFilter}) - resp, err = spt.sender.Do(req) - } - - // don't return a TokenRefreshError here; this will allow retry logic to apply - if err != nil { - return fmt.Errorf("adal: Failed to execute the refresh request. Error = '%v'", err) - } else if resp == nil { - return fmt.Errorf("adal: received nil response and error") - } - - logger.Instance.WriteResponse(resp, logger.Filter{Body: authBodyFilter}) - defer resp.Body.Close() - rb, err := ioutil.ReadAll(resp.Body) - - if resp.StatusCode != http.StatusOK { - if err != nil { - return newTokenRefreshError(fmt.Sprintf("adal: Refresh request failed. Status Code = '%d'. Failed reading response body: %v Endpoint %s", resp.StatusCode, err, req.URL.String()), resp) - } - return newTokenRefreshError(fmt.Sprintf("adal: Refresh request failed. Status Code = '%d'. Response body: %s Endpoint %s", resp.StatusCode, string(rb), req.URL.String()), resp) - } - - // for the following error cases don't return a TokenRefreshError. the operation succeeded - // but some transient failure happened during deserialization. by returning a generic error - // the retry logic will kick in (we don't retry on TokenRefreshError). - - if err != nil { - return fmt.Errorf("adal: Failed to read a new service principal token during refresh. Error = '%v'", err) - } - if len(strings.Trim(string(rb), " ")) == 0 { - return fmt.Errorf("adal: Empty service principal token received during refresh") - } - token := struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - - // AAD returns expires_in as a string, ADFS returns it as an int - ExpiresIn json.Number `json:"expires_in"` - // expires_on can be in two formats, a UTC time stamp or the number of seconds. - ExpiresOn string `json:"expires_on"` - NotBefore json.Number `json:"not_before"` - - Resource string `json:"resource"` - Type string `json:"token_type"` - }{} - // return a TokenRefreshError in the follow error cases as the token is in an unexpected format - err = json.Unmarshal(rb, &token) - if err != nil { - return newTokenRefreshError(fmt.Sprintf("adal: Failed to unmarshal the service principal token during refresh. Error = '%v' JSON = '%s'", err, string(rb)), resp) - } - expiresOn := json.Number("") - // ADFS doesn't include the expires_on field - if token.ExpiresOn != "" { - if expiresOn, err = parseExpiresOn(token.ExpiresOn); err != nil { - return newTokenRefreshError(fmt.Sprintf("adal: failed to parse expires_on: %v value '%s'", err, token.ExpiresOn), resp) - } - } - spt.inner.Token.AccessToken = token.AccessToken - spt.inner.Token.RefreshToken = token.RefreshToken - spt.inner.Token.ExpiresIn = token.ExpiresIn - spt.inner.Token.ExpiresOn = expiresOn - spt.inner.Token.NotBefore = token.NotBefore - spt.inner.Token.Resource = token.Resource - spt.inner.Token.Type = token.Type - - return spt.InvokeRefreshCallbacks(spt.inner.Token) -} - -// converts expires_on to the number of seconds -func parseExpiresOn(s string) (json.Number, error) { - // convert the expiration date to the number of seconds from now - timeToDuration := func(t time.Time) json.Number { - dur := t.Sub(time.Now().UTC()) - return json.Number(strconv.FormatInt(int64(dur.Round(time.Second).Seconds()), 10)) - } - if _, err := strconv.ParseInt(s, 10, 64); err == nil { - // this is the number of seconds case, no conversion required - return json.Number(s), nil - } else if eo, err := time.Parse(expiresOnDateFormatPM, s); err == nil { - return timeToDuration(eo), nil - } else if eo, err := time.Parse(expiresOnDateFormat, s); err == nil { - return timeToDuration(eo), nil - } else { - // unknown format - return json.Number(""), err - } -} - -// retry logic specific to retrieving a token from the IMDS endpoint -func retryForIMDS(sender Sender, req *http.Request, maxAttempts int) (resp *http.Response, err error) { - // copied from client.go due to circular dependency - retries := []int{ - http.StatusRequestTimeout, // 408 - http.StatusTooManyRequests, // 429 - http.StatusInternalServerError, // 500 - http.StatusBadGateway, // 502 - http.StatusServiceUnavailable, // 503 - http.StatusGatewayTimeout, // 504 - } - // extra retry status codes specific to IMDS - retries = append(retries, - http.StatusNotFound, - http.StatusGone, - // all remaining 5xx - http.StatusNotImplemented, - http.StatusHTTPVersionNotSupported, - http.StatusVariantAlsoNegotiates, - http.StatusInsufficientStorage, - http.StatusLoopDetected, - http.StatusNotExtended, - http.StatusNetworkAuthenticationRequired) - - // see https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/how-to-use-vm-token#retry-guidance - - const maxDelay time.Duration = 60 * time.Second - - attempt := 0 - delay := time.Duration(0) - - // maxAttempts is user-specified, ensure that its value is greater than zero else no request will be made - if maxAttempts < 1 { - maxAttempts = defaultMaxMSIRefreshAttempts - } - - for attempt < maxAttempts { - if resp != nil && resp.Body != nil { - io.Copy(ioutil.Discard, resp.Body) - resp.Body.Close() - } - resp, err = sender.Do(req) - // we want to retry if err is not nil or the status code is in the list of retry codes - if err == nil && !responseHasStatusCode(resp, retries...) { - return - } - - // perform exponential backoff with a cap. - // must increment attempt before calculating delay. - attempt++ - // the base value of 2 is the "delta backoff" as specified in the guidance doc - delay += (time.Duration(math.Pow(2, float64(attempt))) * time.Second) - if delay > maxDelay { - delay = maxDelay - } - - select { - case <-time.After(delay): - // intentionally left blank - case <-req.Context().Done(): - err = req.Context().Err() - return - } - } - return -} - -func responseHasStatusCode(resp *http.Response, codes ...int) bool { - if resp != nil { - for _, i := range codes { - if i == resp.StatusCode { - return true - } - } - } - return false -} - -// SetAutoRefresh enables or disables automatic refreshing of stale tokens. -func (spt *ServicePrincipalToken) SetAutoRefresh(autoRefresh bool) { - spt.inner.AutoRefresh = autoRefresh -} - -// SetRefreshWithin sets the interval within which if the token will expire, EnsureFresh will -// refresh the token. -func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration) { - spt.inner.RefreshWithin = d - return -} - -// SetSender sets the http.Client used when obtaining the Service Principal token. An -// undecorated http.Client is used by default. -func (spt *ServicePrincipalToken) SetSender(s Sender) { spt.sender = s } - -// OAuthToken implements the OAuthTokenProvider interface. It returns the current access token. -func (spt *ServicePrincipalToken) OAuthToken() string { - spt.refreshLock.RLock() - defer spt.refreshLock.RUnlock() - return spt.inner.Token.OAuthToken() -} - -// Token returns a copy of the current token. -func (spt *ServicePrincipalToken) Token() Token { - spt.refreshLock.RLock() - defer spt.refreshLock.RUnlock() - return spt.inner.Token -} - -// MultiTenantServicePrincipalToken contains tokens for multi-tenant authorization. -type MultiTenantServicePrincipalToken struct { - PrimaryToken *ServicePrincipalToken - AuxiliaryTokens []*ServicePrincipalToken -} - -// PrimaryOAuthToken returns the primary authorization token. -func (mt *MultiTenantServicePrincipalToken) PrimaryOAuthToken() string { - return mt.PrimaryToken.OAuthToken() -} - -// AuxiliaryOAuthTokens returns one to three auxiliary authorization tokens. -func (mt *MultiTenantServicePrincipalToken) AuxiliaryOAuthTokens() []string { - tokens := make([]string, len(mt.AuxiliaryTokens)) - for i := range mt.AuxiliaryTokens { - tokens[i] = mt.AuxiliaryTokens[i].OAuthToken() - } - return tokens -} - -// NewMultiTenantServicePrincipalToken creates a new MultiTenantServicePrincipalToken with the specified credentials and resource. -func NewMultiTenantServicePrincipalToken(multiTenantCfg MultiTenantOAuthConfig, clientID string, secret string, resource string) (*MultiTenantServicePrincipalToken, error) { - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(secret, "secret"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - auxTenants := multiTenantCfg.AuxiliaryTenants() - m := MultiTenantServicePrincipalToken{ - AuxiliaryTokens: make([]*ServicePrincipalToken, len(auxTenants)), - } - primary, err := NewServicePrincipalToken(*multiTenantCfg.PrimaryTenant(), clientID, secret, resource) - if err != nil { - return nil, fmt.Errorf("failed to create SPT for primary tenant: %v", err) - } - m.PrimaryToken = primary - for i := range auxTenants { - aux, err := NewServicePrincipalToken(*auxTenants[i], clientID, secret, resource) - if err != nil { - return nil, fmt.Errorf("failed to create SPT for auxiliary tenant: %v", err) - } - m.AuxiliaryTokens[i] = aux - } - return &m, nil -} - -// NewMultiTenantServicePrincipalTokenFromCertificate creates a new MultiTenantServicePrincipalToken with the specified certificate credentials and resource. -func NewMultiTenantServicePrincipalTokenFromCertificate(multiTenantCfg MultiTenantOAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string) (*MultiTenantServicePrincipalToken, error) { - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if certificate == nil { - return nil, fmt.Errorf("parameter 'certificate' cannot be nil") - } - if privateKey == nil { - return nil, fmt.Errorf("parameter 'privateKey' cannot be nil") - } - auxTenants := multiTenantCfg.AuxiliaryTenants() - m := MultiTenantServicePrincipalToken{ - AuxiliaryTokens: make([]*ServicePrincipalToken, len(auxTenants)), - } - primary, err := NewServicePrincipalTokenWithSecret( - *multiTenantCfg.PrimaryTenant(), - clientID, - resource, - &ServicePrincipalCertificateSecret{ - PrivateKey: privateKey, - Certificate: certificate, - }, - ) - if err != nil { - return nil, fmt.Errorf("failed to create SPT for primary tenant: %v", err) - } - m.PrimaryToken = primary - for i := range auxTenants { - aux, err := NewServicePrincipalTokenWithSecret( - *auxTenants[i], - clientID, - resource, - &ServicePrincipalCertificateSecret{ - PrivateKey: privateKey, - Certificate: certificate, - }, - ) - if err != nil { - return nil, fmt.Errorf("failed to create SPT for auxiliary tenant: %v", err) - } - m.AuxiliaryTokens[i] = aux - } - return &m, nil -} - -// MSIAvailable returns true if the MSI endpoint is available for authentication. -func MSIAvailable(ctx context.Context, sender Sender) bool { - resp, err := getMSIEndpoint(ctx, sender) - if err == nil { - resp.Body.Close() - } - return err == nil -} - -// used for testing purposes -var msiAvailableHook = func(ctx context.Context, sender Sender) bool { - return MSIAvailable(ctx, sender) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/token_1.13.go b/vendor/github.com/Azure/go-autorest/autorest/adal/token_1.13.go deleted file mode 100644 index 953f7550..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/token_1.13.go +++ /dev/null @@ -1,75 +0,0 @@ -// +build go1.13 - -// Copyright 2017 Microsoft Corporation -// -// 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 adal - -import ( - "context" - "fmt" - "net/http" - "time" -) - -func getMSIEndpoint(ctx context.Context, sender Sender) (*http.Response, error) { - tempCtx, cancel := context.WithTimeout(ctx, 500*time.Millisecond) - defer cancel() - // http.NewRequestWithContext() was added in Go 1.13 - req, _ := http.NewRequestWithContext(tempCtx, http.MethodGet, msiEndpoint, nil) - q := req.URL.Query() - q.Add("api-version", msiAPIVersion) - req.URL.RawQuery = q.Encode() - return sender.Do(req) -} - -// EnsureFreshWithContext will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. -func (mt *MultiTenantServicePrincipalToken) EnsureFreshWithContext(ctx context.Context) error { - if err := mt.PrimaryToken.EnsureFreshWithContext(ctx); err != nil { - return fmt.Errorf("failed to refresh primary token: %w", err) - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.EnsureFreshWithContext(ctx); err != nil { - return fmt.Errorf("failed to refresh auxiliary token: %w", err) - } - } - return nil -} - -// RefreshWithContext obtains a fresh token for the Service Principal. -func (mt *MultiTenantServicePrincipalToken) RefreshWithContext(ctx context.Context) error { - if err := mt.PrimaryToken.RefreshWithContext(ctx); err != nil { - return fmt.Errorf("failed to refresh primary token: %w", err) - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.RefreshWithContext(ctx); err != nil { - return fmt.Errorf("failed to refresh auxiliary token: %w", err) - } - } - return nil -} - -// RefreshExchangeWithContext refreshes the token, but for a different resource. -func (mt *MultiTenantServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error { - if err := mt.PrimaryToken.RefreshExchangeWithContext(ctx, resource); err != nil { - return fmt.Errorf("failed to refresh primary token: %w", err) - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.RefreshExchangeWithContext(ctx, resource); err != nil { - return fmt.Errorf("failed to refresh auxiliary token: %w", err) - } - } - return nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/token_legacy.go b/vendor/github.com/Azure/go-autorest/autorest/adal/token_legacy.go deleted file mode 100644 index 729bfbd0..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/token_legacy.go +++ /dev/null @@ -1,74 +0,0 @@ -// +build !go1.13 - -// Copyright 2017 Microsoft Corporation -// -// 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 adal - -import ( - "context" - "net/http" - "time" -) - -func getMSIEndpoint(ctx context.Context, sender Sender) (*http.Response, error) { - tempCtx, cancel := context.WithTimeout(ctx, 500*time.Millisecond) - defer cancel() - req, _ := http.NewRequest(http.MethodGet, msiEndpoint, nil) - req = req.WithContext(tempCtx) - q := req.URL.Query() - q.Add("api-version", msiAPIVersion) - req.URL.RawQuery = q.Encode() - return sender.Do(req) -} - -// EnsureFreshWithContext will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. -func (mt *MultiTenantServicePrincipalToken) EnsureFreshWithContext(ctx context.Context) error { - if err := mt.PrimaryToken.EnsureFreshWithContext(ctx); err != nil { - return err - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.EnsureFreshWithContext(ctx); err != nil { - return err - } - } - return nil -} - -// RefreshWithContext obtains a fresh token for the Service Principal. -func (mt *MultiTenantServicePrincipalToken) RefreshWithContext(ctx context.Context) error { - if err := mt.PrimaryToken.RefreshWithContext(ctx); err != nil { - return err - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.RefreshWithContext(ctx); err != nil { - return err - } - } - return nil -} - -// RefreshExchangeWithContext refreshes the token, but for a different resource. -func (mt *MultiTenantServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error { - if err := mt.PrimaryToken.RefreshExchangeWithContext(ctx, resource); err != nil { - return err - } - for _, aux := range mt.AuxiliaryTokens { - if err := aux.RefreshExchangeWithContext(ctx, resource); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/version.go b/vendor/github.com/Azure/go-autorest/autorest/adal/version.go deleted file mode 100644 index c867b348..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/version.go +++ /dev/null @@ -1,45 +0,0 @@ -package adal - -import ( - "fmt" - "runtime" -) - -// Copyright 2017 Microsoft Corporation -// -// 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. - -const number = "v1.0.0" - -var ( - ua = fmt.Sprintf("Go/%s (%s-%s) go-autorest/adal/%s", - runtime.Version(), - runtime.GOARCH, - runtime.GOOS, - number, - ) -) - -// UserAgent returns a string containing the Go version, system architecture and OS, and the adal version. -func UserAgent() string { - return ua -} - -// AddToUserAgent adds an extension to the current user agent -func AddToUserAgent(extension string) error { - if extension != "" { - ua = fmt.Sprintf("%s %s", ua, extension) - return nil - } - return fmt.Errorf("Extension was empty, User Agent remained as '%s'", ua) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/authorization.go b/vendor/github.com/Azure/go-autorest/autorest/authorization.go deleted file mode 100644 index 1226c411..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/authorization.go +++ /dev/null @@ -1,353 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "crypto/tls" - "encoding/base64" - "fmt" - "net/http" - "net/url" - "strings" - - "github.com/Azure/go-autorest/autorest/adal" -) - -const ( - bearerChallengeHeader = "Www-Authenticate" - bearer = "Bearer" - tenantID = "tenantID" - apiKeyAuthorizerHeader = "Ocp-Apim-Subscription-Key" - bingAPISdkHeader = "X-BingApis-SDK-Client" - golangBingAPISdkHeaderValue = "Go-SDK" - authorization = "Authorization" - basic = "Basic" -) - -// Authorizer is the interface that provides a PrepareDecorator used to supply request -// authorization. Most often, the Authorizer decorator runs last so it has access to the full -// state of the formed HTTP request. -type Authorizer interface { - WithAuthorization() PrepareDecorator -} - -// NullAuthorizer implements a default, "do nothing" Authorizer. -type NullAuthorizer struct{} - -// WithAuthorization returns a PrepareDecorator that does nothing. -func (na NullAuthorizer) WithAuthorization() PrepareDecorator { - return WithNothing() -} - -// APIKeyAuthorizer implements API Key authorization. -type APIKeyAuthorizer struct { - headers map[string]interface{} - queryParameters map[string]interface{} -} - -// NewAPIKeyAuthorizerWithHeaders creates an ApiKeyAuthorizer with headers. -func NewAPIKeyAuthorizerWithHeaders(headers map[string]interface{}) *APIKeyAuthorizer { - return NewAPIKeyAuthorizer(headers, nil) -} - -// NewAPIKeyAuthorizerWithQueryParameters creates an ApiKeyAuthorizer with query parameters. -func NewAPIKeyAuthorizerWithQueryParameters(queryParameters map[string]interface{}) *APIKeyAuthorizer { - return NewAPIKeyAuthorizer(nil, queryParameters) -} - -// NewAPIKeyAuthorizer creates an ApiKeyAuthorizer with headers. -func NewAPIKeyAuthorizer(headers map[string]interface{}, queryParameters map[string]interface{}) *APIKeyAuthorizer { - return &APIKeyAuthorizer{headers: headers, queryParameters: queryParameters} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP headers and Query Parameters. -func (aka *APIKeyAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return DecoratePreparer(p, WithHeaders(aka.headers), WithQueryParameters(aka.queryParameters)) - } -} - -// CognitiveServicesAuthorizer implements authorization for Cognitive Services. -type CognitiveServicesAuthorizer struct { - subscriptionKey string -} - -// NewCognitiveServicesAuthorizer is -func NewCognitiveServicesAuthorizer(subscriptionKey string) *CognitiveServicesAuthorizer { - return &CognitiveServicesAuthorizer{subscriptionKey: subscriptionKey} -} - -// WithAuthorization is -func (csa *CognitiveServicesAuthorizer) WithAuthorization() PrepareDecorator { - headers := make(map[string]interface{}) - headers[apiKeyAuthorizerHeader] = csa.subscriptionKey - headers[bingAPISdkHeader] = golangBingAPISdkHeaderValue - - return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() -} - -// BearerAuthorizer implements the bearer authorization -type BearerAuthorizer struct { - tokenProvider adal.OAuthTokenProvider -} - -// NewBearerAuthorizer crates a BearerAuthorizer using the given token provider -func NewBearerAuthorizer(tp adal.OAuthTokenProvider) *BearerAuthorizer { - return &BearerAuthorizer{tokenProvider: tp} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Bearer " followed by the token. -// -// By default, the token will be automatically refreshed through the Refresher interface. -func (ba *BearerAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - // the ordering is important here, prefer RefresherWithContext if available - if refresher, ok := ba.tokenProvider.(adal.RefresherWithContext); ok { - err = refresher.EnsureFreshWithContext(r.Context()) - } else if refresher, ok := ba.tokenProvider.(adal.Refresher); ok { - err = refresher.EnsureFresh() - } - if err != nil { - var resp *http.Response - if tokError, ok := err.(adal.TokenRefreshError); ok { - resp = tokError.Response() - } - return r, NewErrorWithError(err, "azure.BearerAuthorizer", "WithAuthorization", resp, - "Failed to refresh the Token for request to %s", r.URL) - } - return Prepare(r, WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", ba.tokenProvider.OAuthToken()))) - } - return r, err - }) - } -} - -// TokenProvider returns OAuthTokenProvider so that it can be used for authorization outside the REST. -func (ba *BearerAuthorizer) TokenProvider() adal.OAuthTokenProvider { - return ba.tokenProvider -} - -// BearerAuthorizerCallbackFunc is the authentication callback signature. -type BearerAuthorizerCallbackFunc func(tenantID, resource string) (*BearerAuthorizer, error) - -// BearerAuthorizerCallback implements bearer authorization via a callback. -type BearerAuthorizerCallback struct { - sender Sender - callback BearerAuthorizerCallbackFunc -} - -// NewBearerAuthorizerCallback creates a bearer authorization callback. The callback -// is invoked when the HTTP request is submitted. -func NewBearerAuthorizerCallback(s Sender, callback BearerAuthorizerCallbackFunc) *BearerAuthorizerCallback { - if s == nil { - s = sender(tls.RenegotiateNever) - } - return &BearerAuthorizerCallback{sender: s, callback: callback} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose value -// is "Bearer " followed by the token. The BearerAuthorizer is obtained via a user-supplied callback. -// -// By default, the token will be automatically refreshed through the Refresher interface. -func (bacb *BearerAuthorizerCallback) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - // make a copy of the request and remove the body as it's not - // required and avoids us having to create a copy of it. - rCopy := *r - removeRequestBody(&rCopy) - - resp, err := bacb.sender.Do(&rCopy) - if err != nil { - return r, err - } - DrainResponseBody(resp) - if resp.StatusCode == 401 && hasBearerChallenge(resp.Header) { - bc, err := newBearerChallenge(resp.Header) - if err != nil { - return r, err - } - if bacb.callback != nil { - ba, err := bacb.callback(bc.values[tenantID], bc.values["resource"]) - if err != nil { - return r, err - } - return Prepare(r, ba.WithAuthorization()) - } - } - } - return r, err - }) - } -} - -// returns true if the HTTP response contains a bearer challenge -func hasBearerChallenge(header http.Header) bool { - authHeader := header.Get(bearerChallengeHeader) - if len(authHeader) == 0 || strings.Index(authHeader, bearer) < 0 { - return false - } - return true -} - -type bearerChallenge struct { - values map[string]string -} - -func newBearerChallenge(header http.Header) (bc bearerChallenge, err error) { - challenge := strings.TrimSpace(header.Get(bearerChallengeHeader)) - trimmedChallenge := challenge[len(bearer)+1:] - - // challenge is a set of key=value pairs that are comma delimited - pairs := strings.Split(trimmedChallenge, ",") - if len(pairs) < 1 { - err = fmt.Errorf("challenge '%s' contains no pairs", challenge) - return bc, err - } - - bc.values = make(map[string]string) - for i := range pairs { - trimmedPair := strings.TrimSpace(pairs[i]) - pair := strings.Split(trimmedPair, "=") - if len(pair) == 2 { - // remove the enclosing quotes - key := strings.Trim(pair[0], "\"") - value := strings.Trim(pair[1], "\"") - - switch key { - case "authorization", "authorization_uri": - // strip the tenant ID from the authorization URL - asURL, err := url.Parse(value) - if err != nil { - return bc, err - } - bc.values[tenantID] = asURL.Path[1:] - default: - bc.values[key] = value - } - } - } - - return bc, err -} - -// EventGridKeyAuthorizer implements authorization for event grid using key authentication. -type EventGridKeyAuthorizer struct { - topicKey string -} - -// NewEventGridKeyAuthorizer creates a new EventGridKeyAuthorizer -// with the specified topic key. -func NewEventGridKeyAuthorizer(topicKey string) EventGridKeyAuthorizer { - return EventGridKeyAuthorizer{topicKey: topicKey} -} - -// WithAuthorization returns a PrepareDecorator that adds the aeg-sas-key authentication header. -func (egta EventGridKeyAuthorizer) WithAuthorization() PrepareDecorator { - headers := map[string]interface{}{ - "aeg-sas-key": egta.topicKey, - } - return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() -} - -// BasicAuthorizer implements basic HTTP authorization by adding the Authorization HTTP header -// with the value "Basic " where is a base64-encoded username:password tuple. -type BasicAuthorizer struct { - userName string - password string -} - -// NewBasicAuthorizer creates a new BasicAuthorizer with the specified username and password. -func NewBasicAuthorizer(userName, password string) *BasicAuthorizer { - return &BasicAuthorizer{ - userName: userName, - password: password, - } -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Basic " followed by the base64-encoded username:password tuple. -func (ba *BasicAuthorizer) WithAuthorization() PrepareDecorator { - headers := make(map[string]interface{}) - headers[authorization] = basic + " " + base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", ba.userName, ba.password))) - - return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() -} - -// MultiTenantServicePrincipalTokenAuthorizer provides authentication across tenants. -type MultiTenantServicePrincipalTokenAuthorizer interface { - WithAuthorization() PrepareDecorator -} - -// NewMultiTenantServicePrincipalTokenAuthorizer crates a BearerAuthorizer using the given token provider -func NewMultiTenantServicePrincipalTokenAuthorizer(tp adal.MultitenantOAuthTokenProvider) MultiTenantServicePrincipalTokenAuthorizer { - return NewMultiTenantBearerAuthorizer(tp) -} - -// MultiTenantBearerAuthorizer implements bearer authorization across multiple tenants. -type MultiTenantBearerAuthorizer struct { - tp adal.MultitenantOAuthTokenProvider -} - -// NewMultiTenantBearerAuthorizer creates a MultiTenantBearerAuthorizer using the given token provider. -func NewMultiTenantBearerAuthorizer(tp adal.MultitenantOAuthTokenProvider) *MultiTenantBearerAuthorizer { - return &MultiTenantBearerAuthorizer{tp: tp} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header using the -// primary token along with the auxiliary authorization header using the auxiliary tokens. -// -// By default, the token will be automatically refreshed through the Refresher interface. -func (mt *MultiTenantBearerAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err != nil { - return r, err - } - if refresher, ok := mt.tp.(adal.RefresherWithContext); ok { - err = refresher.EnsureFreshWithContext(r.Context()) - if err != nil { - var resp *http.Response - if tokError, ok := err.(adal.TokenRefreshError); ok { - resp = tokError.Response() - } - return r, NewErrorWithError(err, "azure.multiTenantSPTAuthorizer", "WithAuthorization", resp, - "Failed to refresh one or more Tokens for request to %s", r.URL) - } - } - r, err = Prepare(r, WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", mt.tp.PrimaryOAuthToken()))) - if err != nil { - return r, err - } - auxTokens := mt.tp.AuxiliaryOAuthTokens() - for i := range auxTokens { - auxTokens[i] = fmt.Sprintf("Bearer %s", auxTokens[i]) - } - return Prepare(r, WithHeader(headerAuxAuthorization, strings.Join(auxTokens, ", "))) - }) - } -} - -// TokenProvider returns the underlying MultitenantOAuthTokenProvider for this authorizer. -func (mt *MultiTenantBearerAuthorizer) TokenProvider() adal.MultitenantOAuthTokenProvider { - return mt.tp -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/authorization_sas.go b/vendor/github.com/Azure/go-autorest/autorest/authorization_sas.go deleted file mode 100644 index 66501493..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/authorization_sas.go +++ /dev/null @@ -1,66 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "fmt" - "net/http" - "strings" -) - -// SASTokenAuthorizer implements an authorization for SAS Token Authentication -// this can be used for interaction with Blob Storage Endpoints -type SASTokenAuthorizer struct { - sasToken string -} - -// NewSASTokenAuthorizer creates a SASTokenAuthorizer using the given credentials -func NewSASTokenAuthorizer(sasToken string) (*SASTokenAuthorizer, error) { - if strings.TrimSpace(sasToken) == "" { - return nil, fmt.Errorf("sasToken cannot be empty") - } - - token := sasToken - if strings.HasPrefix(sasToken, "?") { - token = strings.TrimPrefix(sasToken, "?") - } - - return &SASTokenAuthorizer{ - sasToken: token, - }, nil -} - -// WithAuthorization returns a PrepareDecorator that adds a shared access signature token to the -// URI's query parameters. This can be used for the Blob, Queue, and File Services. -// -// See https://docs.microsoft.com/en-us/rest/api/storageservices/delegate-access-with-shared-access-signature -func (sas *SASTokenAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err != nil { - return r, err - } - - if r.URL.RawQuery == "" { - r.URL.RawQuery = sas.sasToken - } else if !strings.Contains(r.URL.RawQuery, sas.sasToken) { - r.URL.RawQuery = fmt.Sprintf("%s&%s", r.URL.RawQuery, sas.sasToken) - } - - return Prepare(r) - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/authorization_storage.go b/vendor/github.com/Azure/go-autorest/autorest/authorization_storage.go deleted file mode 100644 index 2af5030a..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/authorization_storage.go +++ /dev/null @@ -1,307 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "crypto/hmac" - "crypto/sha256" - "encoding/base64" - "fmt" - "net/http" - "net/url" - "sort" - "strings" - "time" -) - -// SharedKeyType defines the enumeration for the various shared key types. -// See https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key for details on the shared key types. -type SharedKeyType string - -const ( - // SharedKey is used to authorize against blobs, files and queues services. - SharedKey SharedKeyType = "sharedKey" - - // SharedKeyForTable is used to authorize against the table service. - SharedKeyForTable SharedKeyType = "sharedKeyTable" - - // SharedKeyLite is used to authorize against blobs, files and queues services. It's provided for - // backwards compatibility with API versions before 2009-09-19. Prefer SharedKey instead. - SharedKeyLite SharedKeyType = "sharedKeyLite" - - // SharedKeyLiteForTable is used to authorize against the table service. It's provided for - // backwards compatibility with older table API versions. Prefer SharedKeyForTable instead. - SharedKeyLiteForTable SharedKeyType = "sharedKeyLiteTable" -) - -const ( - headerAccept = "Accept" - headerAcceptCharset = "Accept-Charset" - headerContentEncoding = "Content-Encoding" - headerContentLength = "Content-Length" - headerContentMD5 = "Content-MD5" - headerContentLanguage = "Content-Language" - headerIfModifiedSince = "If-Modified-Since" - headerIfMatch = "If-Match" - headerIfNoneMatch = "If-None-Match" - headerIfUnmodifiedSince = "If-Unmodified-Since" - headerDate = "Date" - headerXMSDate = "X-Ms-Date" - headerXMSVersion = "x-ms-version" - headerRange = "Range" -) - -const storageEmulatorAccountName = "devstoreaccount1" - -// SharedKeyAuthorizer implements an authorization for Shared Key -// this can be used for interaction with Blob, File and Queue Storage Endpoints -type SharedKeyAuthorizer struct { - accountName string - accountKey []byte - keyType SharedKeyType -} - -// NewSharedKeyAuthorizer creates a SharedKeyAuthorizer using the provided credentials and shared key type. -func NewSharedKeyAuthorizer(accountName, accountKey string, keyType SharedKeyType) (*SharedKeyAuthorizer, error) { - key, err := base64.StdEncoding.DecodeString(accountKey) - if err != nil { - return nil, fmt.Errorf("malformed storage account key: %v", err) - } - return &SharedKeyAuthorizer{ - accountName: accountName, - accountKey: key, - keyType: keyType, - }, nil -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is " " followed by the computed key. -// This can be used for the Blob, Queue, and File Services -// -// from: https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-shared-key -// You may use Shared Key authorization to authorize a request made against the -// 2009-09-19 version and later of the Blob and Queue services, -// and version 2014-02-14 and later of the File services. -func (sk *SharedKeyAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err != nil { - return r, err - } - - sk, err := buildSharedKey(sk.accountName, sk.accountKey, r, sk.keyType) - if err != nil { - return r, err - } - return Prepare(r, WithHeader(headerAuthorization, sk)) - }) - } -} - -func buildSharedKey(accName string, accKey []byte, req *http.Request, keyType SharedKeyType) (string, error) { - canRes, err := buildCanonicalizedResource(accName, req.URL.String(), keyType) - if err != nil { - return "", err - } - - if req.Header == nil { - req.Header = http.Header{} - } - - // ensure date is set - if req.Header.Get(headerDate) == "" && req.Header.Get(headerXMSDate) == "" { - date := time.Now().UTC().Format(http.TimeFormat) - req.Header.Set(headerXMSDate, date) - } - canString, err := buildCanonicalizedString(req.Method, req.Header, canRes, keyType) - if err != nil { - return "", err - } - return createAuthorizationHeader(accName, accKey, canString, keyType), nil -} - -func buildCanonicalizedResource(accountName, uri string, keyType SharedKeyType) (string, error) { - errMsg := "buildCanonicalizedResource error: %s" - u, err := url.Parse(uri) - if err != nil { - return "", fmt.Errorf(errMsg, err.Error()) - } - - cr := bytes.NewBufferString("") - if accountName != storageEmulatorAccountName { - cr.WriteString("/") - cr.WriteString(getCanonicalizedAccountName(accountName)) - } - - if len(u.Path) > 0 { - // Any portion of the CanonicalizedResource string that is derived from - // the resource's URI should be encoded exactly as it is in the URI. - // -- https://msdn.microsoft.com/en-gb/library/azure/dd179428.aspx - cr.WriteString(u.EscapedPath()) - } else { - // a slash is required to indicate the root path - cr.WriteString("/") - } - - params, err := url.ParseQuery(u.RawQuery) - if err != nil { - return "", fmt.Errorf(errMsg, err.Error()) - } - - // See https://github.com/Azure/azure-storage-net/blob/master/Lib/Common/Core/Util/AuthenticationUtility.cs#L277 - if keyType == SharedKey { - if len(params) > 0 { - cr.WriteString("\n") - - keys := []string{} - for key := range params { - keys = append(keys, key) - } - sort.Strings(keys) - - completeParams := []string{} - for _, key := range keys { - if len(params[key]) > 1 { - sort.Strings(params[key]) - } - - completeParams = append(completeParams, fmt.Sprintf("%s:%s", key, strings.Join(params[key], ","))) - } - cr.WriteString(strings.Join(completeParams, "\n")) - } - } else { - // search for "comp" parameter, if exists then add it to canonicalizedresource - if v, ok := params["comp"]; ok { - cr.WriteString("?comp=" + v[0]) - } - } - - return string(cr.Bytes()), nil -} - -func getCanonicalizedAccountName(accountName string) string { - // since we may be trying to access a secondary storage account, we need to - // remove the -secondary part of the storage name - return strings.TrimSuffix(accountName, "-secondary") -} - -func buildCanonicalizedString(verb string, headers http.Header, canonicalizedResource string, keyType SharedKeyType) (string, error) { - contentLength := headers.Get(headerContentLength) - if contentLength == "0" { - contentLength = "" - } - date := headers.Get(headerDate) - if v := headers.Get(headerXMSDate); v != "" { - if keyType == SharedKey || keyType == SharedKeyLite { - date = "" - } else { - date = v - } - } - var canString string - switch keyType { - case SharedKey: - canString = strings.Join([]string{ - verb, - headers.Get(headerContentEncoding), - headers.Get(headerContentLanguage), - contentLength, - headers.Get(headerContentMD5), - headers.Get(headerContentType), - date, - headers.Get(headerIfModifiedSince), - headers.Get(headerIfMatch), - headers.Get(headerIfNoneMatch), - headers.Get(headerIfUnmodifiedSince), - headers.Get(headerRange), - buildCanonicalizedHeader(headers), - canonicalizedResource, - }, "\n") - case SharedKeyForTable: - canString = strings.Join([]string{ - verb, - headers.Get(headerContentMD5), - headers.Get(headerContentType), - date, - canonicalizedResource, - }, "\n") - case SharedKeyLite: - canString = strings.Join([]string{ - verb, - headers.Get(headerContentMD5), - headers.Get(headerContentType), - date, - buildCanonicalizedHeader(headers), - canonicalizedResource, - }, "\n") - case SharedKeyLiteForTable: - canString = strings.Join([]string{ - date, - canonicalizedResource, - }, "\n") - default: - return "", fmt.Errorf("key type '%s' is not supported", keyType) - } - return canString, nil -} - -func buildCanonicalizedHeader(headers http.Header) string { - cm := make(map[string]string) - - for k := range headers { - headerName := strings.TrimSpace(strings.ToLower(k)) - if strings.HasPrefix(headerName, "x-ms-") { - cm[headerName] = headers.Get(k) - } - } - - if len(cm) == 0 { - return "" - } - - keys := []string{} - for key := range cm { - keys = append(keys, key) - } - - sort.Strings(keys) - - ch := bytes.NewBufferString("") - - for _, key := range keys { - ch.WriteString(key) - ch.WriteRune(':') - ch.WriteString(cm[key]) - ch.WriteRune('\n') - } - - return strings.TrimSuffix(string(ch.Bytes()), "\n") -} - -func createAuthorizationHeader(accountName string, accountKey []byte, canonicalizedString string, keyType SharedKeyType) string { - h := hmac.New(sha256.New, accountKey) - h.Write([]byte(canonicalizedString)) - signature := base64.StdEncoding.EncodeToString(h.Sum(nil)) - var key string - switch keyType { - case SharedKey, SharedKeyForTable: - key = "SharedKey" - case SharedKeyLite, SharedKeyLiteForTable: - key = "SharedKeyLite" - } - return fmt.Sprintf("%s %s:%s", key, getCanonicalizedAccountName(accountName), signature) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/autorest.go b/vendor/github.com/Azure/go-autorest/autorest/autorest.go deleted file mode 100644 index aafdf021..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/autorest.go +++ /dev/null @@ -1,150 +0,0 @@ -/* -Package autorest implements an HTTP request pipeline suitable for use across multiple go-routines -and provides the shared routines relied on by AutoRest (see https://github.com/Azure/autorest/) -generated Go code. - -The package breaks sending and responding to HTTP requests into three phases: Preparing, Sending, -and Responding. A typical pattern is: - - req, err := Prepare(&http.Request{}, - token.WithAuthorization()) - - resp, err := Send(req, - WithLogging(logger), - DoErrorIfStatusCode(http.StatusInternalServerError), - DoCloseIfError(), - DoRetryForAttempts(5, time.Second)) - - err = Respond(resp, - ByDiscardingBody(), - ByClosing()) - -Each phase relies on decorators to modify and / or manage processing. Decorators may first modify -and then pass the data along, pass the data first and then modify the result, or wrap themselves -around passing the data (such as a logger might do). Decorators run in the order provided. For -example, the following: - - req, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPath("a"), - WithPath("b"), - WithPath("c")) - -will set the URL to: - - https://microsoft.com/a/b/c - -Preparers and Responders may be shared and re-used (assuming the underlying decorators support -sharing and re-use). Performant use is obtained by creating one or more Preparers and Responders -shared among multiple go-routines, and a single Sender shared among multiple sending go-routines, -all bound together by means of input / output channels. - -Decorators hold their passed state within a closure (such as the path components in the example -above). Be careful to share Preparers and Responders only in a context where such held state -applies. For example, it may not make sense to share a Preparer that applies a query string from a -fixed set of values. Similarly, sharing a Responder that reads the response body into a passed -struct (e.g., ByUnmarshallingJson) is likely incorrect. - -Lastly, the Swagger specification (https://swagger.io) that drives AutoRest -(https://github.com/Azure/autorest/) precisely defines two date forms: date and date-time. The -github.com/Azure/go-autorest/autorest/date package provides time.Time derivations to ensure -correct parsing and formatting. - -Errors raised by autorest objects and methods will conform to the autorest.Error interface. - -See the included examples for more detail. For details on the suggested use of this package by -generated clients, see the Client described below. -*/ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "context" - "net/http" - "time" -) - -const ( - // HeaderLocation specifies the HTTP Location header. - HeaderLocation = "Location" - - // HeaderRetryAfter specifies the HTTP Retry-After header. - HeaderRetryAfter = "Retry-After" -) - -// ResponseHasStatusCode returns true if the status code in the HTTP Response is in the passed set -// and false otherwise. -func ResponseHasStatusCode(resp *http.Response, codes ...int) bool { - if resp == nil { - return false - } - return containsInt(codes, resp.StatusCode) -} - -// GetLocation retrieves the URL from the Location header of the passed response. -func GetLocation(resp *http.Response) string { - return resp.Header.Get(HeaderLocation) -} - -// GetRetryAfter extracts the retry delay from the Retry-After header of the passed response. If -// the header is absent or is malformed, it will return the supplied default delay time.Duration. -func GetRetryAfter(resp *http.Response, defaultDelay time.Duration) time.Duration { - retry := resp.Header.Get(HeaderRetryAfter) - if retry == "" { - return defaultDelay - } - - d, err := time.ParseDuration(retry + "s") - if err != nil { - return defaultDelay - } - - return d -} - -// NewPollingRequest allocates and returns a new http.Request to poll for the passed response. -func NewPollingRequest(resp *http.Response, cancel <-chan struct{}) (*http.Request, error) { - location := GetLocation(resp) - if location == "" { - return nil, NewErrorWithResponse("autorest", "NewPollingRequest", resp, "Location header missing from response that requires polling") - } - - req, err := Prepare(&http.Request{Cancel: cancel}, - AsGet(), - WithBaseURL(location)) - if err != nil { - return nil, NewErrorWithError(err, "autorest", "NewPollingRequest", nil, "Failure creating poll request to %s", location) - } - - return req, nil -} - -// NewPollingRequestWithContext allocates and returns a new http.Request with the specified context to poll for the passed response. -func NewPollingRequestWithContext(ctx context.Context, resp *http.Response) (*http.Request, error) { - location := GetLocation(resp) - if location == "" { - return nil, NewErrorWithResponse("autorest", "NewPollingRequestWithContext", resp, "Location header missing from response that requires polling") - } - - req, err := Prepare((&http.Request{}).WithContext(ctx), - AsGet(), - WithBaseURL(location)) - if err != nil { - return nil, NewErrorWithError(err, "autorest", "NewPollingRequestWithContext", nil, "Failure creating poll request to %s", location) - } - - return req, nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go deleted file mode 100644 index 42e28cf2..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go +++ /dev/null @@ -1,991 +0,0 @@ -package azure - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/tracing" -) - -const ( - headerAsyncOperation = "Azure-AsyncOperation" -) - -const ( - operationInProgress string = "InProgress" - operationCanceled string = "Canceled" - operationFailed string = "Failed" - operationSucceeded string = "Succeeded" -) - -var pollingCodes = [...]int{http.StatusNoContent, http.StatusAccepted, http.StatusCreated, http.StatusOK} - -// FutureAPI contains the set of methods on the Future type. -type FutureAPI interface { - // Response returns the last HTTP response. - Response() *http.Response - - // Status returns the last status message of the operation. - Status() string - - // PollingMethod returns the method used to monitor the status of the asynchronous operation. - PollingMethod() PollingMethodType - - // DoneWithContext queries the service to see if the operation has completed. - DoneWithContext(context.Context, autorest.Sender) (bool, error) - - // GetPollingDelay returns a duration the application should wait before checking - // the status of the asynchronous request and true; this value is returned from - // the service via the Retry-After response header. If the header wasn't returned - // then the function returns the zero-value time.Duration and false. - GetPollingDelay() (time.Duration, bool) - - // WaitForCompletionRef will return when one of the following conditions is met: the long - // running operation has completed, the provided context is cancelled, or the client's - // polling duration has been exceeded. It will retry failed polling attempts based on - // the retry value defined in the client up to the maximum retry attempts. - // If no deadline is specified in the context then the client.PollingDuration will be - // used to determine if a default deadline should be used. - // If PollingDuration is greater than zero the value will be used as the context's timeout. - // If PollingDuration is zero then no default deadline will be used. - WaitForCompletionRef(context.Context, autorest.Client) error - - // MarshalJSON implements the json.Marshaler interface. - MarshalJSON() ([]byte, error) - - // MarshalJSON implements the json.Unmarshaler interface. - UnmarshalJSON([]byte) error - - // PollingURL returns the URL used for retrieving the status of the long-running operation. - PollingURL() string - - // GetResult should be called once polling has completed successfully. - // It makes the final GET call to retrieve the resultant payload. - GetResult(autorest.Sender) (*http.Response, error) -} - -var _ FutureAPI = (*Future)(nil) - -// Future provides a mechanism to access the status and results of an asynchronous request. -// Since futures are stateful they should be passed by value to avoid race conditions. -type Future struct { - pt pollingTracker -} - -// NewFutureFromResponse returns a new Future object initialized -// with the initial response from an asynchronous operation. -func NewFutureFromResponse(resp *http.Response) (Future, error) { - pt, err := createPollingTracker(resp) - return Future{pt: pt}, err -} - -// Response returns the last HTTP response. -func (f Future) Response() *http.Response { - if f.pt == nil { - return nil - } - return f.pt.latestResponse() -} - -// Status returns the last status message of the operation. -func (f Future) Status() string { - if f.pt == nil { - return "" - } - return f.pt.pollingStatus() -} - -// PollingMethod returns the method used to monitor the status of the asynchronous operation. -func (f Future) PollingMethod() PollingMethodType { - if f.pt == nil { - return PollingUnknown - } - return f.pt.pollingMethod() -} - -// DoneWithContext queries the service to see if the operation has completed. -func (f *Future) DoneWithContext(ctx context.Context, sender autorest.Sender) (done bool, err error) { - ctx = tracing.StartSpan(ctx, "github.com/Azure/go-autorest/autorest/azure/async.DoneWithContext") - defer func() { - sc := -1 - resp := f.Response() - if resp != nil { - sc = resp.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - - if f.pt == nil { - return false, autorest.NewError("Future", "Done", "future is not initialized") - } - if f.pt.hasTerminated() { - return true, f.pt.pollingError() - } - if err := f.pt.pollForStatus(ctx, sender); err != nil { - return false, err - } - if err := f.pt.checkForErrors(); err != nil { - return f.pt.hasTerminated(), err - } - if err := f.pt.updatePollingState(f.pt.provisioningStateApplicable()); err != nil { - return false, err - } - if err := f.pt.initPollingMethod(); err != nil { - return false, err - } - if err := f.pt.updatePollingMethod(); err != nil { - return false, err - } - return f.pt.hasTerminated(), f.pt.pollingError() -} - -// GetPollingDelay returns a duration the application should wait before checking -// the status of the asynchronous request and true; this value is returned from -// the service via the Retry-After response header. If the header wasn't returned -// then the function returns the zero-value time.Duration and false. -func (f Future) GetPollingDelay() (time.Duration, bool) { - if f.pt == nil { - return 0, false - } - resp := f.pt.latestResponse() - if resp == nil { - return 0, false - } - - retry := resp.Header.Get(autorest.HeaderRetryAfter) - if retry == "" { - return 0, false - } - - d, err := time.ParseDuration(retry + "s") - if err != nil { - panic(err) - } - - return d, true -} - -// WaitForCompletionRef will return when one of the following conditions is met: the long -// running operation has completed, the provided context is cancelled, or the client's -// polling duration has been exceeded. It will retry failed polling attempts based on -// the retry value defined in the client up to the maximum retry attempts. -// If no deadline is specified in the context then the client.PollingDuration will be -// used to determine if a default deadline should be used. -// If PollingDuration is greater than zero the value will be used as the context's timeout. -// If PollingDuration is zero then no default deadline will be used. -func (f *Future) WaitForCompletionRef(ctx context.Context, client autorest.Client) (err error) { - ctx = tracing.StartSpan(ctx, "github.com/Azure/go-autorest/autorest/azure/async.WaitForCompletionRef") - defer func() { - sc := -1 - resp := f.Response() - if resp != nil { - sc = resp.StatusCode - } - tracing.EndSpan(ctx, sc, err) - }() - cancelCtx := ctx - // if the provided context already has a deadline don't override it - _, hasDeadline := ctx.Deadline() - if d := client.PollingDuration; !hasDeadline && d != 0 { - var cancel context.CancelFunc - cancelCtx, cancel = context.WithTimeout(ctx, d) - defer cancel() - } - // if the initial response has a Retry-After, sleep for the specified amount of time before starting to poll - if delay, ok := f.GetPollingDelay(); ok { - if delayElapsed := autorest.DelayForBackoff(delay, 0, cancelCtx.Done()); !delayElapsed { - err = cancelCtx.Err() - return - } - } - done, err := f.DoneWithContext(ctx, client) - for attempts := 0; !done; done, err = f.DoneWithContext(ctx, client) { - if attempts >= client.RetryAttempts { - return autorest.NewErrorWithError(err, "Future", "WaitForCompletion", f.pt.latestResponse(), "the number of retries has been exceeded") - } - // we want delayAttempt to be zero in the non-error case so - // that DelayForBackoff doesn't perform exponential back-off - var delayAttempt int - var delay time.Duration - if err == nil { - // check for Retry-After delay, if not present use the client's polling delay - var ok bool - delay, ok = f.GetPollingDelay() - if !ok { - delay = client.PollingDelay - } - } else { - // there was an error polling for status so perform exponential - // back-off based on the number of attempts using the client's retry - // duration. update attempts after delayAttempt to avoid off-by-one. - delayAttempt = attempts - delay = client.RetryDuration - attempts++ - } - // wait until the delay elapses or the context is cancelled - delayElapsed := autorest.DelayForBackoff(delay, delayAttempt, cancelCtx.Done()) - if !delayElapsed { - return autorest.NewErrorWithError(cancelCtx.Err(), "Future", "WaitForCompletion", f.pt.latestResponse(), "context has been cancelled") - } - } - return -} - -// MarshalJSON implements the json.Marshaler interface. -func (f Future) MarshalJSON() ([]byte, error) { - return json.Marshal(f.pt) -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -func (f *Future) UnmarshalJSON(data []byte) error { - // unmarshal into JSON object to determine the tracker type - obj := map[string]interface{}{} - err := json.Unmarshal(data, &obj) - if err != nil { - return err - } - if obj["method"] == nil { - return autorest.NewError("Future", "UnmarshalJSON", "missing 'method' property") - } - method := obj["method"].(string) - switch strings.ToUpper(method) { - case http.MethodDelete: - f.pt = &pollingTrackerDelete{} - case http.MethodPatch: - f.pt = &pollingTrackerPatch{} - case http.MethodPost: - f.pt = &pollingTrackerPost{} - case http.MethodPut: - f.pt = &pollingTrackerPut{} - default: - return autorest.NewError("Future", "UnmarshalJSON", "unsupoorted method '%s'", method) - } - // now unmarshal into the tracker - return json.Unmarshal(data, &f.pt) -} - -// PollingURL returns the URL used for retrieving the status of the long-running operation. -func (f Future) PollingURL() string { - if f.pt == nil { - return "" - } - return f.pt.pollingURL() -} - -// GetResult should be called once polling has completed successfully. -// It makes the final GET call to retrieve the resultant payload. -func (f Future) GetResult(sender autorest.Sender) (*http.Response, error) { - if f.pt.finalGetURL() == "" { - // we can end up in this situation if the async operation returns a 200 - // with no polling URLs. in that case return the response which should - // contain the JSON payload (only do this for successful terminal cases). - if lr := f.pt.latestResponse(); lr != nil && f.pt.hasSucceeded() { - return lr, nil - } - return nil, autorest.NewError("Future", "GetResult", "missing URL for retrieving result") - } - req, err := http.NewRequest(http.MethodGet, f.pt.finalGetURL(), nil) - if err != nil { - return nil, err - } - resp, err := sender.Do(req) - if err == nil && resp.Body != nil { - // copy the body and close it so callers don't have to - defer resp.Body.Close() - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return resp, err - } - resp.Body = ioutil.NopCloser(bytes.NewReader(b)) - } - return resp, err -} - -type pollingTracker interface { - // these methods can differ per tracker - - // checks the response headers and status code to determine the polling mechanism - updatePollingMethod() error - - // checks the response for tracker-specific error conditions - checkForErrors() error - - // returns true if provisioning state should be checked - provisioningStateApplicable() bool - - // methods common to all trackers - - // initializes a tracker's polling URL and method, called for each iteration. - // these values can be overridden by each polling tracker as required. - initPollingMethod() error - - // initializes the tracker's internal state, call this when the tracker is created - initializeState() error - - // makes an HTTP request to check the status of the LRO - pollForStatus(ctx context.Context, sender autorest.Sender) error - - // updates internal tracker state, call this after each call to pollForStatus - updatePollingState(provStateApl bool) error - - // returns the error response from the service, can be nil - pollingError() error - - // returns the polling method being used - pollingMethod() PollingMethodType - - // returns the state of the LRO as returned from the service - pollingStatus() string - - // returns the URL used for polling status - pollingURL() string - - // returns the URL used for the final GET to retrieve the resource - finalGetURL() string - - // returns true if the LRO is in a terminal state - hasTerminated() bool - - // returns true if the LRO is in a failed terminal state - hasFailed() bool - - // returns true if the LRO is in a successful terminal state - hasSucceeded() bool - - // returns the cached HTTP response after a call to pollForStatus(), can be nil - latestResponse() *http.Response -} - -type pollingTrackerBase struct { - // resp is the last response, either from the submission of the LRO or from polling - resp *http.Response - - // method is the HTTP verb, this is needed for deserialization - Method string `json:"method"` - - // rawBody is the raw JSON response body - rawBody map[string]interface{} - - // denotes if polling is using async-operation or location header - Pm PollingMethodType `json:"pollingMethod"` - - // the URL to poll for status - URI string `json:"pollingURI"` - - // the state of the LRO as returned from the service - State string `json:"lroState"` - - // the URL to GET for the final result - FinalGetURI string `json:"resultURI"` - - // used to hold an error object returned from the service - Err *ServiceError `json:"error,omitempty"` -} - -func (pt *pollingTrackerBase) initializeState() error { - // determine the initial polling state based on response body and/or HTTP status - // code. this is applicable to the initial LRO response, not polling responses! - pt.Method = pt.resp.Request.Method - if err := pt.updateRawBody(); err != nil { - return err - } - switch pt.resp.StatusCode { - case http.StatusOK: - if ps := pt.getProvisioningState(); ps != nil { - pt.State = *ps - if pt.hasFailed() { - pt.updateErrorFromResponse() - return pt.pollingError() - } - } else { - pt.State = operationSucceeded - } - case http.StatusCreated: - if ps := pt.getProvisioningState(); ps != nil { - pt.State = *ps - } else { - pt.State = operationInProgress - } - case http.StatusAccepted: - pt.State = operationInProgress - case http.StatusNoContent: - pt.State = operationSucceeded - default: - pt.State = operationFailed - pt.updateErrorFromResponse() - return pt.pollingError() - } - return pt.initPollingMethod() -} - -func (pt pollingTrackerBase) getProvisioningState() *string { - if pt.rawBody != nil && pt.rawBody["properties"] != nil { - p := pt.rawBody["properties"].(map[string]interface{}) - if ps := p["provisioningState"]; ps != nil { - s := ps.(string) - return &s - } - } - return nil -} - -func (pt *pollingTrackerBase) updateRawBody() error { - pt.rawBody = map[string]interface{}{} - if pt.resp.ContentLength != 0 { - defer pt.resp.Body.Close() - b, err := ioutil.ReadAll(pt.resp.Body) - if err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "updateRawBody", nil, "failed to read response body") - } - // put the body back so it's available to other callers - pt.resp.Body = ioutil.NopCloser(bytes.NewReader(b)) - // observed in 204 responses over HTTP/2.0; the content length is -1 but body is empty - if len(b) == 0 { - return nil - } - if err = json.Unmarshal(b, &pt.rawBody); err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "updateRawBody", nil, "failed to unmarshal response body") - } - } - return nil -} - -func (pt *pollingTrackerBase) pollForStatus(ctx context.Context, sender autorest.Sender) error { - req, err := http.NewRequest(http.MethodGet, pt.URI, nil) - if err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "pollForStatus", nil, "failed to create HTTP request") - } - - req = req.WithContext(ctx) - preparer := autorest.CreatePreparer(autorest.GetPrepareDecorators(ctx)...) - req, err = preparer.Prepare(req) - if err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "pollForStatus", nil, "failed preparing HTTP request") - } - pt.resp, err = sender.Do(req) - if err != nil { - return autorest.NewErrorWithError(err, "pollingTrackerBase", "pollForStatus", nil, "failed to send HTTP request") - } - if autorest.ResponseHasStatusCode(pt.resp, pollingCodes[:]...) { - // reset the service error on success case - pt.Err = nil - err = pt.updateRawBody() - } else { - // check response body for error content - pt.updateErrorFromResponse() - err = pt.pollingError() - } - return err -} - -// attempts to unmarshal a ServiceError type from the response body. -// if that fails then make a best attempt at creating something meaningful. -// NOTE: this assumes that the async operation has failed. -func (pt *pollingTrackerBase) updateErrorFromResponse() { - var err error - if pt.resp.ContentLength != 0 { - type respErr struct { - ServiceError *ServiceError `json:"error"` - } - re := respErr{} - defer pt.resp.Body.Close() - var b []byte - if b, err = ioutil.ReadAll(pt.resp.Body); err != nil { - goto Default - } - // put the body back so it's available to other callers - pt.resp.Body = ioutil.NopCloser(bytes.NewReader(b)) - if len(b) == 0 { - goto Default - } - if err = json.Unmarshal(b, &re); err != nil { - goto Default - } - // unmarshalling the error didn't yield anything, try unwrapped error - if re.ServiceError == nil { - err = json.Unmarshal(b, &re.ServiceError) - if err != nil { - goto Default - } - } - // the unmarshaller will ensure re.ServiceError is non-nil - // even if there was no content unmarshalled so check the code. - if re.ServiceError.Code != "" { - pt.Err = re.ServiceError - return - } - } -Default: - se := &ServiceError{ - Code: pt.pollingStatus(), - Message: "The async operation failed.", - } - if err != nil { - se.InnerError = make(map[string]interface{}) - se.InnerError["unmarshalError"] = err.Error() - } - // stick the response body into the error object in hopes - // it contains something useful to help diagnose the failure. - if len(pt.rawBody) > 0 { - se.AdditionalInfo = []map[string]interface{}{ - pt.rawBody, - } - } - pt.Err = se -} - -func (pt *pollingTrackerBase) updatePollingState(provStateApl bool) error { - if pt.Pm == PollingAsyncOperation && pt.rawBody["status"] != nil { - pt.State = pt.rawBody["status"].(string) - } else { - if pt.resp.StatusCode == http.StatusAccepted { - pt.State = operationInProgress - } else if provStateApl { - if ps := pt.getProvisioningState(); ps != nil { - pt.State = *ps - } else { - pt.State = operationSucceeded - } - } else { - return autorest.NewError("pollingTrackerBase", "updatePollingState", "the response from the async operation has an invalid status code") - } - } - // if the operation has failed update the error state - if pt.hasFailed() { - pt.updateErrorFromResponse() - } - return nil -} - -func (pt pollingTrackerBase) pollingError() error { - if pt.Err == nil { - return nil - } - return pt.Err -} - -func (pt pollingTrackerBase) pollingMethod() PollingMethodType { - return pt.Pm -} - -func (pt pollingTrackerBase) pollingStatus() string { - return pt.State -} - -func (pt pollingTrackerBase) pollingURL() string { - return pt.URI -} - -func (pt pollingTrackerBase) finalGetURL() string { - return pt.FinalGetURI -} - -func (pt pollingTrackerBase) hasTerminated() bool { - return strings.EqualFold(pt.State, operationCanceled) || strings.EqualFold(pt.State, operationFailed) || strings.EqualFold(pt.State, operationSucceeded) -} - -func (pt pollingTrackerBase) hasFailed() bool { - return strings.EqualFold(pt.State, operationCanceled) || strings.EqualFold(pt.State, operationFailed) -} - -func (pt pollingTrackerBase) hasSucceeded() bool { - return strings.EqualFold(pt.State, operationSucceeded) -} - -func (pt pollingTrackerBase) latestResponse() *http.Response { - return pt.resp -} - -// error checking common to all trackers -func (pt pollingTrackerBase) baseCheckForErrors() error { - // for Azure-AsyncOperations the response body cannot be nil or empty - if pt.Pm == PollingAsyncOperation { - if pt.resp.Body == nil || pt.resp.ContentLength == 0 { - return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "for Azure-AsyncOperation response body cannot be nil") - } - if pt.rawBody["status"] == nil { - return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "missing status property in Azure-AsyncOperation response body") - } - } - return nil -} - -// default initialization of polling URL/method. each verb tracker will update this as required. -func (pt *pollingTrackerBase) initPollingMethod() error { - if ao, err := getURLFromAsyncOpHeader(pt.resp); err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - return nil - } - if lh, err := getURLFromLocationHeader(pt.resp); err != nil { - return err - } else if lh != "" { - pt.URI = lh - pt.Pm = PollingLocation - return nil - } - // it's ok if we didn't find a polling header, this will be handled elsewhere - return nil -} - -// DELETE - -type pollingTrackerDelete struct { - pollingTrackerBase -} - -func (pt *pollingTrackerDelete) updatePollingMethod() error { - // for 201 the Location header is required - if pt.resp.StatusCode == http.StatusCreated { - if lh, err := getURLFromLocationHeader(pt.resp); err != nil { - return err - } else if lh == "" { - return autorest.NewError("pollingTrackerDelete", "updateHeaders", "missing Location header in 201 response") - } else { - pt.URI = lh - } - pt.Pm = PollingLocation - pt.FinalGetURI = pt.URI - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - // if the Location header is invalid and we already have a polling URL - // then we don't care if the Location header URL is malformed. - if lh, err := getURLFromLocationHeader(pt.resp); err != nil && pt.URI == "" { - return err - } else if lh != "" { - if ao == "" { - pt.URI = lh - pt.Pm = PollingLocation - } - // when both headers are returned we use the value in the Location header for the final GET - pt.FinalGetURI = lh - } - // make sure a polling URL was found - if pt.URI == "" { - return autorest.NewError("pollingTrackerPost", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } - } - return nil -} - -func (pt pollingTrackerDelete) checkForErrors() error { - return pt.baseCheckForErrors() -} - -func (pt pollingTrackerDelete) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusNoContent -} - -// PATCH - -type pollingTrackerPatch struct { - pollingTrackerBase -} - -func (pt *pollingTrackerPatch) updatePollingMethod() error { - // by default we can use the original URL for polling and final GET - if pt.URI == "" { - pt.URI = pt.resp.Request.URL.String() - } - if pt.FinalGetURI == "" { - pt.FinalGetURI = pt.resp.Request.URL.String() - } - if pt.Pm == PollingUnknown { - pt.Pm = PollingRequestURI - } - // for 201 it's permissible for no headers to be returned - if pt.resp.StatusCode == http.StatusCreated { - if ao, err := getURLFromAsyncOpHeader(pt.resp); err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - // note the absence of the "final GET" mechanism for PATCH - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - if ao == "" { - if lh, err := getURLFromLocationHeader(pt.resp); err != nil { - return err - } else if lh == "" { - return autorest.NewError("pollingTrackerPatch", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } else { - pt.URI = lh - pt.Pm = PollingLocation - } - } - } - return nil -} - -func (pt pollingTrackerPatch) checkForErrors() error { - return pt.baseCheckForErrors() -} - -func (pt pollingTrackerPatch) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusCreated -} - -// POST - -type pollingTrackerPost struct { - pollingTrackerBase -} - -func (pt *pollingTrackerPost) updatePollingMethod() error { - // 201 requires Location header - if pt.resp.StatusCode == http.StatusCreated { - if lh, err := getURLFromLocationHeader(pt.resp); err != nil { - return err - } else if lh == "" { - return autorest.NewError("pollingTrackerPost", "updateHeaders", "missing Location header in 201 response") - } else { - pt.URI = lh - pt.FinalGetURI = lh - pt.Pm = PollingLocation - } - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - // if the Location header is invalid and we already have a polling URL - // then we don't care if the Location header URL is malformed. - if lh, err := getURLFromLocationHeader(pt.resp); err != nil && pt.URI == "" { - return err - } else if lh != "" { - if ao == "" { - pt.URI = lh - pt.Pm = PollingLocation - } - // when both headers are returned we use the value in the Location header for the final GET - pt.FinalGetURI = lh - } - // make sure a polling URL was found - if pt.URI == "" { - return autorest.NewError("pollingTrackerPost", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } - } - return nil -} - -func (pt pollingTrackerPost) checkForErrors() error { - return pt.baseCheckForErrors() -} - -func (pt pollingTrackerPost) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusNoContent -} - -// PUT - -type pollingTrackerPut struct { - pollingTrackerBase -} - -func (pt *pollingTrackerPut) updatePollingMethod() error { - // by default we can use the original URL for polling and final GET - if pt.URI == "" { - pt.URI = pt.resp.Request.URL.String() - } - if pt.FinalGetURI == "" { - pt.FinalGetURI = pt.resp.Request.URL.String() - } - if pt.Pm == PollingUnknown { - pt.Pm = PollingRequestURI - } - // for 201 it's permissible for no headers to be returned - if pt.resp.StatusCode == http.StatusCreated { - if ao, err := getURLFromAsyncOpHeader(pt.resp); err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - } - // for 202 prefer the Azure-AsyncOperation header but fall back to Location if necessary - if pt.resp.StatusCode == http.StatusAccepted { - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } else if ao != "" { - pt.URI = ao - pt.Pm = PollingAsyncOperation - } - // if the Location header is invalid and we already have a polling URL - // then we don't care if the Location header URL is malformed. - if lh, err := getURLFromLocationHeader(pt.resp); err != nil && pt.URI == "" { - return err - } else if lh != "" { - if ao == "" { - pt.URI = lh - pt.Pm = PollingLocation - } - } - // make sure a polling URL was found - if pt.URI == "" { - return autorest.NewError("pollingTrackerPut", "updateHeaders", "didn't get any suitable polling URLs in 202 response") - } - } - return nil -} - -func (pt pollingTrackerPut) checkForErrors() error { - err := pt.baseCheckForErrors() - if err != nil { - return err - } - // if there are no LRO headers then the body cannot be empty - ao, err := getURLFromAsyncOpHeader(pt.resp) - if err != nil { - return err - } - lh, err := getURLFromLocationHeader(pt.resp) - if err != nil { - return err - } - if ao == "" && lh == "" && len(pt.rawBody) == 0 { - return autorest.NewError("pollingTrackerPut", "checkForErrors", "the response did not contain a body") - } - return nil -} - -func (pt pollingTrackerPut) provisioningStateApplicable() bool { - return pt.resp.StatusCode == http.StatusOK || pt.resp.StatusCode == http.StatusCreated -} - -// creates a polling tracker based on the verb of the original request -func createPollingTracker(resp *http.Response) (pollingTracker, error) { - var pt pollingTracker - switch strings.ToUpper(resp.Request.Method) { - case http.MethodDelete: - pt = &pollingTrackerDelete{pollingTrackerBase: pollingTrackerBase{resp: resp}} - case http.MethodPatch: - pt = &pollingTrackerPatch{pollingTrackerBase: pollingTrackerBase{resp: resp}} - case http.MethodPost: - pt = &pollingTrackerPost{pollingTrackerBase: pollingTrackerBase{resp: resp}} - case http.MethodPut: - pt = &pollingTrackerPut{pollingTrackerBase: pollingTrackerBase{resp: resp}} - default: - return nil, autorest.NewError("azure", "createPollingTracker", "unsupported HTTP method %s", resp.Request.Method) - } - if err := pt.initializeState(); err != nil { - return pt, err - } - // this initializes the polling header values, we do this during creation in case the - // initial response send us invalid values; this way the API call will return a non-nil - // error (not doing this means the error shows up in Future.Done) - return pt, pt.updatePollingMethod() -} - -// gets the polling URL from the Azure-AsyncOperation header. -// ensures the URL is well-formed and absolute. -func getURLFromAsyncOpHeader(resp *http.Response) (string, error) { - s := resp.Header.Get(http.CanonicalHeaderKey(headerAsyncOperation)) - if s == "" { - return "", nil - } - if !isValidURL(s) { - return "", autorest.NewError("azure", "getURLFromAsyncOpHeader", "invalid polling URL '%s'", s) - } - return s, nil -} - -// gets the polling URL from the Location header. -// ensures the URL is well-formed and absolute. -func getURLFromLocationHeader(resp *http.Response) (string, error) { - s := resp.Header.Get(http.CanonicalHeaderKey(autorest.HeaderLocation)) - if s == "" { - return "", nil - } - if !isValidURL(s) { - return "", autorest.NewError("azure", "getURLFromLocationHeader", "invalid polling URL '%s'", s) - } - return s, nil -} - -// verify that the URL is valid and absolute -func isValidURL(s string) bool { - u, err := url.Parse(s) - return err == nil && u.IsAbs() -} - -// PollingMethodType defines a type used for enumerating polling mechanisms. -type PollingMethodType string - -const ( - // PollingAsyncOperation indicates the polling method uses the Azure-AsyncOperation header. - PollingAsyncOperation PollingMethodType = "AsyncOperation" - - // PollingLocation indicates the polling method uses the Location header. - PollingLocation PollingMethodType = "Location" - - // PollingRequestURI indicates the polling method uses the original request URI. - PollingRequestURI PollingMethodType = "RequestURI" - - // PollingUnknown indicates an unknown polling method and is the default value. - PollingUnknown PollingMethodType = "" -) - -// AsyncOpIncompleteError is the type that's returned from a future that has not completed. -type AsyncOpIncompleteError struct { - // FutureType is the name of the type composed of a azure.Future. - FutureType string -} - -// Error returns an error message including the originating type name of the error. -func (e AsyncOpIncompleteError) Error() string { - return fmt.Sprintf("%s: asynchronous operation has not completed", e.FutureType) -} - -// NewAsyncOpIncompleteError creates a new AsyncOpIncompleteError with the specified parameters. -func NewAsyncOpIncompleteError(futureType string) AsyncOpIncompleteError { - return AsyncOpIncompleteError{ - FutureType: futureType, - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/auth/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/azure/auth/LICENSE deleted file mode 100644 index b9d6a27e..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/auth/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2015 Microsoft Corporation - - 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/Azure/go-autorest/autorest/azure/auth/auth.go b/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go deleted file mode 100644 index 85acf1c9..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go +++ /dev/null @@ -1,757 +0,0 @@ -package auth - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "log" - "os" - "strings" - "unicode/utf16" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/azure/cli" - "github.com/Azure/go-autorest/logger" - "github.com/dimchansky/utfbom" -) - -// The possible keys in the Values map. -const ( - SubscriptionID = "AZURE_SUBSCRIPTION_ID" - TenantID = "AZURE_TENANT_ID" - AuxiliaryTenantIDs = "AZURE_AUXILIARY_TENANT_IDS" - ClientID = "AZURE_CLIENT_ID" - ClientSecret = "AZURE_CLIENT_SECRET" - CertificatePath = "AZURE_CERTIFICATE_PATH" - CertificatePassword = "AZURE_CERTIFICATE_PASSWORD" - Username = "AZURE_USERNAME" - Password = "AZURE_PASSWORD" - EnvironmentName = "AZURE_ENVIRONMENT" - Resource = "AZURE_AD_RESOURCE" - ActiveDirectoryEndpoint = "ActiveDirectoryEndpoint" - ResourceManagerEndpoint = "ResourceManagerEndpoint" - GraphResourceID = "GraphResourceID" - SQLManagementEndpoint = "SQLManagementEndpoint" - GalleryEndpoint = "GalleryEndpoint" - ManagementEndpoint = "ManagementEndpoint" -) - -// NewAuthorizerFromEnvironment creates an Authorizer configured from environment variables in the order: -// 1. Client credentials -// 2. Client certificate -// 3. Username password -// 4. MSI -func NewAuthorizerFromEnvironment() (autorest.Authorizer, error) { - logger.Instance.Writeln(logger.LogInfo, "NewAuthorizerFromEnvironment() determining authentication mechanism") - settings, err := GetSettingsFromEnvironment() - if err != nil { - return nil, err - } - return settings.GetAuthorizer() -} - -// NewAuthorizerFromEnvironmentWithResource creates an Authorizer configured from environment variables in the order: -// 1. Client credentials -// 2. Client certificate -// 3. Username password -// 4. MSI -func NewAuthorizerFromEnvironmentWithResource(resource string) (autorest.Authorizer, error) { - logger.Instance.Writeln(logger.LogInfo, "NewAuthorizerFromEnvironmentWithResource() determining authentication mechanism") - settings, err := GetSettingsFromEnvironment() - if err != nil { - return nil, err - } - settings.Values[Resource] = resource - return settings.GetAuthorizer() -} - -// EnvironmentSettings contains the available authentication settings. -type EnvironmentSettings struct { - Values map[string]string - Environment azure.Environment -} - -// GetSettingsFromEnvironment returns the available authentication settings from the environment. -func GetSettingsFromEnvironment() (s EnvironmentSettings, err error) { - s = EnvironmentSettings{ - Values: map[string]string{}, - } - s.setValue(SubscriptionID) - s.setValue(TenantID) - s.setValue(AuxiliaryTenantIDs) - s.setValue(ClientID) - s.setValue(ClientSecret) - s.setValue(CertificatePath) - s.setValue(CertificatePassword) - s.setValue(Username) - s.setValue(Password) - s.setValue(EnvironmentName) - s.setValue(Resource) - if v := s.Values[EnvironmentName]; v == "" { - s.Environment = azure.PublicCloud - } else { - s.Environment, err = azure.EnvironmentFromName(v) - } - if s.Values[Resource] == "" { - s.Values[Resource] = s.Environment.ResourceManagerEndpoint - } - return -} - -// GetSubscriptionID returns the available subscription ID or an empty string. -func (settings EnvironmentSettings) GetSubscriptionID() string { - return settings.Values[SubscriptionID] -} - -// adds the specified environment variable value to the Values map if it exists -func (settings EnvironmentSettings) setValue(key string) { - if v := os.Getenv(key); v != "" { - logger.Instance.Writef(logger.LogInfo, "GetSettingsFromEnvironment() found environment var %s\n", key) - settings.Values[key] = v - } -} - -// helper to return client and tenant IDs -func (settings EnvironmentSettings) getClientAndTenant() (string, string) { - clientID := settings.Values[ClientID] - tenantID := settings.Values[TenantID] - return clientID, tenantID -} - -// GetClientCredentials creates a config object from the available client credentials. -// An error is returned if no client credentials are available. -func (settings EnvironmentSettings) GetClientCredentials() (ClientCredentialsConfig, error) { - secret := settings.Values[ClientSecret] - if secret == "" { - logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetClientCredentials() missing client secret") - return ClientCredentialsConfig{}, errors.New("missing client secret") - } - clientID, tenantID := settings.getClientAndTenant() - config := NewClientCredentialsConfig(clientID, secret, tenantID) - config.AADEndpoint = settings.Environment.ActiveDirectoryEndpoint - config.Resource = settings.Values[Resource] - if auxTenants, ok := settings.Values[AuxiliaryTenantIDs]; ok { - config.AuxTenants = strings.Split(auxTenants, ";") - for i := range config.AuxTenants { - config.AuxTenants[i] = strings.TrimSpace(config.AuxTenants[i]) - } - } - return config, nil -} - -// GetClientCertificate creates a config object from the available certificate credentials. -// An error is returned if no certificate credentials are available. -func (settings EnvironmentSettings) GetClientCertificate() (ClientCertificateConfig, error) { - certPath := settings.Values[CertificatePath] - if certPath == "" { - logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetClientCertificate() missing certificate path") - return ClientCertificateConfig{}, errors.New("missing certificate path") - } - certPwd := settings.Values[CertificatePassword] - clientID, tenantID := settings.getClientAndTenant() - config := NewClientCertificateConfig(certPath, certPwd, clientID, tenantID) - config.AADEndpoint = settings.Environment.ActiveDirectoryEndpoint - config.Resource = settings.Values[Resource] - return config, nil -} - -// GetUsernamePassword creates a config object from the available username/password credentials. -// An error is returned if no username/password credentials are available. -func (settings EnvironmentSettings) GetUsernamePassword() (UsernamePasswordConfig, error) { - username := settings.Values[Username] - password := settings.Values[Password] - if username == "" || password == "" { - logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetUsernamePassword() missing username and/or password") - return UsernamePasswordConfig{}, errors.New("missing username/password") - } - clientID, tenantID := settings.getClientAndTenant() - config := NewUsernamePasswordConfig(username, password, clientID, tenantID) - config.AADEndpoint = settings.Environment.ActiveDirectoryEndpoint - config.Resource = settings.Values[Resource] - return config, nil -} - -// GetMSI creates a MSI config object from the available client ID. -func (settings EnvironmentSettings) GetMSI() MSIConfig { - config := NewMSIConfig() - config.Resource = settings.Values[Resource] - config.ClientID = settings.Values[ClientID] - return config -} - -// GetDeviceFlow creates a device-flow config object from the available client and tenant IDs. -func (settings EnvironmentSettings) GetDeviceFlow() DeviceFlowConfig { - clientID, tenantID := settings.getClientAndTenant() - config := NewDeviceFlowConfig(clientID, tenantID) - config.AADEndpoint = settings.Environment.ActiveDirectoryEndpoint - config.Resource = settings.Values[Resource] - return config -} - -// GetAuthorizer creates an Authorizer configured from environment variables in the order: -// 1. Client credentials -// 2. Client certificate -// 3. Username password -// 4. MSI -func (settings EnvironmentSettings) GetAuthorizer() (autorest.Authorizer, error) { - //1.Client Credentials - if c, e := settings.GetClientCredentials(); e == nil { - logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetAuthorizer() using client secret credentials") - return c.Authorizer() - } - - //2. Client Certificate - if c, e := settings.GetClientCertificate(); e == nil { - logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetAuthorizer() using client certificate credentials") - return c.Authorizer() - } - - //3. Username Password - if c, e := settings.GetUsernamePassword(); e == nil { - logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetAuthorizer() using user name/password credentials") - return c.Authorizer() - } - - // 4. MSI - logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetAuthorizer() using MSI authentication") - return settings.GetMSI().Authorizer() -} - -// NewAuthorizerFromFile creates an Authorizer configured from a configuration file in the following order. -// 1. Client credentials -// 2. Client certificate -// The path to the configuration file must be specified in the AZURE_AUTH_LOCATION environment variable. -// resourceBaseURI - used to determine the resource type -func NewAuthorizerFromFile(resourceBaseURI string) (autorest.Authorizer, error) { - settings, err := GetSettingsFromFile() - if err != nil { - return nil, err - } - if a, err := settings.ClientCredentialsAuthorizer(resourceBaseURI); err == nil { - return a, err - } - if a, err := settings.ClientCertificateAuthorizer(resourceBaseURI); err == nil { - return a, err - } - return nil, errors.New("auth file missing client and certificate credentials") -} - -// NewAuthorizerFromFileWithResource creates an Authorizer configured from a configuration file in the following order. -// 1. Client credentials -// 2. Client certificate -// The path to the configuration file must be specified in the AZURE_AUTH_LOCATION environment variable. -func NewAuthorizerFromFileWithResource(resource string) (autorest.Authorizer, error) { - s, err := GetSettingsFromFile() - if err != nil { - return nil, err - } - if a, err := s.ClientCredentialsAuthorizerWithResource(resource); err == nil { - return a, err - } - if a, err := s.ClientCertificateAuthorizerWithResource(resource); err == nil { - return a, err - } - return nil, errors.New("auth file missing client and certificate credentials") -} - -// NewAuthorizerFromCLI creates an Authorizer configured from Azure CLI 2.0 for local development scenarios. -func NewAuthorizerFromCLI() (autorest.Authorizer, error) { - settings, err := GetSettingsFromEnvironment() - if err != nil { - return nil, err - } - - if settings.Values[Resource] == "" { - settings.Values[Resource] = settings.Environment.ResourceManagerEndpoint - } - - return NewAuthorizerFromCLIWithResource(settings.Values[Resource]) -} - -// NewAuthorizerFromCLIWithResource creates an Authorizer configured from Azure CLI 2.0 for local development scenarios. -func NewAuthorizerFromCLIWithResource(resource string) (autorest.Authorizer, error) { - token, err := cli.GetTokenFromCLI(resource) - if err != nil { - return nil, err - } - - adalToken, err := token.ToADALToken() - if err != nil { - return nil, err - } - - return autorest.NewBearerAuthorizer(&adalToken), nil -} - -// GetSettingsFromFile returns the available authentication settings from an Azure CLI authentication file. -func GetSettingsFromFile() (FileSettings, error) { - s := FileSettings{} - fileLocation := os.Getenv("AZURE_AUTH_LOCATION") - if fileLocation == "" { - return s, errors.New("environment variable AZURE_AUTH_LOCATION is not set") - } - - contents, err := ioutil.ReadFile(fileLocation) - if err != nil { - return s, err - } - - // Auth file might be encoded - decoded, err := decode(contents) - if err != nil { - return s, err - } - - authFile := map[string]interface{}{} - err = json.Unmarshal(decoded, &authFile) - if err != nil { - return s, err - } - - s.Values = map[string]string{} - s.setKeyValue(ClientID, authFile["clientId"]) - s.setKeyValue(ClientSecret, authFile["clientSecret"]) - s.setKeyValue(CertificatePath, authFile["clientCertificate"]) - s.setKeyValue(CertificatePassword, authFile["clientCertificatePassword"]) - s.setKeyValue(SubscriptionID, authFile["subscriptionId"]) - s.setKeyValue(TenantID, authFile["tenantId"]) - s.setKeyValue(ActiveDirectoryEndpoint, authFile["activeDirectoryEndpointUrl"]) - s.setKeyValue(ResourceManagerEndpoint, authFile["resourceManagerEndpointUrl"]) - s.setKeyValue(GraphResourceID, authFile["activeDirectoryGraphResourceId"]) - s.setKeyValue(SQLManagementEndpoint, authFile["sqlManagementEndpointUrl"]) - s.setKeyValue(GalleryEndpoint, authFile["galleryEndpointUrl"]) - s.setKeyValue(ManagementEndpoint, authFile["managementEndpointUrl"]) - return s, nil -} - -// FileSettings contains the available authentication settings. -type FileSettings struct { - Values map[string]string -} - -// GetSubscriptionID returns the available subscription ID or an empty string. -func (settings FileSettings) GetSubscriptionID() string { - return settings.Values[SubscriptionID] -} - -// adds the specified value to the Values map if it isn't nil -func (settings FileSettings) setKeyValue(key string, val interface{}) { - if val != nil { - settings.Values[key] = val.(string) - } -} - -// returns the specified AAD endpoint or the public cloud endpoint if unspecified -func (settings FileSettings) getAADEndpoint() string { - if v, ok := settings.Values[ActiveDirectoryEndpoint]; ok { - return v - } - return azure.PublicCloud.ActiveDirectoryEndpoint -} - -// ServicePrincipalTokenFromClientCredentials creates a ServicePrincipalToken from the available client credentials. -func (settings FileSettings) ServicePrincipalTokenFromClientCredentials(baseURI string) (*adal.ServicePrincipalToken, error) { - resource, err := settings.getResourceForToken(baseURI) - if err != nil { - return nil, err - } - return settings.ServicePrincipalTokenFromClientCredentialsWithResource(resource) -} - -// ClientCredentialsAuthorizer creates an authorizer from the available client credentials. -func (settings FileSettings) ClientCredentialsAuthorizer(baseURI string) (autorest.Authorizer, error) { - resource, err := settings.getResourceForToken(baseURI) - if err != nil { - return nil, err - } - return settings.ClientCredentialsAuthorizerWithResource(resource) -} - -// ServicePrincipalTokenFromClientCredentialsWithResource creates a ServicePrincipalToken -// from the available client credentials and the specified resource. -func (settings FileSettings) ServicePrincipalTokenFromClientCredentialsWithResource(resource string) (*adal.ServicePrincipalToken, error) { - if _, ok := settings.Values[ClientSecret]; !ok { - return nil, errors.New("missing client secret") - } - config, err := adal.NewOAuthConfig(settings.getAADEndpoint(), settings.Values[TenantID]) - if err != nil { - return nil, err - } - return adal.NewServicePrincipalToken(*config, settings.Values[ClientID], settings.Values[ClientSecret], resource) -} - -func (settings FileSettings) clientCertificateConfigWithResource(resource string) (ClientCertificateConfig, error) { - if _, ok := settings.Values[CertificatePath]; !ok { - return ClientCertificateConfig{}, errors.New("missing certificate path") - } - cfg := NewClientCertificateConfig(settings.Values[CertificatePath], settings.Values[CertificatePassword], settings.Values[ClientID], settings.Values[TenantID]) - cfg.AADEndpoint = settings.getAADEndpoint() - cfg.Resource = resource - return cfg, nil -} - -// ClientCredentialsAuthorizerWithResource creates an authorizer from the available client credentials and the specified resource. -func (settings FileSettings) ClientCredentialsAuthorizerWithResource(resource string) (autorest.Authorizer, error) { - spToken, err := settings.ServicePrincipalTokenFromClientCredentialsWithResource(resource) - if err != nil { - return nil, err - } - return autorest.NewBearerAuthorizer(spToken), nil -} - -// ServicePrincipalTokenFromClientCertificate creates a ServicePrincipalToken from the available certificate credentials. -func (settings FileSettings) ServicePrincipalTokenFromClientCertificate(baseURI string) (*adal.ServicePrincipalToken, error) { - resource, err := settings.getResourceForToken(baseURI) - if err != nil { - return nil, err - } - return settings.ServicePrincipalTokenFromClientCertificateWithResource(resource) -} - -// ClientCertificateAuthorizer creates an authorizer from the available certificate credentials. -func (settings FileSettings) ClientCertificateAuthorizer(baseURI string) (autorest.Authorizer, error) { - resource, err := settings.getResourceForToken(baseURI) - if err != nil { - return nil, err - } - return settings.ClientCertificateAuthorizerWithResource(resource) -} - -// ServicePrincipalTokenFromClientCertificateWithResource creates a ServicePrincipalToken from the available certificate credentials. -func (settings FileSettings) ServicePrincipalTokenFromClientCertificateWithResource(resource string) (*adal.ServicePrincipalToken, error) { - cfg, err := settings.clientCertificateConfigWithResource(resource) - if err != nil { - return nil, err - } - return cfg.ServicePrincipalToken() -} - -// ClientCertificateAuthorizerWithResource creates an authorizer from the available certificate credentials and the specified resource. -func (settings FileSettings) ClientCertificateAuthorizerWithResource(resource string) (autorest.Authorizer, error) { - cfg, err := settings.clientCertificateConfigWithResource(resource) - if err != nil { - return nil, err - } - return cfg.Authorizer() -} - -func decode(b []byte) ([]byte, error) { - reader, enc := utfbom.Skip(bytes.NewReader(b)) - - switch enc { - case utfbom.UTF16LittleEndian: - u16 := make([]uint16, (len(b)/2)-1) - err := binary.Read(reader, binary.LittleEndian, &u16) - if err != nil { - return nil, err - } - return []byte(string(utf16.Decode(u16))), nil - case utfbom.UTF16BigEndian: - u16 := make([]uint16, (len(b)/2)-1) - err := binary.Read(reader, binary.BigEndian, &u16) - if err != nil { - return nil, err - } - return []byte(string(utf16.Decode(u16))), nil - } - return ioutil.ReadAll(reader) -} - -func (settings FileSettings) getResourceForToken(baseURI string) (string, error) { - // Compare default base URI from the SDK to the endpoints from the public cloud - // Base URI and token resource are the same string. This func finds the authentication - // file field that matches the SDK base URI. The SDK defines the public cloud - // endpoint as its default base URI - if !strings.HasSuffix(baseURI, "/") { - baseURI += "/" - } - switch baseURI { - case azure.PublicCloud.ServiceManagementEndpoint: - return settings.Values[ManagementEndpoint], nil - case azure.PublicCloud.ResourceManagerEndpoint: - return settings.Values[ResourceManagerEndpoint], nil - case azure.PublicCloud.ActiveDirectoryEndpoint: - return settings.Values[ActiveDirectoryEndpoint], nil - case azure.PublicCloud.GalleryEndpoint: - return settings.Values[GalleryEndpoint], nil - case azure.PublicCloud.GraphEndpoint: - return settings.Values[GraphResourceID], nil - } - return "", fmt.Errorf("auth: base URI not found in endpoints") -} - -// NewClientCredentialsConfig creates an AuthorizerConfig object configured to obtain an Authorizer through Client Credentials. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewClientCredentialsConfig(clientID string, clientSecret string, tenantID string) ClientCredentialsConfig { - return ClientCredentialsConfig{ - ClientID: clientID, - ClientSecret: clientSecret, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -// NewClientCertificateConfig creates a ClientCertificateConfig object configured to obtain an Authorizer through client certificate. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewClientCertificateConfig(certificatePath string, certificatePassword string, clientID string, tenantID string) ClientCertificateConfig { - return ClientCertificateConfig{ - CertificatePath: certificatePath, - CertificatePassword: certificatePassword, - ClientID: clientID, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -// NewUsernamePasswordConfig creates an UsernamePasswordConfig object configured to obtain an Authorizer through username and password. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewUsernamePasswordConfig(username string, password string, clientID string, tenantID string) UsernamePasswordConfig { - return UsernamePasswordConfig{ - Username: username, - Password: password, - ClientID: clientID, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -// NewMSIConfig creates an MSIConfig object configured to obtain an Authorizer through MSI. -func NewMSIConfig() MSIConfig { - return MSIConfig{ - Resource: azure.PublicCloud.ResourceManagerEndpoint, - } -} - -// NewDeviceFlowConfig creates a DeviceFlowConfig object configured to obtain an Authorizer through device flow. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewDeviceFlowConfig(clientID string, tenantID string) DeviceFlowConfig { - return DeviceFlowConfig{ - ClientID: clientID, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -//AuthorizerConfig provides an authorizer from the configuration provided. -type AuthorizerConfig interface { - Authorizer() (autorest.Authorizer, error) -} - -// ClientCredentialsConfig provides the options to get a bearer authorizer from client credentials. -type ClientCredentialsConfig struct { - ClientID string - ClientSecret string - TenantID string - AuxTenants []string - AADEndpoint string - Resource string -} - -// ServicePrincipalToken creates a ServicePrincipalToken from client credentials. -func (ccc ClientCredentialsConfig) ServicePrincipalToken() (*adal.ServicePrincipalToken, error) { - oauthConfig, err := adal.NewOAuthConfig(ccc.AADEndpoint, ccc.TenantID) - if err != nil { - return nil, err - } - return adal.NewServicePrincipalToken(*oauthConfig, ccc.ClientID, ccc.ClientSecret, ccc.Resource) -} - -// MultiTenantServicePrincipalToken creates a MultiTenantServicePrincipalToken from client credentials. -func (ccc ClientCredentialsConfig) MultiTenantServicePrincipalToken() (*adal.MultiTenantServicePrincipalToken, error) { - oauthConfig, err := adal.NewMultiTenantOAuthConfig(ccc.AADEndpoint, ccc.TenantID, ccc.AuxTenants, adal.OAuthOptions{}) - if err != nil { - return nil, err - } - return adal.NewMultiTenantServicePrincipalToken(oauthConfig, ccc.ClientID, ccc.ClientSecret, ccc.Resource) -} - -// Authorizer gets the authorizer from client credentials. -func (ccc ClientCredentialsConfig) Authorizer() (autorest.Authorizer, error) { - if len(ccc.AuxTenants) == 0 { - spToken, err := ccc.ServicePrincipalToken() - if err != nil { - return nil, fmt.Errorf("failed to get SPT from client credentials: %v", err) - } - return autorest.NewBearerAuthorizer(spToken), nil - } - mtSPT, err := ccc.MultiTenantServicePrincipalToken() - if err != nil { - return nil, fmt.Errorf("failed to get multitenant SPT from client credentials: %v", err) - } - return autorest.NewMultiTenantServicePrincipalTokenAuthorizer(mtSPT), nil -} - -// ClientCertificateConfig provides the options to get a bearer authorizer from a client certificate. -type ClientCertificateConfig struct { - ClientID string - CertificatePath string - CertificatePassword string - TenantID string - AuxTenants []string - AADEndpoint string - Resource string -} - -// ServicePrincipalToken creates a ServicePrincipalToken from client certificate. -func (ccc ClientCertificateConfig) ServicePrincipalToken() (*adal.ServicePrincipalToken, error) { - oauthConfig, err := adal.NewOAuthConfig(ccc.AADEndpoint, ccc.TenantID) - if err != nil { - return nil, err - } - certData, err := ioutil.ReadFile(ccc.CertificatePath) - if err != nil { - return nil, fmt.Errorf("failed to read the certificate file (%s): %v", ccc.CertificatePath, err) - } - certificate, rsaPrivateKey, err := adal.DecodePfxCertificateData(certData, ccc.CertificatePassword) - if err != nil { - return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err) - } - return adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, ccc.ClientID, certificate, rsaPrivateKey, ccc.Resource) -} - -// MultiTenantServicePrincipalToken creates a MultiTenantServicePrincipalToken from client certificate. -func (ccc ClientCertificateConfig) MultiTenantServicePrincipalToken() (*adal.MultiTenantServicePrincipalToken, error) { - oauthConfig, err := adal.NewMultiTenantOAuthConfig(ccc.AADEndpoint, ccc.TenantID, ccc.AuxTenants, adal.OAuthOptions{}) - if err != nil { - return nil, err - } - certData, err := ioutil.ReadFile(ccc.CertificatePath) - if err != nil { - return nil, fmt.Errorf("failed to read the certificate file (%s): %v", ccc.CertificatePath, err) - } - certificate, rsaPrivateKey, err := adal.DecodePfxCertificateData(certData, ccc.CertificatePassword) - if err != nil { - return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err) - } - return adal.NewMultiTenantServicePrincipalTokenFromCertificate(oauthConfig, ccc.ClientID, certificate, rsaPrivateKey, ccc.Resource) -} - -// Authorizer gets an authorizer object from client certificate. -func (ccc ClientCertificateConfig) Authorizer() (autorest.Authorizer, error) { - if len(ccc.AuxTenants) == 0 { - spToken, err := ccc.ServicePrincipalToken() - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from certificate auth: %v", err) - } - return autorest.NewBearerAuthorizer(spToken), nil - } - mtSPT, err := ccc.MultiTenantServicePrincipalToken() - if err != nil { - return nil, fmt.Errorf("failed to get multitenant SPT from certificate auth: %v", err) - } - return autorest.NewMultiTenantServicePrincipalTokenAuthorizer(mtSPT), nil -} - -// DeviceFlowConfig provides the options to get a bearer authorizer using device flow authentication. -type DeviceFlowConfig struct { - ClientID string - TenantID string - AADEndpoint string - Resource string -} - -// Authorizer gets the authorizer from device flow. -func (dfc DeviceFlowConfig) Authorizer() (autorest.Authorizer, error) { - spToken, err := dfc.ServicePrincipalToken() - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from device flow: %v", err) - } - return autorest.NewBearerAuthorizer(spToken), nil -} - -// ServicePrincipalToken gets the service principal token from device flow. -func (dfc DeviceFlowConfig) ServicePrincipalToken() (*adal.ServicePrincipalToken, error) { - oauthConfig, err := adal.NewOAuthConfig(dfc.AADEndpoint, dfc.TenantID) - if err != nil { - return nil, err - } - oauthClient := &autorest.Client{} - deviceCode, err := adal.InitiateDeviceAuth(oauthClient, *oauthConfig, dfc.ClientID, dfc.Resource) - if err != nil { - return nil, fmt.Errorf("failed to start device auth flow: %s", err) - } - log.Println(*deviceCode.Message) - token, err := adal.WaitForUserCompletion(oauthClient, deviceCode) - if err != nil { - return nil, fmt.Errorf("failed to finish device auth flow: %s", err) - } - return adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, dfc.ClientID, dfc.Resource, *token) -} - -// UsernamePasswordConfig provides the options to get a bearer authorizer from a username and a password. -type UsernamePasswordConfig struct { - ClientID string - Username string - Password string - TenantID string - AADEndpoint string - Resource string -} - -// ServicePrincipalToken creates a ServicePrincipalToken from username and password. -func (ups UsernamePasswordConfig) ServicePrincipalToken() (*adal.ServicePrincipalToken, error) { - oauthConfig, err := adal.NewOAuthConfig(ups.AADEndpoint, ups.TenantID) - if err != nil { - return nil, err - } - return adal.NewServicePrincipalTokenFromUsernamePassword(*oauthConfig, ups.ClientID, ups.Username, ups.Password, ups.Resource) -} - -// Authorizer gets the authorizer from a username and a password. -func (ups UsernamePasswordConfig) Authorizer() (autorest.Authorizer, error) { - spToken, err := ups.ServicePrincipalToken() - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from username and password auth: %v", err) - } - return autorest.NewBearerAuthorizer(spToken), nil -} - -// MSIConfig provides the options to get a bearer authorizer through MSI. -type MSIConfig struct { - Resource string - ClientID string -} - -// ServicePrincipalToken creates a ServicePrincipalToken from MSI. -func (mc MSIConfig) ServicePrincipalToken() (*adal.ServicePrincipalToken, error) { - spToken, err := adal.NewServicePrincipalTokenFromManagedIdentity(mc.Resource, &adal.ManagedIdentityOptions{ - ClientID: mc.ClientID, - }) - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from MSI: %v", err) - } - return spToken, nil -} - -// Authorizer gets the authorizer from MSI. -func (mc MSIConfig) Authorizer() (autorest.Authorizer, error) { - spToken, err := mc.ServicePrincipalToken() - if err != nil { - return nil, err - } - - return autorest.NewBearerAuthorizer(spToken), nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/auth/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/azure/auth/go_mod_tidy_hack.go deleted file mode 100644 index 38e4900a..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/auth/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package auth - -// Copyright 2017 Microsoft Corporation -// -// 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. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go b/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go deleted file mode 100644 index 0ded76bc..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go +++ /dev/null @@ -1,388 +0,0 @@ -// Package azure provides Azure-specific implementations used with AutoRest. -// See the included examples for more detail. -package azure - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "strconv" - "strings" - - "github.com/Azure/go-autorest/autorest" -) - -const ( - // HeaderClientID is the Azure extension header to set a user-specified request ID. - HeaderClientID = "x-ms-client-request-id" - - // HeaderReturnClientID is the Azure extension header to set if the user-specified request ID - // should be included in the response. - HeaderReturnClientID = "x-ms-return-client-request-id" - - // HeaderContentType is the type of the content in the HTTP response. - HeaderContentType = "Content-Type" - - // HeaderRequestID is the Azure extension header of the service generated request ID returned - // in the response. - HeaderRequestID = "x-ms-request-id" -) - -// ServiceError encapsulates the error response from an Azure service. -// It adhears to the OData v4 specification for error responses. -type ServiceError struct { - Code string `json:"code"` - Message string `json:"message"` - Target *string `json:"target"` - Details []map[string]interface{} `json:"details"` - InnerError map[string]interface{} `json:"innererror"` - AdditionalInfo []map[string]interface{} `json:"additionalInfo"` -} - -func (se ServiceError) Error() string { - result := fmt.Sprintf("Code=%q Message=%q", se.Code, se.Message) - - if se.Target != nil { - result += fmt.Sprintf(" Target=%q", *se.Target) - } - - if se.Details != nil { - d, err := json.Marshal(se.Details) - if err != nil { - result += fmt.Sprintf(" Details=%v", se.Details) - } - result += fmt.Sprintf(" Details=%v", string(d)) - } - - if se.InnerError != nil { - d, err := json.Marshal(se.InnerError) - if err != nil { - result += fmt.Sprintf(" InnerError=%v", se.InnerError) - } - result += fmt.Sprintf(" InnerError=%v", string(d)) - } - - if se.AdditionalInfo != nil { - d, err := json.Marshal(se.AdditionalInfo) - if err != nil { - result += fmt.Sprintf(" AdditionalInfo=%v", se.AdditionalInfo) - } - result += fmt.Sprintf(" AdditionalInfo=%v", string(d)) - } - - return result -} - -// UnmarshalJSON implements the json.Unmarshaler interface for the ServiceError type. -func (se *ServiceError) UnmarshalJSON(b []byte) error { - // http://docs.oasis-open.org/odata/odata-json-format/v4.0/os/odata-json-format-v4.0-os.html#_Toc372793091 - - type serviceErrorInternal struct { - Code string `json:"code"` - Message string `json:"message"` - Target *string `json:"target,omitempty"` - AdditionalInfo []map[string]interface{} `json:"additionalInfo,omitempty"` - // not all services conform to the OData v4 spec. - // the following fields are where we've seen discrepancies - - // spec calls for []map[string]interface{} but have seen map[string]interface{} - Details interface{} `json:"details,omitempty"` - - // spec calls for map[string]interface{} but have seen []map[string]interface{} and string - InnerError interface{} `json:"innererror,omitempty"` - } - - sei := serviceErrorInternal{} - if err := json.Unmarshal(b, &sei); err != nil { - return err - } - - // copy the fields we know to be correct - se.AdditionalInfo = sei.AdditionalInfo - se.Code = sei.Code - se.Message = sei.Message - se.Target = sei.Target - - // converts an []interface{} to []map[string]interface{} - arrayOfObjs := func(v interface{}) ([]map[string]interface{}, bool) { - arrayOf, ok := v.([]interface{}) - if !ok { - return nil, false - } - final := []map[string]interface{}{} - for _, item := range arrayOf { - as, ok := item.(map[string]interface{}) - if !ok { - return nil, false - } - final = append(final, as) - } - return final, true - } - - // convert the remaining fields, falling back to raw JSON if necessary - - if c, ok := arrayOfObjs(sei.Details); ok { - se.Details = c - } else if c, ok := sei.Details.(map[string]interface{}); ok { - se.Details = []map[string]interface{}{c} - } else if sei.Details != nil { - // stuff into Details - se.Details = []map[string]interface{}{ - {"raw": sei.Details}, - } - } - - if c, ok := sei.InnerError.(map[string]interface{}); ok { - se.InnerError = c - } else if c, ok := arrayOfObjs(sei.InnerError); ok { - // if there's only one error extract it - if len(c) == 1 { - se.InnerError = c[0] - } else { - // multiple errors, stuff them into the value - se.InnerError = map[string]interface{}{ - "multi": c, - } - } - } else if c, ok := sei.InnerError.(string); ok { - se.InnerError = map[string]interface{}{"error": c} - } else if sei.InnerError != nil { - // stuff into InnerError - se.InnerError = map[string]interface{}{ - "raw": sei.InnerError, - } - } - return nil -} - -// RequestError describes an error response returned by Azure service. -type RequestError struct { - autorest.DetailedError - - // The error returned by the Azure service. - ServiceError *ServiceError `json:"error" xml:"Error"` - - // The request id (from the x-ms-request-id-header) of the request. - RequestID string -} - -// Error returns a human-friendly error message from service error. -func (e RequestError) Error() string { - return fmt.Sprintf("autorest/azure: Service returned an error. Status=%v %v", - e.StatusCode, e.ServiceError) -} - -// IsAzureError returns true if the passed error is an Azure Service error; false otherwise. -func IsAzureError(e error) bool { - _, ok := e.(*RequestError) - return ok -} - -// Resource contains details about an Azure resource. -type Resource struct { - SubscriptionID string - ResourceGroup string - Provider string - ResourceType string - ResourceName string -} - -// String function returns a string in form of azureResourceID -func (r Resource) String() string { - return fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/%s/%s/%s", r.SubscriptionID, r.ResourceGroup, r.Provider, r.ResourceType, r.ResourceName) -} - -// ParseResourceID parses a resource ID into a ResourceDetails struct. -// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-template-functions-resource#return-value-4. -func ParseResourceID(resourceID string) (Resource, error) { - - const resourceIDPatternText = `(?i)subscriptions/(.+)/resourceGroups/(.+)/providers/(.+?)/(.+?)/(.+)` - resourceIDPattern := regexp.MustCompile(resourceIDPatternText) - match := resourceIDPattern.FindStringSubmatch(resourceID) - - if len(match) == 0 { - return Resource{}, fmt.Errorf("parsing failed for %s. Invalid resource Id format", resourceID) - } - - v := strings.Split(match[5], "/") - resourceName := v[len(v)-1] - - result := Resource{ - SubscriptionID: match[1], - ResourceGroup: match[2], - Provider: match[3], - ResourceType: match[4], - ResourceName: resourceName, - } - - return result, nil -} - -// NewErrorWithError creates a new Error conforming object from the -// passed packageType, method, statusCode of the given resp (UndefinedStatusCode -// if resp is nil), message, and original error. message is treated as a format -// string to which the optional args apply. -func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) RequestError { - if v, ok := original.(*RequestError); ok { - return *v - } - - statusCode := autorest.UndefinedStatusCode - if resp != nil { - statusCode = resp.StatusCode - } - return RequestError{ - DetailedError: autorest.DetailedError{ - Original: original, - PackageType: packageType, - Method: method, - StatusCode: statusCode, - Message: fmt.Sprintf(message, args...), - }, - } -} - -// WithReturningClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-client-request-id whose value is the passed, undecorated UUID (e.g., -// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). It also sets the x-ms-return-client-request-id -// header to true such that UUID accompanies the http.Response. -func WithReturningClientID(uuid string) autorest.PrepareDecorator { - preparer := autorest.CreatePreparer( - WithClientID(uuid), - WithReturnClientID(true)) - - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err != nil { - return r, err - } - return preparer.Prepare(r) - }) - } -} - -// WithClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-client-request-id whose value is passed, undecorated UUID (e.g., -// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). -func WithClientID(uuid string) autorest.PrepareDecorator { - return autorest.WithHeader(HeaderClientID, uuid) -} - -// WithReturnClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-return-client-request-id whose boolean value indicates if the value of the -// x-ms-client-request-id header should be included in the http.Response. -func WithReturnClientID(b bool) autorest.PrepareDecorator { - return autorest.WithHeader(HeaderReturnClientID, strconv.FormatBool(b)) -} - -// ExtractClientID extracts the client identifier from the x-ms-client-request-id header set on the -// http.Request sent to the service (and returned in the http.Response) -func ExtractClientID(resp *http.Response) string { - return autorest.ExtractHeaderValue(HeaderClientID, resp) -} - -// ExtractRequestID extracts the Azure server generated request identifier from the -// x-ms-request-id header. -func ExtractRequestID(resp *http.Response) string { - return autorest.ExtractHeaderValue(HeaderRequestID, resp) -} - -// WithErrorUnlessStatusCode returns a RespondDecorator that emits an -// azure.RequestError by reading the response body unless the response HTTP status code -// is among the set passed. -// -// If there is a chance service may return responses other than the Azure error -// format and the response cannot be parsed into an error, a decoding error will -// be returned containing the response body. In any case, the Responder will -// return an error if the status code is not satisfied. -// -// If this Responder returns an error, the response body will be replaced with -// an in-memory reader, which needs no further closing. -func WithErrorUnlessStatusCode(codes ...int) autorest.RespondDecorator { - return func(r autorest.Responder) autorest.Responder { - return autorest.ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && !autorest.ResponseHasStatusCode(resp, codes...) { - var e RequestError - defer resp.Body.Close() - - encodedAs := autorest.EncodedAsJSON - if strings.Contains(resp.Header.Get("Content-Type"), "xml") { - encodedAs = autorest.EncodedAsXML - } - - // Copy and replace the Body in case it does not contain an error object. - // This will leave the Body available to the caller. - b, decodeErr := autorest.CopyAndDecode(encodedAs, resp.Body, &e) - resp.Body = ioutil.NopCloser(&b) - if decodeErr != nil { - return fmt.Errorf("autorest/azure: error response cannot be parsed: %q error: %v", b.String(), decodeErr) - } - if e.ServiceError == nil { - // Check if error is unwrapped ServiceError - decoder := autorest.NewDecoder(encodedAs, bytes.NewReader(b.Bytes())) - if err := decoder.Decode(&e.ServiceError); err != nil { - return fmt.Errorf("autorest/azure: error response cannot be parsed: %q error: %v", b.String(), err) - } - - // for example, should the API return the literal value `null` as the response - if e.ServiceError == nil { - e.ServiceError = &ServiceError{ - Code: "Unknown", - Message: "Unknown service error", - Details: []map[string]interface{}{ - { - "HttpResponse.Body": b.String(), - }, - }, - } - } - } - - if e.ServiceError != nil && e.ServiceError.Message == "" { - // if we're here it means the returned error wasn't OData v4 compliant. - // try to unmarshal the body in hopes of getting something. - rawBody := map[string]interface{}{} - decoder := autorest.NewDecoder(encodedAs, bytes.NewReader(b.Bytes())) - if err := decoder.Decode(&rawBody); err != nil { - return fmt.Errorf("autorest/azure: error response cannot be parsed: %q error: %v", b.String(), err) - } - - e.ServiceError = &ServiceError{ - Code: "Unknown", - Message: "Unknown service error", - } - if len(rawBody) > 0 { - e.ServiceError.Details = []map[string]interface{}{rawBody} - } - } - e.Response = resp - e.RequestID = ExtractRequestID(resp) - if e.StatusCode == nil { - e.StatusCode = resp.StatusCode - } - err = &e - } - return err - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/LICENSE deleted file mode 100644 index b9d6a27e..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2015 Microsoft Corporation - - 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/Azure/go-autorest/autorest/azure/cli/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/go_mod_tidy_hack.go deleted file mode 100644 index 861ce298..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package cli - -// Copyright 2017 Microsoft Corporation -// -// 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. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/profile.go b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/profile.go deleted file mode 100644 index f45c3a51..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/profile.go +++ /dev/null @@ -1,83 +0,0 @@ -package cli - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "github.com/dimchansky/utfbom" - "github.com/mitchellh/go-homedir" -) - -// Profile represents a Profile from the Azure CLI -type Profile struct { - InstallationID string `json:"installationId"` - Subscriptions []Subscription `json:"subscriptions"` -} - -// Subscription represents a Subscription from the Azure CLI -type Subscription struct { - EnvironmentName string `json:"environmentName"` - ID string `json:"id"` - IsDefault bool `json:"isDefault"` - Name string `json:"name"` - State string `json:"state"` - TenantID string `json:"tenantId"` - User *User `json:"user"` -} - -// User represents a User from the Azure CLI -type User struct { - Name string `json:"name"` - Type string `json:"type"` -} - -const azureProfileJSON = "azureProfile.json" - -func configDir() string { - return os.Getenv("AZURE_CONFIG_DIR") -} - -// ProfilePath returns the path where the Azure Profile is stored from the Azure CLI -func ProfilePath() (string, error) { - if cfgDir := configDir(); cfgDir != "" { - return filepath.Join(cfgDir, azureProfileJSON), nil - } - return homedir.Expand("~/.azure/" + azureProfileJSON) -} - -// LoadProfile restores a Profile object from a file located at 'path'. -func LoadProfile(path string) (result Profile, err error) { - var contents []byte - contents, err = ioutil.ReadFile(path) - if err != nil { - err = fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) - return - } - reader := utfbom.SkipOnly(bytes.NewReader(contents)) - - dec := json.NewDecoder(reader) - if err = dec.Decode(&result); err != nil { - err = fmt.Errorf("failed to decode contents of file (%s) into a Profile representation: %v", path, err) - return - } - - return -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/token.go b/vendor/github.com/Azure/go-autorest/autorest/azure/cli/token.go deleted file mode 100644 index 44ff446f..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/cli/token.go +++ /dev/null @@ -1,175 +0,0 @@ -package cli - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "encoding/json" - "fmt" - "os" - "os/exec" - "path/filepath" - "regexp" - "runtime" - "strconv" - "time" - - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/date" - "github.com/mitchellh/go-homedir" -) - -// Token represents an AccessToken from the Azure CLI -type Token struct { - AccessToken string `json:"accessToken"` - Authority string `json:"_authority"` - ClientID string `json:"_clientId"` - ExpiresOn string `json:"expiresOn"` - IdentityProvider string `json:"identityProvider"` - IsMRRT bool `json:"isMRRT"` - RefreshToken string `json:"refreshToken"` - Resource string `json:"resource"` - TokenType string `json:"tokenType"` - UserID string `json:"userId"` -} - -const accessTokensJSON = "accessTokens.json" - -// ToADALToken converts an Azure CLI `Token`` to an `adal.Token`` -func (t Token) ToADALToken() (converted adal.Token, err error) { - tokenExpirationDate, err := ParseExpirationDate(t.ExpiresOn) - if err != nil { - err = fmt.Errorf("Error parsing Token Expiration Date %q: %+v", t.ExpiresOn, err) - return - } - - difference := tokenExpirationDate.Sub(date.UnixEpoch()) - - converted = adal.Token{ - AccessToken: t.AccessToken, - Type: t.TokenType, - ExpiresIn: "3600", - ExpiresOn: json.Number(strconv.Itoa(int(difference.Seconds()))), - RefreshToken: t.RefreshToken, - Resource: t.Resource, - } - return -} - -// AccessTokensPath returns the path where access tokens are stored from the Azure CLI -// TODO(#199): add unit test. -func AccessTokensPath() (string, error) { - // Azure-CLI allows user to customize the path of access tokens through environment variable. - if accessTokenPath := os.Getenv("AZURE_ACCESS_TOKEN_FILE"); accessTokenPath != "" { - return accessTokenPath, nil - } - - // Azure-CLI allows user to customize the path to Azure config directory through environment variable. - if cfgDir := configDir(); cfgDir != "" { - return filepath.Join(cfgDir, accessTokensJSON), nil - } - - // Fallback logic to default path on non-cloud-shell environment. - // TODO(#200): remove the dependency on hard-coding path. - return homedir.Expand("~/.azure/" + accessTokensJSON) -} - -// ParseExpirationDate parses either a Azure CLI or CloudShell date into a time object -func ParseExpirationDate(input string) (*time.Time, error) { - // CloudShell (and potentially the Azure CLI in future) - expirationDate, cloudShellErr := time.Parse(time.RFC3339, input) - if cloudShellErr != nil { - // Azure CLI (Python) e.g. 2017-08-31 19:48:57.998857 (plus the local timezone) - const cliFormat = "2006-01-02 15:04:05.999999" - expirationDate, cliErr := time.ParseInLocation(cliFormat, input, time.Local) - if cliErr == nil { - return &expirationDate, nil - } - - return nil, fmt.Errorf("Error parsing expiration date %q.\n\nCloudShell Error: \n%+v\n\nCLI Error:\n%+v", input, cloudShellErr, cliErr) - } - - return &expirationDate, nil -} - -// LoadTokens restores a set of Token objects from a file located at 'path'. -func LoadTokens(path string) ([]Token, error) { - file, err := os.Open(path) - if err != nil { - return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) - } - defer file.Close() - - var tokens []Token - - dec := json.NewDecoder(file) - if err = dec.Decode(&tokens); err != nil { - return nil, fmt.Errorf("failed to decode contents of file (%s) into a `cli.Token` representation: %v", path, err) - } - - return tokens, nil -} - -// GetTokenFromCLI gets a token using Azure CLI 2.0 for local development scenarios. -func GetTokenFromCLI(resource string) (*Token, error) { - // This is the path that a developer can set to tell this class what the install path for Azure CLI is. - const azureCLIPath = "AzureCLIPath" - - // The default install paths are used to find Azure CLI. This is for security, so that any path in the calling program's Path environment is not used to execute Azure CLI. - azureCLIDefaultPathWindows := fmt.Sprintf("%s\\Microsoft SDKs\\Azure\\CLI2\\wbin; %s\\Microsoft SDKs\\Azure\\CLI2\\wbin", os.Getenv("ProgramFiles(x86)"), os.Getenv("ProgramFiles")) - - // Default path for non-Windows. - const azureCLIDefaultPath = "/bin:/sbin:/usr/bin:/usr/local/bin" - - // Validate resource, since it gets sent as a command line argument to Azure CLI - const invalidResourceErrorTemplate = "Resource %s is not in expected format. Only alphanumeric characters, [dot], [colon], [hyphen], and [forward slash] are allowed." - match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource) - if err != nil { - return nil, err - } - if !match { - return nil, fmt.Errorf(invalidResourceErrorTemplate, resource) - } - - // Execute Azure CLI to get token - var cliCmd *exec.Cmd - if runtime.GOOS == "windows" { - cliCmd = exec.Command(fmt.Sprintf("%s\\system32\\cmd.exe", os.Getenv("windir"))) - cliCmd.Env = os.Environ() - cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s;%s", os.Getenv(azureCLIPath), azureCLIDefaultPathWindows)) - cliCmd.Args = append(cliCmd.Args, "/c", "az") - } else { - cliCmd = exec.Command("az") - cliCmd.Env = os.Environ() - cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s:%s", os.Getenv(azureCLIPath), azureCLIDefaultPath)) - } - cliCmd.Args = append(cliCmd.Args, "account", "get-access-token", "-o", "json", "--resource", resource) - - var stderr bytes.Buffer - cliCmd.Stderr = &stderr - - output, err := cliCmd.Output() - if err != nil { - return nil, fmt.Errorf("Invoking Azure CLI failed with the following error: %s", stderr.String()) - } - - tokenResponse := Token{} - err = json.Unmarshal(output, &tokenResponse) - if err != nil { - return nil, err - } - - return &tokenResponse, err -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go deleted file mode 100644 index 9bbc0899..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go +++ /dev/null @@ -1,269 +0,0 @@ -package azure - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "strings" -) - -const ( - // EnvironmentFilepathName captures the name of the environment variable containing the path to the file - // to be used while populating the Azure Environment. - EnvironmentFilepathName = "AZURE_ENVIRONMENT_FILEPATH" - - // NotAvailable is used for endpoints and resource IDs that are not available for a given cloud. - NotAvailable = "N/A" -) - -var environments = map[string]Environment{ - "AZURECHINACLOUD": ChinaCloud, - "AZUREGERMANCLOUD": GermanCloud, - "AZUREPUBLICCLOUD": PublicCloud, - "AZUREUSGOVERNMENTCLOUD": USGovernmentCloud, -} - -// ResourceIdentifier contains a set of Azure resource IDs. -type ResourceIdentifier struct { - Graph string `json:"graph"` - KeyVault string `json:"keyVault"` - Datalake string `json:"datalake"` - Batch string `json:"batch"` - OperationalInsights string `json:"operationalInsights"` - Storage string `json:"storage"` - Synapse string `json:"synapse"` - ServiceBus string `json:"serviceBus"` -} - -// Environment represents a set of endpoints for each of Azure's Clouds. -type Environment struct { - Name string `json:"name"` - ManagementPortalURL string `json:"managementPortalURL"` - PublishSettingsURL string `json:"publishSettingsURL"` - ServiceManagementEndpoint string `json:"serviceManagementEndpoint"` - ResourceManagerEndpoint string `json:"resourceManagerEndpoint"` - ActiveDirectoryEndpoint string `json:"activeDirectoryEndpoint"` - GalleryEndpoint string `json:"galleryEndpoint"` - KeyVaultEndpoint string `json:"keyVaultEndpoint"` - GraphEndpoint string `json:"graphEndpoint"` - ServiceBusEndpoint string `json:"serviceBusEndpoint"` - BatchManagementEndpoint string `json:"batchManagementEndpoint"` - StorageEndpointSuffix string `json:"storageEndpointSuffix"` - SQLDatabaseDNSSuffix string `json:"sqlDatabaseDNSSuffix"` - TrafficManagerDNSSuffix string `json:"trafficManagerDNSSuffix"` - KeyVaultDNSSuffix string `json:"keyVaultDNSSuffix"` - ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"` - ServiceManagementVMDNSSuffix string `json:"serviceManagementVMDNSSuffix"` - ResourceManagerVMDNSSuffix string `json:"resourceManagerVMDNSSuffix"` - ContainerRegistryDNSSuffix string `json:"containerRegistryDNSSuffix"` - CosmosDBDNSSuffix string `json:"cosmosDBDNSSuffix"` - TokenAudience string `json:"tokenAudience"` - APIManagementHostNameSuffix string `json:"apiManagementHostNameSuffix"` - SynapseEndpointSuffix string `json:"synapseEndpointSuffix"` - ResourceIdentifiers ResourceIdentifier `json:"resourceIdentifiers"` -} - -var ( - // PublicCloud is the default public Azure cloud environment - PublicCloud = Environment{ - Name: "AzurePublicCloud", - ManagementPortalURL: "https://manage.windowsazure.com/", - PublishSettingsURL: "https://manage.windowsazure.com/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.windows.net/", - ResourceManagerEndpoint: "https://management.azure.com/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", - GalleryEndpoint: "https://gallery.azure.com/", - KeyVaultEndpoint: "https://vault.azure.net/", - GraphEndpoint: "https://graph.windows.net/", - ServiceBusEndpoint: "https://servicebus.windows.net/", - BatchManagementEndpoint: "https://batch.core.windows.net/", - StorageEndpointSuffix: "core.windows.net", - SQLDatabaseDNSSuffix: "database.windows.net", - TrafficManagerDNSSuffix: "trafficmanager.net", - KeyVaultDNSSuffix: "vault.azure.net", - ServiceBusEndpointSuffix: "servicebus.windows.net", - ServiceManagementVMDNSSuffix: "cloudapp.net", - ResourceManagerVMDNSSuffix: "cloudapp.azure.com", - ContainerRegistryDNSSuffix: "azurecr.io", - CosmosDBDNSSuffix: "documents.azure.com", - TokenAudience: "https://management.azure.com/", - APIManagementHostNameSuffix: "azure-api.net", - SynapseEndpointSuffix: "dev.azuresynapse.net", - ResourceIdentifiers: ResourceIdentifier{ - Graph: "https://graph.windows.net/", - KeyVault: "https://vault.azure.net", - Datalake: "https://datalake.azure.net/", - Batch: "https://batch.core.windows.net/", - OperationalInsights: "https://api.loganalytics.io", - Storage: "https://storage.azure.com/", - Synapse: "https://dev.azuresynapse.net", - ServiceBus: "https://servicebus.azure.net/", - }, - } - - // USGovernmentCloud is the cloud environment for the US Government - USGovernmentCloud = Environment{ - Name: "AzureUSGovernmentCloud", - ManagementPortalURL: "https://manage.windowsazure.us/", - PublishSettingsURL: "https://manage.windowsazure.us/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.usgovcloudapi.net/", - ResourceManagerEndpoint: "https://management.usgovcloudapi.net/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.us/", - GalleryEndpoint: "https://gallery.usgovcloudapi.net/", - KeyVaultEndpoint: "https://vault.usgovcloudapi.net/", - GraphEndpoint: "https://graph.windows.net/", - ServiceBusEndpoint: "https://servicebus.usgovcloudapi.net/", - BatchManagementEndpoint: "https://batch.core.usgovcloudapi.net/", - StorageEndpointSuffix: "core.usgovcloudapi.net", - SQLDatabaseDNSSuffix: "database.usgovcloudapi.net", - TrafficManagerDNSSuffix: "usgovtrafficmanager.net", - KeyVaultDNSSuffix: "vault.usgovcloudapi.net", - ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net", - ServiceManagementVMDNSSuffix: "usgovcloudapp.net", - ResourceManagerVMDNSSuffix: "cloudapp.usgovcloudapi.net", - ContainerRegistryDNSSuffix: "azurecr.us", - CosmosDBDNSSuffix: "documents.azure.us", - TokenAudience: "https://management.usgovcloudapi.net/", - APIManagementHostNameSuffix: "azure-api.us", - SynapseEndpointSuffix: NotAvailable, - ResourceIdentifiers: ResourceIdentifier{ - Graph: "https://graph.windows.net/", - KeyVault: "https://vault.usgovcloudapi.net", - Datalake: NotAvailable, - Batch: "https://batch.core.usgovcloudapi.net/", - OperationalInsights: "https://api.loganalytics.us", - Storage: "https://storage.azure.com/", - Synapse: NotAvailable, - ServiceBus: "https://servicebus.azure.net/", - }, - } - - // ChinaCloud is the cloud environment operated in China - ChinaCloud = Environment{ - Name: "AzureChinaCloud", - ManagementPortalURL: "https://manage.chinacloudapi.com/", - PublishSettingsURL: "https://manage.chinacloudapi.com/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.chinacloudapi.cn/", - ResourceManagerEndpoint: "https://management.chinacloudapi.cn/", - ActiveDirectoryEndpoint: "https://login.chinacloudapi.cn/", - GalleryEndpoint: "https://gallery.chinacloudapi.cn/", - KeyVaultEndpoint: "https://vault.azure.cn/", - GraphEndpoint: "https://graph.chinacloudapi.cn/", - ServiceBusEndpoint: "https://servicebus.chinacloudapi.cn/", - BatchManagementEndpoint: "https://batch.chinacloudapi.cn/", - StorageEndpointSuffix: "core.chinacloudapi.cn", - SQLDatabaseDNSSuffix: "database.chinacloudapi.cn", - TrafficManagerDNSSuffix: "trafficmanager.cn", - KeyVaultDNSSuffix: "vault.azure.cn", - ServiceBusEndpointSuffix: "servicebus.chinacloudapi.cn", - ServiceManagementVMDNSSuffix: "chinacloudapp.cn", - ResourceManagerVMDNSSuffix: "cloudapp.chinacloudapi.cn", - ContainerRegistryDNSSuffix: "azurecr.cn", - CosmosDBDNSSuffix: "documents.azure.cn", - TokenAudience: "https://management.chinacloudapi.cn/", - APIManagementHostNameSuffix: "azure-api.cn", - SynapseEndpointSuffix: "dev.azuresynapse.azure.cn", - ResourceIdentifiers: ResourceIdentifier{ - Graph: "https://graph.chinacloudapi.cn/", - KeyVault: "https://vault.azure.cn", - Datalake: NotAvailable, - Batch: "https://batch.chinacloudapi.cn/", - OperationalInsights: NotAvailable, - Storage: "https://storage.azure.com/", - Synapse: "https://dev.azuresynapse.net", - ServiceBus: "https://servicebus.azure.net/", - }, - } - - // GermanCloud is the cloud environment operated in Germany - GermanCloud = Environment{ - Name: "AzureGermanCloud", - ManagementPortalURL: "http://portal.microsoftazure.de/", - PublishSettingsURL: "https://manage.microsoftazure.de/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.cloudapi.de/", - ResourceManagerEndpoint: "https://management.microsoftazure.de/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.de/", - GalleryEndpoint: "https://gallery.cloudapi.de/", - KeyVaultEndpoint: "https://vault.microsoftazure.de/", - GraphEndpoint: "https://graph.cloudapi.de/", - ServiceBusEndpoint: "https://servicebus.cloudapi.de/", - BatchManagementEndpoint: "https://batch.cloudapi.de/", - StorageEndpointSuffix: "core.cloudapi.de", - SQLDatabaseDNSSuffix: "database.cloudapi.de", - TrafficManagerDNSSuffix: "azuretrafficmanager.de", - KeyVaultDNSSuffix: "vault.microsoftazure.de", - ServiceBusEndpointSuffix: "servicebus.cloudapi.de", - ServiceManagementVMDNSSuffix: "azurecloudapp.de", - ResourceManagerVMDNSSuffix: "cloudapp.microsoftazure.de", - ContainerRegistryDNSSuffix: NotAvailable, - CosmosDBDNSSuffix: "documents.microsoftazure.de", - TokenAudience: "https://management.microsoftazure.de/", - APIManagementHostNameSuffix: NotAvailable, - SynapseEndpointSuffix: NotAvailable, - ResourceIdentifiers: ResourceIdentifier{ - Graph: "https://graph.cloudapi.de/", - KeyVault: "https://vault.microsoftazure.de", - Datalake: NotAvailable, - Batch: "https://batch.cloudapi.de/", - OperationalInsights: NotAvailable, - Storage: "https://storage.azure.com/", - Synapse: NotAvailable, - ServiceBus: "https://servicebus.azure.net/", - }, - } -) - -// EnvironmentFromName returns an Environment based on the common name specified. -func EnvironmentFromName(name string) (Environment, error) { - // IMPORTANT - // As per @radhikagupta5: - // This is technical debt, fundamentally here because Kubernetes is not currently accepting - // contributions to the providers. Once that is an option, the provider should be updated to - // directly call `EnvironmentFromFile`. Until then, we rely on dispatching Azure Stack environment creation - // from this method based on the name that is provided to us. - if strings.EqualFold(name, "AZURESTACKCLOUD") { - return EnvironmentFromFile(os.Getenv(EnvironmentFilepathName)) - } - - name = strings.ToUpper(name) - env, ok := environments[name] - if !ok { - return env, fmt.Errorf("autorest/azure: There is no cloud environment matching the name %q", name) - } - - return env, nil -} - -// EnvironmentFromFile loads an Environment from a configuration file available on disk. -// This function is particularly useful in the Hybrid Cloud model, where one must define their own -// endpoints. -func EnvironmentFromFile(location string) (unmarshaled Environment, err error) { - fileContents, err := ioutil.ReadFile(location) - if err != nil { - return - } - - err = json.Unmarshal(fileContents, &unmarshaled) - - return -} - -// SetEnvironment updates the environment map with the specified values. -func SetEnvironment(name string, env Environment) { - environments[strings.ToUpper(name)] = env -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go b/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go deleted file mode 100644 index 507f9e95..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go +++ /dev/null @@ -1,245 +0,0 @@ -package azure - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" -) - -// Copyright 2017 Microsoft Corporation -// -// 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. - -type audience []string - -type authentication struct { - LoginEndpoint string `json:"loginEndpoint"` - Audiences audience `json:"audiences"` -} - -type environmentMetadataInfo struct { - GalleryEndpoint string `json:"galleryEndpoint"` - GraphEndpoint string `json:"graphEndpoint"` - PortalEndpoint string `json:"portalEndpoint"` - Authentication authentication `json:"authentication"` -} - -// EnvironmentProperty represent property names that clients can override -type EnvironmentProperty string - -const ( - // EnvironmentName ... - EnvironmentName EnvironmentProperty = "name" - // EnvironmentManagementPortalURL .. - EnvironmentManagementPortalURL EnvironmentProperty = "managementPortalURL" - // EnvironmentPublishSettingsURL ... - EnvironmentPublishSettingsURL EnvironmentProperty = "publishSettingsURL" - // EnvironmentServiceManagementEndpoint ... - EnvironmentServiceManagementEndpoint EnvironmentProperty = "serviceManagementEndpoint" - // EnvironmentResourceManagerEndpoint ... - EnvironmentResourceManagerEndpoint EnvironmentProperty = "resourceManagerEndpoint" - // EnvironmentActiveDirectoryEndpoint ... - EnvironmentActiveDirectoryEndpoint EnvironmentProperty = "activeDirectoryEndpoint" - // EnvironmentGalleryEndpoint ... - EnvironmentGalleryEndpoint EnvironmentProperty = "galleryEndpoint" - // EnvironmentKeyVaultEndpoint ... - EnvironmentKeyVaultEndpoint EnvironmentProperty = "keyVaultEndpoint" - // EnvironmentGraphEndpoint ... - EnvironmentGraphEndpoint EnvironmentProperty = "graphEndpoint" - // EnvironmentServiceBusEndpoint ... - EnvironmentServiceBusEndpoint EnvironmentProperty = "serviceBusEndpoint" - // EnvironmentBatchManagementEndpoint ... - EnvironmentBatchManagementEndpoint EnvironmentProperty = "batchManagementEndpoint" - // EnvironmentStorageEndpointSuffix ... - EnvironmentStorageEndpointSuffix EnvironmentProperty = "storageEndpointSuffix" - // EnvironmentSQLDatabaseDNSSuffix ... - EnvironmentSQLDatabaseDNSSuffix EnvironmentProperty = "sqlDatabaseDNSSuffix" - // EnvironmentTrafficManagerDNSSuffix ... - EnvironmentTrafficManagerDNSSuffix EnvironmentProperty = "trafficManagerDNSSuffix" - // EnvironmentKeyVaultDNSSuffix ... - EnvironmentKeyVaultDNSSuffix EnvironmentProperty = "keyVaultDNSSuffix" - // EnvironmentServiceBusEndpointSuffix ... - EnvironmentServiceBusEndpointSuffix EnvironmentProperty = "serviceBusEndpointSuffix" - // EnvironmentServiceManagementVMDNSSuffix ... - EnvironmentServiceManagementVMDNSSuffix EnvironmentProperty = "serviceManagementVMDNSSuffix" - // EnvironmentResourceManagerVMDNSSuffix ... - EnvironmentResourceManagerVMDNSSuffix EnvironmentProperty = "resourceManagerVMDNSSuffix" - // EnvironmentContainerRegistryDNSSuffix ... - EnvironmentContainerRegistryDNSSuffix EnvironmentProperty = "containerRegistryDNSSuffix" - // EnvironmentTokenAudience ... - EnvironmentTokenAudience EnvironmentProperty = "tokenAudience" -) - -// OverrideProperty represents property name and value that clients can override -type OverrideProperty struct { - Key EnvironmentProperty - Value string -} - -// EnvironmentFromURL loads an Environment from a URL -// This function is particularly useful in the Hybrid Cloud model, where one may define their own -// endpoints. -func EnvironmentFromURL(resourceManagerEndpoint string, properties ...OverrideProperty) (environment Environment, err error) { - var metadataEnvProperties environmentMetadataInfo - - if resourceManagerEndpoint == "" { - return environment, fmt.Errorf("Metadata resource manager endpoint is empty") - } - - if metadataEnvProperties, err = retrieveMetadataEnvironment(resourceManagerEndpoint); err != nil { - return environment, err - } - - // Give priority to user's override values - overrideProperties(&environment, properties) - - if environment.Name == "" { - environment.Name = "HybridEnvironment" - } - stampDNSSuffix := environment.StorageEndpointSuffix - if stampDNSSuffix == "" { - stampDNSSuffix = strings.TrimSuffix(strings.TrimPrefix(strings.Replace(resourceManagerEndpoint, strings.Split(resourceManagerEndpoint, ".")[0], "", 1), "."), "/") - environment.StorageEndpointSuffix = stampDNSSuffix - } - if environment.KeyVaultDNSSuffix == "" { - environment.KeyVaultDNSSuffix = fmt.Sprintf("%s.%s", "vault", stampDNSSuffix) - } - if environment.KeyVaultEndpoint == "" { - environment.KeyVaultEndpoint = fmt.Sprintf("%s%s", "https://", environment.KeyVaultDNSSuffix) - } - if environment.TokenAudience == "" { - environment.TokenAudience = metadataEnvProperties.Authentication.Audiences[0] - } - if environment.ActiveDirectoryEndpoint == "" { - environment.ActiveDirectoryEndpoint = metadataEnvProperties.Authentication.LoginEndpoint - } - if environment.ResourceManagerEndpoint == "" { - environment.ResourceManagerEndpoint = resourceManagerEndpoint - } - if environment.GalleryEndpoint == "" { - environment.GalleryEndpoint = metadataEnvProperties.GalleryEndpoint - } - if environment.GraphEndpoint == "" { - environment.GraphEndpoint = metadataEnvProperties.GraphEndpoint - } - - return environment, nil -} - -func overrideProperties(environment *Environment, properties []OverrideProperty) { - for _, property := range properties { - switch property.Key { - case EnvironmentName: - { - environment.Name = property.Value - } - case EnvironmentManagementPortalURL: - { - environment.ManagementPortalURL = property.Value - } - case EnvironmentPublishSettingsURL: - { - environment.PublishSettingsURL = property.Value - } - case EnvironmentServiceManagementEndpoint: - { - environment.ServiceManagementEndpoint = property.Value - } - case EnvironmentResourceManagerEndpoint: - { - environment.ResourceManagerEndpoint = property.Value - } - case EnvironmentActiveDirectoryEndpoint: - { - environment.ActiveDirectoryEndpoint = property.Value - } - case EnvironmentGalleryEndpoint: - { - environment.GalleryEndpoint = property.Value - } - case EnvironmentKeyVaultEndpoint: - { - environment.KeyVaultEndpoint = property.Value - } - case EnvironmentGraphEndpoint: - { - environment.GraphEndpoint = property.Value - } - case EnvironmentServiceBusEndpoint: - { - environment.ServiceBusEndpoint = property.Value - } - case EnvironmentBatchManagementEndpoint: - { - environment.BatchManagementEndpoint = property.Value - } - case EnvironmentStorageEndpointSuffix: - { - environment.StorageEndpointSuffix = property.Value - } - case EnvironmentSQLDatabaseDNSSuffix: - { - environment.SQLDatabaseDNSSuffix = property.Value - } - case EnvironmentTrafficManagerDNSSuffix: - { - environment.TrafficManagerDNSSuffix = property.Value - } - case EnvironmentKeyVaultDNSSuffix: - { - environment.KeyVaultDNSSuffix = property.Value - } - case EnvironmentServiceBusEndpointSuffix: - { - environment.ServiceBusEndpointSuffix = property.Value - } - case EnvironmentServiceManagementVMDNSSuffix: - { - environment.ServiceManagementVMDNSSuffix = property.Value - } - case EnvironmentResourceManagerVMDNSSuffix: - { - environment.ResourceManagerVMDNSSuffix = property.Value - } - case EnvironmentContainerRegistryDNSSuffix: - { - environment.ContainerRegistryDNSSuffix = property.Value - } - case EnvironmentTokenAudience: - { - environment.TokenAudience = property.Value - } - } - } -} - -func retrieveMetadataEnvironment(endpoint string) (environment environmentMetadataInfo, err error) { - client := autorest.NewClientWithUserAgent("") - managementEndpoint := fmt.Sprintf("%s%s", strings.TrimSuffix(endpoint, "/"), "/metadata/endpoints?api-version=1.0") - req, _ := http.NewRequest("GET", managementEndpoint, nil) - response, err := client.Do(req) - if err != nil { - return environment, err - } - defer response.Body.Close() - jsonResponse, err := ioutil.ReadAll(response.Body) - if err != nil { - return environment, err - } - err = json.Unmarshal(jsonResponse, &environment) - return environment, err -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go b/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go deleted file mode 100644 index c6d39f68..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go +++ /dev/null @@ -1,204 +0,0 @@ -// Copyright 2017 Microsoft Corporation -// -// 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 azure - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" -) - -// DoRetryWithRegistration tries to register the resource provider in case it is unregistered. -// It also handles request retries -func DoRetryWithRegistration(client autorest.Client) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := autorest.NewRetriableRequest(r) - for currentAttempt := 0; currentAttempt < client.RetryAttempts; currentAttempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - - resp, err = autorest.SendWithSender(s, rr.Request(), - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return resp, err - } - - if resp.StatusCode != http.StatusConflict || client.SkipResourceProviderRegistration { - return resp, err - } - - var re RequestError - if strings.Contains(r.Header.Get("Content-Type"), "xml") { - // XML errors (e.g. Storage Data Plane) only return the inner object - err = autorest.Respond(resp, autorest.ByUnmarshallingXML(&re.ServiceError)) - } else { - err = autorest.Respond(resp, autorest.ByUnmarshallingJSON(&re)) - } - - if err != nil { - return resp, err - } - err = re - - if re.ServiceError != nil && re.ServiceError.Code == "MissingSubscriptionRegistration" { - regErr := register(client, r, re) - if regErr != nil { - return resp, fmt.Errorf("failed auto registering Resource Provider: %s. Original error: %s", regErr, err) - } - } - } - return resp, err - }) - } -} - -func getProvider(re RequestError) (string, error) { - if re.ServiceError != nil && len(re.ServiceError.Details) > 0 { - return re.ServiceError.Details[0]["target"].(string), nil - } - return "", errors.New("provider was not found in the response") -} - -func register(client autorest.Client, originalReq *http.Request, re RequestError) error { - subID := getSubscription(originalReq.URL.Path) - if subID == "" { - return errors.New("missing parameter subscriptionID to register resource provider") - } - providerName, err := getProvider(re) - if err != nil { - return fmt.Errorf("missing parameter provider to register resource provider: %s", err) - } - newURL := url.URL{ - Scheme: originalReq.URL.Scheme, - Host: originalReq.URL.Host, - } - - // taken from the resources SDK - // with almost identical code, this sections are easier to mantain - // It is also not a good idea to import the SDK here - // https://github.com/Azure/azure-sdk-for-go/blob/9f366792afa3e0ddaecdc860e793ba9d75e76c27/arm/resources/resources/providers.go#L252 - pathParameters := map[string]interface{}{ - "resourceProviderNamespace": autorest.Encode("path", providerName), - "subscriptionId": autorest.Encode("path", subID), - } - - const APIVersion = "2016-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(newURL.String()), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register", pathParameters), - autorest.WithQueryParameters(queryParameters), - ) - - req, err := preparer.Prepare(&http.Request{}) - if err != nil { - return err - } - req = req.WithContext(originalReq.Context()) - - resp, err := autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return err - } - - type Provider struct { - RegistrationState *string `json:"registrationState,omitempty"` - } - var provider Provider - - err = autorest.Respond( - resp, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&provider), - autorest.ByClosing(), - ) - if err != nil { - return err - } - - // poll for registered provisioning state - registrationStartTime := time.Now() - for err == nil && (client.PollingDuration == 0 || (client.PollingDuration != 0 && time.Since(registrationStartTime) < client.PollingDuration)) { - // taken from the resources SDK - // https://github.com/Azure/azure-sdk-for-go/blob/9f366792afa3e0ddaecdc860e793ba9d75e76c27/arm/resources/resources/providers.go#L45 - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(newURL.String()), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}", pathParameters), - autorest.WithQueryParameters(queryParameters), - ) - req, err = preparer.Prepare(&http.Request{}) - if err != nil { - return err - } - req = req.WithContext(originalReq.Context()) - - resp, err := autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return err - } - - err = autorest.Respond( - resp, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&provider), - autorest.ByClosing(), - ) - if err != nil { - return err - } - - if provider.RegistrationState != nil && - *provider.RegistrationState == "Registered" { - break - } - - delayed := autorest.DelayWithRetryAfter(resp, originalReq.Context().Done()) - if !delayed && !autorest.DelayForBackoff(client.PollingDelay, 0, originalReq.Context().Done()) { - return originalReq.Context().Err() - } - } - if client.PollingDuration != 0 && !(time.Since(registrationStartTime) < client.PollingDuration) { - return errors.New("polling for resource provider registration has exceeded the polling duration") - } - return err -} - -func getSubscription(path string) string { - parts := strings.Split(path, "/") - for i, v := range parts { - if v == "subscriptions" && (i+1) < len(parts) { - return parts[i+1] - } - } - return "" -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/client.go b/vendor/github.com/Azure/go-autorest/autorest/client.go deleted file mode 100644 index 0b7525f0..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/client.go +++ /dev/null @@ -1,328 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "crypto/tls" - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "strings" - "time" - - "github.com/Azure/go-autorest/logger" -) - -const ( - // DefaultPollingDelay is a reasonable delay between polling requests. - DefaultPollingDelay = 60 * time.Second - - // DefaultPollingDuration is a reasonable total polling duration. - DefaultPollingDuration = 15 * time.Minute - - // DefaultRetryAttempts is number of attempts for retry status codes (5xx). - DefaultRetryAttempts = 3 - - // DefaultRetryDuration is the duration to wait between retries. - DefaultRetryDuration = 30 * time.Second -) - -var ( - // StatusCodesForRetry are a defined group of status code for which the client will retry - StatusCodesForRetry = []int{ - http.StatusRequestTimeout, // 408 - http.StatusTooManyRequests, // 429 - http.StatusInternalServerError, // 500 - http.StatusBadGateway, // 502 - http.StatusServiceUnavailable, // 503 - http.StatusGatewayTimeout, // 504 - } -) - -const ( - requestFormat = `HTTP Request Begin =================================================== -%s -===================================================== HTTP Request End -` - responseFormat = `HTTP Response Begin =================================================== -%s -===================================================== HTTP Response End -` -) - -// Response serves as the base for all responses from generated clients. It provides access to the -// last http.Response. -type Response struct { - *http.Response `json:"-"` -} - -// IsHTTPStatus returns true if the returned HTTP status code matches the provided status code. -// If there was no response (i.e. the underlying http.Response is nil) the return value is false. -func (r Response) IsHTTPStatus(statusCode int) bool { - if r.Response == nil { - return false - } - return r.Response.StatusCode == statusCode -} - -// HasHTTPStatus returns true if the returned HTTP status code matches one of the provided status codes. -// If there was no response (i.e. the underlying http.Response is nil) or not status codes are provided -// the return value is false. -func (r Response) HasHTTPStatus(statusCodes ...int) bool { - return ResponseHasStatusCode(r.Response, statusCodes...) -} - -// LoggingInspector implements request and response inspectors that log the full request and -// response to a supplied log. -type LoggingInspector struct { - Logger *log.Logger -} - -// WithInspection returns a PrepareDecorator that emits the http.Request to the supplied logger. The -// body is restored after being emitted. -// -// Note: Since it reads the entire Body, this decorator should not be used where body streaming is -// important. It is best used to trace JSON or similar body values. -func (li LoggingInspector) WithInspection() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - var body, b bytes.Buffer - - defer r.Body.Close() - - r.Body = ioutil.NopCloser(io.TeeReader(r.Body, &body)) - if err := r.Write(&b); err != nil { - return nil, fmt.Errorf("Failed to write response: %v", err) - } - - li.Logger.Printf(requestFormat, b.String()) - - r.Body = ioutil.NopCloser(&body) - return p.Prepare(r) - }) - } -} - -// ByInspecting returns a RespondDecorator that emits the http.Response to the supplied logger. The -// body is restored after being emitted. -// -// Note: Since it reads the entire Body, this decorator should not be used where body streaming is -// important. It is best used to trace JSON or similar body values. -func (li LoggingInspector) ByInspecting() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - var body, b bytes.Buffer - defer resp.Body.Close() - resp.Body = ioutil.NopCloser(io.TeeReader(resp.Body, &body)) - if err := resp.Write(&b); err != nil { - return fmt.Errorf("Failed to write response: %v", err) - } - - li.Logger.Printf(responseFormat, b.String()) - - resp.Body = ioutil.NopCloser(&body) - return r.Respond(resp) - }) - } -} - -// Client is the base for autorest generated clients. It provides default, "do nothing" -// implementations of an Authorizer, RequestInspector, and ResponseInspector. It also returns the -// standard, undecorated http.Client as a default Sender. -// -// Generated clients should also use Error (see NewError and NewErrorWithError) for errors and -// return responses that compose with Response. -// -// Most customization of generated clients is best achieved by supplying a custom Authorizer, custom -// RequestInspector, and / or custom ResponseInspector. Users may log requests, implement circuit -// breakers (see https://msdn.microsoft.com/en-us/library/dn589784.aspx) or otherwise influence -// sending the request by providing a decorated Sender. -type Client struct { - Authorizer Authorizer - Sender Sender - RequestInspector PrepareDecorator - ResponseInspector RespondDecorator - - // PollingDelay sets the polling frequency used in absence of a Retry-After HTTP header - PollingDelay time.Duration - - // PollingDuration sets the maximum polling time after which an error is returned. - // Setting this to zero will use the provided context to control the duration. - PollingDuration time.Duration - - // RetryAttempts sets the total number of times the client will attempt to make an HTTP request. - // Set the value to 1 to disable retries. DO NOT set the value to less than 1. - RetryAttempts int - - // RetryDuration sets the delay duration for retries. - RetryDuration time.Duration - - // UserAgent, if not empty, will be set as the HTTP User-Agent header on all requests sent - // through the Do method. - UserAgent string - - Jar http.CookieJar - - // Set to true to skip attempted registration of resource providers (false by default). - SkipResourceProviderRegistration bool - - // SendDecorators can be used to override the default chain of SendDecorators. - // This can be used to specify things like a custom retry SendDecorator. - // Set this to an empty slice to use no SendDecorators. - SendDecorators []SendDecorator -} - -// NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed -// string. -func NewClientWithUserAgent(ua string) Client { - return newClient(ua, tls.RenegotiateNever) -} - -// ClientOptions contains various Client configuration options. -type ClientOptions struct { - // UserAgent is an optional user-agent string to append to the default user agent. - UserAgent string - - // Renegotiation is an optional setting to control client-side TLS renegotiation. - Renegotiation tls.RenegotiationSupport -} - -// NewClientWithOptions returns an instance of a Client with the specified values. -func NewClientWithOptions(options ClientOptions) Client { - return newClient(options.UserAgent, options.Renegotiation) -} - -func newClient(ua string, renegotiation tls.RenegotiationSupport) Client { - c := Client{ - PollingDelay: DefaultPollingDelay, - PollingDuration: DefaultPollingDuration, - RetryAttempts: DefaultRetryAttempts, - RetryDuration: DefaultRetryDuration, - UserAgent: UserAgent(), - } - c.Sender = c.sender(renegotiation) - c.AddToUserAgent(ua) - return c -} - -// AddToUserAgent adds an extension to the current user agent -func (c *Client) AddToUserAgent(extension string) error { - if extension != "" { - c.UserAgent = fmt.Sprintf("%s %s", c.UserAgent, extension) - return nil - } - return fmt.Errorf("Extension was empty, User Agent stayed as %s", c.UserAgent) -} - -// Do implements the Sender interface by invoking the active Sender after applying authorization. -// If Sender is not set, it uses a new instance of http.Client. In both cases it will, if UserAgent -// is set, apply set the User-Agent header. -func (c Client) Do(r *http.Request) (*http.Response, error) { - if r.UserAgent() == "" { - r, _ = Prepare(r, - WithUserAgent(c.UserAgent)) - } - // NOTE: c.WithInspection() must be last in the list so that it can inspect all preceding operations - r, err := Prepare(r, - c.WithAuthorization(), - c.WithInspection()) - if err != nil { - var resp *http.Response - if detErr, ok := err.(DetailedError); ok { - // if the authorization failed (e.g. invalid credentials) there will - // be a response associated with the error, be sure to return it. - resp = detErr.Response - } - return resp, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed") - } - logger.Instance.WriteRequest(r, logger.Filter{ - Header: func(k string, v []string) (bool, []string) { - // remove the auth token from the log - if strings.EqualFold(k, "Authorization") || strings.EqualFold(k, "Ocp-Apim-Subscription-Key") { - v = []string{"**REDACTED**"} - } - return true, v - }, - }) - resp, err := SendWithSender(c.sender(tls.RenegotiateNever), r) - if resp == nil && err == nil { - err = errors.New("autorest: received nil response and error") - } - logger.Instance.WriteResponse(resp, logger.Filter{}) - Respond(resp, c.ByInspecting()) - return resp, err -} - -// sender returns the Sender to which to send requests. -func (c Client) sender(renengotiation tls.RenegotiationSupport) Sender { - if c.Sender == nil { - return sender(renengotiation) - } - return c.Sender -} - -// WithAuthorization is a convenience method that returns the WithAuthorization PrepareDecorator -// from the current Authorizer. If not Authorizer is set, it uses the NullAuthorizer. -func (c Client) WithAuthorization() PrepareDecorator { - return c.authorizer().WithAuthorization() -} - -// authorizer returns the Authorizer to use. -func (c Client) authorizer() Authorizer { - if c.Authorizer == nil { - return NullAuthorizer{} - } - return c.Authorizer -} - -// WithInspection is a convenience method that passes the request to the supplied RequestInspector, -// if present, or returns the WithNothing PrepareDecorator otherwise. -func (c Client) WithInspection() PrepareDecorator { - if c.RequestInspector == nil { - return WithNothing() - } - return c.RequestInspector -} - -// ByInspecting is a convenience method that passes the response to the supplied ResponseInspector, -// if present, or returns the ByIgnoring RespondDecorator otherwise. -func (c Client) ByInspecting() RespondDecorator { - if c.ResponseInspector == nil { - return ByIgnoring() - } - return c.ResponseInspector -} - -// Send sends the provided http.Request using the client's Sender or the default sender. -// It returns the http.Response and possible error. It also accepts a, possibly empty, -// default set of SendDecorators used when sending the request. -// SendDecorators have the following precedence: -// 1. In a request's context via WithSendDecorators() -// 2. Specified on the client in SendDecorators -// 3. The default values specified in this method -func (c Client) Send(req *http.Request, decorators ...SendDecorator) (*http.Response, error) { - if c.SendDecorators != nil { - decorators = c.SendDecorators - } - inCtx := req.Context().Value(ctxSendDecorators{}) - if sd, ok := inCtx.([]SendDecorator); ok { - decorators = sd - } - return SendWithSender(c, req, decorators...) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/date/LICENSE deleted file mode 100644 index b9d6a27e..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2015 Microsoft Corporation - - 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/Azure/go-autorest/autorest/date/date.go b/vendor/github.com/Azure/go-autorest/autorest/date/date.go deleted file mode 100644 index c4571065..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/date.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Package date provides time.Time derivatives that conform to the Swagger.io (https://swagger.io/) -defined date formats: Date and DateTime. Both types may, in most cases, be used in lieu of -time.Time types. And both convert to time.Time through a ToTime method. -*/ -package date - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "fmt" - "time" -) - -const ( - fullDate = "2006-01-02" - fullDateJSON = `"2006-01-02"` - dateFormat = "%04d-%02d-%02d" - jsonFormat = `"%04d-%02d-%02d"` -) - -// Date defines a type similar to time.Time but assumes a layout of RFC3339 full-date (i.e., -// 2006-01-02). -type Date struct { - time.Time -} - -// ParseDate create a new Date from the passed string. -func ParseDate(date string) (d Date, err error) { - return parseDate(date, fullDate) -} - -func parseDate(date string, format string) (Date, error) { - d, err := time.Parse(format, date) - return Date{Time: d}, err -} - -// MarshalBinary preserves the Date as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalBinary() ([]byte, error) { - return d.MarshalText() -} - -// UnmarshalBinary reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalBinary(data []byte) error { - return d.UnmarshalText(data) -} - -// MarshalJSON preserves the Date as a JSON string conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalJSON() (json []byte, err error) { - return []byte(fmt.Sprintf(jsonFormat, d.Year(), d.Month(), d.Day())), nil -} - -// UnmarshalJSON reconstitutes the Date from a JSON string conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalJSON(data []byte) (err error) { - d.Time, err = time.Parse(fullDateJSON, string(data)) - return err -} - -// MarshalText preserves the Date as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalText() (text []byte, err error) { - return []byte(fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day())), nil -} - -// UnmarshalText reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalText(data []byte) (err error) { - d.Time, err = time.Parse(fullDate, string(data)) - return err -} - -// String returns the Date formatted as an RFC3339 full-date string (i.e., 2006-01-02). -func (d Date) String() string { - return fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day()) -} - -// ToTime returns a Date as a time.Time -func (d Date) ToTime() time.Time { - return d.Time -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/date/go_mod_tidy_hack.go deleted file mode 100644 index 4e054320..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package date - -// Copyright 2017 Microsoft Corporation -// -// 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. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/time.go b/vendor/github.com/Azure/go-autorest/autorest/date/time.go deleted file mode 100644 index b453fad0..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/time.go +++ /dev/null @@ -1,103 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "regexp" - "time" -) - -// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. -const ( - azureUtcFormatJSON = `"2006-01-02T15:04:05.999999999"` - azureUtcFormat = "2006-01-02T15:04:05.999999999" - rfc3339JSON = `"` + time.RFC3339Nano + `"` - rfc3339 = time.RFC3339Nano - tzOffsetRegex = `(Z|z|\+|-)(\d+:\d+)*"*$` -) - -// Time defines a type similar to time.Time but assumes a layout of RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -type Time struct { - time.Time -} - -// MarshalBinary preserves the Time as a byte array conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalBinary() ([]byte, error) { - return t.Time.MarshalText() -} - -// UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalBinary(data []byte) error { - return t.UnmarshalText(data) -} - -// MarshalJSON preserves the Time as a JSON string conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalJSON() (json []byte, err error) { - return t.Time.MarshalJSON() -} - -// UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalJSON(data []byte) (err error) { - timeFormat := azureUtcFormatJSON - match, err := regexp.Match(tzOffsetRegex, data) - if err != nil { - return err - } else if match { - timeFormat = rfc3339JSON - } - t.Time, err = ParseTime(timeFormat, string(data)) - return err -} - -// MarshalText preserves the Time as a byte array conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalText() (text []byte, err error) { - return t.Time.MarshalText() -} - -// UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalText(data []byte) (err error) { - timeFormat := azureUtcFormat - match, err := regexp.Match(tzOffsetRegex, data) - if err != nil { - return err - } else if match { - timeFormat = rfc3339 - } - t.Time, err = ParseTime(timeFormat, string(data)) - return err -} - -// String returns the Time formatted as an RFC3339 date-time string (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) String() string { - // Note: time.Time.String does not return an RFC3339 compliant string, time.Time.MarshalText does. - b, err := t.MarshalText() - if err != nil { - return "" - } - return string(b) -} - -// ToTime returns a Time as a time.Time -func (t Time) ToTime() time.Time { - return t.Time -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go b/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go deleted file mode 100644 index 48fb39ba..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go +++ /dev/null @@ -1,100 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "errors" - "time" -) - -const ( - rfc1123JSON = `"` + time.RFC1123 + `"` - rfc1123 = time.RFC1123 -) - -// TimeRFC1123 defines a type similar to time.Time but assumes a layout of RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -type TimeRFC1123 struct { - time.Time -} - -// UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalJSON(data []byte) (err error) { - t.Time, err = ParseTime(rfc1123JSON, string(data)) - if err != nil { - return err - } - return nil -} - -// MarshalJSON preserves the Time as a JSON string conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalJSON() ([]byte, error) { - if y := t.Year(); y < 0 || y >= 10000 { - return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]") - } - b := []byte(t.Format(rfc1123JSON)) - return b, nil -} - -// MarshalText preserves the Time as a byte array conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalText() ([]byte, error) { - if y := t.Year(); y < 0 || y >= 10000 { - return nil, errors.New("Time.MarshalText: year outside of range [0,9999]") - } - - b := []byte(t.Format(rfc1123)) - return b, nil -} - -// UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalText(data []byte) (err error) { - t.Time, err = ParseTime(rfc1123, string(data)) - if err != nil { - return err - } - return nil -} - -// MarshalBinary preserves the Time as a byte array conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalBinary() ([]byte, error) { - return t.MarshalText() -} - -// UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalBinary(data []byte) error { - return t.UnmarshalText(data) -} - -// ToTime returns a Time as a time.Time -func (t TimeRFC1123) ToTime() time.Time { - return t.Time -} - -// String returns the Time formatted as an RFC1123 date-time string (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) String() string { - // Note: time.Time.String does not return an RFC1123 compliant string, time.Time.MarshalText does. - b, err := t.MarshalText() - if err != nil { - return "" - } - return string(b) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go b/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go deleted file mode 100644 index 7073959b..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go +++ /dev/null @@ -1,123 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "time" -) - -// unixEpoch is the moment in time that should be treated as timestamp 0. -var unixEpoch = time.Date(1970, time.January, 1, 0, 0, 0, 0, time.UTC) - -// UnixTime marshals and unmarshals a time that is represented as the number -// of seconds (ignoring skip-seconds) since the Unix Epoch. -type UnixTime time.Time - -// Duration returns the time as a Duration since the UnixEpoch. -func (t UnixTime) Duration() time.Duration { - return time.Time(t).Sub(unixEpoch) -} - -// NewUnixTimeFromSeconds creates a UnixTime as a number of seconds from the UnixEpoch. -func NewUnixTimeFromSeconds(seconds float64) UnixTime { - return NewUnixTimeFromDuration(time.Duration(seconds * float64(time.Second))) -} - -// NewUnixTimeFromNanoseconds creates a UnixTime as a number of nanoseconds from the UnixEpoch. -func NewUnixTimeFromNanoseconds(nanoseconds int64) UnixTime { - return NewUnixTimeFromDuration(time.Duration(nanoseconds)) -} - -// NewUnixTimeFromDuration creates a UnixTime as a duration of time since the UnixEpoch. -func NewUnixTimeFromDuration(dur time.Duration) UnixTime { - return UnixTime(unixEpoch.Add(dur)) -} - -// UnixEpoch retreives the moment considered the Unix Epoch. I.e. The time represented by '0' -func UnixEpoch() time.Time { - return unixEpoch -} - -// MarshalJSON preserves the UnixTime as a JSON number conforming to Unix Timestamp requirements. -// (i.e. the number of seconds since midnight January 1st, 1970 not considering leap seconds.) -func (t UnixTime) MarshalJSON() ([]byte, error) { - buffer := &bytes.Buffer{} - enc := json.NewEncoder(buffer) - err := enc.Encode(float64(time.Time(t).UnixNano()) / 1e9) - if err != nil { - return nil, err - } - return buffer.Bytes(), nil -} - -// UnmarshalJSON reconstitures a UnixTime saved as a JSON number of the number of seconds since -// midnight January 1st, 1970. -func (t *UnixTime) UnmarshalJSON(text []byte) error { - dec := json.NewDecoder(bytes.NewReader(text)) - - var secondsSinceEpoch float64 - if err := dec.Decode(&secondsSinceEpoch); err != nil { - return err - } - - *t = NewUnixTimeFromSeconds(secondsSinceEpoch) - - return nil -} - -// MarshalText stores the number of seconds since the Unix Epoch as a textual floating point number. -func (t UnixTime) MarshalText() ([]byte, error) { - cast := time.Time(t) - return cast.MarshalText() -} - -// UnmarshalText populates a UnixTime with a value stored textually as a floating point number of seconds since the Unix Epoch. -func (t *UnixTime) UnmarshalText(raw []byte) error { - var unmarshaled time.Time - - if err := unmarshaled.UnmarshalText(raw); err != nil { - return err - } - - *t = UnixTime(unmarshaled) - return nil -} - -// MarshalBinary converts a UnixTime into a binary.LittleEndian float64 of nanoseconds since the epoch. -func (t UnixTime) MarshalBinary() ([]byte, error) { - buf := &bytes.Buffer{} - - payload := int64(t.Duration()) - - if err := binary.Write(buf, binary.LittleEndian, &payload); err != nil { - return nil, err - } - - return buf.Bytes(), nil -} - -// UnmarshalBinary converts a from a binary.LittleEndian float64 of nanoseconds since the epoch into a UnixTime. -func (t *UnixTime) UnmarshalBinary(raw []byte) error { - var nanosecondsSinceEpoch int64 - - if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &nanosecondsSinceEpoch); err != nil { - return err - } - *t = NewUnixTimeFromNanoseconds(nanosecondsSinceEpoch) - return nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/utility.go b/vendor/github.com/Azure/go-autorest/autorest/date/utility.go deleted file mode 100644 index 12addf0e..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/utility.go +++ /dev/null @@ -1,25 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "strings" - "time" -) - -// ParseTime to parse Time string to specified format. -func ParseTime(format string, t string) (d time.Time, err error) { - return time.Parse(format, strings.ToUpper(t)) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/error.go b/vendor/github.com/Azure/go-autorest/autorest/error.go deleted file mode 100644 index 35098eda..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/error.go +++ /dev/null @@ -1,103 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "fmt" - "net/http" -) - -const ( - // UndefinedStatusCode is used when HTTP status code is not available for an error. - UndefinedStatusCode = 0 -) - -// DetailedError encloses a error with details of the package, method, and associated HTTP -// status code (if any). -type DetailedError struct { - Original error - - // PackageType is the package type of the object emitting the error. For types, the value - // matches that produced the the '%T' format specifier of the fmt package. For other elements, - // such as functions, it is just the package name (e.g., "autorest"). - PackageType string - - // Method is the name of the method raising the error. - Method string - - // StatusCode is the HTTP Response StatusCode (if non-zero) that led to the error. - StatusCode interface{} - - // Message is the error message. - Message string - - // Service Error is the response body of failed API in bytes - ServiceError []byte - - // Response is the response object that was returned during failure if applicable. - Response *http.Response -} - -// NewError creates a new Error conforming object from the passed packageType, method, and -// message. message is treated as a format string to which the optional args apply. -func NewError(packageType string, method string, message string, args ...interface{}) DetailedError { - return NewErrorWithError(nil, packageType, method, nil, message, args...) -} - -// NewErrorWithResponse creates a new Error conforming object from the passed -// packageType, method, statusCode of the given resp (UndefinedStatusCode if -// resp is nil), and message. message is treated as a format string to which the -// optional args apply. -func NewErrorWithResponse(packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { - return NewErrorWithError(nil, packageType, method, resp, message, args...) -} - -// NewErrorWithError creates a new Error conforming object from the -// passed packageType, method, statusCode of the given resp (UndefinedStatusCode -// if resp is nil), message, and original error. message is treated as a format -// string to which the optional args apply. -func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { - if v, ok := original.(DetailedError); ok { - return v - } - - statusCode := UndefinedStatusCode - if resp != nil { - statusCode = resp.StatusCode - } - - return DetailedError{ - Original: original, - PackageType: packageType, - Method: method, - StatusCode: statusCode, - Message: fmt.Sprintf(message, args...), - Response: resp, - } -} - -// Error returns a formatted containing all available details (i.e., PackageType, Method, -// StatusCode, Message, and original error (if any)). -func (e DetailedError) Error() string { - if e.Original == nil { - return fmt.Sprintf("%s#%s: %s: StatusCode=%d", e.PackageType, e.Method, e.Message, e.StatusCode) - } - return fmt.Sprintf("%s#%s: %s: StatusCode=%d -- Original Error: %v", e.PackageType, e.Method, e.Message, e.StatusCode, e.Original) -} - -// Unwrap returns the original error. -func (e DetailedError) Unwrap() error { - return e.Original -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/go_mod_tidy_hack.go deleted file mode 100644 index da65e104..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/preparer.go b/vendor/github.com/Azure/go-autorest/autorest/preparer.go deleted file mode 100644 index 98574a41..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/preparer.go +++ /dev/null @@ -1,547 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "context" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "net/url" - "strings" -) - -const ( - mimeTypeJSON = "application/json" - mimeTypeOctetStream = "application/octet-stream" - mimeTypeFormPost = "application/x-www-form-urlencoded" - - headerAuthorization = "Authorization" - headerAuxAuthorization = "x-ms-authorization-auxiliary" - headerContentType = "Content-Type" - headerUserAgent = "User-Agent" -) - -// used as a key type in context.WithValue() -type ctxPrepareDecorators struct{} - -// WithPrepareDecorators adds the specified PrepareDecorators to the provided context. -// If no PrepareDecorators are provided the context is unchanged. -func WithPrepareDecorators(ctx context.Context, prepareDecorator []PrepareDecorator) context.Context { - if len(prepareDecorator) == 0 { - return ctx - } - return context.WithValue(ctx, ctxPrepareDecorators{}, prepareDecorator) -} - -// GetPrepareDecorators returns the PrepareDecorators in the provided context or the provided default PrepareDecorators. -func GetPrepareDecorators(ctx context.Context, defaultPrepareDecorators ...PrepareDecorator) []PrepareDecorator { - inCtx := ctx.Value(ctxPrepareDecorators{}) - if pd, ok := inCtx.([]PrepareDecorator); ok { - return pd - } - return defaultPrepareDecorators -} - -// Preparer is the interface that wraps the Prepare method. -// -// Prepare accepts and possibly modifies an http.Request (e.g., adding Headers). Implementations -// must ensure to not share or hold per-invocation state since Preparers may be shared and re-used. -type Preparer interface { - Prepare(*http.Request) (*http.Request, error) -} - -// PreparerFunc is a method that implements the Preparer interface. -type PreparerFunc func(*http.Request) (*http.Request, error) - -// Prepare implements the Preparer interface on PreparerFunc. -func (pf PreparerFunc) Prepare(r *http.Request) (*http.Request, error) { - return pf(r) -} - -// PrepareDecorator takes and possibly decorates, by wrapping, a Preparer. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then affect the result. -type PrepareDecorator func(Preparer) Preparer - -// CreatePreparer creates, decorates, and returns a Preparer. -// Without decorators, the returned Preparer returns the passed http.Request unmodified. -// Preparers are safe to share and re-use. -func CreatePreparer(decorators ...PrepareDecorator) Preparer { - return DecoratePreparer( - Preparer(PreparerFunc(func(r *http.Request) (*http.Request, error) { return r, nil })), - decorators...) -} - -// DecoratePreparer accepts a Preparer and a, possibly empty, set of PrepareDecorators, which it -// applies to the Preparer. Decorators are applied in the order received, but their affect upon the -// request depends on whether they are a pre-decorator (change the http.Request and then pass it -// along) or a post-decorator (pass the http.Request along and alter it on return). -func DecoratePreparer(p Preparer, decorators ...PrepareDecorator) Preparer { - for _, decorate := range decorators { - p = decorate(p) - } - return p -} - -// Prepare accepts an http.Request and a, possibly empty, set of PrepareDecorators. -// It creates a Preparer from the decorators which it then applies to the passed http.Request. -func Prepare(r *http.Request, decorators ...PrepareDecorator) (*http.Request, error) { - if r == nil { - return nil, NewError("autorest", "Prepare", "Invoked without an http.Request") - } - return CreatePreparer(decorators...).Prepare(r) -} - -// WithNothing returns a "do nothing" PrepareDecorator that makes no changes to the passed -// http.Request. -func WithNothing() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - return p.Prepare(r) - }) - } -} - -// WithHeader returns a PrepareDecorator that sets the specified HTTP header of the http.Request to -// the passed value. It canonicalizes the passed header name (via http.CanonicalHeaderKey) before -// adding the header. -func WithHeader(header string, value string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - setHeader(r, http.CanonicalHeaderKey(header), value) - } - return r, err - }) - } -} - -// WithHeaders returns a PrepareDecorator that sets the specified HTTP headers of the http.Request to -// the passed value. It canonicalizes the passed headers name (via http.CanonicalHeaderKey) before -// adding them. -func WithHeaders(headers map[string]interface{}) PrepareDecorator { - h := ensureValueStrings(headers) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.Header == nil { - r.Header = make(http.Header) - } - - for name, value := range h { - r.Header.Set(http.CanonicalHeaderKey(name), value) - } - } - return r, err - }) - } -} - -// WithBearerAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Bearer " followed by the supplied token. -func WithBearerAuthorization(token string) PrepareDecorator { - return WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", token)) -} - -// AsContentType returns a PrepareDecorator that adds an HTTP Content-Type header whose value -// is the passed contentType. -func AsContentType(contentType string) PrepareDecorator { - return WithHeader(headerContentType, contentType) -} - -// WithUserAgent returns a PrepareDecorator that adds an HTTP User-Agent header whose value is the -// passed string. -func WithUserAgent(ua string) PrepareDecorator { - return WithHeader(headerUserAgent, ua) -} - -// AsFormURLEncoded returns a PrepareDecorator that adds an HTTP Content-Type header whose value is -// "application/x-www-form-urlencoded". -func AsFormURLEncoded() PrepareDecorator { - return AsContentType(mimeTypeFormPost) -} - -// AsJSON returns a PrepareDecorator that adds an HTTP Content-Type header whose value is -// "application/json". -func AsJSON() PrepareDecorator { - return AsContentType(mimeTypeJSON) -} - -// AsOctetStream returns a PrepareDecorator that adds the "application/octet-stream" Content-Type header. -func AsOctetStream() PrepareDecorator { - return AsContentType(mimeTypeOctetStream) -} - -// WithMethod returns a PrepareDecorator that sets the HTTP method of the passed request. The -// decorator does not validate that the passed method string is a known HTTP method. -func WithMethod(method string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r.Method = method - return p.Prepare(r) - }) - } -} - -// AsDelete returns a PrepareDecorator that sets the HTTP method to DELETE. -func AsDelete() PrepareDecorator { return WithMethod("DELETE") } - -// AsGet returns a PrepareDecorator that sets the HTTP method to GET. -func AsGet() PrepareDecorator { return WithMethod("GET") } - -// AsHead returns a PrepareDecorator that sets the HTTP method to HEAD. -func AsHead() PrepareDecorator { return WithMethod("HEAD") } - -// AsMerge returns a PrepareDecorator that sets the HTTP method to MERGE. -func AsMerge() PrepareDecorator { return WithMethod("MERGE") } - -// AsOptions returns a PrepareDecorator that sets the HTTP method to OPTIONS. -func AsOptions() PrepareDecorator { return WithMethod("OPTIONS") } - -// AsPatch returns a PrepareDecorator that sets the HTTP method to PATCH. -func AsPatch() PrepareDecorator { return WithMethod("PATCH") } - -// AsPost returns a PrepareDecorator that sets the HTTP method to POST. -func AsPost() PrepareDecorator { return WithMethod("POST") } - -// AsPut returns a PrepareDecorator that sets the HTTP method to PUT. -func AsPut() PrepareDecorator { return WithMethod("PUT") } - -// WithBaseURL returns a PrepareDecorator that populates the http.Request with a url.URL constructed -// from the supplied baseUrl. Query parameters will be encoded as required. -func WithBaseURL(baseURL string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - var u *url.URL - if u, err = url.Parse(baseURL); err != nil { - return r, err - } - if u.Scheme == "" { - return r, fmt.Errorf("autorest: No scheme detected in URL %s", baseURL) - } - if u.RawQuery != "" { - q, err := url.ParseQuery(u.RawQuery) - if err != nil { - return r, err - } - u.RawQuery = q.Encode() - } - r.URL = u - } - return r, err - }) - } -} - -// WithBytes returns a PrepareDecorator that takes a list of bytes -// which passes the bytes directly to the body -func WithBytes(input *[]byte) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if input == nil { - return r, fmt.Errorf("Input Bytes was nil") - } - - r.ContentLength = int64(len(*input)) - r.Body = ioutil.NopCloser(bytes.NewReader(*input)) - } - return r, err - }) - } -} - -// WithCustomBaseURL returns a PrepareDecorator that replaces brace-enclosed keys within the -// request base URL (i.e., http.Request.URL) with the corresponding values from the passed map. -func WithCustomBaseURL(baseURL string, urlParameters map[string]interface{}) PrepareDecorator { - parameters := ensureValueStrings(urlParameters) - for key, value := range parameters { - baseURL = strings.Replace(baseURL, "{"+key+"}", value, -1) - } - return WithBaseURL(baseURL) -} - -// WithFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) into the -// http.Request body. -func WithFormData(v url.Values) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - s := v.Encode() - - setHeader(r, http.CanonicalHeaderKey(headerContentType), mimeTypeFormPost) - r.ContentLength = int64(len(s)) - r.Body = ioutil.NopCloser(strings.NewReader(s)) - } - return r, err - }) - } -} - -// WithMultiPartFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) form parameters -// into the http.Request body. -func WithMultiPartFormData(formDataParameters map[string]interface{}) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - var body bytes.Buffer - writer := multipart.NewWriter(&body) - for key, value := range formDataParameters { - if rc, ok := value.(io.ReadCloser); ok { - var fd io.Writer - if fd, err = writer.CreateFormFile(key, key); err != nil { - return r, err - } - if _, err = io.Copy(fd, rc); err != nil { - return r, err - } - } else { - if err = writer.WriteField(key, ensureValueString(value)); err != nil { - return r, err - } - } - } - if err = writer.Close(); err != nil { - return r, err - } - setHeader(r, http.CanonicalHeaderKey(headerContentType), writer.FormDataContentType()) - r.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes())) - r.ContentLength = int64(body.Len()) - return r, err - } - return r, err - }) - } -} - -// WithFile returns a PrepareDecorator that sends file in request body. -func WithFile(f io.ReadCloser) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - b, err := ioutil.ReadAll(f) - if err != nil { - return r, err - } - r.Body = ioutil.NopCloser(bytes.NewReader(b)) - r.ContentLength = int64(len(b)) - } - return r, err - }) - } -} - -// WithBool returns a PrepareDecorator that encodes the passed bool into the body of the request -// and sets the Content-Length header. -func WithBool(v bool) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithFloat32 returns a PrepareDecorator that encodes the passed float32 into the body of the -// request and sets the Content-Length header. -func WithFloat32(v float32) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithFloat64 returns a PrepareDecorator that encodes the passed float64 into the body of the -// request and sets the Content-Length header. -func WithFloat64(v float64) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithInt32 returns a PrepareDecorator that encodes the passed int32 into the body of the request -// and sets the Content-Length header. -func WithInt32(v int32) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithInt64 returns a PrepareDecorator that encodes the passed int64 into the body of the request -// and sets the Content-Length header. -func WithInt64(v int64) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithString returns a PrepareDecorator that encodes the passed string into the body of the request -// and sets the Content-Length header. -func WithString(v string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - r.ContentLength = int64(len(v)) - r.Body = ioutil.NopCloser(strings.NewReader(v)) - } - return r, err - }) - } -} - -// WithJSON returns a PrepareDecorator that encodes the data passed as JSON into the body of the -// request and sets the Content-Length header. -func WithJSON(v interface{}) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - b, err := json.Marshal(v) - if err == nil { - r.ContentLength = int64(len(b)) - r.Body = ioutil.NopCloser(bytes.NewReader(b)) - } - } - return r, err - }) - } -} - -// WithXML returns a PrepareDecorator that encodes the data passed as XML into the body of the -// request and sets the Content-Length header. -func WithXML(v interface{}) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - b, err := xml.Marshal(v) - if err == nil { - // we have to tack on an XML header - withHeader := xml.Header + string(b) - bytesWithHeader := []byte(withHeader) - - r.ContentLength = int64(len(bytesWithHeader)) - setHeader(r, headerContentLength, fmt.Sprintf("%d", len(bytesWithHeader))) - r.Body = ioutil.NopCloser(bytes.NewReader(bytesWithHeader)) - } - } - return r, err - }) - } -} - -// WithPath returns a PrepareDecorator that adds the supplied path to the request URL. If the path -// is absolute (that is, it begins with a "/"), it replaces the existing path. -func WithPath(path string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithPath", "Invoked with a nil URL") - } - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -// WithEscapedPathParameters returns a PrepareDecorator that replaces brace-enclosed keys within the -// request path (i.e., http.Request.URL.Path) with the corresponding values from the passed map. The -// values will be escaped (aka URL encoded) before insertion into the path. -func WithEscapedPathParameters(path string, pathParameters map[string]interface{}) PrepareDecorator { - parameters := escapeValueStrings(ensureValueStrings(pathParameters)) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithEscapedPathParameters", "Invoked with a nil URL") - } - for key, value := range parameters { - path = strings.Replace(path, "{"+key+"}", value, -1) - } - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -// WithPathParameters returns a PrepareDecorator that replaces brace-enclosed keys within the -// request path (i.e., http.Request.URL.Path) with the corresponding values from the passed map. -func WithPathParameters(path string, pathParameters map[string]interface{}) PrepareDecorator { - parameters := ensureValueStrings(pathParameters) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithPathParameters", "Invoked with a nil URL") - } - for key, value := range parameters { - path = strings.Replace(path, "{"+key+"}", value, -1) - } - - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -func parseURL(u *url.URL, path string) (*url.URL, error) { - p := strings.TrimRight(u.String(), "/") - if !strings.HasPrefix(path, "/") { - path = "/" + path - } - return url.Parse(p + path) -} - -// WithQueryParameters returns a PrepareDecorators that encodes and applies the query parameters -// given in the supplied map (i.e., key=value). -func WithQueryParameters(queryParameters map[string]interface{}) PrepareDecorator { - parameters := MapToValues(queryParameters) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithQueryParameters", "Invoked with a nil URL") - } - v := r.URL.Query() - for key, value := range parameters { - for i := range value { - d, err := url.QueryUnescape(value[i]) - if err != nil { - return r, err - } - value[i] = d - } - v[key] = value - } - r.URL.RawQuery = v.Encode() - } - return r, err - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/responder.go b/vendor/github.com/Azure/go-autorest/autorest/responder.go deleted file mode 100644 index 349e1963..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/responder.go +++ /dev/null @@ -1,269 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "strings" -) - -// Responder is the interface that wraps the Respond method. -// -// Respond accepts and reacts to an http.Response. Implementations must ensure to not share or hold -// state since Responders may be shared and re-used. -type Responder interface { - Respond(*http.Response) error -} - -// ResponderFunc is a method that implements the Responder interface. -type ResponderFunc func(*http.Response) error - -// Respond implements the Responder interface on ResponderFunc. -func (rf ResponderFunc) Respond(r *http.Response) error { - return rf(r) -} - -// RespondDecorator takes and possibly decorates, by wrapping, a Responder. Decorators may react to -// the http.Response and pass it along or, first, pass the http.Response along then react. -type RespondDecorator func(Responder) Responder - -// CreateResponder creates, decorates, and returns a Responder. Without decorators, the returned -// Responder returns the passed http.Response unmodified. Responders may or may not be safe to share -// and re-used: It depends on the applied decorators. For example, a standard decorator that closes -// the response body is fine to share whereas a decorator that reads the body into a passed struct -// is not. -// -// To prevent memory leaks, ensure that at least one Responder closes the response body. -func CreateResponder(decorators ...RespondDecorator) Responder { - return DecorateResponder( - Responder(ResponderFunc(func(r *http.Response) error { return nil })), - decorators...) -} - -// DecorateResponder accepts a Responder and a, possibly empty, set of RespondDecorators, which it -// applies to the Responder. Decorators are applied in the order received, but their affect upon the -// request depends on whether they are a pre-decorator (react to the http.Response and then pass it -// along) or a post-decorator (pass the http.Response along and then react). -func DecorateResponder(r Responder, decorators ...RespondDecorator) Responder { - for _, decorate := range decorators { - r = decorate(r) - } - return r -} - -// Respond accepts an http.Response and a, possibly empty, set of RespondDecorators. -// It creates a Responder from the decorators it then applies to the passed http.Response. -func Respond(r *http.Response, decorators ...RespondDecorator) error { - if r == nil { - return nil - } - return CreateResponder(decorators...).Respond(r) -} - -// ByIgnoring returns a RespondDecorator that ignores the passed http.Response passing it unexamined -// to the next RespondDecorator. -func ByIgnoring() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - return r.Respond(resp) - }) - } -} - -// ByCopying copies the contents of the http.Response Body into the passed bytes.Buffer as -// the Body is read. -func ByCopying(b *bytes.Buffer) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && resp != nil && resp.Body != nil { - resp.Body = TeeReadCloser(resp.Body, b) - } - return err - }) - } -} - -// ByDiscardingBody returns a RespondDecorator that first invokes the passed Responder after which -// it copies the remaining bytes (if any) in the response body to ioutil.Discard. Since the passed -// Responder is invoked prior to discarding the response body, the decorator may occur anywhere -// within the set. -func ByDiscardingBody() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && resp != nil && resp.Body != nil { - if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { - return fmt.Errorf("Error discarding the response body: %v", err) - } - } - return err - }) - } -} - -// ByClosing returns a RespondDecorator that first invokes the passed Responder after which it -// closes the response body. Since the passed Responder is invoked prior to closing the response -// body, the decorator may occur anywhere within the set. -func ByClosing() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if resp != nil && resp.Body != nil { - if err := resp.Body.Close(); err != nil { - return fmt.Errorf("Error closing the response body: %v", err) - } - } - return err - }) - } -} - -// ByClosingIfError returns a RespondDecorator that first invokes the passed Responder after which -// it closes the response if the passed Responder returns an error and the response body exists. -func ByClosingIfError() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err != nil && resp != nil && resp.Body != nil { - if err := resp.Body.Close(); err != nil { - return fmt.Errorf("Error closing the response body: %v", err) - } - } - return err - }) - } -} - -// ByUnmarshallingBytes returns a RespondDecorator that copies the Bytes returned in the -// response Body into the value pointed to by v. -func ByUnmarshallingBytes(v *[]byte) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - bytes, errInner := ioutil.ReadAll(resp.Body) - if errInner != nil { - err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) - } else { - *v = bytes - } - } - return err - }) - } -} - -// ByUnmarshallingJSON returns a RespondDecorator that decodes a JSON document returned in the -// response Body into the value pointed to by v. -func ByUnmarshallingJSON(v interface{}) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - b, errInner := ioutil.ReadAll(resp.Body) - // Some responses might include a BOM, remove for successful unmarshalling - b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")) - if errInner != nil { - err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) - } else if len(strings.Trim(string(b), " ")) > 0 { - errInner = json.Unmarshal(b, v) - if errInner != nil { - err = fmt.Errorf("Error occurred unmarshalling JSON - Error = '%v' JSON = '%s'", errInner, string(b)) - } - } - } - return err - }) - } -} - -// ByUnmarshallingXML returns a RespondDecorator that decodes a XML document returned in the -// response Body into the value pointed to by v. -func ByUnmarshallingXML(v interface{}) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - b, errInner := ioutil.ReadAll(resp.Body) - if errInner != nil { - err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) - } else { - errInner = xml.Unmarshal(b, v) - if errInner != nil { - err = fmt.Errorf("Error occurred unmarshalling Xml - Error = '%v' Xml = '%s'", errInner, string(b)) - } - } - } - return err - }) - } -} - -// WithErrorUnlessStatusCode returns a RespondDecorator that emits an error unless the response -// StatusCode is among the set passed. On error, response body is fully read into a buffer and -// presented in the returned error, as well as in the response body. -func WithErrorUnlessStatusCode(codes ...int) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && !ResponseHasStatusCode(resp, codes...) { - derr := NewErrorWithResponse("autorest", "WithErrorUnlessStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - if resp.Body != nil { - defer resp.Body.Close() - b, _ := ioutil.ReadAll(resp.Body) - derr.ServiceError = b - resp.Body = ioutil.NopCloser(bytes.NewReader(b)) - } - err = derr - } - return err - }) - } -} - -// WithErrorUnlessOK returns a RespondDecorator that emits an error if the response StatusCode is -// anything other than HTTP 200. -func WithErrorUnlessOK() RespondDecorator { - return WithErrorUnlessStatusCode(http.StatusOK) -} - -// ExtractHeader extracts all values of the specified header from the http.Response. It returns an -// empty string slice if the passed http.Response is nil or the header does not exist. -func ExtractHeader(header string, resp *http.Response) []string { - if resp != nil && resp.Header != nil { - return resp.Header[http.CanonicalHeaderKey(header)] - } - return nil -} - -// ExtractHeaderValue extracts the first value of the specified header from the http.Response. It -// returns an empty string if the passed http.Response is nil or the header does not exist. -func ExtractHeaderValue(header string, resp *http.Response) string { - h := ExtractHeader(header, resp) - if len(h) > 0 { - return h[0] - } - return "" -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go b/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go deleted file mode 100644 index fa11dbed..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go +++ /dev/null @@ -1,52 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" -) - -// NewRetriableRequest returns a wrapper around an HTTP request that support retry logic. -func NewRetriableRequest(req *http.Request) *RetriableRequest { - return &RetriableRequest{req: req} -} - -// Request returns the wrapped HTTP request. -func (rr *RetriableRequest) Request() *http.Request { - return rr.req -} - -func (rr *RetriableRequest) prepareFromByteReader() (err error) { - // fall back to making a copy (only do this once) - b := []byte{} - if rr.req.ContentLength > 0 { - b = make([]byte, rr.req.ContentLength) - _, err = io.ReadFull(rr.req.Body, b) - if err != nil { - return err - } - } else { - b, err = ioutil.ReadAll(rr.req.Body) - if err != nil { - return err - } - } - rr.br = bytes.NewReader(b) - rr.req.Body = ioutil.NopCloser(rr.br) - return err -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go b/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go deleted file mode 100644 index 7143cc61..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go +++ /dev/null @@ -1,54 +0,0 @@ -// +build !go1.8 - -// Copyright 2017 Microsoft Corporation -// -// 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 autorest - -import ( - "bytes" - "io/ioutil" - "net/http" -) - -// RetriableRequest provides facilities for retrying an HTTP request. -type RetriableRequest struct { - req *http.Request - br *bytes.Reader -} - -// Prepare signals that the request is about to be sent. -func (rr *RetriableRequest) Prepare() (err error) { - // preserve the request body; this is to support retry logic as - // the underlying transport will always close the reqeust body - if rr.req.Body != nil { - if rr.br != nil { - _, err = rr.br.Seek(0, 0 /*io.SeekStart*/) - rr.req.Body = ioutil.NopCloser(rr.br) - } - if err != nil { - return err - } - if rr.br == nil { - // fall back to making a copy (only do this once) - err = rr.prepareFromByteReader() - } - } - return err -} - -func removeRequestBody(req *http.Request) { - req.Body = nil - req.ContentLength = 0 -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go b/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go deleted file mode 100644 index ae15c6bf..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go +++ /dev/null @@ -1,66 +0,0 @@ -// +build go1.8 - -// Copyright 2017 Microsoft Corporation -// -// 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 autorest - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" -) - -// RetriableRequest provides facilities for retrying an HTTP request. -type RetriableRequest struct { - req *http.Request - rc io.ReadCloser - br *bytes.Reader -} - -// Prepare signals that the request is about to be sent. -func (rr *RetriableRequest) Prepare() (err error) { - // preserve the request body; this is to support retry logic as - // the underlying transport will always close the reqeust body - if rr.req.Body != nil { - if rr.rc != nil { - rr.req.Body = rr.rc - } else if rr.br != nil { - _, err = rr.br.Seek(0, io.SeekStart) - rr.req.Body = ioutil.NopCloser(rr.br) - } - if err != nil { - return err - } - if rr.req.GetBody != nil { - // this will allow us to preserve the body without having to - // make a copy. note we need to do this on each iteration - rr.rc, err = rr.req.GetBody() - if err != nil { - return err - } - } else if rr.br == nil { - // fall back to making a copy (only do this once) - err = rr.prepareFromByteReader() - } - } - return err -} - -func removeRequestBody(req *http.Request) { - req.Body = nil - req.GetBody = nil - req.ContentLength = 0 -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/sender.go b/vendor/github.com/Azure/go-autorest/autorest/sender.go deleted file mode 100644 index 78610ef2..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/sender.go +++ /dev/null @@ -1,447 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "context" - "crypto/tls" - "fmt" - "log" - "math" - "net/http" - "net/http/cookiejar" - "strconv" - "sync" - "time" - - "github.com/Azure/go-autorest/tracing" -) - -// there is one sender per TLS renegotiation type, i.e. count of tls.RenegotiationSupport enums -const defaultSendersCount = 3 - -type defaultSender struct { - sender Sender - init *sync.Once -} - -// each type of sender will be created on demand in sender() -var defaultSenders [defaultSendersCount]defaultSender - -func init() { - for i := 0; i < defaultSendersCount; i++ { - defaultSenders[i].init = &sync.Once{} - } -} - -// used as a key type in context.WithValue() -type ctxSendDecorators struct{} - -// WithSendDecorators adds the specified SendDecorators to the provided context. -// If no SendDecorators are provided the context is unchanged. -func WithSendDecorators(ctx context.Context, sendDecorator []SendDecorator) context.Context { - if len(sendDecorator) == 0 { - return ctx - } - return context.WithValue(ctx, ctxSendDecorators{}, sendDecorator) -} - -// GetSendDecorators returns the SendDecorators in the provided context or the provided default SendDecorators. -func GetSendDecorators(ctx context.Context, defaultSendDecorators ...SendDecorator) []SendDecorator { - inCtx := ctx.Value(ctxSendDecorators{}) - if sd, ok := inCtx.([]SendDecorator); ok { - return sd - } - return defaultSendDecorators -} - -// Sender is the interface that wraps the Do method to send HTTP requests. -// -// The standard http.Client conforms to this interface. -type Sender interface { - Do(*http.Request) (*http.Response, error) -} - -// SenderFunc is a method that implements the Sender interface. -type SenderFunc func(*http.Request) (*http.Response, error) - -// Do implements the Sender interface on SenderFunc. -func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { - return sf(r) -} - -// SendDecorator takes and possibly decorates, by wrapping, a Sender. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then react to the -// http.Response result. -type SendDecorator func(Sender) Sender - -// CreateSender creates, decorates, and returns, as a Sender, the default http.Client. -func CreateSender(decorators ...SendDecorator) Sender { - return DecorateSender(sender(tls.RenegotiateNever), decorators...) -} - -// DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to -// the Sender. Decorators are applied in the order received, but their affect upon the request -// depends on whether they are a pre-decorator (change the http.Request and then pass it along) or a -// post-decorator (pass the http.Request along and react to the results in http.Response). -func DecorateSender(s Sender, decorators ...SendDecorator) Sender { - for _, decorate := range decorators { - s = decorate(s) - } - return s -} - -// Send sends, by means of the default http.Client, the passed http.Request, returning the -// http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which -// it will apply the http.Client before invoking the Do method. -// -// Send is a convenience method and not recommended for production. Advanced users should use -// SendWithSender, passing and sharing their own Sender (e.g., instance of http.Client). -// -// Send will not poll or retry requests. -func Send(r *http.Request, decorators ...SendDecorator) (*http.Response, error) { - return SendWithSender(sender(tls.RenegotiateNever), r, decorators...) -} - -// SendWithSender sends the passed http.Request, through the provided Sender, returning the -// http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which -// it will apply the http.Client before invoking the Do method. -// -// SendWithSender will not poll or retry requests. -func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*http.Response, error) { - return DecorateSender(s, decorators...).Do(r) -} - -func sender(renengotiation tls.RenegotiationSupport) Sender { - // note that we can't init defaultSenders in init() since it will - // execute before calling code has had a chance to enable tracing - defaultSenders[renengotiation].init.Do(func() { - // Use behaviour compatible with DefaultTransport, but require TLS minimum version. - defaultTransport := http.DefaultTransport.(*http.Transport) - transport := &http.Transport{ - Proxy: defaultTransport.Proxy, - DialContext: defaultTransport.DialContext, - MaxIdleConns: defaultTransport.MaxIdleConns, - IdleConnTimeout: defaultTransport.IdleConnTimeout, - TLSHandshakeTimeout: defaultTransport.TLSHandshakeTimeout, - ExpectContinueTimeout: defaultTransport.ExpectContinueTimeout, - TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS12, - Renegotiation: renengotiation, - }, - } - var roundTripper http.RoundTripper = transport - if tracing.IsEnabled() { - roundTripper = tracing.NewTransport(transport) - } - j, _ := cookiejar.New(nil) - defaultSenders[renengotiation].sender = &http.Client{Jar: j, Transport: roundTripper} - }) - return defaultSenders[renengotiation].sender -} - -// AfterDelay returns a SendDecorator that delays for the passed time.Duration before -// invoking the Sender. The delay may be terminated by closing the optional channel on the -// http.Request. If canceled, no further Senders are invoked. -func AfterDelay(d time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - if !DelayForBackoff(d, 0, r.Context().Done()) { - return nil, fmt.Errorf("autorest: AfterDelay canceled before full delay") - } - return s.Do(r) - }) - } -} - -// AsIs returns a SendDecorator that invokes the passed Sender without modifying the http.Request. -func AsIs() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return s.Do(r) - }) - } -} - -// DoCloseIfError returns a SendDecorator that first invokes the passed Sender after which -// it closes the response if the passed Sender returns an error and the response body exists. -func DoCloseIfError() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err != nil { - Respond(resp, ByDiscardingBody(), ByClosing()) - } - return resp, err - }) - } -} - -// DoErrorIfStatusCode returns a SendDecorator that emits an error if the response StatusCode is -// among the set passed. Since these are artificial errors, the response body may still require -// closing. -func DoErrorIfStatusCode(codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil && ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithResponse("autorest", "DoErrorIfStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - } - return resp, err - }) - } -} - -// DoErrorUnlessStatusCode returns a SendDecorator that emits an error unless the response -// StatusCode is among the set passed. Since these are artificial errors, the response body -// may still require closing. -func DoErrorUnlessStatusCode(codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil && !ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithResponse("autorest", "DoErrorUnlessStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - } - return resp, err - }) - } -} - -// DoPollForStatusCodes returns a SendDecorator that polls if the http.Response contains one of the -// passed status codes. It expects the http.Response to contain a Location header providing the -// URL at which to poll (using GET) and will poll until the time passed is equal to or greater than -// the supplied duration. It will delay between requests for the duration specified in the -// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by -// closing the optional channel on the http.Request. -func DoPollForStatusCodes(duration time.Duration, delay time.Duration, codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - resp, err = s.Do(r) - - if err == nil && ResponseHasStatusCode(resp, codes...) { - r, err = NewPollingRequestWithContext(r.Context(), resp) - - for err == nil && ResponseHasStatusCode(resp, codes...) { - Respond(resp, - ByDiscardingBody(), - ByClosing()) - resp, err = SendWithSender(s, r, - AfterDelay(GetRetryAfter(resp, delay))) - } - } - - return resp, err - }) - } -} - -// DoRetryForAttempts returns a SendDecorator that retries a failed request for up to the specified -// number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). Retrying may be canceled by closing the optional channel on -// the http.Request. -func DoRetryForAttempts(attempts int, backoff time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - for attempt := 0; attempt < attempts; attempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - DrainResponseBody(resp) - resp, err = s.Do(rr.Request()) - if err == nil { - return resp, err - } - if !DelayForBackoff(backoff, attempt, r.Context().Done()) { - return nil, r.Context().Err() - } - } - return resp, err - }) - } -} - -// Count429AsRetry indicates that a 429 response should be included as a retry attempt. -var Count429AsRetry = true - -// Max429Delay is the maximum duration to wait between retries on a 429 if no Retry-After header was received. -var Max429Delay time.Duration - -// DoRetryForStatusCodes returns a SendDecorator that retries for specified statusCodes for up to the specified -// number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). Retrying may be canceled by cancelling the context on the http.Request. -// NOTE: Code http.StatusTooManyRequests (429) will *not* be counted against the number of attempts. -func DoRetryForStatusCodes(attempts int, backoff time.Duration, codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return doRetryForStatusCodesImpl(s, r, Count429AsRetry, attempts, backoff, 0, codes...) - }) - } -} - -// DoRetryForStatusCodesWithCap returns a SendDecorator that retries for specified statusCodes for up to the -// specified number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). To cap the maximum possible delay between iterations specify a value greater -// than zero for cap. Retrying may be canceled by cancelling the context on the http.Request. -func DoRetryForStatusCodesWithCap(attempts int, backoff, cap time.Duration, codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return doRetryForStatusCodesImpl(s, r, Count429AsRetry, attempts, backoff, cap, codes...) - }) - } -} - -func doRetryForStatusCodesImpl(s Sender, r *http.Request, count429 bool, attempts int, backoff, cap time.Duration, codes ...int) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - // Increment to add the first call (attempts denotes number of retries) - for attempt, delayCount := 0, 0; attempt < attempts+1; { - err = rr.Prepare() - if err != nil { - return - } - DrainResponseBody(resp) - resp, err = s.Do(rr.Request()) - // we want to retry if err is not nil (e.g. transient network failure). note that for failed authentication - // resp and err will both have a value, so in this case we don't want to retry as it will never succeed. - if err == nil && !ResponseHasStatusCode(resp, codes...) || IsTokenRefreshError(err) { - return resp, err - } - delayed := DelayWithRetryAfter(resp, r.Context().Done()) - // if this was a 429 set the delay cap as specified. - // applicable only in the absence of a retry-after header. - if resp != nil && resp.StatusCode == http.StatusTooManyRequests { - cap = Max429Delay - } - if !delayed && !DelayForBackoffWithCap(backoff, cap, delayCount, r.Context().Done()) { - return resp, r.Context().Err() - } - // when count429 == false don't count a 429 against the number - // of attempts so that we continue to retry until it succeeds - if count429 || (resp == nil || resp.StatusCode != http.StatusTooManyRequests) { - attempt++ - } - // delay count is tracked separately from attempts to - // ensure that 429 participates in exponential back-off - delayCount++ - } - return resp, err -} - -// DelayWithRetryAfter invokes time.After for the duration specified in the "Retry-After" header. -// The value of Retry-After can be either the number of seconds or a date in RFC1123 format. -// The function returns true after successfully waiting for the specified duration. If there is -// no Retry-After header or the wait is cancelled the return value is false. -func DelayWithRetryAfter(resp *http.Response, cancel <-chan struct{}) bool { - if resp == nil { - return false - } - var dur time.Duration - ra := resp.Header.Get("Retry-After") - if retryAfter, _ := strconv.Atoi(ra); retryAfter > 0 { - dur = time.Duration(retryAfter) * time.Second - } else if t, err := time.Parse(time.RFC1123, ra); err == nil { - dur = t.Sub(time.Now()) - } - if dur > 0 { - select { - case <-time.After(dur): - return true - case <-cancel: - return false - } - } - return false -} - -// DoRetryForDuration returns a SendDecorator that retries the request until the total time is equal -// to or greater than the specified duration, exponentially backing off between requests using the -// supplied backoff time.Duration (which may be zero). Retrying may be canceled by closing the -// optional channel on the http.Request. -func DoRetryForDuration(d time.Duration, backoff time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - end := time.Now().Add(d) - for attempt := 0; time.Now().Before(end); attempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - DrainResponseBody(resp) - resp, err = s.Do(rr.Request()) - if err == nil { - return resp, err - } - if !DelayForBackoff(backoff, attempt, r.Context().Done()) { - return nil, r.Context().Err() - } - } - return resp, err - }) - } -} - -// WithLogging returns a SendDecorator that implements simple before and after logging of the -// request. -func WithLogging(logger *log.Logger) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - logger.Printf("Sending %s %s", r.Method, r.URL) - resp, err := s.Do(r) - if err != nil { - logger.Printf("%s %s received error '%v'", r.Method, r.URL, err) - } else { - logger.Printf("%s %s received %s", r.Method, r.URL, resp.Status) - } - return resp, err - }) - } -} - -// DelayForBackoff invokes time.After for the supplied backoff duration raised to the power of -// passed attempt (i.e., an exponential backoff delay). Backoff duration is in seconds and can set -// to zero for no delay. The delay may be canceled by closing the passed channel. If terminated early, -// returns false. -// Note: Passing attempt 1 will result in doubling "backoff" duration. Treat this as a zero-based attempt -// count. -func DelayForBackoff(backoff time.Duration, attempt int, cancel <-chan struct{}) bool { - return DelayForBackoffWithCap(backoff, 0, attempt, cancel) -} - -// DelayForBackoffWithCap invokes time.After for the supplied backoff duration raised to the power of -// passed attempt (i.e., an exponential backoff delay). Backoff duration is in seconds and can set -// to zero for no delay. To cap the maximum possible delay specify a value greater than zero for cap. -// The delay may be canceled by closing the passed channel. If terminated early, returns false. -// Note: Passing attempt 1 will result in doubling "backoff" duration. Treat this as a zero-based attempt -// count. -func DelayForBackoffWithCap(backoff, cap time.Duration, attempt int, cancel <-chan struct{}) bool { - d := time.Duration(backoff.Seconds()*math.Pow(2, float64(attempt))) * time.Second - if cap > 0 && d > cap { - d = cap - } - select { - case <-time.After(d): - return true - case <-cancel: - return false - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/to/LICENSE deleted file mode 100644 index b9d6a27e..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/to/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2015 Microsoft Corporation - - 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/Azure/go-autorest/autorest/to/convert.go b/vendor/github.com/Azure/go-autorest/autorest/to/convert.go deleted file mode 100644 index 86694bd2..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/to/convert.go +++ /dev/null @@ -1,152 +0,0 @@ -/* -Package to provides helpers to ease working with pointer values of marshalled structures. -*/ -package to - -// Copyright 2017 Microsoft Corporation -// -// 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. - -// String returns a string value for the passed string pointer. It returns the empty string if the -// pointer is nil. -func String(s *string) string { - if s != nil { - return *s - } - return "" -} - -// StringPtr returns a pointer to the passed string. -func StringPtr(s string) *string { - return &s -} - -// StringSlice returns a string slice value for the passed string slice pointer. It returns a nil -// slice if the pointer is nil. -func StringSlice(s *[]string) []string { - if s != nil { - return *s - } - return nil -} - -// StringSlicePtr returns a pointer to the passed string slice. -func StringSlicePtr(s []string) *[]string { - return &s -} - -// StringMap returns a map of strings built from the map of string pointers. The empty string is -// used for nil pointers. -func StringMap(msp map[string]*string) map[string]string { - ms := make(map[string]string, len(msp)) - for k, sp := range msp { - if sp != nil { - ms[k] = *sp - } else { - ms[k] = "" - } - } - return ms -} - -// StringMapPtr returns a pointer to a map of string pointers built from the passed map of strings. -func StringMapPtr(ms map[string]string) *map[string]*string { - msp := make(map[string]*string, len(ms)) - for k, s := range ms { - msp[k] = StringPtr(s) - } - return &msp -} - -// Bool returns a bool value for the passed bool pointer. It returns false if the pointer is nil. -func Bool(b *bool) bool { - if b != nil { - return *b - } - return false -} - -// BoolPtr returns a pointer to the passed bool. -func BoolPtr(b bool) *bool { - return &b -} - -// Int returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int(i *int) int { - if i != nil { - return *i - } - return 0 -} - -// IntPtr returns a pointer to the passed int. -func IntPtr(i int) *int { - return &i -} - -// Int32 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int32(i *int32) int32 { - if i != nil { - return *i - } - return 0 -} - -// Int32Ptr returns a pointer to the passed int32. -func Int32Ptr(i int32) *int32 { - return &i -} - -// Int64 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int64(i *int64) int64 { - if i != nil { - return *i - } - return 0 -} - -// Int64Ptr returns a pointer to the passed int64. -func Int64Ptr(i int64) *int64 { - return &i -} - -// Float32 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. -func Float32(i *float32) float32 { - if i != nil { - return *i - } - return 0.0 -} - -// Float32Ptr returns a pointer to the passed float32. -func Float32Ptr(i float32) *float32 { - return &i -} - -// Float64 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. -func Float64(i *float64) float64 { - if i != nil { - return *i - } - return 0.0 -} - -// Float64Ptr returns a pointer to the passed float64. -func Float64Ptr(i float64) *float64 { - return &i -} - -// ByteSlicePtr returns a pointer to the passed byte slice. -func ByteSlicePtr(b []byte) *[]byte { - return &b -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/to/go_mod_tidy_hack.go deleted file mode 100644 index b7310f6b..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/to/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package to - -// Copyright 2017 Microsoft Corporation -// -// 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. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility.go b/vendor/github.com/Azure/go-autorest/autorest/utility.go deleted file mode 100644 index 3467b8fa..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/utility.go +++ /dev/null @@ -1,232 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/url" - "reflect" - "strings" -) - -// EncodedAs is a series of constants specifying various data encodings -type EncodedAs string - -const ( - // EncodedAsJSON states that data is encoded as JSON - EncodedAsJSON EncodedAs = "JSON" - - // EncodedAsXML states that data is encoded as Xml - EncodedAsXML EncodedAs = "XML" -) - -// Decoder defines the decoding method json.Decoder and xml.Decoder share -type Decoder interface { - Decode(v interface{}) error -} - -// NewDecoder creates a new decoder appropriate to the passed encoding. -// encodedAs specifies the type of encoding and r supplies the io.Reader containing the -// encoded data. -func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder { - if encodedAs == EncodedAsJSON { - return json.NewDecoder(r) - } else if encodedAs == EncodedAsXML { - return xml.NewDecoder(r) - } - return nil -} - -// CopyAndDecode decodes the data from the passed io.Reader while making a copy. Having a copy -// is especially useful if there is a chance the data will fail to decode. -// encodedAs specifies the expected encoding, r provides the io.Reader to the data, and v -// is the decoding destination. -func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) { - b := bytes.Buffer{} - return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v) -} - -// TeeReadCloser returns a ReadCloser that writes to w what it reads from rc. -// It utilizes io.TeeReader to copy the data read and has the same behavior when reading. -// Further, when it is closed, it ensures that rc is closed as well. -func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser { - return &teeReadCloser{rc, io.TeeReader(rc, w)} -} - -type teeReadCloser struct { - rc io.ReadCloser - r io.Reader -} - -func (t *teeReadCloser) Read(p []byte) (int, error) { - return t.r.Read(p) -} - -func (t *teeReadCloser) Close() error { - return t.rc.Close() -} - -func containsInt(ints []int, n int) bool { - for _, i := range ints { - if i == n { - return true - } - } - return false -} - -func escapeValueStrings(m map[string]string) map[string]string { - for key, value := range m { - m[key] = url.QueryEscape(value) - } - return m -} - -func ensureValueStrings(mapOfInterface map[string]interface{}) map[string]string { - mapOfStrings := make(map[string]string) - for key, value := range mapOfInterface { - mapOfStrings[key] = ensureValueString(value) - } - return mapOfStrings -} - -func ensureValueString(value interface{}) string { - if value == nil { - return "" - } - switch v := value.(type) { - case string: - return v - case []byte: - return string(v) - default: - return fmt.Sprintf("%v", v) - } -} - -// MapToValues method converts map[string]interface{} to url.Values. -func MapToValues(m map[string]interface{}) url.Values { - v := url.Values{} - for key, value := range m { - x := reflect.ValueOf(value) - if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { - for i := 0; i < x.Len(); i++ { - v.Add(key, ensureValueString(x.Index(i))) - } - } else { - v.Add(key, ensureValueString(value)) - } - } - return v -} - -// AsStringSlice method converts interface{} to []string. -// s must be of type slice or array or an error is returned. -// Each element of s will be converted to its string representation. -func AsStringSlice(s interface{}) ([]string, error) { - v := reflect.ValueOf(s) - if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { - return nil, NewError("autorest", "AsStringSlice", "the value's type is not a slice or array.") - } - stringSlice := make([]string, 0, v.Len()) - - for i := 0; i < v.Len(); i++ { - stringSlice = append(stringSlice, fmt.Sprintf("%v", v.Index(i))) - } - return stringSlice, nil -} - -// String method converts interface v to string. If interface is a list, it -// joins list elements using the separator. Note that only sep[0] will be used for -// joining if any separator is specified. -func String(v interface{}, sep ...string) string { - if len(sep) == 0 { - return ensureValueString(v) - } - stringSlice, ok := v.([]string) - if ok == false { - var err error - stringSlice, err = AsStringSlice(v) - if err != nil { - panic(fmt.Sprintf("autorest: Couldn't convert value to a string %s.", err)) - } - } - return ensureValueString(strings.Join(stringSlice, sep[0])) -} - -// Encode method encodes url path and query parameters. -func Encode(location string, v interface{}, sep ...string) string { - s := String(v, sep...) - switch strings.ToLower(location) { - case "path": - return pathEscape(s) - case "query": - return queryEscape(s) - default: - return s - } -} - -func pathEscape(s string) string { - return strings.Replace(url.QueryEscape(s), "+", "%20", -1) -} - -func queryEscape(s string) string { - return url.QueryEscape(s) -} - -// ChangeToGet turns the specified http.Request into a GET (it assumes it wasn't). -// This is mainly useful for long-running operations that use the Azure-AsyncOperation -// header, so we change the initial PUT into a GET to retrieve the final result. -func ChangeToGet(req *http.Request) *http.Request { - req.Method = "GET" - req.Body = nil - req.ContentLength = 0 - req.Header.Del("Content-Length") - return req -} - -// IsTemporaryNetworkError returns true if the specified error is a temporary network error or false -// if it's not. If the error doesn't implement the net.Error interface the return value is true. -func IsTemporaryNetworkError(err error) bool { - if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) { - return true - } - return false -} - -// DrainResponseBody reads the response body then closes it. -func DrainResponseBody(resp *http.Response) error { - if resp != nil && resp.Body != nil { - _, err := io.Copy(ioutil.Discard, resp.Body) - resp.Body.Close() - return err - } - return nil -} - -func setHeader(r *http.Request, key, value string) { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set(key, value) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility_1.13.go b/vendor/github.com/Azure/go-autorest/autorest/utility_1.13.go deleted file mode 100644 index 4cb5e684..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/utility_1.13.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build go1.13 - -// Copyright 2017 Microsoft Corporation -// -// 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 autorest - -import ( - "errors" - - "github.com/Azure/go-autorest/autorest/adal" -) - -// IsTokenRefreshError returns true if the specified error implements the TokenRefreshError interface. -func IsTokenRefreshError(err error) bool { - var tre adal.TokenRefreshError - return errors.As(err, &tre) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility_legacy.go b/vendor/github.com/Azure/go-autorest/autorest/utility_legacy.go deleted file mode 100644 index ebb51b4f..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/utility_legacy.go +++ /dev/null @@ -1,31 +0,0 @@ -// +build !go1.13 - -// Copyright 2017 Microsoft Corporation -// -// 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 autorest - -import "github.com/Azure/go-autorest/autorest/adal" - -// IsTokenRefreshError returns true if the specified error implements the TokenRefreshError -// interface. If err is a DetailedError it will walk the chain of Original errors. -func IsTokenRefreshError(err error) bool { - if _, ok := err.(adal.TokenRefreshError); ok { - return true - } - if de, ok := err.(DetailedError); ok { - return IsTokenRefreshError(de.Original) - } - return false -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/LICENSE b/vendor/github.com/Azure/go-autorest/autorest/validation/LICENSE deleted file mode 100644 index b9d6a27e..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/validation/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2015 Microsoft Corporation - - 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/Azure/go-autorest/autorest/validation/error.go b/vendor/github.com/Azure/go-autorest/autorest/validation/error.go deleted file mode 100644 index fed156db..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/validation/error.go +++ /dev/null @@ -1,48 +0,0 @@ -package validation - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "fmt" -) - -// Error is the type that's returned when the validation of an APIs arguments constraints fails. -type Error struct { - // PackageType is the package type of the object emitting the error. For types, the value - // matches that produced the the '%T' format specifier of the fmt package. For other elements, - // such as functions, it is just the package name (e.g., "autorest"). - PackageType string - - // Method is the name of the method raising the error. - Method string - - // Message is the error message. - Message string -} - -// Error returns a string containing the details of the validation failure. -func (e Error) Error() string { - return fmt.Sprintf("%s#%s: Invalid input: %s", e.PackageType, e.Method, e.Message) -} - -// NewError creates a new Error object with the specified parameters. -// message is treated as a format string to which the optional args apply. -func NewError(packageType string, method string, message string, args ...interface{}) Error { - return Error{ - PackageType: packageType, - Method: method, - Message: fmt.Sprintf(message, args...), - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/autorest/validation/go_mod_tidy_hack.go deleted file mode 100644 index cf143629..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/validation/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package validation - -// Copyright 2017 Microsoft Corporation -// -// 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. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go b/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go deleted file mode 100644 index ff41cfe0..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/validation/validation.go +++ /dev/null @@ -1,406 +0,0 @@ -/* -Package validation provides methods for validating parameter value using reflection. -*/ -package validation - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "fmt" - "reflect" - "regexp" - "strings" -) - -// Disabled controls if parameter validation should be globally disabled. The default is false. -var Disabled bool - -// Constraint stores constraint name, target field name -// Rule and chain validations. -type Constraint struct { - - // Target field name for validation. - Target string - - // Constraint name e.g. minLength, MaxLength, Pattern, etc. - Name string - - // Rule for constraint e.g. greater than 10, less than 5 etc. - Rule interface{} - - // Chain Validations for struct type - Chain []Constraint -} - -// Validation stores parameter-wise validation. -type Validation struct { - TargetValue interface{} - Constraints []Constraint -} - -// Constraint list -const ( - Empty = "Empty" - Null = "Null" - ReadOnly = "ReadOnly" - Pattern = "Pattern" - MaxLength = "MaxLength" - MinLength = "MinLength" - MaxItems = "MaxItems" - MinItems = "MinItems" - MultipleOf = "MultipleOf" - UniqueItems = "UniqueItems" - InclusiveMaximum = "InclusiveMaximum" - ExclusiveMaximum = "ExclusiveMaximum" - ExclusiveMinimum = "ExclusiveMinimum" - InclusiveMinimum = "InclusiveMinimum" -) - -// Validate method validates constraints on parameter -// passed in validation array. -func Validate(m []Validation) error { - if Disabled { - return nil - } - for _, item := range m { - v := reflect.ValueOf(item.TargetValue) - for _, constraint := range item.Constraints { - var err error - switch v.Kind() { - case reflect.Ptr: - err = validatePtr(v, constraint) - case reflect.String: - err = validateString(v, constraint) - case reflect.Struct: - err = validateStruct(v, constraint) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - err = validateInt(v, constraint) - case reflect.Float32, reflect.Float64: - err = validateFloat(v, constraint) - case reflect.Array, reflect.Slice, reflect.Map: - err = validateArrayMap(v, constraint) - default: - err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind())) - } - - if err != nil { - return err - } - } - } - return nil -} - -func validateStruct(x reflect.Value, v Constraint, name ...string) error { - //Get field name from target name which is in format a.b.c - s := strings.Split(v.Target, ".") - f := x.FieldByName(s[len(s)-1]) - if isZero(f) { - return createError(x, v, fmt.Sprintf("field %q doesn't exist", v.Target)) - } - - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(f), - Constraints: []Constraint{v}, - }, - }) -} - -func validatePtr(x reflect.Value, v Constraint) error { - if v.Name == ReadOnly { - if !x.IsNil() { - return createError(x.Elem(), v, "readonly parameter; must send as nil or empty in request") - } - return nil - } - if x.IsNil() { - return checkNil(x, v) - } - if v.Chain != nil { - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(x.Elem()), - Constraints: v.Chain, - }, - }) - } - return nil -} - -func validateInt(x reflect.Value, v Constraint) error { - i := x.Int() - r, ok := toInt64(v.Rule) - if !ok { - return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) - } - switch v.Name { - case MultipleOf: - if i%r != 0 { - return createError(x, v, fmt.Sprintf("value must be a multiple of %v", r)) - } - case ExclusiveMinimum: - if i <= r { - return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) - } - case ExclusiveMaximum: - if i >= r { - return createError(x, v, fmt.Sprintf("value must be less than %v", r)) - } - case InclusiveMinimum: - if i < r { - return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) - } - case InclusiveMaximum: - if i > r { - return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) - } - default: - return createError(x, v, fmt.Sprintf("constraint %v is not applicable for type integer", v.Name)) - } - return nil -} - -func validateFloat(x reflect.Value, v Constraint) error { - f := x.Float() - r, ok := v.Rule.(float64) - if !ok { - return createError(x, v, fmt.Sprintf("rule must be float value for %v constraint; got: %v", v.Name, v.Rule)) - } - switch v.Name { - case ExclusiveMinimum: - if f <= r { - return createError(x, v, fmt.Sprintf("value must be greater than %v", r)) - } - case ExclusiveMaximum: - if f >= r { - return createError(x, v, fmt.Sprintf("value must be less than %v", r)) - } - case InclusiveMinimum: - if f < r { - return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r)) - } - case InclusiveMaximum: - if f > r { - return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r)) - } - default: - return createError(x, v, fmt.Sprintf("constraint %s is not applicable for type float", v.Name)) - } - return nil -} - -func validateString(x reflect.Value, v Constraint) error { - s := x.String() - switch v.Name { - case Empty: - if len(s) == 0 { - return checkEmpty(x, v) - } - case Pattern: - reg, err := regexp.Compile(v.Rule.(string)) - if err != nil { - return createError(x, v, err.Error()) - } - if !reg.MatchString(s) { - return createError(x, v, fmt.Sprintf("value doesn't match pattern %v", v.Rule)) - } - case MaxLength: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) - } - if len(s) > v.Rule.(int) { - return createError(x, v, fmt.Sprintf("value length must be less than or equal to %v", v.Rule)) - } - case MinLength: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule)) - } - if len(s) < v.Rule.(int) { - return createError(x, v, fmt.Sprintf("value length must be greater than or equal to %v", v.Rule)) - } - case ReadOnly: - if len(s) > 0 { - return createError(reflect.ValueOf(s), v, "readonly parameter; must send as nil or empty in request") - } - default: - return createError(x, v, fmt.Sprintf("constraint %s is not applicable to string type", v.Name)) - } - - if v.Chain != nil { - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(x), - Constraints: v.Chain, - }, - }) - } - return nil -} - -func validateArrayMap(x reflect.Value, v Constraint) error { - switch v.Name { - case Null: - if x.IsNil() { - return checkNil(x, v) - } - case Empty: - if x.IsNil() || x.Len() == 0 { - return checkEmpty(x, v) - } - case MaxItems: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.Name, v.Rule)) - } - if x.Len() > v.Rule.(int) { - return createError(x, v, fmt.Sprintf("maximum item limit is %v; got: %v", v.Rule, x.Len())) - } - case MinItems: - if _, ok := v.Rule.(int); !ok { - return createError(x, v, fmt.Sprintf("rule must be integer for %v constraint; got: %v", v.Name, v.Rule)) - } - if x.Len() < v.Rule.(int) { - return createError(x, v, fmt.Sprintf("minimum item limit is %v; got: %v", v.Rule, x.Len())) - } - case UniqueItems: - if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { - if !checkForUniqueInArray(x) { - return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.Target, x)) - } - } else if x.Kind() == reflect.Map { - if !checkForUniqueInMap(x) { - return createError(x, v, fmt.Sprintf("all items in parameter %q must be unique; got:%v", v.Target, x)) - } - } else { - return createError(x, v, fmt.Sprintf("type must be array, slice or map for constraint %v; got: %v", v.Name, x.Kind())) - } - case ReadOnly: - if x.Len() != 0 { - return createError(x, v, "readonly parameter; must send as nil or empty in request") - } - case Pattern: - reg, err := regexp.Compile(v.Rule.(string)) - if err != nil { - return createError(x, v, err.Error()) - } - keys := x.MapKeys() - for _, k := range keys { - if !reg.MatchString(k.String()) { - return createError(k, v, fmt.Sprintf("map key doesn't match pattern %v", v.Rule)) - } - } - default: - return createError(x, v, fmt.Sprintf("constraint %v is not applicable to array, slice and map type", v.Name)) - } - - if v.Chain != nil { - return Validate([]Validation{ - { - TargetValue: getInterfaceValue(x), - Constraints: v.Chain, - }, - }) - } - return nil -} - -func checkNil(x reflect.Value, v Constraint) error { - if _, ok := v.Rule.(bool); !ok { - return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.Name, v.Rule)) - } - if v.Rule.(bool) { - return createError(x, v, "value can not be null; required parameter") - } - return nil -} - -func checkEmpty(x reflect.Value, v Constraint) error { - if _, ok := v.Rule.(bool); !ok { - return createError(x, v, fmt.Sprintf("rule must be bool value for %v constraint; got: %v", v.Name, v.Rule)) - } - - if v.Rule.(bool) { - return createError(x, v, "value can not be null or empty; required parameter") - } - return nil -} - -func checkForUniqueInArray(x reflect.Value) bool { - if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { - return false - } - arrOfInterface := make([]interface{}, x.Len()) - - for i := 0; i < x.Len(); i++ { - arrOfInterface[i] = x.Index(i).Interface() - } - - m := make(map[interface{}]bool) - for _, val := range arrOfInterface { - if m[val] { - return false - } - m[val] = true - } - return true -} - -func checkForUniqueInMap(x reflect.Value) bool { - if x == reflect.Zero(reflect.TypeOf(x)) || x.Len() == 0 { - return false - } - mapOfInterface := make(map[interface{}]interface{}, x.Len()) - - keys := x.MapKeys() - for _, k := range keys { - mapOfInterface[k.Interface()] = x.MapIndex(k).Interface() - } - - m := make(map[interface{}]bool) - for _, val := range mapOfInterface { - if m[val] { - return false - } - m[val] = true - } - return true -} - -func getInterfaceValue(x reflect.Value) interface{} { - if x.Kind() == reflect.Invalid { - return nil - } - return x.Interface() -} - -func isZero(x interface{}) bool { - return x == reflect.Zero(reflect.TypeOf(x)).Interface() -} - -func createError(x reflect.Value, v Constraint, err string) error { - return fmt.Errorf("autorest/validation: validation failed: parameter=%s constraint=%s value=%#v details: %s", - v.Target, v.Name, getInterfaceValue(x), err) -} - -func toInt64(v interface{}) (int64, bool) { - if i64, ok := v.(int64); ok { - return i64, true - } - // older generators emit max constants as int, so if int64 fails fall back to int - if i32, ok := v.(int); ok { - return int64(i32), true - } - return 0, false -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/version.go b/vendor/github.com/Azure/go-autorest/autorest/version.go deleted file mode 100644 index 713e2358..00000000 --- a/vendor/github.com/Azure/go-autorest/autorest/version.go +++ /dev/null @@ -1,41 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "fmt" - "runtime" -) - -const number = "v14.2.1" - -var ( - userAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s", - runtime.Version(), - runtime.GOARCH, - runtime.GOOS, - number, - ) -) - -// UserAgent returns a string containing the Go version, system architecture and OS, and the go-autorest version. -func UserAgent() string { - return userAgent -} - -// Version returns the semantic version (see http://semver.org). -func Version() string { - return number -} diff --git a/vendor/github.com/Azure/go-autorest/azure-pipelines.yml b/vendor/github.com/Azure/go-autorest/azure-pipelines.yml deleted file mode 100644 index 6fb8404f..00000000 --- a/vendor/github.com/Azure/go-autorest/azure-pipelines.yml +++ /dev/null @@ -1,105 +0,0 @@ -variables: - GOPATH: '$(system.defaultWorkingDirectory)/work' - sdkPath: '$(GOPATH)/src/github.com/$(build.repository.name)' - -jobs: - - job: 'goautorest' - displayName: 'Run go-autorest CI Checks' - - strategy: - matrix: - Linux_Go113: - vm.image: 'ubuntu-18.04' - go.version: '1.13' - Linux_Go114: - vm.image: 'ubuntu-18.04' - go.version: '1.14' - - pool: - vmImage: '$(vm.image)' - - steps: - - task: GoTool@0 - inputs: - version: '$(go.version)' - displayName: "Select Go Version" - - - script: | - set -e - mkdir -p '$(GOPATH)/bin' - mkdir -p '$(sdkPath)' - shopt -s extglob - mv !(work) '$(sdkPath)' - echo '##vso[task.prependpath]$(GOPATH)/bin' - displayName: 'Create Go Workspace' - - - script: | - set -e - curl -sSL https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - dep ensure -v - go install ./vendor/golang.org/x/lint/golint - go get github.com/jstemmer/go-junit-report - go get github.com/axw/gocov/gocov - go get github.com/AlekSi/gocov-xml - go get -u github.com/matm/gocov-html - workingDirectory: '$(sdkPath)' - displayName: 'Install Dependencies' - - - script: | - go vet ./autorest/... - go vet ./logger/... - go vet ./tracing/... - workingDirectory: '$(sdkPath)' - displayName: 'Vet' - - - script: | - go build -v ./autorest/... - go build -v ./logger/... - go build -v ./tracing/... - workingDirectory: '$(sdkPath)' - displayName: 'Build' - - - script: | - set -e - go test -race -v -coverprofile=coverage.txt -covermode atomic ./autorest/... ./logger/... ./tracing/... 2>&1 | go-junit-report > report.xml - gocov convert coverage.txt > coverage.json - gocov-xml < coverage.json > coverage.xml - gocov-html < coverage.json > coverage.html - workingDirectory: '$(sdkPath)' - displayName: 'Run Tests' - - - script: grep -L -r --include *.go --exclude-dir vendor -P "Copyright (\d{4}|\(c\)) Microsoft" ./ | tee >&2 - workingDirectory: '$(sdkPath)' - displayName: 'Copyright Header Check' - failOnStderr: true - condition: succeededOrFailed() - - - script: | - gofmt -s -l -w ./autorest/. >&2 - gofmt -s -l -w ./logger/. >&2 - gofmt -s -l -w ./tracing/. >&2 - workingDirectory: '$(sdkPath)' - displayName: 'Format Check' - failOnStderr: true - condition: succeededOrFailed() - - - script: | - golint ./autorest/... >&2 - golint ./logger/... >&2 - golint ./tracing/... >&2 - workingDirectory: '$(sdkPath)' - displayName: 'Linter Check' - failOnStderr: true - condition: succeededOrFailed() - - - task: PublishTestResults@2 - inputs: - testRunner: JUnit - testResultsFiles: $(sdkPath)/report.xml - failTaskOnFailedTests: true - - - task: PublishCodeCoverageResults@1 - inputs: - codeCoverageTool: Cobertura - summaryFileLocation: $(sdkPath)/coverage.xml - additionalCodeCoverageFiles: $(sdkPath)/coverage.html diff --git a/vendor/github.com/Azure/go-autorest/doc.go b/vendor/github.com/Azure/go-autorest/doc.go deleted file mode 100644 index 99ae6ca9..00000000 --- a/vendor/github.com/Azure/go-autorest/doc.go +++ /dev/null @@ -1,18 +0,0 @@ -/* -Package go-autorest provides an HTTP request client for use with Autorest-generated API client packages. -*/ -package go_autorest - -// Copyright 2017 Microsoft Corporation -// -// 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/Azure/go-autorest/logger/LICENSE b/vendor/github.com/Azure/go-autorest/logger/LICENSE deleted file mode 100644 index b9d6a27e..00000000 --- a/vendor/github.com/Azure/go-autorest/logger/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2015 Microsoft Corporation - - 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/Azure/go-autorest/logger/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/logger/go_mod_tidy_hack.go deleted file mode 100644 index 0aa27680..00000000 --- a/vendor/github.com/Azure/go-autorest/logger/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package logger - -// Copyright 2017 Microsoft Corporation -// -// 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. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/logger/logger.go b/vendor/github.com/Azure/go-autorest/logger/logger.go deleted file mode 100644 index 2f5d8cc1..00000000 --- a/vendor/github.com/Azure/go-autorest/logger/logger.go +++ /dev/null @@ -1,337 +0,0 @@ -package logger - -// Copyright 2017 Microsoft Corporation -// -// 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. - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - "strings" - "sync" - "time" -) - -// LevelType tells a logger the minimum level to log. When code reports a log entry, -// the LogLevel indicates the level of the log entry. The logger only records entries -// whose level is at least the level it was told to log. See the Log* constants. -// For example, if a logger is configured with LogError, then LogError, LogPanic, -// and LogFatal entries will be logged; lower level entries are ignored. -type LevelType uint32 - -const ( - // LogNone tells a logger not to log any entries passed to it. - LogNone LevelType = iota - - // LogFatal tells a logger to log all LogFatal entries passed to it. - LogFatal - - // LogPanic tells a logger to log all LogPanic and LogFatal entries passed to it. - LogPanic - - // LogError tells a logger to log all LogError, LogPanic and LogFatal entries passed to it. - LogError - - // LogWarning tells a logger to log all LogWarning, LogError, LogPanic and LogFatal entries passed to it. - LogWarning - - // LogInfo tells a logger to log all LogInfo, LogWarning, LogError, LogPanic and LogFatal entries passed to it. - LogInfo - - // LogDebug tells a logger to log all LogDebug, LogInfo, LogWarning, LogError, LogPanic and LogFatal entries passed to it. - LogDebug - - // LogAuth is a special case of LogDebug, it tells a logger to also log the body of an authentication request and response. - // NOTE: this can disclose sensitive information, use with care. - LogAuth -) - -const ( - logNone = "NONE" - logFatal = "FATAL" - logPanic = "PANIC" - logError = "ERROR" - logWarning = "WARNING" - logInfo = "INFO" - logDebug = "DEBUG" - logAuth = "AUTH" - logUnknown = "UNKNOWN" -) - -// ParseLevel converts the specified string into the corresponding LevelType. -func ParseLevel(s string) (lt LevelType, err error) { - switch strings.ToUpper(s) { - case logFatal: - lt = LogFatal - case logPanic: - lt = LogPanic - case logError: - lt = LogError - case logWarning: - lt = LogWarning - case logInfo: - lt = LogInfo - case logDebug: - lt = LogDebug - case logAuth: - lt = LogAuth - default: - err = fmt.Errorf("bad log level '%s'", s) - } - return -} - -// String implements the stringer interface for LevelType. -func (lt LevelType) String() string { - switch lt { - case LogNone: - return logNone - case LogFatal: - return logFatal - case LogPanic: - return logPanic - case LogError: - return logError - case LogWarning: - return logWarning - case LogInfo: - return logInfo - case LogDebug: - return logDebug - case LogAuth: - return logAuth - default: - return logUnknown - } -} - -// Filter defines functions for filtering HTTP request/response content. -type Filter struct { - // URL returns a potentially modified string representation of a request URL. - URL func(u *url.URL) string - - // Header returns a potentially modified set of values for the specified key. - // To completely exclude the header key/values return false. - Header func(key string, val []string) (bool, []string) - - // Body returns a potentially modified request/response body. - Body func(b []byte) []byte -} - -func (f Filter) processURL(u *url.URL) string { - if f.URL == nil { - return u.String() - } - return f.URL(u) -} - -func (f Filter) processHeader(k string, val []string) (bool, []string) { - if f.Header == nil { - return true, val - } - return f.Header(k, val) -} - -func (f Filter) processBody(b []byte) []byte { - if f.Body == nil { - return b - } - return f.Body(b) -} - -// Writer defines methods for writing to a logging facility. -type Writer interface { - // Writeln writes the specified message with the standard log entry header and new-line character. - Writeln(level LevelType, message string) - - // Writef writes the specified format specifier with the standard log entry header and no new-line character. - Writef(level LevelType, format string, a ...interface{}) - - // WriteRequest writes the specified HTTP request to the logger if the log level is greater than - // or equal to LogInfo. The request body, if set, is logged at level LogDebug or higher. - // Custom filters can be specified to exclude URL, header, and/or body content from the log. - // By default no request content is excluded. - WriteRequest(req *http.Request, filter Filter) - - // WriteResponse writes the specified HTTP response to the logger if the log level is greater than - // or equal to LogInfo. The response body, if set, is logged at level LogDebug or higher. - // Custom filters can be specified to exclude URL, header, and/or body content from the log. - // By default no response content is excluded. - WriteResponse(resp *http.Response, filter Filter) -} - -// Instance is the default log writer initialized during package init. -// This can be replaced with a custom implementation as required. -var Instance Writer - -// default log level -var logLevel = LogNone - -// Level returns the value specified in AZURE_GO_AUTOREST_LOG_LEVEL. -// If no value was specified the default value is LogNone. -// Custom loggers can call this to retrieve the configured log level. -func Level() LevelType { - return logLevel -} - -func init() { - // separated for testing purposes - initDefaultLogger() -} - -func initDefaultLogger() { - // init with nilLogger so callers don't have to do a nil check on Default - Instance = nilLogger{} - llStr := strings.ToLower(os.Getenv("AZURE_GO_SDK_LOG_LEVEL")) - if llStr == "" { - return - } - var err error - logLevel, err = ParseLevel(llStr) - if err != nil { - fmt.Fprintf(os.Stderr, "go-autorest: failed to parse log level: %s\n", err.Error()) - return - } - if logLevel == LogNone { - return - } - // default to stderr - dest := os.Stderr - lfStr := os.Getenv("AZURE_GO_SDK_LOG_FILE") - if strings.EqualFold(lfStr, "stdout") { - dest = os.Stdout - } else if lfStr != "" { - lf, err := os.Create(lfStr) - if err == nil { - dest = lf - } else { - fmt.Fprintf(os.Stderr, "go-autorest: failed to create log file, using stderr: %s\n", err.Error()) - } - } - Instance = fileLogger{ - logLevel: logLevel, - mu: &sync.Mutex{}, - logFile: dest, - } -} - -// the nil logger does nothing -type nilLogger struct{} - -func (nilLogger) Writeln(LevelType, string) {} - -func (nilLogger) Writef(LevelType, string, ...interface{}) {} - -func (nilLogger) WriteRequest(*http.Request, Filter) {} - -func (nilLogger) WriteResponse(*http.Response, Filter) {} - -// A File is used instead of a Logger so the stream can be flushed after every write. -type fileLogger struct { - logLevel LevelType - mu *sync.Mutex // for synchronizing writes to logFile - logFile *os.File -} - -func (fl fileLogger) Writeln(level LevelType, message string) { - fl.Writef(level, "%s\n", message) -} - -func (fl fileLogger) Writef(level LevelType, format string, a ...interface{}) { - if fl.logLevel >= level { - fl.mu.Lock() - defer fl.mu.Unlock() - fmt.Fprintf(fl.logFile, "%s %s", entryHeader(level), fmt.Sprintf(format, a...)) - fl.logFile.Sync() - } -} - -func (fl fileLogger) WriteRequest(req *http.Request, filter Filter) { - if req == nil || fl.logLevel < LogInfo { - return - } - b := &bytes.Buffer{} - fmt.Fprintf(b, "%s REQUEST: %s %s\n", entryHeader(LogInfo), req.Method, filter.processURL(req.URL)) - // dump headers - for k, v := range req.Header { - if ok, mv := filter.processHeader(k, v); ok { - fmt.Fprintf(b, "%s: %s\n", k, strings.Join(mv, ",")) - } - } - if fl.shouldLogBody(req.Header, req.Body) { - // dump body - body, err := ioutil.ReadAll(req.Body) - if err == nil { - fmt.Fprintln(b, string(filter.processBody(body))) - if nc, ok := req.Body.(io.Seeker); ok { - // rewind to the beginning - nc.Seek(0, io.SeekStart) - } else { - // recreate the body - req.Body = ioutil.NopCloser(bytes.NewReader(body)) - } - } else { - fmt.Fprintf(b, "failed to read body: %v\n", err) - } - } - fl.mu.Lock() - defer fl.mu.Unlock() - fmt.Fprint(fl.logFile, b.String()) - fl.logFile.Sync() -} - -func (fl fileLogger) WriteResponse(resp *http.Response, filter Filter) { - if resp == nil || fl.logLevel < LogInfo { - return - } - b := &bytes.Buffer{} - fmt.Fprintf(b, "%s RESPONSE: %d %s\n", entryHeader(LogInfo), resp.StatusCode, filter.processURL(resp.Request.URL)) - // dump headers - for k, v := range resp.Header { - if ok, mv := filter.processHeader(k, v); ok { - fmt.Fprintf(b, "%s: %s\n", k, strings.Join(mv, ",")) - } - } - if fl.shouldLogBody(resp.Header, resp.Body) { - // dump body - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err == nil { - fmt.Fprintln(b, string(filter.processBody(body))) - resp.Body = ioutil.NopCloser(bytes.NewReader(body)) - } else { - fmt.Fprintf(b, "failed to read body: %v\n", err) - } - } - fl.mu.Lock() - defer fl.mu.Unlock() - fmt.Fprint(fl.logFile, b.String()) - fl.logFile.Sync() -} - -// returns true if the provided body should be included in the log -func (fl fileLogger) shouldLogBody(header http.Header, body io.ReadCloser) bool { - ct := header.Get("Content-Type") - return fl.logLevel >= LogDebug && body != nil && !strings.Contains(ct, "application/octet-stream") -} - -// creates standard header for log entries, it contains a timestamp and the log level -func entryHeader(level LevelType) string { - // this format provides a fixed number of digits so the size of the timestamp is constant - return fmt.Sprintf("(%s) %s:", time.Now().Format("2006-01-02T15:04:05.0000000Z07:00"), level.String()) -} diff --git a/vendor/github.com/Azure/go-autorest/tracing/LICENSE b/vendor/github.com/Azure/go-autorest/tracing/LICENSE deleted file mode 100644 index b9d6a27e..00000000 --- a/vendor/github.com/Azure/go-autorest/tracing/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2015 Microsoft Corporation - - 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/Azure/go-autorest/tracing/go_mod_tidy_hack.go b/vendor/github.com/Azure/go-autorest/tracing/go_mod_tidy_hack.go deleted file mode 100644 index e163975c..00000000 --- a/vendor/github.com/Azure/go-autorest/tracing/go_mod_tidy_hack.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build modhack - -package tracing - -// Copyright 2017 Microsoft Corporation -// -// 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. - -// This file, and the github.com/Azure/go-autorest import, won't actually become part of -// the resultant binary. - -// Necessary for safely adding multi-module repo. -// See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository -import _ "github.com/Azure/go-autorest" diff --git a/vendor/github.com/Azure/go-autorest/tracing/tracing.go b/vendor/github.com/Azure/go-autorest/tracing/tracing.go deleted file mode 100644 index 0e7a6e96..00000000 --- a/vendor/github.com/Azure/go-autorest/tracing/tracing.go +++ /dev/null @@ -1,67 +0,0 @@ -package tracing - -// Copyright 2018 Microsoft Corporation -// -// 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. - -import ( - "context" - "net/http" -) - -// Tracer represents an HTTP tracing facility. -type Tracer interface { - NewTransport(base *http.Transport) http.RoundTripper - StartSpan(ctx context.Context, name string) context.Context - EndSpan(ctx context.Context, httpStatusCode int, err error) -} - -var ( - tracer Tracer -) - -// Register will register the provided Tracer. Pass nil to unregister a Tracer. -func Register(t Tracer) { - tracer = t -} - -// IsEnabled returns true if a Tracer has been registered. -func IsEnabled() bool { - return tracer != nil -} - -// NewTransport creates a new instrumenting http.RoundTripper for the -// registered Tracer. If no Tracer has been registered it returns nil. -func NewTransport(base *http.Transport) http.RoundTripper { - if tracer != nil { - return tracer.NewTransport(base) - } - return nil -} - -// StartSpan starts a trace span with the specified name, associating it with the -// provided context. Has no effect if a Tracer has not been registered. -func StartSpan(ctx context.Context, name string) context.Context { - if tracer != nil { - return tracer.StartSpan(ctx, name) - } - return ctx -} - -// EndSpan ends a previously started span stored in the context. -// Has no effect if a Tracer has not been registered. -func EndSpan(ctx context.Context, httpStatusCode int, err error) { - if tracer != nil { - tracer.EndSpan(ctx, httpStatusCode, err) - } -} diff --git a/vendor/github.com/DopplerHQ/cli/LICENSE b/vendor/github.com/DopplerHQ/cli/LICENSE deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/DopplerHQ/cli/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/DopplerHQ/cli/pkg/configuration/config.go b/vendor/github.com/DopplerHQ/cli/pkg/configuration/config.go deleted file mode 100644 index 341355e8..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/configuration/config.go +++ /dev/null @@ -1,527 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 configuration - -import ( - "errors" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "sort" - "strconv" - "strings" - - "github.com/DopplerHQ/cli/pkg/controllers" - "github.com/DopplerHQ/cli/pkg/models" - "github.com/DopplerHQ/cli/pkg/utils" - "github.com/spf13/cobra" - "gopkg.in/yaml.v3" -) - -// baseConfigDir (e.g. /home/user/) -var baseConfigDir string - -// UserConfigDir (e.g. /home/user/.doppler) -var UserConfigDir string - -// UserConfigFile (e.g. /home/user/doppler/.doppler.yaml) -var UserConfigFile string - -// Scope to use for config file -var Scope = "." - -var configFileName = ".doppler.yaml" -var configContents models.ConfigFile - -func init() { - baseConfigDir = utils.HomeDir() - UserConfigDir = filepath.Join(baseConfigDir, ".doppler") - UserConfigFile = filepath.Join(UserConfigDir, configFileName) -} - -// Setup the config directory and config file -func Setup() { - utils.LogDebug(fmt.Sprintf("Using config file %s", UserConfigFile)) - - if !utils.Exists(UserConfigDir) { - utils.LogDebug(fmt.Sprintf("Creating the config directory %s", UserConfigDir)) - err := os.Mkdir(UserConfigDir, 0700) - if err != nil { - utils.HandleError(err, fmt.Sprintf("Unable to create config directory %s", UserConfigDir)) - } - } - - // This may be different from `UserConfigDir` if `--configuration` was provided - configDir := filepath.Dir(UserConfigFile) - if !utils.Exists(configDir) { - utils.HandleError(fmt.Errorf("Configuration file directory does not exist %s", configDir)) - } - - if !utils.Exists(UserConfigFile) { - v1ConfigA := filepath.Join(utils.ConfigDir(), configFileName) - v1ConfigB := filepath.Join(utils.HomeDir(), configFileName) - if utils.Exists(v1ConfigA) { - utils.LogDebug("Migrating the config from CLI v1") - err := os.Rename(v1ConfigA, UserConfigFile) - if err != nil { - utils.HandleError(err, "Unable to migrate config from CLI v1") - } - } else if utils.Exists(v1ConfigB) { - utils.LogDebug("Migrating the config from CLI v1") - err := os.Rename(v1ConfigB, UserConfigFile) - if err != nil { - utils.HandleError(err, "Unable to migrate config from CLI v1") - } - } else if jsonExists() { - utils.LogDebug("Migrating the config from the Node CLI") - migrateJSONToYaml() - } else { - utils.LogDebug("Creating a new config file") - var blankConfig models.ConfigFile - writeConfig(blankConfig) - } - } -} - -// LoadConfig load the configuration file -func LoadConfig() { - configContents = readConfig() -} - -// VersionCheck the last version check -func VersionCheck() models.VersionCheck { - return configContents.VersionCheck -} - -// SetVersionCheck the last version check -func SetVersionCheck(version models.VersionCheck) { - configContents.VersionCheck = version - writeConfig(configContents) -} - -// Get the config at the specified scope -func Get(scope string) models.ScopedOptions { - var normalizedScope string - var err error - if normalizedScope, err = NormalizeScope(scope); err != nil { - utils.HandleError(err, fmt.Sprintf("Invalid scope: %s", scope)) - } - if !strings.HasSuffix(normalizedScope, string(filepath.Separator)) { - normalizedScope = normalizedScope + string(filepath.Separator) - } - var scopedConfig models.ScopedOptions - - for confScope, conf := range configContents.Scoped { - confScopePath := confScope - // both paths must end in / to prevent partial match (e.g. /test matching /test123) - if !strings.HasSuffix(confScopePath, string(filepath.Separator)) { - confScopePath = confScopePath + string(filepath.Separator) - } - - if !strings.HasPrefix(normalizedScope, confScopePath) { - continue - } - - pairs := models.Pairs(conf) - scopedPairs := models.ScopedPairs(&scopedConfig) - for name, pair := range pairs { - if pair != "" { - scopedPair := scopedPairs[name] - if *scopedPair == (models.ScopedOption{}) || len(confScope) > len(scopedPair.Scope) { - scopedPair.Value = pair - scopedPair.Scope = confScope - scopedPair.Source = models.ConfigFileSource.String() - } - } - } - } - - if controllers.IsKeyringSecret(scopedConfig.Token.Value) { - utils.LogDebug(fmt.Sprintf("Retrieving %s from system keyring", models.ConfigToken.String())) - token, err := controllers.GetKeyring(scopedConfig.Token.Value) - if !err.IsNil() { - utils.HandleError(err.Unwrap(), err.Message) - } - - scopedConfig.Token.Value = token - } - - return scopedConfig -} - -// LocalConfig retrieves the config for the scoped directory -func LocalConfig(cmd *cobra.Command) models.ScopedOptions { - // config file (lowest priority) - localConfig := Get(Scope) - - // environment variables - if !utils.GetBoolFlag(cmd, "no-read-env") { - pairs := models.EnvPairs(&localConfig) - envVars := []string{} - for envVar := range pairs { - envVars = append(envVars, envVar) - } - - // sort variables so that they are processed in a deterministic order - // this also ensures ENCLAVE_ variables are given precedence over (i.e. read after) DOPPLER_ variables, - // which is necessary for backwards compatibility until we drop support for ENCLAVE_ variables - sort.Strings(envVars) - - for _, envVar := range envVars { - envValue := os.Getenv(envVar) - if envValue != "" { - pair := pairs[envVar] - pair.Value = envValue - pair.Scope = "/" - pair.Source = models.EnvironmentSource.String() - } - } - } - - // individual flags (highest priority) - flagSet := cmd.Flags().Changed("token") - if flagSet || localConfig.Token.Value == "" { - localConfig.Token.Value = cmd.Flag("token").Value.String() - localConfig.Token.Scope = "/" - - if flagSet { - localConfig.Token.Source = models.FlagSource.String() - } else { - localConfig.Token.Source = models.DefaultValueSource.String() - } - } - - flagSet = cmd.Flags().Changed("api-host") - if flagSet || localConfig.APIHost.Value == "" { - localConfig.APIHost.Value = cmd.Flag("api-host").Value.String() - localConfig.APIHost.Scope = "/" - - if flagSet { - localConfig.APIHost.Source = models.FlagSource.String() - } else { - localConfig.APIHost.Source = models.DefaultValueSource.String() - } - } - - flagSet = cmd.Flags().Changed("dashboard-host") - if flagSet || localConfig.DashboardHost.Value == "" { - localConfig.DashboardHost.Value = cmd.Flag("dashboard-host").Value.String() - localConfig.DashboardHost.Scope = "/" - - if flagSet { - localConfig.DashboardHost.Source = models.FlagSource.String() - } else { - localConfig.DashboardHost.Source = models.DefaultValueSource.String() - } - } - - flagSet = cmd.Flags().Changed("no-verify-tls") - if flagSet || localConfig.VerifyTLS.Value == "" { - noVerifyTLS := cmd.Flag("no-verify-tls").Value.String() - localConfig.VerifyTLS.Value = strconv.FormatBool(!utils.GetBool(noVerifyTLS, false)) - localConfig.VerifyTLS.Scope = "/" - - if flagSet { - localConfig.VerifyTLS.Source = models.FlagSource.String() - } else { - localConfig.VerifyTLS.Source = models.DefaultValueSource.String() - } - } - - // these flags below do not have a default value and should only be used if specified by the user (or will cause invalid memory access) - flagSet = cmd.Flags().Changed("project") - if flagSet { - localConfig.EnclaveProject.Value = cmd.Flag("project").Value.String() - localConfig.EnclaveProject.Scope = "/" - - if flagSet { - localConfig.EnclaveProject.Source = models.FlagSource.String() - } else { - localConfig.EnclaveProject.Source = models.DefaultValueSource.String() - } - } - - flagSet = cmd.Flags().Changed("config") - if flagSet { - localConfig.EnclaveConfig.Value = cmd.Flag("config").Value.String() - localConfig.EnclaveConfig.Scope = "/" - - if flagSet { - localConfig.EnclaveConfig.Source = models.FlagSource.String() - } else { - localConfig.EnclaveConfig.Source = models.DefaultValueSource.String() - } - } - - return localConfig -} - -// AllConfigs get all configs we know about -func AllConfigs() map[string]models.FileScopedOptions { - all := map[string]models.FileScopedOptions{} - for scope, scopedOptions := range configContents.Scoped { - options := scopedOptions - - if controllers.IsKeyringSecret(options.Token) { - utils.LogDebug(fmt.Sprintf("Retrieving %s from system keyring", models.ConfigToken.String())) - token, err := controllers.GetKeyring(options.Token) - if !err.IsNil() { - utils.HandleError(err.Unwrap(), err.Message) - } - - options.Token = token - } - - all[scope] = options - } - return all -} - -// Set properties on a scoped config -func Set(scope string, options map[string]string) { - var normalizedScope string - var err error - if normalizedScope, err = NormalizeScope(scope); err != nil { - utils.HandleError(err, fmt.Sprintf("Invalid scope: %s", scope)) - } - - config := configContents.Scoped[normalizedScope] - previousToken := config.Token - - for key, value := range options { - if !IsValidConfigOption(key) { - utils.HandleError(errors.New("invalid option "+key), "") - } - - if key == models.ConfigToken.String() { - utils.LogDebug(fmt.Sprintf("Saving %s to system keyring", key)) - uuid, err := utils.UUID() - if err != nil { - utils.HandleError(err, "Unable to generate UUID for keyring") - } - id := controllers.GenerateKeyringID(uuid) - - if controllerError := controllers.SetKeyring(id, value); !controllerError.IsNil() { - utils.LogDebugError(controllerError.Unwrap()) - utils.LogDebug(controllerError.Message) - } else { - value = id - - // remove old token from keyring - if controllers.IsKeyringSecret(previousToken) { - utils.LogDebug("Removing previous token from system keyring") - if controllerError := controllers.DeleteKeyring(previousToken); !controllerError.IsNil() { - utils.LogDebugError(controllerError.Unwrap()) - utils.LogDebug(controllerError.Message) - } - } - } - } - - SetConfigValue(&config, key, value) - configContents.Scoped[normalizedScope] = config - } - - writeConfig(configContents) -} - -// Unset a local config -func Unset(scope string, options []string) { - var normalizedScope string - var err error - if normalizedScope, err = NormalizeScope(scope); err != nil { - utils.HandleError(err, fmt.Sprintf("Invalid scope: %s", scope)) - } - - if configContents.Scoped[normalizedScope] == (models.FileScopedOptions{}) { - return - } - - for _, key := range options { - if !IsValidConfigOption(key) { - utils.HandleError(errors.New("invalid option "+key), "") - } - - config := configContents.Scoped[normalizedScope] - - if key == models.ConfigToken.String() { - previousToken := config.Token - // remove old token from keyring - if controllers.IsKeyringSecret(previousToken) { - if controllerError := controllers.DeleteKeyring(previousToken); !controllerError.IsNil() { - utils.LogDebugError(controllerError.Unwrap()) - utils.LogDebug(controllerError.Message) - } - } - } - - SetConfigValue(&config, key, "") - configContents.Scoped[normalizedScope] = config - } - - if configContents.Scoped[normalizedScope] == (models.FileScopedOptions{}) { - delete(configContents.Scoped, normalizedScope) - } - - writeConfig(configContents) -} - -// Write config to filesystem -func writeConfig(config models.ConfigFile) { - bytes, err := yaml.Marshal(config) - if err != nil { - utils.HandleError(err) - } - - utils.LogDebug(fmt.Sprintf("Writing user config to %s", UserConfigFile)) - if err := utils.WriteFile(UserConfigFile, bytes, os.FileMode(0600)); err != nil { - utils.HandleError(err) - } -} - -func readConfig() models.ConfigFile { - utils.LogDebug("Reading config file") - - fileContents, err := ioutil.ReadFile(UserConfigFile) // #nosec G304 - if err != nil { - utils.HandleError(err, "Unable to read user config file") - } - - var config models.ConfigFile - err = yaml.Unmarshal(fileContents, &config) - if err != nil { - utils.HandleError(err, "Unable to parse user config file") - } - - // sort scopes before normalizing so that if multiple scopes normalize to - // the same value (like '/' and '*') they'll apply in a deterministic order - var sorted []string - for scope := range config.Scoped { - sorted = append(sorted, scope) - } - sort.Strings(sorted) - - // normalize config scope and merge options from conflicting scopes - normalizedOptions := map[string]models.FileScopedOptions{} - for _, scope := range sorted { - var normalizedScope string - if normalizedScope, err = NormalizeScope(scope); err != nil { - utils.HandleError(err, fmt.Sprintf("Invalid scope: %s", scope)) - } - scopedOption := normalizedOptions[normalizedScope] - - options := config.Scoped[scope] - if options.APIHost != "" { - scopedOption.APIHost = options.APIHost - } - if options.DashboardHost != "" { - scopedOption.DashboardHost = options.DashboardHost - } - if options.EnclaveConfig != "" { - scopedOption.EnclaveConfig = options.EnclaveConfig - } - if options.EnclaveProject != "" { - scopedOption.EnclaveProject = options.EnclaveProject - } - if options.Token != "" { - scopedOption.Token = options.Token - } - if options.VerifyTLS != "" { - scopedOption.VerifyTLS = options.VerifyTLS - } - - normalizedOptions[normalizedScope] = scopedOption - } - - config.Scoped = normalizedOptions - return config -} - -// IsValidConfigOption whether the specified key is a valid config option -func IsValidConfigOption(key string) bool { - configOptions := map[string]interface{}{ - models.ConfigToken.String(): nil, - models.ConfigAPIHost.String(): nil, - models.ConfigDashboardHost.String(): nil, - models.ConfigVerifyTLS.String(): nil, - models.ConfigEnclaveProject.String(): nil, - models.ConfigEnclaveConfig.String(): nil, - } - - _, exists := configOptions[key] - return exists -} - -// IsTranslatableConfigOption checks whether the key can be translated to a valid config option -func IsTranslatableConfigOption(key string) bool { - // TODO remove this function when releasing CLI v4 (DPLR-435) - if key == "config" || key == "project" { - return true - } - - return false -} - -// TranslateFriendlyOption to its config option name -func TranslateFriendlyOption(key string) string { - // TODO remove this function when releasing CLI v4 (DPLR-435) - if key == "config" { - return models.ConfigEnclaveConfig.String() - } - if key == "project" { - return models.ConfigEnclaveProject.String() - } - return key -} - -// TranslateConfigOption to its friendly name -func TranslateConfigOption(key string) string { - // TODO remove this function when releasing CLI v4 (DPLR-435) - if key == models.ConfigEnclaveConfig.String() { - return "config" - } - if key == models.ConfigEnclaveProject.String() { - return "project" - } - return key -} - -// SetConfigValue set the value for the specified key in the config -func SetConfigValue(conf *models.FileScopedOptions, key string, value string) { - if key == models.ConfigToken.String() { - (*conf).Token = value - } else if key == models.ConfigAPIHost.String() { - (*conf).APIHost = value - } else if key == models.ConfigDashboardHost.String() { - (*conf).DashboardHost = value - } else if key == models.ConfigVerifyTLS.String() { - (*conf).VerifyTLS = value - } else if key == models.ConfigEnclaveProject.String() { - (*conf).EnclaveProject = value - } else if key == models.ConfigEnclaveConfig.String() { - (*conf).EnclaveConfig = value - } -} - -// NormalizeScope from legacy '*' to '/' -func NormalizeScope(scope string) (string, error) { - if scope == "*" { - return "/", nil - } - - return utils.ParsePath(scope) -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/configuration/migration.go b/vendor/github.com/DopplerHQ/cli/pkg/configuration/migration.go deleted file mode 100644 index 699b0835..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/configuration/migration.go +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 configuration - -import ( - "encoding/json" - "io/ioutil" - "path/filepath" - - "github.com/DopplerHQ/cli/pkg/models" - "github.com/DopplerHQ/cli/pkg/utils" -) - -type oldConfig struct { - Pipeline string - Environment string - Key string -} - -var jsonFile = filepath.Join(utils.HomeDir(), ".doppler.json") - -func jsonExists() bool { - return utils.Exists(jsonFile) -} - -// migrateJSONToYaml migrate ~/.doppler.json to yaml config -func migrateJSONToYaml() { - jsonConfig := parseJSONConfig() - newConfig := convertOldConfig(jsonConfig) - writeConfig(newConfig) -} - -func convertOldConfig(oldConfig map[string]oldConfig) models.ConfigFile { - config := map[string]models.FileScopedOptions{} - - for key, val := range oldConfig { - var err error - // skip items that fail to parse - if key, err = NormalizeScope(key); err == nil { - config[key] = models.FileScopedOptions{EnclaveProject: val.Pipeline, EnclaveConfig: val.Environment, Token: val.Key} - } - } - - return models.ConfigFile{Scoped: config} -} - -func parseJSONConfig() map[string]oldConfig { - fileContents, err := ioutil.ReadFile(jsonFile) // #nosec G304 - if err != nil { - utils.HandleError(err) - } - - var config map[string]oldConfig - err = json.Unmarshal(fileContents, &config) - if err != nil { - utils.HandleError(err) - } - - return config -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/controllers/fallback.go b/vendor/github.com/DopplerHQ/cli/pkg/controllers/fallback.go deleted file mode 100644 index cc03f24b..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/controllers/fallback.go +++ /dev/null @@ -1,128 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 controllers - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - - "github.com/DopplerHQ/cli/pkg/crypto" - "github.com/DopplerHQ/cli/pkg/models" - "github.com/DopplerHQ/cli/pkg/utils" - "gopkg.in/yaml.v3" -) - -// DefaultMetadataDir the directory containing metadata files -var DefaultMetadataDir string - -// MetadataFilePath calculates the name of the metadata file -func MetadataFilePath(token string, project string, config string) string { - var name string - if project == "" && config == "" { - name = fmt.Sprintf("%s", token) - } else { - name = fmt.Sprintf("%s:%s:%s", token, project, config) - } - - fileName := fmt.Sprintf(".metadata-%s.json", crypto.Hash(name)) - path := filepath.Join(DefaultMetadataDir, fileName) - if absPath, err := filepath.Abs(path); err == nil { - return absPath - } - return path -} - -// MetadataFile reads the contents of the metadata file -func MetadataFile(path string) (models.SecretsFileMetadata, Error) { - utils.LogDebug(fmt.Sprintf("Using metadata file %s", path)) - - if _, err := os.Stat(path); err != nil { - var e Error - e.Err = err - if os.IsNotExist(err) { - e.Message = "Metadata file does not exist" - } else { - e.Message = "Unable to read metadata file" - } - return models.SecretsFileMetadata{}, e - } - - utils.LogDebug(fmt.Sprintf("Reading metadata file %s", path)) - response, err := ioutil.ReadFile(path) // #nosec G304 - if err != nil { - return models.SecretsFileMetadata{}, Error{Err: err, Message: "Unable to read metadata file"} - } - - var metadata models.SecretsFileMetadata - if err := yaml.Unmarshal(response, &metadata); err != nil { - return models.SecretsFileMetadata{}, Error{Err: err, Message: "Unable to parse metadata file"} - } - - return metadata, Error{} -} - -// WriteMetadataFile writes the contents of the metadata file -func WriteMetadataFile(path string, etag string, hash string) Error { - utils.LogDebug(fmt.Sprintf("Writing ETag to metadata file %s", path)) - - metadata := models.SecretsFileMetadata{ - Version: "1", - ETag: etag, - Hash: hash, - } - - metadataBytes, err := yaml.Marshal(metadata) - if err != nil { - return Error{Err: err, Message: "Unable to marshal metadata to YAML"} - } - - if err := utils.WriteFile(path, []byte(metadataBytes), utils.RestrictedFilePerms()); err != nil { - return Error{Err: err, Message: "Unable to write metadata file"} - } - - return Error{} -} - -// SecretsCacheFile reads the contents of the cache file -func SecretsCacheFile(path string, passphrase string) (map[string]string, Error) { - utils.LogDebug(fmt.Sprintf("Using fallback file for cache %s", path)) - - if _, err := os.Stat(path); err != nil { - return nil, Error{Err: err, Message: "Unable to stat cache file"} - } - - response, err := ioutil.ReadFile(path) // #nosec G304 - if err != nil { - return nil, Error{Err: err, Message: "Unable to read cache file"} - } - - utils.LogDebug("Decrypting cache file") - decryptedSecrets, err := crypto.Decrypt(passphrase, response) - if err != nil { - return nil, Error{Err: err, Message: "Unable to decrypt cache file"} - } - - secrets := map[string]string{} - err = json.Unmarshal([]byte(decryptedSecrets), &secrets) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse cache file"} - } - - return secrets, Error{} -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/controllers/keyring.go b/vendor/github.com/DopplerHQ/cli/pkg/controllers/keyring.go deleted file mode 100644 index a547cd33..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/controllers/keyring.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 controllers - -import ( - "fmt" - "strings" - - "github.com/zalando/go-keyring" -) - -const keyringService = "doppler-cli" -const keyringSecretPrefix = "secret" - -// IsKeyringSecret checks whether the secret is stored in keyring -func IsKeyringSecret(value string) bool { - return strings.HasPrefix(value, fmt.Sprintf("%s-", keyringSecretPrefix)) -} - -// GenerateKeyringID generates a keyring-compliant key -func GenerateKeyringID(id string) string { - return fmt.Sprintf("%s-%s", keyringSecretPrefix, id) -} - -// GetKeyring fetches a secret from the keyring -func GetKeyring(id string) (string, Error) { - value, err := keyring.Get(keyringService, id) - if err != nil { - if err == keyring.ErrUnsupportedPlatform { - return "", Error{Err: err, Message: "Your OS does not support keyring"} - } else if err == keyring.ErrNotFound { - return "", Error{Err: err, Message: "Token not found in system keyring"} - } else { - return "", Error{Err: err, Message: "Unable to retrieve value from system keyring"} - } - } - - return value, Error{} -} - -// SetKeyring saves a value to the keyring -func SetKeyring(key string, value string) Error { - if err := keyring.Set(keyringService, key, value); err != nil { - if err == keyring.ErrUnsupportedPlatform { - return Error{Err: err, Message: "Your OS does not support keyring"} - } else { - return Error{Err: err, Message: "Unable to access system keyring for secure storage"} - } - } - - return Error{} -} - -// DeleteKeyring removes a value from the keyring -func DeleteKeyring(key string) Error { - if err := keyring.Delete(keyringService, key); err != nil { - return Error{Err: err, Message: "Unable to remove value from keyring"} - } - - return Error{} -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/controllers/repo_config.go b/vendor/github.com/DopplerHQ/cli/pkg/controllers/repo_config.go deleted file mode 100644 index 1aed5637..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/controllers/repo_config.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 controllers - -import ( - "fmt" - "io/ioutil" - "path/filepath" - - "github.com/DopplerHQ/cli/pkg/models" - "github.com/DopplerHQ/cli/pkg/utils" - "gopkg.in/yaml.v3" -) - -// repoConfigFileName (doppler.yaml) -const repoConfigFileName = "doppler.yaml" -// ymlRepoConfigFileName (doppler.yml) -const ymlRepoConfigFileName = "doppler.yml" - -// RepoConfig Reads the configuration file (doppler.yaml) if exists and returns the set configuration -func RepoConfig() (models.RepoConfig, Error) { - - repoConfigFile := filepath.Join("./", repoConfigFileName) - ymlRepoConfigFile := filepath.Join("./", ymlRepoConfigFileName) - - if utils.Exists(repoConfigFile) { - utils.LogDebug(fmt.Sprintf("Reading repo config file %s", repoConfigFile)) - - yamlFile, err := ioutil.ReadFile(repoConfigFile) // #nosec G304 - - if err != nil { - var e Error - e.Err = err - e.Message = "Unable to read doppler repo config file" - return models.RepoConfig{}, e - } - - var repoConfig models.RepoConfig - - if err := yaml.Unmarshal(yamlFile, &repoConfig); err != nil { - var e Error - e.Err = err - e.Message = "Unable to parse doppler repo config file" - return models.RepoConfig{}, e - } - - return repoConfig, Error{} - } else if utils.Exists(ymlRepoConfigFile) { - utils.LogWarning(fmt.Sprintf("Found %s file, please rename to %s for repo configuration", ymlRepoConfigFile, repoConfigFileName)) - } - return models.RepoConfig{}, Error{} -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/controllers/update.go b/vendor/github.com/DopplerHQ/cli/pkg/controllers/update.go deleted file mode 100644 index 616b1a63..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/controllers/update.go +++ /dev/null @@ -1,111 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 controllers - -import ( - "errors" - "fmt" - "os" - "os/exec" - "regexp" - "strings" - - "github.com/DopplerHQ/cli/pkg/http" - "github.com/DopplerHQ/cli/pkg/models" - "github.com/DopplerHQ/cli/pkg/utils" - "github.com/DopplerHQ/cli/pkg/version" -) - -// Error controller errors -type Error struct { - Err error - Message string -} - -// Unwrap get the original error -func (e *Error) Unwrap() error { return e.Err } - -// IsNil whether the error is nil -func (e *Error) IsNil() bool { return e.Err == nil && e.Message == "" } - -// RunInstallScript downloads and executes the CLI install scriptm, returning true if an update was installed -func RunInstallScript() (bool, string, Error) { - // download script - script, apiErr := http.GetCLIInstallScript() - if !apiErr.IsNil() { - return false, "", Error{Err: apiErr.Unwrap(), Message: apiErr.Message} - } - - // write script to temp file - tmpFile, err := utils.WriteTempFile("install.sh", script, 0555) - // clean up temp file once we're done with it - defer os.Remove(tmpFile) - - // execute script - utils.LogDebug("Executing install script") - command := []string{tmpFile, "--debug"} - out, err := exec.Command(command[0], command[1:]...).CombinedOutput() // #nosec G204 - strOut := string(out) - // log output before checking error - utils.LogDebug(fmt.Sprintf("Executing \"%s\"", strings.Join(command, " "))) - if utils.Debug { - fmt.Println(strOut) - } - if err != nil { - return false, "", Error{Err: err, Message: "Unable to install the latest Doppler CLI"} - } - - // find installed version within script output - // Ex: `Installed Doppler CLI v3.7.1` - re := regexp.MustCompile(`Installed Doppler CLI v(\d+\.\d+\.\d+)`) - matches := re.FindStringSubmatch(strOut) - if matches == nil || len(matches) != 2 { - return false, "", Error{Err: errors.New("Unable to determine new CLI version")} - } - // parse latest version string - newVersion, err := version.ParseVersion(matches[1]) - if err != nil { - return false, "", Error{Err: err, Message: "Unable to parse new CLI version"} - } - - wasUpdated := false - // parse current version string - currentVersion, currVersionErr := version.ParseVersion(version.ProgramVersion) - if currVersionErr != nil { - // unexpected error; just consider it an update and continue executing - wasUpdated = true - utils.LogDebug("Unable to parse current CLI version") - utils.LogDebugError(currVersionErr) - } - - if !wasUpdated { - wasUpdated = version.CompareVersions(currentVersion, newVersion) == 1 - } - - return wasUpdated, newVersion.String(), Error{} -} - -// CLIChangeLog fetches the latest changelog -func CLIChangeLog() (map[string]models.ChangeLog, http.Error) { - response, apiError := http.GetChangelog() - if !apiError.IsNil() { - return nil, apiError - - } - - changes := models.ParseChangeLog(response) - return changes, http.Error{} -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/controllers/version.go b/vendor/github.com/DopplerHQ/cli/pkg/controllers/version.go deleted file mode 100644 index 483ccbbf..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/controllers/version.go +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 controllers - -import ( - "time" - - "github.com/DopplerHQ/cli/pkg/http" - "github.com/DopplerHQ/cli/pkg/models" - "github.com/DopplerHQ/cli/pkg/utils" - "github.com/DopplerHQ/cli/pkg/version" -) - -// NewVersionAvailable checks whether a CLI version is available that's newer than this CLI -func NewVersionAvailable(prevVersionCheck models.VersionCheck) (bool, models.VersionCheck, error) { - now := time.Now() - check, err := http.GetLatestCLIVersion() - if err != nil { - utils.LogDebug("Unable to fetch latest CLI version") - utils.LogDebugError(err) - return false, models.VersionCheck{}, err - } - - versionCheck := models.VersionCheck{CheckedAt: now, LatestVersion: version.Normalize(check.LatestVersion)} - - // skip if available version is unchanged from previous check - if versionCheck.LatestVersion == prevVersionCheck.LatestVersion { - utils.LogDebug("Previous version check is still latest version") - return false, versionCheck, nil - } - - newVersion, err := version.ParseVersion(versionCheck.LatestVersion) - if err != nil { - utils.LogDebug("Unable to parse new CLI version") - return false, models.VersionCheck{}, err - } - - currentVersion, err := version.ParseVersion(version.ProgramVersion) - if err != nil { - // if current version can't be parsed, consider an update available - utils.LogDebug("Unable to parse current CLI version") - utils.LogDebugError(err) - return true, versionCheck, nil - } - - compare := version.CompareVersions(currentVersion, newVersion) - if compare == 1 { - return true, versionCheck, nil - } - - return false, versionCheck, nil -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/crypto/aes.go b/vendor/github.com/DopplerHQ/cli/pkg/crypto/aes.go deleted file mode 100644 index eae46303..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/crypto/aes.go +++ /dev/null @@ -1,120 +0,0 @@ -/* -Copyright © 2020 Doppler - -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. -*/ - -// From https://gist.github.com/tscholl2/dc7dc15dc132ea70a98e8542fefffa28 - -package crypto - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "crypto/sha256" - "encoding/hex" - "fmt" - "strings" - "time" - - "github.com/DopplerHQ/cli/pkg/utils" - "golang.org/x/crypto/pbkdf2" -) - -func deriveKey(passphrase string, salt []byte) ([]byte, []byte, error) { - if salt == nil { - salt = make([]byte, 8) - // http://www.ietf.org/rfc/rfc2898.txt - // Salt. - _, err := rand.Read(salt) - if err != nil { - return nil, nil, err - } - } - - return pbkdf2.Key([]byte(passphrase), salt, 50000, 32, sha256.New), salt, nil -} - -// Encrypt plaintext with a passphrase; uses pbkdf2 for key deriv and aes-256-gcm for encryption -func Encrypt(passphrase string, plaintext []byte) (string, error) { - now := time.Now() - key, salt, err := deriveKey(passphrase, nil) - if err != nil { - return "", err - } - - utils.LogDebug(fmt.Sprintf("PBKDF2 key derivation took %d ms", time.Now().Sub(now).Milliseconds())) - - iv := make([]byte, 12) - // http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf - // Section 8.2 - _, err = rand.Read(iv) - if err != nil { - return "", err - } - - b, err := aes.NewCipher(key) - if err != nil { - return "", err - } - - aesgcm, err := cipher.NewGCM(b) - if err != nil { - return "", err - } - - data := aesgcm.Seal(nil, iv, plaintext, nil) - return hex.EncodeToString(salt) + "-" + hex.EncodeToString(iv) + "-" + hex.EncodeToString(data), nil -} - -// Decrypt ciphertext with a passphrase -func Decrypt(passphrase string, ciphertext []byte) (string, error) { - arr := strings.Split(string(ciphertext), "-") - salt, err := hex.DecodeString(arr[0]) - if err != nil { - return "", err - } - - iv, err := hex.DecodeString(arr[1]) - if err != nil { - return "", err - } - - data, err := hex.DecodeString(arr[2]) - if err != nil { - return "", err - } - - key, _, err := deriveKey(passphrase, salt) - if err != nil { - return "", err - } - - b, err := aes.NewCipher(key) - if err != nil { - return "", err - } - - aesgcm, err := cipher.NewGCM(b) - if err != nil { - return "", err - } - - data, err = aesgcm.Open(nil, iv, data, nil) - if err != nil { - return "", err - } - - return string(data), nil -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/crypto/util.go b/vendor/github.com/DopplerHQ/cli/pkg/crypto/util.go deleted file mode 100644 index 7efdd50a..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/crypto/util.go +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 crypto - -import ( - "crypto/sha256" - "fmt" - "github.com/DopplerHQ/cli/pkg/utils" -) - -// Hash a string -func Hash(s string) string { - hash := sha256.New() - _, err := hash.Write([]byte(s)) - if err != nil { - utils.HandleError(err, "Unable to generate hash") - } - return fmt.Sprintf("%x", hash.Sum(nil)) -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/http/api.go b/vendor/github.com/DopplerHQ/cli/pkg/http/api.go deleted file mode 100644 index 86343706..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/http/api.go +++ /dev/null @@ -1,796 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 http - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "net/http" - - "github.com/DopplerHQ/cli/pkg/models" - "github.com/DopplerHQ/cli/pkg/version" -) - -// Error API errors -type Error struct { - Err error - Message string - Code int -} - -// Unwrap get the original error -func (e *Error) Unwrap() error { return e.Err } - -// IsNil whether the error is nil -func (e *Error) IsNil() bool { return e.Err == nil && e.Message == "" } - -func apiKeyHeader(apiKey string) map[string]string { - encoded := base64.StdEncoding.EncodeToString([]byte(apiKey + ":")) - return map[string]string{"Authorization": fmt.Sprintf("Basic %s", encoded)} -} - -// GenerateAuthCode generate an auth code -func GenerateAuthCode(host string, verifyTLS bool, hostname string, os string, arch string) (map[string]interface{}, Error) { - var params []queryParam - params = append(params, queryParam{Key: "hostname", Value: hostname}) - params = append(params, queryParam{Key: "version", Value: version.ProgramVersion}) - params = append(params, queryParam{Key: "os", Value: os}) - params = append(params, queryParam{Key: "arch", Value: arch}) - - statusCode, _, response, err := GetRequest(host, verifyTLS, nil, "/v3/auth/cli/generate", params) - if err != nil { - return nil, Error{Err: err, Message: "Unable to fetch auth code", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - return result, Error{} -} - -// GetAuthToken get an auth token -func GetAuthToken(host string, verifyTLS bool, code string) (map[string]interface{}, Error) { - reqBody := map[string]interface{}{} - reqBody["code"] = code - body, err := json.Marshal(reqBody) - if err != nil { - return nil, Error{Err: err, Message: "Invalid auth code"} - } - - statusCode, _, response, err := PostRequest(host, verifyTLS, nil, "/v3/auth/cli/authorize", []queryParam{}, body) - if err != nil { - return nil, Error{Err: err, Message: "Unable to fetch auth token", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to fetch auth token", Code: statusCode} - } - - return result, Error{} -} - -// RollAuthToken roll an auth token -func RollAuthToken(host string, verifyTLS bool, token string) (map[string]interface{}, Error) { - reqBody := map[string]interface{}{} - reqBody["token"] = token - body, err := json.Marshal(reqBody) - if err != nil { - return nil, Error{Err: err, Message: "Invalid auth token"} - } - - statusCode, _, response, err := PostRequest(host, verifyTLS, nil, "/v3/auth/cli/roll", []queryParam{}, body) - if err != nil { - return nil, Error{Err: err, Message: "Unable to roll auth token", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - return result, Error{} -} - -// RevokeAuthToken revoke an auth token -func RevokeAuthToken(host string, verifyTLS bool, token string) (map[string]interface{}, Error) { - reqBody := map[string]interface{}{} - reqBody["token"] = token - body, err := json.Marshal(reqBody) - if err != nil { - return nil, Error{Err: err, Message: "Invalid auth token"} - } - - statusCode, _, response, err := PostRequest(host, verifyTLS, nil, "/v3/auth/cli/revoke", []queryParam{}, body) - if err != nil { - return nil, Error{Err: err, Message: "Unable to revoke auth token", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - return result, Error{} -} - -// DownloadSecrets for specified project and config -func DownloadSecrets(host string, verifyTLS bool, apiKey string, project string, config string, format models.SecretsFormat, etag string) (int, http.Header, []byte, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - params = append(params, queryParam{Key: "format", Value: format.String()}) - - headers := apiKeyHeader(apiKey) - if etag != "" { - headers["If-None-Match"] = etag - } - - statusCode, respHeaders, response, err := GetRequest(host, verifyTLS, headers, "/v3/configs/config/secrets/download", params) - if err != nil { - return statusCode, respHeaders, nil, Error{Err: err, Message: "Unable to download secrets", Code: statusCode} - } - - return statusCode, respHeaders, response, Error{} -} - -// GetSecrets for specified project and config -func GetSecrets(host string, verifyTLS bool, apiKey string, project string, config string) ([]byte, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - headers := apiKeyHeader(apiKey) - headers["Accept"] = "application/json" - statusCode, _, response, err := GetRequest(host, verifyTLS, headers, "/v3/configs/config/secrets", params) - if err != nil { - return nil, Error{Err: err, Message: "Unable to fetch secrets", Code: statusCode} - } - - return response, Error{} -} - -// SetSecrets for specified project and config -func SetSecrets(host string, verifyTLS bool, apiKey string, project string, config string, secrets map[string]interface{}) (map[string]models.ComputedSecret, Error) { - reqBody := map[string]interface{}{} - reqBody["secrets"] = secrets - body, err := json.Marshal(reqBody) - if err != nil { - return nil, Error{Err: err, Message: "Invalid secrets"} - } - - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config/secrets", params, body) - if err != nil { - return nil, Error{Err: err, Message: "Unable to set secrets", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - computed := map[string]models.ComputedSecret{} - for key, secret := range result["secrets"].(map[string]interface{}) { - val := secret.(map[string]interface{}) - computed[key] = models.ComputedSecret{Name: key, RawValue: val["raw"].(string), ComputedValue: val["computed"].(string)} - } - - return computed, Error{} -} - -// UploadSecrets for specified project and config -func UploadSecrets(host string, verifyTLS bool, apiKey string, project string, config string, secrets string) (map[string]models.ComputedSecret, Error) { - reqBody := map[string]interface{}{} - reqBody["file"] = secrets - body, err := json.Marshal(reqBody) - if err != nil { - return nil, Error{Err: err, Message: "Invalid file"} - } - - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config/secrets/upload", params, body) - if err != nil { - return nil, Error{Err: err, Message: "Unable to upload secrets", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - computed := map[string]models.ComputedSecret{} - for key, secret := range result["secrets"].(map[string]interface{}) { - val := secret.(map[string]interface{}) - computed[key] = models.ComputedSecret{Name: key, RawValue: val["raw"].(string), ComputedValue: val["computed"].(string)} - } - - return computed, Error{} -} - -// GetWorkplaceSettings get specified workplace settings -func GetWorkplaceSettings(host string, verifyTLS bool, apiKey string) (models.WorkplaceSettings, Error) { - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/workplace/v1", []queryParam{}) - if err != nil { - return models.WorkplaceSettings{}, Error{Err: err, Message: "Unable to fetch workplace settings", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.WorkplaceSettings{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - settings := models.ParseWorkplaceSettings(result["workplace"].(map[string]interface{})) - return settings, Error{} -} - -// SetWorkplaceSettings set workplace settings -func SetWorkplaceSettings(host string, verifyTLS bool, apiKey string, values models.WorkplaceSettings) (models.WorkplaceSettings, Error) { - body, err := json.Marshal(values) - if err != nil { - return models.WorkplaceSettings{}, Error{Err: err, Message: "Invalid workplace settings"} - } - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/workplace/v1", []queryParam{}, body) - if err != nil { - return models.WorkplaceSettings{}, Error{Err: err, Message: "Unable to update workplace settings", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.WorkplaceSettings{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - settings := models.ParseWorkplaceSettings(result["workplace"].(map[string]interface{})) - return settings, Error{} -} - -// GetProjects get projects -func GetProjects(host string, verifyTLS bool, apiKey string) ([]models.ProjectInfo, Error) { - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/projects", []queryParam{}) - if err != nil { - return nil, Error{Err: err, Message: "Unable to fetch projects", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - var info []models.ProjectInfo - for _, project := range result["projects"].([]interface{}) { - projectInfo := models.ParseProjectInfo(project.(map[string]interface{})) - info = append(info, projectInfo) - } - return info, Error{} -} - -// GetProject get specified project -func GetProject(host string, verifyTLS bool, apiKey string, project string) (models.ProjectInfo, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/projects/project", params) - if err != nil { - return models.ProjectInfo{}, Error{Err: err, Message: "Unable to fetch project", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ProjectInfo{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - projectInfo := models.ParseProjectInfo(result["project"].(map[string]interface{})) - return projectInfo, Error{} -} - -// CreateProject create a project -func CreateProject(host string, verifyTLS bool, apiKey string, name string, description string) (models.ProjectInfo, Error) { - postBody := map[string]string{"name": name, "description": description} - body, err := json.Marshal(postBody) - if err != nil { - return models.ProjectInfo{}, Error{Err: err, Message: "Invalid project info"} - } - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/projects", []queryParam{}, body) - if err != nil { - return models.ProjectInfo{}, Error{Err: err, Message: "Unable to create project", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ProjectInfo{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - projectInfo := models.ParseProjectInfo(result["project"].(map[string]interface{})) - return projectInfo, Error{} -} - -// UpdateProject update a project's name and (optional) description -func UpdateProject(host string, verifyTLS bool, apiKey string, project string, name string, description ...string) (models.ProjectInfo, Error) { - postBody := map[string]string{"name": name} - if len(description) > 0 { - desc := description[0] - postBody["description"] = desc - } - - body, err := json.Marshal(postBody) - if err != nil { - return models.ProjectInfo{}, Error{Err: err, Message: "Invalid project info"} - } - - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/projects/project", params, body) - if err != nil { - return models.ProjectInfo{}, Error{Err: err, Message: "Unable to update project", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ProjectInfo{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - projectInfo := models.ParseProjectInfo(result["project"].(map[string]interface{})) - return projectInfo, Error{} -} - -// DeleteProject create a project -func DeleteProject(host string, verifyTLS bool, apiKey string, project string) Error { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - - statusCode, _, response, err := DeleteRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/projects/project", params) - if err != nil { - return Error{Err: err, Message: "Unable to delete project", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - return Error{} -} - -// GetEnvironments get environments -func GetEnvironments(host string, verifyTLS bool, apiKey string, project string) ([]models.EnvironmentInfo, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/environments", params) - if err != nil { - return nil, Error{Err: err, Message: "Unable to fetch environments", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - var info []models.EnvironmentInfo - for _, environment := range result["environments"].([]interface{}) { - environmentInfo := models.ParseEnvironmentInfo(environment.(map[string]interface{})) - info = append(info, environmentInfo) - } - return info, Error{} -} - -// GetEnvironment get specified environment -func GetEnvironment(host string, verifyTLS bool, apiKey string, project string, environment string) (models.EnvironmentInfo, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "environment", Value: environment}) - - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/environments/environment", params) - if err != nil { - return models.EnvironmentInfo{}, Error{Err: err, Message: "Unable to fetch environment", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.EnvironmentInfo{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - info := models.ParseEnvironmentInfo(result["environment"].(map[string]interface{})) - return info, Error{} -} - -// GetConfigs get configs -func GetConfigs(host string, verifyTLS bool, apiKey string, project string) ([]models.ConfigInfo, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs", params) - if err != nil { - return nil, Error{Err: err, Message: "Unable to fetch configs", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - var info []models.ConfigInfo - for _, config := range result["configs"].([]interface{}) { - configInfo := models.ParseConfigInfo(config.(map[string]interface{})) - info = append(info, configInfo) - } - return info, Error{} -} - -// GetConfig get a config -func GetConfig(host string, verifyTLS bool, apiKey string, project string, config string) (models.ConfigInfo, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config", params) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to fetch configs", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - info := models.ParseConfigInfo(result["config"].(map[string]interface{})) - return info, Error{} -} - -// CreateConfig create a config -func CreateConfig(host string, verifyTLS bool, apiKey string, project string, name string, environment string) (models.ConfigInfo, Error) { - postBody := map[string]interface{}{"name": name, "environment": environment} - body, err := json.Marshal(postBody) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Invalid config info"} - } - - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs", params, body) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to create config", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - info := models.ParseConfigInfo(result["config"].(map[string]interface{})) - return info, Error{} -} - -// DeleteConfig delete a config -func DeleteConfig(host string, verifyTLS bool, apiKey string, project string, config string) Error { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - statusCode, _, response, err := DeleteRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config", params) - if err != nil { - return Error{Err: err, Message: "Unable to delete config", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - return Error{} -} - -// LockConfig lock a config -func LockConfig(host string, verifyTLS bool, apiKey string, project string, config string) (models.ConfigInfo, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config/lock", params, nil) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to lock config", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - info := models.ParseConfigInfo(result["config"].(map[string]interface{})) - return info, Error{} -} - -// UnlockConfig unlock a config -func UnlockConfig(host string, verifyTLS bool, apiKey string, project string, config string) (models.ConfigInfo, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config/unlock", params, nil) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to unlock config", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - info := models.ParseConfigInfo(result["config"].(map[string]interface{})) - return info, Error{} -} - -// CloneConfig clone a config -func CloneConfig(host string, verifyTLS bool, apiKey string, project string, config string) (models.ConfigInfo, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config/clone", params, nil) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to clone config", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - info := models.ParseConfigInfo(result["config"].(map[string]interface{})) - return info, Error{} -} - -// UpdateConfig update a config -func UpdateConfig(host string, verifyTLS bool, apiKey string, project string, config string, name string) (models.ConfigInfo, Error) { - postBody := map[string]interface{}{"name": name} - body, err := json.Marshal(postBody) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Invalid config info"} - } - - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config", params, body) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to update config", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ConfigInfo{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - info := models.ParseConfigInfo(result["config"].(map[string]interface{})) - return info, Error{} -} - -// GetActivityLogs get activity logs -func GetActivityLogs(host string, verifyTLS bool, apiKey string) ([]models.ActivityLog, Error) { - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/logs/v1", []queryParam{}) - if err != nil { - return nil, Error{Err: err, Message: "Unable to fetch activity logs", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - var logs []models.ActivityLog - for _, log := range result["logs"].([]interface{}) { - parsedLog := models.ParseActivityLog(log.(map[string]interface{})) - logs = append(logs, parsedLog) - } - return logs, Error{} -} - -// GetActivityLog get specified activity log -func GetActivityLog(host string, verifyTLS bool, apiKey string, log string) (models.ActivityLog, Error) { - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/logs/v1/"+log, []queryParam{}) - if err != nil { - return models.ActivityLog{}, Error{Err: err, Message: "Unable to fetch activity log", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ActivityLog{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - parsedLog := models.ParseActivityLog(result["log"].(map[string]interface{})) - return parsedLog, Error{} -} - -// GetConfigLogs get config audit logs -func GetConfigLogs(host string, verifyTLS bool, apiKey string, project string, config string) ([]models.ConfigLog, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config/logs", params) - if err != nil { - return nil, Error{Err: err, Message: "Unable to fetch config logs", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - var logs []models.ConfigLog - for _, log := range result["logs"].([]interface{}) { - parsedLog := models.ParseConfigLog(log.(map[string]interface{})) - logs = append(logs, parsedLog) - } - return logs, Error{} -} - -// GetConfigLog get config audit log -func GetConfigLog(host string, verifyTLS bool, apiKey string, project string, config string, log string) (models.ConfigLog, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - params = append(params, queryParam{Key: "log", Value: log}) - - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config/logs/log", params) - if err != nil { - return models.ConfigLog{}, Error{Err: err, Message: "Unable to fetch config log", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ConfigLog{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - parsedLog := models.ParseConfigLog(result["log"].(map[string]interface{})) - return parsedLog, Error{} -} - -// RollbackConfigLog rollback a config log -func RollbackConfigLog(host string, verifyTLS bool, apiKey string, project string, config string, log string) (models.ConfigLog, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - params = append(params, queryParam{Key: "log", Value: log}) - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config/logs/log/rollback", params, nil) - if err != nil { - return models.ConfigLog{}, Error{Err: err, Message: "Unable to rollback config log", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ConfigLog{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - parsedLog := models.ParseConfigLog(result["log"].(map[string]interface{})) - return parsedLog, Error{} -} - -// GetConfigServiceTokens get config service tokens -func GetConfigServiceTokens(host string, verifyTLS bool, apiKey string, project string, config string) ([]models.ConfigServiceToken, Error) { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - statusCode, _, response, err := GetRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config/tokens", params) - if err != nil { - return nil, Error{Err: err, Message: "Unable to fetch service tokens", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return nil, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - var tokens []models.ConfigServiceToken - for _, log := range result["tokens"].([]interface{}) { - parsedToken := models.ParseConfigServiceToken(log.(map[string]interface{})) - tokens = append(tokens, parsedToken) - } - return tokens, Error{} -} - -// CreateConfigServiceToken create a config service token -func CreateConfigServiceToken(host string, verifyTLS bool, apiKey string, project string, config string, name string) (models.ConfigServiceToken, Error) { - postBody := map[string]interface{}{"name": name} - body, err := json.Marshal(postBody) - if err != nil { - return models.ConfigServiceToken{}, Error{Err: err, Message: "Invalid service token info"} - } - - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - - statusCode, _, response, err := PostRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config/tokens", params, body) - if err != nil { - return models.ConfigServiceToken{}, Error{Err: err, Message: "Unable to create service token", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return models.ConfigServiceToken{}, Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - info := models.ParseConfigServiceToken(result["token"].(map[string]interface{})) - return info, Error{} -} - -// DeleteConfigServiceToken delete a config service token -func DeleteConfigServiceToken(host string, verifyTLS bool, apiKey string, project string, config string, slug string) Error { - var params []queryParam - params = append(params, queryParam{Key: "project", Value: project}) - params = append(params, queryParam{Key: "config", Value: config}) - params = append(params, queryParam{Key: "slug", Value: slug}) - - statusCode, _, response, err := DeleteRequest(host, verifyTLS, apiKeyHeader(apiKey), "/v3/configs/config/tokens/token", params) - if err != nil { - return Error{Err: err, Message: "Unable to delete service token", Code: statusCode} - } - - var result map[string]interface{} - err = json.Unmarshal(response, &result) - if err != nil { - return Error{Err: err, Message: "Unable to parse API response", Code: statusCode} - } - - return Error{} -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/http/config.go b/vendor/github.com/DopplerHQ/cli/pkg/http/config.go deleted file mode 100644 index b70f97cb..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/http/config.go +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 http - -import "time" - -// UseTimeout whether to timeout long-running requests -var UseTimeout = true - -// TimeoutDuration how long to wait for a request to complete before timing out -var TimeoutDuration = 10 * time.Second diff --git a/vendor/github.com/DopplerHQ/cli/pkg/http/github.go b/vendor/github.com/DopplerHQ/cli/pkg/http/github.go deleted file mode 100644 index b7fe0a84..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/http/github.go +++ /dev/null @@ -1,81 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 http - -import ( - "encoding/json" - "errors" - "time" - - "github.com/DopplerHQ/cli/pkg/models" - "github.com/DopplerHQ/cli/pkg/utils" - "github.com/DopplerHQ/cli/pkg/version" -) - -func getLatestVersion() (string, error) { - origTimeout := TimeoutDuration - TimeoutDuration = 2 * time.Second - _, _, resp, err := GetRequest("https://api.github.com", true, nil, "/repos/DopplerHQ/cli/releases/latest", nil) - TimeoutDuration = origTimeout - if err != nil { - return "", err - } - - var body map[string]interface{} - err = json.Unmarshal(resp, &body) - if err != nil { - return "", err - } - - if version, exists := body["tag_name"]; exists { - return version.(string), nil - } - - return "", errors.New("unable to retrieve tag_name of latest release") -} - -// GetLatestCLIVersion fetches the latest CLI version -func GetLatestCLIVersion() (models.VersionCheck, error) { - utils.LogDebug("Checking for latest version of the CLI") - tag, err := getLatestVersion() - if err != nil { - utils.LogDebug("Unable to check for CLI updates") - utils.LogDebugError(err) - return models.VersionCheck{}, err - } - - versionCheck := models.VersionCheck{CheckedAt: time.Now(), LatestVersion: version.Normalize(tag)} - return versionCheck, nil -} - -// GetCLIInstallScript from cli.doppler.com -func GetCLIInstallScript() ([]byte, Error) { - _, _, resp, err := GetRequest("https://cli.doppler.com", true, nil, "/install.sh", nil) - if err != nil { - return nil, Error{Err: err, Message: "Unable to download CLI install script"} - } - return resp, Error{} -} - -// GetChangelog of CLI releases -func GetChangelog() ([]byte, Error) { - headers := map[string]string{"Accept": "application/json"} - _, _, resp, err := GetRequest("https://cli.doppler.com", true, headers, "/changes", nil) - if err != nil { - return nil, Error{Err: err, Message: "Unable to fetch changelog"} - } - return resp, Error{} -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/http/http.go b/vendor/github.com/DopplerHQ/cli/pkg/http/http.go deleted file mode 100644 index ba2c12d0..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/http/http.go +++ /dev/null @@ -1,243 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 http - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "strings" - "time" - - "github.com/DopplerHQ/cli/pkg/utils" - "github.com/DopplerHQ/cli/pkg/version" -) - -type queryParam struct { - Key string - Value string -} - -type errorResponse struct { - Messages []string - Success bool -} - -// GetRequest perform HTTP GET -func GetRequest(host string, verifyTLS bool, headers map[string]string, uri string, params []queryParam) (int, http.Header, []byte, error) { - url := fmt.Sprintf("%s%s", host, uri) - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return 0, nil, nil, err - } - - for key, value := range headers { - req.Header.Set(key, value) - } - - statusCode, respHeaders, body, err := performRequest(req, verifyTLS, params) - if err != nil { - return statusCode, respHeaders, body, err - } - - return statusCode, respHeaders, body, nil -} - -// PostRequest perform HTTP POST -func PostRequest(host string, verifyTLS bool, headers map[string]string, uri string, params []queryParam, body []byte) (int, http.Header, []byte, error) { - url := fmt.Sprintf("%s%s", host, uri) - req, err := http.NewRequest("POST", url, bytes.NewReader(body)) - if err != nil { - return 0, nil, nil, err - } - - for key, value := range headers { - req.Header.Set(key, value) - } - - statusCode, respHeaders, body, err := performRequest(req, verifyTLS, params) - if err != nil { - return statusCode, respHeaders, body, err - } - - return statusCode, respHeaders, body, nil -} - -// DeleteRequest perform HTTP DELETE -func DeleteRequest(host string, verifyTLS bool, headers map[string]string, uri string, params []queryParam) (int, http.Header, []byte, error) { - url := fmt.Sprintf("%s%s", host, uri) - req, err := http.NewRequest("DELETE", url, nil) - if err != nil { - return 0, nil, nil, err - } - - for key, value := range headers { - req.Header.Set(key, value) - } - - statusCode, respHeaders, body, err := performRequest(req, verifyTLS, params) - if err != nil { - return statusCode, respHeaders, body, err - } - - return statusCode, respHeaders, body, nil -} - -func performRequest(req *http.Request, verifyTLS bool, params []queryParam) (int, http.Header, []byte, error) { - // set headers - req.Header.Set("client-sdk", "go-cli") - req.Header.Set("client-version", version.ProgramVersion) - req.Header.Set("user-agent", "doppler-go-cli-"+version.ProgramVersion) - if req.Header.Get("Accept") == "" { - req.Header.Set("Accept", "application/json") - } - req.Header.Set("Content-Type", "application/json") - - // set url query parameters - query := req.URL.Query() - for _, param := range params { - query.Add(param.Key, param.Value) - } - req.URL.RawQuery = query.Encode() - - // close the connection after reading the response, to help prevent socket exhaustion - req.Close = true - - client := &http.Client{} - // set http timeout - if UseTimeout { - client.Timeout = TimeoutDuration - } - - transport := &http.Transport{ - // disable keep alives to prevent multiple CLI instances from exhausting the - // OS's available network sockets. this adds a negligible performance penalty - DisableKeepAlives: true, - } - // set TLS config - // #nosec G402 - if !verifyTLS { - transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} - } - client.Transport = transport - - startTime := time.Now() - var response *http.Response - response = nil - - requestErr := retry(5, 100*time.Millisecond, func() error { - resp, err := client.Do(req) - if err != nil { - if resp != nil { - defer resp.Body.Close() - } - - utils.LogDebug(err.Error()) - - if isTimeout(err) { - // retry request - return err - } - - return StopRetry{err} - } - - response = resp - - utils.LogDebug(fmt.Sprintf("Performing HTTP %s to %s", req.Method, req.URL)) - if requestID := resp.Header.Get("x-request-id"); requestID != "" { - utils.LogDebug(fmt.Sprintf("Request ID %s", requestID)) - } - - if isSuccess(resp.StatusCode) { - return nil - } - - contentType := resp.Header.Get("content-type") - if isRetry(resp.StatusCode, contentType) { - // start logging retries after 10 seconds so it doesn't feel like we've frozen - // we subtract 1 millisecond so that we always win the race against a request that exhausts its full 10 second time out - if time.Now().After(startTime.Add(10 * time.Second).Add(-1 * time.Millisecond)) { - utils.Log(fmt.Sprintf("Request failed with HTTP %d, retrying", resp.StatusCode)) - } - return errors.New("Request failed") - } - - // we cannot recover from this error code; accept defeat - return StopRetry{errors.New("Request failed")} - }) - - if response != nil { - defer response.Body.Close() - } - - if requestErr != nil && response == nil { - return 0, nil, nil, requestErr - } - - body, err := ioutil.ReadAll(response.Body) - if err != nil { - return response.StatusCode, nil, nil, err - } - - headers := response.Header.Clone() - - // success - if requestErr == nil { - return response.StatusCode, headers, body, nil - } - - // print the response body error messages - if contentType := response.Header.Get("content-type"); strings.HasPrefix(contentType, "application/json") { - var errResponse errorResponse - err = json.Unmarshal(body, &errResponse) - if err != nil { - utils.LogDebug(fmt.Sprintf("Unable to parse response body: \n%s", string(body))) - return response.StatusCode, headers, nil, err - } - - return response.StatusCode, headers, body, errors.New(strings.Join(errResponse.Messages, "\n")) - } - - return response.StatusCode, headers, nil, fmt.Errorf("Request failed with HTTP %d", response.StatusCode) -} - -func isSuccess(statusCode int) bool { - return (statusCode >= 200 && statusCode <= 299) || (statusCode >= 300 && statusCode <= 399) -} - -func isRetry(statusCode int, contentType string) bool { - return (statusCode == 429) || - (statusCode >= 100 && statusCode <= 199) || - // don't retry 5xx errors w/ a JSON body - (statusCode >= 500 && statusCode <= 599 && !strings.HasPrefix(contentType, "application/json")) -} - -func isTimeout(err error) bool { - if urlErr, ok := err.(*url.Error); ok { - if netErr, ok := urlErr.Err.(net.Error); ok { - return netErr.Timeout() - } - } - - return false -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/http/retry.go b/vendor/github.com/DopplerHQ/cli/pkg/http/retry.go deleted file mode 100644 index b664b634..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/http/retry.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 http - -import ( - "math/rand" - "time" -) - -func init() { - rand.Seed(time.Now().UnixNano()) -} - -func retry(attempts int, sleep time.Duration, f func() error) error { - if err := f(); err != nil { - if s, ok := err.(StopRetry); ok { - // Return the original error for later checking - return s.error - } - - if attempts--; attempts > 0 { - // Add some randomness to prevent creating a Thundering Herd - jitter := time.Duration(rand.Int63n(int64(sleep))) // #nosec G404 - sleep = sleep + jitter/2 - - time.Sleep(sleep) - return retry(attempts, 2*sleep, f) - } - return err - } - - return nil -} - -// StopRetry indicates to stop attempting retries. wraps an error -type StopRetry struct { - error -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/models/api.go b/vendor/github.com/DopplerHQ/cli/pkg/models/api.go deleted file mode 100644 index 2499a0a0..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/models/api.go +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 models - -// ComputedSecret holds all info about a secret -type ComputedSecret struct { - Name string `json:"name"` - RawValue string `json:"raw"` - ComputedValue string `json:"computed"` -} - -// WorkplaceSettings workplace settings -type WorkplaceSettings struct { - ID string `json:"id"` - Name string `json:"name"` - BillingEmail string `json:"billing_email"` -} - -// ProjectInfo project info -type ProjectInfo struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - CreatedAt string `json:"created_at"` -} - -// EnvironmentInfo environment info -type EnvironmentInfo struct { - ID string `json:"id"` - Name string `json:"name"` - CreatedAt string `json:"created_at"` - InitialFetchAt string `json:"initial_fetch_at"` - Project string `json:"project"` -} - -// ConfigInfo project info -type ConfigInfo struct { - Name string `json:"name"` - Root bool `json:"root"` - Locked bool `json:"locked"` - Environment string `json:"environment"` - Project string `json:"project"` - CreatedAt string `json:"created_at"` - InitialFetchAt string `json:"initial_fetch_at"` - LastFetchAt string `json:"last_fetch_at"` -} - -// ConfigLog a log -type ConfigLog struct { - ID string `json:"id"` - Text string `json:"text"` - HTML string `json:"html"` - CreatedAt string `json:"created_at"` - Config string `json:"config"` - Environment string `json:"environment"` - Project string `json:"project"` - User User `json:"user"` - Diff []LogDiff `json:"diff"` -} - -// ActivityLog an activity log -type ActivityLog struct { - ID string `json:"id"` - Text string `json:"text"` - HTML string `json:"html"` - CreatedAt string `json:"created_at"` - EnclaveConfig string `json:"enclave_config"` - EnclaveEnvironment string `json:"enclave_environment"` - EnclaveProject string `json:"enclave_project"` - User User `json:"user"` -} - -// User user profile -type User struct { - Email string `json:"email"` - Name string `json:"name"` - Username string `json:"username"` - ProfileImage string `json:"profile_image_url"` -} - -// LogDiff diff of log entries -type LogDiff struct { - Name string `json:"name"` - Added string `json:"added"` - Removed string `json:"removed"` -} - -// ConfigServiceToken a service token -type ConfigServiceToken struct { - Name string `json:"name"` - Token string `json:"token"` - Slug string `json:"slug"` - CreatedAt string `json:"created_at"` - Project string `json:"project"` - Environment string `json:"environment"` - Config string `json:"config"` -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/models/config.go b/vendor/github.com/DopplerHQ/cli/pkg/models/config.go deleted file mode 100644 index 3d2568bb..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/models/config.go +++ /dev/null @@ -1,139 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 models - -import "time" - -// ConfigFile structure of the config file -type ConfigFile struct { - Scoped map[string]FileScopedOptions `yaml:"scoped"` - VersionCheck VersionCheck `yaml:"version-check"` -} - -// FileScopedOptions config options -type FileScopedOptions struct { - Token string `json:"token,omitempty" yaml:"token,omitempty"` - APIHost string `json:"api-host,omitempty" yaml:"api-host,omitempty"` - DashboardHost string `json:"dashboard-host,omitempty" yaml:"dashboard-host,omitempty"` - VerifyTLS string `json:"verify-tls,omitempty" yaml:"verify-tls,omitempty"` - EnclaveProject string `json:"enclave.project,omitempty" yaml:"enclave.project,omitempty"` - EnclaveConfig string `json:"enclave.config,omitempty" yaml:"enclave.config,omitempty"` -} - -// VersionCheck info about the last check for the latest cli version -type VersionCheck struct { - LatestVersion string `yaml:"latest-version,omitempty"` - CheckedAt time.Time `yaml:"checked-at,omitempty"` -} - -// ScopedOptions options with their scope -type ScopedOptions struct { - Token ScopedOption `json:"token,omitempty" yaml:"token,omitempty"` - APIHost ScopedOption `json:"api-host,omitempty" yaml:"api-host,omitempty"` - DashboardHost ScopedOption `json:"dashboard-host,omitempty" yaml:"dashboard-host,omitempty"` - VerifyTLS ScopedOption `json:"verify-tls,omitempty" yaml:"verify-tls,omitempty"` - EnclaveProject ScopedOption `json:"enclave.project,omitempty" yaml:"enclave.project,omitempty"` - EnclaveConfig ScopedOption `json:"enclave.config,omitempty" yaml:"enclave.config,omitempty"` -} - -// ScopedOption value and its scope -type ScopedOption struct { - Value string `json:"value"` - Scope string `json:"scope"` - Source string `json:"source"` -} - -type source int - -// the source of the value -const ( - FlagSource source = iota - ConfigFileSource - EnvironmentSource - DefaultValueSource -) - -func (s source) String() string { - return [...]string{"Flag", "Config File", "Environment", "Default Value"}[s] -} - -var allConfigOptions = []string{ - "token", - "api-host", - "dashboard-host", - "verify-tls", - "enclave.project", - "enclave.config", -} - -type configOption int - -// valid config options -const ( - ConfigToken configOption = iota - ConfigAPIHost - ConfigDashboardHost - ConfigVerifyTLS - ConfigEnclaveProject - ConfigEnclaveConfig -) - -func (s configOption) String() string { - return allConfigOptions[s] -} - -// AllConfigOptions all supported options -func AllConfigOptions() []string { - return allConfigOptions -} - -// Pairs get the pairs for the given config -func Pairs(conf FileScopedOptions) map[string]string { - return map[string]string{ - ConfigToken.String(): conf.Token, - ConfigAPIHost.String(): conf.APIHost, - ConfigDashboardHost.String(): conf.DashboardHost, - ConfigVerifyTLS.String(): conf.VerifyTLS, - ConfigEnclaveProject.String(): conf.EnclaveProject, - ConfigEnclaveConfig.String(): conf.EnclaveConfig, - } -} - -// ScopedPairs get the pairs for the given scoped config -func ScopedPairs(conf *ScopedOptions) map[string]*ScopedOption { - return map[string]*ScopedOption{ - ConfigToken.String(): &conf.Token, - ConfigAPIHost.String(): &conf.APIHost, - ConfigDashboardHost.String(): &conf.DashboardHost, - ConfigVerifyTLS.String(): &conf.VerifyTLS, - ConfigEnclaveProject.String(): &conf.EnclaveProject, - ConfigEnclaveConfig.String(): &conf.EnclaveConfig, - } -} - -// EnvPairs get the scoped config pairs for each environment variable -func EnvPairs(conf *ScopedOptions) map[string]*ScopedOption { - return map[string]*ScopedOption{ - "DOPPLER_TOKEN": &conf.Token, - "DOPPLER_API_HOST": &conf.APIHost, - "DOPPLER_DASHBOARD_HOST": &conf.DashboardHost, - "DOPPLER_VERIFY_TLS": &conf.VerifyTLS, - "DOPPLER_PROJECT": &conf.EnclaveProject, - "DOPPLER_CONFIG": &conf.EnclaveConfig, - "ENCLAVE_PROJECT": &conf.EnclaveProject, // deprecated, remove in v4 - "ENCLAVE_CONFIG": &conf.EnclaveConfig, // deprecated, remove in v4 - } -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/models/files.go b/vendor/github.com/DopplerHQ/cli/pkg/models/files.go deleted file mode 100644 index c0414024..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/models/files.go +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 models - -// SecretsFileMetadata contains metadata about a secrets file -type SecretsFileMetadata struct { - Version string `json:"version,omitempty" yaml:"version,omitempty"` - ETag string `json:"etag,omitempty" yaml:"etag,omitempty"` - Hash string `json:"hash,omitempty" yaml:"hash,omitempty"` -} - -// ParseSecretsFileMetadata parse secrets file metadata -func ParseSecretsFileMetadata(data map[string]interface{}) SecretsFileMetadata { - var parsedMetadata SecretsFileMetadata - - if data["version"] != nil { - parsedMetadata.Version = data["version"].(string) - } - if data["etag"] != nil { - parsedMetadata.ETag = data["etag"].(string) - } - if data["hash"] != nil { - parsedMetadata.Hash = data["hash"].(string) - } - - return parsedMetadata -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/models/parse.go b/vendor/github.com/DopplerHQ/cli/pkg/models/parse.go deleted file mode 100644 index 454a814f..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/models/parse.go +++ /dev/null @@ -1,262 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 models - -import ( - "encoding/json" -) - -// ParseWorkplaceSettings parse workplace settings -func ParseWorkplaceSettings(info map[string]interface{}) WorkplaceSettings { - var workplaceInfo WorkplaceSettings - - if info["id"] != nil { - workplaceInfo.ID = info["id"].(string) - } - if info["name"] != nil { - workplaceInfo.Name = info["name"].(string) - } - if info["billing_email"] != nil { - workplaceInfo.BillingEmail = info["billing_email"].(string) - } - - return workplaceInfo -} - -// ParseProjectInfo parse project info -func ParseProjectInfo(info map[string]interface{}) ProjectInfo { - var projectInfo ProjectInfo - - if info["id"] != nil { - projectInfo.ID = info["id"].(string) - } - if info["name"] != nil { - projectInfo.Name = info["name"].(string) - } - if info["description"] != nil { - projectInfo.Description = info["description"].(string) - } - if info["created_at"] != nil { - projectInfo.CreatedAt = info["created_at"].(string) - } - - return projectInfo -} - -// ParseEnvironmentInfo parse environment info -func ParseEnvironmentInfo(info map[string]interface{}) EnvironmentInfo { - var environmentInfo EnvironmentInfo - - if info["id"] != nil { - environmentInfo.ID = info["id"].(string) - } - if info["name"] != nil { - environmentInfo.Name = info["name"].(string) - } - if info["created_at"] != nil { - environmentInfo.CreatedAt = info["created_at"].(string) - } - if info["initial_fetch_at"] != nil { - environmentInfo.InitialFetchAt = info["initial_fetch_at"].(string) - } - if info["project"] != nil { - environmentInfo.Project = info["project"].(string) - } - - return environmentInfo -} - -// ParseConfigInfo parse config info -func ParseConfigInfo(info map[string]interface{}) ConfigInfo { - var configInfo ConfigInfo - - if info["name"] != nil { - configInfo.Name = info["name"].(string) - } - if info["root"] != nil { - configInfo.Root = info["root"].(bool) - } - if info["locked"] != nil { - configInfo.Locked = info["locked"].(bool) - } - if info["environment"] != nil { - configInfo.Environment = info["environment"].(string) - } - if info["project"] != nil { - configInfo.Project = info["project"].(string) - } - if info["created_at"] != nil { - configInfo.CreatedAt = info["created_at"].(string) - } - if info["initial_fetch_at"] != nil { - configInfo.InitialFetchAt = info["initial_fetch_at"].(string) - } - if info["last_fetch_at"] != nil { - configInfo.LastFetchAt = info["last_fetch_at"].(string) - } - - return configInfo -} - -// ParseConfigLog parse config log -func ParseConfigLog(log map[string]interface{}) ConfigLog { - var parsedLog ConfigLog - - if log["id"] != nil { - parsedLog.ID = log["id"].(string) - } - if log["text"] != nil { - parsedLog.Text = log["text"].(string) - } - if log["html"] != nil { - parsedLog.HTML = log["html"].(string) - } - if log["created_at"] != nil { - parsedLog.CreatedAt = log["created_at"].(string) - } - if log["config"] != nil { - parsedLog.Config = log["config"].(string) - } - if log["environment"] != nil { - parsedLog.Environment = log["environment"].(string) - } - if log["project"] != nil { - parsedLog.Project = log["project"].(string) - } - if log["user"] != nil { - user := log["user"].(map[string]interface{}) - parsedLog.User.Email = user["email"].(string) - parsedLog.User.Name = user["name"].(string) - parsedLog.User.Username = user["username"].(string) - parsedLog.User.ProfileImage = user["profile_image_url"].(string) - } - if log["diff"] != nil { - for _, diff := range log["diff"].([]interface{}) { - diffMap := diff.(map[string]interface{}) - d := LogDiff{} - if diffMap["name"] != nil { - d.Name = diffMap["name"].(string) - } - if diffMap["added"] != nil { - d.Added = diffMap["added"].(string) - } - if diffMap["removed"] != nil { - d.Removed = diffMap["removed"].(string) - } - parsedLog.Diff = append(parsedLog.Diff, d) - } - } - - return parsedLog -} - -// ParseActivityLog parse activity log -func ParseActivityLog(log map[string]interface{}) ActivityLog { - var parsedLog ActivityLog - - if log["id"] != nil { - parsedLog.ID = log["id"].(string) - } - if log["text"] != nil { - parsedLog.Text = log["text"].(string) - } - if log["html"] != nil { - parsedLog.HTML = log["html"].(string) - } - if log["created_at"] != nil { - parsedLog.CreatedAt = log["created_at"].(string) - } - if log["enclave_config"] != nil { - parsedLog.EnclaveConfig = log["enclave_config"].(string) - } - if log["enclave_environment"] != nil { - parsedLog.EnclaveEnvironment = log["enclave_environment"].(string) - } - if log["enclave_project"] != nil { - parsedLog.EnclaveProject = log["enclave_project"].(string) - } - if log["user"] != nil { - user := log["user"].(map[string]interface{}) - if user["email"] != nil { - parsedLog.User.Email = user["email"].(string) - } - if user["name"] != nil { - parsedLog.User.Name = user["name"].(string) - } - if user["username"] != nil { - parsedLog.User.Username = user["username"].(string) - } - if user["profile_image_url"] != nil { - parsedLog.User.ProfileImage = user["profile_image_url"].(string) - } - } - - return parsedLog -} - -// ParseSecrets parse secrets -func ParseSecrets(response []byte) (map[string]ComputedSecret, error) { - var result map[string]interface{} - err := json.Unmarshal(response, &result) - if err != nil { - return nil, err - } - - computed := map[string]ComputedSecret{} - secrets := result["secrets"].(map[string]interface{}) - for key, secret := range secrets { - computedSecret := ComputedSecret{Name: key} - val := secret.(map[string]interface{}) - if val["raw"] != nil { - computedSecret.RawValue = val["raw"].(string) - } - if val["computed"] != nil { - computedSecret.ComputedValue = val["computed"].(string) - } - computed[key] = computedSecret - } - - return computed, nil -} - -// ParseConfigServiceToken parse config service token -func ParseConfigServiceToken(token map[string]interface{}) ConfigServiceToken { - var parsedToken ConfigServiceToken - - if token["name"] != nil { - parsedToken.Name = token["name"].(string) - } - if token["key"] != nil { - parsedToken.Token = token["key"].(string) - } - if token["slug"] != nil { - parsedToken.Slug = token["slug"].(string) - } - if token["project"] != nil { - parsedToken.Project = token["project"].(string) - } - if token["environment"] != nil { - parsedToken.Environment = token["environment"].(string) - } - if token["config"] != nil { - parsedToken.Config = token["config"].(string) - } - if token["created_at"] != nil { - parsedToken.CreatedAt = token["created_at"].(string) - } - - return parsedToken -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/models/repo_config.go b/vendor/github.com/DopplerHQ/cli/pkg/models/repo_config.go deleted file mode 100644 index daebbfdb..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/models/repo_config.go +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 models - -// RepoConfig holds all repo configuration -type RepoConfig struct { - Setup struct { - Config string `yaml:"config"` - Project string `yaml:"project"` - } `yaml:"setup"` -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/models/secrets_format.go b/vendor/github.com/DopplerHQ/cli/pkg/models/secrets_format.go deleted file mode 100644 index b3183b30..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/models/secrets_format.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 models - -// SecretsFormat the format secrets should use -type SecretsFormat int - -// the source of the value -const ( - JSON SecretsFormat = iota - ENV - YAML - DOCKER - ENV_NO_FILE -) - -var SecretFormats = []string{"json", "env", "yaml", "docker", "env-no-quotes"} - -func (s SecretsFormat) String() string { - return SecretFormats[s] -} - -// OutputFile the default secrets file name -func (s SecretsFormat) OutputFile() string { - return [...]string{"doppler.json", "doppler.env", "secrets.yaml", "doppler.env", "doppler.env"}[s] -} - -// SecretsFormatList list of supported secrets formats -var SecretsFormatList []SecretsFormat - -func init() { - SecretsFormatList = append(SecretsFormatList, JSON) - SecretsFormatList = append(SecretsFormatList, ENV) - SecretsFormatList = append(SecretsFormatList, YAML) - SecretsFormatList = append(SecretsFormatList, DOCKER) - SecretsFormatList = append(SecretsFormatList, ENV_NO_FILE) -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/models/workers.go b/vendor/github.com/DopplerHQ/cli/pkg/models/workers.go deleted file mode 100644 index 22395a74..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/models/workers.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 models - -import ( - "encoding/json" - - "github.com/DopplerHQ/cli/pkg/utils" -) - -// ChangeLog lists changes -type ChangeLog struct { - Changes []string `json:"changes"` -} - -// ParseChangeLog parse change log -func ParseChangeLog(response []byte) map[string]ChangeLog { - var releaseMap []map[string]interface{} - if err := json.Unmarshal(response, &releaseMap); err != nil { - utils.HandleError(err, "Unable to parse changelog") - } - - changes := map[string]ChangeLog{} - - for _, release := range releaseMap { - v := release["version"].(string) - var list []string - for _, change := range release["changes"].([]interface{}) { - list = append(list, change.(string)) - } - - changes[v] = ChangeLog{Changes: list} - } - - return changes -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/utils/config.go b/vendor/github.com/DopplerHQ/cli/pkg/utils/config.go deleted file mode 100644 index 22a2c325..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/utils/config.go +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 utils - -// Debug whether we're running in debug mode -var Debug = false - -// Silent whether we should display Info messages -var Silent = false - -// OutputJSON whether to print OutputJSON -var OutputJSON = false diff --git a/vendor/github.com/DopplerHQ/cli/pkg/utils/io.go b/vendor/github.com/DopplerHQ/cli/pkg/utils/io.go deleted file mode 100644 index b283135b..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/utils/io.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 utils - -import ( - "fmt" - "io/ioutil" - "os" -) - -// RestrictedFilePerms perms used for creating restrictied files meant to be accessible only to the user -func RestrictedFilePerms() os.FileMode { - // windows disallows overwriting an existing file with 0400 perms - if IsWindows() { - return 0600 - } - - return 0400 -} - -// WriteFile atomically writes data to a file named by filename. -func WriteFile(filename string, data []byte, perm os.FileMode) error { - temp := fmt.Sprintf("%s.%s", filename, RandomBase64String(8)) - - // write to a unique temp file first before performing an atomic move to the actual file name - // this prevents a race condition between multiple CLIs reading/writing the same file - LogDebug(fmt.Sprintf("Writing to temp file %s", temp)) - if err := ioutil.WriteFile(temp, data, os.FileMode(perm)); err != nil { - return err - } - - LogDebug(fmt.Sprintf("Renaming temp file to %s", filename)) - if err := os.Rename(temp, filename); err != nil { - // clean up temp file - _ = os.Remove(temp) - return err - } - - return nil -} - -// WriteTempFile writes data to a unique temp file and returns the file name -func WriteTempFile(name string, data []byte, perm os.FileMode) (string, error) { - // create hidden file in user's home dir to ensure no other users have write access - tmpFile, err := ioutil.TempFile(HomeDir(), fmt.Sprintf(".%s.", name)) - if err != nil { - return "", err - } - - LogDebug(fmt.Sprintf("Writing to temp file %s", tmpFile.Name())) - if _, err := tmpFile.Write(data); err != nil { - return "", err - } - - tmpFileName := tmpFile.Name() - if err := tmpFile.Close(); err != nil { - return "", err - } - - if err := os.Chmod(tmpFileName, perm); err != nil { - return "", err - } - - return tmpFileName, nil -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/utils/log.go b/vendor/github.com/DopplerHQ/cli/pkg/utils/log.go deleted file mode 100644 index 58056977..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/utils/log.go +++ /dev/null @@ -1,105 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 utils - -import ( - "encoding/json" - "fmt" - "os" - - "gopkg.in/gookit/color.v1" -) - -// Log info message to stdout -func Log(info string) { - if CanLogInfo() { - fmt.Println(info) - } -} - -// LogWarning message to stdout -func LogWarning(s string) { - if CanLogInfo() { - fmt.Println(color.Yellow.Render("Warning:"), s) - } -} - -// LogError prints an error message to stderr -func LogError(e error) { - if CanLogInfo() { - printError(e) - } -} - -// CanLogInfo messages to stdout -func CanLogInfo() bool { - silent := Silent || OutputJSON - return Debug || !silent -} - -// LogDebug prints a debug message to stdout -func LogDebug(s string) { - if CanLogDebug() { - // log debug messages to stderr - fmt.Fprintln(os.Stderr, color.Blue.Render("Debug:"), s) - } -} - -// LogDebugError prints an error message to stderr when in debug mode -func LogDebugError(e error) { - if CanLogDebug() { - printError(e) - } -} - -// CanLogDebug messages to stdout -func CanLogDebug() bool { - return Debug -} - -// HandleError prints the error and exits with code 1 -func HandleError(e error, messages ...string) { - ErrExit(e, 1, messages...) -} - -// ErrExit prints the error and exits with the specified code -func ErrExit(e error, exitCode int, messages ...string) { - if OutputJSON { - resp, err := json.Marshal(map[string]string{"error": e.Error()}) - if err != nil { - panic(err) - } - fmt.Fprintln(os.Stderr, string(resp)) - } else { - if len(messages) > 0 && messages[0] != "" { - fmt.Fprintln(os.Stderr, messages[0]) - } - - printError(e) - - if len(messages) > 0 { - for _, message := range messages[1:] { - fmt.Fprintln(os.Stderr, message) - } - } - } - - os.Exit(exitCode) -} - -func printError(e error) { - fmt.Fprintln(os.Stderr, color.Red.Render("Doppler Error:"), e) -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/utils/random.go b/vendor/github.com/DopplerHQ/cli/pkg/utils/random.go deleted file mode 100644 index 2d020de5..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/utils/random.go +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright © 2020 Doppler - -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 utils - -import ( - "crypto/rand" - "encoding/base64" - "math" -) - -// RandomBase64String cryptographically secure random string -// from https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-go -func RandomBase64String(l int) string { - // Base 64 text is 1/3 longer than base 256. (2^8 vs 2^6; 8bits/6bits = 1.333 ratio) - buffer := make([]byte, int(math.Round(float64(l)/float64(4/3)))) - rand.Read(buffer) // #nosec G104 - str := base64.RawURLEncoding.EncodeToString(buffer) - return str[:l] // strip 1 extra character we get from odd length results -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/utils/util.go b/vendor/github.com/DopplerHQ/cli/pkg/utils/util.go deleted file mode 100644 index 093ed466..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/utils/util.go +++ /dev/null @@ -1,396 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 utils - -import ( - "errors" - "fmt" - "os" - "os/exec" - "os/signal" - "os/user" - "path/filepath" - "runtime" - "strconv" - "strings" - "syscall" - "time" - - "github.com/AlecAivazis/survey/v2" - "github.com/AlecAivazis/survey/v2/terminal" - "github.com/atotto/clipboard" - "github.com/google/uuid" - "github.com/spf13/cobra" -) - -// ConfigDir DEPRECATED get configuration directory -func ConfigDir() string { - // this function is deprecated and should not be used. - // in testing, node:12-alpine creates the ~/.config directory at some indeterminate point - // in the build. this means some doppler commands called by docker RUN may use the home - // directory to store config, while doppler commands called by ENTRYPOINT will use ~/config. - dir, err := os.UserConfigDir() - if err != nil { - HandleError(err, "Unable to determine configuration directory") - } - - return dir -} - -// HomeDir get home directory -func HomeDir() string { - dir, err := os.UserHomeDir() - if err != nil { - HandleError(err, "Unable to determine home directory") - } - - return dir -} - -// ParsePath returns an absolute path, parsing ~ . .. etc -func ParsePath(path string) (string, error) { - if path == "" { - return "", errors.New("Path cannot be blank") - } - - if strings.HasPrefix(path, "~") { - firstPath := strings.Split(path, string(filepath.Separator))[0] - - if firstPath != "~" { - username, err := user.Current() - if err != nil || firstPath != fmt.Sprintf("~%s", username.Username) { - return "", fmt.Errorf("unable to parse path, please specify an absolute path (e.g. /home/%s)", path[1:]) - } - } - - path = strings.Replace(path, firstPath, HomeDir(), 1) - } - - absolutePath, err := filepath.Abs(filepath.Clean(path)) - if err != nil { - return "", err - } - - return absolutePath, nil -} - -// Exists whether path exists and the user has permission -func Exists(path string) bool { - if _, err := os.Stat(path); err != nil { - return false - } - return true -} - -// Cwd current working directory of user's shell -func Cwd() string { - cwd, err := os.Getwd() - if err != nil { - HandleError(err) - } - return cwd -} - -// RunCommand runs the specified command -func RunCommand(command []string, env []string, inFile *os.File, outFile *os.File, errFile *os.File, forwardSignals bool) (int, error) { - cmd := exec.Command(command[0], command[1:]...) // #nosec G204 - cmd.Env = env - cmd.Stdin = inFile - cmd.Stdout = outFile - cmd.Stderr = errFile - - return execCommand(cmd, forwardSignals) -} - -// RunCommandString runs the specified command string -func RunCommandString(command string, env []string, inFile *os.File, outFile *os.File, errFile *os.File, forwardSignals bool) (int, error) { - shell := [2]string{"sh", "-c"} - if IsWindows() { - shell = [2]string{"cmd", "/C"} - } else { - // these shells all support the same options we use for sh - shells := []string{"/bash", "/dash", "/fish", "/zsh", "/ksh", "/csh", "/tcsh"} - envShell := os.Getenv("SHELL") - for _, s := range shells { - if strings.HasSuffix(envShell, s) { - shell[0] = envShell - break - } - } - } - cmd := exec.Command(shell[0], shell[1], command) // #nosec G204 - cmd.Env = env - cmd.Stdin = inFile - cmd.Stdout = outFile - cmd.Stderr = errFile - - return execCommand(cmd, forwardSignals) -} - -func execCommand(cmd *exec.Cmd, forwardSignals bool) (int, error) { - // signal handling logic adapted from aws-vault https://github.com/99designs/aws-vault/ - sigChan := make(chan os.Signal, 1) - signal.Notify(sigChan) - - if err := cmd.Start(); err != nil { - return 1, err - } - - // handle all signals - go func() { - for { - // When running with a TTY, user-generated signals (like SIGINT) are sent to the entire process group. - // If we forward the signal, the child process will end up receiving the signal twice. - if forwardSignals { - // forward to process - sig := <-sigChan - cmd.Process.Signal(sig) // #nosec G104 - } else { - // ignore - <-sigChan - } - } - }() - - if err := cmd.Wait(); err != nil { - // ignore errors - cmd.Process.Signal(os.Kill) // #nosec G104 - - if exitError, ok := err.(*exec.ExitError); ok { - return exitError.ExitCode(), exitError - } - - return 2, err - } - - waitStatus := cmd.ProcessState.Sys().(syscall.WaitStatus) - return waitStatus.ExitStatus(), nil -} - -// RequireValue throws an error if a value is blank -func RequireValue(name string, value string) { - value = strings.TrimSpace(value) - if value == "" { - HandleError(fmt.Errorf("you must provide a %s", name)) - } -} - -// GetBool parse string into a boolean -func GetBool(value string, def bool) bool { - b, err := strconv.ParseBool(value) - if err != nil { - return def - } - return b -} - -// GetBoolFlag gets the flag's boolean value -func GetBoolFlag(cmd *cobra.Command, flag string) bool { - b, err := strconv.ParseBool(cmd.Flag(flag).Value.String()) - if err != nil { - HandleError(err) - } - return b -} - -// GetBoolFlagIfChanged gets the flag's boolean value, if specified; -// protects against reading an undefined flag -func GetBoolFlagIfChanged(cmd *cobra.Command, flag string, def bool) bool { - if !cmd.Flags().Changed(flag) { - return def - } - - return GetBoolFlag(cmd, flag) -} - -// GetFlagIfChanged gets the flag's value, if specified; -// protects against reading an undefined flag -func GetFlagIfChanged(cmd *cobra.Command, flag string, def string) string { - if !cmd.Flags().Changed(flag) { - return def - } - - return cmd.Flag(flag).Value.String() -} - -// GetPathFlagIfChanged gets the flag's path, if specified; -// always returns an absolute path -func GetPathFlagIfChanged(cmd *cobra.Command, flag string, def string) string { - if !cmd.Flags().Changed(flag) { - return def - } - - path, err := ParsePath(cmd.Flag(flag).Value.String()) - if err != nil { - HandleError(err, "Unable to parse path") - } - return path -} - -// GetIntFlag gets the flag's int value -func GetIntFlag(cmd *cobra.Command, flag string, bits int) int { - number, err := strconv.ParseInt(cmd.Flag(flag).Value.String(), 10, bits) - if err != nil { - HandleError(err) - } - - return int(number) -} - -// GetDurationFlag gets the flag's duration -func GetDurationFlag(cmd *cobra.Command, flag string) time.Duration { - value, err := time.ParseDuration(cmd.Flag(flag).Value.String()) - if err != nil { - HandleError(err) - } - return value -} - -// GetDurationFlagIfChanged gets the flag's duration, if specified; -// protects against reading an undefined flag -func GetDurationFlagIfChanged(cmd *cobra.Command, flag string, def time.Duration) time.Duration { - if !cmd.Flags().Changed(flag) { - return def - } - - return GetDurationFlag(cmd, flag) -} - -// GetFilePath verify a file path and name are provided -func GetFilePath(fullPath string) (string, error) { - if fullPath == "" { - return "", errors.New("Invalid file path") - } - - fullPath, err := ParsePath(fullPath) - if err != nil { - return "", errors.New("Invalid file path") - } - - parsedPath := filepath.Dir(fullPath) - parsedName := filepath.Base(fullPath) - - isNameValid := (parsedName != ".") && (parsedName != "..") && (parsedName != "/") && (parsedName != string(filepath.Separator)) - if !isNameValid { - return "", errors.New("Invalid file path") - } - - return filepath.Join(parsedPath, parsedName), nil -} - -// ConfirmationPrompt prompt user to confirm yes/no -func ConfirmationPrompt(message string, defaultValue bool) bool { - confirm := false - prompt := &survey.Confirm{ - Message: message, - Default: defaultValue, - } - - err := survey.AskOne(prompt, &confirm) - if err != nil { - if err == terminal.InterruptErr { - Log("Exiting") - os.Exit(1) - } - HandleError(err) - } - return confirm -} - -// SelectPrompt prompt user to select from a list of options -func SelectPrompt(message string, options []string, defaultOption string) string { - prompt := &survey.Select{ - Message: message, - Options: options, - PageSize: 25, - } - if defaultOption != "" { - prompt.Default = defaultOption - } - - selectedProject := "" - err := survey.AskOne(prompt, &selectedProject) - if err != nil { - if err == terminal.InterruptErr { - Log("Exiting") - os.Exit(1) - } - HandleError(err) - } - - return selectedProject -} - -// CopyToClipboard copies text to the user's clipboard -func CopyToClipboard(text string) error { - if !clipboard.Unsupported { - err := clipboard.WriteAll(text) - if err != nil { - return err - } - } - return nil -} - -// HostOS the host OS -func HostOS() string { - os := runtime.GOOS - - switch os { - case "darwin": - return "macOS" - case "windows": - return "Windows" - } - - return os -} - -// HostArch the host architecture -func HostArch() string { - arch := runtime.GOARCH - - switch arch { - case "amd64": - return "64-bit" - case "amd64p32": - case "386": - return "32-bit" - } - - return arch -} - -// IsWindows whether the host os is Windows -func IsWindows() bool { - return runtime.GOOS == "windows" -} - -// IsMacOS whether the host os is macOS -func IsMacOS() bool { - return runtime.GOOS == "darwin" -} - -// UUID generates a random UUID -func UUID() (string, error) { - uuid, err := uuid.NewRandom() - if err != nil { - LogDebug("Unable to generate random UUID") - return "", err - } - - return uuid.String(), nil -} diff --git a/vendor/github.com/DopplerHQ/cli/pkg/version/config.go b/vendor/github.com/DopplerHQ/cli/pkg/version/config.go deleted file mode 100644 index 9ca86505..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/version/config.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 version - -// PerformVersionCheck whether to check for new versions of the Doppler CLI -var PerformVersionCheck = true diff --git a/vendor/github.com/DopplerHQ/cli/pkg/version/version.go b/vendor/github.com/DopplerHQ/cli/pkg/version/version.go deleted file mode 100644 index 9c17400c..00000000 --- a/vendor/github.com/DopplerHQ/cli/pkg/version/version.go +++ /dev/null @@ -1,112 +0,0 @@ -/* -Copyright © 2019 Doppler - -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 version - -import ( - "fmt" - "strconv" - "strings" -) - -// ProgramVersion the current version of this program -var ProgramVersion = "dev" - -// Version semver -type Version struct { - Major int16 - Minor int16 - Patch int16 -} - -// Unwrap get the original error -func (v Version) String() string { - return fmt.Sprintf("v%d.%d.%d", v.Major, v.Minor, v.Patch) -} - -// IsDevelopment whether the CLI is running in development mode (not a released version) -func IsDevelopment() bool { - return strings.HasPrefix(ProgramVersion, "dev") -} - -// CompareVersions returns -1 if first is greater, 1 if second is greater, and 0 otherwise -func CompareVersions(a Version, b Version) int { - // major version - if a.Major > b.Major { - return -1 - } - if b.Major > a.Major { - return 1 - } - - // minor version - if a.Minor > b.Minor { - return -1 - } - if b.Minor > a.Minor { - return 1 - } - - // patch version - if a.Patch > b.Patch { - return -1 - } - if b.Patch > a.Patch { - return 1 - } - - return 0 -} - -// ParseVersion from a string -func ParseVersion(s string) (Version, error) { - if strings.HasPrefix(s, "v") { - s = s[1:] - } - parts := strings.Split(s, ".") - if len(parts) != 3 { - return Version{}, fmt.Errorf("Invalid version %s", s) - } - - var v Version - var major int64 - var minor int64 - var patch int64 - var err error - if major, err = strconv.ParseInt(parts[0], 10, 16); err != nil { - return Version{}, fmt.Errorf("Invalid version %s", s) - } - if minor, err = strconv.ParseInt(parts[1], 10, 16); err != nil { - return Version{}, fmt.Errorf("Invalid version %s", s) - } - if patch, err = strconv.ParseInt(parts[2], 10, 16); err != nil { - return Version{}, fmt.Errorf("Invalid version %s", s) - } - - v.Major = int16(major) - v.Minor = int16(minor) - v.Patch = int16(patch) - return v, nil -} - -// Normalize prepends a 'v' to a version (e.g. 1.0.0 -> v1.0.0) -func Normalize(version string) string { - version = strings.TrimSpace(version) - if !strings.HasPrefix(version, "v") { - return "v" + version - } - - return version -} diff --git a/vendor/github.com/Microsoft/go-winio/.gitignore b/vendor/github.com/Microsoft/go-winio/.gitignore deleted file mode 100644 index b883f1fd..00000000 --- a/vendor/github.com/Microsoft/go-winio/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.exe diff --git a/vendor/github.com/Microsoft/go-winio/CODEOWNERS b/vendor/github.com/Microsoft/go-winio/CODEOWNERS deleted file mode 100644 index ae1b4942..00000000 --- a/vendor/github.com/Microsoft/go-winio/CODEOWNERS +++ /dev/null @@ -1 +0,0 @@ - * @microsoft/containerplat diff --git a/vendor/github.com/Microsoft/go-winio/LICENSE b/vendor/github.com/Microsoft/go-winio/LICENSE deleted file mode 100644 index b8b569d7..00000000 --- a/vendor/github.com/Microsoft/go-winio/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Microsoft - -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/github.com/Microsoft/go-winio/README.md b/vendor/github.com/Microsoft/go-winio/README.md deleted file mode 100644 index 56800105..00000000 --- a/vendor/github.com/Microsoft/go-winio/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# go-winio - -This repository contains utilities for efficiently performing Win32 IO operations in -Go. Currently, this is focused on accessing named pipes and other file handles, and -for using named pipes as a net transport. - -This code relies on IO completion ports to avoid blocking IO on system threads, allowing Go -to reuse the thread to schedule another goroutine. This limits support to Windows Vista and -newer operating systems. This is similar to the implementation of network sockets in Go's net -package. - -Please see the LICENSE file for licensing information. - -This project has adopted the [Microsoft Open Source Code of -Conduct](https://opensource.microsoft.com/codeofconduct/). For more information -see the [Code of Conduct -FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact -[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional -questions or comments. - -Thanks to natefinch for the inspiration for this library. See https://github.com/natefinch/npipe -for another named pipe implementation. diff --git a/vendor/github.com/Microsoft/go-winio/backup.go b/vendor/github.com/Microsoft/go-winio/backup.go deleted file mode 100644 index 2be34af4..00000000 --- a/vendor/github.com/Microsoft/go-winio/backup.go +++ /dev/null @@ -1,280 +0,0 @@ -// +build windows - -package winio - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "runtime" - "syscall" - "unicode/utf16" -) - -//sys backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupRead -//sys backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupWrite - -const ( - BackupData = uint32(iota + 1) - BackupEaData - BackupSecurity - BackupAlternateData - BackupLink - BackupPropertyData - BackupObjectId - BackupReparseData - BackupSparseBlock - BackupTxfsData -) - -const ( - StreamSparseAttributes = uint32(8) -) - -const ( - WRITE_DAC = 0x40000 - WRITE_OWNER = 0x80000 - ACCESS_SYSTEM_SECURITY = 0x1000000 -) - -// BackupHeader represents a backup stream of a file. -type BackupHeader struct { - Id uint32 // The backup stream ID - Attributes uint32 // Stream attributes - Size int64 // The size of the stream in bytes - Name string // The name of the stream (for BackupAlternateData only). - Offset int64 // The offset of the stream in the file (for BackupSparseBlock only). -} - -type win32StreamId struct { - StreamId uint32 - Attributes uint32 - Size uint64 - NameSize uint32 -} - -// BackupStreamReader reads from a stream produced by the BackupRead Win32 API and produces a series -// of BackupHeader values. -type BackupStreamReader struct { - r io.Reader - bytesLeft int64 -} - -// NewBackupStreamReader produces a BackupStreamReader from any io.Reader. -func NewBackupStreamReader(r io.Reader) *BackupStreamReader { - return &BackupStreamReader{r, 0} -} - -// Next returns the next backup stream and prepares for calls to Read(). It skips the remainder of the current stream if -// it was not completely read. -func (r *BackupStreamReader) Next() (*BackupHeader, error) { - if r.bytesLeft > 0 { - if s, ok := r.r.(io.Seeker); ok { - // Make sure Seek on io.SeekCurrent sometimes succeeds - // before trying the actual seek. - if _, err := s.Seek(0, io.SeekCurrent); err == nil { - if _, err = s.Seek(r.bytesLeft, io.SeekCurrent); err != nil { - return nil, err - } - r.bytesLeft = 0 - } - } - if _, err := io.Copy(ioutil.Discard, r); err != nil { - return nil, err - } - } - var wsi win32StreamId - if err := binary.Read(r.r, binary.LittleEndian, &wsi); err != nil { - return nil, err - } - hdr := &BackupHeader{ - Id: wsi.StreamId, - Attributes: wsi.Attributes, - Size: int64(wsi.Size), - } - if wsi.NameSize != 0 { - name := make([]uint16, int(wsi.NameSize/2)) - if err := binary.Read(r.r, binary.LittleEndian, name); err != nil { - return nil, err - } - hdr.Name = syscall.UTF16ToString(name) - } - if wsi.StreamId == BackupSparseBlock { - if err := binary.Read(r.r, binary.LittleEndian, &hdr.Offset); err != nil { - return nil, err - } - hdr.Size -= 8 - } - r.bytesLeft = hdr.Size - return hdr, nil -} - -// Read reads from the current backup stream. -func (r *BackupStreamReader) Read(b []byte) (int, error) { - if r.bytesLeft == 0 { - return 0, io.EOF - } - if int64(len(b)) > r.bytesLeft { - b = b[:r.bytesLeft] - } - n, err := r.r.Read(b) - r.bytesLeft -= int64(n) - if err == io.EOF { - err = io.ErrUnexpectedEOF - } else if r.bytesLeft == 0 && err == nil { - err = io.EOF - } - return n, err -} - -// BackupStreamWriter writes a stream compatible with the BackupWrite Win32 API. -type BackupStreamWriter struct { - w io.Writer - bytesLeft int64 -} - -// NewBackupStreamWriter produces a BackupStreamWriter on top of an io.Writer. -func NewBackupStreamWriter(w io.Writer) *BackupStreamWriter { - return &BackupStreamWriter{w, 0} -} - -// WriteHeader writes the next backup stream header and prepares for calls to Write(). -func (w *BackupStreamWriter) WriteHeader(hdr *BackupHeader) error { - if w.bytesLeft != 0 { - return fmt.Errorf("missing %d bytes", w.bytesLeft) - } - name := utf16.Encode([]rune(hdr.Name)) - wsi := win32StreamId{ - StreamId: hdr.Id, - Attributes: hdr.Attributes, - Size: uint64(hdr.Size), - NameSize: uint32(len(name) * 2), - } - if hdr.Id == BackupSparseBlock { - // Include space for the int64 block offset - wsi.Size += 8 - } - if err := binary.Write(w.w, binary.LittleEndian, &wsi); err != nil { - return err - } - if len(name) != 0 { - if err := binary.Write(w.w, binary.LittleEndian, name); err != nil { - return err - } - } - if hdr.Id == BackupSparseBlock { - if err := binary.Write(w.w, binary.LittleEndian, hdr.Offset); err != nil { - return err - } - } - w.bytesLeft = hdr.Size - return nil -} - -// Write writes to the current backup stream. -func (w *BackupStreamWriter) Write(b []byte) (int, error) { - if w.bytesLeft < int64(len(b)) { - return 0, fmt.Errorf("too many bytes by %d", int64(len(b))-w.bytesLeft) - } - n, err := w.w.Write(b) - w.bytesLeft -= int64(n) - return n, err -} - -// BackupFileReader provides an io.ReadCloser interface on top of the BackupRead Win32 API. -type BackupFileReader struct { - f *os.File - includeSecurity bool - ctx uintptr -} - -// NewBackupFileReader returns a new BackupFileReader from a file handle. If includeSecurity is true, -// Read will attempt to read the security descriptor of the file. -func NewBackupFileReader(f *os.File, includeSecurity bool) *BackupFileReader { - r := &BackupFileReader{f, includeSecurity, 0} - return r -} - -// Read reads a backup stream from the file by calling the Win32 API BackupRead(). -func (r *BackupFileReader) Read(b []byte) (int, error) { - var bytesRead uint32 - err := backupRead(syscall.Handle(r.f.Fd()), b, &bytesRead, false, r.includeSecurity, &r.ctx) - if err != nil { - return 0, &os.PathError{"BackupRead", r.f.Name(), err} - } - runtime.KeepAlive(r.f) - if bytesRead == 0 { - return 0, io.EOF - } - return int(bytesRead), nil -} - -// Close frees Win32 resources associated with the BackupFileReader. It does not close -// the underlying file. -func (r *BackupFileReader) Close() error { - if r.ctx != 0 { - backupRead(syscall.Handle(r.f.Fd()), nil, nil, true, false, &r.ctx) - runtime.KeepAlive(r.f) - r.ctx = 0 - } - return nil -} - -// BackupFileWriter provides an io.WriteCloser interface on top of the BackupWrite Win32 API. -type BackupFileWriter struct { - f *os.File - includeSecurity bool - ctx uintptr -} - -// NewBackupFileWriter returns a new BackupFileWriter from a file handle. If includeSecurity is true, -// Write() will attempt to restore the security descriptor from the stream. -func NewBackupFileWriter(f *os.File, includeSecurity bool) *BackupFileWriter { - w := &BackupFileWriter{f, includeSecurity, 0} - return w -} - -// Write restores a portion of the file using the provided backup stream. -func (w *BackupFileWriter) Write(b []byte) (int, error) { - var bytesWritten uint32 - err := backupWrite(syscall.Handle(w.f.Fd()), b, &bytesWritten, false, w.includeSecurity, &w.ctx) - if err != nil { - return 0, &os.PathError{"BackupWrite", w.f.Name(), err} - } - runtime.KeepAlive(w.f) - if int(bytesWritten) != len(b) { - return int(bytesWritten), errors.New("not all bytes could be written") - } - return len(b), nil -} - -// Close frees Win32 resources associated with the BackupFileWriter. It does not -// close the underlying file. -func (w *BackupFileWriter) Close() error { - if w.ctx != 0 { - backupWrite(syscall.Handle(w.f.Fd()), nil, nil, true, false, &w.ctx) - runtime.KeepAlive(w.f) - w.ctx = 0 - } - return nil -} - -// OpenForBackup opens a file or directory, potentially skipping access checks if the backup -// or restore privileges have been acquired. -// -// If the file opened was a directory, it cannot be used with Readdir(). -func OpenForBackup(path string, access uint32, share uint32, createmode uint32) (*os.File, error) { - winPath, err := syscall.UTF16FromString(path) - if err != nil { - return nil, err - } - h, err := syscall.CreateFile(&winPath[0], access, share, nil, createmode, syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OPEN_REPARSE_POINT, 0) - if err != nil { - err = &os.PathError{Op: "open", Path: path, Err: err} - return nil, err - } - return os.NewFile(uintptr(h), path), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/ea.go b/vendor/github.com/Microsoft/go-winio/ea.go deleted file mode 100644 index 4051c1b3..00000000 --- a/vendor/github.com/Microsoft/go-winio/ea.go +++ /dev/null @@ -1,137 +0,0 @@ -package winio - -import ( - "bytes" - "encoding/binary" - "errors" -) - -type fileFullEaInformation struct { - NextEntryOffset uint32 - Flags uint8 - NameLength uint8 - ValueLength uint16 -} - -var ( - fileFullEaInformationSize = binary.Size(&fileFullEaInformation{}) - - errInvalidEaBuffer = errors.New("invalid extended attribute buffer") - errEaNameTooLarge = errors.New("extended attribute name too large") - errEaValueTooLarge = errors.New("extended attribute value too large") -) - -// ExtendedAttribute represents a single Windows EA. -type ExtendedAttribute struct { - Name string - Value []byte - Flags uint8 -} - -func parseEa(b []byte) (ea ExtendedAttribute, nb []byte, err error) { - var info fileFullEaInformation - err = binary.Read(bytes.NewReader(b), binary.LittleEndian, &info) - if err != nil { - err = errInvalidEaBuffer - return - } - - nameOffset := fileFullEaInformationSize - nameLen := int(info.NameLength) - valueOffset := nameOffset + int(info.NameLength) + 1 - valueLen := int(info.ValueLength) - nextOffset := int(info.NextEntryOffset) - if valueLen+valueOffset > len(b) || nextOffset < 0 || nextOffset > len(b) { - err = errInvalidEaBuffer - return - } - - ea.Name = string(b[nameOffset : nameOffset+nameLen]) - ea.Value = b[valueOffset : valueOffset+valueLen] - ea.Flags = info.Flags - if info.NextEntryOffset != 0 { - nb = b[info.NextEntryOffset:] - } - return -} - -// DecodeExtendedAttributes decodes a list of EAs from a FILE_FULL_EA_INFORMATION -// buffer retrieved from BackupRead, ZwQueryEaFile, etc. -func DecodeExtendedAttributes(b []byte) (eas []ExtendedAttribute, err error) { - for len(b) != 0 { - ea, nb, err := parseEa(b) - if err != nil { - return nil, err - } - - eas = append(eas, ea) - b = nb - } - return -} - -func writeEa(buf *bytes.Buffer, ea *ExtendedAttribute, last bool) error { - if int(uint8(len(ea.Name))) != len(ea.Name) { - return errEaNameTooLarge - } - if int(uint16(len(ea.Value))) != len(ea.Value) { - return errEaValueTooLarge - } - entrySize := uint32(fileFullEaInformationSize + len(ea.Name) + 1 + len(ea.Value)) - withPadding := (entrySize + 3) &^ 3 - nextOffset := uint32(0) - if !last { - nextOffset = withPadding - } - info := fileFullEaInformation{ - NextEntryOffset: nextOffset, - Flags: ea.Flags, - NameLength: uint8(len(ea.Name)), - ValueLength: uint16(len(ea.Value)), - } - - err := binary.Write(buf, binary.LittleEndian, &info) - if err != nil { - return err - } - - _, err = buf.Write([]byte(ea.Name)) - if err != nil { - return err - } - - err = buf.WriteByte(0) - if err != nil { - return err - } - - _, err = buf.Write(ea.Value) - if err != nil { - return err - } - - _, err = buf.Write([]byte{0, 0, 0}[0 : withPadding-entrySize]) - if err != nil { - return err - } - - return nil -} - -// EncodeExtendedAttributes encodes a list of EAs into a FILE_FULL_EA_INFORMATION -// buffer for use with BackupWrite, ZwSetEaFile, etc. -func EncodeExtendedAttributes(eas []ExtendedAttribute) ([]byte, error) { - var buf bytes.Buffer - for i := range eas { - last := false - if i == len(eas)-1 { - last = true - } - - err := writeEa(&buf, &eas[i], last) - if err != nil { - return nil, err - } - } - return buf.Bytes(), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/file.go b/vendor/github.com/Microsoft/go-winio/file.go deleted file mode 100644 index 0385e410..00000000 --- a/vendor/github.com/Microsoft/go-winio/file.go +++ /dev/null @@ -1,323 +0,0 @@ -// +build windows - -package winio - -import ( - "errors" - "io" - "runtime" - "sync" - "sync/atomic" - "syscall" - "time" -) - -//sys cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) = CancelIoEx -//sys createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) = CreateIoCompletionPort -//sys getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) = GetQueuedCompletionStatus -//sys setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) = SetFileCompletionNotificationModes -//sys wsaGetOverlappedResult(h syscall.Handle, o *syscall.Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) = ws2_32.WSAGetOverlappedResult - -type atomicBool int32 - -func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 } -func (b *atomicBool) setFalse() { atomic.StoreInt32((*int32)(b), 0) } -func (b *atomicBool) setTrue() { atomic.StoreInt32((*int32)(b), 1) } -func (b *atomicBool) swap(new bool) bool { - var newInt int32 - if new { - newInt = 1 - } - return atomic.SwapInt32((*int32)(b), newInt) == 1 -} - -const ( - cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1 - cFILE_SKIP_SET_EVENT_ON_HANDLE = 2 -) - -var ( - ErrFileClosed = errors.New("file has already been closed") - ErrTimeout = &timeoutError{} -) - -type timeoutError struct{} - -func (e *timeoutError) Error() string { return "i/o timeout" } -func (e *timeoutError) Timeout() bool { return true } -func (e *timeoutError) Temporary() bool { return true } - -type timeoutChan chan struct{} - -var ioInitOnce sync.Once -var ioCompletionPort syscall.Handle - -// ioResult contains the result of an asynchronous IO operation -type ioResult struct { - bytes uint32 - err error -} - -// ioOperation represents an outstanding asynchronous Win32 IO -type ioOperation struct { - o syscall.Overlapped - ch chan ioResult -} - -func initIo() { - h, err := createIoCompletionPort(syscall.InvalidHandle, 0, 0, 0xffffffff) - if err != nil { - panic(err) - } - ioCompletionPort = h - go ioCompletionProcessor(h) -} - -// win32File implements Reader, Writer, and Closer on a Win32 handle without blocking in a syscall. -// It takes ownership of this handle and will close it if it is garbage collected. -type win32File struct { - handle syscall.Handle - wg sync.WaitGroup - wgLock sync.RWMutex - closing atomicBool - socket bool - readDeadline deadlineHandler - writeDeadline deadlineHandler -} - -type deadlineHandler struct { - setLock sync.Mutex - channel timeoutChan - channelLock sync.RWMutex - timer *time.Timer - timedout atomicBool -} - -// makeWin32File makes a new win32File from an existing file handle -func makeWin32File(h syscall.Handle) (*win32File, error) { - f := &win32File{handle: h} - ioInitOnce.Do(initIo) - _, err := createIoCompletionPort(h, ioCompletionPort, 0, 0xffffffff) - if err != nil { - return nil, err - } - err = setFileCompletionNotificationModes(h, cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS|cFILE_SKIP_SET_EVENT_ON_HANDLE) - if err != nil { - return nil, err - } - f.readDeadline.channel = make(timeoutChan) - f.writeDeadline.channel = make(timeoutChan) - return f, nil -} - -func MakeOpenFile(h syscall.Handle) (io.ReadWriteCloser, error) { - // If we return the result of makeWin32File directly, it can result in an - // interface-wrapped nil, rather than a nil interface value. - f, err := makeWin32File(h) - if err != nil { - return nil, err - } - return f, nil -} - -// closeHandle closes the resources associated with a Win32 handle -func (f *win32File) closeHandle() { - f.wgLock.Lock() - // Atomically set that we are closing, releasing the resources only once. - if !f.closing.swap(true) { - f.wgLock.Unlock() - // cancel all IO and wait for it to complete - cancelIoEx(f.handle, nil) - f.wg.Wait() - // at this point, no new IO can start - syscall.Close(f.handle) - f.handle = 0 - } else { - f.wgLock.Unlock() - } -} - -// Close closes a win32File. -func (f *win32File) Close() error { - f.closeHandle() - return nil -} - -// prepareIo prepares for a new IO operation. -// The caller must call f.wg.Done() when the IO is finished, prior to Close() returning. -func (f *win32File) prepareIo() (*ioOperation, error) { - f.wgLock.RLock() - if f.closing.isSet() { - f.wgLock.RUnlock() - return nil, ErrFileClosed - } - f.wg.Add(1) - f.wgLock.RUnlock() - c := &ioOperation{} - c.ch = make(chan ioResult) - return c, nil -} - -// ioCompletionProcessor processes completed async IOs forever -func ioCompletionProcessor(h syscall.Handle) { - for { - var bytes uint32 - var key uintptr - var op *ioOperation - err := getQueuedCompletionStatus(h, &bytes, &key, &op, syscall.INFINITE) - if op == nil { - panic(err) - } - op.ch <- ioResult{bytes, err} - } -} - -// asyncIo processes the return value from ReadFile or WriteFile, blocking until -// the operation has actually completed. -func (f *win32File) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, err error) (int, error) { - if err != syscall.ERROR_IO_PENDING { - return int(bytes), err - } - - if f.closing.isSet() { - cancelIoEx(f.handle, &c.o) - } - - var timeout timeoutChan - if d != nil { - d.channelLock.Lock() - timeout = d.channel - d.channelLock.Unlock() - } - - var r ioResult - select { - case r = <-c.ch: - err = r.err - if err == syscall.ERROR_OPERATION_ABORTED { - if f.closing.isSet() { - err = ErrFileClosed - } - } else if err != nil && f.socket { - // err is from Win32. Query the overlapped structure to get the winsock error. - var bytes, flags uint32 - err = wsaGetOverlappedResult(f.handle, &c.o, &bytes, false, &flags) - } - case <-timeout: - cancelIoEx(f.handle, &c.o) - r = <-c.ch - err = r.err - if err == syscall.ERROR_OPERATION_ABORTED { - err = ErrTimeout - } - } - - // runtime.KeepAlive is needed, as c is passed via native - // code to ioCompletionProcessor, c must remain alive - // until the channel read is complete. - runtime.KeepAlive(c) - return int(r.bytes), err -} - -// Read reads from a file handle. -func (f *win32File) Read(b []byte) (int, error) { - c, err := f.prepareIo() - if err != nil { - return 0, err - } - defer f.wg.Done() - - if f.readDeadline.timedout.isSet() { - return 0, ErrTimeout - } - - var bytes uint32 - err = syscall.ReadFile(f.handle, b, &bytes, &c.o) - n, err := f.asyncIo(c, &f.readDeadline, bytes, err) - runtime.KeepAlive(b) - - // Handle EOF conditions. - if err == nil && n == 0 && len(b) != 0 { - return 0, io.EOF - } else if err == syscall.ERROR_BROKEN_PIPE { - return 0, io.EOF - } else { - return n, err - } -} - -// Write writes to a file handle. -func (f *win32File) Write(b []byte) (int, error) { - c, err := f.prepareIo() - if err != nil { - return 0, err - } - defer f.wg.Done() - - if f.writeDeadline.timedout.isSet() { - return 0, ErrTimeout - } - - var bytes uint32 - err = syscall.WriteFile(f.handle, b, &bytes, &c.o) - n, err := f.asyncIo(c, &f.writeDeadline, bytes, err) - runtime.KeepAlive(b) - return n, err -} - -func (f *win32File) SetReadDeadline(deadline time.Time) error { - return f.readDeadline.set(deadline) -} - -func (f *win32File) SetWriteDeadline(deadline time.Time) error { - return f.writeDeadline.set(deadline) -} - -func (f *win32File) Flush() error { - return syscall.FlushFileBuffers(f.handle) -} - -func (f *win32File) Fd() uintptr { - return uintptr(f.handle) -} - -func (d *deadlineHandler) set(deadline time.Time) error { - d.setLock.Lock() - defer d.setLock.Unlock() - - if d.timer != nil { - if !d.timer.Stop() { - <-d.channel - } - d.timer = nil - } - d.timedout.setFalse() - - select { - case <-d.channel: - d.channelLock.Lock() - d.channel = make(chan struct{}) - d.channelLock.Unlock() - default: - } - - if deadline.IsZero() { - return nil - } - - timeoutIO := func() { - d.timedout.setTrue() - close(d.channel) - } - - now := time.Now() - duration := deadline.Sub(now) - if deadline.After(now) { - // Deadline is in the future, set a timer to wait - d.timer = time.AfterFunc(duration, timeoutIO) - } else { - // Deadline is in the past. Cancel all pending IO now. - timeoutIO() - } - return nil -} diff --git a/vendor/github.com/Microsoft/go-winio/fileinfo.go b/vendor/github.com/Microsoft/go-winio/fileinfo.go deleted file mode 100644 index 3ab6bff6..00000000 --- a/vendor/github.com/Microsoft/go-winio/fileinfo.go +++ /dev/null @@ -1,73 +0,0 @@ -// +build windows - -package winio - -import ( - "os" - "runtime" - "unsafe" - - "golang.org/x/sys/windows" -) - -// FileBasicInfo contains file access time and file attributes information. -type FileBasicInfo struct { - CreationTime, LastAccessTime, LastWriteTime, ChangeTime windows.Filetime - FileAttributes uint32 - pad uint32 // padding -} - -// GetFileBasicInfo retrieves times and attributes for a file. -func GetFileBasicInfo(f *os.File) (*FileBasicInfo, error) { - bi := &FileBasicInfo{} - if err := windows.GetFileInformationByHandleEx(windows.Handle(f.Fd()), windows.FileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil { - return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return bi, nil -} - -// SetFileBasicInfo sets times and attributes for a file. -func SetFileBasicInfo(f *os.File, bi *FileBasicInfo) error { - if err := windows.SetFileInformationByHandle(windows.Handle(f.Fd()), windows.FileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil { - return &os.PathError{Op: "SetFileInformationByHandle", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return nil -} - -// FileStandardInfo contains extended information for the file. -// FILE_STANDARD_INFO in WinBase.h -// https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_standard_info -type FileStandardInfo struct { - AllocationSize, EndOfFile int64 - NumberOfLinks uint32 - DeletePending, Directory bool -} - -// GetFileStandardInfo retrieves ended information for the file. -func GetFileStandardInfo(f *os.File) (*FileStandardInfo, error) { - si := &FileStandardInfo{} - if err := windows.GetFileInformationByHandleEx(windows.Handle(f.Fd()), windows.FileStandardInfo, (*byte)(unsafe.Pointer(si)), uint32(unsafe.Sizeof(*si))); err != nil { - return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return si, nil -} - -// FileIDInfo contains the volume serial number and file ID for a file. This pair should be -// unique on a system. -type FileIDInfo struct { - VolumeSerialNumber uint64 - FileID [16]byte -} - -// GetFileID retrieves the unique (volume, file ID) pair for a file. -func GetFileID(f *os.File) (*FileIDInfo, error) { - fileID := &FileIDInfo{} - if err := windows.GetFileInformationByHandleEx(windows.Handle(f.Fd()), windows.FileIdInfo, (*byte)(unsafe.Pointer(fileID)), uint32(unsafe.Sizeof(*fileID))); err != nil { - return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return fileID, nil -} diff --git a/vendor/github.com/Microsoft/go-winio/hvsock.go b/vendor/github.com/Microsoft/go-winio/hvsock.go deleted file mode 100644 index b632f8f8..00000000 --- a/vendor/github.com/Microsoft/go-winio/hvsock.go +++ /dev/null @@ -1,307 +0,0 @@ -// +build windows - -package winio - -import ( - "fmt" - "io" - "net" - "os" - "syscall" - "time" - "unsafe" - - "github.com/Microsoft/go-winio/pkg/guid" -) - -//sys bind(s syscall.Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socketError] = ws2_32.bind - -const ( - afHvSock = 34 // AF_HYPERV - - socketError = ^uintptr(0) -) - -// An HvsockAddr is an address for a AF_HYPERV socket. -type HvsockAddr struct { - VMID guid.GUID - ServiceID guid.GUID -} - -type rawHvsockAddr struct { - Family uint16 - _ uint16 - VMID guid.GUID - ServiceID guid.GUID -} - -// Network returns the address's network name, "hvsock". -func (addr *HvsockAddr) Network() string { - return "hvsock" -} - -func (addr *HvsockAddr) String() string { - return fmt.Sprintf("%s:%s", &addr.VMID, &addr.ServiceID) -} - -// VsockServiceID returns an hvsock service ID corresponding to the specified AF_VSOCK port. -func VsockServiceID(port uint32) guid.GUID { - g, _ := guid.FromString("00000000-facb-11e6-bd58-64006a7986d3") - g.Data1 = port - return g -} - -func (addr *HvsockAddr) raw() rawHvsockAddr { - return rawHvsockAddr{ - Family: afHvSock, - VMID: addr.VMID, - ServiceID: addr.ServiceID, - } -} - -func (addr *HvsockAddr) fromRaw(raw *rawHvsockAddr) { - addr.VMID = raw.VMID - addr.ServiceID = raw.ServiceID -} - -// HvsockListener is a socket listener for the AF_HYPERV address family. -type HvsockListener struct { - sock *win32File - addr HvsockAddr -} - -// HvsockConn is a connected socket of the AF_HYPERV address family. -type HvsockConn struct { - sock *win32File - local, remote HvsockAddr -} - -func newHvSocket() (*win32File, error) { - fd, err := syscall.Socket(afHvSock, syscall.SOCK_STREAM, 1) - if err != nil { - return nil, os.NewSyscallError("socket", err) - } - f, err := makeWin32File(fd) - if err != nil { - syscall.Close(fd) - return nil, err - } - f.socket = true - return f, nil -} - -// ListenHvsock listens for connections on the specified hvsock address. -func ListenHvsock(addr *HvsockAddr) (_ *HvsockListener, err error) { - l := &HvsockListener{addr: *addr} - sock, err := newHvSocket() - if err != nil { - return nil, l.opErr("listen", err) - } - sa := addr.raw() - err = bind(sock.handle, unsafe.Pointer(&sa), int32(unsafe.Sizeof(sa))) - if err != nil { - return nil, l.opErr("listen", os.NewSyscallError("socket", err)) - } - err = syscall.Listen(sock.handle, 16) - if err != nil { - return nil, l.opErr("listen", os.NewSyscallError("listen", err)) - } - return &HvsockListener{sock: sock, addr: *addr}, nil -} - -func (l *HvsockListener) opErr(op string, err error) error { - return &net.OpError{Op: op, Net: "hvsock", Addr: &l.addr, Err: err} -} - -// Addr returns the listener's network address. -func (l *HvsockListener) Addr() net.Addr { - return &l.addr -} - -// Accept waits for the next connection and returns it. -func (l *HvsockListener) Accept() (_ net.Conn, err error) { - sock, err := newHvSocket() - if err != nil { - return nil, l.opErr("accept", err) - } - defer func() { - if sock != nil { - sock.Close() - } - }() - c, err := l.sock.prepareIo() - if err != nil { - return nil, l.opErr("accept", err) - } - defer l.sock.wg.Done() - - // AcceptEx, per documentation, requires an extra 16 bytes per address. - const addrlen = uint32(16 + unsafe.Sizeof(rawHvsockAddr{})) - var addrbuf [addrlen * 2]byte - - var bytes uint32 - err = syscall.AcceptEx(l.sock.handle, sock.handle, &addrbuf[0], 0, addrlen, addrlen, &bytes, &c.o) - _, err = l.sock.asyncIo(c, nil, bytes, err) - if err != nil { - return nil, l.opErr("accept", os.NewSyscallError("acceptex", err)) - } - conn := &HvsockConn{ - sock: sock, - } - conn.local.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[0]))) - conn.remote.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[addrlen]))) - sock = nil - return conn, nil -} - -// Close closes the listener, causing any pending Accept calls to fail. -func (l *HvsockListener) Close() error { - return l.sock.Close() -} - -/* Need to finish ConnectEx handling -func DialHvsock(ctx context.Context, addr *HvsockAddr) (*HvsockConn, error) { - sock, err := newHvSocket() - if err != nil { - return nil, err - } - defer func() { - if sock != nil { - sock.Close() - } - }() - c, err := sock.prepareIo() - if err != nil { - return nil, err - } - defer sock.wg.Done() - var bytes uint32 - err = windows.ConnectEx(windows.Handle(sock.handle), sa, nil, 0, &bytes, &c.o) - _, err = sock.asyncIo(ctx, c, nil, bytes, err) - if err != nil { - return nil, err - } - conn := &HvsockConn{ - sock: sock, - remote: *addr, - } - sock = nil - return conn, nil -} -*/ - -func (conn *HvsockConn) opErr(op string, err error) error { - return &net.OpError{Op: op, Net: "hvsock", Source: &conn.local, Addr: &conn.remote, Err: err} -} - -func (conn *HvsockConn) Read(b []byte) (int, error) { - c, err := conn.sock.prepareIo() - if err != nil { - return 0, conn.opErr("read", err) - } - defer conn.sock.wg.Done() - buf := syscall.WSABuf{Buf: &b[0], Len: uint32(len(b))} - var flags, bytes uint32 - err = syscall.WSARecv(conn.sock.handle, &buf, 1, &bytes, &flags, &c.o, nil) - n, err := conn.sock.asyncIo(c, &conn.sock.readDeadline, bytes, err) - if err != nil { - if _, ok := err.(syscall.Errno); ok { - err = os.NewSyscallError("wsarecv", err) - } - return 0, conn.opErr("read", err) - } else if n == 0 { - err = io.EOF - } - return n, err -} - -func (conn *HvsockConn) Write(b []byte) (int, error) { - t := 0 - for len(b) != 0 { - n, err := conn.write(b) - if err != nil { - return t + n, err - } - t += n - b = b[n:] - } - return t, nil -} - -func (conn *HvsockConn) write(b []byte) (int, error) { - c, err := conn.sock.prepareIo() - if err != nil { - return 0, conn.opErr("write", err) - } - defer conn.sock.wg.Done() - buf := syscall.WSABuf{Buf: &b[0], Len: uint32(len(b))} - var bytes uint32 - err = syscall.WSASend(conn.sock.handle, &buf, 1, &bytes, 0, &c.o, nil) - n, err := conn.sock.asyncIo(c, &conn.sock.writeDeadline, bytes, err) - if err != nil { - if _, ok := err.(syscall.Errno); ok { - err = os.NewSyscallError("wsasend", err) - } - return 0, conn.opErr("write", err) - } - return n, err -} - -// Close closes the socket connection, failing any pending read or write calls. -func (conn *HvsockConn) Close() error { - return conn.sock.Close() -} - -func (conn *HvsockConn) shutdown(how int) error { - err := syscall.Shutdown(conn.sock.handle, syscall.SHUT_RD) - if err != nil { - return os.NewSyscallError("shutdown", err) - } - return nil -} - -// CloseRead shuts down the read end of the socket. -func (conn *HvsockConn) CloseRead() error { - err := conn.shutdown(syscall.SHUT_RD) - if err != nil { - return conn.opErr("close", err) - } - return nil -} - -// CloseWrite shuts down the write end of the socket, notifying the other endpoint that -// no more data will be written. -func (conn *HvsockConn) CloseWrite() error { - err := conn.shutdown(syscall.SHUT_WR) - if err != nil { - return conn.opErr("close", err) - } - return nil -} - -// LocalAddr returns the local address of the connection. -func (conn *HvsockConn) LocalAddr() net.Addr { - return &conn.local -} - -// RemoteAddr returns the remote address of the connection. -func (conn *HvsockConn) RemoteAddr() net.Addr { - return &conn.remote -} - -// SetDeadline implements the net.Conn SetDeadline method. -func (conn *HvsockConn) SetDeadline(t time.Time) error { - conn.SetReadDeadline(t) - conn.SetWriteDeadline(t) - return nil -} - -// SetReadDeadline implements the net.Conn SetReadDeadline method. -func (conn *HvsockConn) SetReadDeadline(t time.Time) error { - return conn.sock.SetReadDeadline(t) -} - -// SetWriteDeadline implements the net.Conn SetWriteDeadline method. -func (conn *HvsockConn) SetWriteDeadline(t time.Time) error { - return conn.sock.SetWriteDeadline(t) -} diff --git a/vendor/github.com/Microsoft/go-winio/pipe.go b/vendor/github.com/Microsoft/go-winio/pipe.go deleted file mode 100644 index 96700a73..00000000 --- a/vendor/github.com/Microsoft/go-winio/pipe.go +++ /dev/null @@ -1,517 +0,0 @@ -// +build windows - -package winio - -import ( - "context" - "errors" - "fmt" - "io" - "net" - "os" - "runtime" - "syscall" - "time" - "unsafe" -) - -//sys connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) = ConnectNamedPipe -//sys createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateNamedPipeW -//sys createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateFileW -//sys getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) = GetNamedPipeInfo -//sys getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW -//sys localAlloc(uFlags uint32, length uint32) (ptr uintptr) = LocalAlloc -//sys ntCreateNamedPipeFile(pipe *syscall.Handle, access uint32, oa *objectAttributes, iosb *ioStatusBlock, share uint32, disposition uint32, options uint32, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (status ntstatus) = ntdll.NtCreateNamedPipeFile -//sys rtlNtStatusToDosError(status ntstatus) (winerr error) = ntdll.RtlNtStatusToDosErrorNoTeb -//sys rtlDosPathNameToNtPathName(name *uint16, ntName *unicodeString, filePart uintptr, reserved uintptr) (status ntstatus) = ntdll.RtlDosPathNameToNtPathName_U -//sys rtlDefaultNpAcl(dacl *uintptr) (status ntstatus) = ntdll.RtlDefaultNpAcl - -type ioStatusBlock struct { - Status, Information uintptr -} - -type objectAttributes struct { - Length uintptr - RootDirectory uintptr - ObjectName *unicodeString - Attributes uintptr - SecurityDescriptor *securityDescriptor - SecurityQoS uintptr -} - -type unicodeString struct { - Length uint16 - MaximumLength uint16 - Buffer uintptr -} - -type securityDescriptor struct { - Revision byte - Sbz1 byte - Control uint16 - Owner uintptr - Group uintptr - Sacl uintptr - Dacl uintptr -} - -type ntstatus int32 - -func (status ntstatus) Err() error { - if status >= 0 { - return nil - } - return rtlNtStatusToDosError(status) -} - -const ( - cERROR_PIPE_BUSY = syscall.Errno(231) - cERROR_NO_DATA = syscall.Errno(232) - cERROR_PIPE_CONNECTED = syscall.Errno(535) - cERROR_SEM_TIMEOUT = syscall.Errno(121) - - cSECURITY_SQOS_PRESENT = 0x100000 - cSECURITY_ANONYMOUS = 0 - - cPIPE_TYPE_MESSAGE = 4 - - cPIPE_READMODE_MESSAGE = 2 - - cFILE_OPEN = 1 - cFILE_CREATE = 2 - - cFILE_PIPE_MESSAGE_TYPE = 1 - cFILE_PIPE_REJECT_REMOTE_CLIENTS = 2 - - cSE_DACL_PRESENT = 4 -) - -var ( - // ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed. - // This error should match net.errClosing since docker takes a dependency on its text. - ErrPipeListenerClosed = errors.New("use of closed network connection") - - errPipeWriteClosed = errors.New("pipe has been closed for write") -) - -type win32Pipe struct { - *win32File - path string -} - -type win32MessageBytePipe struct { - win32Pipe - writeClosed bool - readEOF bool -} - -type pipeAddress string - -func (f *win32Pipe) LocalAddr() net.Addr { - return pipeAddress(f.path) -} - -func (f *win32Pipe) RemoteAddr() net.Addr { - return pipeAddress(f.path) -} - -func (f *win32Pipe) SetDeadline(t time.Time) error { - f.SetReadDeadline(t) - f.SetWriteDeadline(t) - return nil -} - -// CloseWrite closes the write side of a message pipe in byte mode. -func (f *win32MessageBytePipe) CloseWrite() error { - if f.writeClosed { - return errPipeWriteClosed - } - err := f.win32File.Flush() - if err != nil { - return err - } - _, err = f.win32File.Write(nil) - if err != nil { - return err - } - f.writeClosed = true - return nil -} - -// Write writes bytes to a message pipe in byte mode. Zero-byte writes are ignored, since -// they are used to implement CloseWrite(). -func (f *win32MessageBytePipe) Write(b []byte) (int, error) { - if f.writeClosed { - return 0, errPipeWriteClosed - } - if len(b) == 0 { - return 0, nil - } - return f.win32File.Write(b) -} - -// Read reads bytes from a message pipe in byte mode. A read of a zero-byte message on a message -// mode pipe will return io.EOF, as will all subsequent reads. -func (f *win32MessageBytePipe) Read(b []byte) (int, error) { - if f.readEOF { - return 0, io.EOF - } - n, err := f.win32File.Read(b) - if err == io.EOF { - // If this was the result of a zero-byte read, then - // it is possible that the read was due to a zero-size - // message. Since we are simulating CloseWrite with a - // zero-byte message, ensure that all future Read() calls - // also return EOF. - f.readEOF = true - } else if err == syscall.ERROR_MORE_DATA { - // ERROR_MORE_DATA indicates that the pipe's read mode is message mode - // and the message still has more bytes. Treat this as a success, since - // this package presents all named pipes as byte streams. - err = nil - } - return n, err -} - -func (s pipeAddress) Network() string { - return "pipe" -} - -func (s pipeAddress) String() string { - return string(s) -} - -// tryDialPipe attempts to dial the pipe at `path` until `ctx` cancellation or timeout. -func tryDialPipe(ctx context.Context, path *string, access uint32) (syscall.Handle, error) { - for { - - select { - case <-ctx.Done(): - return syscall.Handle(0), ctx.Err() - default: - h, err := createFile(*path, access, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_OVERLAPPED|cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0) - if err == nil { - return h, nil - } - if err != cERROR_PIPE_BUSY { - return h, &os.PathError{Err: err, Op: "open", Path: *path} - } - // Wait 10 msec and try again. This is a rather simplistic - // view, as we always try each 10 milliseconds. - time.Sleep(10 * time.Millisecond) - } - } -} - -// DialPipe connects to a named pipe by path, timing out if the connection -// takes longer than the specified duration. If timeout is nil, then we use -// a default timeout of 2 seconds. (We do not use WaitNamedPipe.) -func DialPipe(path string, timeout *time.Duration) (net.Conn, error) { - var absTimeout time.Time - if timeout != nil { - absTimeout = time.Now().Add(*timeout) - } else { - absTimeout = time.Now().Add(2 * time.Second) - } - ctx, _ := context.WithDeadline(context.Background(), absTimeout) - conn, err := DialPipeContext(ctx, path) - if err == context.DeadlineExceeded { - return nil, ErrTimeout - } - return conn, err -} - -// DialPipeContext attempts to connect to a named pipe by `path` until `ctx` -// cancellation or timeout. -func DialPipeContext(ctx context.Context, path string) (net.Conn, error) { - return DialPipeAccess(ctx, path, syscall.GENERIC_READ|syscall.GENERIC_WRITE) -} - -// DialPipeAccess attempts to connect to a named pipe by `path` with `access` until `ctx` -// cancellation or timeout. -func DialPipeAccess(ctx context.Context, path string, access uint32) (net.Conn, error) { - var err error - var h syscall.Handle - h, err = tryDialPipe(ctx, &path, access) - if err != nil { - return nil, err - } - - var flags uint32 - err = getNamedPipeInfo(h, &flags, nil, nil, nil) - if err != nil { - return nil, err - } - - f, err := makeWin32File(h) - if err != nil { - syscall.Close(h) - return nil, err - } - - // If the pipe is in message mode, return a message byte pipe, which - // supports CloseWrite(). - if flags&cPIPE_TYPE_MESSAGE != 0 { - return &win32MessageBytePipe{ - win32Pipe: win32Pipe{win32File: f, path: path}, - }, nil - } - return &win32Pipe{win32File: f, path: path}, nil -} - -type acceptResponse struct { - f *win32File - err error -} - -type win32PipeListener struct { - firstHandle syscall.Handle - path string - config PipeConfig - acceptCh chan (chan acceptResponse) - closeCh chan int - doneCh chan int -} - -func makeServerPipeHandle(path string, sd []byte, c *PipeConfig, first bool) (syscall.Handle, error) { - path16, err := syscall.UTF16FromString(path) - if err != nil { - return 0, &os.PathError{Op: "open", Path: path, Err: err} - } - - var oa objectAttributes - oa.Length = unsafe.Sizeof(oa) - - var ntPath unicodeString - if err := rtlDosPathNameToNtPathName(&path16[0], &ntPath, 0, 0).Err(); err != nil { - return 0, &os.PathError{Op: "open", Path: path, Err: err} - } - defer localFree(ntPath.Buffer) - oa.ObjectName = &ntPath - - // The security descriptor is only needed for the first pipe. - if first { - if sd != nil { - len := uint32(len(sd)) - sdb := localAlloc(0, len) - defer localFree(sdb) - copy((*[0xffff]byte)(unsafe.Pointer(sdb))[:], sd) - oa.SecurityDescriptor = (*securityDescriptor)(unsafe.Pointer(sdb)) - } else { - // Construct the default named pipe security descriptor. - var dacl uintptr - if err := rtlDefaultNpAcl(&dacl).Err(); err != nil { - return 0, fmt.Errorf("getting default named pipe ACL: %s", err) - } - defer localFree(dacl) - - sdb := &securityDescriptor{ - Revision: 1, - Control: cSE_DACL_PRESENT, - Dacl: dacl, - } - oa.SecurityDescriptor = sdb - } - } - - typ := uint32(cFILE_PIPE_REJECT_REMOTE_CLIENTS) - if c.MessageMode { - typ |= cFILE_PIPE_MESSAGE_TYPE - } - - disposition := uint32(cFILE_OPEN) - access := uint32(syscall.GENERIC_READ | syscall.GENERIC_WRITE | syscall.SYNCHRONIZE) - if first { - disposition = cFILE_CREATE - // By not asking for read or write access, the named pipe file system - // will put this pipe into an initially disconnected state, blocking - // client connections until the next call with first == false. - access = syscall.SYNCHRONIZE - } - - timeout := int64(-50 * 10000) // 50ms - - var ( - h syscall.Handle - iosb ioStatusBlock - ) - err = ntCreateNamedPipeFile(&h, access, &oa, &iosb, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE, disposition, 0, typ, 0, 0, 0xffffffff, uint32(c.InputBufferSize), uint32(c.OutputBufferSize), &timeout).Err() - if err != nil { - return 0, &os.PathError{Op: "open", Path: path, Err: err} - } - - runtime.KeepAlive(ntPath) - return h, nil -} - -func (l *win32PipeListener) makeServerPipe() (*win32File, error) { - h, err := makeServerPipeHandle(l.path, nil, &l.config, false) - if err != nil { - return nil, err - } - f, err := makeWin32File(h) - if err != nil { - syscall.Close(h) - return nil, err - } - return f, nil -} - -func (l *win32PipeListener) makeConnectedServerPipe() (*win32File, error) { - p, err := l.makeServerPipe() - if err != nil { - return nil, err - } - - // Wait for the client to connect. - ch := make(chan error) - go func(p *win32File) { - ch <- connectPipe(p) - }(p) - - select { - case err = <-ch: - if err != nil { - p.Close() - p = nil - } - case <-l.closeCh: - // Abort the connect request by closing the handle. - p.Close() - p = nil - err = <-ch - if err == nil || err == ErrFileClosed { - err = ErrPipeListenerClosed - } - } - return p, err -} - -func (l *win32PipeListener) listenerRoutine() { - closed := false - for !closed { - select { - case <-l.closeCh: - closed = true - case responseCh := <-l.acceptCh: - var ( - p *win32File - err error - ) - for { - p, err = l.makeConnectedServerPipe() - // If the connection was immediately closed by the client, try - // again. - if err != cERROR_NO_DATA { - break - } - } - responseCh <- acceptResponse{p, err} - closed = err == ErrPipeListenerClosed - } - } - syscall.Close(l.firstHandle) - l.firstHandle = 0 - // Notify Close() and Accept() callers that the handle has been closed. - close(l.doneCh) -} - -// PipeConfig contain configuration for the pipe listener. -type PipeConfig struct { - // SecurityDescriptor contains a Windows security descriptor in SDDL format. - SecurityDescriptor string - - // MessageMode determines whether the pipe is in byte or message mode. In either - // case the pipe is read in byte mode by default. The only practical difference in - // this implementation is that CloseWrite() is only supported for message mode pipes; - // CloseWrite() is implemented as a zero-byte write, but zero-byte writes are only - // transferred to the reader (and returned as io.EOF in this implementation) - // when the pipe is in message mode. - MessageMode bool - - // InputBufferSize specifies the size of the input buffer, in bytes. - InputBufferSize int32 - - // OutputBufferSize specifies the size of the output buffer, in bytes. - OutputBufferSize int32 -} - -// ListenPipe creates a listener on a Windows named pipe path, e.g. \\.\pipe\mypipe. -// The pipe must not already exist. -func ListenPipe(path string, c *PipeConfig) (net.Listener, error) { - var ( - sd []byte - err error - ) - if c == nil { - c = &PipeConfig{} - } - if c.SecurityDescriptor != "" { - sd, err = SddlToSecurityDescriptor(c.SecurityDescriptor) - if err != nil { - return nil, err - } - } - h, err := makeServerPipeHandle(path, sd, c, true) - if err != nil { - return nil, err - } - l := &win32PipeListener{ - firstHandle: h, - path: path, - config: *c, - acceptCh: make(chan (chan acceptResponse)), - closeCh: make(chan int), - doneCh: make(chan int), - } - go l.listenerRoutine() - return l, nil -} - -func connectPipe(p *win32File) error { - c, err := p.prepareIo() - if err != nil { - return err - } - defer p.wg.Done() - - err = connectNamedPipe(p.handle, &c.o) - _, err = p.asyncIo(c, nil, 0, err) - if err != nil && err != cERROR_PIPE_CONNECTED { - return err - } - return nil -} - -func (l *win32PipeListener) Accept() (net.Conn, error) { - ch := make(chan acceptResponse) - select { - case l.acceptCh <- ch: - response := <-ch - err := response.err - if err != nil { - return nil, err - } - if l.config.MessageMode { - return &win32MessageBytePipe{ - win32Pipe: win32Pipe{win32File: response.f, path: l.path}, - }, nil - } - return &win32Pipe{win32File: response.f, path: l.path}, nil - case <-l.doneCh: - return nil, ErrPipeListenerClosed - } -} - -func (l *win32PipeListener) Close() error { - select { - case l.closeCh <- 1: - <-l.doneCh - case <-l.doneCh: - } - return nil -} - -func (l *win32PipeListener) Addr() net.Addr { - return pipeAddress(l.path) -} diff --git a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go b/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go deleted file mode 100644 index f497c0e3..00000000 --- a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go +++ /dev/null @@ -1,237 +0,0 @@ -// +build windows - -// Package guid provides a GUID type. The backing structure for a GUID is -// identical to that used by the golang.org/x/sys/windows GUID type. -// There are two main binary encodings used for a GUID, the big-endian encoding, -// and the Windows (mixed-endian) encoding. See here for details: -// https://en.wikipedia.org/wiki/Universally_unique_identifier#Encoding -package guid - -import ( - "crypto/rand" - "crypto/sha1" - "encoding" - "encoding/binary" - "fmt" - "strconv" - - "golang.org/x/sys/windows" -) - -// Variant specifies which GUID variant (or "type") of the GUID. It determines -// how the entirety of the rest of the GUID is interpreted. -type Variant uint8 - -// The variants specified by RFC 4122. -const ( - // VariantUnknown specifies a GUID variant which does not conform to one of - // the variant encodings specified in RFC 4122. - VariantUnknown Variant = iota - VariantNCS - VariantRFC4122 - VariantMicrosoft - VariantFuture -) - -// Version specifies how the bits in the GUID were generated. For instance, a -// version 4 GUID is randomly generated, and a version 5 is generated from the -// hash of an input string. -type Version uint8 - -var _ = (encoding.TextMarshaler)(GUID{}) -var _ = (encoding.TextUnmarshaler)(&GUID{}) - -// GUID represents a GUID/UUID. It has the same structure as -// golang.org/x/sys/windows.GUID so that it can be used with functions expecting -// that type. It is defined as its own type so that stringification and -// marshaling can be supported. The representation matches that used by native -// Windows code. -type GUID windows.GUID - -// NewV4 returns a new version 4 (pseudorandom) GUID, as defined by RFC 4122. -func NewV4() (GUID, error) { - var b [16]byte - if _, err := rand.Read(b[:]); err != nil { - return GUID{}, err - } - - g := FromArray(b) - g.setVersion(4) // Version 4 means randomly generated. - g.setVariant(VariantRFC4122) - - return g, nil -} - -// NewV5 returns a new version 5 (generated from a string via SHA-1 hashing) -// GUID, as defined by RFC 4122. The RFC is unclear on the encoding of the name, -// and the sample code treats it as a series of bytes, so we do the same here. -// -// Some implementations, such as those found on Windows, treat the name as a -// big-endian UTF16 stream of bytes. If that is desired, the string can be -// encoded as such before being passed to this function. -func NewV5(namespace GUID, name []byte) (GUID, error) { - b := sha1.New() - namespaceBytes := namespace.ToArray() - b.Write(namespaceBytes[:]) - b.Write(name) - - a := [16]byte{} - copy(a[:], b.Sum(nil)) - - g := FromArray(a) - g.setVersion(5) // Version 5 means generated from a string. - g.setVariant(VariantRFC4122) - - return g, nil -} - -func fromArray(b [16]byte, order binary.ByteOrder) GUID { - var g GUID - g.Data1 = order.Uint32(b[0:4]) - g.Data2 = order.Uint16(b[4:6]) - g.Data3 = order.Uint16(b[6:8]) - copy(g.Data4[:], b[8:16]) - return g -} - -func (g GUID) toArray(order binary.ByteOrder) [16]byte { - b := [16]byte{} - order.PutUint32(b[0:4], g.Data1) - order.PutUint16(b[4:6], g.Data2) - order.PutUint16(b[6:8], g.Data3) - copy(b[8:16], g.Data4[:]) - return b -} - -// FromArray constructs a GUID from a big-endian encoding array of 16 bytes. -func FromArray(b [16]byte) GUID { - return fromArray(b, binary.BigEndian) -} - -// ToArray returns an array of 16 bytes representing the GUID in big-endian -// encoding. -func (g GUID) ToArray() [16]byte { - return g.toArray(binary.BigEndian) -} - -// FromWindowsArray constructs a GUID from a Windows encoding array of bytes. -func FromWindowsArray(b [16]byte) GUID { - return fromArray(b, binary.LittleEndian) -} - -// ToWindowsArray returns an array of 16 bytes representing the GUID in Windows -// encoding. -func (g GUID) ToWindowsArray() [16]byte { - return g.toArray(binary.LittleEndian) -} - -func (g GUID) String() string { - return fmt.Sprintf( - "%08x-%04x-%04x-%04x-%012x", - g.Data1, - g.Data2, - g.Data3, - g.Data4[:2], - g.Data4[2:]) -} - -// FromString parses a string containing a GUID and returns the GUID. The only -// format currently supported is the `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` -// format. -func FromString(s string) (GUID, error) { - if len(s) != 36 { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - - var g GUID - - data1, err := strconv.ParseUint(s[0:8], 16, 32) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data1 = uint32(data1) - - data2, err := strconv.ParseUint(s[9:13], 16, 16) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data2 = uint16(data2) - - data3, err := strconv.ParseUint(s[14:18], 16, 16) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data3 = uint16(data3) - - for i, x := range []int{19, 21, 24, 26, 28, 30, 32, 34} { - v, err := strconv.ParseUint(s[x:x+2], 16, 8) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data4[i] = uint8(v) - } - - return g, nil -} - -func (g *GUID) setVariant(v Variant) { - d := g.Data4[0] - switch v { - case VariantNCS: - d = (d & 0x7f) - case VariantRFC4122: - d = (d & 0x3f) | 0x80 - case VariantMicrosoft: - d = (d & 0x1f) | 0xc0 - case VariantFuture: - d = (d & 0x0f) | 0xe0 - case VariantUnknown: - fallthrough - default: - panic(fmt.Sprintf("invalid variant: %d", v)) - } - g.Data4[0] = d -} - -// Variant returns the GUID variant, as defined in RFC 4122. -func (g GUID) Variant() Variant { - b := g.Data4[0] - if b&0x80 == 0 { - return VariantNCS - } else if b&0xc0 == 0x80 { - return VariantRFC4122 - } else if b&0xe0 == 0xc0 { - return VariantMicrosoft - } else if b&0xe0 == 0xe0 { - return VariantFuture - } - return VariantUnknown -} - -func (g *GUID) setVersion(v Version) { - g.Data3 = (g.Data3 & 0x0fff) | (uint16(v) << 12) -} - -// Version returns the GUID version, as defined in RFC 4122. -func (g GUID) Version() Version { - return Version((g.Data3 & 0xF000) >> 12) -} - -// MarshalText returns the textual representation of the GUID. -func (g GUID) MarshalText() ([]byte, error) { - return []byte(g.String()), nil -} - -// UnmarshalText takes the textual representation of a GUID, and unmarhals it -// into this GUID. -func (g *GUID) UnmarshalText(text []byte) error { - g2, err := FromString(string(text)) - if err != nil { - return err - } - *g = g2 - return nil -} diff --git a/vendor/github.com/Microsoft/go-winio/pkg/security/grantvmgroupaccess.go b/vendor/github.com/Microsoft/go-winio/pkg/security/grantvmgroupaccess.go deleted file mode 100644 index fca24159..00000000 --- a/vendor/github.com/Microsoft/go-winio/pkg/security/grantvmgroupaccess.go +++ /dev/null @@ -1,161 +0,0 @@ -// +build windows - -package security - -import ( - "os" - "syscall" - "unsafe" - - "github.com/pkg/errors" -) - -type ( - accessMask uint32 - accessMode uint32 - desiredAccess uint32 - inheritMode uint32 - objectType uint32 - shareMode uint32 - securityInformation uint32 - trusteeForm uint32 - trusteeType uint32 - - explicitAccess struct { - accessPermissions accessMask - accessMode accessMode - inheritance inheritMode - trustee trustee - } - - trustee struct { - multipleTrustee *trustee - multipleTrusteeOperation int32 - trusteeForm trusteeForm - trusteeType trusteeType - name uintptr - } -) - -const ( - accessMaskDesiredPermission accessMask = 1 << 31 // GENERIC_READ - - accessModeGrant accessMode = 1 - - desiredAccessReadControl desiredAccess = 0x20000 - desiredAccessWriteDac desiredAccess = 0x40000 - - gvmga = "GrantVmGroupAccess:" - - inheritModeNoInheritance inheritMode = 0x0 - inheritModeSubContainersAndObjectsInherit inheritMode = 0x3 - - objectTypeFileObject objectType = 0x1 - - securityInformationDACL securityInformation = 0x4 - - shareModeRead shareMode = 0x1 - shareModeWrite shareMode = 0x2 - - sidVmGroup = "S-1-5-83-0" - - trusteeFormIsSid trusteeForm = 0 - - trusteeTypeWellKnownGroup trusteeType = 5 -) - -// GrantVMGroupAccess sets the DACL for a specified file or directory to -// include Grant ACE entries for the VM Group SID. This is a golang re- -// implementation of the same function in vmcompute, just not exported in -// RS5. Which kind of sucks. Sucks a lot :/ -func GrantVmGroupAccess(name string) error { - // Stat (to determine if `name` is a directory). - s, err := os.Stat(name) - if err != nil { - return errors.Wrapf(err, "%s os.Stat %s", gvmga, name) - } - - // Get a handle to the file/directory. Must defer Close on success. - fd, err := createFile(name, s.IsDir()) - if err != nil { - return err // Already wrapped - } - defer syscall.CloseHandle(fd) - - // Get the current DACL and Security Descriptor. Must defer LocalFree on success. - ot := objectTypeFileObject - si := securityInformationDACL - sd := uintptr(0) - origDACL := uintptr(0) - if err := getSecurityInfo(fd, uint32(ot), uint32(si), nil, nil, &origDACL, nil, &sd); err != nil { - return errors.Wrapf(err, "%s GetSecurityInfo %s", gvmga, name) - } - defer syscall.LocalFree((syscall.Handle)(unsafe.Pointer(sd))) - - // Generate a new DACL which is the current DACL with the required ACEs added. - // Must defer LocalFree on success. - newDACL, err := generateDACLWithAcesAdded(name, s.IsDir(), origDACL) - if err != nil { - return err // Already wrapped - } - defer syscall.LocalFree((syscall.Handle)(unsafe.Pointer(newDACL))) - - // And finally use SetSecurityInfo to apply the updated DACL. - if err := setSecurityInfo(fd, uint32(ot), uint32(si), uintptr(0), uintptr(0), newDACL, uintptr(0)); err != nil { - return errors.Wrapf(err, "%s SetSecurityInfo %s", gvmga, name) - } - - return nil -} - -// createFile is a helper function to call [Nt]CreateFile to get a handle to -// the file or directory. -func createFile(name string, isDir bool) (syscall.Handle, error) { - namep := syscall.StringToUTF16(name) - da := uint32(desiredAccessReadControl | desiredAccessWriteDac) - sm := uint32(shareModeRead | shareModeWrite) - fa := uint32(syscall.FILE_ATTRIBUTE_NORMAL) - if isDir { - fa = uint32(fa | syscall.FILE_FLAG_BACKUP_SEMANTICS) - } - fd, err := syscall.CreateFile(&namep[0], da, sm, nil, syscall.OPEN_EXISTING, fa, 0) - if err != nil { - return 0, errors.Wrapf(err, "%s syscall.CreateFile %s", gvmga, name) - } - return fd, nil -} - -// generateDACLWithAcesAdded generates a new DACL with the two needed ACEs added. -// The caller is responsible for LocalFree of the returned DACL on success. -func generateDACLWithAcesAdded(name string, isDir bool, origDACL uintptr) (uintptr, error) { - // Generate pointers to the SIDs based on the string SIDs - sid, err := syscall.StringToSid(sidVmGroup) - if err != nil { - return 0, errors.Wrapf(err, "%s syscall.StringToSid %s %s", gvmga, name, sidVmGroup) - } - - inheritance := inheritModeNoInheritance - if isDir { - inheritance = inheritModeSubContainersAndObjectsInherit - } - - eaArray := []explicitAccess{ - explicitAccess{ - accessPermissions: accessMaskDesiredPermission, - accessMode: accessModeGrant, - inheritance: inheritance, - trustee: trustee{ - trusteeForm: trusteeFormIsSid, - trusteeType: trusteeTypeWellKnownGroup, - name: uintptr(unsafe.Pointer(sid)), - }, - }, - } - - modifiedDACL := uintptr(0) - if err := setEntriesInAcl(uintptr(uint32(1)), uintptr(unsafe.Pointer(&eaArray[0])), origDACL, &modifiedDACL); err != nil { - return 0, errors.Wrapf(err, "%s SetEntriesInAcl %s", gvmga, name) - } - - return modifiedDACL, nil -} diff --git a/vendor/github.com/Microsoft/go-winio/pkg/security/syscall_windows.go b/vendor/github.com/Microsoft/go-winio/pkg/security/syscall_windows.go deleted file mode 100644 index c40c2739..00000000 --- a/vendor/github.com/Microsoft/go-winio/pkg/security/syscall_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -package security - -//go:generate go run mksyscall_windows.go -output zsyscall_windows.go syscall_windows.go - -//sys getSecurityInfo(handle syscall.Handle, objectType uint32, si uint32, ppsidOwner **uintptr, ppsidGroup **uintptr, ppDacl *uintptr, ppSacl *uintptr, ppSecurityDescriptor *uintptr) (err error) [failretval!=0] = advapi32.GetSecurityInfo -//sys setSecurityInfo(handle syscall.Handle, objectType uint32, si uint32, psidOwner uintptr, psidGroup uintptr, pDacl uintptr, pSacl uintptr) (err error) [failretval!=0] = advapi32.SetSecurityInfo -//sys setEntriesInAcl(count uintptr, pListOfEEs uintptr, oldAcl uintptr, newAcl *uintptr) (err error) [failretval!=0] = advapi32.SetEntriesInAclW diff --git a/vendor/github.com/Microsoft/go-winio/pkg/security/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/pkg/security/zsyscall_windows.go deleted file mode 100644 index 4a90cb3c..00000000 --- a/vendor/github.com/Microsoft/go-winio/pkg/security/zsyscall_windows.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by 'go generate'; DO NOT EDIT. - -package security - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) - errERROR_EINVAL error = syscall.EINVAL -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return errERROR_EINVAL - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") - - procGetSecurityInfo = modadvapi32.NewProc("GetSecurityInfo") - procSetEntriesInAclW = modadvapi32.NewProc("SetEntriesInAclW") - procSetSecurityInfo = modadvapi32.NewProc("SetSecurityInfo") -) - -func getSecurityInfo(handle syscall.Handle, objectType uint32, si uint32, ppsidOwner **uintptr, ppsidGroup **uintptr, ppDacl *uintptr, ppSacl *uintptr, ppSecurityDescriptor *uintptr) (err error) { - r1, _, e1 := syscall.Syscall9(procGetSecurityInfo.Addr(), 8, uintptr(handle), uintptr(objectType), uintptr(si), uintptr(unsafe.Pointer(ppsidOwner)), uintptr(unsafe.Pointer(ppsidGroup)), uintptr(unsafe.Pointer(ppDacl)), uintptr(unsafe.Pointer(ppSacl)), uintptr(unsafe.Pointer(ppSecurityDescriptor)), 0) - if r1 != 0 { - err = errnoErr(e1) - } - return -} - -func setEntriesInAcl(count uintptr, pListOfEEs uintptr, oldAcl uintptr, newAcl *uintptr) (err error) { - r1, _, e1 := syscall.Syscall6(procSetEntriesInAclW.Addr(), 4, uintptr(count), uintptr(pListOfEEs), uintptr(oldAcl), uintptr(unsafe.Pointer(newAcl)), 0, 0) - if r1 != 0 { - err = errnoErr(e1) - } - return -} - -func setSecurityInfo(handle syscall.Handle, objectType uint32, si uint32, psidOwner uintptr, psidGroup uintptr, pDacl uintptr, pSacl uintptr) (err error) { - r1, _, e1 := syscall.Syscall9(procSetSecurityInfo.Addr(), 7, uintptr(handle), uintptr(objectType), uintptr(si), uintptr(psidOwner), uintptr(psidGroup), uintptr(pDacl), uintptr(pSacl), 0, 0) - if r1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/Microsoft/go-winio/privilege.go b/vendor/github.com/Microsoft/go-winio/privilege.go deleted file mode 100644 index 9c83d36f..00000000 --- a/vendor/github.com/Microsoft/go-winio/privilege.go +++ /dev/null @@ -1,202 +0,0 @@ -// +build windows - -package winio - -import ( - "bytes" - "encoding/binary" - "fmt" - "runtime" - "sync" - "syscall" - "unicode/utf16" - - "golang.org/x/sys/windows" -) - -//sys adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) [true] = advapi32.AdjustTokenPrivileges -//sys impersonateSelf(level uint32) (err error) = advapi32.ImpersonateSelf -//sys revertToSelf() (err error) = advapi32.RevertToSelf -//sys openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) = advapi32.OpenThreadToken -//sys getCurrentThread() (h syscall.Handle) = GetCurrentThread -//sys lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) = advapi32.LookupPrivilegeValueW -//sys lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW -//sys lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) = advapi32.LookupPrivilegeDisplayNameW - -const ( - SE_PRIVILEGE_ENABLED = 2 - - ERROR_NOT_ALL_ASSIGNED syscall.Errno = 1300 - - SeBackupPrivilege = "SeBackupPrivilege" - SeRestorePrivilege = "SeRestorePrivilege" -) - -const ( - securityAnonymous = iota - securityIdentification - securityImpersonation - securityDelegation -) - -var ( - privNames = make(map[string]uint64) - privNameMutex sync.Mutex -) - -// PrivilegeError represents an error enabling privileges. -type PrivilegeError struct { - privileges []uint64 -} - -func (e *PrivilegeError) Error() string { - s := "" - if len(e.privileges) > 1 { - s = "Could not enable privileges " - } else { - s = "Could not enable privilege " - } - for i, p := range e.privileges { - if i != 0 { - s += ", " - } - s += `"` - s += getPrivilegeName(p) - s += `"` - } - return s -} - -// RunWithPrivilege enables a single privilege for a function call. -func RunWithPrivilege(name string, fn func() error) error { - return RunWithPrivileges([]string{name}, fn) -} - -// RunWithPrivileges enables privileges for a function call. -func RunWithPrivileges(names []string, fn func() error) error { - privileges, err := mapPrivileges(names) - if err != nil { - return err - } - runtime.LockOSThread() - defer runtime.UnlockOSThread() - token, err := newThreadToken() - if err != nil { - return err - } - defer releaseThreadToken(token) - err = adjustPrivileges(token, privileges, SE_PRIVILEGE_ENABLED) - if err != nil { - return err - } - return fn() -} - -func mapPrivileges(names []string) ([]uint64, error) { - var privileges []uint64 - privNameMutex.Lock() - defer privNameMutex.Unlock() - for _, name := range names { - p, ok := privNames[name] - if !ok { - err := lookupPrivilegeValue("", name, &p) - if err != nil { - return nil, err - } - privNames[name] = p - } - privileges = append(privileges, p) - } - return privileges, nil -} - -// EnableProcessPrivileges enables privileges globally for the process. -func EnableProcessPrivileges(names []string) error { - return enableDisableProcessPrivilege(names, SE_PRIVILEGE_ENABLED) -} - -// DisableProcessPrivileges disables privileges globally for the process. -func DisableProcessPrivileges(names []string) error { - return enableDisableProcessPrivilege(names, 0) -} - -func enableDisableProcessPrivilege(names []string, action uint32) error { - privileges, err := mapPrivileges(names) - if err != nil { - return err - } - - p, _ := windows.GetCurrentProcess() - var token windows.Token - err = windows.OpenProcessToken(p, windows.TOKEN_ADJUST_PRIVILEGES|windows.TOKEN_QUERY, &token) - if err != nil { - return err - } - - defer token.Close() - return adjustPrivileges(token, privileges, action) -} - -func adjustPrivileges(token windows.Token, privileges []uint64, action uint32) error { - var b bytes.Buffer - binary.Write(&b, binary.LittleEndian, uint32(len(privileges))) - for _, p := range privileges { - binary.Write(&b, binary.LittleEndian, p) - binary.Write(&b, binary.LittleEndian, action) - } - prevState := make([]byte, b.Len()) - reqSize := uint32(0) - success, err := adjustTokenPrivileges(token, false, &b.Bytes()[0], uint32(len(prevState)), &prevState[0], &reqSize) - if !success { - return err - } - if err == ERROR_NOT_ALL_ASSIGNED { - return &PrivilegeError{privileges} - } - return nil -} - -func getPrivilegeName(luid uint64) string { - var nameBuffer [256]uint16 - bufSize := uint32(len(nameBuffer)) - err := lookupPrivilegeName("", &luid, &nameBuffer[0], &bufSize) - if err != nil { - return fmt.Sprintf("", luid) - } - - var displayNameBuffer [256]uint16 - displayBufSize := uint32(len(displayNameBuffer)) - var langID uint32 - err = lookupPrivilegeDisplayName("", &nameBuffer[0], &displayNameBuffer[0], &displayBufSize, &langID) - if err != nil { - return fmt.Sprintf("", string(utf16.Decode(nameBuffer[:bufSize]))) - } - - return string(utf16.Decode(displayNameBuffer[:displayBufSize])) -} - -func newThreadToken() (windows.Token, error) { - err := impersonateSelf(securityImpersonation) - if err != nil { - return 0, err - } - - var token windows.Token - err = openThreadToken(getCurrentThread(), syscall.TOKEN_ADJUST_PRIVILEGES|syscall.TOKEN_QUERY, false, &token) - if err != nil { - rerr := revertToSelf() - if rerr != nil { - panic(rerr) - } - return 0, err - } - return token, nil -} - -func releaseThreadToken(h windows.Token) { - err := revertToSelf() - if err != nil { - panic(err) - } - h.Close() -} diff --git a/vendor/github.com/Microsoft/go-winio/reparse.go b/vendor/github.com/Microsoft/go-winio/reparse.go deleted file mode 100644 index fc1ee4d3..00000000 --- a/vendor/github.com/Microsoft/go-winio/reparse.go +++ /dev/null @@ -1,128 +0,0 @@ -package winio - -import ( - "bytes" - "encoding/binary" - "fmt" - "strings" - "unicode/utf16" - "unsafe" -) - -const ( - reparseTagMountPoint = 0xA0000003 - reparseTagSymlink = 0xA000000C -) - -type reparseDataBuffer struct { - ReparseTag uint32 - ReparseDataLength uint16 - Reserved uint16 - SubstituteNameOffset uint16 - SubstituteNameLength uint16 - PrintNameOffset uint16 - PrintNameLength uint16 -} - -// ReparsePoint describes a Win32 symlink or mount point. -type ReparsePoint struct { - Target string - IsMountPoint bool -} - -// UnsupportedReparsePointError is returned when trying to decode a non-symlink or -// mount point reparse point. -type UnsupportedReparsePointError struct { - Tag uint32 -} - -func (e *UnsupportedReparsePointError) Error() string { - return fmt.Sprintf("unsupported reparse point %x", e.Tag) -} - -// DecodeReparsePoint decodes a Win32 REPARSE_DATA_BUFFER structure containing either a symlink -// or a mount point. -func DecodeReparsePoint(b []byte) (*ReparsePoint, error) { - tag := binary.LittleEndian.Uint32(b[0:4]) - return DecodeReparsePointData(tag, b[8:]) -} - -func DecodeReparsePointData(tag uint32, b []byte) (*ReparsePoint, error) { - isMountPoint := false - switch tag { - case reparseTagMountPoint: - isMountPoint = true - case reparseTagSymlink: - default: - return nil, &UnsupportedReparsePointError{tag} - } - nameOffset := 8 + binary.LittleEndian.Uint16(b[4:6]) - if !isMountPoint { - nameOffset += 4 - } - nameLength := binary.LittleEndian.Uint16(b[6:8]) - name := make([]uint16, nameLength/2) - err := binary.Read(bytes.NewReader(b[nameOffset:nameOffset+nameLength]), binary.LittleEndian, &name) - if err != nil { - return nil, err - } - return &ReparsePoint{string(utf16.Decode(name)), isMountPoint}, nil -} - -func isDriveLetter(c byte) bool { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') -} - -// EncodeReparsePoint encodes a Win32 REPARSE_DATA_BUFFER structure describing a symlink or -// mount point. -func EncodeReparsePoint(rp *ReparsePoint) []byte { - // Generate an NT path and determine if this is a relative path. - var ntTarget string - relative := false - if strings.HasPrefix(rp.Target, `\\?\`) { - ntTarget = `\??\` + rp.Target[4:] - } else if strings.HasPrefix(rp.Target, `\\`) { - ntTarget = `\??\UNC\` + rp.Target[2:] - } else if len(rp.Target) >= 2 && isDriveLetter(rp.Target[0]) && rp.Target[1] == ':' { - ntTarget = `\??\` + rp.Target - } else { - ntTarget = rp.Target - relative = true - } - - // The paths must be NUL-terminated even though they are counted strings. - target16 := utf16.Encode([]rune(rp.Target + "\x00")) - ntTarget16 := utf16.Encode([]rune(ntTarget + "\x00")) - - size := int(unsafe.Sizeof(reparseDataBuffer{})) - 8 - size += len(ntTarget16)*2 + len(target16)*2 - - tag := uint32(reparseTagMountPoint) - if !rp.IsMountPoint { - tag = reparseTagSymlink - size += 4 // Add room for symlink flags - } - - data := reparseDataBuffer{ - ReparseTag: tag, - ReparseDataLength: uint16(size), - SubstituteNameOffset: 0, - SubstituteNameLength: uint16((len(ntTarget16) - 1) * 2), - PrintNameOffset: uint16(len(ntTarget16) * 2), - PrintNameLength: uint16((len(target16) - 1) * 2), - } - - var b bytes.Buffer - binary.Write(&b, binary.LittleEndian, &data) - if !rp.IsMountPoint { - flags := uint32(0) - if relative { - flags |= 1 - } - binary.Write(&b, binary.LittleEndian, flags) - } - - binary.Write(&b, binary.LittleEndian, ntTarget16) - binary.Write(&b, binary.LittleEndian, target16) - return b.Bytes() -} diff --git a/vendor/github.com/Microsoft/go-winio/sd.go b/vendor/github.com/Microsoft/go-winio/sd.go deleted file mode 100644 index db1b370a..00000000 --- a/vendor/github.com/Microsoft/go-winio/sd.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build windows - -package winio - -import ( - "syscall" - "unsafe" -) - -//sys lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountNameW -//sys convertSidToStringSid(sid *byte, str **uint16) (err error) = advapi32.ConvertSidToStringSidW -//sys convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW -//sys convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) = advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW -//sys localFree(mem uintptr) = LocalFree -//sys getSecurityDescriptorLength(sd uintptr) (len uint32) = advapi32.GetSecurityDescriptorLength - -const ( - cERROR_NONE_MAPPED = syscall.Errno(1332) -) - -type AccountLookupError struct { - Name string - Err error -} - -func (e *AccountLookupError) Error() string { - if e.Name == "" { - return "lookup account: empty account name specified" - } - var s string - switch e.Err { - case cERROR_NONE_MAPPED: - s = "not found" - default: - s = e.Err.Error() - } - return "lookup account " + e.Name + ": " + s -} - -type SddlConversionError struct { - Sddl string - Err error -} - -func (e *SddlConversionError) Error() string { - return "convert " + e.Sddl + ": " + e.Err.Error() -} - -// LookupSidByName looks up the SID of an account by name -func LookupSidByName(name string) (sid string, err error) { - if name == "" { - return "", &AccountLookupError{name, cERROR_NONE_MAPPED} - } - - var sidSize, sidNameUse, refDomainSize uint32 - err = lookupAccountName(nil, name, nil, &sidSize, nil, &refDomainSize, &sidNameUse) - if err != nil && err != syscall.ERROR_INSUFFICIENT_BUFFER { - return "", &AccountLookupError{name, err} - } - sidBuffer := make([]byte, sidSize) - refDomainBuffer := make([]uint16, refDomainSize) - err = lookupAccountName(nil, name, &sidBuffer[0], &sidSize, &refDomainBuffer[0], &refDomainSize, &sidNameUse) - if err != nil { - return "", &AccountLookupError{name, err} - } - var strBuffer *uint16 - err = convertSidToStringSid(&sidBuffer[0], &strBuffer) - if err != nil { - return "", &AccountLookupError{name, err} - } - sid = syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(strBuffer))[:]) - localFree(uintptr(unsafe.Pointer(strBuffer))) - return sid, nil -} - -func SddlToSecurityDescriptor(sddl string) ([]byte, error) { - var sdBuffer uintptr - err := convertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, &sdBuffer, nil) - if err != nil { - return nil, &SddlConversionError{sddl, err} - } - defer localFree(sdBuffer) - sd := make([]byte, getSecurityDescriptorLength(sdBuffer)) - copy(sd, (*[0xffff]byte)(unsafe.Pointer(sdBuffer))[:len(sd)]) - return sd, nil -} - -func SecurityDescriptorToSddl(sd []byte) (string, error) { - var sddl *uint16 - // The returned string length seems to including an aribtrary number of terminating NULs. - // Don't use it. - err := convertSecurityDescriptorToStringSecurityDescriptor(&sd[0], 1, 0xff, &sddl, nil) - if err != nil { - return "", err - } - defer localFree(uintptr(unsafe.Pointer(sddl))) - return syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(sddl))[:]), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/syscall.go b/vendor/github.com/Microsoft/go-winio/syscall.go deleted file mode 100644 index 5955c99f..00000000 --- a/vendor/github.com/Microsoft/go-winio/syscall.go +++ /dev/null @@ -1,3 +0,0 @@ -package winio - -//go:generate go run golang.org/x/sys/windows/mkwinsyscall -output zsyscall_windows.go file.go pipe.go sd.go fileinfo.go privilege.go backup.go hvsock.go diff --git a/vendor/github.com/Microsoft/go-winio/vhd/vhd.go b/vendor/github.com/Microsoft/go-winio/vhd/vhd.go deleted file mode 100644 index b03b789e..00000000 --- a/vendor/github.com/Microsoft/go-winio/vhd/vhd.go +++ /dev/null @@ -1,323 +0,0 @@ -// +build windows - -package vhd - -import ( - "fmt" - "syscall" - - "github.com/Microsoft/go-winio/pkg/guid" - "github.com/pkg/errors" - "golang.org/x/sys/windows" -) - -//go:generate go run mksyscall_windows.go -output zvhd_windows.go vhd.go - -//sys createVirtualDisk(virtualStorageType *VirtualStorageType, path string, virtualDiskAccessMask uint32, securityDescriptor *uintptr, createVirtualDiskFlags uint32, providerSpecificFlags uint32, parameters *CreateVirtualDiskParameters, overlapped *syscall.Overlapped, handle *syscall.Handle) (err error) [failretval != 0] = virtdisk.CreateVirtualDisk -//sys openVirtualDisk(virtualStorageType *VirtualStorageType, path string, virtualDiskAccessMask uint32, openVirtualDiskFlags uint32, parameters *OpenVirtualDiskParameters, handle *syscall.Handle) (err error) [failretval != 0] = virtdisk.OpenVirtualDisk -//sys attachVirtualDisk(handle syscall.Handle, securityDescriptor *uintptr, attachVirtualDiskFlag uint32, providerSpecificFlags uint32, parameters *AttachVirtualDiskParameters, overlapped *syscall.Overlapped) (err error) [failretval != 0] = virtdisk.AttachVirtualDisk -//sys detachVirtualDisk(handle syscall.Handle, detachVirtualDiskFlags uint32, providerSpecificFlags uint32) (err error) [failretval != 0] = virtdisk.DetachVirtualDisk -//sys getVirtualDiskPhysicalPath(handle syscall.Handle, diskPathSizeInBytes *uint32, buffer *uint16) (err error) [failretval != 0] = virtdisk.GetVirtualDiskPhysicalPath - -type ( - CreateVirtualDiskFlag uint32 - VirtualDiskFlag uint32 - AttachVirtualDiskFlag uint32 - DetachVirtualDiskFlag uint32 - VirtualDiskAccessMask uint32 -) - -type VirtualStorageType struct { - DeviceID uint32 - VendorID guid.GUID -} - -type CreateVersion2 struct { - UniqueID guid.GUID - MaximumSize uint64 - BlockSizeInBytes uint32 - SectorSizeInBytes uint32 - PhysicalSectorSizeInByte uint32 - ParentPath *uint16 // string - SourcePath *uint16 // string - OpenFlags uint32 - ParentVirtualStorageType VirtualStorageType - SourceVirtualStorageType VirtualStorageType - ResiliencyGUID guid.GUID -} - -type CreateVirtualDiskParameters struct { - Version uint32 // Must always be set to 2 - Version2 CreateVersion2 -} - -type OpenVersion2 struct { - GetInfoOnly bool - ReadOnly bool - ResiliencyGUID guid.GUID -} - -type OpenVirtualDiskParameters struct { - Version uint32 // Must always be set to 2 - Version2 OpenVersion2 -} - -type AttachVersion2 struct { - RestrictedOffset uint64 - RestrictedLength uint64 -} - -type AttachVirtualDiskParameters struct { - Version uint32 // Must always be set to 2 - Version2 AttachVersion2 -} - -const ( - VIRTUAL_STORAGE_TYPE_DEVICE_VHDX = 0x3 - - // Access Mask for opening a VHD - VirtualDiskAccessNone VirtualDiskAccessMask = 0x00000000 - VirtualDiskAccessAttachRO VirtualDiskAccessMask = 0x00010000 - VirtualDiskAccessAttachRW VirtualDiskAccessMask = 0x00020000 - VirtualDiskAccessDetach VirtualDiskAccessMask = 0x00040000 - VirtualDiskAccessGetInfo VirtualDiskAccessMask = 0x00080000 - VirtualDiskAccessCreate VirtualDiskAccessMask = 0x00100000 - VirtualDiskAccessMetaOps VirtualDiskAccessMask = 0x00200000 - VirtualDiskAccessRead VirtualDiskAccessMask = 0x000d0000 - VirtualDiskAccessAll VirtualDiskAccessMask = 0x003f0000 - VirtualDiskAccessWritable VirtualDiskAccessMask = 0x00320000 - - // Flags for creating a VHD - CreateVirtualDiskFlagNone CreateVirtualDiskFlag = 0x0 - CreateVirtualDiskFlagFullPhysicalAllocation CreateVirtualDiskFlag = 0x1 - CreateVirtualDiskFlagPreventWritesToSourceDisk CreateVirtualDiskFlag = 0x2 - CreateVirtualDiskFlagDoNotCopyMetadataFromParent CreateVirtualDiskFlag = 0x4 - CreateVirtualDiskFlagCreateBackingStorage CreateVirtualDiskFlag = 0x8 - CreateVirtualDiskFlagUseChangeTrackingSourceLimit CreateVirtualDiskFlag = 0x10 - CreateVirtualDiskFlagPreserveParentChangeTrackingState CreateVirtualDiskFlag = 0x20 - CreateVirtualDiskFlagVhdSetUseOriginalBackingStorage CreateVirtualDiskFlag = 0x40 - CreateVirtualDiskFlagSparseFile CreateVirtualDiskFlag = 0x80 - CreateVirtualDiskFlagPmemCompatible CreateVirtualDiskFlag = 0x100 - CreateVirtualDiskFlagSupportCompressedVolumes CreateVirtualDiskFlag = 0x200 - - // Flags for opening a VHD - OpenVirtualDiskFlagNone VirtualDiskFlag = 0x00000000 - OpenVirtualDiskFlagNoParents VirtualDiskFlag = 0x00000001 - OpenVirtualDiskFlagBlankFile VirtualDiskFlag = 0x00000002 - OpenVirtualDiskFlagBootDrive VirtualDiskFlag = 0x00000004 - OpenVirtualDiskFlagCachedIO VirtualDiskFlag = 0x00000008 - OpenVirtualDiskFlagCustomDiffChain VirtualDiskFlag = 0x00000010 - OpenVirtualDiskFlagParentCachedIO VirtualDiskFlag = 0x00000020 - OpenVirtualDiskFlagVhdsetFileOnly VirtualDiskFlag = 0x00000040 - OpenVirtualDiskFlagIgnoreRelativeParentLocator VirtualDiskFlag = 0x00000080 - OpenVirtualDiskFlagNoWriteHardening VirtualDiskFlag = 0x00000100 - OpenVirtualDiskFlagSupportCompressedVolumes VirtualDiskFlag = 0x00000200 - - // Flags for attaching a VHD - AttachVirtualDiskFlagNone AttachVirtualDiskFlag = 0x00000000 - AttachVirtualDiskFlagReadOnly AttachVirtualDiskFlag = 0x00000001 - AttachVirtualDiskFlagNoDriveLetter AttachVirtualDiskFlag = 0x00000002 - AttachVirtualDiskFlagPermanentLifetime AttachVirtualDiskFlag = 0x00000004 - AttachVirtualDiskFlagNoLocalHost AttachVirtualDiskFlag = 0x00000008 - AttachVirtualDiskFlagNoSecurityDescriptor AttachVirtualDiskFlag = 0x00000010 - AttachVirtualDiskFlagBypassDefaultEncryptionPolicy AttachVirtualDiskFlag = 0x00000020 - AttachVirtualDiskFlagNonPnp AttachVirtualDiskFlag = 0x00000040 - AttachVirtualDiskFlagRestrictedRange AttachVirtualDiskFlag = 0x00000080 - AttachVirtualDiskFlagSinglePartition AttachVirtualDiskFlag = 0x00000100 - AttachVirtualDiskFlagRegisterVolume AttachVirtualDiskFlag = 0x00000200 - - // Flags for detaching a VHD - DetachVirtualDiskFlagNone DetachVirtualDiskFlag = 0x0 -) - -// CreateVhdx is a helper function to create a simple vhdx file at the given path using -// default values. -func CreateVhdx(path string, maxSizeInGb, blockSizeInMb uint32) error { - params := CreateVirtualDiskParameters{ - Version: 2, - Version2: CreateVersion2{ - MaximumSize: uint64(maxSizeInGb) * 1024 * 1024 * 1024, - BlockSizeInBytes: blockSizeInMb * 1024 * 1024, - }, - } - - handle, err := CreateVirtualDisk(path, VirtualDiskAccessNone, CreateVirtualDiskFlagNone, ¶ms) - if err != nil { - return err - } - - if err := syscall.CloseHandle(handle); err != nil { - return err - } - return nil -} - -// DetachVirtualDisk detaches a virtual hard disk by handle. -func DetachVirtualDisk(handle syscall.Handle) (err error) { - if err := detachVirtualDisk(handle, 0, 0); err != nil { - return errors.Wrap(err, "failed to detach virtual disk") - } - return nil -} - -// DetachVhd detaches a vhd found at `path`. -func DetachVhd(path string) error { - handle, err := OpenVirtualDisk( - path, - VirtualDiskAccessNone, - OpenVirtualDiskFlagCachedIO|OpenVirtualDiskFlagIgnoreRelativeParentLocator, - ) - if err != nil { - return err - } - defer syscall.CloseHandle(handle) - return DetachVirtualDisk(handle) -} - -// AttachVirtualDisk attaches a virtual hard disk for use. -func AttachVirtualDisk(handle syscall.Handle, attachVirtualDiskFlag AttachVirtualDiskFlag, parameters *AttachVirtualDiskParameters) (err error) { - // Supports both version 1 and 2 of the attach parameters as version 2 wasn't present in RS5. - if err := attachVirtualDisk( - handle, - nil, - uint32(attachVirtualDiskFlag), - 0, - parameters, - nil, - ); err != nil { - return errors.Wrap(err, "failed to attach virtual disk") - } - return nil -} - -// AttachVhd attaches a virtual hard disk at `path` for use. Attaches using version 2 -// of the ATTACH_VIRTUAL_DISK_PARAMETERS. -func AttachVhd(path string) (err error) { - handle, err := OpenVirtualDisk( - path, - VirtualDiskAccessNone, - OpenVirtualDiskFlagCachedIO|OpenVirtualDiskFlagIgnoreRelativeParentLocator, - ) - if err != nil { - return err - } - - defer syscall.CloseHandle(handle) - params := AttachVirtualDiskParameters{Version: 2} - if err := AttachVirtualDisk( - handle, - AttachVirtualDiskFlagNone, - ¶ms, - ); err != nil { - return errors.Wrap(err, "failed to attach virtual disk") - } - return nil -} - -// OpenVirtualDisk obtains a handle to a VHD opened with supplied access mask and flags. -func OpenVirtualDisk(vhdPath string, virtualDiskAccessMask VirtualDiskAccessMask, openVirtualDiskFlags VirtualDiskFlag) (syscall.Handle, error) { - parameters := OpenVirtualDiskParameters{Version: 2} - handle, err := OpenVirtualDiskWithParameters( - vhdPath, - virtualDiskAccessMask, - openVirtualDiskFlags, - ¶meters, - ) - if err != nil { - return 0, err - } - return handle, nil -} - -// OpenVirtualDiskWithParameters obtains a handle to a VHD opened with supplied access mask, flags and parameters. -func OpenVirtualDiskWithParameters(vhdPath string, virtualDiskAccessMask VirtualDiskAccessMask, openVirtualDiskFlags VirtualDiskFlag, parameters *OpenVirtualDiskParameters) (syscall.Handle, error) { - var ( - handle syscall.Handle - defaultType VirtualStorageType - ) - if parameters.Version != 2 { - return handle, fmt.Errorf("only version 2 VHDs are supported, found version: %d", parameters.Version) - } - if err := openVirtualDisk( - &defaultType, - vhdPath, - uint32(virtualDiskAccessMask), - uint32(openVirtualDiskFlags), - parameters, - &handle, - ); err != nil { - return 0, errors.Wrap(err, "failed to open virtual disk") - } - return handle, nil -} - -// CreateVirtualDisk creates a virtual harddisk and returns a handle to the disk. -func CreateVirtualDisk(path string, virtualDiskAccessMask VirtualDiskAccessMask, createVirtualDiskFlags CreateVirtualDiskFlag, parameters *CreateVirtualDiskParameters) (syscall.Handle, error) { - var ( - handle syscall.Handle - defaultType VirtualStorageType - ) - if parameters.Version != 2 { - return handle, fmt.Errorf("only version 2 VHDs are supported, found version: %d", parameters.Version) - } - - if err := createVirtualDisk( - &defaultType, - path, - uint32(virtualDiskAccessMask), - nil, - uint32(createVirtualDiskFlags), - 0, - parameters, - nil, - &handle, - ); err != nil { - return handle, errors.Wrap(err, "failed to create virtual disk") - } - return handle, nil -} - -// GetVirtualDiskPhysicalPath takes a handle to a virtual hard disk and returns the physical -// path of the disk on the machine. This path is in the form \\.\PhysicalDriveX where X is an integer -// that represents the particular enumeration of the physical disk on the caller's system. -func GetVirtualDiskPhysicalPath(handle syscall.Handle) (_ string, err error) { - var ( - diskPathSizeInBytes uint32 = 256 * 2 // max path length 256 wide chars - diskPhysicalPathBuf [256]uint16 - ) - if err := getVirtualDiskPhysicalPath( - handle, - &diskPathSizeInBytes, - &diskPhysicalPathBuf[0], - ); err != nil { - return "", errors.Wrap(err, "failed to get disk physical path") - } - return windows.UTF16ToString(diskPhysicalPathBuf[:]), nil -} - -// CreateDiffVhd is a helper function to create a differencing virtual disk. -func CreateDiffVhd(diffVhdPath, baseVhdPath string, blockSizeInMB uint32) error { - // Setting `ParentPath` is how to signal to create a differencing disk. - createParams := &CreateVirtualDiskParameters{ - Version: 2, - Version2: CreateVersion2{ - ParentPath: windows.StringToUTF16Ptr(baseVhdPath), - BlockSizeInBytes: blockSizeInMB * 1024 * 1024, - OpenFlags: uint32(OpenVirtualDiskFlagCachedIO), - }, - } - - vhdHandle, err := CreateVirtualDisk( - diffVhdPath, - VirtualDiskAccessNone, - CreateVirtualDiskFlagNone, - createParams, - ) - if err != nil { - return fmt.Errorf("failed to create differencing vhd: %s", err) - } - if err := syscall.CloseHandle(vhdHandle); err != nil { - return fmt.Errorf("failed to close differencing vhd handle: %s", err) - } - return nil -} diff --git a/vendor/github.com/Microsoft/go-winio/vhd/zvhd_windows.go b/vendor/github.com/Microsoft/go-winio/vhd/zvhd_windows.go deleted file mode 100644 index 572f7b42..00000000 --- a/vendor/github.com/Microsoft/go-winio/vhd/zvhd_windows.go +++ /dev/null @@ -1,106 +0,0 @@ -// Code generated by 'go generate'; DO NOT EDIT. - -package vhd - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) - errERROR_EINVAL error = syscall.EINVAL -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return errERROR_EINVAL - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modvirtdisk = windows.NewLazySystemDLL("virtdisk.dll") - - procAttachVirtualDisk = modvirtdisk.NewProc("AttachVirtualDisk") - procCreateVirtualDisk = modvirtdisk.NewProc("CreateVirtualDisk") - procDetachVirtualDisk = modvirtdisk.NewProc("DetachVirtualDisk") - procGetVirtualDiskPhysicalPath = modvirtdisk.NewProc("GetVirtualDiskPhysicalPath") - procOpenVirtualDisk = modvirtdisk.NewProc("OpenVirtualDisk") -) - -func attachVirtualDisk(handle syscall.Handle, securityDescriptor *uintptr, attachVirtualDiskFlag uint32, providerSpecificFlags uint32, parameters *AttachVirtualDiskParameters, overlapped *syscall.Overlapped) (err error) { - r1, _, e1 := syscall.Syscall6(procAttachVirtualDisk.Addr(), 6, uintptr(handle), uintptr(unsafe.Pointer(securityDescriptor)), uintptr(attachVirtualDiskFlag), uintptr(providerSpecificFlags), uintptr(unsafe.Pointer(parameters)), uintptr(unsafe.Pointer(overlapped))) - if r1 != 0 { - err = errnoErr(e1) - } - return -} - -func createVirtualDisk(virtualStorageType *VirtualStorageType, path string, virtualDiskAccessMask uint32, securityDescriptor *uintptr, createVirtualDiskFlags uint32, providerSpecificFlags uint32, parameters *CreateVirtualDiskParameters, overlapped *syscall.Overlapped, handle *syscall.Handle) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(path) - if err != nil { - return - } - return _createVirtualDisk(virtualStorageType, _p0, virtualDiskAccessMask, securityDescriptor, createVirtualDiskFlags, providerSpecificFlags, parameters, overlapped, handle) -} - -func _createVirtualDisk(virtualStorageType *VirtualStorageType, path *uint16, virtualDiskAccessMask uint32, securityDescriptor *uintptr, createVirtualDiskFlags uint32, providerSpecificFlags uint32, parameters *CreateVirtualDiskParameters, overlapped *syscall.Overlapped, handle *syscall.Handle) (err error) { - r1, _, e1 := syscall.Syscall9(procCreateVirtualDisk.Addr(), 9, uintptr(unsafe.Pointer(virtualStorageType)), uintptr(unsafe.Pointer(path)), uintptr(virtualDiskAccessMask), uintptr(unsafe.Pointer(securityDescriptor)), uintptr(createVirtualDiskFlags), uintptr(providerSpecificFlags), uintptr(unsafe.Pointer(parameters)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(handle))) - if r1 != 0 { - err = errnoErr(e1) - } - return -} - -func detachVirtualDisk(handle syscall.Handle, detachVirtualDiskFlags uint32, providerSpecificFlags uint32) (err error) { - r1, _, e1 := syscall.Syscall(procDetachVirtualDisk.Addr(), 3, uintptr(handle), uintptr(detachVirtualDiskFlags), uintptr(providerSpecificFlags)) - if r1 != 0 { - err = errnoErr(e1) - } - return -} - -func getVirtualDiskPhysicalPath(handle syscall.Handle, diskPathSizeInBytes *uint32, buffer *uint16) (err error) { - r1, _, e1 := syscall.Syscall(procGetVirtualDiskPhysicalPath.Addr(), 3, uintptr(handle), uintptr(unsafe.Pointer(diskPathSizeInBytes)), uintptr(unsafe.Pointer(buffer))) - if r1 != 0 { - err = errnoErr(e1) - } - return -} - -func openVirtualDisk(virtualStorageType *VirtualStorageType, path string, virtualDiskAccessMask uint32, openVirtualDiskFlags uint32, parameters *OpenVirtualDiskParameters, handle *syscall.Handle) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(path) - if err != nil { - return - } - return _openVirtualDisk(virtualStorageType, _p0, virtualDiskAccessMask, openVirtualDiskFlags, parameters, handle) -} - -func _openVirtualDisk(virtualStorageType *VirtualStorageType, path *uint16, virtualDiskAccessMask uint32, openVirtualDiskFlags uint32, parameters *OpenVirtualDiskParameters, handle *syscall.Handle) (err error) { - r1, _, e1 := syscall.Syscall6(procOpenVirtualDisk.Addr(), 6, uintptr(unsafe.Pointer(virtualStorageType)), uintptr(unsafe.Pointer(path)), uintptr(virtualDiskAccessMask), uintptr(openVirtualDiskFlags), uintptr(unsafe.Pointer(parameters)), uintptr(unsafe.Pointer(handle))) - if r1 != 0 { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go deleted file mode 100644 index 176ff75e..00000000 --- a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go +++ /dev/null @@ -1,427 +0,0 @@ -// Code generated by 'go generate'; DO NOT EDIT. - -package winio - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) - errERROR_EINVAL error = syscall.EINVAL -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return errERROR_EINVAL - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") - modkernel32 = windows.NewLazySystemDLL("kernel32.dll") - modntdll = windows.NewLazySystemDLL("ntdll.dll") - modws2_32 = windows.NewLazySystemDLL("ws2_32.dll") - - procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges") - procConvertSecurityDescriptorToStringSecurityDescriptorW = modadvapi32.NewProc("ConvertSecurityDescriptorToStringSecurityDescriptorW") - procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW") - procConvertStringSecurityDescriptorToSecurityDescriptorW = modadvapi32.NewProc("ConvertStringSecurityDescriptorToSecurityDescriptorW") - procGetSecurityDescriptorLength = modadvapi32.NewProc("GetSecurityDescriptorLength") - procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf") - procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW") - procLookupPrivilegeDisplayNameW = modadvapi32.NewProc("LookupPrivilegeDisplayNameW") - procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW") - procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW") - procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken") - procRevertToSelf = modadvapi32.NewProc("RevertToSelf") - procBackupRead = modkernel32.NewProc("BackupRead") - procBackupWrite = modkernel32.NewProc("BackupWrite") - procCancelIoEx = modkernel32.NewProc("CancelIoEx") - procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") - procCreateFileW = modkernel32.NewProc("CreateFileW") - procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort") - procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") - procGetCurrentThread = modkernel32.NewProc("GetCurrentThread") - procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW") - procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo") - procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus") - procLocalAlloc = modkernel32.NewProc("LocalAlloc") - procLocalFree = modkernel32.NewProc("LocalFree") - procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes") - procNtCreateNamedPipeFile = modntdll.NewProc("NtCreateNamedPipeFile") - procRtlDefaultNpAcl = modntdll.NewProc("RtlDefaultNpAcl") - procRtlDosPathNameToNtPathName_U = modntdll.NewProc("RtlDosPathNameToNtPathName_U") - procRtlNtStatusToDosErrorNoTeb = modntdll.NewProc("RtlNtStatusToDosErrorNoTeb") - procWSAGetOverlappedResult = modws2_32.NewProc("WSAGetOverlappedResult") - procbind = modws2_32.NewProc("bind") -) - -func adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) { - var _p0 uint32 - if releaseAll { - _p0 = 1 - } - r0, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6, uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(input)), uintptr(outputSize), uintptr(unsafe.Pointer(output)), uintptr(unsafe.Pointer(requiredSize))) - success = r0 != 0 - if true { - err = errnoErr(e1) - } - return -} - -func convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procConvertSecurityDescriptorToStringSecurityDescriptorW.Addr(), 5, uintptr(unsafe.Pointer(sd)), uintptr(revision), uintptr(secInfo), uintptr(unsafe.Pointer(sddl)), uintptr(unsafe.Pointer(sddlSize)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func convertSidToStringSid(sid *byte, str **uint16) (err error) { - r1, _, e1 := syscall.Syscall(procConvertSidToStringSidW.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(str)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(str) - if err != nil { - return - } - return _convertStringSecurityDescriptorToSecurityDescriptor(_p0, revision, sd, size) -} - -func _convertStringSecurityDescriptorToSecurityDescriptor(str *uint16, revision uint32, sd *uintptr, size *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procConvertStringSecurityDescriptorToSecurityDescriptorW.Addr(), 4, uintptr(unsafe.Pointer(str)), uintptr(revision), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(size)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func getSecurityDescriptorLength(sd uintptr) (len uint32) { - r0, _, _ := syscall.Syscall(procGetSecurityDescriptorLength.Addr(), 1, uintptr(sd), 0, 0) - len = uint32(r0) - return -} - -func impersonateSelf(level uint32) (err error) { - r1, _, e1 := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(level), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(accountName) - if err != nil { - return - } - return _lookupAccountName(systemName, _p0, sid, sidSize, refDomain, refDomainSize, sidNameUse) -} - -func _lookupAccountName(systemName *uint16, accountName *uint16, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procLookupAccountNameW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidSize)), uintptr(unsafe.Pointer(refDomain)), uintptr(unsafe.Pointer(refDomainSize)), uintptr(unsafe.Pointer(sidNameUse)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - return _lookupPrivilegeDisplayName(_p0, name, buffer, size, languageId) -} - -func _lookupPrivilegeDisplayName(systemName *uint16, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procLookupPrivilegeDisplayNameW.Addr(), 5, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), uintptr(unsafe.Pointer(languageId)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - return _lookupPrivilegeName(_p0, luid, buffer, size) -} - -func _lookupPrivilegeName(systemName *uint16, luid *uint64, buffer *uint16, size *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procLookupPrivilegeNameW.Addr(), 4, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(luid)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - var _p1 *uint16 - _p1, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _lookupPrivilegeValue(_p0, _p1, luid) -} - -func _lookupPrivilegeValue(systemName *uint16, name *uint16, luid *uint64) (err error) { - r1, _, e1 := syscall.Syscall(procLookupPrivilegeValueW.Addr(), 3, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid))) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) { - var _p0 uint32 - if openAsSelf { - _p0 = 1 - } - r1, _, e1 := syscall.Syscall6(procOpenThreadToken.Addr(), 4, uintptr(thread), uintptr(accessMask), uintptr(_p0), uintptr(unsafe.Pointer(token)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func revertToSelf() (err error) { - r1, _, e1 := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - var _p1 uint32 - if abort { - _p1 = 1 - } - var _p2 uint32 - if processSecurity { - _p2 = 1 - } - r1, _, e1 := syscall.Syscall9(procBackupRead.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesRead)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - var _p1 uint32 - if abort { - _p1 = 1 - } - var _p2 uint32 - if processSecurity { - _p2 = 1 - } - r1, _, e1 := syscall.Syscall9(procBackupWrite.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesWritten)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) { - r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(file), uintptr(unsafe.Pointer(o)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) { - r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(o)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _createFile(_p0, access, mode, sa, createmode, attrs, templatefile) -} - -func _createFile(name *uint16, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - err = errnoErr(e1) - } - return -} - -func createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall6(procCreateIoCompletionPort.Addr(), 4, uintptr(file), uintptr(port), uintptr(key), uintptr(threadCount), 0, 0) - newport = syscall.Handle(r0) - if newport == 0 { - err = errnoErr(e1) - } - return -} - -func createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _createNamedPipe(_p0, flags, pipeMode, maxInstances, outSize, inSize, defaultTimeout, sa) -} - -func _createNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(pipeMode), uintptr(maxInstances), uintptr(outSize), uintptr(inSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - err = errnoErr(e1) - } - return -} - -func getCurrentThread() (h syscall.Handle) { - r0, _, _ := syscall.Syscall(procGetCurrentThread.Addr(), 0, 0, 0, 0) - h = syscall.Handle(r0) - return -} - -func getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procGetNamedPipeHandleStateW.Addr(), 7, uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(curInstances)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), uintptr(unsafe.Pointer(userName)), uintptr(maxUserNameSize), 0, 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetNamedPipeInfo.Addr(), 5, uintptr(pipe), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(outSize)), uintptr(unsafe.Pointer(inSize)), uintptr(unsafe.Pointer(maxInstances)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetQueuedCompletionStatus.Addr(), 5, uintptr(port), uintptr(unsafe.Pointer(bytes)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(o)), uintptr(timeout), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func localAlloc(uFlags uint32, length uint32) (ptr uintptr) { - r0, _, _ := syscall.Syscall(procLocalAlloc.Addr(), 2, uintptr(uFlags), uintptr(length), 0) - ptr = uintptr(r0) - return -} - -func localFree(mem uintptr) { - syscall.Syscall(procLocalFree.Addr(), 1, uintptr(mem), 0, 0) - return -} - -func setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) { - r1, _, e1 := syscall.Syscall(procSetFileCompletionNotificationModes.Addr(), 2, uintptr(h), uintptr(flags), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func ntCreateNamedPipeFile(pipe *syscall.Handle, access uint32, oa *objectAttributes, iosb *ioStatusBlock, share uint32, disposition uint32, options uint32, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (status ntstatus) { - r0, _, _ := syscall.Syscall15(procNtCreateNamedPipeFile.Addr(), 14, uintptr(unsafe.Pointer(pipe)), uintptr(access), uintptr(unsafe.Pointer(oa)), uintptr(unsafe.Pointer(iosb)), uintptr(share), uintptr(disposition), uintptr(options), uintptr(typ), uintptr(readMode), uintptr(completionMode), uintptr(maxInstances), uintptr(inboundQuota), uintptr(outputQuota), uintptr(unsafe.Pointer(timeout)), 0) - status = ntstatus(r0) - return -} - -func rtlDefaultNpAcl(dacl *uintptr) (status ntstatus) { - r0, _, _ := syscall.Syscall(procRtlDefaultNpAcl.Addr(), 1, uintptr(unsafe.Pointer(dacl)), 0, 0) - status = ntstatus(r0) - return -} - -func rtlDosPathNameToNtPathName(name *uint16, ntName *unicodeString, filePart uintptr, reserved uintptr) (status ntstatus) { - r0, _, _ := syscall.Syscall6(procRtlDosPathNameToNtPathName_U.Addr(), 4, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(ntName)), uintptr(filePart), uintptr(reserved), 0, 0) - status = ntstatus(r0) - return -} - -func rtlNtStatusToDosError(status ntstatus) (winerr error) { - r0, _, _ := syscall.Syscall(procRtlNtStatusToDosErrorNoTeb.Addr(), 1, uintptr(status), 0, 0) - if r0 != 0 { - winerr = syscall.Errno(r0) - } - return -} - -func wsaGetOverlappedResult(h syscall.Handle, o *syscall.Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) { - var _p0 uint32 - if wait { - _p0 = 1 - } - r1, _, e1 := syscall.Syscall6(procWSAGetOverlappedResult.Addr(), 5, uintptr(h), uintptr(unsafe.Pointer(o)), uintptr(unsafe.Pointer(bytes)), uintptr(_p0), uintptr(unsafe.Pointer(flags)), 0) - if r1 == 0 { - err = errnoErr(e1) - } - return -} - -func bind(s syscall.Handle, name unsafe.Pointer, namelen int32) (err error) { - r1, _, e1 := syscall.Syscall(procbind.Addr(), 3, uintptr(s), uintptr(name), uintptr(namelen)) - if r1 == socketError { - err = errnoErr(e1) - } - return -} diff --git a/vendor/github.com/Microsoft/hcsshim/.gitattributes b/vendor/github.com/Microsoft/hcsshim/.gitattributes deleted file mode 100644 index 94f480de..00000000 --- a/vendor/github.com/Microsoft/hcsshim/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -* text=auto eol=lf \ No newline at end of file diff --git a/vendor/github.com/Microsoft/hcsshim/.gitignore b/vendor/github.com/Microsoft/hcsshim/.gitignore deleted file mode 100644 index aec9bd4b..00000000 --- a/vendor/github.com/Microsoft/hcsshim/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*.exe -.idea -.vscode diff --git a/vendor/github.com/Microsoft/hcsshim/.gometalinter.json b/vendor/github.com/Microsoft/hcsshim/.gometalinter.json deleted file mode 100644 index 00e9a6e2..00000000 --- a/vendor/github.com/Microsoft/hcsshim/.gometalinter.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "Vendor": true, - "Deadline": "2m", - "Sort": [ - "linter", - "severity", - "path", - "line" - ], - "Skip": [ - "internal\\schema2" - ], - "EnableGC": true, - "Enable": [ - "gofmt" - ] -} \ No newline at end of file diff --git a/vendor/github.com/Microsoft/hcsshim/CODEOWNERS b/vendor/github.com/Microsoft/hcsshim/CODEOWNERS deleted file mode 100644 index 87f49df3..00000000 --- a/vendor/github.com/Microsoft/hcsshim/CODEOWNERS +++ /dev/null @@ -1,3 +0,0 @@ -* @microsoft/containerplat - -/hcn/* @nagiesek \ No newline at end of file diff --git a/vendor/github.com/Microsoft/hcsshim/LICENSE b/vendor/github.com/Microsoft/hcsshim/LICENSE deleted file mode 100644 index 49d21669..00000000 --- a/vendor/github.com/Microsoft/hcsshim/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Microsoft - -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. \ No newline at end of file diff --git a/vendor/github.com/Microsoft/hcsshim/Protobuild.toml b/vendor/github.com/Microsoft/hcsshim/Protobuild.toml deleted file mode 100644 index 47d7650f..00000000 --- a/vendor/github.com/Microsoft/hcsshim/Protobuild.toml +++ /dev/null @@ -1,54 +0,0 @@ -version = "unstable" -generator = "gogoctrd" -plugins = ["grpc", "fieldpath"] - -# Control protoc include paths. Below are usually some good defaults, but feel -# free to try it without them if it works for your project. -[includes] - # Include paths that will be added before all others. Typically, you want to - # treat the root of the project as an include, but this may not be necessary. - before = ["./protobuf"] - - # Paths that should be treated as include roots in relation to the vendor - # directory. These will be calculated with the vendor directory nearest the - # target package. - packages = ["github.com/gogo/protobuf"] - - # Paths that will be added untouched to the end of the includes. We use - # `/usr/local/include` to pickup the common install location of protobuf. - # This is the default. - after = ["/usr/local/include"] - -# This section maps protobuf imports to Go packages. These will become -# `-M` directives in the call to the go protobuf generator. -[packages] - "gogoproto/gogo.proto" = "github.com/gogo/protobuf/gogoproto" - "google/protobuf/any.proto" = "github.com/gogo/protobuf/types" - "google/protobuf/empty.proto" = "github.com/gogo/protobuf/types" - "google/protobuf/descriptor.proto" = "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" - "google/protobuf/field_mask.proto" = "github.com/gogo/protobuf/types" - "google/protobuf/timestamp.proto" = "github.com/gogo/protobuf/types" - "google/protobuf/duration.proto" = "github.com/gogo/protobuf/types" - "github/containerd/cgroups/stats/v1/metrics.proto" = "github.com/containerd/cgroups/stats/v1" - -[[overrides]] -prefixes = ["github.com/Microsoft/hcsshim/internal/shimdiag"] -plugins = ["ttrpc"] - -# Lock down runhcs config - -[[descriptors]] -prefix = "github.com/Microsoft/hcsshim/cmd/containerd-shim-runhcs-v1/options" -target = "cmd/containerd-shim-runhcs-v1/options/next.pb.txt" -ignore_files = [ - "google/protobuf/descriptor.proto", - "gogoproto/gogo.proto" -] - -[[descriptors]] -prefix = "github.com/Microsoft/hcsshim/cmd/containerd-shim-runhcs-v1/stats" -target = "cmd/containerd-shim-runhcs-v1/stats/next.pb.txt" -ignore_files = [ - "google/protobuf/descriptor.proto", - "gogoproto/gogo.proto" -] \ No newline at end of file diff --git a/vendor/github.com/Microsoft/hcsshim/README.md b/vendor/github.com/Microsoft/hcsshim/README.md deleted file mode 100644 index d504f188..00000000 --- a/vendor/github.com/Microsoft/hcsshim/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# hcsshim - -[![Build status](https://ci.appveyor.com/api/projects/status/nbcw28mnkqml0loa/branch/master?svg=true)](https://ci.appveyor.com/project/WindowsVirtualization/hcsshim/branch/master) - -This package contains the Golang interface for using the Windows [Host Compute Service](https://techcommunity.microsoft.com/t5/containers/introducing-the-host-compute-service-hcs/ba-p/382332) (HCS) to launch and manage [Windows Containers](https://docs.microsoft.com/en-us/virtualization/windowscontainers/about/). It also contains other helpers and functions for managing Windows Containers such as the Golang interface for the Host Network Service (HNS). - -It is primarily used in the [Moby Project](https://github.com/moby/moby), but it can be freely used by other projects as well. - -## Contributing - -This project welcomes contributions and suggestions. Most contributions require you to agree to a -Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us -the rights to use your contribution. For details, visit https://cla.microsoft.com. - -When you submit a pull request, a CLA-bot will automatically determine whether you need to provide -a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions -provided by the bot. You will only need to do this once across all repos using our CLA. - -We also ask that contributors [sign their commits](https://git-scm.com/docs/git-commit) using `git commit -s` or `git commit --signoff` to certify they either authored the work themselves or otherwise have permission to use it in this project. - - -## Code of Conduct - -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). -For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or -contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. - -## Dependencies - -This project requires Golang 1.9 or newer to build. - -For system requirements to run this project, see the Microsoft docs on [Windows Container requirements](https://docs.microsoft.com/en-us/virtualization/windowscontainers/deploy-containers/system-requirements). - -## Reporting Security Issues - -Security issues and bugs should be reported privately, via email, to the Microsoft Security -Response Center (MSRC) at [secure@microsoft.com](mailto:secure@microsoft.com). You should -receive a response within 24 hours. If for some reason you do not, please follow up via -email to ensure we received your original message. Further information, including the -[MSRC PGP](https://technet.microsoft.com/en-us/security/dn606155) key, can be found in -the [Security TechCenter](https://technet.microsoft.com/en-us/security/default). - -For additional details, see [Report a Computer Security Vulnerability](https://technet.microsoft.com/en-us/security/ff852094.aspx) on Technet - ---------------- -Copyright (c) 2018 Microsoft Corp. All rights reserved. diff --git a/vendor/github.com/Microsoft/hcsshim/appveyor.yml b/vendor/github.com/Microsoft/hcsshim/appveyor.yml deleted file mode 100644 index b214a962..00000000 --- a/vendor/github.com/Microsoft/hcsshim/appveyor.yml +++ /dev/null @@ -1,49 +0,0 @@ -version: 0.1.{build} - -image: Visual Studio 2019 - -clone_folder: c:\gopath\src\github.com\Microsoft\hcsshim - -environment: - GOPATH: c:\gopath - PATH: "%GOPATH%\\bin;C:\\gometalinter-2.0.12-windows-amd64;%PATH%" - GOPROXY: 'off' - GOFLAGS: '-mod=vendor' - -stack: go 1.15 - -build_script: - - appveyor DownloadFile https://github.com/alecthomas/gometalinter/releases/download/v2.0.12/gometalinter-2.0.12-windows-amd64.zip - - 7z x gometalinter-2.0.12-windows-amd64.zip -y -oC:\ > NUL - - gometalinter.exe --config .gometalinter.json ./... - - go build ./cmd/containerd-shim-runhcs-v1 - - go build ./cmd/runhcs - - go build ./cmd/tar2ext4 - - go build ./cmd/wclayer - - go build ./cmd/device-util - - go build ./internal/tools/grantvmgroupaccess - - go build ./internal/tools/uvmboot - - go build ./internal/tools/zapdir - - go test -gcflags=all=-d=checkptr -v ./... -tags admin - - cd test - - go test -gcflags=all=-d=checkptr -v ./internal -tags admin - - go test -gcflags=all=-d=checkptr -c ./containerd-shim-runhcs-v1/ -tags functional - - go test -gcflags=all=-d=checkptr -c ./cri-containerd/ -tags functional - - go test -gcflags=all=-d=checkptr -c ./functional/ -tags functional - - go test -gcflags=all=-d=checkptr -c ./runhcs/ -tags functional - - go build -o sample-logging-driver.exe ./cri-containerd/helpers/log.go - -artifacts: - - path: 'containerd-shim-runhcs-v1.exe' - - path: 'runhcs.exe' - - path: 'tar2ext4.exe' - - path: 'device-util.exe' - - path: 'wclayer.exe' - - path: 'grantvmgroupaccess.exe' - - path: 'uvmboot.exe' - - path: 'zapdir.exe' - - path: './test/containerd-shim-runhcs-v1.test.exe' - - path: './test/cri-containerd.test.exe' - - path: './test/functional.test.exe' - - path: './test/runhcs.test.exe' - - path: './test/sample-logging-driver.exe' diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/attach.go b/vendor/github.com/Microsoft/hcsshim/computestorage/attach.go deleted file mode 100644 index dcc61347..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/attach.go +++ /dev/null @@ -1,38 +0,0 @@ -package computestorage - -import ( - "context" - "encoding/json" - - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/pkg/errors" - "go.opencensus.io/trace" -) - -// AttachLayerStorageFilter sets up the layer storage filter on a writable -// container layer. -// -// `layerPath` is a path to a directory the writable layer is mounted. If the -// path does not end in a `\` the platform will append it automatically. -// -// `layerData` is the parent read-only layer data. -func AttachLayerStorageFilter(ctx context.Context, layerPath string, layerData LayerData) (err error) { - title := "hcsshim.AttachLayerStorageFilter" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("layerPath", layerPath), - ) - - bytes, err := json.Marshal(layerData) - if err != nil { - return err - } - - err = hcsAttachLayerStorageFilter(layerPath, string(bytes)) - if err != nil { - return errors.Wrap(err, "failed to attach layer storage filter") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/destroy.go b/vendor/github.com/Microsoft/hcsshim/computestorage/destroy.go deleted file mode 100644 index 39a9ba38..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/destroy.go +++ /dev/null @@ -1,26 +0,0 @@ -package computestorage - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/pkg/errors" - "go.opencensus.io/trace" -) - -// DestroyLayer deletes a container layer. -// -// `layerPath` is a path to a directory containing the layer to export. -func DestroyLayer(ctx context.Context, layerPath string) (err error) { - title := "hcsshim.DestroyLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("layerPath", layerPath)) - - err = hcsDestroyLayer(layerPath) - if err != nil { - return errors.Wrap(err, "failed to destroy layer") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/detach.go b/vendor/github.com/Microsoft/hcsshim/computestorage/detach.go deleted file mode 100644 index 9c144c06..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/detach.go +++ /dev/null @@ -1,26 +0,0 @@ -package computestorage - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/pkg/errors" - "go.opencensus.io/trace" -) - -// DetachLayerStorageFilter detaches the layer storage filter on a writable container layer. -// -// `layerPath` is a path to a directory containing the layer to export. -func DetachLayerStorageFilter(ctx context.Context, layerPath string) (err error) { - title := "hcsshim.DetachLayerStorageFilter" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("layerPath", layerPath)) - - err = hcsDetachLayerStorageFilter(layerPath) - if err != nil { - return errors.Wrap(err, "failed to detach layer storage filter") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/export.go b/vendor/github.com/Microsoft/hcsshim/computestorage/export.go deleted file mode 100644 index 649b2602..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/export.go +++ /dev/null @@ -1,46 +0,0 @@ -package computestorage - -import ( - "context" - "encoding/json" - - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/pkg/errors" - "go.opencensus.io/trace" -) - -// ExportLayer exports a container layer. -// -// `layerPath` is a path to a directory containing the layer to export. -// -// `exportFolderPath` is a pre-existing folder to export the layer to. -// -// `layerData` is the parent layer data. -// -// `options` are the export options applied to the exported layer. -func ExportLayer(ctx context.Context, layerPath, exportFolderPath string, layerData LayerData, options ExportLayerOptions) (err error) { - title := "hcsshim.ExportLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("layerPath", layerPath), - trace.StringAttribute("exportFolderPath", exportFolderPath), - ) - - ldbytes, err := json.Marshal(layerData) - if err != nil { - return err - } - - obytes, err := json.Marshal(options) - if err != nil { - return err - } - - err = hcsExportLayer(layerPath, exportFolderPath, string(ldbytes), string(obytes)) - if err != nil { - return errors.Wrap(err, "failed to export layer") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/format.go b/vendor/github.com/Microsoft/hcsshim/computestorage/format.go deleted file mode 100644 index fe0861d2..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/format.go +++ /dev/null @@ -1,26 +0,0 @@ -package computestorage - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/pkg/errors" - "go.opencensus.io/trace" - "golang.org/x/sys/windows" -) - -// FormatWritableLayerVhd formats a virtual disk for use as a writable container layer. -// -// If the VHD is not mounted it will be temporarily mounted. -func FormatWritableLayerVhd(ctx context.Context, vhdHandle windows.Handle) (err error) { - title := "hcsshim.FormatWritableLayerVhd" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - - err = hcsFormatWritableLayerVhd(vhdHandle) - if err != nil { - return errors.Wrap(err, "failed to format writable layer vhd") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/helpers.go b/vendor/github.com/Microsoft/hcsshim/computestorage/helpers.go deleted file mode 100644 index d31efd66..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/helpers.go +++ /dev/null @@ -1,197 +0,0 @@ -package computestorage - -import ( - "context" - "os" - "path/filepath" - "syscall" - - "github.com/Microsoft/go-winio/pkg/security" - "github.com/Microsoft/go-winio/vhd" - "github.com/pkg/errors" - "golang.org/x/sys/windows" -) - -const defaultVHDXBlockSizeInMB = 1 - -// SetupContainerBaseLayer is a helper to setup a containers scratch. It -// will create and format the vhdx's inside and the size is configurable with the sizeInGB -// parameter. -// -// `layerPath` is the path to the base container layer on disk. -// -// `baseVhdPath` is the path to where the base vhdx for the base layer should be created. -// -// `diffVhdPath` is the path where the differencing disk for the base layer should be created. -// -// `sizeInGB` is the size in gigabytes to make the base vhdx. -func SetupContainerBaseLayer(ctx context.Context, layerPath, baseVhdPath, diffVhdPath string, sizeInGB uint64) (err error) { - var ( - hivesPath = filepath.Join(layerPath, "Hives") - layoutPath = filepath.Join(layerPath, "Layout") - ) - - // We need to remove the hives directory and layout file as `SetupBaseOSLayer` fails if these files - // already exist. `SetupBaseOSLayer` will create these files internally. We also remove the base and - // differencing disks if they exist in case we're asking for a different size. - if _, err := os.Stat(hivesPath); err == nil { - if err := os.RemoveAll(hivesPath); err != nil { - return errors.Wrap(err, "failed to remove prexisting hives directory") - } - } - if _, err := os.Stat(layoutPath); err == nil { - if err := os.RemoveAll(layoutPath); err != nil { - return errors.Wrap(err, "failed to remove prexisting layout file") - } - } - - if _, err := os.Stat(baseVhdPath); err == nil { - if err := os.RemoveAll(baseVhdPath); err != nil { - return errors.Wrap(err, "failed to remove base vhdx path") - } - } - if _, err := os.Stat(diffVhdPath); err == nil { - if err := os.RemoveAll(diffVhdPath); err != nil { - return errors.Wrap(err, "failed to remove differencing vhdx") - } - } - - createParams := &vhd.CreateVirtualDiskParameters{ - Version: 2, - Version2: vhd.CreateVersion2{ - MaximumSize: sizeInGB * 1024 * 1024 * 1024, - BlockSizeInBytes: defaultVHDXBlockSizeInMB * 1024 * 1024, - }, - } - handle, err := vhd.CreateVirtualDisk(baseVhdPath, vhd.VirtualDiskAccessNone, vhd.CreateVirtualDiskFlagNone, createParams) - if err != nil { - return errors.Wrap(err, "failed to create vhdx") - } - - defer func() { - if err != nil { - syscall.CloseHandle(handle) - os.RemoveAll(baseVhdPath) - if os.Stat(diffVhdPath); err == nil { - os.RemoveAll(diffVhdPath) - } - } - }() - - if err = FormatWritableLayerVhd(ctx, windows.Handle(handle)); err != nil { - return err - } - // Base vhd handle must be closed before calling SetupBaseLayer in case of Container layer - if err = syscall.CloseHandle(handle); err != nil { - return errors.Wrap(err, "failed to close vhdx handle") - } - - options := OsLayerOptions{ - Type: OsLayerTypeContainer, - } - - // SetupBaseOSLayer expects an empty vhd handle for a container layer and will - // error out otherwise. - if err = SetupBaseOSLayer(ctx, layerPath, 0, options); err != nil { - return err - } - // Create the differencing disk that will be what's copied for the final rw layer - // for a container. - if err = vhd.CreateDiffVhd(diffVhdPath, baseVhdPath, defaultVHDXBlockSizeInMB); err != nil { - return errors.Wrap(err, "failed to create differencing disk") - } - - if err = security.GrantVmGroupAccess(baseVhdPath); err != nil { - return errors.Wrapf(err, "failed to grant vm group access to %s", baseVhdPath) - } - if err = security.GrantVmGroupAccess(diffVhdPath); err != nil { - return errors.Wrapf(err, "failed to grant vm group access to %s", diffVhdPath) - } - return nil -} - -// SetupUtilityVMBaseLayer is a helper to setup a UVMs scratch space. It will create and format -// the vhdx inside and the size is configurable by the sizeInGB parameter. -// -// `uvmPath` is the path to the UtilityVM filesystem. -// -// `baseVhdPath` is the path to where the base vhdx for the UVM should be created. -// -// `diffVhdPath` is the path where the differencing disk for the UVM should be created. -// -// `sizeInGB` specifies the size in gigabytes to make the base vhdx. -func SetupUtilityVMBaseLayer(ctx context.Context, uvmPath, baseVhdPath, diffVhdPath string, sizeInGB uint64) (err error) { - // Remove the base and differencing disks if they exist in case we're asking for a different size. - if _, err := os.Stat(baseVhdPath); err == nil { - if err := os.RemoveAll(baseVhdPath); err != nil { - return errors.Wrap(err, "failed to remove base vhdx") - } - } - if _, err := os.Stat(diffVhdPath); err == nil { - if err := os.RemoveAll(diffVhdPath); err != nil { - return errors.Wrap(err, "failed to remove differencing vhdx") - } - } - - // Just create the vhdx for utilityVM layer, no need to format it. - createParams := &vhd.CreateVirtualDiskParameters{ - Version: 2, - Version2: vhd.CreateVersion2{ - MaximumSize: sizeInGB * 1024 * 1024 * 1024, - BlockSizeInBytes: defaultVHDXBlockSizeInMB * 1024 * 1024, - }, - } - handle, err := vhd.CreateVirtualDisk(baseVhdPath, vhd.VirtualDiskAccessNone, vhd.CreateVirtualDiskFlagNone, createParams) - if err != nil { - return errors.Wrap(err, "failed to create vhdx") - } - - defer func() { - if err != nil { - syscall.CloseHandle(handle) - os.RemoveAll(baseVhdPath) - if os.Stat(diffVhdPath); err == nil { - os.RemoveAll(diffVhdPath) - } - } - }() - - // If it is a UtilityVM layer then the base vhdx must be attached when calling - // `SetupBaseOSLayer` - attachParams := &vhd.AttachVirtualDiskParameters{ - Version: 2, - } - if err := vhd.AttachVirtualDisk(handle, vhd.AttachVirtualDiskFlagNone, attachParams); err != nil { - return errors.Wrapf(err, "failed to attach virtual disk") - } - - options := OsLayerOptions{ - Type: OsLayerTypeVM, - } - if err := SetupBaseOSLayer(ctx, uvmPath, windows.Handle(handle), options); err != nil { - return err - } - - // Detach and close the handle after setting up the layer as we don't need the handle - // for anything else and we no longer need to be attached either. - if err = vhd.DetachVirtualDisk(handle); err != nil { - return errors.Wrap(err, "failed to detach vhdx") - } - if err = syscall.CloseHandle(handle); err != nil { - return errors.Wrap(err, "failed to close vhdx handle") - } - - // Create the differencing disk that will be what's copied for the final rw layer - // for a container. - if err = vhd.CreateDiffVhd(diffVhdPath, baseVhdPath, defaultVHDXBlockSizeInMB); err != nil { - return errors.Wrap(err, "failed to create differencing disk") - } - - if err := security.GrantVmGroupAccess(baseVhdPath); err != nil { - return errors.Wrapf(err, "failed to grant vm group access to %s", baseVhdPath) - } - if err := security.GrantVmGroupAccess(diffVhdPath); err != nil { - return errors.Wrapf(err, "failed to grant vm group access to %s", diffVhdPath) - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/import.go b/vendor/github.com/Microsoft/hcsshim/computestorage/import.go deleted file mode 100644 index 8ad2b085..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/import.go +++ /dev/null @@ -1,41 +0,0 @@ -package computestorage - -import ( - "context" - "encoding/json" - - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/pkg/errors" - "go.opencensus.io/trace" -) - -// ImportLayer imports a container layer. -// -// `layerPath` is a path to a directory to import the layer to. If the directory -// does not exist it will be automatically created. -// -// `sourceFolderpath` is a pre-existing folder that contains the layer to -// import. -// -// `layerData` is the parent layer data. -func ImportLayer(ctx context.Context, layerPath, sourceFolderPath string, layerData LayerData) (err error) { - title := "hcsshim.ImportLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("layerPath", layerPath), - trace.StringAttribute("sourceFolderPath", sourceFolderPath), - ) - - bytes, err := json.Marshal(layerData) - if err != nil { - return err - } - - err = hcsImportLayer(layerPath, sourceFolderPath, string(bytes)) - if err != nil { - return errors.Wrap(err, "failed to import layer") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/initialize.go b/vendor/github.com/Microsoft/hcsshim/computestorage/initialize.go deleted file mode 100644 index a50afd82..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/initialize.go +++ /dev/null @@ -1,38 +0,0 @@ -package computestorage - -import ( - "context" - "encoding/json" - - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/pkg/errors" - "go.opencensus.io/trace" -) - -// InitializeWritableLayer initializes a writable layer for a container. -// -// `layerPath` is a path to a directory the layer is mounted. If the -// path does not end in a `\` the platform will append it automatically. -// -// `layerData` is the parent read-only layer data. -func InitializeWritableLayer(ctx context.Context, layerPath string, layerData LayerData) (err error) { - title := "hcsshim.InitializeWritableLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("layerPath", layerPath), - ) - - bytes, err := json.Marshal(layerData) - if err != nil { - return err - } - - // Options are not used in the platform as of RS5 - err = hcsInitializeWritableLayer(layerPath, string(bytes), "") - if err != nil { - return errors.Wrap(err, "failed to intitialize container layer") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/mount.go b/vendor/github.com/Microsoft/hcsshim/computestorage/mount.go deleted file mode 100644 index 1c16ff40..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/mount.go +++ /dev/null @@ -1,27 +0,0 @@ -package computestorage - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/interop" - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/pkg/errors" - "go.opencensus.io/trace" - "golang.org/x/sys/windows" -) - -// GetLayerVhdMountPath returns the volume path for a virtual disk of a writable container layer. -func GetLayerVhdMountPath(ctx context.Context, vhdHandle windows.Handle) (path string, err error) { - title := "hcsshim.GetLayerVhdMountPath" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - - var mountPath *uint16 - err = hcsGetLayerVhdMountPath(vhdHandle, &mountPath) - if err != nil { - return "", errors.Wrap(err, "failed to get vhd mount path") - } - path = interop.ConvertAndFreeCoTaskMemString(mountPath) - return path, nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/setup.go b/vendor/github.com/Microsoft/hcsshim/computestorage/setup.go deleted file mode 100644 index 7506709c..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/setup.go +++ /dev/null @@ -1,74 +0,0 @@ -package computestorage - -import ( - "context" - "encoding/json" - - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/Microsoft/hcsshim/osversion" - "github.com/pkg/errors" - "go.opencensus.io/trace" - "golang.org/x/sys/windows" -) - -// SetupBaseOSLayer sets up a layer that contains a base OS for a container. -// -// `layerPath` is a path to a directory containing the layer. -// -// `vhdHandle` is an empty file handle of `options.Type == OsLayerTypeContainer` -// or else it is a file handle to the 'SystemTemplateBase.vhdx' if `options.Type -// == OsLayerTypeVm`. -// -// `options` are the options applied while processing the layer. -func SetupBaseOSLayer(ctx context.Context, layerPath string, vhdHandle windows.Handle, options OsLayerOptions) (err error) { - title := "hcsshim.SetupBaseOSLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("layerPath", layerPath), - ) - - bytes, err := json.Marshal(options) - if err != nil { - return err - } - - err = hcsSetupBaseOSLayer(layerPath, vhdHandle, string(bytes)) - if err != nil { - return errors.Wrap(err, "failed to setup base OS layer") - } - return nil -} - -// SetupBaseOSVolume sets up a volume that contains a base OS for a container. -// -// `layerPath` is a path to a directory containing the layer. -// -// `volumePath` is the path to the volume to be used for setup. -// -// `options` are the options applied while processing the layer. -func SetupBaseOSVolume(ctx context.Context, layerPath, volumePath string, options OsLayerOptions) (err error) { - if osversion.Get().Build < 19645 { - return errors.New("SetupBaseOSVolume is not present on builds older than 19645") - } - title := "hcsshim.SetupBaseOSVolume" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("layerPath", layerPath), - trace.StringAttribute("volumePath", volumePath), - ) - - bytes, err := json.Marshal(options) - if err != nil { - return err - } - - err = hcsSetupBaseOSVolume(layerPath, volumePath, string(bytes)) - if err != nil { - return errors.Wrap(err, "failed to setup base OS layer") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/storage.go b/vendor/github.com/Microsoft/hcsshim/computestorage/storage.go deleted file mode 100644 index 9cd283d4..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/storage.go +++ /dev/null @@ -1,50 +0,0 @@ -// Package computestorage is a wrapper around the HCS storage APIs. These are new storage APIs introduced -// separate from the original graphdriver calls intended to give more freedom around creating -// and managing container layers and scratch spaces. -package computestorage - -import ( - hcsschema "github.com/Microsoft/hcsshim/internal/schema2" -) - -//go:generate go run ../mksyscall_windows.go -output zsyscall_windows.go storage.go - -//sys hcsImportLayer(layerPath string, sourceFolderPath string, layerData string) (hr error) = computestorage.HcsImportLayer? -//sys hcsExportLayer(layerPath string, exportFolderPath string, layerData string, options string) (hr error) = computestorage.HcsExportLayer? -//sys hcsDestroyLayer(layerPath string) (hr error) = computestorage.HcsDestoryLayer? -//sys hcsSetupBaseOSLayer(layerPath string, handle windows.Handle, options string) (hr error) = computestorage.HcsSetupBaseOSLayer? -//sys hcsInitializeWritableLayer(writableLayerPath string, layerData string, options string) (hr error) = computestorage.HcsInitializeWritableLayer? -//sys hcsAttachLayerStorageFilter(layerPath string, layerData string) (hr error) = computestorage.HcsAttachLayerStorageFilter? -//sys hcsDetachLayerStorageFilter(layerPath string) (hr error) = computestorage.HcsDetachLayerStorageFilter? -//sys hcsFormatWritableLayerVhd(handle windows.Handle) (hr error) = computestorage.HcsFormatWritableLayerVhd? -//sys hcsGetLayerVhdMountPath(vhdHandle windows.Handle, mountPath **uint16) (hr error) = computestorage.HcsGetLayerVhdMountPath? -//sys hcsSetupBaseOSVolume(layerPath string, volumePath string, options string) (hr error) = computestorage.HcsSetupBaseOSVolume? - -// LayerData is the data used to describe parent layer information. -type LayerData struct { - SchemaVersion hcsschema.Version `json:"SchemaVersion,omitempty"` - Layers []hcsschema.Layer `json:"Layers,omitempty"` -} - -// ExportLayerOptions are the set of options that are used with the `computestorage.HcsExportLayer` syscall. -type ExportLayerOptions struct { - IsWritableLayer bool `json:"IsWritableLayer,omitempty"` -} - -// OsLayerType is the type of layer being operated on. -type OsLayerType string - -const ( - // OsLayerTypeContainer is a container layer. - OsLayerTypeContainer OsLayerType = "Container" - // OsLayerTypeVM is a virtual machine layer. - OsLayerTypeVM OsLayerType = "Vm" -) - -// OsLayerOptions are the set of options that are used with the `SetupBaseOSLayer` and -// `SetupBaseOSVolume` calls. -type OsLayerOptions struct { - Type OsLayerType `json:"Type,omitempty"` - DisableCiCacheOptimization bool `json:"DisableCiCacheOptimization,omitempty"` - SkipUpdateBcdForBoot bool `json:"SkipUpdateBcdForBoot,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/computestorage/zsyscall_windows.go b/vendor/github.com/Microsoft/hcsshim/computestorage/zsyscall_windows.go deleted file mode 100644 index 4f951806..00000000 --- a/vendor/github.com/Microsoft/hcsshim/computestorage/zsyscall_windows.go +++ /dev/null @@ -1,319 +0,0 @@ -// Code generated mksyscall_windows.exe DO NOT EDIT - -package computestorage - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return nil - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modcomputestorage = windows.NewLazySystemDLL("computestorage.dll") - - procHcsImportLayer = modcomputestorage.NewProc("HcsImportLayer") - procHcsExportLayer = modcomputestorage.NewProc("HcsExportLayer") - procHcsDestoryLayer = modcomputestorage.NewProc("HcsDestoryLayer") - procHcsSetupBaseOSLayer = modcomputestorage.NewProc("HcsSetupBaseOSLayer") - procHcsInitializeWritableLayer = modcomputestorage.NewProc("HcsInitializeWritableLayer") - procHcsAttachLayerStorageFilter = modcomputestorage.NewProc("HcsAttachLayerStorageFilter") - procHcsDetachLayerStorageFilter = modcomputestorage.NewProc("HcsDetachLayerStorageFilter") - procHcsFormatWritableLayerVhd = modcomputestorage.NewProc("HcsFormatWritableLayerVhd") - procHcsGetLayerVhdMountPath = modcomputestorage.NewProc("HcsGetLayerVhdMountPath") - procHcsSetupBaseOSVolume = modcomputestorage.NewProc("HcsSetupBaseOSVolume") -) - -func hcsImportLayer(layerPath string, sourceFolderPath string, layerData string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(layerPath) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(sourceFolderPath) - if hr != nil { - return - } - var _p2 *uint16 - _p2, hr = syscall.UTF16PtrFromString(layerData) - if hr != nil { - return - } - return _hcsImportLayer(_p0, _p1, _p2) -} - -func _hcsImportLayer(layerPath *uint16, sourceFolderPath *uint16, layerData *uint16) (hr error) { - if hr = procHcsImportLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsImportLayer.Addr(), 3, uintptr(unsafe.Pointer(layerPath)), uintptr(unsafe.Pointer(sourceFolderPath)), uintptr(unsafe.Pointer(layerData))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsExportLayer(layerPath string, exportFolderPath string, layerData string, options string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(layerPath) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(exportFolderPath) - if hr != nil { - return - } - var _p2 *uint16 - _p2, hr = syscall.UTF16PtrFromString(layerData) - if hr != nil { - return - } - var _p3 *uint16 - _p3, hr = syscall.UTF16PtrFromString(options) - if hr != nil { - return - } - return _hcsExportLayer(_p0, _p1, _p2, _p3) -} - -func _hcsExportLayer(layerPath *uint16, exportFolderPath *uint16, layerData *uint16, options *uint16) (hr error) { - if hr = procHcsExportLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procHcsExportLayer.Addr(), 4, uintptr(unsafe.Pointer(layerPath)), uintptr(unsafe.Pointer(exportFolderPath)), uintptr(unsafe.Pointer(layerData)), uintptr(unsafe.Pointer(options)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsDestroyLayer(layerPath string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(layerPath) - if hr != nil { - return - } - return _hcsDestroyLayer(_p0) -} - -func _hcsDestroyLayer(layerPath *uint16) (hr error) { - if hr = procHcsDestoryLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsDestoryLayer.Addr(), 1, uintptr(unsafe.Pointer(layerPath)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsSetupBaseOSLayer(layerPath string, handle windows.Handle, options string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(layerPath) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(options) - if hr != nil { - return - } - return _hcsSetupBaseOSLayer(_p0, handle, _p1) -} - -func _hcsSetupBaseOSLayer(layerPath *uint16, handle windows.Handle, options *uint16) (hr error) { - if hr = procHcsSetupBaseOSLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsSetupBaseOSLayer.Addr(), 3, uintptr(unsafe.Pointer(layerPath)), uintptr(handle), uintptr(unsafe.Pointer(options))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsInitializeWritableLayer(writableLayerPath string, layerData string, options string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(writableLayerPath) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(layerData) - if hr != nil { - return - } - var _p2 *uint16 - _p2, hr = syscall.UTF16PtrFromString(options) - if hr != nil { - return - } - return _hcsInitializeWritableLayer(_p0, _p1, _p2) -} - -func _hcsInitializeWritableLayer(writableLayerPath *uint16, layerData *uint16, options *uint16) (hr error) { - if hr = procHcsInitializeWritableLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsInitializeWritableLayer.Addr(), 3, uintptr(unsafe.Pointer(writableLayerPath)), uintptr(unsafe.Pointer(layerData)), uintptr(unsafe.Pointer(options))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsAttachLayerStorageFilter(layerPath string, layerData string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(layerPath) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(layerData) - if hr != nil { - return - } - return _hcsAttachLayerStorageFilter(_p0, _p1) -} - -func _hcsAttachLayerStorageFilter(layerPath *uint16, layerData *uint16) (hr error) { - if hr = procHcsAttachLayerStorageFilter.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsAttachLayerStorageFilter.Addr(), 2, uintptr(unsafe.Pointer(layerPath)), uintptr(unsafe.Pointer(layerData)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsDetachLayerStorageFilter(layerPath string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(layerPath) - if hr != nil { - return - } - return _hcsDetachLayerStorageFilter(_p0) -} - -func _hcsDetachLayerStorageFilter(layerPath *uint16) (hr error) { - if hr = procHcsDetachLayerStorageFilter.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsDetachLayerStorageFilter.Addr(), 1, uintptr(unsafe.Pointer(layerPath)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsFormatWritableLayerVhd(handle windows.Handle) (hr error) { - if hr = procHcsFormatWritableLayerVhd.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsFormatWritableLayerVhd.Addr(), 1, uintptr(handle), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsGetLayerVhdMountPath(vhdHandle windows.Handle, mountPath **uint16) (hr error) { - if hr = procHcsGetLayerVhdMountPath.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsGetLayerVhdMountPath.Addr(), 2, uintptr(vhdHandle), uintptr(unsafe.Pointer(mountPath)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsSetupBaseOSVolume(layerPath string, volumePath string, options string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(layerPath) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(volumePath) - if hr != nil { - return - } - var _p2 *uint16 - _p2, hr = syscall.UTF16PtrFromString(options) - if hr != nil { - return - } - return _hcsSetupBaseOSVolume(_p0, _p1, _p2) -} - -func _hcsSetupBaseOSVolume(layerPath *uint16, volumePath *uint16, options *uint16) (hr error) { - if hr = procHcsSetupBaseOSVolume.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsSetupBaseOSVolume.Addr(), 3, uintptr(unsafe.Pointer(layerPath)), uintptr(unsafe.Pointer(volumePath)), uintptr(unsafe.Pointer(options))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} diff --git a/vendor/github.com/Microsoft/hcsshim/container.go b/vendor/github.com/Microsoft/hcsshim/container.go deleted file mode 100644 index 7205a62c..00000000 --- a/vendor/github.com/Microsoft/hcsshim/container.go +++ /dev/null @@ -1,223 +0,0 @@ -package hcsshim - -import ( - "context" - "fmt" - "os" - "sync" - "time" - - "github.com/Microsoft/hcsshim/internal/hcs" - "github.com/Microsoft/hcsshim/internal/mergemaps" - "github.com/Microsoft/hcsshim/internal/schema1" -) - -// ContainerProperties holds the properties for a container and the processes running in that container -type ContainerProperties = schema1.ContainerProperties - -// MemoryStats holds the memory statistics for a container -type MemoryStats = schema1.MemoryStats - -// ProcessorStats holds the processor statistics for a container -type ProcessorStats = schema1.ProcessorStats - -// StorageStats holds the storage statistics for a container -type StorageStats = schema1.StorageStats - -// NetworkStats holds the network statistics for a container -type NetworkStats = schema1.NetworkStats - -// Statistics is the structure returned by a statistics call on a container -type Statistics = schema1.Statistics - -// ProcessList is the structure of an item returned by a ProcessList call on a container -type ProcessListItem = schema1.ProcessListItem - -// MappedVirtualDiskController is the structure of an item returned by a MappedVirtualDiskList call on a container -type MappedVirtualDiskController = schema1.MappedVirtualDiskController - -// Type of Request Support in ModifySystem -type RequestType = schema1.RequestType - -// Type of Resource Support in ModifySystem -type ResourceType = schema1.ResourceType - -// RequestType const -const ( - Add = schema1.Add - Remove = schema1.Remove - Network = schema1.Network -) - -// ResourceModificationRequestResponse is the structure used to send request to the container to modify the system -// Supported resource types are Network and Request Types are Add/Remove -type ResourceModificationRequestResponse = schema1.ResourceModificationRequestResponse - -type container struct { - system *hcs.System - waitOnce sync.Once - waitErr error - waitCh chan struct{} -} - -// createComputeSystemAdditionalJSON is read from the environment at initialisation -// time. It allows an environment variable to define additional JSON which -// is merged in the CreateComputeSystem call to HCS. -var createContainerAdditionalJSON []byte - -func init() { - createContainerAdditionalJSON = ([]byte)(os.Getenv("HCSSHIM_CREATECONTAINER_ADDITIONALJSON")) -} - -// CreateContainer creates a new container with the given configuration but does not start it. -func CreateContainer(id string, c *ContainerConfig) (Container, error) { - fullConfig, err := mergemaps.MergeJSON(c, createContainerAdditionalJSON) - if err != nil { - return nil, fmt.Errorf("failed to merge additional JSON '%s': %s", createContainerAdditionalJSON, err) - } - - system, err := hcs.CreateComputeSystem(context.Background(), id, fullConfig) - if err != nil { - return nil, err - } - return &container{system: system}, err -} - -// OpenContainer opens an existing container by ID. -func OpenContainer(id string) (Container, error) { - system, err := hcs.OpenComputeSystem(context.Background(), id) - if err != nil { - return nil, err - } - return &container{system: system}, err -} - -// GetContainers gets a list of the containers on the system that match the query -func GetContainers(q ComputeSystemQuery) ([]ContainerProperties, error) { - return hcs.GetComputeSystems(context.Background(), q) -} - -// Start synchronously starts the container. -func (container *container) Start() error { - return convertSystemError(container.system.Start(context.Background()), container) -} - -// Shutdown requests a container shutdown, but it may not actually be shutdown until Wait() succeeds. -func (container *container) Shutdown() error { - err := container.system.Shutdown(context.Background()) - if err != nil { - return convertSystemError(err, container) - } - return &ContainerError{Container: container, Err: ErrVmcomputeOperationPending, Operation: "hcsshim::ComputeSystem::Shutdown"} -} - -// Terminate requests a container terminate, but it may not actually be terminated until Wait() succeeds. -func (container *container) Terminate() error { - err := container.system.Terminate(context.Background()) - if err != nil { - return convertSystemError(err, container) - } - return &ContainerError{Container: container, Err: ErrVmcomputeOperationPending, Operation: "hcsshim::ComputeSystem::Terminate"} -} - -// Waits synchronously waits for the container to shutdown or terminate. -func (container *container) Wait() error { - err := container.system.Wait() - if err == nil { - err = container.system.ExitError() - } - return convertSystemError(err, container) -} - -// WaitTimeout synchronously waits for the container to terminate or the duration to elapse. It -// returns false if timeout occurs. -func (container *container) WaitTimeout(timeout time.Duration) error { - container.waitOnce.Do(func() { - container.waitCh = make(chan struct{}) - go func() { - container.waitErr = container.Wait() - close(container.waitCh) - }() - }) - t := time.NewTimer(timeout) - defer t.Stop() - select { - case <-t.C: - return &ContainerError{Container: container, Err: ErrTimeout, Operation: "hcsshim::ComputeSystem::Wait"} - case <-container.waitCh: - return container.waitErr - } -} - -// Pause pauses the execution of a container. -func (container *container) Pause() error { - return convertSystemError(container.system.Pause(context.Background()), container) -} - -// Resume resumes the execution of a container. -func (container *container) Resume() error { - return convertSystemError(container.system.Resume(context.Background()), container) -} - -// HasPendingUpdates returns true if the container has updates pending to install -func (container *container) HasPendingUpdates() (bool, error) { - return false, nil -} - -// Statistics returns statistics for the container. This is a legacy v1 call -func (container *container) Statistics() (Statistics, error) { - properties, err := container.system.Properties(context.Background(), schema1.PropertyTypeStatistics) - if err != nil { - return Statistics{}, convertSystemError(err, container) - } - - return properties.Statistics, nil -} - -// ProcessList returns an array of ProcessListItems for the container. This is a legacy v1 call -func (container *container) ProcessList() ([]ProcessListItem, error) { - properties, err := container.system.Properties(context.Background(), schema1.PropertyTypeProcessList) - if err != nil { - return nil, convertSystemError(err, container) - } - - return properties.ProcessList, nil -} - -// This is a legacy v1 call -func (container *container) MappedVirtualDisks() (map[int]MappedVirtualDiskController, error) { - properties, err := container.system.Properties(context.Background(), schema1.PropertyTypeMappedVirtualDisk) - if err != nil { - return nil, convertSystemError(err, container) - } - - return properties.MappedVirtualDiskControllers, nil -} - -// CreateProcess launches a new process within the container. -func (container *container) CreateProcess(c *ProcessConfig) (Process, error) { - p, err := container.system.CreateProcess(context.Background(), c) - if err != nil { - return nil, convertSystemError(err, container) - } - return &process{p: p.(*hcs.Process)}, nil -} - -// OpenProcess gets an interface to an existing process within the container. -func (container *container) OpenProcess(pid int) (Process, error) { - p, err := container.system.OpenProcess(context.Background(), pid) - if err != nil { - return nil, convertSystemError(err, container) - } - return &process{p: p}, nil -} - -// Close cleans up any state associated with the container but does not terminate or wait for it. -func (container *container) Close() error { - return convertSystemError(container.system.Close(), container) -} - -// Modify the System -func (container *container) Modify(config *ResourceModificationRequestResponse) error { - return convertSystemError(container.system.Modify(context.Background(), config), container) -} diff --git a/vendor/github.com/Microsoft/hcsshim/errors.go b/vendor/github.com/Microsoft/hcsshim/errors.go deleted file mode 100644 index 061727c6..00000000 --- a/vendor/github.com/Microsoft/hcsshim/errors.go +++ /dev/null @@ -1,269 +0,0 @@ -package hcsshim - -import ( - "fmt" - "syscall" - - "github.com/Microsoft/hcsshim/internal/hns" - - "github.com/Microsoft/hcsshim/internal/hcs" - "github.com/Microsoft/hcsshim/internal/hcserror" -) - -var ( - // ErrComputeSystemDoesNotExist is an error encountered when the container being operated on no longer exists = hcs.exist - ErrComputeSystemDoesNotExist = hcs.ErrComputeSystemDoesNotExist - - // ErrElementNotFound is an error encountered when the object being referenced does not exist - ErrElementNotFound = hcs.ErrElementNotFound - - // ErrElementNotFound is an error encountered when the object being referenced does not exist - ErrNotSupported = hcs.ErrNotSupported - - // ErrInvalidData is an error encountered when the request being sent to hcs is invalid/unsupported - // decimal -2147024883 / hex 0x8007000d - ErrInvalidData = hcs.ErrInvalidData - - // ErrHandleClose is an error encountered when the handle generating the notification being waited on has been closed - ErrHandleClose = hcs.ErrHandleClose - - // ErrAlreadyClosed is an error encountered when using a handle that has been closed by the Close method - ErrAlreadyClosed = hcs.ErrAlreadyClosed - - // ErrInvalidNotificationType is an error encountered when an invalid notification type is used - ErrInvalidNotificationType = hcs.ErrInvalidNotificationType - - // ErrInvalidProcessState is an error encountered when the process is not in a valid state for the requested operation - ErrInvalidProcessState = hcs.ErrInvalidProcessState - - // ErrTimeout is an error encountered when waiting on a notification times out - ErrTimeout = hcs.ErrTimeout - - // ErrUnexpectedContainerExit is the error encountered when a container exits while waiting for - // a different expected notification - ErrUnexpectedContainerExit = hcs.ErrUnexpectedContainerExit - - // ErrUnexpectedProcessAbort is the error encountered when communication with the compute service - // is lost while waiting for a notification - ErrUnexpectedProcessAbort = hcs.ErrUnexpectedProcessAbort - - // ErrUnexpectedValue is an error encountered when hcs returns an invalid value - ErrUnexpectedValue = hcs.ErrUnexpectedValue - - // ErrVmcomputeAlreadyStopped is an error encountered when a shutdown or terminate request is made on a stopped container - ErrVmcomputeAlreadyStopped = hcs.ErrVmcomputeAlreadyStopped - - // ErrVmcomputeOperationPending is an error encountered when the operation is being completed asynchronously - ErrVmcomputeOperationPending = hcs.ErrVmcomputeOperationPending - - // ErrVmcomputeOperationInvalidState is an error encountered when the compute system is not in a valid state for the requested operation - ErrVmcomputeOperationInvalidState = hcs.ErrVmcomputeOperationInvalidState - - // ErrProcNotFound is an error encountered when the the process cannot be found - ErrProcNotFound = hcs.ErrProcNotFound - - // ErrVmcomputeOperationAccessIsDenied is an error which can be encountered when enumerating compute systems in RS1/RS2 - // builds when the underlying silo might be in the process of terminating. HCS was fixed in RS3. - ErrVmcomputeOperationAccessIsDenied = hcs.ErrVmcomputeOperationAccessIsDenied - - // ErrVmcomputeInvalidJSON is an error encountered when the compute system does not support/understand the messages sent by management - ErrVmcomputeInvalidJSON = hcs.ErrVmcomputeInvalidJSON - - // ErrVmcomputeUnknownMessage is an error encountered guest compute system doesn't support the message - ErrVmcomputeUnknownMessage = hcs.ErrVmcomputeUnknownMessage - - // ErrNotSupported is an error encountered when hcs doesn't support the request - ErrPlatformNotSupported = hcs.ErrPlatformNotSupported -) - -type EndpointNotFoundError = hns.EndpointNotFoundError -type NetworkNotFoundError = hns.NetworkNotFoundError - -// ProcessError is an error encountered in HCS during an operation on a Process object -type ProcessError struct { - Process *process - Operation string - ExtraInfo string - Err error - Events []hcs.ErrorEvent -} - -// ContainerError is an error encountered in HCS during an operation on a Container object -type ContainerError struct { - Container *container - Operation string - ExtraInfo string - Err error - Events []hcs.ErrorEvent -} - -func (e *ContainerError) Error() string { - if e == nil { - return "" - } - - if e.Container == nil { - return "unexpected nil container for error: " + e.Err.Error() - } - - s := "container " + e.Container.system.ID() - - if e.Operation != "" { - s += " encountered an error during " + e.Operation - } - - switch e.Err.(type) { - case nil: - break - case syscall.Errno: - s += fmt.Sprintf(": failure in a Windows system call: %s (0x%x)", e.Err, hcserror.Win32FromError(e.Err)) - default: - s += fmt.Sprintf(": %s", e.Err.Error()) - } - - for _, ev := range e.Events { - s += "\n" + ev.String() - } - - if e.ExtraInfo != "" { - s += " extra info: " + e.ExtraInfo - } - - return s -} - -func makeContainerError(container *container, operation string, extraInfo string, err error) error { - // Don't double wrap errors - if _, ok := err.(*ContainerError); ok { - return err - } - containerError := &ContainerError{Container: container, Operation: operation, ExtraInfo: extraInfo, Err: err} - return containerError -} - -func (e *ProcessError) Error() string { - if e == nil { - return "" - } - - if e.Process == nil { - return "Unexpected nil process for error: " + e.Err.Error() - } - - s := fmt.Sprintf("process %d in container %s", e.Process.p.Pid(), e.Process.p.SystemID()) - if e.Operation != "" { - s += " encountered an error during " + e.Operation - } - - switch e.Err.(type) { - case nil: - break - case syscall.Errno: - s += fmt.Sprintf(": failure in a Windows system call: %s (0x%x)", e.Err, hcserror.Win32FromError(e.Err)) - default: - s += fmt.Sprintf(": %s", e.Err.Error()) - } - - for _, ev := range e.Events { - s += "\n" + ev.String() - } - - return s -} - -func makeProcessError(process *process, operation string, extraInfo string, err error) error { - // Don't double wrap errors - if _, ok := err.(*ProcessError); ok { - return err - } - processError := &ProcessError{Process: process, Operation: operation, ExtraInfo: extraInfo, Err: err} - return processError -} - -// IsNotExist checks if an error is caused by the Container or Process not existing. -// Note: Currently, ErrElementNotFound can mean that a Process has either -// already exited, or does not exist. Both IsAlreadyStopped and IsNotExist -// will currently return true when the error is ErrElementNotFound or ErrProcNotFound. -func IsNotExist(err error) bool { - if _, ok := err.(EndpointNotFoundError); ok { - return true - } - if _, ok := err.(NetworkNotFoundError); ok { - return true - } - return hcs.IsNotExist(getInnerError(err)) -} - -// IsAlreadyClosed checks if an error is caused by the Container or Process having been -// already closed by a call to the Close() method. -func IsAlreadyClosed(err error) bool { - return hcs.IsAlreadyClosed(getInnerError(err)) -} - -// IsPending returns a boolean indicating whether the error is that -// the requested operation is being completed in the background. -func IsPending(err error) bool { - return hcs.IsPending(getInnerError(err)) -} - -// IsTimeout returns a boolean indicating whether the error is caused by -// a timeout waiting for the operation to complete. -func IsTimeout(err error) bool { - return hcs.IsTimeout(getInnerError(err)) -} - -// IsAlreadyStopped returns a boolean indicating whether the error is caused by -// a Container or Process being already stopped. -// Note: Currently, ErrElementNotFound can mean that a Process has either -// already exited, or does not exist. Both IsAlreadyStopped and IsNotExist -// will currently return true when the error is ErrElementNotFound or ErrProcNotFound. -func IsAlreadyStopped(err error) bool { - return hcs.IsAlreadyStopped(getInnerError(err)) -} - -// IsNotSupported returns a boolean indicating whether the error is caused by -// unsupported platform requests -// Note: Currently Unsupported platform requests can be mean either -// ErrVmcomputeInvalidJSON, ErrInvalidData, ErrNotSupported or ErrVmcomputeUnknownMessage -// is thrown from the Platform -func IsNotSupported(err error) bool { - return hcs.IsNotSupported(getInnerError(err)) -} - -// IsOperationInvalidState returns true when err is caused by -// `ErrVmcomputeOperationInvalidState`. -func IsOperationInvalidState(err error) bool { - return hcs.IsOperationInvalidState(getInnerError(err)) -} - -// IsAccessIsDenied returns true when err is caused by -// `ErrVmcomputeOperationAccessIsDenied`. -func IsAccessIsDenied(err error) bool { - return hcs.IsAccessIsDenied(getInnerError(err)) -} - -func getInnerError(err error) error { - switch pe := err.(type) { - case nil: - return nil - case *ContainerError: - err = pe.Err - case *ProcessError: - err = pe.Err - } - return err -} - -func convertSystemError(err error, c *container) error { - if serr, ok := err.(*hcs.SystemError); ok { - return &ContainerError{Container: c, Operation: serr.Op, ExtraInfo: serr.Extra, Err: serr.Err, Events: serr.Events} - } - return err -} - -func convertProcessError(err error, p *process) error { - if perr, ok := err.(*hcs.ProcessError); ok { - return &ProcessError{Process: p, Operation: perr.Op, Err: perr.Err, Events: perr.Events} - } - return err -} diff --git a/vendor/github.com/Microsoft/hcsshim/functional_tests.ps1 b/vendor/github.com/Microsoft/hcsshim/functional_tests.ps1 deleted file mode 100644 index ce6edbcf..00000000 --- a/vendor/github.com/Microsoft/hcsshim/functional_tests.ps1 +++ /dev/null @@ -1,12 +0,0 @@ -# Requirements so far: -# dockerd running -# - image microsoft/nanoserver (matching host base image) docker load -i c:\baseimages\nanoserver.tar -# - image alpine (linux) docker pull --platform=linux alpine - - -# TODO: Add this a parameter for debugging. ie "functional-tests -debug=$true" -#$env:HCSSHIM_FUNCTIONAL_TESTS_DEBUG="yes please" - -#pushd uvm -go test -v -tags "functional uvmcreate uvmscratch uvmscsi uvmvpmem uvmvsmb uvmp9" ./... -#popd \ No newline at end of file diff --git a/vendor/github.com/Microsoft/hcsshim/hcsshim.go b/vendor/github.com/Microsoft/hcsshim/hcsshim.go deleted file mode 100644 index ceb3ac85..00000000 --- a/vendor/github.com/Microsoft/hcsshim/hcsshim.go +++ /dev/null @@ -1,28 +0,0 @@ -// Shim for the Host Compute Service (HCS) to manage Windows Server -// containers and Hyper-V containers. - -package hcsshim - -import ( - "syscall" - - "github.com/Microsoft/hcsshim/internal/hcserror" -) - -//go:generate go run mksyscall_windows.go -output zsyscall_windows.go hcsshim.go - -//sys SetCurrentThreadCompartmentId(compartmentId uint32) (hr error) = iphlpapi.SetCurrentThreadCompartmentId - -const ( - // Specific user-visible exit codes - WaitErrExecFailed = 32767 - - ERROR_GEN_FAILURE = hcserror.ERROR_GEN_FAILURE - ERROR_SHUTDOWN_IN_PROGRESS = syscall.Errno(1115) - WSAEINVAL = syscall.Errno(10022) - - // Timeout on wait calls - TimeoutInfinite = 0xFFFFFFFF -) - -type HcsError = hcserror.HcsError diff --git a/vendor/github.com/Microsoft/hcsshim/hnsendpoint.go b/vendor/github.com/Microsoft/hcsshim/hnsendpoint.go deleted file mode 100644 index 09b3860a..00000000 --- a/vendor/github.com/Microsoft/hcsshim/hnsendpoint.go +++ /dev/null @@ -1,104 +0,0 @@ -package hcsshim - -import ( - "github.com/Microsoft/hcsshim/internal/hns" -) - -// HNSEndpoint represents a network endpoint in HNS -type HNSEndpoint = hns.HNSEndpoint - -// Namespace represents a Compartment. -type Namespace = hns.Namespace - -//SystemType represents the type of the system on which actions are done -type SystemType string - -// SystemType const -const ( - ContainerType SystemType = "Container" - VirtualMachineType SystemType = "VirtualMachine" - HostType SystemType = "Host" -) - -// EndpointAttachDetachRequest is the structure used to send request to the container to modify the system -// Supported resource types are Network and Request Types are Add/Remove -type EndpointAttachDetachRequest = hns.EndpointAttachDetachRequest - -// EndpointResquestResponse is object to get the endpoint request response -type EndpointResquestResponse = hns.EndpointResquestResponse - -// HNSEndpointRequest makes a HNS call to modify/query a network endpoint -func HNSEndpointRequest(method, path, request string) (*HNSEndpoint, error) { - return hns.HNSEndpointRequest(method, path, request) -} - -// HNSListEndpointRequest makes a HNS call to query the list of available endpoints -func HNSListEndpointRequest() ([]HNSEndpoint, error) { - return hns.HNSListEndpointRequest() -} - -// HotAttachEndpoint makes a HCS Call to attach the endpoint to the container -func HotAttachEndpoint(containerID string, endpointID string) error { - endpoint, err := GetHNSEndpointByID(endpointID) - isAttached, err := endpoint.IsAttached(containerID) - if isAttached { - return err - } - return modifyNetworkEndpoint(containerID, endpointID, Add) -} - -// HotDetachEndpoint makes a HCS Call to detach the endpoint from the container -func HotDetachEndpoint(containerID string, endpointID string) error { - endpoint, err := GetHNSEndpointByID(endpointID) - isAttached, err := endpoint.IsAttached(containerID) - if !isAttached { - return err - } - return modifyNetworkEndpoint(containerID, endpointID, Remove) -} - -// ModifyContainer corresponding to the container id, by sending a request -func modifyContainer(id string, request *ResourceModificationRequestResponse) error { - container, err := OpenContainer(id) - if err != nil { - if IsNotExist(err) { - return ErrComputeSystemDoesNotExist - } - return getInnerError(err) - } - defer container.Close() - err = container.Modify(request) - if err != nil { - if IsNotSupported(err) { - return ErrPlatformNotSupported - } - return getInnerError(err) - } - - return nil -} - -func modifyNetworkEndpoint(containerID string, endpointID string, request RequestType) error { - requestMessage := &ResourceModificationRequestResponse{ - Resource: Network, - Request: request, - Data: endpointID, - } - err := modifyContainer(containerID, requestMessage) - - if err != nil { - return err - } - - return nil -} - -// GetHNSEndpointByID get the Endpoint by ID -func GetHNSEndpointByID(endpointID string) (*HNSEndpoint, error) { - return hns.GetHNSEndpointByID(endpointID) -} - -// GetHNSEndpointByName gets the endpoint filtered by Name -func GetHNSEndpointByName(endpointName string) (*HNSEndpoint, error) { - return hns.GetHNSEndpointByName(endpointName) -} diff --git a/vendor/github.com/Microsoft/hcsshim/hnsglobals.go b/vendor/github.com/Microsoft/hcsshim/hnsglobals.go deleted file mode 100644 index 2b538190..00000000 --- a/vendor/github.com/Microsoft/hcsshim/hnsglobals.go +++ /dev/null @@ -1,16 +0,0 @@ -package hcsshim - -import ( - "github.com/Microsoft/hcsshim/internal/hns" -) - -type HNSGlobals = hns.HNSGlobals -type HNSVersion = hns.HNSVersion - -var ( - HNSVersion1803 = hns.HNSVersion1803 -) - -func GetHNSGlobals() (*HNSGlobals, error) { - return hns.GetHNSGlobals() -} diff --git a/vendor/github.com/Microsoft/hcsshim/hnsnetwork.go b/vendor/github.com/Microsoft/hcsshim/hnsnetwork.go deleted file mode 100644 index f775fa1d..00000000 --- a/vendor/github.com/Microsoft/hcsshim/hnsnetwork.go +++ /dev/null @@ -1,36 +0,0 @@ -package hcsshim - -import ( - "github.com/Microsoft/hcsshim/internal/hns" -) - -// Subnet is assoicated with a network and represents a list -// of subnets available to the network -type Subnet = hns.Subnet - -// MacPool is assoicated with a network and represents a list -// of macaddresses available to the network -type MacPool = hns.MacPool - -// HNSNetwork represents a network in HNS -type HNSNetwork = hns.HNSNetwork - -// HNSNetworkRequest makes a call into HNS to update/query a single network -func HNSNetworkRequest(method, path, request string) (*HNSNetwork, error) { - return hns.HNSNetworkRequest(method, path, request) -} - -// HNSListNetworkRequest makes a HNS call to query the list of available networks -func HNSListNetworkRequest(method, path, request string) ([]HNSNetwork, error) { - return hns.HNSListNetworkRequest(method, path, request) -} - -// GetHNSNetworkByID -func GetHNSNetworkByID(networkID string) (*HNSNetwork, error) { - return hns.GetHNSNetworkByID(networkID) -} - -// GetHNSNetworkName filtered by Name -func GetHNSNetworkByName(networkName string) (*HNSNetwork, error) { - return hns.GetHNSNetworkByName(networkName) -} diff --git a/vendor/github.com/Microsoft/hcsshim/hnspolicy.go b/vendor/github.com/Microsoft/hcsshim/hnspolicy.go deleted file mode 100644 index 00ab2636..00000000 --- a/vendor/github.com/Microsoft/hcsshim/hnspolicy.go +++ /dev/null @@ -1,60 +0,0 @@ -package hcsshim - -import ( - "github.com/Microsoft/hcsshim/internal/hns" -) - -// Type of Request Support in ModifySystem -type PolicyType = hns.PolicyType - -// RequestType const -const ( - Nat = hns.Nat - ACL = hns.ACL - PA = hns.PA - VLAN = hns.VLAN - VSID = hns.VSID - VNet = hns.VNet - L2Driver = hns.L2Driver - Isolation = hns.Isolation - QOS = hns.QOS - OutboundNat = hns.OutboundNat - ExternalLoadBalancer = hns.ExternalLoadBalancer - Route = hns.Route - Proxy = hns.Proxy -) - -type ProxyPolicy = hns.ProxyPolicy - -type NatPolicy = hns.NatPolicy - -type QosPolicy = hns.QosPolicy - -type IsolationPolicy = hns.IsolationPolicy - -type VlanPolicy = hns.VlanPolicy - -type VsidPolicy = hns.VsidPolicy - -type PaPolicy = hns.PaPolicy - -type OutboundNatPolicy = hns.OutboundNatPolicy - -type ActionType = hns.ActionType -type DirectionType = hns.DirectionType -type RuleType = hns.RuleType - -const ( - Allow = hns.Allow - Block = hns.Block - - In = hns.In - Out = hns.Out - - Host = hns.Host - Switch = hns.Switch -) - -type ACLPolicy = hns.ACLPolicy - -type Policy = hns.Policy diff --git a/vendor/github.com/Microsoft/hcsshim/hnspolicylist.go b/vendor/github.com/Microsoft/hcsshim/hnspolicylist.go deleted file mode 100644 index 55aaa4a5..00000000 --- a/vendor/github.com/Microsoft/hcsshim/hnspolicylist.go +++ /dev/null @@ -1,47 +0,0 @@ -package hcsshim - -import ( - "github.com/Microsoft/hcsshim/internal/hns" -) - -// RoutePolicy is a structure defining schema for Route based Policy -type RoutePolicy = hns.RoutePolicy - -// ELBPolicy is a structure defining schema for ELB LoadBalancing based Policy -type ELBPolicy = hns.ELBPolicy - -// LBPolicy is a structure defining schema for LoadBalancing based Policy -type LBPolicy = hns.LBPolicy - -// PolicyList is a structure defining schema for Policy list request -type PolicyList = hns.PolicyList - -// HNSPolicyListRequest makes a call into HNS to update/query a single network -func HNSPolicyListRequest(method, path, request string) (*PolicyList, error) { - return hns.HNSPolicyListRequest(method, path, request) -} - -// HNSListPolicyListRequest gets all the policy list -func HNSListPolicyListRequest() ([]PolicyList, error) { - return hns.HNSListPolicyListRequest() -} - -// PolicyListRequest makes a HNS call to modify/query a network policy list -func PolicyListRequest(method, path, request string) (*PolicyList, error) { - return hns.PolicyListRequest(method, path, request) -} - -// GetPolicyListByID get the policy list by ID -func GetPolicyListByID(policyListID string) (*PolicyList, error) { - return hns.GetPolicyListByID(policyListID) -} - -// AddLoadBalancer policy list for the specified endpoints -func AddLoadBalancer(endpoints []HNSEndpoint, isILB bool, sourceVIP, vip string, protocol uint16, internalPort uint16, externalPort uint16) (*PolicyList, error) { - return hns.AddLoadBalancer(endpoints, isILB, sourceVIP, vip, protocol, internalPort, externalPort) -} - -// AddRoute adds route policy list for the specified endpoints -func AddRoute(endpoints []HNSEndpoint, destinationPrefix string, nextHop string, encapEnabled bool) (*PolicyList, error) { - return hns.AddRoute(endpoints, destinationPrefix, nextHop, encapEnabled) -} diff --git a/vendor/github.com/Microsoft/hcsshim/hnssupport.go b/vendor/github.com/Microsoft/hcsshim/hnssupport.go deleted file mode 100644 index 69405244..00000000 --- a/vendor/github.com/Microsoft/hcsshim/hnssupport.go +++ /dev/null @@ -1,13 +0,0 @@ -package hcsshim - -import ( - "github.com/Microsoft/hcsshim/internal/hns" -) - -type HNSSupportedFeatures = hns.HNSSupportedFeatures - -type HNSAclFeatures = hns.HNSAclFeatures - -func GetHNSSupportedFeatures() HNSSupportedFeatures { - return hns.GetHNSSupportedFeatures() -} diff --git a/vendor/github.com/Microsoft/hcsshim/interface.go b/vendor/github.com/Microsoft/hcsshim/interface.go deleted file mode 100644 index 5b91e0cc..00000000 --- a/vendor/github.com/Microsoft/hcsshim/interface.go +++ /dev/null @@ -1,114 +0,0 @@ -package hcsshim - -import ( - "io" - "time" - - "github.com/Microsoft/hcsshim/internal/schema1" -) - -// ProcessConfig is used as both the input of Container.CreateProcess -// and to convert the parameters to JSON for passing onto the HCS -type ProcessConfig = schema1.ProcessConfig - -type Layer = schema1.Layer -type MappedDir = schema1.MappedDir -type MappedPipe = schema1.MappedPipe -type HvRuntime = schema1.HvRuntime -type MappedVirtualDisk = schema1.MappedVirtualDisk - -// AssignedDevice represents a device that has been directly assigned to a container -// -// NOTE: Support added in RS5 -type AssignedDevice = schema1.AssignedDevice - -// ContainerConfig is used as both the input of CreateContainer -// and to convert the parameters to JSON for passing onto the HCS -type ContainerConfig = schema1.ContainerConfig - -type ComputeSystemQuery = schema1.ComputeSystemQuery - -// Container represents a created (but not necessarily running) container. -type Container interface { - // Start synchronously starts the container. - Start() error - - // Shutdown requests a container shutdown, but it may not actually be shutdown until Wait() succeeds. - Shutdown() error - - // Terminate requests a container terminate, but it may not actually be terminated until Wait() succeeds. - Terminate() error - - // Waits synchronously waits for the container to shutdown or terminate. - Wait() error - - // WaitTimeout synchronously waits for the container to terminate or the duration to elapse. It - // returns false if timeout occurs. - WaitTimeout(time.Duration) error - - // Pause pauses the execution of a container. - Pause() error - - // Resume resumes the execution of a container. - Resume() error - - // HasPendingUpdates returns true if the container has updates pending to install. - HasPendingUpdates() (bool, error) - - // Statistics returns statistics for a container. - Statistics() (Statistics, error) - - // ProcessList returns details for the processes in a container. - ProcessList() ([]ProcessListItem, error) - - // MappedVirtualDisks returns virtual disks mapped to a utility VM, indexed by controller - MappedVirtualDisks() (map[int]MappedVirtualDiskController, error) - - // CreateProcess launches a new process within the container. - CreateProcess(c *ProcessConfig) (Process, error) - - // OpenProcess gets an interface to an existing process within the container. - OpenProcess(pid int) (Process, error) - - // Close cleans up any state associated with the container but does not terminate or wait for it. - Close() error - - // Modify the System - Modify(config *ResourceModificationRequestResponse) error -} - -// Process represents a running or exited process. -type Process interface { - // Pid returns the process ID of the process within the container. - Pid() int - - // Kill signals the process to terminate but does not wait for it to finish terminating. - Kill() error - - // Wait waits for the process to exit. - Wait() error - - // WaitTimeout waits for the process to exit or the duration to elapse. It returns - // false if timeout occurs. - WaitTimeout(time.Duration) error - - // ExitCode returns the exit code of the process. The process must have - // already terminated. - ExitCode() (int, error) - - // ResizeConsole resizes the console of the process. - ResizeConsole(width, height uint16) error - - // Stdio returns the stdin, stdout, and stderr pipes, respectively. Closing - // these pipes does not close the underlying pipes; it should be possible to - // call this multiple times to get multiple interfaces. - Stdio() (io.WriteCloser, io.ReadCloser, io.ReadCloser, error) - - // CloseStdin closes the write side of the stdin pipe so that the process is - // notified on the read side that there is no more data in stdin. - CloseStdin() error - - // Close cleans up any state associated with the process but does not kill - // or wait on it. - Close() error -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/cow/cow.go b/vendor/github.com/Microsoft/hcsshim/internal/cow/cow.go deleted file mode 100644 index b8e2d4f3..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/cow/cow.go +++ /dev/null @@ -1,85 +0,0 @@ -package cow - -import ( - "context" - "io" - - "github.com/Microsoft/hcsshim/internal/schema1" - hcsschema "github.com/Microsoft/hcsshim/internal/schema2" -) - -// Process is the interface for an OS process running in a container or utility VM. -type Process interface { - // Close releases resources associated with the process and closes the - // writer and readers returned by Stdio. Depending on the implementation, - // this may also terminate the process. - Close() error - // CloseStdin causes the process's stdin handle to receive EOF/EPIPE/whatever - // is appropriate to indicate that no more data is available. - CloseStdin(ctx context.Context) error - // Pid returns the process ID. - Pid() int - // Stdio returns the stdio streams for a process. These may be nil if a stream - // was not requested during CreateProcess. - Stdio() (_ io.Writer, _ io.Reader, _ io.Reader) - // ResizeConsole resizes the virtual terminal associated with the process. - ResizeConsole(ctx context.Context, width, height uint16) error - // Kill sends a SIGKILL or equivalent signal to the process and returns whether - // the signal was delivered. It does not wait for the process to terminate. - Kill(ctx context.Context) (bool, error) - // Signal sends a signal to the process and returns whether the signal was - // delivered. The input is OS specific (either - // guestrequest.SignalProcessOptionsWCOW or - // guestrequest.SignalProcessOptionsLCOW). It does not wait for the process - // to terminate. - Signal(ctx context.Context, options interface{}) (bool, error) - // Wait waits for the process to complete, or for a connection to the process to be - // terminated by some error condition (including calling Close). - Wait() error - // ExitCode returns the exit code of the process. Returns an error if the process is - // not running. - ExitCode() (int, error) -} - -// ProcessHost is the interface for creating processes. -type ProcessHost interface { - // CreateProcess creates a process. The configuration is host specific - // (either hcsschema.ProcessParameters or lcow.ProcessParameters). - CreateProcess(ctx context.Context, config interface{}) (Process, error) - // OS returns the host's operating system, "linux" or "windows". - OS() string - // IsOCI specifies whether this is an OCI-compliant process host. If true, - // then the configuration passed to CreateProcess should have an OCI process - // spec (or nil if this is the initial process in an OCI container). - // Otherwise, it should have the HCS-specific process parameters. - IsOCI() bool -} - -// Container is the interface for container objects, either running on the host or -// in a utility VM. -type Container interface { - ProcessHost - // Close releases the resources associated with the container. Depending on - // the implementation, this may also terminate the container. - Close() error - // ID returns the container ID. - ID() string - // Properties returns the requested container properties targeting a V1 schema container. - Properties(ctx context.Context, types ...schema1.PropertyType) (*schema1.ContainerProperties, error) - // PropertiesV2 returns the requested container properties targeting a V2 schema container. - PropertiesV2(ctx context.Context, types ...hcsschema.PropertyType) (*hcsschema.Properties, error) - // Start starts a container. - Start(ctx context.Context) error - // Shutdown sends a shutdown request to the container (but does not wait for - // the shutdown to complete). - Shutdown(ctx context.Context) error - // Terminate sends a terminate request to the container (but does not wait - // for the terminate to complete). - Terminate(ctx context.Context) error - // Wait waits for the container to terminate, or for the connection to the - // container to be terminated by some error condition (including calling - // Close). - Wait() error - // Modify sends a request to modify container resources - Modify(ctx context.Context, config interface{}) error -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hcs/callback.go b/vendor/github.com/Microsoft/hcsshim/internal/hcs/callback.go deleted file mode 100644 index cebbe75a..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hcs/callback.go +++ /dev/null @@ -1,161 +0,0 @@ -package hcs - -import ( - "fmt" - "sync" - "syscall" - - "github.com/Microsoft/hcsshim/internal/interop" - "github.com/Microsoft/hcsshim/internal/logfields" - "github.com/Microsoft/hcsshim/internal/vmcompute" - "github.com/sirupsen/logrus" -) - -var ( - nextCallback uintptr - callbackMap = map[uintptr]*notifcationWatcherContext{} - callbackMapLock = sync.RWMutex{} - - notificationWatcherCallback = syscall.NewCallback(notificationWatcher) - - // Notifications for HCS_SYSTEM handles - hcsNotificationSystemExited hcsNotification = 0x00000001 - hcsNotificationSystemCreateCompleted hcsNotification = 0x00000002 - hcsNotificationSystemStartCompleted hcsNotification = 0x00000003 - hcsNotificationSystemPauseCompleted hcsNotification = 0x00000004 - hcsNotificationSystemResumeCompleted hcsNotification = 0x00000005 - hcsNotificationSystemCrashReport hcsNotification = 0x00000006 - hcsNotificationSystemSiloJobCreated hcsNotification = 0x00000007 - hcsNotificationSystemSaveCompleted hcsNotification = 0x00000008 - hcsNotificationSystemRdpEnhancedModeStateChanged hcsNotification = 0x00000009 - hcsNotificationSystemShutdownFailed hcsNotification = 0x0000000A - hcsNotificationSystemGetPropertiesCompleted hcsNotification = 0x0000000B - hcsNotificationSystemModifyCompleted hcsNotification = 0x0000000C - hcsNotificationSystemCrashInitiated hcsNotification = 0x0000000D - hcsNotificationSystemGuestConnectionClosed hcsNotification = 0x0000000E - - // Notifications for HCS_PROCESS handles - hcsNotificationProcessExited hcsNotification = 0x00010000 - - // Common notifications - hcsNotificationInvalid hcsNotification = 0x00000000 - hcsNotificationServiceDisconnect hcsNotification = 0x01000000 -) - -type hcsNotification uint32 - -func (hn hcsNotification) String() string { - switch hn { - case hcsNotificationSystemExited: - return "SystemExited" - case hcsNotificationSystemCreateCompleted: - return "SystemCreateCompleted" - case hcsNotificationSystemStartCompleted: - return "SystemStartCompleted" - case hcsNotificationSystemPauseCompleted: - return "SystemPauseCompleted" - case hcsNotificationSystemResumeCompleted: - return "SystemResumeCompleted" - case hcsNotificationSystemCrashReport: - return "SystemCrashReport" - case hcsNotificationSystemSiloJobCreated: - return "SystemSiloJobCreated" - case hcsNotificationSystemSaveCompleted: - return "SystemSaveCompleted" - case hcsNotificationSystemRdpEnhancedModeStateChanged: - return "SystemRdpEnhancedModeStateChanged" - case hcsNotificationSystemShutdownFailed: - return "SystemShutdownFailed" - case hcsNotificationSystemGetPropertiesCompleted: - return "SystemGetPropertiesCompleted" - case hcsNotificationSystemModifyCompleted: - return "SystemModifyCompleted" - case hcsNotificationSystemCrashInitiated: - return "SystemCrashInitiated" - case hcsNotificationSystemGuestConnectionClosed: - return "SystemGuestConnectionClosed" - case hcsNotificationProcessExited: - return "ProcessExited" - case hcsNotificationInvalid: - return "Invalid" - case hcsNotificationServiceDisconnect: - return "ServiceDisconnect" - default: - return fmt.Sprintf("Unknown: %d", hn) - } -} - -type notificationChannel chan error - -type notifcationWatcherContext struct { - channels notificationChannels - handle vmcompute.HcsCallback - - systemID string - processID int -} - -type notificationChannels map[hcsNotification]notificationChannel - -func newSystemChannels() notificationChannels { - channels := make(notificationChannels) - for _, notif := range []hcsNotification{ - hcsNotificationServiceDisconnect, - hcsNotificationSystemExited, - hcsNotificationSystemCreateCompleted, - hcsNotificationSystemStartCompleted, - hcsNotificationSystemPauseCompleted, - hcsNotificationSystemResumeCompleted, - hcsNotificationSystemSaveCompleted, - } { - channels[notif] = make(notificationChannel, 1) - } - return channels -} - -func newProcessChannels() notificationChannels { - channels := make(notificationChannels) - for _, notif := range []hcsNotification{ - hcsNotificationServiceDisconnect, - hcsNotificationProcessExited, - } { - channels[notif] = make(notificationChannel, 1) - } - return channels -} - -func closeChannels(channels notificationChannels) { - for _, c := range channels { - close(c) - } -} - -func notificationWatcher(notificationType hcsNotification, callbackNumber uintptr, notificationStatus uintptr, notificationData *uint16) uintptr { - var result error - if int32(notificationStatus) < 0 { - result = interop.Win32FromHresult(notificationStatus) - } - - callbackMapLock.RLock() - context := callbackMap[callbackNumber] - callbackMapLock.RUnlock() - - if context == nil { - return 0 - } - - log := logrus.WithFields(logrus.Fields{ - "notification-type": notificationType.String(), - "system-id": context.systemID, - }) - if context.processID != 0 { - log.Data[logfields.ProcessID] = context.processID - } - log.Debug("HCS notification") - - if channel, ok := context.channels[notificationType]; ok { - channel <- result - } - - return 0 -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hcs/errors.go b/vendor/github.com/Microsoft/hcsshim/internal/hcs/errors.go deleted file mode 100644 index bca824b8..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hcs/errors.go +++ /dev/null @@ -1,343 +0,0 @@ -package hcs - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net" - "syscall" - - "github.com/Microsoft/hcsshim/internal/log" -) - -var ( - // ErrComputeSystemDoesNotExist is an error encountered when the container being operated on no longer exists - ErrComputeSystemDoesNotExist = syscall.Errno(0xc037010e) - - // ErrElementNotFound is an error encountered when the object being referenced does not exist - ErrElementNotFound = syscall.Errno(0x490) - - // ErrElementNotFound is an error encountered when the object being referenced does not exist - ErrNotSupported = syscall.Errno(0x32) - - // ErrInvalidData is an error encountered when the request being sent to hcs is invalid/unsupported - // decimal -2147024883 / hex 0x8007000d - ErrInvalidData = syscall.Errno(0xd) - - // ErrHandleClose is an error encountered when the handle generating the notification being waited on has been closed - ErrHandleClose = errors.New("hcsshim: the handle generating this notification has been closed") - - // ErrAlreadyClosed is an error encountered when using a handle that has been closed by the Close method - ErrAlreadyClosed = errors.New("hcsshim: the handle has already been closed") - - // ErrInvalidNotificationType is an error encountered when an invalid notification type is used - ErrInvalidNotificationType = errors.New("hcsshim: invalid notification type") - - // ErrInvalidProcessState is an error encountered when the process is not in a valid state for the requested operation - ErrInvalidProcessState = errors.New("the process is in an invalid state for the attempted operation") - - // ErrTimeout is an error encountered when waiting on a notification times out - ErrTimeout = errors.New("hcsshim: timeout waiting for notification") - - // ErrUnexpectedContainerExit is the error encountered when a container exits while waiting for - // a different expected notification - ErrUnexpectedContainerExit = errors.New("unexpected container exit") - - // ErrUnexpectedProcessAbort is the error encountered when communication with the compute service - // is lost while waiting for a notification - ErrUnexpectedProcessAbort = errors.New("lost communication with compute service") - - // ErrUnexpectedValue is an error encountered when hcs returns an invalid value - ErrUnexpectedValue = errors.New("unexpected value returned from hcs") - - // ErrVmcomputeAlreadyStopped is an error encountered when a shutdown or terminate request is made on a stopped container - ErrVmcomputeAlreadyStopped = syscall.Errno(0xc0370110) - - // ErrVmcomputeOperationPending is an error encountered when the operation is being completed asynchronously - ErrVmcomputeOperationPending = syscall.Errno(0xC0370103) - - // ErrVmcomputeOperationInvalidState is an error encountered when the compute system is not in a valid state for the requested operation - ErrVmcomputeOperationInvalidState = syscall.Errno(0xc0370105) - - // ErrProcNotFound is an error encountered when the the process cannot be found - ErrProcNotFound = syscall.Errno(0x7f) - - // ErrVmcomputeOperationAccessIsDenied is an error which can be encountered when enumerating compute systems in RS1/RS2 - // builds when the underlying silo might be in the process of terminating. HCS was fixed in RS3. - ErrVmcomputeOperationAccessIsDenied = syscall.Errno(0x5) - - // ErrVmcomputeInvalidJSON is an error encountered when the compute system does not support/understand the messages sent by management - ErrVmcomputeInvalidJSON = syscall.Errno(0xc037010d) - - // ErrVmcomputeUnknownMessage is an error encountered guest compute system doesn't support the message - ErrVmcomputeUnknownMessage = syscall.Errno(0xc037010b) - - // ErrVmcomputeUnexpectedExit is an error encountered when the compute system terminates unexpectedly - ErrVmcomputeUnexpectedExit = syscall.Errno(0xC0370106) - - // ErrNotSupported is an error encountered when hcs doesn't support the request - ErrPlatformNotSupported = errors.New("unsupported platform request") -) - -type ErrorEvent struct { - Message string `json:"Message,omitempty"` // Fully formated error message - StackTrace string `json:"StackTrace,omitempty"` // Stack trace in string form - Provider string `json:"Provider,omitempty"` - EventID uint16 `json:"EventId,omitempty"` - Flags uint32 `json:"Flags,omitempty"` - Source string `json:"Source,omitempty"` - //Data []EventData `json:"Data,omitempty"` // Omit this as HCS doesn't encode this well. It's more confusing to include. It is however logged in debug mode (see processHcsResult function) -} - -type hcsResult struct { - Error int32 - ErrorMessage string - ErrorEvents []ErrorEvent `json:"ErrorEvents,omitempty"` -} - -func (ev *ErrorEvent) String() string { - evs := "[Event Detail: " + ev.Message - if ev.StackTrace != "" { - evs += " Stack Trace: " + ev.StackTrace - } - if ev.Provider != "" { - evs += " Provider: " + ev.Provider - } - if ev.EventID != 0 { - evs = fmt.Sprintf("%s EventID: %d", evs, ev.EventID) - } - if ev.Flags != 0 { - evs = fmt.Sprintf("%s flags: %d", evs, ev.Flags) - } - if ev.Source != "" { - evs += " Source: " + ev.Source - } - evs += "]" - return evs -} - -func processHcsResult(ctx context.Context, resultJSON string) []ErrorEvent { - if resultJSON != "" { - result := &hcsResult{} - if err := json.Unmarshal([]byte(resultJSON), result); err != nil { - log.G(ctx).WithError(err).Warning("Could not unmarshal HCS result") - return nil - } - return result.ErrorEvents - } - return nil -} - -type HcsError struct { - Op string - Err error - Events []ErrorEvent -} - -var _ net.Error = &HcsError{} - -func (e *HcsError) Error() string { - s := e.Op + ": " + e.Err.Error() - for _, ev := range e.Events { - s += "\n" + ev.String() - } - return s -} - -func (e *HcsError) Temporary() bool { - err, ok := e.Err.(net.Error) - return ok && err.Temporary() -} - -func (e *HcsError) Timeout() bool { - err, ok := e.Err.(net.Error) - return ok && err.Timeout() -} - -// ProcessError is an error encountered in HCS during an operation on a Process object -type ProcessError struct { - SystemID string - Pid int - Op string - Err error - Events []ErrorEvent -} - -var _ net.Error = &ProcessError{} - -// SystemError is an error encountered in HCS during an operation on a Container object -type SystemError struct { - ID string - Op string - Err error - Extra string - Events []ErrorEvent -} - -var _ net.Error = &SystemError{} - -func (e *SystemError) Error() string { - s := e.Op + " " + e.ID + ": " + e.Err.Error() - for _, ev := range e.Events { - s += "\n" + ev.String() - } - if e.Extra != "" { - s += "\n(extra info: " + e.Extra + ")" - } - return s -} - -func (e *SystemError) Temporary() bool { - err, ok := e.Err.(net.Error) - return ok && err.Temporary() -} - -func (e *SystemError) Timeout() bool { - err, ok := e.Err.(net.Error) - return ok && err.Timeout() -} - -func makeSystemError(system *System, op string, extra string, err error, events []ErrorEvent) error { - // Don't double wrap errors - if _, ok := err.(*SystemError); ok { - return err - } - return &SystemError{ - ID: system.ID(), - Op: op, - Extra: extra, - Err: err, - Events: events, - } -} - -func (e *ProcessError) Error() string { - s := fmt.Sprintf("%s %s:%d: %s", e.Op, e.SystemID, e.Pid, e.Err.Error()) - for _, ev := range e.Events { - s += "\n" + ev.String() - } - return s -} - -func (e *ProcessError) Temporary() bool { - err, ok := e.Err.(net.Error) - return ok && err.Temporary() -} - -func (e *ProcessError) Timeout() bool { - err, ok := e.Err.(net.Error) - return ok && err.Timeout() -} - -func makeProcessError(process *Process, op string, err error, events []ErrorEvent) error { - // Don't double wrap errors - if _, ok := err.(*ProcessError); ok { - return err - } - return &ProcessError{ - Pid: process.Pid(), - SystemID: process.SystemID(), - Op: op, - Err: err, - Events: events, - } -} - -// IsNotExist checks if an error is caused by the Container or Process not existing. -// Note: Currently, ErrElementNotFound can mean that a Process has either -// already exited, or does not exist. Both IsAlreadyStopped and IsNotExist -// will currently return true when the error is ErrElementNotFound or ErrProcNotFound. -func IsNotExist(err error) bool { - err = getInnerError(err) - return err == ErrComputeSystemDoesNotExist || - err == ErrElementNotFound || - err == ErrProcNotFound -} - -// IsAlreadyClosed checks if an error is caused by the Container or Process having been -// already closed by a call to the Close() method. -func IsAlreadyClosed(err error) bool { - err = getInnerError(err) - return err == ErrAlreadyClosed -} - -// IsPending returns a boolean indicating whether the error is that -// the requested operation is being completed in the background. -func IsPending(err error) bool { - err = getInnerError(err) - return err == ErrVmcomputeOperationPending -} - -// IsTimeout returns a boolean indicating whether the error is caused by -// a timeout waiting for the operation to complete. -func IsTimeout(err error) bool { - if err, ok := err.(net.Error); ok && err.Timeout() { - return true - } - err = getInnerError(err) - return err == ErrTimeout -} - -// IsAlreadyStopped returns a boolean indicating whether the error is caused by -// a Container or Process being already stopped. -// Note: Currently, ErrElementNotFound can mean that a Process has either -// already exited, or does not exist. Both IsAlreadyStopped and IsNotExist -// will currently return true when the error is ErrElementNotFound or ErrProcNotFound. -func IsAlreadyStopped(err error) bool { - err = getInnerError(err) - return err == ErrVmcomputeAlreadyStopped || - err == ErrElementNotFound || - err == ErrProcNotFound -} - -// IsNotSupported returns a boolean indicating whether the error is caused by -// unsupported platform requests -// Note: Currently Unsupported platform requests can be mean either -// ErrVmcomputeInvalidJSON, ErrInvalidData, ErrNotSupported or ErrVmcomputeUnknownMessage -// is thrown from the Platform -func IsNotSupported(err error) bool { - err = getInnerError(err) - // If Platform doesn't recognize or support the request sent, below errors are seen - return err == ErrVmcomputeInvalidJSON || - err == ErrInvalidData || - err == ErrNotSupported || - err == ErrVmcomputeUnknownMessage -} - -// IsOperationInvalidState returns true when err is caused by -// `ErrVmcomputeOperationInvalidState`. -func IsOperationInvalidState(err error) bool { - err = getInnerError(err) - return err == ErrVmcomputeOperationInvalidState -} - -// IsAccessIsDenied returns true when err is caused by -// `ErrVmcomputeOperationAccessIsDenied`. -func IsAccessIsDenied(err error) bool { - err = getInnerError(err) - return err == ErrVmcomputeOperationAccessIsDenied -} - -func getInnerError(err error) error { - switch pe := err.(type) { - case nil: - return nil - case *HcsError: - err = pe.Err - case *SystemError: - err = pe.Err - case *ProcessError: - err = pe.Err - } - return err -} - -func getOperationLogResult(err error) (string, error) { - switch err { - case nil: - return "Success", nil - default: - return "Error", err - } -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hcs/process.go b/vendor/github.com/Microsoft/hcsshim/internal/hcs/process.go deleted file mode 100644 index 2ad978f2..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hcs/process.go +++ /dev/null @@ -1,474 +0,0 @@ -package hcs - -import ( - "context" - "encoding/json" - "io" - "sync" - "syscall" - "time" - - "github.com/Microsoft/hcsshim/internal/log" - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/Microsoft/hcsshim/internal/vmcompute" - "go.opencensus.io/trace" -) - -// ContainerError is an error encountered in HCS -type Process struct { - handleLock sync.RWMutex - handle vmcompute.HcsProcess - processID int - system *System - hasCachedStdio bool - stdioLock sync.Mutex - stdin io.WriteCloser - stdout io.ReadCloser - stderr io.ReadCloser - callbackNumber uintptr - - closedWaitOnce sync.Once - waitBlock chan struct{} - exitCode int - waitError error -} - -func newProcess(process vmcompute.HcsProcess, processID int, computeSystem *System) *Process { - return &Process{ - handle: process, - processID: processID, - system: computeSystem, - waitBlock: make(chan struct{}), - } -} - -type processModifyRequest struct { - Operation string - ConsoleSize *consoleSize `json:",omitempty"` - CloseHandle *closeHandle `json:",omitempty"` -} - -type consoleSize struct { - Height uint16 - Width uint16 -} - -type closeHandle struct { - Handle string -} - -type processStatus struct { - ProcessID uint32 - Exited bool - ExitCode uint32 - LastWaitResult int32 -} - -const ( - stdIn string = "StdIn" - stdOut string = "StdOut" - stdErr string = "StdErr" -) - -const ( - modifyConsoleSize string = "ConsoleSize" - modifyCloseHandle string = "CloseHandle" -) - -// Pid returns the process ID of the process within the container. -func (process *Process) Pid() int { - return process.processID -} - -// SystemID returns the ID of the process's compute system. -func (process *Process) SystemID() string { - return process.system.ID() -} - -func (process *Process) processSignalResult(ctx context.Context, err error) (bool, error) { - switch err { - case nil: - return true, nil - case ErrVmcomputeOperationInvalidState, ErrComputeSystemDoesNotExist, ErrElementNotFound: - select { - case <-process.waitBlock: - // The process exit notification has already arrived. - default: - // The process should be gone, but we have not received the notification. - // After a second, force unblock the process wait to work around a possible - // deadlock in the HCS. - go func() { - time.Sleep(time.Second) - process.closedWaitOnce.Do(func() { - log.G(ctx).WithError(err).Warn("force unblocking process waits") - process.exitCode = -1 - process.waitError = err - close(process.waitBlock) - }) - }() - } - return false, nil - default: - return false, err - } -} - -// Signal signals the process with `options`. -// -// For LCOW `guestrequest.SignalProcessOptionsLCOW`. -// -// For WCOW `guestrequest.SignalProcessOptionsWCOW`. -func (process *Process) Signal(ctx context.Context, options interface{}) (bool, error) { - process.handleLock.RLock() - defer process.handleLock.RUnlock() - - operation := "hcsshim::Process::Signal" - - if process.handle == 0 { - return false, makeProcessError(process, operation, ErrAlreadyClosed, nil) - } - - optionsb, err := json.Marshal(options) - if err != nil { - return false, err - } - - resultJSON, err := vmcompute.HcsSignalProcess(ctx, process.handle, string(optionsb)) - events := processHcsResult(ctx, resultJSON) - delivered, err := process.processSignalResult(ctx, err) - if err != nil { - err = makeProcessError(process, operation, err, events) - } - return delivered, err -} - -// Kill signals the process to terminate but does not wait for it to finish terminating. -func (process *Process) Kill(ctx context.Context) (bool, error) { - process.handleLock.RLock() - defer process.handleLock.RUnlock() - - operation := "hcsshim::Process::Kill" - - if process.handle == 0 { - return false, makeProcessError(process, operation, ErrAlreadyClosed, nil) - } - - resultJSON, err := vmcompute.HcsTerminateProcess(ctx, process.handle) - events := processHcsResult(ctx, resultJSON) - delivered, err := process.processSignalResult(ctx, err) - if err != nil { - err = makeProcessError(process, operation, err, events) - } - return delivered, err -} - -// waitBackground waits for the process exit notification. Once received sets -// `process.waitError` (if any) and unblocks all `Wait` calls. -// -// This MUST be called exactly once per `process.handle` but `Wait` is safe to -// call multiple times. -func (process *Process) waitBackground() { - operation := "hcsshim::Process::waitBackground" - ctx, span := trace.StartSpan(context.Background(), operation) - defer span.End() - span.AddAttributes( - trace.StringAttribute("cid", process.SystemID()), - trace.Int64Attribute("pid", int64(process.processID))) - - var ( - err error - exitCode = -1 - ) - - err = waitForNotification(ctx, process.callbackNumber, hcsNotificationProcessExited, nil) - if err != nil { - err = makeProcessError(process, operation, err, nil) - log.G(ctx).WithError(err).Error("failed wait") - } else { - process.handleLock.RLock() - defer process.handleLock.RUnlock() - - // Make sure we didnt race with Close() here - if process.handle != 0 { - propertiesJSON, resultJSON, err := vmcompute.HcsGetProcessProperties(ctx, process.handle) - events := processHcsResult(ctx, resultJSON) - if err != nil { - err = makeProcessError(process, operation, err, events) - } else { - properties := &processStatus{} - err = json.Unmarshal([]byte(propertiesJSON), properties) - if err != nil { - err = makeProcessError(process, operation, err, nil) - } else { - if properties.LastWaitResult != 0 { - log.G(ctx).WithField("wait-result", properties.LastWaitResult).Warning("non-zero last wait result") - } else { - exitCode = int(properties.ExitCode) - } - } - } - } - } - log.G(ctx).WithField("exitCode", exitCode).Debug("process exited") - - process.closedWaitOnce.Do(func() { - process.exitCode = exitCode - process.waitError = err - close(process.waitBlock) - }) - oc.SetSpanStatus(span, err) -} - -// Wait waits for the process to exit. If the process has already exited returns -// the pervious error (if any). -func (process *Process) Wait() error { - <-process.waitBlock - return process.waitError -} - -// ResizeConsole resizes the console of the process. -func (process *Process) ResizeConsole(ctx context.Context, width, height uint16) error { - process.handleLock.RLock() - defer process.handleLock.RUnlock() - - operation := "hcsshim::Process::ResizeConsole" - - if process.handle == 0 { - return makeProcessError(process, operation, ErrAlreadyClosed, nil) - } - - modifyRequest := processModifyRequest{ - Operation: modifyConsoleSize, - ConsoleSize: &consoleSize{ - Height: height, - Width: width, - }, - } - - modifyRequestb, err := json.Marshal(modifyRequest) - if err != nil { - return err - } - - resultJSON, err := vmcompute.HcsModifyProcess(ctx, process.handle, string(modifyRequestb)) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return makeProcessError(process, operation, err, events) - } - - return nil -} - -// ExitCode returns the exit code of the process. The process must have -// already terminated. -func (process *Process) ExitCode() (int, error) { - select { - case <-process.waitBlock: - if process.waitError != nil { - return -1, process.waitError - } - return process.exitCode, nil - default: - return -1, makeProcessError(process, "hcsshim::Process::ExitCode", ErrInvalidProcessState, nil) - } -} - -// StdioLegacy returns the stdin, stdout, and stderr pipes, respectively. Closing -// these pipes does not close the underlying pipes. Once returned, these pipes -// are the responsibility of the caller to close. -func (process *Process) StdioLegacy() (_ io.WriteCloser, _ io.ReadCloser, _ io.ReadCloser, err error) { - operation := "hcsshim::Process::StdioLegacy" - ctx, span := trace.StartSpan(context.Background(), operation) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("cid", process.SystemID()), - trace.Int64Attribute("pid", int64(process.processID))) - - process.handleLock.RLock() - defer process.handleLock.RUnlock() - - if process.handle == 0 { - return nil, nil, nil, makeProcessError(process, operation, ErrAlreadyClosed, nil) - } - - process.stdioLock.Lock() - defer process.stdioLock.Unlock() - if process.hasCachedStdio { - stdin, stdout, stderr := process.stdin, process.stdout, process.stderr - process.stdin, process.stdout, process.stderr = nil, nil, nil - process.hasCachedStdio = false - return stdin, stdout, stderr, nil - } - - processInfo, resultJSON, err := vmcompute.HcsGetProcessInfo(ctx, process.handle) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return nil, nil, nil, makeProcessError(process, operation, err, events) - } - - pipes, err := makeOpenFiles([]syscall.Handle{processInfo.StdInput, processInfo.StdOutput, processInfo.StdError}) - if err != nil { - return nil, nil, nil, makeProcessError(process, operation, err, nil) - } - - return pipes[0], pipes[1], pipes[2], nil -} - -// Stdio returns the stdin, stdout, and stderr pipes, respectively. -// To close them, close the process handle. -func (process *Process) Stdio() (stdin io.Writer, stdout, stderr io.Reader) { - process.stdioLock.Lock() - defer process.stdioLock.Unlock() - return process.stdin, process.stdout, process.stderr -} - -// CloseStdin closes the write side of the stdin pipe so that the process is -// notified on the read side that there is no more data in stdin. -func (process *Process) CloseStdin(ctx context.Context) error { - process.handleLock.RLock() - defer process.handleLock.RUnlock() - - operation := "hcsshim::Process::CloseStdin" - - if process.handle == 0 { - return makeProcessError(process, operation, ErrAlreadyClosed, nil) - } - - modifyRequest := processModifyRequest{ - Operation: modifyCloseHandle, - CloseHandle: &closeHandle{ - Handle: stdIn, - }, - } - - modifyRequestb, err := json.Marshal(modifyRequest) - if err != nil { - return err - } - - resultJSON, err := vmcompute.HcsModifyProcess(ctx, process.handle, string(modifyRequestb)) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return makeProcessError(process, operation, err, events) - } - - process.stdioLock.Lock() - if process.stdin != nil { - process.stdin.Close() - process.stdin = nil - } - process.stdioLock.Unlock() - - return nil -} - -// Close cleans up any state associated with the process but does not kill -// or wait on it. -func (process *Process) Close() (err error) { - operation := "hcsshim::Process::Close" - ctx, span := trace.StartSpan(context.Background(), operation) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("cid", process.SystemID()), - trace.Int64Attribute("pid", int64(process.processID))) - - process.handleLock.Lock() - defer process.handleLock.Unlock() - - // Don't double free this - if process.handle == 0 { - return nil - } - - process.stdioLock.Lock() - if process.stdin != nil { - process.stdin.Close() - process.stdin = nil - } - if process.stdout != nil { - process.stdout.Close() - process.stdout = nil - } - if process.stderr != nil { - process.stderr.Close() - process.stderr = nil - } - process.stdioLock.Unlock() - - if err = process.unregisterCallback(ctx); err != nil { - return makeProcessError(process, operation, err, nil) - } - - if err = vmcompute.HcsCloseProcess(ctx, process.handle); err != nil { - return makeProcessError(process, operation, err, nil) - } - - process.handle = 0 - process.closedWaitOnce.Do(func() { - process.exitCode = -1 - process.waitError = ErrAlreadyClosed - close(process.waitBlock) - }) - - return nil -} - -func (process *Process) registerCallback(ctx context.Context) error { - callbackContext := ¬ifcationWatcherContext{ - channels: newProcessChannels(), - systemID: process.SystemID(), - processID: process.processID, - } - - callbackMapLock.Lock() - callbackNumber := nextCallback - nextCallback++ - callbackMap[callbackNumber] = callbackContext - callbackMapLock.Unlock() - - callbackHandle, err := vmcompute.HcsRegisterProcessCallback(ctx, process.handle, notificationWatcherCallback, callbackNumber) - if err != nil { - return err - } - callbackContext.handle = callbackHandle - process.callbackNumber = callbackNumber - - return nil -} - -func (process *Process) unregisterCallback(ctx context.Context) error { - callbackNumber := process.callbackNumber - - callbackMapLock.RLock() - callbackContext := callbackMap[callbackNumber] - callbackMapLock.RUnlock() - - if callbackContext == nil { - return nil - } - - handle := callbackContext.handle - - if handle == 0 { - return nil - } - - // vmcompute.HcsUnregisterProcessCallback has its own synchronization to - // wait for all callbacks to complete. We must NOT hold the callbackMapLock. - err := vmcompute.HcsUnregisterProcessCallback(ctx, handle) - if err != nil { - return err - } - - closeChannels(callbackContext.channels) - - callbackMapLock.Lock() - delete(callbackMap, callbackNumber) - callbackMapLock.Unlock() - - handle = 0 - - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hcs/service.go b/vendor/github.com/Microsoft/hcsshim/internal/hcs/service.go deleted file mode 100644 index 3a5f0125..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hcs/service.go +++ /dev/null @@ -1,49 +0,0 @@ -package hcs - -import ( - "context" - "encoding/json" - - hcsschema "github.com/Microsoft/hcsshim/internal/schema2" - "github.com/Microsoft/hcsshim/internal/vmcompute" -) - -// GetServiceProperties returns properties of the host compute service. -func GetServiceProperties(ctx context.Context, q hcsschema.PropertyQuery) (*hcsschema.ServiceProperties, error) { - operation := "hcsshim::GetServiceProperties" - - queryb, err := json.Marshal(q) - if err != nil { - return nil, err - } - propertiesJSON, resultJSON, err := vmcompute.HcsGetServiceProperties(ctx, string(queryb)) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return nil, &HcsError{Op: operation, Err: err, Events: events} - } - - if propertiesJSON == "" { - return nil, ErrUnexpectedValue - } - properties := &hcsschema.ServiceProperties{} - if err := json.Unmarshal([]byte(propertiesJSON), properties); err != nil { - return nil, err - } - return properties, nil -} - -// ModifyServiceSettings modifies settings of the host compute service. -func ModifyServiceSettings(ctx context.Context, settings hcsschema.ModificationRequest) error { - operation := "hcsshim::ModifyServiceSettings" - - settingsJSON, err := json.Marshal(settings) - if err != nil { - return err - } - resultJSON, err := vmcompute.HcsModifyServiceSettings(ctx, string(settingsJSON)) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return &HcsError{Op: operation, Err: err, Events: events} - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hcs/system.go b/vendor/github.com/Microsoft/hcsshim/internal/hcs/system.go deleted file mode 100644 index bda393a6..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hcs/system.go +++ /dev/null @@ -1,637 +0,0 @@ -package hcs - -import ( - "context" - "encoding/json" - "errors" - "strings" - "sync" - "syscall" - - "github.com/Microsoft/hcsshim/internal/cow" - "github.com/Microsoft/hcsshim/internal/log" - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/Microsoft/hcsshim/internal/schema1" - hcsschema "github.com/Microsoft/hcsshim/internal/schema2" - "github.com/Microsoft/hcsshim/internal/timeout" - "github.com/Microsoft/hcsshim/internal/vmcompute" - "go.opencensus.io/trace" -) - -type System struct { - handleLock sync.RWMutex - handle vmcompute.HcsSystem - id string - callbackNumber uintptr - - closedWaitOnce sync.Once - waitBlock chan struct{} - waitError error - exitError error - os, typ string -} - -func newSystem(id string) *System { - return &System{ - id: id, - waitBlock: make(chan struct{}), - } -} - -// CreateComputeSystem creates a new compute system with the given configuration but does not start it. -func CreateComputeSystem(ctx context.Context, id string, hcsDocumentInterface interface{}) (_ *System, err error) { - operation := "hcsshim::CreateComputeSystem" - - // hcsCreateComputeSystemContext is an async operation. Start the outer span - // here to measure the full create time. - ctx, span := trace.StartSpan(ctx, operation) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("cid", id)) - - computeSystem := newSystem(id) - - hcsDocumentB, err := json.Marshal(hcsDocumentInterface) - if err != nil { - return nil, err - } - - hcsDocument := string(hcsDocumentB) - - var ( - identity syscall.Handle - resultJSON string - createError error - ) - computeSystem.handle, resultJSON, createError = vmcompute.HcsCreateComputeSystem(ctx, id, hcsDocument, identity) - if createError == nil || IsPending(createError) { - defer func() { - if err != nil { - computeSystem.Close() - } - }() - if err = computeSystem.registerCallback(ctx); err != nil { - // Terminate the compute system if it still exists. We're okay to - // ignore a failure here. - computeSystem.Terminate(ctx) - return nil, makeSystemError(computeSystem, operation, "", err, nil) - } - } - - events, err := processAsyncHcsResult(ctx, createError, resultJSON, computeSystem.callbackNumber, hcsNotificationSystemCreateCompleted, &timeout.SystemCreate) - if err != nil { - if err == ErrTimeout { - // Terminate the compute system if it still exists. We're okay to - // ignore a failure here. - computeSystem.Terminate(ctx) - } - return nil, makeSystemError(computeSystem, operation, hcsDocument, err, events) - } - go computeSystem.waitBackground() - if err = computeSystem.getCachedProperties(ctx); err != nil { - return nil, err - } - return computeSystem, nil -} - -// OpenComputeSystem opens an existing compute system by ID. -func OpenComputeSystem(ctx context.Context, id string) (*System, error) { - operation := "hcsshim::OpenComputeSystem" - - computeSystem := newSystem(id) - handle, resultJSON, err := vmcompute.HcsOpenComputeSystem(ctx, id) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, events) - } - computeSystem.handle = handle - defer func() { - if err != nil { - computeSystem.Close() - } - }() - if err = computeSystem.registerCallback(ctx); err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, nil) - } - go computeSystem.waitBackground() - if err = computeSystem.getCachedProperties(ctx); err != nil { - return nil, err - } - return computeSystem, nil -} - -func (computeSystem *System) getCachedProperties(ctx context.Context) error { - props, err := computeSystem.Properties(ctx) - if err != nil { - return err - } - computeSystem.typ = strings.ToLower(props.SystemType) - computeSystem.os = strings.ToLower(props.RuntimeOSType) - if computeSystem.os == "" && computeSystem.typ == "container" { - // Pre-RS5 HCS did not return the OS, but it only supported containers - // that ran Windows. - computeSystem.os = "windows" - } - return nil -} - -// OS returns the operating system of the compute system, "linux" or "windows". -func (computeSystem *System) OS() string { - return computeSystem.os -} - -// IsOCI returns whether processes in the compute system should be created via -// OCI. -func (computeSystem *System) IsOCI() bool { - return computeSystem.os == "linux" && computeSystem.typ == "container" -} - -// GetComputeSystems gets a list of the compute systems on the system that match the query -func GetComputeSystems(ctx context.Context, q schema1.ComputeSystemQuery) ([]schema1.ContainerProperties, error) { - operation := "hcsshim::GetComputeSystems" - - queryb, err := json.Marshal(q) - if err != nil { - return nil, err - } - - computeSystemsJSON, resultJSON, err := vmcompute.HcsEnumerateComputeSystems(ctx, string(queryb)) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return nil, &HcsError{Op: operation, Err: err, Events: events} - } - - if computeSystemsJSON == "" { - return nil, ErrUnexpectedValue - } - computeSystems := []schema1.ContainerProperties{} - if err = json.Unmarshal([]byte(computeSystemsJSON), &computeSystems); err != nil { - return nil, err - } - - return computeSystems, nil -} - -// Start synchronously starts the computeSystem. -func (computeSystem *System) Start(ctx context.Context) (err error) { - operation := "hcsshim::System::Start" - - // hcsStartComputeSystemContext is an async operation. Start the outer span - // here to measure the full start time. - ctx, span := trace.StartSpan(ctx, operation) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("cid", computeSystem.id)) - - computeSystem.handleLock.RLock() - defer computeSystem.handleLock.RUnlock() - - if computeSystem.handle == 0 { - return makeSystemError(computeSystem, operation, "", ErrAlreadyClosed, nil) - } - - resultJSON, err := vmcompute.HcsStartComputeSystem(ctx, computeSystem.handle, "") - events, err := processAsyncHcsResult(ctx, err, resultJSON, computeSystem.callbackNumber, hcsNotificationSystemStartCompleted, &timeout.SystemStart) - if err != nil { - return makeSystemError(computeSystem, operation, "", err, events) - } - - return nil -} - -// ID returns the compute system's identifier. -func (computeSystem *System) ID() string { - return computeSystem.id -} - -// Shutdown requests a compute system shutdown. -func (computeSystem *System) Shutdown(ctx context.Context) error { - computeSystem.handleLock.RLock() - defer computeSystem.handleLock.RUnlock() - - operation := "hcsshim::System::Shutdown" - - if computeSystem.handle == 0 { - return nil - } - - resultJSON, err := vmcompute.HcsShutdownComputeSystem(ctx, computeSystem.handle, "") - events := processHcsResult(ctx, resultJSON) - switch err { - case nil, ErrVmcomputeAlreadyStopped, ErrComputeSystemDoesNotExist, ErrVmcomputeOperationPending: - default: - return makeSystemError(computeSystem, operation, "", err, events) - } - return nil -} - -// Terminate requests a compute system terminate. -func (computeSystem *System) Terminate(ctx context.Context) error { - computeSystem.handleLock.RLock() - defer computeSystem.handleLock.RUnlock() - - operation := "hcsshim::System::Terminate" - - if computeSystem.handle == 0 { - return nil - } - - resultJSON, err := vmcompute.HcsTerminateComputeSystem(ctx, computeSystem.handle, "") - events := processHcsResult(ctx, resultJSON) - switch err { - case nil, ErrVmcomputeAlreadyStopped, ErrComputeSystemDoesNotExist, ErrVmcomputeOperationPending: - default: - return makeSystemError(computeSystem, operation, "", err, events) - } - return nil -} - -// waitBackground waits for the compute system exit notification. Once received -// sets `computeSystem.waitError` (if any) and unblocks all `Wait` calls. -// -// This MUST be called exactly once per `computeSystem.handle` but `Wait` is -// safe to call multiple times. -func (computeSystem *System) waitBackground() { - operation := "hcsshim::System::waitBackground" - ctx, span := trace.StartSpan(context.Background(), operation) - defer span.End() - span.AddAttributes(trace.StringAttribute("cid", computeSystem.id)) - - err := waitForNotification(ctx, computeSystem.callbackNumber, hcsNotificationSystemExited, nil) - switch err { - case nil: - log.G(ctx).Debug("system exited") - case ErrVmcomputeUnexpectedExit: - log.G(ctx).Debug("unexpected system exit") - computeSystem.exitError = makeSystemError(computeSystem, operation, "", err, nil) - err = nil - default: - err = makeSystemError(computeSystem, operation, "", err, nil) - } - computeSystem.closedWaitOnce.Do(func() { - computeSystem.waitError = err - close(computeSystem.waitBlock) - }) - oc.SetSpanStatus(span, err) -} - -// Wait synchronously waits for the compute system to shutdown or terminate. If -// the compute system has already exited returns the previous error (if any). -func (computeSystem *System) Wait() error { - <-computeSystem.waitBlock - return computeSystem.waitError -} - -// ExitError returns an error describing the reason the compute system terminated. -func (computeSystem *System) ExitError() error { - select { - case <-computeSystem.waitBlock: - if computeSystem.waitError != nil { - return computeSystem.waitError - } - return computeSystem.exitError - default: - return errors.New("container not exited") - } -} - -// Properties returns the requested container properties targeting a V1 schema container. -func (computeSystem *System) Properties(ctx context.Context, types ...schema1.PropertyType) (*schema1.ContainerProperties, error) { - computeSystem.handleLock.RLock() - defer computeSystem.handleLock.RUnlock() - - operation := "hcsshim::System::Properties" - - queryBytes, err := json.Marshal(schema1.PropertyQuery{PropertyTypes: types}) - if err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, nil) - } - - propertiesJSON, resultJSON, err := vmcompute.HcsGetComputeSystemProperties(ctx, computeSystem.handle, string(queryBytes)) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, events) - } - - if propertiesJSON == "" { - return nil, ErrUnexpectedValue - } - properties := &schema1.ContainerProperties{} - if err := json.Unmarshal([]byte(propertiesJSON), properties); err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, nil) - } - - return properties, nil -} - -// PropertiesV2 returns the requested container properties targeting a V2 schema container. -func (computeSystem *System) PropertiesV2(ctx context.Context, types ...hcsschema.PropertyType) (*hcsschema.Properties, error) { - computeSystem.handleLock.RLock() - defer computeSystem.handleLock.RUnlock() - - operation := "hcsshim::System::PropertiesV2" - - queryBytes, err := json.Marshal(hcsschema.PropertyQuery{PropertyTypes: types}) - if err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, nil) - } - - propertiesJSON, resultJSON, err := vmcompute.HcsGetComputeSystemProperties(ctx, computeSystem.handle, string(queryBytes)) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, events) - } - - if propertiesJSON == "" { - return nil, ErrUnexpectedValue - } - properties := &hcsschema.Properties{} - if err := json.Unmarshal([]byte(propertiesJSON), properties); err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, nil) - } - - return properties, nil -} - -// Pause pauses the execution of the computeSystem. This feature is not enabled in TP5. -func (computeSystem *System) Pause(ctx context.Context) (err error) { - operation := "hcsshim::System::Pause" - - // hcsPauseComputeSystemContext is an async peration. Start the outer span - // here to measure the full pause time. - ctx, span := trace.StartSpan(ctx, operation) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("cid", computeSystem.id)) - - computeSystem.handleLock.RLock() - defer computeSystem.handleLock.RUnlock() - - if computeSystem.handle == 0 { - return makeSystemError(computeSystem, operation, "", ErrAlreadyClosed, nil) - } - - resultJSON, err := vmcompute.HcsPauseComputeSystem(ctx, computeSystem.handle, "") - events, err := processAsyncHcsResult(ctx, err, resultJSON, computeSystem.callbackNumber, hcsNotificationSystemPauseCompleted, &timeout.SystemPause) - if err != nil { - return makeSystemError(computeSystem, operation, "", err, events) - } - - return nil -} - -// Resume resumes the execution of the computeSystem. This feature is not enabled in TP5. -func (computeSystem *System) Resume(ctx context.Context) (err error) { - operation := "hcsshim::System::Resume" - - // hcsResumeComputeSystemContext is an async operation. Start the outer span - // here to measure the full restore time. - ctx, span := trace.StartSpan(ctx, operation) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("cid", computeSystem.id)) - - computeSystem.handleLock.RLock() - defer computeSystem.handleLock.RUnlock() - - if computeSystem.handle == 0 { - return makeSystemError(computeSystem, operation, "", ErrAlreadyClosed, nil) - } - - resultJSON, err := vmcompute.HcsResumeComputeSystem(ctx, computeSystem.handle, "") - events, err := processAsyncHcsResult(ctx, err, resultJSON, computeSystem.callbackNumber, hcsNotificationSystemResumeCompleted, &timeout.SystemResume) - if err != nil { - return makeSystemError(computeSystem, operation, "", err, events) - } - - return nil -} - -// Save the compute system -func (computeSystem *System) Save(ctx context.Context, options interface{}) (err error) { - operation := "hcsshim::System::Save" - - // hcsSaveComputeSystemContext is an async peration. Start the outer span - // here to measure the full save time. - ctx, span := trace.StartSpan(ctx, operation) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("cid", computeSystem.id)) - - saveOptions, err := json.Marshal(options) - if err != nil { - return err - } - - computeSystem.handleLock.RLock() - defer computeSystem.handleLock.RUnlock() - - if computeSystem.handle == 0 { - return makeSystemError(computeSystem, operation, "", ErrAlreadyClosed, nil) - } - - result, err := vmcompute.HcsSaveComputeSystem(ctx, computeSystem.handle, string(saveOptions)) - events, err := processAsyncHcsResult(ctx, err, result, computeSystem.callbackNumber, hcsNotificationSystemSaveCompleted, &timeout.SystemSave) - if err != nil { - return makeSystemError(computeSystem, operation, "", err, events) - } - - return nil -} - -func (computeSystem *System) createProcess(ctx context.Context, operation string, c interface{}) (*Process, *vmcompute.HcsProcessInformation, error) { - computeSystem.handleLock.RLock() - defer computeSystem.handleLock.RUnlock() - - if computeSystem.handle == 0 { - return nil, nil, makeSystemError(computeSystem, operation, "", ErrAlreadyClosed, nil) - } - - configurationb, err := json.Marshal(c) - if err != nil { - return nil, nil, makeSystemError(computeSystem, operation, "", err, nil) - } - - configuration := string(configurationb) - processInfo, processHandle, resultJSON, err := vmcompute.HcsCreateProcess(ctx, computeSystem.handle, configuration) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return nil, nil, makeSystemError(computeSystem, operation, configuration, err, events) - } - - log.G(ctx).WithField("pid", processInfo.ProcessId).Debug("created process pid") - return newProcess(processHandle, int(processInfo.ProcessId), computeSystem), &processInfo, nil -} - -// CreateProcess launches a new process within the computeSystem. -func (computeSystem *System) CreateProcess(ctx context.Context, c interface{}) (cow.Process, error) { - operation := "hcsshim::System::CreateProcess" - process, processInfo, err := computeSystem.createProcess(ctx, operation, c) - if err != nil { - return nil, err - } - defer func() { - if err != nil { - process.Close() - } - }() - - pipes, err := makeOpenFiles([]syscall.Handle{processInfo.StdInput, processInfo.StdOutput, processInfo.StdError}) - if err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, nil) - } - process.stdin = pipes[0] - process.stdout = pipes[1] - process.stderr = pipes[2] - process.hasCachedStdio = true - - if err = process.registerCallback(ctx); err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, nil) - } - go process.waitBackground() - - return process, nil -} - -// OpenProcess gets an interface to an existing process within the computeSystem. -func (computeSystem *System) OpenProcess(ctx context.Context, pid int) (*Process, error) { - computeSystem.handleLock.RLock() - defer computeSystem.handleLock.RUnlock() - - operation := "hcsshim::System::OpenProcess" - - if computeSystem.handle == 0 { - return nil, makeSystemError(computeSystem, operation, "", ErrAlreadyClosed, nil) - } - - processHandle, resultJSON, err := vmcompute.HcsOpenProcess(ctx, computeSystem.handle, uint32(pid)) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, events) - } - - process := newProcess(processHandle, pid, computeSystem) - if err = process.registerCallback(ctx); err != nil { - return nil, makeSystemError(computeSystem, operation, "", err, nil) - } - go process.waitBackground() - - return process, nil -} - -// Close cleans up any state associated with the compute system but does not terminate or wait for it. -func (computeSystem *System) Close() (err error) { - operation := "hcsshim::System::Close" - ctx, span := trace.StartSpan(context.Background(), operation) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("cid", computeSystem.id)) - - computeSystem.handleLock.Lock() - defer computeSystem.handleLock.Unlock() - - // Don't double free this - if computeSystem.handle == 0 { - return nil - } - - if err = computeSystem.unregisterCallback(ctx); err != nil { - return makeSystemError(computeSystem, operation, "", err, nil) - } - - err = vmcompute.HcsCloseComputeSystem(ctx, computeSystem.handle) - if err != nil { - return makeSystemError(computeSystem, operation, "", err, nil) - } - - computeSystem.handle = 0 - computeSystem.closedWaitOnce.Do(func() { - computeSystem.waitError = ErrAlreadyClosed - close(computeSystem.waitBlock) - }) - - return nil -} - -func (computeSystem *System) registerCallback(ctx context.Context) error { - callbackContext := ¬ifcationWatcherContext{ - channels: newSystemChannels(), - systemID: computeSystem.id, - } - - callbackMapLock.Lock() - callbackNumber := nextCallback - nextCallback++ - callbackMap[callbackNumber] = callbackContext - callbackMapLock.Unlock() - - callbackHandle, err := vmcompute.HcsRegisterComputeSystemCallback(ctx, computeSystem.handle, notificationWatcherCallback, callbackNumber) - if err != nil { - return err - } - callbackContext.handle = callbackHandle - computeSystem.callbackNumber = callbackNumber - - return nil -} - -func (computeSystem *System) unregisterCallback(ctx context.Context) error { - callbackNumber := computeSystem.callbackNumber - - callbackMapLock.RLock() - callbackContext := callbackMap[callbackNumber] - callbackMapLock.RUnlock() - - if callbackContext == nil { - return nil - } - - handle := callbackContext.handle - - if handle == 0 { - return nil - } - - // hcsUnregisterComputeSystemCallback has its own syncronization - // to wait for all callbacks to complete. We must NOT hold the callbackMapLock. - err := vmcompute.HcsUnregisterComputeSystemCallback(ctx, handle) - if err != nil { - return err - } - - closeChannels(callbackContext.channels) - - callbackMapLock.Lock() - delete(callbackMap, callbackNumber) - callbackMapLock.Unlock() - - handle = 0 - - return nil -} - -// Modify the System by sending a request to HCS -func (computeSystem *System) Modify(ctx context.Context, config interface{}) error { - computeSystem.handleLock.RLock() - defer computeSystem.handleLock.RUnlock() - - operation := "hcsshim::System::Modify" - - if computeSystem.handle == 0 { - return makeSystemError(computeSystem, operation, "", ErrAlreadyClosed, nil) - } - - requestBytes, err := json.Marshal(config) - if err != nil { - return err - } - - requestJSON := string(requestBytes) - resultJSON, err := vmcompute.HcsModifyComputeSystem(ctx, computeSystem.handle, requestJSON) - events := processHcsResult(ctx, resultJSON) - if err != nil { - return makeSystemError(computeSystem, operation, requestJSON, err, events) - } - - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hcs/utils.go b/vendor/github.com/Microsoft/hcsshim/internal/hcs/utils.go deleted file mode 100644 index 3342e5bb..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hcs/utils.go +++ /dev/null @@ -1,62 +0,0 @@ -package hcs - -import ( - "context" - "io" - "syscall" - - "github.com/Microsoft/go-winio" - diskutil "github.com/Microsoft/go-winio/vhd" - "github.com/Microsoft/hcsshim/computestorage" - "github.com/pkg/errors" - "golang.org/x/sys/windows" -) - -// makeOpenFiles calls winio.MakeOpenFile for each handle in a slice but closes all the handles -// if there is an error. -func makeOpenFiles(hs []syscall.Handle) (_ []io.ReadWriteCloser, err error) { - fs := make([]io.ReadWriteCloser, len(hs)) - for i, h := range hs { - if h != syscall.Handle(0) { - if err == nil { - fs[i], err = winio.MakeOpenFile(h) - } - if err != nil { - syscall.Close(h) - } - } - } - if err != nil { - for _, f := range fs { - if f != nil { - f.Close() - } - } - return nil, err - } - return fs, nil -} - -// CreateNTFSVHD creates a VHD formatted with NTFS of size `sizeGB` at the given `vhdPath`. -func CreateNTFSVHD(ctx context.Context, vhdPath string, sizeGB uint32) (err error) { - if err := diskutil.CreateVhdx(vhdPath, sizeGB, 1); err != nil { - return errors.Wrap(err, "failed to create VHD") - } - - vhd, err := diskutil.OpenVirtualDisk(vhdPath, diskutil.VirtualDiskAccessNone, diskutil.OpenVirtualDiskFlagNone) - if err != nil { - return errors.Wrap(err, "failed to open VHD") - } - defer func() { - err2 := windows.CloseHandle(windows.Handle(vhd)) - if err == nil { - err = errors.Wrap(err2, "failed to close VHD") - } - }() - - if err := computestorage.FormatWritableLayerVhd(ctx, windows.Handle(vhd)); err != nil { - return errors.Wrap(err, "failed to format VHD") - } - - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hcs/waithelper.go b/vendor/github.com/Microsoft/hcsshim/internal/hcs/waithelper.go deleted file mode 100644 index f07f532c..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hcs/waithelper.go +++ /dev/null @@ -1,69 +0,0 @@ -package hcs - -import ( - "context" - "time" - - "github.com/Microsoft/hcsshim/internal/log" -) - -func processAsyncHcsResult(ctx context.Context, err error, resultJSON string, callbackNumber uintptr, expectedNotification hcsNotification, timeout *time.Duration) ([]ErrorEvent, error) { - events := processHcsResult(ctx, resultJSON) - if IsPending(err) { - return nil, waitForNotification(ctx, callbackNumber, expectedNotification, timeout) - } - - return events, err -} - -func waitForNotification(ctx context.Context, callbackNumber uintptr, expectedNotification hcsNotification, timeout *time.Duration) error { - callbackMapLock.RLock() - if _, ok := callbackMap[callbackNumber]; !ok { - callbackMapLock.RUnlock() - log.G(ctx).WithField("callbackNumber", callbackNumber).Error("failed to waitForNotification: callbackNumber does not exist in callbackMap") - return ErrHandleClose - } - channels := callbackMap[callbackNumber].channels - callbackMapLock.RUnlock() - - expectedChannel := channels[expectedNotification] - if expectedChannel == nil { - log.G(ctx).WithField("type", expectedNotification).Error("unknown notification type in waitForNotification") - return ErrInvalidNotificationType - } - - var c <-chan time.Time - if timeout != nil { - timer := time.NewTimer(*timeout) - c = timer.C - defer timer.Stop() - } - - select { - case err, ok := <-expectedChannel: - if !ok { - return ErrHandleClose - } - return err - case err, ok := <-channels[hcsNotificationSystemExited]: - if !ok { - return ErrHandleClose - } - // If the expected notification is hcsNotificationSystemExited which of the two selects - // chosen is random. Return the raw error if hcsNotificationSystemExited is expected - if channels[hcsNotificationSystemExited] == expectedChannel { - return err - } - return ErrUnexpectedContainerExit - case _, ok := <-channels[hcsNotificationServiceDisconnect]: - if !ok { - return ErrHandleClose - } - // hcsNotificationServiceDisconnect should never be an expected notification - // it does not need the same handling as hcsNotificationSystemExited - return ErrUnexpectedProcessAbort - case <-c: - return ErrTimeout - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hcserror/hcserror.go b/vendor/github.com/Microsoft/hcsshim/internal/hcserror/hcserror.go deleted file mode 100644 index 921c2c85..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hcserror/hcserror.go +++ /dev/null @@ -1,47 +0,0 @@ -package hcserror - -import ( - "fmt" - "syscall" -) - -const ERROR_GEN_FAILURE = syscall.Errno(31) - -type HcsError struct { - title string - rest string - Err error -} - -func (e *HcsError) Error() string { - s := e.title - if len(s) > 0 && s[len(s)-1] != ' ' { - s += " " - } - s += fmt.Sprintf("failed in Win32: %s (0x%x)", e.Err, Win32FromError(e.Err)) - if e.rest != "" { - if e.rest[0] != ' ' { - s += " " - } - s += e.rest - } - return s -} - -func New(err error, title, rest string) error { - // Pass through DLL errors directly since they do not originate from HCS. - if _, ok := err.(*syscall.DLLError); ok { - return err - } - return &HcsError{title, rest, err} -} - -func Win32FromError(err error) uint32 { - if herr, ok := err.(*HcsError); ok { - return Win32FromError(herr.Err) - } - if code, ok := err.(syscall.Errno); ok { - return uint32(code) - } - return uint32(ERROR_GEN_FAILURE) -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hns/hns.go b/vendor/github.com/Microsoft/hcsshim/internal/hns/hns.go deleted file mode 100644 index b2e475f5..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hns/hns.go +++ /dev/null @@ -1,23 +0,0 @@ -package hns - -import "fmt" - -//go:generate go run ../../mksyscall_windows.go -output zsyscall_windows.go hns.go - -//sys _hnsCall(method string, path string, object string, response **uint16) (hr error) = vmcompute.HNSCall? - -type EndpointNotFoundError struct { - EndpointName string -} - -func (e EndpointNotFoundError) Error() string { - return fmt.Sprintf("Endpoint %s not found", e.EndpointName) -} - -type NetworkNotFoundError struct { - NetworkName string -} - -func (e NetworkNotFoundError) Error() string { - return fmt.Sprintf("Network %s not found", e.NetworkName) -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsendpoint.go b/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsendpoint.go deleted file mode 100644 index b36315a3..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsendpoint.go +++ /dev/null @@ -1,308 +0,0 @@ -package hns - -import ( - "encoding/json" - "net" - "strings" - - "github.com/sirupsen/logrus" -) - -// HNSEndpoint represents a network endpoint in HNS -type HNSEndpoint struct { - Id string `json:"ID,omitempty"` - Name string `json:",omitempty"` - VirtualNetwork string `json:",omitempty"` - VirtualNetworkName string `json:",omitempty"` - Policies []json.RawMessage `json:",omitempty"` - MacAddress string `json:",omitempty"` - IPAddress net.IP `json:",omitempty"` - IPv6Address net.IP `json:",omitempty"` - DNSSuffix string `json:",omitempty"` - DNSServerList string `json:",omitempty"` - GatewayAddress string `json:",omitempty"` - GatewayAddressV6 string `json:",omitempty"` - EnableInternalDNS bool `json:",omitempty"` - DisableICC bool `json:",omitempty"` - PrefixLength uint8 `json:",omitempty"` - IPv6PrefixLength uint8 `json:",omitempty"` - IsRemoteEndpoint bool `json:",omitempty"` - EnableLowMetric bool `json:",omitempty"` - Namespace *Namespace `json:",omitempty"` - EncapOverhead uint16 `json:",omitempty"` -} - -//SystemType represents the type of the system on which actions are done -type SystemType string - -// SystemType const -const ( - ContainerType SystemType = "Container" - VirtualMachineType SystemType = "VirtualMachine" - HostType SystemType = "Host" -) - -// EndpointAttachDetachRequest is the structure used to send request to the container to modify the system -// Supported resource types are Network and Request Types are Add/Remove -type EndpointAttachDetachRequest struct { - ContainerID string `json:"ContainerId,omitempty"` - SystemType SystemType `json:"SystemType"` - CompartmentID uint16 `json:"CompartmentId,omitempty"` - VirtualNICName string `json:"VirtualNicName,omitempty"` -} - -// EndpointResquestResponse is object to get the endpoint request response -type EndpointResquestResponse struct { - Success bool - Error string -} - -// HNSEndpointRequest makes a HNS call to modify/query a network endpoint -func HNSEndpointRequest(method, path, request string) (*HNSEndpoint, error) { - endpoint := &HNSEndpoint{} - err := hnsCall(method, "/endpoints/"+path, request, &endpoint) - if err != nil { - return nil, err - } - - return endpoint, nil -} - -// HNSListEndpointRequest makes a HNS call to query the list of available endpoints -func HNSListEndpointRequest() ([]HNSEndpoint, error) { - var endpoint []HNSEndpoint - err := hnsCall("GET", "/endpoints/", "", &endpoint) - if err != nil { - return nil, err - } - - return endpoint, nil -} - -// GetHNSEndpointByID get the Endpoint by ID -func GetHNSEndpointByID(endpointID string) (*HNSEndpoint, error) { - return HNSEndpointRequest("GET", endpointID, "") -} - -// GetHNSEndpointByName gets the endpoint filtered by Name -func GetHNSEndpointByName(endpointName string) (*HNSEndpoint, error) { - hnsResponse, err := HNSListEndpointRequest() - if err != nil { - return nil, err - } - for _, hnsEndpoint := range hnsResponse { - if hnsEndpoint.Name == endpointName { - return &hnsEndpoint, nil - } - } - return nil, EndpointNotFoundError{EndpointName: endpointName} -} - -type endpointAttachInfo struct { - SharedContainers json.RawMessage `json:",omitempty"` -} - -func (endpoint *HNSEndpoint) IsAttached(vID string) (bool, error) { - attachInfo := endpointAttachInfo{} - err := hnsCall("GET", "/endpoints/"+endpoint.Id, "", &attachInfo) - - // Return false allows us to just return the err - if err != nil { - return false, err - } - - if strings.Contains(strings.ToLower(string(attachInfo.SharedContainers)), strings.ToLower(vID)) { - return true, nil - } - - return false, nil - -} - -// Create Endpoint by sending EndpointRequest to HNS. TODO: Create a separate HNS interface to place all these methods -func (endpoint *HNSEndpoint) Create() (*HNSEndpoint, error) { - operation := "Create" - title := "hcsshim::HNSEndpoint::" + operation - logrus.Debugf(title+" id=%s", endpoint.Id) - - jsonString, err := json.Marshal(endpoint) - if err != nil { - return nil, err - } - return HNSEndpointRequest("POST", "", string(jsonString)) -} - -// Delete Endpoint by sending EndpointRequest to HNS -func (endpoint *HNSEndpoint) Delete() (*HNSEndpoint, error) { - operation := "Delete" - title := "hcsshim::HNSEndpoint::" + operation - logrus.Debugf(title+" id=%s", endpoint.Id) - - return HNSEndpointRequest("DELETE", endpoint.Id, "") -} - -// Update Endpoint -func (endpoint *HNSEndpoint) Update() (*HNSEndpoint, error) { - operation := "Update" - title := "hcsshim::HNSEndpoint::" + operation - logrus.Debugf(title+" id=%s", endpoint.Id) - jsonString, err := json.Marshal(endpoint) - if err != nil { - return nil, err - } - err = hnsCall("POST", "/endpoints/"+endpoint.Id, string(jsonString), &endpoint) - - return endpoint, err -} - -// ApplyACLPolicy applies a set of ACL Policies on the Endpoint -func (endpoint *HNSEndpoint) ApplyACLPolicy(policies ...*ACLPolicy) error { - operation := "ApplyACLPolicy" - title := "hcsshim::HNSEndpoint::" + operation - logrus.Debugf(title+" id=%s", endpoint.Id) - - for _, policy := range policies { - if policy == nil { - continue - } - jsonString, err := json.Marshal(policy) - if err != nil { - return err - } - endpoint.Policies = append(endpoint.Policies, jsonString) - } - - _, err := endpoint.Update() - return err -} - -// ApplyProxyPolicy applies a set of Proxy Policies on the Endpoint -func (endpoint *HNSEndpoint) ApplyProxyPolicy(policies ...*ProxyPolicy) error { - operation := "ApplyProxyPolicy" - title := "hcsshim::HNSEndpoint::" + operation - logrus.Debugf(title+" id=%s", endpoint.Id) - - for _, policy := range policies { - if policy == nil { - continue - } - jsonString, err := json.Marshal(policy) - if err != nil { - return err - } - endpoint.Policies = append(endpoint.Policies, jsonString) - } - - _, err := endpoint.Update() - return err -} - -// ContainerAttach attaches an endpoint to container -func (endpoint *HNSEndpoint) ContainerAttach(containerID string, compartmentID uint16) error { - operation := "ContainerAttach" - title := "hcsshim::HNSEndpoint::" + operation - logrus.Debugf(title+" id=%s", endpoint.Id) - - requestMessage := &EndpointAttachDetachRequest{ - ContainerID: containerID, - CompartmentID: compartmentID, - SystemType: ContainerType, - } - response := &EndpointResquestResponse{} - jsonString, err := json.Marshal(requestMessage) - if err != nil { - return err - } - return hnsCall("POST", "/endpoints/"+endpoint.Id+"/attach", string(jsonString), &response) -} - -// ContainerDetach detaches an endpoint from container -func (endpoint *HNSEndpoint) ContainerDetach(containerID string) error { - operation := "ContainerDetach" - title := "hcsshim::HNSEndpoint::" + operation - logrus.Debugf(title+" id=%s", endpoint.Id) - - requestMessage := &EndpointAttachDetachRequest{ - ContainerID: containerID, - SystemType: ContainerType, - } - response := &EndpointResquestResponse{} - - jsonString, err := json.Marshal(requestMessage) - if err != nil { - return err - } - return hnsCall("POST", "/endpoints/"+endpoint.Id+"/detach", string(jsonString), &response) -} - -// HostAttach attaches a nic on the host -func (endpoint *HNSEndpoint) HostAttach(compartmentID uint16) error { - operation := "HostAttach" - title := "hcsshim::HNSEndpoint::" + operation - logrus.Debugf(title+" id=%s", endpoint.Id) - requestMessage := &EndpointAttachDetachRequest{ - CompartmentID: compartmentID, - SystemType: HostType, - } - response := &EndpointResquestResponse{} - - jsonString, err := json.Marshal(requestMessage) - if err != nil { - return err - } - return hnsCall("POST", "/endpoints/"+endpoint.Id+"/attach", string(jsonString), &response) - -} - -// HostDetach detaches a nic on the host -func (endpoint *HNSEndpoint) HostDetach() error { - operation := "HostDetach" - title := "hcsshim::HNSEndpoint::" + operation - logrus.Debugf(title+" id=%s", endpoint.Id) - requestMessage := &EndpointAttachDetachRequest{ - SystemType: HostType, - } - response := &EndpointResquestResponse{} - - jsonString, err := json.Marshal(requestMessage) - if err != nil { - return err - } - return hnsCall("POST", "/endpoints/"+endpoint.Id+"/detach", string(jsonString), &response) -} - -// VirtualMachineNICAttach attaches a endpoint to a virtual machine -func (endpoint *HNSEndpoint) VirtualMachineNICAttach(virtualMachineNICName string) error { - operation := "VirtualMachineNicAttach" - title := "hcsshim::HNSEndpoint::" + operation - logrus.Debugf(title+" id=%s", endpoint.Id) - requestMessage := &EndpointAttachDetachRequest{ - VirtualNICName: virtualMachineNICName, - SystemType: VirtualMachineType, - } - response := &EndpointResquestResponse{} - - jsonString, err := json.Marshal(requestMessage) - if err != nil { - return err - } - return hnsCall("POST", "/endpoints/"+endpoint.Id+"/attach", string(jsonString), &response) -} - -// VirtualMachineNICDetach detaches a endpoint from a virtual machine -func (endpoint *HNSEndpoint) VirtualMachineNICDetach() error { - operation := "VirtualMachineNicDetach" - title := "hcsshim::HNSEndpoint::" + operation - logrus.Debugf(title+" id=%s", endpoint.Id) - - requestMessage := &EndpointAttachDetachRequest{ - SystemType: VirtualMachineType, - } - response := &EndpointResquestResponse{} - - jsonString, err := json.Marshal(requestMessage) - if err != nil { - return err - } - return hnsCall("POST", "/endpoints/"+endpoint.Id+"/detach", string(jsonString), &response) -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsfuncs.go b/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsfuncs.go deleted file mode 100644 index 2df4a57f..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsfuncs.go +++ /dev/null @@ -1,49 +0,0 @@ -package hns - -import ( - "encoding/json" - "fmt" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/interop" - "github.com/sirupsen/logrus" -) - -func hnsCallRawResponse(method, path, request string) (*hnsResponse, error) { - var responseBuffer *uint16 - logrus.Debugf("[%s]=>[%s] Request : %s", method, path, request) - - err := _hnsCall(method, path, request, &responseBuffer) - if err != nil { - return nil, hcserror.New(err, "hnsCall ", "") - } - response := interop.ConvertAndFreeCoTaskMemString(responseBuffer) - - hnsresponse := &hnsResponse{} - if err = json.Unmarshal([]byte(response), &hnsresponse); err != nil { - return nil, err - } - return hnsresponse, nil -} - -func hnsCall(method, path, request string, returnResponse interface{}) error { - hnsresponse, err := hnsCallRawResponse(method, path, request) - if err != nil { - return fmt.Errorf("failed during hnsCallRawResponse: %v", err) - } - if !hnsresponse.Success { - return fmt.Errorf("hns failed with error : %s", hnsresponse.Error) - } - - if len(hnsresponse.Output) == 0 { - return nil - } - - logrus.Debugf("Network Response : %s", hnsresponse.Output) - err = json.Unmarshal(hnsresponse.Output, returnResponse) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsglobals.go b/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsglobals.go deleted file mode 100644 index a8d8cc56..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsglobals.go +++ /dev/null @@ -1,28 +0,0 @@ -package hns - -type HNSGlobals struct { - Version HNSVersion `json:"Version"` -} - -type HNSVersion struct { - Major int `json:"Major"` - Minor int `json:"Minor"` -} - -var ( - HNSVersion1803 = HNSVersion{Major: 7, Minor: 2} -) - -func GetHNSGlobals() (*HNSGlobals, error) { - var version HNSVersion - err := hnsCall("GET", "/globals/version", "", &version) - if err != nil { - return nil, err - } - - globals := &HNSGlobals{ - Version: version, - } - - return globals, nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsnetwork.go b/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsnetwork.go deleted file mode 100644 index b7ae96fd..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnsnetwork.go +++ /dev/null @@ -1,147 +0,0 @@ -package hns - -import ( - "encoding/json" - "errors" - "github.com/sirupsen/logrus" - "net" -) - -// Subnet is assoicated with a network and represents a list -// of subnets available to the network -type Subnet struct { - AddressPrefix string `json:",omitempty"` - GatewayAddress string `json:",omitempty"` - Policies []json.RawMessage `json:",omitempty"` -} - -// MacPool is assoicated with a network and represents a list -// of macaddresses available to the network -type MacPool struct { - StartMacAddress string `json:",omitempty"` - EndMacAddress string `json:",omitempty"` -} - -// HNSNetwork represents a network in HNS -type HNSNetwork struct { - Id string `json:"ID,omitempty"` - Name string `json:",omitempty"` - Type string `json:",omitempty"` - NetworkAdapterName string `json:",omitempty"` - SourceMac string `json:",omitempty"` - Policies []json.RawMessage `json:",omitempty"` - MacPools []MacPool `json:",omitempty"` - Subnets []Subnet `json:",omitempty"` - DNSSuffix string `json:",omitempty"` - DNSServerList string `json:",omitempty"` - DNSServerCompartment uint32 `json:",omitempty"` - ManagementIP string `json:",omitempty"` - AutomaticDNS bool `json:",omitempty"` -} - -type hnsNetworkResponse struct { - Success bool - Error string - Output HNSNetwork -} - -type hnsResponse struct { - Success bool - Error string - Output json.RawMessage -} - -// HNSNetworkRequest makes a call into HNS to update/query a single network -func HNSNetworkRequest(method, path, request string) (*HNSNetwork, error) { - var network HNSNetwork - err := hnsCall(method, "/networks/"+path, request, &network) - if err != nil { - return nil, err - } - - return &network, nil -} - -// HNSListNetworkRequest makes a HNS call to query the list of available networks -func HNSListNetworkRequest(method, path, request string) ([]HNSNetwork, error) { - var network []HNSNetwork - err := hnsCall(method, "/networks/"+path, request, &network) - if err != nil { - return nil, err - } - - return network, nil -} - -// GetHNSNetworkByID -func GetHNSNetworkByID(networkID string) (*HNSNetwork, error) { - return HNSNetworkRequest("GET", networkID, "") -} - -// GetHNSNetworkName filtered by Name -func GetHNSNetworkByName(networkName string) (*HNSNetwork, error) { - hsnnetworks, err := HNSListNetworkRequest("GET", "", "") - if err != nil { - return nil, err - } - for _, hnsnetwork := range hsnnetworks { - if hnsnetwork.Name == networkName { - return &hnsnetwork, nil - } - } - return nil, NetworkNotFoundError{NetworkName: networkName} -} - -// Create Network by sending NetworkRequest to HNS. -func (network *HNSNetwork) Create() (*HNSNetwork, error) { - operation := "Create" - title := "hcsshim::HNSNetwork::" + operation - logrus.Debugf(title+" id=%s", network.Id) - - for _, subnet := range network.Subnets { - if (subnet.AddressPrefix != "") && (subnet.GatewayAddress == "") { - return nil, errors.New("network create error, subnet has address prefix but no gateway specified") - } - } - - jsonString, err := json.Marshal(network) - if err != nil { - return nil, err - } - return HNSNetworkRequest("POST", "", string(jsonString)) -} - -// Delete Network by sending NetworkRequest to HNS -func (network *HNSNetwork) Delete() (*HNSNetwork, error) { - operation := "Delete" - title := "hcsshim::HNSNetwork::" + operation - logrus.Debugf(title+" id=%s", network.Id) - - return HNSNetworkRequest("DELETE", network.Id, "") -} - -// Creates an endpoint on the Network. -func (network *HNSNetwork) NewEndpoint(ipAddress net.IP, macAddress net.HardwareAddr) *HNSEndpoint { - return &HNSEndpoint{ - VirtualNetwork: network.Id, - IPAddress: ipAddress, - MacAddress: string(macAddress), - } -} - -func (network *HNSNetwork) CreateEndpoint(endpoint *HNSEndpoint) (*HNSEndpoint, error) { - operation := "CreateEndpoint" - title := "hcsshim::HNSNetwork::" + operation - logrus.Debugf(title+" id=%s, endpointId=%s", network.Id, endpoint.Id) - - endpoint.VirtualNetwork = network.Id - return endpoint.Create() -} - -func (network *HNSNetwork) CreateRemoteEndpoint(endpoint *HNSEndpoint) (*HNSEndpoint, error) { - operation := "CreateRemoteEndpoint" - title := "hcsshim::HNSNetwork::" + operation - logrus.Debugf(title+" id=%s", network.Id) - endpoint.IsRemoteEndpoint = true - return network.CreateEndpoint(endpoint) -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnspolicy.go b/vendor/github.com/Microsoft/hcsshim/internal/hns/hnspolicy.go deleted file mode 100644 index 6765aaea..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnspolicy.go +++ /dev/null @@ -1,109 +0,0 @@ -package hns - -// Type of Request Support in ModifySystem -type PolicyType string - -// RequestType const -const ( - Nat PolicyType = "NAT" - ACL PolicyType = "ACL" - PA PolicyType = "PA" - VLAN PolicyType = "VLAN" - VSID PolicyType = "VSID" - VNet PolicyType = "VNET" - L2Driver PolicyType = "L2Driver" - Isolation PolicyType = "Isolation" - QOS PolicyType = "QOS" - OutboundNat PolicyType = "OutBoundNAT" - ExternalLoadBalancer PolicyType = "ELB" - Route PolicyType = "ROUTE" - Proxy PolicyType = "PROXY" -) - -type NatPolicy struct { - Type PolicyType `json:"Type"` - Protocol string - InternalPort uint16 - ExternalPort uint16 -} - -type QosPolicy struct { - Type PolicyType `json:"Type"` - MaximumOutgoingBandwidthInBytes uint64 -} - -type IsolationPolicy struct { - Type PolicyType `json:"Type"` - VLAN uint - VSID uint - InDefaultIsolation bool -} - -type VlanPolicy struct { - Type PolicyType `json:"Type"` - VLAN uint -} - -type VsidPolicy struct { - Type PolicyType `json:"Type"` - VSID uint -} - -type PaPolicy struct { - Type PolicyType `json:"Type"` - PA string `json:"PA"` -} - -type OutboundNatPolicy struct { - Policy - VIP string `json:"VIP,omitempty"` - Exceptions []string `json:"ExceptionList,omitempty"` - Destinations []string `json:",omitempty"` -} - -type ProxyPolicy struct { - Type PolicyType `json:"Type"` - IP string `json:",omitempty"` - Port string `json:",omitempty"` - ExceptionList []string `json:",omitempty"` - Destination string `json:",omitempty"` - OutboundNat bool `json:",omitempty"` -} - -type ActionType string -type DirectionType string -type RuleType string - -const ( - Allow ActionType = "Allow" - Block ActionType = "Block" - - In DirectionType = "In" - Out DirectionType = "Out" - - Host RuleType = "Host" - Switch RuleType = "Switch" -) - -type ACLPolicy struct { - Type PolicyType `json:"Type"` - Id string `json:"Id,omitempty"` - Protocol uint16 - Protocols string `json:"Protocols,omitempty"` - InternalPort uint16 - Action ActionType - Direction DirectionType - LocalAddresses string - RemoteAddresses string - LocalPorts string `json:"LocalPorts,omitempty"` - LocalPort uint16 - RemotePorts string `json:"RemotePorts,omitempty"` - RemotePort uint16 - RuleType RuleType `json:"RuleType,omitempty"` - Priority uint16 - ServiceName string -} - -type Policy struct { - Type PolicyType `json:"Type"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnspolicylist.go b/vendor/github.com/Microsoft/hcsshim/internal/hns/hnspolicylist.go deleted file mode 100644 index 31322a68..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnspolicylist.go +++ /dev/null @@ -1,201 +0,0 @@ -package hns - -import ( - "encoding/json" - - "github.com/sirupsen/logrus" -) - -// RoutePolicy is a structure defining schema for Route based Policy -type RoutePolicy struct { - Policy - DestinationPrefix string `json:"DestinationPrefix,omitempty"` - NextHop string `json:"NextHop,omitempty"` - EncapEnabled bool `json:"NeedEncap,omitempty"` -} - -// ELBPolicy is a structure defining schema for ELB LoadBalancing based Policy -type ELBPolicy struct { - LBPolicy - SourceVIP string `json:"SourceVIP,omitempty"` - VIPs []string `json:"VIPs,omitempty"` - ILB bool `json:"ILB,omitempty"` - DSR bool `json:"IsDSR,omitempty"` -} - -// LBPolicy is a structure defining schema for LoadBalancing based Policy -type LBPolicy struct { - Policy - Protocol uint16 `json:"Protocol,omitempty"` - InternalPort uint16 - ExternalPort uint16 -} - -// PolicyList is a structure defining schema for Policy list request -type PolicyList struct { - ID string `json:"ID,omitempty"` - EndpointReferences []string `json:"References,omitempty"` - Policies []json.RawMessage `json:"Policies,omitempty"` -} - -// HNSPolicyListRequest makes a call into HNS to update/query a single network -func HNSPolicyListRequest(method, path, request string) (*PolicyList, error) { - var policy PolicyList - err := hnsCall(method, "/policylists/"+path, request, &policy) - if err != nil { - return nil, err - } - - return &policy, nil -} - -// HNSListPolicyListRequest gets all the policy list -func HNSListPolicyListRequest() ([]PolicyList, error) { - var plist []PolicyList - err := hnsCall("GET", "/policylists/", "", &plist) - if err != nil { - return nil, err - } - - return plist, nil -} - -// PolicyListRequest makes a HNS call to modify/query a network policy list -func PolicyListRequest(method, path, request string) (*PolicyList, error) { - policylist := &PolicyList{} - err := hnsCall(method, "/policylists/"+path, request, &policylist) - if err != nil { - return nil, err - } - - return policylist, nil -} - -// GetPolicyListByID get the policy list by ID -func GetPolicyListByID(policyListID string) (*PolicyList, error) { - return PolicyListRequest("GET", policyListID, "") -} - -// Create PolicyList by sending PolicyListRequest to HNS. -func (policylist *PolicyList) Create() (*PolicyList, error) { - operation := "Create" - title := "hcsshim::PolicyList::" + operation - logrus.Debugf(title+" id=%s", policylist.ID) - jsonString, err := json.Marshal(policylist) - if err != nil { - return nil, err - } - return PolicyListRequest("POST", "", string(jsonString)) -} - -// Delete deletes PolicyList -func (policylist *PolicyList) Delete() (*PolicyList, error) { - operation := "Delete" - title := "hcsshim::PolicyList::" + operation - logrus.Debugf(title+" id=%s", policylist.ID) - - return PolicyListRequest("DELETE", policylist.ID, "") -} - -// AddEndpoint add an endpoint to a Policy List -func (policylist *PolicyList) AddEndpoint(endpoint *HNSEndpoint) (*PolicyList, error) { - operation := "AddEndpoint" - title := "hcsshim::PolicyList::" + operation - logrus.Debugf(title+" id=%s, endpointId:%s", policylist.ID, endpoint.Id) - - _, err := policylist.Delete() - if err != nil { - return nil, err - } - - // Add Endpoint to the Existing List - policylist.EndpointReferences = append(policylist.EndpointReferences, "/endpoints/"+endpoint.Id) - - return policylist.Create() -} - -// RemoveEndpoint removes an endpoint from the Policy List -func (policylist *PolicyList) RemoveEndpoint(endpoint *HNSEndpoint) (*PolicyList, error) { - operation := "RemoveEndpoint" - title := "hcsshim::PolicyList::" + operation - logrus.Debugf(title+" id=%s, endpointId:%s", policylist.ID, endpoint.Id) - - _, err := policylist.Delete() - if err != nil { - return nil, err - } - - elementToRemove := "/endpoints/" + endpoint.Id - - var references []string - - for _, endpointReference := range policylist.EndpointReferences { - if endpointReference == elementToRemove { - continue - } - references = append(references, endpointReference) - } - policylist.EndpointReferences = references - return policylist.Create() -} - -// AddLoadBalancer policy list for the specified endpoints -func AddLoadBalancer(endpoints []HNSEndpoint, isILB bool, sourceVIP, vip string, protocol uint16, internalPort uint16, externalPort uint16) (*PolicyList, error) { - operation := "AddLoadBalancer" - title := "hcsshim::PolicyList::" + operation - logrus.Debugf(title+" endpointId=%v, isILB=%v, sourceVIP=%s, vip=%s, protocol=%v, internalPort=%v, externalPort=%v", endpoints, isILB, sourceVIP, vip, protocol, internalPort, externalPort) - - policylist := &PolicyList{} - - elbPolicy := &ELBPolicy{ - SourceVIP: sourceVIP, - ILB: isILB, - } - - if len(vip) > 0 { - elbPolicy.VIPs = []string{vip} - } - elbPolicy.Type = ExternalLoadBalancer - elbPolicy.Protocol = protocol - elbPolicy.InternalPort = internalPort - elbPolicy.ExternalPort = externalPort - - for _, endpoint := range endpoints { - policylist.EndpointReferences = append(policylist.EndpointReferences, "/endpoints/"+endpoint.Id) - } - - jsonString, err := json.Marshal(elbPolicy) - if err != nil { - return nil, err - } - policylist.Policies = append(policylist.Policies, jsonString) - return policylist.Create() -} - -// AddRoute adds route policy list for the specified endpoints -func AddRoute(endpoints []HNSEndpoint, destinationPrefix string, nextHop string, encapEnabled bool) (*PolicyList, error) { - operation := "AddRoute" - title := "hcsshim::PolicyList::" + operation - logrus.Debugf(title+" destinationPrefix:%s", destinationPrefix) - - policylist := &PolicyList{} - - rPolicy := &RoutePolicy{ - DestinationPrefix: destinationPrefix, - NextHop: nextHop, - EncapEnabled: encapEnabled, - } - rPolicy.Type = Route - - for _, endpoint := range endpoints { - policylist.EndpointReferences = append(policylist.EndpointReferences, "/endpoints/"+endpoint.Id) - } - - jsonString, err := json.Marshal(rPolicy) - if err != nil { - return nil, err - } - - policylist.Policies = append(policylist.Policies, jsonString) - return policylist.Create() -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnssupport.go b/vendor/github.com/Microsoft/hcsshim/internal/hns/hnssupport.go deleted file mode 100644 index d5efba7f..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hns/hnssupport.go +++ /dev/null @@ -1,49 +0,0 @@ -package hns - -import ( - "github.com/sirupsen/logrus" -) - -type HNSSupportedFeatures struct { - Acl HNSAclFeatures `json:"ACL"` -} - -type HNSAclFeatures struct { - AclAddressLists bool `json:"AclAddressLists"` - AclNoHostRulePriority bool `json:"AclHostRulePriority"` - AclPortRanges bool `json:"AclPortRanges"` - AclRuleId bool `json:"AclRuleId"` -} - -func GetHNSSupportedFeatures() HNSSupportedFeatures { - var hnsFeatures HNSSupportedFeatures - - globals, err := GetHNSGlobals() - if err != nil { - // Expected on pre-1803 builds, all features will be false/unsupported - logrus.Debugf("Unable to obtain HNS globals: %s", err) - return hnsFeatures - } - - hnsFeatures.Acl = HNSAclFeatures{ - AclAddressLists: isHNSFeatureSupported(globals.Version, HNSVersion1803), - AclNoHostRulePriority: isHNSFeatureSupported(globals.Version, HNSVersion1803), - AclPortRanges: isHNSFeatureSupported(globals.Version, HNSVersion1803), - AclRuleId: isHNSFeatureSupported(globals.Version, HNSVersion1803), - } - - return hnsFeatures -} - -func isHNSFeatureSupported(currentVersion HNSVersion, minVersionSupported HNSVersion) bool { - if currentVersion.Major < minVersionSupported.Major { - return false - } - if currentVersion.Major > minVersionSupported.Major { - return true - } - if currentVersion.Minor < minVersionSupported.Minor { - return false - } - return true -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hns/namespace.go b/vendor/github.com/Microsoft/hcsshim/internal/hns/namespace.go deleted file mode 100644 index d3b04eef..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hns/namespace.go +++ /dev/null @@ -1,111 +0,0 @@ -package hns - -import ( - "encoding/json" - "fmt" - "os" - "path" - "strings" -) - -type namespaceRequest struct { - IsDefault bool `json:",omitempty"` -} - -type namespaceEndpointRequest struct { - ID string `json:"Id"` -} - -type NamespaceResource struct { - Type string - Data json.RawMessage -} - -type namespaceResourceRequest struct { - Type string - Data interface{} -} - -type Namespace struct { - ID string - IsDefault bool `json:",omitempty"` - ResourceList []NamespaceResource `json:",omitempty"` - CompartmentId uint32 `json:",omitempty"` -} - -func issueNamespaceRequest(id *string, method, subpath string, request interface{}) (*Namespace, error) { - var err error - hnspath := "/namespaces/" - if id != nil { - hnspath = path.Join(hnspath, *id) - } - if subpath != "" { - hnspath = path.Join(hnspath, subpath) - } - var reqJSON []byte - if request != nil { - if reqJSON, err = json.Marshal(request); err != nil { - return nil, err - } - } - var ns Namespace - err = hnsCall(method, hnspath, string(reqJSON), &ns) - if err != nil { - if strings.Contains(err.Error(), "Element not found.") { - return nil, os.ErrNotExist - } - return nil, fmt.Errorf("%s %s: %s", method, hnspath, err) - } - return &ns, err -} - -func CreateNamespace() (string, error) { - req := namespaceRequest{} - ns, err := issueNamespaceRequest(nil, "POST", "", &req) - if err != nil { - return "", err - } - return ns.ID, nil -} - -func RemoveNamespace(id string) error { - _, err := issueNamespaceRequest(&id, "DELETE", "", nil) - return err -} - -func GetNamespaceEndpoints(id string) ([]string, error) { - ns, err := issueNamespaceRequest(&id, "GET", "", nil) - if err != nil { - return nil, err - } - var endpoints []string - for _, rsrc := range ns.ResourceList { - if rsrc.Type == "Endpoint" { - var endpoint namespaceEndpointRequest - err = json.Unmarshal(rsrc.Data, &endpoint) - if err != nil { - return nil, fmt.Errorf("unmarshal endpoint: %s", err) - } - endpoints = append(endpoints, endpoint.ID) - } - } - return endpoints, nil -} - -func AddNamespaceEndpoint(id string, endpointID string) error { - resource := namespaceResourceRequest{ - Type: "Endpoint", - Data: namespaceEndpointRequest{endpointID}, - } - _, err := issueNamespaceRequest(&id, "POST", "addresource", &resource) - return err -} - -func RemoveNamespaceEndpoint(id string, endpointID string) error { - resource := namespaceResourceRequest{ - Type: "Endpoint", - Data: namespaceEndpointRequest{endpointID}, - } - _, err := issueNamespaceRequest(&id, "POST", "removeresource", &resource) - return err -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/hns/zsyscall_windows.go b/vendor/github.com/Microsoft/hcsshim/internal/hns/zsyscall_windows.go deleted file mode 100644 index 204633a4..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/hns/zsyscall_windows.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated mksyscall_windows.exe DO NOT EDIT - -package hns - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return nil - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modvmcompute = windows.NewLazySystemDLL("vmcompute.dll") - - procHNSCall = modvmcompute.NewProc("HNSCall") -) - -func _hnsCall(method string, path string, object string, response **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(method) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(path) - if hr != nil { - return - } - var _p2 *uint16 - _p2, hr = syscall.UTF16PtrFromString(object) - if hr != nil { - return - } - return __hnsCall(_p0, _p1, _p2, response) -} - -func __hnsCall(method *uint16, path *uint16, object *uint16, response **uint16) (hr error) { - if hr = procHNSCall.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procHNSCall.Addr(), 4, uintptr(unsafe.Pointer(method)), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(object)), uintptr(unsafe.Pointer(response)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/interop/interop.go b/vendor/github.com/Microsoft/hcsshim/internal/interop/interop.go deleted file mode 100644 index 922f7c67..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/interop/interop.go +++ /dev/null @@ -1,23 +0,0 @@ -package interop - -import ( - "syscall" - "unsafe" -) - -//go:generate go run ../../mksyscall_windows.go -output zsyscall_windows.go interop.go - -//sys coTaskMemFree(buffer unsafe.Pointer) = api_ms_win_core_com_l1_1_0.CoTaskMemFree - -func ConvertAndFreeCoTaskMemString(buffer *uint16) string { - str := syscall.UTF16ToString((*[1 << 29]uint16)(unsafe.Pointer(buffer))[:]) - coTaskMemFree(unsafe.Pointer(buffer)) - return str -} - -func Win32FromHresult(hr uintptr) syscall.Errno { - if hr&0x1fff0000 == 0x00070000 { - return syscall.Errno(hr & 0xffff) - } - return syscall.Errno(hr) -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/interop/zsyscall_windows.go b/vendor/github.com/Microsoft/hcsshim/internal/interop/zsyscall_windows.go deleted file mode 100644 index 12b0c71c..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/interop/zsyscall_windows.go +++ /dev/null @@ -1,48 +0,0 @@ -// Code generated mksyscall_windows.exe DO NOT EDIT - -package interop - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return nil - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modapi_ms_win_core_com_l1_1_0 = windows.NewLazySystemDLL("api-ms-win-core-com-l1-1-0.dll") - - procCoTaskMemFree = modapi_ms_win_core_com_l1_1_0.NewProc("CoTaskMemFree") -) - -func coTaskMemFree(buffer unsafe.Pointer) { - syscall.Syscall(procCoTaskMemFree.Addr(), 1, uintptr(buffer), 0, 0) - return -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/log/g.go b/vendor/github.com/Microsoft/hcsshim/internal/log/g.go deleted file mode 100644 index ba6b1a4a..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/log/g.go +++ /dev/null @@ -1,23 +0,0 @@ -package log - -import ( - "context" - - "github.com/sirupsen/logrus" - "go.opencensus.io/trace" -) - -// G returns a `logrus.Entry` with the `TraceID, SpanID` from `ctx` if `ctx` -// contains an OpenCensus `trace.Span`. -func G(ctx context.Context) *logrus.Entry { - span := trace.FromContext(ctx) - if span != nil { - sctx := span.SpanContext() - return logrus.WithFields(logrus.Fields{ - "traceID": sctx.TraceID.String(), - "spanID": sctx.SpanID.String(), - // "parentSpanID": TODO: JTERRY75 - Try to convince OC to export this? - }) - } - return logrus.NewEntry(logrus.StandardLogger()) -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/logfields/fields.go b/vendor/github.com/Microsoft/hcsshim/internal/logfields/fields.go deleted file mode 100644 index cf2c166d..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/logfields/fields.go +++ /dev/null @@ -1,32 +0,0 @@ -package logfields - -const ( - // Identifiers - - ContainerID = "cid" - UVMID = "uvm-id" - ProcessID = "pid" - - // Common Misc - - // Timeout represents an operation timeout. - Timeout = "timeout" - JSON = "json" - - // Keys/values - - Field = "field" - OCIAnnotation = "oci-annotation" - Value = "value" - - // Golang type's - - ExpectedType = "expected-type" - Bool = "bool" - Uint32 = "uint32" - Uint64 = "uint64" - - // runhcs - - VMShimOperation = "vmshim-op" -) diff --git a/vendor/github.com/Microsoft/hcsshim/internal/longpath/longpath.go b/vendor/github.com/Microsoft/hcsshim/internal/longpath/longpath.go deleted file mode 100644 index e5b8b85e..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/longpath/longpath.go +++ /dev/null @@ -1,24 +0,0 @@ -package longpath - -import ( - "path/filepath" - "strings" -) - -// LongAbs makes a path absolute and returns it in NT long path form. -func LongAbs(path string) (string, error) { - if strings.HasPrefix(path, `\\?\`) || strings.HasPrefix(path, `\\.\`) { - return path, nil - } - if !filepath.IsAbs(path) { - absPath, err := filepath.Abs(path) - if err != nil { - return "", err - } - path = absPath - } - if strings.HasPrefix(path, `\\`) { - return `\\?\UNC\` + path[2:], nil - } - return `\\?\` + path, nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/mergemaps/merge.go b/vendor/github.com/Microsoft/hcsshim/internal/mergemaps/merge.go deleted file mode 100644 index 7e95efb3..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/mergemaps/merge.go +++ /dev/null @@ -1,52 +0,0 @@ -package mergemaps - -import "encoding/json" - -// Merge recursively merges map `fromMap` into map `ToMap`. Any pre-existing values -// in ToMap are overwritten. Values in fromMap are added to ToMap. -// From http://stackoverflow.com/questions/40491438/merging-two-json-strings-in-golang -func Merge(fromMap, ToMap interface{}) interface{} { - switch fromMap := fromMap.(type) { - case map[string]interface{}: - ToMap, ok := ToMap.(map[string]interface{}) - if !ok { - return fromMap - } - for keyToMap, valueToMap := range ToMap { - if valueFromMap, ok := fromMap[keyToMap]; ok { - fromMap[keyToMap] = Merge(valueFromMap, valueToMap) - } else { - fromMap[keyToMap] = valueToMap - } - } - case nil: - // merge(nil, map[string]interface{...}) -> map[string]interface{...} - ToMap, ok := ToMap.(map[string]interface{}) - if ok { - return ToMap - } - } - return fromMap -} - -// MergeJSON merges the contents of a JSON string into an object representation, -// returning a new object suitable for translating to JSON. -func MergeJSON(object interface{}, additionalJSON []byte) (interface{}, error) { - if len(additionalJSON) == 0 { - return object, nil - } - objectJSON, err := json.Marshal(object) - if err != nil { - return nil, err - } - var objectMap, newMap map[string]interface{} - err = json.Unmarshal(objectJSON, &objectMap) - if err != nil { - return nil, err - } - err = json.Unmarshal(additionalJSON, &newMap) - if err != nil { - return nil, err - } - return Merge(newMap, objectMap), nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/oc/exporter.go b/vendor/github.com/Microsoft/hcsshim/internal/oc/exporter.go deleted file mode 100644 index f428bdaf..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/oc/exporter.go +++ /dev/null @@ -1,43 +0,0 @@ -package oc - -import ( - "github.com/sirupsen/logrus" - "go.opencensus.io/trace" -) - -var _ = (trace.Exporter)(&LogrusExporter{}) - -// LogrusExporter is an OpenCensus `trace.Exporter` that exports -// `trace.SpanData` to logrus output. -type LogrusExporter struct { -} - -// ExportSpan exports `s` based on the the following rules: -// -// 1. All output will contain `s.Attributes`, `s.TraceID`, `s.SpanID`, -// `s.ParentSpanID` for correlation -// -// 2. Any calls to .Annotate will not be supported. -// -// 3. The span itself will be written at `logrus.InfoLevel` unless -// `s.Status.Code != 0` in which case it will be written at `logrus.ErrorLevel` -// providing `s.Status.Message` as the error value. -func (le *LogrusExporter) ExportSpan(s *trace.SpanData) { - // Combine all span annotations with traceID, spanID, parentSpanID - baseEntry := logrus.WithFields(logrus.Fields(s.Attributes)) - baseEntry.Data["traceID"] = s.TraceID.String() - baseEntry.Data["spanID"] = s.SpanID.String() - baseEntry.Data["parentSpanID"] = s.ParentSpanID.String() - baseEntry.Data["startTime"] = s.StartTime - baseEntry.Data["endTime"] = s.EndTime - baseEntry.Data["duration"] = s.EndTime.Sub(s.StartTime).String() - baseEntry.Data["name"] = s.Name - baseEntry.Time = s.StartTime - - level := logrus.InfoLevel - if s.Status.Code != 0 { - level = logrus.ErrorLevel - baseEntry.Data[logrus.ErrorKey] = s.Status.Message - } - baseEntry.Log(level, "Span") -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/oc/span.go b/vendor/github.com/Microsoft/hcsshim/internal/oc/span.go deleted file mode 100644 index fee4765c..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/oc/span.go +++ /dev/null @@ -1,17 +0,0 @@ -package oc - -import ( - "go.opencensus.io/trace" -) - -// SetSpanStatus sets `span.SetStatus` to the proper status depending on `err`. If -// `err` is `nil` assumes `trace.StatusCodeOk`. -func SetSpanStatus(span *trace.Span, err error) { - status := trace.Status{} - if err != nil { - // TODO: JTERRY75 - Handle errors in a non-generic way - status.Code = trace.StatusCodeUnknown - status.Message = err.Error() - } - span.SetStatus(status) -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/safefile/safeopen.go b/vendor/github.com/Microsoft/hcsshim/internal/safefile/safeopen.go deleted file mode 100644 index 05f22f39..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/safefile/safeopen.go +++ /dev/null @@ -1,375 +0,0 @@ -package safefile - -import ( - "errors" - "io" - "os" - "path/filepath" - "strings" - "syscall" - "unicode/utf16" - "unsafe" - - "github.com/Microsoft/hcsshim/internal/longpath" - "github.com/Microsoft/hcsshim/internal/winapi" - - winio "github.com/Microsoft/go-winio" -) - -func OpenRoot(path string) (*os.File, error) { - longpath, err := longpath.LongAbs(path) - if err != nil { - return nil, err - } - return winio.OpenForBackup(longpath, syscall.GENERIC_READ, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, syscall.OPEN_EXISTING) -} - -func cleanGoStringRelativePath(path string) (string, error) { - path = filepath.Clean(path) - if strings.Contains(path, ":") { - // Since alternate data streams must follow the file they - // are attached to, finding one here (out of order) is invalid. - return "", errors.New("path contains invalid character `:`") - } - fspath := filepath.FromSlash(path) - if len(fspath) > 0 && fspath[0] == '\\' { - return "", errors.New("expected relative path") - } - return fspath, nil -} - -func ntRelativePath(path string) ([]uint16, error) { - fspath, err := cleanGoStringRelativePath(path) - if err != nil { - return nil, err - } - - path16 := utf16.Encode(([]rune)(fspath)) - if len(path16) > 32767 { - return nil, syscall.ENAMETOOLONG - } - - return path16, nil -} - -// openRelativeInternal opens a relative path from the given root, failing if -// any of the intermediate path components are reparse points. -func openRelativeInternal(path string, root *os.File, accessMask uint32, shareFlags uint32, createDisposition uint32, flags uint32) (*os.File, error) { - var ( - h uintptr - iosb winapi.IOStatusBlock - oa winapi.ObjectAttributes - ) - - cleanRelativePath, err := cleanGoStringRelativePath(path) - if err != nil { - return nil, err - } - - if root == nil || root.Fd() == 0 { - return nil, errors.New("missing root directory") - } - - pathUnicode, err := winapi.NewUnicodeString(cleanRelativePath) - if err != nil { - return nil, err - } - - oa.Length = unsafe.Sizeof(oa) - oa.ObjectName = pathUnicode - oa.RootDirectory = uintptr(root.Fd()) - oa.Attributes = winapi.OBJ_DONT_REPARSE - status := winapi.NtCreateFile( - &h, - accessMask|syscall.SYNCHRONIZE, - &oa, - &iosb, - nil, - 0, - shareFlags, - createDisposition, - winapi.FILE_OPEN_FOR_BACKUP_INTENT|winapi.FILE_SYNCHRONOUS_IO_NONALERT|flags, - nil, - 0, - ) - if status != 0 { - return nil, winapi.RtlNtStatusToDosError(status) - } - - fullPath, err := longpath.LongAbs(filepath.Join(root.Name(), path)) - if err != nil { - syscall.Close(syscall.Handle(h)) - return nil, err - } - - return os.NewFile(h, fullPath), nil -} - -// OpenRelative opens a relative path from the given root, failing if -// any of the intermediate path components are reparse points. -func OpenRelative(path string, root *os.File, accessMask uint32, shareFlags uint32, createDisposition uint32, flags uint32) (*os.File, error) { - f, err := openRelativeInternal(path, root, accessMask, shareFlags, createDisposition, flags) - if err != nil { - err = &os.PathError{Op: "open", Path: filepath.Join(root.Name(), path), Err: err} - } - return f, err -} - -// LinkRelative creates a hard link from oldname to newname (relative to oldroot -// and newroot), failing if any of the intermediate path components are reparse -// points. -func LinkRelative(oldname string, oldroot *os.File, newname string, newroot *os.File) error { - // Open the old file. - oldf, err := openRelativeInternal( - oldname, - oldroot, - syscall.FILE_WRITE_ATTRIBUTES, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, - winapi.FILE_OPEN, - 0, - ) - if err != nil { - return &os.LinkError{Op: "link", Old: filepath.Join(oldroot.Name(), oldname), New: filepath.Join(newroot.Name(), newname), Err: err} - } - defer oldf.Close() - - // Open the parent of the new file. - var parent *os.File - parentPath := filepath.Dir(newname) - if parentPath != "." { - parent, err = openRelativeInternal( - parentPath, - newroot, - syscall.GENERIC_READ, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, - winapi.FILE_OPEN, - winapi.FILE_DIRECTORY_FILE) - if err != nil { - return &os.LinkError{Op: "link", Old: oldf.Name(), New: filepath.Join(newroot.Name(), newname), Err: err} - } - defer parent.Close() - - fi, err := winio.GetFileBasicInfo(parent) - if err != nil { - return err - } - if (fi.FileAttributes & syscall.FILE_ATTRIBUTE_REPARSE_POINT) != 0 { - return &os.LinkError{Op: "link", Old: oldf.Name(), New: filepath.Join(newroot.Name(), newname), Err: winapi.RtlNtStatusToDosError(winapi.STATUS_REPARSE_POINT_ENCOUNTERED)} - } - - } else { - parent = newroot - } - - // Issue an NT call to create the link. This will be safe because NT will - // not open any more directories to create the link, so it cannot walk any - // more reparse points. - newbase := filepath.Base(newname) - newbase16, err := ntRelativePath(newbase) - if err != nil { - return err - } - - size := int(unsafe.Offsetof(winapi.FileLinkInformation{}.FileName)) + len(newbase16)*2 - linkinfoBuffer := winapi.LocalAlloc(0, size) - defer winapi.LocalFree(linkinfoBuffer) - - linkinfo := (*winapi.FileLinkInformation)(unsafe.Pointer(linkinfoBuffer)) - linkinfo.RootDirectory = parent.Fd() - linkinfo.FileNameLength = uint32(len(newbase16) * 2) - copy(winapi.Uint16BufferToSlice(&linkinfo.FileName[0], len(newbase16)), newbase16) - - var iosb winapi.IOStatusBlock - status := winapi.NtSetInformationFile( - oldf.Fd(), - &iosb, - linkinfoBuffer, - uint32(size), - winapi.FileLinkInformationClass, - ) - if status != 0 { - return &os.LinkError{Op: "link", Old: oldf.Name(), New: filepath.Join(parent.Name(), newbase), Err: winapi.RtlNtStatusToDosError(status)} - } - - return nil -} - -// deleteOnClose marks a file to be deleted when the handle is closed. -func deleteOnClose(f *os.File) error { - disposition := winapi.FileDispositionInformationEx{Flags: winapi.FILE_DISPOSITION_DELETE} - var iosb winapi.IOStatusBlock - status := winapi.NtSetInformationFile( - f.Fd(), - &iosb, - uintptr(unsafe.Pointer(&disposition)), - uint32(unsafe.Sizeof(disposition)), - winapi.FileDispositionInformationExClass, - ) - if status != 0 { - return winapi.RtlNtStatusToDosError(status) - } - return nil -} - -// clearReadOnly clears the readonly attribute on a file. -func clearReadOnly(f *os.File) error { - bi, err := winio.GetFileBasicInfo(f) - if err != nil { - return err - } - if bi.FileAttributes&syscall.FILE_ATTRIBUTE_READONLY == 0 { - return nil - } - sbi := winio.FileBasicInfo{ - FileAttributes: bi.FileAttributes &^ syscall.FILE_ATTRIBUTE_READONLY, - } - if sbi.FileAttributes == 0 { - sbi.FileAttributes = syscall.FILE_ATTRIBUTE_NORMAL - } - return winio.SetFileBasicInfo(f, &sbi) -} - -// RemoveRelative removes a file or directory relative to a root, failing if any -// intermediate path components are reparse points. -func RemoveRelative(path string, root *os.File) error { - f, err := openRelativeInternal( - path, - root, - winapi.FILE_READ_ATTRIBUTES|winapi.FILE_WRITE_ATTRIBUTES|winapi.DELETE, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, - winapi.FILE_OPEN, - winapi.FILE_OPEN_REPARSE_POINT) - if err == nil { - defer f.Close() - err = deleteOnClose(f) - if err == syscall.ERROR_ACCESS_DENIED { - // Maybe the file is marked readonly. Clear the bit and retry. - clearReadOnly(f) - err = deleteOnClose(f) - } - } - if err != nil { - return &os.PathError{Op: "remove", Path: filepath.Join(root.Name(), path), Err: err} - } - return nil -} - -// RemoveAllRelative removes a directory tree relative to a root, failing if any -// intermediate path components are reparse points. -func RemoveAllRelative(path string, root *os.File) error { - fi, err := LstatRelative(path, root) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return err - } - fileAttributes := fi.Sys().(*syscall.Win32FileAttributeData).FileAttributes - if fileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY == 0 || fileAttributes&syscall.FILE_ATTRIBUTE_REPARSE_POINT != 0 { - // If this is a reparse point, it can't have children. Simple remove will do. - err := RemoveRelative(path, root) - if err == nil || os.IsNotExist(err) { - return nil - } - return err - } - - // It is necessary to use os.Open as Readdirnames does not work with - // OpenRelative. This is safe because the above lstatrelative fails - // if the target is outside the root, and we know this is not a - // symlink from the above FILE_ATTRIBUTE_REPARSE_POINT check. - fd, err := os.Open(filepath.Join(root.Name(), path)) - if err != nil { - if os.IsNotExist(err) { - // Race. It was deleted between the Lstat and Open. - // Return nil per RemoveAll's docs. - return nil - } - return err - } - - // Remove contents & return first error. - for { - names, err1 := fd.Readdirnames(100) - for _, name := range names { - err1 := RemoveAllRelative(path+string(os.PathSeparator)+name, root) - if err == nil { - err = err1 - } - } - if err1 == io.EOF { - break - } - // If Readdirnames returned an error, use it. - if err == nil { - err = err1 - } - if len(names) == 0 { - break - } - } - fd.Close() - - // Remove directory. - err1 := RemoveRelative(path, root) - if err1 == nil || os.IsNotExist(err1) { - return nil - } - if err == nil { - err = err1 - } - return err -} - -// MkdirRelative creates a directory relative to a root, failing if any -// intermediate path components are reparse points. -func MkdirRelative(path string, root *os.File) error { - f, err := openRelativeInternal( - path, - root, - 0, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, - winapi.FILE_CREATE, - winapi.FILE_DIRECTORY_FILE) - if err == nil { - f.Close() - } else { - err = &os.PathError{Op: "mkdir", Path: filepath.Join(root.Name(), path), Err: err} - } - return err -} - -// LstatRelative performs a stat operation on a file relative to a root, failing -// if any intermediate path components are reparse points. -func LstatRelative(path string, root *os.File) (os.FileInfo, error) { - f, err := openRelativeInternal( - path, - root, - winapi.FILE_READ_ATTRIBUTES, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, - winapi.FILE_OPEN, - winapi.FILE_OPEN_REPARSE_POINT) - if err != nil { - return nil, &os.PathError{Op: "stat", Path: filepath.Join(root.Name(), path), Err: err} - } - defer f.Close() - return f.Stat() -} - -// EnsureNotReparsePointRelative validates that a given file (relative to a -// root) and all intermediate path components are not a reparse points. -func EnsureNotReparsePointRelative(path string, root *os.File) error { - // Perform an open with OBJ_DONT_REPARSE but without specifying FILE_OPEN_REPARSE_POINT. - f, err := OpenRelative( - path, - root, - 0, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, - winapi.FILE_OPEN, - 0) - if err != nil { - return err - } - f.Close() - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema1/schema1.go b/vendor/github.com/Microsoft/hcsshim/internal/schema1/schema1.go deleted file mode 100644 index cd1ec84a..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema1/schema1.go +++ /dev/null @@ -1,250 +0,0 @@ -package schema1 - -import ( - "encoding/json" - "time" - - "github.com/Microsoft/go-winio/pkg/guid" - hcsschema "github.com/Microsoft/hcsshim/internal/schema2" -) - -// ProcessConfig is used as both the input of Container.CreateProcess -// and to convert the parameters to JSON for passing onto the HCS -type ProcessConfig struct { - ApplicationName string `json:",omitempty"` - CommandLine string `json:",omitempty"` - CommandArgs []string `json:",omitempty"` // Used by Linux Containers on Windows - User string `json:",omitempty"` - WorkingDirectory string `json:",omitempty"` - Environment map[string]string `json:",omitempty"` - EmulateConsole bool `json:",omitempty"` - CreateStdInPipe bool `json:",omitempty"` - CreateStdOutPipe bool `json:",omitempty"` - CreateStdErrPipe bool `json:",omitempty"` - ConsoleSize [2]uint `json:",omitempty"` - CreateInUtilityVm bool `json:",omitempty"` // Used by Linux Containers on Windows - OCISpecification *json.RawMessage `json:",omitempty"` // Used by Linux Containers on Windows -} - -type Layer struct { - ID string - Path string -} - -type MappedDir struct { - HostPath string - ContainerPath string - ReadOnly bool - BandwidthMaximum uint64 - IOPSMaximum uint64 - CreateInUtilityVM bool - // LinuxMetadata - Support added in 1803/RS4+. - LinuxMetadata bool `json:",omitempty"` -} - -type MappedPipe struct { - HostPath string - ContainerPipeName string -} - -type HvRuntime struct { - ImagePath string `json:",omitempty"` - SkipTemplate bool `json:",omitempty"` - LinuxInitrdFile string `json:",omitempty"` // File under ImagePath on host containing an initrd image for starting a Linux utility VM - LinuxKernelFile string `json:",omitempty"` // File under ImagePath on host containing a kernel for starting a Linux utility VM - LinuxBootParameters string `json:",omitempty"` // Additional boot parameters for starting a Linux Utility VM in initrd mode - BootSource string `json:",omitempty"` // "Vhd" for Linux Utility VM booting from VHD - WritableBootSource bool `json:",omitempty"` // Linux Utility VM booting from VHD -} - -type MappedVirtualDisk struct { - HostPath string `json:",omitempty"` // Path to VHD on the host - ContainerPath string // Platform-specific mount point path in the container - CreateInUtilityVM bool `json:",omitempty"` - ReadOnly bool `json:",omitempty"` - Cache string `json:",omitempty"` // "" (Unspecified); "Disabled"; "Enabled"; "Private"; "PrivateAllowSharing" - AttachOnly bool `json:",omitempty"` -} - -// AssignedDevice represents a device that has been directly assigned to a container -// -// NOTE: Support added in RS5 -type AssignedDevice struct { - // InterfaceClassGUID of the device to assign to container. - InterfaceClassGUID string `json:"InterfaceClassGuid,omitempty"` -} - -// ContainerConfig is used as both the input of CreateContainer -// and to convert the parameters to JSON for passing onto the HCS -type ContainerConfig struct { - SystemType string // HCS requires this to be hard-coded to "Container" - Name string // Name of the container. We use the docker ID. - Owner string `json:",omitempty"` // The management platform that created this container - VolumePath string `json:",omitempty"` // Windows volume path for scratch space. Used by Windows Server Containers only. Format \\?\\Volume{GUID} - IgnoreFlushesDuringBoot bool `json:",omitempty"` // Optimization hint for container startup in Windows - LayerFolderPath string `json:",omitempty"` // Where the layer folders are located. Used by Windows Server Containers only. Format %root%\windowsfilter\containerID - Layers []Layer // List of storage layers. Required for Windows Server and Hyper-V Containers. Format ID=GUID;Path=%root%\windowsfilter\layerID - Credentials string `json:",omitempty"` // Credentials information - ProcessorCount uint32 `json:",omitempty"` // Number of processors to assign to the container. - ProcessorWeight uint64 `json:",omitempty"` // CPU shares (relative weight to other containers with cpu shares). Range is from 1 to 10000. A value of 0 results in default shares. - ProcessorMaximum int64 `json:",omitempty"` // Specifies the portion of processor cycles that this container can use as a percentage times 100. Range is from 1 to 10000. A value of 0 results in no limit. - StorageIOPSMaximum uint64 `json:",omitempty"` // Maximum Storage IOPS - StorageBandwidthMaximum uint64 `json:",omitempty"` // Maximum Storage Bandwidth in bytes per second - StorageSandboxSize uint64 `json:",omitempty"` // Size in bytes that the container system drive should be expanded to if smaller - MemoryMaximumInMB int64 `json:",omitempty"` // Maximum memory available to the container in Megabytes - HostName string `json:",omitempty"` // Hostname - MappedDirectories []MappedDir `json:",omitempty"` // List of mapped directories (volumes/mounts) - MappedPipes []MappedPipe `json:",omitempty"` // List of mapped Windows named pipes - HvPartition bool // True if it a Hyper-V Container - NetworkSharedContainerName string `json:",omitempty"` // Name (ID) of the container that we will share the network stack with. - EndpointList []string `json:",omitempty"` // List of networking endpoints to be attached to container - HvRuntime *HvRuntime `json:",omitempty"` // Hyper-V container settings. Used by Hyper-V containers only. Format ImagePath=%root%\BaseLayerID\UtilityVM - Servicing bool `json:",omitempty"` // True if this container is for servicing - AllowUnqualifiedDNSQuery bool `json:",omitempty"` // True to allow unqualified DNS name resolution - DNSSearchList string `json:",omitempty"` // Comma seperated list of DNS suffixes to use for name resolution - ContainerType string `json:",omitempty"` // "Linux" for Linux containers on Windows. Omitted otherwise. - TerminateOnLastHandleClosed bool `json:",omitempty"` // Should HCS terminate the container once all handles have been closed - MappedVirtualDisks []MappedVirtualDisk `json:",omitempty"` // Array of virtual disks to mount at start - AssignedDevices []AssignedDevice `json:",omitempty"` // Array of devices to assign. NOTE: Support added in RS5 -} - -type ComputeSystemQuery struct { - IDs []string `json:"Ids,omitempty"` - Types []string `json:",omitempty"` - Names []string `json:",omitempty"` - Owners []string `json:",omitempty"` -} - -type PropertyType string - -const ( - PropertyTypeStatistics PropertyType = "Statistics" // V1 and V2 - PropertyTypeProcessList = "ProcessList" // V1 and V2 - PropertyTypeMappedVirtualDisk = "MappedVirtualDisk" // Not supported in V2 schema call - PropertyTypeGuestConnection = "GuestConnection" // V1 and V2. Nil return from HCS before RS5 -) - -type PropertyQuery struct { - PropertyTypes []PropertyType `json:",omitempty"` -} - -// ContainerProperties holds the properties for a container and the processes running in that container -type ContainerProperties struct { - ID string `json:"Id"` - State string - Name string - SystemType string - RuntimeOSType string `json:"RuntimeOsType,omitempty"` - Owner string - SiloGUID string `json:"SiloGuid,omitempty"` - RuntimeID guid.GUID `json:"RuntimeId,omitempty"` - IsRuntimeTemplate bool `json:",omitempty"` - RuntimeImagePath string `json:",omitempty"` - Stopped bool `json:",omitempty"` - ExitType string `json:",omitempty"` - AreUpdatesPending bool `json:",omitempty"` - ObRoot string `json:",omitempty"` - Statistics Statistics `json:",omitempty"` - ProcessList []ProcessListItem `json:",omitempty"` - MappedVirtualDiskControllers map[int]MappedVirtualDiskController `json:",omitempty"` - GuestConnectionInfo GuestConnectionInfo `json:",omitempty"` -} - -// MemoryStats holds the memory statistics for a container -type MemoryStats struct { - UsageCommitBytes uint64 `json:"MemoryUsageCommitBytes,omitempty"` - UsageCommitPeakBytes uint64 `json:"MemoryUsageCommitPeakBytes,omitempty"` - UsagePrivateWorkingSetBytes uint64 `json:"MemoryUsagePrivateWorkingSetBytes,omitempty"` -} - -// ProcessorStats holds the processor statistics for a container -type ProcessorStats struct { - TotalRuntime100ns uint64 `json:",omitempty"` - RuntimeUser100ns uint64 `json:",omitempty"` - RuntimeKernel100ns uint64 `json:",omitempty"` -} - -// StorageStats holds the storage statistics for a container -type StorageStats struct { - ReadCountNormalized uint64 `json:",omitempty"` - ReadSizeBytes uint64 `json:",omitempty"` - WriteCountNormalized uint64 `json:",omitempty"` - WriteSizeBytes uint64 `json:",omitempty"` -} - -// NetworkStats holds the network statistics for a container -type NetworkStats struct { - BytesReceived uint64 `json:",omitempty"` - BytesSent uint64 `json:",omitempty"` - PacketsReceived uint64 `json:",omitempty"` - PacketsSent uint64 `json:",omitempty"` - DroppedPacketsIncoming uint64 `json:",omitempty"` - DroppedPacketsOutgoing uint64 `json:",omitempty"` - EndpointId string `json:",omitempty"` - InstanceId string `json:",omitempty"` -} - -// Statistics is the structure returned by a statistics call on a container -type Statistics struct { - Timestamp time.Time `json:",omitempty"` - ContainerStartTime time.Time `json:",omitempty"` - Uptime100ns uint64 `json:",omitempty"` - Memory MemoryStats `json:",omitempty"` - Processor ProcessorStats `json:",omitempty"` - Storage StorageStats `json:",omitempty"` - Network []NetworkStats `json:",omitempty"` -} - -// ProcessList is the structure of an item returned by a ProcessList call on a container -type ProcessListItem struct { - CreateTimestamp time.Time `json:",omitempty"` - ImageName string `json:",omitempty"` - KernelTime100ns uint64 `json:",omitempty"` - MemoryCommitBytes uint64 `json:",omitempty"` - MemoryWorkingSetPrivateBytes uint64 `json:",omitempty"` - MemoryWorkingSetSharedBytes uint64 `json:",omitempty"` - ProcessId uint32 `json:",omitempty"` - UserTime100ns uint64 `json:",omitempty"` -} - -// MappedVirtualDiskController is the structure of an item returned by a MappedVirtualDiskList call on a container -type MappedVirtualDiskController struct { - MappedVirtualDisks map[int]MappedVirtualDisk `json:",omitempty"` -} - -// GuestDefinedCapabilities is part of the GuestConnectionInfo returned by a GuestConnection call on a utility VM -type GuestDefinedCapabilities struct { - NamespaceAddRequestSupported bool `json:",omitempty"` - SignalProcessSupported bool `json:",omitempty"` - DumpStacksSupported bool `json:",omitempty"` - DeleteContainerStateSupported bool `json:",omitempty"` - UpdateContainerSupported bool `json:",omitempty"` -} - -// GuestConnectionInfo is the structure of an iterm return by a GuestConnection call on a utility VM -type GuestConnectionInfo struct { - SupportedSchemaVersions []hcsschema.Version `json:",omitempty"` - ProtocolVersion uint32 `json:",omitempty"` - GuestDefinedCapabilities GuestDefinedCapabilities `json:",omitempty"` -} - -// Type of Request Support in ModifySystem -type RequestType string - -// Type of Resource Support in ModifySystem -type ResourceType string - -// RequestType const -const ( - Add RequestType = "Add" - Remove RequestType = "Remove" - Network ResourceType = "Network" -) - -// ResourceModificationRequestResponse is the structure used to send request to the container to modify the system -// Supported resource types are Network and Request Types are Add/Remove -type ResourceModificationRequestResponse struct { - Resource ResourceType `json:"ResourceType"` - Data interface{} `json:"Settings"` - Request RequestType `json:"RequestType,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/attachment.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/attachment.go deleted file mode 100644 index bcfeb34d..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/attachment.go +++ /dev/null @@ -1,30 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Attachment struct { - Type_ string `json:"Type,omitempty"` - - Path string `json:"Path,omitempty"` - - IgnoreFlushes bool `json:"IgnoreFlushes,omitempty"` - - CachingMode string `json:"CachingMode,omitempty"` - - NoWriteHardening bool `json:"NoWriteHardening,omitempty"` - - DisableExpansionOptimization bool `json:"DisableExpansionOptimization,omitempty"` - - IgnoreRelativeLocator bool `json:"IgnoreRelativeLocator,omitempty"` - - CaptureIoAttributionContext bool `json:"CaptureIoAttributionContext,omitempty"` - - ReadOnly bool `json:"ReadOnly,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/battery.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/battery.go deleted file mode 100644 index ecbbed4c..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/battery.go +++ /dev/null @@ -1,13 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Battery struct { -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cache_query_stats_response.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/cache_query_stats_response.go deleted file mode 100644 index c1ea3953..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cache_query_stats_response.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type CacheQueryStatsResponse struct { - L3OccupancyBytes int32 `json:"L3OccupancyBytes,omitempty"` - - L3TotalBwBytes int32 `json:"L3TotalBwBytes,omitempty"` - - L3LocalBwBytes int32 `json:"L3LocalBwBytes,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/chipset.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/chipset.go deleted file mode 100644 index ca75277a..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/chipset.go +++ /dev/null @@ -1,27 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Chipset struct { - Uefi *Uefi `json:"Uefi,omitempty"` - - IsNumLockDisabled bool `json:"IsNumLockDisabled,omitempty"` - - BaseBoardSerialNumber string `json:"BaseBoardSerialNumber,omitempty"` - - ChassisSerialNumber string `json:"ChassisSerialNumber,omitempty"` - - ChassisAssetTag string `json:"ChassisAssetTag,omitempty"` - - UseUtc bool `json:"UseUtc,omitempty"` - - // LinuxKernelDirect - Added in v2.2 Builds >=181117 - LinuxKernelDirect *LinuxKernelDirect `json:"LinuxKernelDirect,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/close_handle.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/close_handle.go deleted file mode 100644 index b4f9c315..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/close_handle.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type CloseHandle struct { - Handle string `json:"Handle,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/com_port.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/com_port.go deleted file mode 100644 index 8bf8cab6..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/com_port.go +++ /dev/null @@ -1,17 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// ComPort specifies the named pipe that will be used for the port, with empty string indicating a disconnected port. -type ComPort struct { - NamedPipe string `json:"NamedPipe,omitempty"` - - OptimizeForDebugger bool `json:"OptimizeForDebugger,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/compute_system.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/compute_system.go deleted file mode 100644 index 10cea67e..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/compute_system.go +++ /dev/null @@ -1,26 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ComputeSystem struct { - Owner string `json:"Owner,omitempty"` - - SchemaVersion *Version `json:"SchemaVersion,omitempty"` - - HostingSystemId string `json:"HostingSystemId,omitempty"` - - HostedSystem interface{} `json:"HostedSystem,omitempty"` - - Container *Container `json:"Container,omitempty"` - - VirtualMachine *VirtualMachine `json:"VirtualMachine,omitempty"` - - ShouldTerminateOnLastHandleClosed bool `json:"ShouldTerminateOnLastHandleClosed,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/configuration.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/configuration.go deleted file mode 100644 index 1d5dfe68..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/configuration.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -import ( - "net/http" -) - -// contextKeys are used to identify the type of value in the context. -// Since these are string, it is possible to get a short description of the -// context key for logging and debugging using key.String(). - -type contextKey string - -func (c contextKey) String() string { - return "auth " + string(c) -} - -var ( - // ContextOAuth2 takes a oauth2.TokenSource as authentication for the request. - ContextOAuth2 = contextKey("token") - - // ContextBasicAuth takes BasicAuth as authentication for the request. - ContextBasicAuth = contextKey("basic") - - // ContextAccessToken takes a string oauth2 access token as authentication for the request. - ContextAccessToken = contextKey("accesstoken") - - // ContextAPIKey takes an APIKey as authentication for the request - ContextAPIKey = contextKey("apikey") -) - -// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth -type BasicAuth struct { - UserName string `json:"userName,omitempty"` - Password string `json:"password,omitempty"` -} - -// APIKey provides API key based authentication to a request passed via context using ContextAPIKey -type APIKey struct { - Key string - Prefix string -} - -type Configuration struct { - BasePath string `json:"basePath,omitempty"` - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - HTTPClient *http.Client -} - -func NewConfiguration() *Configuration { - cfg := &Configuration{ - BasePath: "https://localhost", - DefaultHeader: make(map[string]string), - UserAgent: "Swagger-Codegen/2.1.0/go", - } - return cfg -} - -func (c *Configuration) AddDefaultHeader(key string, value string) { - c.DefaultHeader[key] = value -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/console_size.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/console_size.go deleted file mode 100644 index 68aa04a5..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/console_size.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ConsoleSize struct { - Height int32 `json:"Height,omitempty"` - - Width int32 `json:"Width,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/container.go deleted file mode 100644 index 4fb23107..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container.go +++ /dev/null @@ -1,34 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Container struct { - GuestOs *GuestOs `json:"GuestOs,omitempty"` - - Storage *Storage `json:"Storage,omitempty"` - - MappedDirectories []MappedDirectory `json:"MappedDirectories,omitempty"` - - MappedPipes []MappedPipe `json:"MappedPipes,omitempty"` - - Memory *Memory `json:"Memory,omitempty"` - - Processor *Processor `json:"Processor,omitempty"` - - Networking *Networking `json:"Networking,omitempty"` - - HvSocket *HvSocket `json:"HvSocket,omitempty"` - - ContainerCredentialGuard *ContainerCredentialGuardState `json:"ContainerCredentialGuard,omitempty"` - - RegistryChanges *RegistryChanges `json:"RegistryChanges,omitempty"` - - AssignedDevices []Device `json:"AssignedDevices,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_add_instance_request.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_add_instance_request.go deleted file mode 100644 index 495c6ebc..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_add_instance_request.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ContainerCredentialGuardAddInstanceRequest struct { - Id string `json:"Id,omitempty"` - CredentialSpec string `json:"CredentialSpec,omitempty"` - Transport string `json:"Transport,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_hv_socket_service_config.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_hv_socket_service_config.go deleted file mode 100644 index 1ed4c008..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_hv_socket_service_config.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ContainerCredentialGuardHvSocketServiceConfig struct { - ServiceId string `json:"ServiceId,omitempty"` - ServiceConfig *HvSocketServiceConfig `json:"ServiceConfig,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_instance.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_instance.go deleted file mode 100644 index d7ebd0fc..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_instance.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ContainerCredentialGuardInstance struct { - Id string `json:"Id,omitempty"` - CredentialGuard *ContainerCredentialGuardState `json:"CredentialGuard,omitempty"` - HvSocketConfig *ContainerCredentialGuardHvSocketServiceConfig `json:"HvSocketConfig,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_modify_operation.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_modify_operation.go deleted file mode 100644 index 71005b09..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_modify_operation.go +++ /dev/null @@ -1,17 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ContainerCredentialGuardModifyOperation string - -const ( - AddInstance ContainerCredentialGuardModifyOperation = "AddInstance" - RemoveInstance ContainerCredentialGuardModifyOperation = "RemoveInstance" -) diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_operation_request.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_operation_request.go deleted file mode 100644 index 952cda49..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_operation_request.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ContainerCredentialGuardOperationRequest struct { - Operation ContainerCredentialGuardModifyOperation `json:"Operation,omitempty"` - OperationDetails interface{} `json:"OperationDetails,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_remove_instance_request.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_remove_instance_request.go deleted file mode 100644 index 32e5a3be..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_remove_instance_request.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ContainerCredentialGuardRemoveInstanceRequest struct { - Id string `json:"Id,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_state.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_state.go deleted file mode 100644 index 0f8f6443..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_state.go +++ /dev/null @@ -1,25 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ContainerCredentialGuardState struct { - - // Authentication cookie for calls to a Container Credential Guard instance. - Cookie string `json:"Cookie,omitempty"` - - // Name of the RPC endpoint of the Container Credential Guard instance. - RpcEndpoint string `json:"RpcEndpoint,omitempty"` - - // Transport used for the configured Container Credential Guard instance. - Transport string `json:"Transport,omitempty"` - - // Credential spec used for the configured Container Credential Guard instance. - CredentialSpec string `json:"CredentialSpec,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_system_info.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_system_info.go deleted file mode 100644 index ea306fa2..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_credential_guard_system_info.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ContainerCredentialGuardSystemInfo struct { - Instances []ContainerCredentialGuardInstance `json:"Instances,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_memory_information.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_memory_information.go deleted file mode 100644 index 1fd7ca5d..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/container_memory_information.go +++ /dev/null @@ -1,25 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// memory usage as viewed from within the container -type ContainerMemoryInformation struct { - TotalPhysicalBytes int32 `json:"TotalPhysicalBytes,omitempty"` - - TotalUsage int32 `json:"TotalUsage,omitempty"` - - CommittedBytes int32 `json:"CommittedBytes,omitempty"` - - SharedCommittedBytes int32 `json:"SharedCommittedBytes,omitempty"` - - CommitLimitBytes int32 `json:"CommitLimitBytes,omitempty"` - - PeakCommitmentBytes int32 `json:"PeakCommitmentBytes,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group.go deleted file mode 100644 index 90332a51..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// CPU groups allow Hyper-V administrators to better manage and allocate the host's CPU resources across guest virtual machines -type CpuGroup struct { - Id string `json:"Id,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_affinity.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_affinity.go deleted file mode 100644 index 8794961b..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_affinity.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type CpuGroupAffinity struct { - LogicalProcessorCount int32 `json:"LogicalProcessorCount,omitempty"` - LogicalProcessors []int32 `json:"LogicalProcessors,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_config.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_config.go deleted file mode 100644 index f1a28cd3..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_config.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type CpuGroupConfig struct { - GroupId string `json:"GroupId,omitempty"` - Affinity *CpuGroupAffinity `json:"Affinity,omitempty"` - GroupProperties []CpuGroupProperty `json:"GroupProperties,omitempty"` - // Hypervisor CPU group IDs exposed to clients - HypervisorGroupId int32 `json:"HypervisorGroupId,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_configurations.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_configurations.go deleted file mode 100644 index 3ace0ccc..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_configurations.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Structure used to return cpu groups for a Service property query -type CpuGroupConfigurations struct { - CpuGroups []CpuGroupConfig `json:"CpuGroups,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_operations.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_operations.go deleted file mode 100644 index 7d897807..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_operations.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type CPUGroupOperation string - -const ( - CreateGroup CPUGroupOperation = "CreateGroup" - DeleteGroup CPUGroupOperation = "DeleteGroup" - SetProperty CPUGroupOperation = "SetProperty" -) diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_property.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_property.go deleted file mode 100644 index bbad6a2c..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/cpu_group_property.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type CpuGroupProperty struct { - PropertyCode uint32 `json:"PropertyCode,omitempty"` - PropertyValue uint32 `json:"PropertyValue,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/create_group_operation.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/create_group_operation.go deleted file mode 100644 index 91a8278f..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/create_group_operation.go +++ /dev/null @@ -1,17 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Create group operation settings -type CreateGroupOperation struct { - GroupId string `json:"GroupId,omitempty"` - LogicalProcessorCount uint32 `json:"LogicalProcessorCount,omitempty"` - LogicalProcessors []uint32 `json:"LogicalProcessors,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/delete_group_operation.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/delete_group_operation.go deleted file mode 100644 index 134bd988..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/delete_group_operation.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Delete group operation settings -type DeleteGroupOperation struct { - GroupId string `json:"GroupId,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/device.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/device.go deleted file mode 100644 index 0b9c0fbf..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/device.go +++ /dev/null @@ -1,27 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type DeviceType string - -const ( - ClassGUID DeviceType = "ClassGuid" - DeviceInstance = "DeviceInstance" - GPUMirror = "GpuMirror" -) - -type Device struct { - // The type of device to assign to the container. - Type DeviceType `json:"Type,omitempty"` - // The interface class guid of the device interfaces to assign to the container. Only used when Type is ClassGuid. - InterfaceClassGuid string `json:"InterfaceClassGuid,omitempty"` - // The location path of the device to assign to the container. Only used when Type is DeviceInstance. - LocationPath string `json:"LocationPath,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/devices.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/devices.go deleted file mode 100644 index e985d96d..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/devices.go +++ /dev/null @@ -1,46 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Devices struct { - ComPorts map[string]ComPort `json:"ComPorts,omitempty"` - - Scsi map[string]Scsi `json:"Scsi,omitempty"` - - VirtualPMem *VirtualPMemController `json:"VirtualPMem,omitempty"` - - NetworkAdapters map[string]NetworkAdapter `json:"NetworkAdapters,omitempty"` - - VideoMonitor *VideoMonitor `json:"VideoMonitor,omitempty"` - - Keyboard *Keyboard `json:"Keyboard,omitempty"` - - Mouse *Mouse `json:"Mouse,omitempty"` - - HvSocket *HvSocket2 `json:"HvSocket,omitempty"` - - EnhancedModeVideo *EnhancedModeVideo `json:"EnhancedModeVideo,omitempty"` - - GuestCrashReporting *GuestCrashReporting `json:"GuestCrashReporting,omitempty"` - - VirtualSmb *VirtualSmb `json:"VirtualSmb,omitempty"` - - Plan9 *Plan9 `json:"Plan9,omitempty"` - - Battery *Battery `json:"Battery,omitempty"` - - FlexibleIov map[string]FlexibleIoDevice `json:"FlexibleIov,omitempty"` - - SharedMemory *SharedMemoryConfiguration `json:"SharedMemory,omitempty"` - - // TODO: This is pre-release support in schema 2.3. Need to add build number - // docs when a public build with this is out. - VirtualPci map[string]VirtualPciDevice `json:",omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/enhanced_mode_video.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/enhanced_mode_video.go deleted file mode 100644 index 85450c41..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/enhanced_mode_video.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type EnhancedModeVideo struct { - ConnectionOptions *RdpConnectionOptions `json:"ConnectionOptions,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/flexible_io_device.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/flexible_io_device.go deleted file mode 100644 index fe86cab6..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/flexible_io_device.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type FlexibleIoDevice struct { - EmulatorId string `json:"EmulatorId,omitempty"` - - HostingModel string `json:"HostingModel,omitempty"` - - Configuration []string `json:"Configuration,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_connection.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_connection.go deleted file mode 100644 index 7db29495..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_connection.go +++ /dev/null @@ -1,19 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type GuestConnection struct { - - // Use Vsock rather than Hyper-V sockets to communicate with the guest service. - UseVsock bool `json:"UseVsock,omitempty"` - - // Don't disconnect the guest connection when pausing the virtual machine. - UseConnectedSuspend bool `json:"UseConnectedSuspend,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_connection_info.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_connection_info.go deleted file mode 100644 index 8a369bab..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_connection_info.go +++ /dev/null @@ -1,21 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Information about the guest. -type GuestConnectionInfo struct { - - // Each schema version x.y stands for the range of versions a.b where a==x and b<=y. This list comes from the SupportedSchemaVersions field in GcsCapabilities. - SupportedSchemaVersions []Version `json:"SupportedSchemaVersions,omitempty"` - - ProtocolVersion int32 `json:"ProtocolVersion,omitempty"` - - GuestDefinedCapabilities *interface{} `json:"GuestDefinedCapabilities,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_crash_reporting.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_crash_reporting.go deleted file mode 100644 index af828004..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_crash_reporting.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type GuestCrashReporting struct { - WindowsCrashSettings *WindowsCrashReporting `json:"WindowsCrashSettings,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_os.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_os.go deleted file mode 100644 index 8838519a..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_os.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type GuestOs struct { - HostName string `json:"HostName,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_state.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_state.go deleted file mode 100644 index ef1eec88..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/guest_state.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type GuestState struct { - - // The path to an existing file uses for persistent guest state storage. An empty string indicates the system should initialize new transient, in-memory guest state. - GuestStateFilePath string `json:"GuestStateFilePath,omitempty"` - - // The path to an existing file for persistent runtime state storage. An empty string indicates the system should initialize new transient, in-memory runtime state. - RuntimeStateFilePath string `json:"RuntimeStateFilePath,omitempty"` - - // If true, the guest state and runtime state files will be used as templates to populate transient, in-memory state instead of using the files as persistent backing store. - ForceTransientState bool `json:"ForceTransientState,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/host_processor_modify_request.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/host_processor_modify_request.go deleted file mode 100644 index 2238ce53..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/host_processor_modify_request.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Structure used to request a service processor modification -type HostProcessorModificationRequest struct { - Operation CPUGroupOperation `json:"Operation,omitempty"` - OperationDetails interface{} `json:"OperationDetails,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hosted_system.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/hosted_system.go deleted file mode 100644 index ea3084bc..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hosted_system.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type HostedSystem struct { - SchemaVersion *Version `json:"SchemaVersion,omitempty"` - - Container *Container `json:"Container,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket.go deleted file mode 100644 index 23b2ee9e..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type HvSocket struct { - Config *HvSocketSystemConfig `json:"Config,omitempty"` - - EnablePowerShellDirect bool `json:"EnablePowerShellDirect,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_2.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_2.go deleted file mode 100644 index a017691f..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_2.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// HvSocket configuration for a VM -type HvSocket2 struct { - HvSocketConfig *HvSocketSystemConfig `json:"HvSocketConfig,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_address.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_address.go deleted file mode 100644 index 84c11b93..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_address.go +++ /dev/null @@ -1,17 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// This class defines address settings applied to a VM -// by the GCS every time a VM starts or restores. -type HvSocketAddress struct { - LocalAddress string `json:"LocalAddress,omitempty"` - ParentAddress string `json:"ParentAddress,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_service_config.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_service_config.go deleted file mode 100644 index ecd9f7fb..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_service_config.go +++ /dev/null @@ -1,28 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type HvSocketServiceConfig struct { - - // SDDL string that HvSocket will check before allowing a host process to bind to this specific service. If not specified, defaults to the system DefaultBindSecurityDescriptor, defined in HvSocketSystemWpConfig in V1. - BindSecurityDescriptor string `json:"BindSecurityDescriptor,omitempty"` - - // SDDL string that HvSocket will check before allowing a host process to connect to this specific service. If not specified, defaults to the system DefaultConnectSecurityDescriptor, defined in HvSocketSystemWpConfig in V1. - ConnectSecurityDescriptor string `json:"ConnectSecurityDescriptor,omitempty"` - - // If true, HvSocket will process wildcard binds for this service/system combination. Wildcard binds are secured in the registry at SOFTWARE/Microsoft/Windows NT/CurrentVersion/Virtualization/HvSocket/WildcardDescriptors - AllowWildcardBinds bool `json:"AllowWildcardBinds,omitempty"` - - // Disabled controls whether the HvSocket service is accepting connection requests. - // This set to true will make the service refuse all incoming connections as well as cancel - // any connections already established. The service itself will still be active however - // and can be re-enabled at a future time. - Disabled bool `json:"Disabled,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_system_config.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_system_config.go deleted file mode 100644 index 69f4f9d3..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/hv_socket_system_config.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// This is the HCS Schema version of the HvSocket configuration. The VMWP version is located in Config.Devices.IC in V1. -type HvSocketSystemConfig struct { - - // SDDL string that HvSocket will check before allowing a host process to bind to an unlisted service for this specific container/VM (not wildcard binds). - DefaultBindSecurityDescriptor string `json:"DefaultBindSecurityDescriptor,omitempty"` - - // SDDL string that HvSocket will check before allowing a host process to connect to an unlisted service in the VM/container. - DefaultConnectSecurityDescriptor string `json:"DefaultConnectSecurityDescriptor,omitempty"` - - ServiceTable map[string]HvSocketServiceConfig `json:"ServiceTable,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/keyboard.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/keyboard.go deleted file mode 100644 index 3d3fa3b1..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/keyboard.go +++ /dev/null @@ -1,13 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Keyboard struct { -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/layer.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/layer.go deleted file mode 100644 index 176c49d4..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/layer.go +++ /dev/null @@ -1,21 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Layer struct { - Id string `json:"Id,omitempty"` - - Path string `json:"Path,omitempty"` - - PathType string `json:"PathType,omitempty"` - - // Unspecified defaults to Enabled - Cache string `json:"Cache,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/linux_kernel_direct.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/linux_kernel_direct.go deleted file mode 100644 index 0ab6c280..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/linux_kernel_direct.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.2 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type LinuxKernelDirect struct { - KernelFilePath string `json:"KernelFilePath,omitempty"` - - InitRdPath string `json:"InitRdPath,omitempty"` - - KernelCmdLine string `json:"KernelCmdLine,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/logical_processor.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/logical_processor.go deleted file mode 100644 index 676ad300..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/logical_processor.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type LogicalProcessor struct { - LpIndex uint32 `json:"LpIndex,omitempty"` - NodeNumber uint8 `json:"NodeNumber, omitempty"` - PackageId uint32 `json:"PackageId, omitempty"` - CoreId uint32 `json:"CoreId, omitempty"` - RootVpIndex int32 `json:"RootVpIndex, omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/mapped_directory.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/mapped_directory.go deleted file mode 100644 index 9b86a404..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/mapped_directory.go +++ /dev/null @@ -1,20 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type MappedDirectory struct { - HostPath string `json:"HostPath,omitempty"` - - HostPathType string `json:"HostPathType,omitempty"` - - ContainerPath string `json:"ContainerPath,omitempty"` - - ReadOnly bool `json:"ReadOnly,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/mapped_pipe.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/mapped_pipe.go deleted file mode 100644 index 208074e9..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/mapped_pipe.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type MappedPipe struct { - ContainerPipeName string `json:"ContainerPipeName,omitempty"` - - HostPath string `json:"HostPath,omitempty"` - - HostPathType string `json:"HostPathType,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory.go deleted file mode 100644 index 30749c67..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Memory struct { - SizeInMB uint64 `json:"SizeInMB,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory_2.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory_2.go deleted file mode 100644 index 71224c75..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory_2.go +++ /dev/null @@ -1,49 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Memory2 struct { - SizeInMB uint64 `json:"SizeInMB,omitempty"` - - AllowOvercommit bool `json:"AllowOvercommit,omitempty"` - - EnableHotHint bool `json:"EnableHotHint,omitempty"` - - EnableColdHint bool `json:"EnableColdHint,omitempty"` - - EnableEpf bool `json:"EnableEpf,omitempty"` - - // EnableDeferredCommit is private in the schema. If regenerated need to add back. - EnableDeferredCommit bool `json:"EnableDeferredCommit,omitempty"` - - // EnableColdDiscardHint if enabled, then the memory cold discard hint feature is exposed - // to the VM, allowing it to trim non-zeroed pages from the working set (if supported by - // the guest operating system). - EnableColdDiscardHint bool `json:"EnableColdDiscardHint,omitempty"` - - // LowMmioGapInMB is the low MMIO region allocated below 4GB. - // - // TODO: This is pre-release support in schema 2.3. Need to add build number - // docs when a public build with this is out. - LowMMIOGapInMB uint64 `json:"LowMmioGapInMB,omitempty"` - - // HighMmioBaseInMB is the high MMIO region allocated above 4GB (base and - // size). - // - // TODO: This is pre-release support in schema 2.3. Need to add build number - // docs when a public build with this is out. - HighMMIOBaseInMB uint64 `json:"HighMmioBaseInMB,omitempty"` - - // HighMmioGapInMB is the high MMIO region. - // - // TODO: This is pre-release support in schema 2.3. Need to add build number - // docs when a public build with this is out. - HighMMIOGapInMB uint64 `json:"HighMmioGapInMB,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory_information_for_vm.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory_information_for_vm.go deleted file mode 100644 index 811779b0..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory_information_for_vm.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type MemoryInformationForVm struct { - VirtualNodeCount uint32 `json:"VirtualNodeCount,omitempty"` - - VirtualMachineMemory *VmMemory `json:"VirtualMachineMemory,omitempty"` - - VirtualNodes []VirtualNodeInfo `json:"VirtualNodes,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory_stats.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory_stats.go deleted file mode 100644 index 906ba597..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/memory_stats.go +++ /dev/null @@ -1,19 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Memory runtime statistics -type MemoryStats struct { - MemoryUsageCommitBytes uint64 `json:"MemoryUsageCommitBytes,omitempty"` - - MemoryUsageCommitPeakBytes uint64 `json:"MemoryUsageCommitPeakBytes,omitempty"` - - MemoryUsagePrivateWorkingSetBytes uint64 `json:"MemoryUsagePrivateWorkingSetBytes,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/modification_request.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/modification_request.go deleted file mode 100644 index 1384ed88..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/modification_request.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ModificationRequest struct { - PropertyType PropertyType `json:"PropertyType,omitempty"` - Settings interface{} `json:"Settings,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/modify_setting_request.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/modify_setting_request.go deleted file mode 100644 index d29455a3..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/modify_setting_request.go +++ /dev/null @@ -1,20 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ModifySettingRequest struct { - ResourcePath string `json:"ResourcePath,omitempty"` - - RequestType string `json:"RequestType,omitempty"` - - Settings interface{} `json:"Settings,omitempty"` // NOTE: Swagger generated as *interface{}. Locally updated - - GuestRequest interface{} `json:"GuestRequest,omitempty"` // NOTE: Swagger generated as *interface{}. Locally updated -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/mouse.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/mouse.go deleted file mode 100644 index ccf8b938..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/mouse.go +++ /dev/null @@ -1,13 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Mouse struct { -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/network_adapter.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/network_adapter.go deleted file mode 100644 index a9c750b3..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/network_adapter.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type NetworkAdapter struct { - EndpointId string `json:"EndpointId,omitempty"` - - MacAddress string `json:"MacAddress,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/networking.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/networking.go deleted file mode 100644 index e5ea187a..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/networking.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Networking struct { - AllowUnqualifiedDnsQuery bool `json:"AllowUnqualifiedDnsQuery,omitempty"` - - DnsSearchList string `json:"DnsSearchList,omitempty"` - - NetworkSharedContainerName string `json:"NetworkSharedContainerName,omitempty"` - - // Guid in windows; string in linux - Namespace string `json:"Namespace,omitempty"` - - NetworkAdapters []string `json:"NetworkAdapters,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/pause_notification.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/pause_notification.go deleted file mode 100644 index d96c9501..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/pause_notification.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Notification data that is indicated to components running in the Virtual Machine. -type PauseNotification struct { - Reason string `json:"Reason,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/pause_options.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/pause_options.go deleted file mode 100644 index 21707a88..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/pause_options.go +++ /dev/null @@ -1,17 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Options for HcsPauseComputeSystem -type PauseOptions struct { - SuspensionLevel string `json:"SuspensionLevel,omitempty"` - - HostedNotification *PauseNotification `json:"HostedNotification,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/plan9.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/plan9.go deleted file mode 100644 index 29d8c801..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/plan9.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Plan9 struct { - Shares []Plan9Share `json:"Shares,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/plan9_share.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/plan9_share.go deleted file mode 100644 index 41f8fdea..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/plan9_share.go +++ /dev/null @@ -1,34 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Plan9Share struct { - Name string `json:"Name,omitempty"` - - // The name by which the guest operation system can access this share, via the aname parameter in the Plan9 protocol. - AccessName string `json:"AccessName,omitempty"` - - Path string `json:"Path,omitempty"` - - Port int32 `json:"Port,omitempty"` - - // Flags are marked private. Until they are exported correctly - // - // ReadOnly 0x00000001 - // LinuxMetadata 0x00000004 - // CaseSensitive 0x00000008 - Flags int32 `json:"Flags,omitempty"` - - ReadOnly bool `json:"ReadOnly,omitempty"` - - UseShareRootIdentity bool `json:"UseShareRootIdentity,omitempty"` - - AllowedFiles []string `json:"AllowedFiles,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_details.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_details.go deleted file mode 100644 index e9a662dd..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_details.go +++ /dev/null @@ -1,33 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -import ( - "time" -) - -// Information about a process running in a container -type ProcessDetails struct { - ProcessId int32 `json:"ProcessId,omitempty"` - - ImageName string `json:"ImageName,omitempty"` - - CreateTimestamp time.Time `json:"CreateTimestamp,omitempty"` - - UserTime100ns int32 `json:"UserTime100ns,omitempty"` - - KernelTime100ns int32 `json:"KernelTime100ns,omitempty"` - - MemoryCommitBytes int32 `json:"MemoryCommitBytes,omitempty"` - - MemoryWorkingSetPrivateBytes int32 `json:"MemoryWorkingSetPrivateBytes,omitempty"` - - MemoryWorkingSetSharedBytes int32 `json:"MemoryWorkingSetSharedBytes,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_modify_request.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_modify_request.go deleted file mode 100644 index e4ed095c..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_modify_request.go +++ /dev/null @@ -1,19 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Passed to HcsRpc_ModifyProcess -type ProcessModifyRequest struct { - Operation string `json:"Operation,omitempty"` - - ConsoleSize *ConsoleSize `json:"ConsoleSize,omitempty"` - - CloseHandle *CloseHandle `json:"CloseHandle,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_parameters.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_parameters.go deleted file mode 100644 index 82b0d053..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_parameters.go +++ /dev/null @@ -1,46 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ProcessParameters struct { - ApplicationName string `json:"ApplicationName,omitempty"` - - CommandLine string `json:"CommandLine,omitempty"` - - // optional alternative to CommandLine, currently only supported by Linux GCS - CommandArgs []string `json:"CommandArgs,omitempty"` - - User string `json:"User,omitempty"` - - WorkingDirectory string `json:"WorkingDirectory,omitempty"` - - Environment map[string]string `json:"Environment,omitempty"` - - // if set, will run as low-privilege process - RestrictedToken bool `json:"RestrictedToken,omitempty"` - - // if set, ignore StdErrPipe - EmulateConsole bool `json:"EmulateConsole,omitempty"` - - CreateStdInPipe bool `json:"CreateStdInPipe,omitempty"` - - CreateStdOutPipe bool `json:"CreateStdOutPipe,omitempty"` - - CreateStdErrPipe bool `json:"CreateStdErrPipe,omitempty"` - - // height then width - ConsoleSize []int32 `json:"ConsoleSize,omitempty"` - - // if set, find an existing session for the user and create the process in it - UseExistingLogin bool `json:"UseExistingLogin,omitempty"` - - // if set, use the legacy console instead of conhost - UseLegacyConsole bool `json:"UseLegacyConsole,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_status.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_status.go deleted file mode 100644 index ad9a4fa9..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/process_status.go +++ /dev/null @@ -1,21 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Status of a process running in a container -type ProcessStatus struct { - ProcessId int32 `json:"ProcessId,omitempty"` - - Exited bool `json:"Exited,omitempty"` - - ExitCode int32 `json:"ExitCode,omitempty"` - - LastWaitResult int32 `json:"LastWaitResult,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor.go deleted file mode 100644 index bb24e88d..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Processor struct { - Count int32 `json:"Count,omitempty"` - - Maximum int32 `json:"Maximum,omitempty"` - - Weight int32 `json:"Weight,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor_2.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor_2.go deleted file mode 100644 index 21fe4606..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor_2.go +++ /dev/null @@ -1,20 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Processor2 struct { - Count int32 `json:"Count,omitempty"` - - Limit int32 `json:"Limit,omitempty"` - - Weight int32 `json:"Weight,omitempty"` - - ExposeVirtualizationExtensions bool `json:"ExposeVirtualizationExtensions,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor_stats.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor_stats.go deleted file mode 100644 index 6157e252..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor_stats.go +++ /dev/null @@ -1,19 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// CPU runtime statistics -type ProcessorStats struct { - TotalRuntime100ns uint64 `json:"TotalRuntime100ns,omitempty"` - - RuntimeUser100ns uint64 `json:"RuntimeUser100ns,omitempty"` - - RuntimeKernel100ns uint64 `json:"RuntimeKernel100ns,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor_topology.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor_topology.go deleted file mode 100644 index 885156e7..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/processor_topology.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type ProcessorTopology struct { - LogicalProcessorCount uint32 `json:"LogicalProcessorCount,omitempty"` - LogicalProcessors []LogicalProcessor `json:"LogicalProcessors,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/properties.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/properties.go deleted file mode 100644 index 17558cba..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/properties.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -import ( - v1 "github.com/containerd/cgroups/stats/v1" -) - -type Properties struct { - Id string `json:"Id,omitempty"` - - SystemType string `json:"SystemType,omitempty"` - - RuntimeOsType string `json:"RuntimeOsType,omitempty"` - - Name string `json:"Name,omitempty"` - - Owner string `json:"Owner,omitempty"` - - RuntimeId string `json:"RuntimeId,omitempty"` - - RuntimeTemplateId string `json:"RuntimeTemplateId,omitempty"` - - State string `json:"State,omitempty"` - - Stopped bool `json:"Stopped,omitempty"` - - ExitType string `json:"ExitType,omitempty"` - - Memory *MemoryInformationForVm `json:"Memory,omitempty"` - - Statistics *Statistics `json:"Statistics,omitempty"` - - ProcessList []ProcessDetails `json:"ProcessList,omitempty"` - - TerminateOnLastHandleClosed bool `json:"TerminateOnLastHandleClosed,omitempty"` - - HostingSystemId string `json:"HostingSystemId,omitempty"` - - SharedMemoryRegionInfo []SharedMemoryRegionInfo `json:"SharedMemoryRegionInfo,omitempty"` - - GuestConnectionInfo *GuestConnectionInfo `json:"GuestConnectionInfo,omitempty"` - - // Metrics is not part of the API for HCS but this is used for LCOW v2 to - // return the full cgroup metrics from the guest. - Metrics *v1.Metrics `json:"LCOWMetrics,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/property_query.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/property_query.go deleted file mode 100644 index d6d80df1..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/property_query.go +++ /dev/null @@ -1,15 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// By default the basic properties will be returned. This query provides a way to request specific properties. -type PropertyQuery struct { - PropertyTypes []PropertyType `json:"PropertyTypes,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/property_type.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/property_type.go deleted file mode 100644 index 98f2c96e..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/property_type.go +++ /dev/null @@ -1,26 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type PropertyType string - -const ( - PTMemory PropertyType = "Memory" - PTGuestMemory PropertyType = "GuestMemory" - PTStatistics PropertyType = "Statistics" - PTProcessList PropertyType = "ProcessList" - PTTerminateOnLastHandleClosed PropertyType = "TerminateOnLastHandleClosed" - PTSharedMemoryRegion PropertyType = "SharedMemoryRegion" - PTContainerCredentialGuard PropertyType = "ContainerCredentialGuard" // This field is not generated by swagger. This was added manually. - PTGuestConnection PropertyType = "GuestConnection" - PTICHeartbeatStatus PropertyType = "ICHeartbeatStatus" - PTProcessorTopology PropertyType = "ProcessorTopology" - PTCPUGroup PropertyType = "CpuGroup" -) diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/rdp_connection_options.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/rdp_connection_options.go deleted file mode 100644 index 8d5f5c17..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/rdp_connection_options.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type RdpConnectionOptions struct { - AccessSids []string `json:"AccessSids,omitempty"` - - NamedPipe string `json:"NamedPipe,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/registry_changes.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/registry_changes.go deleted file mode 100644 index 006906f6..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/registry_changes.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type RegistryChanges struct { - AddValues []RegistryValue `json:"AddValues,omitempty"` - - DeleteKeys []RegistryKey `json:"DeleteKeys,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/registry_key.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/registry_key.go deleted file mode 100644 index 26fde99c..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/registry_key.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type RegistryKey struct { - Hive string `json:"Hive,omitempty"` - - Name string `json:"Name,omitempty"` - - Volatile bool `json:"Volatile,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/registry_value.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/registry_value.go deleted file mode 100644 index 3f203176..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/registry_value.go +++ /dev/null @@ -1,30 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type RegistryValue struct { - Key *RegistryKey `json:"Key,omitempty"` - - Name string `json:"Name,omitempty"` - - Type_ string `json:"Type,omitempty"` - - // One and only one value type must be set. - StringValue string `json:"StringValue,omitempty"` - - BinaryValue string `json:"BinaryValue,omitempty"` - - DWordValue int32 `json:"DWordValue,omitempty"` - - QWordValue int32 `json:"QWordValue,omitempty"` - - // Only used if RegistryValueType is CustomType The data is in BinaryValue - CustomType int32 `json:"CustomType,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/restore_state.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/restore_state.go deleted file mode 100644 index 778ff587..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/restore_state.go +++ /dev/null @@ -1,19 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type RestoreState struct { - - // The path to the save state file to restore the system from. - SaveStateFilePath string `json:"SaveStateFilePath,omitempty"` - - // The ID of the template system to clone this new system off of. An empty string indicates the system should not be cloned from a template. - TemplateSystemId string `json:"TemplateSystemId,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/save_options.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/save_options.go deleted file mode 100644 index e55fa1d9..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/save_options.go +++ /dev/null @@ -1,19 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type SaveOptions struct { - - // The type of save operation to be performed. - SaveType string `json:"SaveType,omitempty"` - - // The path to the file that will container the saved state. - SaveStateFilePath string `json:"SaveStateFilePath,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/scsi.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/scsi.go deleted file mode 100644 index bf253a47..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/scsi.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Scsi struct { - - // Map of attachments, where the key is the integer LUN number on the controller. - Attachments map[string]Attachment `json:"Attachments,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/service_properties.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/service_properties.go deleted file mode 100644 index b8142ca6..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/service_properties.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -import "encoding/json" - -type ServiceProperties struct { - // Changed Properties field to []json.RawMessage from []interface{} to avoid having to - // remarshal sp.Properties[n] and unmarshal into the type(s) we want. - Properties []json.RawMessage `json:"Properties,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/shared_memory_configuration.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/shared_memory_configuration.go deleted file mode 100644 index df9baa92..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/shared_memory_configuration.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type SharedMemoryConfiguration struct { - Regions []SharedMemoryRegion `json:"Regions,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/shared_memory_region.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/shared_memory_region.go deleted file mode 100644 index 825b7186..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/shared_memory_region.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type SharedMemoryRegion struct { - SectionName string `json:"SectionName,omitempty"` - - StartOffset int32 `json:"StartOffset,omitempty"` - - Length int32 `json:"Length,omitempty"` - - AllowGuestWrite bool `json:"AllowGuestWrite,omitempty"` - - HiddenFromGuest bool `json:"HiddenFromGuest,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/shared_memory_region_info.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/shared_memory_region_info.go deleted file mode 100644 index f67b08eb..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/shared_memory_region_info.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type SharedMemoryRegionInfo struct { - SectionName string `json:"SectionName,omitempty"` - - GuestPhysicalAddress int32 `json:"GuestPhysicalAddress,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/silo_properties.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/silo_properties.go deleted file mode 100644 index 5eaf6a7f..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/silo_properties.go +++ /dev/null @@ -1,17 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Silo job information -type SiloProperties struct { - Enabled bool `json:"Enabled,omitempty"` - - JobName string `json:"JobName,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/statistics.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/statistics.go deleted file mode 100644 index ba7a6b39..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/statistics.go +++ /dev/null @@ -1,29 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -import ( - "time" -) - -// Runtime statistics for a container -type Statistics struct { - Timestamp time.Time `json:"Timestamp,omitempty"` - - ContainerStartTime time.Time `json:"ContainerStartTime,omitempty"` - - Uptime100ns uint64 `json:"Uptime100ns,omitempty"` - - Processor *ProcessorStats `json:"Processor,omitempty"` - - Memory *MemoryStats `json:"Memory,omitempty"` - - Storage *StorageStats `json:"Storage,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/storage.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/storage.go deleted file mode 100644 index 2627af91..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/storage.go +++ /dev/null @@ -1,21 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Storage struct { - - // List of layers that describe the parent hierarchy for a container's storage. These layers combined together, presented as a disposable and/or committable working storage, are used by the container to record all changes done to the parent layers. - Layers []Layer `json:"Layers,omitempty"` - - // Path that points to the scratch space of a container, where parent layers are combined together to present a new disposable and/or committable layer with the changes done during its runtime. - Path string `json:"Path,omitempty"` - - QoS *StorageQoS `json:"QoS,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/storage_qo_s.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/storage_qo_s.go deleted file mode 100644 index 9c5e6eb5..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/storage_qo_s.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type StorageQoS struct { - IopsMaximum int32 `json:"IopsMaximum,omitempty"` - - BandwidthMaximum int32 `json:"BandwidthMaximum,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/storage_stats.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/storage_stats.go deleted file mode 100644 index 4f042ffd..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/storage_stats.go +++ /dev/null @@ -1,21 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// Storage runtime statistics -type StorageStats struct { - ReadCountNormalized uint64 `json:"ReadCountNormalized,omitempty"` - - ReadSizeBytes uint64 `json:"ReadSizeBytes,omitempty"` - - WriteCountNormalized uint64 `json:"WriteCountNormalized,omitempty"` - - WriteSizeBytes uint64 `json:"WriteSizeBytes,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/topology.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/topology.go deleted file mode 100644 index 83486994..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/topology.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Topology struct { - Memory *Memory2 `json:"Memory,omitempty"` - - Processor *Processor2 `json:"Processor,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/uefi.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/uefi.go deleted file mode 100644 index 0e48ece5..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/uefi.go +++ /dev/null @@ -1,20 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Uefi struct { - EnableDebugger bool `json:"EnableDebugger,omitempty"` - - SecureBootTemplateId string `json:"SecureBootTemplateId,omitempty"` - - BootThis *UefiBootEntry `json:"BootThis,omitempty"` - - Console string `json:"Console,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/uefi_boot_entry.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/uefi_boot_entry.go deleted file mode 100644 index 3ab409d8..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/uefi_boot_entry.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type UefiBootEntry struct { - DeviceType string `json:"DeviceType,omitempty"` - - DevicePath string `json:"DevicePath,omitempty"` - - DiskNumber int32 `json:"DiskNumber,omitempty"` - - OptionalData string `json:"OptionalData,omitempty"` - - VmbFsRootPath string `json:"VmbFsRootPath,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/version.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/version.go deleted file mode 100644 index 2abfccca..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/version.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type Version struct { - Major int32 `json:"Major,omitempty"` - - Minor int32 `json:"Minor,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/video_monitor.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/video_monitor.go deleted file mode 100644 index ec5d0fb9..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/video_monitor.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type VideoMonitor struct { - HorizontalResolution int32 `json:"HorizontalResolution,omitempty"` - - VerticalResolution int32 `json:"VerticalResolution,omitempty"` - - ConnectionOptions *RdpConnectionOptions `json:"ConnectionOptions,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_machine.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_machine.go deleted file mode 100644 index 2d22b1bc..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_machine.go +++ /dev/null @@ -1,32 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type VirtualMachine struct { - - // StopOnReset is private in the schema. If regenerated need to put back. - StopOnReset bool `json:"StopOnReset,omitempty"` - - Chipset *Chipset `json:"Chipset,omitempty"` - - ComputeTopology *Topology `json:"ComputeTopology,omitempty"` - - Devices *Devices `json:"Devices,omitempty"` - - GuestState *GuestState `json:"GuestState,omitempty"` - - RestoreState *RestoreState `json:"RestoreState,omitempty"` - - RegistryChanges *RegistryChanges `json:"RegistryChanges,omitempty"` - - StorageQoS *StorageQoS `json:"StorageQoS,omitempty"` - - GuestConnection *GuestConnection `json:"GuestConnection,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_node_info.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_node_info.go deleted file mode 100644 index 91a3c83d..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_node_info.go +++ /dev/null @@ -1,20 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type VirtualNodeInfo struct { - VirtualNodeIndex int32 `json:"VirtualNodeIndex,omitempty"` - - PhysicalNodeNumber int32 `json:"PhysicalNodeNumber,omitempty"` - - VirtualProcessorCount int32 `json:"VirtualProcessorCount,omitempty"` - - MemoryUsageInPages int32 `json:"MemoryUsageInPages,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_p_mem_controller.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_p_mem_controller.go deleted file mode 100644 index f5b7f3e3..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_p_mem_controller.go +++ /dev/null @@ -1,20 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type VirtualPMemController struct { - Devices map[string]VirtualPMemDevice `json:"Devices,omitempty"` - - MaximumCount uint32 `json:"MaximumCount,omitempty"` - - MaximumSizeBytes uint64 `json:"MaximumSizeBytes,omitempty"` - - Backing string `json:"Backing,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_p_mem_device.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_p_mem_device.go deleted file mode 100644 index 70cf2d90..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_p_mem_device.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type VirtualPMemDevice struct { - HostPath string `json:"HostPath,omitempty"` - - ReadOnly bool `json:"ReadOnly,omitempty"` - - ImageFormat string `json:"ImageFormat,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_pci_device.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_pci_device.go deleted file mode 100644 index f5e05903..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_pci_device.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.3 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// TODO: This is pre-release support in schema 2.3. Need to add build number -// docs when a public build with this is out. -type VirtualPciDevice struct { - Functions []VirtualPciFunction `json:",omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_pci_function.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_pci_function.go deleted file mode 100644 index cedb7d18..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_pci_function.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.3 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// TODO: This is pre-release support in schema 2.3. Need to add build number -// docs when a public build with this is out. -type VirtualPciFunction struct { - DeviceInstancePath string `json:",omitempty"` - - VirtualFunction uint16 `json:",omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_smb.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_smb.go deleted file mode 100644 index 362df363..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_smb.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type VirtualSmb struct { - Shares []VirtualSmbShare `json:"Shares,omitempty"` - - DirectFileMappingInMB int64 `json:"DirectFileMappingInMB,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_smb_share.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_smb_share.go deleted file mode 100644 index 915e9b63..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_smb_share.go +++ /dev/null @@ -1,20 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type VirtualSmbShare struct { - Name string `json:"Name,omitempty"` - - Path string `json:"Path,omitempty"` - - AllowedFiles []string `json:"AllowedFiles,omitempty"` - - Options *VirtualSmbShareOptions `json:"Options,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_smb_share_options.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_smb_share_options.go deleted file mode 100644 index 75196bd8..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/virtual_smb_share_options.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type VirtualSmbShareOptions struct { - ReadOnly bool `json:"ReadOnly,omitempty"` - - // convert exclusive access to shared read access - ShareRead bool `json:"ShareRead,omitempty"` - - // all opens will use cached I/O - CacheIo bool `json:"CacheIo,omitempty"` - - // disable oplock support - NoOplocks bool `json:"NoOplocks,omitempty"` - - // Acquire the backup privilege when attempting to open - TakeBackupPrivilege bool `json:"TakeBackupPrivilege,omitempty"` - - // Use the identity of the share root when opening - UseShareRootIdentity bool `json:"UseShareRootIdentity,omitempty"` - - // disable Direct Mapping - NoDirectmap bool `json:"NoDirectmap,omitempty"` - - // disable Byterange locks - NoLocks bool `json:"NoLocks,omitempty"` - - // disable Directory CHange Notifications - NoDirnotify bool `json:"NoDirnotify,omitempty"` - - // share is use for VM shared memory - VmSharedMemory bool `json:"VmSharedMemory,omitempty"` - - // allow access only to the files specified in AllowedFiles - RestrictFileAccess bool `json:"RestrictFileAccess,omitempty"` - - // disable all oplocks except Level II - ForceLevelIIOplocks bool `json:"ForceLevelIIOplocks,omitempty"` - - // Allow the host to reparse this base layer - ReparseBaseLayer bool `json:"ReparseBaseLayer,omitempty"` - - // Enable pseudo-oplocks - PseudoOplocks bool `json:"PseudoOplocks,omitempty"` - - // All opens will use non-cached IO - NonCacheIo bool `json:"NonCacheIo,omitempty"` - - // Enable pseudo directory change notifications - PseudoDirnotify bool `json:"PseudoDirnotify,omitempty"` - - // Block directory enumeration, renames, and deletes. - SingleFileMapping bool `json:"SingleFileMapping,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/vm_memory.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/vm_memory.go deleted file mode 100644 index 8e1836dd..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/vm_memory.go +++ /dev/null @@ -1,26 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type VmMemory struct { - AvailableMemory int32 `json:"AvailableMemory,omitempty"` - - AvailableMemoryBuffer int32 `json:"AvailableMemoryBuffer,omitempty"` - - ReservedMemory uint64 `json:"ReservedMemory,omitempty"` - - AssignedMemory uint64 `json:"AssignedMemory,omitempty"` - - SlpActive bool `json:"SlpActive,omitempty"` - - BalancingEnabled bool `json:"BalancingEnabled,omitempty"` - - DmOperationInProgress bool `json:"DmOperationInProgress,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/vm_processor_limits.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/vm_processor_limits.go deleted file mode 100644 index de1b9cf1..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/vm_processor_limits.go +++ /dev/null @@ -1,22 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.4 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -// ProcessorLimits is used when modifying processor scheduling limits of a virtual machine. -type ProcessorLimits struct { - // Maximum amount of host CPU resources that the virtual machine can use. - Limit uint64 `json:"Limit,omitempty"` - // Value describing the relative priority of this virtual machine compared to other virtual machines. - Weight uint64 `json:"Weight,omitempty"` - // Minimum amount of host CPU resources that the virtual machine is guaranteed. - Reservation uint64 `json:"Reservation,omitempty"` - // Provides the target maximum CPU frequency, in MHz, for a virtual machine. - MaximumFrequencyMHz uint32 `json:"MaximumFrequencyMHz,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/schema2/windows_crash_reporting.go b/vendor/github.com/Microsoft/hcsshim/internal/schema2/windows_crash_reporting.go deleted file mode 100644 index 8ed7e566..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/schema2/windows_crash_reporting.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * HCS API - * - * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) - * - * API version: 2.1 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ - -package hcsschema - -type WindowsCrashReporting struct { - DumpFileName string `json:"DumpFileName,omitempty"` - - MaxDumpSize int64 `json:"MaxDumpSize,omitempty"` -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/timeout/timeout.go b/vendor/github.com/Microsoft/hcsshim/internal/timeout/timeout.go deleted file mode 100644 index eaf39fa5..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/timeout/timeout.go +++ /dev/null @@ -1,74 +0,0 @@ -package timeout - -import ( - "os" - "strconv" - "time" -) - -var ( - // defaultTimeout is the timeout for most operations that is not overridden. - defaultTimeout = 4 * time.Minute - - // defaultTimeoutTestdRetry is the retry loop timeout for testd to respond - // for a disk to come online in LCOW. - defaultTimeoutTestdRetry = 5 * time.Second -) - -// External variables for HCSShim consumers to use. -var ( - // SystemCreate is the timeout for creating a compute system - SystemCreate time.Duration = defaultTimeout - - // SystemStart is the timeout for starting a compute system - SystemStart time.Duration = defaultTimeout - - // SystemPause is the timeout for pausing a compute system - SystemPause time.Duration = defaultTimeout - - // SystemResume is the timeout for resuming a compute system - SystemResume time.Duration = defaultTimeout - - // SystemSave is the timeout for saving a compute system - SystemSave time.Duration = defaultTimeout - - // SyscallWatcher is the timeout before warning of a potential stuck platform syscall. - SyscallWatcher time.Duration = defaultTimeout - - // Tar2VHD is the timeout for the tar2vhd operation to complete - Tar2VHD time.Duration = defaultTimeout - - // ExternalCommandToStart is the timeout for external commands to start - ExternalCommandToStart = defaultTimeout - - // ExternalCommandToComplete is the timeout for external commands to complete. - // Generally this means copying data from their stdio pipes. - ExternalCommandToComplete = defaultTimeout - - // TestDRetryLoop is the timeout for testd retry loop when onlining a SCSI disk in LCOW - TestDRetryLoop = defaultTimeoutTestdRetry -) - -func init() { - SystemCreate = durationFromEnvironment("HCSSHIM_TIMEOUT_SYSTEMCREATE", SystemCreate) - SystemStart = durationFromEnvironment("HCSSHIM_TIMEOUT_SYSTEMSTART", SystemStart) - SystemPause = durationFromEnvironment("HCSSHIM_TIMEOUT_SYSTEMPAUSE", SystemPause) - SystemResume = durationFromEnvironment("HCSSHIM_TIMEOUT_SYSTEMRESUME", SystemResume) - SystemSave = durationFromEnvironment("HCSSHIM_TIMEOUT_SYSTEMSAVE", SystemSave) - SyscallWatcher = durationFromEnvironment("HCSSHIM_TIMEOUT_SYSCALLWATCHER", SyscallWatcher) - Tar2VHD = durationFromEnvironment("HCSSHIM_TIMEOUT_TAR2VHD", Tar2VHD) - ExternalCommandToStart = durationFromEnvironment("HCSSHIM_TIMEOUT_EXTERNALCOMMANDSTART", ExternalCommandToStart) - ExternalCommandToComplete = durationFromEnvironment("HCSSHIM_TIMEOUT_EXTERNALCOMMANDCOMPLETE", ExternalCommandToComplete) - TestDRetryLoop = durationFromEnvironment("HCSSHIM_TIMEOUT_TESTDRETRYLOOP", TestDRetryLoop) -} - -func durationFromEnvironment(env string, defaultValue time.Duration) time.Duration { - envTimeout := os.Getenv(env) - if len(envTimeout) > 0 { - e, err := strconv.Atoi(envTimeout) - if err == nil && e > 0 { - return time.Second * time.Duration(e) - } - } - return defaultValue -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/vmcompute/vmcompute.go b/vendor/github.com/Microsoft/hcsshim/internal/vmcompute/vmcompute.go deleted file mode 100644 index 32491f2c..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/vmcompute/vmcompute.go +++ /dev/null @@ -1,610 +0,0 @@ -package vmcompute - -import ( - gcontext "context" - "syscall" - "time" - - "github.com/Microsoft/hcsshim/internal/interop" - "github.com/Microsoft/hcsshim/internal/log" - "github.com/Microsoft/hcsshim/internal/logfields" - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/Microsoft/hcsshim/internal/timeout" - "go.opencensus.io/trace" -) - -//go:generate go run ../../mksyscall_windows.go -output zsyscall_windows.go vmcompute.go - -//sys hcsEnumerateComputeSystems(query string, computeSystems **uint16, result **uint16) (hr error) = vmcompute.HcsEnumerateComputeSystems? -//sys hcsCreateComputeSystem(id string, configuration string, identity syscall.Handle, computeSystem *HcsSystem, result **uint16) (hr error) = vmcompute.HcsCreateComputeSystem? -//sys hcsOpenComputeSystem(id string, computeSystem *HcsSystem, result **uint16) (hr error) = vmcompute.HcsOpenComputeSystem? -//sys hcsCloseComputeSystem(computeSystem HcsSystem) (hr error) = vmcompute.HcsCloseComputeSystem? -//sys hcsStartComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsStartComputeSystem? -//sys hcsShutdownComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsShutdownComputeSystem? -//sys hcsTerminateComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsTerminateComputeSystem? -//sys hcsPauseComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsPauseComputeSystem? -//sys hcsResumeComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsResumeComputeSystem? -//sys hcsGetComputeSystemProperties(computeSystem HcsSystem, propertyQuery string, properties **uint16, result **uint16) (hr error) = vmcompute.HcsGetComputeSystemProperties? -//sys hcsModifyComputeSystem(computeSystem HcsSystem, configuration string, result **uint16) (hr error) = vmcompute.HcsModifyComputeSystem? -//sys hcsModifyServiceSettings(settings string, result **uint16) (hr error) = vmcompute.HcsModifyServiceSettings? -//sys hcsRegisterComputeSystemCallback(computeSystem HcsSystem, callback uintptr, context uintptr, callbackHandle *HcsCallback) (hr error) = vmcompute.HcsRegisterComputeSystemCallback? -//sys hcsUnregisterComputeSystemCallback(callbackHandle HcsCallback) (hr error) = vmcompute.HcsUnregisterComputeSystemCallback? -//sys hcsSaveComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsSaveComputeSystem? - -//sys hcsCreateProcess(computeSystem HcsSystem, processParameters string, processInformation *HcsProcessInformation, process *HcsProcess, result **uint16) (hr error) = vmcompute.HcsCreateProcess? -//sys hcsOpenProcess(computeSystem HcsSystem, pid uint32, process *HcsProcess, result **uint16) (hr error) = vmcompute.HcsOpenProcess? -//sys hcsCloseProcess(process HcsProcess) (hr error) = vmcompute.HcsCloseProcess? -//sys hcsTerminateProcess(process HcsProcess, result **uint16) (hr error) = vmcompute.HcsTerminateProcess? -//sys hcsSignalProcess(process HcsProcess, options string, result **uint16) (hr error) = vmcompute.HcsSignalProcess? -//sys hcsGetProcessInfo(process HcsProcess, processInformation *HcsProcessInformation, result **uint16) (hr error) = vmcompute.HcsGetProcessInfo? -//sys hcsGetProcessProperties(process HcsProcess, processProperties **uint16, result **uint16) (hr error) = vmcompute.HcsGetProcessProperties? -//sys hcsModifyProcess(process HcsProcess, settings string, result **uint16) (hr error) = vmcompute.HcsModifyProcess? -//sys hcsGetServiceProperties(propertyQuery string, properties **uint16, result **uint16) (hr error) = vmcompute.HcsGetServiceProperties? -//sys hcsRegisterProcessCallback(process HcsProcess, callback uintptr, context uintptr, callbackHandle *HcsCallback) (hr error) = vmcompute.HcsRegisterProcessCallback? -//sys hcsUnregisterProcessCallback(callbackHandle HcsCallback) (hr error) = vmcompute.HcsUnregisterProcessCallback? - -// errVmcomputeOperationPending is an error encountered when the operation is being completed asynchronously -const errVmcomputeOperationPending = syscall.Errno(0xC0370103) - -// HcsSystem is the handle associated with a created compute system. -type HcsSystem syscall.Handle - -// HcsProcess is the handle associated with a created process in a compute -// system. -type HcsProcess syscall.Handle - -// HcsCallback is the handle associated with the function to call when events -// occur. -type HcsCallback syscall.Handle - -// HcsProcessInformation is the structure used when creating or getting process -// info. -type HcsProcessInformation struct { - // ProcessId is the pid of the created process. - ProcessId uint32 - reserved uint32 - // StdInput is the handle associated with the stdin of the process. - StdInput syscall.Handle - // StdOutput is the handle associated with the stdout of the process. - StdOutput syscall.Handle - // StdError is the handle associated with the stderr of the process. - StdError syscall.Handle -} - -func execute(ctx gcontext.Context, timeout time.Duration, f func() error) error { - if timeout > 0 { - var cancel gcontext.CancelFunc - ctx, cancel = gcontext.WithTimeout(ctx, timeout) - defer cancel() - } - - done := make(chan error, 1) - go func() { - done <- f() - }() - select { - case <-ctx.Done(): - if ctx.Err() == gcontext.DeadlineExceeded { - log.G(ctx).WithField(logfields.Timeout, timeout). - Warning("Syscall did not complete within operation timeout. This may indicate a platform issue. If it appears to be making no forward progress, obtain the stacks and see if there is a syscall stuck in the platform API for a significant length of time.") - } - return ctx.Err() - case err := <-done: - return err - } -} - -func HcsEnumerateComputeSystems(ctx gcontext.Context, query string) (computeSystems, result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsEnumerateComputeSystems") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - span.AddAttributes(trace.StringAttribute("query", query)) - - return computeSystems, result, execute(ctx, timeout.SyscallWatcher, func() error { - var ( - computeSystemsp *uint16 - resultp *uint16 - ) - err := hcsEnumerateComputeSystems(query, &computeSystemsp, &resultp) - if computeSystemsp != nil { - computeSystems = interop.ConvertAndFreeCoTaskMemString(computeSystemsp) - } - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsCreateComputeSystem(ctx gcontext.Context, id string, configuration string, identity syscall.Handle) (computeSystem HcsSystem, result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsCreateComputeSystem") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - if hr != errVmcomputeOperationPending { - oc.SetSpanStatus(span, hr) - } - }() - span.AddAttributes( - trace.StringAttribute("id", id), - trace.StringAttribute("configuration", configuration)) - - return computeSystem, result, execute(ctx, timeout.SystemCreate, func() error { - var resultp *uint16 - err := hcsCreateComputeSystem(id, configuration, identity, &computeSystem, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsOpenComputeSystem(ctx gcontext.Context, id string) (computeSystem HcsSystem, result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsOpenComputeSystem") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - - return computeSystem, result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsOpenComputeSystem(id, &computeSystem, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsCloseComputeSystem(ctx gcontext.Context, computeSystem HcsSystem) (hr error) { - ctx, span := trace.StartSpan(ctx, "HcsCloseComputeSystem") - defer span.End() - defer func() { oc.SetSpanStatus(span, hr) }() - - return execute(ctx, timeout.SyscallWatcher, func() error { - return hcsCloseComputeSystem(computeSystem) - }) -} - -func HcsStartComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsStartComputeSystem") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - if hr != errVmcomputeOperationPending { - oc.SetSpanStatus(span, hr) - } - }() - span.AddAttributes(trace.StringAttribute("options", options)) - - return result, execute(ctx, timeout.SystemStart, func() error { - var resultp *uint16 - err := hcsStartComputeSystem(computeSystem, options, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsShutdownComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsShutdownComputeSystem") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - if hr != errVmcomputeOperationPending { - oc.SetSpanStatus(span, hr) - } - }() - span.AddAttributes(trace.StringAttribute("options", options)) - - return result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsShutdownComputeSystem(computeSystem, options, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsTerminateComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsTerminateComputeSystem") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - if hr != errVmcomputeOperationPending { - oc.SetSpanStatus(span, hr) - } - }() - span.AddAttributes(trace.StringAttribute("options", options)) - - return result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsTerminateComputeSystem(computeSystem, options, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsPauseComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsPauseComputeSystem") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - if hr != errVmcomputeOperationPending { - oc.SetSpanStatus(span, hr) - } - }() - span.AddAttributes(trace.StringAttribute("options", options)) - - return result, execute(ctx, timeout.SystemPause, func() error { - var resultp *uint16 - err := hcsPauseComputeSystem(computeSystem, options, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsResumeComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsResumeComputeSystem") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - if hr != errVmcomputeOperationPending { - oc.SetSpanStatus(span, hr) - } - }() - span.AddAttributes(trace.StringAttribute("options", options)) - - return result, execute(ctx, timeout.SystemResume, func() error { - var resultp *uint16 - err := hcsResumeComputeSystem(computeSystem, options, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsGetComputeSystemProperties(ctx gcontext.Context, computeSystem HcsSystem, propertyQuery string) (properties, result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsGetComputeSystemProperties") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - span.AddAttributes(trace.StringAttribute("propertyQuery", propertyQuery)) - - return properties, result, execute(ctx, timeout.SyscallWatcher, func() error { - var ( - propertiesp *uint16 - resultp *uint16 - ) - err := hcsGetComputeSystemProperties(computeSystem, propertyQuery, &propertiesp, &resultp) - if propertiesp != nil { - properties = interop.ConvertAndFreeCoTaskMemString(propertiesp) - } - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsModifyComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, configuration string) (result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsModifyComputeSystem") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - span.AddAttributes(trace.StringAttribute("configuration", configuration)) - - return result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsModifyComputeSystem(computeSystem, configuration, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsModifyServiceSettings(ctx gcontext.Context, settings string) (result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsModifyServiceSettings") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - span.AddAttributes(trace.StringAttribute("settings", settings)) - - return result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsModifyServiceSettings(settings, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsRegisterComputeSystemCallback(ctx gcontext.Context, computeSystem HcsSystem, callback uintptr, context uintptr) (callbackHandle HcsCallback, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsRegisterComputeSystemCallback") - defer span.End() - defer func() { oc.SetSpanStatus(span, hr) }() - - return callbackHandle, execute(ctx, timeout.SyscallWatcher, func() error { - return hcsRegisterComputeSystemCallback(computeSystem, callback, context, &callbackHandle) - }) -} - -func HcsUnregisterComputeSystemCallback(ctx gcontext.Context, callbackHandle HcsCallback) (hr error) { - ctx, span := trace.StartSpan(ctx, "HcsUnregisterComputeSystemCallback") - defer span.End() - defer func() { oc.SetSpanStatus(span, hr) }() - - return execute(ctx, timeout.SyscallWatcher, func() error { - return hcsUnregisterComputeSystemCallback(callbackHandle) - }) -} - -func HcsCreateProcess(ctx gcontext.Context, computeSystem HcsSystem, processParameters string) (processInformation HcsProcessInformation, process HcsProcess, result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsCreateProcess") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - span.AddAttributes(trace.StringAttribute("processParameters", processParameters)) - - return processInformation, process, result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsCreateProcess(computeSystem, processParameters, &processInformation, &process, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsOpenProcess(ctx gcontext.Context, computeSystem HcsSystem, pid uint32) (process HcsProcess, result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsOpenProcess") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - span.AddAttributes(trace.Int64Attribute("pid", int64(pid))) - - return process, result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsOpenProcess(computeSystem, pid, &process, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsCloseProcess(ctx gcontext.Context, process HcsProcess) (hr error) { - ctx, span := trace.StartSpan(ctx, "HcsCloseProcess") - defer span.End() - defer func() { oc.SetSpanStatus(span, hr) }() - - return execute(ctx, timeout.SyscallWatcher, func() error { - return hcsCloseProcess(process) - }) -} - -func HcsTerminateProcess(ctx gcontext.Context, process HcsProcess) (result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsTerminateProcess") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - - return result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsTerminateProcess(process, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsSignalProcess(ctx gcontext.Context, process HcsProcess, options string) (result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsSignalProcess") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - span.AddAttributes(trace.StringAttribute("options", options)) - - return result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsSignalProcess(process, options, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsGetProcessInfo(ctx gcontext.Context, process HcsProcess) (processInformation HcsProcessInformation, result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsGetProcessInfo") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - - return processInformation, result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsGetProcessInfo(process, &processInformation, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsGetProcessProperties(ctx gcontext.Context, process HcsProcess) (processProperties, result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsGetProcessProperties") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - - return processProperties, result, execute(ctx, timeout.SyscallWatcher, func() error { - var ( - processPropertiesp *uint16 - resultp *uint16 - ) - err := hcsGetProcessProperties(process, &processPropertiesp, &resultp) - if processPropertiesp != nil { - processProperties = interop.ConvertAndFreeCoTaskMemString(processPropertiesp) - } - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsModifyProcess(ctx gcontext.Context, process HcsProcess, settings string) (result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsModifyProcess") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - span.AddAttributes(trace.StringAttribute("settings", settings)) - - return result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsModifyProcess(process, settings, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsGetServiceProperties(ctx gcontext.Context, propertyQuery string) (properties, result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsGetServiceProperties") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - oc.SetSpanStatus(span, hr) - }() - span.AddAttributes(trace.StringAttribute("propertyQuery", propertyQuery)) - - return properties, result, execute(ctx, timeout.SyscallWatcher, func() error { - var ( - propertiesp *uint16 - resultp *uint16 - ) - err := hcsGetServiceProperties(propertyQuery, &propertiesp, &resultp) - if propertiesp != nil { - properties = interop.ConvertAndFreeCoTaskMemString(propertiesp) - } - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} - -func HcsRegisterProcessCallback(ctx gcontext.Context, process HcsProcess, callback uintptr, context uintptr) (callbackHandle HcsCallback, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsRegisterProcessCallback") - defer span.End() - defer func() { oc.SetSpanStatus(span, hr) }() - - return callbackHandle, execute(ctx, timeout.SyscallWatcher, func() error { - return hcsRegisterProcessCallback(process, callback, context, &callbackHandle) - }) -} - -func HcsUnregisterProcessCallback(ctx gcontext.Context, callbackHandle HcsCallback) (hr error) { - ctx, span := trace.StartSpan(ctx, "HcsUnregisterProcessCallback") - defer span.End() - defer func() { oc.SetSpanStatus(span, hr) }() - - return execute(ctx, timeout.SyscallWatcher, func() error { - return hcsUnregisterProcessCallback(callbackHandle) - }) -} - -func HcsSaveComputeSystem(ctx gcontext.Context, computeSystem HcsSystem, options string) (result string, hr error) { - ctx, span := trace.StartSpan(ctx, "HcsSaveComputeSystem") - defer span.End() - defer func() { - if result != "" { - span.AddAttributes(trace.StringAttribute("result", result)) - } - if hr != errVmcomputeOperationPending { - oc.SetSpanStatus(span, hr) - } - }() - - return result, execute(ctx, timeout.SyscallWatcher, func() error { - var resultp *uint16 - err := hcsSaveComputeSystem(computeSystem, options, &resultp) - if resultp != nil { - result = interop.ConvertAndFreeCoTaskMemString(resultp) - } - return err - }) -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/vmcompute/zsyscall_windows.go b/vendor/github.com/Microsoft/hcsshim/internal/vmcompute/zsyscall_windows.go deleted file mode 100644 index cae55058..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/vmcompute/zsyscall_windows.go +++ /dev/null @@ -1,581 +0,0 @@ -// Code generated mksyscall_windows.exe DO NOT EDIT - -package vmcompute - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return nil - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modvmcompute = windows.NewLazySystemDLL("vmcompute.dll") - - procHcsEnumerateComputeSystems = modvmcompute.NewProc("HcsEnumerateComputeSystems") - procHcsCreateComputeSystem = modvmcompute.NewProc("HcsCreateComputeSystem") - procHcsOpenComputeSystem = modvmcompute.NewProc("HcsOpenComputeSystem") - procHcsCloseComputeSystem = modvmcompute.NewProc("HcsCloseComputeSystem") - procHcsStartComputeSystem = modvmcompute.NewProc("HcsStartComputeSystem") - procHcsShutdownComputeSystem = modvmcompute.NewProc("HcsShutdownComputeSystem") - procHcsTerminateComputeSystem = modvmcompute.NewProc("HcsTerminateComputeSystem") - procHcsPauseComputeSystem = modvmcompute.NewProc("HcsPauseComputeSystem") - procHcsResumeComputeSystem = modvmcompute.NewProc("HcsResumeComputeSystem") - procHcsGetComputeSystemProperties = modvmcompute.NewProc("HcsGetComputeSystemProperties") - procHcsModifyComputeSystem = modvmcompute.NewProc("HcsModifyComputeSystem") - procHcsModifyServiceSettings = modvmcompute.NewProc("HcsModifyServiceSettings") - procHcsRegisterComputeSystemCallback = modvmcompute.NewProc("HcsRegisterComputeSystemCallback") - procHcsUnregisterComputeSystemCallback = modvmcompute.NewProc("HcsUnregisterComputeSystemCallback") - procHcsSaveComputeSystem = modvmcompute.NewProc("HcsSaveComputeSystem") - procHcsCreateProcess = modvmcompute.NewProc("HcsCreateProcess") - procHcsOpenProcess = modvmcompute.NewProc("HcsOpenProcess") - procHcsCloseProcess = modvmcompute.NewProc("HcsCloseProcess") - procHcsTerminateProcess = modvmcompute.NewProc("HcsTerminateProcess") - procHcsSignalProcess = modvmcompute.NewProc("HcsSignalProcess") - procHcsGetProcessInfo = modvmcompute.NewProc("HcsGetProcessInfo") - procHcsGetProcessProperties = modvmcompute.NewProc("HcsGetProcessProperties") - procHcsModifyProcess = modvmcompute.NewProc("HcsModifyProcess") - procHcsGetServiceProperties = modvmcompute.NewProc("HcsGetServiceProperties") - procHcsRegisterProcessCallback = modvmcompute.NewProc("HcsRegisterProcessCallback") - procHcsUnregisterProcessCallback = modvmcompute.NewProc("HcsUnregisterProcessCallback") -) - -func hcsEnumerateComputeSystems(query string, computeSystems **uint16, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(query) - if hr != nil { - return - } - return _hcsEnumerateComputeSystems(_p0, computeSystems, result) -} - -func _hcsEnumerateComputeSystems(query *uint16, computeSystems **uint16, result **uint16) (hr error) { - if hr = procHcsEnumerateComputeSystems.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsEnumerateComputeSystems.Addr(), 3, uintptr(unsafe.Pointer(query)), uintptr(unsafe.Pointer(computeSystems)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsCreateComputeSystem(id string, configuration string, identity syscall.Handle, computeSystem *HcsSystem, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(configuration) - if hr != nil { - return - } - return _hcsCreateComputeSystem(_p0, _p1, identity, computeSystem, result) -} - -func _hcsCreateComputeSystem(id *uint16, configuration *uint16, identity syscall.Handle, computeSystem *HcsSystem, result **uint16) (hr error) { - if hr = procHcsCreateComputeSystem.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procHcsCreateComputeSystem.Addr(), 5, uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(configuration)), uintptr(identity), uintptr(unsafe.Pointer(computeSystem)), uintptr(unsafe.Pointer(result)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsOpenComputeSystem(id string, computeSystem *HcsSystem, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - return _hcsOpenComputeSystem(_p0, computeSystem, result) -} - -func _hcsOpenComputeSystem(id *uint16, computeSystem *HcsSystem, result **uint16) (hr error) { - if hr = procHcsOpenComputeSystem.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsOpenComputeSystem.Addr(), 3, uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(computeSystem)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsCloseComputeSystem(computeSystem HcsSystem) (hr error) { - if hr = procHcsCloseComputeSystem.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsCloseComputeSystem.Addr(), 1, uintptr(computeSystem), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsStartComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(options) - if hr != nil { - return - } - return _hcsStartComputeSystem(computeSystem, _p0, result) -} - -func _hcsStartComputeSystem(computeSystem HcsSystem, options *uint16, result **uint16) (hr error) { - if hr = procHcsStartComputeSystem.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsStartComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsShutdownComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(options) - if hr != nil { - return - } - return _hcsShutdownComputeSystem(computeSystem, _p0, result) -} - -func _hcsShutdownComputeSystem(computeSystem HcsSystem, options *uint16, result **uint16) (hr error) { - if hr = procHcsShutdownComputeSystem.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsShutdownComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsTerminateComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(options) - if hr != nil { - return - } - return _hcsTerminateComputeSystem(computeSystem, _p0, result) -} - -func _hcsTerminateComputeSystem(computeSystem HcsSystem, options *uint16, result **uint16) (hr error) { - if hr = procHcsTerminateComputeSystem.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsTerminateComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsPauseComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(options) - if hr != nil { - return - } - return _hcsPauseComputeSystem(computeSystem, _p0, result) -} - -func _hcsPauseComputeSystem(computeSystem HcsSystem, options *uint16, result **uint16) (hr error) { - if hr = procHcsPauseComputeSystem.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsPauseComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsResumeComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(options) - if hr != nil { - return - } - return _hcsResumeComputeSystem(computeSystem, _p0, result) -} - -func _hcsResumeComputeSystem(computeSystem HcsSystem, options *uint16, result **uint16) (hr error) { - if hr = procHcsResumeComputeSystem.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsResumeComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsGetComputeSystemProperties(computeSystem HcsSystem, propertyQuery string, properties **uint16, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(propertyQuery) - if hr != nil { - return - } - return _hcsGetComputeSystemProperties(computeSystem, _p0, properties, result) -} - -func _hcsGetComputeSystemProperties(computeSystem HcsSystem, propertyQuery *uint16, properties **uint16, result **uint16) (hr error) { - if hr = procHcsGetComputeSystemProperties.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procHcsGetComputeSystemProperties.Addr(), 4, uintptr(computeSystem), uintptr(unsafe.Pointer(propertyQuery)), uintptr(unsafe.Pointer(properties)), uintptr(unsafe.Pointer(result)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsModifyComputeSystem(computeSystem HcsSystem, configuration string, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(configuration) - if hr != nil { - return - } - return _hcsModifyComputeSystem(computeSystem, _p0, result) -} - -func _hcsModifyComputeSystem(computeSystem HcsSystem, configuration *uint16, result **uint16) (hr error) { - if hr = procHcsModifyComputeSystem.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsModifyComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(configuration)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsModifyServiceSettings(settings string, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(settings) - if hr != nil { - return - } - return _hcsModifyServiceSettings(_p0, result) -} - -func _hcsModifyServiceSettings(settings *uint16, result **uint16) (hr error) { - if hr = procHcsModifyServiceSettings.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsModifyServiceSettings.Addr(), 2, uintptr(unsafe.Pointer(settings)), uintptr(unsafe.Pointer(result)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsRegisterComputeSystemCallback(computeSystem HcsSystem, callback uintptr, context uintptr, callbackHandle *HcsCallback) (hr error) { - if hr = procHcsRegisterComputeSystemCallback.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procHcsRegisterComputeSystemCallback.Addr(), 4, uintptr(computeSystem), uintptr(callback), uintptr(context), uintptr(unsafe.Pointer(callbackHandle)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsUnregisterComputeSystemCallback(callbackHandle HcsCallback) (hr error) { - if hr = procHcsUnregisterComputeSystemCallback.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsUnregisterComputeSystemCallback.Addr(), 1, uintptr(callbackHandle), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsSaveComputeSystem(computeSystem HcsSystem, options string, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(options) - if hr != nil { - return - } - return _hcsSaveComputeSystem(computeSystem, _p0, result) -} - -func _hcsSaveComputeSystem(computeSystem HcsSystem, options *uint16, result **uint16) (hr error) { - if hr = procHcsSaveComputeSystem.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsSaveComputeSystem.Addr(), 3, uintptr(computeSystem), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsCreateProcess(computeSystem HcsSystem, processParameters string, processInformation *HcsProcessInformation, process *HcsProcess, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(processParameters) - if hr != nil { - return - } - return _hcsCreateProcess(computeSystem, _p0, processInformation, process, result) -} - -func _hcsCreateProcess(computeSystem HcsSystem, processParameters *uint16, processInformation *HcsProcessInformation, process *HcsProcess, result **uint16) (hr error) { - if hr = procHcsCreateProcess.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procHcsCreateProcess.Addr(), 5, uintptr(computeSystem), uintptr(unsafe.Pointer(processParameters)), uintptr(unsafe.Pointer(processInformation)), uintptr(unsafe.Pointer(process)), uintptr(unsafe.Pointer(result)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsOpenProcess(computeSystem HcsSystem, pid uint32, process *HcsProcess, result **uint16) (hr error) { - if hr = procHcsOpenProcess.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procHcsOpenProcess.Addr(), 4, uintptr(computeSystem), uintptr(pid), uintptr(unsafe.Pointer(process)), uintptr(unsafe.Pointer(result)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsCloseProcess(process HcsProcess) (hr error) { - if hr = procHcsCloseProcess.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsCloseProcess.Addr(), 1, uintptr(process), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsTerminateProcess(process HcsProcess, result **uint16) (hr error) { - if hr = procHcsTerminateProcess.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsTerminateProcess.Addr(), 2, uintptr(process), uintptr(unsafe.Pointer(result)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsSignalProcess(process HcsProcess, options string, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(options) - if hr != nil { - return - } - return _hcsSignalProcess(process, _p0, result) -} - -func _hcsSignalProcess(process HcsProcess, options *uint16, result **uint16) (hr error) { - if hr = procHcsSignalProcess.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsSignalProcess.Addr(), 3, uintptr(process), uintptr(unsafe.Pointer(options)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsGetProcessInfo(process HcsProcess, processInformation *HcsProcessInformation, result **uint16) (hr error) { - if hr = procHcsGetProcessInfo.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsGetProcessInfo.Addr(), 3, uintptr(process), uintptr(unsafe.Pointer(processInformation)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsGetProcessProperties(process HcsProcess, processProperties **uint16, result **uint16) (hr error) { - if hr = procHcsGetProcessProperties.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsGetProcessProperties.Addr(), 3, uintptr(process), uintptr(unsafe.Pointer(processProperties)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsModifyProcess(process HcsProcess, settings string, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(settings) - if hr != nil { - return - } - return _hcsModifyProcess(process, _p0, result) -} - -func _hcsModifyProcess(process HcsProcess, settings *uint16, result **uint16) (hr error) { - if hr = procHcsModifyProcess.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsModifyProcess.Addr(), 3, uintptr(process), uintptr(unsafe.Pointer(settings)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsGetServiceProperties(propertyQuery string, properties **uint16, result **uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(propertyQuery) - if hr != nil { - return - } - return _hcsGetServiceProperties(_p0, properties, result) -} - -func _hcsGetServiceProperties(propertyQuery *uint16, properties **uint16, result **uint16) (hr error) { - if hr = procHcsGetServiceProperties.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsGetServiceProperties.Addr(), 3, uintptr(unsafe.Pointer(propertyQuery)), uintptr(unsafe.Pointer(properties)), uintptr(unsafe.Pointer(result))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsRegisterProcessCallback(process HcsProcess, callback uintptr, context uintptr, callbackHandle *HcsCallback) (hr error) { - if hr = procHcsRegisterProcessCallback.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procHcsRegisterProcessCallback.Addr(), 4, uintptr(process), uintptr(callback), uintptr(context), uintptr(unsafe.Pointer(callbackHandle)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func hcsUnregisterProcessCallback(callbackHandle HcsCallback) (hr error) { - if hr = procHcsUnregisterProcessCallback.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procHcsUnregisterProcessCallback.Addr(), 1, uintptr(callbackHandle), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/activatelayer.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/activatelayer.go deleted file mode 100644 index 81e45495..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/activatelayer.go +++ /dev/null @@ -1,27 +0,0 @@ -package wclayer - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// ActivateLayer will find the layer with the given id and mount it's filesystem. -// For a read/write layer, the mounted filesystem will appear as a volume on the -// host, while a read-only layer is generally expected to be a no-op. -// An activated layer must later be deactivated via DeactivateLayer. -func ActivateLayer(ctx context.Context, path string) (err error) { - title := "hcsshim::ActivateLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("path", path)) - - err = activateLayer(&stdDriverInfo, path) - if err != nil { - return hcserror.New(err, title+" - failed", "") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/baselayer.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/baselayer.go deleted file mode 100644 index 3ec708d1..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/baselayer.go +++ /dev/null @@ -1,182 +0,0 @@ -package wclayer - -import ( - "context" - "errors" - "os" - "path/filepath" - "syscall" - - "github.com/Microsoft/go-winio" - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/Microsoft/hcsshim/internal/safefile" - "github.com/Microsoft/hcsshim/internal/winapi" - "go.opencensus.io/trace" -) - -type baseLayerWriter struct { - ctx context.Context - s *trace.Span - - root *os.File - f *os.File - bw *winio.BackupFileWriter - err error - hasUtilityVM bool - dirInfo []dirInfo -} - -type dirInfo struct { - path string - fileInfo winio.FileBasicInfo -} - -// reapplyDirectoryTimes reapplies directory modification, creation, etc. times -// after processing of the directory tree has completed. The times are expected -// to be ordered such that parent directories come before child directories. -func reapplyDirectoryTimes(root *os.File, dis []dirInfo) error { - for i := range dis { - di := &dis[len(dis)-i-1] // reverse order: process child directories first - f, err := safefile.OpenRelative(di.path, root, syscall.GENERIC_READ|syscall.GENERIC_WRITE, syscall.FILE_SHARE_READ, winapi.FILE_OPEN, winapi.FILE_DIRECTORY_FILE|syscall.FILE_FLAG_OPEN_REPARSE_POINT) - if err != nil { - return err - } - - err = winio.SetFileBasicInfo(f, &di.fileInfo) - f.Close() - if err != nil { - return err - } - - } - return nil -} - -func (w *baseLayerWriter) closeCurrentFile() error { - if w.f != nil { - err := w.bw.Close() - err2 := w.f.Close() - w.f = nil - w.bw = nil - if err != nil { - return err - } - if err2 != nil { - return err2 - } - } - return nil -} - -func (w *baseLayerWriter) Add(name string, fileInfo *winio.FileBasicInfo) (err error) { - defer func() { - if err != nil { - w.err = err - } - }() - - err = w.closeCurrentFile() - if err != nil { - return err - } - - if filepath.ToSlash(name) == `UtilityVM/Files` { - w.hasUtilityVM = true - } - - var f *os.File - defer func() { - if f != nil { - f.Close() - } - }() - - extraFlags := uint32(0) - if fileInfo.FileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 { - extraFlags |= winapi.FILE_DIRECTORY_FILE - w.dirInfo = append(w.dirInfo, dirInfo{name, *fileInfo}) - } - - mode := uint32(syscall.GENERIC_READ | syscall.GENERIC_WRITE | winio.WRITE_DAC | winio.WRITE_OWNER | winio.ACCESS_SYSTEM_SECURITY) - f, err = safefile.OpenRelative(name, w.root, mode, syscall.FILE_SHARE_READ, winapi.FILE_CREATE, extraFlags) - if err != nil { - return hcserror.New(err, "Failed to safefile.OpenRelative", name) - } - - err = winio.SetFileBasicInfo(f, fileInfo) - if err != nil { - return hcserror.New(err, "Failed to SetFileBasicInfo", name) - } - - w.f = f - w.bw = winio.NewBackupFileWriter(f, true) - f = nil - return nil -} - -func (w *baseLayerWriter) AddLink(name string, target string) (err error) { - defer func() { - if err != nil { - w.err = err - } - }() - - err = w.closeCurrentFile() - if err != nil { - return err - } - - return safefile.LinkRelative(target, w.root, name, w.root) -} - -func (w *baseLayerWriter) Remove(name string) error { - return errors.New("base layer cannot have tombstones") -} - -func (w *baseLayerWriter) Write(b []byte) (int, error) { - n, err := w.bw.Write(b) - if err != nil { - w.err = err - } - return n, err -} - -func (w *baseLayerWriter) Close() (err error) { - defer w.s.End() - defer func() { oc.SetSpanStatus(w.s, err) }() - defer func() { - w.root.Close() - w.root = nil - }() - - err = w.closeCurrentFile() - if err != nil { - return err - } - if w.err == nil { - // Restore the file times of all the directories, since they may have - // been modified by creating child directories. - err = reapplyDirectoryTimes(w.root, w.dirInfo) - if err != nil { - return err - } - - err = ProcessBaseLayer(w.ctx, w.root.Name()) - if err != nil { - return err - } - - if w.hasUtilityVM { - err := safefile.EnsureNotReparsePointRelative("UtilityVM", w.root) - if err != nil { - return err - } - err = ProcessUtilityVMImage(w.ctx, filepath.Join(w.root.Name(), "UtilityVM")) - if err != nil { - return err - } - } - } - return w.err -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/createlayer.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/createlayer.go deleted file mode 100644 index 41e5e673..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/createlayer.go +++ /dev/null @@ -1,27 +0,0 @@ -package wclayer - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// CreateLayer creates a new, empty, read-only layer on the filesystem based on -// the parent layer provided. -func CreateLayer(ctx context.Context, path, parent string) (err error) { - title := "hcsshim::CreateLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("path", path), - trace.StringAttribute("parent", parent)) - - err = createLayer(&stdDriverInfo, path, parent) - if err != nil { - return hcserror.New(err, title+" - failed", "") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/createscratchlayer.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/createscratchlayer.go deleted file mode 100644 index 5a3809ae..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/createscratchlayer.go +++ /dev/null @@ -1,34 +0,0 @@ -package wclayer - -import ( - "context" - "strings" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// CreateScratchLayer creates and populates new read-write layer for use by a container. -// This requires the full list of paths to all parent layers up to the base -func CreateScratchLayer(ctx context.Context, path string, parentLayerPaths []string) (err error) { - title := "hcsshim::CreateScratchLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("path", path), - trace.StringAttribute("parentLayerPaths", strings.Join(parentLayerPaths, ", "))) - - // Generate layer descriptors - layers, err := layerPathsToDescriptors(ctx, parentLayerPaths) - if err != nil { - return err - } - - err = createSandboxLayer(&stdDriverInfo, path, 0, layers) - if err != nil { - return hcserror.New(err, title+" - failed", "") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/deactivatelayer.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/deactivatelayer.go deleted file mode 100644 index 70a711cf..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/deactivatelayer.go +++ /dev/null @@ -1,24 +0,0 @@ -package wclayer - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// DeactivateLayer will dismount a layer that was mounted via ActivateLayer. -func DeactivateLayer(ctx context.Context, path string) (err error) { - title := "hcsshim::DeactivateLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("path", path)) - - err = deactivateLayer(&stdDriverInfo, path) - if err != nil { - return hcserror.New(err, title+"- failed", "") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/destroylayer.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/destroylayer.go deleted file mode 100644 index bf197e3b..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/destroylayer.go +++ /dev/null @@ -1,25 +0,0 @@ -package wclayer - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// DestroyLayer will remove the on-disk files representing the layer with the given -// path, including that layer's containing folder, if any. -func DestroyLayer(ctx context.Context, path string) (err error) { - title := "hcsshim::DestroyLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("path", path)) - - err = destroyLayer(&stdDriverInfo, path) - if err != nil { - return hcserror.New(err, title+" - failed", "") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/expandscratchsize.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/expandscratchsize.go deleted file mode 100644 index 93f27da8..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/expandscratchsize.go +++ /dev/null @@ -1,140 +0,0 @@ -package wclayer - -import ( - "context" - "os" - "path/filepath" - "syscall" - "unsafe" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/Microsoft/hcsshim/osversion" - "go.opencensus.io/trace" -) - -// ExpandScratchSize expands the size of a layer to at least size bytes. -func ExpandScratchSize(ctx context.Context, path string, size uint64) (err error) { - title := "hcsshim::ExpandScratchSize" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("path", path), - trace.Int64Attribute("size", int64(size))) - - err = expandSandboxSize(&stdDriverInfo, path, size) - if err != nil { - return hcserror.New(err, title+" - failed", "") - } - - // Manually expand the volume now in order to work around bugs in 19H1 and - // prerelease versions of Vb. Remove once this is fixed in Windows. - if build := osversion.Get().Build; build >= osversion.V19H1 && build < 19020 { - err = expandSandboxVolume(ctx, path) - if err != nil { - return err - } - } - return nil -} - -type virtualStorageType struct { - DeviceID uint32 - VendorID [16]byte -} - -type openVersion2 struct { - GetInfoOnly int32 // bool but 4-byte aligned - ReadOnly int32 // bool but 4-byte aligned - ResiliencyGUID [16]byte // GUID -} - -type openVirtualDiskParameters struct { - Version uint32 // Must always be set to 2 - Version2 openVersion2 -} - -func attachVhd(path string) (syscall.Handle, error) { - var ( - defaultType virtualStorageType - handle syscall.Handle - ) - parameters := openVirtualDiskParameters{Version: 2} - err := openVirtualDisk( - &defaultType, - path, - 0, - 0, - ¶meters, - &handle) - if err != nil { - return 0, &os.PathError{Op: "OpenVirtualDisk", Path: path, Err: err} - } - err = attachVirtualDisk(handle, 0, 0, 0, 0, 0) - if err != nil { - syscall.Close(handle) - return 0, &os.PathError{Op: "AttachVirtualDisk", Path: path, Err: err} - } - return handle, nil -} - -func expandSandboxVolume(ctx context.Context, path string) error { - // Mount the sandbox VHD temporarily. - vhdPath := filepath.Join(path, "sandbox.vhdx") - vhd, err := attachVhd(vhdPath) - if err != nil { - return &os.PathError{Op: "OpenVirtualDisk", Path: vhdPath, Err: err} - } - defer syscall.Close(vhd) - - // Open the volume. - volumePath, err := GetLayerMountPath(ctx, path) - if err != nil { - return err - } - if volumePath[len(volumePath)-1] == '\\' { - volumePath = volumePath[:len(volumePath)-1] - } - volume, err := os.OpenFile(volumePath, os.O_RDWR, 0) - if err != nil { - return err - } - defer volume.Close() - - // Get the volume's underlying partition size in NTFS clusters. - var ( - partitionSize int64 - bytes uint32 - ) - const _IOCTL_DISK_GET_LENGTH_INFO = 0x0007405C - err = syscall.DeviceIoControl(syscall.Handle(volume.Fd()), _IOCTL_DISK_GET_LENGTH_INFO, nil, 0, (*byte)(unsafe.Pointer(&partitionSize)), 8, &bytes, nil) - if err != nil { - return &os.PathError{Op: "IOCTL_DISK_GET_LENGTH_INFO", Path: volume.Name(), Err: err} - } - const ( - clusterSize = 4096 - sectorSize = 512 - ) - targetClusters := partitionSize / clusterSize - - // Get the volume's current size in NTFS clusters. - var volumeSize int64 - err = getDiskFreeSpaceEx(volume.Name()+"\\", nil, &volumeSize, nil) - if err != nil { - return &os.PathError{Op: "GetDiskFreeSpaceEx", Path: volume.Name(), Err: err} - } - volumeClusters := volumeSize / clusterSize - - // Only resize the volume if there is space to grow, otherwise this will - // fail with invalid parameter. NTFS reserves one cluster. - if volumeClusters+1 < targetClusters { - targetSectors := targetClusters * (clusterSize / sectorSize) - const _FSCTL_EXTEND_VOLUME = 0x000900F0 - err = syscall.DeviceIoControl(syscall.Handle(volume.Fd()), _FSCTL_EXTEND_VOLUME, (*byte)(unsafe.Pointer(&targetSectors)), 8, nil, 0, &bytes, nil) - if err != nil { - return &os.PathError{Op: "FSCTL_EXTEND_VOLUME", Path: volume.Name(), Err: err} - } - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/exportlayer.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/exportlayer.go deleted file mode 100644 index 09f0de1a..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/exportlayer.go +++ /dev/null @@ -1,94 +0,0 @@ -package wclayer - -import ( - "context" - "io/ioutil" - "os" - "strings" - - "github.com/Microsoft/go-winio" - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// ExportLayer will create a folder at exportFolderPath and fill that folder with -// the transport format version of the layer identified by layerId. This transport -// format includes any metadata required for later importing the layer (using -// ImportLayer), and requires the full list of parent layer paths in order to -// perform the export. -func ExportLayer(ctx context.Context, path string, exportFolderPath string, parentLayerPaths []string) (err error) { - title := "hcsshim::ExportLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("path", path), - trace.StringAttribute("exportFolderPath", exportFolderPath), - trace.StringAttribute("parentLayerPaths", strings.Join(parentLayerPaths, ", "))) - - // Generate layer descriptors - layers, err := layerPathsToDescriptors(ctx, parentLayerPaths) - if err != nil { - return err - } - - err = exportLayer(&stdDriverInfo, path, exportFolderPath, layers) - if err != nil { - return hcserror.New(err, title+" - failed", "") - } - return nil -} - -type LayerReader interface { - Next() (string, int64, *winio.FileBasicInfo, error) - Read(b []byte) (int, error) - Close() error -} - -// NewLayerReader returns a new layer reader for reading the contents of an on-disk layer. -// The caller must have taken the SeBackupPrivilege privilege -// to call this and any methods on the resulting LayerReader. -func NewLayerReader(ctx context.Context, path string, parentLayerPaths []string) (_ LayerReader, err error) { - ctx, span := trace.StartSpan(ctx, "hcsshim::NewLayerReader") - defer func() { - if err != nil { - oc.SetSpanStatus(span, err) - span.End() - } - }() - span.AddAttributes( - trace.StringAttribute("path", path), - trace.StringAttribute("parentLayerPaths", strings.Join(parentLayerPaths, ", "))) - - exportPath, err := ioutil.TempDir("", "hcs") - if err != nil { - return nil, err - } - err = ExportLayer(ctx, path, exportPath, parentLayerPaths) - if err != nil { - os.RemoveAll(exportPath) - return nil, err - } - return &legacyLayerReaderWrapper{ - ctx: ctx, - s: span, - legacyLayerReader: newLegacyLayerReader(exportPath), - }, nil -} - -type legacyLayerReaderWrapper struct { - ctx context.Context - s *trace.Span - - *legacyLayerReader -} - -func (r *legacyLayerReaderWrapper) Close() (err error) { - defer r.s.End() - defer func() { oc.SetSpanStatus(r.s, err) }() - - err = r.legacyLayerReader.Close() - os.RemoveAll(r.root) - return err -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/getlayermountpath.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/getlayermountpath.go deleted file mode 100644 index 942e3bbf..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/getlayermountpath.go +++ /dev/null @@ -1,51 +0,0 @@ -package wclayer - -import ( - "context" - "syscall" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/log" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// GetLayerMountPath will look for a mounted layer with the given path and return -// the path at which that layer can be accessed. This path may be a volume path -// if the layer is a mounted read-write layer, otherwise it is expected to be the -// folder path at which the layer is stored. -func GetLayerMountPath(ctx context.Context, path string) (_ string, err error) { - title := "hcsshim::GetLayerMountPath" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("path", path)) - - var mountPathLength uintptr - mountPathLength = 0 - - // Call the procedure itself. - log.G(ctx).Debug("Calling proc (1)") - err = getLayerMountPath(&stdDriverInfo, path, &mountPathLength, nil) - if err != nil { - return "", hcserror.New(err, title+" - failed", "(first call)") - } - - // Allocate a mount path of the returned length. - if mountPathLength == 0 { - return "", nil - } - mountPathp := make([]uint16, mountPathLength) - mountPathp[0] = 0 - - // Call the procedure again - log.G(ctx).Debug("Calling proc (2)") - err = getLayerMountPath(&stdDriverInfo, path, &mountPathLength, &mountPathp[0]) - if err != nil { - return "", hcserror.New(err, title+" - failed", "(second call)") - } - - mountPath := syscall.UTF16ToString(mountPathp[0:]) - span.AddAttributes(trace.StringAttribute("mountPath", mountPath)) - return mountPath, nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/getsharedbaseimages.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/getsharedbaseimages.go deleted file mode 100644 index a50378f4..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/getsharedbaseimages.go +++ /dev/null @@ -1,29 +0,0 @@ -package wclayer - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/interop" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// GetSharedBaseImages will enumerate the images stored in the common central -// image store and return descriptive info about those images for the purpose -// of registering them with the graphdriver, graph, and tagstore. -func GetSharedBaseImages(ctx context.Context) (_ string, err error) { - title := "hcsshim::GetSharedBaseImages" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - - var buffer *uint16 - err = getBaseImages(&buffer) - if err != nil { - return "", hcserror.New(err, title+" - failed", "") - } - imageData := interop.ConvertAndFreeCoTaskMemString(buffer) - span.AddAttributes(trace.StringAttribute("imageData", imageData)) - return imageData, nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/grantvmaccess.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/grantvmaccess.go deleted file mode 100644 index aa7c8ae1..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/grantvmaccess.go +++ /dev/null @@ -1,26 +0,0 @@ -package wclayer - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// GrantVmAccess adds access to a file for a given VM -func GrantVmAccess(ctx context.Context, vmid string, filepath string) (err error) { - title := "hcsshim::GrantVmAccess" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("vm-id", vmid), - trace.StringAttribute("path", filepath)) - - err = grantVmAccess(vmid, filepath) - if err != nil { - return hcserror.New(err, title+" - failed", "") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/importlayer.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/importlayer.go deleted file mode 100644 index b3c150d6..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/importlayer.go +++ /dev/null @@ -1,166 +0,0 @@ -package wclayer - -import ( - "context" - "io/ioutil" - "os" - "path/filepath" - "strings" - - "github.com/Microsoft/go-winio" - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "github.com/Microsoft/hcsshim/internal/safefile" - "go.opencensus.io/trace" -) - -// ImportLayer will take the contents of the folder at importFolderPath and import -// that into a layer with the id layerId. Note that in order to correctly populate -// the layer and interperet the transport format, all parent layers must already -// be present on the system at the paths provided in parentLayerPaths. -func ImportLayer(ctx context.Context, path string, importFolderPath string, parentLayerPaths []string) (err error) { - title := "hcsshim::ImportLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("path", path), - trace.StringAttribute("importFolderPath", importFolderPath), - trace.StringAttribute("parentLayerPaths", strings.Join(parentLayerPaths, ", "))) - - // Generate layer descriptors - layers, err := layerPathsToDescriptors(ctx, parentLayerPaths) - if err != nil { - return err - } - - err = importLayer(&stdDriverInfo, path, importFolderPath, layers) - if err != nil { - return hcserror.New(err, title+" - failed", "") - } - return nil -} - -// LayerWriter is an interface that supports writing a new container image layer. -type LayerWriter interface { - // Add adds a file to the layer with given metadata. - Add(name string, fileInfo *winio.FileBasicInfo) error - // AddLink adds a hard link to the layer. The target must already have been added. - AddLink(name string, target string) error - // Remove removes a file that was present in a parent layer from the layer. - Remove(name string) error - // Write writes data to the current file. The data must be in the format of a Win32 - // backup stream. - Write(b []byte) (int, error) - // Close finishes the layer writing process and releases any resources. - Close() error -} - -type legacyLayerWriterWrapper struct { - ctx context.Context - s *trace.Span - - *legacyLayerWriter - path string - parentLayerPaths []string -} - -func (r *legacyLayerWriterWrapper) Close() (err error) { - defer r.s.End() - defer func() { oc.SetSpanStatus(r.s, err) }() - defer os.RemoveAll(r.root.Name()) - defer r.legacyLayerWriter.CloseRoots() - - err = r.legacyLayerWriter.Close() - if err != nil { - return err - } - - if err = ImportLayer(r.ctx, r.destRoot.Name(), r.path, r.parentLayerPaths); err != nil { - return err - } - for _, name := range r.Tombstones { - if err = safefile.RemoveRelative(name, r.destRoot); err != nil && !os.IsNotExist(err) { - return err - } - } - // Add any hard links that were collected. - for _, lnk := range r.PendingLinks { - if err = safefile.RemoveRelative(lnk.Path, r.destRoot); err != nil && !os.IsNotExist(err) { - return err - } - if err = safefile.LinkRelative(lnk.Target, lnk.TargetRoot, lnk.Path, r.destRoot); err != nil { - return err - } - } - - // The reapplyDirectoryTimes must be called AFTER we are done with Tombstone - // deletion and hard link creation. This is because Tombstone deletion and hard link - // creation updates the directory last write timestamps so that will change the - // timestamps added by the `Add` call. Some container applications depend on the - // correctness of these timestamps and so we should change the timestamps back to - // the original value (i.e the value provided in the Add call) after this - // processing is done. - err = reapplyDirectoryTimes(r.destRoot, r.changedDi) - if err != nil { - return err - } - - // Prepare the utility VM for use if one is present in the layer. - if r.HasUtilityVM { - err := safefile.EnsureNotReparsePointRelative("UtilityVM", r.destRoot) - if err != nil { - return err - } - err = ProcessUtilityVMImage(r.ctx, filepath.Join(r.destRoot.Name(), "UtilityVM")) - if err != nil { - return err - } - } - return nil -} - -// NewLayerWriter returns a new layer writer for creating a layer on disk. -// The caller must have taken the SeBackupPrivilege and SeRestorePrivilege privileges -// to call this and any methods on the resulting LayerWriter. -func NewLayerWriter(ctx context.Context, path string, parentLayerPaths []string) (_ LayerWriter, err error) { - ctx, span := trace.StartSpan(ctx, "hcsshim::NewLayerWriter") - defer func() { - if err != nil { - oc.SetSpanStatus(span, err) - span.End() - } - }() - span.AddAttributes( - trace.StringAttribute("path", path), - trace.StringAttribute("parentLayerPaths", strings.Join(parentLayerPaths, ", "))) - - if len(parentLayerPaths) == 0 { - // This is a base layer. It gets imported differently. - f, err := safefile.OpenRoot(path) - if err != nil { - return nil, err - } - return &baseLayerWriter{ - ctx: ctx, - s: span, - root: f, - }, nil - } - - importPath, err := ioutil.TempDir("", "hcs") - if err != nil { - return nil, err - } - w, err := newLegacyLayerWriter(importPath, parentLayerPaths, path) - if err != nil { - return nil, err - } - return &legacyLayerWriterWrapper{ - ctx: ctx, - s: span, - legacyLayerWriter: w, - path: importPath, - parentLayerPaths: parentLayerPaths, - }, nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/layerexists.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/layerexists.go deleted file mode 100644 index 6dd6f2d5..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/layerexists.go +++ /dev/null @@ -1,28 +0,0 @@ -package wclayer - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// LayerExists will return true if a layer with the given id exists and is known -// to the system. -func LayerExists(ctx context.Context, path string) (_ bool, err error) { - title := "hcsshim::LayerExists" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("path", path)) - - // Call the procedure itself. - var exists uint32 - err = layerExists(&stdDriverInfo, path, &exists) - if err != nil { - return false, hcserror.New(err, title+" - failed", "") - } - span.AddAttributes(trace.BoolAttribute("layer-exists", exists != 0)) - return exists != 0, nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/layerid.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/layerid.go deleted file mode 100644 index 0ce34a30..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/layerid.go +++ /dev/null @@ -1,22 +0,0 @@ -package wclayer - -import ( - "context" - "path/filepath" - - "github.com/Microsoft/go-winio/pkg/guid" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// LayerID returns the layer ID of a layer on disk. -func LayerID(ctx context.Context, path string) (_ guid.GUID, err error) { - title := "hcsshim::LayerID" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("path", path)) - - _, file := filepath.Split(path) - return NameToGuid(ctx, file) -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/layerutils.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/layerutils.go deleted file mode 100644 index 1ec893c6..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/layerutils.go +++ /dev/null @@ -1,97 +0,0 @@ -package wclayer - -// This file contains utility functions to support storage (graph) related -// functionality. - -import ( - "context" - "syscall" - - "github.com/Microsoft/go-winio/pkg/guid" - "github.com/sirupsen/logrus" -) - -/* To pass into syscall, we need a struct matching the following: -enum GraphDriverType -{ - DiffDriver, - FilterDriver -}; - -struct DriverInfo { - GraphDriverType Flavour; - LPCWSTR HomeDir; -}; -*/ - -type driverInfo struct { - Flavour int - HomeDirp *uint16 -} - -var ( - utf16EmptyString uint16 - stdDriverInfo = driverInfo{1, &utf16EmptyString} -) - -/* To pass into syscall, we need a struct matching the following: -typedef struct _WC_LAYER_DESCRIPTOR { - - // - // The ID of the layer - // - - GUID LayerId; - - // - // Additional flags - // - - union { - struct { - ULONG Reserved : 31; - ULONG Dirty : 1; // Created from sandbox as a result of snapshot - }; - ULONG Value; - } Flags; - - // - // Path to the layer root directory, null-terminated - // - - PCWSTR Path; - -} WC_LAYER_DESCRIPTOR, *PWC_LAYER_DESCRIPTOR; -*/ -type WC_LAYER_DESCRIPTOR struct { - LayerId guid.GUID - Flags uint32 - Pathp *uint16 -} - -func layerPathsToDescriptors(ctx context.Context, parentLayerPaths []string) ([]WC_LAYER_DESCRIPTOR, error) { - // Array of descriptors that gets constructed. - var layers []WC_LAYER_DESCRIPTOR - - for i := 0; i < len(parentLayerPaths); i++ { - g, err := LayerID(ctx, parentLayerPaths[i]) - if err != nil { - logrus.WithError(err).Debug("Failed to convert name to guid") - return nil, err - } - - p, err := syscall.UTF16PtrFromString(parentLayerPaths[i]) - if err != nil { - logrus.WithError(err).Debug("Failed conversion of parentLayerPath to pointer") - return nil, err - } - - layers = append(layers, WC_LAYER_DESCRIPTOR{ - LayerId: g, - Flags: 0, - Pathp: p, - }) - } - - return layers, nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/legacy.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/legacy.go deleted file mode 100644 index dc3caf75..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/legacy.go +++ /dev/null @@ -1,811 +0,0 @@ -package wclayer - -import ( - "bufio" - "encoding/binary" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - "syscall" - - "github.com/Microsoft/go-winio" - "github.com/Microsoft/hcsshim/internal/longpath" - "github.com/Microsoft/hcsshim/internal/safefile" - "github.com/Microsoft/hcsshim/internal/winapi" -) - -var errorIterationCanceled = errors.New("") - -var mutatedUtilityVMFiles = map[string]bool{ - `EFI\Microsoft\Boot\BCD`: true, - `EFI\Microsoft\Boot\BCD.LOG`: true, - `EFI\Microsoft\Boot\BCD.LOG1`: true, - `EFI\Microsoft\Boot\BCD.LOG2`: true, -} - -const ( - filesPath = `Files` - hivesPath = `Hives` - utilityVMPath = `UtilityVM` - utilityVMFilesPath = `UtilityVM\Files` -) - -func openFileOrDir(path string, mode uint32, createDisposition uint32) (file *os.File, err error) { - return winio.OpenForBackup(path, mode, syscall.FILE_SHARE_READ, createDisposition) -} - -func hasPathPrefix(p, prefix string) bool { - return strings.HasPrefix(p, prefix) && len(p) > len(prefix) && p[len(prefix)] == '\\' -} - -type fileEntry struct { - path string - fi os.FileInfo - err error -} - -type legacyLayerReader struct { - root string - result chan *fileEntry - proceed chan bool - currentFile *os.File - backupReader *winio.BackupFileReader -} - -// newLegacyLayerReader returns a new LayerReader that can read the Windows -// container layer transport format from disk. -func newLegacyLayerReader(root string) *legacyLayerReader { - r := &legacyLayerReader{ - root: root, - result: make(chan *fileEntry), - proceed: make(chan bool), - } - go r.walk() - return r -} - -func readTombstones(path string) (map[string]([]string), error) { - tf, err := os.Open(filepath.Join(path, "tombstones.txt")) - if err != nil { - return nil, err - } - defer tf.Close() - s := bufio.NewScanner(tf) - if !s.Scan() || s.Text() != "\xef\xbb\xbfVersion 1.0" { - return nil, errors.New("Invalid tombstones file") - } - - ts := make(map[string]([]string)) - for s.Scan() { - t := filepath.Join(filesPath, s.Text()[1:]) // skip leading `\` - dir := filepath.Dir(t) - ts[dir] = append(ts[dir], t) - } - if err = s.Err(); err != nil { - return nil, err - } - - return ts, nil -} - -func (r *legacyLayerReader) walkUntilCancelled() error { - root, err := longpath.LongAbs(r.root) - if err != nil { - return err - } - - r.root = root - ts, err := readTombstones(r.root) - if err != nil { - return err - } - - err = filepath.Walk(r.root, func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - // Indirect fix for https://github.com/moby/moby/issues/32838#issuecomment-343610048. - // Handle failure from what may be a golang bug in the conversion of - // UTF16 to UTF8 in files which are left in the recycle bin. Os.Lstat - // which is called by filepath.Walk will fail when a filename contains - // unicode characters. Skip the recycle bin regardless which is goodness. - if strings.EqualFold(path, filepath.Join(r.root, `Files\$Recycle.Bin`)) && info.IsDir() { - return filepath.SkipDir - } - - if path == r.root || path == filepath.Join(r.root, "tombstones.txt") || strings.HasSuffix(path, ".$wcidirs$") { - return nil - } - - r.result <- &fileEntry{path, info, nil} - if !<-r.proceed { - return errorIterationCanceled - } - - // List all the tombstones. - if info.IsDir() { - relPath, err := filepath.Rel(r.root, path) - if err != nil { - return err - } - if dts, ok := ts[relPath]; ok { - for _, t := range dts { - r.result <- &fileEntry{filepath.Join(r.root, t), nil, nil} - if !<-r.proceed { - return errorIterationCanceled - } - } - } - } - return nil - }) - if err == errorIterationCanceled { - return nil - } - if err == nil { - return io.EOF - } - return err -} - -func (r *legacyLayerReader) walk() { - defer close(r.result) - if !<-r.proceed { - return - } - - err := r.walkUntilCancelled() - if err != nil { - for { - r.result <- &fileEntry{err: err} - if !<-r.proceed { - return - } - } - } -} - -func (r *legacyLayerReader) reset() { - if r.backupReader != nil { - r.backupReader.Close() - r.backupReader = nil - } - if r.currentFile != nil { - r.currentFile.Close() - r.currentFile = nil - } -} - -func findBackupStreamSize(r io.Reader) (int64, error) { - br := winio.NewBackupStreamReader(r) - for { - hdr, err := br.Next() - if err != nil { - if err == io.EOF { - err = nil - } - return 0, err - } - if hdr.Id == winio.BackupData { - return hdr.Size, nil - } - } -} - -func (r *legacyLayerReader) Next() (path string, size int64, fileInfo *winio.FileBasicInfo, err error) { - r.reset() - r.proceed <- true - fe := <-r.result - if fe == nil { - err = errors.New("LegacyLayerReader closed") - return - } - if fe.err != nil { - err = fe.err - return - } - - path, err = filepath.Rel(r.root, fe.path) - if err != nil { - return - } - - if fe.fi == nil { - // This is a tombstone. Return a nil fileInfo. - return - } - - if fe.fi.IsDir() && hasPathPrefix(path, filesPath) { - fe.path += ".$wcidirs$" - } - - f, err := openFileOrDir(fe.path, syscall.GENERIC_READ, syscall.OPEN_EXISTING) - if err != nil { - return - } - defer func() { - if f != nil { - f.Close() - } - }() - - fileInfo, err = winio.GetFileBasicInfo(f) - if err != nil { - return - } - - if !hasPathPrefix(path, filesPath) { - size = fe.fi.Size() - r.backupReader = winio.NewBackupFileReader(f, false) - if path == hivesPath || path == filesPath { - // The Hives directory has a non-deterministic file time because of the - // nature of the import process. Use the times from System_Delta. - var g *os.File - g, err = os.Open(filepath.Join(r.root, hivesPath, `System_Delta`)) - if err != nil { - return - } - attr := fileInfo.FileAttributes - fileInfo, err = winio.GetFileBasicInfo(g) - g.Close() - if err != nil { - return - } - fileInfo.FileAttributes = attr - } - - // The creation time and access time get reset for files outside of the Files path. - fileInfo.CreationTime = fileInfo.LastWriteTime - fileInfo.LastAccessTime = fileInfo.LastWriteTime - - } else { - // The file attributes are written before the backup stream. - var attr uint32 - err = binary.Read(f, binary.LittleEndian, &attr) - if err != nil { - return - } - fileInfo.FileAttributes = attr - beginning := int64(4) - - // Find the accurate file size. - if !fe.fi.IsDir() { - size, err = findBackupStreamSize(f) - if err != nil { - err = &os.PathError{Op: "findBackupStreamSize", Path: fe.path, Err: err} - return - } - } - - // Return back to the beginning of the backup stream. - _, err = f.Seek(beginning, 0) - if err != nil { - return - } - } - - r.currentFile = f - f = nil - return -} - -func (r *legacyLayerReader) Read(b []byte) (int, error) { - if r.backupReader == nil { - if r.currentFile == nil { - return 0, io.EOF - } - return r.currentFile.Read(b) - } - return r.backupReader.Read(b) -} - -func (r *legacyLayerReader) Seek(offset int64, whence int) (int64, error) { - if r.backupReader == nil { - if r.currentFile == nil { - return 0, errors.New("no current file") - } - return r.currentFile.Seek(offset, whence) - } - return 0, errors.New("seek not supported on this stream") -} - -func (r *legacyLayerReader) Close() error { - r.proceed <- false - <-r.result - r.reset() - return nil -} - -type pendingLink struct { - Path, Target string - TargetRoot *os.File -} - -type pendingDir struct { - Path string - Root *os.File -} - -type legacyLayerWriter struct { - root *os.File - destRoot *os.File - parentRoots []*os.File - currentFile *os.File - bufWriter *bufio.Writer - currentFileName string - currentFileRoot *os.File - backupWriter *winio.BackupFileWriter - Tombstones []string - HasUtilityVM bool - changedDi []dirInfo - addedFiles map[string]bool - PendingLinks []pendingLink - pendingDirs []pendingDir - currentIsDir bool -} - -// newLegacyLayerWriter returns a LayerWriter that can write the contaler layer -// transport format to disk. -func newLegacyLayerWriter(root string, parentRoots []string, destRoot string) (w *legacyLayerWriter, err error) { - w = &legacyLayerWriter{ - addedFiles: make(map[string]bool), - } - defer func() { - if err != nil { - w.CloseRoots() - w = nil - } - }() - w.root, err = safefile.OpenRoot(root) - if err != nil { - return - } - w.destRoot, err = safefile.OpenRoot(destRoot) - if err != nil { - return - } - for _, r := range parentRoots { - f, err := safefile.OpenRoot(r) - if err != nil { - return w, err - } - w.parentRoots = append(w.parentRoots, f) - } - w.bufWriter = bufio.NewWriterSize(ioutil.Discard, 65536) - return -} - -func (w *legacyLayerWriter) CloseRoots() { - if w.root != nil { - w.root.Close() - w.root = nil - } - if w.destRoot != nil { - w.destRoot.Close() - w.destRoot = nil - } - for i := range w.parentRoots { - w.parentRoots[i].Close() - } - w.parentRoots = nil -} - -func (w *legacyLayerWriter) initUtilityVM() error { - if !w.HasUtilityVM { - err := safefile.MkdirRelative(utilityVMPath, w.destRoot) - if err != nil { - return err - } - // Server 2016 does not support multiple layers for the utility VM, so - // clone the utility VM from the parent layer into this layer. Use hard - // links to avoid unnecessary copying, since most of the files are - // immutable. - err = cloneTree(w.parentRoots[0], w.destRoot, utilityVMFilesPath, mutatedUtilityVMFiles) - if err != nil { - return fmt.Errorf("cloning the parent utility VM image failed: %s", err) - } - w.HasUtilityVM = true - } - return nil -} - -func (w *legacyLayerWriter) reset() error { - err := w.bufWriter.Flush() - if err != nil { - return err - } - w.bufWriter.Reset(ioutil.Discard) - if w.currentIsDir { - r := w.currentFile - br := winio.NewBackupStreamReader(r) - // Seek to the beginning of the backup stream, skipping the fileattrs - if _, err := r.Seek(4, io.SeekStart); err != nil { - return err - } - - for { - bhdr, err := br.Next() - if err == io.EOF { - // end of backupstream data - break - } - if err != nil { - return err - } - switch bhdr.Id { - case winio.BackupReparseData: - // The current file is a `.$wcidirs$` metadata file that - // describes a directory reparse point. Delete the placeholder - // directory to prevent future files being added into the - // destination of the reparse point during the ImportLayer call - if err := safefile.RemoveRelative(w.currentFileName, w.currentFileRoot); err != nil { - return err - } - w.pendingDirs = append(w.pendingDirs, pendingDir{Path: w.currentFileName, Root: w.currentFileRoot}) - default: - // ignore all other stream types, as we only care about directory reparse points - } - } - w.currentIsDir = false - } - if w.backupWriter != nil { - w.backupWriter.Close() - w.backupWriter = nil - } - if w.currentFile != nil { - w.currentFile.Close() - w.currentFile = nil - w.currentFileName = "" - w.currentFileRoot = nil - } - return nil -} - -// copyFileWithMetadata copies a file using the backup/restore APIs in order to preserve metadata -func copyFileWithMetadata(srcRoot, destRoot *os.File, subPath string, isDir bool) (fileInfo *winio.FileBasicInfo, err error) { - src, err := safefile.OpenRelative( - subPath, - srcRoot, - syscall.GENERIC_READ|winio.ACCESS_SYSTEM_SECURITY, - syscall.FILE_SHARE_READ, - winapi.FILE_OPEN, - winapi.FILE_OPEN_REPARSE_POINT) - if err != nil { - return nil, err - } - defer src.Close() - srcr := winio.NewBackupFileReader(src, true) - defer srcr.Close() - - fileInfo, err = winio.GetFileBasicInfo(src) - if err != nil { - return nil, err - } - - extraFlags := uint32(0) - if isDir { - extraFlags |= winapi.FILE_DIRECTORY_FILE - } - dest, err := safefile.OpenRelative( - subPath, - destRoot, - syscall.GENERIC_READ|syscall.GENERIC_WRITE|winio.WRITE_DAC|winio.WRITE_OWNER|winio.ACCESS_SYSTEM_SECURITY, - syscall.FILE_SHARE_READ, - winapi.FILE_CREATE, - extraFlags) - if err != nil { - return nil, err - } - defer dest.Close() - - err = winio.SetFileBasicInfo(dest, fileInfo) - if err != nil { - return nil, err - } - - destw := winio.NewBackupFileWriter(dest, true) - defer func() { - cerr := destw.Close() - if err == nil { - err = cerr - } - }() - - _, err = io.Copy(destw, srcr) - if err != nil { - return nil, err - } - - return fileInfo, nil -} - -// cloneTree clones a directory tree using hard links. It skips hard links for -// the file names in the provided map and just copies those files. -func cloneTree(srcRoot *os.File, destRoot *os.File, subPath string, mutatedFiles map[string]bool) error { - var di []dirInfo - err := safefile.EnsureNotReparsePointRelative(subPath, srcRoot) - if err != nil { - return err - } - err = filepath.Walk(filepath.Join(srcRoot.Name(), subPath), func(srcFilePath string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - relPath, err := filepath.Rel(srcRoot.Name(), srcFilePath) - if err != nil { - return err - } - - fileAttributes := info.Sys().(*syscall.Win32FileAttributeData).FileAttributes - // Directories, reparse points, and files that will be mutated during - // utility VM import must be copied. All other files can be hard linked. - isReparsePoint := fileAttributes&syscall.FILE_ATTRIBUTE_REPARSE_POINT != 0 - // In go1.9, FileInfo.IsDir() returns false if the directory is also a symlink. - // See: https://github.com/golang/go/commit/1989921aef60c83e6f9127a8448fb5ede10e9acc - // Fixes the problem by checking syscall.FILE_ATTRIBUTE_DIRECTORY directly - isDir := fileAttributes&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 - - if isDir || isReparsePoint || mutatedFiles[relPath] { - fi, err := copyFileWithMetadata(srcRoot, destRoot, relPath, isDir) - if err != nil { - return err - } - if isDir { - di = append(di, dirInfo{path: relPath, fileInfo: *fi}) - } - } else { - err = safefile.LinkRelative(relPath, srcRoot, relPath, destRoot) - if err != nil { - return err - } - } - - return nil - }) - if err != nil { - return err - } - - return reapplyDirectoryTimes(destRoot, di) -} - -func (w *legacyLayerWriter) Add(name string, fileInfo *winio.FileBasicInfo) error { - if err := w.reset(); err != nil { - return err - } - - if name == utilityVMPath { - return w.initUtilityVM() - } - - if (fileInfo.FileAttributes & syscall.FILE_ATTRIBUTE_DIRECTORY) != 0 { - w.changedDi = append(w.changedDi, dirInfo{path: name, fileInfo: *fileInfo}) - } - - name = filepath.Clean(name) - if hasPathPrefix(name, utilityVMPath) { - if !w.HasUtilityVM { - return errors.New("missing UtilityVM directory") - } - if !hasPathPrefix(name, utilityVMFilesPath) && name != utilityVMFilesPath { - return errors.New("invalid UtilityVM layer") - } - createDisposition := uint32(winapi.FILE_OPEN) - if (fileInfo.FileAttributes & syscall.FILE_ATTRIBUTE_DIRECTORY) != 0 { - st, err := safefile.LstatRelative(name, w.destRoot) - if err != nil && !os.IsNotExist(err) { - return err - } - if st != nil { - // Delete the existing file/directory if it is not the same type as this directory. - existingAttr := st.Sys().(*syscall.Win32FileAttributeData).FileAttributes - if (uint32(fileInfo.FileAttributes)^existingAttr)&(syscall.FILE_ATTRIBUTE_DIRECTORY|syscall.FILE_ATTRIBUTE_REPARSE_POINT) != 0 { - if err = safefile.RemoveAllRelative(name, w.destRoot); err != nil { - return err - } - st = nil - } - } - if st == nil { - if err = safefile.MkdirRelative(name, w.destRoot); err != nil { - return err - } - } - } else { - // Overwrite any existing hard link. - err := safefile.RemoveRelative(name, w.destRoot) - if err != nil && !os.IsNotExist(err) { - return err - } - createDisposition = winapi.FILE_CREATE - } - - f, err := safefile.OpenRelative( - name, - w.destRoot, - syscall.GENERIC_READ|syscall.GENERIC_WRITE|winio.WRITE_DAC|winio.WRITE_OWNER|winio.ACCESS_SYSTEM_SECURITY, - syscall.FILE_SHARE_READ, - createDisposition, - winapi.FILE_OPEN_REPARSE_POINT, - ) - if err != nil { - return err - } - defer func() { - if f != nil { - f.Close() - safefile.RemoveRelative(name, w.destRoot) - } - }() - - err = winio.SetFileBasicInfo(f, fileInfo) - if err != nil { - return err - } - - w.backupWriter = winio.NewBackupFileWriter(f, true) - w.bufWriter.Reset(w.backupWriter) - w.currentFile = f - w.currentFileName = name - w.currentFileRoot = w.destRoot - w.addedFiles[name] = true - f = nil - return nil - } - - fname := name - if (fileInfo.FileAttributes & syscall.FILE_ATTRIBUTE_DIRECTORY) != 0 { - err := safefile.MkdirRelative(name, w.root) - if err != nil { - return err - } - fname += ".$wcidirs$" - w.currentIsDir = true - } - - f, err := safefile.OpenRelative(fname, w.root, syscall.GENERIC_READ|syscall.GENERIC_WRITE, syscall.FILE_SHARE_READ, winapi.FILE_CREATE, 0) - if err != nil { - return err - } - defer func() { - if f != nil { - f.Close() - safefile.RemoveRelative(fname, w.root) - } - }() - - strippedFi := *fileInfo - strippedFi.FileAttributes = 0 - err = winio.SetFileBasicInfo(f, &strippedFi) - if err != nil { - return err - } - - if hasPathPrefix(name, hivesPath) { - w.backupWriter = winio.NewBackupFileWriter(f, false) - w.bufWriter.Reset(w.backupWriter) - } else { - w.bufWriter.Reset(f) - // The file attributes are written before the stream. - err = binary.Write(w.bufWriter, binary.LittleEndian, uint32(fileInfo.FileAttributes)) - if err != nil { - w.bufWriter.Reset(ioutil.Discard) - return err - } - } - - w.currentFile = f - w.currentFileName = name - w.currentFileRoot = w.root - w.addedFiles[name] = true - f = nil - return nil -} - -func (w *legacyLayerWriter) AddLink(name string, target string) error { - if err := w.reset(); err != nil { - return err - } - - target = filepath.Clean(target) - var roots []*os.File - if hasPathPrefix(target, filesPath) { - // Look for cross-layer hard link targets in the parent layers, since - // nothing is in the destination path yet. - roots = w.parentRoots - } else if hasPathPrefix(target, utilityVMFilesPath) { - // Since the utility VM is fully cloned into the destination path - // already, look for cross-layer hard link targets directly in the - // destination path. - roots = []*os.File{w.destRoot} - } - - if roots == nil || (!hasPathPrefix(name, filesPath) && !hasPathPrefix(name, utilityVMFilesPath)) { - return errors.New("invalid hard link in layer") - } - - // Find to try the target of the link in a previously added file. If that - // fails, search in parent layers. - var selectedRoot *os.File - if _, ok := w.addedFiles[target]; ok { - selectedRoot = w.destRoot - } else { - for _, r := range roots { - if _, err := safefile.LstatRelative(target, r); err != nil { - if !os.IsNotExist(err) { - return err - } - } else { - selectedRoot = r - break - } - } - if selectedRoot == nil { - return fmt.Errorf("failed to find link target for '%s' -> '%s'", name, target) - } - } - - // The link can't be written until after the ImportLayer call. - w.PendingLinks = append(w.PendingLinks, pendingLink{ - Path: name, - Target: target, - TargetRoot: selectedRoot, - }) - w.addedFiles[name] = true - return nil -} - -func (w *legacyLayerWriter) Remove(name string) error { - name = filepath.Clean(name) - if hasPathPrefix(name, filesPath) { - w.Tombstones = append(w.Tombstones, name) - } else if hasPathPrefix(name, utilityVMFilesPath) { - err := w.initUtilityVM() - if err != nil { - return err - } - // Make sure the path exists; os.RemoveAll will not fail if the file is - // already gone, and this needs to be a fatal error for diagnostics - // purposes. - if _, err := safefile.LstatRelative(name, w.destRoot); err != nil { - return err - } - err = safefile.RemoveAllRelative(name, w.destRoot) - if err != nil { - return err - } - } else { - return fmt.Errorf("invalid tombstone %s", name) - } - - return nil -} - -func (w *legacyLayerWriter) Write(b []byte) (int, error) { - if w.backupWriter == nil && w.currentFile == nil { - return 0, errors.New("closed") - } - return w.bufWriter.Write(b) -} - -func (w *legacyLayerWriter) Close() error { - if err := w.reset(); err != nil { - return err - } - if err := safefile.RemoveRelative("tombstones.txt", w.root); err != nil && !os.IsNotExist(err) { - return err - } - for _, pd := range w.pendingDirs { - err := safefile.MkdirRelative(pd.Path, pd.Root) - if err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/nametoguid.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/nametoguid.go deleted file mode 100644 index b732857b..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/nametoguid.go +++ /dev/null @@ -1,29 +0,0 @@ -package wclayer - -import ( - "context" - - "github.com/Microsoft/go-winio/pkg/guid" - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// NameToGuid converts the given string into a GUID using the algorithm in the -// Host Compute Service, ensuring GUIDs generated with the same string are common -// across all clients. -func NameToGuid(ctx context.Context, name string) (_ guid.GUID, err error) { - title := "hcsshim::NameToGuid" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("name", name)) - - var id guid.GUID - err = nameToGuid(name, &id) - if err != nil { - return guid.GUID{}, hcserror.New(err, title+" - failed", "") - } - span.AddAttributes(trace.StringAttribute("guid", id.String())) - return id, nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/preparelayer.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/preparelayer.go deleted file mode 100644 index 55f7730d..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/preparelayer.go +++ /dev/null @@ -1,44 +0,0 @@ -package wclayer - -import ( - "context" - "strings" - "sync" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -var prepareLayerLock sync.Mutex - -// PrepareLayer finds a mounted read-write layer matching path and enables the -// the filesystem filter for use on that layer. This requires the paths to all -// parent layers, and is necessary in order to view or interact with the layer -// as an actual filesystem (reading and writing files, creating directories, etc). -// Disabling the filter must be done via UnprepareLayer. -func PrepareLayer(ctx context.Context, path string, parentLayerPaths []string) (err error) { - title := "hcsshim::PrepareLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes( - trace.StringAttribute("path", path), - trace.StringAttribute("parentLayerPaths", strings.Join(parentLayerPaths, ", "))) - - // Generate layer descriptors - layers, err := layerPathsToDescriptors(ctx, parentLayerPaths) - if err != nil { - return err - } - - // This lock is a temporary workaround for a Windows bug. Only allowing one - // call to prepareLayer at a time vastly reduces the chance of a timeout. - prepareLayerLock.Lock() - defer prepareLayerLock.Unlock() - err = prepareLayer(&stdDriverInfo, path, layers) - if err != nil { - return hcserror.New(err, title+" - failed", "") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/processimage.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/processimage.go deleted file mode 100644 index aabb3136..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/processimage.go +++ /dev/null @@ -1,41 +0,0 @@ -package wclayer - -import ( - "context" - "os" - - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// ProcessBaseLayer post-processes a base layer that has had its files extracted. -// The files should have been extracted to \Files. -func ProcessBaseLayer(ctx context.Context, path string) (err error) { - title := "hcsshim::ProcessBaseLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("path", path)) - - err = processBaseImage(path) - if err != nil { - return &os.PathError{Op: title, Path: path, Err: err} - } - return nil -} - -// ProcessUtilityVMImage post-processes a utility VM image that has had its files extracted. -// The files should have been extracted to \Files. -func ProcessUtilityVMImage(ctx context.Context, path string) (err error) { - title := "hcsshim::ProcessUtilityVMImage" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("path", path)) - - err = processUtilityImage(path) - if err != nil { - return &os.PathError{Op: title, Path: path, Err: err} - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/unpreparelayer.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/unpreparelayer.go deleted file mode 100644 index 84f81848..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/unpreparelayer.go +++ /dev/null @@ -1,25 +0,0 @@ -package wclayer - -import ( - "context" - - "github.com/Microsoft/hcsshim/internal/hcserror" - "github.com/Microsoft/hcsshim/internal/oc" - "go.opencensus.io/trace" -) - -// UnprepareLayer disables the filesystem filter for the read-write layer with -// the given id. -func UnprepareLayer(ctx context.Context, path string) (err error) { - title := "hcsshim::UnprepareLayer" - ctx, span := trace.StartSpan(ctx, title) - defer span.End() - defer func() { oc.SetSpanStatus(span, err) }() - span.AddAttributes(trace.StringAttribute("path", path)) - - err = unprepareLayer(&stdDriverInfo, path) - if err != nil { - return hcserror.New(err, title+" - failed", "") - } - return nil -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/wclayer.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/wclayer.go deleted file mode 100644 index 9b1e06d5..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/wclayer.go +++ /dev/null @@ -1,35 +0,0 @@ -// Package wclayer provides bindings to HCS's legacy layer management API and -// provides a higher level interface around these calls for container layer -// management. -package wclayer - -import "github.com/Microsoft/go-winio/pkg/guid" - -//go:generate go run ../../mksyscall_windows.go -output zsyscall_windows.go wclayer.go - -//sys activateLayer(info *driverInfo, id string) (hr error) = vmcompute.ActivateLayer? -//sys copyLayer(info *driverInfo, srcId string, dstId string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) = vmcompute.CopyLayer? -//sys createLayer(info *driverInfo, id string, parent string) (hr error) = vmcompute.CreateLayer? -//sys createSandboxLayer(info *driverInfo, id string, parent uintptr, descriptors []WC_LAYER_DESCRIPTOR) (hr error) = vmcompute.CreateSandboxLayer? -//sys expandSandboxSize(info *driverInfo, id string, size uint64) (hr error) = vmcompute.ExpandSandboxSize? -//sys deactivateLayer(info *driverInfo, id string) (hr error) = vmcompute.DeactivateLayer? -//sys destroyLayer(info *driverInfo, id string) (hr error) = vmcompute.DestroyLayer? -//sys exportLayer(info *driverInfo, id string, path string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) = vmcompute.ExportLayer? -//sys getLayerMountPath(info *driverInfo, id string, length *uintptr, buffer *uint16) (hr error) = vmcompute.GetLayerMountPath? -//sys getBaseImages(buffer **uint16) (hr error) = vmcompute.GetBaseImages? -//sys importLayer(info *driverInfo, id string, path string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) = vmcompute.ImportLayer? -//sys layerExists(info *driverInfo, id string, exists *uint32) (hr error) = vmcompute.LayerExists? -//sys nameToGuid(name string, guid *_guid) (hr error) = vmcompute.NameToGuid? -//sys prepareLayer(info *driverInfo, id string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) = vmcompute.PrepareLayer? -//sys unprepareLayer(info *driverInfo, id string) (hr error) = vmcompute.UnprepareLayer? -//sys processBaseImage(path string) (hr error) = vmcompute.ProcessBaseImage? -//sys processUtilityImage(path string) (hr error) = vmcompute.ProcessUtilityImage? - -//sys grantVmAccess(vmid string, filepath string) (hr error) = vmcompute.GrantVmAccess? - -//sys openVirtualDisk(virtualStorageType *virtualStorageType, path string, virtualDiskAccessMask uint32, flags uint32, parameters *openVirtualDiskParameters, handle *syscall.Handle) (err error) [failretval != 0] = virtdisk.OpenVirtualDisk -//sys attachVirtualDisk(handle syscall.Handle, sd uintptr, flags uint32, providerFlags uint32, params uintptr, overlapped uintptr) (err error) [failretval != 0] = virtdisk.AttachVirtualDisk - -//sys getDiskFreeSpaceEx(directoryName string, freeBytesAvailableToCaller *int64, totalNumberOfBytes *int64, totalNumberOfFreeBytes *int64) (err error) = GetDiskFreeSpaceExW - -type _guid = guid.GUID diff --git a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/zsyscall_windows.go b/vendor/github.com/Microsoft/hcsshim/internal/wclayer/zsyscall_windows.go deleted file mode 100644 index 67f917f0..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/wclayer/zsyscall_windows.go +++ /dev/null @@ -1,569 +0,0 @@ -// Code generated mksyscall_windows.exe DO NOT EDIT - -package wclayer - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return nil - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modvmcompute = windows.NewLazySystemDLL("vmcompute.dll") - modvirtdisk = windows.NewLazySystemDLL("virtdisk.dll") - modkernel32 = windows.NewLazySystemDLL("kernel32.dll") - - procActivateLayer = modvmcompute.NewProc("ActivateLayer") - procCopyLayer = modvmcompute.NewProc("CopyLayer") - procCreateLayer = modvmcompute.NewProc("CreateLayer") - procCreateSandboxLayer = modvmcompute.NewProc("CreateSandboxLayer") - procExpandSandboxSize = modvmcompute.NewProc("ExpandSandboxSize") - procDeactivateLayer = modvmcompute.NewProc("DeactivateLayer") - procDestroyLayer = modvmcompute.NewProc("DestroyLayer") - procExportLayer = modvmcompute.NewProc("ExportLayer") - procGetLayerMountPath = modvmcompute.NewProc("GetLayerMountPath") - procGetBaseImages = modvmcompute.NewProc("GetBaseImages") - procImportLayer = modvmcompute.NewProc("ImportLayer") - procLayerExists = modvmcompute.NewProc("LayerExists") - procNameToGuid = modvmcompute.NewProc("NameToGuid") - procPrepareLayer = modvmcompute.NewProc("PrepareLayer") - procUnprepareLayer = modvmcompute.NewProc("UnprepareLayer") - procProcessBaseImage = modvmcompute.NewProc("ProcessBaseImage") - procProcessUtilityImage = modvmcompute.NewProc("ProcessUtilityImage") - procGrantVmAccess = modvmcompute.NewProc("GrantVmAccess") - procOpenVirtualDisk = modvirtdisk.NewProc("OpenVirtualDisk") - procAttachVirtualDisk = modvirtdisk.NewProc("AttachVirtualDisk") - procGetDiskFreeSpaceExW = modkernel32.NewProc("GetDiskFreeSpaceExW") -) - -func activateLayer(info *driverInfo, id string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - return _activateLayer(info, _p0) -} - -func _activateLayer(info *driverInfo, id *uint16) (hr error) { - if hr = procActivateLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procActivateLayer.Addr(), 2, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func copyLayer(info *driverInfo, srcId string, dstId string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(srcId) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(dstId) - if hr != nil { - return - } - return _copyLayer(info, _p0, _p1, descriptors) -} - -func _copyLayer(info *driverInfo, srcId *uint16, dstId *uint16, descriptors []WC_LAYER_DESCRIPTOR) (hr error) { - var _p2 *WC_LAYER_DESCRIPTOR - if len(descriptors) > 0 { - _p2 = &descriptors[0] - } - if hr = procCopyLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procCopyLayer.Addr(), 5, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(srcId)), uintptr(unsafe.Pointer(dstId)), uintptr(unsafe.Pointer(_p2)), uintptr(len(descriptors)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func createLayer(info *driverInfo, id string, parent string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(parent) - if hr != nil { - return - } - return _createLayer(info, _p0, _p1) -} - -func _createLayer(info *driverInfo, id *uint16, parent *uint16) (hr error) { - if hr = procCreateLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procCreateLayer.Addr(), 3, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(parent))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func createSandboxLayer(info *driverInfo, id string, parent uintptr, descriptors []WC_LAYER_DESCRIPTOR) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - return _createSandboxLayer(info, _p0, parent, descriptors) -} - -func _createSandboxLayer(info *driverInfo, id *uint16, parent uintptr, descriptors []WC_LAYER_DESCRIPTOR) (hr error) { - var _p1 *WC_LAYER_DESCRIPTOR - if len(descriptors) > 0 { - _p1 = &descriptors[0] - } - if hr = procCreateSandboxLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procCreateSandboxLayer.Addr(), 5, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(parent), uintptr(unsafe.Pointer(_p1)), uintptr(len(descriptors)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func expandSandboxSize(info *driverInfo, id string, size uint64) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - return _expandSandboxSize(info, _p0, size) -} - -func _expandSandboxSize(info *driverInfo, id *uint16, size uint64) (hr error) { - if hr = procExpandSandboxSize.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procExpandSandboxSize.Addr(), 3, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(size)) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func deactivateLayer(info *driverInfo, id string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - return _deactivateLayer(info, _p0) -} - -func _deactivateLayer(info *driverInfo, id *uint16) (hr error) { - if hr = procDeactivateLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procDeactivateLayer.Addr(), 2, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func destroyLayer(info *driverInfo, id string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - return _destroyLayer(info, _p0) -} - -func _destroyLayer(info *driverInfo, id *uint16) (hr error) { - if hr = procDestroyLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procDestroyLayer.Addr(), 2, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func exportLayer(info *driverInfo, id string, path string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(path) - if hr != nil { - return - } - return _exportLayer(info, _p0, _p1, descriptors) -} - -func _exportLayer(info *driverInfo, id *uint16, path *uint16, descriptors []WC_LAYER_DESCRIPTOR) (hr error) { - var _p2 *WC_LAYER_DESCRIPTOR - if len(descriptors) > 0 { - _p2 = &descriptors[0] - } - if hr = procExportLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procExportLayer.Addr(), 5, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(_p2)), uintptr(len(descriptors)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func getLayerMountPath(info *driverInfo, id string, length *uintptr, buffer *uint16) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - return _getLayerMountPath(info, _p0, length, buffer) -} - -func _getLayerMountPath(info *driverInfo, id *uint16, length *uintptr, buffer *uint16) (hr error) { - if hr = procGetLayerMountPath.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procGetLayerMountPath.Addr(), 4, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(length)), uintptr(unsafe.Pointer(buffer)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func getBaseImages(buffer **uint16) (hr error) { - if hr = procGetBaseImages.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procGetBaseImages.Addr(), 1, uintptr(unsafe.Pointer(buffer)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func importLayer(info *driverInfo, id string, path string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(path) - if hr != nil { - return - } - return _importLayer(info, _p0, _p1, descriptors) -} - -func _importLayer(info *driverInfo, id *uint16, path *uint16, descriptors []WC_LAYER_DESCRIPTOR) (hr error) { - var _p2 *WC_LAYER_DESCRIPTOR - if len(descriptors) > 0 { - _p2 = &descriptors[0] - } - if hr = procImportLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procImportLayer.Addr(), 5, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(_p2)), uintptr(len(descriptors)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func layerExists(info *driverInfo, id string, exists *uint32) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - return _layerExists(info, _p0, exists) -} - -func _layerExists(info *driverInfo, id *uint16, exists *uint32) (hr error) { - if hr = procLayerExists.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procLayerExists.Addr(), 3, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(exists))) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func nameToGuid(name string, guid *_guid) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(name) - if hr != nil { - return - } - return _nameToGuid(_p0, guid) -} - -func _nameToGuid(name *uint16, guid *_guid) (hr error) { - if hr = procNameToGuid.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procNameToGuid.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(guid)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func prepareLayer(info *driverInfo, id string, descriptors []WC_LAYER_DESCRIPTOR) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - return _prepareLayer(info, _p0, descriptors) -} - -func _prepareLayer(info *driverInfo, id *uint16, descriptors []WC_LAYER_DESCRIPTOR) (hr error) { - var _p1 *WC_LAYER_DESCRIPTOR - if len(descriptors) > 0 { - _p1 = &descriptors[0] - } - if hr = procPrepareLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall6(procPrepareLayer.Addr(), 4, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), uintptr(unsafe.Pointer(_p1)), uintptr(len(descriptors)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func unprepareLayer(info *driverInfo, id string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(id) - if hr != nil { - return - } - return _unprepareLayer(info, _p0) -} - -func _unprepareLayer(info *driverInfo, id *uint16) (hr error) { - if hr = procUnprepareLayer.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procUnprepareLayer.Addr(), 2, uintptr(unsafe.Pointer(info)), uintptr(unsafe.Pointer(id)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func processBaseImage(path string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(path) - if hr != nil { - return - } - return _processBaseImage(_p0) -} - -func _processBaseImage(path *uint16) (hr error) { - if hr = procProcessBaseImage.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procProcessBaseImage.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func processUtilityImage(path string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(path) - if hr != nil { - return - } - return _processUtilityImage(_p0) -} - -func _processUtilityImage(path *uint16) (hr error) { - if hr = procProcessUtilityImage.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procProcessUtilityImage.Addr(), 1, uintptr(unsafe.Pointer(path)), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func grantVmAccess(vmid string, filepath string) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(vmid) - if hr != nil { - return - } - var _p1 *uint16 - _p1, hr = syscall.UTF16PtrFromString(filepath) - if hr != nil { - return - } - return _grantVmAccess(_p0, _p1) -} - -func _grantVmAccess(vmid *uint16, filepath *uint16) (hr error) { - if hr = procGrantVmAccess.Find(); hr != nil { - return - } - r0, _, _ := syscall.Syscall(procGrantVmAccess.Addr(), 2, uintptr(unsafe.Pointer(vmid)), uintptr(unsafe.Pointer(filepath)), 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func openVirtualDisk(virtualStorageType *virtualStorageType, path string, virtualDiskAccessMask uint32, flags uint32, parameters *openVirtualDiskParameters, handle *syscall.Handle) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(path) - if err != nil { - return - } - return _openVirtualDisk(virtualStorageType, _p0, virtualDiskAccessMask, flags, parameters, handle) -} - -func _openVirtualDisk(virtualStorageType *virtualStorageType, path *uint16, virtualDiskAccessMask uint32, flags uint32, parameters *openVirtualDiskParameters, handle *syscall.Handle) (err error) { - r1, _, e1 := syscall.Syscall6(procOpenVirtualDisk.Addr(), 6, uintptr(unsafe.Pointer(virtualStorageType)), uintptr(unsafe.Pointer(path)), uintptr(virtualDiskAccessMask), uintptr(flags), uintptr(unsafe.Pointer(parameters)), uintptr(unsafe.Pointer(handle))) - if r1 != 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func attachVirtualDisk(handle syscall.Handle, sd uintptr, flags uint32, providerFlags uint32, params uintptr, overlapped uintptr) (err error) { - r1, _, e1 := syscall.Syscall6(procAttachVirtualDisk.Addr(), 6, uintptr(handle), uintptr(sd), uintptr(flags), uintptr(providerFlags), uintptr(params), uintptr(overlapped)) - if r1 != 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getDiskFreeSpaceEx(directoryName string, freeBytesAvailableToCaller *int64, totalNumberOfBytes *int64, totalNumberOfFreeBytes *int64) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(directoryName) - if err != nil { - return - } - return _getDiskFreeSpaceEx(_p0, freeBytesAvailableToCaller, totalNumberOfBytes, totalNumberOfFreeBytes) -} - -func _getDiskFreeSpaceEx(directoryName *uint16, freeBytesAvailableToCaller *int64, totalNumberOfBytes *int64, totalNumberOfFreeBytes *int64) (err error) { - r1, _, e1 := syscall.Syscall6(procGetDiskFreeSpaceExW.Addr(), 4, uintptr(unsafe.Pointer(directoryName)), uintptr(unsafe.Pointer(freeBytesAvailableToCaller)), uintptr(unsafe.Pointer(totalNumberOfBytes)), uintptr(unsafe.Pointer(totalNumberOfFreeBytes)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/devices.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/devices.go deleted file mode 100644 index df28ea24..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/devices.go +++ /dev/null @@ -1,13 +0,0 @@ -package winapi - -import "github.com/Microsoft/go-winio/pkg/guid" - -//sys CMGetDeviceIDListSize(pulLen *uint32, pszFilter *byte, uFlags uint32) (hr error) = cfgmgr32.CM_Get_Device_ID_List_SizeA -//sys CMGetDeviceIDList(pszFilter *byte, buffer *byte, bufferLen uint32, uFlags uint32) (hr error)= cfgmgr32.CM_Get_Device_ID_ListA -//sys CMLocateDevNode(pdnDevInst *uint32, pDeviceID string, uFlags uint32) (hr error) = cfgmgr32.CM_Locate_DevNodeW -//sys CMGetDevNodeProperty(dnDevInst uint32, propertyKey *DevPropKey, propertyType *uint32, propertyBuffer *uint16, propertyBufferSize *uint32, uFlags uint32) (hr error) = cfgmgr32.CM_Get_DevNode_PropertyW - -type DevPropKey struct { - Fmtid guid.GUID - Pid uint32 -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/errors.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/errors.go deleted file mode 100644 index 4e80ef68..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/errors.go +++ /dev/null @@ -1,15 +0,0 @@ -package winapi - -import "syscall" - -//sys RtlNtStatusToDosError(status uint32) (winerr error) = ntdll.RtlNtStatusToDosError - -const ( - STATUS_REPARSE_POINT_ENCOUNTERED = 0xC000050B - ERROR_NO_MORE_ITEMS = 0x103 - ERROR_MORE_DATA syscall.Errno = 234 -) - -func NTSuccess(status uint32) bool { - return status == 0 -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/filesystem.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/filesystem.go deleted file mode 100644 index 7ce52afd..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/filesystem.go +++ /dev/null @@ -1,110 +0,0 @@ -package winapi - -//sys NtCreateFile(handle *uintptr, accessMask uint32, oa *ObjectAttributes, iosb *IOStatusBlock, allocationSize *uint64, fileAttributes uint32, shareAccess uint32, createDisposition uint32, createOptions uint32, eaBuffer *byte, eaLength uint32) (status uint32) = ntdll.NtCreateFile -//sys NtSetInformationFile(handle uintptr, iosb *IOStatusBlock, information uintptr, length uint32, class uint32) (status uint32) = ntdll.NtSetInformationFile - -//sys NtOpenDirectoryObject(handle *uintptr, accessMask uint32, oa *ObjectAttributes) (status uint32) = ntdll.NtOpenDirectoryObject -//sys NtQueryDirectoryObject(handle uintptr, buffer *byte, length uint32, singleEntry bool, restartScan bool, context *uint32, returnLength *uint32)(status uint32) = ntdll.NtQueryDirectoryObject - -const ( - FileLinkInformationClass = 11 - FileDispositionInformationExClass = 64 - - FILE_READ_ATTRIBUTES = 0x0080 - FILE_WRITE_ATTRIBUTES = 0x0100 - DELETE = 0x10000 - - FILE_OPEN = 1 - FILE_CREATE = 2 - - FILE_LIST_DIRECTORY = 0x00000001 - FILE_DIRECTORY_FILE = 0x00000001 - FILE_SYNCHRONOUS_IO_NONALERT = 0x00000020 - FILE_OPEN_FOR_BACKUP_INTENT = 0x00004000 - FILE_OPEN_REPARSE_POINT = 0x00200000 - - FILE_DISPOSITION_DELETE = 0x00000001 - - OBJ_DONT_REPARSE = 0x1000 - - STATUS_MORE_ENTRIES = 0x105 - STATUS_NO_MORE_ENTRIES = 0x8000001a -) - -// Select entries from FILE_INFO_BY_HANDLE_CLASS. -// -// C declaration: -// typedef enum _FILE_INFO_BY_HANDLE_CLASS { -// FileBasicInfo, -// FileStandardInfo, -// FileNameInfo, -// FileRenameInfo, -// FileDispositionInfo, -// FileAllocationInfo, -// FileEndOfFileInfo, -// FileStreamInfo, -// FileCompressionInfo, -// FileAttributeTagInfo, -// FileIdBothDirectoryInfo, -// FileIdBothDirectoryRestartInfo, -// FileIoPriorityHintInfo, -// FileRemoteProtocolInfo, -// FileFullDirectoryInfo, -// FileFullDirectoryRestartInfo, -// FileStorageInfo, -// FileAlignmentInfo, -// FileIdInfo, -// FileIdExtdDirectoryInfo, -// FileIdExtdDirectoryRestartInfo, -// FileDispositionInfoEx, -// FileRenameInfoEx, -// FileCaseSensitiveInfo, -// FileNormalizedNameInfo, -// MaximumFileInfoByHandleClass -// } FILE_INFO_BY_HANDLE_CLASS, *PFILE_INFO_BY_HANDLE_CLASS; -// -// Documentation: https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ne-minwinbase-file_info_by_handle_class -const ( - FileIdInfo = 18 -) - -type FileDispositionInformationEx struct { - Flags uintptr -} - -type IOStatusBlock struct { - Status, Information uintptr -} - -type ObjectAttributes struct { - Length uintptr - RootDirectory uintptr - ObjectName *UnicodeString - Attributes uintptr - SecurityDescriptor uintptr - SecurityQoS uintptr -} - -type ObjectDirectoryInformation struct { - Name UnicodeString - TypeName UnicodeString -} - -type FileLinkInformation struct { - ReplaceIfExists bool - RootDirectory uintptr - FileNameLength uint32 - FileName [1]uint16 -} - -// C declaration: -// typedef struct _FILE_ID_INFO { -// ULONGLONG VolumeSerialNumber; -// FILE_ID_128 FileId; -// } FILE_ID_INFO, *PFILE_ID_INFO; -// -// Documentation: https://docs.microsoft.com/en-us/windows/win32/api/winbase/ns-winbase-file_id_info -type FILE_ID_INFO struct { - VolumeSerialNumber uint64 - FileID [16]byte -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/iocp.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/iocp.go deleted file mode 100644 index 4e609cbf..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/iocp.go +++ /dev/null @@ -1,3 +0,0 @@ -package winapi - -//sys GetQueuedCompletionStatus(cphandle windows.Handle, qty *uint32, key *uintptr, overlapped **windows.Overlapped, timeout uint32) (err error) diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/jobobject.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/jobobject.go deleted file mode 100644 index ba12b1ad..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/jobobject.go +++ /dev/null @@ -1,215 +0,0 @@ -package winapi - -import ( - "unsafe" - - "golang.org/x/sys/windows" -) - -// Messages that can be received from an assigned io completion port. -// https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_associate_completion_port -const ( - JOB_OBJECT_MSG_END_OF_JOB_TIME uint32 = 1 - JOB_OBJECT_MSG_END_OF_PROCESS_TIME uint32 = 2 - JOB_OBJECT_MSG_ACTIVE_PROCESS_LIMIT uint32 = 3 - JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO uint32 = 4 - JOB_OBJECT_MSG_NEW_PROCESS uint32 = 6 - JOB_OBJECT_MSG_EXIT_PROCESS uint32 = 7 - JOB_OBJECT_MSG_ABNORMAL_EXIT_PROCESS uint32 = 8 - JOB_OBJECT_MSG_PROCESS_MEMORY_LIMIT uint32 = 9 - JOB_OBJECT_MSG_JOB_MEMORY_LIMIT uint32 = 10 - JOB_OBJECT_MSG_NOTIFICATION_LIMIT uint32 = 11 -) - -// Access rights for creating or opening job objects. -// -// https://docs.microsoft.com/en-us/windows/win32/procthread/job-object-security-and-access-rights -const JOB_OBJECT_ALL_ACCESS = 0x1F001F - -// IO limit flags -// -// https://docs.microsoft.com/en-us/windows/win32/api/jobapi2/ns-jobapi2-jobobject_io_rate_control_information -const JOB_OBJECT_IO_RATE_CONTROL_ENABLE = 0x1 - -const JOBOBJECT_IO_ATTRIBUTION_CONTROL_ENABLE uint32 = 0x1 - -// https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_cpu_rate_control_information -const ( - JOB_OBJECT_CPU_RATE_CONTROL_ENABLE uint32 = 1 << iota - JOB_OBJECT_CPU_RATE_CONTROL_WEIGHT_BASED - JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP - JOB_OBJECT_CPU_RATE_CONTROL_NOTIFY - JOB_OBJECT_CPU_RATE_CONTROL_MIN_MAX_RATE -) - -// JobObjectInformationClass values. Used for a call to QueryInformationJobObject -// -// https://docs.microsoft.com/en-us/windows/win32/api/jobapi2/nf-jobapi2-queryinformationjobobject -const ( - JobObjectBasicAccountingInformation uint32 = 1 - JobObjectBasicProcessIdList uint32 = 3 - JobObjectBasicAndIoAccountingInformation uint32 = 8 - JobObjectLimitViolationInformation uint32 = 13 - JobObjectMemoryUsageInformation uint32 = 28 - JobObjectNotificationLimitInformation2 uint32 = 33 - JobObjectIoAttribution uint32 = 42 -) - -// https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_basic_limit_information -type JOBOBJECT_BASIC_LIMIT_INFORMATION struct { - PerProcessUserTimeLimit int64 - PerJobUserTimeLimit int64 - LimitFlags uint32 - MinimumWorkingSetSize uintptr - MaximumWorkingSetSize uintptr - ActiveProcessLimit uint32 - Affinity uintptr - PriorityClass uint32 - SchedulingClass uint32 -} - -// https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_cpu_rate_control_information -type JOBOBJECT_CPU_RATE_CONTROL_INFORMATION struct { - ControlFlags uint32 - Value uint32 -} - -// https://docs.microsoft.com/en-us/windows/win32/api/jobapi2/ns-jobapi2-jobobject_io_rate_control_information -type JOBOBJECT_IO_RATE_CONTROL_INFORMATION struct { - MaxIops int64 - MaxBandwidth int64 - ReservationIops int64 - BaseIOSize uint32 - VolumeName string - ControlFlags uint32 -} - -// https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_basic_process_id_list -type JOBOBJECT_BASIC_PROCESS_ID_LIST struct { - NumberOfAssignedProcesses uint32 - NumberOfProcessIdsInList uint32 - ProcessIdList [1]uintptr -} - -// AllPids returns all the process Ids in the job object. -func (p *JOBOBJECT_BASIC_PROCESS_ID_LIST) AllPids() []uintptr { - return (*[(1 << 27) - 1]uintptr)(unsafe.Pointer(&p.ProcessIdList[0]))[:p.NumberOfProcessIdsInList] -} - -// https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_basic_accounting_information -type JOBOBJECT_BASIC_ACCOUNTING_INFORMATION struct { - TotalUserTime int64 - TotalKernelTime int64 - ThisPeriodTotalUserTime int64 - ThisPeriodTotalKernelTime int64 - TotalPageFaultCount uint32 - TotalProcesses uint32 - ActiveProcesses uint32 - TotalTerminateProcesses uint32 -} - -//https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_basic_and_io_accounting_information -type JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION struct { - BasicInfo JOBOBJECT_BASIC_ACCOUNTING_INFORMATION - IoInfo windows.IO_COUNTERS -} - -// typedef struct _JOBOBJECT_MEMORY_USAGE_INFORMATION { -// ULONG64 JobMemory; -// ULONG64 PeakJobMemoryUsed; -// } JOBOBJECT_MEMORY_USAGE_INFORMATION, *PJOBOBJECT_MEMORY_USAGE_INFORMATION; -// -type JOBOBJECT_MEMORY_USAGE_INFORMATION struct { - JobMemory uint64 - PeakJobMemoryUsed uint64 -} - -// typedef struct _JOBOBJECT_IO_ATTRIBUTION_STATS { -// ULONG_PTR IoCount; -// ULONGLONG TotalNonOverlappedQueueTime; -// ULONGLONG TotalNonOverlappedServiceTime; -// ULONGLONG TotalSize; -// } JOBOBJECT_IO_ATTRIBUTION_STATS, *PJOBOBJECT_IO_ATTRIBUTION_STATS; -// -type JOBOBJECT_IO_ATTRIBUTION_STATS struct { - IoCount uintptr - TotalNonOverlappedQueueTime uint64 - TotalNonOverlappedServiceTime uint64 - TotalSize uint64 -} - -// typedef struct _JOBOBJECT_IO_ATTRIBUTION_INFORMATION { -// ULONG ControlFlags; -// JOBOBJECT_IO_ATTRIBUTION_STATS ReadStats; -// JOBOBJECT_IO_ATTRIBUTION_STATS WriteStats; -// } JOBOBJECT_IO_ATTRIBUTION_INFORMATION, *PJOBOBJECT_IO_ATTRIBUTION_INFORMATION; -// -type JOBOBJECT_IO_ATTRIBUTION_INFORMATION struct { - ControlFlags uint32 - ReadStats JOBOBJECT_IO_ATTRIBUTION_STATS - WriteStats JOBOBJECT_IO_ATTRIBUTION_STATS -} - -// https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_associate_completion_port -type JOBOBJECT_ASSOCIATE_COMPLETION_PORT struct { - CompletionKey windows.Handle - CompletionPort windows.Handle -} - -// BOOL IsProcessInJob( -// HANDLE ProcessHandle, -// HANDLE JobHandle, -// PBOOL Result -// ); -// -//sys IsProcessInJob(procHandle windows.Handle, jobHandle windows.Handle, result *bool) (err error) = kernel32.IsProcessInJob - -// BOOL QueryInformationJobObject( -// HANDLE hJob, -// JOBOBJECTINFOCLASS JobObjectInformationClass, -// LPVOID lpJobObjectInformation, -// DWORD cbJobObjectInformationLength, -// LPDWORD lpReturnLength -// ); -// -//sys QueryInformationJobObject(jobHandle windows.Handle, infoClass uint32, jobObjectInfo uintptr, jobObjectInformationLength uint32, lpReturnLength *uint32) (err error) = kernel32.QueryInformationJobObject - -// HANDLE OpenJobObjectW( -// DWORD dwDesiredAccess, -// BOOL bInheritHandle, -// LPCWSTR lpName -// ); -// -//sys OpenJobObject(desiredAccess uint32, inheritHandle bool, lpName *uint16) (handle windows.Handle, err error) = kernel32.OpenJobObjectW - -// DWORD SetIoRateControlInformationJobObject( -// HANDLE hJob, -// JOBOBJECT_IO_RATE_CONTROL_INFORMATION *IoRateControlInfo -// ); -// -//sys SetIoRateControlInformationJobObject(jobHandle windows.Handle, ioRateControlInfo *JOBOBJECT_IO_RATE_CONTROL_INFORMATION) (ret uint32, err error) = kernel32.SetIoRateControlInformationJobObject - -// DWORD QueryIoRateControlInformationJobObject( -// HANDLE hJob, -// PCWSTR VolumeName, -// JOBOBJECT_IO_RATE_CONTROL_INFORMATION **InfoBlocks, -// ULONG *InfoBlockCount -// ); -//sys QueryIoRateControlInformationJobObject(jobHandle windows.Handle, volumeName *uint16, ioRateControlInfo **JOBOBJECT_IO_RATE_CONTROL_INFORMATION, infoBlockCount *uint32) (ret uint32, err error) = kernel32.QueryIoRateControlInformationJobObject - -// NTSTATUS -// NtOpenJobObject ( -// _Out_ PHANDLE JobHandle, -// _In_ ACCESS_MASK DesiredAccess, -// _In_ POBJECT_ATTRIBUTES ObjectAttributes -// ); -//sys NtOpenJobObject(jobHandle *windows.Handle, desiredAccess uint32, objAttributes *ObjectAttributes) (status uint32) = ntdll.NtOpenJobObject - -// NTSTATUS -// NTAPI -// NtCreateJobObject ( -// _Out_ PHANDLE JobHandle, -// _In_ ACCESS_MASK DesiredAccess, -// _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes -// ); -//sys NtCreateJobObject(jobHandle *windows.Handle, desiredAccess uint32, objAttributes *ObjectAttributes) (status uint32) = ntdll.NtCreateJobObject diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/logon.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/logon.go deleted file mode 100644 index b6e7cfd4..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/logon.go +++ /dev/null @@ -1,30 +0,0 @@ -package winapi - -// BOOL LogonUserA( -// LPCWSTR lpszUsername, -// LPCWSTR lpszDomain, -// LPCWSTR lpszPassword, -// DWORD dwLogonType, -// DWORD dwLogonProvider, -// PHANDLE phToken -// ); -// -//sys LogonUser(username *uint16, domain *uint16, password *uint16, logonType uint32, logonProvider uint32, token *windows.Token) (err error) = advapi32.LogonUserW - -// Logon types -const ( - LOGON32_LOGON_INTERACTIVE uint32 = 2 - LOGON32_LOGON_NETWORK uint32 = 3 - LOGON32_LOGON_BATCH uint32 = 4 - LOGON32_LOGON_SERVICE uint32 = 5 - LOGON32_LOGON_UNLOCK uint32 = 7 - LOGON32_LOGON_NETWORK_CLEARTEXT uint32 = 8 - LOGON32_LOGON_NEW_CREDENTIALS uint32 = 9 -) - -// Logon providers -const ( - LOGON32_PROVIDER_DEFAULT uint32 = 0 - LOGON32_PROVIDER_WINNT40 uint32 = 2 - LOGON32_PROVIDER_WINNT50 uint32 = 3 -) diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/memory.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/memory.go deleted file mode 100644 index ccaf5a62..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/memory.go +++ /dev/null @@ -1,11 +0,0 @@ -package winapi - -// VOID RtlMoveMemory( -// _Out_ VOID UNALIGNED *Destination, -// _In_ const VOID UNALIGNED *Source, -// _In_ SIZE_T Length -// ); -//sys RtlMoveMemory(destination *byte, source *byte, length uintptr) (err error) = kernel32.RtlMoveMemory - -//sys LocalAlloc(flags uint32, size int) (ptr uintptr) = kernel32.LocalAlloc -//sys LocalFree(ptr uintptr) = kernel32.LocalFree diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/net.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/net.go deleted file mode 100644 index f3791002..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/net.go +++ /dev/null @@ -1,3 +0,0 @@ -package winapi - -//sys SetJobCompartmentId(handle windows.Handle, compartmentId uint32) (win32Err error) = iphlpapi.SetJobCompartmentId diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/path.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/path.go deleted file mode 100644 index 0ae8f33e..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/path.go +++ /dev/null @@ -1,11 +0,0 @@ -package winapi - -// DWORD SearchPathW( -// LPCWSTR lpPath, -// LPCWSTR lpFileName, -// LPCWSTR lpExtension, -// DWORD nBufferLength, -// LPWSTR lpBuffer, -// LPWSTR *lpFilePart -// ); -//sys SearchPath(lpPath *uint16, lpFileName *uint16, lpExtension *uint16, nBufferLength uint32, lpBuffer *uint16, lpFilePath **uint16) (size uint32, err error) = kernel32.SearchPathW diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/process.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/process.go deleted file mode 100644 index adf0168e..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/process.go +++ /dev/null @@ -1,3 +0,0 @@ -package winapi - -const PROCESS_ALL_ACCESS uint32 = 2097151 diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/processor.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/processor.go deleted file mode 100644 index ce79ac2c..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/processor.go +++ /dev/null @@ -1,7 +0,0 @@ -package winapi - -// Get count from all processor groups. -// https://docs.microsoft.com/en-us/windows/win32/procthread/processor-groups -const ALL_PROCESSOR_GROUPS = 0xFFFF - -//sys GetActiveProcessorCount(groupNumber uint16) (amount uint32) = kernel32.GetActiveProcessorCount diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/utils.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/utils.go deleted file mode 100644 index db59567d..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/utils.go +++ /dev/null @@ -1,75 +0,0 @@ -package winapi - -import ( - "errors" - "reflect" - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -// Uint16BufferToSlice wraps a uint16 pointer-and-length into a slice -// for easier interop with Go APIs -func Uint16BufferToSlice(buffer *uint16, bufferLength int) (result []uint16) { - hdr := (*reflect.SliceHeader)(unsafe.Pointer(&result)) - hdr.Data = uintptr(unsafe.Pointer(buffer)) - hdr.Cap = bufferLength - hdr.Len = bufferLength - - return -} - -type UnicodeString struct { - Length uint16 - MaximumLength uint16 - Buffer *uint16 -} - -//String converts a UnicodeString to a golang string -func (uni UnicodeString) String() string { - // UnicodeString is not guaranteed to be null terminated, therefore - // use the UnicodeString's Length field - return syscall.UTF16ToString(Uint16BufferToSlice(uni.Buffer, int(uni.Length/2))) -} - -// NewUnicodeString allocates a new UnicodeString and copies `s` into -// the buffer of the new UnicodeString. -func NewUnicodeString(s string) (*UnicodeString, error) { - // Get length of original `s` to use in the UnicodeString since the `buf` - // created later will have an additional trailing null character - length := len(s) - if length > 32767 { - return nil, syscall.ENAMETOOLONG - } - - buf, err := windows.UTF16FromString(s) - if err != nil { - return nil, err - } - uni := &UnicodeString{ - Length: uint16(length * 2), - MaximumLength: uint16(length * 2), - Buffer: &buf[0], - } - return uni, nil -} - -// ConvertStringSetToSlice is a helper function used to convert the contents of -// `buf` into a string slice. `buf` contains a set of null terminated strings -// with an additional null at the end to indicate the end of the set. -func ConvertStringSetToSlice(buf []byte) ([]string, error) { - var results []string - prev := 0 - for i := range buf { - if buf[i] == 0 { - if prev == i { - // found two null characters in a row, return result - return results, nil - } - results = append(results, string(buf[prev:i])) - prev = i + 1 - } - } - return nil, errors.New("string set malformed: missing null terminator at end of buffer") -} diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/winapi.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/winapi.go deleted file mode 100644 index 77ea13e3..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/winapi.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package winapi contains various low-level bindings to Windows APIs. It can -// be thought of as an extension to golang.org/x/sys/windows. -package winapi - -//go:generate go run ..\..\mksyscall_windows.go -output zsyscall_windows.go net.go iocp.go jobobject.go path.go logon.go memory.go processor.go devices.go filesystem.go errors.go diff --git a/vendor/github.com/Microsoft/hcsshim/internal/winapi/zsyscall_windows.go b/vendor/github.com/Microsoft/hcsshim/internal/winapi/zsyscall_windows.go deleted file mode 100644 index 3a54c1fa..00000000 --- a/vendor/github.com/Microsoft/hcsshim/internal/winapi/zsyscall_windows.go +++ /dev/null @@ -1,322 +0,0 @@ -// Code generated mksyscall_windows.exe DO NOT EDIT - -package winapi - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return nil - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modiphlpapi = windows.NewLazySystemDLL("iphlpapi.dll") - modkernel32 = windows.NewLazySystemDLL("kernel32.dll") - modntdll = windows.NewLazySystemDLL("ntdll.dll") - modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") - modcfgmgr32 = windows.NewLazySystemDLL("cfgmgr32.dll") - - procSetJobCompartmentId = modiphlpapi.NewProc("SetJobCompartmentId") - procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus") - procIsProcessInJob = modkernel32.NewProc("IsProcessInJob") - procQueryInformationJobObject = modkernel32.NewProc("QueryInformationJobObject") - procOpenJobObjectW = modkernel32.NewProc("OpenJobObjectW") - procSetIoRateControlInformationJobObject = modkernel32.NewProc("SetIoRateControlInformationJobObject") - procQueryIoRateControlInformationJobObject = modkernel32.NewProc("QueryIoRateControlInformationJobObject") - procNtOpenJobObject = modntdll.NewProc("NtOpenJobObject") - procNtCreateJobObject = modntdll.NewProc("NtCreateJobObject") - procSearchPathW = modkernel32.NewProc("SearchPathW") - procLogonUserW = modadvapi32.NewProc("LogonUserW") - procRtlMoveMemory = modkernel32.NewProc("RtlMoveMemory") - procLocalAlloc = modkernel32.NewProc("LocalAlloc") - procLocalFree = modkernel32.NewProc("LocalFree") - procGetActiveProcessorCount = modkernel32.NewProc("GetActiveProcessorCount") - procCM_Get_Device_ID_List_SizeA = modcfgmgr32.NewProc("CM_Get_Device_ID_List_SizeA") - procCM_Get_Device_ID_ListA = modcfgmgr32.NewProc("CM_Get_Device_ID_ListA") - procCM_Locate_DevNodeW = modcfgmgr32.NewProc("CM_Locate_DevNodeW") - procCM_Get_DevNode_PropertyW = modcfgmgr32.NewProc("CM_Get_DevNode_PropertyW") - procNtCreateFile = modntdll.NewProc("NtCreateFile") - procNtSetInformationFile = modntdll.NewProc("NtSetInformationFile") - procNtOpenDirectoryObject = modntdll.NewProc("NtOpenDirectoryObject") - procNtQueryDirectoryObject = modntdll.NewProc("NtQueryDirectoryObject") - procRtlNtStatusToDosError = modntdll.NewProc("RtlNtStatusToDosError") -) - -func SetJobCompartmentId(handle windows.Handle, compartmentId uint32) (win32Err error) { - r0, _, _ := syscall.Syscall(procSetJobCompartmentId.Addr(), 2, uintptr(handle), uintptr(compartmentId), 0) - if r0 != 0 { - win32Err = syscall.Errno(r0) - } - return -} - -func GetQueuedCompletionStatus(cphandle windows.Handle, qty *uint32, key *uintptr, overlapped **windows.Overlapped, timeout uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetQueuedCompletionStatus.Addr(), 5, uintptr(cphandle), uintptr(unsafe.Pointer(qty)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(overlapped)), uintptr(timeout), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func IsProcessInJob(procHandle windows.Handle, jobHandle windows.Handle, result *bool) (err error) { - r1, _, e1 := syscall.Syscall(procIsProcessInJob.Addr(), 3, uintptr(procHandle), uintptr(jobHandle), uintptr(unsafe.Pointer(result))) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func QueryInformationJobObject(jobHandle windows.Handle, infoClass uint32, jobObjectInfo uintptr, jobObjectInformationLength uint32, lpReturnLength *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procQueryInformationJobObject.Addr(), 5, uintptr(jobHandle), uintptr(infoClass), uintptr(jobObjectInfo), uintptr(jobObjectInformationLength), uintptr(unsafe.Pointer(lpReturnLength)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func OpenJobObject(desiredAccess uint32, inheritHandle bool, lpName *uint16) (handle windows.Handle, err error) { - var _p0 uint32 - if inheritHandle { - _p0 = 1 - } else { - _p0 = 0 - } - r0, _, e1 := syscall.Syscall(procOpenJobObjectW.Addr(), 3, uintptr(desiredAccess), uintptr(_p0), uintptr(unsafe.Pointer(lpName))) - handle = windows.Handle(r0) - if handle == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func SetIoRateControlInformationJobObject(jobHandle windows.Handle, ioRateControlInfo *JOBOBJECT_IO_RATE_CONTROL_INFORMATION) (ret uint32, err error) { - r0, _, e1 := syscall.Syscall(procSetIoRateControlInformationJobObject.Addr(), 2, uintptr(jobHandle), uintptr(unsafe.Pointer(ioRateControlInfo)), 0) - ret = uint32(r0) - if ret == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func QueryIoRateControlInformationJobObject(jobHandle windows.Handle, volumeName *uint16, ioRateControlInfo **JOBOBJECT_IO_RATE_CONTROL_INFORMATION, infoBlockCount *uint32) (ret uint32, err error) { - r0, _, e1 := syscall.Syscall6(procQueryIoRateControlInformationJobObject.Addr(), 4, uintptr(jobHandle), uintptr(unsafe.Pointer(volumeName)), uintptr(unsafe.Pointer(ioRateControlInfo)), uintptr(unsafe.Pointer(infoBlockCount)), 0, 0) - ret = uint32(r0) - if ret == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func NtOpenJobObject(jobHandle *windows.Handle, desiredAccess uint32, objAttributes *ObjectAttributes) (status uint32) { - r0, _, _ := syscall.Syscall(procNtOpenJobObject.Addr(), 3, uintptr(unsafe.Pointer(jobHandle)), uintptr(desiredAccess), uintptr(unsafe.Pointer(objAttributes))) - status = uint32(r0) - return -} - -func NtCreateJobObject(jobHandle *windows.Handle, desiredAccess uint32, objAttributes *ObjectAttributes) (status uint32) { - r0, _, _ := syscall.Syscall(procNtCreateJobObject.Addr(), 3, uintptr(unsafe.Pointer(jobHandle)), uintptr(desiredAccess), uintptr(unsafe.Pointer(objAttributes))) - status = uint32(r0) - return -} - -func SearchPath(lpPath *uint16, lpFileName *uint16, lpExtension *uint16, nBufferLength uint32, lpBuffer *uint16, lpFilePath **uint16) (size uint32, err error) { - r0, _, e1 := syscall.Syscall6(procSearchPathW.Addr(), 6, uintptr(unsafe.Pointer(lpPath)), uintptr(unsafe.Pointer(lpFileName)), uintptr(unsafe.Pointer(lpExtension)), uintptr(nBufferLength), uintptr(unsafe.Pointer(lpBuffer)), uintptr(unsafe.Pointer(lpFilePath))) - size = uint32(r0) - if size == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func LogonUser(username *uint16, domain *uint16, password *uint16, logonType uint32, logonProvider uint32, token *windows.Token) (err error) { - r1, _, e1 := syscall.Syscall6(procLogonUserW.Addr(), 6, uintptr(unsafe.Pointer(username)), uintptr(unsafe.Pointer(domain)), uintptr(unsafe.Pointer(password)), uintptr(logonType), uintptr(logonProvider), uintptr(unsafe.Pointer(token))) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func RtlMoveMemory(destination *byte, source *byte, length uintptr) (err error) { - r1, _, e1 := syscall.Syscall(procRtlMoveMemory.Addr(), 3, uintptr(unsafe.Pointer(destination)), uintptr(unsafe.Pointer(source)), uintptr(length)) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func LocalAlloc(flags uint32, size int) (ptr uintptr) { - r0, _, _ := syscall.Syscall(procLocalAlloc.Addr(), 2, uintptr(flags), uintptr(size), 0) - ptr = uintptr(r0) - return -} - -func LocalFree(ptr uintptr) { - syscall.Syscall(procLocalFree.Addr(), 1, uintptr(ptr), 0, 0) - return -} - -func GetActiveProcessorCount(groupNumber uint16) (amount uint32) { - r0, _, _ := syscall.Syscall(procGetActiveProcessorCount.Addr(), 1, uintptr(groupNumber), 0, 0) - amount = uint32(r0) - return -} - -func CMGetDeviceIDListSize(pulLen *uint32, pszFilter *byte, uFlags uint32) (hr error) { - r0, _, _ := syscall.Syscall(procCM_Get_Device_ID_List_SizeA.Addr(), 3, uintptr(unsafe.Pointer(pulLen)), uintptr(unsafe.Pointer(pszFilter)), uintptr(uFlags)) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func CMGetDeviceIDList(pszFilter *byte, buffer *byte, bufferLen uint32, uFlags uint32) (hr error) { - r0, _, _ := syscall.Syscall6(procCM_Get_Device_ID_ListA.Addr(), 4, uintptr(unsafe.Pointer(pszFilter)), uintptr(unsafe.Pointer(buffer)), uintptr(bufferLen), uintptr(uFlags), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func CMLocateDevNode(pdnDevInst *uint32, pDeviceID string, uFlags uint32) (hr error) { - var _p0 *uint16 - _p0, hr = syscall.UTF16PtrFromString(pDeviceID) - if hr != nil { - return - } - return _CMLocateDevNode(pdnDevInst, _p0, uFlags) -} - -func _CMLocateDevNode(pdnDevInst *uint32, pDeviceID *uint16, uFlags uint32) (hr error) { - r0, _, _ := syscall.Syscall(procCM_Locate_DevNodeW.Addr(), 3, uintptr(unsafe.Pointer(pdnDevInst)), uintptr(unsafe.Pointer(pDeviceID)), uintptr(uFlags)) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func CMGetDevNodeProperty(dnDevInst uint32, propertyKey *DevPropKey, propertyType *uint32, propertyBuffer *uint16, propertyBufferSize *uint32, uFlags uint32) (hr error) { - r0, _, _ := syscall.Syscall6(procCM_Get_DevNode_PropertyW.Addr(), 6, uintptr(dnDevInst), uintptr(unsafe.Pointer(propertyKey)), uintptr(unsafe.Pointer(propertyType)), uintptr(unsafe.Pointer(propertyBuffer)), uintptr(unsafe.Pointer(propertyBufferSize)), uintptr(uFlags)) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} - -func NtCreateFile(handle *uintptr, accessMask uint32, oa *ObjectAttributes, iosb *IOStatusBlock, allocationSize *uint64, fileAttributes uint32, shareAccess uint32, createDisposition uint32, createOptions uint32, eaBuffer *byte, eaLength uint32) (status uint32) { - r0, _, _ := syscall.Syscall12(procNtCreateFile.Addr(), 11, uintptr(unsafe.Pointer(handle)), uintptr(accessMask), uintptr(unsafe.Pointer(oa)), uintptr(unsafe.Pointer(iosb)), uintptr(unsafe.Pointer(allocationSize)), uintptr(fileAttributes), uintptr(shareAccess), uintptr(createDisposition), uintptr(createOptions), uintptr(unsafe.Pointer(eaBuffer)), uintptr(eaLength), 0) - status = uint32(r0) - return -} - -func NtSetInformationFile(handle uintptr, iosb *IOStatusBlock, information uintptr, length uint32, class uint32) (status uint32) { - r0, _, _ := syscall.Syscall6(procNtSetInformationFile.Addr(), 5, uintptr(handle), uintptr(unsafe.Pointer(iosb)), uintptr(information), uintptr(length), uintptr(class), 0) - status = uint32(r0) - return -} - -func NtOpenDirectoryObject(handle *uintptr, accessMask uint32, oa *ObjectAttributes) (status uint32) { - r0, _, _ := syscall.Syscall(procNtOpenDirectoryObject.Addr(), 3, uintptr(unsafe.Pointer(handle)), uintptr(accessMask), uintptr(unsafe.Pointer(oa))) - status = uint32(r0) - return -} - -func NtQueryDirectoryObject(handle uintptr, buffer *byte, length uint32, singleEntry bool, restartScan bool, context *uint32, returnLength *uint32) (status uint32) { - var _p0 uint32 - if singleEntry { - _p0 = 1 - } else { - _p0 = 0 - } - var _p1 uint32 - if restartScan { - _p1 = 1 - } else { - _p1 = 0 - } - r0, _, _ := syscall.Syscall9(procNtQueryDirectoryObject.Addr(), 7, uintptr(handle), uintptr(unsafe.Pointer(buffer)), uintptr(length), uintptr(_p0), uintptr(_p1), uintptr(unsafe.Pointer(context)), uintptr(unsafe.Pointer(returnLength)), 0, 0) - status = uint32(r0) - return -} - -func RtlNtStatusToDosError(status uint32) (winerr error) { - r0, _, _ := syscall.Syscall(procRtlNtStatusToDosError.Addr(), 1, uintptr(status), 0, 0) - if r0 != 0 { - winerr = syscall.Errno(r0) - } - return -} diff --git a/vendor/github.com/Microsoft/hcsshim/layer.go b/vendor/github.com/Microsoft/hcsshim/layer.go deleted file mode 100644 index 89161637..00000000 --- a/vendor/github.com/Microsoft/hcsshim/layer.go +++ /dev/null @@ -1,107 +0,0 @@ -package hcsshim - -import ( - "context" - "crypto/sha1" - "path/filepath" - - "github.com/Microsoft/go-winio/pkg/guid" - "github.com/Microsoft/hcsshim/internal/wclayer" -) - -func layerPath(info *DriverInfo, id string) string { - return filepath.Join(info.HomeDir, id) -} - -func ActivateLayer(info DriverInfo, id string) error { - return wclayer.ActivateLayer(context.Background(), layerPath(&info, id)) -} -func CreateLayer(info DriverInfo, id, parent string) error { - return wclayer.CreateLayer(context.Background(), layerPath(&info, id), parent) -} - -// New clients should use CreateScratchLayer instead. Kept in to preserve API compatibility. -func CreateSandboxLayer(info DriverInfo, layerId, parentId string, parentLayerPaths []string) error { - return wclayer.CreateScratchLayer(context.Background(), layerPath(&info, layerId), parentLayerPaths) -} -func CreateScratchLayer(info DriverInfo, layerId, parentId string, parentLayerPaths []string) error { - return wclayer.CreateScratchLayer(context.Background(), layerPath(&info, layerId), parentLayerPaths) -} -func DeactivateLayer(info DriverInfo, id string) error { - return wclayer.DeactivateLayer(context.Background(), layerPath(&info, id)) -} -func DestroyLayer(info DriverInfo, id string) error { - return wclayer.DestroyLayer(context.Background(), layerPath(&info, id)) -} - -// New clients should use ExpandScratchSize instead. Kept in to preserve API compatibility. -func ExpandSandboxSize(info DriverInfo, layerId string, size uint64) error { - return wclayer.ExpandScratchSize(context.Background(), layerPath(&info, layerId), size) -} -func ExpandScratchSize(info DriverInfo, layerId string, size uint64) error { - return wclayer.ExpandScratchSize(context.Background(), layerPath(&info, layerId), size) -} -func ExportLayer(info DriverInfo, layerId string, exportFolderPath string, parentLayerPaths []string) error { - return wclayer.ExportLayer(context.Background(), layerPath(&info, layerId), exportFolderPath, parentLayerPaths) -} -func GetLayerMountPath(info DriverInfo, id string) (string, error) { - return wclayer.GetLayerMountPath(context.Background(), layerPath(&info, id)) -} -func GetSharedBaseImages() (imageData string, err error) { - return wclayer.GetSharedBaseImages(context.Background()) -} -func ImportLayer(info DriverInfo, layerID string, importFolderPath string, parentLayerPaths []string) error { - return wclayer.ImportLayer(context.Background(), layerPath(&info, layerID), importFolderPath, parentLayerPaths) -} -func LayerExists(info DriverInfo, id string) (bool, error) { - return wclayer.LayerExists(context.Background(), layerPath(&info, id)) -} -func PrepareLayer(info DriverInfo, layerId string, parentLayerPaths []string) error { - return wclayer.PrepareLayer(context.Background(), layerPath(&info, layerId), parentLayerPaths) -} -func ProcessBaseLayer(path string) error { - return wclayer.ProcessBaseLayer(context.Background(), path) -} -func ProcessUtilityVMImage(path string) error { - return wclayer.ProcessUtilityVMImage(context.Background(), path) -} -func UnprepareLayer(info DriverInfo, layerId string) error { - return wclayer.UnprepareLayer(context.Background(), layerPath(&info, layerId)) -} - -type DriverInfo struct { - Flavour int - HomeDir string -} - -type GUID [16]byte - -func NameToGuid(name string) (id GUID, err error) { - g, err := wclayer.NameToGuid(context.Background(), name) - return g.ToWindowsArray(), err -} - -func NewGUID(source string) *GUID { - h := sha1.Sum([]byte(source)) - var g GUID - copy(g[0:], h[0:16]) - return &g -} - -func (g *GUID) ToString() string { - return guid.FromWindowsArray(*g).String() -} - -type LayerReader = wclayer.LayerReader - -func NewLayerReader(info DriverInfo, layerID string, parentLayerPaths []string) (LayerReader, error) { - return wclayer.NewLayerReader(context.Background(), layerPath(&info, layerID), parentLayerPaths) -} - -type LayerWriter = wclayer.LayerWriter - -func NewLayerWriter(info DriverInfo, layerID string, parentLayerPaths []string) (LayerWriter, error) { - return wclayer.NewLayerWriter(context.Background(), layerPath(&info, layerID), parentLayerPaths) -} - -type WC_LAYER_DESCRIPTOR = wclayer.WC_LAYER_DESCRIPTOR diff --git a/vendor/github.com/Microsoft/hcsshim/osversion/osversion_windows.go b/vendor/github.com/Microsoft/hcsshim/osversion/osversion_windows.go deleted file mode 100644 index 477fe707..00000000 --- a/vendor/github.com/Microsoft/hcsshim/osversion/osversion_windows.go +++ /dev/null @@ -1,57 +0,0 @@ -package osversion - -import ( - "fmt" - - "golang.org/x/sys/windows" -) - -// OSVersion is a wrapper for Windows version information -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx -type OSVersion struct { - Version uint32 - MajorVersion uint8 - MinorVersion uint8 - Build uint16 -} - -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx -type osVersionInfoEx struct { - OSVersionInfoSize uint32 - MajorVersion uint32 - MinorVersion uint32 - BuildNumber uint32 - PlatformID uint32 - CSDVersion [128]uint16 - ServicePackMajor uint16 - ServicePackMinor uint16 - SuiteMask uint16 - ProductType byte - Reserve byte -} - -// Get gets the operating system version on Windows. -// The calling application must be manifested to get the correct version information. -func Get() OSVersion { - var err error - osv := OSVersion{} - osv.Version, err = windows.GetVersion() - if err != nil { - // GetVersion never fails. - panic(err) - } - osv.MajorVersion = uint8(osv.Version & 0xFF) - osv.MinorVersion = uint8(osv.Version >> 8 & 0xFF) - osv.Build = uint16(osv.Version >> 16) - return osv -} - -// Build gets the build-number on Windows -// The calling application must be manifested to get the correct version information. -func Build() uint16 { - return Get().Build -} - -func (osv OSVersion) ToString() string { - return fmt.Sprintf("%d.%d.%d", osv.MajorVersion, osv.MinorVersion, osv.Build) -} diff --git a/vendor/github.com/Microsoft/hcsshim/osversion/windowsbuilds.go b/vendor/github.com/Microsoft/hcsshim/osversion/windowsbuilds.go deleted file mode 100644 index e9267b95..00000000 --- a/vendor/github.com/Microsoft/hcsshim/osversion/windowsbuilds.go +++ /dev/null @@ -1,38 +0,0 @@ -package osversion - -const ( - // RS1 (version 1607, codename "Redstone 1") corresponds to Windows Server - // 2016 (ltsc2016) and Windows 10 (Anniversary Update). - RS1 = 14393 - - // RS2 (version 1703, codename "Redstone 2") was a client-only update, and - // corresponds to Windows 10 (Creators Update). - RS2 = 15063 - - // RS3 (version 1709, codename "Redstone 3") corresponds to Windows Server - // 1709 (Semi-Annual Channel (SAC)), and Windows 10 (Fall Creators Update). - RS3 = 16299 - - // RS4 (version 1803, codename "Redstone 4") corresponds to Windows Server - // 1803 (Semi-Annual Channel (SAC)), and Windows 10 (April 2018 Update). - RS4 = 17134 - - // RS5 (version 1809, codename "Redstone 5") corresponds to Windows Server - // 2019 (ltsc2019), and Windows 10 (October 2018 Update). - RS5 = 17763 - - // V19H1 (version 1903) corresponds to Windows Server 1903 (semi-annual - // channel). - V19H1 = 18362 - - // V19H2 (version 1909) corresponds to Windows Server 1909 (semi-annual - // channel). - V19H2 = 18363 - - // V20H1 (version 2004) corresponds to Windows Server 2004 (semi-annual - // channel). - V20H1 = 19041 - - // V20H2 corresponds to Windows Server 20H2 (semi-annual channel). - V20H2 = 19042 -) diff --git a/vendor/github.com/Microsoft/hcsshim/process.go b/vendor/github.com/Microsoft/hcsshim/process.go deleted file mode 100644 index 3362c683..00000000 --- a/vendor/github.com/Microsoft/hcsshim/process.go +++ /dev/null @@ -1,98 +0,0 @@ -package hcsshim - -import ( - "context" - "io" - "sync" - "time" - - "github.com/Microsoft/hcsshim/internal/hcs" -) - -// ContainerError is an error encountered in HCS -type process struct { - p *hcs.Process - waitOnce sync.Once - waitCh chan struct{} - waitErr error -} - -// Pid returns the process ID of the process within the container. -func (process *process) Pid() int { - return process.p.Pid() -} - -// Kill signals the process to terminate but does not wait for it to finish terminating. -func (process *process) Kill() error { - found, err := process.p.Kill(context.Background()) - if err != nil { - return convertProcessError(err, process) - } - if !found { - return &ProcessError{Process: process, Err: ErrElementNotFound, Operation: "hcsshim::Process::Kill"} - } - return nil -} - -// Wait waits for the process to exit. -func (process *process) Wait() error { - return convertProcessError(process.p.Wait(), process) -} - -// WaitTimeout waits for the process to exit or the duration to elapse. It returns -// false if timeout occurs. -func (process *process) WaitTimeout(timeout time.Duration) error { - process.waitOnce.Do(func() { - process.waitCh = make(chan struct{}) - go func() { - process.waitErr = process.Wait() - close(process.waitCh) - }() - }) - t := time.NewTimer(timeout) - defer t.Stop() - select { - case <-t.C: - return &ProcessError{Process: process, Err: ErrTimeout, Operation: "hcsshim::Process::Wait"} - case <-process.waitCh: - return process.waitErr - } -} - -// ExitCode returns the exit code of the process. The process must have -// already terminated. -func (process *process) ExitCode() (int, error) { - code, err := process.p.ExitCode() - if err != nil { - err = convertProcessError(err, process) - } - return code, err -} - -// ResizeConsole resizes the console of the process. -func (process *process) ResizeConsole(width, height uint16) error { - return convertProcessError(process.p.ResizeConsole(context.Background(), width, height), process) -} - -// Stdio returns the stdin, stdout, and stderr pipes, respectively. Closing -// these pipes does not close the underlying pipes; it should be possible to -// call this multiple times to get multiple interfaces. -func (process *process) Stdio() (io.WriteCloser, io.ReadCloser, io.ReadCloser, error) { - stdin, stdout, stderr, err := process.p.StdioLegacy() - if err != nil { - err = convertProcessError(err, process) - } - return stdin, stdout, stderr, err -} - -// CloseStdin closes the write side of the stdin pipe so that the process is -// notified on the read side that there is no more data in stdin. -func (process *process) CloseStdin() error { - return convertProcessError(process.p.CloseStdin(context.Background()), process) -} - -// Close cleans up any state associated with the process but does not kill -// or wait on it. -func (process *process) Close() error { - return convertProcessError(process.p.Close(), process) -} diff --git a/vendor/github.com/Microsoft/hcsshim/zsyscall_windows.go b/vendor/github.com/Microsoft/hcsshim/zsyscall_windows.go deleted file mode 100644 index 8bed8485..00000000 --- a/vendor/github.com/Microsoft/hcsshim/zsyscall_windows.go +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated mksyscall_windows.exe DO NOT EDIT - -package hcsshim - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return nil - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modiphlpapi = windows.NewLazySystemDLL("iphlpapi.dll") - - procSetCurrentThreadCompartmentId = modiphlpapi.NewProc("SetCurrentThreadCompartmentId") -) - -func SetCurrentThreadCompartmentId(compartmentId uint32) (hr error) { - r0, _, _ := syscall.Syscall(procSetCurrentThreadCompartmentId.Addr(), 1, uintptr(compartmentId), 0, 0) - if int32(r0) < 0 { - if r0&0x1fff0000 == 0x00070000 { - r0 &= 0xffff - } - hr = syscall.Errno(r0) - } - return -} diff --git a/vendor/github.com/ProtonMail/go-crypto/AUTHORS b/vendor/github.com/ProtonMail/go-crypto/AUTHORS deleted file mode 100644 index 2b00ddba..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code refers to The Go Authors for copyright purposes. -# The master list of authors is in the main Go distribution, -# visible at https://tip.golang.org/AUTHORS. diff --git a/vendor/github.com/ProtonMail/go-crypto/CONTRIBUTORS b/vendor/github.com/ProtonMail/go-crypto/CONTRIBUTORS deleted file mode 100644 index 1fbd3e97..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# This source code was written by the Go contributors. -# The master list of contributors is in the main Go distribution, -# visible at https://tip.golang.org/CONTRIBUTORS. diff --git a/vendor/github.com/ProtonMail/go-crypto/LICENSE b/vendor/github.com/ProtonMail/go-crypto/LICENSE deleted file mode 100644 index 6a66aea5..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/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/ProtonMail/go-crypto/PATENTS b/vendor/github.com/ProtonMail/go-crypto/PATENTS deleted file mode 100644 index 73309904..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go b/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go deleted file mode 100644 index 3ed3f435..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/bitcurves/bitcurve.go +++ /dev/null @@ -1,381 +0,0 @@ -package bitcurves - -// Copyright 2010 The Go Authors. All rights reserved. -// Copyright 2011 ThePiachu. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package bitelliptic implements several Koblitz elliptic curves over prime -// fields. - -// This package operates, internally, on Jacobian coordinates. For a given -// (x, y) position on the curve, the Jacobian coordinates are (x1, y1, z1) -// where x = x1/z1² and y = y1/z1³. The greatest speedups come when the whole -// calculation can be performed within the transform (as in ScalarMult and -// ScalarBaseMult). But even for Add and Double, it's faster to apply and -// reverse the transform than to operate in affine coordinates. - -import ( - "crypto/elliptic" - "io" - "math/big" - "sync" -) - -// A BitCurve represents a Koblitz Curve with a=0. -// See http://www.hyperelliptic.org/EFD/g1p/auto-shortw.html -type BitCurve struct { - Name string - P *big.Int // the order of the underlying field - N *big.Int // the order of the base point - B *big.Int // the constant of the BitCurve equation - Gx, Gy *big.Int // (x,y) of the base point - BitSize int // the size of the underlying field -} - -// Params returns the parameters of the given BitCurve (see BitCurve struct) -func (bitCurve *BitCurve) Params() (cp *elliptic.CurveParams) { - cp = new(elliptic.CurveParams) - cp.Name = bitCurve.Name - cp.P = bitCurve.P - cp.N = bitCurve.N - cp.Gx = bitCurve.Gx - cp.Gy = bitCurve.Gy - cp.BitSize = bitCurve.BitSize - return cp -} - -// IsOnCurve returns true if the given (x,y) lies on the BitCurve. -func (bitCurve *BitCurve) IsOnCurve(x, y *big.Int) bool { - // y² = x³ + b - y2 := new(big.Int).Mul(y, y) //y² - y2.Mod(y2, bitCurve.P) //y²%P - - x3 := new(big.Int).Mul(x, x) //x² - x3.Mul(x3, x) //x³ - - x3.Add(x3, bitCurve.B) //x³+B - x3.Mod(x3, bitCurve.P) //(x³+B)%P - - return x3.Cmp(y2) == 0 -} - -// affineFromJacobian reverses the Jacobian transform. See the comment at the -// top of the file. -func (bitCurve *BitCurve) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) { - if z.Cmp(big.NewInt(0)) == 0 { - panic("bitcurve: Can't convert to affine with Jacobian Z = 0") - } - // x = YZ^2 mod P - zinv := new(big.Int).ModInverse(z, bitCurve.P) - zinvsq := new(big.Int).Mul(zinv, zinv) - - xOut = new(big.Int).Mul(x, zinvsq) - xOut.Mod(xOut, bitCurve.P) - // y = YZ^3 mod P - zinvsq.Mul(zinvsq, zinv) - yOut = new(big.Int).Mul(y, zinvsq) - yOut.Mod(yOut, bitCurve.P) - return xOut, yOut -} - -// Add returns the sum of (x1,y1) and (x2,y2) -func (bitCurve *BitCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { - z := new(big.Int).SetInt64(1) - x, y, z := bitCurve.addJacobian(x1, y1, z, x2, y2, z) - return bitCurve.affineFromJacobian(x, y, z) -} - -// addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and -// (x2, y2, z2) and returns their sum, also in Jacobian form. -func (bitCurve *BitCurve) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { - // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl - z1z1 := new(big.Int).Mul(z1, z1) - z1z1.Mod(z1z1, bitCurve.P) - z2z2 := new(big.Int).Mul(z2, z2) - z2z2.Mod(z2z2, bitCurve.P) - - u1 := new(big.Int).Mul(x1, z2z2) - u1.Mod(u1, bitCurve.P) - u2 := new(big.Int).Mul(x2, z1z1) - u2.Mod(u2, bitCurve.P) - h := new(big.Int).Sub(u2, u1) - if h.Sign() == -1 { - h.Add(h, bitCurve.P) - } - i := new(big.Int).Lsh(h, 1) - i.Mul(i, i) - j := new(big.Int).Mul(h, i) - - s1 := new(big.Int).Mul(y1, z2) - s1.Mul(s1, z2z2) - s1.Mod(s1, bitCurve.P) - s2 := new(big.Int).Mul(y2, z1) - s2.Mul(s2, z1z1) - s2.Mod(s2, bitCurve.P) - r := new(big.Int).Sub(s2, s1) - if r.Sign() == -1 { - r.Add(r, bitCurve.P) - } - r.Lsh(r, 1) - v := new(big.Int).Mul(u1, i) - - x3 := new(big.Int).Set(r) - x3.Mul(x3, x3) - x3.Sub(x3, j) - x3.Sub(x3, v) - x3.Sub(x3, v) - x3.Mod(x3, bitCurve.P) - - y3 := new(big.Int).Set(r) - v.Sub(v, x3) - y3.Mul(y3, v) - s1.Mul(s1, j) - s1.Lsh(s1, 1) - y3.Sub(y3, s1) - y3.Mod(y3, bitCurve.P) - - z3 := new(big.Int).Add(z1, z2) - z3.Mul(z3, z3) - z3.Sub(z3, z1z1) - if z3.Sign() == -1 { - z3.Add(z3, bitCurve.P) - } - z3.Sub(z3, z2z2) - if z3.Sign() == -1 { - z3.Add(z3, bitCurve.P) - } - z3.Mul(z3, h) - z3.Mod(z3, bitCurve.P) - - return x3, y3, z3 -} - -// Double returns 2*(x,y) -func (bitCurve *BitCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { - z1 := new(big.Int).SetInt64(1) - return bitCurve.affineFromJacobian(bitCurve.doubleJacobian(x1, y1, z1)) -} - -// doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and -// returns its double, also in Jacobian form. -func (bitCurve *BitCurve) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { - // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l - - a := new(big.Int).Mul(x, x) //X1² - b := new(big.Int).Mul(y, y) //Y1² - c := new(big.Int).Mul(b, b) //B² - - d := new(big.Int).Add(x, b) //X1+B - d.Mul(d, d) //(X1+B)² - d.Sub(d, a) //(X1+B)²-A - d.Sub(d, c) //(X1+B)²-A-C - d.Mul(d, big.NewInt(2)) //2*((X1+B)²-A-C) - - e := new(big.Int).Mul(big.NewInt(3), a) //3*A - f := new(big.Int).Mul(e, e) //E² - - x3 := new(big.Int).Mul(big.NewInt(2), d) //2*D - x3.Sub(f, x3) //F-2*D - x3.Mod(x3, bitCurve.P) - - y3 := new(big.Int).Sub(d, x3) //D-X3 - y3.Mul(e, y3) //E*(D-X3) - y3.Sub(y3, new(big.Int).Mul(big.NewInt(8), c)) //E*(D-X3)-8*C - y3.Mod(y3, bitCurve.P) - - z3 := new(big.Int).Mul(y, z) //Y1*Z1 - z3.Mul(big.NewInt(2), z3) //3*Y1*Z1 - z3.Mod(z3, bitCurve.P) - - return x3, y3, z3 -} - -//TODO: double check if it is okay -// ScalarMult returns k*(Bx,By) where k is a number in big-endian form. -func (bitCurve *BitCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { - // We have a slight problem in that the identity of the group (the - // point at infinity) cannot be represented in (x, y) form on a finite - // machine. Thus the standard add/double algorithm has to be tweaked - // slightly: our initial state is not the identity, but x, and we - // ignore the first true bit in |k|. If we don't find any true bits in - // |k|, then we return nil, nil, because we cannot return the identity - // element. - - Bz := new(big.Int).SetInt64(1) - x := Bx - y := By - z := Bz - - seenFirstTrue := false - for _, byte := range k { - for bitNum := 0; bitNum < 8; bitNum++ { - if seenFirstTrue { - x, y, z = bitCurve.doubleJacobian(x, y, z) - } - if byte&0x80 == 0x80 { - if !seenFirstTrue { - seenFirstTrue = true - } else { - x, y, z = bitCurve.addJacobian(Bx, By, Bz, x, y, z) - } - } - byte <<= 1 - } - } - - if !seenFirstTrue { - return nil, nil - } - - return bitCurve.affineFromJacobian(x, y, z) -} - -// ScalarBaseMult returns k*G, where G is the base point of the group and k is -// an integer in big-endian form. -func (bitCurve *BitCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - return bitCurve.ScalarMult(bitCurve.Gx, bitCurve.Gy, k) -} - -var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f} - -//TODO: double check if it is okay -// GenerateKey returns a public/private key pair. The private key is generated -// using the given reader, which must return random data. -func (bitCurve *BitCurve) GenerateKey(rand io.Reader) (priv []byte, x, y *big.Int, err error) { - byteLen := (bitCurve.BitSize + 7) >> 3 - priv = make([]byte, byteLen) - - for x == nil { - _, err = io.ReadFull(rand, priv) - if err != nil { - return - } - // We have to mask off any excess bits in the case that the size of the - // underlying field is not a whole number of bytes. - priv[0] &= mask[bitCurve.BitSize%8] - // This is because, in tests, rand will return all zeros and we don't - // want to get the point at infinity and loop forever. - priv[1] ^= 0x42 - x, y = bitCurve.ScalarBaseMult(priv) - } - return -} - -// Marshal converts a point into the form specified in section 4.3.6 of ANSI -// X9.62. -func (bitCurve *BitCurve) Marshal(x, y *big.Int) []byte { - byteLen := (bitCurve.BitSize + 7) >> 3 - - ret := make([]byte, 1+2*byteLen) - ret[0] = 4 // uncompressed point - - xBytes := x.Bytes() - copy(ret[1+byteLen-len(xBytes):], xBytes) - yBytes := y.Bytes() - copy(ret[1+2*byteLen-len(yBytes):], yBytes) - return ret -} - -// Unmarshal converts a point, serialised by Marshal, into an x, y pair. On -// error, x = nil. -func (bitCurve *BitCurve) Unmarshal(data []byte) (x, y *big.Int) { - byteLen := (bitCurve.BitSize + 7) >> 3 - if len(data) != 1+2*byteLen { - return - } - if data[0] != 4 { // uncompressed form - return - } - x = new(big.Int).SetBytes(data[1 : 1+byteLen]) - y = new(big.Int).SetBytes(data[1+byteLen:]) - return -} - -//curve parameters taken from: -//http://www.secg.org/collateral/sec2_final.pdf - -var initonce sync.Once -var secp160k1 *BitCurve -var secp192k1 *BitCurve -var secp224k1 *BitCurve -var secp256k1 *BitCurve - -func initAll() { - initS160() - initS192() - initS224() - initS256() -} - -func initS160() { - // See SEC 2 section 2.4.1 - secp160k1 = new(BitCurve) - secp160k1.Name = "secp160k1" - secp160k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", 16) - secp160k1.N, _ = new(big.Int).SetString("0100000000000000000001B8FA16DFAB9ACA16B6B3", 16) - secp160k1.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000007", 16) - secp160k1.Gx, _ = new(big.Int).SetString("3B4C382CE37AA192A4019E763036F4F5DD4D7EBB", 16) - secp160k1.Gy, _ = new(big.Int).SetString("938CF935318FDCED6BC28286531733C3F03C4FEE", 16) - secp160k1.BitSize = 160 -} - -func initS192() { - // See SEC 2 section 2.5.1 - secp192k1 = new(BitCurve) - secp192k1.Name = "secp192k1" - secp192k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37", 16) - secp192k1.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D", 16) - secp192k1.B, _ = new(big.Int).SetString("000000000000000000000000000000000000000000000003", 16) - secp192k1.Gx, _ = new(big.Int).SetString("DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", 16) - secp192k1.Gy, _ = new(big.Int).SetString("9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", 16) - secp192k1.BitSize = 192 -} - -func initS224() { - // See SEC 2 section 2.6.1 - secp224k1 = new(BitCurve) - secp224k1.Name = "secp224k1" - secp224k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D", 16) - secp224k1.N, _ = new(big.Int).SetString("010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7", 16) - secp224k1.B, _ = new(big.Int).SetString("00000000000000000000000000000000000000000000000000000005", 16) - secp224k1.Gx, _ = new(big.Int).SetString("A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C", 16) - secp224k1.Gy, _ = new(big.Int).SetString("7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5", 16) - secp224k1.BitSize = 224 -} - -func initS256() { - // See SEC 2 section 2.7.1 - secp256k1 = new(BitCurve) - secp256k1.Name = "secp256k1" - secp256k1.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16) - secp256k1.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16) - secp256k1.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000007", 16) - secp256k1.Gx, _ = new(big.Int).SetString("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16) - secp256k1.Gy, _ = new(big.Int).SetString("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16) - secp256k1.BitSize = 256 -} - -// S160 returns a BitCurve which implements secp160k1 (see SEC 2 section 2.4.1) -func S160() *BitCurve { - initonce.Do(initAll) - return secp160k1 -} - -// S192 returns a BitCurve which implements secp192k1 (see SEC 2 section 2.5.1) -func S192() *BitCurve { - initonce.Do(initAll) - return secp192k1 -} - -// S224 returns a BitCurve which implements secp224k1 (see SEC 2 section 2.6.1) -func S224() *BitCurve { - initonce.Do(initAll) - return secp224k1 -} - -// S256 returns a BitCurve which implements bitcurves (see SEC 2 section 2.7.1) -func S256() *BitCurve { - initonce.Do(initAll) - return secp256k1 -} diff --git a/vendor/github.com/ProtonMail/go-crypto/brainpool/brainpool.go b/vendor/github.com/ProtonMail/go-crypto/brainpool/brainpool.go deleted file mode 100644 index cb6676de..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/brainpool/brainpool.go +++ /dev/null @@ -1,134 +0,0 @@ -// Package brainpool implements Brainpool elliptic curves. -// Implementation of rcurves is from github.com/ebfe/brainpool -// Note that these curves are implemented with naive, non-constant time operations -// and are likely not suitable for environments where timing attacks are a concern. -package brainpool - -import ( - "crypto/elliptic" - "math/big" - "sync" -) - -var ( - once sync.Once - p256t1, p384t1, p512t1 *elliptic.CurveParams - p256r1, p384r1, p512r1 *rcurve -) - -func initAll() { - initP256t1() - initP384t1() - initP512t1() - initP256r1() - initP384r1() - initP512r1() -} - -func initP256t1() { - p256t1 = &elliptic.CurveParams{Name: "brainpoolP256t1"} - p256t1.P, _ = new(big.Int).SetString("A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", 16) - p256t1.N, _ = new(big.Int).SetString("A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", 16) - p256t1.B, _ = new(big.Int).SetString("662C61C430D84EA4FE66A7733D0B76B7BF93EBC4AF2F49256AE58101FEE92B04", 16) - p256t1.Gx, _ = new(big.Int).SetString("A3E8EB3CC1CFE7B7732213B23A656149AFA142C47AAFBC2B79A191562E1305F4", 16) - p256t1.Gy, _ = new(big.Int).SetString("2D996C823439C56D7F7B22E14644417E69BCB6DE39D027001DABE8F35B25C9BE", 16) - p256t1.BitSize = 256 -} - -func initP256r1() { - twisted := p256t1 - params := &elliptic.CurveParams{ - Name: "brainpoolP256r1", - P: twisted.P, - N: twisted.N, - BitSize: twisted.BitSize, - } - params.Gx, _ = new(big.Int).SetString("8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262", 16) - params.Gy, _ = new(big.Int).SetString("547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997", 16) - z, _ := new(big.Int).SetString("3E2D4BD9597B58639AE7AA669CAB9837CF5CF20A2C852D10F655668DFC150EF0", 16) - p256r1 = newrcurve(twisted, params, z) -} - -func initP384t1() { - p384t1 = &elliptic.CurveParams{Name: "brainpoolP384t1"} - p384t1.P, _ = new(big.Int).SetString("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", 16) - p384t1.N, _ = new(big.Int).SetString("8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", 16) - p384t1.B, _ = new(big.Int).SetString("7F519EADA7BDA81BD826DBA647910F8C4B9346ED8CCDC64E4B1ABD11756DCE1D2074AA263B88805CED70355A33B471EE", 16) - p384t1.Gx, _ = new(big.Int).SetString("18DE98B02DB9A306F2AFCD7235F72A819B80AB12EBD653172476FECD462AABFFC4FF191B946A5F54D8D0AA2F418808CC", 16) - p384t1.Gy, _ = new(big.Int).SetString("25AB056962D30651A114AFD2755AD336747F93475B7A1FCA3B88F2B6A208CCFE469408584DC2B2912675BF5B9E582928", 16) - p384t1.BitSize = 384 -} - -func initP384r1() { - twisted := p384t1 - params := &elliptic.CurveParams{ - Name: "brainpoolP384r1", - P: twisted.P, - N: twisted.N, - BitSize: twisted.BitSize, - } - params.Gx, _ = new(big.Int).SetString("1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E", 16) - params.Gy, _ = new(big.Int).SetString("8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315", 16) - z, _ := new(big.Int).SetString("41DFE8DD399331F7166A66076734A89CD0D2BCDB7D068E44E1F378F41ECBAE97D2D63DBC87BCCDDCCC5DA39E8589291C", 16) - p384r1 = newrcurve(twisted, params, z) -} - -func initP512t1() { - p512t1 = &elliptic.CurveParams{Name: "brainpoolP512t1"} - p512t1.P, _ = new(big.Int).SetString("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", 16) - p512t1.N, _ = new(big.Int).SetString("AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", 16) - p512t1.B, _ = new(big.Int).SetString("7CBBBCF9441CFAB76E1890E46884EAE321F70C0BCB4981527897504BEC3E36A62BCDFA2304976540F6450085F2DAE145C22553B465763689180EA2571867423E", 16) - p512t1.Gx, _ = new(big.Int).SetString("640ECE5C12788717B9C1BA06CBC2A6FEBA85842458C56DDE9DB1758D39C0313D82BA51735CDB3EA499AA77A7D6943A64F7A3F25FE26F06B51BAA2696FA9035DA", 16) - p512t1.Gy, _ = new(big.Int).SetString("5B534BD595F5AF0FA2C892376C84ACE1BB4E3019B71634C01131159CAE03CEE9D9932184BEEF216BD71DF2DADF86A627306ECFF96DBB8BACE198B61E00F8B332", 16) - p512t1.BitSize = 512 -} - -func initP512r1() { - twisted := p512t1 - params := &elliptic.CurveParams{ - Name: "brainpoolP512r1", - P: twisted.P, - N: twisted.N, - BitSize: twisted.BitSize, - } - params.Gx, _ = new(big.Int).SetString("81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822", 16) - params.Gy, _ = new(big.Int).SetString("7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892", 16) - z, _ := new(big.Int).SetString("12EE58E6764838B69782136F0F2D3BA06E27695716054092E60A80BEDB212B64E585D90BCE13761F85C3F1D2A64E3BE8FEA2220F01EBA5EEB0F35DBD29D922AB", 16) - p512r1 = newrcurve(twisted, params, z) -} - -// P256t1 returns a Curve which implements Brainpool P256t1 (see RFC 5639, section 3.4) -func P256t1() elliptic.Curve { - once.Do(initAll) - return p256t1 -} - -// P256r1 returns a Curve which implements Brainpool P256r1 (see RFC 5639, section 3.4) -func P256r1() elliptic.Curve { - once.Do(initAll) - return p256r1 -} - -// P384t1 returns a Curve which implements Brainpool P384t1 (see RFC 5639, section 3.6) -func P384t1() elliptic.Curve { - once.Do(initAll) - return p384t1 -} - -// P384r1 returns a Curve which implements Brainpool P384r1 (see RFC 5639, section 3.6) -func P384r1() elliptic.Curve { - once.Do(initAll) - return p384r1 -} - -// P512t1 returns a Curve which implements Brainpool P512t1 (see RFC 5639, section 3.7) -func P512t1() elliptic.Curve { - once.Do(initAll) - return p512t1 -} - -// P512r1 returns a Curve which implements Brainpool P512r1 (see RFC 5639, section 3.7) -func P512r1() elliptic.Curve { - once.Do(initAll) - return p512r1 -} diff --git a/vendor/github.com/ProtonMail/go-crypto/brainpool/rcurve.go b/vendor/github.com/ProtonMail/go-crypto/brainpool/rcurve.go deleted file mode 100644 index 2d535508..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/brainpool/rcurve.go +++ /dev/null @@ -1,83 +0,0 @@ -package brainpool - -import ( - "crypto/elliptic" - "math/big" -) - -var _ elliptic.Curve = (*rcurve)(nil) - -type rcurve struct { - twisted elliptic.Curve - params *elliptic.CurveParams - z *big.Int - zinv *big.Int - z2 *big.Int - z3 *big.Int - zinv2 *big.Int - zinv3 *big.Int -} - -var ( - two = big.NewInt(2) - three = big.NewInt(3) -) - -func newrcurve(twisted elliptic.Curve, params *elliptic.CurveParams, z *big.Int) *rcurve { - zinv := new(big.Int).ModInverse(z, params.P) - return &rcurve{ - twisted: twisted, - params: params, - z: z, - zinv: zinv, - z2: new(big.Int).Exp(z, two, params.P), - z3: new(big.Int).Exp(z, three, params.P), - zinv2: new(big.Int).Exp(zinv, two, params.P), - zinv3: new(big.Int).Exp(zinv, three, params.P), - } -} - -func (curve *rcurve) toTwisted(x, y *big.Int) (*big.Int, *big.Int) { - var tx, ty big.Int - tx.Mul(x, curve.z2) - tx.Mod(&tx, curve.params.P) - ty.Mul(y, curve.z3) - ty.Mod(&ty, curve.params.P) - return &tx, &ty -} - -func (curve *rcurve) fromTwisted(tx, ty *big.Int) (*big.Int, *big.Int) { - var x, y big.Int - x.Mul(tx, curve.zinv2) - x.Mod(&x, curve.params.P) - y.Mul(ty, curve.zinv3) - y.Mod(&y, curve.params.P) - return &x, &y -} - -func (curve *rcurve) Params() *elliptic.CurveParams { - return curve.params -} - -func (curve *rcurve) IsOnCurve(x, y *big.Int) bool { - return curve.twisted.IsOnCurve(curve.toTwisted(x, y)) -} - -func (curve *rcurve) Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int) { - tx1, ty1 := curve.toTwisted(x1, y1) - tx2, ty2 := curve.toTwisted(x2, y2) - return curve.fromTwisted(curve.twisted.Add(tx1, ty1, tx2, ty2)) -} - -func (curve *rcurve) Double(x1, y1 *big.Int) (x, y *big.Int) { - return curve.fromTwisted(curve.twisted.Double(curve.toTwisted(x1, y1))) -} - -func (curve *rcurve) ScalarMult(x1, y1 *big.Int, scalar []byte) (x, y *big.Int) { - tx1, ty1 := curve.toTwisted(x1, y1) - return curve.fromTwisted(curve.twisted.ScalarMult(tx1, ty1, scalar)) -} - -func (curve *rcurve) ScalarBaseMult(scalar []byte) (x, y *big.Int) { - return curve.fromTwisted(curve.twisted.ScalarBaseMult(scalar)) -} \ No newline at end of file diff --git a/vendor/github.com/ProtonMail/go-crypto/eax/eax.go b/vendor/github.com/ProtonMail/go-crypto/eax/eax.go deleted file mode 100644 index 6b6bc7ae..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/eax/eax.go +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (C) 2019 ProtonTech AG - -// Package eax provides an implementation of the EAX -// (encrypt-authenticate-translate) mode of operation, as described in -// Bellare, Rogaway, and Wagner "THE EAX MODE OF OPERATION: A TWO-PASS -// AUTHENTICATED-ENCRYPTION SCHEME OPTIMIZED FOR SIMPLICITY AND EFFICIENCY." -// In FSE'04, volume 3017 of LNCS, 2004 -package eax - -import ( - "crypto/cipher" - "crypto/subtle" - "errors" - "github.com/ProtonMail/go-crypto/internal/byteutil" -) - -const ( - defaultTagSize = 16 - defaultNonceSize = 16 -) - -type eax struct { - block cipher.Block // Only AES-{128, 192, 256} supported - tagSize int // At least 12 bytes recommended - nonceSize int -} - -func (e *eax) NonceSize() int { - return e.nonceSize -} - -func (e *eax) Overhead() int { - return e.tagSize -} - -// NewEAX returns an EAX instance with AES-{KEYLENGTH} and default nonce and -// tag lengths. Supports {128, 192, 256}- bit key length. -func NewEAX(block cipher.Block) (cipher.AEAD, error) { - return NewEAXWithNonceAndTagSize(block, defaultNonceSize, defaultTagSize) -} - -// NewEAXWithNonceAndTagSize returns an EAX instance with AES-{keyLength} and -// given nonce and tag lengths in bytes. Panics on zero nonceSize and -// exceedingly long tags. -// -// It is recommended to use at least 12 bytes as tag length (see, for instance, -// NIST SP 800-38D). -// -// Only to be used for compatibility with existing cryptosystems with -// non-standard parameters. For all other cases, prefer NewEAX. -func NewEAXWithNonceAndTagSize( - block cipher.Block, nonceSize, tagSize int) (cipher.AEAD, error) { - if nonceSize < 1 { - return nil, eaxError("Cannot initialize EAX with nonceSize = 0") - } - if tagSize > block.BlockSize() { - return nil, eaxError("Custom tag length exceeds blocksize") - } - return &eax{ - block: block, - tagSize: tagSize, - nonceSize: nonceSize, - }, nil -} - -func (e *eax) Seal(dst, nonce, plaintext, adata []byte) []byte { - if len(nonce) > e.nonceSize { - panic("crypto/eax: Nonce too long for this instance") - } - ret, out := byteutil.SliceForAppend(dst, len(plaintext) + e.tagSize) - omacNonce := e.omacT(0, nonce) - omacAdata := e.omacT(1, adata) - - // Encrypt message using CTR mode and omacNonce as IV - ctr := cipher.NewCTR(e.block, omacNonce) - ciphertextData := out[:len(plaintext)] - ctr.XORKeyStream(ciphertextData, plaintext) - - omacCiphertext := e.omacT(2, ciphertextData) - - tag := out[len(plaintext):] - for i := 0; i < e.tagSize; i++ { - tag[i] = omacCiphertext[i] ^ omacNonce[i] ^ omacAdata[i] - } - return ret -} - -func (e* eax) Open(dst, nonce, ciphertext, adata []byte) ([]byte, error) { - if len(nonce) > e.nonceSize { - panic("crypto/eax: Nonce too long for this instance") - } - if len(ciphertext) < e.tagSize { - return nil, eaxError("Ciphertext shorter than tag length") - } - sep := len(ciphertext) - e.tagSize - - // Compute tag - omacNonce := e.omacT(0, nonce) - omacAdata := e.omacT(1, adata) - omacCiphertext := e.omacT(2, ciphertext[:sep]) - - tag := make([]byte, e.tagSize) - for i := 0; i < e.tagSize; i++ { - tag[i] = omacCiphertext[i] ^ omacNonce[i] ^ omacAdata[i] - } - - // Compare tags - if subtle.ConstantTimeCompare(ciphertext[sep:], tag) != 1 { - return nil, eaxError("Tag authentication failed") - } - - // Decrypt ciphertext - ret, out := byteutil.SliceForAppend(dst, len(ciphertext)) - ctr := cipher.NewCTR(e.block, omacNonce) - ctr.XORKeyStream(out, ciphertext[:sep]) - - return ret[:sep], nil -} - -// Tweakable OMAC - Calls OMAC_K([t]_n || plaintext) -func (e *eax) omacT(t byte, plaintext []byte) []byte { - blockSize := e.block.BlockSize() - byteT := make([]byte, blockSize) - byteT[blockSize-1] = t - concat := append(byteT, plaintext...) - return e.omac(concat) -} - -func (e *eax) omac(plaintext []byte) []byte { - blockSize := e.block.BlockSize() - // L ← E_K(0^n); B ← 2L; P ← 4L - L := make([]byte, blockSize) - e.block.Encrypt(L, L) - B := byteutil.GfnDouble(L) - P := byteutil.GfnDouble(B) - - // CBC with IV = 0 - cbc := cipher.NewCBCEncrypter(e.block, make([]byte, blockSize)) - padded := e.pad(plaintext, B, P) - cbcCiphertext := make([]byte, len(padded)) - cbc.CryptBlocks(cbcCiphertext, padded) - - return cbcCiphertext[len(cbcCiphertext)-blockSize:] -} - -func (e *eax) pad(plaintext, B, P []byte) []byte { - // if |M| in {n, 2n, 3n, ...} - blockSize := e.block.BlockSize() - if len(plaintext) != 0 && len(plaintext)%blockSize == 0 { - return byteutil.RightXor(plaintext, B) - } - - // else return (M || 1 || 0^(n−1−(|M| % n))) xor→ P - ending := make([]byte, blockSize-len(plaintext)%blockSize) - ending[0] = 0x80 - padded := append(plaintext, ending...) - return byteutil.RightXor(padded, P) -} - -func eaxError(err string) error { - return errors.New("crypto/eax: " + err) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/eax/eax_test_vectors.go b/vendor/github.com/ProtonMail/go-crypto/eax/eax_test_vectors.go deleted file mode 100644 index ddb53d07..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/eax/eax_test_vectors.go +++ /dev/null @@ -1,58 +0,0 @@ -package eax - -// Test vectors from -// https://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf -var testVectors = []struct { - msg, key, nonce, header, ciphertext string -}{ - {"", - "233952DEE4D5ED5F9B9C6D6FF80FF478", - "62EC67F9C3A4A407FCB2A8C49031A8B3", - "6BFB914FD07EAE6B", - "E037830E8389F27B025A2D6527E79D01"}, - {"F7FB", - "91945D3F4DCBEE0BF45EF52255F095A4", - "BECAF043B0A23D843194BA972C66DEBD", - "FA3BFD4806EB53FA", - "19DD5C4C9331049D0BDAB0277408F67967E5"}, - {"1A47CB4933", - "01F74AD64077F2E704C0F60ADA3DD523", - "70C3DB4F0D26368400A10ED05D2BFF5E", - "234A3463C1264AC6", - "D851D5BAE03A59F238A23E39199DC9266626C40F80"}, - {"481C9E39B1", - "D07CF6CBB7F313BDDE66B727AFD3C5E8", - "8408DFFF3C1A2B1292DC199E46B7D617", - "33CCE2EABFF5A79D", - "632A9D131AD4C168A4225D8E1FF755939974A7BEDE"}, - {"40D0C07DA5E4", - "35B6D0580005BBC12B0587124557D2C2", - "FDB6B06676EEDC5C61D74276E1F8E816", - "AEB96EAEBE2970E9", - "071DFE16C675CB0677E536F73AFE6A14B74EE49844DD"}, - {"4DE3B35C3FC039245BD1FB7D", - "BD8E6E11475E60B268784C38C62FEB22", - "6EAC5C93072D8E8513F750935E46DA1B", - "D4482D1CA78DCE0F", - "835BB4F15D743E350E728414ABB8644FD6CCB86947C5E10590210A4F"}, - {"8B0A79306C9CE7ED99DAE4F87F8DD61636", - "7C77D6E813BED5AC98BAA417477A2E7D", - "1A8C98DCD73D38393B2BF1569DEEFC19", - "65D2017990D62528", - "02083E3979DA014812F59F11D52630DA30137327D10649B0AA6E1C181DB617D7F2"}, - {"1BDA122BCE8A8DBAF1877D962B8592DD2D56", - "5FFF20CAFAB119CA2FC73549E20F5B0D", - "DDE59B97D722156D4D9AFF2BC7559826", - "54B9F04E6A09189A", - "2EC47B2C4954A489AFC7BA4897EDCDAE8CC33B60450599BD02C96382902AEF7F832A"}, - {"6CF36720872B8513F6EAB1A8A44438D5EF11", - "A4A4782BCFFD3EC5E7EF6D8C34A56123", - "B781FCF2F75FA5A8DE97A9CA48E522EC", - "899A175897561D7E", - "0DE18FD0FDD91E7AF19F1D8EE8733938B1E8E7F6D2231618102FDB7FE55FF1991700"}, - {"CA40D7446E545FFAED3BD12A740A659FFBBB3CEAB7", - "8395FCF1E95BEBD697BD010BC766AAC3", - "22E7ADD93CFC6393C57EC0B3C17D6B44", - "126735FCC320D25A", - "CB8920F87A6C75CFF39627B56E3ED197C552D295A7CFC46AFC253B4652B1AF3795B124AB6E"}, -} diff --git a/vendor/github.com/ProtonMail/go-crypto/eax/random_vectors.go b/vendor/github.com/ProtonMail/go-crypto/eax/random_vectors.go deleted file mode 100644 index 4eb19f28..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/eax/random_vectors.go +++ /dev/null @@ -1,131 +0,0 @@ -// These vectors include key length in {128, 192, 256}, tag size 128, and -// random nonce, header, and plaintext lengths. - -// This file was automatically generated. - -package eax - -var randomVectors = []struct { - key, nonce, header, plaintext, ciphertext string -}{ - {"DFDE093F36B0356E5A81F609786982E3", - "1D8AC604419001816905BA72B14CED7E", - "152A1517A998D7A24163FCDD146DE81AC347C8B97088F502093C1ABB8F6E33D9A219C34D7603A18B1F5ABE02E56661B7D7F67E81EC08C1302EF38D80A859486D450E94A4F26AD9E68EEBBC0C857A0FC5CF9E641D63D565A7E361BC8908F5A8DC8FD6", - "1C8EAAB71077FE18B39730A3156ADE29C5EE824C7EE86ED2A253B775603FB237116E654F6FEC588DD27F523A0E01246FE73FE348491F2A8E9ABC6CA58D663F71CDBCF4AD798BE46C42AE6EE8B599DB44A1A48D7BBBBA0F7D2750181E1C5E66967F7D57CBD30AFBDA5727", - "79E7E150934BBEBF7013F61C60462A14D8B15AF7A248AFB8A344EF021C1500E16666891D6E973D8BB56B71A371F12CA34660C4410C016982B20F547E3762A58B7BF4F20236CADCF559E2BE7D783B13723B2741FC7CDC8997D839E39A3DDD2BADB96743DD7049F1BDB0516A262869915B3F70498AFB7B191BF960"}, - {"F10619EF02E5D94D7550EB84ED364A21", - "8DC0D4F2F745BBAE835CC5574B942D20", - "FE561358F2E8DF7E1024FF1AE9A8D36EBD01352214505CB99D644777A8A1F6027FA2BDBFC529A9B91136D5F2416CFC5F0F4EC3A1AFD32BDDA23CA504C5A5CB451785FABF4DFE4CD50D817491991A60615B30286361C100A95D1712F2A45F8E374461F4CA2B", - "D7B5A971FC219631D30EFC3664AE3127D9CF3097DAD9C24AC7905D15E8D9B25B026B31D68CAE00975CDB81EB1FD96FD5E1A12E2BB83FA25F1B1D91363457657FC03875C27F2946C5", - "2F336ED42D3CC38FC61660C4CD60BA4BD438B05F5965D8B7B399D2E7167F5D34F792D318F94DB15D67463AC449E13D568CC09BFCE32A35EE3EE96A041927680AE329811811E27F2D1E8E657707AF99BA96D13A478D695D59"}, - {"429F514EFC64D98A698A9247274CFF45", - "976AA5EB072F912D126ACEBC954FEC38", - "A71D89DC5B6CEDBB7451A27C3C2CAE09126DB4C421", - "5632FE62AB1DC549D54D3BC3FC868ACCEDEFD9ECF5E9F8", - "848AE4306CA8C7F416F8707625B7F55881C0AB430353A5C967CDA2DA787F581A70E34DBEBB2385"}, - {"398138F309085F47F8457CDF53895A63", - "F8A8A7F2D28E5FFF7BBC2F24353F7A36", - "5D633C21BA7764B8855CAB586F3746E236AD486039C83C6B56EFA9C651D38A41D6B20DAEE3418BFEA44B8BD6", - "A3BBAA91920AF5E10659818B1B3B300AC79BFC129C8329E75251F73A66D3AE0128EB91D5031E0A65C329DB7D1E9C0493E268", - "D078097267606E5FB07CFB7E2B4B718172A82C6A4CEE65D549A4DFB9838003BD2FBF64A7A66988AC1A632FD88F9E9FBB57C5A78AD2E086EACBA3DB68511D81C2970A"}, - {"7A4151EBD3901B42CBA45DAFB2E931BA", - "0FC88ACEE74DD538040321C330974EB8", - "250464FB04733BAB934C59E6AD2D6AE8D662CBCFEFBE61E5A308D4211E58C4C25935B72C69107722E946BFCBF416796600542D76AEB73F2B25BF53BAF97BDEB36ED3A7A51C31E7F170EB897457E7C17571D1BA0A908954E9", - "88C41F3EBEC23FAB8A362D969CAC810FAD4F7CA6A7F7D0D44F060F92E37E1183768DD4A8C733F71C96058D362A39876D183B86C103DE", - "74A25B2182C51096D48A870D80F18E1CE15867778E34FCBA6BD7BFB3739FDCD42AD0F2D9F4EBA29085285C6048C15BCE5E5166F1F962D3337AA88E6062F05523029D0A7F0BF9"}, - {"BFB147E1CD5459424F8C0271FC0E0DC5", - "EABCC126442BF373969EA3015988CC45", - "4C0880E1D71AA2C7", - "BE1B5EC78FBF73E7A6682B21BA7E0E5D2D1C7ABE", - "5660D7C1380E2F306895B1402CB2D6C37876504276B414D120F4CF92FDDDBB293A238EA0"}, - {"595DD6F52D18BC2CA8EB4EDAA18D9FA3", - "0F84B5D36CF4BC3B863313AF3B4D2E97", - "30AE6CC5F99580F12A779D98BD379A60948020C0B6FBD5746B30BA3A15C6CD33DAF376C70A9F15B6C0EB410A93161F7958AE23", - "8EF3687A1642B070970B0B91462229D1D76ABC154D18211F7152AA9FF368", - "317C1DDB11417E5A9CC4DDE7FDFF6659A5AC4B31DE025212580A05CDAC6024D3E4AE7C2966E52B9129E9ECDBED86"}, - {"44E6F2DC8FDC778AD007137D11410F50", - "270A237AD977F7187AA6C158A0BAB24F", - "509B0F0EB12E2AA5C5BA2DE553C07FAF4CE0C9E926531AA709A3D6224FCB783ACCF1559E10B1123EBB7D52E8AB54E6B5352A9ED0D04124BF0E9D9BACFD7E32B817B2E625F5EE94A64EDE9E470DE7FE6886C19B294F9F828209FE257A78", - "8B3D7815DF25618A5D0C55A601711881483878F113A12EC36CF64900549A3199555528559DC118F789788A55FAFD944E6E99A9CA3F72F238CD3F4D88223F7A745992B3FAED1848", - "1CC00D79F7AD82FDA71B58D286E5F34D0CC4CEF30704E771CC1E50746BDF83E182B078DB27149A42BAE619DF0F85B0B1090AD55D3B4471B0D6F6ECCD09C8F876B30081F0E7537A9624F8AAF29DA85E324122EFB4D68A56"}, - {"BB7BC352A03044B4428D8DBB4B0701FDEC4649FD17B81452", - "8B4BBE26CCD9859DCD84884159D6B0A4", - "2212BEB0E78E0F044A86944CF33C8D5C80D9DBE1034BF3BCF73611835C7D3A52F5BD2D81B68FD681B68540A496EE5DA16FD8AC8824E60E1EC2042BE28FB0BFAD4E4B03596446BDD8C37D936D9B3D5295BE19F19CF5ACE1D33A46C952CE4DE5C12F92C1DD051E04AEED", - "9037234CC44FFF828FABED3A7084AF40FA7ABFF8E0C0EFB57A1CC361E18FC4FAC1AB54F3ABFE9FF77263ACE16C3A", - "A9391B805CCD956081E0B63D282BEA46E7025126F1C1631239C33E92AA6F92CD56E5A4C56F00FF9658E93D48AF4EF0EF81628E34AD4DB0CDAEDCD2A17EE7"}, - {"99C0AD703196D2F60A74E6B378B838B31F82EA861F06FC4E", - "92745C018AA708ECFEB1667E9F3F1B01", - "828C69F376C0C0EC651C67749C69577D589EE39E51404D80EBF70C8660A8F5FD375473F4A7C611D59CB546A605D67446CE2AA844135FCD78BB5FBC90222A00D42920BB1D7EEDFB0C4672554F583EF23184F89063CDECBE482367B5F9AF3ACBC3AF61392BD94CBCD9B64677", - "A879214658FD0A5B0E09836639BF82E05EC7A5EF71D4701934BDA228435C68AC3D5CEB54997878B06A655EEACEFB1345C15867E7FE6C6423660C8B88DF128EBD6BCD85118DBAE16E9252FFB204324E5C8F38CA97759BDBF3CB0083", - "51FE87996F194A2585E438B023B345439EA60D1AEBED4650CDAF48A4D4EEC4FC77DC71CC4B09D3BEEF8B7B7AF716CE2B4EFFB3AC9E6323C18AC35E0AA6E2BBBC8889490EB6226C896B0D105EAB42BFE7053CCF00ED66BA94C1BA09A792AA873F0C3B26C5C5F9A936E57B25"}, - {"7086816D00D648FB8304AA8C9E552E1B69A9955FB59B25D1", - "0F45CF7F0BF31CCEB85D9DA10F4D749F", - "93F27C60A417D9F0669E86ACC784FC8917B502DAF30A6338F11B30B94D74FEFE2F8BE1BBE2EAD10FAB7EED3C6F72B7C3ECEE1937C32ED4970A6404E139209C05", - "877F046601F3CBE4FB1491943FA29487E738F94B99AF206262A1D6FF856C9AA0B8D4D08A54370C98F8E88FA3DCC2B14C1F76D71B2A4C7963AEE8AF960464C5BEC8357AD00DC8", - "FE96906B895CE6A8E72BC72344E2C8BB3C63113D70EAFA26C299BAFE77A8A6568172EB447FB3E86648A0AF3512DEB1AAC0819F3EC553903BF28A9FB0F43411237A774BF9EE03E445D280FBB9CD12B9BAAB6EF5E52691"}, - {"062F65A896D5BF1401BADFF70E91B458E1F9BD4888CB2E4D", - "5B11EA1D6008EBB41CF892FCA5B943D1", - "BAF4FF5C8242", - "A8870E091238355984EB2F7D61A865B9170F440BFF999A5993DD41A10F4440D21FF948DDA2BF663B2E03AC3324492DC5E40262ECC6A65C07672353BE23E7FB3A9D79FF6AA38D97960905A38DECC312CB6A59E5467ECF06C311CD43ADC0B543EDF34FE8BE611F176460D5627CA51F8F8D9FED71F55C", - "B10E127A632172CF8AA7539B140D2C9C2590E6F28C3CB892FC498FCE56A34F732FBFF32E79C7B9747D9094E8635A0C084D6F0247F9768FB5FF83493799A9BEC6C39572120C40E9292C8C947AE8573462A9108C36D9D7112E6995AE5867E6C8BB387D1C5D4BEF524F391B9FD9F0A3B4BFA079E915BCD920185CFD38D114C558928BD7D47877"}, - {"38A8E45D6D705A11AF58AED5A1344896998EACF359F2E26A", - "FD82B5B31804FF47D44199B533D0CF84", - "DE454D4E62FE879F2050EE3E25853623D3E9AC52EEC1A1779A48CFAF5ECA0BFDE44749391866D1", - "B804", - "164BB965C05EBE0931A1A63293EDF9C38C27"}, - {"34C33C97C6D7A0850DA94D78A58DC61EC717CD7574833068", - "343BE00DA9483F05C14F2E9EB8EA6AE8", - "78312A43EFDE3CAE34A65796FF059A3FE15304EEA5CF1D9306949FE5BF3349D4977D4EBE76C040FE894C5949E4E4D6681153DA87FB9AC5062063CA2EA183566343362370944CE0362D25FC195E124FD60E8682E665D13F2229DDA3E4B2CB1DCA", - "CC11BB284B1153578E4A5ED9D937B869DAF00F5B1960C23455CA9CC43F486A3BE0B66254F1041F04FDF459C8640465B6E1D2CF899A381451E8E7FCB50CF87823BE77E24B132BBEEDC72E53369B275E1D8F49ECE59F4F215230AC4FE133FC80E4F634EE80BA4682B62C86", - "E7F703DC31A95E3A4919FF957836CB76C063D81702AEA4703E1C2BF30831E58C4609D626EC6810E12EAA5B930F049FF9EFC22C3E3F1EBD4A1FB285CB02A1AC5AD46B425199FC0A85670A5C4E3DAA9636C8F64C199F42F18AAC8EA7457FD377F322DD7752D7D01B946C8F0A97E6113F0D50106F319AFD291AAACE"}, - {"C6ECF7F053573E403E61B83052A343D93CBCC179D1E835BE", - "E280E13D7367042E3AA09A80111B6184", - "21486C9D7A9647", - "5F2639AFA6F17931853791CD8C92382BBB677FD72D0AB1A080D0E49BFAA21810E963E4FACD422E92F65CBFAD5884A60CD94740DF31AF02F95AA57DA0C4401B0ED906", - "5C51DB20755302070C45F52E50128A67C8B2E4ED0EACB7E29998CCE2E8C289DD5655913EC1A51CC3AABE5CDC2402B2BE7D6D4BF6945F266FBD70BA9F37109067157AE7530678B45F64475D4EBFCB5FFF46A5"}, - {"5EC6CF7401BC57B18EF154E8C38ACCA8959E57D2F3975FF5", - "656B41CB3F9CF8C08BAD7EBFC80BD225", - "6B817C2906E2AF425861A7EF59BA5801F143EE2A139EE72697CDE168B4", - "2C0E1DDC9B1E5389BA63845B18B1F8A1DB062037151BCC56EF7C21C0BB4DAE366636BBA975685D7CC5A94AFBE89C769016388C56FB7B57CE750A12B718A8BDCF70E80E8659A8330EFC8F86640F21735E8C80E23FE43ABF23507CE3F964AE4EC99D", - "ED780CF911E6D1AA8C979B889B0B9DC1ABE261832980BDBFB576901D9EF5AB8048998E31A15BE54B3E5845A4D136AD24D0BDA1C3006168DF2F8AC06729CB0818867398150020131D8F04EDF1923758C9EABB5F735DE5EA1758D4BC0ACFCA98AFD202E9839B8720253693B874C65586C6F0"}, - {"C92F678EB2208662F5BCF3403EC05F5961E957908A3E79421E1D25FC19054153", - "DA0F3A40983D92F2D4C01FED33C7A192", - "2B6E9D26DB406A0FAB47608657AA10EFC2B4AA5F459B29FF85AC9A40BFFE7AEB04F77E9A11FAAA116D7F6D4DA417671A9AB02C588E0EF59CB1BFB4B1CC931B63A3B3A159FCEC97A04D1E6F0C7E6A9CEF6B0ABB04758A69F1FE754DF4C2610E8C46B6CF413BDB31351D55BEDCB7B4A13A1C98E10984475E0F2F957853", - "F37326A80E08", - "83519E53E321D334F7C10B568183775C0E9AAE55F806"}, - {"6847E0491BE57E72995D186D50094B0B3593957A5146798FCE68B287B2FB37B5", - "3EE1182AEBB19A02B128F28E1D5F7F99", - "D9F35ABB16D776CE", - "DB7566ED8EA95BDF837F23DB277BAFBC5E70D1105ADFD0D9EF15475051B1EF94709C67DCA9F8D5", - "2CDCED0C9EBD6E2A508822A685F7DCD1CDD99E7A5FCA786C234E7F7F1D27EC49751AD5DCFA30C5EDA87C43CAE3B919B6BBCFE34C8EDA59"}, - {"82B019673642C08388D3E42075A4D5D587558C229E4AB8F660E37650C4C41A0A", - "336F5D681E0410FAE7B607246092C6DC", - "D430CBD8FE435B64214E9E9CDC5DE99D31CFCFB8C10AA0587A49DF276611", - "998404153AD77003E1737EDE93ED79859EE6DCCA93CB40C4363AA817ABF2DBBD46E42A14A7183B6CC01E12A577888141363D0AE011EB6E8D28C0B235", - "9BEF69EEB60BD3D6065707B7557F25292A8872857CFBD24F2F3C088E4450995333088DA50FD9121221C504DF1D0CD5EFE6A12666C5D5BB12282CF4C19906E9CFAB97E9BDF7F49DC17CFC384B"}, - {"747B2E269B1859F0622C15C8BAD6A725028B1F94B8DB7326948D1E6ED663A8BC", - "AB91F7245DDCE3F1C747872D47BE0A8A", - "3B03F786EF1DDD76E1D42646DA4CD2A5165DC5383CE86D1A0B5F13F910DC278A4E451EE0192CBA178E13B3BA27FDC7840DF73D2E104B", - "6B803F4701114F3E5FE21718845F8416F70F626303F545BE197189E0A2BA396F37CE06D389EB2658BC7D56D67868708F6D0D32", - "1570DDB0BCE75AA25D1957A287A2C36B1A5F2270186DA81BA6112B7F43B0F3D1D0ED072591DCF1F1C99BBB25621FC39B896FF9BD9413A2845363A9DCD310C32CF98E57"}, - {"02E59853FB29AEDA0FE1C5F19180AD99A12FF2F144670BB2B8BADF09AD812E0A", - "C691294EF67CD04D1B9242AF83DD1421", - "879334DAE3", - "1E17F46A98FEF5CBB40759D95354", - "FED8C3FF27DDF6313AED444A2985B36CBA268AAD6AAC563C0BA28F6DB5DB"}, - {"F6C1FB9B4188F2288FF03BD716023198C3582CF2A037FC2F29760916C2B7FCDB", - "4228DA0678CA3534588859E77DFF014C", - "D8153CAF35539A61DD8D05B3C9B44F01E564FB9348BCD09A1C23B84195171308861058F0A3CD2A55B912A3AAEE06FF4D356C77275828F2157C2FC7C115DA39E443210CCC56BEDB0CC99BBFB227ABD5CC454F4E7F547C7378A659EEB6A7E809101A84F866503CB18D4484E1FA09B3EC7FC75EB2E35270800AA7", - "23B660A779AD285704B12EC1C580387A47BEC7B00D452C6570", - "5AA642BBABA8E49849002A2FAF31DB8FC7773EFDD656E469CEC19B3206D4174C9A263D0A05484261F6"}, - {"8FF6086F1FADB9A3FBE245EAC52640C43B39D43F89526BB5A6EBA47710931446", - "943188480C99437495958B0AE4831AA9", - "AD5CD0BDA426F6EBA23C8EB23DC73FF9FEC173355EDBD6C9344C4C4383F211888F7CE6B29899A6801DF6B38651A7C77150941A", - "80CD5EA8D7F81DDF5070B934937912E8F541A5301877528EB41AB60C020968D459960ED8FB73083329841A", - "ABAE8EB7F36FCA2362551E72DAC890BA1BB6794797E0FC3B67426EC9372726ED4725D379EA0AC9147E48DCD0005C502863C2C5358A38817C8264B5"}, - {"A083B54E6B1FE01B65D42FCD248F97BB477A41462BBFE6FD591006C022C8FD84", - "B0490F5BD68A52459556B3749ACDF40E", - "8892E047DA5CFBBDF7F3CFCBD1BD21C6D4C80774B1826999234394BD3E513CC7C222BB40E1E3140A152F19B3802F0D036C24A590512AD0E8", - "D7B15752789DC94ED0F36778A5C7BBB207BEC32BAC66E702B39966F06E381E090C6757653C3D26A81EC6AD6C364D66867A334C91BB0B8A8A4B6EACDF0783D09010AEBA2DD2062308FE99CC1F", - "C071280A732ADC93DF272BF1E613B2BB7D46FC6665EF2DC1671F3E211D6BDE1D6ADDD28DF3AA2E47053FC8BB8AE9271EC8BC8B2CFFA320D225B451685B6D23ACEFDD241FE284F8ADC8DB07F456985B14330BBB66E0FB212213E05B3E"}, -} diff --git a/vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go b/vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go deleted file mode 100644 index a6bdf512..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/internal/byteutil/byteutil.go +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (C) 2019 ProtonTech AG -// This file contains necessary tools for the aex and ocb packages. -// -// These functions SHOULD NOT be used elsewhere, since they are optimized for -// specific input nature in the EAX and OCB modes of operation. - -package byteutil - -// GfnDouble computes 2 * input in the field of 2^n elements. -// The irreducible polynomial in the finite field for n=128 is -// x^128 + x^7 + x^2 + x + 1 (equals 0x87) -// Constant-time execution in order to avoid side-channel attacks -func GfnDouble(input []byte) []byte { - if len(input) != 16 { - panic("Doubling in GFn only implemented for n = 128") - } - // If the first bit is zero, return 2L = L << 1 - // Else return (L << 1) xor 0^120 10000111 - shifted := ShiftBytesLeft(input) - shifted[15] ^= ((input[0] >> 7) * 0x87) - return shifted -} - -// ShiftBytesLeft outputs the byte array corresponding to x << 1 in binary. -func ShiftBytesLeft(x []byte) []byte { - l := len(x) - dst := make([]byte, l) - for i := 0; i < l-1; i++ { - dst[i] = (x[i] << 1) | (x[i+1] >> 7) - } - dst[l-1] = x[l-1] << 1 - return dst -} - -// ShiftNBytesLeft puts in dst the byte array corresponding to x << n in binary. -func ShiftNBytesLeft(dst, x []byte, n int) { - // Erase first n / 8 bytes - copy(dst, x[n/8:]) - - // Shift the remaining n % 8 bits - bits := uint(n % 8) - l := len(dst) - for i := 0; i < l-1; i++ { - dst[i] = (dst[i] << bits) | (dst[i+1] >> uint(8 - bits)) - } - dst[l-1] = dst[l-1] << bits - - // Append trailing zeroes - dst = append(dst, make([]byte, n/8)...) -} - -// XorBytesMut assumes equal input length, replaces X with X XOR Y -func XorBytesMut(X, Y []byte) { - for i := 0; i < len(X); i++ { - X[i] ^= Y[i] - } -} - - -// XorBytes assumes equal input length, puts X XOR Y into Z -func XorBytes(Z, X, Y []byte) { - for i := 0; i < len(X); i++ { - Z[i] = X[i] ^ Y[i] - } -} - -// RightXor XORs smaller input (assumed Y) at the right of the larger input (assumed X) -func RightXor(X, Y []byte) []byte { - offset := len(X) - len(Y) - xored := make([]byte, len(X)); - copy(xored, X) - for i := 0; i < len(Y); i++ { - xored[offset + i] ^= Y[i] - } - return xored -} - -// SliceForAppend takes a slice and a requested number of bytes. It returns a -// slice with the contents of the given slice followed by that many bytes and a -// second slice that aliases into it and contains only the extra bytes. If the -// original slice has sufficient capacity then no allocation is performed. -func SliceForAppend(in []byte, n int) (head, tail []byte) { - if total := len(in) + n; cap(in) >= total { - head = in[:total] - } else { - head = make([]byte, total) - copy(head, in) - } - tail = head[len(in):] - return -} - diff --git a/vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go b/vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go deleted file mode 100644 index 7f78cfa7..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/ocb/ocb.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright (C) 2019 ProtonTech AG - -// Package ocb provides an implementation of the OCB (offset codebook) mode of -// operation, as described in RFC-7253 of the IRTF and in Rogaway, Bellare, -// Black and Krovetz - OCB: A BLOCK-CIPHER MODE OF OPERATION FOR EFFICIENT -// AUTHENTICATED ENCRYPTION (2003). -// Security considerations (from RFC-7253): A private key MUST NOT be used to -// encrypt more than 2^48 blocks. Tag length should be at least 12 bytes (a -// brute-force forging adversary succeeds after 2^{tag length} attempts). A -// single key SHOULD NOT be used to decrypt ciphertext with different tag -// lengths. Nonces need not be secret, but MUST NOT be reused. -// This package only supports underlying block ciphers with 128-bit blocks, -// such as AES-{128, 192, 256}, but may be extended to other sizes. -package ocb - -import ( - "bytes" - "crypto/cipher" - "crypto/subtle" - "errors" - "github.com/ProtonMail/go-crypto/internal/byteutil" - "math/bits" -) - -type ocb struct { - block cipher.Block - tagSize int - nonceSize int - mask mask - // Optimized en/decrypt: For each nonce N used to en/decrypt, the 'Ktop' - // internal variable can be reused for en/decrypting with nonces sharing - // all but the last 6 bits with N. The prefix of the first nonce used to - // compute the new Ktop, and the Ktop value itself, are stored in - // reusableKtop. If using incremental nonces, this saves one block cipher - // call every 63 out of 64 OCB encryptions, and stores one nonce and one - // output of the block cipher in memory only. - reusableKtop reusableKtop -} - -type mask struct { - // L_*, L_$, (L_i)_{i ∈ N} - lAst []byte - lDol []byte - L [][]byte -} - -type reusableKtop struct { - noncePrefix []byte - Ktop []byte -} - -const ( - defaultTagSize = 16 - defaultNonceSize = 15 -) - -const ( - enc = iota - dec -) - -func (o *ocb) NonceSize() int { - return o.nonceSize -} - -func (o *ocb) Overhead() int { - return o.tagSize -} - -// NewOCB returns an OCB instance with the given block cipher and default -// tag and nonce sizes. -func NewOCB(block cipher.Block) (cipher.AEAD, error) { - return NewOCBWithNonceAndTagSize(block, defaultNonceSize, defaultTagSize) -} - -// NewOCBWithNonceAndTagSize returns an OCB instance with the given block -// cipher, nonce length, and tag length. Panics on zero nonceSize and -// exceedingly long tag size. -// -// It is recommended to use at least 12 bytes as tag length. -func NewOCBWithNonceAndTagSize( - block cipher.Block, nonceSize, tagSize int) (cipher.AEAD, error) { - if block.BlockSize() != 16 { - return nil, ocbError("Block cipher must have 128-bit blocks") - } - if nonceSize < 1 { - return nil, ocbError("Incorrect nonce length") - } - if nonceSize >= block.BlockSize() { - return nil, ocbError("Nonce length exceeds blocksize - 1") - } - if tagSize > block.BlockSize() { - return nil, ocbError("Custom tag length exceeds blocksize") - } - return &ocb{ - block: block, - tagSize: tagSize, - nonceSize: nonceSize, - mask: initializeMaskTable(block), - reusableKtop: reusableKtop{ - noncePrefix: nil, - Ktop: nil, - }, - }, nil -} - -func (o *ocb) Seal(dst, nonce, plaintext, adata []byte) []byte { - if len(nonce) > o.nonceSize { - panic("crypto/ocb: Incorrect nonce length given to OCB") - } - ret, out := byteutil.SliceForAppend(dst, len(plaintext)+o.tagSize) - o.crypt(enc, out, nonce, adata, plaintext) - return ret -} - -func (o *ocb) Open(dst, nonce, ciphertext, adata []byte) ([]byte, error) { - if len(nonce) > o.nonceSize { - panic("Nonce too long for this instance") - } - if len(ciphertext) < o.tagSize { - return nil, ocbError("Ciphertext shorter than tag length") - } - sep := len(ciphertext) - o.tagSize - ret, out := byteutil.SliceForAppend(dst, len(ciphertext)) - ciphertextData := ciphertext[:sep] - tag := ciphertext[sep:] - o.crypt(dec, out, nonce, adata, ciphertextData) - if subtle.ConstantTimeCompare(ret[sep:], tag) == 1 { - ret = ret[:sep] - return ret, nil - } - for i := range out { - out[i] = 0 - } - return nil, ocbError("Tag authentication failed") -} - -// On instruction enc (resp. dec), crypt is the encrypt (resp. decrypt) -// function. It returns the resulting plain/ciphertext with the tag appended. -func (o *ocb) crypt(instruction int, Y, nonce, adata, X []byte) []byte { - // - // Consider X as a sequence of 128-bit blocks - // - // Note: For encryption (resp. decryption), X is the plaintext (resp., the - // ciphertext without the tag). - blockSize := o.block.BlockSize() - - // - // Nonce-dependent and per-encryption variables - // - // Zero out the last 6 bits of the nonce into truncatedNonce to see if Ktop - // is already computed. - truncatedNonce := make([]byte, len(nonce)) - copy(truncatedNonce, nonce) - truncatedNonce[len(truncatedNonce)-1] &= 192 - Ktop := make([]byte, blockSize) - if bytes.Equal(truncatedNonce, o.reusableKtop.noncePrefix) { - Ktop = o.reusableKtop.Ktop - } else { - // Nonce = num2str(TAGLEN mod 128, 7) || zeros(120 - bitlen(N)) || 1 || N - paddedNonce := append(make([]byte, blockSize-1-len(nonce)), 1) - paddedNonce = append(paddedNonce, truncatedNonce...) - paddedNonce[0] |= byte(((8 * o.tagSize) % (8 * blockSize)) << 1) - // Last 6 bits of paddedNonce are already zero. Encrypt into Ktop - paddedNonce[blockSize-1] &= 192 - Ktop = paddedNonce - o.block.Encrypt(Ktop, Ktop) - o.reusableKtop.noncePrefix = truncatedNonce - o.reusableKtop.Ktop = Ktop - } - - // Stretch = Ktop || ((lower half of Ktop) XOR (lower half of Ktop << 8)) - xorHalves := make([]byte, blockSize/2) - byteutil.XorBytes(xorHalves, Ktop[:blockSize/2], Ktop[1:1+blockSize/2]) - stretch := append(Ktop, xorHalves...) - bottom := int(nonce[len(nonce)-1] & 63) - offset := make([]byte, len(stretch)) - byteutil.ShiftNBytesLeft(offset, stretch, bottom) - offset = offset[:blockSize] - - // - // Process any whole blocks - // - // Note: For encryption Y is ciphertext || tag, for decryption Y is - // plaintext || tag. - checksum := make([]byte, blockSize) - m := len(X) / blockSize - for i := 0; i < m; i++ { - index := bits.TrailingZeros(uint(i + 1)) - if len(o.mask.L)-1 < index { - o.mask.extendTable(index) - } - byteutil.XorBytesMut(offset, o.mask.L[bits.TrailingZeros(uint(i+1))]) - blockX := X[i*blockSize : (i+1)*blockSize] - blockY := Y[i*blockSize : (i+1)*blockSize] - byteutil.XorBytes(blockY, blockX, offset) - switch instruction { - case enc: - o.block.Encrypt(blockY, blockY) - byteutil.XorBytesMut(blockY, offset) - byteutil.XorBytesMut(checksum, blockX) - case dec: - o.block.Decrypt(blockY, blockY) - byteutil.XorBytesMut(blockY, offset) - byteutil.XorBytesMut(checksum, blockY) - } - } - // - // Process any final partial block and compute raw tag - // - tag := make([]byte, blockSize) - if len(X)%blockSize != 0 { - byteutil.XorBytesMut(offset, o.mask.lAst) - pad := make([]byte, blockSize) - o.block.Encrypt(pad, offset) - chunkX := X[blockSize*m:] - chunkY := Y[blockSize*m : len(X)] - byteutil.XorBytes(chunkY, chunkX, pad[:len(chunkX)]) - // P_* || bit(1) || zeroes(127) - len(P_*) - switch instruction { - case enc: - paddedY := append(chunkX, byte(128)) - paddedY = append(paddedY, make([]byte, blockSize-len(chunkX)-1)...) - byteutil.XorBytesMut(checksum, paddedY) - case dec: - paddedX := append(chunkY, byte(128)) - paddedX = append(paddedX, make([]byte, blockSize-len(chunkY)-1)...) - byteutil.XorBytesMut(checksum, paddedX) - } - byteutil.XorBytes(tag, checksum, offset) - byteutil.XorBytesMut(tag, o.mask.lDol) - o.block.Encrypt(tag, tag) - byteutil.XorBytesMut(tag, o.hash(adata)) - copy(Y[blockSize*m+len(chunkY):], tag[:o.tagSize]) - } else { - byteutil.XorBytes(tag, checksum, offset) - byteutil.XorBytesMut(tag, o.mask.lDol) - o.block.Encrypt(tag, tag) - byteutil.XorBytesMut(tag, o.hash(adata)) - copy(Y[blockSize*m:], tag[:o.tagSize]) - } - return Y -} - -// This hash function is used to compute the tag. Per design, on empty input it -// returns a slice of zeros, of the same length as the underlying block cipher -// block size. -func (o *ocb) hash(adata []byte) []byte { - // - // Consider A as a sequence of 128-bit blocks - // - A := make([]byte, len(adata)) - copy(A, adata) - blockSize := o.block.BlockSize() - - // - // Process any whole blocks - // - sum := make([]byte, blockSize) - offset := make([]byte, blockSize) - m := len(A) / blockSize - for i := 0; i < m; i++ { - chunk := A[blockSize*i : blockSize*(i+1)] - index := bits.TrailingZeros(uint(i + 1)) - // If the mask table is too short - if len(o.mask.L)-1 < index { - o.mask.extendTable(index) - } - byteutil.XorBytesMut(offset, o.mask.L[index]) - byteutil.XorBytesMut(chunk, offset) - o.block.Encrypt(chunk, chunk) - byteutil.XorBytesMut(sum, chunk) - } - - // - // Process any final partial block; compute final hash value - // - if len(A)%blockSize != 0 { - byteutil.XorBytesMut(offset, o.mask.lAst) - // Pad block with 1 || 0 ^ 127 - bitlength(a) - ending := make([]byte, blockSize-len(A)%blockSize) - ending[0] = 0x80 - encrypted := append(A[blockSize*m:], ending...) - byteutil.XorBytesMut(encrypted, offset) - o.block.Encrypt(encrypted, encrypted) - byteutil.XorBytesMut(sum, encrypted) - } - return sum -} - -func initializeMaskTable(block cipher.Block) mask { - // - // Key-dependent variables - // - lAst := make([]byte, block.BlockSize()) - block.Encrypt(lAst, lAst) - lDol := byteutil.GfnDouble(lAst) - L := make([][]byte, 1) - L[0] = byteutil.GfnDouble(lDol) - - return mask{ - lAst: lAst, - lDol: lDol, - L: L, - } -} - -// Extends the L array of mask m up to L[limit], with L[i] = GfnDouble(L[i-1]) -func (m *mask) extendTable(limit int) { - for i := len(m.L); i <= limit; i++ { - m.L = append(m.L, byteutil.GfnDouble(m.L[i-1])) - } -} - -func ocbError(err string) error { - return errors.New("crypto/ocb: " + err) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/ocb/random_vectors.go b/vendor/github.com/ProtonMail/go-crypto/ocb/random_vectors.go deleted file mode 100644 index 0efaf344..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/ocb/random_vectors.go +++ /dev/null @@ -1,136 +0,0 @@ -// In the test vectors provided by RFC 7253, the "bottom" -// internal variable, which defines "offset" for the first time, does not -// exceed 15. However, it can attain values up to 63. - -// These vectors include key length in {128, 192, 256}, tag size 128, and -// random nonce, header, and plaintext lengths. - -// This file was automatically generated. - -package ocb - -var randomVectors = []struct { - key, nonce, header, plaintext, ciphertext string -}{ - - {"9438C5D599308EAF13F800D2D31EA7F0", - "C38EE4801BEBFFA1CD8635BE", - "0E507B7DADD8A98CDFE272D3CB6B3E8332B56AE583FB049C0874D4200BED16BD1A044182434E9DA0E841F182DFD5B3016B34641CED0784F1745F63AB3D0DA22D3351C9EF9A658B8081E24498EBF61FCE40DA6D8E184536", - "962D227786FB8913A8BAD5DC3250", - "EEDEF5FFA5986D1E3BF86DDD33EF9ADC79DCA06E215FA772CCBA814F63AD"}, - {"BA7DE631C7D6712167C6724F5B9A2B1D", - "35263EBDA05765DC0E71F1F5", - "0103257B4224507C0242FEFE821EA7FA42E0A82863E5F8B68F7D881B4B44FA428A2B6B21D2F591260802D8AB6D83", - "9D6D1FC93AE8A64E7889B7B2E3521EFA9B920A8DDB692E6F833DDC4A38AFA535E5E2A3ED82CB7E26404AB86C54D01C4668F28398C2DF33D5D561CBA1C8DCFA7A912F5048E545B59483C0E3221F54B14DAA2E4EB657B3BEF9554F34CAD69B2724AE962D3D8A", - "E93852D1985C5E775655E937FA79CE5BF28A585F2AF53A5018853B9634BE3C84499AC0081918FDCE0624494D60E25F76ACD6853AC7576E3C350F332249BFCABD4E73CEABC36BE4EDDA40914E598AE74174A0D7442149B26990899491BDDFE8FC54D6C18E83AE9E9A6FFBF5D376565633862EEAD88D"}, - {"2E74B25289F6FD3E578C24866E9C72A5", - "FD912F15025AF8414642BA1D1D", - "FB5FB8C26F365EEDAB5FE260C6E3CCD27806729C8335F146063A7F9EA93290E56CF84576EB446350D22AD730547C267B1F0BBB97EB34E1E2C41A", - "6C092EBF78F76EE8C1C6E592277D9545BA16EDB67BC7D8480B9827702DC2F8A129E2B08A2CE710CA7E1DA45CE162BB6CD4B512E632116E2211D3C90871EFB06B8D4B902681C7FB", - "6AC0A77F26531BF4F354A1737F99E49BE32ECD909A7A71AD69352906F54B08A9CE9B8CA5D724CBFFC5673437F23F630697F3B84117A1431D6FA8CC13A974FB4AD360300522E09511B99E71065D5AC4BBCB1D791E864EF4"}, - {"E7EC507C802528F790AFF5303A017B17", - "4B97A7A568940A9E3CE7A99E93031E", - "28349BDC5A09390C480F9B8AA3EDEA3DDB8B9D64BCA322C570B8225DF0E31190DAB25A4014BA39519E02ABFB12B89AA28BBFD29E486E7FB28734258C817B63CED9912DBAFEBB93E2798AB2890DE3B0ACFCFF906AB15563EF7823CE83D27CDB251195E22BD1337BCBDE65E7C2C427321C463C2777BFE5AEAA", - "9455B3EA706B74", - "7F33BA3EA848D48A96B9530E26888F43EBD4463C9399B6"}, - {"6C928AA3224736F28EE7378DE0090191", - "8936138E2E4C6A13280017A1622D", - "6202717F2631565BDCDC57C6584543E72A7C8BD444D0D108ED35069819633C", - "DA0691439E5F035F3E455269D14FE5C201C8C9B0A3FE2D3F86BCC59387C868FE65733D388360B31E3CE28B4BF6A8BE636706B536D5720DB66B47CF1C7A5AFD6F61E0EF90F1726D6B0E169F9A768B2B7AE4EE00A17F630AC905FCAAA1B707FFF25B3A1AAE83B504837C64A5639B2A34002B300EC035C9B43654DA55", - "B8804D182AB0F0EEB464FA7BD1329AD6154F982013F3765FEDFE09E26DAC078C9C1439BFC1159D6C02A25E3FF83EF852570117B315852AD5EE20E0FA3AA0A626B0E43BC0CEA38B44579DD36803455FB46989B90E6D229F513FD727AF8372517E9488384C515D6067704119C931299A0982EDDFB9C2E86A90C450C077EB222511EC9CCABC9FCFDB19F70088"}, - {"ECEA315CA4B3F425B0C9957A17805EA4", - "664CDAE18403F4F9BA13015A44FC", - "642AFB090D6C6DB46783F08B01A3EF2A8FEB5736B531EAC226E7888FCC8505F396818F83105065FACB3267485B9E5E4A0261F621041C08FCCB2A809A49AB5252A91D0971BCC620B9D614BD77E57A0EED2FA5", - "6852C31F8083E20E364CEA21BB7854D67CEE812FE1C9ED2425C0932A90D3780728D1BB", - "2ECEF962A9695A463ADABB275BDA9FF8B2BA57AEC2F52EFFB700CD9271A74D2A011C24AEA946051BD6291776429B7E681BA33E"}, - {"4EE616C4A58AAA380878F71A373461F6", - "91B8C9C176D9C385E9C47E52", - "CDA440B7F9762C572A718AC754EDEECC119E5EE0CCB9FEA4FFB22EEE75087C032EBF3DA9CDD8A28CC010B99ED45143B41A4BA50EA2A005473F89639237838867A57F23B0F0ED3BF22490E4501DAC9C658A9B9F", - "D6E645FA9AE410D15B8123FD757FA356A8DBE9258DDB5BE88832E615910993F497EC", - "B70ED7BF959FB2AAED4F36174A2A99BFB16992C8CDF369C782C4DB9C73DE78C5DB8E0615F647243B97ACDB24503BC9CADC48"}, - {"DCD475773136C830D5E3D0C5FE05B7FF", - "BB8E1FBB483BE7616A922C4A", - "36FEF2E1CB29E76A6EA663FC3AF66ECD7404F466382F7B040AABED62293302B56E8783EF7EBC21B4A16C3E78A7483A0A403F253A2CDC5BBF79DC3DAE6C73F39A961D8FBBE8D41B", - "441E886EA38322B2437ECA7DEB5282518865A66780A454E510878E61BFEC3106A3CD93D2A02052E6F9E1832F9791053E3B76BF4C07EFDD6D4106E3027FABB752E60C1AA425416A87D53938163817A1051EBA1D1DEEB4B9B25C7E97368B52E5911A31810B0EC5AF547559B6142D9F4C4A6EF24A4CF75271BF9D48F62B", - "1BE4DD2F4E25A6512C2CC71D24BBB07368589A94C2714962CD0ACE5605688F06342587521E75F0ACAFFD86212FB5C34327D238DB36CF2B787794B9A4412E7CD1410EA5DDD2450C265F29CF96013CD213FD2880657694D718558964BC189B4A84AFCF47EB012935483052399DBA5B088B0A0477F20DFE0E85DCB735E21F22A439FB837DD365A93116D063E607"}, - {"3FBA2B3D30177FFE15C1C59ED2148BB2C091F5615FBA7C07", - "FACF804A4BEBF998505FF9DE", - "8213B9263B2971A5BDA18DBD02208EE1", - "15B323926993B326EA19F892D704439FC478828322AF72118748284A1FD8A6D814E641F70512FD706980337379F31DC63355974738D7FEA87AD2858C0C2EBBFBE74371C21450072373C7B651B334D7C4D43260B9D7CCD3AF9EDB", - "6D35DC1469B26E6AAB26272A41B46916397C24C485B61162E640A062D9275BC33DDCFD3D9E1A53B6C8F51AC89B66A41D59B3574197A40D9B6DCF8A4E2A001409C8112F16B9C389E0096179DB914E05D6D11ED0005AD17E1CE105A2F0BAB8F6B1540DEB968B7A5428FF44"}, - {"53B52B8D4D748BCDF1DDE68857832FA46227FA6E2F32EFA1", - "0B0EF53D4606B28D1398355F", - "F23882436349094AF98BCACA8218E81581A043B19009E28EFBF2DE37883E04864148CC01D240552CA8844EC1456F42034653067DA67E80F87105FD06E14FF771246C9612867BE4D215F6D761", - "F15030679BD4088D42CAC9BF2E9606EAD4798782FA3ED8C57EBE7F84A53236F51B25967C6489D0CD20C9EEA752F9BC", - "67B96E2D67C3729C96DAEAEDF821D61C17E648643A2134C5621FEC621186915AD80864BFD1EB5B238BF526A679385E012A457F583AFA78134242E9D9C1B4E4"}, - {"0272DD80F23399F49BFC320381A5CD8225867245A49A7D41", - "5C83F4896D0738E1366B1836", - "69B0337289B19F73A12BAEEA857CCAF396C11113715D9500CCCF48BA08CFF12BC8B4BADB3084E63B85719DB5058FA7C2C11DEB096D7943CFA7CAF5", - "C01AD10FC8B562CD17C7BC2FAB3E26CBDFF8D7F4DEA816794BBCC12336991712972F52816AABAB244EB43B0137E2BAC1DD413CE79531E78BEF782E6B439612BB3AEF154DE3502784F287958EBC159419F9EBA27916A28D6307324129F506B1DE80C1755A929F87", - "FEFE52DD7159C8DD6E8EC2D3D3C0F37AB6CB471A75A071D17EC4ACDD8F3AA4D7D4F7BB559F3C09099E3D9003E5E8AA1F556B79CECDE66F85B08FA5955E6976BF2695EA076388A62D2AD5BAB7CBF1A7F3F4C8D5CDF37CDE99BD3E30B685D9E5EEE48C7C89118EF4878EB89747F28271FA2CC45F8E9E7601"}, - {"3EEAED04A455D6E5E5AB53CFD5AFD2F2BC625C7BF4BE49A5", - "36B88F63ADBB5668588181D774", - "D367E3CB3703E762D23C6533188EF7028EFF9D935A3977150361997EC9DEAF1E4794BDE26AA8B53C124980B1362EC86FCDDFC7A90073171C1BAEE351A53234B86C66E8AB92FAE99EC6967A6D3428892D80", - "573454C719A9A55E04437BF7CBAAF27563CCCD92ADD5E515CD63305DFF0687E5EEF790C5DCA5C0033E9AB129505E2775438D92B38F08F3B0356BA142C6F694", - "E9F79A5B432D9E682C9AAA5661CFC2E49A0FCB81A431E54B42EB73DD3BED3F377FEC556ABA81624BA64A5D739AD41467460088F8D4F442180A9382CA635745473794C382FCDDC49BA4EB6D8A44AE3C"}, - {"B695C691538F8CBD60F039D0E28894E3693CC7C36D92D79D", - "BC099AEB637361BAC536B57618", - "BFFF1A65AE38D1DC142C71637319F5F6508E2CB33C9DCB94202B359ED5A5ED8042E7F4F09231D32A7242976677E6F4C549BF65FADC99E5AF43F7A46FD95E16C2", - "081DF3FD85B415D803F0BE5AC58CFF0023FDDED99788296C3731D8", - "E50C64E3614D94FE69C47092E46ACC9957C6FEA2CCBF96BC62FBABE7424753C75F9C147C42AE26FE171531"}, - {"C9ACBD2718F0689A1BE9802A551B6B8D9CF5614DAF5E65ED", - "B1B0AAF373B8B026EB80422051D8", - "6648C0E61AC733C76119D23FB24548D637751387AA2EAE9D80E912B7BD486CAAD9EAF4D7A5FE2B54AAD481E8EC94BB4D558000896E2010462B70C9FED1E7273080D1", - "189F591F6CB6D59AFEDD14C341741A8F1037DC0DF00FC57CE65C30F49E860255CEA5DC6019380CC0FE8880BC1A9E685F41C239C38F36E3F2A1388865C5C311059C0A", - "922A5E949B61D03BE34AB5F4E58607D4504EA14017BB363DAE3C873059EA7A1C77A746FB78981671D26C2CF6D9F24952D510044CE02A10177E9DB42D0145211DFE6E84369C5E3BC2669EAB4147B2822895F9"}, - {"7A832BD2CF5BF4919F353CE2A8C86A5E406DA2D52BE16A72", - "2F2F17CECF7E5A756D10785A3CB9DB", - "61DA05E3788CC2D8405DBA70C7A28E5AF699863C9F72E6C6770126929F5D6FA267F005EBCF49495CB46400958A3AE80D1289D1C671", - "44E91121195A41AF14E8CFDBD39A4B517BE0DF1A72977ED8A3EEF8EEDA1166B2EB6DB2C4AE2E74FA0F0C74537F659BFBD141E5DDEC67E64EDA85AABD3F52C85A785B9FB3CECD70E7DF", - "BEDF596EA21288D2B84901E188F6EE1468B14D5161D3802DBFE00D60203A24E2AB62714BF272A45551489838C3A7FEAADC177B591836E73684867CCF4E12901DCF2064058726BBA554E84ADC5136F507E961188D4AF06943D3"}, - {"1508E8AE9079AA15F1CEC4F776B4D11BCCB061B58AA56C18", - "BCA625674F41D1E3AB47672DC0C3", - "8B12CF84F16360F0EAD2A41BC021530FFCEC7F3579CAE658E10E2D3D81870F65AFCED0C77C6C4C6E6BA424FF23088C796BA6195ABA35094BF1829E089662E7A95FC90750AE16D0C8AFA55DAC789D7735B970B58D4BE7CEC7341DA82A0179A01929C27A59C5063215B859EA43", - "E525422519ECE070E82C", - "B47BC07C3ED1C0A43BA52C43CBACBCDBB29CAF1001E09FDF7107"}, - {"7550C2761644E911FE9ADD119BAC07376BEA442845FEAD876D7E7AC1B713E464", - "36D2EC25ADD33CDEDF495205BBC923", - "7FCFE81A3790DE97FFC3DE160C470847EA7E841177C2F759571CBD837EA004A6CA8C6F4AEBFF2E9FD552D73EB8A30705D58D70C0B67AEEA280CBBF0A477358ACEF1E7508F2735CD9A0E4F9AC92B8C008F575D3B6278F1C18BD01227E3502E5255F3AB1893632AD00C717C588EF652A51A43209E7EE90", - "2B1A62F8FDFAA3C16470A21AD307C9A7D03ADE8EF72C69B06F8D738CDE578D7AEFD0D40BD9C022FB9F580DF5394C998ACCCEFC5471A3996FB8F1045A81FDC6F32D13502EA65A211390C8D882B8E0BEFD8DD8CBEF51D1597B124E9F7F", - "C873E02A22DB89EB0787DB6A60B99F7E4A0A085D5C4232A81ADCE2D60AA36F92DDC33F93DD8640AC0E08416B187FB382B3EC3EE85A64B0E6EE41C1366A5AD2A282F66605E87031CCBA2FA7B2DA201D975994AADE3DD1EE122AE09604AD489B84BF0C1AB7129EE16C6934850E"}, - {"A51300285E554FDBDE7F771A9A9A80955639DD87129FAEF74987C91FB9687C71", - "81691D5D20EC818FCFF24B33DECC", - "C948093218AA9EB2A8E44A87EEA73FC8B6B75A196819A14BD83709EA323E8DF8B491045220E1D88729A38DBCFFB60D3056DAD4564498FD6574F74512945DEB34B69329ACED9FFC05D5D59DFCD5B973E2ACAFE6AD1EF8BBBC49351A2DD12508ED89ED", - "EB861165DAF7625F827C6B574ED703F03215", - "C6CD1CE76D2B3679C1B5AA1CFD67CCB55444B6BFD3E22C81CBC9BB738796B83E54E3"}, - {"8CE0156D26FAEB7E0B9B800BBB2E9D4075B5EAC5C62358B0E7F6FCE610223282", - "D2A7B94DD12CDACA909D3AD7", - "E021A78F374FC271389AB9A3E97077D755", - "7C26000B58929F5095E1CEE154F76C2A299248E299F9B5ADE6C403AA1FD4A67FD4E0232F214CE7B919EE7A1027D2B76C57475715CD078461", - "C556FB38DF069B56F337B5FF5775CE6EAA16824DFA754F20B78819028EA635C3BB7AA731DE8776B2DCB67DCA2D33EEDF3C7E52EA450013722A41755A0752433ED17BDD5991AAE77A"}, - {"1E8000A2CE00A561C9920A30BF0D7B983FEF8A1014C8F04C35CA6970E6BA02BD", - "65ED3D63F79F90BBFD19775E", - "336A8C0B7243582A46B221AA677647FCAE91", - "134A8B34824A290E7B", - "914FBEF80D0E6E17F8BDBB6097EBF5FBB0554952DC2B9E5151"}, - {"53D5607BBE690B6E8D8F6D97F3DF2BA853B682597A214B8AA0EA6E598650AF15", - "C391A856B9FE234E14BA1AC7BB40FF", - "479682BC21349C4BE1641D5E78FE2C79EC1B9CF5470936DCAD9967A4DCD7C4EFADA593BC9EDE71E6A08829B8580901B61E274227E9D918502DE3", - "EAD154DC09C5E26C5D26FF33ED148B27120C7F2C23225CC0D0631B03E1F6C6D96FEB88C1A4052ACB4CE746B884B6502931F407021126C6AAB8C514C077A5A38438AE88EE", - "938821286EBB671D999B87C032E1D6055392EB564E57970D55E545FC5E8BAB90E6E3E3C0913F6320995FC636D72CD9919657CC38BD51552F4A502D8D1FE56DB33EBAC5092630E69EBB986F0E15CEE9FC8C052501"}, - {"294362FCC984F440CEA3E9F7D2C06AF20C53AAC1B3738CA2186C914A6E193ABB", - "B15B61C8BB39261A8F55AB178EC3", - "D0729B6B75BB", - "2BD089ADCE9F334BAE3B065996C7D616DD0C27DF4218DCEEA0FBCA0F968837CE26B0876083327E25681FDDD620A32EC0DA12F73FAE826CC94BFF2B90A54D2651", - "AC94B25E4E21DE2437B806966CCD5D9385EF0CD4A51AB9FA6DE675C7B8952D67802E9FEC1FDE9F5D1EAB06057498BC0EEA454804FC9D2068982A3E24182D9AC2E7AB9994DDC899A604264583F63D066B"}, - {"959DBFEB039B1A5B8CE6A44649B602AAA5F98A906DB96143D202CD2024F749D9", - "01D7BDB1133E9C347486C1EFA6", - "F3843955BD741F379DD750585EDC55E2CDA05CCBA8C1F4622AC2FE35214BC3A019B8BD12C4CC42D9213D1E1556941E8D8450830287FFB3B763A13722DD4140ED9846FB5FFF745D7B0B967D810A068222E10B259AF1D392035B0D83DC1498A6830B11B2418A840212599171E0258A1C203B05362978", - "A21811232C950FA8B12237C2EBD6A7CD2C3A155905E9E0C7C120", - "63C1CE397B22F1A03F1FA549B43178BC405B152D3C95E977426D519B3DFCA28498823240592B6EEE7A14"}, - {"096AE499F5294173F34FF2B375F0E5D5AB79D0D03B33B1A74D7D576826345DF4", - "0C52B3D11D636E5910A4DD76D32C", - "229E9ECA3053789E937447BC719467075B6138A142DA528DA8F0CF8DDF022FD9AF8E74779BA3AC306609", - "8B7A00038783E8BAF6EDEAE0C4EAB48FC8FD501A588C7E4A4DB71E3604F2155A97687D3D2FFF8569261375A513CF4398CE0F87CA1658A1050F6EF6C4EA3E25", - "C20B6CF8D3C8241825FD90B2EDAC7593600646E579A8D8DAAE9E2E40C3835FE801B2BE4379131452BC5182C90307B176DFBE2049544222FE7783147B690774F6D9D7CEF52A91E61E298E9AA15464AC"}, -} diff --git a/vendor/github.com/ProtonMail/go-crypto/ocb/rfc7253_test_vectors_suite_a.go b/vendor/github.com/ProtonMail/go-crypto/ocb/rfc7253_test_vectors_suite_a.go deleted file mode 100644 index 330309ff..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/ocb/rfc7253_test_vectors_suite_a.go +++ /dev/null @@ -1,78 +0,0 @@ -package ocb - -import ( - "encoding/hex" -) - -// Test vectors from https://tools.ietf.org/html/rfc7253. Note that key is -// shared across tests. -var testKey, _ = hex.DecodeString("000102030405060708090A0B0C0D0E0F") - -var rfc7253testVectors = []struct { - nonce, header, plaintext, ciphertext string -}{ - {"BBAA99887766554433221100", - "", - "", - "785407BFFFC8AD9EDCC5520AC9111EE6"}, - {"BBAA99887766554433221101", - "0001020304050607", - "0001020304050607", - "6820B3657B6F615A5725BDA0D3B4EB3A257C9AF1F8F03009"}, - {"BBAA99887766554433221102", - "0001020304050607", - "", - "81017F8203F081277152FADE694A0A00"}, - {"BBAA99887766554433221103", - "", - "0001020304050607", - "45DD69F8F5AAE72414054CD1F35D82760B2CD00D2F99BFA9"}, - {"BBAA99887766554433221104", - "000102030405060708090A0B0C0D0E0F", - "000102030405060708090A0B0C0D0E0F", - "571D535B60B277188BE5147170A9A22C3AD7A4FF3835B8C5701C1CCEC8FC3358"}, - {"BBAA99887766554433221105", - "000102030405060708090A0B0C0D0E0F", - "", - "8CF761B6902EF764462AD86498CA6B97"}, - {"BBAA99887766554433221106", - "", - "000102030405060708090A0B0C0D0E0F", - "5CE88EC2E0692706A915C00AEB8B2396F40E1C743F52436BDF06D8FA1ECA343D"}, - {"BBAA99887766554433221107", - "000102030405060708090A0B0C0D0E0F1011121314151617", - "000102030405060708090A0B0C0D0E0F1011121314151617", - "1CA2207308C87C010756104D8840CE1952F09673A448A122C92C62241051F57356D7F3C90BB0E07F"}, - {"BBAA99887766554433221108", - "000102030405060708090A0B0C0D0E0F1011121314151617", - "", - "6DC225A071FC1B9F7C69F93B0F1E10DE"}, - {"BBAA99887766554433221109", - "", - "000102030405060708090A0B0C0D0E0F1011121314151617", - "221BD0DE7FA6FE993ECCD769460A0AF2D6CDED0C395B1C3CE725F32494B9F914D85C0B1EB38357FF"}, - {"BBAA9988776655443322110A", - "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", - "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", - "BD6F6C496201C69296C11EFD138A467ABD3C707924B964DEAFFC40319AF5A48540FBBA186C5553C68AD9F592A79A4240"}, - {"BBAA9988776655443322110B", - "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", - "", - "FE80690BEE8A485D11F32965BC9D2A32"}, - {"BBAA9988776655443322110C", - "", - "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F", - "2942BFC773BDA23CABC6ACFD9BFD5835BD300F0973792EF46040C53F1432BCDFB5E1DDE3BC18A5F840B52E653444D5DF"}, - {"BBAA9988776655443322110D", - "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627", - "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627", - "D5CA91748410C1751FF8A2F618255B68A0A12E093FF454606E59F9C1D0DDC54B65E8628E568BAD7AED07BA06A4A69483A7035490C5769E60"}, - {"BBAA9988776655443322110E", - "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627", - "", - "C5CD9D1850C141E358649994EE701B68"}, - {"BBAA9988776655443322110F", - "", - "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627", - "4412923493C57D5DE0D700F753CCE0D1D2D95060122E9F15A5DDBFC5787E50B5CC55EE507BCB084E479AD363AC366B95A98CA5F3000B1479"}, -} diff --git a/vendor/github.com/ProtonMail/go-crypto/ocb/rfc7253_test_vectors_suite_b.go b/vendor/github.com/ProtonMail/go-crypto/ocb/rfc7253_test_vectors_suite_b.go deleted file mode 100644 index 5dc158f0..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/ocb/rfc7253_test_vectors_suite_b.go +++ /dev/null @@ -1,24 +0,0 @@ -package ocb - -// Second set of test vectors from https://tools.ietf.org/html/rfc7253 -var rfc7253TestVectorTaglen96 = struct { - key, nonce, header, plaintext, ciphertext string -}{"0F0E0D0C0B0A09080706050403020100", - "BBAA9988776655443322110D", - "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627", - "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627", - "1792A4E31E0755FB03E31B22116E6C2DDF9EFD6E33D536F1A0124B0A55BAE884ED93481529C76B6AD0C515F4D1CDD4FDAC4F02AA"} - -var rfc7253AlgorithmTest = []struct { - KEYLEN, TAGLEN int - OUTPUT string }{ - {128, 128, "67E944D23256C5E0B6C61FA22FDF1EA2"}, - {192, 128, "F673F2C3E7174AAE7BAE986CA9F29E17"}, - {256, 128, "D90EB8E9C977C88B79DD793D7FFA161C"}, - {128, 96, "77A3D8E73589158D25D01209"}, - {192, 96, "05D56EAD2752C86BE6932C5E"}, - {256, 96, "5458359AC23B0CBA9E6330DD"}, - {128, 64, "192C9B7BD90BA06A"}, - {192, 64, "0066BC6E0EF34E24"}, - {256, 64, "7D4EA5D445501CBE"}, - } diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/aes/keywrap/keywrap.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/aes/keywrap/keywrap.go deleted file mode 100644 index 3c6251d1..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/aes/keywrap/keywrap.go +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2014 Matthew Endsley -// All rights reserved -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted providing 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. -// 2. 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 AUTHOR ``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 AUTHOR 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. - -// Package keywrap is an implementation of the RFC 3394 AES key wrapping -// algorithm. This is used in OpenPGP with elliptic curve keys. -package keywrap - -import ( - "crypto/aes" - "encoding/binary" - "errors" -) - -var ( - // ErrWrapPlaintext is returned if the plaintext is not a multiple - // of 64 bits. - ErrWrapPlaintext = errors.New("keywrap: plainText must be a multiple of 64 bits") - - // ErrUnwrapCiphertext is returned if the ciphertext is not a - // multiple of 64 bits. - ErrUnwrapCiphertext = errors.New("keywrap: cipherText must by a multiple of 64 bits") - - // ErrUnwrapFailed is returned if unwrapping a key fails. - ErrUnwrapFailed = errors.New("keywrap: failed to unwrap key") - - // NB: the AES NewCipher call only fails if the key is an invalid length. - - // ErrInvalidKey is returned when the AES key is invalid. - ErrInvalidKey = errors.New("keywrap: invalid AES key") -) - -// Wrap a key using the RFC 3394 AES Key Wrap Algorithm. -func Wrap(key, plainText []byte) ([]byte, error) { - if len(plainText)%8 != 0 { - return nil, ErrWrapPlaintext - } - - c, err := aes.NewCipher(key) - if err != nil { - return nil, ErrInvalidKey - } - - nblocks := len(plainText) / 8 - - // 1) Initialize variables. - var block [aes.BlockSize]byte - // - Set A = IV, an initial value (see 2.2.3) - for ii := 0; ii < 8; ii++ { - block[ii] = 0xA6 - } - - // - For i = 1 to n - // - Set R[i] = P[i] - intermediate := make([]byte, len(plainText)) - copy(intermediate, plainText) - - // 2) Calculate intermediate values. - for ii := 0; ii < 6; ii++ { - for jj := 0; jj < nblocks; jj++ { - // - B = AES(K, A | R[i]) - copy(block[8:], intermediate[jj*8:jj*8+8]) - c.Encrypt(block[:], block[:]) - - // - A = MSB(64, B) ^ t where t = (n*j)+1 - t := uint64(ii*nblocks + jj + 1) - val := binary.BigEndian.Uint64(block[:8]) ^ t - binary.BigEndian.PutUint64(block[:8], val) - - // - R[i] = LSB(64, B) - copy(intermediate[jj*8:jj*8+8], block[8:]) - } - } - - // 3) Output results. - // - Set C[0] = A - // - For i = 1 to n - // - C[i] = R[i] - return append(block[:8], intermediate...), nil -} - -// Unwrap a key using the RFC 3394 AES Key Wrap Algorithm. -func Unwrap(key, cipherText []byte) ([]byte, error) { - if len(cipherText)%8 != 0 { - return nil, ErrUnwrapCiphertext - } - - c, err := aes.NewCipher(key) - if err != nil { - return nil, ErrInvalidKey - } - - nblocks := len(cipherText)/8 - 1 - - // 1) Initialize variables. - var block [aes.BlockSize]byte - // - Set A = C[0] - copy(block[:8], cipherText[:8]) - - // - For i = 1 to n - // - Set R[i] = C[i] - intermediate := make([]byte, len(cipherText)-8) - copy(intermediate, cipherText[8:]) - - // 2) Compute intermediate values. - for jj := 5; jj >= 0; jj-- { - for ii := nblocks - 1; ii >= 0; ii-- { - // - B = AES-1(K, (A ^ t) | R[i]) where t = n*j+1 - // - A = MSB(64, B) - t := uint64(jj*nblocks + ii + 1) - val := binary.BigEndian.Uint64(block[:8]) ^ t - binary.BigEndian.PutUint64(block[:8], val) - - copy(block[8:], intermediate[ii*8:ii*8+8]) - c.Decrypt(block[:], block[:]) - - // - R[i] = LSB(B, 64) - copy(intermediate[ii*8:ii*8+8], block[8:]) - } - } - - // 3) Output results. - // - If A is an appropriate initial value (see 2.2.3), - for ii := 0; ii < 8; ii++ { - if block[ii] != 0xA6 { - return nil, ErrUnwrapFailed - } - } - - // - For i = 1 to n - // - P[i] = R[i] - return intermediate, nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/armor/armor.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/armor/armor.go deleted file mode 100644 index 3b357e58..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/armor/armor.go +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2010 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 armor implements OpenPGP ASCII Armor, see RFC 4880. OpenPGP Armor is -// very similar to PEM except that it has an additional CRC checksum. -package armor // import "github.com/ProtonMail/go-crypto/openpgp/armor" - -import ( - "bufio" - "bytes" - "encoding/base64" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "io" -) - -// A Block represents an OpenPGP armored structure. -// -// The encoded form is: -// -----BEGIN Type----- -// Headers -// -// base64-encoded Bytes -// '=' base64 encoded checksum -// -----END Type----- -// where Headers is a possibly empty sequence of Key: Value lines. -// -// Since the armored data can be very large, this package presents a streaming -// interface. -type Block struct { - Type string // The type, taken from the preamble (i.e. "PGP SIGNATURE"). - Header map[string]string // Optional headers. - Body io.Reader // A Reader from which the contents can be read - lReader lineReader - oReader openpgpReader -} - -var ArmorCorrupt error = errors.StructuralError("armor invalid") - -const crc24Init = 0xb704ce -const crc24Poly = 0x1864cfb -const crc24Mask = 0xffffff - -// crc24 calculates the OpenPGP checksum as specified in RFC 4880, section 6.1 -func crc24(crc uint32, d []byte) uint32 { - for _, b := range d { - crc ^= uint32(b) << 16 - for i := 0; i < 8; i++ { - crc <<= 1 - if crc&0x1000000 != 0 { - crc ^= crc24Poly - } - } - } - return crc -} - -var armorStart = []byte("-----BEGIN ") -var armorEnd = []byte("-----END ") -var armorEndOfLine = []byte("-----") - -// lineReader wraps a line based reader. It watches for the end of an armor -// block and records the expected CRC value. -type lineReader struct { - in *bufio.Reader - buf []byte - eof bool - crc uint32 - crcSet bool -} - -func (l *lineReader) Read(p []byte) (n int, err error) { - if l.eof { - return 0, io.EOF - } - - if len(l.buf) > 0 { - n = copy(p, l.buf) - l.buf = l.buf[n:] - return - } - - line, isPrefix, err := l.in.ReadLine() - if err != nil { - return - } - if isPrefix { - return 0, ArmorCorrupt - } - - if bytes.HasPrefix(line, armorEnd) { - l.eof = true - return 0, io.EOF - } - - if len(line) == 5 && line[0] == '=' { - // This is the checksum line - var expectedBytes [3]byte - var m int - m, err = base64.StdEncoding.Decode(expectedBytes[0:], line[1:]) - if m != 3 || err != nil { - return - } - l.crc = uint32(expectedBytes[0])<<16 | - uint32(expectedBytes[1])<<8 | - uint32(expectedBytes[2]) - - line, _, err = l.in.ReadLine() - if err != nil && err != io.EOF { - return - } - if !bytes.HasPrefix(line, armorEnd) { - return 0, ArmorCorrupt - } - - l.eof = true - l.crcSet = true - return 0, io.EOF - } - - if len(line) > 96 { - return 0, ArmorCorrupt - } - - n = copy(p, line) - bytesToSave := len(line) - n - if bytesToSave > 0 { - if cap(l.buf) < bytesToSave { - l.buf = make([]byte, 0, bytesToSave) - } - l.buf = l.buf[0:bytesToSave] - copy(l.buf, line[n:]) - } - - return -} - -// openpgpReader passes Read calls to the underlying base64 decoder, but keeps -// a running CRC of the resulting data and checks the CRC against the value -// found by the lineReader at EOF. -type openpgpReader struct { - lReader *lineReader - b64Reader io.Reader - currentCRC uint32 -} - -func (r *openpgpReader) Read(p []byte) (n int, err error) { - n, err = r.b64Reader.Read(p) - r.currentCRC = crc24(r.currentCRC, p[:n]) - - if err == io.EOF && r.lReader.crcSet && r.lReader.crc != uint32(r.currentCRC&crc24Mask) { - return 0, ArmorCorrupt - } - - return -} - -// Decode reads a PGP armored block from the given Reader. It will ignore -// leading garbage. If it doesn't find a block, it will return nil, io.EOF. The -// given Reader is not usable after calling this function: an arbitrary amount -// of data may have been read past the end of the block. -func Decode(in io.Reader) (p *Block, err error) { - r := bufio.NewReaderSize(in, 100) - var line []byte - ignoreNext := false - -TryNextBlock: - p = nil - - // Skip leading garbage - for { - ignoreThis := ignoreNext - line, ignoreNext, err = r.ReadLine() - if err != nil { - return - } - if ignoreNext || ignoreThis { - continue - } - line = bytes.TrimSpace(line) - if len(line) > len(armorStart)+len(armorEndOfLine) && bytes.HasPrefix(line, armorStart) { - break - } - } - - p = new(Block) - p.Type = string(line[len(armorStart) : len(line)-len(armorEndOfLine)]) - p.Header = make(map[string]string) - nextIsContinuation := false - var lastKey string - - // Read headers - for { - isContinuation := nextIsContinuation - line, nextIsContinuation, err = r.ReadLine() - if err != nil { - p = nil - return - } - if isContinuation { - p.Header[lastKey] += string(line) - continue - } - line = bytes.TrimSpace(line) - if len(line) == 0 { - break - } - - i := bytes.Index(line, []byte(": ")) - if i == -1 { - goto TryNextBlock - } - lastKey = string(line[:i]) - p.Header[lastKey] = string(line[i+2:]) - } - - p.lReader.in = r - p.oReader.currentCRC = crc24Init - p.oReader.lReader = &p.lReader - p.oReader.b64Reader = base64.NewDecoder(base64.StdEncoding, &p.lReader) - p.Body = &p.oReader - - return -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/armor/encode.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/armor/encode.go deleted file mode 100644 index 6f07582c..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/armor/encode.go +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright 2010 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 armor - -import ( - "encoding/base64" - "io" -) - -var armorHeaderSep = []byte(": ") -var blockEnd = []byte("\n=") -var newline = []byte("\n") -var armorEndOfLineOut = []byte("-----\n") - -// writeSlices writes its arguments to the given Writer. -func writeSlices(out io.Writer, slices ...[]byte) (err error) { - for _, s := range slices { - _, err = out.Write(s) - if err != nil { - return err - } - } - return -} - -// lineBreaker breaks data across several lines, all of the same byte length -// (except possibly the last). Lines are broken with a single '\n'. -type lineBreaker struct { - lineLength int - line []byte - used int - out io.Writer - haveWritten bool -} - -func newLineBreaker(out io.Writer, lineLength int) *lineBreaker { - return &lineBreaker{ - lineLength: lineLength, - line: make([]byte, lineLength), - used: 0, - out: out, - } -} - -func (l *lineBreaker) Write(b []byte) (n int, err error) { - n = len(b) - - if n == 0 { - return - } - - if l.used == 0 && l.haveWritten { - _, err = l.out.Write([]byte{'\n'}) - if err != nil { - return - } - } - - if l.used+len(b) < l.lineLength { - l.used += copy(l.line[l.used:], b) - return - } - - l.haveWritten = true - _, err = l.out.Write(l.line[0:l.used]) - if err != nil { - return - } - excess := l.lineLength - l.used - l.used = 0 - - _, err = l.out.Write(b[0:excess]) - if err != nil { - return - } - - _, err = l.Write(b[excess:]) - return -} - -func (l *lineBreaker) Close() (err error) { - if l.used > 0 { - _, err = l.out.Write(l.line[0:l.used]) - if err != nil { - return - } - } - - return -} - -// encoding keeps track of a running CRC24 over the data which has been written -// to it and outputs a OpenPGP checksum when closed, followed by an armor -// trailer. -// -// It's built into a stack of io.Writers: -// encoding -> base64 encoder -> lineBreaker -> out -type encoding struct { - out io.Writer - breaker *lineBreaker - b64 io.WriteCloser - crc uint32 - blockType []byte -} - -func (e *encoding) Write(data []byte) (n int, err error) { - e.crc = crc24(e.crc, data) - return e.b64.Write(data) -} - -func (e *encoding) Close() (err error) { - err = e.b64.Close() - if err != nil { - return - } - e.breaker.Close() - - var checksumBytes [3]byte - checksumBytes[0] = byte(e.crc >> 16) - checksumBytes[1] = byte(e.crc >> 8) - checksumBytes[2] = byte(e.crc) - - var b64ChecksumBytes [4]byte - base64.StdEncoding.Encode(b64ChecksumBytes[:], checksumBytes[:]) - - return writeSlices(e.out, blockEnd, b64ChecksumBytes[:], newline, armorEnd, e.blockType, armorEndOfLine) -} - -// Encode returns a WriteCloser which will encode the data written to it in -// OpenPGP armor. -func Encode(out io.Writer, blockType string, headers map[string]string) (w io.WriteCloser, err error) { - bType := []byte(blockType) - err = writeSlices(out, armorStart, bType, armorEndOfLineOut) - if err != nil { - return - } - - for k, v := range headers { - err = writeSlices(out, []byte(k), armorHeaderSep, []byte(v), newline) - if err != nil { - return - } - } - - _, err = out.Write(newline) - if err != nil { - return - } - - e := &encoding{ - out: out, - breaker: newLineBreaker(out, 64), - crc: crc24Init, - blockType: bType, - } - e.b64 = base64.NewEncoder(base64.StdEncoding, e.breaker) - return e, nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/canonical_text.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/canonical_text.go deleted file mode 100644 index a94f6150..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/canonical_text.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2011 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 openpgp - -import ( - "hash" - "io" -) - -// NewCanonicalTextHash reformats text written to it into the canonical -// form and then applies the hash h. See RFC 4880, section 5.2.1. -func NewCanonicalTextHash(h hash.Hash) hash.Hash { - return &canonicalTextHash{h, 0} -} - -type canonicalTextHash struct { - h hash.Hash - s int -} - -var newline = []byte{'\r', '\n'} - -func writeCanonical(cw io.Writer, buf []byte, s *int) (int, error) { - start := 0 - for i, c := range buf { - switch *s { - case 0: - if c == '\r' { - *s = 1 - } else if c == '\n' { - cw.Write(buf[start:i]) - cw.Write(newline) - start = i + 1 - } - case 1: - *s = 0 - } - } - - cw.Write(buf[start:]) - return len(buf), nil -} - -func (cth *canonicalTextHash) Write(buf []byte) (int, error) { - return writeCanonical(cth.h, buf, &cth.s) -} - -func (cth *canonicalTextHash) Sum(in []byte) []byte { - return cth.h.Sum(in) -} - -func (cth *canonicalTextHash) Reset() { - cth.h.Reset() - cth.s = 0 -} - -func (cth *canonicalTextHash) Size() int { - return cth.h.Size() -} - -func (cth *canonicalTextHash) BlockSize() int { - return cth.h.BlockSize() -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/ecdh/ecdh.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/ecdh/ecdh.go deleted file mode 100644 index b09e2a73..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/ecdh/ecdh.go +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright 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 ecdh implements ECDH encryption, suitable for OpenPGP, -// as specified in RFC 6637, section 8. -package ecdh - -import ( - "bytes" - "errors" - "io" - - "github.com/ProtonMail/go-crypto/openpgp/aes/keywrap" - "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm" - "github.com/ProtonMail/go-crypto/openpgp/internal/ecc" -) - -type KDF struct { - Hash algorithm.Hash - Cipher algorithm.Cipher -} - -type PublicKey struct { - curve ecc.ECDHCurve - Point []byte - KDF -} - -type PrivateKey struct { - PublicKey - D []byte -} - -func NewPublicKey(curve ecc.ECDHCurve, kdfHash algorithm.Hash, kdfCipher algorithm.Cipher) *PublicKey { - return &PublicKey{ - curve: curve, - KDF: KDF{ - Hash: kdfHash, - Cipher: kdfCipher, - }, - } -} - -func NewPrivateKey(key PublicKey) *PrivateKey { - return &PrivateKey{ - PublicKey: key, - } -} - -func (pk *PublicKey) GetCurve() ecc.ECDHCurve { - return pk.curve -} - -func (pk *PublicKey) MarshalPoint() []byte { - return pk.curve.MarshalBytePoint(pk.Point) -} - -func (pk *PublicKey) UnmarshalPoint(p []byte) error { - pk.Point = pk.curve.UnmarshalBytePoint(p) - if pk.Point == nil { - return errors.New("ecdh: failed to parse EC point") - } - return nil -} - -func (sk *PrivateKey) MarshalByteSecret() []byte { - return sk.curve.MarshalByteSecret(sk.D) -} - -func (sk *PrivateKey) UnmarshalByteSecret(d []byte) error { - sk.D = sk.curve.UnmarshalByteSecret(d) - - if sk.D == nil { - return errors.New("ecdh: failed to parse scalar") - } - return nil -} - -func GenerateKey(rand io.Reader, c ecc.ECDHCurve, kdf KDF) (priv *PrivateKey, err error) { - priv = new(PrivateKey) - priv.PublicKey.curve = c - priv.PublicKey.KDF = kdf - priv.PublicKey.Point, priv.D, err = c.GenerateECDH(rand) - return -} - -func Encrypt(random io.Reader, pub *PublicKey, msg, curveOID, fingerprint []byte) (vsG, c []byte, err error) { - if len(msg) > 40 { - return nil, nil, errors.New("ecdh: message too long") - } - // the sender MAY use 21, 13, and 5 bytes of padding for AES-128, - // AES-192, and AES-256, respectively, to provide the same number of - // octets, 40 total, as an input to the key wrapping method. - padding := make([]byte, 40-len(msg)) - for i := range padding { - padding[i] = byte(40 - len(msg)) - } - m := append(msg, padding...) - - ephemeral, zb, err := pub.curve.Encaps(random, pub.Point) - if err != nil { - return nil, nil, err - } - - vsG = pub.curve.MarshalBytePoint(ephemeral) - - z, err := buildKey(pub, zb, curveOID, fingerprint, false, false) - if err != nil { - return nil, nil, err - } - - if c, err = keywrap.Wrap(z, m); err != nil { - return nil, nil, err - } - - return vsG, c, nil - -} - -func Decrypt(priv *PrivateKey, vsG, c, curveOID, fingerprint []byte) (msg []byte, err error) { - var m []byte - zb, err := priv.PublicKey.curve.Decaps(priv.curve.UnmarshalBytePoint(vsG), priv.D) - - // Try buildKey three times to workaround an old bug, see comments in buildKey. - for i := 0; i < 3; i++ { - var z []byte - // RFC6637 §8: "Compute Z = KDF( S, Z_len, Param );" - z, err = buildKey(&priv.PublicKey, zb, curveOID, fingerprint, i == 1, i == 2) - if err != nil { - return nil, err - } - - // RFC6637 §8: "Compute C = AESKeyWrap( Z, c ) as per [RFC3394]" - m, err = keywrap.Unwrap(z, c) - if err == nil { - break - } - } - - // Only return an error after we've tried all (required) variants of buildKey. - if err != nil { - return nil, err - } - - // RFC6637 §8: "m = symm_alg_ID || session key || checksum || pkcs5_padding" - // The last byte should be the length of the padding, as per PKCS5; strip it off. - return m[:len(m)-int(m[len(m)-1])], nil -} - -func buildKey(pub *PublicKey, zb []byte, curveOID, fingerprint []byte, stripLeading, stripTrailing bool) ([]byte, error) { - // Param = curve_OID_len || curve_OID || public_key_alg_ID || 03 - // || 01 || KDF_hash_ID || KEK_alg_ID for AESKeyWrap - // || "Anonymous Sender " || recipient_fingerprint; - param := new(bytes.Buffer) - if _, err := param.Write(curveOID); err != nil { - return nil, err - } - algKDF := []byte{18, 3, 1, pub.KDF.Hash.Id(), pub.KDF.Cipher.Id()} - if _, err := param.Write(algKDF); err != nil { - return nil, err - } - if _, err := param.Write([]byte("Anonymous Sender ")); err != nil { - return nil, err - } - // For v5 keys, the 20 leftmost octets of the fingerprint are used. - if _, err := param.Write(fingerprint[:20]); err != nil { - return nil, err - } - if param.Len() - len(curveOID) != 45 { - return nil, errors.New("ecdh: malformed KDF Param") - } - - // MB = Hash ( 00 || 00 || 00 || 01 || ZB || Param ); - h := pub.KDF.Hash.New() - if _, err := h.Write([]byte{0x0, 0x0, 0x0, 0x1}); err != nil { - return nil, err - } - zbLen := len(zb) - i := 0 - j := zbLen - 1 - if stripLeading { - // Work around old go crypto bug where the leading zeros are missing. - for ; i < zbLen && zb[i] == 0; i++ {} - } - if stripTrailing { - // Work around old OpenPGP.js bug where insignificant trailing zeros in - // this little-endian number are missing. - // (See https://github.com/openpgpjs/openpgpjs/pull/853.) - for ; j >= 0 && zb[j] == 0; j-- {} - } - if _, err := h.Write(zb[i:j+1]); err != nil { - return nil, err - } - if _, err := h.Write(param.Bytes()); err != nil { - return nil, err - } - mb := h.Sum(nil) - - return mb[:pub.KDF.Cipher.KeySize()], nil // return oBits leftmost bits of MB. - -} - -func Validate(priv *PrivateKey) error { - return priv.curve.ValidateECDH(priv.Point, priv.D) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/ecdsa/ecdsa.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/ecdsa/ecdsa.go deleted file mode 100644 index 6682a21a..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/ecdsa/ecdsa.go +++ /dev/null @@ -1,80 +0,0 @@ -// Package ecdsa implements ECDSA signature, suitable for OpenPGP, -// as specified in RFC 6637, section 5. -package ecdsa - -import ( - "errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/ecc" - "io" - "math/big" -) - -type PublicKey struct { - X, Y *big.Int - curve ecc.ECDSACurve -} - -type PrivateKey struct { - PublicKey - D *big.Int -} - -func NewPublicKey(curve ecc.ECDSACurve) *PublicKey { - return &PublicKey{ - curve: curve, - } -} - -func NewPrivateKey(key PublicKey) *PrivateKey { - return &PrivateKey{ - PublicKey: key, - } -} - -func (pk *PublicKey) GetCurve() ecc.ECDSACurve { - return pk.curve -} - -func (pk *PublicKey) MarshalPoint() []byte { - return pk.curve.MarshalIntegerPoint(pk.X, pk.Y) -} - -func (pk *PublicKey) UnmarshalPoint(p []byte) error { - pk.X, pk.Y = pk.curve.UnmarshalIntegerPoint(p) - if pk.X == nil { - return errors.New("ecdsa: failed to parse EC point") - } - return nil -} - -func (sk *PrivateKey) MarshalIntegerSecret() []byte { - return sk.curve.MarshalIntegerSecret(sk.D) -} - -func (sk *PrivateKey) UnmarshalIntegerSecret(d []byte) error { - sk.D = sk.curve.UnmarshalIntegerSecret(d) - - if sk.D == nil { - return errors.New("ecdsa: failed to parse scalar") - } - return nil -} - -func GenerateKey(rand io.Reader, c ecc.ECDSACurve) (priv *PrivateKey, err error) { - priv = new(PrivateKey) - priv.PublicKey.curve = c - priv.PublicKey.X, priv.PublicKey.Y, priv.D, err = c.GenerateECDSA(rand) - return -} - -func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) { - return priv.PublicKey.curve.Sign(rand, priv.X, priv.Y, priv.D, hash) -} - -func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool { - return pub.curve.Verify(pub.X, pub.Y, hash, r, s) -} - -func Validate(priv *PrivateKey) error { - return priv.curve.ValidateECDSA(priv.X, priv.Y, priv.D.Bytes()) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/eddsa/eddsa.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/eddsa/eddsa.go deleted file mode 100644 index 12866c12..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/eddsa/eddsa.go +++ /dev/null @@ -1,91 +0,0 @@ -// Package eddsa implements EdDSA signature, suitable for OpenPGP, as specified in -// https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-13.7 -package eddsa - -import ( - "errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/ecc" - "io" -) - -type PublicKey struct { - X []byte - curve ecc.EdDSACurve -} - -type PrivateKey struct { - PublicKey - D []byte -} - -func NewPublicKey(curve ecc.EdDSACurve) *PublicKey { - return &PublicKey{ - curve: curve, - } -} - -func NewPrivateKey(key PublicKey) *PrivateKey { - return &PrivateKey{ - PublicKey: key, - } -} - -func (pk *PublicKey) GetCurve() ecc.EdDSACurve { - return pk.curve -} - -func (pk *PublicKey) MarshalPoint() []byte { - return pk.curve.MarshalBytePoint(pk.X) -} - -func (pk *PublicKey) UnmarshalPoint(x []byte) error { - pk.X = pk.curve.UnmarshalBytePoint(x) - - if pk.X == nil { - return errors.New("eddsa: failed to parse EC point") - } - return nil -} - -func (sk *PrivateKey) MarshalByteSecret() []byte { - return sk.curve.MarshalByteSecret(sk.D) -} - -func (sk *PrivateKey) UnmarshalByteSecret(d []byte) error { - sk.D = sk.curve.UnmarshalByteSecret(d) - - if sk.D == nil { - return errors.New("eddsa: failed to parse scalar") - } - return nil -} - -func GenerateKey(rand io.Reader, c ecc.EdDSACurve) (priv *PrivateKey, err error) { - priv = new(PrivateKey) - priv.PublicKey.curve = c - priv.PublicKey.X, priv.D, err = c.GenerateEdDSA(rand) - return -} - -func Sign(priv *PrivateKey, message []byte) (r, s []byte, err error) { - sig, err := priv.PublicKey.curve.Sign(priv.PublicKey.X, priv.D, message) - if err != nil { - return nil, nil, err - } - - r, s = priv.PublicKey.curve.MarshalSignature(sig) - return -} - -func Verify(pub *PublicKey, message, r, s []byte) bool { - sig := pub.curve.UnmarshalSignature(r, s) - if sig == nil { - return false - } - - return pub.curve.Verify(pub.X, message, sig) -} - -func Validate(priv *PrivateKey) error { - return priv.curve.ValidateEdDSA(priv.PublicKey.X, priv.D) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/elgamal/elgamal.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/elgamal/elgamal.go deleted file mode 100644 index 6a07d8ff..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/elgamal/elgamal.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2011 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 elgamal implements ElGamal encryption, suitable for OpenPGP, -// as specified in "A Public-Key Cryptosystem and a Signature Scheme Based on -// Discrete Logarithms," IEEE Transactions on Information Theory, v. IT-31, -// n. 4, 1985, pp. 469-472. -// -// This form of ElGamal embeds PKCS#1 v1.5 padding, which may make it -// unsuitable for other protocols. RSA should be used in preference in any -// case. -package elgamal // import "github.com/ProtonMail/go-crypto/openpgp/elgamal" - -import ( - "crypto/rand" - "crypto/subtle" - "errors" - "io" - "math/big" -) - -// PublicKey represents an ElGamal public key. -type PublicKey struct { - G, P, Y *big.Int -} - -// PrivateKey represents an ElGamal private key. -type PrivateKey struct { - PublicKey - X *big.Int -} - -// Encrypt encrypts the given message to the given public key. The result is a -// pair of integers. Errors can result from reading random, or because msg is -// too large to be encrypted to the public key. -func Encrypt(random io.Reader, pub *PublicKey, msg []byte) (c1, c2 *big.Int, err error) { - pLen := (pub.P.BitLen() + 7) / 8 - if len(msg) > pLen-11 { - err = errors.New("elgamal: message too long") - return - } - - // EM = 0x02 || PS || 0x00 || M - em := make([]byte, pLen-1) - em[0] = 2 - ps, mm := em[1:len(em)-len(msg)-1], em[len(em)-len(msg):] - err = nonZeroRandomBytes(ps, random) - if err != nil { - return - } - em[len(em)-len(msg)-1] = 0 - copy(mm, msg) - - m := new(big.Int).SetBytes(em) - - k, err := rand.Int(random, pub.P) - if err != nil { - return - } - - c1 = new(big.Int).Exp(pub.G, k, pub.P) - s := new(big.Int).Exp(pub.Y, k, pub.P) - c2 = s.Mul(s, m) - c2.Mod(c2, pub.P) - - return -} - -// Decrypt takes two integers, resulting from an ElGamal encryption, and -// returns the plaintext of the message. An error can result only if the -// ciphertext is invalid. Users should keep in mind that this is a padding -// oracle and thus, if exposed to an adaptive chosen ciphertext attack, can -// be used to break the cryptosystem. See ``Chosen Ciphertext Attacks -// Against Protocols Based on the RSA Encryption Standard PKCS #1'', Daniel -// Bleichenbacher, Advances in Cryptology (Crypto '98), -func Decrypt(priv *PrivateKey, c1, c2 *big.Int) (msg []byte, err error) { - s := new(big.Int).Exp(c1, priv.X, priv.P) - if s.ModInverse(s, priv.P) == nil { - return nil, errors.New("elgamal: invalid private key") - } - s.Mul(s, c2) - s.Mod(s, priv.P) - em := s.Bytes() - - firstByteIsTwo := subtle.ConstantTimeByteEq(em[0], 2) - - // The remainder of the plaintext must be a string of non-zero random - // octets, followed by a 0, followed by the message. - // lookingForIndex: 1 iff we are still looking for the zero. - // index: the offset of the first zero byte. - var lookingForIndex, index int - lookingForIndex = 1 - - for i := 1; i < len(em); i++ { - equals0 := subtle.ConstantTimeByteEq(em[i], 0) - index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index) - lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex) - } - - if firstByteIsTwo != 1 || lookingForIndex != 0 || index < 9 { - return nil, errors.New("elgamal: decryption error") - } - return em[index+1:], nil -} - -// nonZeroRandomBytes fills the given slice with non-zero random octets. -func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) { - _, err = io.ReadFull(rand, s) - if err != nil { - return - } - - for i := 0; i < len(s); i++ { - for s[i] == 0 { - _, err = io.ReadFull(rand, s[i:i+1]) - if err != nil { - return - } - } - } - - return -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/errors/errors.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/errors/errors.go deleted file mode 100644 index 17e2bcfe..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/errors/errors.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2010 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 errors contains common error types for the OpenPGP packages. -package errors // import "github.com/ProtonMail/go-crypto/openpgp/errors" - -import ( - "strconv" -) - -// A StructuralError is returned when OpenPGP data is found to be syntactically -// invalid. -type StructuralError string - -func (s StructuralError) Error() string { - return "openpgp: invalid data: " + string(s) -} - -// UnsupportedError indicates that, although the OpenPGP data is valid, it -// makes use of currently unimplemented features. -type UnsupportedError string - -func (s UnsupportedError) Error() string { - return "openpgp: unsupported feature: " + string(s) -} - -// InvalidArgumentError indicates that the caller is in error and passed an -// incorrect value. -type InvalidArgumentError string - -func (i InvalidArgumentError) Error() string { - return "openpgp: invalid argument: " + string(i) -} - -// SignatureError indicates that a syntactically valid signature failed to -// validate. -type SignatureError string - -func (b SignatureError) Error() string { - return "openpgp: invalid signature: " + string(b) -} - -var ErrMDCHashMismatch error = SignatureError("MDC hash mismatch") -var ErrMDCMissing error = SignatureError("MDC packet not found") - -type signatureExpiredError int - -func (se signatureExpiredError) Error() string { - return "openpgp: signature expired" -} - -var ErrSignatureExpired error = signatureExpiredError(0) - -type keyExpiredError int - -func (ke keyExpiredError) Error() string { - return "openpgp: key expired" -} - -var ErrKeyExpired error = keyExpiredError(0) - -type keyIncorrectError int - -func (ki keyIncorrectError) Error() string { - return "openpgp: incorrect key" -} - -var ErrKeyIncorrect error = keyIncorrectError(0) - -// KeyInvalidError indicates that the public key parameters are invalid -// as they do not match the private ones -type KeyInvalidError string - -func (e KeyInvalidError) Error() string { - return "openpgp: invalid key: " + string(e) -} - -type unknownIssuerError int - -func (unknownIssuerError) Error() string { - return "openpgp: signature made by unknown entity" -} - -var ErrUnknownIssuer error = unknownIssuerError(0) - -type keyRevokedError int - -func (keyRevokedError) Error() string { - return "openpgp: signature made by revoked key" -} - -var ErrKeyRevoked error = keyRevokedError(0) - -type UnknownPacketTypeError uint8 - -func (upte UnknownPacketTypeError) Error() string { - return "openpgp: unknown packet type: " + strconv.Itoa(int(upte)) -} - -// AEADError indicates that there is a problem when initializing or using a -// AEAD instance, configuration struct, nonces or index values. -type AEADError string - -func (ae AEADError) Error() string { - return "openpgp: aead error: " + string(ae) -} - -// ErrDummyPrivateKey results when operations are attempted on a private key -// that is just a dummy key. See -// https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob;f=doc/DETAILS;h=fe55ae16ab4e26d8356dc574c9e8bc935e71aef1;hb=23191d7851eae2217ecdac6484349849a24fd94a#l1109 -type ErrDummyPrivateKey string - -func (dke ErrDummyPrivateKey) Error() string { - return "openpgp: s2k GNU dummy key: " + string(dke) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/algorithm/aead.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/algorithm/aead.go deleted file mode 100644 index d0670651..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/algorithm/aead.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (C) 2019 ProtonTech AG - -package algorithm - -import ( - "crypto/cipher" - "github.com/ProtonMail/go-crypto/eax" - "github.com/ProtonMail/go-crypto/ocb" -) - -// AEADMode defines the Authenticated Encryption with Associated Data mode of -// operation. -type AEADMode uint8 - -// Supported modes of operation (see RFC4880bis [EAX] and RFC7253) -const ( - AEADModeEAX = AEADMode(1) - AEADModeOCB = AEADMode(2) - AEADModeGCM = AEADMode(3) -) - -// TagLength returns the length in bytes of authentication tags. -func (mode AEADMode) TagLength() int { - switch mode { - case AEADModeEAX: - return 16 - case AEADModeOCB: - return 16 - case AEADModeGCM: - return 16 - default: - return 0 - } -} - -// NonceLength returns the length in bytes of nonces. -func (mode AEADMode) NonceLength() int { - switch mode { - case AEADModeEAX: - return 16 - case AEADModeOCB: - return 15 - case AEADModeGCM: - return 12 - default: - return 0 - } -} - -// New returns a fresh instance of the given mode -func (mode AEADMode) New(block cipher.Block) (alg cipher.AEAD) { - var err error - switch mode { - case AEADModeEAX: - alg, err = eax.NewEAX(block) - case AEADModeOCB: - alg, err = ocb.NewOCB(block) - case AEADModeGCM: - alg, err = cipher.NewGCM(block) - } - if err != nil { - panic(err.Error()) - } - return alg -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/algorithm/cipher.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/algorithm/cipher.go deleted file mode 100644 index 5760cff8..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/algorithm/cipher.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 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 algorithm - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/des" - - "golang.org/x/crypto/cast5" -) - -// Cipher is an official symmetric key cipher algorithm. See RFC 4880, -// section 9.2. -type Cipher interface { - // Id returns the algorithm ID, as a byte, of the cipher. - Id() uint8 - // KeySize returns the key size, in bytes, of the cipher. - KeySize() int - // BlockSize returns the block size, in bytes, of the cipher. - BlockSize() int - // New returns a fresh instance of the given cipher. - New(key []byte) cipher.Block -} - -// The following constants mirror the OpenPGP standard (RFC 4880). -const ( - TripleDES = CipherFunction(2) - CAST5 = CipherFunction(3) - AES128 = CipherFunction(7) - AES192 = CipherFunction(8) - AES256 = CipherFunction(9) -) - -// CipherById represents the different block ciphers specified for OpenPGP. See -// http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-13 -var CipherById = map[uint8]Cipher{ - TripleDES.Id(): TripleDES, - CAST5.Id(): CAST5, - AES128.Id(): AES128, - AES192.Id(): AES192, - AES256.Id(): AES256, -} - -type CipherFunction uint8 - -// ID returns the algorithm Id, as a byte, of cipher. -func (sk CipherFunction) Id() uint8 { - return uint8(sk) -} - -var keySizeByID = map[uint8]int{ - TripleDES.Id(): 24, - CAST5.Id(): cast5.KeySize, - AES128.Id(): 16, - AES192.Id(): 24, - AES256.Id(): 32, -} - -// KeySize returns the key size, in bytes, of cipher. -func (cipher CipherFunction) KeySize() int { - switch cipher { - case TripleDES: - return 24 - case CAST5: - return cast5.KeySize - case AES128: - return 16 - case AES192: - return 24 - case AES256: - return 32 - } - return 0 -} - -// BlockSize returns the block size, in bytes, of cipher. -func (cipher CipherFunction) BlockSize() int { - switch cipher { - case TripleDES: - return des.BlockSize - case CAST5: - return 8 - case AES128, AES192, AES256: - return 16 - } - return 0 -} - -// New returns a fresh instance of the given cipher. -func (cipher CipherFunction) New(key []byte) (block cipher.Block) { - var err error - switch cipher { - case TripleDES: - block, err = des.NewTripleDESCipher(key) - case CAST5: - block, err = cast5.NewCipher(key) - case AES128, AES192, AES256: - block, err = aes.NewCipher(key) - } - if err != nil { - panic(err.Error()) - } - return -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/algorithm/hash.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/algorithm/hash.go deleted file mode 100644 index 82e43d67..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/algorithm/hash.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 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 algorithm - -import ( - "crypto" - "fmt" - "hash" -) - -// Hash is an official hash function algorithm. See RFC 4880, section 9.4. -type Hash interface { - // Id returns the algorithm ID, as a byte, of Hash. - Id() uint8 - // Available reports whether the given hash function is linked into the binary. - Available() bool - // HashFunc simply returns the value of h so that Hash implements SignerOpts. - HashFunc() crypto.Hash - // New returns a new hash.Hash calculating the given hash function. New - // panics if the hash function is not linked into the binary. - New() hash.Hash - // Size returns the length, in bytes, of a digest resulting from the given - // hash function. It doesn't require that the hash function in question be - // linked into the program. - Size() int - // String is the name of the hash function corresponding to the given - // OpenPGP hash id. - String() string -} - -// The following vars mirror the crypto/Hash supported hash functions. -var ( - SHA1 Hash = cryptoHash{2, crypto.SHA1} - SHA256 Hash = cryptoHash{8, crypto.SHA256} - SHA384 Hash = cryptoHash{9, crypto.SHA384} - SHA512 Hash = cryptoHash{10, crypto.SHA512} - SHA224 Hash = cryptoHash{11, crypto.SHA224} - SHA3_256 Hash = cryptoHash{12, crypto.SHA3_256} - SHA3_512 Hash = cryptoHash{14, crypto.SHA3_512} -) - -// HashById represents the different hash functions specified for OpenPGP. See -// http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-14 -var ( - HashById = map[uint8]Hash{ - SHA256.Id(): SHA256, - SHA384.Id(): SHA384, - SHA512.Id(): SHA512, - SHA224.Id(): SHA224, - SHA3_256.Id(): SHA3_256, - SHA3_512.Id(): SHA3_512, - } -) - -// cryptoHash contains pairs relating OpenPGP's hash identifier with -// Go's crypto.Hash type. See RFC 4880, section 9.4. -type cryptoHash struct { - id uint8 - crypto.Hash -} - -// Id returns the algorithm ID, as a byte, of cryptoHash. -func (h cryptoHash) Id() uint8 { - return h.id -} - -var hashNames = map[uint8]string{ - SHA256.Id(): "SHA256", - SHA384.Id(): "SHA384", - SHA512.Id(): "SHA512", - SHA224.Id(): "SHA224", - SHA3_256.Id(): "SHA3-256", - SHA3_512.Id(): "SHA3-512", -} - -func (h cryptoHash) String() string { - s, ok := hashNames[h.id] - if !ok { - panic(fmt.Sprintf("Unsupported hash function %d", h.id)) - } - return s -} - -// HashIdToHash returns a crypto.Hash which corresponds to the given OpenPGP -// hash id. -func HashIdToHash(id byte) (h crypto.Hash, ok bool) { - if hash, ok := HashById[id]; ok { - return hash.HashFunc(), true - } - return 0, false -} - -// HashIdToHashWithSha1 returns a crypto.Hash which corresponds to the given OpenPGP -// hash id, allowing sha1. -func HashIdToHashWithSha1(id byte) (h crypto.Hash, ok bool) { - if hash, ok := HashById[id]; ok { - return hash.HashFunc(), true - } - - if id == SHA1.Id() { - return SHA1.HashFunc(), true - } - - return 0, false -} - -// HashIdToString returns the name of the hash function corresponding to the -// given OpenPGP hash id. -func HashIdToString(id byte) (name string, ok bool) { - if hash, ok := HashById[id]; ok { - return hash.String(), true - } - return "", false -} - -// HashToHashId returns an OpenPGP hash id which corresponds the given Hash. -func HashToHashId(h crypto.Hash) (id byte, ok bool) { - for id, hash := range HashById { - if hash.HashFunc() == h { - return id, true - } - } - - return 0, false -} - -// HashToHashIdWithSha1 returns an OpenPGP hash id which corresponds the given Hash, -// allowing instances of SHA1 -func HashToHashIdWithSha1(h crypto.Hash) (id byte, ok bool) { - for id, hash := range HashById { - if hash.HashFunc() == h { - return id, true - } - } - - if h == SHA1.HashFunc() { - return SHA1.Id(), true - } - - return 0, false -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/curve25519.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/curve25519.go deleted file mode 100644 index 266635ec..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/curve25519.go +++ /dev/null @@ -1,171 +0,0 @@ -// Package ecc implements a generic interface for ECDH, ECDSA, and EdDSA. -package ecc - -import ( - "crypto/subtle" - "io" - - "github.com/ProtonMail/go-crypto/openpgp/errors" - x25519lib "github.com/cloudflare/circl/dh/x25519" -) - -type curve25519 struct {} - -func NewCurve25519() *curve25519 { - return &curve25519{} -} - -func (c *curve25519) GetCurveName() string { - return "curve25519" -} - -// MarshalBytePoint encodes the public point from native format, adding the prefix. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.6 -func (c *curve25519) MarshalBytePoint(point [] byte) []byte { - return append([]byte{0x40}, point...) -} - -// UnmarshalBytePoint decodes the public point to native format, removing the prefix. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.6 -func (c *curve25519) UnmarshalBytePoint(point []byte) []byte { - if len(point) != x25519lib.Size + 1 { - return nil - } - - // Remove prefix - return point[1:] -} - -// MarshalByteSecret encodes the secret scalar from native format. -// Note that the EC secret scalar differs from the definition of public keys in -// [Curve25519] in two ways: (1) the byte-ordering is big-endian, which is -// more uniform with how big integers are represented in OpenPGP, and (2) the -// leading zeros are truncated. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.6.1.1 -// Note that leading zero bytes are stripped later when encoding as an MPI. -func (c *curve25519) MarshalByteSecret(secret []byte) []byte { - d := make([]byte, x25519lib.Size) - copyReversed(d, secret) - - // The following ensures that the private key is a number of the form - // 2^{254} + 8 * [0, 2^{251}), in order to avoid the small subgroup of - // the curve. - // - // This masking is done internally in the underlying lib and so is unnecessary - // for security, but OpenPGP implementations require that private keys be - // pre-masked. - d[0] &= 127 - d[0] |= 64 - d[31] &= 248 - - return d -} - -// UnmarshalByteSecret decodes the secret scalar from native format. -// Note that the EC secret scalar differs from the definition of public keys in -// [Curve25519] in two ways: (1) the byte-ordering is big-endian, which is -// more uniform with how big integers are represented in OpenPGP, and (2) the -// leading zeros are truncated. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.6.1.1 -func (c *curve25519) UnmarshalByteSecret(d []byte) []byte { - if len(d) > x25519lib.Size { - return nil - } - - // Ensure truncated leading bytes are re-added - secret := make([]byte, x25519lib.Size) - copyReversed(secret, d) - - return secret -} - -// generateKeyPairBytes Generates a private-public key-pair. -// 'priv' is a private key; a little-endian scalar belonging to the set -// 2^{254} + 8 * [0, 2^{251}), in order to avoid the small subgroup of the -// curve. 'pub' is simply 'priv' * G where G is the base point. -// See https://cr.yp.to/ecdh.html and RFC7748, sec 5. -func (c *curve25519) generateKeyPairBytes(rand io.Reader) (priv, pub x25519lib.Key, err error) { - _, err = io.ReadFull(rand, priv[:]) - if err != nil { - return - } - - x25519lib.KeyGen(&pub, &priv) - return -} - -func (c *curve25519) GenerateECDH(rand io.Reader) (point []byte, secret []byte, err error) { - priv, pub, err := c.generateKeyPairBytes(rand) - if err != nil { - return - } - - return pub[:], priv[:], nil -} - -func (c *genericCurve) MaskSecret(secret []byte) []byte { - return secret -} - -func (c *curve25519) Encaps(rand io.Reader, point []byte) (ephemeral, sharedSecret []byte, err error) { - // RFC6637 §8: "Generate an ephemeral key pair {v, V=vG}" - // ephemeralPrivate corresponds to `v`. - // ephemeralPublic corresponds to `V`. - ephemeralPrivate, ephemeralPublic, err := c.generateKeyPairBytes(rand) - if err != nil { - return nil, nil, err - } - - // RFC6637 §8: "Obtain the authenticated recipient public key R" - // pubKey corresponds to `R`. - var pubKey x25519lib.Key - copy(pubKey[:], point) - - // RFC6637 §8: "Compute the shared point S = vR" - // "VB = convert point V to the octet string" - // sharedPoint corresponds to `VB`. - var sharedPoint x25519lib.Key - x25519lib.Shared(&sharedPoint, &ephemeralPrivate, &pubKey) - - return ephemeralPublic[:], sharedPoint[:], nil -} - -func (c *curve25519) Decaps(vsG, secret []byte) (sharedSecret []byte, err error) { - var ephemeralPublic, decodedPrivate, sharedPoint x25519lib.Key - // RFC6637 §8: "The decryption is the inverse of the method given." - // All quoted descriptions in comments below describe encryption, and - // the reverse is performed. - // vsG corresponds to `VB` in RFC6637 §8 . - - // RFC6637 §8: "VB = convert point V to the octet string" - copy(ephemeralPublic[:], vsG) - - // decodedPrivate corresponds to `r` in RFC6637 §8 . - copy(decodedPrivate[:], secret) - - // RFC6637 §8: "Note that the recipient obtains the shared secret by calculating - // S = rV = rvG, where (r,R) is the recipient's key pair." - // sharedPoint corresponds to `S`. - x25519lib.Shared(&sharedPoint, &decodedPrivate, &ephemeralPublic) - - return sharedPoint[:], nil -} - -func (c *curve25519) ValidateECDH(point []byte, secret []byte) (err error) { - var pk, sk x25519lib.Key - copy(sk[:], secret) - x25519lib.KeyGen(&pk, &sk) - - if subtle.ConstantTimeCompare(point, pk[:]) == 0 { - return errors.KeyInvalidError("ecc: invalid curve25519 public point") - } - - return nil -} - -func copyReversed(out []byte, in []byte) { - l := len(in) - for i := 0; i < l; i++ { - out[i] = in[l-i-1] - } -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/curve_info.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/curve_info.go deleted file mode 100644 index df2878c9..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/curve_info.go +++ /dev/null @@ -1,140 +0,0 @@ -// Package ecc implements a generic interface for ECDH, ECDSA, and EdDSA. -package ecc - -import ( - "bytes" - "crypto/elliptic" - "github.com/ProtonMail/go-crypto/bitcurves" - "github.com/ProtonMail/go-crypto/brainpool" - "github.com/ProtonMail/go-crypto/openpgp/internal/encoding" -) - -type CurveInfo struct { - GenName string - Oid *encoding.OID - Curve Curve -} - -var Curves = []CurveInfo{ - { - // NIST P-256 - GenName: "P256", - Oid: encoding.NewOID([]byte{0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07}), - Curve: NewGenericCurve(elliptic.P256()), - }, - { - // NIST P-384 - GenName: "P384", - Oid: encoding.NewOID([]byte{0x2B, 0x81, 0x04, 0x00, 0x22}), - Curve: NewGenericCurve(elliptic.P384()), - }, - { - // NIST P-521 - GenName: "P521", - Oid: encoding.NewOID([]byte{0x2B, 0x81, 0x04, 0x00, 0x23}), - Curve: NewGenericCurve(elliptic.P521()), - }, - { - // SecP256k1 - GenName: "SecP256k1", - Oid: encoding.NewOID([]byte{0x2B, 0x81, 0x04, 0x00, 0x0A}), - Curve: NewGenericCurve(bitcurves.S256()), - }, - { - // Curve25519 - GenName: "Curve25519", - Oid: encoding.NewOID([]byte{0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01}), - Curve: NewCurve25519(), - }, - { - // X448 - GenName: "Curve448", - Oid: encoding.NewOID([]byte{0x2B, 0x65, 0x6F}), - Curve: NewX448(), - }, - { - // Ed25519 - GenName: "Curve25519", - Oid: encoding.NewOID([]byte{0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01}), - Curve: NewEd25519(), - }, - { - // Ed448 - GenName: "Curve448", - Oid: encoding.NewOID([]byte{0x2B, 0x65, 0x71}), - Curve: NewEd448(), - }, - { - // BrainpoolP256r1 - GenName: "BrainpoolP256", - Oid: encoding.NewOID([]byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07}), - Curve: NewGenericCurve(brainpool.P256r1()), - }, - { - // BrainpoolP384r1 - GenName: "BrainpoolP384", - Oid: encoding.NewOID([]byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B}), - Curve: NewGenericCurve(brainpool.P384r1()), - }, - { - // BrainpoolP512r1 - GenName: "BrainpoolP512", - Oid: encoding.NewOID([]byte{0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D}), - Curve: NewGenericCurve(brainpool.P512r1()), - }, -} - -func FindByCurve(curve Curve) *CurveInfo { - for _, curveInfo := range Curves { - if curveInfo.Curve.GetCurveName() == curve.GetCurveName() { - return &curveInfo - } - } - return nil -} - -func FindByOid(oid encoding.Field) *CurveInfo { - var rawBytes = oid.Bytes() - for _, curveInfo := range Curves { - if bytes.Equal(curveInfo.Oid.Bytes(), rawBytes) { - return &curveInfo - } - } - return nil -} - -func FindEdDSAByGenName(curveGenName string) EdDSACurve { - for _, curveInfo := range Curves { - if curveInfo.GenName == curveGenName { - curve, ok := curveInfo.Curve.(EdDSACurve) - if ok { - return curve - } - } - } - return nil -} - -func FindECDSAByGenName(curveGenName string) ECDSACurve { - for _, curveInfo := range Curves { - if curveInfo.GenName == curveGenName { - curve, ok := curveInfo.Curve.(ECDSACurve) - if ok { - return curve - } - } - } - return nil -} - -func FindECDHByGenName(curveGenName string) ECDHCurve { - for _, curveInfo := range Curves { - if curveInfo.GenName == curveGenName { - curve, ok := curveInfo.Curve.(ECDHCurve) - if ok { - return curve - } - } - } - return nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/curves.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/curves.go deleted file mode 100644 index c47072b4..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/curves.go +++ /dev/null @@ -1,48 +0,0 @@ -// Package ecc implements a generic interface for ECDH, ECDSA, and EdDSA. -package ecc - -import ( - "io" - "math/big" -) - -type Curve interface { - GetCurveName() string -} - -type ECDSACurve interface { - Curve - MarshalIntegerPoint(x, y *big.Int) []byte - UnmarshalIntegerPoint([]byte) (x, y *big.Int) - MarshalIntegerSecret(d *big.Int) []byte - UnmarshalIntegerSecret(d []byte) *big.Int - GenerateECDSA(rand io.Reader) (x, y, secret *big.Int, err error) - Sign(rand io.Reader, x, y, d *big.Int, hash []byte) (r, s *big.Int, err error) - Verify(x, y *big.Int, hash []byte, r, s *big.Int) bool - ValidateECDSA(x, y *big.Int, secret []byte) error -} - -type EdDSACurve interface { - Curve - MarshalBytePoint(x []byte) []byte - UnmarshalBytePoint([]byte) (x []byte) - MarshalByteSecret(d []byte) []byte - UnmarshalByteSecret(d []byte) []byte - MarshalSignature(sig []byte) (r, s []byte) - UnmarshalSignature(r, s []byte) (sig []byte) - GenerateEdDSA(rand io.Reader) (pub, priv []byte, err error) - Sign(publicKey, privateKey, message []byte) (sig []byte, err error) - Verify(publicKey, message, sig []byte) bool - ValidateEdDSA(publicKey, privateKey []byte) (err error) -} -type ECDHCurve interface { - Curve - MarshalBytePoint([]byte) (encoded []byte) - UnmarshalBytePoint(encoded []byte) ([]byte) - MarshalByteSecret(d []byte) []byte - UnmarshalByteSecret(d []byte) []byte - GenerateECDH(rand io.Reader) (point []byte, secret []byte, err error) - Encaps(rand io.Reader, point []byte) (ephemeral, sharedSecret []byte, err error) - Decaps(ephemeral, secret []byte) (sharedSecret []byte, err error) - ValidateECDH(public []byte, secret []byte) error -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/ed25519.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/ed25519.go deleted file mode 100644 index 29f6cba9..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/ed25519.go +++ /dev/null @@ -1,111 +0,0 @@ -// Package ecc implements a generic interface for ECDH, ECDSA, and EdDSA. -package ecc - -import ( - "crypto/subtle" - "io" - - "github.com/ProtonMail/go-crypto/openpgp/errors" - ed25519lib "github.com/cloudflare/circl/sign/ed25519" -) - -const ed25519Size = 32 -type ed25519 struct {} - -func NewEd25519() *ed25519 { - return &ed25519{} -} - -func (c *ed25519) GetCurveName() string { - return "ed25519" -} - -// MarshalBytePoint encodes the public point from native format, adding the prefix. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.5 -func (c *ed25519) MarshalBytePoint(x []byte) []byte { - return append([]byte{0x40}, x...) -} - -// UnmarshalBytePoint decodes a point from prefixed format to native. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.5 -func (c *ed25519) UnmarshalBytePoint(point []byte) (x []byte) { - if len(point) != ed25519lib.PublicKeySize + 1 { - return nil - } - - // Return unprefixed - return point[1:] -} - -// MarshalByteSecret encodes a scalar in native format. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.5 -func (c *ed25519) MarshalByteSecret(d []byte) []byte { - return d -} - -// UnmarshalByteSecret decodes a scalar in native format and re-adds the stripped leading zeroes -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.5 -func (c *ed25519) UnmarshalByteSecret(s []byte) (d []byte) { - if len(s) > ed25519lib.SeedSize { - return nil - } - - // Handle stripped leading zeroes - d = make([]byte, ed25519lib.SeedSize) - copy(d[ed25519lib.SeedSize - len(s):], s) - return -} - -// MarshalSignature splits a signature in R and S. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.2.3.3.1 -func (c *ed25519) MarshalSignature(sig []byte) (r, s []byte) { - return sig[:ed25519Size], sig[ed25519Size:] -} - -// UnmarshalSignature decodes R and S in the native format, re-adding the stripped leading zeroes -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.2.3.3.1 -func (c *ed25519) UnmarshalSignature(r, s []byte) (sig []byte) { - // Check size - if len(r) > 32 || len(s) > 32 { - return nil - } - - sig = make([]byte, ed25519lib.SignatureSize) - - // Handle stripped leading zeroes - copy(sig[ed25519Size-len(r):ed25519Size], r) - copy(sig[ed25519lib.SignatureSize-len(s):], s) - return sig -} - -func (c *ed25519) GenerateEdDSA(rand io.Reader) (pub, priv []byte, err error) { - pk, sk, err := ed25519lib.GenerateKey(rand) - - if err != nil { - return nil, nil, err - } - - return pk, sk[:ed25519lib.SeedSize], nil -} - -func getEd25519Sk(publicKey, privateKey []byte) ed25519lib.PrivateKey { - return append(privateKey, publicKey...) -} - -func (c *ed25519) Sign(publicKey, privateKey, message []byte) (sig []byte, err error) { - sig = ed25519lib.Sign(getEd25519Sk(publicKey, privateKey), message) - return sig, nil -} - -func (c *ed25519) Verify(publicKey, message, sig []byte) bool { - return ed25519lib.Verify(publicKey, message, sig) -} - -func (c *ed25519) ValidateEdDSA(publicKey, privateKey []byte) (err error) { - priv := getEd25519Sk(publicKey, privateKey) - expectedPriv := ed25519lib.NewKeyFromSeed(priv.Seed()) - if subtle.ConstantTimeCompare(priv, expectedPriv) == 0 { - return errors.KeyInvalidError("ecc: invalid ed25519 secret") - } - return nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/ed448.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/ed448.go deleted file mode 100644 index a2df3dab..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/ed448.go +++ /dev/null @@ -1,111 +0,0 @@ -// Package ecc implements a generic interface for ECDH, ECDSA, and EdDSA. -package ecc - -import ( - "crypto/subtle" - "io" - - "github.com/ProtonMail/go-crypto/openpgp/errors" - ed448lib "github.com/cloudflare/circl/sign/ed448" -) - -type ed448 struct {} - -func NewEd448() *ed448 { - return &ed448{} -} - -func (c *ed448) GetCurveName() string { - return "ed448" -} - -// MarshalBytePoint encodes the public point from native format, adding the prefix. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.5 -func (c *ed448) MarshalBytePoint(x []byte) []byte { - // Return prefixed - return append([]byte{0x40}, x...) -} - -// UnmarshalBytePoint decodes a point from prefixed format to native. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.5 -func (c *ed448) UnmarshalBytePoint(point []byte) (x []byte) { - if len(point) != ed448lib.PublicKeySize + 1 { - return nil - } - - // Strip prefix - return point[1:] -} - -// MarshalByteSecret encoded a scalar from native format to prefixed. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.5 -func (c *ed448) MarshalByteSecret(d []byte) []byte { - // Return prefixed - return append([]byte{0x40}, d...) -} - -// UnmarshalByteSecret decodes a scalar from prefixed format to native. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.5 -func (c *ed448) UnmarshalByteSecret(s []byte) (d []byte) { - // Check prefixed size - if len(s) != ed448lib.SeedSize + 1 { - return nil - } - - // Strip prefix - return s[1:] -} - -// MarshalSignature splits a signature in R and S, where R is in prefixed native format and -// S is an MPI with value zero. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.2.3.3.2 -func (c *ed448) MarshalSignature(sig []byte) (r, s []byte) { - return append([]byte{0x40}, sig...), []byte{} -} - -// UnmarshalSignature decodes R and S in the native format. Only R is used, in prefixed native format. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.2.3.3.2 -func (c *ed448) UnmarshalSignature(r, s []byte) (sig []byte) { - if len(r) != ed448lib.SignatureSize + 1 { - return nil - } - - return r[1:] -} - -func (c *ed448) GenerateEdDSA(rand io.Reader) (pub, priv []byte, err error) { - pk, sk, err := ed448lib.GenerateKey(rand) - - if err != nil { - return nil, nil, err - } - - return pk, sk[:ed448lib.SeedSize], nil -} - -func getEd448Sk(publicKey, privateKey []byte) ed448lib.PrivateKey { - return append(privateKey, publicKey...) -} - -func (c *ed448) Sign(publicKey, privateKey, message []byte) (sig []byte, err error) { - // Ed448 is used with the empty string as a context string. - // See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-13.7 - sig = ed448lib.Sign(getEd448Sk(publicKey, privateKey), message, "") - - return sig, nil -} - -func (c *ed448) Verify(publicKey, message, sig []byte) bool { - // Ed448 is used with the empty string as a context string. - // See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-13.7 - return ed448lib.Verify(publicKey, message, sig, "") -} - -func (c *ed448) ValidateEdDSA(publicKey, privateKey []byte) (err error) { - priv := getEd448Sk(publicKey, privateKey) - expectedPriv := ed448lib.NewKeyFromSeed(priv.Seed()) - if subtle.ConstantTimeCompare(priv, expectedPriv) == 0 { - return errors.KeyInvalidError("ecc: invalid ed448 secret") - } - return nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/generic.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/generic.go deleted file mode 100644 index e28d7c71..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/generic.go +++ /dev/null @@ -1,149 +0,0 @@ -// Package ecc implements a generic interface for ECDH, ECDSA, and EdDSA. -package ecc - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "fmt" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "io" - "math/big" -) - -type genericCurve struct { - Curve elliptic.Curve -} - -func NewGenericCurve(c elliptic.Curve) *genericCurve { - return &genericCurve{ - Curve: c, - } -} - -func (c *genericCurve) GetCurveName() string { - return c.Curve.Params().Name -} - -func (c *genericCurve) MarshalBytePoint(point []byte) []byte { - return point -} - -func (c *genericCurve) UnmarshalBytePoint(point []byte) []byte { - return point -} - -func (c *genericCurve) MarshalIntegerPoint(x, y *big.Int) []byte { - return elliptic.Marshal(c.Curve, x, y) -} - -func (c *genericCurve) UnmarshalIntegerPoint(point []byte) (x, y *big.Int) { - return elliptic.Unmarshal(c.Curve, point) -} - -func (c *genericCurve) MarshalByteSecret(d []byte) []byte { - return d -} - -func (c *genericCurve) UnmarshalByteSecret(d []byte) []byte { - return d -} - -func (c *genericCurve) MarshalIntegerSecret(d *big.Int) []byte { - return d.Bytes() -} - -func (c *genericCurve) UnmarshalIntegerSecret(d []byte) *big.Int { - return new(big.Int).SetBytes(d) -} - -func (c *genericCurve) GenerateECDH(rand io.Reader) (point, secret []byte, err error) { - secret, x, y, err := elliptic.GenerateKey(c.Curve, rand) - if err != nil { - return nil, nil, err - } - - point = elliptic.Marshal(c.Curve, x, y) - return point, secret, nil -} - -func (c *genericCurve) GenerateECDSA(rand io.Reader) (x, y, secret *big.Int, err error) { - priv, err := ecdsa.GenerateKey(c.Curve, rand) - if err != nil { - return - } - - return priv.X, priv.Y, priv.D, nil -} - -func (c *genericCurve) Encaps(rand io.Reader, point []byte) (ephemeral, sharedSecret []byte, err error) { - xP, yP := elliptic.Unmarshal(c.Curve, point) - if xP == nil { - panic("invalid point") - } - - d, x, y, err := elliptic.GenerateKey(c.Curve, rand) - if err != nil { - return nil, nil, err - } - - vsG := elliptic.Marshal(c.Curve, x, y) - zbBig, _ := c.Curve.ScalarMult(xP, yP, d) - - byteLen := (c.Curve.Params().BitSize + 7) >> 3 - zb := make([]byte, byteLen) - zbBytes := zbBig.Bytes() - copy(zb[byteLen-len(zbBytes):], zbBytes) - - return vsG, zb, nil -} - -func (c *genericCurve) Decaps(ephemeral, secret []byte) (sharedSecret []byte, err error) { - x, y := elliptic.Unmarshal(c.Curve, ephemeral) - zbBig, _ := c.Curve.ScalarMult(x, y, secret) - byteLen := (c.Curve.Params().BitSize + 7) >> 3 - zb := make([]byte, byteLen) - zbBytes := zbBig.Bytes() - copy(zb[byteLen-len(zbBytes):], zbBytes) - - return zb, nil -} - -func (c *genericCurve) Sign(rand io.Reader, x, y, d *big.Int, hash []byte) (r, s *big.Int, err error) { - priv := &ecdsa.PrivateKey{D: d, PublicKey: ecdsa.PublicKey{X: x, Y: y, Curve: c.Curve}} - return ecdsa.Sign(rand, priv, hash) -} - -func (c *genericCurve) Verify(x, y *big.Int, hash []byte, r, s *big.Int) bool { - pub := &ecdsa.PublicKey{X: x, Y: y, Curve: c.Curve} - return ecdsa.Verify(pub, hash, r, s) -} - -func (c *genericCurve) validate(xP, yP *big.Int, secret []byte) error { - // the public point should not be at infinity (0,0) - zero := new(big.Int) - if xP.Cmp(zero) == 0 && yP.Cmp(zero) == 0 { - return errors.KeyInvalidError(fmt.Sprintf("ecc (%s): infinity point", c.Curve.Params().Name)) - } - - // re-derive the public point Q' = (X,Y) = dG - // to compare to declared Q in public key - expectedX, expectedY := c.Curve.ScalarBaseMult(secret) - if xP.Cmp(expectedX) != 0 || yP.Cmp(expectedY) != 0 { - return errors.KeyInvalidError(fmt.Sprintf("ecc (%s): invalid point", c.Curve.Params().Name)) - } - - return nil -} - -func (c *genericCurve) ValidateECDSA(xP, yP *big.Int, secret []byte) error { - return c.validate(xP, yP, secret) -} - -func (c *genericCurve) ValidateECDH(point []byte, secret []byte) error { - xP, yP := elliptic.Unmarshal(c.Curve, point) - if xP == nil { - return errors.KeyInvalidError(fmt.Sprintf("ecc (%s): invalid point", c.Curve.Params().Name)) - } - - return c.validate(xP, yP, secret) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/x448.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/x448.go deleted file mode 100644 index 4a940b4f..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/ecc/x448.go +++ /dev/null @@ -1,105 +0,0 @@ -// Package ecc implements a generic interface for ECDH, ECDSA, and EdDSA. -package ecc - -import ( - "crypto/subtle" - "io" - - "github.com/ProtonMail/go-crypto/openpgp/errors" - x448lib "github.com/cloudflare/circl/dh/x448" -) - -type x448 struct {} - -func NewX448() *x448 { - return &x448{} -} - -func (c *x448) GetCurveName() string { - return "x448" -} - -// MarshalBytePoint encodes the public point from native format, adding the prefix. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.6 -func (c *x448) MarshalBytePoint(point []byte) []byte { - return append([]byte{0x40}, point...) -} - -// UnmarshalBytePoint decodes a point from prefixed format to native. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.6 -func (c *x448) UnmarshalBytePoint(point []byte) []byte { - if len(point) != x448lib.Size + 1 { - return nil - } - - return point[1:] -} - -// MarshalByteSecret encoded a scalar from native format to prefixed. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.6.1.2 -func (c *x448) MarshalByteSecret(d []byte) []byte { - return append([]byte{0x40}, d...) -} - -// UnmarshalByteSecret decodes a scalar from prefixed format to native. -// See https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh-06#section-5.5.5.6.1.2 -func (c *x448) UnmarshalByteSecret(d []byte) []byte { - if len(d) != x448lib.Size + 1 { - return nil - } - - // Store without prefix - return d[1:] -} - -func (c *x448) generateKeyPairBytes(rand io.Reader) (sk, pk x448lib.Key, err error) { - if _, err = rand.Read(sk[:]); err != nil { - return - } - - x448lib.KeyGen(&pk, &sk) - return -} - -func (c *x448) GenerateECDH(rand io.Reader) (point []byte, secret []byte, err error) { - priv, pub, err := c.generateKeyPairBytes(rand) - if err != nil { - return - } - - return pub[:], priv[:], nil -} - -func (c *x448) Encaps(rand io.Reader, point []byte) (ephemeral, sharedSecret []byte, err error) { - var pk, ss x448lib.Key - seed, e, err := c.generateKeyPairBytes(rand) - - copy(pk[:], point) - x448lib.Shared(&ss, &seed, &pk) - - return e[:], ss[:], nil -} - -func (c *x448) Decaps(ephemeral, secret []byte) (sharedSecret []byte, err error) { - var ss, sk, e x448lib.Key - - copy(sk[:], secret) - copy(e[:], ephemeral) - x448lib.Shared(&ss, &sk, &e) - - return ss[:], nil -} - -func (c *x448) ValidateECDH(point []byte, secret []byte) error { - var sk, pk, expectedPk x448lib.Key - - copy(pk[:], point) - copy(sk[:], secret) - x448lib.KeyGen(&expectedPk, &sk) - - if subtle.ConstantTimeCompare(expectedPk[:], pk[:]) == 0 { - return errors.KeyInvalidError("ecc: invalid curve25519 public point") - } - - return nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/encoding/encoding.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/encoding/encoding.go deleted file mode 100644 index 6c921481..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/encoding/encoding.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 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 encoding implements openpgp packet field encodings as specified in -// RFC 4880 and 6637. -package encoding - -import "io" - -// Field is an encoded field of an openpgp packet. -type Field interface { - // Bytes returns the decoded data. - Bytes() []byte - - // BitLength is the size in bits of the decoded data. - BitLength() uint16 - - // EncodedBytes returns the encoded data. - EncodedBytes() []byte - - // EncodedLength is the size in bytes of the encoded data. - EncodedLength() uint16 - - // ReadFrom reads the next Field from r. - ReadFrom(r io.Reader) (int64, error) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/encoding/mpi.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/encoding/mpi.go deleted file mode 100644 index 02e5e695..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/encoding/mpi.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 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 encoding - -import ( - "io" - "math/big" - "math/bits" -) - -// An MPI is used to store the contents of a big integer, along with the bit -// length that was specified in the original input. This allows the MPI to be -// reserialized exactly. -type MPI struct { - bytes []byte - bitLength uint16 -} - -// NewMPI returns a MPI initialized with bytes. -func NewMPI(bytes []byte) *MPI { - for len(bytes) != 0 && bytes[0] == 0 { - bytes = bytes[1:] - } - if len(bytes) == 0 { - bitLength := uint16(0) - return &MPI{bytes, bitLength} - } - bitLength := 8*uint16(len(bytes)-1) + uint16(bits.Len8(bytes[0])) - return &MPI{bytes, bitLength} -} - -// Bytes returns the decoded data. -func (m *MPI) Bytes() []byte { - return m.bytes -} - -// BitLength is the size in bits of the decoded data. -func (m *MPI) BitLength() uint16 { - return m.bitLength -} - -// EncodedBytes returns the encoded data. -func (m *MPI) EncodedBytes() []byte { - return append([]byte{byte(m.bitLength >> 8), byte(m.bitLength)}, m.bytes...) -} - -// EncodedLength is the size in bytes of the encoded data. -func (m *MPI) EncodedLength() uint16 { - return uint16(2 + len(m.bytes)) -} - -// ReadFrom reads into m the next MPI from r. -func (m *MPI) ReadFrom(r io.Reader) (int64, error) { - var buf [2]byte - n, err := io.ReadFull(r, buf[0:]) - if err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return int64(n), err - } - - m.bitLength = uint16(buf[0])<<8 | uint16(buf[1]) - m.bytes = make([]byte, (int(m.bitLength)+7)/8) - - nn, err := io.ReadFull(r, m.bytes) - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - - // remove leading zero bytes from malformed GnuPG encoded MPIs: - // https://bugs.gnupg.org/gnupg/issue1853 - // for _, b := range m.bytes { - // if b != 0 { - // break - // } - // m.bytes = m.bytes[1:] - // m.bitLength -= 8 - // } - - return int64(n) + int64(nn), err -} - -// SetBig initializes m with the bits from n. -func (m *MPI) SetBig(n *big.Int) *MPI { - m.bytes = n.Bytes() - m.bitLength = uint16(n.BitLen()) - return m -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/encoding/oid.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/encoding/oid.go deleted file mode 100644 index c9df9fe2..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/internal/encoding/oid.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 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 encoding - -import ( - "io" - - "github.com/ProtonMail/go-crypto/openpgp/errors" -) - -// OID is used to store a variable-length field with a one-octet size -// prefix. See https://tools.ietf.org/html/rfc6637#section-9. -type OID struct { - bytes []byte -} - -const ( - // maxOID is the maximum number of bytes in a OID. - maxOID = 254 - // reservedOIDLength1 and reservedOIDLength2 are OID lengths that the RFC - // specifies are reserved. - reservedOIDLength1 = 0 - reservedOIDLength2 = 0xff -) - -// NewOID returns a OID initialized with bytes. -func NewOID(bytes []byte) *OID { - switch len(bytes) { - case reservedOIDLength1, reservedOIDLength2: - panic("encoding: NewOID argument length is reserved") - default: - if len(bytes) > maxOID { - panic("encoding: NewOID argument too large") - } - } - - return &OID{ - bytes: bytes, - } -} - -// Bytes returns the decoded data. -func (o *OID) Bytes() []byte { - return o.bytes -} - -// BitLength is the size in bits of the decoded data. -func (o *OID) BitLength() uint16 { - return uint16(len(o.bytes) * 8) -} - -// EncodedBytes returns the encoded data. -func (o *OID) EncodedBytes() []byte { - return append([]byte{byte(len(o.bytes))}, o.bytes...) -} - -// EncodedLength is the size in bytes of the encoded data. -func (o *OID) EncodedLength() uint16 { - return uint16(1 + len(o.bytes)) -} - -// ReadFrom reads into b the next OID from r. -func (o *OID) ReadFrom(r io.Reader) (int64, error) { - var buf [1]byte - n, err := io.ReadFull(r, buf[:]) - if err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return int64(n), err - } - - switch buf[0] { - case reservedOIDLength1, reservedOIDLength2: - return int64(n), errors.UnsupportedError("reserved for future extensions") - } - - o.bytes = make([]byte, buf[0]) - - nn, err := io.ReadFull(r, o.bytes) - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - - return int64(n) + int64(nn), err -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go deleted file mode 100644 index 77012fe1..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/key_generation.go +++ /dev/null @@ -1,414 +0,0 @@ -// Copyright 2011 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 openpgp - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - goerrors "errors" - "io" - "math/big" - "time" - - "github.com/ProtonMail/go-crypto/openpgp/ecdh" - "github.com/ProtonMail/go-crypto/openpgp/ecdsa" - "github.com/ProtonMail/go-crypto/openpgp/eddsa" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm" - "github.com/ProtonMail/go-crypto/openpgp/internal/ecc" - "github.com/ProtonMail/go-crypto/openpgp/packet" -) - -// NewEntity returns an Entity that contains a fresh RSA/RSA keypair with a -// single identity composed of the given full name, comment and email, any of -// which may be empty but must not contain any of "()<>\x00". -// If config is nil, sensible defaults will be used. -func NewEntity(name, comment, email string, config *packet.Config) (*Entity, error) { - creationTime := config.Now() - keyLifetimeSecs := config.KeyLifetime() - - // Generate a primary signing key - primaryPrivRaw, err := newSigner(config) - if err != nil { - return nil, err - } - primary := packet.NewSignerPrivateKey(creationTime, primaryPrivRaw) - if config != nil && config.V5Keys { - primary.UpgradeToV5() - } - - e := &Entity{ - PrimaryKey: &primary.PublicKey, - PrivateKey: primary, - Identities: make(map[string]*Identity), - Subkeys: []Subkey{}, - } - - err = e.addUserId(name, comment, email, config, creationTime, keyLifetimeSecs) - if err != nil { - return nil, err - } - - // NOTE: No key expiry here, but we will not return this subkey in EncryptionKey() - // if the primary/master key has expired. - err = e.addEncryptionSubkey(config, creationTime, 0) - if err != nil { - return nil, err - } - - return e, nil -} - -func (t *Entity) AddUserId(name, comment, email string, config *packet.Config) error { - creationTime := config.Now() - keyLifetimeSecs := config.KeyLifetime() - return t.addUserId(name, comment, email, config, creationTime, keyLifetimeSecs) -} - -func (t *Entity) addUserId(name, comment, email string, config *packet.Config, creationTime time.Time, keyLifetimeSecs uint32) error { - uid := packet.NewUserId(name, comment, email) - if uid == nil { - return errors.InvalidArgumentError("user id field contained invalid characters") - } - - if _, ok := t.Identities[uid.Id]; ok { - return errors.InvalidArgumentError("user id exist") - } - - primary := t.PrivateKey - - isPrimaryId := len(t.Identities) == 0 - - selfSignature := &packet.Signature{ - Version: primary.PublicKey.Version, - SigType: packet.SigTypePositiveCert, - PubKeyAlgo: primary.PublicKey.PubKeyAlgo, - Hash: config.Hash(), - CreationTime: creationTime, - KeyLifetimeSecs: &keyLifetimeSecs, - IssuerKeyId: &primary.PublicKey.KeyId, - IssuerFingerprint: primary.PublicKey.Fingerprint, - IsPrimaryId: &isPrimaryId, - FlagsValid: true, - FlagSign: true, - FlagCertify: true, - SEIPDv1: true, // true by default, see 5.8 vs. 5.14 - SEIPDv2: config.AEAD() != nil, - } - - // Set the PreferredHash for the SelfSignature from the packet.Config. - // If it is not the must-implement algorithm from rfc4880bis, append that. - hash, ok := algorithm.HashToHashId(config.Hash()) - if !ok { - return errors.UnsupportedError("unsupported preferred hash function") - } - - selfSignature.PreferredHash = []uint8{hash} - if config.Hash() != crypto.SHA256 { - selfSignature.PreferredHash = append(selfSignature.PreferredHash, hashToHashId(crypto.SHA256)) - } - - // Likewise for DefaultCipher. - selfSignature.PreferredSymmetric = []uint8{uint8(config.Cipher())} - if config.Cipher() != packet.CipherAES128 { - selfSignature.PreferredSymmetric = append(selfSignature.PreferredSymmetric, uint8(packet.CipherAES128)) - } - - // We set CompressionNone as the preferred compression algorithm because - // of compression side channel attacks, then append the configured - // DefaultCompressionAlgo if any is set (to signal support for cases - // where the application knows that using compression is safe). - selfSignature.PreferredCompression = []uint8{uint8(packet.CompressionNone)} - if config.Compression() != packet.CompressionNone { - selfSignature.PreferredCompression = append(selfSignature.PreferredCompression, uint8(config.Compression())) - } - - // And for DefaultMode. - modes := []uint8{uint8(config.AEAD().Mode())} - if config.AEAD().Mode() != packet.AEADModeOCB { - modes = append(modes, uint8(packet.AEADModeOCB)) - } - - // For preferred (AES256, GCM), we'll generate (AES256, GCM), (AES256, OCB), (AES128, GCM), (AES128, OCB) - for _, cipher := range selfSignature.PreferredSymmetric { - for _, mode := range modes { - selfSignature.PreferredCipherSuites = append(selfSignature.PreferredCipherSuites, [2]uint8{cipher, mode}) - } - } - - // User ID binding signature - err := selfSignature.SignUserId(uid.Id, &primary.PublicKey, primary, config) - if err != nil { - return err - } - t.Identities[uid.Id] = &Identity{ - Name: uid.Id, - UserId: uid, - SelfSignature: selfSignature, - Signatures: []*packet.Signature{selfSignature}, - } - return nil -} - -// AddSigningSubkey adds a signing keypair as a subkey to the Entity. -// If config is nil, sensible defaults will be used. -func (e *Entity) AddSigningSubkey(config *packet.Config) error { - creationTime := config.Now() - keyLifetimeSecs := config.KeyLifetime() - - subPrivRaw, err := newSigner(config) - if err != nil { - return err - } - sub := packet.NewSignerPrivateKey(creationTime, subPrivRaw) - - subkey := Subkey{ - PublicKey: &sub.PublicKey, - PrivateKey: sub, - Sig: &packet.Signature{ - Version: e.PrimaryKey.Version, - CreationTime: creationTime, - KeyLifetimeSecs: &keyLifetimeSecs, - SigType: packet.SigTypeSubkeyBinding, - PubKeyAlgo: e.PrimaryKey.PubKeyAlgo, - Hash: config.Hash(), - FlagsValid: true, - FlagSign: true, - IssuerKeyId: &e.PrimaryKey.KeyId, - EmbeddedSignature: &packet.Signature{ - Version: e.PrimaryKey.Version, - CreationTime: creationTime, - SigType: packet.SigTypePrimaryKeyBinding, - PubKeyAlgo: sub.PublicKey.PubKeyAlgo, - Hash: config.Hash(), - IssuerKeyId: &e.PrimaryKey.KeyId, - }, - }, - } - if config != nil && config.V5Keys { - subkey.PublicKey.UpgradeToV5() - } - - err = subkey.Sig.EmbeddedSignature.CrossSignKey(subkey.PublicKey, e.PrimaryKey, subkey.PrivateKey, config) - if err != nil { - return err - } - - subkey.PublicKey.IsSubkey = true - subkey.PrivateKey.IsSubkey = true - if err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config); err != nil { - return err - } - - e.Subkeys = append(e.Subkeys, subkey) - return nil -} - -// AddEncryptionSubkey adds an encryption keypair as a subkey to the Entity. -// If config is nil, sensible defaults will be used. -func (e *Entity) AddEncryptionSubkey(config *packet.Config) error { - creationTime := config.Now() - keyLifetimeSecs := config.KeyLifetime() - return e.addEncryptionSubkey(config, creationTime, keyLifetimeSecs) -} - -func (e *Entity) addEncryptionSubkey(config *packet.Config, creationTime time.Time, keyLifetimeSecs uint32) error { - subPrivRaw, err := newDecrypter(config) - if err != nil { - return err - } - sub := packet.NewDecrypterPrivateKey(creationTime, subPrivRaw) - - subkey := Subkey{ - PublicKey: &sub.PublicKey, - PrivateKey: sub, - Sig: &packet.Signature{ - Version: e.PrimaryKey.Version, - CreationTime: creationTime, - KeyLifetimeSecs: &keyLifetimeSecs, - SigType: packet.SigTypeSubkeyBinding, - PubKeyAlgo: e.PrimaryKey.PubKeyAlgo, - Hash: config.Hash(), - FlagsValid: true, - FlagEncryptStorage: true, - FlagEncryptCommunications: true, - IssuerKeyId: &e.PrimaryKey.KeyId, - }, - } - if config != nil && config.V5Keys { - subkey.PublicKey.UpgradeToV5() - } - - subkey.PublicKey.IsSubkey = true - subkey.PrivateKey.IsSubkey = true - if err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config); err != nil { - return err - } - - e.Subkeys = append(e.Subkeys, subkey) - return nil -} - -// Generates a signing key -func newSigner(config *packet.Config) (signer interface{}, err error) { - switch config.PublicKeyAlgorithm() { - case packet.PubKeyAlgoRSA: - bits := config.RSAModulusBits() - if bits < 1024 { - return nil, errors.InvalidArgumentError("bits must be >= 1024") - } - if config != nil && len(config.RSAPrimes) >= 2 { - primes := config.RSAPrimes[0:2] - config.RSAPrimes = config.RSAPrimes[2:] - return generateRSAKeyWithPrimes(config.Random(), 2, bits, primes) - } - return rsa.GenerateKey(config.Random(), bits) - case packet.PubKeyAlgoEdDSA: - curve := ecc.FindEdDSAByGenName(string(config.CurveName())) - if curve == nil { - return nil, errors.InvalidArgumentError("unsupported curve") - } - - priv, err := eddsa.GenerateKey(config.Random(), curve) - if err != nil { - return nil, err - } - return priv, nil - case packet.PubKeyAlgoECDSA: - curve := ecc.FindECDSAByGenName(string(config.CurveName())) - if curve == nil { - return nil, errors.InvalidArgumentError("unsupported curve") - } - - priv, err := ecdsa.GenerateKey(config.Random(), curve) - if err != nil { - return nil, err - } - return priv, nil - default: - return nil, errors.InvalidArgumentError("unsupported public key algorithm") - } -} - -// Generates an encryption/decryption key -func newDecrypter(config *packet.Config) (decrypter interface{}, err error) { - switch config.PublicKeyAlgorithm() { - case packet.PubKeyAlgoRSA: - bits := config.RSAModulusBits() - if bits < 1024 { - return nil, errors.InvalidArgumentError("bits must be >= 1024") - } - if config != nil && len(config.RSAPrimes) >= 2 { - primes := config.RSAPrimes[0:2] - config.RSAPrimes = config.RSAPrimes[2:] - return generateRSAKeyWithPrimes(config.Random(), 2, bits, primes) - } - return rsa.GenerateKey(config.Random(), bits) - case packet.PubKeyAlgoEdDSA, packet.PubKeyAlgoECDSA: - fallthrough // When passing EdDSA or ECDSA, we generate an ECDH subkey - case packet.PubKeyAlgoECDH: - var kdf = ecdh.KDF{ - Hash: algorithm.SHA512, - Cipher: algorithm.AES256, - } - curve := ecc.FindECDHByGenName(string(config.CurveName())) - if curve == nil { - return nil, errors.InvalidArgumentError("unsupported curve") - } - return ecdh.GenerateKey(config.Random(), curve, kdf) - default: - return nil, errors.InvalidArgumentError("unsupported public key algorithm") - } -} - -var bigOne = big.NewInt(1) - -// generateRSAKeyWithPrimes generates a multi-prime RSA keypair of the -// given bit size, using the given random source and prepopulated primes. -func generateRSAKeyWithPrimes(random io.Reader, nprimes int, bits int, prepopulatedPrimes []*big.Int) (*rsa.PrivateKey, error) { - priv := new(rsa.PrivateKey) - priv.E = 65537 - - if nprimes < 2 { - return nil, goerrors.New("generateRSAKeyWithPrimes: nprimes must be >= 2") - } - - if bits < 1024 { - return nil, goerrors.New("generateRSAKeyWithPrimes: bits must be >= 1024") - } - - primes := make([]*big.Int, nprimes) - -NextSetOfPrimes: - for { - todo := bits - // crypto/rand should set the top two bits in each prime. - // Thus each prime has the form - // p_i = 2^bitlen(p_i) × 0.11... (in base 2). - // And the product is: - // P = 2^todo × α - // where α is the product of nprimes numbers of the form 0.11... - // - // If α < 1/2 (which can happen for nprimes > 2), we need to - // shift todo to compensate for lost bits: the mean value of 0.11... - // is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2 - // will give good results. - if nprimes >= 7 { - todo += (nprimes - 2) / 5 - } - for i := 0; i < nprimes; i++ { - var err error - if len(prepopulatedPrimes) == 0 { - primes[i], err = rand.Prime(random, todo/(nprimes-i)) - if err != nil { - return nil, err - } - } else { - primes[i] = prepopulatedPrimes[0] - prepopulatedPrimes = prepopulatedPrimes[1:] - } - - todo -= primes[i].BitLen() - } - - // Make sure that primes is pairwise unequal. - for i, prime := range primes { - for j := 0; j < i; j++ { - if prime.Cmp(primes[j]) == 0 { - continue NextSetOfPrimes - } - } - } - - n := new(big.Int).Set(bigOne) - totient := new(big.Int).Set(bigOne) - pminus1 := new(big.Int) - for _, prime := range primes { - n.Mul(n, prime) - pminus1.Sub(prime, bigOne) - totient.Mul(totient, pminus1) - } - if n.BitLen() != bits { - // This should never happen for nprimes == 2 because - // crypto/rand should set the top two bits in each prime. - // For nprimes > 2 we hope it does not happen often. - continue NextSetOfPrimes - } - - priv.D = new(big.Int) - e := big.NewInt(int64(priv.E)) - ok := priv.D.ModInverse(e, totient) - - if ok != nil { - priv.Primes = primes - priv.N = n - break - } - } - - priv.Precompute() - return priv, nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go deleted file mode 100644 index 48278e6e..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/keys.go +++ /dev/null @@ -1,829 +0,0 @@ -// Copyright 2011 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 openpgp - -import ( - goerrors "errors" - "io" - "time" - - "github.com/ProtonMail/go-crypto/openpgp/armor" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/packet" -) - -// PublicKeyType is the armor type for a PGP public key. -var PublicKeyType = "PGP PUBLIC KEY BLOCK" - -// PrivateKeyType is the armor type for a PGP private key. -var PrivateKeyType = "PGP PRIVATE KEY BLOCK" - -// An Entity represents the components of an OpenPGP key: a primary public key -// (which must be a signing key), one or more identities claimed by that key, -// and zero or more subkeys, which may be encryption keys. -type Entity struct { - PrimaryKey *packet.PublicKey - PrivateKey *packet.PrivateKey - Identities map[string]*Identity // indexed by Identity.Name - Revocations []*packet.Signature - Subkeys []Subkey -} - -// An Identity represents an identity claimed by an Entity and zero or more -// assertions by other entities about that claim. -type Identity struct { - Name string // by convention, has the form "Full Name (comment) " - UserId *packet.UserId - SelfSignature *packet.Signature - Revocations []*packet.Signature - Signatures []*packet.Signature // all (potentially unverified) self-signatures, revocations, and third-party signatures -} - -// A Subkey is an additional public key in an Entity. Subkeys can be used for -// encryption. -type Subkey struct { - PublicKey *packet.PublicKey - PrivateKey *packet.PrivateKey - Sig *packet.Signature - Revocations []*packet.Signature -} - -// A Key identifies a specific public key in an Entity. This is either the -// Entity's primary key or a subkey. -type Key struct { - Entity *Entity - PublicKey *packet.PublicKey - PrivateKey *packet.PrivateKey - SelfSignature *packet.Signature - Revocations []*packet.Signature -} - -// A KeyRing provides access to public and private keys. -type KeyRing interface { - // KeysById returns the set of keys that have the given key id. - KeysById(id uint64) []Key - // KeysByIdAndUsage returns the set of keys with the given id - // that also meet the key usage given by requiredUsage. - // The requiredUsage is expressed as the bitwise-OR of - // packet.KeyFlag* values. - KeysByIdUsage(id uint64, requiredUsage byte) []Key - // DecryptionKeys returns all private keys that are valid for - // decryption. - DecryptionKeys() []Key -} - -// PrimaryIdentity returns an Identity, preferring non-revoked identities, -// identities marked as primary, or the latest-created identity, in that order. -func (e *Entity) PrimaryIdentity() *Identity { - var primaryIdentity *Identity - for _, ident := range e.Identities { - if shouldPreferIdentity(primaryIdentity, ident) { - primaryIdentity = ident - } - } - return primaryIdentity -} - -func shouldPreferIdentity(existingId, potentialNewId *Identity) bool { - if existingId == nil { - return true - } - - if len(existingId.Revocations) > len(potentialNewId.Revocations) { - return true - } - - if len(existingId.Revocations) < len(potentialNewId.Revocations) { - return false - } - - if existingId.SelfSignature == nil { - return true - } - - if existingId.SelfSignature.IsPrimaryId != nil && *existingId.SelfSignature.IsPrimaryId && - !(potentialNewId.SelfSignature.IsPrimaryId != nil && *potentialNewId.SelfSignature.IsPrimaryId) { - return false - } - - if !(existingId.SelfSignature.IsPrimaryId != nil && *existingId.SelfSignature.IsPrimaryId) && - potentialNewId.SelfSignature.IsPrimaryId != nil && *potentialNewId.SelfSignature.IsPrimaryId { - return true - } - - return potentialNewId.SelfSignature.CreationTime.After(existingId.SelfSignature.CreationTime) -} - -// EncryptionKey returns the best candidate Key for encrypting a message to the -// given Entity. -func (e *Entity) EncryptionKey(now time.Time) (Key, bool) { - // Fail to find any encryption key if the... - i := e.PrimaryIdentity() - if e.PrimaryKey.KeyExpired(i.SelfSignature, now) || // primary key has expired - i.SelfSignature == nil || // user ID has no self-signature - i.SelfSignature.SigExpired(now) || // user ID self-signature has expired - e.Revoked(now) || // primary key has been revoked - i.Revoked(now) { // user ID has been revoked - return Key{}, false - } - - // Iterate the keys to find the newest, unexpired one - candidateSubkey := -1 - var maxTime time.Time - for i, subkey := range e.Subkeys { - if subkey.Sig.FlagsValid && - subkey.Sig.FlagEncryptCommunications && - subkey.PublicKey.PubKeyAlgo.CanEncrypt() && - !subkey.PublicKey.KeyExpired(subkey.Sig, now) && - !subkey.Sig.SigExpired(now) && - !subkey.Revoked(now) && - (maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) { - candidateSubkey = i - maxTime = subkey.Sig.CreationTime - } - } - - if candidateSubkey != -1 { - subkey := e.Subkeys[candidateSubkey] - return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Revocations}, true - } - - // If we don't have any candidate subkeys for encryption and - // the primary key doesn't have any usage metadata then we - // assume that the primary key is ok. Or, if the primary key is - // marked as ok to encrypt with, then we can obviously use it. - if !i.SelfSignature.FlagsValid || i.SelfSignature.FlagEncryptCommunications && - e.PrimaryKey.PubKeyAlgo.CanEncrypt() { - return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature, e.Revocations}, true - } - - return Key{}, false -} - - -// CertificationKey return the best candidate Key for certifying a key with this -// Entity. -func (e *Entity) CertificationKey(now time.Time) (Key, bool) { - return e.CertificationKeyById(now, 0) -} - -// CertificationKeyById return the Key for key certification with this -// Entity and keyID. -func (e *Entity) CertificationKeyById(now time.Time, id uint64) (Key, bool) { - return e.signingKeyByIdUsage(now, id, packet.KeyFlagCertify) -} - -// SigningKey return the best candidate Key for signing a message with this -// Entity. -func (e *Entity) SigningKey(now time.Time) (Key, bool) { - return e.SigningKeyById(now, 0) -} - -// SigningKeyById return the Key for signing a message with this -// Entity and keyID. -func (e *Entity) SigningKeyById(now time.Time, id uint64) (Key, bool) { - return e.signingKeyByIdUsage(now, id, packet.KeyFlagSign) -} - -func (e *Entity) signingKeyByIdUsage(now time.Time, id uint64, flags int) (Key, bool) { - // Fail to find any signing key if the... - i := e.PrimaryIdentity() - if e.PrimaryKey.KeyExpired(i.SelfSignature, now) || // primary key has expired - i.SelfSignature == nil || // user ID has no self-signature - i.SelfSignature.SigExpired(now) || // user ID self-signature has expired - e.Revoked(now) || // primary key has been revoked - i.Revoked(now) { // user ID has been revoked - return Key{}, false - } - - // Iterate the keys to find the newest, unexpired one - candidateSubkey := -1 - var maxTime time.Time - for idx, subkey := range e.Subkeys { - if subkey.Sig.FlagsValid && - (flags & packet.KeyFlagCertify == 0 || subkey.Sig.FlagCertify) && - (flags & packet.KeyFlagSign == 0 || subkey.Sig.FlagSign) && - subkey.PublicKey.PubKeyAlgo.CanSign() && - !subkey.PublicKey.KeyExpired(subkey.Sig, now) && - !subkey.Sig.SigExpired(now) && - !subkey.Revoked(now) && - (maxTime.IsZero() || subkey.Sig.CreationTime.After(maxTime)) && - (id == 0 || subkey.PublicKey.KeyId == id) { - candidateSubkey = idx - maxTime = subkey.Sig.CreationTime - } - } - - if candidateSubkey != -1 { - subkey := e.Subkeys[candidateSubkey] - return Key{e, subkey.PublicKey, subkey.PrivateKey, subkey.Sig, subkey.Revocations}, true - } - - // If we have no candidate subkey then we assume that it's ok to sign - // with the primary key. Or, if the primary key is marked as ok to - // sign with, then we can use it. - if !i.SelfSignature.FlagsValid || ( - (flags & packet.KeyFlagCertify == 0 || i.SelfSignature.FlagCertify) && - (flags & packet.KeyFlagSign == 0 || i.SelfSignature.FlagSign)) && - e.PrimaryKey.PubKeyAlgo.CanSign() && - (id == 0 || e.PrimaryKey.KeyId == id) { - return Key{e, e.PrimaryKey, e.PrivateKey, i.SelfSignature, e.Revocations}, true - } - - // No keys with a valid Signing Flag or no keys matched the id passed in - return Key{}, false -} - -func revoked(revocations []*packet.Signature, now time.Time) bool { - for _, revocation := range revocations { - if revocation.RevocationReason != nil && *revocation.RevocationReason == packet.KeyCompromised { - // If the key is compromised, the key is considered revoked even before the revocation date. - return true - } - if !revocation.SigExpired(now) { - return true - } - } - return false -} - -// Revoked returns whether the entity has any direct key revocation signatures. -// Note that third-party revocation signatures are not supported. -// Note also that Identity and Subkey revocation should be checked separately. -func (e *Entity) Revoked(now time.Time) bool { - return revoked(e.Revocations, now) -} - -// Revoked returns whether the identity has been revoked by a self-signature. -// Note that third-party revocation signatures are not supported. -func (i *Identity) Revoked(now time.Time) bool { - return revoked(i.Revocations, now) -} - -// Revoked returns whether the subkey has been revoked by a self-signature. -// Note that third-party revocation signatures are not supported. -func (s *Subkey) Revoked(now time.Time) bool { - return revoked(s.Revocations, now) -} - -// Revoked returns whether the key or subkey has been revoked by a self-signature. -// Note that third-party revocation signatures are not supported. -// Note also that Identity revocation should be checked separately. -// Normally, it's not necessary to call this function, except on keys returned by -// KeysById or KeysByIdUsage. -func (key *Key) Revoked(now time.Time) bool { - return revoked(key.Revocations, now) -} - -// An EntityList contains one or more Entities. -type EntityList []*Entity - -// KeysById returns the set of keys that have the given key id. -func (el EntityList) KeysById(id uint64) (keys []Key) { - for _, e := range el { - if e.PrimaryKey.KeyId == id { - ident := e.PrimaryIdentity() - selfSig := ident.SelfSignature - keys = append(keys, Key{e, e.PrimaryKey, e.PrivateKey, selfSig, e.Revocations}) - } - - for _, subKey := range e.Subkeys { - if subKey.PublicKey.KeyId == id { - keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig, subKey.Revocations}) - } - } - } - return -} - -// KeysByIdAndUsage returns the set of keys with the given id that also meet -// the key usage given by requiredUsage. The requiredUsage is expressed as -// the bitwise-OR of packet.KeyFlag* values. -func (el EntityList) KeysByIdUsage(id uint64, requiredUsage byte) (keys []Key) { - for _, key := range el.KeysById(id) { - if key.SelfSignature != nil && key.SelfSignature.FlagsValid && requiredUsage != 0 { - var usage byte - if key.SelfSignature.FlagCertify { - usage |= packet.KeyFlagCertify - } - if key.SelfSignature.FlagSign { - usage |= packet.KeyFlagSign - } - if key.SelfSignature.FlagEncryptCommunications { - usage |= packet.KeyFlagEncryptCommunications - } - if key.SelfSignature.FlagEncryptStorage { - usage |= packet.KeyFlagEncryptStorage - } - if usage&requiredUsage != requiredUsage { - continue - } - } - - keys = append(keys, key) - } - return -} - -// DecryptionKeys returns all private keys that are valid for decryption. -func (el EntityList) DecryptionKeys() (keys []Key) { - for _, e := range el { - for _, subKey := range e.Subkeys { - if subKey.PrivateKey != nil && (!subKey.Sig.FlagsValid || subKey.Sig.FlagEncryptStorage || subKey.Sig.FlagEncryptCommunications) { - keys = append(keys, Key{e, subKey.PublicKey, subKey.PrivateKey, subKey.Sig, subKey.Revocations}) - } - } - } - return -} - -// ReadArmoredKeyRing reads one or more public/private keys from an armor keyring file. -func ReadArmoredKeyRing(r io.Reader) (EntityList, error) { - block, err := armor.Decode(r) - if err == io.EOF { - return nil, errors.InvalidArgumentError("no armored data found") - } - if err != nil { - return nil, err - } - if block.Type != PublicKeyType && block.Type != PrivateKeyType { - return nil, errors.InvalidArgumentError("expected public or private key block, got: " + block.Type) - } - - return ReadKeyRing(block.Body) -} - -// ReadKeyRing reads one or more public/private keys. Unsupported keys are -// ignored as long as at least a single valid key is found. -func ReadKeyRing(r io.Reader) (el EntityList, err error) { - packets := packet.NewReader(r) - var lastUnsupportedError error - - for { - var e *Entity - e, err = ReadEntity(packets) - if err != nil { - // TODO: warn about skipped unsupported/unreadable keys - if _, ok := err.(errors.UnsupportedError); ok { - lastUnsupportedError = err - err = readToNextPublicKey(packets) - } else if _, ok := err.(errors.StructuralError); ok { - // Skip unreadable, badly-formatted keys - lastUnsupportedError = err - err = readToNextPublicKey(packets) - } - if err == io.EOF { - err = nil - break - } - if err != nil { - el = nil - break - } - } else { - el = append(el, e) - } - } - - if len(el) == 0 && err == nil { - err = lastUnsupportedError - } - return -} - -// readToNextPublicKey reads packets until the start of the entity and leaves -// the first packet of the new entity in the Reader. -func readToNextPublicKey(packets *packet.Reader) (err error) { - var p packet.Packet - for { - p, err = packets.Next() - if err == io.EOF { - return - } else if err != nil { - if _, ok := err.(errors.UnsupportedError); ok { - err = nil - continue - } - return - } - - if pk, ok := p.(*packet.PublicKey); ok && !pk.IsSubkey { - packets.Unread(p) - return - } - } -} - -// ReadEntity reads an entity (public key, identities, subkeys etc) from the -// given Reader. -func ReadEntity(packets *packet.Reader) (*Entity, error) { - e := new(Entity) - e.Identities = make(map[string]*Identity) - - p, err := packets.Next() - if err != nil { - return nil, err - } - - var ok bool - if e.PrimaryKey, ok = p.(*packet.PublicKey); !ok { - if e.PrivateKey, ok = p.(*packet.PrivateKey); !ok { - packets.Unread(p) - return nil, errors.StructuralError("first packet was not a public/private key") - } - e.PrimaryKey = &e.PrivateKey.PublicKey - } - - if !e.PrimaryKey.PubKeyAlgo.CanSign() { - return nil, errors.StructuralError("primary key cannot be used for signatures") - } - - var revocations []*packet.Signature -EachPacket: - for { - p, err := packets.Next() - if err == io.EOF { - break - } else if err != nil { - return nil, err - } - - switch pkt := p.(type) { - case *packet.UserId: - if err := addUserID(e, packets, pkt); err != nil { - return nil, err - } - case *packet.Signature: - if pkt.SigType == packet.SigTypeKeyRevocation { - revocations = append(revocations, pkt) - } else if pkt.SigType == packet.SigTypeDirectSignature { - // TODO: RFC4880 5.2.1 permits signatures - // directly on keys (eg. to bind additional - // revocation keys). - } - // Else, ignoring the signature as it does not follow anything - // we would know to attach it to. - case *packet.PrivateKey: - if pkt.IsSubkey == false { - packets.Unread(p) - break EachPacket - } - err = addSubkey(e, packets, &pkt.PublicKey, pkt) - if err != nil { - return nil, err - } - case *packet.PublicKey: - if pkt.IsSubkey == false { - packets.Unread(p) - break EachPacket - } - err = addSubkey(e, packets, pkt, nil) - if err != nil { - return nil, err - } - default: - // we ignore unknown packets - } - } - - if len(e.Identities) == 0 { - return nil, errors.StructuralError("entity without any identities") - } - - for _, revocation := range revocations { - err = e.PrimaryKey.VerifyRevocationSignature(revocation) - if err == nil { - e.Revocations = append(e.Revocations, revocation) - } else { - // TODO: RFC 4880 5.2.3.15 defines revocation keys. - return nil, errors.StructuralError("revocation signature signed by alternate key") - } - } - - return e, nil -} - -func addUserID(e *Entity, packets *packet.Reader, pkt *packet.UserId) error { - // Make a new Identity object, that we might wind up throwing away. - // We'll only add it if we get a valid self-signature over this - // userID. - identity := new(Identity) - identity.Name = pkt.Id - identity.UserId = pkt - - for { - p, err := packets.Next() - if err == io.EOF { - break - } else if err != nil { - return err - } - - sig, ok := p.(*packet.Signature) - if !ok { - packets.Unread(p) - break - } - - if sig.SigType != packet.SigTypeGenericCert && - sig.SigType != packet.SigTypePersonaCert && - sig.SigType != packet.SigTypeCasualCert && - sig.SigType != packet.SigTypePositiveCert && - sig.SigType != packet.SigTypeCertificationRevocation { - return errors.StructuralError("user ID signature with wrong type") - } - - if sig.CheckKeyIdOrFingerprint(e.PrimaryKey) { - if err = e.PrimaryKey.VerifyUserIdSignature(pkt.Id, e.PrimaryKey, sig); err != nil { - return errors.StructuralError("user ID self-signature invalid: " + err.Error()) - } - if sig.SigType == packet.SigTypeCertificationRevocation { - identity.Revocations = append(identity.Revocations, sig) - } else if identity.SelfSignature == nil || sig.CreationTime.After(identity.SelfSignature.CreationTime) { - identity.SelfSignature = sig - } - identity.Signatures = append(identity.Signatures, sig) - e.Identities[pkt.Id] = identity - } else { - identity.Signatures = append(identity.Signatures, sig) - } - } - - return nil -} - -func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *packet.PrivateKey) error { - var subKey Subkey - subKey.PublicKey = pub - subKey.PrivateKey = priv - - for { - p, err := packets.Next() - if err == io.EOF { - break - } else if err != nil { - return errors.StructuralError("subkey signature invalid: " + err.Error()) - } - - sig, ok := p.(*packet.Signature) - if !ok { - packets.Unread(p) - break - } - - if sig.SigType != packet.SigTypeSubkeyBinding && sig.SigType != packet.SigTypeSubkeyRevocation { - return errors.StructuralError("subkey signature with wrong type") - } - - if err := e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, sig); err != nil { - return errors.StructuralError("subkey signature invalid: " + err.Error()) - } - - switch sig.SigType { - case packet.SigTypeSubkeyRevocation: - subKey.Revocations = append(subKey.Revocations, sig) - case packet.SigTypeSubkeyBinding: - if subKey.Sig == nil || sig.CreationTime.After(subKey.Sig.CreationTime) { - subKey.Sig = sig - } - } - } - - if subKey.Sig == nil { - return errors.StructuralError("subkey packet not followed by signature") - } - - e.Subkeys = append(e.Subkeys, subKey) - - return nil -} - -// SerializePrivate serializes an Entity, including private key material, but -// excluding signatures from other entities, to the given Writer. -// Identities and subkeys are re-signed in case they changed since NewEntry. -// If config is nil, sensible defaults will be used. -func (e *Entity) SerializePrivate(w io.Writer, config *packet.Config) (err error) { - if e.PrivateKey.Dummy() { - return errors.ErrDummyPrivateKey("dummy private key cannot re-sign identities") - } - return e.serializePrivate(w, config, true) -} - -// SerializePrivateWithoutSigning serializes an Entity, including private key -// material, but excluding signatures from other entities, to the given Writer. -// Self-signatures of identities and subkeys are not re-signed. This is useful -// when serializing GNU dummy keys, among other things. -// If config is nil, sensible defaults will be used. -func (e *Entity) SerializePrivateWithoutSigning(w io.Writer, config *packet.Config) (err error) { - return e.serializePrivate(w, config, false) -} - -func (e *Entity) serializePrivate(w io.Writer, config *packet.Config, reSign bool) (err error) { - if e.PrivateKey == nil { - return goerrors.New("openpgp: private key is missing") - } - err = e.PrivateKey.Serialize(w) - if err != nil { - return - } - for _, revocation := range e.Revocations { - err := revocation.Serialize(w) - if err != nil { - return err - } - } - for _, ident := range e.Identities { - err = ident.UserId.Serialize(w) - if err != nil { - return - } - if reSign { - if ident.SelfSignature == nil { - return goerrors.New("openpgp: can't re-sign identity without valid self-signature") - } - err = ident.SelfSignature.SignUserId(ident.UserId.Id, e.PrimaryKey, e.PrivateKey, config) - if err != nil { - return - } - } - for _, sig := range ident.Signatures { - err = sig.Serialize(w) - if err != nil { - return err - } - } - } - for _, subkey := range e.Subkeys { - err = subkey.PrivateKey.Serialize(w) - if err != nil { - return - } - if reSign { - err = subkey.Sig.SignKey(subkey.PublicKey, e.PrivateKey, config) - if err != nil { - return - } - if subkey.Sig.EmbeddedSignature != nil { - err = subkey.Sig.EmbeddedSignature.CrossSignKey(subkey.PublicKey, e.PrimaryKey, - subkey.PrivateKey, config) - if err != nil { - return - } - } - } - for _, revocation := range subkey.Revocations { - err := revocation.Serialize(w) - if err != nil { - return err - } - } - err = subkey.Sig.Serialize(w) - if err != nil { - return - } - } - return nil -} - -// Serialize writes the public part of the given Entity to w, including -// signatures from other entities. No private key material will be output. -func (e *Entity) Serialize(w io.Writer) error { - err := e.PrimaryKey.Serialize(w) - if err != nil { - return err - } - for _, revocation := range e.Revocations { - err := revocation.Serialize(w) - if err != nil { - return err - } - } - for _, ident := range e.Identities { - err = ident.UserId.Serialize(w) - if err != nil { - return err - } - for _, sig := range ident.Signatures { - err = sig.Serialize(w) - if err != nil { - return err - } - } - } - for _, subkey := range e.Subkeys { - err = subkey.PublicKey.Serialize(w) - if err != nil { - return err - } - for _, revocation := range subkey.Revocations { - err := revocation.Serialize(w) - if err != nil { - return err - } - } - err = subkey.Sig.Serialize(w) - if err != nil { - return err - } - } - return nil -} - -// SignIdentity adds a signature to e, from signer, attesting that identity is -// associated with e. The provided identity must already be an element of -// e.Identities and the private key of signer must have been decrypted if -// necessary. -// If config is nil, sensible defaults will be used. -func (e *Entity) SignIdentity(identity string, signer *Entity, config *packet.Config) error { - certificationKey, ok := signer.CertificationKey(config.Now()) - if !ok { - return errors.InvalidArgumentError("no valid certification key found") - } - - if certificationKey.PrivateKey.Encrypted { - return errors.InvalidArgumentError("signing Entity's private key must be decrypted") - } - - ident, ok := e.Identities[identity] - if !ok { - return errors.InvalidArgumentError("given identity string not found in Entity") - } - - sig := &packet.Signature{ - Version: certificationKey.PrivateKey.Version, - SigType: packet.SigTypeGenericCert, - PubKeyAlgo: certificationKey.PrivateKey.PubKeyAlgo, - Hash: config.Hash(), - CreationTime: config.Now(), - IssuerKeyId: &certificationKey.PrivateKey.KeyId, - } - - if config.SigLifetime() != 0 { - sig.SigLifetimeSecs = &config.SigLifetimeSecs - } - - signingUserID := config.SigningUserId() - if signingUserID != "" { - if _, ok := signer.Identities[signingUserID]; !ok { - return errors.InvalidArgumentError("signer identity string not found in signer Entity") - } - sig.SignerUserId = &signingUserID - } - - if err := sig.SignUserId(identity, e.PrimaryKey, certificationKey.PrivateKey, config); err != nil { - return err - } - ident.Signatures = append(ident.Signatures, sig) - return nil -} - -// RevokeKey generates a key revocation signature (packet.SigTypeKeyRevocation) with the -// specified reason code and text (RFC4880 section-5.2.3.23). -// If config is nil, sensible defaults will be used. -func (e *Entity) RevokeKey(reason packet.ReasonForRevocation, reasonText string, config *packet.Config) error { - revSig := &packet.Signature{ - Version: e.PrimaryKey.Version, - CreationTime: config.Now(), - SigType: packet.SigTypeKeyRevocation, - PubKeyAlgo: e.PrimaryKey.PubKeyAlgo, - Hash: config.Hash(), - RevocationReason: &reason, - RevocationReasonText: reasonText, - IssuerKeyId: &e.PrimaryKey.KeyId, - } - - if err := revSig.RevokeKey(e.PrimaryKey, e.PrivateKey, config); err != nil { - return err - } - e.Revocations = append(e.Revocations, revSig) - return nil -} - -// RevokeSubkey generates a subkey revocation signature (packet.SigTypeSubkeyRevocation) for -// a subkey with the specified reason code and text (RFC4880 section-5.2.3.23). -// If config is nil, sensible defaults will be used. -func (e *Entity) RevokeSubkey(sk *Subkey, reason packet.ReasonForRevocation, reasonText string, config *packet.Config) error { - if err := e.PrimaryKey.VerifyKeySignature(sk.PublicKey, sk.Sig); err != nil { - return errors.InvalidArgumentError("given subkey is not associated with this key") - } - - revSig := &packet.Signature{ - Version: e.PrimaryKey.Version, - CreationTime: config.Now(), - SigType: packet.SigTypeSubkeyRevocation, - PubKeyAlgo: e.PrimaryKey.PubKeyAlgo, - Hash: config.Hash(), - RevocationReason: &reason, - RevocationReasonText: reasonText, - IssuerKeyId: &e.PrimaryKey.KeyId, - } - - if err := revSig.RevokeSubkey(sk.PublicKey, e.PrivateKey, config); err != nil { - return err - } - - sk.Revocations = append(sk.Revocations, revSig) - return nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/keys_test_data.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/keys_test_data.go deleted file mode 100644 index 108fd096..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/keys_test_data.go +++ /dev/null @@ -1,538 +0,0 @@ -package openpgp - -const expiringKeyHex = "c6c04d0451d0c680010800abbb021fd03ffc4e96618901180c3fdcb060ee69eeead97b91256d11420d80b5f1b51930248044130bd300605cf8a05b7a40d3d8cfb0a910be2e3db50dcd50a9c54064c2a5550801daa834ff4480b33d3d3ca495ff8a4e84a886977d17d998f881241a874083d8b995beab555b6d22b8a4817ab17ac3e7304f7d4d2c05c495fb2218348d3bc13651db1d92732e368a9dd7dcefa6eddff30b94706a9aaee47e9d39321460b740c59c6fc3c2fd8ab6c0fb868cb87c0051f0321301fe0f0e1820b15e7fb7063395769b525005c7e30a7ce85984f5cac00504e7b4fdc45d74958de8388436fd5c7ba9ea121f1c851b5911dd1b47a14d81a09e92ef37721e2325b6790011010001cd00c2c07b041001080025050251d0c680050900278d00060b09070803020415080a0203160201021901021b03021e01000a0910e7b484133a890a35ae4b0800a1beb82e7f28eaf5273d6af9d3391314f6280b2b624eaca2851f89a9ebcaf80ac589ebd509f168bc4322106ca2e2ce77a76e071a3c7444787d65216b5f05e82c77928860b92aace3b7d0327db59492f422eb9dfab7249266d37429870b091a98aba8724c2259ebf8f85093f21255eafa75aa841e31d94f2ac891b9755fed455e539044ee69fc47950b80e003fc9f298d695660f28329eaa38037c367efde1727458e514faf990d439a21461b719edaddf9296d3d0647b43ca56cb8dbf63b4fcf8b9968e7928c463470fab3b98e44d0d95645062f94b2d04fe56bd52822b71934db8ce845622c40b92fcbe765a142e7f38b61a6aa9606c8e8858dcd3b6eb1894acec04d0451d1f06b01080088bea67444e1789390e7c0335c86775502d58ec783d99c8ef4e06de235ed3dd4b0467f6f358d818c7d8989d43ec6d69fcbc8c32632d5a1b605e3fa8e41d695fcdcaa535936cd0157f9040dce362519803b908eafe838bb13216c885c6f93e9e8d5745607f0d062322085d6bdc760969149a8ff8dd9f5c18d9bfe2e6f63a06e17694cf1f67587c6fb70e9aebf90ffc528ca3b615ac7c9d4a21ea4f7c06f2e98fbbd90a859b8608bf9ea638e3a54289ce44c283110d0c45fa458de6251cd6e7baf71f80f12c8978340490fd90c92b81736ae902ed958e478dceae2835953d189c45d182aff02ea2be61b81d8e94430f041d638647b43e2fcb45fd512fbf5068b810011010001c2c06504180108000f050251d1f06b050900081095021b0c000a0910e7b484133a890a35e63407fe2ec88d6d1e6c9ce7553ece0cb2524747217bad29f251d33df84599ffcc900141a355abd62126800744068a5e05dc167056aa9205273dc7765a2ed49db15c2a83b8d6e6429c902136f1e12229086c1c10c0053242c2a4ae1930db58163387a48cad64607ff2153c320e42843dec28e3fce90e7399d63ac0affa2fee1f0adc0953c89eb3f46ef1d6c04328ed13b491669d5120a3782e3ffb7c69575fb77eebd108794f4dda9d34be2bae57e8e59ec8ebfda2f6f06104b2321be408ea146e2db482b00c5055c8618de36ac9716f80da2617e225556d0fce61b01c8cea2d1e0ea982c31711060ca370f2739366e1e708f38405d784b49d16a26cf62d152eae734327cec04d0451d1f07b010800d5af91c5e7c2fd8951c8d254eab0c97cdcb66822f868b79b78c366255059a68fd74ebca9adb9b970cd9e586690e6e0756705432306878c897b10a4b4ca0005966f99ac8fa4e6f9caf54bf8e53844544beee9872a7ac64c119cf1393d96e674254b661f61ee975633d0e8a8672531edb6bb8e211204e7754a9efa802342118eee850beea742bac95a3f706cc2024cf6037a308bb68162b2f53b9a6346a96e6d31871a2456186e24a1c7a82b82ac04afdfd57cd7fb9ba77a9c760d40b76a170f7be525e5fb6a9848cc726e806187710d9b190387df28700f321f988a392899f93815cc937f309129eb94d5299c5547cb2c085898e6639496e70d746c9d3fb9881d0011010001c2c06504180108000f050251d1f07b050900266305021b0c000a0910e7b484133a890a35bff207fd10dfe8c4a6ea1dd30568012b6fd6891a763c87ad0f7a1d112aad9e8e3239378a3b85588c235865bac2e614348cb4f216d7217f53b3ef48c192e0a4d31d64d7bfa5faccf21155965fa156e887056db644a05ad08a85cc6152d1377d9e37b46f4ff462bbe68ace2dc586ef90070314576c985d8037c2ba63f0a7dc17a62e15bd77e88bc61d9d00858979709f12304264a4cf4225c5cf86f12c8e19486cb9cdcc69f18f027e5f16f4ca8b50e28b3115eaff3a345acd21f624aef81f6ede515c1b55b26b84c1e32264754eab672d5489b287e7277ea855e0a5ff2aa9e8b8c76d579a964ec225255f4d57bf66639ccb34b64798846943e162a41096a7002ca21c7f56" -const subkeyUsageHex = "988d04533a52bc010400d26af43085558f65b9e7dbc90cb9238015259aed5e954637adcfa2181548b2d0b60c65f1f42ec5081cbf1bc0a8aa4900acfb77070837c58f26012fbce297d70afe96e759ad63531f0037538e70dbf8e384569b9720d99d8eb39d8d0a2947233ed242436cb6ac7dfe74123354b3d0119b5c235d3dd9c9d6c004f8ffaf67ad8583001101000188b7041f010200210502533b8552170c8001ce094aa433f7040bb2ddf0be3893cb843d0fe70c020700000a0910a42704b92866382aa98404009d63d916a27543da4221c60087c33f1c44bec9998c5438018ed370cca4962876c748e94b73eb39c58eb698063f3fd6346d58dd2a11c0247934c4a9d71f24754f7468f96fb24c3e791dd2392b62f626148ad724189498cbf993db2df7c0cdc2d677c35da0f16cb16c9ce7c33b4de65a4a91b1d21a130ae9cc26067718910ef8e2b417556d627261203c756d627261407379642e65642e61753e88b80413010200220502533a52bc021b03060b090807030206150802090a0b0416020301021e01021780000a0910a42704b92866382a47840400c0c2bd04f5fca586de408b395b3c280a278259c93eaaa8b79a53b97003f8ed502a8a00446dd9947fb462677e4fcac0dac2f0701847d15130aadb6cd9e0705ea0cf5f92f129136c7be21a718d46c8e641eb7f044f2adae573e11ae423a0a9ca51324f03a8a2f34b91fa40c3cc764bee4dccadedb54c768ba0469b683ea53f1c29b88d04533a52bc01040099c92a5d6f8b744224da27bc2369127c35269b58bec179de6bbc038f749344222f85a31933224f26b70243c4e4b2d242f0c4777eaef7b5502f9dad6d8bf3aaeb471210674b74de2d7078af497d55f5cdad97c7bedfbc1b41e8065a97c9c3d344b21fc81d27723af8e374bc595da26ea242dccb6ae497be26eea57e563ed517e90011010001889f0418010200090502533a52bc021b0c000a0910a42704b92866382afa1403ff70284c2de8a043ff51d8d29772602fa98009b7861c540535f874f2c230af8caf5638151a636b21f8255003997ccd29747fdd06777bb24f9593bd7d98a3e887689bf902f999915fcc94625ae487e5d13e6616f89090ebc4fdc7eb5cad8943e4056995bb61c6af37f8043016876a958ec7ebf39c43d20d53b7f546cfa83e8d2604b88d04533b8283010400c0b529316dbdf58b4c54461e7e669dc11c09eb7f73819f178ccd4177b9182b91d138605fcf1e463262fabefa73f94a52b5e15d1904635541c7ea540f07050ce0fb51b73e6f88644cec86e91107c957a114f69554548a85295d2b70bd0b203992f76eb5d493d86d9eabcaa7ef3fc7db7e458438db3fcdb0ca1cc97c638439a9170011010001889f0418010200090502533b8283021b0c000a0910a42704b92866382adc6d0400cfff6258485a21675adb7a811c3e19ebca18851533f75a7ba317950b9997fda8d1a4c8c76505c08c04b6c2cc31dc704d33da36a21273f2b388a1a706f7c3378b66d887197a525936ed9a69acb57fe7f718133da85ec742001c5d1864e9c6c8ea1b94f1c3759cebfd93b18606066c063a63be86085b7e37bdbc65f9a915bf084bb901a204533b85cd110400aed3d2c52af2b38b5b67904b0ef73d6dd7aef86adb770e2b153cd22489654dcc91730892087bb9856ae2d9f7ed1eb48f214243fe86bfe87b349ebd7c30e630e49c07b21fdabf78b7a95c8b7f969e97e3d33f2e074c63552ba64a2ded7badc05ce0ea2be6d53485f6900c7860c7aa76560376ce963d7271b9b54638a4028b573f00a0d8854bfcdb04986141568046202192263b9b67350400aaa1049dbc7943141ef590a70dcb028d730371d92ea4863de715f7f0f16d168bd3dc266c2450457d46dcbbf0b071547e5fbee7700a820c3750b236335d8d5848adb3c0da010e998908dfd93d961480084f3aea20b247034f8988eccb5546efaa35a92d0451df3aaf1aee5aa36a4c4d462c760ecd9cebcabfbe1412b1f21450f203fd126687cd486496e971a87fd9e1a8a765fe654baa219a6871ab97768596ab05c26c1aeea8f1a2c72395a58dbc12ef9640d2b95784e974a4d2d5a9b17c25fedacfe551bda52602de8f6d2e48443f5dd1a2a2a8e6a5e70ecdb88cd6e766ad9745c7ee91d78cc55c3d06536b49c3fee6c3d0b6ff0fb2bf13a314f57c953b8f4d93bf88e70418010200090502533b85cd021b0200520910a42704b92866382a47200419110200060502533b85cd000a091042ce2c64bc0ba99214b2009e26b26852c8b13b10c35768e40e78fbbb48bd084100a0c79d9ea0844fa5853dd3c85ff3ecae6f2c9dd6c557aa04008bbbc964cd65b9b8299d4ebf31f41cc7264b8cf33a00e82c5af022331fac79efc9563a822497ba012953cefe2629f1242fcdcb911dbb2315985bab060bfd58261ace3c654bdbbe2e8ed27a46e836490145c86dc7bae15c011f7e1ffc33730109b9338cd9f483e7cef3d2f396aab5bd80efb6646d7e778270ee99d934d187dd98" -const revokedKeyHex = "988d045331ce82010400c4fdf7b40a5477f206e6ee278eaef888ca73bf9128a9eef9f2f1ddb8b7b71a4c07cfa241f028a04edb405e4d916c61d6beabc333813dc7b484d2b3c52ee233c6a79b1eea4e9cc51596ba9cd5ac5aeb9df62d86ea051055b79d03f8a4fa9f38386f5bd17529138f3325d46801514ea9047977e0829ed728e68636802796801be10011010001889f04200102000905025331d0e3021d03000a0910a401d9f09a34f7c042aa040086631196405b7e6af71026b88e98012eab44aa9849f6ef3fa930c7c9f23deaedba9db1538830f8652fb7648ec3fcade8dbcbf9eaf428e83c6cbcc272201bfe2fbb90d41963397a7c0637a1a9d9448ce695d9790db2dc95433ad7be19eb3de72dacf1d6db82c3644c13eae2a3d072b99bb341debba012c5ce4006a7d34a1f4b94b444526567205265766f6b657220283c52656727732022424d204261726973746122204b657920262530305c303e5c29203c72656740626d626172697374612e636f2e61753e88b704130102002205025331ce82021b03060b090807030206150802090a0b0416020301021e01021780000a0910a401d9f09a34f7c0019c03f75edfbeb6a73e7225ad3cc52724e2872e04260d7daf0d693c170d8c4b243b8767bc7785763533febc62ec2600c30603c433c095453ede59ff2fcabeb84ce32e0ed9d5cf15ffcbc816202b64370d4d77c1e9077d74e94a16fb4fa2e5bec23a56d7a73cf275f91691ae1801a976fcde09e981a2f6327ac27ea1fecf3185df0d56889c04100102000605025331cfb5000a0910fe9645554e8266b64b4303fc084075396674fb6f778d302ac07cef6bc0b5d07b66b2004c44aef711cbac79617ef06d836b4957522d8772dd94bf41a2f4ac8b1ee6d70c57503f837445a74765a076d07b829b8111fc2a918423ddb817ead7ca2a613ef0bfb9c6b3562aec6c3cf3c75ef3031d81d95f6563e4cdcc9960bcb386c5d757b104fcca5fe11fc709df884604101102000605025331cfe7000a09107b15a67f0b3ddc0317f6009e360beea58f29c1d963a22b962b80788c3fa6c84e009d148cfde6b351469b8eae91187eff07ad9d08fcaab88d045331ce820104009f25e20a42b904f3fa555530fe5c46737cf7bd076c35a2a0d22b11f7e0b61a69320b768f4a80fe13980ce380d1cfc4a0cd8fbe2d2e2ef85416668b77208baa65bf973fe8e500e78cc310d7c8705cdb34328bf80e24f0385fce5845c33bc7943cf6b11b02348a23da0bf6428e57c05135f2dc6bd7c1ce325d666d5a5fd2fd5e410011010001889f04180102000905025331ce82021b0c000a0910a401d9f09a34f7c0418003fe34feafcbeaef348a800a0d908a7a6809cc7304017d820f70f0474d5e23cb17e38b67dc6dca282c6ca00961f4ec9edf2738d0f087b1d81e4871ef08e1798010863afb4eac4c44a376cb343be929c5be66a78cfd4456ae9ec6a99d97f4e1c3ff3583351db2147a65c0acef5c003fb544ab3a2e2dc4d43646f58b811a6c3a369d1f" -const revokedSubkeyHex = "988d04533121f6010400aefc803a3e4bb1a61c86e8a86d2726c6a43e0079e9f2713f1fa017e9854c83877f4aced8e331d675c67ea83ddab80aacbfa0b9040bb12d96f5a3d6be09455e2a76546cbd21677537db941cab710216b6d24ec277ee0bd65b910f416737ed120f6b93a9d3b306245c8cfd8394606fdb462e5cf43c551438d2864506c63367fc890011010001b41d416c696365203c616c69636540626d626172697374612e636f2e61753e88bb041301020025021b03060b090807030206150802090a0b0416020301021e01021780050253312798021901000a09104ef7e4beccde97f015a803ff5448437780f63263b0df8442a995e7f76c221351a51edd06f2063d8166cf3157aada4923dfc44aa0f2a6a4da5cf83b7fe722ba8ab416c976e77c6b5682e7f1069026673bd0de56ba06fd5d7a9f177607f277d9b55ff940a638c3e68525c67517e2b3d976899b93ca267f705b3e5efad7d61220e96b618a4497eab8d04403d23f8846041011020006050253312910000a09107b15a67f0b3ddc03d96e009f50b6365d86c4be5d5e9d0ea42d5e56f5794c617700a0ab274e19c2827780016d23417ce89e0a2c0d987d889c04100102000605025331cf7a000a0910a401d9f09a34f7c0ee970400aca292f213041c9f3b3fc49148cbda9d84afee6183c8dd6c5ff2600b29482db5fecd4303797be1ee6d544a20a858080fec43412061c9a71fae4039fd58013b4ae341273e6c66ad4c7cdd9e68245bedb260562e7b166f2461a1032f2b38c0e0e5715fb3d1656979e052b55ca827a76f872b78a9fdae64bc298170bfcebedc1271b41a416c696365203c616c696365407379646973702e6f722e61753e88b804130102002205025331278b021b03060b090807030206150802090a0b0416020301021e01021780000a09104ef7e4beccde97f06a7003fa03c3af68d272ebc1fa08aa72a03b02189c26496a2833d90450801c4e42c5b5f51ad96ce2d2c9cef4b7c02a6a2fcf1412d6a2d486098eb762f5010a201819c17fd2888aec8eda20c65a3b75744de7ee5cc8ac7bfc470cbe3cb982720405a27a3c6a8c229cfe36905f881b02ed5680f6a8f05866efb9d6c5844897e631deb949ca8846041011020006050253312910000a09107b15a67f0b3ddc0347bc009f7fa35db59147469eb6f2c5aaf6428accb138b22800a0caa2f5f0874bacc5909c652a57a31beda65eddd5889c04100102000605025331cf7a000a0910a401d9f09a34f7c0316403ff46f2a5c101256627f16384d34a38fb47a6c88ba60506843e532d91614339fccae5f884a5741e7582ffaf292ba38ee10a270a05f139bde3814b6a077e8cd2db0f105ebea2a83af70d385f13b507fac2ad93ff79d84950328bb86f3074745a8b7f9b64990fb142e2a12976e27e8d09a28dc5621f957ac49091116da410ac3cbde1b88d04533121f6010400cbd785b56905e4192e2fb62a720727d43c4fa487821203cf72138b884b78b701093243e1d8c92a0248a6c0203a5a88693da34af357499abacaf4b3309c640797d03093870a323b4b6f37865f6eaa2838148a67df4735d43a90ca87942554cdf1c4a751b1e75f9fd4ce4e97e278d6c1c7ed59d33441df7d084f3f02beb68896c70011010001889f0418010200090502533121f6021b0c000a09104ef7e4beccde97f0b98b03fc0a5ccf6a372995835a2f5da33b282a7d612c0ab2a97f59cf9fff73e9110981aac2858c41399afa29624a7fd8a0add11654e3d882c0fd199e161bdad65e5e2548f7b68a437ea64293db1246e3011cbb94dc1bcdeaf0f2539bd88ff16d95547144d97cead6a8c5927660a91e6db0d16eb36b7b49a3525b54d1644e65599b032b7eb901a204533127a0110400bd3edaa09eff9809c4edc2c2a0ebe52e53c50a19c1e49ab78e6167bf61473bb08f2050d78a5cbbc6ed66aff7b42cd503f16b4a0b99fa1609681fca9b7ce2bbb1a5b3864d6cdda4d7ef7849d156d534dea30fb0efb9e4cf8959a2b2ce623905882d5430b995a15c3b9fe92906086788b891002924f94abe139b42cbbfaaabe42f00a0b65dc1a1ad27d798adbcb5b5ad02d2688c89477b03ff4eebb6f7b15a73b96a96bed201c0e5e4ea27e4c6e2dd1005b94d4b90137a5b1cf5e01c6226c070c4cc999938101578877ee76d296b9aab8246d57049caacf489e80a3f40589cade790a020b1ac146d6f7a6241184b8c7fcde680eae3188f5dcbe846d7f7bdad34f6fcfca08413e19c1d5df83fc7c7c627d493492e009c2f52a80400a2fe82de87136fd2e8845888c4431b032ba29d9a29a804277e31002a8201fb8591a3e55c7a0d0881496caf8b9fb07544a5a4879291d0dc026a0ea9e5bd88eb4aa4947bbd694b25012e208a250d65ddc6f1eea59d3aed3b4ec15fcab85e2afaa23a40ab1ef9ce3e11e1bc1c34a0e758e7aa64deb8739276df0af7d4121f834a9b88e70418010200090502533127a0021b02005209104ef7e4beccde97f047200419110200060502533127a0000a0910dbce4ee19529437fe045009c0b32f5ead48ee8a7e98fac0dea3d3e6c0e2c552500a0ad71fadc5007cfaf842d9b7db3335a8cdad15d3d1a6404009b08e2c68fe8f3b45c1bb72a4b3278cdf3012aa0f229883ad74aa1f6000bb90b18301b2f85372ca5d6b9bf478d235b733b1b197d19ccca48e9daf8e890cb64546b4ce1b178faccfff07003c172a2d4f5ebaba9f57153955f3f61a9b80a4f5cb959908f8b211b03b7026a8a82fc612bfedd3794969bcf458c4ce92be215a1176ab88d045331d144010400a5063000c5aaf34953c1aa3bfc95045b3aab9882b9a8027fecfe2142dc6b47ba8aca667399990244d513dd0504716908c17d92c65e74219e004f7b83fc125e575dd58efec3ab6dd22e3580106998523dea42ec75bf9aa111734c82df54630bebdff20fe981cfc36c76f865eb1c2fb62c9e85bc3a6e5015a361a2eb1c8431578d0011010001889f04280102000905025331d433021d03000a09104ef7e4beccde97f02e5503ff5e0630d1b65291f4882b6d40a29da4616bb5088717d469fbcc3648b8276de04a04988b1f1b9f3e18f52265c1f8b6c85861691c1a6b8a3a25a1809a0b32ad330aec5667cb4262f4450649184e8113849b05e5ad06a316ea80c001e8e71838190339a6e48bbde30647bcf245134b9a97fa875c1d83a9862cae87ffd7e2c4ce3a1b89013d04180102000905025331d144021b0200a809104ef7e4beccde97f09d2004190102000605025331d144000a0910677815e371c2fd23522203fe22ab62b8e7a151383cea3edd3a12995693911426f8ccf125e1f6426388c0010f88d9ca7da2224aee8d1c12135998640c5e1813d55a93df472faae75bef858457248db41b4505827590aeccf6f9eb646da7f980655dd3050c6897feddddaca90676dee856d66db8923477d251712bb9b3186b4d0114daf7d6b59272b53218dd1da94a03ff64006fcbe71211e5daecd9961fba66cdb6de3f914882c58ba5beddeba7dcb950c1156d7fba18c19ea880dccc800eae335deec34e3b84ac75ffa24864f782f87815cda1c0f634b3dd2fa67cea30811d21723d21d9551fa12ccbcfa62b6d3a15d01307b99925707992556d50065505b090aadb8579083a20fe65bd2a270da9b011" - -const missingCrossSignatureKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Charset: UTF-8 - -mQENBFMYynYBCACVOZ3/e8Bm2b9KH9QyIlHGo/i1bnkpqsgXj8tpJ2MIUOnXMMAY -ztW7kKFLCmgVdLIC0vSoLA4yhaLcMojznh/2CcUglZeb6Ao8Gtelr//Rd5DRfPpG -zqcfUo+m+eO1co2Orabw0tZDfGpg5p3AYl0hmxhUyYSc/xUq93xL1UJzBFgYXY54 -QsM8dgeQgFseSk/YvdP5SMx1ev+eraUyiiUtWzWrWC1TdyRa5p4UZg6Rkoppf+WJ -QrW6BWrhAtqATHc8ozV7uJjeONjUEq24roRc/OFZdmQQGK6yrzKnnbA6MdHhqpdo -9kWDcXYb7pSE63Lc+OBa5X2GUVvXJLS/3nrtABEBAAG0F2ludmFsaWQtc2lnbmlu -Zy1zdWJrZXlziQEoBBMBAgASBQJTnKB5AhsBAgsHAhUIAh4BAAoJEO3UDQUIHpI/ -dN4H/idX4FQ1LIZCnpHS/oxoWQWfpRgdKAEM0qCqjMgiipJeEwSQbqjTCynuh5/R -JlODDz85ABR06aoF4l5ebGLQWFCYifPnJZ/Yf5OYcMGtb7dIbqxWVFL9iLMO/oDL -ioI3dotjPui5e+2hI9pVH1UHB/bZ/GvMGo6Zg0XxLPolKQODMVjpjLAQ0YJ3spew -RAmOGre6tIvbDsMBnm8qREt7a07cBJ6XK7xjxYaZHQBiHVxyEWDa6gyANONx8duW -/fhQ/zDTnyVM/ik6VO0Ty9BhPpcEYLFwh5c1ilFari1ta3e6qKo6ZGa9YMk/REhu -yBHd9nTkI+0CiQUmbckUiVjDKKe5AQ0EUxjKdgEIAJcXQeP+NmuciE99YcJoffxv -2gVLU4ZXBNHEaP0mgaJ1+tmMD089vUQAcyGRvw8jfsNsVZQIOAuRxY94aHQhIRHR -bUzBN28ofo/AJJtfx62C15xt6fDKRV6HXYqAiygrHIpEoRLyiN69iScUsjIJeyFL -C8wa72e8pSL6dkHoaV1N9ZH/xmrJ+k0vsgkQaAh9CzYufncDxcwkoP+aOlGtX1gP -WwWoIbz0JwLEMPHBWvDDXQcQPQTYQyj+LGC9U6f9VZHN25E94subM1MjuT9OhN9Y -MLfWaaIc5WyhLFyQKW2Upofn9wSFi8ubyBnv640Dfd0rVmaWv7LNTZpoZ/GbJAMA -EQEAAYkBHwQYAQIACQUCU5ygeQIbAgAKCRDt1A0FCB6SP0zCB/sEzaVR38vpx+OQ -MMynCBJrakiqDmUZv9xtplY7zsHSQjpd6xGflbU2n+iX99Q+nav0ETQZifNUEd4N -1ljDGQejcTyKD6Pkg6wBL3x9/RJye7Zszazm4+toJXZ8xJ3800+BtaPoI39akYJm -+ijzbskvN0v/j5GOFJwQO0pPRAFtdHqRs9Kf4YanxhedB4dIUblzlIJuKsxFit6N -lgGRblagG3Vv2eBszbxzPbJjHCgVLR3RmrVezKOsZjr/2i7X+xLWIR0uD3IN1qOW -CXQxLBizEEmSNVNxsp7KPGTLnqO3bPtqFirxS9PJLIMPTPLNBY7ZYuPNTMqVIUWF -4artDmrG -=7FfJ ------END PGP PUBLIC KEY BLOCK-----` - -const invalidCrossSignatureKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- - -mQENBFMYynYBCACVOZ3/e8Bm2b9KH9QyIlHGo/i1bnkpqsgXj8tpJ2MIUOnXMMAY -ztW7kKFLCmgVdLIC0vSoLA4yhaLcMojznh/2CcUglZeb6Ao8Gtelr//Rd5DRfPpG -zqcfUo+m+eO1co2Orabw0tZDfGpg5p3AYl0hmxhUyYSc/xUq93xL1UJzBFgYXY54 -QsM8dgeQgFseSk/YvdP5SMx1ev+eraUyiiUtWzWrWC1TdyRa5p4UZg6Rkoppf+WJ -QrW6BWrhAtqATHc8ozV7uJjeONjUEq24roRc/OFZdmQQGK6yrzKnnbA6MdHhqpdo -9kWDcXYb7pSE63Lc+OBa5X2GUVvXJLS/3nrtABEBAAG0F2ludmFsaWQtc2lnbmlu -Zy1zdWJrZXlziQEoBBMBAgASBQJTnKB5AhsBAgsHAhUIAh4BAAoJEO3UDQUIHpI/ -dN4H/idX4FQ1LIZCnpHS/oxoWQWfpRgdKAEM0qCqjMgiipJeEwSQbqjTCynuh5/R -JlODDz85ABR06aoF4l5ebGLQWFCYifPnJZ/Yf5OYcMGtb7dIbqxWVFL9iLMO/oDL -ioI3dotjPui5e+2hI9pVH1UHB/bZ/GvMGo6Zg0XxLPolKQODMVjpjLAQ0YJ3spew -RAmOGre6tIvbDsMBnm8qREt7a07cBJ6XK7xjxYaZHQBiHVxyEWDa6gyANONx8duW -/fhQ/zDTnyVM/ik6VO0Ty9BhPpcEYLFwh5c1ilFari1ta3e6qKo6ZGa9YMk/REhu -yBHd9nTkI+0CiQUmbckUiVjDKKe5AQ0EUxjKdgEIAIINDqlj7X6jYKc6DjwrOkjQ -UIRWbQQar0LwmNilehmt70g5DCL1SYm9q4LcgJJ2Nhxj0/5qqsYib50OSWMcKeEe -iRXpXzv1ObpcQtI5ithp0gR53YPXBib80t3bUzomQ5UyZqAAHzMp3BKC54/vUrSK -FeRaxDzNLrCeyI00+LHNUtwghAqHvdNcsIf8VRumK8oTm3RmDh0TyjASWYbrt9c8 -R1Um3zuoACOVy+mEIgIzsfHq0u7dwYwJB5+KeM7ZLx+HGIYdUYzHuUE1sLwVoELh -+SHIGHI1HDicOjzqgajShuIjj5hZTyQySVprrsLKiXS6NEwHAP20+XjayJ/R3tEA -EQEAAYkCPgQYAQIBKAUCU5ygeQIbAsBdIAQZAQIABgUCU5ygeQAKCRCpVlnFZmhO -52RJB/9uD1MSa0wjY6tHOIgquZcP3bHBvHmrHNMw9HR2wRCMO91ZkhrpdS3ZHtgb -u3/55etj0FdvDo1tb8P8FGSVtO5Vcwf5APM8sbbqoi8L951Q3i7qt847lfhu6sMl -w0LWFvPTOLHrliZHItPRjOltS1WAWfr2jUYhsU9ytaDAJmvf9DujxEOsN5G1YJep -54JCKVCkM/y585Zcnn+yxk/XwqoNQ0/iJUT9qRrZWvoeasxhl1PQcwihCwss44A+ -YXaAt3hbk+6LEQuZoYS73yR3WHj+42tfm7YxRGeubXfgCEz/brETEWXMh4pe0vCL -bfWrmfSPq2rDegYcAybxRQz0lF8PAAoJEO3UDQUIHpI/exkH/0vQfdHA8g/N4T6E -i6b1CUVBAkvtdJpCATZjWPhXmShOw62gkDw306vHPilL4SCvEEi4KzG72zkp6VsB -DSRcpxCwT4mHue+duiy53/aRMtSJ+vDfiV1Vhq+3sWAck/yUtfDU9/u4eFaiNok1 -8/Gd7reyuZt5CiJnpdPpjCwelK21l2w7sHAnJF55ITXdOxI8oG3BRKufz0z5lyDY -s2tXYmhhQIggdgelN8LbcMhWs/PBbtUr6uZlNJG2lW1yscD4aI529VjwJlCeo745 -U7pO4eF05VViUJ2mmfoivL3tkhoTUWhx8xs8xCUcCg8DoEoSIhxtOmoTPR22Z9BL -6LCg2mg= -=Dhm4 ------END PGP PUBLIC KEY BLOCK-----` - -const goodCrossSignatureKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1 - -mI0EVUqeVwEEAMufHRrMPWK3gyvi0O0tABCs/oON9zV9KDZlr1a1M91ShCSFwCPo -7r80PxdWVWcj0V5h50/CJYtpN3eE/mUIgW2z1uDYQF1OzrQ8ubrksfsJvpAhENom -lTQEppv9mV8qhcM278teb7TX0pgrUHLYF5CfPdp1L957JLLXoQR/lwLVABEBAAG0 -E2dvb2Qtc2lnbmluZy1zdWJrZXmIuAQTAQIAIgUCVUqeVwIbAwYLCQgHAwIGFQgC -CQoLBBYCAwECHgECF4AACgkQNRjL95IRWP69XQQAlH6+eyXJN4DZTLX78KGjHrsw -6FCvxxClEPtPUjcJy/1KCRQmtLAt9PbbA78dvgzjDeZMZqRAwdjyJhjyg/fkU2OH -7wq4ktjUu+dLcOBb+BFMEY+YjKZhf6EJuVfxoTVr5f82XNPbYHfTho9/OABKH6kv -X70PaKZhbwnwij8Nts65AaIEVUqftREEAJ3WxZfqAX0bTDbQPf2CMT2IVMGDfhK7 -GyubOZgDFFjwUJQvHNvsrbeGLZ0xOBumLINyPO1amIfTgJNm1iiWFWfmnHReGcDl -y5mpYG60Mb79Whdcer7CMm3AqYh/dW4g6IB02NwZMKoUHo3PXmFLxMKXnWyJ0clw -R0LI/Qn509yXAKDh1SO20rqrBM+EAP2c5bfI98kyNwQAi3buu94qo3RR1ZbvfxgW -CKXDVm6N99jdZGNK7FbRifXqzJJDLcXZKLnstnC4Sd3uyfyf1uFhmDLIQRryn5m+ -LBYHfDBPN3kdm7bsZDDq9GbTHiFZUfm/tChVKXWxkhpAmHhU/tH6GGzNSMXuIWSO -aOz3Rqq0ED4NXyNKjdF9MiwD/i83S0ZBc0LmJYt4Z10jtH2B6tYdqnAK29uQaadx -yZCX2scE09UIm32/w7pV77CKr1Cp/4OzAXS1tmFzQ+bX7DR+Gl8t4wxr57VeEMvl -BGw4Vjh3X8//m3xynxycQU18Q1zJ6PkiMyPw2owZ/nss3hpSRKFJsxMLhW3fKmKr -Ey2KiOcEGAECAAkFAlVKn7UCGwIAUgkQNRjL95IRWP5HIAQZEQIABgUCVUqftQAK -CRD98VjDN10SqkWrAKDTpEY8D8HC02E/KVC5YUI01B30wgCgurpILm20kXEDCeHp -C5pygfXw1DJrhAP+NyPJ4um/bU1I+rXaHHJYroYJs8YSweiNcwiHDQn0Engh/mVZ -SqLHvbKh2dL/RXymC3+rjPvQf5cup9bPxNMa6WagdYBNAfzWGtkVISeaQW+cTEp/ -MtgVijRGXR/lGLGETPg2X3Afwn9N9bLMBkBprKgbBqU7lpaoPupxT61bL70= -=vtbN ------END PGP PUBLIC KEY BLOCK-----` - -const revokedUserIDKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- - -mQENBFsgO5EBCADhREPmcjsPkXe1z7ctvyWL0S7oa9JaoGZ9oPDHFDlQxd0qlX2e -DZJZDg0qYvVixmaULIulApq1puEsaJCn3lHUbHlb4PYKwLEywYXM28JN91KtLsz/ -uaEX2KC5WqeP40utmzkNLq+oRX/xnRMgwbO7yUNVG2UlEa6eI+xOXO3YtLdmJMBW -ClQ066ZnOIzEo1JxnIwha1CDBMWLLfOLrg6l8InUqaXbtEBbnaIYO6fXVXELUjkx -nmk7t/QOk0tXCy8muH9UDqJkwDUESY2l79XwBAcx9riX8vY7vwC34pm22fAUVLCJ -x1SJx0J8bkeNp38jKM2Zd9SUQqSbfBopQ4pPABEBAAG0I0dvbGFuZyBHb3BoZXIg -PG5vLXJlcGx5QGdvbGFuZy5jb20+iQFUBBMBCgA+FiEE5Ik5JLcNx6l6rZfw1oFy -9I6cUoMFAlsgO5ECGwMFCQPCZwAFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AACgkQ -1oFy9I6cUoMIkwf8DNPeD23i4jRwd/pylbvxwZintZl1fSwTJW1xcOa1emXaEtX2 -depuqhP04fjlRQGfsYAQh7X9jOJxAHjTmhqFBi5sD7QvKU00cPFYbJ/JTx0B41bl -aXnSbGhRPh63QtEZL7ACAs+shwvvojJqysx7kyVRu0EW2wqjXdHwR/SJO6nhNBa2 -DXzSiOU/SUA42mmG+5kjF8Aabq9wPwT9wjraHShEweNerNMmOqJExBOy3yFeyDpa -XwEZFzBfOKoxFNkIaVf5GSdIUGhFECkGvBMB935khftmgR8APxdU4BE7XrXexFJU -8RCuPXonm4WQOwTWR0vQg64pb2WKAzZ8HhwTGbQiR29sYW5nIEdvcGhlciA8cmV2 -b2tlZEBnb2xhbmcuY29tPokBNgQwAQoAIBYhBOSJOSS3Dcepeq2X8NaBcvSOnFKD -BQJbIDv3Ah0AAAoJENaBcvSOnFKDfWMIAKhI/Tvu3h8fSUxp/gSAcduT6bC1JttG -0lYQ5ilKB/58lBUA5CO3ZrKDKlzW3M8VEcvohVaqeTMKeoQd5rCZq8KxHn/KvN6N -s85REfXfniCKfAbnGgVXX3kDmZ1g63pkxrFu0fDZjVDXC6vy+I0sGyI/Inro0Pzb -tvn0QCsxjapKK15BtmSrpgHgzVqVg0cUp8vqZeKFxarYbYB2idtGRci4b9tObOK0 -BSTVFy26+I/mrFGaPrySYiy2Kz5NMEcRhjmTxJ8jSwEr2O2sUR0yjbgUAXbTxDVE -/jg5fQZ1ACvBRQnB7LvMHcInbzjyeTM3FazkkSYQD6b97+dkWwb1iWG5AQ0EWyA7 -kQEIALkg04REDZo1JgdYV4x8HJKFS4xAYWbIva1ZPqvDNmZRUbQZR2+gpJGEwn7z -VofGvnOYiGW56AS5j31SFf5kro1+1bZQ5iOONBng08OOo58/l1hRseIIVGB5TGSa -PCdChKKHreJI6hS3mShxH6hdfFtiZuB45rwoaArMMsYcjaezLwKeLc396cpUwwcZ -snLUNd1Xu5EWEF2OdFkZ2a1qYdxBvAYdQf4+1Nr+NRIx1u1NS9c8jp3PuMOkrQEi -bNtc1v6v0Jy52mKLG4y7mC/erIkvkQBYJdxPaP7LZVaPYc3/xskcyijrJ/5ufoD8 -K71/ShtsZUXSQn9jlRaYR0EbojMAEQEAAYkBPAQYAQoAJhYhBOSJOSS3Dcepeq2X -8NaBcvSOnFKDBQJbIDuRAhsMBQkDwmcAAAoJENaBcvSOnFKDkFMIAIt64bVZ8x7+ -TitH1bR4pgcNkaKmgKoZz6FXu80+SnbuEt2NnDyf1cLOSimSTILpwLIuv9Uft5Pb -OraQbYt3xi9yrqdKqGLv80bxqK0NuryNkvh9yyx5WoG1iKqMj9/FjGghuPrRaT4l -QinNAghGVkEy1+aXGFrG2DsOC1FFI51CC2WVTzZ5RwR2GpiNRfESsU1rZAUqf/2V -yJl9bD5R4SUNy8oQmhOxi+gbhD4Ao34e4W0ilibslI/uawvCiOwlu5NGd8zv5n+U -heiQvzkApQup5c+BhH5zFDFdKJ2CBByxw9+7QjMFI/wgLixKuE0Ob2kAokXf7RlB -7qTZOahrETw= -=IKnw ------END PGP PUBLIC KEY BLOCK-----` - -const keyWithFirstUserIDRevoked = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Version: OpenPGP.js v4.10.10 -Comment: https://openpgpjs.org - -xsBNBFsgO5EBCADhREPmcjsPkXe1z7ctvyWL0S7oa9JaoGZ9oPDHFDlQxd0q -lX2eDZJZDg0qYvVixmaULIulApq1puEsaJCn3lHUbHlb4PYKwLEywYXM28JN -91KtLsz/uaEX2KC5WqeP40utmzkNLq+oRX/xnRMgwbO7yUNVG2UlEa6eI+xO -XO3YtLdmJMBWClQ066ZnOIzEo1JxnIwha1CDBMWLLfOLrg6l8InUqaXbtEBb -naIYO6fXVXELUjkxnmk7t/QOk0tXCy8muH9UDqJkwDUESY2l79XwBAcx9riX -8vY7vwC34pm22fAUVLCJx1SJx0J8bkeNp38jKM2Zd9SUQqSbfBopQ4pPABEB -AAHNIkdvbGFuZyBHb3BoZXIgPHJldm9rZWRAZ29sYW5nLmNvbT7CwI0EMAEK -ACAWIQTkiTkktw3HqXqtl/DWgXL0jpxSgwUCWyA79wIdAAAhCRDWgXL0jpxS -gxYhBOSJOSS3Dcepeq2X8NaBcvSOnFKDfWMIAKhI/Tvu3h8fSUxp/gSAcduT -6bC1JttG0lYQ5ilKB/58lBUA5CO3ZrKDKlzW3M8VEcvohVaqeTMKeoQd5rCZ -q8KxHn/KvN6Ns85REfXfniCKfAbnGgVXX3kDmZ1g63pkxrFu0fDZjVDXC6vy -+I0sGyI/Inro0Pzbtvn0QCsxjapKK15BtmSrpgHgzVqVg0cUp8vqZeKFxarY -bYB2idtGRci4b9tObOK0BSTVFy26+I/mrFGaPrySYiy2Kz5NMEcRhjmTxJ8j -SwEr2O2sUR0yjbgUAXbTxDVE/jg5fQZ1ACvBRQnB7LvMHcInbzjyeTM3Fazk -kSYQD6b97+dkWwb1iWHNI0dvbGFuZyBHb3BoZXIgPG5vLXJlcGx5QGdvbGFu -Zy5jb20+wsCrBBMBCgA+FiEE5Ik5JLcNx6l6rZfw1oFy9I6cUoMFAlsgO5EC -GwMFCQPCZwAFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AAIQkQ1oFy9I6cUoMW -IQTkiTkktw3HqXqtl/DWgXL0jpxSgwiTB/wM094PbeLiNHB3+nKVu/HBmKe1 -mXV9LBMlbXFw5rV6ZdoS1fZ16m6qE/Th+OVFAZ+xgBCHtf2M4nEAeNOaGoUG -LmwPtC8pTTRw8Vhsn8lPHQHjVuVpedJsaFE+HrdC0RkvsAICz6yHC++iMmrK -zHuTJVG7QRbbCqNd0fBH9Ik7qeE0FrYNfNKI5T9JQDjaaYb7mSMXwBpur3A/ -BP3COtodKETB416s0yY6okTEE7LfIV7IOlpfARkXMF84qjEU2QhpV/kZJ0hQ -aEUQKQa8EwH3fmSF+2aBHwA/F1TgETtetd7EUlTxEK49eiebhZA7BNZHS9CD -rilvZYoDNnweHBMZzsBNBFsgO5EBCAC5INOERA2aNSYHWFeMfByShUuMQGFm -yL2tWT6rwzZmUVG0GUdvoKSRhMJ+81aHxr5zmIhluegEuY99UhX+ZK6NftW2 -UOYjjjQZ4NPDjqOfP5dYUbHiCFRgeUxkmjwnQoSih63iSOoUt5kocR+oXXxb -YmbgeOa8KGgKzDLGHI2nsy8Cni3N/enKVMMHGbJy1DXdV7uRFhBdjnRZGdmt -amHcQbwGHUH+PtTa/jUSMdbtTUvXPI6dz7jDpK0BImzbXNb+r9CcudpiixuM -u5gv3qyJL5EAWCXcT2j+y2VWj2HN/8bJHMoo6yf+bn6A/Cu9f0obbGVF0kJ/ -Y5UWmEdBG6IzABEBAAHCwJMEGAEKACYWIQTkiTkktw3HqXqtl/DWgXL0jpxS -gwUCWyA7kQIbDAUJA8JnAAAhCRDWgXL0jpxSgxYhBOSJOSS3Dcepeq2X8NaB -cvSOnFKDkFMIAIt64bVZ8x7+TitH1bR4pgcNkaKmgKoZz6FXu80+SnbuEt2N -nDyf1cLOSimSTILpwLIuv9Uft5PbOraQbYt3xi9yrqdKqGLv80bxqK0NuryN -kvh9yyx5WoG1iKqMj9/FjGghuPrRaT4lQinNAghGVkEy1+aXGFrG2DsOC1FF -I51CC2WVTzZ5RwR2GpiNRfESsU1rZAUqf/2VyJl9bD5R4SUNy8oQmhOxi+gb -hD4Ao34e4W0ilibslI/uawvCiOwlu5NGd8zv5n+UheiQvzkApQup5c+BhH5z -FDFdKJ2CBByxw9+7QjMFI/wgLixKuE0Ob2kAokXf7RlB7qTZOahrETw= -=+2T8 ------END PGP PUBLIC KEY BLOCK----- -` - -const keyWithOnlyUserIDRevoked = `-----BEGIN PGP PUBLIC KEY BLOCK----- - -mDMEYYwB7RYJKwYBBAHaRw8BAQdARimqhPPzyGAXmfQJjcqM1QVPzLtURJSzNVll -JV4tEaW0KVJldm9rZWQgUHJpbWFyeSBVc2VyIElEIDxyZXZva2VkQGtleS5jb20+ -iHgEMBYIACAWIQSpyJZAXYqVEFkjyKutFcS0yeB0LQUCYYwCtgIdAAAKCRCtFcS0 -yeB0LbSsAQD8OYMaaBjrdzzpwIkP1stgmPd4/kzN/ZG28Ywl6a5F5QEA5Xg7aq4e -/t6Fsb4F5iqB956kSPe6YJrikobD/tBbMwSIkAQTFggAOBYhBKnIlkBdipUQWSPI -q60VxLTJ4HQtBQJhjAHtAhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAAAoJEK0V -xLTJ4HQtBaoBAPZL7luTCji+Tqhn7XNfFE/0QIahCt8k9wfO1cGlB3inAQDf8Tzw -ZGR5fNluUcNoVxQT7bUSFStbaGo3k0BaOYPbCLg4BGGMAe0SCisGAQQBl1UBBQEB -B0DLwSpveSrbIO/IVZD13yrs1XuB3FURZUnafGrRq7+jUAMBCAeIeAQYFggAIBYh -BKnIlkBdipUQWSPIq60VxLTJ4HQtBQJhjAHtAhsMAAoJEK0VxLTJ4HQtZ1oA/j9u -8+p3xTNzsmabTL6BkNbMeB/RUKCrlm6woM6AV+vxAQCcXTn3JC2sNoNrLoXuVzaA -mcG3/TwG5GSQUUPkrDsGDA== -=mFWy ------END PGP PUBLIC KEY BLOCK----- -` - -const keyWithSubKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- - -mI0EWyKwKQEEALwXhKBnyaaNFeK3ljfc/qn9X/QFw+28EUfgZPHjRmHubuXLE2uR -s3ZoSXY2z7Dkv+NyHYMt8p+X8q5fR7JvUjK2XbPyKoiJVnHINll83yl67DaWfKNL -EjNoO0kIfbXfCkZ7EG6DL+iKtuxniGTcnGT47e+HJSqb/STpLMnWwXjBABEBAAG0 -I0dvbGFuZyBHb3BoZXIgPG5vLXJlcGx5QGdvbGFuZy5jb20+iM4EEwEKADgWIQQ/ -lRafP/p9PytHbwxMvYJsOQdOOAUCWyKwKQIbAwULCQgHAwUVCgkICwUWAgMBAAIe -AQIXgAAKCRBMvYJsOQdOOOsFBAC62mXww8XuqvYLcVOvHkWLT6mhxrQOJXnlfpn7 -2uBV9CMhoG/Ycd43NONsJrB95Apr9TDIqWnVszNbqPCuBhZQSGLdbiDKjxnCWBk0 -69qv4RNtkpOhYB7jK4s8F5oQZqId6JasT/PmJTH92mhBYhhTQr0GYFuPX2UJdkw9 -Sn9C67iNBFsisDUBBAC3A+Yo9lgCnxi/pfskyLrweYif6kIXWLAtLTsM6g/6jt7b -wTrknuCPyTv0QKGXsAEe/cK/Xq3HvX9WfXPGIHc/X56ZIsHQ+RLowbZV/Lhok1IW -FAuQm8axr/by80cRwFnzhfPc/ukkAq2Qyj4hLsGblu6mxeAhzcp8aqmWOO2H9QAR -AQABiLYEKAEKACAWIQQ/lRafP/p9PytHbwxMvYJsOQdOOAUCWyK16gIdAAAKCRBM -vYJsOQdOOB1vA/4u4uLONsE+2GVOyBsHyy7uTdkuxaR9b54A/cz6jT/tzUbeIzgx -22neWhgvIEghnUZd0vEyK9k1wy5vbDlEo6nKzHso32N1QExGr5upRERAxweDxGOj -7luDwNypI7QcifE64lS/JmlnunwRCdRWMKc0Fp+7jtRc5mpwyHN/Suf5RokBagQY -AQoAIBYhBD+VFp8/+n0/K0dvDEy9gmw5B044BQJbIrA1AhsCAL8JEEy9gmw5B044 -tCAEGQEKAB0WIQSNdnkaWY6t62iX336UXbGvYdhXJwUCWyKwNQAKCRCUXbGvYdhX -JxJSA/9fCPHP6sUtGF1o3G1a3yvOUDGr1JWcct9U+QpbCt1mZoNopCNDDQAJvDWl -mvDgHfuogmgNJRjOMznvahbF+wpTXmB7LS0SK412gJzl1fFIpK4bgnhu0TwxNsO1 -8UkCZWqxRMgcNUn9z6XWONK8dgt5JNvHSHrwF4CxxwjL23AAtK+FA/UUoi3U4kbC -0XnSr1Sl+mrzQi1+H7xyMe7zjqe+gGANtskqexHzwWPUJCPZ5qpIa2l8ghiUim6b -4ymJ+N8/T8Yva1FaPEqfMzzqJr8McYFm0URioXJPvOAlRxdHPteZ0qUopt/Jawxl -Xt6B9h1YpeLoJwjwsvbi98UTRs0jXwoY -=3fWu ------END PGP PUBLIC KEY BLOCK-----` - -const keyWithSubKeyAndBadSelfSigOrder = `-----BEGIN PGP PUBLIC KEY BLOCK----- - -mI0EWyLLDQEEAOqIOpJ/ha1OYAGduu9tS3rBz5vyjbNgJO4sFveEM0mgsHQ0X9/L -plonW+d0gRoO1dhJ8QICjDAc6+cna1DE3tEb5m6JtQ30teLZuqrR398Cf6w7NNVz -r3lrlmnH9JaKRuXl7tZciwyovneBfZVCdtsRZjaLI1uMQCz/BToiYe3DABEBAAG0 -I0dvbGFuZyBHb3BoZXIgPG5vLXJlcGx5QGdvbGFuZy5jb20+iM4EEwEKADgWIQRZ -sixZOfQcZdW0wUqmgmdsv1O9xgUCWyLLDQIbAwULCQgHAwUVCgkICwUWAgMBAAIe -AQIXgAAKCRCmgmdsv1O9xql2A/4pix98NxjhdsXtazA9agpAKeADf9tG4Za27Gj+ -3DCww/E4iP2X35jZimSm/30QRB6j08uGCqd9vXkkJxtOt63y/IpVOtWX6vMWSTUm -k8xKkaYMP0/IzKNJ1qC/qYEUYpwERBKg9Z+k99E2Ql4kRHdxXUHq6OzY79H18Y+s -GdeM/riNBFsiyxsBBAC54Pxg/8ZWaZX1phGdwfe5mek27SOYpC0AxIDCSOdMeQ6G -HPk38pywl1d+S+KmF/F4Tdi+kWro62O4eG2uc/T8JQuRDUhSjX0Qa51gPzJrUOVT -CFyUkiZ/3ZDhtXkgfuso8ua2ChBgR9Ngr4v43tSqa9y6AK7v0qjxD1x+xMrjXQAR -AQABiQFxBBgBCgAmAhsCFiEEWbIsWTn0HGXVtMFKpoJnbL9TvcYFAlsizTIFCQAN -MRcAv7QgBBkBCgAdFiEEJcoVUVJIk5RWj1c/o62jUpRPICQFAlsiyxsACgkQo62j -UpRPICQq5gQApoWIigZxXFoM0uw4uJBS5JFZtirTANvirZV5RhndwHeMN6JttaBS -YnjyA4+n1D+zB2VqliD2QrsX12KJN6rGOehCtEIClQ1Hodo9nC6kMzzAwW1O8bZs -nRJmXV+bsvD4sidLZLjdwOVa3Cxh6pvq4Uur6a7/UYx121hEY0Qx0s8JEKaCZ2y/ -U73GGi0D/i20VW8AWYAPACm2zMlzExKTOAV01YTQH/3vW0WLrOse53WcIVZga6es -HuO4So0SOEAvxKMe5HpRIu2dJxTvd99Bo9xk9xJU0AoFrO0vNCRnL+5y68xMlODK -lEw5/kl0jeaTBp6xX0HDQOEVOpPGUwWV4Ij2EnvfNDXaE1vK1kffiQFrBBgBCgAg -AhsCFiEEWbIsWTn0HGXVtMFKpoJnbL9TvcYFAlsi0AYAv7QgBBkBCgAdFiEEJcoV -UVJIk5RWj1c/o62jUpRPICQFAlsiyxsACgkQo62jUpRPICQq5gQApoWIigZxXFoM -0uw4uJBS5JFZtirTANvirZV5RhndwHeMN6JttaBSYnjyA4+n1D+zB2VqliD2QrsX -12KJN6rGOehCtEIClQ1Hodo9nC6kMzzAwW1O8bZsnRJmXV+bsvD4sidLZLjdwOVa -3Cxh6pvq4Uur6a7/UYx121hEY0Qx0s8JEKaCZ2y/U73GRl0EAJokkXmy4zKDHWWi -wvK9gi2gQgRkVnu2AiONxJb5vjeLhM/07BRmH6K1o+w3fOeEQp4FjXj1eQ5fPSM6 -Hhwx2CTl9SDnPSBMiKXsEFRkmwQ2AAsQZLmQZvKBkLZYeBiwf+IY621eYDhZfo+G -1dh1WoUCyREZsJQg2YoIpWIcvw+a -=bNRo ------END PGP PUBLIC KEY BLOCK----- -` - -const onlySubkeyNoPrivateKey = `-----BEGIN PGP PRIVATE KEY BLOCK----- -Version: GnuPG v1 - -lQCVBFggvocBBAC7vBsHn7MKmS6IiiZNTXdciplVgS9cqVd+RTdIAoyNTcsiV1H0 -GQ3QtodOPeDlQDNoqinqaobd7R9g3m3hS53Nor7yBZkCWQ5x9v9JxRtoAq0sklh1 -I1X2zEqZk2l6YrfBF/64zWrhjnW3j23szkrAIVu0faQXbQ4z56tmZrw11wARAQAB -/gdlAkdOVQG0CUdOVSBEdW1teYi4BBMBAgAiBQJYIL6HAhsDBgsJCAcDAgYVCAIJ -CgsEFgIDAQIeAQIXgAAKCRCd1xxWp1CYAnjGA/9synn6ZXJUKAXQzySgmCZvCIbl -rqBfEpxwLG4Q/lONhm5vthAE0z49I8hj5Gc5e2tLYUtq0o0OCRdCrYHa/efOYWpJ -6RsK99bePOisVzmOABLIgZkcr022kHoMCmkPgv9CUGKP1yqbGl+zzAwQfUjRUmvD -ZIcWLHi2ge4GzPMPi50B2ARYIL6cAQQAxWHnicKejAFcFcF1/3gUSgSH7eiwuBPX -M7vDdgGzlve1o1jbV4tzrjN9jsCl6r0nJPDMfBSzgLr1auNTRG6HpJ4abcOx86ED -Ad+avDcQPZb7z3dPhH/gb2lQejZsHh7bbeOS8WMSzHV3RqCLd8J/xwWPNR5zKn1f -yp4IGfopidMAEQEAAQAD+wQOelnR82+dxyM2IFmZdOB9wSXQeCVOvxSaNMh6Y3lk -UOOkO8Nlic4x0ungQRvjoRs4wBmCuwFK/MII6jKui0B7dn/NDf51i7rGdNGuJXDH -e676By1sEY/NGkc74jr74T+5GWNU64W0vkpfgVmjSAzsUtpmhJMXsc7beBhJdnVl -AgDKCb8hZqj1alcdmLoNvb7ibA3K/V8J462CPD7bMySPBa/uayoFhNxibpoXml2r -oOtHa5izF3b0/9JY97F6rqkdAgD6GdTJ+xmlCoz1Sewoif1I6krq6xoa7gOYpIXo -UL1Afr+LiJeyAnF/M34j/kjIVmPanZJjry0kkjHE5ILjH3uvAf4/6n9np+Th8ujS -YDCIzKwR7639+H+qccOaddCep8Y6KGUMVdD/vTKEx1rMtK+hK/CDkkkxnFslifMJ -kqoqv3WUqCWJAT0EGAECAAkFAlggvpwCGwIAqAkQndccVqdQmAKdIAQZAQIABgUC -WCC+nAAKCRDmGUholQPwvQk+A/9latnSsR5s5/1A9TFki11GzSEnfLbx46FYOdkW -n3YBxZoPQGxNA1vIn8GmouxZInw9CF4jdOJxEdzLlYQJ9YLTLtN5tQEMl/19/bR8 -/qLacAZ9IOezYRWxxZsyn6//jfl7A0Y+FV59d4YajKkEfItcIIlgVBSW6T+TNQT3 -R+EH5HJ/A/4/AN0CmBhhE2vGzTnVU0VPrE4V64pjn1rufFdclgpixNZCuuqpKpoE -VVHn6mnBf4njKjZrAGPs5kfQ+H4NsM7v3Zz4yV6deu9FZc4O6E+V1WJ38rO8eBix -7G2jko106CC6vtxsCPVIzY7aaG3H5pjRtomw+pX7SzrQ7FUg2PGumg== -=F/T0 ------END PGP PRIVATE KEY BLOCK-----` - -const ecdsaPrivateKey = `-----BEGIN PGP PRIVATE KEY BLOCK----- - -xaUEX1KsSRMIKoZIzj0DAQcCAwTpYqJsnJiFhKKh+8TulWD+lVmerBFNS+Ii -B+nlG3T0xQQ4Sy5eIjJ0CExIQQzi3EElF/Z2l4F3WC5taFA11NgA/gkDCHSS -PThf1M2K4LN8F1MRcvR+sb7i0nH55ojkwuVB1DE6jqIT9m9i+mX1tzjSAS+6 -lPQiweCJvG7xTC7Hs3AzRapf/r1At4TB+v+5G2/CKynNFEJpbGwgPGJpbGxA -aG9tZS5jb20+wncEEBMIAB8FAl9SrEkGCwkHCAMCBBUICgIDFgIBAhkBAhsD -Ah4BAAoJEMpwT3+q3+xqw5UBAMebZN9isEZ1ML+R/jWAAWMwa/knMugrEZ1v -Bl9+ZwM0AQCZdf80/wYY4Nve01qSRFv8OmKswLli3TvDv6FKc4cLz8epBF9S -rEkSCCqGSM49AwEHAgMEAjKnT9b5wY2bf9TpAV3d7OUfPOxKj9c4VzeVzSrH -AtQgo/MuI1cdYVURicV4i76DNjFhQHQFTk7BrC+C2u1yqQMBCAf+CQMIHImA -iYfzQtjgQWSFZYUkCFpbbwhNF0ch+3HNaZkaHCnZRIsWsRnc6FCb6lRQyK9+ -Dq59kHlduE5QgY40894jfmP2JdJHU6nBdYrivbEdbMJhBBgTCAAJBQJfUqxJ -AhsMAAoJEMpwT3+q3+xqUI0BAMykhV08kQ4Ip9Qlbss6Jdufv7YrU0Vd5hou -b5TmiPd0APoDBh3qIic+aLLUcAuG3+Gt1P1AbUlmqV61ozn1WfHxfw== -=KLN8 ------END PGP PRIVATE KEY BLOCK-----` - -const dsaPrivateKeyWithElGamalSubkey = `-----BEGIN PGP PRIVATE KEY BLOCK----- - -lQOBBF9/MLsRCACeaF6BI0jTgDAs86t8/kXPfwlPvR2MCYzB0BCqAdcq1hV/GTYd -oNmJRna/ZJfsI/vf+d8Nv+EYOQkPheFS1MJVBitkAXjQPgm8i1tQWen1FCWZxqGk -/vwZYF4yo8GhZ+Wxi3w09W9Cp9QM/CTmyE1Xe7wpPBGe+oD+me8Zxjyt8JBS4Qx+ -gvWbfHxfHnggh4pz7U8QkItlLsBNQEdX4R5+zwRN66g2ZSX/shaa/EkVnihUhD7r -njP9I51ORWucTQD6OvgooaNQZCkQ/Se9TzdakwWKS2XSIFXiY/e2E5ZgKI/pfKDU -iA/KessxddPb7nP/05OIJqg9AoDrD4vmehLzAQD+zsUS3LDU1m9/cG4LMsQbT2VK -Te4HqbGIAle+eu/asQf8DDJMrbZpiJZvADum9j0TJ0oep6VdMbzo9RSDKvlLKT9m -kG63H8oDWnCZm1a+HmGq9YIX+JHWmsLXXsFLeEouLzHO+mZo0X28eji3V2T87hyR -MmUM0wFo4k7jK8uVmkDXv3XwNp2uByWxUKZd7EnWmcEZWqIiexJ7XpCS0Pg3tRaI -zxve0SRe/dxfUPnTk/9KQ9hS6DWroBKquL182zx1Fggh4LIWWE2zq+UYn8BI0E8A -rmIDFJdF8ymFQGRrEy6g79NnkPmkrZWsgMRYY65P6v4zLVmqohJKkpm3/Uxa6QAP -CCoPh/JTOvPeCP2bOJH8z4Z9Py3ouMIjofQW8sXqRgf/RIHbh0KsINHrwwZ4gVIr -MK3RofpaYxw1ztPIWb4cMWoWZHH1Pxh7ggTGSBpAhKXkiWw2Rxat8QF5aA7e962c -bLvVv8dqsPrD/RnVJHag89cbPTzjn7gY9elE8EM8ithV3oQkwHTr4avYlpDZsgNd -hUW3YgRwGo31tdzxoG04AcpV2t+07P8XMPr9hsfWs4rHohXPi38Hseu1Ji+dBoWQ -3+1w/HH3o55s+jy4Ruaz78AIrjbmAJq+6rA2mIcCgrhw3DnzuwQAKeBvSeqn9zfS -ZC812osMBVmkycwelpaIh64WZ0vWL3GvdXDctV2kXM+qVpDTLEny0LuiXxrwCKQL -Ev4HAwK9uQBcreDEEud7pfRb8EYP5lzO2ZA7RaIvje6EWAGBvJGMRT0QQE5SGqc7 -Fw5geigBdt+vVyRuNNhg3c2fdn/OBQaYu0J/8AiOogG8EaM8tCFlbGdhbWFsQGRz -YS5jb20gPGVsZ2FtYWxAZHNhLmNvbT6IkAQTEQgAOBYhBI+gnfiHQxB35/Dp0XAQ -aE/rsWC5BQJffzC7AhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4BAheAAAoJEHAQaE/r -sWC5A4EA/0GcJmyPtN+Klc7b9sVT3JgKTRnB/URxOJfYJofP0hZLAQCkqyMO+adV -JvbgDH0zaITQWZSSXPqpgMpCA6juTrDsd50CawRffzC7EAgAxFFFSAAEQzWTgKU5 -EBtpxxoPzHqcChawTHRxHxjcELXzmUBS5PzfA1HXSPnNqK/x3Ut5ycC3CsW41Fnt -Gm3706Wu9VFbFZVn55F9lPiplUo61n5pqMvOr1gmuQsdXiTa0t5FRa4TZ2VSiHFw -vdAVSPTUsT4ZxJ1rPyFYRtq1n3pQcvdZowd07r0JnzTMjLLMFYCKhwIowoOC4zqJ -iB8enjwOlpaqBATRm9xpVF7SJkroPF6/B1vdhj7E3c1aJyHlo0PYBAg756sSHWHg -UuLyUQ4TA0hcCVenn/L/aSY2LnbdZB1EBhlYjA7dTCgwIqsQhfQmPkjz6g64A7+Y -HbbrLwADBQgAk14QIEQ+J/VHetpQV/jt2pNsFK1kVK7mXK0spTExaC2yj2sXlHjL -Ie3bO5T/KqmIaBEB5db5fA5xK9cZt79qrQHDKsEqUetUeMUWLBx77zBsus3grIgy -bwDZKseRzQ715pwxquxQlScGoDIBKEh08HpwHkq140eIj3w+MAIfndaZaSCNaxaP -Snky7BQmJ7Wc7qrIwoQP6yrnUqyW2yNi81nJYUhxjChqaFSlwzLs/iNGryBKo0ic -BqVIRjikKHBlwBng6WyrltQo/Vt9GG8w+lqaAVXbJRlaBZJUR+2NKi/YhP3qQse3 -v8fi4kns0gh5LK+2C01RvdX4T49QSExuIf4HAwLJqYIGwadA2uem5v7/765ZtFWV -oL0iZ0ueTJDby4wTFDpLVzzDi/uVcB0ZRFrGOp7w6OYcNYTtV8n3xmli2Q5Trw0c -wZVzvg+ABKWiv7faBjMczIFF8y6WZKOIeAQYEQgAIBYhBI+gnfiHQxB35/Dp0XAQ -aE/rsWC5BQJffzC7AhsMAAoJEHAQaE/rsWC5ZmIA/jhS4r4lClbvjuPWt0Yqdn7R -fss2SPMYvMrrDh42aE0OAQD8xn4G6CN8UtW9xihXOY6FpxiJ/sMc2VaneeUd34oa -4g== -=XZm8 ------END PGP PRIVATE KEY BLOCK-----` - -// https://tests.sequoia-pgp.org/#Certificate_expiration -// P _ U p -const expiringPrimaryUIDKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- - -xsDNBF2lnPIBDAC5cL9PQoQLTMuhjbYvb4Ncuuo0bfmgPRFywX53jPhoFf4Zg6mv -/seOXpgecTdOcVttfzC8ycIKrt3aQTiwOG/ctaR4Bk/t6ayNFfdUNxHWk4WCKzdz -/56fW2O0F23qIRd8UUJp5IIlN4RDdRCtdhVQIAuzvp2oVy/LaS2kxQoKvph/5pQ/ -5whqsyroEWDJoSV0yOb25B/iwk/pLUFoyhDG9bj0kIzDxrEqW+7Ba8nocQlecMF3 -X5KMN5kp2zraLv9dlBBpWW43XktjcCZgMy20SouraVma8Je/ECwUWYUiAZxLIlMv -9CurEOtxUw6N3RdOtLmYZS9uEnn5y1UkF88o8Nku890uk6BrewFzJyLAx5wRZ4F0 -qV/yq36UWQ0JB/AUGhHVPdFf6pl6eaxBwT5GXvbBUibtf8YI2og5RsgTWtXfU7eb -SGXrl5ZMpbA6mbfhd0R8aPxWfmDWiIOhBufhMCvUHh1sApMKVZnvIff9/0Dca3wb -vLIwa3T4CyshfT0AEQEAAc0hQm9iIEJhYmJhZ2UgPGJvYkBvcGVucGdwLmV4YW1w -bGU+wsFcBBMBCgCQBYJhesp/BYkEWQPJBQsJCAcCCRD7/MgqAV5zMEcUAAAAAAAe -ACBzYWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmeEOQlNyTLFkc9I/elp+BpY -495V7KatqtDmsyDr+zDAdwYVCgkICwIEFgIDAQIXgAIbAwIeARYhBNGmbhojsYLJ -mA94jPv8yCoBXnMwAABSCQv/av8hKyynMtXVKFuWOGJw0mR8auDm84WdhMFRZg8t -yTJ1L88+Ny4WUAFeqo2j7DU2yPGrm5rmuvzlEedFYFeOWt+A4adz+oumgRd0nsgG -Lf3QYUWQhLWVlz+H7zubgKqSB2A2RqV65S7mTTVro42nb2Mng6rvGWiqeKG5nrXN -/01p1mIBQGR/KnZSqYLzA2Pw2PiJoSkXT26PDz/kiEMXpjKMR6sicV4bKVlEdUvm -pIImIPBHZq1EsKXEyWtWC41w/pc+FofGE+uSFs2aef1vvEHFkj3BHSK8gRcH3kfR -eFroTET8C2q9V1AOELWm+Ys6PzGzF72URK1MKXlThuL4t4LjvXWGNA78IKW+/RQH -DzK4U0jqSO0mL6qxqVS5Ij6jjL6OTrVEGdtDf5n0vI8tcUTBKtVqYAYk+t2YGT05 -ayxALtb7viVKo8f10WEcCuKshn0gdsEFMRZQzJ89uQIY3R3FbsdRCaE6OEaDgKMQ -UTFROyfhthgzRKbRxfcplMUCzsDNBF2lnPIBDADWML9cbGMrp12CtF9b2P6z9TTT -74S8iyBOzaSvdGDQY/sUtZXRg21HWamXnn9sSXvIDEINOQ6A9QxdxoqWdCHrOuW3 -ofneYXoG+zeKc4dC86wa1TR2q9vW+RMXSO4uImA+Uzula/6k1DogDf28qhCxMwG/ -i/m9g1c/0aApuDyKdQ1PXsHHNlgd/Dn6rrd5y2AObaifV7wIhEJnvqgFXDN2RXGj -LeCOHV4Q2WTYPg/S4k1nMXVDwZXrvIsA0YwIMgIT86Rafp1qKlgPNbiIlC1g9RY/ -iFaGN2b4Ir6GDohBQSfZW2+LXoPZuVE/wGlQ01rh827KVZW4lXvqsge+wtnWlszc -selGATyzqOK9LdHPdZGzROZYI2e8c+paLNDdVPL6vdRBUnkCaEkOtl1mr2JpQi5n -TU+gTX4IeInC7E+1a9UDF/Y85ybUz8XV8rUnR76UqVC7KidNepdHbZjjXCt8/Zo+ -Tec9JNbYNQB/e9ExmDntmlHEsSEQzFwzj8sxH48AEQEAAcLA9gQYAQoAIBYhBNGm -bhojsYLJmA94jPv8yCoBXnMwBQJdpZzyAhsMAAoJEPv8yCoBXnMw6f8L/26C34dk -jBffTzMj5Bdzm8MtF67OYneJ4TQMw7+41IL4rVcSKhIhk/3Ud5knaRtP2ef1+5F6 -6h9/RPQOJ5+tvBwhBAcUWSupKnUrdVaZQanYmtSxcVV2PL9+QEiNN3tzluhaWO// -rACxJ+K/ZXQlIzwQVTpNhfGzAaMVV9zpf3u0k14itcv6alKY8+rLZvO1wIIeRZLm -U0tZDD5HtWDvUV7rIFI1WuoLb+KZgbYn3OWjCPHVdTrdZ2CqnZbG3SXw6awH9bzR -LV9EXkbhIMez0deCVdeo+wFFklh8/5VK2b0vk/+wqMJxfpa1lHvJLobzOP9fvrsw -sr92MA2+k901WeISR7qEzcI0Fdg8AyFAExaEK6VyjP7SXGLwvfisw34OxuZr3qmx -1Sufu4toH3XrB7QJN8XyqqbsGxUCBqWif9RSK4xjzRTe56iPeiSJJOIciMP9i2ld -I+KgLycyeDvGoBj0HCLO3gVaBe4ubVrj5KjhX2PVNEJd3XZRzaXZE2aAMQ== -=AmgT ------END PGP PUBLIC KEY BLOCK-----` - -const rsa2048PrivateKey = `-----BEGIN PGP PRIVATE KEY BLOCK----- -Comment: gpg (GnuPG) 2.2.27 with libgcrypt 1.9.4 - -lQPGBGL07P0BCADL0etN8efyAXA6sL2WfQvHe5wEKYXPWeN2+jiqSppfeRZAOlzP -kZ3U+cloeJriplYvVJwI3ID2aw52Z/TRn8iKRP5eOUFrEgcgl06lazLtOndK7o7p -oBV5mLtHEirFHm6W61fNt10jzM0jx0PV6nseLhFB2J42F1cmU/aBgFo41wjLSZYr -owR+v+O9S5sUXblQF6sEDcY01sBEu09zrIgT49VFwQ1Cvdh9XZEOTQBfdiugoj5a -DS3fAqAka3r1VoQK4eR7/upnYSgSACGeaQ4pUelKku5rpm50gdWTY8ppq0k9e1eT -y2x0OQcW3hWE+j4os1ca0ZEADMdqr/99MOxrABEBAAH+BwMCJWxU4VOZOJ7/I6vX -FxdfBhIBEXlJ52FM3S/oYtXqLhkGyrtmZOeEazVvUtuCe3M3ScHI8xCthcmE8E0j -bi+ZEHPS2NiBZtgHFF27BLn7zZuTc+oD5WKduZdK3463egnyThTqIIMl25WZBuab -k5ycwYrWwBH0jfA4gwJ13ai4pufKC2RM8qIu6YAVPglYBKFLKGvvJHa5vI+LuA0E -K+k35hIic7yVUcQneNnAF2598X5yWiieYnOZpmHlRw1zfbMwOJr3ZNj2v94u7b+L -sTa/1Uv9887Vb6sJp0c2Sh4cwEccoPYkvMqFn3ZrJUr3UdDu1K2vWohPtswzhrYV -+RdPZE5RLoCQufKvlPezk0Pzhzb3bBU7XjUbdGY1nH/EyQeBNp+Gw6qldKvzcBaB -cyOK1c6hPSszpJX93m5UxCN55IeifmcNjmbDh8vGCCdajy6d56qV2n4F3k7vt1J1 -0UlxIGhqijJoaTCX66xjLMC6VXkSz6aHQ35rnXosm/cqPcQshsZTdlfSyWkorfdr -4Hj8viBER26mjYurTMLBKDtUN724ZrR0Ev5jorX9uoKlgl87bDZHty2Ku2S+vR68 -VAvnj6Fi1BYNclnDoqxdRB2z5T9JbWE52HuG83/QsplhEqXxESDxriTyTHMbNxEe -88soVCDh4tgflZFa2ucUr6gEKJKij7jgahARnyaXfPZlQBUAS1YUeILYmN+VR+M/ -sHENpwDWc7TInn8VN638nJV+ScZGMih3AwWZTIoiLju3MMt1K0YZ3NuiqwGH4Jwg -/BbEdTWeCci9y3NEQHQ3uZZ5p6j2CwFVlK11idemCMvAiTVxF+gKdaLMkeCwKxru -J3YzhKEo+iDVYbPYBYizx/EHBn2U5kITQ5SBXzjTaaFMNZJEf9JYsL1ybPB6HOFY -VNVB2KT8CGVwtCJHb2xhbmcgR29waGVyIDxnb2xhbmdAZXhhbXBsZS5vcmc+iQFO -BBMBCgA4FiEEC6K7U7f4qesybTnqSkra7gHusm0FAmL07P0CGwMFCwkIBwIGFQoJ -CAsCBBYCAwECHgECF4AACgkQSkra7gHusm1MvwgAxpClWkeSqIhMQfbiuz0+lOkE -89y1DCFw8bHjZoUf4/4K8hFA3dGkk+q72XFgiyaCpfXxMt6Gi+dN47t+tTv9NIqC -sukbaoJBmJDhN6+djmJOgOYy+FWsW2LAk2LOwKYulpnBZdcA5rlMAhBg7gevQpF+ -ruSU69P7UUaFJl/DC7hDmaIcj+4cjBE/HO26SnVQjoTfjZT82rDh1Wsuf8LnkJUk -b3wezBLpXKjDvdHikdv4gdlR4AputVM38aZntYYglh/EASo5TneyZ7ZscdLNRdcF -r5O2fKqrOJLOdaoYRFZZWOvP5GtEVFDU7WGivOSVfiszBE0wZR3dgZRJipHCXJ0D -xgRi9Oz9AQgAtMJcJqLLVANJHl90tWuoizDkm+Imcwq2ubQAjpclnNrODnDK+7o4 -pBsWmXbZSdkC4gY+LhOQA6bPDD0JEHM58DOnrm49BddxXAyK0HPsk4sGGt2SS86B -OawWNdfJVyqw4bAiHWDmQg4PcjBbt3ocOIxAR6I5kBSiQVxuGQs9T+Zvg3G1r3Or -fS6DzlgY3HFUML5YsGH4lOxNSOoKAP68GIH/WNdUZ+feiRg9knIib6I3Hgtf5eO8 -JRH7aWE/TD7eNu36bLLjT5TZPq5r6xaD2plbtPOyXbNPWs9qI1yG+VnErfaLY0w8 -Qo0aqzbgID+CTZVomXSOpOcQseaFKw8ZfQARAQAB/gcDArha6+/+d4OY/w9N32K9 -hFNYt4LufTETMQ+k/sBeaMuAVzmT47DlAXzkrZhGW4dZOtXMu1rXaUwHlqkhEyzL -L4MYEWVXfD+LbZNEK3MEFss6RK+UAMeT/PTV9aA8cXQVPcSJYzfBXHQ1U1hnOgrO -apn92MN8RmkhX8wJLyeWTMMuP4lXByJMmmGo8WvifeRD2kFY4y0WVBDAXJAV4Ljf -Di/bBiwoc5a+gxHuZT2W9ZSxBQJNXdt4Un2IlyZuo58s5MLx2N0EaNJ8PwRUE6fM -RZYO8aZCEPUtINE4njbvsWOMCtrblsMPwZ1B0SiIaWmLaNyGdCNKea+fCIW7kasC -JYMhnLumpUTXg5HNexkCsl7ABWj0PYBflOE61h8EjWpnQ7JBBVKS2ua4lMjwHRX7 -5o5yxym9k5UZNFdGoXVL7xpizCcdGawxTJvwhs3vBqu1ZWYCegOAZWDrOkCyhUpq -8uKMROZFbn+FwE+7tjt+v2ed62FVEvD6g4V3ThCA6mQqeOARfJWN8GZY8BDm8lht -crOXriUkrx+FlrgGtm2CkwjW5/9Xd7AhFpHnQdFeozOHyq1asNSgJF9sNi9Lz94W -skQSVRi0IExxSXYGI3Y0nnAZUe2BAQflYPJdEveSr3sKlUqXiETTA1VXsTPK3kOC -92CbLzj/Hz199jZvywwyu53I+GKMpF42rMq7zxr2oa61YWY4YE/GDezwwys/wLx/ -QpCW4X3ppI7wJjCSSqEV0baYZSSli1ayheS6dxi8QnSpX1Bmpz6gU7m/M9Sns+hl -J7ZvgpjCAiV7KJTjtclr5/S02zP78LTVkoTWoz/6MOTROwaP63VBUXX8pbJhf/vu -DLmNnDk8joMJxoDXWeNU0EnNl4hP7Z/jExRBOEO4oAnUf/Sf6gCWQhL5qcajtg6w -tGv7vx3f2IkBNgQYAQoAIBYhBAuiu1O3+KnrMm056kpK2u4B7rJtBQJi9Oz9AhsM -AAoJEEpK2u4B7rJt6lgIAMBWqP4BCOGnQXBbgJ0+ACVghpkFUXZTb/tXJc8UUvTM -8uov6k/RsqDGZrvhhufD7Wwt7j9v7dD7VPp7bPyjVWyimglQzWguTUUqLDGlstYH -5uYv1pzma0ZsAGNqFeGlTLsKOSGKFMH4rB2KfN2n51L8POvtp1y7GKZQbWIWneaB -cZr3BINU5GMvYYU7pAYcoR+mJPdJx5Up3Ocn+bn8Tu1sy9C/ArtCQucazGnoE9u1 -HhNLrh0CdzzX7TNH6TQ8LwPOvq0K5l/WqbN9lE0WBBhMv2HydxhluO8AhU+A5GqC -C+wET7nVDnhoOm/fstIeb7/LN7OYejKPeHdFBJEL9GA= -=u442 ------END PGP PRIVATE KEY BLOCK-----` - -const curve25519PrivateKey = `-----BEGIN PGP PRIVATE KEY BLOCK----- -Comment: gpg (GnuPG) 2.2.27 with libgcrypt 1.9.4 - -lFgEYvTtQBYJKwYBBAHaRw8BAQdAxsNXLbrk5xOjpO24VhOMvQ0/F+JcyIkckMDH -X3FIGxcAAQDFOlunZWYuPsCx5JLp78vKqUTfgef9TGG4oD6I/Sa0zBMstCJHb2xh -bmcgR29waGVyIDxnb2xhbmdAZXhhbXBsZS5vcmc+iJAEExYIADgWIQSFQHEOazmo -h1ldII4MvfnLQ4JBNwUCYvTtQAIbAwULCQgHAgYVCgkICwIEFgIDAQIeAQIXgAAK -CRAMvfnLQ4JBN5yeAQCKdry8B5ScCPrev2+UByMCss7Sdu5RhomCFsHdNPLcKAEA -8ugei+1owHsV+3cGwWWzKk6sLa8ZN87i3SKuOGp9DQycXQRi9O1AEgorBgEEAZdV -AQUBAQdA5CubPp8l7lrVQ25h7Hx5XN2C8xanRnnpcjzEooCaEA0DAQgHAAD/Rpc+ -sOZUXrFk9HOWB1XU41LoWbDBoG8sP8RWAVYwD5AQRYh4BBgWCAAgFiEEhUBxDms5 -qIdZXSCODL35y0OCQTcFAmL07UACGwwACgkQDL35y0OCQTcvdwEA7lb5g/YisrEf -iq660uwMGoepLUfvtqKzuQ6heYe83y0BAN65Ffg5HYOJzUEi0kZQRf7OhdtuL2kJ -SRXn8DmCTfEB -=cELM ------END PGP PRIVATE KEY BLOCK-----` - -const curve448PrivateKey = `-----BEGIN PGP PRIVATE KEY BLOCK----- -Comment: C1DB 65D5 80D7 B922 7254 4B1E A699 9895 FABA CE52 - -xYUEYV2UmRYDK2VxAc9AFyxgh5xnSbyt50TWl558mw9xdMN+/UBLr5+UMP8IsrvV -MdXuTIE8CyaUQKSotHtH2RkYEXj5nsMAAAHPQIbTMSzjIWug8UFECzAex5FHgAgH -gYF3RK+TS8D24wX8kOu2C/NoVxwGY+p+i0JHaB+7yljriSKAGxs6wsBEBB8WCgCD -BYJhXZSZBYkFpI+9AwsJBwkQppmYlfq6zlJHFAAAAAAAHgAgc2FsdEBub3RhdGlv -bnMuc2VxdW9pYS1wZ3Aub3Jn5wSpIutJ5HncJWk4ruUV8GzQF390rR5+qWEAnAoY -akcDFQoIApsBAh4BFiEEwdtl1YDXuSJyVEseppmYlfq6zlIAALzdA5dA/fsgYg/J -qaQriYKaPUkyHL7EB3BXhV2d1h/gk+qJLvXQuU2WEJ/XSs3GrsBRiiZwvPH4o+7b -mleAxjy5wpS523vqrrBR2YZ5FwIku7WS4litSdn4AtVam/TlLdMNIf41CtFeZKBe -c5R5VNdQy8y7qy8AAADNEUN1cnZlNDQ4IE9wdGlvbiA4wsBHBBMWCgCGBYJhXZSZ -BYkFpI+9AwsJBwkQppmYlfq6zlJHFAAAAAAAHgAgc2FsdEBub3RhdGlvbnMuc2Vx -dW9pYS1wZ3Aub3JnD55UsYMzE6OACP+mgw5zvT+BBgol8/uFQjHg4krjUCMDFQoI -ApkBApsBAh4BFiEEwdtl1YDXuSJyVEseppmYlfq6zlIAAPQJA5dA0Xqwzn/0uwCq -RlsOVCB3f5NOj1exKnlBvRw0xT1VBee1yxvlUt5eIAoCxWoRlWBJob3TTkhm9AEA -8dyhwPmyGfWHzPw5NFG3xsXrZdNXNvit9WMVAPcmsyR7teXuDlJItxRAdJJc/qfJ -YVbBFoaNrhYAAADHhQRhXZSZFgMrZXEBz0BL7THZ9MnCLfSPJ1FMLim9eGkQ3Bfn -M3he5rOwO3t14QI1LjI96OjkeJipMgcFAmEP1Bq/ZHGO7oAAAc9AFnE8iNBaT3OU -EFtxkmWHXtdaYMmGGRdopw9JPXr/UxuunDln5o9dxPxf7q7z26zXrZen+qed/Isa -HsDCwSwEGBYKAWsFgmFdlJkFiQWkj70JEKaZmJX6us5SRxQAAAAAAB4AIHNhbHRA -bm90YXRpb25zLnNlcXVvaWEtcGdwLm9yZxREUizdTcepBzgSMOv2VWQCWbl++3CZ -EbgAWDryvSsyApsCwDGgBBkWCgBvBYJhXZSZCRBKo3SL4S5djkcUAAAAAAAeACBz -YWx0QG5vdGF0aW9ucy5zZXF1b2lhLXBncC5vcmemoGTDjmNQiIzw6HOEddvS0OB7 -UZ/P07jM/EVmnYxTlBYhBAxsnkGpx1UCiH6gUUqjdIvhLl2OAAALYQOXQAMB1oKq -OWxSFmvmgCKNcbAAyA3piF5ERIqs4z07oJvqDYrOWt75UsEIH/04gU/vHc4EmfG2 -JDLJgOLlyTUPkL/08f0ydGZPofFQBhn8HkuFFjnNtJ5oz3GIP4cdWMQFaUw0uvjb -PM9Tm3ptENGd6Ts1AAAAFiEEwdtl1YDXuSJyVEseppmYlfq6zlIAAGpTA5dATR6i -U2GrpUcQgpG+JqfAsGmF4yAOhgFxc1UfidFk3nTup3fLgjipkYY170WLRNbyKkVO -Sodx93GAs58rizO1acDAWiLq3cyEPBFXbyFThbcNPcLl+/77Uk/mgkYrPQFAQWdK -1kSRm4SizDBK37K8ChAAAADHhwRhXZSZEgMrZW8Bx0DMhzvhQo+OsXeqQ6QVw4sF -CaexHh6rLohh7TzL3hQSjoJ27fV6JBkIWdn0LfrMlJIDbSv2SLdlgQMBCgkAAcdA -MO7Dc1myF6Co1fAH+EuP+OxhxP/7V6ljuSCZENDfA49tQkzTta+PniG+pOVB2LHb -huyaKBkqiaogo8LAOQQYFgoAeAWCYV2UmQWJBaSPvQkQppmYlfq6zlJHFAAAAAAA -HgAgc2FsdEBub3RhdGlvbnMuc2VxdW9pYS1wZ3Aub3JnEjBMQAmc/2u45u5FQGmB -QAytjSG2LM3JQN+PPVl5vEkCmwwWIQTB22XVgNe5InJUSx6mmZiV+rrOUgAASdYD -l0DXEHQ9ykNP2rZP35ET1dmiFagFtTj/hLQcWlg16LqvJNGqOgYXuqTerbiOOt02 -XLCBln+wdewpU4ChEffMUDRBfqfQco/YsMqWV7bHJHAO0eC/DMKCjyU90xdH7R/d -QgqsfguR1PqPuJxpXV4bSr6CGAAAAA== -=MSvh ------END PGP PRIVATE KEY BLOCK-----` - -const keyWithNotation = `-----BEGIN PGP PRIVATE KEY BLOCK----- - -xVgEY9gIshYJKwYBBAHaRw8BAQdAF25fSM8OpFlXZhop4Qpqo5ywGZ4jgWlR -ppjhIKDthREAAQC+LFpzFcMJYcjxGKzBGHN0Px2jU4d04YSRnFAik+lVVQ6u -zRdUZXN0IDx0ZXN0QGV4YW1wbGUuY29tPsLACgQQFgoAfAUCY9gIsgQLCQcI -CRD/utJOCym8pR0UgAAAAAAQAAR0ZXh0QGV4YW1wbGUuY29tdGVzdB8UAAAA -AAASAARiaW5hcnlAZXhhbXBsZS5jb20AAQIDAxUICgQWAAIBAhkBAhsDAh4B -FiEEEMCQTUVGKgCX5rDQ/7rSTgspvKUAAPl5AP9Npz90LxzrB97Qr2DrGwfG -wuYn4FSYwtuPfZHHeoIabwD/QEbvpQJ/NBb9EAZuow4Rirlt1yv19mmnF+j5 -8yUzhQjHXQRj2AiyEgorBgEEAZdVAQUBAQdARXAo30DmKcyUg6co7OUm0RNT -z9iqFbDBzA8A47JEt1MDAQgHAAD/XKK3lBm0SqMR558HLWdBrNG6NqKuqb5X -joCML987ZNgRD8J4BBgWCAAqBQJj2AiyCRD/utJOCym8pQIbDBYhBBDAkE1F -RioAl+aw0P+60k4LKbylAADRxgEAg7UfBDiDPp5LHcW9D+SgFHk6+GyEU4ev -VppQxdtxPvAA/34snHBX7Twnip1nMt7P4e2hDiw/hwQ7oqioOvc6jMkP -=Z8YJ ------END PGP PRIVATE KEY BLOCK----- -` diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/aead_config.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/aead_config.go deleted file mode 100644 index fec41a0e..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/aead_config.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (C) 2019 ProtonTech AG - -package packet - -import "math/bits" - -// CipherSuite contains a combination of Cipher and Mode -type CipherSuite struct { - // The cipher function - Cipher CipherFunction - // The AEAD mode of operation. - Mode AEADMode -} - -// AEADConfig collects a number of AEAD parameters along with sensible defaults. -// A nil AEADConfig is valid and results in all default values. -type AEADConfig struct { - // The AEAD mode of operation. - DefaultMode AEADMode - // Amount of octets in each chunk of data - ChunkSize uint64 -} - -// Mode returns the AEAD mode of operation. -func (conf *AEADConfig) Mode() AEADMode { - // If no preference is specified, OCB is used (which is mandatory to implement). - if conf == nil || conf.DefaultMode == 0 { - return AEADModeOCB - } - - mode := conf.DefaultMode - if mode != AEADModeEAX && mode != AEADModeOCB && mode != AEADModeGCM { - panic("AEAD mode unsupported") - } - return mode -} - -// ChunkSizeByte returns the byte indicating the chunk size. The effective -// chunk size is computed with the formula uint64(1) << (chunkSizeByte + 6) -// limit to 16 = 4 MiB -// https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-5.13.2 -func (conf *AEADConfig) ChunkSizeByte() byte { - if conf == nil || conf.ChunkSize == 0 { - return 12 // 1 << (12 + 6) == 262144 bytes - } - - chunkSize := conf.ChunkSize - exponent := bits.Len64(chunkSize) - 1 - switch { - case exponent < 6: - exponent = 6 - case exponent > 16: - exponent = 16 - } - - return byte(exponent - 6) -} - -// decodeAEADChunkSize returns the effective chunk size. In 32-bit systems, the -// maximum returned value is 1 << 30. -func decodeAEADChunkSize(c byte) int { - size := uint64(1 << (c + 6)) - if size != uint64(int(size)) { - return 1 << 30 - } - return int(size) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/aead_crypter.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/aead_crypter.go deleted file mode 100644 index a82b040b..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/aead_crypter.go +++ /dev/null @@ -1,265 +0,0 @@ -// Copyright (C) 2019 ProtonTech AG - -package packet - -import ( - "bytes" - "crypto/cipher" - "encoding/binary" - "io" - - "github.com/ProtonMail/go-crypto/openpgp/errors" -) - -// aeadCrypter is an AEAD opener/sealer, its configuration, and data for en/decryption. -type aeadCrypter struct { - aead cipher.AEAD - chunkSize int - initialNonce []byte - associatedData []byte // Chunk-independent associated data - chunkIndex []byte // Chunk counter - packetTag packetType - bytesProcessed int // Amount of plaintext bytes encrypted/decrypted - buffer bytes.Buffer // Buffered bytes across chunks -} - -// computeNonce takes the incremental index and computes an eXclusive OR with -// the least significant 8 bytes of the receivers' initial nonce (see sec. -// 5.16.1 and 5.16.2). It returns the resulting nonce. -func (wo *aeadCrypter) computeNextNonce() (nonce []byte) { - if wo.packetTag == packetTypeSymmetricallyEncryptedIntegrityProtected { - return append(wo.initialNonce, wo.chunkIndex...) - } - - nonce = make([]byte, len(wo.initialNonce)) - copy(nonce, wo.initialNonce) - offset := len(wo.initialNonce) - 8 - for i := 0; i < 8; i++ { - nonce[i+offset] ^= wo.chunkIndex[i] - } - return -} - -// incrementIndex performs an integer increment by 1 of the integer represented by the -// slice, modifying it accordingly. -func (wo *aeadCrypter) incrementIndex() error { - index := wo.chunkIndex - if len(index) == 0 { - return errors.AEADError("Index has length 0") - } - for i := len(index) - 1; i >= 0; i-- { - if index[i] < 255 { - index[i]++ - return nil - } - index[i] = 0 - } - return errors.AEADError("cannot further increment index") -} - -// aeadDecrypter reads and decrypts bytes. It buffers extra decrypted bytes when -// necessary, similar to aeadEncrypter. -type aeadDecrypter struct { - aeadCrypter // Embedded ciphertext opener - reader io.Reader // 'reader' is a partialLengthReader - peekedBytes []byte // Used to detect last chunk - eof bool -} - -// Read decrypts bytes and reads them into dst. It decrypts when necessary and -// buffers extra decrypted bytes. It returns the number of bytes copied into dst -// and an error. -func (ar *aeadDecrypter) Read(dst []byte) (n int, err error) { - // Return buffered plaintext bytes from previous calls - if ar.buffer.Len() > 0 { - return ar.buffer.Read(dst) - } - - // Return EOF if we've previously validated the final tag - if ar.eof { - return 0, io.EOF - } - - // Read a chunk - tagLen := ar.aead.Overhead() - cipherChunkBuf := new(bytes.Buffer) - _, errRead := io.CopyN(cipherChunkBuf, ar.reader, int64(ar.chunkSize + tagLen)) - cipherChunk := cipherChunkBuf.Bytes() - if errRead != nil && errRead != io.EOF { - return 0, errRead - } - decrypted, errChunk := ar.openChunk(cipherChunk) - if errChunk != nil { - return 0, errChunk - } - - // Return decrypted bytes, buffering if necessary - if len(dst) < len(decrypted) { - n = copy(dst, decrypted[:len(dst)]) - ar.buffer.Write(decrypted[len(dst):]) - } else { - n = copy(dst, decrypted) - } - - // Check final authentication tag - if errRead == io.EOF { - errChunk := ar.validateFinalTag(ar.peekedBytes) - if errChunk != nil { - return n, errChunk - } - ar.eof = true // Mark EOF for when we've returned all buffered data - } - return -} - -// Close is noOp. The final authentication tag of the stream was already -// checked in the last Read call. In the future, this function could be used to -// wipe the reader and peeked, decrypted bytes, if necessary. -func (ar *aeadDecrypter) Close() (err error) { - return nil -} - -// openChunk decrypts and checks integrity of an encrypted chunk, returning -// the underlying plaintext and an error. It accesses peeked bytes from next -// chunk, to identify the last chunk and decrypt/validate accordingly. -func (ar *aeadDecrypter) openChunk(data []byte) ([]byte, error) { - tagLen := ar.aead.Overhead() - // Restore carried bytes from last call - chunkExtra := append(ar.peekedBytes, data...) - // 'chunk' contains encrypted bytes, followed by an authentication tag. - chunk := chunkExtra[:len(chunkExtra)-tagLen] - ar.peekedBytes = chunkExtra[len(chunkExtra)-tagLen:] - - adata := ar.associatedData - if ar.aeadCrypter.packetTag == packetTypeAEADEncrypted { - adata = append(ar.associatedData, ar.chunkIndex...) - } - - nonce := ar.computeNextNonce() - plainChunk, err := ar.aead.Open(nil, nonce, chunk, adata) - if err != nil { - return nil, err - } - ar.bytesProcessed += len(plainChunk) - if err = ar.aeadCrypter.incrementIndex(); err != nil { - return nil, err - } - return plainChunk, nil -} - -// Checks the summary tag. It takes into account the total decrypted bytes into -// the associated data. It returns an error, or nil if the tag is valid. -func (ar *aeadDecrypter) validateFinalTag(tag []byte) error { - // Associated: tag, version, cipher, aead, chunk size, ... - amountBytes := make([]byte, 8) - binary.BigEndian.PutUint64(amountBytes, uint64(ar.bytesProcessed)) - - adata := ar.associatedData - if ar.aeadCrypter.packetTag == packetTypeAEADEncrypted { - // ... index ... - adata = append(ar.associatedData, ar.chunkIndex...) - } - - // ... and total number of encrypted octets - adata = append(adata, amountBytes...) - nonce := ar.computeNextNonce() - _, err := ar.aead.Open(nil, nonce, tag, adata) - if err != nil { - return err - } - return nil -} - -// aeadEncrypter encrypts and writes bytes. It encrypts when necessary according -// to the AEAD block size, and buffers the extra encrypted bytes for next write. -type aeadEncrypter struct { - aeadCrypter // Embedded plaintext sealer - writer io.WriteCloser // 'writer' is a partialLengthWriter -} - - -// Write encrypts and writes bytes. It encrypts when necessary and buffers extra -// plaintext bytes for next call. When the stream is finished, Close() MUST be -// called to append the final tag. -func (aw *aeadEncrypter) Write(plaintextBytes []byte) (n int, err error) { - // Append plaintextBytes to existing buffered bytes - n, err = aw.buffer.Write(plaintextBytes) - if err != nil { - return n, err - } - // Encrypt and write chunks - for aw.buffer.Len() >= aw.chunkSize { - plainChunk := aw.buffer.Next(aw.chunkSize) - encryptedChunk, err := aw.sealChunk(plainChunk) - if err != nil { - return n, err - } - _, err = aw.writer.Write(encryptedChunk) - if err != nil { - return n, err - } - } - return -} - -// Close encrypts and writes the remaining buffered plaintext if any, appends -// the final authentication tag, and closes the embedded writer. This function -// MUST be called at the end of a stream. -func (aw *aeadEncrypter) Close() (err error) { - // Encrypt and write a chunk if there's buffered data left, or if we haven't - // written any chunks yet. - if aw.buffer.Len() > 0 || aw.bytesProcessed == 0 { - plainChunk := aw.buffer.Bytes() - lastEncryptedChunk, err := aw.sealChunk(plainChunk) - if err != nil { - return err - } - _, err = aw.writer.Write(lastEncryptedChunk) - if err != nil { - return err - } - } - // Compute final tag (associated data: packet tag, version, cipher, aead, - // chunk size... - adata := aw.associatedData - - if aw.aeadCrypter.packetTag == packetTypeAEADEncrypted { - // ... index ... - adata = append(aw.associatedData, aw.chunkIndex...) - } - - // ... and total number of encrypted octets - amountBytes := make([]byte, 8) - binary.BigEndian.PutUint64(amountBytes, uint64(aw.bytesProcessed)) - adata = append(adata, amountBytes...) - - nonce := aw.computeNextNonce() - finalTag := aw.aead.Seal(nil, nonce, nil, adata) - _, err = aw.writer.Write(finalTag) - if err != nil { - return err - } - return aw.writer.Close() -} - -// sealChunk Encrypts and authenticates the given chunk. -func (aw *aeadEncrypter) sealChunk(data []byte) ([]byte, error) { - if len(data) > aw.chunkSize { - return nil, errors.AEADError("chunk exceeds maximum length") - } - if aw.associatedData == nil { - return nil, errors.AEADError("can't seal without headers") - } - adata := aw.associatedData - if aw.aeadCrypter.packetTag == packetTypeAEADEncrypted { - adata = append(aw.associatedData, aw.chunkIndex...) - } - - nonce := aw.computeNextNonce() - encrypted := aw.aead.Seal(nil, nonce, data, adata) - aw.bytesProcessed += len(data) - if err := aw.aeadCrypter.incrementIndex(); err != nil { - return nil, err - } - return encrypted, nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/aead_encrypted.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/aead_encrypted.go deleted file mode 100644 index 98bd876b..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/aead_encrypted.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (C) 2019 ProtonTech AG - -package packet - -import ( - "io" - - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm" -) - -// AEADEncrypted represents an AEAD Encrypted Packet. -// See https://www.ietf.org/archive/id/draft-koch-openpgp-2015-rfc4880bis-00.html#name-aead-encrypted-data-packet-t -type AEADEncrypted struct { - cipher CipherFunction - mode AEADMode - chunkSizeByte byte - Contents io.Reader // Encrypted chunks and tags - initialNonce []byte // Referred to as IV in RFC4880-bis -} - -// Only currently defined version -const aeadEncryptedVersion = 1 - -func (ae *AEADEncrypted) parse(buf io.Reader) error { - headerData := make([]byte, 4) - if n, err := io.ReadFull(buf, headerData); n < 4 { - return errors.AEADError("could not read aead header:" + err.Error()) - } - // Read initial nonce - mode := AEADMode(headerData[2]) - nonceLen := mode.IvLength() - - // This packet supports only EAX and OCB - // https://www.ietf.org/archive/id/draft-koch-openpgp-2015-rfc4880bis-00.html#name-aead-encrypted-data-packet-t - if nonceLen == 0 || mode > AEADModeOCB { - return errors.AEADError("unknown mode") - } - - initialNonce := make([]byte, nonceLen) - if n, err := io.ReadFull(buf, initialNonce); n < nonceLen { - return errors.AEADError("could not read aead nonce:" + err.Error()) - } - ae.Contents = buf - ae.initialNonce = initialNonce - c := headerData[1] - if _, ok := algorithm.CipherById[c]; !ok { - return errors.UnsupportedError("unknown cipher: " + string(c)) - } - ae.cipher = CipherFunction(c) - ae.mode = mode - ae.chunkSizeByte = headerData[3] - return nil -} - -// Decrypt returns a io.ReadCloser from which decrypted bytes can be read, or -// an error. -func (ae *AEADEncrypted) Decrypt(ciph CipherFunction, key []byte) (io.ReadCloser, error) { - return ae.decrypt(key) -} - -// decrypt prepares an aeadCrypter and returns a ReadCloser from which -// decrypted bytes can be read (see aeadDecrypter.Read()). -func (ae *AEADEncrypted) decrypt(key []byte) (io.ReadCloser, error) { - blockCipher := ae.cipher.new(key) - aead := ae.mode.new(blockCipher) - // Carry the first tagLen bytes - tagLen := ae.mode.TagLength() - peekedBytes := make([]byte, tagLen) - n, err := io.ReadFull(ae.Contents, peekedBytes) - if n < tagLen || (err != nil && err != io.EOF) { - return nil, errors.AEADError("Not enough data to decrypt:" + err.Error()) - } - chunkSize := decodeAEADChunkSize(ae.chunkSizeByte) - return &aeadDecrypter{ - aeadCrypter: aeadCrypter{ - aead: aead, - chunkSize: chunkSize, - initialNonce: ae.initialNonce, - associatedData: ae.associatedData(), - chunkIndex: make([]byte, 8), - packetTag: packetTypeAEADEncrypted, - }, - reader: ae.Contents, - peekedBytes: peekedBytes}, nil -} - -// associatedData for chunks: tag, version, cipher, mode, chunk size byte -func (ae *AEADEncrypted) associatedData() []byte { - return []byte{ - 0xD4, - aeadEncryptedVersion, - byte(ae.cipher), - byte(ae.mode), - ae.chunkSizeByte} -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/compressed.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/compressed.go deleted file mode 100644 index 2f5cad71..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/compressed.go +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "compress/bzip2" - "compress/flate" - "compress/zlib" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "io" - "strconv" -) - -// Compressed represents a compressed OpenPGP packet. The decompressed contents -// will contain more OpenPGP packets. See RFC 4880, section 5.6. -type Compressed struct { - Body io.Reader -} - -const ( - NoCompression = flate.NoCompression - BestSpeed = flate.BestSpeed - BestCompression = flate.BestCompression - DefaultCompression = flate.DefaultCompression -) - -// CompressionConfig contains compressor configuration settings. -type CompressionConfig struct { - // Level is the compression level to use. It must be set to - // between -1 and 9, with -1 causing the compressor to use the - // default compression level, 0 causing the compressor to use - // no compression and 1 to 9 representing increasing (better, - // slower) compression levels. If Level is less than -1 or - // more then 9, a non-nil error will be returned during - // encryption. See the constants above for convenient common - // settings for Level. - Level int -} - -func (c *Compressed) parse(r io.Reader) error { - var buf [1]byte - _, err := readFull(r, buf[:]) - if err != nil { - return err - } - - switch buf[0] { - case 0: - c.Body = r - case 1: - c.Body = flate.NewReader(r) - case 2: - c.Body, err = zlib.NewReader(r) - case 3: - c.Body = bzip2.NewReader(r) - default: - err = errors.UnsupportedError("unknown compression algorithm: " + strconv.Itoa(int(buf[0]))) - } - - return err -} - -// compressedWriterCloser represents the serialized compression stream -// header and the compressor. Its Close() method ensures that both the -// compressor and serialized stream header are closed. Its Write() -// method writes to the compressor. -type compressedWriteCloser struct { - sh io.Closer // Stream Header - c io.WriteCloser // Compressor -} - -func (cwc compressedWriteCloser) Write(p []byte) (int, error) { - return cwc.c.Write(p) -} - -func (cwc compressedWriteCloser) Close() (err error) { - err = cwc.c.Close() - if err != nil { - return err - } - - return cwc.sh.Close() -} - -// SerializeCompressed serializes a compressed data packet to w and -// returns a WriteCloser to which the literal data packets themselves -// can be written and which MUST be closed on completion. If cc is -// nil, sensible defaults will be used to configure the compression -// algorithm. -func SerializeCompressed(w io.WriteCloser, algo CompressionAlgo, cc *CompressionConfig) (literaldata io.WriteCloser, err error) { - compressed, err := serializeStreamHeader(w, packetTypeCompressed) - if err != nil { - return - } - - _, err = compressed.Write([]byte{uint8(algo)}) - if err != nil { - return - } - - level := DefaultCompression - if cc != nil { - level = cc.Level - } - - var compressor io.WriteCloser - switch algo { - case CompressionZIP: - compressor, err = flate.NewWriter(compressed, level) - case CompressionZLIB: - compressor, err = zlib.NewWriterLevel(compressed, level) - default: - s := strconv.Itoa(int(algo)) - err = errors.UnsupportedError("Unsupported compression algorithm: " + s) - } - if err != nil { - return - } - - literaldata = compressedWriteCloser{compressed, compressor} - - return -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/config.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/config.go deleted file mode 100644 index 4e2b27d1..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/config.go +++ /dev/null @@ -1,215 +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 packet - -import ( - "crypto" - "crypto/rand" - "io" - "math/big" - "time" -) - -// Config collects a number of parameters along with sensible defaults. -// A nil *Config is valid and results in all default values. -type Config struct { - // Rand provides the source of entropy. - // If nil, the crypto/rand Reader is used. - Rand io.Reader - // DefaultHash is the default hash function to be used. - // If zero, SHA-256 is used. - DefaultHash crypto.Hash - // DefaultCipher is the cipher to be used. - // If zero, AES-128 is used. - DefaultCipher CipherFunction - // Time returns the current time as the number of seconds since the - // epoch. If Time is nil, time.Now is used. - Time func() time.Time - // DefaultCompressionAlgo is the compression algorithm to be - // applied to the plaintext before encryption. If zero, no - // compression is done. - DefaultCompressionAlgo CompressionAlgo - // CompressionConfig configures the compression settings. - CompressionConfig *CompressionConfig - // S2KCount is only used for symmetric encryption. It - // determines the strength of the passphrase stretching when - // the said passphrase is hashed to produce a key. S2KCount - // should be between 1024 and 65011712, inclusive. If Config - // is nil or S2KCount is 0, the value 65536 used. Not all - // values in the above range can be represented. S2KCount will - // be rounded up to the next representable value if it cannot - // be encoded exactly. When set, it is strongly encrouraged to - // use a value that is at least 65536. See RFC 4880 Section - // 3.7.1.3. - S2KCount int - // RSABits is the number of bits in new RSA keys made with NewEntity. - // If zero, then 2048 bit keys are created. - RSABits int - // The public key algorithm to use - will always create a signing primary - // key and encryption subkey. - Algorithm PublicKeyAlgorithm - // Some known primes that are optionally prepopulated by the caller - RSAPrimes []*big.Int - // Curve configures the desired packet.Curve if the Algorithm is PubKeyAlgoECDSA, - // PubKeyAlgoEdDSA, or PubKeyAlgoECDH. If empty Curve25519 is used. - Curve Curve - // AEADConfig configures the use of the new AEAD Encrypted Data Packet, - // defined in the draft of the next version of the OpenPGP specification. - // If a non-nil AEADConfig is passed, usage of this packet is enabled. By - // default, it is disabled. See the documentation of AEADConfig for more - // configuration options related to AEAD. - // **Note: using this option may break compatibility with other OpenPGP - // implementations, as well as future versions of this library.** - AEADConfig *AEADConfig - // V5Keys configures version 5 key generation. If false, this package still - // supports version 5 keys, but produces version 4 keys. - V5Keys bool - // "The validity period of the key. This is the number of seconds after - // the key creation time that the key expires. If this is not present - // or has a value of zero, the key never expires. This is found only on - // a self-signature."" - // https://tools.ietf.org/html/rfc4880#section-5.2.3.6 - KeyLifetimeSecs uint32 - // "The validity period of the signature. This is the number of seconds - // after the signature creation time that the signature expires. If - // this is not present or has a value of zero, it never expires." - // https://tools.ietf.org/html/rfc4880#section-5.2.3.10 - SigLifetimeSecs uint32 - // SigningKeyId is used to specify the signing key to use (by Key ID). - // By default, the signing key is selected automatically, preferring - // signing subkeys if available. - SigningKeyId uint64 - // SigningIdentity is used to specify a user ID (packet Signer's User ID, type 28) - // when producing a generic certification signature onto an existing user ID. - // The identity must be present in the signer Entity. - SigningIdentity string - // InsecureAllowUnauthenticatedMessages controls, whether it is tolerated to read - // encrypted messages without Modification Detection Code (MDC). - // MDC is mandated by the IETF OpenPGP Crypto Refresh draft and has long been implemented - // in most OpenPGP implementations. Messages without MDC are considered unnecessarily - // insecure and should be prevented whenever possible. - // In case one needs to deal with messages from very old OpenPGP implementations, there - // might be no other way than to tolerate the missing MDC. Setting this flag, allows this - // mode of operation. It should be considered a measure of last resort. - InsecureAllowUnauthenticatedMessages bool - // KnownNotations is a map of Notation Data names to bools, which controls - // the notation names that are allowed to be present in critical Notation Data - // signature subpackets. - KnownNotations map[string]bool -} - -func (c *Config) Random() io.Reader { - if c == nil || c.Rand == nil { - return rand.Reader - } - return c.Rand -} - -func (c *Config) Hash() crypto.Hash { - if c == nil || uint(c.DefaultHash) == 0 { - return crypto.SHA256 - } - return c.DefaultHash -} - -func (c *Config) Cipher() CipherFunction { - if c == nil || uint8(c.DefaultCipher) == 0 { - return CipherAES128 - } - return c.DefaultCipher -} - -func (c *Config) Now() time.Time { - if c == nil || c.Time == nil { - return time.Now() - } - return c.Time() -} - -// KeyLifetime returns the validity period of the key. -func (c *Config) KeyLifetime() uint32 { - if c == nil { - return 0 - } - return c.KeyLifetimeSecs -} - -// SigLifetime returns the validity period of the signature. -func (c *Config) SigLifetime() uint32 { - if c == nil { - return 0 - } - return c.SigLifetimeSecs -} - -func (c *Config) Compression() CompressionAlgo { - if c == nil { - return CompressionNone - } - return c.DefaultCompressionAlgo -} - -func (c *Config) PasswordHashIterations() int { - if c == nil || c.S2KCount == 0 { - return 0 - } - return c.S2KCount -} - -func (c *Config) RSAModulusBits() int { - if c == nil || c.RSABits == 0 { - return 2048 - } - return c.RSABits -} - -func (c *Config) PublicKeyAlgorithm() PublicKeyAlgorithm { - if c == nil || c.Algorithm == 0 { - return PubKeyAlgoRSA - } - return c.Algorithm -} - -func (c *Config) CurveName() Curve { - if c == nil || c.Curve == "" { - return Curve25519 - } - return c.Curve -} - -func (c *Config) AEAD() *AEADConfig { - if c == nil { - return nil - } - return c.AEADConfig -} - -func (c *Config) SigningKey() uint64 { - if c == nil { - return 0 - } - return c.SigningKeyId -} - -func (c *Config) SigningUserId() string { - if c == nil { - return "" - } - return c.SigningIdentity -} - -func (c *Config) AllowUnauthenticatedMessages() bool { - if c == nil { - return false - } - return c.InsecureAllowUnauthenticatedMessages -} - -func (c *Config) KnownNotation(notationName string) bool { - if c == nil { - return false - } - return c.KnownNotations[notationName] -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/encrypted_key.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/encrypted_key.go deleted file mode 100644 index eeff2902..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/encrypted_key.go +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "crypto" - "crypto/rsa" - "encoding/binary" - "io" - "math/big" - "strconv" - - "github.com/ProtonMail/go-crypto/openpgp/ecdh" - "github.com/ProtonMail/go-crypto/openpgp/elgamal" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/encoding" -) - -const encryptedKeyVersion = 3 - -// EncryptedKey represents a public-key encrypted session key. See RFC 4880, -// section 5.1. -type EncryptedKey struct { - KeyId uint64 - Algo PublicKeyAlgorithm - CipherFunc CipherFunction // only valid after a successful Decrypt for a v3 packet - Key []byte // only valid after a successful Decrypt - - encryptedMPI1, encryptedMPI2 encoding.Field -} - -func (e *EncryptedKey) parse(r io.Reader) (err error) { - var buf [10]byte - _, err = readFull(r, buf[:]) - if err != nil { - return - } - if buf[0] != encryptedKeyVersion { - return errors.UnsupportedError("unknown EncryptedKey version " + strconv.Itoa(int(buf[0]))) - } - e.KeyId = binary.BigEndian.Uint64(buf[1:9]) - e.Algo = PublicKeyAlgorithm(buf[9]) - switch e.Algo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - e.encryptedMPI1 = new(encoding.MPI) - if _, err = e.encryptedMPI1.ReadFrom(r); err != nil { - return - } - case PubKeyAlgoElGamal: - e.encryptedMPI1 = new(encoding.MPI) - if _, err = e.encryptedMPI1.ReadFrom(r); err != nil { - return - } - - e.encryptedMPI2 = new(encoding.MPI) - if _, err = e.encryptedMPI2.ReadFrom(r); err != nil { - return - } - case PubKeyAlgoECDH: - e.encryptedMPI1 = new(encoding.MPI) - if _, err = e.encryptedMPI1.ReadFrom(r); err != nil { - return - } - - e.encryptedMPI2 = new(encoding.OID) - if _, err = e.encryptedMPI2.ReadFrom(r); err != nil { - return - } - } - _, err = consumeAll(r) - return -} - -func checksumKeyMaterial(key []byte) uint16 { - var checksum uint16 - for _, v := range key { - checksum += uint16(v) - } - return checksum -} - -// Decrypt decrypts an encrypted session key with the given private key. The -// private key must have been decrypted first. -// If config is nil, sensible defaults will be used. -func (e *EncryptedKey) Decrypt(priv *PrivateKey, config *Config) error { - if e.KeyId != 0 && e.KeyId != priv.KeyId { - return errors.InvalidArgumentError("cannot decrypt encrypted session key for key id " + strconv.FormatUint(e.KeyId, 16) + " with private key id " + strconv.FormatUint(priv.KeyId, 16)) - } - if e.Algo != priv.PubKeyAlgo { - return errors.InvalidArgumentError("cannot decrypt encrypted session key of type " + strconv.Itoa(int(e.Algo)) + " with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo))) - } - if priv.Dummy() { - return errors.ErrDummyPrivateKey("dummy key found") - } - - var err error - var b []byte - - // TODO(agl): use session key decryption routines here to avoid - // padding oracle attacks. - switch priv.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - // Supports both *rsa.PrivateKey and crypto.Decrypter - k := priv.PrivateKey.(crypto.Decrypter) - b, err = k.Decrypt(config.Random(), padToKeySize(k.Public().(*rsa.PublicKey), e.encryptedMPI1.Bytes()), nil) - case PubKeyAlgoElGamal: - c1 := new(big.Int).SetBytes(e.encryptedMPI1.Bytes()) - c2 := new(big.Int).SetBytes(e.encryptedMPI2.Bytes()) - b, err = elgamal.Decrypt(priv.PrivateKey.(*elgamal.PrivateKey), c1, c2) - case PubKeyAlgoECDH: - vsG := e.encryptedMPI1.Bytes() - m := e.encryptedMPI2.Bytes() - oid := priv.PublicKey.oid.EncodedBytes() - b, err = ecdh.Decrypt(priv.PrivateKey.(*ecdh.PrivateKey), vsG, m, oid, priv.PublicKey.Fingerprint[:]) - default: - err = errors.InvalidArgumentError("cannot decrypt encrypted session key with private key of type " + strconv.Itoa(int(priv.PubKeyAlgo))) - } - - if err != nil { - return err - } - - e.CipherFunc = CipherFunction(b[0]) - if !e.CipherFunc.IsSupported() { - return errors.UnsupportedError("unsupported encryption function") - } - - e.Key = b[1 : len(b)-2] - expectedChecksum := uint16(b[len(b)-2])<<8 | uint16(b[len(b)-1]) - checksum := checksumKeyMaterial(e.Key) - if checksum != expectedChecksum { - return errors.StructuralError("EncryptedKey checksum incorrect") - } - - return nil -} - -// Serialize writes the encrypted key packet, e, to w. -func (e *EncryptedKey) Serialize(w io.Writer) error { - var mpiLen int - switch e.Algo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - mpiLen = int(e.encryptedMPI1.EncodedLength()) - case PubKeyAlgoElGamal: - mpiLen = int(e.encryptedMPI1.EncodedLength()) + int(e.encryptedMPI2.EncodedLength()) - case PubKeyAlgoECDH: - mpiLen = int(e.encryptedMPI1.EncodedLength()) + int(e.encryptedMPI2.EncodedLength()) - default: - return errors.InvalidArgumentError("don't know how to serialize encrypted key type " + strconv.Itoa(int(e.Algo))) - } - - err := serializeHeader(w, packetTypeEncryptedKey, 1 /* version */ +8 /* key id */ +1 /* algo */ +mpiLen) - if err != nil { - return err - } - - w.Write([]byte{encryptedKeyVersion}) - binary.Write(w, binary.BigEndian, e.KeyId) - w.Write([]byte{byte(e.Algo)}) - - switch e.Algo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - _, err := w.Write(e.encryptedMPI1.EncodedBytes()) - return err - case PubKeyAlgoElGamal: - if _, err := w.Write(e.encryptedMPI1.EncodedBytes()); err != nil { - return err - } - _, err := w.Write(e.encryptedMPI2.EncodedBytes()) - return err - case PubKeyAlgoECDH: - if _, err := w.Write(e.encryptedMPI1.EncodedBytes()); err != nil { - return err - } - _, err := w.Write(e.encryptedMPI2.EncodedBytes()) - return err - default: - panic("internal error") - } -} - -// SerializeEncryptedKey serializes an encrypted key packet to w that contains -// key, encrypted to pub. -// If config is nil, sensible defaults will be used. -func SerializeEncryptedKey(w io.Writer, pub *PublicKey, cipherFunc CipherFunction, key []byte, config *Config) error { - var buf [10]byte - buf[0] = encryptedKeyVersion - binary.BigEndian.PutUint64(buf[1:9], pub.KeyId) - buf[9] = byte(pub.PubKeyAlgo) - - keyBlock := make([]byte, 1 /* cipher type */ +len(key)+2 /* checksum */) - keyBlock[0] = byte(cipherFunc) - copy(keyBlock[1:], key) - checksum := checksumKeyMaterial(key) - keyBlock[1+len(key)] = byte(checksum >> 8) - keyBlock[1+len(key)+1] = byte(checksum) - - switch pub.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly: - return serializeEncryptedKeyRSA(w, config.Random(), buf, pub.PublicKey.(*rsa.PublicKey), keyBlock) - case PubKeyAlgoElGamal: - return serializeEncryptedKeyElGamal(w, config.Random(), buf, pub.PublicKey.(*elgamal.PublicKey), keyBlock) - case PubKeyAlgoECDH: - return serializeEncryptedKeyECDH(w, config.Random(), buf, pub.PublicKey.(*ecdh.PublicKey), keyBlock, pub.oid, pub.Fingerprint) - case PubKeyAlgoDSA, PubKeyAlgoRSASignOnly: - return errors.InvalidArgumentError("cannot encrypt to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) - } - - return errors.UnsupportedError("encrypting a key to public key of type " + strconv.Itoa(int(pub.PubKeyAlgo))) -} - -func serializeEncryptedKeyRSA(w io.Writer, rand io.Reader, header [10]byte, pub *rsa.PublicKey, keyBlock []byte) error { - cipherText, err := rsa.EncryptPKCS1v15(rand, pub, keyBlock) - if err != nil { - return errors.InvalidArgumentError("RSA encryption failed: " + err.Error()) - } - - cipherMPI := encoding.NewMPI(cipherText) - packetLen := 10 /* header length */ + int(cipherMPI.EncodedLength()) - - err = serializeHeader(w, packetTypeEncryptedKey, packetLen) - if err != nil { - return err - } - _, err = w.Write(header[:]) - if err != nil { - return err - } - _, err = w.Write(cipherMPI.EncodedBytes()) - return err -} - -func serializeEncryptedKeyElGamal(w io.Writer, rand io.Reader, header [10]byte, pub *elgamal.PublicKey, keyBlock []byte) error { - c1, c2, err := elgamal.Encrypt(rand, pub, keyBlock) - if err != nil { - return errors.InvalidArgumentError("ElGamal encryption failed: " + err.Error()) - } - - packetLen := 10 /* header length */ - packetLen += 2 /* mpi size */ + (c1.BitLen()+7)/8 - packetLen += 2 /* mpi size */ + (c2.BitLen()+7)/8 - - err = serializeHeader(w, packetTypeEncryptedKey, packetLen) - if err != nil { - return err - } - _, err = w.Write(header[:]) - if err != nil { - return err - } - if _, err = w.Write(new(encoding.MPI).SetBig(c1).EncodedBytes()); err != nil { - return err - } - _, err = w.Write(new(encoding.MPI).SetBig(c2).EncodedBytes()) - return err -} - -func serializeEncryptedKeyECDH(w io.Writer, rand io.Reader, header [10]byte, pub *ecdh.PublicKey, keyBlock []byte, oid encoding.Field, fingerprint []byte) error { - vsG, c, err := ecdh.Encrypt(rand, pub, keyBlock, oid.EncodedBytes(), fingerprint) - if err != nil { - return errors.InvalidArgumentError("ECDH encryption failed: " + err.Error()) - } - - g := encoding.NewMPI(vsG) - m := encoding.NewOID(c) - - packetLen := 10 /* header length */ - packetLen += int(g.EncodedLength()) + int(m.EncodedLength()) - - err = serializeHeader(w, packetTypeEncryptedKey, packetLen) - if err != nil { - return err - } - - _, err = w.Write(header[:]) - if err != nil { - return err - } - if _, err = w.Write(g.EncodedBytes()); err != nil { - return err - } - _, err = w.Write(m.EncodedBytes()) - return err -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/literal.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/literal.go deleted file mode 100644 index 4be98760..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/literal.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "encoding/binary" - "io" -) - -// LiteralData represents an encrypted file. See RFC 4880, section 5.9. -type LiteralData struct { - Format uint8 - IsBinary bool - FileName string - Time uint32 // Unix epoch time. Either creation time or modification time. 0 means undefined. - Body io.Reader -} - -// ForEyesOnly returns whether the contents of the LiteralData have been marked -// as especially sensitive. -func (l *LiteralData) ForEyesOnly() bool { - return l.FileName == "_CONSOLE" -} - -func (l *LiteralData) parse(r io.Reader) (err error) { - var buf [256]byte - - _, err = readFull(r, buf[:2]) - if err != nil { - return - } - - l.Format = buf[0] - l.IsBinary = l.Format == 'b' - fileNameLen := int(buf[1]) - - _, err = readFull(r, buf[:fileNameLen]) - if err != nil { - return - } - - l.FileName = string(buf[:fileNameLen]) - - _, err = readFull(r, buf[:4]) - if err != nil { - return - } - - l.Time = binary.BigEndian.Uint32(buf[:4]) - l.Body = r - return -} - -// SerializeLiteral serializes a literal data packet to w and returns a -// WriteCloser to which the data itself can be written and which MUST be closed -// on completion. The fileName is truncated to 255 bytes. -func SerializeLiteral(w io.WriteCloser, isBinary bool, fileName string, time uint32) (plaintext io.WriteCloser, err error) { - var buf [4]byte - buf[0] = 't' - if isBinary { - buf[0] = 'b' - } - if len(fileName) > 255 { - fileName = fileName[:255] - } - buf[1] = byte(len(fileName)) - - inner, err := serializeStreamHeader(w, packetTypeLiteralData) - if err != nil { - return - } - - _, err = inner.Write(buf[:2]) - if err != nil { - return - } - _, err = inner.Write([]byte(fileName)) - if err != nil { - return - } - binary.BigEndian.PutUint32(buf[:], time) - _, err = inner.Write(buf[:]) - if err != nil { - return - } - - plaintext = inner - return -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/notation.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/notation.go deleted file mode 100644 index 2c3e3f50..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/notation.go +++ /dev/null @@ -1,29 +0,0 @@ -package packet - -// Notation type represents a Notation Data subpacket -// see https://tools.ietf.org/html/rfc4880#section-5.2.3.16 -type Notation struct { - Name string - Value []byte - IsCritical bool - IsHumanReadable bool -} - -func (notation *Notation) getData() []byte { - nameData := []byte(notation.Name) - nameLen := len(nameData) - valueLen := len(notation.Value) - - data := make([]byte, 8+nameLen+valueLen) - if notation.IsHumanReadable { - data[0] = 0x80 - } - - data[4] = byte(nameLen >> 8) - data[5] = byte(nameLen) - data[6] = byte(valueLen >> 8) - data[7] = byte(valueLen) - copy(data[8:8+nameLen], nameData) - copy(data[8+nameLen:], notation.Value) - return data -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/ocfb.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/ocfb.go deleted file mode 100644 index 4f26d0a0..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/ocfb.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2010 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. - -// OpenPGP CFB Mode. http://tools.ietf.org/html/rfc4880#section-13.9 - -package packet - -import ( - "crypto/cipher" -) - -type ocfbEncrypter struct { - b cipher.Block - fre []byte - outUsed int -} - -// An OCFBResyncOption determines if the "resynchronization step" of OCFB is -// performed. -type OCFBResyncOption bool - -const ( - OCFBResync OCFBResyncOption = true - OCFBNoResync OCFBResyncOption = false -) - -// NewOCFBEncrypter returns a cipher.Stream which encrypts data with OpenPGP's -// cipher feedback mode using the given cipher.Block, and an initial amount of -// ciphertext. randData must be random bytes and be the same length as the -// cipher.Block's block size. Resync determines if the "resynchronization step" -// from RFC 4880, 13.9 step 7 is performed. Different parts of OpenPGP vary on -// this point. -func NewOCFBEncrypter(block cipher.Block, randData []byte, resync OCFBResyncOption) (cipher.Stream, []byte) { - blockSize := block.BlockSize() - if len(randData) != blockSize { - return nil, nil - } - - x := &ocfbEncrypter{ - b: block, - fre: make([]byte, blockSize), - outUsed: 0, - } - prefix := make([]byte, blockSize+2) - - block.Encrypt(x.fre, x.fre) - for i := 0; i < blockSize; i++ { - prefix[i] = randData[i] ^ x.fre[i] - } - - block.Encrypt(x.fre, prefix[:blockSize]) - prefix[blockSize] = x.fre[0] ^ randData[blockSize-2] - prefix[blockSize+1] = x.fre[1] ^ randData[blockSize-1] - - if resync { - block.Encrypt(x.fre, prefix[2:]) - } else { - x.fre[0] = prefix[blockSize] - x.fre[1] = prefix[blockSize+1] - x.outUsed = 2 - } - return x, prefix -} - -func (x *ocfbEncrypter) XORKeyStream(dst, src []byte) { - for i := 0; i < len(src); i++ { - if x.outUsed == len(x.fre) { - x.b.Encrypt(x.fre, x.fre) - x.outUsed = 0 - } - - x.fre[x.outUsed] ^= src[i] - dst[i] = x.fre[x.outUsed] - x.outUsed++ - } -} - -type ocfbDecrypter struct { - b cipher.Block - fre []byte - outUsed int -} - -// NewOCFBDecrypter returns a cipher.Stream which decrypts data with OpenPGP's -// cipher feedback mode using the given cipher.Block. Prefix must be the first -// blockSize + 2 bytes of the ciphertext, where blockSize is the cipher.Block's -// block size. On successful exit, blockSize+2 bytes of decrypted data are written into -// prefix. Resync determines if the "resynchronization step" from RFC 4880, -// 13.9 step 7 is performed. Different parts of OpenPGP vary on this point. -func NewOCFBDecrypter(block cipher.Block, prefix []byte, resync OCFBResyncOption) cipher.Stream { - blockSize := block.BlockSize() - if len(prefix) != blockSize+2 { - return nil - } - - x := &ocfbDecrypter{ - b: block, - fre: make([]byte, blockSize), - outUsed: 0, - } - prefixCopy := make([]byte, len(prefix)) - copy(prefixCopy, prefix) - - block.Encrypt(x.fre, x.fre) - for i := 0; i < blockSize; i++ { - prefixCopy[i] ^= x.fre[i] - } - - block.Encrypt(x.fre, prefix[:blockSize]) - prefixCopy[blockSize] ^= x.fre[0] - prefixCopy[blockSize+1] ^= x.fre[1] - - if resync { - block.Encrypt(x.fre, prefix[2:]) - } else { - x.fre[0] = prefix[blockSize] - x.fre[1] = prefix[blockSize+1] - x.outUsed = 2 - } - copy(prefix, prefixCopy) - return x -} - -func (x *ocfbDecrypter) XORKeyStream(dst, src []byte) { - for i := 0; i < len(src); i++ { - if x.outUsed == len(x.fre) { - x.b.Encrypt(x.fre, x.fre) - x.outUsed = 0 - } - - c := src[i] - dst[i] = x.fre[x.outUsed] ^ src[i] - x.fre[x.outUsed] = c - x.outUsed++ - } -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/one_pass_signature.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/one_pass_signature.go deleted file mode 100644 index fff119e6..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/one_pass_signature.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "crypto" - "encoding/binary" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm" - "io" - "strconv" -) - -// OnePassSignature represents a one-pass signature packet. See RFC 4880, -// section 5.4. -type OnePassSignature struct { - SigType SignatureType - Hash crypto.Hash - PubKeyAlgo PublicKeyAlgorithm - KeyId uint64 - IsLast bool -} - -const onePassSignatureVersion = 3 - -func (ops *OnePassSignature) parse(r io.Reader) (err error) { - var buf [13]byte - - _, err = readFull(r, buf[:]) - if err != nil { - return - } - if buf[0] != onePassSignatureVersion { - err = errors.UnsupportedError("one-pass-signature packet version " + strconv.Itoa(int(buf[0]))) - } - - var ok bool - ops.Hash, ok = algorithm.HashIdToHashWithSha1(buf[2]) - if !ok { - return errors.UnsupportedError("hash function: " + strconv.Itoa(int(buf[2]))) - } - - ops.SigType = SignatureType(buf[1]) - ops.PubKeyAlgo = PublicKeyAlgorithm(buf[3]) - ops.KeyId = binary.BigEndian.Uint64(buf[4:12]) - ops.IsLast = buf[12] != 0 - return -} - -// Serialize marshals the given OnePassSignature to w. -func (ops *OnePassSignature) Serialize(w io.Writer) error { - var buf [13]byte - buf[0] = onePassSignatureVersion - buf[1] = uint8(ops.SigType) - var ok bool - buf[2], ok = algorithm.HashToHashId(ops.Hash) - if !ok { - return errors.UnsupportedError("hash type: " + strconv.Itoa(int(ops.Hash))) - } - buf[3] = uint8(ops.PubKeyAlgo) - binary.BigEndian.PutUint64(buf[4:12], ops.KeyId) - if ops.IsLast { - buf[12] = 1 - } - - if err := serializeHeader(w, packetTypeOnePassSignature, len(buf)); err != nil { - return err - } - _, err := w.Write(buf[:]) - return err -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/opaque.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/opaque.go deleted file mode 100644 index 4f820407..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/opaque.go +++ /dev/null @@ -1,171 +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 packet - -import ( - "bytes" - "io" - "io/ioutil" - - "github.com/ProtonMail/go-crypto/openpgp/errors" -) - -// OpaquePacket represents an OpenPGP packet as raw, unparsed data. This is -// useful for splitting and storing the original packet contents separately, -// handling unsupported packet types or accessing parts of the packet not yet -// implemented by this package. -type OpaquePacket struct { - // Packet type - Tag uint8 - // Reason why the packet was parsed opaquely - Reason error - // Binary contents of the packet data - Contents []byte -} - -func (op *OpaquePacket) parse(r io.Reader) (err error) { - op.Contents, err = ioutil.ReadAll(r) - return -} - -// Serialize marshals the packet to a writer in its original form, including -// the packet header. -func (op *OpaquePacket) Serialize(w io.Writer) (err error) { - err = serializeHeader(w, packetType(op.Tag), len(op.Contents)) - if err == nil { - _, err = w.Write(op.Contents) - } - return -} - -// Parse attempts to parse the opaque contents into a structure supported by -// this package. If the packet is not known then the result will be another -// OpaquePacket. -func (op *OpaquePacket) Parse() (p Packet, err error) { - hdr := bytes.NewBuffer(nil) - err = serializeHeader(hdr, packetType(op.Tag), len(op.Contents)) - if err != nil { - op.Reason = err - return op, err - } - p, err = Read(io.MultiReader(hdr, bytes.NewBuffer(op.Contents))) - if err != nil { - op.Reason = err - p = op - } - return -} - -// OpaqueReader reads OpaquePackets from an io.Reader. -type OpaqueReader struct { - r io.Reader -} - -func NewOpaqueReader(r io.Reader) *OpaqueReader { - return &OpaqueReader{r: r} -} - -// Read the next OpaquePacket. -func (or *OpaqueReader) Next() (op *OpaquePacket, err error) { - tag, _, contents, err := readHeader(or.r) - if err != nil { - return - } - op = &OpaquePacket{Tag: uint8(tag), Reason: err} - err = op.parse(contents) - if err != nil { - consumeAll(contents) - } - return -} - -// OpaqueSubpacket represents an unparsed OpenPGP subpacket, -// as found in signature and user attribute packets. -type OpaqueSubpacket struct { - SubType uint8 - EncodedLength []byte // Store the original encoded length for signature verifications. - Contents []byte -} - -// OpaqueSubpackets extracts opaque, unparsed OpenPGP subpackets from -// their byte representation. -func OpaqueSubpackets(contents []byte) (result []*OpaqueSubpacket, err error) { - var ( - subHeaderLen int - subPacket *OpaqueSubpacket - ) - for len(contents) > 0 { - subHeaderLen, subPacket, err = nextSubpacket(contents) - if err != nil { - break - } - result = append(result, subPacket) - contents = contents[subHeaderLen+len(subPacket.Contents):] - } - return -} - -func nextSubpacket(contents []byte) (subHeaderLen int, subPacket *OpaqueSubpacket, err error) { - // RFC 4880, section 5.2.3.1 - var subLen uint32 - var encodedLength []byte - if len(contents) < 1 { - goto Truncated - } - subPacket = &OpaqueSubpacket{} - switch { - case contents[0] < 192: - subHeaderLen = 2 // 1 length byte, 1 subtype byte - if len(contents) < subHeaderLen { - goto Truncated - } - encodedLength = contents[0:1] - subLen = uint32(contents[0]) - contents = contents[1:] - case contents[0] < 255: - subHeaderLen = 3 // 2 length bytes, 1 subtype - if len(contents) < subHeaderLen { - goto Truncated - } - encodedLength = contents[0:2] - subLen = uint32(contents[0]-192)<<8 + uint32(contents[1]) + 192 - contents = contents[2:] - default: - subHeaderLen = 6 // 5 length bytes, 1 subtype - if len(contents) < subHeaderLen { - goto Truncated - } - encodedLength = contents[0:5] - subLen = uint32(contents[1])<<24 | - uint32(contents[2])<<16 | - uint32(contents[3])<<8 | - uint32(contents[4]) - contents = contents[5:] - - } - if subLen > uint32(len(contents)) || subLen == 0 { - goto Truncated - } - subPacket.SubType = contents[0] - subPacket.EncodedLength = encodedLength - subPacket.Contents = contents[1:subLen] - return -Truncated: - err = errors.StructuralError("subpacket truncated") - return -} - -func (osp *OpaqueSubpacket) Serialize(w io.Writer) (err error) { - buf := make([]byte, 6) - copy(buf, osp.EncodedLength) - n := len(osp.EncodedLength) - - buf[n] = osp.SubType - if _, err = w.Write(buf[:n+1]); err != nil { - return - } - _, err = w.Write(osp.Contents) - return -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/packet.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/packet.go deleted file mode 100644 index f73f6f40..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/packet.go +++ /dev/null @@ -1,551 +0,0 @@ -// Copyright 2011 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 packet implements parsing and serialization of OpenPGP packets, as -// specified in RFC 4880. -package packet // import "github.com/ProtonMail/go-crypto/openpgp/packet" - -import ( - "bytes" - "crypto/cipher" - "crypto/rsa" - "io" - - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm" -) - -// readFull is the same as io.ReadFull except that reading zero bytes returns -// ErrUnexpectedEOF rather than EOF. -func readFull(r io.Reader, buf []byte) (n int, err error) { - n, err = io.ReadFull(r, buf) - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return -} - -// readLength reads an OpenPGP length from r. See RFC 4880, section 4.2.2. -func readLength(r io.Reader) (length int64, isPartial bool, err error) { - var buf [4]byte - _, err = readFull(r, buf[:1]) - if err != nil { - return - } - switch { - case buf[0] < 192: - length = int64(buf[0]) - case buf[0] < 224: - length = int64(buf[0]-192) << 8 - _, err = readFull(r, buf[0:1]) - if err != nil { - return - } - length += int64(buf[0]) + 192 - case buf[0] < 255: - length = int64(1) << (buf[0] & 0x1f) - isPartial = true - default: - _, err = readFull(r, buf[0:4]) - if err != nil { - return - } - length = int64(buf[0])<<24 | - int64(buf[1])<<16 | - int64(buf[2])<<8 | - int64(buf[3]) - } - return -} - -// partialLengthReader wraps an io.Reader and handles OpenPGP partial lengths. -// The continuation lengths are parsed and removed from the stream and EOF is -// returned at the end of the packet. See RFC 4880, section 4.2.2.4. -type partialLengthReader struct { - r io.Reader - remaining int64 - isPartial bool -} - -func (r *partialLengthReader) Read(p []byte) (n int, err error) { - for r.remaining == 0 { - if !r.isPartial { - return 0, io.EOF - } - r.remaining, r.isPartial, err = readLength(r.r) - if err != nil { - return 0, err - } - } - - toRead := int64(len(p)) - if toRead > r.remaining { - toRead = r.remaining - } - - n, err = r.r.Read(p[:int(toRead)]) - r.remaining -= int64(n) - if n < int(toRead) && err == io.EOF { - err = io.ErrUnexpectedEOF - } - return -} - -// partialLengthWriter writes a stream of data using OpenPGP partial lengths. -// See RFC 4880, section 4.2.2.4. -type partialLengthWriter struct { - w io.WriteCloser - buf bytes.Buffer - lengthByte [1]byte -} - -func (w *partialLengthWriter) Write(p []byte) (n int, err error) { - bufLen := w.buf.Len() - if bufLen > 512 { - for power := uint(30); ; power-- { - l := 1 << power - if bufLen >= l { - w.lengthByte[0] = 224 + uint8(power) - _, err = w.w.Write(w.lengthByte[:]) - if err != nil { - return - } - var m int - m, err = w.w.Write(w.buf.Next(l)) - if err != nil { - return - } - if m != l { - return 0, io.ErrShortWrite - } - break - } - } - } - return w.buf.Write(p) -} - -func (w *partialLengthWriter) Close() (err error) { - len := w.buf.Len() - err = serializeLength(w.w, len) - if err != nil { - return err - } - _, err = w.buf.WriteTo(w.w) - if err != nil { - return err - } - return w.w.Close() -} - -// A spanReader is an io.LimitReader, but it returns ErrUnexpectedEOF if the -// underlying Reader returns EOF before the limit has been reached. -type spanReader struct { - r io.Reader - n int64 -} - -func (l *spanReader) Read(p []byte) (n int, err error) { - if l.n <= 0 { - return 0, io.EOF - } - if int64(len(p)) > l.n { - p = p[0:l.n] - } - n, err = l.r.Read(p) - l.n -= int64(n) - if l.n > 0 && err == io.EOF { - err = io.ErrUnexpectedEOF - } - return -} - -// readHeader parses a packet header and returns an io.Reader which will return -// the contents of the packet. See RFC 4880, section 4.2. -func readHeader(r io.Reader) (tag packetType, length int64, contents io.Reader, err error) { - var buf [4]byte - _, err = io.ReadFull(r, buf[:1]) - if err != nil { - return - } - if buf[0]&0x80 == 0 { - err = errors.StructuralError("tag byte does not have MSB set") - return - } - if buf[0]&0x40 == 0 { - // Old format packet - tag = packetType((buf[0] & 0x3f) >> 2) - lengthType := buf[0] & 3 - if lengthType == 3 { - length = -1 - contents = r - return - } - lengthBytes := 1 << lengthType - _, err = readFull(r, buf[0:lengthBytes]) - if err != nil { - return - } - for i := 0; i < lengthBytes; i++ { - length <<= 8 - length |= int64(buf[i]) - } - contents = &spanReader{r, length} - return - } - - // New format packet - tag = packetType(buf[0] & 0x3f) - length, isPartial, err := readLength(r) - if err != nil { - return - } - if isPartial { - contents = &partialLengthReader{ - remaining: length, - isPartial: true, - r: r, - } - length = -1 - } else { - contents = &spanReader{r, length} - } - return -} - -// serializeHeader writes an OpenPGP packet header to w. See RFC 4880, section -// 4.2. -func serializeHeader(w io.Writer, ptype packetType, length int) (err error) { - err = serializeType(w, ptype) - if err != nil { - return - } - return serializeLength(w, length) -} - -// serializeType writes an OpenPGP packet type to w. See RFC 4880, section -// 4.2. -func serializeType(w io.Writer, ptype packetType) (err error) { - var buf [1]byte - buf[0] = 0x80 | 0x40 | byte(ptype) - _, err = w.Write(buf[:]) - return -} - -// serializeLength writes an OpenPGP packet length to w. See RFC 4880, section -// 4.2.2. -func serializeLength(w io.Writer, length int) (err error) { - var buf [5]byte - var n int - - if length < 192 { - buf[0] = byte(length) - n = 1 - } else if length < 8384 { - length -= 192 - buf[0] = 192 + byte(length>>8) - buf[1] = byte(length) - n = 2 - } else { - buf[0] = 255 - buf[1] = byte(length >> 24) - buf[2] = byte(length >> 16) - buf[3] = byte(length >> 8) - buf[4] = byte(length) - n = 5 - } - - _, err = w.Write(buf[:n]) - return -} - -// serializeStreamHeader writes an OpenPGP packet header to w where the -// length of the packet is unknown. It returns a io.WriteCloser which can be -// used to write the contents of the packet. See RFC 4880, section 4.2. -func serializeStreamHeader(w io.WriteCloser, ptype packetType) (out io.WriteCloser, err error) { - err = serializeType(w, ptype) - if err != nil { - return - } - out = &partialLengthWriter{w: w} - return -} - -// Packet represents an OpenPGP packet. Users are expected to try casting -// instances of this interface to specific packet types. -type Packet interface { - parse(io.Reader) error -} - -// consumeAll reads from the given Reader until error, returning the number of -// bytes read. -func consumeAll(r io.Reader) (n int64, err error) { - var m int - var buf [1024]byte - - for { - m, err = r.Read(buf[:]) - n += int64(m) - if err == io.EOF { - err = nil - return - } - if err != nil { - return - } - } -} - -// packetType represents the numeric ids of the different OpenPGP packet types. See -// http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-2 -type packetType uint8 - -const ( - packetTypeEncryptedKey packetType = 1 - packetTypeSignature packetType = 2 - packetTypeSymmetricKeyEncrypted packetType = 3 - packetTypeOnePassSignature packetType = 4 - packetTypePrivateKey packetType = 5 - packetTypePublicKey packetType = 6 - packetTypePrivateSubkey packetType = 7 - packetTypeCompressed packetType = 8 - packetTypeSymmetricallyEncrypted packetType = 9 - packetTypeLiteralData packetType = 11 - packetTypeUserId packetType = 13 - packetTypePublicSubkey packetType = 14 - packetTypeUserAttribute packetType = 17 - packetTypeSymmetricallyEncryptedIntegrityProtected packetType = 18 - packetTypeAEADEncrypted packetType = 20 -) - -// EncryptedDataPacket holds encrypted data. It is currently implemented by -// SymmetricallyEncrypted and AEADEncrypted. -type EncryptedDataPacket interface { - Decrypt(CipherFunction, []byte) (io.ReadCloser, error) -} - -// Read reads a single OpenPGP packet from the given io.Reader. If there is an -// error parsing a packet, the whole packet is consumed from the input. -func Read(r io.Reader) (p Packet, err error) { - tag, _, contents, err := readHeader(r) - if err != nil { - return - } - - switch tag { - case packetTypeEncryptedKey: - p = new(EncryptedKey) - case packetTypeSignature: - p = new(Signature) - case packetTypeSymmetricKeyEncrypted: - p = new(SymmetricKeyEncrypted) - case packetTypeOnePassSignature: - p = new(OnePassSignature) - case packetTypePrivateKey, packetTypePrivateSubkey: - pk := new(PrivateKey) - if tag == packetTypePrivateSubkey { - pk.IsSubkey = true - } - p = pk - case packetTypePublicKey, packetTypePublicSubkey: - isSubkey := tag == packetTypePublicSubkey - p = &PublicKey{IsSubkey: isSubkey} - case packetTypeCompressed: - p = new(Compressed) - case packetTypeSymmetricallyEncrypted: - p = new(SymmetricallyEncrypted) - case packetTypeLiteralData: - p = new(LiteralData) - case packetTypeUserId: - p = new(UserId) - case packetTypeUserAttribute: - p = new(UserAttribute) - case packetTypeSymmetricallyEncryptedIntegrityProtected: - se := new(SymmetricallyEncrypted) - se.IntegrityProtected = true - p = se - case packetTypeAEADEncrypted: - p = new(AEADEncrypted) - default: - err = errors.UnknownPacketTypeError(tag) - } - if p != nil { - err = p.parse(contents) - } - if err != nil { - consumeAll(contents) - } - return -} - -// SignatureType represents the different semantic meanings of an OpenPGP -// signature. See RFC 4880, section 5.2.1. -type SignatureType uint8 - -const ( - SigTypeBinary SignatureType = 0x00 - SigTypeText = 0x01 - SigTypeGenericCert = 0x10 - SigTypePersonaCert = 0x11 - SigTypeCasualCert = 0x12 - SigTypePositiveCert = 0x13 - SigTypeSubkeyBinding = 0x18 - SigTypePrimaryKeyBinding = 0x19 - SigTypeDirectSignature = 0x1F - SigTypeKeyRevocation = 0x20 - SigTypeSubkeyRevocation = 0x28 - SigTypeCertificationRevocation = 0x30 -) - -// PublicKeyAlgorithm represents the different public key system specified for -// OpenPGP. See -// http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-12 -type PublicKeyAlgorithm uint8 - -const ( - PubKeyAlgoRSA PublicKeyAlgorithm = 1 - PubKeyAlgoElGamal PublicKeyAlgorithm = 16 - PubKeyAlgoDSA PublicKeyAlgorithm = 17 - // RFC 6637, Section 5. - PubKeyAlgoECDH PublicKeyAlgorithm = 18 - PubKeyAlgoECDSA PublicKeyAlgorithm = 19 - // https://www.ietf.org/archive/id/draft-koch-eddsa-for-openpgp-04.txt - PubKeyAlgoEdDSA PublicKeyAlgorithm = 22 - - // Deprecated in RFC 4880, Section 13.5. Use key flags instead. - PubKeyAlgoRSAEncryptOnly PublicKeyAlgorithm = 2 - PubKeyAlgoRSASignOnly PublicKeyAlgorithm = 3 -) - -// CanEncrypt returns true if it's possible to encrypt a message to a public -// key of the given type. -func (pka PublicKeyAlgorithm) CanEncrypt() bool { - switch pka { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoElGamal, PubKeyAlgoECDH: - return true - } - return false -} - -// CanSign returns true if it's possible for a public key of the given type to -// sign a message. -func (pka PublicKeyAlgorithm) CanSign() bool { - switch pka { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA, PubKeyAlgoEdDSA: - return true - } - return false -} - -// CipherFunction represents the different block ciphers specified for OpenPGP. See -// http://www.iana.org/assignments/pgp-parameters/pgp-parameters.xhtml#pgp-parameters-13 -type CipherFunction algorithm.CipherFunction - -const ( - Cipher3DES CipherFunction = 2 - CipherCAST5 CipherFunction = 3 - CipherAES128 CipherFunction = 7 - CipherAES192 CipherFunction = 8 - CipherAES256 CipherFunction = 9 -) - -// KeySize returns the key size, in bytes, of cipher. -func (cipher CipherFunction) KeySize() int { - return algorithm.CipherFunction(cipher).KeySize() -} - -// IsSupported returns true if the cipher is supported from the library -func (cipher CipherFunction) IsSupported() bool { - return algorithm.CipherFunction(cipher).KeySize() > 0 -} - -// blockSize returns the block size, in bytes, of cipher. -func (cipher CipherFunction) blockSize() int { - return algorithm.CipherFunction(cipher).BlockSize() -} - -// new returns a fresh instance of the given cipher. -func (cipher CipherFunction) new(key []byte) (block cipher.Block) { - return algorithm.CipherFunction(cipher).New(key) -} - -// padToKeySize left-pads a MPI with zeroes to match the length of the -// specified RSA public. -func padToKeySize(pub *rsa.PublicKey, b []byte) []byte { - k := (pub.N.BitLen() + 7) / 8 - if len(b) >= k { - return b - } - bb := make([]byte, k) - copy(bb[len(bb)-len(b):], b) - return bb -} - -// CompressionAlgo Represents the different compression algorithms -// supported by OpenPGP (except for BZIP2, which is not currently -// supported). See Section 9.3 of RFC 4880. -type CompressionAlgo uint8 - -const ( - CompressionNone CompressionAlgo = 0 - CompressionZIP CompressionAlgo = 1 - CompressionZLIB CompressionAlgo = 2 -) - -// AEADMode represents the different Authenticated Encryption with Associated -// Data specified for OpenPGP. -// See https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.6 -type AEADMode algorithm.AEADMode - -const ( - AEADModeEAX AEADMode = 1 - AEADModeOCB AEADMode = 2 - AEADModeGCM AEADMode = 3 -) - -func (mode AEADMode) IvLength() int { - return algorithm.AEADMode(mode).NonceLength() -} - -func (mode AEADMode) TagLength() int { - return algorithm.AEADMode(mode).TagLength() -} - -// new returns a fresh instance of the given mode. -func (mode AEADMode) new(block cipher.Block) cipher.AEAD { - return algorithm.AEADMode(mode).New(block) -} - -// ReasonForRevocation represents a revocation reason code as per RFC4880 -// section 5.2.3.23. -type ReasonForRevocation uint8 - -const ( - NoReason ReasonForRevocation = 0 - KeySuperseded ReasonForRevocation = 1 - KeyCompromised ReasonForRevocation = 2 - KeyRetired ReasonForRevocation = 3 -) - -// Curve is a mapping to supported ECC curves for key generation. -// See https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-06.html#name-curve-specific-wire-formats -type Curve string - -const ( - Curve25519 Curve = "Curve25519" - Curve448 Curve = "Curve448" - CurveNistP256 Curve = "P256" - CurveNistP384 Curve = "P384" - CurveNistP521 Curve = "P521" - CurveSecP256k1 Curve = "SecP256k1" - CurveBrainpoolP256 Curve = "BrainpoolP256" - CurveBrainpoolP384 Curve = "BrainpoolP384" - CurveBrainpoolP512 Curve = "BrainpoolP512" -) - -// TrustLevel represents a trust level per RFC4880 5.2.3.13 -type TrustLevel uint8 - -// TrustAmount represents a trust amount per RFC4880 5.2.3.13 -type TrustAmount uint8 diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/private_key.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/private_key.go deleted file mode 100644 index 2898fa74..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/private_key.go +++ /dev/null @@ -1,739 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "bytes" - "crypto" - "crypto/cipher" - "crypto/dsa" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "io" - "io/ioutil" - "math/big" - "strconv" - "time" - - "github.com/ProtonMail/go-crypto/openpgp/ecdh" - "github.com/ProtonMail/go-crypto/openpgp/ecdsa" - "github.com/ProtonMail/go-crypto/openpgp/eddsa" - "github.com/ProtonMail/go-crypto/openpgp/elgamal" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/encoding" - "github.com/ProtonMail/go-crypto/openpgp/s2k" -) - -// PrivateKey represents a possibly encrypted private key. See RFC 4880, -// section 5.5.3. -type PrivateKey struct { - PublicKey - Encrypted bool // if true then the private key is unavailable until Decrypt has been called. - encryptedData []byte - cipher CipherFunction - s2k func(out, in []byte) - // An *{rsa|dsa|elgamal|ecdh|ecdsa|ed25519}.PrivateKey or - // crypto.Signer/crypto.Decrypter (Decryptor RSA only). - PrivateKey interface{} - sha1Checksum bool - iv []byte - - // Type of encryption of the S2K packet - // Allowed values are 0 (Not encrypted), 254 (SHA1), or - // 255 (2-byte checksum) - s2kType S2KType - // Full parameters of the S2K packet - s2kParams *s2k.Params -} - -//S2KType s2k packet type -type S2KType uint8 - -const ( - // S2KNON unencrypt - S2KNON S2KType = 0 - // S2KSHA1 sha1 sum check - S2KSHA1 S2KType = 254 - // S2KCHECKSUM sum check - S2KCHECKSUM S2KType = 255 -) - -func NewRSAPrivateKey(creationTime time.Time, priv *rsa.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewRSAPublicKey(creationTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewDSAPrivateKey(creationTime time.Time, priv *dsa.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewDSAPublicKey(creationTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewElGamalPrivateKey(creationTime time.Time, priv *elgamal.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewElGamalPublicKey(creationTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewECDSAPrivateKey(creationTime time.Time, priv *ecdsa.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewECDSAPublicKey(creationTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewEdDSAPrivateKey(creationTime time.Time, priv *eddsa.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewEdDSAPublicKey(creationTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -func NewECDHPrivateKey(creationTime time.Time, priv *ecdh.PrivateKey) *PrivateKey { - pk := new(PrivateKey) - pk.PublicKey = *NewECDHPublicKey(creationTime, &priv.PublicKey) - pk.PrivateKey = priv - return pk -} - -// NewSignerPrivateKey creates a PrivateKey from a crypto.Signer that -// implements RSA, ECDSA or EdDSA. -func NewSignerPrivateKey(creationTime time.Time, signer interface{}) *PrivateKey { - pk := new(PrivateKey) - // In general, the public Keys should be used as pointers. We still - // type-switch on the values, for backwards-compatibility. - switch pubkey := signer.(type) { - case *rsa.PrivateKey: - pk.PublicKey = *NewRSAPublicKey(creationTime, &pubkey.PublicKey) - case rsa.PrivateKey: - pk.PublicKey = *NewRSAPublicKey(creationTime, &pubkey.PublicKey) - case *ecdsa.PrivateKey: - pk.PublicKey = *NewECDSAPublicKey(creationTime, &pubkey.PublicKey) - case ecdsa.PrivateKey: - pk.PublicKey = *NewECDSAPublicKey(creationTime, &pubkey.PublicKey) - case *eddsa.PrivateKey: - pk.PublicKey = *NewEdDSAPublicKey(creationTime, &pubkey.PublicKey) - case eddsa.PrivateKey: - pk.PublicKey = *NewEdDSAPublicKey(creationTime, &pubkey.PublicKey) - default: - panic("openpgp: unknown signer type in NewSignerPrivateKey") - } - pk.PrivateKey = signer - return pk -} - -// NewDecrypterPrivateKey creates a PrivateKey from a *{rsa|elgamal|ecdh}.PrivateKey. -func NewDecrypterPrivateKey(creationTime time.Time, decrypter interface{}) *PrivateKey { - pk := new(PrivateKey) - switch priv := decrypter.(type) { - case *rsa.PrivateKey: - pk.PublicKey = *NewRSAPublicKey(creationTime, &priv.PublicKey) - case *elgamal.PrivateKey: - pk.PublicKey = *NewElGamalPublicKey(creationTime, &priv.PublicKey) - case *ecdh.PrivateKey: - pk.PublicKey = *NewECDHPublicKey(creationTime, &priv.PublicKey) - default: - panic("openpgp: unknown decrypter type in NewDecrypterPrivateKey") - } - pk.PrivateKey = decrypter - return pk -} - -func (pk *PrivateKey) parse(r io.Reader) (err error) { - err = (&pk.PublicKey).parse(r) - if err != nil { - return - } - v5 := pk.PublicKey.Version == 5 - - var buf [1]byte - _, err = readFull(r, buf[:]) - if err != nil { - return - } - pk.s2kType = S2KType(buf[0]) - var optCount [1]byte - if v5 { - if _, err = readFull(r, optCount[:]); err != nil { - return - } - } - - switch pk.s2kType { - case S2KNON: - pk.s2k = nil - pk.Encrypted = false - case S2KSHA1, S2KCHECKSUM: - if v5 && pk.s2kType == S2KCHECKSUM { - return errors.StructuralError("wrong s2k identifier for version 5") - } - _, err = readFull(r, buf[:]) - if err != nil { - return - } - pk.cipher = CipherFunction(buf[0]) - if pk.cipher != 0 && !pk.cipher.IsSupported() { - return errors.UnsupportedError("unsupported cipher function in private key") - } - pk.s2kParams, err = s2k.ParseIntoParams(r) - if err != nil { - return - } - if pk.s2kParams.Dummy() { - return - } - pk.s2k, err = pk.s2kParams.Function() - if err != nil { - return - } - pk.Encrypted = true - if pk.s2kType == S2KSHA1 { - pk.sha1Checksum = true - } - default: - return errors.UnsupportedError("deprecated s2k function in private key") - } - - if pk.Encrypted { - blockSize := pk.cipher.blockSize() - if blockSize == 0 { - return errors.UnsupportedError("unsupported cipher in private key: " + strconv.Itoa(int(pk.cipher))) - } - pk.iv = make([]byte, blockSize) - _, err = readFull(r, pk.iv) - if err != nil { - return - } - } - - var privateKeyData []byte - if v5 { - var n [4]byte /* secret material four octet count */ - _, err = readFull(r, n[:]) - if err != nil { - return - } - count := uint32(uint32(n[0])<<24 | uint32(n[1])<<16 | uint32(n[2])<<8 | uint32(n[3])) - if !pk.Encrypted { - count = count + 2 /* two octet checksum */ - } - privateKeyData = make([]byte, count) - _, err = readFull(r, privateKeyData) - if err != nil { - return - } - } else { - privateKeyData, err = ioutil.ReadAll(r) - if err != nil { - return - } - } - if !pk.Encrypted { - if len(privateKeyData) < 2 { - return errors.StructuralError("truncated private key data") - } - var sum uint16 - for i := 0; i < len(privateKeyData)-2; i++ { - sum += uint16(privateKeyData[i]) - } - if privateKeyData[len(privateKeyData)-2] != uint8(sum>>8) || - privateKeyData[len(privateKeyData)-1] != uint8(sum) { - return errors.StructuralError("private key checksum failure") - } - privateKeyData = privateKeyData[:len(privateKeyData)-2] - return pk.parsePrivateKey(privateKeyData) - } - - pk.encryptedData = privateKeyData - return -} - -// Dummy returns true if the private key is a dummy key. This is a GNU extension. -func (pk *PrivateKey) Dummy() bool { - return pk.s2kParams.Dummy() -} - -func mod64kHash(d []byte) uint16 { - var h uint16 - for _, b := range d { - h += uint16(b) - } - return h -} - -func (pk *PrivateKey) Serialize(w io.Writer) (err error) { - contents := bytes.NewBuffer(nil) - err = pk.PublicKey.serializeWithoutHeaders(contents) - if err != nil { - return - } - if _, err = contents.Write([]byte{uint8(pk.s2kType)}); err != nil { - return - } - - optional := bytes.NewBuffer(nil) - if pk.Encrypted || pk.Dummy() { - optional.Write([]byte{uint8(pk.cipher)}) - if err := pk.s2kParams.Serialize(optional); err != nil { - return err - } - if pk.Encrypted { - optional.Write(pk.iv) - } - } - if pk.Version == 5 { - contents.Write([]byte{uint8(optional.Len())}) - } - io.Copy(contents, optional) - - if !pk.Dummy() { - l := 0 - var priv []byte - if !pk.Encrypted { - buf := bytes.NewBuffer(nil) - err = pk.serializePrivateKey(buf) - if err != nil { - return err - } - l = buf.Len() - checksum := mod64kHash(buf.Bytes()) - buf.Write([]byte{byte(checksum >> 8), byte(checksum)}) - priv = buf.Bytes() - } else { - priv, l = pk.encryptedData, len(pk.encryptedData) - } - - if pk.Version == 5 { - contents.Write([]byte{byte(l >> 24), byte(l >> 16), byte(l >> 8), byte(l)}) - } - contents.Write(priv) - } - - ptype := packetTypePrivateKey - if pk.IsSubkey { - ptype = packetTypePrivateSubkey - } - err = serializeHeader(w, ptype, contents.Len()) - if err != nil { - return - } - _, err = io.Copy(w, contents) - if err != nil { - return - } - return -} - -func serializeRSAPrivateKey(w io.Writer, priv *rsa.PrivateKey) error { - if _, err := w.Write(new(encoding.MPI).SetBig(priv.D).EncodedBytes()); err != nil { - return err - } - if _, err := w.Write(new(encoding.MPI).SetBig(priv.Primes[1]).EncodedBytes()); err != nil { - return err - } - if _, err := w.Write(new(encoding.MPI).SetBig(priv.Primes[0]).EncodedBytes()); err != nil { - return err - } - _, err := w.Write(new(encoding.MPI).SetBig(priv.Precomputed.Qinv).EncodedBytes()) - return err -} - -func serializeDSAPrivateKey(w io.Writer, priv *dsa.PrivateKey) error { - _, err := w.Write(new(encoding.MPI).SetBig(priv.X).EncodedBytes()) - return err -} - -func serializeElGamalPrivateKey(w io.Writer, priv *elgamal.PrivateKey) error { - _, err := w.Write(new(encoding.MPI).SetBig(priv.X).EncodedBytes()) - return err -} - -func serializeECDSAPrivateKey(w io.Writer, priv *ecdsa.PrivateKey) error { - _, err := w.Write(encoding.NewMPI(priv.MarshalIntegerSecret()).EncodedBytes()) - return err -} - -func serializeEdDSAPrivateKey(w io.Writer, priv *eddsa.PrivateKey) error { - _, err := w.Write(encoding.NewMPI(priv.MarshalByteSecret()).EncodedBytes()) - return err -} - -func serializeECDHPrivateKey(w io.Writer, priv *ecdh.PrivateKey) error { - _, err := w.Write(encoding.NewMPI(priv.MarshalByteSecret()).EncodedBytes()) - return err -} - -// Decrypt decrypts an encrypted private key using a passphrase. -func (pk *PrivateKey) Decrypt(passphrase []byte) error { - if pk.Dummy() { - return errors.ErrDummyPrivateKey("dummy key found") - } - if !pk.Encrypted { - return nil - } - - key := make([]byte, pk.cipher.KeySize()) - pk.s2k(key, passphrase) - block := pk.cipher.new(key) - cfb := cipher.NewCFBDecrypter(block, pk.iv) - - data := make([]byte, len(pk.encryptedData)) - cfb.XORKeyStream(data, pk.encryptedData) - - if pk.sha1Checksum { - if len(data) < sha1.Size { - return errors.StructuralError("truncated private key data") - } - h := sha1.New() - h.Write(data[:len(data)-sha1.Size]) - sum := h.Sum(nil) - if !bytes.Equal(sum, data[len(data)-sha1.Size:]) { - return errors.StructuralError("private key checksum failure") - } - data = data[:len(data)-sha1.Size] - } else { - if len(data) < 2 { - return errors.StructuralError("truncated private key data") - } - var sum uint16 - for i := 0; i < len(data)-2; i++ { - sum += uint16(data[i]) - } - if data[len(data)-2] != uint8(sum>>8) || - data[len(data)-1] != uint8(sum) { - return errors.StructuralError("private key checksum failure") - } - data = data[:len(data)-2] - } - - err := pk.parsePrivateKey(data) - if _, ok := err.(errors.KeyInvalidError); ok { - return errors.KeyInvalidError("invalid key parameters") - } - if err != nil { - return err - } - - // Mark key as unencrypted - pk.s2kType = S2KNON - pk.s2k = nil - pk.Encrypted = false - pk.encryptedData = nil - - return nil -} - -// Encrypt encrypts an unencrypted private key using a passphrase. -func (pk *PrivateKey) Encrypt(passphrase []byte) error { - priv := bytes.NewBuffer(nil) - err := pk.serializePrivateKey(priv) - if err != nil { - return err - } - - //Default config of private key encryption - pk.cipher = CipherAES256 - s2kConfig := &s2k.Config{ - S2KMode: 3, //Iterated - S2KCount: 65536, - Hash: crypto.SHA256, - } - - pk.s2kParams, err = s2k.Generate(rand.Reader, s2kConfig) - if err != nil { - return err - } - privateKeyBytes := priv.Bytes() - key := make([]byte, pk.cipher.KeySize()) - - pk.sha1Checksum = true - pk.s2k, err = pk.s2kParams.Function() - if err != nil { - return err - } - pk.s2k(key, passphrase) - block := pk.cipher.new(key) - pk.iv = make([]byte, pk.cipher.blockSize()) - _, err = rand.Read(pk.iv) - if err != nil { - return err - } - cfb := cipher.NewCFBEncrypter(block, pk.iv) - - if pk.sha1Checksum { - pk.s2kType = S2KSHA1 - h := sha1.New() - h.Write(privateKeyBytes) - sum := h.Sum(nil) - privateKeyBytes = append(privateKeyBytes, sum...) - } else { - pk.s2kType = S2KCHECKSUM - var sum uint16 - for _, b := range privateKeyBytes { - sum += uint16(b) - } - priv.Write([]byte{uint8(sum >> 8), uint8(sum)}) - } - - pk.encryptedData = make([]byte, len(privateKeyBytes)) - cfb.XORKeyStream(pk.encryptedData, privateKeyBytes) - pk.Encrypted = true - pk.PrivateKey = nil - return err -} - -func (pk *PrivateKey) serializePrivateKey(w io.Writer) (err error) { - switch priv := pk.PrivateKey.(type) { - case *rsa.PrivateKey: - err = serializeRSAPrivateKey(w, priv) - case *dsa.PrivateKey: - err = serializeDSAPrivateKey(w, priv) - case *elgamal.PrivateKey: - err = serializeElGamalPrivateKey(w, priv) - case *ecdsa.PrivateKey: - err = serializeECDSAPrivateKey(w, priv) - case *eddsa.PrivateKey: - err = serializeEdDSAPrivateKey(w, priv) - case *ecdh.PrivateKey: - err = serializeECDHPrivateKey(w, priv) - default: - err = errors.InvalidArgumentError("unknown private key type") - } - return -} - -func (pk *PrivateKey) parsePrivateKey(data []byte) (err error) { - switch pk.PublicKey.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoRSAEncryptOnly: - return pk.parseRSAPrivateKey(data) - case PubKeyAlgoDSA: - return pk.parseDSAPrivateKey(data) - case PubKeyAlgoElGamal: - return pk.parseElGamalPrivateKey(data) - case PubKeyAlgoECDSA: - return pk.parseECDSAPrivateKey(data) - case PubKeyAlgoECDH: - return pk.parseECDHPrivateKey(data) - case PubKeyAlgoEdDSA: - return pk.parseEdDSAPrivateKey(data) - } - panic("impossible") -} - -func (pk *PrivateKey) parseRSAPrivateKey(data []byte) (err error) { - rsaPub := pk.PublicKey.PublicKey.(*rsa.PublicKey) - rsaPriv := new(rsa.PrivateKey) - rsaPriv.PublicKey = *rsaPub - - buf := bytes.NewBuffer(data) - d := new(encoding.MPI) - if _, err := d.ReadFrom(buf); err != nil { - return err - } - - p := new(encoding.MPI) - if _, err := p.ReadFrom(buf); err != nil { - return err - } - - q := new(encoding.MPI) - if _, err := q.ReadFrom(buf); err != nil { - return err - } - - rsaPriv.D = new(big.Int).SetBytes(d.Bytes()) - rsaPriv.Primes = make([]*big.Int, 2) - rsaPriv.Primes[0] = new(big.Int).SetBytes(p.Bytes()) - rsaPriv.Primes[1] = new(big.Int).SetBytes(q.Bytes()) - if err := rsaPriv.Validate(); err != nil { - return errors.KeyInvalidError(err.Error()) - } - rsaPriv.Precompute() - pk.PrivateKey = rsaPriv - - return nil -} - -func (pk *PrivateKey) parseDSAPrivateKey(data []byte) (err error) { - dsaPub := pk.PublicKey.PublicKey.(*dsa.PublicKey) - dsaPriv := new(dsa.PrivateKey) - dsaPriv.PublicKey = *dsaPub - - buf := bytes.NewBuffer(data) - x := new(encoding.MPI) - if _, err := x.ReadFrom(buf); err != nil { - return err - } - - dsaPriv.X = new(big.Int).SetBytes(x.Bytes()) - if err := validateDSAParameters(dsaPriv); err != nil { - return err - } - pk.PrivateKey = dsaPriv - - return nil -} - -func (pk *PrivateKey) parseElGamalPrivateKey(data []byte) (err error) { - pub := pk.PublicKey.PublicKey.(*elgamal.PublicKey) - priv := new(elgamal.PrivateKey) - priv.PublicKey = *pub - - buf := bytes.NewBuffer(data) - x := new(encoding.MPI) - if _, err := x.ReadFrom(buf); err != nil { - return err - } - - priv.X = new(big.Int).SetBytes(x.Bytes()) - if err := validateElGamalParameters(priv); err != nil { - return err - } - pk.PrivateKey = priv - - return nil -} - -func (pk *PrivateKey) parseECDSAPrivateKey(data []byte) (err error) { - ecdsaPub := pk.PublicKey.PublicKey.(*ecdsa.PublicKey) - ecdsaPriv := ecdsa.NewPrivateKey(*ecdsaPub) - - buf := bytes.NewBuffer(data) - d := new(encoding.MPI) - if _, err := d.ReadFrom(buf); err != nil { - return err - } - - if err := ecdsaPriv.UnmarshalIntegerSecret(d.Bytes()); err != nil { - return err - } - if err := ecdsa.Validate(ecdsaPriv); err != nil { - return err - } - pk.PrivateKey = ecdsaPriv - - return nil -} - -func (pk *PrivateKey) parseECDHPrivateKey(data []byte) (err error) { - ecdhPub := pk.PublicKey.PublicKey.(*ecdh.PublicKey) - ecdhPriv := ecdh.NewPrivateKey(*ecdhPub) - - buf := bytes.NewBuffer(data) - d := new(encoding.MPI) - if _, err := d.ReadFrom(buf); err != nil { - return err - } - - if err := ecdhPriv.UnmarshalByteSecret(d.Bytes()); err != nil { - return err - } - - if err := ecdh.Validate(ecdhPriv); err != nil { - return err - } - - pk.PrivateKey = ecdhPriv - - return nil -} - -func (pk *PrivateKey) parseEdDSAPrivateKey(data []byte) (err error) { - eddsaPub := pk.PublicKey.PublicKey.(*eddsa.PublicKey) - eddsaPriv := eddsa.NewPrivateKey(*eddsaPub) - eddsaPriv.PublicKey = *eddsaPub - - buf := bytes.NewBuffer(data) - d := new(encoding.MPI) - if _, err := d.ReadFrom(buf); err != nil { - return err - } - - if err = eddsaPriv.UnmarshalByteSecret(d.Bytes()); err != nil { - return err - } - - if err := eddsa.Validate(eddsaPriv); err != nil { - return err - } - - pk.PrivateKey = eddsaPriv - - return nil -} - -func validateDSAParameters(priv *dsa.PrivateKey) error { - p := priv.P // group prime - q := priv.Q // subgroup order - g := priv.G // g has order q mod p - x := priv.X // secret - y := priv.Y // y == g**x mod p - one := big.NewInt(1) - // expect g, y >= 2 and g < p - if g.Cmp(one) <= 0 || y.Cmp(one) <= 0 || g.Cmp(p) > 0 { - return errors.KeyInvalidError("dsa: invalid group") - } - // expect p > q - if p.Cmp(q) <= 0 { - return errors.KeyInvalidError("dsa: invalid group prime") - } - // q should be large enough and divide p-1 - pSub1 := new(big.Int).Sub(p, one) - if q.BitLen() < 150 || new(big.Int).Mod(pSub1, q).Cmp(big.NewInt(0)) != 0 { - return errors.KeyInvalidError("dsa: invalid order") - } - // confirm that g has order q mod p - if !q.ProbablyPrime(32) || new(big.Int).Exp(g, q, p).Cmp(one) != 0 { - return errors.KeyInvalidError("dsa: invalid order") - } - // check y - if new(big.Int).Exp(g, x, p).Cmp(y) != 0 { - return errors.KeyInvalidError("dsa: mismatching values") - } - - return nil -} - -func validateElGamalParameters(priv *elgamal.PrivateKey) error { - p := priv.P // group prime - g := priv.G // g has order p-1 mod p - x := priv.X // secret - y := priv.Y // y == g**x mod p - one := big.NewInt(1) - // Expect g, y >= 2 and g < p - if g.Cmp(one) <= 0 || y.Cmp(one) <= 0 || g.Cmp(p) > 0 { - return errors.KeyInvalidError("elgamal: invalid group") - } - if p.BitLen() < 1024 { - return errors.KeyInvalidError("elgamal: group order too small") - } - pSub1 := new(big.Int).Sub(p, one) - if new(big.Int).Exp(g, pSub1, p).Cmp(one) != 0 { - return errors.KeyInvalidError("elgamal: invalid group") - } - // Since p-1 is not prime, g might have a smaller order that divides p-1. - // We cannot confirm the exact order of g, but we make sure it is not too small. - gExpI := new(big.Int).Set(g) - i := 1 - threshold := 2 << 17 // we want order > threshold - for i < threshold { - i++ // we check every order to make sure key validation is not easily bypassed by guessing y' - gExpI.Mod(new(big.Int).Mul(gExpI, g), p) - if gExpI.Cmp(one) == 0 { - return errors.KeyInvalidError("elgamal: order too small") - } - } - // Check y - if new(big.Int).Exp(g, x, p).Cmp(y) != 0 { - return errors.KeyInvalidError("elgamal: mismatching values") - } - - return nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/private_key_test_data.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/private_key_test_data.go deleted file mode 100644 index 029b8f1a..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/private_key_test_data.go +++ /dev/null @@ -1,12 +0,0 @@ -package packet - -// Generated with `gpg --export-secret-keys "Test Key 2"` -const privKeyRSAHex = "9501fe044cc349a8010400b70ca0010e98c090008d45d1ee8f9113bd5861fd57b88bacb7c68658747663f1e1a3b5a98f32fda6472373c024b97359cd2efc88ff60f77751adfbf6af5e615e6a1408cfad8bf0cea30b0d5f53aa27ad59089ba9b15b7ebc2777a25d7b436144027e3bcd203909f147d0e332b240cf63d3395f5dfe0df0a6c04e8655af7eacdf0011010001fe0303024a252e7d475fd445607de39a265472aa74a9320ba2dac395faa687e9e0336aeb7e9a7397e511b5afd9dc84557c80ac0f3d4d7bfec5ae16f20d41c8c84a04552a33870b930420e230e179564f6d19bb153145e76c33ae993886c388832b0fa042ddda7f133924f3854481533e0ede31d51278c0519b29abc3bf53da673e13e3e1214b52413d179d7f66deee35cac8eacb060f78379d70ef4af8607e68131ff529439668fc39c9ce6dfef8a5ac234d234802cbfb749a26107db26406213ae5c06d4673253a3cbee1fcbae58d6ab77e38d6e2c0e7c6317c48e054edadb5a40d0d48acb44643d998139a8a66bb820be1f3f80185bc777d14b5954b60effe2448a036d565c6bc0b915fcea518acdd20ab07bc1529f561c58cd044f723109b93f6fd99f876ff891d64306b5d08f48bab59f38695e9109c4dec34013ba3153488ce070268381ba923ee1eb77125b36afcb4347ec3478c8f2735b06ef17351d872e577fa95d0c397c88c71b59629a36aec" - -// Generated by `gpg --export-secret-keys` followed by a manual extraction of -// the ElGamal subkey from the packets. -const privKeyElGamalHex = "9d0157044df9ee1a100400eb8e136a58ec39b582629cdadf830bc64e0a94ed8103ca8bb247b27b11b46d1d25297ef4bcc3071785ba0c0bedfe89eabc5287fcc0edf81ab5896c1c8e4b20d27d79813c7aede75320b33eaeeaa586edc00fd1036c10133e6ba0ff277245d0d59d04b2b3421b7244aca5f4a8d870c6f1c1fbff9e1c26699a860b9504f35ca1d700030503fd1ededd3b840795be6d9ccbe3c51ee42e2f39233c432b831ddd9c4e72b7025a819317e47bf94f9ee316d7273b05d5fcf2999c3a681f519b1234bbfa6d359b4752bd9c3f77d6b6456cde152464763414ca130f4e91d91041432f90620fec0e6d6b5116076c2985d5aeaae13be492b9b329efcaf7ee25120159a0a30cd976b42d7afe030302dae7eb80db744d4960c4df930d57e87fe81412eaace9f900e6c839817a614ddb75ba6603b9417c33ea7b6c93967dfa2bcff3fa3c74a5ce2c962db65b03aece14c96cbd0038fc" - -// pkcs1PrivKeyHex is a PKCS#1, RSA private key. -// Generated by `openssl genrsa 1024 | openssl rsa -outform DER | xxd -p` -const pkcs1PrivKeyHex = "3082025d02010002818100e98edfa1c3b35884a54d0b36a6a603b0290fa85e49e30fa23fc94fef9c6790bc4849928607aa48d809da326fb42a969d06ad756b98b9c1a90f5d4a2b6d0ac05953c97f4da3120164a21a679793ce181c906dc01d235cc085ddcdf6ea06c389b6ab8885dfd685959e693138856a68a7e5db263337ff82a088d583a897cf2d59e9020301000102818100b6d5c9eb70b02d5369b3ee5b520a14490b5bde8a317d36f7e4c74b7460141311d1e5067735f8f01d6f5908b2b96fbd881f7a1ab9a84d82753e39e19e2d36856be960d05ac9ef8e8782ea1b6d65aee28fdfe1d61451e8cff0adfe84322f12cf455028b581cf60eb9e0e140ba5d21aeba6c2634d7c65318b9a665fc01c3191ca21024100fa5e818da3705b0fa33278bb28d4b6f6050388af2d4b75ec9375dd91ccf2e7d7068086a8b82a8f6282e4fbbdb8a7f2622eb97295249d87acea7f5f816f54d347024100eecf9406d7dc49cdfb95ab1eff4064de84c7a30f64b2798936a0d2018ba9eb52e4b636f82e96c49cc63b80b675e91e40d1b2e4017d4b9adaf33ab3d9cf1c214f024100c173704ace742c082323066226a4655226819a85304c542b9dacbeacbf5d1881ee863485fcf6f59f3a604f9b42289282067447f2b13dfeed3eab7851fc81e0550240741fc41f3fc002b382eed8730e33c5d8de40256e4accee846667f536832f711ab1d4590e7db91a8a116ac5bff3be13d3f9243ff2e976662aa9b395d907f8e9c9024046a5696c9ef882363e06c9fa4e2f5b580906452befba03f4a99d0f873697ef1f851d2226ca7934b30b7c3e80cb634a67172bbbf4781735fe3e09263e2dd723e7" diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/public_key.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/public_key.go deleted file mode 100644 index e0f5f74a..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/public_key.go +++ /dev/null @@ -1,802 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "crypto" - "crypto/dsa" - "crypto/rsa" - "crypto/sha1" - "crypto/sha256" - _ "crypto/sha512" - "encoding/binary" - "fmt" - "hash" - "io" - "math/big" - "strconv" - "time" - - "github.com/ProtonMail/go-crypto/openpgp/ecdh" - "github.com/ProtonMail/go-crypto/openpgp/ecdsa" - "github.com/ProtonMail/go-crypto/openpgp/eddsa" - "github.com/ProtonMail/go-crypto/openpgp/elgamal" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm" - "github.com/ProtonMail/go-crypto/openpgp/internal/ecc" - "github.com/ProtonMail/go-crypto/openpgp/internal/encoding" -) - -type kdfHashFunction byte -type kdfAlgorithm byte - -// PublicKey represents an OpenPGP public key. See RFC 4880, section 5.5.2. -type PublicKey struct { - Version int - CreationTime time.Time - PubKeyAlgo PublicKeyAlgorithm - PublicKey interface{} // *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey or *eddsa.PublicKey - Fingerprint []byte - KeyId uint64 - IsSubkey bool - - // RFC 4880 fields - n, e, p, q, g, y encoding.Field - - // RFC 6637 fields - // oid contains the OID byte sequence identifying the elliptic curve used - oid encoding.Field - - // kdf stores key derivation function parameters - // used for ECDH encryption. See RFC 6637, Section 9. - kdf encoding.Field -} - -// UpgradeToV5 updates the version of the key to v5, and updates all necessary -// fields. -func (pk *PublicKey) UpgradeToV5() { - pk.Version = 5 - pk.setFingerprintAndKeyId() -} - -// signingKey provides a convenient abstraction over signature verification -// for v3 and v4 public keys. -type signingKey interface { - SerializeForHash(io.Writer) error - SerializeSignaturePrefix(io.Writer) - serializeWithoutHeaders(io.Writer) error -} - -// NewRSAPublicKey returns a PublicKey that wraps the given rsa.PublicKey. -func NewRSAPublicKey(creationTime time.Time, pub *rsa.PublicKey) *PublicKey { - pk := &PublicKey{ - Version: 4, - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoRSA, - PublicKey: pub, - n: new(encoding.MPI).SetBig(pub.N), - e: new(encoding.MPI).SetBig(big.NewInt(int64(pub.E))), - } - - pk.setFingerprintAndKeyId() - return pk -} - -// NewDSAPublicKey returns a PublicKey that wraps the given dsa.PublicKey. -func NewDSAPublicKey(creationTime time.Time, pub *dsa.PublicKey) *PublicKey { - pk := &PublicKey{ - Version: 4, - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoDSA, - PublicKey: pub, - p: new(encoding.MPI).SetBig(pub.P), - q: new(encoding.MPI).SetBig(pub.Q), - g: new(encoding.MPI).SetBig(pub.G), - y: new(encoding.MPI).SetBig(pub.Y), - } - - pk.setFingerprintAndKeyId() - return pk -} - -// NewElGamalPublicKey returns a PublicKey that wraps the given elgamal.PublicKey. -func NewElGamalPublicKey(creationTime time.Time, pub *elgamal.PublicKey) *PublicKey { - pk := &PublicKey{ - Version: 4, - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoElGamal, - PublicKey: pub, - p: new(encoding.MPI).SetBig(pub.P), - g: new(encoding.MPI).SetBig(pub.G), - y: new(encoding.MPI).SetBig(pub.Y), - } - - pk.setFingerprintAndKeyId() - return pk -} - -func NewECDSAPublicKey(creationTime time.Time, pub *ecdsa.PublicKey) *PublicKey { - pk := &PublicKey{ - Version: 4, - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoECDSA, - PublicKey: pub, - p: encoding.NewMPI(pub.MarshalPoint()), - } - - curveInfo := ecc.FindByCurve(pub.GetCurve()) - if curveInfo == nil { - panic("unknown elliptic curve") - } - pk.oid = curveInfo.Oid - pk.setFingerprintAndKeyId() - return pk -} - -func NewECDHPublicKey(creationTime time.Time, pub *ecdh.PublicKey) *PublicKey { - var pk *PublicKey - var kdf = encoding.NewOID([]byte{0x1, pub.Hash.Id(), pub.Cipher.Id()}) - pk = &PublicKey{ - Version: 4, - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoECDH, - PublicKey: pub, - p: encoding.NewMPI(pub.MarshalPoint()), - kdf: kdf, - } - - curveInfo := ecc.FindByCurve(pub.GetCurve()) - - if curveInfo == nil { - panic("unknown elliptic curve") - } - - pk.oid = curveInfo.Oid - pk.setFingerprintAndKeyId() - return pk -} - -func NewEdDSAPublicKey(creationTime time.Time, pub *eddsa.PublicKey) *PublicKey { - curveInfo := ecc.FindByCurve(pub.GetCurve()) - pk := &PublicKey{ - Version: 4, - CreationTime: creationTime, - PubKeyAlgo: PubKeyAlgoEdDSA, - PublicKey: pub, - oid: curveInfo.Oid, - // Native point format, see draft-koch-eddsa-for-openpgp-04, Appendix B - p: encoding.NewMPI(pub.MarshalPoint()), - } - - pk.setFingerprintAndKeyId() - return pk -} - -func (pk *PublicKey) parse(r io.Reader) (err error) { - // RFC 4880, section 5.5.2 - var buf [6]byte - _, err = readFull(r, buf[:]) - if err != nil { - return - } - if buf[0] != 4 && buf[0] != 5 { - return errors.UnsupportedError("public key version " + strconv.Itoa(int(buf[0]))) - } - - pk.Version = int(buf[0]) - if pk.Version == 5 { - var n [4]byte - _, err = readFull(r, n[:]) - if err != nil { - return - } - } - pk.CreationTime = time.Unix(int64(uint32(buf[1])<<24|uint32(buf[2])<<16|uint32(buf[3])<<8|uint32(buf[4])), 0) - pk.PubKeyAlgo = PublicKeyAlgorithm(buf[5]) - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - err = pk.parseRSA(r) - case PubKeyAlgoDSA: - err = pk.parseDSA(r) - case PubKeyAlgoElGamal: - err = pk.parseElGamal(r) - case PubKeyAlgoECDSA: - err = pk.parseECDSA(r) - case PubKeyAlgoECDH: - err = pk.parseECDH(r) - case PubKeyAlgoEdDSA: - err = pk.parseEdDSA(r) - default: - err = errors.UnsupportedError("public key type: " + strconv.Itoa(int(pk.PubKeyAlgo))) - } - if err != nil { - return - } - - pk.setFingerprintAndKeyId() - return -} - -func (pk *PublicKey) setFingerprintAndKeyId() { - // RFC 4880, section 12.2 - if pk.Version == 5 { - fingerprint := sha256.New() - pk.SerializeForHash(fingerprint) - pk.Fingerprint = make([]byte, 32) - copy(pk.Fingerprint, fingerprint.Sum(nil)) - pk.KeyId = binary.BigEndian.Uint64(pk.Fingerprint[:8]) - } else { - fingerprint := sha1.New() - pk.SerializeForHash(fingerprint) - pk.Fingerprint = make([]byte, 20) - copy(pk.Fingerprint, fingerprint.Sum(nil)) - pk.KeyId = binary.BigEndian.Uint64(pk.Fingerprint[12:20]) - } -} - -// parseRSA parses RSA public key material from the given Reader. See RFC 4880, -// section 5.5.2. -func (pk *PublicKey) parseRSA(r io.Reader) (err error) { - pk.n = new(encoding.MPI) - if _, err = pk.n.ReadFrom(r); err != nil { - return - } - pk.e = new(encoding.MPI) - if _, err = pk.e.ReadFrom(r); err != nil { - return - } - - if len(pk.e.Bytes()) > 3 { - err = errors.UnsupportedError("large public exponent") - return - } - rsa := &rsa.PublicKey{ - N: new(big.Int).SetBytes(pk.n.Bytes()), - E: 0, - } - for i := 0; i < len(pk.e.Bytes()); i++ { - rsa.E <<= 8 - rsa.E |= int(pk.e.Bytes()[i]) - } - pk.PublicKey = rsa - return -} - -// parseDSA parses DSA public key material from the given Reader. See RFC 4880, -// section 5.5.2. -func (pk *PublicKey) parseDSA(r io.Reader) (err error) { - pk.p = new(encoding.MPI) - if _, err = pk.p.ReadFrom(r); err != nil { - return - } - pk.q = new(encoding.MPI) - if _, err = pk.q.ReadFrom(r); err != nil { - return - } - pk.g = new(encoding.MPI) - if _, err = pk.g.ReadFrom(r); err != nil { - return - } - pk.y = new(encoding.MPI) - if _, err = pk.y.ReadFrom(r); err != nil { - return - } - - dsa := new(dsa.PublicKey) - dsa.P = new(big.Int).SetBytes(pk.p.Bytes()) - dsa.Q = new(big.Int).SetBytes(pk.q.Bytes()) - dsa.G = new(big.Int).SetBytes(pk.g.Bytes()) - dsa.Y = new(big.Int).SetBytes(pk.y.Bytes()) - pk.PublicKey = dsa - return -} - -// parseElGamal parses ElGamal public key material from the given Reader. See -// RFC 4880, section 5.5.2. -func (pk *PublicKey) parseElGamal(r io.Reader) (err error) { - pk.p = new(encoding.MPI) - if _, err = pk.p.ReadFrom(r); err != nil { - return - } - pk.g = new(encoding.MPI) - if _, err = pk.g.ReadFrom(r); err != nil { - return - } - pk.y = new(encoding.MPI) - if _, err = pk.y.ReadFrom(r); err != nil { - return - } - - elgamal := new(elgamal.PublicKey) - elgamal.P = new(big.Int).SetBytes(pk.p.Bytes()) - elgamal.G = new(big.Int).SetBytes(pk.g.Bytes()) - elgamal.Y = new(big.Int).SetBytes(pk.y.Bytes()) - pk.PublicKey = elgamal - return -} - -// parseECDSA parses ECDSA public key material from the given Reader. See -// RFC 6637, Section 9. -func (pk *PublicKey) parseECDSA(r io.Reader) (err error) { - pk.oid = new(encoding.OID) - if _, err = pk.oid.ReadFrom(r); err != nil { - return - } - pk.p = new(encoding.MPI) - if _, err = pk.p.ReadFrom(r); err != nil { - return - } - - curveInfo := ecc.FindByOid(pk.oid) - if curveInfo == nil { - return errors.UnsupportedError(fmt.Sprintf("unknown oid: %x", pk.oid)) - } - - c, ok := curveInfo.Curve.(ecc.ECDSACurve) - if !ok { - return errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", pk.oid)) - } - - ecdsaKey := ecdsa.NewPublicKey(c) - err = ecdsaKey.UnmarshalPoint(pk.p.Bytes()) - pk.PublicKey = ecdsaKey - - return -} - -// parseECDH parses ECDH public key material from the given Reader. See -// RFC 6637, Section 9. -func (pk *PublicKey) parseECDH(r io.Reader) (err error) { - pk.oid = new(encoding.OID) - if _, err = pk.oid.ReadFrom(r); err != nil { - return - } - pk.p = new(encoding.MPI) - if _, err = pk.p.ReadFrom(r); err != nil { - return - } - pk.kdf = new(encoding.OID) - if _, err = pk.kdf.ReadFrom(r); err != nil { - return - } - - curveInfo := ecc.FindByOid(pk.oid) - - if curveInfo == nil { - return errors.UnsupportedError(fmt.Sprintf("unknown oid: %x", pk.oid)) - } - - c, ok := curveInfo.Curve.(ecc.ECDHCurve) - if !ok { - return errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", pk.oid)) - } - - if kdfLen := len(pk.kdf.Bytes()); kdfLen < 3 { - return errors.UnsupportedError("unsupported ECDH KDF length: " + strconv.Itoa(kdfLen)) - } - if reserved := pk.kdf.Bytes()[0]; reserved != 0x01 { - return errors.UnsupportedError("unsupported KDF reserved field: " + strconv.Itoa(int(reserved))) - } - kdfHash, ok := algorithm.HashById[pk.kdf.Bytes()[1]] - if !ok { - return errors.UnsupportedError("unsupported ECDH KDF hash: " + strconv.Itoa(int(pk.kdf.Bytes()[1]))) - } - kdfCipher, ok := algorithm.CipherById[pk.kdf.Bytes()[2]] - if !ok { - return errors.UnsupportedError("unsupported ECDH KDF cipher: " + strconv.Itoa(int(pk.kdf.Bytes()[2]))) - } - - ecdhKey := ecdh.NewPublicKey(c, kdfHash, kdfCipher) - err = ecdhKey.UnmarshalPoint(pk.p.Bytes()) - pk.PublicKey = ecdhKey - - return -} - -func (pk *PublicKey) parseEdDSA(r io.Reader) (err error) { - pk.oid = new(encoding.OID) - if _, err = pk.oid.ReadFrom(r); err != nil { - return - } - curveInfo := ecc.FindByOid(pk.oid) - if curveInfo == nil { - return errors.UnsupportedError(fmt.Sprintf("unknown oid: %x", pk.oid)) - } - - c, ok := curveInfo.Curve.(ecc.EdDSACurve) - if !ok { - return errors.UnsupportedError(fmt.Sprintf("unsupported oid: %x", pk.oid)) - } - - pk.p = new(encoding.MPI) - if _, err = pk.p.ReadFrom(r); err != nil { - return - } - - pub := eddsa.NewPublicKey(c) - - switch flag := pk.p.Bytes()[0]; flag { - case 0x04: - // TODO: see _grcy_ecc_eddsa_ensure_compact in grcypt - return errors.UnsupportedError("unsupported EdDSA compression: " + strconv.Itoa(int(flag))) - case 0x40: - err = pub.UnmarshalPoint(pk.p.Bytes()) - default: - return errors.UnsupportedError("unsupported EdDSA compression: " + strconv.Itoa(int(flag))) - } - - pk.PublicKey = pub - return -} - -// SerializeForHash serializes the PublicKey to w with the special packet -// header format needed for hashing. -func (pk *PublicKey) SerializeForHash(w io.Writer) error { - pk.SerializeSignaturePrefix(w) - return pk.serializeWithoutHeaders(w) -} - -// SerializeSignaturePrefix writes the prefix for this public key to the given Writer. -// The prefix is used when calculating a signature over this public key. See -// RFC 4880, section 5.2.4. -func (pk *PublicKey) SerializeSignaturePrefix(w io.Writer) { - var pLength = pk.algorithmSpecificByteCount() - if pk.Version == 5 { - pLength += 10 // version, timestamp (4), algorithm, key octet count (4). - w.Write([]byte{ - 0x9A, - byte(pLength >> 24), - byte(pLength >> 16), - byte(pLength >> 8), - byte(pLength), - }) - return - } - pLength += 6 - w.Write([]byte{0x99, byte(pLength >> 8), byte(pLength)}) -} - -func (pk *PublicKey) Serialize(w io.Writer) (err error) { - length := 6 // 6 byte header - length += pk.algorithmSpecificByteCount() - if pk.Version == 5 { - length += 4 // octet key count - } - packetType := packetTypePublicKey - if pk.IsSubkey { - packetType = packetTypePublicSubkey - } - err = serializeHeader(w, packetType, length) - if err != nil { - return - } - return pk.serializeWithoutHeaders(w) -} - -func (pk *PublicKey) algorithmSpecificByteCount() int { - length := 0 - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - length += int(pk.n.EncodedLength()) - length += int(pk.e.EncodedLength()) - case PubKeyAlgoDSA: - length += int(pk.p.EncodedLength()) - length += int(pk.q.EncodedLength()) - length += int(pk.g.EncodedLength()) - length += int(pk.y.EncodedLength()) - case PubKeyAlgoElGamal: - length += int(pk.p.EncodedLength()) - length += int(pk.g.EncodedLength()) - length += int(pk.y.EncodedLength()) - case PubKeyAlgoECDSA: - length += int(pk.oid.EncodedLength()) - length += int(pk.p.EncodedLength()) - case PubKeyAlgoECDH: - length += int(pk.oid.EncodedLength()) - length += int(pk.p.EncodedLength()) - length += int(pk.kdf.EncodedLength()) - case PubKeyAlgoEdDSA: - length += int(pk.oid.EncodedLength()) - length += int(pk.p.EncodedLength()) - default: - panic("unknown public key algorithm") - } - return length -} - -// serializeWithoutHeaders marshals the PublicKey to w in the form of an -// OpenPGP public key packet, not including the packet header. -func (pk *PublicKey) serializeWithoutHeaders(w io.Writer) (err error) { - t := uint32(pk.CreationTime.Unix()) - if _, err = w.Write([]byte{ - byte(pk.Version), - byte(t >> 24), byte(t >> 16), byte(t >> 8), byte(t), - byte(pk.PubKeyAlgo), - }); err != nil { - return - } - - if pk.Version == 5 { - n := pk.algorithmSpecificByteCount() - if _, err = w.Write([]byte{ - byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n), - }); err != nil { - return - } - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - if _, err = w.Write(pk.n.EncodedBytes()); err != nil { - return - } - _, err = w.Write(pk.e.EncodedBytes()) - return - case PubKeyAlgoDSA: - if _, err = w.Write(pk.p.EncodedBytes()); err != nil { - return - } - if _, err = w.Write(pk.q.EncodedBytes()); err != nil { - return - } - if _, err = w.Write(pk.g.EncodedBytes()); err != nil { - return - } - _, err = w.Write(pk.y.EncodedBytes()) - return - case PubKeyAlgoElGamal: - if _, err = w.Write(pk.p.EncodedBytes()); err != nil { - return - } - if _, err = w.Write(pk.g.EncodedBytes()); err != nil { - return - } - _, err = w.Write(pk.y.EncodedBytes()) - return - case PubKeyAlgoECDSA: - if _, err = w.Write(pk.oid.EncodedBytes()); err != nil { - return - } - _, err = w.Write(pk.p.EncodedBytes()) - return - case PubKeyAlgoECDH: - if _, err = w.Write(pk.oid.EncodedBytes()); err != nil { - return - } - if _, err = w.Write(pk.p.EncodedBytes()); err != nil { - return - } - _, err = w.Write(pk.kdf.EncodedBytes()) - return - case PubKeyAlgoEdDSA: - if _, err = w.Write(pk.oid.EncodedBytes()); err != nil { - return - } - _, err = w.Write(pk.p.EncodedBytes()) - return - } - return errors.InvalidArgumentError("bad public-key algorithm") -} - -// CanSign returns true iff this public key can generate signatures -func (pk *PublicKey) CanSign() bool { - return pk.PubKeyAlgo != PubKeyAlgoRSAEncryptOnly && pk.PubKeyAlgo != PubKeyAlgoElGamal && pk.PubKeyAlgo != PubKeyAlgoECDH -} - -// VerifySignature returns nil iff sig is a valid signature, made by this -// public key, of the data hashed into signed. signed is mutated by this call. -func (pk *PublicKey) VerifySignature(signed hash.Hash, sig *Signature) (err error) { - if !pk.CanSign() { - return errors.InvalidArgumentError("public key cannot generate signatures") - } - if sig.Version == 5 && (sig.SigType == 0x00 || sig.SigType == 0x01) { - sig.AddMetadataToHashSuffix() - } - signed.Write(sig.HashSuffix) - hashBytes := signed.Sum(nil) - if hashBytes[0] != sig.HashTag[0] || hashBytes[1] != sig.HashTag[1] { - return errors.SignatureError("hash tag doesn't match") - } - - if pk.PubKeyAlgo != sig.PubKeyAlgo { - return errors.InvalidArgumentError("public key and signature use different algorithms") - } - - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - rsaPublicKey, _ := pk.PublicKey.(*rsa.PublicKey) - err = rsa.VerifyPKCS1v15(rsaPublicKey, sig.Hash, hashBytes, padToKeySize(rsaPublicKey, sig.RSASignature.Bytes())) - if err != nil { - return errors.SignatureError("RSA verification failure") - } - return nil - case PubKeyAlgoDSA: - dsaPublicKey, _ := pk.PublicKey.(*dsa.PublicKey) - // Need to truncate hashBytes to match FIPS 186-3 section 4.6. - subgroupSize := (dsaPublicKey.Q.BitLen() + 7) / 8 - if len(hashBytes) > subgroupSize { - hashBytes = hashBytes[:subgroupSize] - } - if !dsa.Verify(dsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.DSASigR.Bytes()), new(big.Int).SetBytes(sig.DSASigS.Bytes())) { - return errors.SignatureError("DSA verification failure") - } - return nil - case PubKeyAlgoECDSA: - ecdsaPublicKey := pk.PublicKey.(*ecdsa.PublicKey) - if !ecdsa.Verify(ecdsaPublicKey, hashBytes, new(big.Int).SetBytes(sig.ECDSASigR.Bytes()), new(big.Int).SetBytes(sig.ECDSASigS.Bytes())) { - return errors.SignatureError("ECDSA verification failure") - } - return nil - case PubKeyAlgoEdDSA: - eddsaPublicKey := pk.PublicKey.(*eddsa.PublicKey) - if !eddsa.Verify(eddsaPublicKey, hashBytes, sig.EdDSASigR.Bytes(), sig.EdDSASigS.Bytes()) { - return errors.SignatureError("EdDSA verification failure") - } - return nil - default: - return errors.SignatureError("Unsupported public key algorithm used in signature") - } -} - -// keySignatureHash returns a Hash of the message that needs to be signed for -// pk to assert a subkey relationship to signed. -func keySignatureHash(pk, signed signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) { - if !hashFunc.Available() { - return nil, errors.UnsupportedError("hash function") - } - h = hashFunc.New() - - // RFC 4880, section 5.2.4 - err = pk.SerializeForHash(h) - if err != nil { - return nil, err - } - - err = signed.SerializeForHash(h) - return -} - -// VerifyKeySignature returns nil iff sig is a valid signature, made by this -// public key, of signed. -func (pk *PublicKey) VerifyKeySignature(signed *PublicKey, sig *Signature) error { - h, err := keySignatureHash(pk, signed, sig.Hash) - if err != nil { - return err - } - if err = pk.VerifySignature(h, sig); err != nil { - return err - } - - if sig.FlagSign { - // Signing subkeys must be cross-signed. See - // https://www.gnupg.org/faq/subkey-cross-certify.html. - if sig.EmbeddedSignature == nil { - return errors.StructuralError("signing subkey is missing cross-signature") - } - // Verify the cross-signature. This is calculated over the same - // data as the main signature, so we cannot just recursively - // call signed.VerifyKeySignature(...) - if h, err = keySignatureHash(pk, signed, sig.EmbeddedSignature.Hash); err != nil { - return errors.StructuralError("error while hashing for cross-signature: " + err.Error()) - } - if err := signed.VerifySignature(h, sig.EmbeddedSignature); err != nil { - return errors.StructuralError("error while verifying cross-signature: " + err.Error()) - } - } - - return nil -} - -func keyRevocationHash(pk signingKey, hashFunc crypto.Hash) (h hash.Hash, err error) { - if !hashFunc.Available() { - return nil, errors.UnsupportedError("hash function") - } - h = hashFunc.New() - - // RFC 4880, section 5.2.4 - err = pk.SerializeForHash(h) - - return -} - -// VerifyRevocationSignature returns nil iff sig is a valid signature, made by this -// public key. -func (pk *PublicKey) VerifyRevocationSignature(sig *Signature) (err error) { - h, err := keyRevocationHash(pk, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignature(h, sig) -} - -// VerifySubkeyRevocationSignature returns nil iff sig is a valid subkey revocation signature, -// made by this public key, of signed. -func (pk *PublicKey) VerifySubkeyRevocationSignature(sig *Signature, signed *PublicKey) (err error) { - h, err := keySignatureHash(pk, signed, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignature(h, sig) -} - -// userIdSignatureHash returns a Hash of the message that needs to be signed -// to assert that pk is a valid key for id. -func userIdSignatureHash(id string, pk *PublicKey, hashFunc crypto.Hash) (h hash.Hash, err error) { - if !hashFunc.Available() { - return nil, errors.UnsupportedError("hash function") - } - h = hashFunc.New() - - // RFC 4880, section 5.2.4 - pk.SerializeSignaturePrefix(h) - pk.serializeWithoutHeaders(h) - - var buf [5]byte - buf[0] = 0xb4 - buf[1] = byte(len(id) >> 24) - buf[2] = byte(len(id) >> 16) - buf[3] = byte(len(id) >> 8) - buf[4] = byte(len(id)) - h.Write(buf[:]) - h.Write([]byte(id)) - - return -} - -// VerifyUserIdSignature returns nil iff sig is a valid signature, made by this -// public key, that id is the identity of pub. -func (pk *PublicKey) VerifyUserIdSignature(id string, pub *PublicKey, sig *Signature) (err error) { - h, err := userIdSignatureHash(id, pub, sig.Hash) - if err != nil { - return err - } - return pk.VerifySignature(h, sig) -} - -// KeyIdString returns the public key's fingerprint in capital hex -// (e.g. "6C7EE1B8621CC013"). -func (pk *PublicKey) KeyIdString() string { - return fmt.Sprintf("%X", pk.Fingerprint[12:20]) -} - -// KeyIdShortString returns the short form of public key's fingerprint -// in capital hex, as shown by gpg --list-keys (e.g. "621CC013"). -func (pk *PublicKey) KeyIdShortString() string { - return fmt.Sprintf("%X", pk.Fingerprint[16:20]) -} - -// BitLength returns the bit length for the given public key. -func (pk *PublicKey) BitLength() (bitLength uint16, err error) { - switch pk.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSAEncryptOnly, PubKeyAlgoRSASignOnly: - bitLength = pk.n.BitLength() - case PubKeyAlgoDSA: - bitLength = pk.p.BitLength() - case PubKeyAlgoElGamal: - bitLength = pk.p.BitLength() - case PubKeyAlgoECDSA: - bitLength = pk.p.BitLength() - case PubKeyAlgoECDH: - bitLength = pk.p.BitLength() - case PubKeyAlgoEdDSA: - bitLength = pk.p.BitLength() - default: - err = errors.InvalidArgumentError("bad public-key algorithm") - } - return -} - -// KeyExpired returns whether sig is a self-signature of a key that has -// expired or is created in the future. -func (pk *PublicKey) KeyExpired(sig *Signature, currentTime time.Time) bool { - if pk.CreationTime.After(currentTime) { - return true - } - if sig.KeyLifetimeSecs == nil || *sig.KeyLifetimeSecs == 0 { - return false - } - expiry := pk.CreationTime.Add(time.Duration(*sig.KeyLifetimeSecs) * time.Second) - return currentTime.After(expiry) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/public_key_test_data.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/public_key_test_data.go deleted file mode 100644 index b255f1f6..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/public_key_test_data.go +++ /dev/null @@ -1,24 +0,0 @@ -package packet - -const rsaFingerprintHex = "5fb74b1d03b1e3cb31bc2f8aa34d7e18c20c31bb" - -const rsaPkDataHex = "988d044d3c5c10010400b1d13382944bd5aba23a4312968b5095d14f947f600eb478e14a6fcb16b0e0cac764884909c020bc495cfcc39a935387c661507bdb236a0612fb582cac3af9b29cc2c8c70090616c41b662f4da4c1201e195472eb7f4ae1ccbcbf9940fe21d985e379a5563dde5b9a23d35f1cfaa5790da3b79db26f23695107bfaca8e7b5bcd0011010001" - -const dsaFingerprintHex = "eece4c094db002103714c63c8e8fbe54062f19ed" - -const dsaPkDataHex = "9901a2044d432f89110400cd581334f0d7a1e1bdc8b9d6d8c0baf68793632735d2bb0903224cbaa1dfbf35a60ee7a13b92643421e1eb41aa8d79bea19a115a677f6b8ba3c7818ce53a6c2a24a1608bd8b8d6e55c5090cbde09dd26e356267465ae25e69ec8bdd57c7bbb2623e4d73336f73a0a9098f7f16da2e25252130fd694c0e8070c55a812a423ae7f00a0ebf50e70c2f19c3520a551bd4b08d30f23530d3d03ff7d0bf4a53a64a09dc5e6e6e35854b7d70c882b0c60293401958b1bd9e40abec3ea05ba87cf64899299d4bd6aa7f459c201d3fbbd6c82004bdc5e8a9eb8082d12054cc90fa9d4ec251a843236a588bf49552441817436c4f43326966fe85447d4e6d0acf8fa1ef0f014730770603ad7634c3088dc52501c237328417c31c89ed70400b2f1a98b0bf42f11fefc430704bebbaa41d9f355600c3facee1e490f64208e0e094ea55e3a598a219a58500bf78ac677b670a14f4e47e9cf8eab4f368cc1ddcaa18cc59309d4cc62dd4f680e73e6cc3e1ce87a84d0925efbcb26c575c093fc42eecf45135fabf6403a25c2016e1774c0484e440a18319072c617cc97ac0a3bb0" - -const ecdsaFingerprintHex = "9892270b38b8980b05c8d56d43fe956c542ca00b" - -const ecdsaPkDataHex = "9893045071c29413052b8104002304230401f4867769cedfa52c325018896245443968e52e51d0c2df8d939949cb5b330f2921711fbee1c9b9dddb95d15cb0255e99badeddda7cc23d9ddcaacbc290969b9f24019375d61c2e4e3b36953a28d8b2bc95f78c3f1d592fb24499be348656a7b17e3963187b4361afe497bc5f9f81213f04069f8e1fb9e6a6290ae295ca1a92b894396cb4" - -const ecdhFingerprintHex = "722354df2475a42164d1d49faa8b938f9a201946" - -const ecdhPkDataHex = "b90073044d53059212052b810400220303042faa84024a20b6735c4897efa5bfb41bf85b7eefeab5ca0cb9ffc8ea04a46acb25534a577694f9e25340a4ab5223a9dd1eda530c8aa2e6718db10d7e672558c7736fe09369ea5739a2a3554bf16d41faa50562f11c6d39bbd5dffb6b9a9ec91803010909" - -const eddsaFingerprintHex = "b2d5e5ec0e6deca6bc8eeeb00907e75e1dd99ad8" - -const eddsaPkDataHex = "98330456e2132b16092b06010401da470f01010740bbda39266affa511a8c2d02edf690fb784b0499c4406185811a163539ef11dc1b41d74657374696e67203c74657374696e674074657374696e672e636f6d3e8879041316080021050256e2132b021b03050b09080702061508090a0b020416020301021e01021780000a09100907e75e1dd99ad86d0c00fe39d2008359352782bc9b61ac382584cd8eff3f57a18c2287e3afeeb05d1f04ba00fe2d0bc1ddf3ff8adb9afa3e7d9287244b4ec567f3db4d60b74a9b5465ed528203" - -// Source: https://sites.google.com/site/brainhub/pgpecckeys#TOC-ECC-NIST-P-384-key -const ecc384PubHex = `99006f044d53059213052b81040022030304f6b8c5aced5b84ef9f4a209db2e4a9dfb70d28cb8c10ecd57674a9fa5a67389942b62d5e51367df4c7bfd3f8e500feecf07ed265a621a8ebbbe53e947ec78c677eba143bd1533c2b350e1c29f82313e1e1108eba063be1e64b10e6950e799c2db42465635f6473615f64685f333834203c6f70656e70677040627261696e6875622e6f72673e8900cb04101309005305024d530592301480000000002000077072656665727265642d656d61696c2d656e636f64696e67407067702e636f6d7067706d696d65040b090807021901051b03000000021602051e010000000415090a08000a0910098033880f54719fca2b0180aa37350968bd5f115afd8ce7bc7b103822152dbff06d0afcda835329510905b98cb469ba208faab87c7412b799e7b633017f58364ea480e8a1a3f253a0c5f22c446e8be9a9fce6210136ee30811abbd49139de28b5bdf8dc36d06ae748579e9ff503b90073044d53059212052b810400220303042faa84024a20b6735c4897efa5bfb41bf85b7eefeab5ca0cb9ffc8ea04a46acb25534a577694f9e25340a4ab5223a9dd1eda530c8aa2e6718db10d7e672558c7736fe09369ea5739a2a3554bf16d41faa50562f11c6d39bbd5dffb6b9a9ec9180301090989008404181309000c05024d530592051b0c000000000a0910098033880f54719f80970180eee7a6d8fcee41ee4f9289df17f9bcf9d955dca25c583b94336f3a2b2d4986dc5cf417b8d2dc86f741a9e1a6d236c0e3017d1c76575458a0cfb93ae8a2b274fcc65ceecd7a91eec83656ba13219969f06945b48c56bd04152c3a0553c5f2f4bd1267` diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/reader.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/reader.go deleted file mode 100644 index 10215fe5..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/reader.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "io" - - "github.com/ProtonMail/go-crypto/openpgp/errors" -) - -// Reader reads packets from an io.Reader and allows packets to be 'unread' so -// that they result from the next call to Next. -type Reader struct { - q []Packet - readers []io.Reader -} - -// New io.Readers are pushed when a compressed or encrypted packet is processed -// and recursively treated as a new source of packets. However, a carefully -// crafted packet can trigger an infinite recursive sequence of packets. See -// http://mumble.net/~campbell/misc/pgp-quine -// https://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2013-4402 -// This constant limits the number of recursive packets that may be pushed. -const maxReaders = 32 - -// Next returns the most recently unread Packet, or reads another packet from -// the top-most io.Reader. Unknown packet types are skipped. -func (r *Reader) Next() (p Packet, err error) { - if len(r.q) > 0 { - p = r.q[len(r.q)-1] - r.q = r.q[:len(r.q)-1] - return - } - - for len(r.readers) > 0 { - p, err = Read(r.readers[len(r.readers)-1]) - if err == nil { - return - } - if err == io.EOF { - r.readers = r.readers[:len(r.readers)-1] - continue - } - // TODO: Add strict mode that rejects unknown packets, instead of ignoring them. - if _, ok := err.(errors.UnknownPacketTypeError); ok { - continue - } - if _, ok := err.(errors.UnsupportedError); ok { - switch p.(type) { - case *SymmetricallyEncrypted, *AEADEncrypted, *Compressed, *LiteralData: - return nil, err - } - continue - } - return nil, err - } - - return nil, io.EOF -} - -// Push causes the Reader to start reading from a new io.Reader. When an EOF -// error is seen from the new io.Reader, it is popped and the Reader continues -// to read from the next most recent io.Reader. Push returns a StructuralError -// if pushing the reader would exceed the maximum recursion level, otherwise it -// returns nil. -func (r *Reader) Push(reader io.Reader) (err error) { - if len(r.readers) >= maxReaders { - return errors.StructuralError("too many layers of packets") - } - r.readers = append(r.readers, reader) - return nil -} - -// Unread causes the given Packet to be returned from the next call to Next. -func (r *Reader) Unread(p Packet) { - r.q = append(r.q, p) -} - -func NewReader(r io.Reader) *Reader { - return &Reader{ - q: nil, - readers: []io.Reader{r}, - } -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/signature.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/signature.go deleted file mode 100644 index 9f0b1b19..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/signature.go +++ /dev/null @@ -1,1068 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "bytes" - "crypto" - "crypto/dsa" - "encoding/binary" - "hash" - "io" - "strconv" - "time" - - "github.com/ProtonMail/go-crypto/openpgp/ecdsa" - "github.com/ProtonMail/go-crypto/openpgp/eddsa" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm" - "github.com/ProtonMail/go-crypto/openpgp/internal/encoding" -) - -const ( - // See RFC 4880, section 5.2.3.21 for details. - KeyFlagCertify = 1 << iota - KeyFlagSign - KeyFlagEncryptCommunications - KeyFlagEncryptStorage - KeyFlagSplitKey - KeyFlagAuthenticate - _ - KeyFlagGroupKey -) - -// Signature represents a signature. See RFC 4880, section 5.2. -type Signature struct { - Version int - SigType SignatureType - PubKeyAlgo PublicKeyAlgorithm - Hash crypto.Hash - - // HashSuffix is extra data that is hashed in after the signed data. - HashSuffix []byte - // HashTag contains the first two bytes of the hash for fast rejection - // of bad signed data. - HashTag [2]byte - - // Metadata includes format, filename and time, and is protected by v5 - // signatures of type 0x00 or 0x01. This metadata is included into the hash - // computation; if nil, six 0x00 bytes are used instead. See section 5.2.4. - Metadata *LiteralData - - CreationTime time.Time - - RSASignature encoding.Field - DSASigR, DSASigS encoding.Field - ECDSASigR, ECDSASigS encoding.Field - EdDSASigR, EdDSASigS encoding.Field - - // rawSubpackets contains the unparsed subpackets, in order. - rawSubpackets []outputSubpacket - - // The following are optional so are nil when not included in the - // signature. - - SigLifetimeSecs, KeyLifetimeSecs *uint32 - PreferredSymmetric, PreferredHash, PreferredCompression []uint8 - PreferredCipherSuites [][2]uint8 - IssuerKeyId *uint64 - IssuerFingerprint []byte - SignerUserId *string - IsPrimaryId *bool - Notations []*Notation - - // TrustLevel and TrustAmount can be set by the signer to assert that - // the key is not only valid but also trustworthy at the specified - // level. - // See RFC 4880, section 5.2.3.13 for details. - TrustLevel TrustLevel - TrustAmount TrustAmount - - // TrustRegularExpression can be used in conjunction with trust Signature - // packets to limit the scope of the trust that is extended. - // See RFC 4880, section 5.2.3.14 for details. - TrustRegularExpression *string - - // PolicyURI can be set to the URI of a document that describes the - // policy under which the signature was issued. See RFC 4880, section - // 5.2.3.20 for details. - PolicyURI string - - // FlagsValid is set if any flags were given. See RFC 4880, section - // 5.2.3.21 for details. - FlagsValid bool - FlagCertify, FlagSign, FlagEncryptCommunications, FlagEncryptStorage, FlagSplitKey, FlagAuthenticate, FlagGroupKey bool - - // RevocationReason is set if this signature has been revoked. - // See RFC 4880, section 5.2.3.23 for details. - RevocationReason *ReasonForRevocation - RevocationReasonText string - - // In a self-signature, these flags are set there is a features subpacket - // indicating that the issuer implementation supports these features - // see https://datatracker.ietf.org/doc/html/draft-ietf-openpgp-crypto-refresh#features-subpacket - SEIPDv1, SEIPDv2 bool - - // EmbeddedSignature, if non-nil, is a signature of the parent key, by - // this key. This prevents an attacker from claiming another's signing - // subkey as their own. - EmbeddedSignature *Signature - - outSubpackets []outputSubpacket -} - -func (sig *Signature) parse(r io.Reader) (err error) { - // RFC 4880, section 5.2.3 - var buf [5]byte - _, err = readFull(r, buf[:1]) - if err != nil { - return - } - if buf[0] != 4 && buf[0] != 5 { - err = errors.UnsupportedError("signature packet version " + strconv.Itoa(int(buf[0]))) - return - } - sig.Version = int(buf[0]) - _, err = readFull(r, buf[:5]) - if err != nil { - return - } - sig.SigType = SignatureType(buf[0]) - sig.PubKeyAlgo = PublicKeyAlgorithm(buf[1]) - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly, PubKeyAlgoDSA, PubKeyAlgoECDSA, PubKeyAlgoEdDSA: - default: - err = errors.UnsupportedError("public key algorithm " + strconv.Itoa(int(sig.PubKeyAlgo))) - return - } - - var ok bool - - if sig.Version < 5 { - sig.Hash, ok = algorithm.HashIdToHashWithSha1(buf[2]) - } else { - sig.Hash, ok = algorithm.HashIdToHash(buf[2]) - } - - if !ok { - return errors.UnsupportedError("hash function " + strconv.Itoa(int(buf[2]))) - } - - hashedSubpacketsLength := int(buf[3])<<8 | int(buf[4]) - hashedSubpackets := make([]byte, hashedSubpacketsLength) - _, err = readFull(r, hashedSubpackets) - if err != nil { - return - } - err = sig.buildHashSuffix(hashedSubpackets) - if err != nil { - return - } - - err = parseSignatureSubpackets(sig, hashedSubpackets, true) - if err != nil { - return - } - - _, err = readFull(r, buf[:2]) - if err != nil { - return - } - unhashedSubpacketsLength := int(buf[0])<<8 | int(buf[1]) - unhashedSubpackets := make([]byte, unhashedSubpacketsLength) - _, err = readFull(r, unhashedSubpackets) - if err != nil { - return - } - err = parseSignatureSubpackets(sig, unhashedSubpackets, false) - if err != nil { - return - } - - _, err = readFull(r, sig.HashTag[:2]) - if err != nil { - return - } - - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - sig.RSASignature = new(encoding.MPI) - _, err = sig.RSASignature.ReadFrom(r) - case PubKeyAlgoDSA: - sig.DSASigR = new(encoding.MPI) - if _, err = sig.DSASigR.ReadFrom(r); err != nil { - return - } - - sig.DSASigS = new(encoding.MPI) - _, err = sig.DSASigS.ReadFrom(r) - case PubKeyAlgoECDSA: - sig.ECDSASigR = new(encoding.MPI) - if _, err = sig.ECDSASigR.ReadFrom(r); err != nil { - return - } - - sig.ECDSASigS = new(encoding.MPI) - _, err = sig.ECDSASigS.ReadFrom(r) - case PubKeyAlgoEdDSA: - sig.EdDSASigR = new(encoding.MPI) - if _, err = sig.EdDSASigR.ReadFrom(r); err != nil { - return - } - - sig.EdDSASigS = new(encoding.MPI) - if _, err = sig.EdDSASigS.ReadFrom(r); err != nil { - return - } - default: - panic("unreachable") - } - return -} - -// parseSignatureSubpackets parses subpackets of the main signature packet. See -// RFC 4880, section 5.2.3.1. -func parseSignatureSubpackets(sig *Signature, subpackets []byte, isHashed bool) (err error) { - for len(subpackets) > 0 { - subpackets, err = parseSignatureSubpacket(sig, subpackets, isHashed) - if err != nil { - return - } - } - - if sig.CreationTime.IsZero() { - err = errors.StructuralError("no creation time in signature") - } - - return -} - -type signatureSubpacketType uint8 - -const ( - creationTimeSubpacket signatureSubpacketType = 2 - signatureExpirationSubpacket signatureSubpacketType = 3 - trustSubpacket signatureSubpacketType = 5 - regularExpressionSubpacket signatureSubpacketType = 6 - keyExpirationSubpacket signatureSubpacketType = 9 - prefSymmetricAlgosSubpacket signatureSubpacketType = 11 - issuerSubpacket signatureSubpacketType = 16 - notationDataSubpacket signatureSubpacketType = 20 - prefHashAlgosSubpacket signatureSubpacketType = 21 - prefCompressionSubpacket signatureSubpacketType = 22 - primaryUserIdSubpacket signatureSubpacketType = 25 - policyUriSubpacket signatureSubpacketType = 26 - keyFlagsSubpacket signatureSubpacketType = 27 - signerUserIdSubpacket signatureSubpacketType = 28 - reasonForRevocationSubpacket signatureSubpacketType = 29 - featuresSubpacket signatureSubpacketType = 30 - embeddedSignatureSubpacket signatureSubpacketType = 32 - issuerFingerprintSubpacket signatureSubpacketType = 33 - prefCipherSuitesSubpacket signatureSubpacketType = 39 -) - -// parseSignatureSubpacket parses a single subpacket. len(subpacket) is >= 1. -func parseSignatureSubpacket(sig *Signature, subpacket []byte, isHashed bool) (rest []byte, err error) { - // RFC 4880, section 5.2.3.1 - var ( - length uint32 - packetType signatureSubpacketType - isCritical bool - ) - switch { - case subpacket[0] < 192: - length = uint32(subpacket[0]) - subpacket = subpacket[1:] - case subpacket[0] < 255: - if len(subpacket) < 2 { - goto Truncated - } - length = uint32(subpacket[0]-192)<<8 + uint32(subpacket[1]) + 192 - subpacket = subpacket[2:] - default: - if len(subpacket) < 5 { - goto Truncated - } - length = uint32(subpacket[1])<<24 | - uint32(subpacket[2])<<16 | - uint32(subpacket[3])<<8 | - uint32(subpacket[4]) - subpacket = subpacket[5:] - } - if length > uint32(len(subpacket)) { - goto Truncated - } - rest = subpacket[length:] - subpacket = subpacket[:length] - if len(subpacket) == 0 { - err = errors.StructuralError("zero length signature subpacket") - return - } - packetType = signatureSubpacketType(subpacket[0] & 0x7f) - isCritical = subpacket[0]&0x80 == 0x80 - subpacket = subpacket[1:] - sig.rawSubpackets = append(sig.rawSubpackets, outputSubpacket{isHashed, packetType, isCritical, subpacket}) - if !isHashed && - packetType != issuerSubpacket && - packetType != issuerFingerprintSubpacket && - packetType != embeddedSignatureSubpacket { - return - } - switch packetType { - case creationTimeSubpacket: - if len(subpacket) != 4 { - err = errors.StructuralError("signature creation time not four bytes") - return - } - t := binary.BigEndian.Uint32(subpacket) - sig.CreationTime = time.Unix(int64(t), 0) - case signatureExpirationSubpacket: - // Signature expiration time, section 5.2.3.10 - if len(subpacket) != 4 { - err = errors.StructuralError("expiration subpacket with bad length") - return - } - sig.SigLifetimeSecs = new(uint32) - *sig.SigLifetimeSecs = binary.BigEndian.Uint32(subpacket) - case trustSubpacket: - // Trust level and amount, section 5.2.3.13 - sig.TrustLevel = TrustLevel(subpacket[0]) - sig.TrustAmount = TrustAmount(subpacket[1]) - case regularExpressionSubpacket: - // Trust regular expression, section 5.2.3.14 - // RFC specifies the string should be null-terminated; remove a null byte from the end - if subpacket[len(subpacket)-1] != 0x00 { - err = errors.StructuralError("expected regular expression to be null-terminated") - return - } - trustRegularExpression := string(subpacket[:len(subpacket)-1]) - sig.TrustRegularExpression = &trustRegularExpression - case keyExpirationSubpacket: - // Key expiration time, section 5.2.3.6 - if len(subpacket) != 4 { - err = errors.StructuralError("key expiration subpacket with bad length") - return - } - sig.KeyLifetimeSecs = new(uint32) - *sig.KeyLifetimeSecs = binary.BigEndian.Uint32(subpacket) - case prefSymmetricAlgosSubpacket: - // Preferred symmetric algorithms, section 5.2.3.7 - sig.PreferredSymmetric = make([]byte, len(subpacket)) - copy(sig.PreferredSymmetric, subpacket) - case issuerSubpacket: - // Issuer, section 5.2.3.5 - if sig.Version > 4 { - err = errors.StructuralError("issuer subpacket found in v5 key") - return - } - if len(subpacket) != 8 { - err = errors.StructuralError("issuer subpacket with bad length") - return - } - sig.IssuerKeyId = new(uint64) - *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket) - case notationDataSubpacket: - // Notation data, section 5.2.3.16 - if len(subpacket) < 8 { - err = errors.StructuralError("notation data subpacket with bad length") - return - } - - nameLength := uint32(subpacket[4])<<8 | uint32(subpacket[5]) - valueLength := uint32(subpacket[6])<<8 | uint32(subpacket[7]) - if len(subpacket) != int(nameLength) + int(valueLength) + 8 { - err = errors.StructuralError("notation data subpacket with bad length") - return - } - - notation := Notation{ - IsHumanReadable: (subpacket[0] & 0x80) == 0x80, - Name: string(subpacket[8: (nameLength + 8)]), - Value: subpacket[(nameLength + 8) : (valueLength + nameLength + 8)], - IsCritical: isCritical, - } - - sig.Notations = append(sig.Notations, ¬ation) - case prefHashAlgosSubpacket: - // Preferred hash algorithms, section 5.2.3.8 - sig.PreferredHash = make([]byte, len(subpacket)) - copy(sig.PreferredHash, subpacket) - case prefCompressionSubpacket: - // Preferred compression algorithms, section 5.2.3.9 - sig.PreferredCompression = make([]byte, len(subpacket)) - copy(sig.PreferredCompression, subpacket) - case primaryUserIdSubpacket: - // Primary User ID, section 5.2.3.19 - if len(subpacket) != 1 { - err = errors.StructuralError("primary user id subpacket with bad length") - return - } - sig.IsPrimaryId = new(bool) - if subpacket[0] > 0 { - *sig.IsPrimaryId = true - } - case keyFlagsSubpacket: - // Key flags, section 5.2.3.21 - if len(subpacket) == 0 { - err = errors.StructuralError("empty key flags subpacket") - return - } - sig.FlagsValid = true - if subpacket[0]&KeyFlagCertify != 0 { - sig.FlagCertify = true - } - if subpacket[0]&KeyFlagSign != 0 { - sig.FlagSign = true - } - if subpacket[0]&KeyFlagEncryptCommunications != 0 { - sig.FlagEncryptCommunications = true - } - if subpacket[0]&KeyFlagEncryptStorage != 0 { - sig.FlagEncryptStorage = true - } - if subpacket[0]&KeyFlagSplitKey != 0 { - sig.FlagSplitKey = true - } - if subpacket[0]&KeyFlagAuthenticate != 0 { - sig.FlagAuthenticate = true - } - if subpacket[0]&KeyFlagGroupKey != 0 { - sig.FlagGroupKey = true - } - case signerUserIdSubpacket: - userId := string(subpacket) - sig.SignerUserId = &userId - case reasonForRevocationSubpacket: - // Reason For Revocation, section 5.2.3.23 - if len(subpacket) == 0 { - err = errors.StructuralError("empty revocation reason subpacket") - return - } - sig.RevocationReason = new(ReasonForRevocation) - *sig.RevocationReason = ReasonForRevocation(subpacket[0]) - sig.RevocationReasonText = string(subpacket[1:]) - case featuresSubpacket: - // Features subpacket, section 5.2.3.24 specifies a very general - // mechanism for OpenPGP implementations to signal support for new - // features. - if len(subpacket) > 0 { - if subpacket[0]&0x01 != 0 { - sig.SEIPDv1 = true - } - // 0x02 and 0x04 are reserved - if subpacket[0]&0x08 != 0 { - sig.SEIPDv2 = true - } - } - case embeddedSignatureSubpacket: - // Only usage is in signatures that cross-certify - // signing subkeys. section 5.2.3.26 describes the - // format, with its usage described in section 11.1 - if sig.EmbeddedSignature != nil { - err = errors.StructuralError("Cannot have multiple embedded signatures") - return - } - sig.EmbeddedSignature = new(Signature) - // Embedded signatures are required to be v4 signatures see - // section 12.1. However, we only parse v4 signatures in this - // file anyway. - if err := sig.EmbeddedSignature.parse(bytes.NewBuffer(subpacket)); err != nil { - return nil, err - } - if sigType := sig.EmbeddedSignature.SigType; sigType != SigTypePrimaryKeyBinding { - return nil, errors.StructuralError("cross-signature has unexpected type " + strconv.Itoa(int(sigType))) - } - case policyUriSubpacket: - // Policy URI, section 5.2.3.20 - sig.PolicyURI = string(subpacket) - case issuerFingerprintSubpacket: - v, l := subpacket[0], len(subpacket[1:]) - if v == 5 && l != 32 || v != 5 && l != 20 { - return nil, errors.StructuralError("bad fingerprint length") - } - sig.IssuerFingerprint = make([]byte, l) - copy(sig.IssuerFingerprint, subpacket[1:]) - sig.IssuerKeyId = new(uint64) - if v == 5 { - *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket[1:9]) - } else { - *sig.IssuerKeyId = binary.BigEndian.Uint64(subpacket[13:21]) - } - case prefCipherSuitesSubpacket: - // Preferred AEAD cipher suites - // See https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#name-preferred-aead-ciphersuites - if len(subpacket) % 2 != 0 { - err = errors.StructuralError("invalid aead cipher suite length") - return - } - - sig.PreferredCipherSuites = make([][2]byte, len(subpacket) / 2) - - for i := 0; i < len(subpacket) / 2; i++ { - sig.PreferredCipherSuites[i] = [2]uint8{subpacket[2*i], subpacket[2*i+1]} - } - default: - if isCritical { - err = errors.UnsupportedError("unknown critical signature subpacket type " + strconv.Itoa(int(packetType))) - return - } - } - return - -Truncated: - err = errors.StructuralError("signature subpacket truncated") - return -} - -// subpacketLengthLength returns the length, in bytes, of an encoded length value. -func subpacketLengthLength(length int) int { - if length < 192 { - return 1 - } - if length < 16320 { - return 2 - } - return 5 -} - -func (sig *Signature) CheckKeyIdOrFingerprint(pk *PublicKey) bool { - if sig.IssuerFingerprint != nil && len(sig.IssuerFingerprint) >= 20 { - return bytes.Equal(sig.IssuerFingerprint, pk.Fingerprint) - } - return sig.IssuerKeyId != nil && *sig.IssuerKeyId == pk.KeyId -} - -// serializeSubpacketLength marshals the given length into to. -func serializeSubpacketLength(to []byte, length int) int { - // RFC 4880, Section 4.2.2. - if length < 192 { - to[0] = byte(length) - return 1 - } - if length < 16320 { - length -= 192 - to[0] = byte((length >> 8) + 192) - to[1] = byte(length) - return 2 - } - to[0] = 255 - to[1] = byte(length >> 24) - to[2] = byte(length >> 16) - to[3] = byte(length >> 8) - to[4] = byte(length) - return 5 -} - -// subpacketsLength returns the serialized length, in bytes, of the given -// subpackets. -func subpacketsLength(subpackets []outputSubpacket, hashed bool) (length int) { - for _, subpacket := range subpackets { - if subpacket.hashed == hashed { - length += subpacketLengthLength(len(subpacket.contents) + 1) - length += 1 // type byte - length += len(subpacket.contents) - } - } - return -} - -// serializeSubpackets marshals the given subpackets into to. -func serializeSubpackets(to []byte, subpackets []outputSubpacket, hashed bool) { - for _, subpacket := range subpackets { - if subpacket.hashed == hashed { - n := serializeSubpacketLength(to, len(subpacket.contents)+1) - to[n] = byte(subpacket.subpacketType) - if subpacket.isCritical { - to[n] |= 0x80 - } - to = to[1+n:] - n = copy(to, subpacket.contents) - to = to[n:] - } - } - return -} - -// SigExpired returns whether sig is a signature that has expired or is created -// in the future. -func (sig *Signature) SigExpired(currentTime time.Time) bool { - if sig.CreationTime.After(currentTime) { - return true - } - if sig.SigLifetimeSecs == nil || *sig.SigLifetimeSecs == 0 { - return false - } - expiry := sig.CreationTime.Add(time.Duration(*sig.SigLifetimeSecs) * time.Second) - return currentTime.After(expiry) -} - -// buildHashSuffix constructs the HashSuffix member of sig in preparation for signing. -func (sig *Signature) buildHashSuffix(hashedSubpackets []byte) (err error) { - var hashId byte - var ok bool - - if sig.Version < 5 { - hashId, ok = algorithm.HashToHashIdWithSha1(sig.Hash) - } else { - hashId, ok = algorithm.HashToHashId(sig.Hash) - } - - if !ok { - sig.HashSuffix = nil - return errors.InvalidArgumentError("hash cannot be represented in OpenPGP: " + strconv.Itoa(int(sig.Hash))) - } - - hashedFields := bytes.NewBuffer([]byte{ - uint8(sig.Version), - uint8(sig.SigType), - uint8(sig.PubKeyAlgo), - uint8(hashId), - uint8(len(hashedSubpackets) >> 8), - uint8(len(hashedSubpackets)), - }) - hashedFields.Write(hashedSubpackets) - - var l uint64 = uint64(6 + len(hashedSubpackets)) - if sig.Version == 5 { - hashedFields.Write([]byte{0x05, 0xff}) - hashedFields.Write([]byte{ - uint8(l >> 56), uint8(l >> 48), uint8(l >> 40), uint8(l >> 32), - uint8(l >> 24), uint8(l >> 16), uint8(l >> 8), uint8(l), - }) - } else { - hashedFields.Write([]byte{0x04, 0xff}) - hashedFields.Write([]byte{ - uint8(l >> 24), uint8(l >> 16), uint8(l >> 8), uint8(l), - }) - } - sig.HashSuffix = make([]byte, hashedFields.Len()) - copy(sig.HashSuffix, hashedFields.Bytes()) - return -} - -func (sig *Signature) signPrepareHash(h hash.Hash) (digest []byte, err error) { - hashedSubpacketsLen := subpacketsLength(sig.outSubpackets, true) - hashedSubpackets := make([]byte, hashedSubpacketsLen) - serializeSubpackets(hashedSubpackets, sig.outSubpackets, true) - err = sig.buildHashSuffix(hashedSubpackets) - if err != nil { - return - } - if sig.Version == 5 && (sig.SigType == 0x00 || sig.SigType == 0x01) { - sig.AddMetadataToHashSuffix() - } - - h.Write(sig.HashSuffix) - digest = h.Sum(nil) - copy(sig.HashTag[:], digest) - return -} - -// Sign signs a message with a private key. The hash, h, must contain -// the hash of the message to be signed and will be mutated by this function. -// On success, the signature is stored in sig. Call Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) Sign(h hash.Hash, priv *PrivateKey, config *Config) (err error) { - if priv.Dummy() { - return errors.ErrDummyPrivateKey("dummy key found") - } - sig.Version = priv.PublicKey.Version - sig.IssuerFingerprint = priv.PublicKey.Fingerprint - sig.outSubpackets, err = sig.buildSubpackets(priv.PublicKey) - if err != nil { - return err - } - digest, err := sig.signPrepareHash(h) - if err != nil { - return - } - switch priv.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - // supports both *rsa.PrivateKey and crypto.Signer - sigdata, err := priv.PrivateKey.(crypto.Signer).Sign(config.Random(), digest, sig.Hash) - if err == nil { - sig.RSASignature = encoding.NewMPI(sigdata) - } - case PubKeyAlgoDSA: - dsaPriv := priv.PrivateKey.(*dsa.PrivateKey) - - // Need to truncate hashBytes to match FIPS 186-3 section 4.6. - subgroupSize := (dsaPriv.Q.BitLen() + 7) / 8 - if len(digest) > subgroupSize { - digest = digest[:subgroupSize] - } - r, s, err := dsa.Sign(config.Random(), dsaPriv, digest) - if err == nil { - sig.DSASigR = new(encoding.MPI).SetBig(r) - sig.DSASigS = new(encoding.MPI).SetBig(s) - } - case PubKeyAlgoECDSA: - sk := priv.PrivateKey.(*ecdsa.PrivateKey) - r, s, err := ecdsa.Sign(config.Random(), sk, digest) - - if err == nil { - sig.ECDSASigR = new(encoding.MPI).SetBig(r) - sig.ECDSASigS = new(encoding.MPI).SetBig(s) - } - case PubKeyAlgoEdDSA: - sk := priv.PrivateKey.(*eddsa.PrivateKey) - r, s, err := eddsa.Sign(sk, digest) - if err == nil { - sig.EdDSASigR = encoding.NewMPI(r) - sig.EdDSASigS = encoding.NewMPI(s) - } - default: - err = errors.UnsupportedError("public key algorithm: " + strconv.Itoa(int(sig.PubKeyAlgo))) - } - - return -} - -// SignUserId computes a signature from priv, asserting that pub is a valid -// key for the identity id. On success, the signature is stored in sig. Call -// Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) SignUserId(id string, pub *PublicKey, priv *PrivateKey, config *Config) error { - if priv.Dummy() { - return errors.ErrDummyPrivateKey("dummy key found") - } - h, err := userIdSignatureHash(id, pub, sig.Hash) - if err != nil { - return err - } - return sig.Sign(h, priv, config) -} - -// CrossSignKey computes a signature from signingKey on pub hashed using hashKey. On success, -// the signature is stored in sig. Call Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) CrossSignKey(pub *PublicKey, hashKey *PublicKey, signingKey *PrivateKey, - config *Config) error { - h, err := keySignatureHash(hashKey, pub, sig.Hash) - if err != nil { - return err - } - return sig.Sign(h, signingKey, config) -} - -// SignKey computes a signature from priv, asserting that pub is a subkey. On -// success, the signature is stored in sig. Call Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) SignKey(pub *PublicKey, priv *PrivateKey, config *Config) error { - if priv.Dummy() { - return errors.ErrDummyPrivateKey("dummy key found") - } - h, err := keySignatureHash(&priv.PublicKey, pub, sig.Hash) - if err != nil { - return err - } - return sig.Sign(h, priv, config) -} - -// RevokeKey computes a revocation signature of pub using priv. On success, the signature is -// stored in sig. Call Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) RevokeKey(pub *PublicKey, priv *PrivateKey, config *Config) error { - h, err := keyRevocationHash(pub, sig.Hash) - if err != nil { - return err - } - return sig.Sign(h, priv, config) -} - -// RevokeSubkey computes a subkey revocation signature of pub using priv. -// On success, the signature is stored in sig. Call Serialize to write it out. -// If config is nil, sensible defaults will be used. -func (sig *Signature) RevokeSubkey(pub *PublicKey, priv *PrivateKey, config *Config) error { - // Identical to a subkey binding signature - return sig.SignKey(pub, priv, config) -} - -// Serialize marshals sig to w. Sign, SignUserId or SignKey must have been -// called first. -func (sig *Signature) Serialize(w io.Writer) (err error) { - if len(sig.outSubpackets) == 0 { - sig.outSubpackets = sig.rawSubpackets - } - if sig.RSASignature == nil && sig.DSASigR == nil && sig.ECDSASigR == nil && sig.EdDSASigR == nil { - return errors.InvalidArgumentError("Signature: need to call Sign, SignUserId or SignKey before Serialize") - } - - sigLength := 0 - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - sigLength = int(sig.RSASignature.EncodedLength()) - case PubKeyAlgoDSA: - sigLength = int(sig.DSASigR.EncodedLength()) - sigLength += int(sig.DSASigS.EncodedLength()) - case PubKeyAlgoECDSA: - sigLength = int(sig.ECDSASigR.EncodedLength()) - sigLength += int(sig.ECDSASigS.EncodedLength()) - case PubKeyAlgoEdDSA: - sigLength = int(sig.EdDSASigR.EncodedLength()) - sigLength += int(sig.EdDSASigS.EncodedLength()) - default: - panic("impossible") - } - - unhashedSubpacketsLen := subpacketsLength(sig.outSubpackets, false) - length := len(sig.HashSuffix) - 6 /* trailer not included */ + - 2 /* length of unhashed subpackets */ + unhashedSubpacketsLen + - 2 /* hash tag */ + sigLength - if sig.Version == 5 { - length -= 4 // eight-octet instead of four-octet big endian - } - err = serializeHeader(w, packetTypeSignature, length) - if err != nil { - return - } - err = sig.serializeBody(w) - if err != nil { - return err - } - return -} - -func (sig *Signature) serializeBody(w io.Writer) (err error) { - hashedSubpacketsLen := uint16(uint16(sig.HashSuffix[4])<<8) | uint16(sig.HashSuffix[5]) - fields := sig.HashSuffix[:6+hashedSubpacketsLen] - _, err = w.Write(fields) - if err != nil { - return - } - - unhashedSubpacketsLen := subpacketsLength(sig.outSubpackets, false) - unhashedSubpackets := make([]byte, 2+unhashedSubpacketsLen) - unhashedSubpackets[0] = byte(unhashedSubpacketsLen >> 8) - unhashedSubpackets[1] = byte(unhashedSubpacketsLen) - serializeSubpackets(unhashedSubpackets[2:], sig.outSubpackets, false) - - _, err = w.Write(unhashedSubpackets) - if err != nil { - return - } - _, err = w.Write(sig.HashTag[:]) - if err != nil { - return - } - - switch sig.PubKeyAlgo { - case PubKeyAlgoRSA, PubKeyAlgoRSASignOnly: - _, err = w.Write(sig.RSASignature.EncodedBytes()) - case PubKeyAlgoDSA: - if _, err = w.Write(sig.DSASigR.EncodedBytes()); err != nil { - return - } - _, err = w.Write(sig.DSASigS.EncodedBytes()) - case PubKeyAlgoECDSA: - if _, err = w.Write(sig.ECDSASigR.EncodedBytes()); err != nil { - return - } - _, err = w.Write(sig.ECDSASigS.EncodedBytes()) - case PubKeyAlgoEdDSA: - if _, err = w.Write(sig.EdDSASigR.EncodedBytes()); err != nil { - return - } - _, err = w.Write(sig.EdDSASigS.EncodedBytes()) - default: - panic("impossible") - } - return -} - -// outputSubpacket represents a subpacket to be marshaled. -type outputSubpacket struct { - hashed bool // true if this subpacket is in the hashed area. - subpacketType signatureSubpacketType - isCritical bool - contents []byte -} - -func (sig *Signature) buildSubpackets(issuer PublicKey) (subpackets []outputSubpacket, err error) { - creationTime := make([]byte, 4) - binary.BigEndian.PutUint32(creationTime, uint32(sig.CreationTime.Unix())) - subpackets = append(subpackets, outputSubpacket{true, creationTimeSubpacket, false, creationTime}) - - if sig.IssuerKeyId != nil && sig.Version == 4 { - keyId := make([]byte, 8) - binary.BigEndian.PutUint64(keyId, *sig.IssuerKeyId) - subpackets = append(subpackets, outputSubpacket{true, issuerSubpacket, true, keyId}) - } - if sig.IssuerFingerprint != nil { - contents := append([]uint8{uint8(issuer.Version)}, sig.IssuerFingerprint...) - subpackets = append(subpackets, outputSubpacket{true, issuerFingerprintSubpacket, sig.Version == 5, contents}) - } - if sig.SignerUserId != nil { - subpackets = append(subpackets, outputSubpacket{true, signerUserIdSubpacket, false, []byte(*sig.SignerUserId)}) - } - if sig.SigLifetimeSecs != nil && *sig.SigLifetimeSecs != 0 { - sigLifetime := make([]byte, 4) - binary.BigEndian.PutUint32(sigLifetime, *sig.SigLifetimeSecs) - subpackets = append(subpackets, outputSubpacket{true, signatureExpirationSubpacket, true, sigLifetime}) - } - - // Key flags may only appear in self-signatures or certification signatures. - - if sig.FlagsValid { - var flags byte - if sig.FlagCertify { - flags |= KeyFlagCertify - } - if sig.FlagSign { - flags |= KeyFlagSign - } - if sig.FlagEncryptCommunications { - flags |= KeyFlagEncryptCommunications - } - if sig.FlagEncryptStorage { - flags |= KeyFlagEncryptStorage - } - if sig.FlagSplitKey { - flags |= KeyFlagSplitKey - } - if sig.FlagAuthenticate { - flags |= KeyFlagAuthenticate - } - if sig.FlagGroupKey { - flags |= KeyFlagGroupKey - } - subpackets = append(subpackets, outputSubpacket{true, keyFlagsSubpacket, false, []byte{flags}}) - } - - for _, notation := range sig.Notations { - subpackets = append( - subpackets, - outputSubpacket{ - true, - notationDataSubpacket, - notation.IsCritical, - notation.getData(), - }) - } - - // The following subpackets may only appear in self-signatures. - - var features = byte(0x00) - if sig.SEIPDv1 { - features |= 0x01 - } - if sig.SEIPDv2 { - features |= 0x08 - } - - if features != 0x00 { - subpackets = append(subpackets, outputSubpacket{true, featuresSubpacket, false, []byte{features}}) - } - - if sig.TrustLevel != 0 { - subpackets = append(subpackets, outputSubpacket{true, trustSubpacket, true, []byte{byte(sig.TrustLevel), byte(sig.TrustAmount)}}) - } - - if sig.TrustRegularExpression != nil { - // RFC specifies the string should be null-terminated; add a null byte to the end - subpackets = append(subpackets, outputSubpacket{true, regularExpressionSubpacket, true, []byte(*sig.TrustRegularExpression + "\000")}) - } - - if sig.KeyLifetimeSecs != nil && *sig.KeyLifetimeSecs != 0 { - keyLifetime := make([]byte, 4) - binary.BigEndian.PutUint32(keyLifetime, *sig.KeyLifetimeSecs) - subpackets = append(subpackets, outputSubpacket{true, keyExpirationSubpacket, true, keyLifetime}) - } - - if sig.IsPrimaryId != nil && *sig.IsPrimaryId { - subpackets = append(subpackets, outputSubpacket{true, primaryUserIdSubpacket, false, []byte{1}}) - } - - if len(sig.PreferredSymmetric) > 0 { - subpackets = append(subpackets, outputSubpacket{true, prefSymmetricAlgosSubpacket, false, sig.PreferredSymmetric}) - } - - if len(sig.PreferredHash) > 0 { - subpackets = append(subpackets, outputSubpacket{true, prefHashAlgosSubpacket, false, sig.PreferredHash}) - } - - if len(sig.PreferredCompression) > 0 { - subpackets = append(subpackets, outputSubpacket{true, prefCompressionSubpacket, false, sig.PreferredCompression}) - } - - if len(sig.PolicyURI) > 0 { - subpackets = append(subpackets, outputSubpacket{true, policyUriSubpacket, false, []uint8(sig.PolicyURI)}) - } - - if len(sig.PreferredCipherSuites) > 0 { - serialized := make([]byte, len(sig.PreferredCipherSuites)*2) - for i, cipherSuite := range sig.PreferredCipherSuites { - serialized[2*i] = cipherSuite[0] - serialized[2*i+1] = cipherSuite[1] - } - subpackets = append(subpackets, outputSubpacket{true, prefCipherSuitesSubpacket, false, serialized}) - } - - // Revocation reason appears only in revocation signatures and is serialized as per section 5.2.3.23. - if sig.RevocationReason != nil { - subpackets = append(subpackets, outputSubpacket{true, reasonForRevocationSubpacket, true, - append([]uint8{uint8(*sig.RevocationReason)}, []uint8(sig.RevocationReasonText)...)}) - } - - // EmbeddedSignature appears only in subkeys capable of signing and is serialized as per section 5.2.3.26. - if sig.EmbeddedSignature != nil { - var buf bytes.Buffer - err = sig.EmbeddedSignature.serializeBody(&buf) - if err != nil { - return - } - subpackets = append(subpackets, outputSubpacket{true, embeddedSignatureSubpacket, true, buf.Bytes()}) - } - - return -} - -// AddMetadataToHashSuffix modifies the current hash suffix to include metadata -// (format, filename, and time). Version 5 keys protect this data including it -// in the hash computation. See section 5.2.4. -func (sig *Signature) AddMetadataToHashSuffix() { - if sig == nil || sig.Version != 5 { - return - } - if sig.SigType != 0x00 && sig.SigType != 0x01 { - return - } - lit := sig.Metadata - if lit == nil { - // This will translate into six 0x00 bytes. - lit = &LiteralData{} - } - - // Extract the current byte count - n := sig.HashSuffix[len(sig.HashSuffix)-8:] - l := uint64( - uint64(n[0])<<56 | uint64(n[1])<<48 | uint64(n[2])<<40 | uint64(n[3])<<32 | - uint64(n[4])<<24 | uint64(n[5])<<16 | uint64(n[6])<<8 | uint64(n[7])) - - suffix := bytes.NewBuffer(nil) - suffix.Write(sig.HashSuffix[:l]) - - // Add the metadata - var buf [4]byte - buf[0] = lit.Format - fileName := lit.FileName - if len(lit.FileName) > 255 { - fileName = fileName[:255] - } - buf[1] = byte(len(fileName)) - suffix.Write(buf[:2]) - suffix.Write([]byte(lit.FileName)) - binary.BigEndian.PutUint32(buf[:], lit.Time) - suffix.Write(buf[:]) - - // Update the counter and restore trailing bytes - l = uint64(suffix.Len()) - suffix.Write([]byte{0x05, 0xff}) - suffix.Write([]byte{ - uint8(l >> 56), uint8(l >> 48), uint8(l >> 40), uint8(l >> 32), - uint8(l >> 24), uint8(l >> 16), uint8(l >> 8), uint8(l), - }) - sig.HashSuffix = suffix.Bytes() -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetric_key_encrypted.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetric_key_encrypted.go deleted file mode 100644 index bc2caf0e..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetric_key_encrypted.go +++ /dev/null @@ -1,303 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "bytes" - "crypto/cipher" - "crypto/sha256" - "io" - "strconv" - - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/s2k" - "golang.org/x/crypto/hkdf" -) - -// This is the largest session key that we'll support. Since at most 256-bit cipher -// is supported in OpenPGP, this is large enough to contain also the auth tag. -const maxSessionKeySizeInBytes = 64 - -// SymmetricKeyEncrypted represents a passphrase protected session key. See RFC -// 4880, section 5.3. -type SymmetricKeyEncrypted struct { - Version int - CipherFunc CipherFunction - Mode AEADMode - s2k func(out, in []byte) - iv []byte - encryptedKey []byte // Contains also the authentication tag for AEAD -} - -// parse parses an SymmetricKeyEncrypted packet as specified in -// https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#name-symmetric-key-encrypted-ses -func (ske *SymmetricKeyEncrypted) parse(r io.Reader) error { - var buf [1]byte - - // Version - if _, err := readFull(r, buf[:]); err != nil { - return err - } - ske.Version = int(buf[0]) - if ske.Version != 4 && ske.Version != 5 { - return errors.UnsupportedError("unknown SymmetricKeyEncrypted version") - } - - if ske.Version == 5 { - // Scalar octet count - if _, err := readFull(r, buf[:]); err != nil { - return err - } - } - - // Cipher function - if _, err := readFull(r, buf[:]); err != nil { - return err - } - ske.CipherFunc = CipherFunction(buf[0]) - if !ske.CipherFunc.IsSupported() { - return errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(buf[0]))) - } - - if ske.Version == 5 { - // AEAD mode - if _, err := readFull(r, buf[:]); err != nil { - return errors.StructuralError("cannot read AEAD octet from packet") - } - ske.Mode = AEADMode(buf[0]) - - // Scalar octet count - if _, err := readFull(r, buf[:]); err != nil { - return err - } - } - - var err error - if ske.s2k, err = s2k.Parse(r); err != nil { - if _, ok := err.(errors.ErrDummyPrivateKey); ok { - return errors.UnsupportedError("missing key GNU extension in session key") - } - return err - } - - if ske.Version == 5 { - // AEAD IV - iv := make([]byte, ske.Mode.IvLength()) - _, err := readFull(r, iv) - if err != nil { - return errors.StructuralError("cannot read AEAD IV") - } - - ske.iv = iv - } - - encryptedKey := make([]byte, maxSessionKeySizeInBytes) - // The session key may follow. We just have to try and read to find - // out. If it exists then we limit it to maxSessionKeySizeInBytes. - n, err := readFull(r, encryptedKey) - if err != nil && err != io.ErrUnexpectedEOF { - return err - } - - if n != 0 { - if n == maxSessionKeySizeInBytes { - return errors.UnsupportedError("oversized encrypted session key") - } - ske.encryptedKey = encryptedKey[:n] - } - return nil -} - -// Decrypt attempts to decrypt an encrypted session key and returns the key and -// the cipher to use when decrypting a subsequent Symmetrically Encrypted Data -// packet. -func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) ([]byte, CipherFunction, error) { - key := make([]byte, ske.CipherFunc.KeySize()) - ske.s2k(key, passphrase) - if len(ske.encryptedKey) == 0 { - return key, ske.CipherFunc, nil - } - switch ske.Version { - case 4: - plaintextKey, cipherFunc, err := ske.decryptV4(key) - return plaintextKey, cipherFunc, err - case 5: - plaintextKey, err := ske.decryptV5(key) - return plaintextKey, CipherFunction(0), err - } - err := errors.UnsupportedError("unknown SymmetricKeyEncrypted version") - return nil, CipherFunction(0), err -} - -func (ske *SymmetricKeyEncrypted) decryptV4(key []byte) ([]byte, CipherFunction, error) { - // the IV is all zeros - iv := make([]byte, ske.CipherFunc.blockSize()) - c := cipher.NewCFBDecrypter(ske.CipherFunc.new(key), iv) - plaintextKey := make([]byte, len(ske.encryptedKey)) - c.XORKeyStream(plaintextKey, ske.encryptedKey) - cipherFunc := CipherFunction(plaintextKey[0]) - if cipherFunc.blockSize() == 0 { - return nil, ske.CipherFunc, errors.UnsupportedError( - "unknown cipher: " + strconv.Itoa(int(cipherFunc))) - } - plaintextKey = plaintextKey[1:] - if len(plaintextKey) != cipherFunc.KeySize() { - return nil, cipherFunc, errors.StructuralError( - "length of decrypted key not equal to cipher keysize") - } - return plaintextKey, cipherFunc, nil -} - -func (ske *SymmetricKeyEncrypted) decryptV5(key []byte) ([]byte, error) { - adata := []byte{0xc3, byte(5), byte(ske.CipherFunc), byte(ske.Mode)} - aead := getEncryptedKeyAeadInstance(ske.CipherFunc, ske.Mode, key, adata) - - plaintextKey, err := aead.Open(nil, ske.iv, ske.encryptedKey, adata) - if err != nil { - return nil, err - } - return plaintextKey, nil -} - -// SerializeSymmetricKeyEncrypted serializes a symmetric key packet to w. -// The packet contains a random session key, encrypted by a key derived from -// the given passphrase. The session key is returned and must be passed to -// SerializeSymmetricallyEncrypted. -// If config is nil, sensible defaults will be used. -func SerializeSymmetricKeyEncrypted(w io.Writer, passphrase []byte, config *Config) (key []byte, err error) { - cipherFunc := config.Cipher() - - sessionKey := make([]byte, cipherFunc.KeySize()) - _, err = io.ReadFull(config.Random(), sessionKey) - if err != nil { - return - } - - err = SerializeSymmetricKeyEncryptedReuseKey(w, sessionKey, passphrase, config) - if err != nil { - return - } - - key = sessionKey - return -} - -// SerializeSymmetricKeyEncryptedReuseKey serializes a symmetric key packet to w. -// The packet contains the given session key, encrypted by a key derived from -// the given passphrase. The returned session key must be passed to -// SerializeSymmetricallyEncrypted. -// If config is nil, sensible defaults will be used. -func SerializeSymmetricKeyEncryptedReuseKey(w io.Writer, sessionKey []byte, passphrase []byte, config *Config) (err error) { - var version int - if config.AEAD() != nil { - version = 5 - } else { - version = 4 - } - cipherFunc := config.Cipher() - // cipherFunc must be AES - if !cipherFunc.IsSupported() || cipherFunc < CipherAES128 || cipherFunc > CipherAES256 { - return errors.UnsupportedError("unsupported cipher: " + strconv.Itoa(int(cipherFunc))) - } - - keySize := cipherFunc.KeySize() - s2kBuf := new(bytes.Buffer) - keyEncryptingKey := make([]byte, keySize) - // s2k.Serialize salts and stretches the passphrase, and writes the - // resulting key to keyEncryptingKey and the s2k descriptor to s2kBuf. - err = s2k.Serialize(s2kBuf, keyEncryptingKey, config.Random(), passphrase, &s2k.Config{Hash: config.Hash(), S2KCount: config.PasswordHashIterations()}) - if err != nil { - return - } - s2kBytes := s2kBuf.Bytes() - - var packetLength int - switch version { - case 4: - packetLength = 2 /* header */ + len(s2kBytes) + 1 /* cipher type */ + keySize - case 5: - ivLen := config.AEAD().Mode().IvLength() - tagLen := config.AEAD().Mode().TagLength() - packetLength = 5 + len(s2kBytes) + ivLen + keySize + tagLen - } - err = serializeHeader(w, packetTypeSymmetricKeyEncrypted, packetLength) - if err != nil { - return - } - - // Symmetric Key Encrypted Version - buf := []byte{byte(version)} - - if version == 5 { - // Scalar octet count - buf = append(buf, byte(3 + len(s2kBytes) + config.AEAD().Mode().IvLength())) - } - - // Cipher function - buf = append(buf, byte(cipherFunc)) - - if version == 5 { - // AEAD mode - buf = append(buf, byte(config.AEAD().Mode())) - - // Scalar octet count - buf = append(buf, byte(len(s2kBytes))) - } - _, err = w.Write(buf) - if err != nil { - return - } - _, err = w.Write(s2kBytes) - if err != nil { - return - } - - switch version { - case 4: - iv := make([]byte, cipherFunc.blockSize()) - c := cipher.NewCFBEncrypter(cipherFunc.new(keyEncryptingKey), iv) - encryptedCipherAndKey := make([]byte, keySize+1) - c.XORKeyStream(encryptedCipherAndKey, buf[1:]) - c.XORKeyStream(encryptedCipherAndKey[1:], sessionKey) - _, err = w.Write(encryptedCipherAndKey) - if err != nil { - return - } - case 5: - mode := config.AEAD().Mode() - adata := []byte{0xc3, byte(5), byte(cipherFunc), byte(mode)} - aead := getEncryptedKeyAeadInstance(cipherFunc, mode, keyEncryptingKey, adata) - - // Sample iv using random reader - iv := make([]byte, config.AEAD().Mode().IvLength()) - _, err = io.ReadFull(config.Random(), iv) - if err != nil { - return - } - // Seal and write (encryptedData includes auth. tag) - - encryptedData := aead.Seal(nil, iv, sessionKey, adata) - _, err = w.Write(iv) - if err != nil { - return - } - _, err = w.Write(encryptedData) - if err != nil { - return - } - } - - return -} - -func getEncryptedKeyAeadInstance(c CipherFunction, mode AEADMode, inputKey, associatedData []byte) (aead cipher.AEAD) { - hkdfReader := hkdf.New(sha256.New, inputKey, []byte{}, associatedData) - - encryptionKey := make([]byte, c.KeySize()) - _, _ = readFull(hkdfReader, encryptionKey) - - blockCipher := c.new(encryptionKey) - return mode.new(blockCipher) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetrically_encrypted.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetrically_encrypted.go deleted file mode 100644 index dc1a2403..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetrically_encrypted.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "io" - - "github.com/ProtonMail/go-crypto/openpgp/errors" -) - -const aeadSaltSize = 32 - -// SymmetricallyEncrypted represents a symmetrically encrypted byte string. The -// encrypted Contents will consist of more OpenPGP packets. See RFC 4880, -// sections 5.7 and 5.13. -type SymmetricallyEncrypted struct { - Version int - Contents io.Reader // contains tag for version 2 - IntegrityProtected bool // If true it is type 18 (with MDC or AEAD). False is packet type 9 - - // Specific to version 1 - prefix []byte - - // Specific to version 2 - cipher CipherFunction - mode AEADMode - chunkSizeByte byte - salt [aeadSaltSize]byte -} - -const ( - symmetricallyEncryptedVersionMdc = 1 - symmetricallyEncryptedVersionAead = 2 -) - - -func (se *SymmetricallyEncrypted) parse(r io.Reader) error { - if se.IntegrityProtected { - // See RFC 4880, section 5.13. - var buf [1]byte - _, err := readFull(r, buf[:]) - if err != nil { - return err - } - - switch buf[0] { - case symmetricallyEncryptedVersionMdc: - se.Version = symmetricallyEncryptedVersionMdc - case symmetricallyEncryptedVersionAead: - se.Version = symmetricallyEncryptedVersionAead - if err := se.parseAead(r); err != nil { - return err - } - default: - return errors.UnsupportedError("unknown SymmetricallyEncrypted version") - } - } - se.Contents = r - return nil -} - -// Decrypt returns a ReadCloser, from which the decrypted Contents of the -// packet can be read. An incorrect key will only be detected after trying -// to decrypt the entire data. -func (se *SymmetricallyEncrypted) Decrypt(c CipherFunction, key []byte) (io.ReadCloser, error) { - if se.Version == symmetricallyEncryptedVersionAead { - return se.decryptAead(key) - } - - return se.decryptMdc(c, key) -} - -// SerializeSymmetricallyEncrypted serializes a symmetrically encrypted packet -// to w and returns a WriteCloser to which the to-be-encrypted packets can be -// written. -// If config is nil, sensible defaults will be used. -func SerializeSymmetricallyEncrypted(w io.Writer, c CipherFunction, aeadSupported bool, cipherSuite CipherSuite, key []byte, config *Config) (Contents io.WriteCloser, err error) { - writeCloser := noOpCloser{w} - ciphertext, err := serializeStreamHeader(writeCloser, packetTypeSymmetricallyEncryptedIntegrityProtected) - if err != nil { - return - } - - if aeadSupported { - return serializeSymmetricallyEncryptedAead(ciphertext, cipherSuite, config.AEADConfig.ChunkSizeByte(), config.Random(), key) - } - - return serializeSymmetricallyEncryptedMdc(ciphertext, c, key, config) -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetrically_encrypted_aead.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetrically_encrypted_aead.go deleted file mode 100644 index 241800c0..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetrically_encrypted_aead.go +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2023 Proton AG. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package packet - -import ( - "crypto/cipher" - "crypto/sha256" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "golang.org/x/crypto/hkdf" - "io" -) - -// parseAead parses a V2 SEIPD packet (AEAD) as specified in -// https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-5.13.2 -func (se *SymmetricallyEncrypted) parseAead(r io.Reader) error { - headerData := make([]byte, 3) - if n, err := io.ReadFull(r, headerData); n < 3 { - return errors.StructuralError("could not read aead header: " + err.Error()) - } - - // Cipher - se.cipher = CipherFunction(headerData[0]) - // cipherFunc must have block size 16 to use AEAD - if se.cipher.blockSize() != 16 { - return errors.UnsupportedError("invalid aead cipher: " + string(se.cipher)) - } - - // Mode - se.mode = AEADMode(headerData[1]) - if se.mode.TagLength() == 0 { - return errors.UnsupportedError("unknown aead mode: " + string(se.mode)) - } - - // Chunk size - se.chunkSizeByte = headerData[2] - if se.chunkSizeByte > 16 { - return errors.UnsupportedError("invalid aead chunk size byte: " + string(se.chunkSizeByte)) - } - - // Salt - if n, err := io.ReadFull(r, se.salt[:]); n < aeadSaltSize { - return errors.StructuralError("could not read aead salt: " + err.Error()) - } - - return nil -} - -// associatedData for chunks: tag, version, cipher, mode, chunk size byte -func (se *SymmetricallyEncrypted) associatedData() []byte { - return []byte{ - 0xD2, - symmetricallyEncryptedVersionAead, - byte(se.cipher), - byte(se.mode), - se.chunkSizeByte, - } -} - -// decryptAead decrypts a V2 SEIPD packet (AEAD) as specified in -// https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-5.13.2 -func (se *SymmetricallyEncrypted) decryptAead(inputKey []byte) (io.ReadCloser, error) { - aead, nonce := getSymmetricallyEncryptedAeadInstance(se.cipher, se.mode, inputKey, se.salt[:], se.associatedData()) - - // Carry the first tagLen bytes - tagLen := se.mode.TagLength() - peekedBytes := make([]byte, tagLen) - n, err := io.ReadFull(se.Contents, peekedBytes) - if n < tagLen || (err != nil && err != io.EOF) { - return nil, errors.StructuralError("not enough data to decrypt:" + err.Error()) - } - - return &aeadDecrypter{ - aeadCrypter: aeadCrypter{ - aead: aead, - chunkSize: decodeAEADChunkSize(se.chunkSizeByte), - initialNonce: nonce, - associatedData: se.associatedData(), - chunkIndex: make([]byte, 8), - packetTag: packetTypeSymmetricallyEncryptedIntegrityProtected, - }, - reader: se.Contents, - peekedBytes: peekedBytes, - }, nil -} - -// serializeSymmetricallyEncryptedAead encrypts to a writer a V2 SEIPD packet (AEAD) as specified in -// https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-5.13.2 -func serializeSymmetricallyEncryptedAead(ciphertext io.WriteCloser, cipherSuite CipherSuite, chunkSizeByte byte, rand io.Reader, inputKey []byte) (Contents io.WriteCloser, err error) { - // cipherFunc must have block size 16 to use AEAD - if cipherSuite.Cipher.blockSize() != 16 { - return nil, errors.InvalidArgumentError("invalid aead cipher function") - } - - if cipherSuite.Cipher.KeySize() != len(inputKey) { - return nil, errors.InvalidArgumentError("error in aead serialization: bad key length") - } - - // Data for en/decryption: tag, version, cipher, aead mode, chunk size - prefix := []byte{ - 0xD2, - symmetricallyEncryptedVersionAead, - byte(cipherSuite.Cipher), - byte(cipherSuite.Mode), - chunkSizeByte, - } - - // Write header (that correspond to prefix except first byte) - n, err := ciphertext.Write(prefix[1:]) - if err != nil || n < 4 { - return nil, err - } - - // Random salt - salt := make([]byte, aeadSaltSize) - if _, err := rand.Read(salt); err != nil { - return nil, err - } - - if _, err := ciphertext.Write(salt); err != nil { - return nil, err - } - - aead, nonce := getSymmetricallyEncryptedAeadInstance(cipherSuite.Cipher, cipherSuite.Mode, inputKey, salt, prefix) - - return &aeadEncrypter{ - aeadCrypter: aeadCrypter{ - aead: aead, - chunkSize: decodeAEADChunkSize(chunkSizeByte), - associatedData: prefix, - chunkIndex: make([]byte, 8), - initialNonce: nonce, - packetTag: packetTypeSymmetricallyEncryptedIntegrityProtected, - }, - writer: ciphertext, - }, nil -} - -func getSymmetricallyEncryptedAeadInstance(c CipherFunction, mode AEADMode, inputKey, salt, associatedData []byte) (aead cipher.AEAD, nonce []byte) { - hkdfReader := hkdf.New(sha256.New, inputKey, salt, associatedData) - - encryptionKey := make([]byte, c.KeySize()) - _, _ = readFull(hkdfReader, encryptionKey) - - // Last 64 bits of nonce are the counter - nonce = make([]byte, mode.IvLength() - 8) - - _, _ = readFull(hkdfReader, nonce) - - blockCipher := c.new(encryptionKey) - aead = mode.new(blockCipher) - - return -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetrically_encrypted_mdc.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetrically_encrypted_mdc.go deleted file mode 100644 index 3e070f8b..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/symmetrically_encrypted_mdc.go +++ /dev/null @@ -1,256 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "crypto/cipher" - "crypto/sha1" - "crypto/subtle" - "hash" - "io" - "strconv" - - "github.com/ProtonMail/go-crypto/openpgp/errors" -) - -// seMdcReader wraps an io.Reader with a no-op Close method. -type seMdcReader struct { - in io.Reader -} - -func (ser seMdcReader) Read(buf []byte) (int, error) { - return ser.in.Read(buf) -} - -func (ser seMdcReader) Close() error { - return nil -} - -func (se *SymmetricallyEncrypted) decryptMdc(c CipherFunction, key []byte) (io.ReadCloser, error) { - if !c.IsSupported() { - return nil, errors.UnsupportedError("unsupported cipher: " + strconv.Itoa(int(c))) - } - - if len(key) != c.KeySize() { - return nil, errors.InvalidArgumentError("SymmetricallyEncrypted: incorrect key length") - } - - if se.prefix == nil { - se.prefix = make([]byte, c.blockSize()+2) - _, err := readFull(se.Contents, se.prefix) - if err != nil { - return nil, err - } - } else if len(se.prefix) != c.blockSize()+2 { - return nil, errors.InvalidArgumentError("can't try ciphers with different block lengths") - } - - ocfbResync := OCFBResync - if se.IntegrityProtected { - // MDC packets use a different form of OCFB mode. - ocfbResync = OCFBNoResync - } - - s := NewOCFBDecrypter(c.new(key), se.prefix, ocfbResync) - - plaintext := cipher.StreamReader{S: s, R: se.Contents} - - if se.IntegrityProtected { - // IntegrityProtected packets have an embedded hash that we need to check. - h := sha1.New() - h.Write(se.prefix) - return &seMDCReader{in: plaintext, h: h}, nil - } - - // Otherwise, we just need to wrap plaintext so that it's a valid ReadCloser. - return seMdcReader{plaintext}, nil -} - -const mdcTrailerSize = 1 /* tag byte */ + 1 /* length byte */ + sha1.Size - -// An seMDCReader wraps an io.Reader, maintains a running hash and keeps hold -// of the most recent 22 bytes (mdcTrailerSize). Upon EOF, those bytes form an -// MDC packet containing a hash of the previous Contents which is checked -// against the running hash. See RFC 4880, section 5.13. -type seMDCReader struct { - in io.Reader - h hash.Hash - trailer [mdcTrailerSize]byte - scratch [mdcTrailerSize]byte - trailerUsed int - error bool - eof bool -} - -func (ser *seMDCReader) Read(buf []byte) (n int, err error) { - if ser.error { - err = io.ErrUnexpectedEOF - return - } - if ser.eof { - err = io.EOF - return - } - - // If we haven't yet filled the trailer buffer then we must do that - // first. - for ser.trailerUsed < mdcTrailerSize { - n, err = ser.in.Read(ser.trailer[ser.trailerUsed:]) - ser.trailerUsed += n - if err == io.EOF { - if ser.trailerUsed != mdcTrailerSize { - n = 0 - err = io.ErrUnexpectedEOF - ser.error = true - return - } - ser.eof = true - n = 0 - return - } - - if err != nil { - n = 0 - return - } - } - - // If it's a short read then we read into a temporary buffer and shift - // the data into the caller's buffer. - if len(buf) <= mdcTrailerSize { - n, err = readFull(ser.in, ser.scratch[:len(buf)]) - copy(buf, ser.trailer[:n]) - ser.h.Write(buf[:n]) - copy(ser.trailer[:], ser.trailer[n:]) - copy(ser.trailer[mdcTrailerSize-n:], ser.scratch[:]) - if n < len(buf) { - ser.eof = true - err = io.EOF - } - return - } - - n, err = ser.in.Read(buf[mdcTrailerSize:]) - copy(buf, ser.trailer[:]) - ser.h.Write(buf[:n]) - copy(ser.trailer[:], buf[n:]) - - if err == io.EOF { - ser.eof = true - } - return -} - -// This is a new-format packet tag byte for a type 19 (Integrity Protected) packet. -const mdcPacketTagByte = byte(0x80) | 0x40 | 19 - -func (ser *seMDCReader) Close() error { - if ser.error { - return errors.ErrMDCMissing - } - - for !ser.eof { - // We haven't seen EOF so we need to read to the end - var buf [1024]byte - _, err := ser.Read(buf[:]) - if err == io.EOF { - break - } - if err != nil { - return errors.ErrMDCMissing - } - } - - ser.h.Write(ser.trailer[:2]) - - final := ser.h.Sum(nil) - if subtle.ConstantTimeCompare(final, ser.trailer[2:]) != 1 { - return errors.ErrMDCHashMismatch - } - // The hash already includes the MDC header, but we still check its value - // to confirm encryption correctness - if ser.trailer[0] != mdcPacketTagByte || ser.trailer[1] != sha1.Size { - return errors.ErrMDCMissing - } - return nil -} - -// An seMDCWriter writes through to an io.WriteCloser while maintains a running -// hash of the data written. On close, it emits an MDC packet containing the -// running hash. -type seMDCWriter struct { - w io.WriteCloser - h hash.Hash -} - -func (w *seMDCWriter) Write(buf []byte) (n int, err error) { - w.h.Write(buf) - return w.w.Write(buf) -} - -func (w *seMDCWriter) Close() (err error) { - var buf [mdcTrailerSize]byte - - buf[0] = mdcPacketTagByte - buf[1] = sha1.Size - w.h.Write(buf[:2]) - digest := w.h.Sum(nil) - copy(buf[2:], digest) - - _, err = w.w.Write(buf[:]) - if err != nil { - return - } - return w.w.Close() -} - -// noOpCloser is like an ioutil.NopCloser, but for an io.Writer. -type noOpCloser struct { - w io.Writer -} - -func (c noOpCloser) Write(data []byte) (n int, err error) { - return c.w.Write(data) -} - -func (c noOpCloser) Close() error { - return nil -} - -func serializeSymmetricallyEncryptedMdc(ciphertext io.WriteCloser, c CipherFunction, key []byte, config *Config) (Contents io.WriteCloser, err error) { - // Disallow old cipher suites - if !c.IsSupported() || c < CipherAES128 { - return nil, errors.InvalidArgumentError("invalid mdc cipher function") - } - - if c.KeySize() != len(key) { - return nil, errors.InvalidArgumentError("error in mdc serialization: bad key length") - } - - _, err = ciphertext.Write([]byte{symmetricallyEncryptedVersionMdc}) - if err != nil { - return - } - - block := c.new(key) - blockSize := block.BlockSize() - iv := make([]byte, blockSize) - _, err = config.Random().Read(iv) - if err != nil { - return - } - s, prefix := NewOCFBEncrypter(block, iv, OCFBNoResync) - _, err = ciphertext.Write(prefix) - if err != nil { - return - } - plaintext := cipher.StreamWriter{S: s, W: ciphertext} - - h := sha1.New() - h.Write(iv) - h.Write(iv[blockSize-2:]) - Contents = &seMDCWriter{w: plaintext, h: h} - return -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/userattribute.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/userattribute.go deleted file mode 100644 index 88ec72c6..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/userattribute.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2013 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 packet - -import ( - "bytes" - "image" - "image/jpeg" - "io" - "io/ioutil" -) - -const UserAttrImageSubpacket = 1 - -// UserAttribute is capable of storing other types of data about a user -// beyond name, email and a text comment. In practice, user attributes are typically used -// to store a signed thumbnail photo JPEG image of the user. -// See RFC 4880, section 5.12. -type UserAttribute struct { - Contents []*OpaqueSubpacket -} - -// NewUserAttributePhoto creates a user attribute packet -// containing the given images. -func NewUserAttributePhoto(photos ...image.Image) (uat *UserAttribute, err error) { - uat = new(UserAttribute) - for _, photo := range photos { - var buf bytes.Buffer - // RFC 4880, Section 5.12.1. - data := []byte{ - 0x10, 0x00, // Little-endian image header length (16 bytes) - 0x01, // Image header version 1 - 0x01, // JPEG - 0, 0, 0, 0, // 12 reserved octets, must be all zero. - 0, 0, 0, 0, - 0, 0, 0, 0} - if _, err = buf.Write(data); err != nil { - return - } - if err = jpeg.Encode(&buf, photo, nil); err != nil { - return - } - - lengthBuf := make([]byte, 5) - n := serializeSubpacketLength(lengthBuf, len(buf.Bytes())+1) - lengthBuf = lengthBuf[:n] - - uat.Contents = append(uat.Contents, &OpaqueSubpacket{ - SubType: UserAttrImageSubpacket, - EncodedLength: lengthBuf, - Contents: buf.Bytes(), - }) - } - return -} - -// NewUserAttribute creates a new user attribute packet containing the given subpackets. -func NewUserAttribute(contents ...*OpaqueSubpacket) *UserAttribute { - return &UserAttribute{Contents: contents} -} - -func (uat *UserAttribute) parse(r io.Reader) (err error) { - // RFC 4880, section 5.13 - b, err := ioutil.ReadAll(r) - if err != nil { - return - } - uat.Contents, err = OpaqueSubpackets(b) - return -} - -// Serialize marshals the user attribute to w in the form of an OpenPGP packet, including -// header. -func (uat *UserAttribute) Serialize(w io.Writer) (err error) { - var buf bytes.Buffer - for _, sp := range uat.Contents { - err = sp.Serialize(&buf) - if err != nil { - return err - } - } - if err = serializeHeader(w, packetTypeUserAttribute, buf.Len()); err != nil { - return err - } - _, err = w.Write(buf.Bytes()) - return -} - -// ImageData returns zero or more byte slices, each containing -// JPEG File Interchange Format (JFIF), for each photo in the -// user attribute packet. -func (uat *UserAttribute) ImageData() (imageData [][]byte) { - for _, sp := range uat.Contents { - if sp.SubType == UserAttrImageSubpacket && len(sp.Contents) > 16 { - imageData = append(imageData, sp.Contents[16:]) - } - } - return -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/userid.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/userid.go deleted file mode 100644 index 614fbafd..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/packet/userid.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2011 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 packet - -import ( - "io" - "io/ioutil" - "strings" -) - -// UserId contains text that is intended to represent the name and email -// address of the key holder. See RFC 4880, section 5.11. By convention, this -// takes the form "Full Name (Comment) " -type UserId struct { - Id string // By convention, this takes the form "Full Name (Comment) " which is split out in the fields below. - - Name, Comment, Email string -} - -func hasInvalidCharacters(s string) bool { - for _, c := range s { - switch c { - case '(', ')', '<', '>', 0: - return true - } - } - return false -} - -// NewUserId returns a UserId or nil if any of the arguments contain invalid -// characters. The invalid characters are '\x00', '(', ')', '<' and '>' -func NewUserId(name, comment, email string) *UserId { - // RFC 4880 doesn't deal with the structure of userid strings; the - // name, comment and email form is just a convention. However, there's - // no convention about escaping the metacharacters and GPG just refuses - // to create user ids where, say, the name contains a '('. We mirror - // this behaviour. - - if hasInvalidCharacters(name) || hasInvalidCharacters(comment) || hasInvalidCharacters(email) { - return nil - } - - uid := new(UserId) - uid.Name, uid.Comment, uid.Email = name, comment, email - uid.Id = name - if len(comment) > 0 { - if len(uid.Id) > 0 { - uid.Id += " " - } - uid.Id += "(" - uid.Id += comment - uid.Id += ")" - } - if len(email) > 0 { - if len(uid.Id) > 0 { - uid.Id += " " - } - uid.Id += "<" - uid.Id += email - uid.Id += ">" - } - return uid -} - -func (uid *UserId) parse(r io.Reader) (err error) { - // RFC 4880, section 5.11 - b, err := ioutil.ReadAll(r) - if err != nil { - return - } - uid.Id = string(b) - uid.Name, uid.Comment, uid.Email = parseUserId(uid.Id) - return -} - -// Serialize marshals uid to w in the form of an OpenPGP packet, including -// header. -func (uid *UserId) Serialize(w io.Writer) error { - err := serializeHeader(w, packetTypeUserId, len(uid.Id)) - if err != nil { - return err - } - _, err = w.Write([]byte(uid.Id)) - return err -} - -// parseUserId extracts the name, comment and email from a user id string that -// is formatted as "Full Name (Comment) ". -func parseUserId(id string) (name, comment, email string) { - var n, c, e struct { - start, end int - } - var state int - - for offset, rune := range id { - switch state { - case 0: - // Entering name - n.start = offset - state = 1 - fallthrough - case 1: - // In name - if rune == '(' { - state = 2 - n.end = offset - } else if rune == '<' { - state = 5 - n.end = offset - } - case 2: - // Entering comment - c.start = offset - state = 3 - fallthrough - case 3: - // In comment - if rune == ')' { - state = 4 - c.end = offset - } - case 4: - // Between comment and email - if rune == '<' { - state = 5 - } - case 5: - // Entering email - e.start = offset - state = 6 - fallthrough - case 6: - // In email - if rune == '>' { - state = 7 - e.end = offset - } - default: - // After email - } - } - switch state { - case 1: - // ended in the name - n.end = len(id) - case 3: - // ended in comment - c.end = len(id) - case 6: - // ended in email - e.end = len(id) - } - - name = strings.TrimSpace(id[n.start:n.end]) - comment = strings.TrimSpace(id[c.start:c.end]) - email = strings.TrimSpace(id[e.start:e.end]) - - // RFC 2822 3.4: alternate simple form of a mailbox - if email == "" && strings.ContainsRune(name, '@') { - email = name - name = "" - } - - return -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go deleted file mode 100644 index 537aa4c1..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/read.go +++ /dev/null @@ -1,571 +0,0 @@ -// Copyright 2011 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 openpgp implements high level operations on OpenPGP messages. -package openpgp // import "github.com/ProtonMail/go-crypto/openpgp" - -import ( - "crypto" - _ "crypto/sha256" - _ "crypto/sha512" - "hash" - "io" - "strconv" - - "github.com/ProtonMail/go-crypto/openpgp/armor" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm" - "github.com/ProtonMail/go-crypto/openpgp/packet" - _ "golang.org/x/crypto/sha3" -) - -// SignatureType is the armor type for a PGP signature. -var SignatureType = "PGP SIGNATURE" - -// readArmored reads an armored block with the given type. -func readArmored(r io.Reader, expectedType string) (body io.Reader, err error) { - block, err := armor.Decode(r) - if err != nil { - return - } - - if block.Type != expectedType { - return nil, errors.InvalidArgumentError("expected '" + expectedType + "', got: " + block.Type) - } - - return block.Body, nil -} - -// MessageDetails contains the result of parsing an OpenPGP encrypted and/or -// signed message. -type MessageDetails struct { - IsEncrypted bool // true if the message was encrypted. - EncryptedToKeyIds []uint64 // the list of recipient key ids. - IsSymmetricallyEncrypted bool // true if a passphrase could have decrypted the message. - DecryptedWith Key // the private key used to decrypt the message, if any. - IsSigned bool // true if the message is signed. - SignedByKeyId uint64 // the key id of the signer, if any. - SignedBy *Key // the key of the signer, if available. - LiteralData *packet.LiteralData // the metadata of the contents - UnverifiedBody io.Reader // the contents of the message. - - // If IsSigned is true and SignedBy is non-zero then the signature will - // be verified as UnverifiedBody is read. The signature cannot be - // checked until the whole of UnverifiedBody is read so UnverifiedBody - // must be consumed until EOF before the data can be trusted. Even if a - // message isn't signed (or the signer is unknown) the data may contain - // an authentication code that is only checked once UnverifiedBody has - // been consumed. Once EOF has been seen, the following fields are - // valid. (An authentication code failure is reported as a - // SignatureError error when reading from UnverifiedBody.) - Signature *packet.Signature // the signature packet itself. - SignatureError error // nil if the signature is good. - UnverifiedSignatures []*packet.Signature // all other unverified signature packets. - - decrypted io.ReadCloser -} - -// A PromptFunction is used as a callback by functions that may need to decrypt -// a private key, or prompt for a passphrase. It is called with a list of -// acceptable, encrypted private keys and a boolean that indicates whether a -// passphrase is usable. It should either decrypt a private key or return a -// passphrase to try. If the decrypted private key or given passphrase isn't -// correct, the function will be called again, forever. Any error returned will -// be passed up. -type PromptFunction func(keys []Key, symmetric bool) ([]byte, error) - -// A keyEnvelopePair is used to store a private key with the envelope that -// contains a symmetric key, encrypted with that key. -type keyEnvelopePair struct { - key Key - encryptedKey *packet.EncryptedKey -} - -// ReadMessage parses an OpenPGP message that may be signed and/or encrypted. -// The given KeyRing should contain both public keys (for signature -// verification) and, possibly encrypted, private keys for decrypting. -// If config is nil, sensible defaults will be used. -func ReadMessage(r io.Reader, keyring KeyRing, prompt PromptFunction, config *packet.Config) (md *MessageDetails, err error) { - var p packet.Packet - - var symKeys []*packet.SymmetricKeyEncrypted - var pubKeys []keyEnvelopePair - // Integrity protected encrypted packet: SymmetricallyEncrypted or AEADEncrypted - var edp packet.EncryptedDataPacket - - packets := packet.NewReader(r) - md = new(MessageDetails) - md.IsEncrypted = true - - // The message, if encrypted, starts with a number of packets - // containing an encrypted decryption key. The decryption key is either - // encrypted to a public key, or with a passphrase. This loop - // collects these packets. -ParsePackets: - for { - p, err = packets.Next() - if err != nil { - return nil, err - } - switch p := p.(type) { - case *packet.SymmetricKeyEncrypted: - // This packet contains the decryption key encrypted with a passphrase. - md.IsSymmetricallyEncrypted = true - symKeys = append(symKeys, p) - case *packet.EncryptedKey: - // This packet contains the decryption key encrypted to a public key. - md.EncryptedToKeyIds = append(md.EncryptedToKeyIds, p.KeyId) - switch p.Algo { - case packet.PubKeyAlgoRSA, packet.PubKeyAlgoRSAEncryptOnly, packet.PubKeyAlgoElGamal, packet.PubKeyAlgoECDH: - break - default: - continue - } - if keyring != nil { - var keys []Key - if p.KeyId == 0 { - keys = keyring.DecryptionKeys() - } else { - keys = keyring.KeysById(p.KeyId) - } - for _, k := range keys { - pubKeys = append(pubKeys, keyEnvelopePair{k, p}) - } - } - case *packet.SymmetricallyEncrypted: - if !p.IntegrityProtected && !config.AllowUnauthenticatedMessages() { - return nil, errors.UnsupportedError("message is not integrity protected") - } - edp = p - break ParsePackets - case *packet.AEADEncrypted: - edp = p - break ParsePackets - case *packet.Compressed, *packet.LiteralData, *packet.OnePassSignature: - // This message isn't encrypted. - if len(symKeys) != 0 || len(pubKeys) != 0 { - return nil, errors.StructuralError("key material not followed by encrypted message") - } - packets.Unread(p) - return readSignedMessage(packets, nil, keyring, config) - } - } - - var candidates []Key - var decrypted io.ReadCloser - - // Now that we have the list of encrypted keys we need to decrypt at - // least one of them or, if we cannot, we need to call the prompt - // function so that it can decrypt a key or give us a passphrase. -FindKey: - for { - // See if any of the keys already have a private key available - candidates = candidates[:0] - candidateFingerprints := make(map[string]bool) - - for _, pk := range pubKeys { - if pk.key.PrivateKey == nil { - continue - } - if !pk.key.PrivateKey.Encrypted { - if len(pk.encryptedKey.Key) == 0 { - errDec := pk.encryptedKey.Decrypt(pk.key.PrivateKey, config) - if errDec != nil { - continue - } - } - // Try to decrypt symmetrically encrypted - decrypted, err = edp.Decrypt(pk.encryptedKey.CipherFunc, pk.encryptedKey.Key) - if err != nil && err != errors.ErrKeyIncorrect { - return nil, err - } - if decrypted != nil { - md.DecryptedWith = pk.key - break FindKey - } - } else { - fpr := string(pk.key.PublicKey.Fingerprint[:]) - if v := candidateFingerprints[fpr]; v { - continue - } - candidates = append(candidates, pk.key) - candidateFingerprints[fpr] = true - } - } - - if len(candidates) == 0 && len(symKeys) == 0 { - return nil, errors.ErrKeyIncorrect - } - - if prompt == nil { - return nil, errors.ErrKeyIncorrect - } - - passphrase, err := prompt(candidates, len(symKeys) != 0) - if err != nil { - return nil, err - } - - // Try the symmetric passphrase first - if len(symKeys) != 0 && passphrase != nil { - for _, s := range symKeys { - key, cipherFunc, err := s.Decrypt(passphrase) - // In v4, on wrong passphrase, session key decryption is very likely to result in an invalid cipherFunc: - // only for < 5% of cases we will proceed to decrypt the data - if err == nil { - decrypted, err = edp.Decrypt(cipherFunc, key) - if err != nil { - return nil, err - } - if decrypted != nil { - break FindKey - } - } - } - } - } - - md.decrypted = decrypted - if err := packets.Push(decrypted); err != nil { - return nil, err - } - mdFinal, sensitiveParsingErr := readSignedMessage(packets, md, keyring, config) - if sensitiveParsingErr != nil { - return nil, errors.StructuralError("parsing error") - } - return mdFinal, nil -} - -// readSignedMessage reads a possibly signed message if mdin is non-zero then -// that structure is updated and returned. Otherwise a fresh MessageDetails is -// used. -func readSignedMessage(packets *packet.Reader, mdin *MessageDetails, keyring KeyRing, config *packet.Config) (md *MessageDetails, err error) { - if mdin == nil { - mdin = new(MessageDetails) - } - md = mdin - - var p packet.Packet - var h hash.Hash - var wrappedHash hash.Hash - var prevLast bool -FindLiteralData: - for { - p, err = packets.Next() - if err != nil { - return nil, err - } - switch p := p.(type) { - case *packet.Compressed: - if err := packets.Push(p.Body); err != nil { - return nil, err - } - case *packet.OnePassSignature: - if prevLast { - return nil, errors.UnsupportedError("nested signature packets") - } - - if p.IsLast { - prevLast = true - } - - h, wrappedHash, err = hashForSignature(p.Hash, p.SigType) - if err != nil { - md.SignatureError = err - } - - md.IsSigned = true - md.SignedByKeyId = p.KeyId - if keyring != nil { - keys := keyring.KeysByIdUsage(p.KeyId, packet.KeyFlagSign) - if len(keys) > 0 { - md.SignedBy = &keys[0] - } - } - case *packet.LiteralData: - md.LiteralData = p - break FindLiteralData - } - } - - if md.IsSigned && md.SignatureError == nil { - md.UnverifiedBody = &signatureCheckReader{packets, h, wrappedHash, md, config} - } else if md.decrypted != nil { - md.UnverifiedBody = checkReader{md} - } else { - md.UnverifiedBody = md.LiteralData.Body - } - - return md, nil -} - -// hashForSignature returns a pair of hashes that can be used to verify a -// signature. The signature may specify that the contents of the signed message -// should be preprocessed (i.e. to normalize line endings). Thus this function -// returns two hashes. The second should be used to hash the message itself and -// performs any needed preprocessing. -func hashForSignature(hashFunc crypto.Hash, sigType packet.SignatureType) (hash.Hash, hash.Hash, error) { - if _, ok := algorithm.HashToHashIdWithSha1(hashFunc); !ok { - return nil, nil, errors.UnsupportedError("unsupported hash function") - } - if !hashFunc.Available() { - return nil, nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashFunc))) - } - h := hashFunc.New() - - switch sigType { - case packet.SigTypeBinary: - return h, h, nil - case packet.SigTypeText: - return h, NewCanonicalTextHash(h), nil - } - - return nil, nil, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(sigType))) -} - -// checkReader wraps an io.Reader from a LiteralData packet. When it sees EOF -// it closes the ReadCloser from any SymmetricallyEncrypted packet to trigger -// MDC checks. -type checkReader struct { - md *MessageDetails -} - -func (cr checkReader) Read(buf []byte) (int, error) { - n, sensitiveParsingError := cr.md.LiteralData.Body.Read(buf) - if sensitiveParsingError == io.EOF { - mdcErr := cr.md.decrypted.Close() - if mdcErr != nil { - return n, mdcErr - } - return n, io.EOF - } - - if sensitiveParsingError != nil { - return n, errors.StructuralError("parsing error") - } - - return n, nil -} - -// signatureCheckReader wraps an io.Reader from a LiteralData packet and hashes -// the data as it is read. When it sees an EOF from the underlying io.Reader -// it parses and checks a trailing Signature packet and triggers any MDC checks. -type signatureCheckReader struct { - packets *packet.Reader - h, wrappedHash hash.Hash - md *MessageDetails - config *packet.Config -} - -func (scr *signatureCheckReader) Read(buf []byte) (int, error) { - n, sensitiveParsingError := scr.md.LiteralData.Body.Read(buf) - - // Hash only if required - if scr.md.SignedBy != nil { - scr.wrappedHash.Write(buf[:n]) - } - - if sensitiveParsingError == io.EOF { - var p packet.Packet - var readError error - var sig *packet.Signature - - p, readError = scr.packets.Next() - for readError == nil { - var ok bool - if sig, ok = p.(*packet.Signature); ok { - if sig.Version == 5 && (sig.SigType == 0x00 || sig.SigType == 0x01) { - sig.Metadata = scr.md.LiteralData - } - - // If signature KeyID matches - if scr.md.SignedBy != nil && *sig.IssuerKeyId == scr.md.SignedByKeyId { - key := scr.md.SignedBy - signatureError := key.PublicKey.VerifySignature(scr.h, sig) - if signatureError == nil { - signatureError = checkSignatureDetails(key, sig, scr.config) - } - scr.md.Signature = sig - scr.md.SignatureError = signatureError - } else { - scr.md.UnverifiedSignatures = append(scr.md.UnverifiedSignatures, sig) - } - } - - p, readError = scr.packets.Next() - } - - if scr.md.SignedBy != nil && scr.md.Signature == nil { - if scr.md.UnverifiedSignatures == nil { - scr.md.SignatureError = errors.StructuralError("LiteralData not followed by signature") - } else { - scr.md.SignatureError = errors.StructuralError("No matching signature found") - } - } - - // The SymmetricallyEncrypted packet, if any, might have an - // unsigned hash of its own. In order to check this we need to - // close that Reader. - if scr.md.decrypted != nil { - mdcErr := scr.md.decrypted.Close() - if mdcErr != nil { - return n, mdcErr - } - } - return n, io.EOF - } - - if sensitiveParsingError != nil { - return n, errors.StructuralError("parsing error") - } - - return n, nil -} - -// CheckDetachedSignature takes a signed file and a detached signature and -// returns the entity the signature was signed by, if any, and a possible -// signature verification error. If the signer isn't known, -// ErrUnknownIssuer is returned. -func CheckDetachedSignature(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (signer *Entity, err error) { - var expectedHashes []crypto.Hash - return CheckDetachedSignatureAndHash(keyring, signed, signature, expectedHashes, config) -} - -// CheckDetachedSignatureAndHash performs the same actions as -// CheckDetachedSignature and checks that the expected hash functions were used. -func CheckDetachedSignatureAndHash(keyring KeyRing, signed, signature io.Reader, expectedHashes []crypto.Hash, config *packet.Config) (signer *Entity, err error) { - var issuerKeyId uint64 - var hashFunc crypto.Hash - var sigType packet.SignatureType - var keys []Key - var p packet.Packet - - expectedHashesLen := len(expectedHashes) - packets := packet.NewReader(signature) - var sig *packet.Signature - for { - p, err = packets.Next() - if err == io.EOF { - return nil, errors.ErrUnknownIssuer - } - if err != nil { - return nil, err - } - - var ok bool - sig, ok = p.(*packet.Signature) - if !ok { - return nil, errors.StructuralError("non signature packet found") - } - if sig.IssuerKeyId == nil { - return nil, errors.StructuralError("signature doesn't have an issuer") - } - issuerKeyId = *sig.IssuerKeyId - hashFunc = sig.Hash - sigType = sig.SigType - - for i, expectedHash := range expectedHashes { - if hashFunc == expectedHash { - break - } - if i+1 == expectedHashesLen { - return nil, errors.StructuralError("hash algorithm mismatch with cleartext message headers") - } - } - - keys = keyring.KeysByIdUsage(issuerKeyId, packet.KeyFlagSign) - if len(keys) > 0 { - break - } - } - - if len(keys) == 0 { - panic("unreachable") - } - - h, wrappedHash, err := hashForSignature(hashFunc, sigType) - if err != nil { - return nil, err - } - - if _, err := io.Copy(wrappedHash, signed); err != nil && err != io.EOF { - return nil, err - } - - for _, key := range keys { - err = key.PublicKey.VerifySignature(h, sig) - if err == nil { - return key.Entity, checkSignatureDetails(&key, sig, config) - } - } - - return nil, err -} - -// CheckArmoredDetachedSignature performs the same actions as -// CheckDetachedSignature but expects the signature to be armored. -func CheckArmoredDetachedSignature(keyring KeyRing, signed, signature io.Reader, config *packet.Config) (signer *Entity, err error) { - body, err := readArmored(signature, SignatureType) - if err != nil { - return - } - - return CheckDetachedSignature(keyring, signed, body, config) -} - -// checkSignatureDetails returns an error if: -// - The signature (or one of the binding signatures mentioned below) -// has a unknown critical notation data subpacket -// - The primary key of the signing entity is revoked -// The signature was signed by a subkey and: -// - The signing subkey is revoked -// - The primary identity is revoked -// - The signature is expired -// - The primary key of the signing entity is expired according to the -// primary identity binding signature -// The signature was signed by a subkey and: -// - The signing subkey is expired according to the subkey binding signature -// - The signing subkey binding signature is expired -// - The signing subkey cross-signature is expired -// NOTE: The order of these checks is important, as the caller may choose to -// ignore ErrSignatureExpired or ErrKeyExpired errors, but should never -// ignore any other errors. -// TODO: Also return an error if: -// - The primary key is expired according to a direct-key signature -// - (For V5 keys only:) The direct-key signature (exists and) is expired -func checkSignatureDetails(key *Key, signature *packet.Signature, config *packet.Config) error { - now := config.Now() - primaryIdentity := key.Entity.PrimaryIdentity() - signedBySubKey := key.PublicKey != key.Entity.PrimaryKey - sigsToCheck := []*packet.Signature{ signature, primaryIdentity.SelfSignature } - if signedBySubKey { - sigsToCheck = append(sigsToCheck, key.SelfSignature, key.SelfSignature.EmbeddedSignature) - } - for _, sig := range sigsToCheck { - for _, notation := range sig.Notations { - if notation.IsCritical && !config.KnownNotation(notation.Name) { - return errors.SignatureError("unknown critical notation: " + notation.Name) - } - } - } - if key.Entity.Revoked(now) || // primary key is revoked - (signedBySubKey && key.Revoked(now)) || // subkey is revoked - primaryIdentity.Revoked(now) { // primary identity is revoked - return errors.ErrKeyRevoked - } - if key.Entity.PrimaryKey.KeyExpired(primaryIdentity.SelfSignature, now) { // primary key is expired - return errors.ErrKeyExpired - } - if signedBySubKey { - if key.PublicKey.KeyExpired(key.SelfSignature, now) { // subkey is expired - return errors.ErrKeyExpired - } - } - for _, sig := range sigsToCheck { - if sig.SigExpired(now) { // any of the relevant signatures are expired - return errors.ErrSignatureExpired - } - } - return nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/read_write_test_data.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/read_write_test_data.go deleted file mode 100644 index a5224424..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/read_write_test_data.go +++ /dev/null @@ -1,274 +0,0 @@ -package openpgp - -const testKey1KeyId = 0xA34D7E18C20C31BB -const testKey3KeyId = 0x338934250CCC0360 -const testKeyP256KeyId = 0xd44a2c495918513e - -const signedInput = "Signed message\nline 2\nline 3\n" -const signedTextInput = "Signed message\r\nline 2\r\nline 3\r\n" - -const recipientUnspecifiedHex = "848c0300000000000000000103ff62d4d578d03cf40c3da998dfe216c074fa6ddec5e31c197c9666ba292830d91d18716a80f699f9d897389a90e6d62d0238f5f07a5248073c0f24920e4bc4a30c2d17ee4e0cae7c3d4aaa4e8dced50e3010a80ee692175fa0385f62ecca4b56ee6e9980aa3ec51b61b077096ac9e800edaf161268593eedb6cc7027ff5cb32745d250010d407a6221ae22ef18469b444f2822478c4d190b24d36371a95cb40087cdd42d9399c3d06a53c0673349bfb607927f20d1e122bde1e2bf3aa6cae6edf489629bcaa0689539ae3b718914d88ededc3b" - -const detachedSignatureHex = "889c04000102000605024d449cd1000a0910a34d7e18c20c31bb167603ff57718d09f28a519fdc7b5a68b6a3336da04df85e38c5cd5d5bd2092fa4629848a33d85b1729402a2aab39c3ac19f9d573f773cc62c264dc924c067a79dfd8a863ae06c7c8686120760749f5fd9b1e03a64d20a7df3446ddc8f0aeadeaeba7cbaee5c1e366d65b6a0c6cc749bcb912d2f15013f812795c2e29eb7f7b77f39ce77" - -const detachedSignatureTextHex = "889c04010102000605024d449d21000a0910a34d7e18c20c31bbc8c60400a24fbef7342603a41cb1165767bd18985d015fb72fe05db42db36cfb2f1d455967f1e491194fbf6cf88146222b23bf6ffbd50d17598d976a0417d3192ff9cc0034fd00f287b02e90418bbefe609484b09231e4e7a5f3562e199bf39909ab5276c4d37382fe088f6b5c3426fc1052865da8b3ab158672d58b6264b10823dc4b39" - -const detachedSignatureDSAHex = "884604001102000605024d6c4eac000a0910338934250ccc0360f18d00a087d743d6405ed7b87755476629600b8b694a39e900a0abff8126f46faf1547c1743c37b21b4ea15b8f83" - -const detachedSignatureP256Hex = "885e0400130a0006050256e5bb00000a0910d44a2c495918513edef001009841a4f792beb0befccb35c8838a6a87d9b936beaa86db6745ddc7b045eee0cf00fd1ac1f78306b17e965935dd3f8bae4587a76587e4af231efe19cc4011a8434817" - -// The plaintext is https://www.gutenberg.org/cache/epub/1080/pg1080.txt -const modestProposalSha512 = "lbbrB1+WP3T9AaC9OQqBdOcCjgeEQadlulXsNPgVx0tyqPzDHwUugZ2gE7V0ESKAw6kAVfgkcuvfgxAAGaeHtw==" - -const testKeys1And2Hex = "988d044d3c5c10010400b1d13382944bd5aba23a4312968b5095d14f947f600eb478e14a6fcb16b0e0cac764884909c020bc495cfcc39a935387c661507bdb236a0612fb582cac3af9b29cc2c8c70090616c41b662f4da4c1201e195472eb7f4ae1ccbcbf9940fe21d985e379a5563dde5b9a23d35f1cfaa5790da3b79db26f23695107bfaca8e7b5bcd0011010001b41054657374204b6579203120285253412988b804130102002205024d3c5c10021b03060b090807030206150802090a0b0416020301021e01021780000a0910a34d7e18c20c31bbb5b304009cc45fe610b641a2c146331be94dade0a396e73ca725e1b25c21708d9cab46ecca5ccebc23055879df8f99eea39b377962a400f2ebdc36a7c99c333d74aeba346315137c3ff9d0a09b0273299090343048afb8107cf94cbd1400e3026f0ccac7ecebbc4d78588eb3e478fe2754d3ca664bcf3eac96ca4a6b0c8d7df5102f60f6b0020003b88d044d3c5c10010400b201df61d67487301f11879d514f4248ade90c8f68c7af1284c161098de4c28c2850f1ec7b8e30f959793e571542ffc6532189409cb51c3d30dad78c4ad5165eda18b20d9826d8707d0f742e2ab492103a85bbd9ddf4f5720f6de7064feb0d39ee002219765bb07bcfb8b877f47abe270ddeda4f676108cecb6b9bb2ad484a4f0011010001889f04180102000905024d3c5c10021b0c000a0910a34d7e18c20c31bb1a03040085c8d62e16d05dc4e9dad64953c8a2eed8b6c12f92b1575eeaa6dcf7be9473dd5b24b37b6dffbb4e7c99ed1bd3cb11634be19b3e6e207bed7505c7ca111ccf47cb323bf1f8851eb6360e8034cbff8dd149993c959de89f8f77f38e7e98b8e3076323aa719328e2b408db5ec0d03936efd57422ba04f925cdc7b4c1af7590e40ab0020003988d044d3c5c33010400b488c3e5f83f4d561f317817538d9d0397981e9aef1321ca68ebfae1cf8b7d388e19f4b5a24a82e2fbbf1c6c26557a6c5845307a03d815756f564ac7325b02bc83e87d5480a8fae848f07cb891f2d51ce7df83dcafdc12324517c86d472cc0ee10d47a68fd1d9ae49a6c19bbd36d82af597a0d88cc9c49de9df4e696fc1f0b5d0011010001b42754657374204b6579203220285253412c20656e637279707465642070726976617465206b65792988b804130102002205024d3c5c33021b03060b090807030206150802090a0b0416020301021e01021780000a0910d4984f961e35246b98940400908a73b6a6169f700434f076c6c79015a49bee37130eaf23aaa3cfa9ce60bfe4acaa7bc95f1146ada5867e0079babb38804891f4f0b8ebca57a86b249dee786161a755b7a342e68ccf3f78ed6440a93a6626beb9a37aa66afcd4f888790cb4bb46d94a4ae3eb3d7d3e6b00f6bfec940303e89ec5b32a1eaaacce66497d539328b0020003b88d044d3c5c33010400a4e913f9442abcc7f1804ccab27d2f787ffa592077ca935a8bb23165bd8d57576acac647cc596b2c3f814518cc8c82953c7a4478f32e0cf645630a5ba38d9618ef2bc3add69d459ae3dece5cab778938d988239f8c5ae437807075e06c828019959c644ff05ef6a5a1dab72227c98e3a040b0cf219026640698d7a13d8538a570011010001889f04180102000905024d3c5c33021b0c000a0910d4984f961e35246b26c703ff7ee29ef53bc1ae1ead533c408fa136db508434e233d6e62be621e031e5940bbd4c08142aed0f82217e7c3e1ec8de574bc06ccf3c36633be41ad78a9eacd209f861cae7b064100758545cc9dd83db71806dc1cfd5fb9ae5c7474bba0c19c44034ae61bae5eca379383339dece94ff56ff7aa44a582f3e5c38f45763af577c0934b0020003" - -const testKeys1And2PrivateHex = "9501d8044d3c5c10010400b1d13382944bd5aba23a4312968b5095d14f947f600eb478e14a6fcb16b0e0cac764884909c020bc495cfcc39a935387c661507bdb236a0612fb582cac3af9b29cc2c8c70090616c41b662f4da4c1201e195472eb7f4ae1ccbcbf9940fe21d985e379a5563dde5b9a23d35f1cfaa5790da3b79db26f23695107bfaca8e7b5bcd00110100010003ff4d91393b9a8e3430b14d6209df42f98dc927425b881f1209f319220841273a802a97c7bdb8b3a7740b3ab5866c4d1d308ad0d3a79bd1e883aacf1ac92dfe720285d10d08752a7efe3c609b1d00f17f2805b217be53999a7da7e493bfc3e9618fd17018991b8128aea70a05dbce30e4fbe626aa45775fa255dd9177aabf4df7cf0200c1ded12566e4bc2bb590455e5becfb2e2c9796482270a943343a7835de41080582c2be3caf5981aa838140e97afa40ad652a0b544f83eb1833b0957dce26e47b0200eacd6046741e9ce2ec5beb6fb5e6335457844fb09477f83b050a96be7da043e17f3a9523567ed40e7a521f818813a8b8a72209f1442844843ccc7eb9805442570200bdafe0438d97ac36e773c7162028d65844c4d463e2420aa2228c6e50dc2743c3d6c72d0d782a5173fe7be2169c8a9f4ef8a7cf3e37165e8c61b89c346cdc6c1799d2b41054657374204b6579203120285253412988b804130102002205024d3c5c10021b03060b090807030206150802090a0b0416020301021e01021780000a0910a34d7e18c20c31bbb5b304009cc45fe610b641a2c146331be94dade0a396e73ca725e1b25c21708d9cab46ecca5ccebc23055879df8f99eea39b377962a400f2ebdc36a7c99c333d74aeba346315137c3ff9d0a09b0273299090343048afb8107cf94cbd1400e3026f0ccac7ecebbc4d78588eb3e478fe2754d3ca664bcf3eac96ca4a6b0c8d7df5102f60f6b00200009d01d8044d3c5c10010400b201df61d67487301f11879d514f4248ade90c8f68c7af1284c161098de4c28c2850f1ec7b8e30f959793e571542ffc6532189409cb51c3d30dad78c4ad5165eda18b20d9826d8707d0f742e2ab492103a85bbd9ddf4f5720f6de7064feb0d39ee002219765bb07bcfb8b877f47abe270ddeda4f676108cecb6b9bb2ad484a4f00110100010003fd17a7490c22a79c59281fb7b20f5e6553ec0c1637ae382e8adaea295f50241037f8997cf42c1ce26417e015091451b15424b2c59eb8d4161b0975630408e394d3b00f88d4b4e18e2cc85e8251d4753a27c639c83f5ad4a571c4f19d7cd460b9b73c25ade730c99df09637bd173d8e3e981ac64432078263bb6dc30d3e974150dd0200d0ee05be3d4604d2146fb0457f31ba17c057560785aa804e8ca5530a7cd81d3440d0f4ba6851efcfd3954b7e68908fc0ba47f7ac37bf559c6c168b70d3a7c8cd0200da1c677c4bce06a068070f2b3733b0a714e88d62aa3f9a26c6f5216d48d5c2b5624144f3807c0df30be66b3268eeeca4df1fbded58faf49fc95dc3c35f134f8b01fd1396b6c0fc1b6c4f0eb8f5e44b8eace1e6073e20d0b8bc5385f86f1cf3f050f66af789f3ef1fc107b7f4421e19e0349c730c68f0a226981f4e889054fdb4dc149e8e889f04180102000905024d3c5c10021b0c000a0910a34d7e18c20c31bb1a03040085c8d62e16d05dc4e9dad64953c8a2eed8b6c12f92b1575eeaa6dcf7be9473dd5b24b37b6dffbb4e7c99ed1bd3cb11634be19b3e6e207bed7505c7ca111ccf47cb323bf1f8851eb6360e8034cbff8dd149993c959de89f8f77f38e7e98b8e3076323aa719328e2b408db5ec0d03936efd57422ba04f925cdc7b4c1af7590e40ab00200009501fe044d3c5c33010400b488c3e5f83f4d561f317817538d9d0397981e9aef1321ca68ebfae1cf8b7d388e19f4b5a24a82e2fbbf1c6c26557a6c5845307a03d815756f564ac7325b02bc83e87d5480a8fae848f07cb891f2d51ce7df83dcafdc12324517c86d472cc0ee10d47a68fd1d9ae49a6c19bbd36d82af597a0d88cc9c49de9df4e696fc1f0b5d0011010001fe030302e9030f3c783e14856063f16938530e148bc57a7aa3f3e4f90df9dceccdc779bc0835e1ad3d006e4a8d7b36d08b8e0de5a0d947254ecfbd22037e6572b426bcfdc517796b224b0036ff90bc574b5509bede85512f2eefb520fb4b02aa523ba739bff424a6fe81c5041f253f8d757e69a503d3563a104d0d49e9e890b9d0c26f96b55b743883b472caa7050c4acfd4a21f875bdf1258d88bd61224d303dc9df77f743137d51e6d5246b88c406780528fd9a3e15bab5452e5b93970d9dcc79f48b38651b9f15bfbcf6da452837e9cc70683d1bdca94507870f743e4ad902005812488dd342f836e72869afd00ce1850eea4cfa53ce10e3608e13d3c149394ee3cbd0e23d018fcbcb6e2ec5a1a22972d1d462ca05355d0d290dd2751e550d5efb38c6c89686344df64852bf4ff86638708f644e8ec6bd4af9b50d8541cb91891a431326ab2e332faa7ae86cfb6e0540aa63160c1e5cdd5a4add518b303fff0a20117c6bc77f7cfbaf36b04c865c6c2b42754657374204b6579203220285253412c20656e637279707465642070726976617465206b65792988b804130102002205024d3c5c33021b03060b090807030206150802090a0b0416020301021e01021780000a0910d4984f961e35246b98940400908a73b6a6169f700434f076c6c79015a49bee37130eaf23aaa3cfa9ce60bfe4acaa7bc95f1146ada5867e0079babb38804891f4f0b8ebca57a86b249dee786161a755b7a342e68ccf3f78ed6440a93a6626beb9a37aa66afcd4f888790cb4bb46d94a4ae3eb3d7d3e6b00f6bfec940303e89ec5b32a1eaaacce66497d539328b00200009d01fe044d3c5c33010400a4e913f9442abcc7f1804ccab27d2f787ffa592077ca935a8bb23165bd8d57576acac647cc596b2c3f814518cc8c82953c7a4478f32e0cf645630a5ba38d9618ef2bc3add69d459ae3dece5cab778938d988239f8c5ae437807075e06c828019959c644ff05ef6a5a1dab72227c98e3a040b0cf219026640698d7a13d8538a570011010001fe030302e9030f3c783e148560f936097339ae381d63116efcf802ff8b1c9360767db5219cc987375702a4123fd8657d3e22700f23f95020d1b261eda5257e9a72f9a918e8ef22dd5b3323ae03bbc1923dd224db988cadc16acc04b120a9f8b7e84da9716c53e0334d7b66586ddb9014df604b41be1e960dcfcbc96f4ed150a1a0dd070b9eb14276b9b6be413a769a75b519a53d3ecc0c220e85cd91ca354d57e7344517e64b43b6e29823cbd87eae26e2b2e78e6dedfbb76e3e9f77bcb844f9a8932eb3db2c3f9e44316e6f5d60e9e2a56e46b72abe6b06dc9a31cc63f10023d1f5e12d2a3ee93b675c96f504af0001220991c88db759e231b3320dcedf814dcf723fd9857e3d72d66a0f2af26950b915abdf56c1596f46a325bf17ad4810d3535fb02a259b247ac3dbd4cc3ecf9c51b6c07cebb009c1506fba0a89321ec8683e3fd009a6e551d50243e2d5092fefb3321083a4bad91320dc624bd6b5dddf93553e3d53924c05bfebec1fb4bd47e89a1a889f04180102000905024d3c5c33021b0c000a0910d4984f961e35246b26c703ff7ee29ef53bc1ae1ead533c408fa136db508434e233d6e62be621e031e5940bbd4c08142aed0f82217e7c3e1ec8de574bc06ccf3c36633be41ad78a9eacd209f861cae7b064100758545cc9dd83db71806dc1cfd5fb9ae5c7474bba0c19c44034ae61bae5eca379383339dece94ff56ff7aa44a582f3e5c38f45763af577c0934b0020000" - -const dsaElGamalTestKeysHex = "9501e1044dfcb16a110400aa3e5c1a1f43dd28c2ffae8abf5cfce555ee874134d8ba0a0f7b868ce2214beddc74e5e1e21ded354a95d18acdaf69e5e342371a71fbb9093162e0c5f3427de413a7f2c157d83f5cd2f9d791256dc4f6f0e13f13c3302af27f2384075ab3021dff7a050e14854bbde0a1094174855fc02f0bae8e00a340d94a1f22b32e48485700a0cec672ac21258fb95f61de2ce1af74b2c4fa3e6703ff698edc9be22c02ae4d916e4fa223f819d46582c0516235848a77b577ea49018dcd5e9e15cff9dbb4663a1ae6dd7580fa40946d40c05f72814b0f88481207e6c0832c3bded4853ebba0a7e3bd8e8c66df33d5a537cd4acf946d1080e7a3dcea679cb2b11a72a33a2b6a9dc85f466ad2ddf4c3db6283fa645343286971e3dd700703fc0c4e290d45767f370831a90187e74e9972aae5bff488eeff7d620af0362bfb95c1a6c3413ab5d15a2e4139e5d07a54d72583914661ed6a87cce810be28a0aa8879a2dd39e52fb6fe800f4f181ac7e328f740cde3d09a05cecf9483e4cca4253e60d4429ffd679d9996a520012aad119878c941e3cf151459873bdfc2a9563472fe0303027a728f9feb3b864260a1babe83925ce794710cfd642ee4ae0e5b9d74cee49e9c67b6cd0ea5dfbb582132195a121356a1513e1bca73e5b80c58c7ccb4164453412f456c47616d616c2054657374204b65792031886204131102002205024dfcb16a021b03060b090807030206150802090a0b0416020301021e01021780000a091033af447ccd759b09fadd00a0b8fd6f5a790bad7e9f2dbb7632046dc4493588db009c087c6a9ba9f7f49fab221587a74788c00db4889ab00200009d0157044dfcb16a1004008dec3f9291205255ccff8c532318133a6840739dd68b03ba942676f9038612071447bf07d00d559c5c0875724ea16a4c774f80d8338b55fca691a0522e530e604215b467bbc9ccfd483a1da99d7bc2648b4318fdbd27766fc8bfad3fddb37c62b8ae7ccfe9577e9b8d1e77c1d417ed2c2ef02d52f4da11600d85d3229607943700030503ff506c94c87c8cab778e963b76cf63770f0a79bf48fb49d3b4e52234620fc9f7657f9f8d56c96a2b7c7826ae6b57ebb2221a3fe154b03b6637cea7e6d98e3e45d87cf8dc432f723d3d71f89c5192ac8d7290684d2c25ce55846a80c9a7823f6acd9bb29fa6cd71f20bc90eccfca20451d0c976e460e672b000df49466408d527affe0303027a728f9feb3b864260abd761730327bca2aaa4ea0525c175e92bf240682a0e83b226f97ecb2e935b62c9a133858ce31b271fa8eb41f6a1b3cd72a63025ce1a75ee4180dcc284884904181102000905024dfcb16a021b0c000a091033af447ccd759b09dd0b009e3c3e7296092c81bee5a19929462caaf2fff3ae26009e218c437a2340e7ea628149af1ec98ec091a43992b00200009501e1044dfcb1be1104009f61faa61aa43df75d128cbe53de528c4aec49ce9360c992e70c77072ad5623de0a3a6212771b66b39a30dad6781799e92608316900518ec01184a85d872365b7d2ba4bacfb5882ea3c2473d3750dc6178cc1cf82147fb58caa28b28e9f12f6d1efcb0534abed644156c91cca4ab78834268495160b2400bc422beb37d237c2300a0cac94911b6d493bda1e1fbc6feeca7cb7421d34b03fe22cec6ccb39675bb7b94a335c2b7be888fd3906a1125f33301d8aa6ec6ee6878f46f73961c8d57a3e9544d8ef2a2cbfd4d52da665b1266928cfe4cb347a58c412815f3b2d2369dec04b41ac9a71cc9547426d5ab941cccf3b18575637ccfb42df1a802df3cfe0a999f9e7109331170e3a221991bf868543960f8c816c28097e503fe319db10fb98049f3a57d7c80c420da66d56f3644371631fad3f0ff4040a19a4fedc2d07727a1b27576f75a4d28c47d8246f27071e12d7a8de62aad216ddbae6aa02efd6b8a3e2818cda48526549791ab277e447b3a36c57cefe9b592f5eab73959743fcc8e83cbefec03a329b55018b53eec196765ae40ef9e20521a603c551efe0303020950d53a146bf9c66034d00c23130cce95576a2ff78016ca471276e8227fb30b1ffbd92e61804fb0c3eff9e30b1a826ee8f3e4730b4d86273ca977b4164453412f456c47616d616c2054657374204b65792032886204131102002205024dfcb1be021b03060b090807030206150802090a0b0416020301021e01021780000a0910a86bf526325b21b22bd9009e34511620415c974750a20df5cb56b182f3b48e6600a0a9466cb1a1305a84953445f77d461593f1d42bc1b00200009d0157044dfcb1be1004009565a951da1ee87119d600c077198f1c1bceb0f7aa54552489298e41ff788fa8f0d43a69871f0f6f77ebdfb14a4260cf9fbeb65d5844b4272a1904dd95136d06c3da745dc46327dd44a0f16f60135914368c8039a34033862261806bb2c5ce1152e2840254697872c85441ccb7321431d75a747a4bfb1d2c66362b51ce76311700030503fc0ea76601c196768070b7365a200e6ddb09307f262d5f39eec467b5f5784e22abdf1aa49226f59ab37cb49969d8f5230ea65caf56015abda62604544ed526c5c522bf92bed178a078789f6c807b6d34885688024a5bed9e9f8c58d11d4b82487b44c5f470c5606806a0443b79cadb45e0f897a561a53f724e5349b9267c75ca17fe0303020950d53a146bf9c660bc5f4ce8f072465e2d2466434320c1e712272fafc20e342fe7608101580fa1a1a367e60486a7cd1246b7ef5586cf5e10b32762b710a30144f12dd17dd4884904181102000905024dfcb1be021b0c000a0910a86bf526325b21b2904c00a0b2b66b4b39ccffda1d10f3ea8d58f827e30a8b8e009f4255b2d8112a184e40cde43a34e8655ca7809370b0020000" - -const signedMessageHex = "a3019bc0cbccc0c4b8d8b74ee2108fe16ec6d3ca490cbe362d3f8333d3f352531472538b8b13d353b97232f352158c20943157c71c16064626063656269052062e4e01987e9b6fccff4b7df3a34c534b23e679cbec3bc0f8f6e64dfb4b55fe3f8efa9ce110ddb5cd79faf1d753c51aecfa669f7e7aa043436596cccc3359cb7dd6bbe9ecaa69e5989d9e57209571edc0b2fa7f57b9b79a64ee6e99ce1371395fee92fec2796f7b15a77c386ff668ee27f6d38f0baa6c438b561657377bf6acff3c5947befd7bf4c196252f1d6e5c524d0300" - -const signedTextMessageHex = "a3019bc0cbccc8c4b8d8b74ee2108fe16ec6d36a250cbece0c178233d3f352531472538b8b13d35379b97232f352158ca0b4312f57c71c1646462606365626906a062e4e019811591798ff99bf8afee860b0d8a8c2a85c3387e3bcf0bb3b17987f2bbcfab2aa526d930cbfd3d98757184df3995c9f3e7790e36e3e9779f06089d4c64e9e47dd6202cb6e9bc73c5d11bb59fbaf89d22d8dc7cf199ddf17af96e77c5f65f9bbed56f427bd8db7af37f6c9984bf9385efaf5f184f986fb3e6adb0ecfe35bbf92d16a7aa2a344fb0bc52fb7624f0200" - -const signedEncryptedMessageHex = "c18c032a67d68660df41c70103ff5a84c9a72f80e74ef0384c2d6a9ebfe2b09e06a8f298394f6d2abf174e40934ab0ec01fb2d0ddf21211c6fe13eb238563663b017a6b44edca552eb4736c4b7dc6ed907dd9e12a21b51b64b46f902f76fb7aaf805c1db8070574d8d0431a23e324a750f77fb72340a17a42300ee4ca8207301e95a731da229a63ab9c6b44541fbd2c11d016d810b3b3b2b38f15b5b40f0a4910332829c2062f1f7cc61f5b03677d73c54cafa1004ced41f315d46444946faae571d6f426e6dbd45d9780eb466df042005298adabf7ce0ef766dfeb94cd449c7ed0046c880339599c4711af073ce649b1e237c40b50a5536283e03bdbb7afad78bd08707715c67fb43295f905b4c479178809d429a8e167a9a8c6dfd8ab20b4edebdc38d6dec879a3202e1b752690d9bb5b0c07c5a227c79cc200e713a99251a4219d62ad5556900cf69bd384b6c8e726c7be267471d0d23af956da165af4af757246c2ebcc302b39e8ef2fccb4971b234fcda22d759ddb20e27269ee7f7fe67898a9de721bfa02ab0becaa046d00ea16cb1afc4e2eab40d0ac17121c565686e5cbd0cbdfbd9d6db5c70278b9c9db5a83176d04f61fbfbc4471d721340ede2746e5c312ded4f26787985af92b64fae3f253dbdde97f6a5e1996fd4d865599e32ff76325d3e9abe93184c02988ee89a4504356a4ef3b9b7a57cbb9637ca90af34a7676b9ef559325c3cca4e29d69fec1887f5440bb101361d744ad292a8547f22b4f22b419a42aa836169b89190f46d9560824cb2ac6e8771de8223216a5e647e132ab9eebcba89569ab339cb1c3d70fe806b31f4f4c600b4103b8d7583ebff16e43dcda551e6530f975122eb8b29" - -const verifiedSignatureEncryptedMessageHex = "c2b304000108000605026048f6d600210910a34d7e18c20c31bb1621045fb74b1d03b1e3cb31bc2f8aa34d7e18c20c31bb9a3b0400a32ddac1af259c1b0abab0041327ea04970944401978fb647dd1cf9aba4f164e43f0d8a9389501886474bdd4a6e77f6aea945c07dfbf87743835b44cc2c39a1f9aeecfa83135abc92e18e50396f2e6a06c44e0188b0081effbfb4160d28f118d4ff73dd199a102e47cffd8c7ff2bacd83ae72b5820c021a486766dd587b5da61" - -const unverifiedSignatureEncryptedMessageHex = "c2b304000108000605026048f6d600210910a34d7e18c20c31bb1621045fb74b1d03b1e3cb31bc2f8aa34d7e18c20c31bb9a3b0400a32ddac1af259c1b0abab0041327ea04970944401978fb647dd1cf9aba4f164e43f0d8a9389501886474bdd4a6e77f6aea945c07dfbf87743835b44cc2c39a1f9aeecfa83135abc92e18e50396f2e6a06c44e0188b0081effbfb4160d28f118d4ff73dd199a102e47cffd8c7ff2bacd83ae72b5820c021a486766dd587b5da61" - -const signedEncryptedMessage2Hex = "85010e03cf6a7abcd43e36731003fb057f5495b79db367e277cdbe4ab90d924ddee0c0381494112ff8c1238fb0184af35d1731573b01bc4c55ecacd2aafbe2003d36310487d1ecc9ac994f3fada7f9f7f5c3a64248ab7782906c82c6ff1303b69a84d9a9529c31ecafbcdb9ba87e05439897d87e8a2a3dec55e14df19bba7f7bd316291c002ae2efd24f83f9e3441203fc081c0c23dc3092a454ca8a082b27f631abf73aca341686982e8fbda7e0e7d863941d68f3de4a755c2964407f4b5e0477b3196b8c93d551dd23c8beef7d0f03fbb1b6066f78907faf4bf1677d8fcec72651124080e0b7feae6b476e72ab207d38d90b958759fdedfc3c6c35717c9dbfc979b3cfbbff0a76d24a5e57056bb88acbd2a901ef64bc6e4db02adc05b6250ff378de81dca18c1910ab257dff1b9771b85bb9bbe0a69f5989e6d1710a35e6dfcceb7d8fb5ccea8db3932b3d9ff3fe0d327597c68b3622aec8e3716c83a6c93f497543b459b58ba504ed6bcaa747d37d2ca746fe49ae0a6ce4a8b694234e941b5159ff8bd34b9023da2814076163b86f40eed7c9472f81b551452d5ab87004a373c0172ec87ea6ce42ccfa7dbdad66b745496c4873d8019e8c28d6b3" - -const signatureEncryptedMessage2Hex = "c24604001102000605024dfd0166000a091033af447ccd759b09bae600a096ec5e63ecf0a403085e10f75cc3bab327663282009f51fad9df457ed8d2b70d8a73c76e0443eac0f377" - -const symmetricallyEncryptedCompressedHex = "c32e040903085a357c1a7b5614ed00cc0d1d92f428162058b3f558a0fb0980d221ebac6c97d5eda4e0fe32f6e706e94dd263012d6ca1ef8c4bbd324098225e603a10c85ebf09cbf7b5aeeb5ce46381a52edc51038b76a8454483be74e6dcd1e50d5689a8ae7eceaeefed98a0023d49b22eb1f65c2aa1ef1783bb5e1995713b0457102ec3c3075fe871267ffa4b686ad5d52000d857" - -const dsaTestKeyHex = "9901a2044d6c49de110400cb5ce438cf9250907ac2ba5bf6547931270b89f7c4b53d9d09f4d0213a5ef2ec1f26806d3d259960f872a4a102ef1581ea3f6d6882d15134f21ef6a84de933cc34c47cc9106efe3bd84c6aec12e78523661e29bc1a61f0aab17fa58a627fd5fd33f5149153fbe8cd70edf3d963bc287ef875270ff14b5bfdd1bca4483793923b00a0fe46d76cb6e4cbdc568435cd5480af3266d610d303fe33ae8273f30a96d4d34f42fa28ce1112d425b2e3bf7ea553d526e2db6b9255e9dc7419045ce817214d1a0056dbc8d5289956a4b1b69f20f1105124096e6a438f41f2e2495923b0f34b70642607d45559595c7fe94d7fa85fc41bf7d68c1fd509ebeaa5f315f6059a446b9369c277597e4f474a9591535354c7e7f4fd98a08aa60400b130c24ff20bdfbf683313f5daebf1c9b34b3bdadfc77f2ddd72ee1fb17e56c473664bc21d66467655dd74b9005e3a2bacce446f1920cd7017231ae447b67036c9b431b8179deacd5120262d894c26bc015bffe3d827ba7087ad9b700d2ca1f6d16cc1786581e5dd065f293c31209300f9b0afcc3f7c08dd26d0a22d87580b4db41054657374204b65792033202844534129886204131102002205024d6c49de021b03060b090807030206150802090a0b0416020301021e01021780000a0910338934250ccc03607e0400a0bdb9193e8a6b96fc2dfc108ae848914b504481f100a09c4dc148cb693293a67af24dd40d2b13a9e36794" - -const dsaTestKeyPrivateHex = "9501bb044d6c49de110400cb5ce438cf9250907ac2ba5bf6547931270b89f7c4b53d9d09f4d0213a5ef2ec1f26806d3d259960f872a4a102ef1581ea3f6d6882d15134f21ef6a84de933cc34c47cc9106efe3bd84c6aec12e78523661e29bc1a61f0aab17fa58a627fd5fd33f5149153fbe8cd70edf3d963bc287ef875270ff14b5bfdd1bca4483793923b00a0fe46d76cb6e4cbdc568435cd5480af3266d610d303fe33ae8273f30a96d4d34f42fa28ce1112d425b2e3bf7ea553d526e2db6b9255e9dc7419045ce817214d1a0056dbc8d5289956a4b1b69f20f1105124096e6a438f41f2e2495923b0f34b70642607d45559595c7fe94d7fa85fc41bf7d68c1fd509ebeaa5f315f6059a446b9369c277597e4f474a9591535354c7e7f4fd98a08aa60400b130c24ff20bdfbf683313f5daebf1c9b34b3bdadfc77f2ddd72ee1fb17e56c473664bc21d66467655dd74b9005e3a2bacce446f1920cd7017231ae447b67036c9b431b8179deacd5120262d894c26bc015bffe3d827ba7087ad9b700d2ca1f6d16cc1786581e5dd065f293c31209300f9b0afcc3f7c08dd26d0a22d87580b4d00009f592e0619d823953577d4503061706843317e4fee083db41054657374204b65792033202844534129886204131102002205024d6c49de021b03060b090807030206150802090a0b0416020301021e01021780000a0910338934250ccc03607e0400a0bdb9193e8a6b96fc2dfc108ae848914b504481f100a09c4dc148cb693293a67af24dd40d2b13a9e36794" - -const p256TestKeyHex = "98520456e5b83813082a8648ce3d030107020304a2072cd6d21321266c758cc5b83fab0510f751cb8d91897cddb7047d8d6f185546e2107111b0a95cb8ef063c33245502af7a65f004d5919d93ee74eb71a66253b424502d3235362054657374204b6579203c696e76616c6964406578616d706c652e636f6d3e8879041313080021050256e5b838021b03050b09080702061508090a0b020416020301021e01021780000a0910d44a2c495918513e54e50100dfa64f97d9b47766fc1943c6314ba3f2b2a103d71ad286dc5b1efb96a345b0c80100dbc8150b54241f559da6ef4baacea6d31902b4f4b1bdc09b34bf0502334b7754b8560456e5b83812082a8648ce3d030107020304bfe3cea9cee13486f8d518aa487fecab451f25467d2bf08e58f63e5fa525d5482133e6a79299c274b068ef0be448152ad65cf11cf764348588ca4f6a0bcf22b6030108078861041813080009050256e5b838021b0c000a0910d44a2c495918513e4a4800ff49d589fa64024ad30be363a032e3a0e0e6f5db56ba4c73db850518bf0121b8f20100fd78e065f4c70ea5be9df319ea67e493b936fc78da834a71828043d3154af56e" - -const p256TestKeyPrivateHex = "94a50456e5b83813082a8648ce3d030107020304a2072cd6d21321266c758cc5b83fab0510f751cb8d91897cddb7047d8d6f185546e2107111b0a95cb8ef063c33245502af7a65f004d5919d93ee74eb71a66253fe070302f0c2bfb0b6c30f87ee1599472b8636477eab23ced13b271886a4b50ed34c9d8436af5af5b8f88921f0efba6ef8c37c459bbb88bc1c6a13bbd25c4ce9b1e97679569ee77645d469bf4b43de637f5561b424502d3235362054657374204b6579203c696e76616c6964406578616d706c652e636f6d3e8879041313080021050256e5b838021b03050b09080702061508090a0b020416020301021e01021780000a0910d44a2c495918513e54e50100dfa64f97d9b47766fc1943c6314ba3f2b2a103d71ad286dc5b1efb96a345b0c80100dbc8150b54241f559da6ef4baacea6d31902b4f4b1bdc09b34bf0502334b77549ca90456e5b83812082a8648ce3d030107020304bfe3cea9cee13486f8d518aa487fecab451f25467d2bf08e58f63e5fa525d5482133e6a79299c274b068ef0be448152ad65cf11cf764348588ca4f6a0bcf22b603010807fe0703027510012471a603cfee2968dce19f732721ddf03e966fd133b4e3c7a685b788705cbc46fb026dc94724b830c9edbaecd2fb2c662f23169516cacd1fe423f0475c364ecc10abcabcfd4bbbda1a36a1bd8861041813080009050256e5b838021b0c000a0910d44a2c495918513e4a4800ff49d589fa64024ad30be363a032e3a0e0e6f5db56ba4c73db850518bf0121b8f20100fd78e065f4c70ea5be9df319ea67e493b936fc78da834a71828043d3154af56e" - -const armoredPrivateKeyBlock = `-----BEGIN PGP PRIVATE KEY BLOCK----- -Version: GnuPG v1.4.10 (GNU/Linux) - -lQHYBE2rFNoBBADFwqWQIW/DSqcB4yCQqnAFTJ27qS5AnB46ccAdw3u4Greeu3Bp -idpoHdjULy7zSKlwR1EA873dO/k/e11Ml3dlAFUinWeejWaK2ugFP6JjiieSsrKn -vWNicdCS4HTWn0X4sjl0ZiAygw6GNhqEQ3cpLeL0g8E9hnYzJKQ0LWJa0QARAQAB -AAP/TB81EIo2VYNmTq0pK1ZXwUpxCrvAAIG3hwKjEzHcbQznsjNvPUihZ+NZQ6+X -0HCfPAdPkGDCLCb6NavcSW+iNnLTrdDnSI6+3BbIONqWWdRDYJhqZCkqmG6zqSfL -IdkJgCw94taUg5BWP/AAeQrhzjChvpMQTVKQL5mnuZbUCeMCAN5qrYMP2S9iKdnk -VANIFj7656ARKt/nf4CBzxcpHTyB8+d2CtPDKCmlJP6vL8t58Jmih+kHJMvC0dzn -gr5f5+sCAOOe5gt9e0am7AvQWhdbHVfJU0TQJx+m2OiCJAqGTB1nvtBLHdJnfdC9 -TnXXQ6ZXibqLyBies/xeY2sCKL5qtTMCAKnX9+9d/5yQxRyrQUHt1NYhaXZnJbHx -q4ytu0eWz+5i68IYUSK69jJ1NWPM0T6SkqpB3KCAIv68VFm9PxqG1KmhSrQIVGVz -dCBLZXmIuAQTAQIAIgUCTasU2gIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AA -CgkQO9o98PRieSoLhgQAkLEZex02Qt7vGhZzMwuN0R22w3VwyYyjBx+fM3JFETy1 -ut4xcLJoJfIaF5ZS38UplgakHG0FQ+b49i8dMij0aZmDqGxrew1m4kBfjXw9B/v+ -eIqpODryb6cOSwyQFH0lQkXC040pjq9YqDsO5w0WYNXYKDnzRV0p4H1pweo2VDid -AdgETasU2gEEAN46UPeWRqKHvA99arOxee38fBt2CI08iiWyI8T3J6ivtFGixSqV -bRcPxYO/qLpVe5l84Nb3X71GfVXlc9hyv7CD6tcowL59hg1E/DC5ydI8K8iEpUmK -/UnHdIY5h8/kqgGxkY/T/hgp5fRQgW1ZoZxLajVlMRZ8W4tFtT0DeA+JABEBAAEA -A/0bE1jaaZKj6ndqcw86jd+QtD1SF+Cf21CWRNeLKnUds4FRRvclzTyUMuWPkUeX -TaNNsUOFqBsf6QQ2oHUBBK4VCHffHCW4ZEX2cd6umz7mpHW6XzN4DECEzOVksXtc -lUC1j4UB91DC/RNQqwX1IV2QLSwssVotPMPqhOi0ZLNY7wIA3n7DWKInxYZZ4K+6 -rQ+POsz6brEoRHwr8x6XlHenq1Oki855pSa1yXIARoTrSJkBtn5oI+f8AzrnN0BN -oyeQAwIA/7E++3HDi5aweWrViiul9cd3rcsS0dEnksPhvS0ozCJiHsq/6GFmy7J8 -QSHZPteedBnZyNp5jR+H7cIfVN3KgwH/Skq4PsuPhDq5TKK6i8Pc1WW8MA6DXTdU -nLkX7RGmMwjC0DBf7KWAlPjFaONAX3a8ndnz//fy1q7u2l9AZwrj1qa1iJ8EGAEC -AAkFAk2rFNoCGwwACgkQO9o98PRieSo2/QP/WTzr4ioINVsvN1akKuekmEMI3LAp -BfHwatufxxP1U+3Si/6YIk7kuPB9Hs+pRqCXzbvPRrI8NHZBmc8qIGthishdCYad -AHcVnXjtxrULkQFGbGvhKURLvS9WnzD/m1K2zzwxzkPTzT9/Yf06O6Mal5AdugPL -VrM0m72/jnpKo04= -=zNCn ------END PGP PRIVATE KEY BLOCK-----` - -const e2ePublicKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Charset: UTF-8 - -xv8AAABSBAAAAAATCCqGSM49AwEHAgME1LRoXSpOxtHXDUdmuvzchyg6005qIBJ4 -sfaSxX7QgH9RV2ONUhC+WiayCNADq+UMzuR/vunSr4aQffXvuGnR383/AAAAFDxk -Z2lsQHlhaG9vLWluYy5jb20+wv8AAACGBBATCAA4/wAAAAWCVGvAG/8AAAACiwn/ -AAAACZC2VkQCOjdvYf8AAAAFlQgJCgv/AAAAA5YBAv8AAAACngEAAE1BAP0X8veD -24IjmI5/C6ZAfVNXxgZZFhTAACFX75jUA3oD6AEAzoSwKf1aqH6oq62qhCN/pekX -+WAsVMBhNwzLpqtCRjLO/wAAAFYEAAAAABIIKoZIzj0DAQcCAwT50ain7vXiIRv8 -B1DO3x3cE/aattZ5sHNixJzRCXi2vQIA5QmOxZ6b5jjUekNbdHG3SZi1a2Ak5mfX -fRxC/5VGAwEIB8L/AAAAZQQYEwgAGP8AAAAFglRrwBz/AAAACZC2VkQCOjdvYQAA -FJAA9isX3xtGyMLYwp2F3nXm7QEdY5bq5VUcD/RJlj792VwA/1wH0pCzVLl4Q9F9 -ex7En5r7rHR5xwX82Msc+Rq9dSyO -=7MrZ ------END PGP PUBLIC KEY BLOCK-----` - -const dsaKeyWithSHA512 = `9901a2044f04b07f110400db244efecc7316553ee08d179972aab87bb1214de7692593fcf5b6feb1c80fba268722dd464748539b85b81d574cd2d7ad0ca2444de4d849b8756bad7768c486c83a824f9bba4af773d11742bdfb4ac3b89ef8cc9452d4aad31a37e4b630d33927bff68e879284a1672659b8b298222fc68f370f3e24dccacc4a862442b9438b00a0ea444a24088dc23e26df7daf8f43cba3bffc4fe703fe3d6cd7fdca199d54ed8ae501c30e3ec7871ea9cdd4cf63cfe6fc82281d70a5b8bb493f922cd99fba5f088935596af087c8d818d5ec4d0b9afa7f070b3d7c1dd32a84fca08d8280b4890c8da1dde334de8e3cad8450eed2a4a4fcc2db7b8e5528b869a74a7f0189e11ef097ef1253582348de072bb07a9fa8ab838e993cef0ee203ff49298723e2d1f549b00559f886cd417a41692ce58d0ac1307dc71d85a8af21b0cf6eaa14baf2922d3a70389bedf17cc514ba0febbd107675a372fe84b90162a9e88b14d4b1c6be855b96b33fb198c46f058568817780435b6936167ebb3724b680f32bf27382ada2e37a879b3d9de2abe0c3f399350afd1ad438883f4791e2e3b4184453412068617368207472756e636174696f6e207465737488620413110a002205024f04b07f021b03060b090807030206150802090a0b0416020301021e01021780000a0910ef20e0cefca131581318009e2bf3bf047a44d75a9bacd00161ee04d435522397009a03a60d51bd8a568c6c021c8d7cf1be8d990d6417b0020003` - -const unknownHashFunctionHex = `8a00000040040001990006050253863c24000a09103b4fe6acc0b21f32ffff0101010101010101010101010101010101010101010101010101010101010101010101010101` - -const rsaSignatureBadMPIlength = `8a00000040040001030006050253863c24000a09103b4fe6acc0b21f32ffff0101010101010101010101010101010101010101010101010101010101010101010101010101` - -const missingHashFunctionHex = `8a00000040040001030006050253863c24000a09103b4fe6acc0b21f32ffff0101010101010101010101010101010101010101010101010101010101010101010101010101` - -const campbellQuine = `a0b001000300fcffa0b001000d00f2ff000300fcffa0b001000d00f2ff8270a01c00000500faff8270a01c00000500faff000500faff001400ebff8270a01c00000500faff000500faff001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400001400ebff428821c400000000ffff000000ffff000b00f4ff428821c400000000ffff000000ffff000b00f4ff0233214c40000100feff000233214c40000100feff0000` - -const keyV4forVerifyingSignedMessageV3 = `-----BEGIN PGP PUBLIC KEY BLOCK----- -Comment: GPGTools - https://gpgtools.org - -mI0EVfxoFQEEAMBIqmbDfYygcvP6Phr1wr1XI41IF7Qixqybs/foBF8qqblD9gIY -BKpXjnBOtbkcVOJ0nljd3/sQIfH4E0vQwK5/4YRQSI59eKOqd6Fx+fWQOLG+uu6z -tewpeCj9LLHvibx/Sc7VWRnrznia6ftrXxJ/wHMezSab3tnGC0YPVdGNABEBAAG0 -JEdvY3J5cHRvIFRlc3QgS2V5IDx0aGVtYXhAZ21haWwuY29tPoi5BBMBCgAjBQJV -/GgVAhsDBwsJCAcDAgEGFQgCCQoLBBYCAwECHgECF4AACgkQeXnQmhdGW9PFVAP+ -K7TU0qX5ArvIONIxh/WAweyOk884c5cE8f+3NOPOOCRGyVy0FId5A7MmD5GOQh4H -JseOZVEVCqlmngEvtHZb3U1VYtVGE5WZ+6rQhGsMcWP5qaT4soYwMBlSYxgYwQcx -YhN9qOr292f9j2Y//TTIJmZT4Oa+lMxhWdqTfX+qMgG4jQRV/GgVAQQArhFSiij1 -b+hT3dnapbEU+23Z1yTu1DfF6zsxQ4XQWEV3eR8v+8mEDDNcz8oyyF56k6UQ3rXi -UMTIwRDg4V6SbZmaFbZYCOwp/EmXJ3rfhm7z7yzXj2OFN22luuqbyVhuL7LRdB0M -pxgmjXb4tTvfgKd26x34S+QqUJ7W6uprY4sAEQEAAYifBBgBCgAJBQJV/GgVAhsM -AAoJEHl50JoXRlvT7y8D/02ckx4OMkKBZo7viyrBw0MLG92i+DC2bs35PooHR6zz -786mitjOp5z2QWNLBvxC70S0qVfCIz8jKupO1J6rq6Z8CcbLF3qjm6h1omUBf8Nd -EfXKD2/2HV6zMKVknnKzIEzauh+eCKS2CeJUSSSryap/QLVAjRnckaES/OsEWhNB -=RZia ------END PGP PUBLIC KEY BLOCK----- -` - -const signedMessageV3 = `-----BEGIN PGP MESSAGE----- -Comment: GPGTools - https://gpgtools.org - -owGbwMvMwMVYWXlhlrhb9GXG03JJDKF/MtxDMjKLFYAoUaEktbhEITe1uDgxPVWP -q5NhKjMrWAVcC9evD8z/bF/uWNjqtk/X3y5/38XGRQHm/57rrDRYuGnTw597Xqka -uM3137/hH3Os+Jf2dc0fXOITKwJvXJvecPVs0ta+Vg7ZO1MLn8w58Xx+6L58mbka -DGHyU9yTueZE8D+QF/Tz28Y78dqtF56R1VPn9Xw4uJqrWYdd7b3vIZ1V6R4Nh05d -iT57d/OhWwA= -=hG7R ------END PGP MESSAGE----- -` - -// https://mailarchive.ietf.org/arch/msg/openpgp/9SheW_LENE0Kxf7haNllovPyAdY/ -const v5PrivKey = `-----BEGIN PGP PRIVATE KEY BLOCK----- - -lGEFXJH05BYAAAAtCSsGAQQB2kcPAQEHQFhZlVcVVtwf+21xNQPX+ecMJJBL0MPd -fj75iux+my8QAAAAAAAiAQCHZ1SnSUmWqxEsoI6facIVZQu6mph3cBFzzTvcm5lA -Ng5ctBhlbW1hLmdvbGRtYW5AZXhhbXBsZS5uZXSIlgUTFggASCIhBRk0e8mHJGQC -X5nfPsLgAA7ZiEiS4fez6kyUAJFZVptUBQJckfTkAhsDBQsJCAcCAyICAQYVCgkI -CwIEFgIDAQIeBwIXgAAA9cAA/jiR3yMsZMeEQ40u6uzEoXa6UXeV/S3wwJAXRJy9 -M8s0AP9vuL/7AyTfFXwwzSjDnYmzS0qAhbLDQ643N+MXGBJ2BZxmBVyR9OQSAAAA -MgorBgEEAZdVAQUBAQdA+nysrzml2UCweAqtpDuncSPlvrcBWKU0yfU0YvYWWAoD -AQgHAAAAAAAiAP9OdAPppjU1WwpqjIItkxr+VPQRT8Zm/Riw7U3F6v3OiBFHiHoF -GBYIACwiIQUZNHvJhyRkAl+Z3z7C4AAO2YhIkuH3s+pMlACRWVabVAUCXJH05AIb -DAAAOSQBAP4BOOIR/sGLNMOfeb5fPs/02QMieoiSjIBnijhob2U5AQC+RtOHCHx7 -TcIYl5/Uyoi+FOvPLcNw4hOv2nwUzSSVAw== -=IiS2 ------END PGP PRIVATE KEY BLOCK-----` - -// Generated with the above private key -const v5PrivKeyMsg = `-----BEGIN PGP MESSAGE----- -Version: OpenPGP.js v4.10.7 -Comment: https://openpgpjs.org - -xA0DAQoWGTR7yYckZAIByxF1B21zZy50eHRfbIGSdGVzdMJ3BQEWCgAGBQJf -bIGSACMiIQUZNHvJhyRkAl+Z3z7C4AAO2YhIkuH3s+pMlACRWVabVDQvAP9G -y29VPonFXqi2zKkpZrvyvZxg+n5e8Nt9wNbuxeCd3QD/TtO2s+JvjrE4Siwv -UQdl5MlBka1QSNbMq2Bz7XwNPg4= -=6lbM ------END PGP MESSAGE-----` - -const keyWithExpiredCrossSig = `-----BEGIN PGP PUBLIC KEY BLOCK----- - -xsDNBF2lnPIBDAC5cL9PQoQLTMuhjbYvb4Ncuuo0bfmgPRFywX53jPhoFf4Zg6mv -/seOXpgecTdOcVttfzC8ycIKrt3aQTiwOG/ctaR4Bk/t6ayNFfdUNxHWk4WCKzdz -/56fW2O0F23qIRd8UUJp5IIlN4RDdRCtdhVQIAuzvp2oVy/LaS2kxQoKvph/5pQ/ -5whqsyroEWDJoSV0yOb25B/iwk/pLUFoyhDG9bj0kIzDxrEqW+7Ba8nocQlecMF3 -X5KMN5kp2zraLv9dlBBpWW43XktjcCZgMy20SouraVma8Je/ECwUWYUiAZxLIlMv -9CurEOtxUw6N3RdOtLmYZS9uEnn5y1UkF88o8Nku890uk6BrewFzJyLAx5wRZ4F0 -qV/yq36UWQ0JB/AUGhHVPdFf6pl6eaxBwT5GXvbBUibtf8YI2og5RsgTWtXfU7eb -SGXrl5ZMpbA6mbfhd0R8aPxWfmDWiIOhBufhMCvUHh1sApMKVZnvIff9/0Dca3wb -vLIwa3T4CyshfT0AEQEAAc0hQm9iIEJhYmJhZ2UgPGJvYkBvcGVucGdwLmV4YW1w -bGU+wsEABBMBCgATBYJeO2eVAgsJAxUICgKbAQIeAQAhCRD7/MgqAV5zMBYhBNGm -bhojsYLJmA94jPv8yCoBXnMwKWUMAJ3FKZfJ2mXvh+GFqgymvK4NoKkDRPB0CbUN -aDdG7ZOizQrWXo7Da2MYIZ6eZUDqBKLdhZ5gZfVnisDfu/yeCgpENaKib1MPHpA8 -nZQjnPejbBDomNqY8HRzr5jvXNlwywBpjWGtegCKUY9xbSynjbfzIlMrWL4S+Rfl -+bOOQKRyYJWXmECmVyqY8cz2VUYmETjNcwC8VCDUxQnhtcCJ7Aej22hfYwVEPb/J -BsJBPq8WECCiGfJ9Y2y6TF+62KzG9Kfs5hqUeHhQy8V4TSi479ewwL7DH86XmIIK -chSANBS+7iyMtctjNZfmF9zYdGJFvjI/mbBR/lK66E515Inuf75XnL8hqlXuwqvG -ni+i03Aet1DzULZEIio4uIU6ioc1lGO9h7K2Xn4S7QQH1QoISNMWqXibUR0RCGjw -FsEDTt2QwJl8XXxoJCooM7BCcCQo+rMNVUHDjIwrdoQjPld3YZsUQQRcqH6bLuln -cfn5ufl8zTGWKydoj/iTz8KcjZ7w187AzQRdpZzyAQwA1jC/XGxjK6ddgrRfW9j+ -s/U00++EvIsgTs2kr3Rg0GP7FLWV0YNtR1mpl55/bEl7yAxCDTkOgPUMXcaKlnQh -6zrlt6H53mF6Bvs3inOHQvOsGtU0dqvb1vkTF0juLiJgPlM7pWv+pNQ6IA39vKoQ -sTMBv4v5vYNXP9GgKbg8inUNT17BxzZYHfw5+q63ectgDm2on1e8CIRCZ76oBVwz -dkVxoy3gjh1eENlk2D4P0uJNZzF1Q8GV67yLANGMCDICE/OkWn6daipYDzW4iJQt -YPUWP4hWhjdm+CK+hg6IQUEn2Vtvi16D2blRP8BpUNNa4fNuylWVuJV76rIHvsLZ -1pbM3LHpRgE8s6jivS3Rz3WRs0TmWCNnvHPqWizQ3VTy+r3UQVJ5AmhJDrZdZq9i -aUIuZ01PoE1+CHiJwuxPtWvVAxf2POcm1M/F1fK1J0e+lKlQuyonTXqXR22Y41wr -fP2aPk3nPSTW2DUAf3vRMZg57ZpRxLEhEMxcM4/LMR+PABEBAAHCwrIEGAEKAAkF -gl8sAVYCmwIB3QkQ+/zIKgFeczDA+qAEGQEKAAwFgl47Z5UFgwB4TOAAIQkQfC+q -Tfk8N7IWIQQd3OFfCSF87i87N2B8L6pN+Tw3st58C/0exp0X2U4LqicSHEOSqHZj -jiysdqIELHGyo5DSPv92UFPp36aqjF9OFgtNNwSa56fmAVCD4+hor/fKARRIeIjF -qdIC5Y/9a4B10NQFJa5lsvB38x/d39LI2kEoglZnqWgdJskROo3vNQF4KlIcm6FH -dn4WI8UkC5oUUcrpZVMSKoacIaxLwqnXT42nIVgYYuqrd/ZagZZjG5WlrTOd5+NI -zi/l0fWProcPHGLjmAh4Thu8i7omtVw1nQaMnq9I77ffg3cPDgXknYrLL+q8xXh/ -0mEJyIhnmPwllWCSZuLv9DrD5pOexFfdlwXhf6cLzNpW6QhXD/Tf5KrqIPr9aOv8 -9xaEEXWh0vEby2kIsI2++ft+vfdIyxYw/wKqx0awTSnuBV1rG3z1dswX4BfoY66x -Bz3KOVqlz9+mG/FTRQwrgPvR+qgLCHbuotxoGN7fzW+PI75hQG5JQAqhsC9sHjQH -UrI21/VUNwzfw3v5pYsWuFb5bdQ3ASJetICQiMy7IW8WIQTRpm4aI7GCyZgPeIz7 -/MgqAV5zMG6/C/wLpPl/9e6Hf5wmXIUwpZNQbNZvpiCcyx9sXsHXaycOQVxn3McZ -nYOUP9/mobl1tIeDQyTNbkxWjU0zzJl8XQsDZerb5098pg+x7oGIL7M1vn5s5JMl -owROourqF88JEtOBxLMxlAM7X4hB48xKQ3Hu9hS1GdnqLKki4MqRGl4l5FUwyGOM -GjyS3TzkfiDJNwQxybQiC9n57ij20ieNyLfuWCMLcNNnZUgZtnF6wCctoq/0ZIWu -a7nvuA/XC2WW9YjEJJiWdy5109pqac+qWiY11HWy/nms4gpMdxVpT0RhrKGWq4o0 -M5q3ZElOoeN70UO3OSbU5EVrG7gB1GuwF9mTHUVlV0veSTw0axkta3FGT//XfSpD -lRrCkyLzwq0M+UUHQAuYpAfobDlDdnxxOD2jm5GyTzak3GSVFfjW09QFVO6HlGp5 -01/jtzkUiS6nwoHHkfnyn0beZuR8X6KlcrzLB0VFgQFLmkSM9cSOgYhD0PTu9aHb -hW1Hj9AO8lzggBQ= -=Nt+N ------END PGP PUBLIC KEY BLOCK----- -` - -const sigFromKeyWithExpiredCrossSig = `-----BEGIN PGP SIGNATURE----- - -wsDzBAABCgAGBYJfLAFsACEJEHwvqk35PDeyFiEEHdzhXwkhfO4vOzdgfC+qTfk8 -N7KiqwwAts4QGB7v9bABCC2qkTxJhmStC0wQMcHRcjL/qAiVnmasQWmvE9KVsdm3 -AaXd8mIx4a37/RRvr9dYrY2eE4uw72cMqPxNja2tvVXkHQvk1oEUqfkvbXs4ypKI -NyeTWjXNOTZEbg0hbm3nMy+Wv7zgB1CEvAsEboLDJlhGqPcD+X8a6CJGrBGUBUrv -KVmZr3U6vEzClz3DBLpoddCQseJRhT4YM1nKmBlZ5quh2LFgTSpajv5OsZheqt9y -EZAPbqmLhDmWRQwGzkWHKceKS7nZ/ox2WK6OS7Ob8ZGZkM64iPo6/EGj5Yc19vQN -AGiIaPEGszBBWlOpHTPhNm0LB0nMWqqaT87oNYwP8CQuuxDb6rKJ2lffCmZH27Lb -UbQZcH8J+0UhpeaiadPZxH5ATJAcenmVtVVMLVOFnm+eIlxzov9ntpgGYt8hLdXB -ITEG9mMgp3TGS9ZzSifMZ8UGtHdp9QdBg8NEVPFzDOMGxpc/Bftav7RRRuPiAER+ -7A5CBid5 -=aQkm ------END PGP SIGNATURE----- -` - -const signedMessageWithCriticalNotation = `-----BEGIN PGP MESSAGE----- - -owGbwMvMwMH4oOW7S46CznTG09xJDDE3Wl1KUotLuDousDAwcjBYiSmyXL+48d6x -U1PSGUxcj8IUszKBVMpMaWAAAgEGZpAeh9SKxNyCnFS95PzcytRiBi5OAZjyXXzM -f8WYLqv7TXP61Sa4rqT12CI3xaN73YS2pt089f96odCKaEPnWJ3iSGmzJaW/ug10 -2Zo8Wj2k4s7t8wt4H3HtTu+y5UZfV3VOO+l//sdE/o+Lsub8FZH7/eOq7OnbNp4n -vwjE8mqJXetNMfj8r2SCyvkEnlVRYR+/mnge+ib56FdJ8uKtqSxyvgA= -=fRXs ------END PGP MESSAGE-----` - -const criticalNotationSigner = `-----BEGIN PGP PUBLIC KEY BLOCK----- - -mI0EUmEvTgEEANyWtQQMOybQ9JltDqmaX0WnNPJeLILIM36sw6zL0nfTQ5zXSS3+ -fIF6P29lJFxpblWk02PSID5zX/DYU9/zjM2xPO8Oa4xo0cVTOTLj++Ri5mtr//f5 -GLsIXxFrBJhD/ghFsL3Op0GXOeLJ9A5bsOn8th7x6JucNKuaRB6bQbSPABEBAAG0 -JFRlc3QgTWNUZXN0aW5ndG9uIDx0ZXN0QGV4YW1wbGUuY29tPoi5BBMBAgAjBQJS -YS9OAhsvBwsJCAcDAgEGFQgCCQoLBBYCAwECHgECF4AACgkQSmNhOk1uQJQwDAP6 -AgrTyqkRlJVqz2pb46TfbDM2TDF7o9CBnBzIGoxBhlRwpqALz7z2kxBDmwpQa+ki -Bq3jZN/UosY9y8bhwMAlnrDY9jP1gdCo+H0sD48CdXybblNwaYpwqC8VSpDdTndf -9j2wE/weihGp/DAdy/2kyBCaiOY1sjhUfJ1GogF49rC4jQRSYS9OAQQA6R/PtBFa -JaT4jq10yqASk4sqwVMsc6HcifM5lSdxzExFP74naUMMyEsKHP53QxTF0Grqusag -Qg/ZtgT0CN1HUM152y7ACOdp1giKjpMzOTQClqCoclyvWOFB+L/SwGEIJf7LSCEr -woBuJifJc8xAVr0XX0JthoW+uP91eTQ3XpsAEQEAAYkBPQQYAQIACQUCUmEvTgIb -LgCoCRBKY2E6TW5AlJ0gBBkBAgAGBQJSYS9OAAoJEOCE90RsICyXuqIEANmmiRCA -SF7YK7PvFkieJNwzeK0V3F2lGX+uu6Y3Q/Zxdtwc4xR+me/CSBmsURyXTO29OWhP -GLszPH9zSJU9BdDi6v0yNprmFPX/1Ng0Abn/sCkwetvjxC1YIvTLFwtUL/7v6NS2 -bZpsUxRTg9+cSrMWWSNjiY9qUKajm1tuzPDZXAUEAMNmAN3xXN/Kjyvj2OK2ck0X -W748sl/tc3qiKPMJ+0AkMF7Pjhmh9nxqE9+QCEl7qinFqqBLjuzgUhBU4QlwX1GD -AtNTq6ihLMD5v1d82ZC7tNatdlDMGWnIdvEMCv2GZcuIqDQ9rXWs49e7tq1NncLY -hz3tYjKhoFTKEIq3y3Pp -=h/aX ------END PGP PUBLIC KEY BLOCK-----` diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k.go deleted file mode 100644 index d0b85834..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/s2k/s2k.go +++ /dev/null @@ -1,339 +0,0 @@ -// Copyright 2011 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 s2k implements the various OpenPGP string-to-key transforms as -// specified in RFC 4800 section 3.7.1. -package s2k // import "github.com/ProtonMail/go-crypto/openpgp/s2k" - -import ( - "crypto" - "hash" - "io" - "strconv" - - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm" -) - -// Config collects configuration parameters for s2k key-stretching -// transformations. A nil *Config is valid and results in all default -// values. Currently, Config is used only by the Serialize function in -// this package. -type Config struct { - // S2KMode is the mode of s2k function. - // It can be 0 (simple), 1(salted), 3(iterated) - // 2(reserved) 100-110(private/experimental). - S2KMode uint8 - // Hash is the default hash function to be used. If - // nil, SHA256 is used. - Hash crypto.Hash - // S2KCount is only used for symmetric encryption. It - // determines the strength of the passphrase stretching when - // the said passphrase is hashed to produce a key. S2KCount - // should be between 65536 and 65011712, inclusive. If Config - // is nil or S2KCount is 0, the value 16777216 used. Not all - // values in the above range can be represented. S2KCount will - // be rounded up to the next representable value if it cannot - // be encoded exactly. See RFC 4880 Section 3.7.1.3. - S2KCount int -} - -// Params contains all the parameters of the s2k packet -type Params struct { - // mode is the mode of s2k function. - // It can be 0 (simple), 1(salted), 3(iterated) - // 2(reserved) 100-110(private/experimental). - mode uint8 - // hashId is the ID of the hash function used in any of the modes - hashId byte - // salt is a byte array to use as a salt in hashing process - salt []byte - // countByte is used to determine how many rounds of hashing are to - // be performed in s2k mode 3. See RFC 4880 Section 3.7.1.3. - countByte byte -} - -func (c *Config) hash() crypto.Hash { - if c == nil || uint(c.Hash) == 0 { - return crypto.SHA256 - } - - return c.Hash -} - -// EncodedCount get encoded count -func (c *Config) EncodedCount() uint8 { - if c == nil || c.S2KCount == 0 { - return 224 // The common case. Corresponding to 16777216 - } - - i := c.S2KCount - - switch { - case i < 65536: - i = 65536 - case i > 65011712: - i = 65011712 - } - - return encodeCount(i) -} - -// encodeCount converts an iterative "count" in the range 1024 to -// 65011712, inclusive, to an encoded count. The return value is the -// octet that is actually stored in the GPG file. encodeCount panics -// if i is not in the above range (encodedCount above takes care to -// pass i in the correct range). See RFC 4880 Section 3.7.7.1. -func encodeCount(i int) uint8 { - if i < 65536 || i > 65011712 { - panic("count arg i outside the required range") - } - - for encoded := 96; encoded < 256; encoded++ { - count := decodeCount(uint8(encoded)) - if count >= i { - return uint8(encoded) - } - } - - return 255 -} - -// decodeCount returns the s2k mode 3 iterative "count" corresponding to -// the encoded octet c. -func decodeCount(c uint8) int { - return (16 + int(c&15)) << (uint32(c>>4) + 6) -} - -// Simple writes to out the result of computing the Simple S2K function (RFC -// 4880, section 3.7.1.1) using the given hash and input passphrase. -func Simple(out []byte, h hash.Hash, in []byte) { - Salted(out, h, in, nil) -} - -var zero [1]byte - -// Salted writes to out the result of computing the Salted S2K function (RFC -// 4880, section 3.7.1.2) using the given hash, input passphrase and salt. -func Salted(out []byte, h hash.Hash, in []byte, salt []byte) { - done := 0 - var digest []byte - - for i := 0; done < len(out); i++ { - h.Reset() - for j := 0; j < i; j++ { - h.Write(zero[:]) - } - h.Write(salt) - h.Write(in) - digest = h.Sum(digest[:0]) - n := copy(out[done:], digest) - done += n - } -} - -// Iterated writes to out the result of computing the Iterated and Salted S2K -// function (RFC 4880, section 3.7.1.3) using the given hash, input passphrase, -// salt and iteration count. -func Iterated(out []byte, h hash.Hash, in []byte, salt []byte, count int) { - combined := make([]byte, len(in)+len(salt)) - copy(combined, salt) - copy(combined[len(salt):], in) - - if count < len(combined) { - count = len(combined) - } - - done := 0 - var digest []byte - for i := 0; done < len(out); i++ { - h.Reset() - for j := 0; j < i; j++ { - h.Write(zero[:]) - } - written := 0 - for written < count { - if written+len(combined) > count { - todo := count - written - h.Write(combined[:todo]) - written = count - } else { - h.Write(combined) - written += len(combined) - } - } - digest = h.Sum(digest[:0]) - n := copy(out[done:], digest) - done += n - } -} - -// Generate generates valid parameters from given configuration. -// It will enforce salted + hashed s2k method -func Generate(rand io.Reader, c *Config) (*Params, error) { - hashId, ok := algorithm.HashToHashId(c.Hash) - if !ok { - return nil, errors.UnsupportedError("no such hash") - } - - params := &Params{ - mode: 3, // Enforce iterared + salted method - hashId: hashId, - salt: make([]byte, 8), - countByte: c.EncodedCount(), - } - - if _, err := io.ReadFull(rand, params.salt); err != nil { - return nil, err - } - - return params, nil -} - -// Parse reads a binary specification for a string-to-key transformation from r -// and returns a function which performs that transform. If the S2K is a special -// GNU extension that indicates that the private key is missing, then the error -// returned is errors.ErrDummyPrivateKey. -func Parse(r io.Reader) (f func(out, in []byte), err error) { - params, err := ParseIntoParams(r) - if err != nil { - return nil, err - } - - return params.Function() -} - -// ParseIntoParams reads a binary specification for a string-to-key -// transformation from r and returns a struct describing the s2k parameters. -func ParseIntoParams(r io.Reader) (params *Params, err error) { - var buf [9]byte - - _, err = io.ReadFull(r, buf[:2]) - if err != nil { - return - } - - params = &Params{ - mode: buf[0], - hashId: buf[1], - } - - switch params.mode { - case 0: - return params, nil - case 1: - _, err = io.ReadFull(r, buf[:8]) - if err != nil { - return nil, err - } - - params.salt = buf[:8] - return params, nil - case 3: - _, err = io.ReadFull(r, buf[:9]) - if err != nil { - return nil, err - } - - params.salt = buf[:8] - params.countByte = buf[8] - return params, nil - case 101: - // This is a GNU extension. See - // https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob;f=doc/DETAILS;h=fe55ae16ab4e26d8356dc574c9e8bc935e71aef1;hb=23191d7851eae2217ecdac6484349849a24fd94a#l1109 - if _, err = io.ReadFull(r, buf[:4]); err != nil { - return nil, err - } - if buf[0] == 'G' && buf[1] == 'N' && buf[2] == 'U' && buf[3] == 1 { - return params, nil - } - return nil, errors.UnsupportedError("GNU S2K extension") - } - - return nil, errors.UnsupportedError("S2K function") -} - -func (params *Params) Dummy() bool { - return params != nil && params.mode == 101 -} - -func (params *Params) Function() (f func(out, in []byte), err error) { - if params.Dummy() { - return nil, errors.ErrDummyPrivateKey("dummy key found") - } - hashObj, ok := algorithm.HashIdToHashWithSha1(params.hashId) - if !ok { - return nil, errors.UnsupportedError("hash for S2K function: " + strconv.Itoa(int(params.hashId))) - } - if !hashObj.Available() { - return nil, errors.UnsupportedError("hash not available: " + strconv.Itoa(int(hashObj))) - } - - switch params.mode { - case 0: - f := func(out, in []byte) { - Simple(out, hashObj.New(), in) - } - - return f, nil - case 1: - f := func(out, in []byte) { - Salted(out, hashObj.New(), in, params.salt) - } - - return f, nil - case 3: - f := func(out, in []byte) { - Iterated(out, hashObj.New(), in, params.salt, decodeCount(params.countByte)) - } - - return f, nil - } - - return nil, errors.UnsupportedError("S2K function") -} - -func (params *Params) Serialize(w io.Writer) (err error) { - if _, err = w.Write([]byte{params.mode}); err != nil { - return - } - if _, err = w.Write([]byte{params.hashId}); err != nil { - return - } - if params.Dummy() { - _, err = w.Write(append([]byte("GNU"), 1)) - return - } - if params.mode > 0 { - if _, err = w.Write(params.salt); err != nil { - return - } - if params.mode == 3 { - _, err = w.Write([]byte{params.countByte}) - } - } - return -} - -// Serialize salts and stretches the given passphrase and writes the -// resulting key into key. It also serializes an S2K descriptor to -// w. The key stretching can be configured with c, which may be -// nil. In that case, sensible defaults will be used. -func Serialize(w io.Writer, key []byte, rand io.Reader, passphrase []byte, c *Config) error { - params, err := Generate(rand, c) - if err != nil { - return err - } - err = params.Serialize(w) - if err != nil { - return err - } - - f, err := params.Function() - if err != nil { - return err - } - f(key, passphrase) - return nil -} diff --git a/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go b/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go deleted file mode 100644 index cae4fe6d..00000000 --- a/vendor/github.com/ProtonMail/go-crypto/openpgp/write.go +++ /dev/null @@ -1,581 +0,0 @@ -// Copyright 2011 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 openpgp - -import ( - "crypto" - "hash" - "io" - "strconv" - "time" - - "github.com/ProtonMail/go-crypto/openpgp/armor" - "github.com/ProtonMail/go-crypto/openpgp/errors" - "github.com/ProtonMail/go-crypto/openpgp/internal/algorithm" - "github.com/ProtonMail/go-crypto/openpgp/packet" -) - -// DetachSign signs message with the private key from signer (which must -// already have been decrypted) and writes the signature to w. -// If config is nil, sensible defaults will be used. -func DetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { - return detachSign(w, signer, message, packet.SigTypeBinary, config) -} - -// ArmoredDetachSign signs message with the private key from signer (which -// must already have been decrypted) and writes an armored signature to w. -// If config is nil, sensible defaults will be used. -func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) (err error) { - return armoredDetachSign(w, signer, message, packet.SigTypeBinary, config) -} - -// DetachSignText signs message (after canonicalising the line endings) with -// the private key from signer (which must already have been decrypted) and -// writes the signature to w. -// If config is nil, sensible defaults will be used. -func DetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { - return detachSign(w, signer, message, packet.SigTypeText, config) -} - -// ArmoredDetachSignText signs message (after canonicalising the line endings) -// with the private key from signer (which must already have been decrypted) -// and writes an armored signature to w. -// If config is nil, sensible defaults will be used. -func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error { - return armoredDetachSign(w, signer, message, packet.SigTypeText, config) -} - -func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { - out, err := armor.Encode(w, SignatureType, nil) - if err != nil { - return - } - err = detachSign(out, signer, message, sigType, config) - if err != nil { - return - } - return out.Close() -} - -func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) { - signingKey, ok := signer.SigningKeyById(config.Now(), config.SigningKey()) - if !ok { - return errors.InvalidArgumentError("no valid signing keys") - } - if signingKey.PrivateKey == nil { - return errors.InvalidArgumentError("signing key doesn't have a private key") - } - if signingKey.PrivateKey.Encrypted { - return errors.InvalidArgumentError("signing key is encrypted") - } - if _, ok := algorithm.HashToHashId(config.Hash()); !ok { - return errors.InvalidArgumentError("invalid hash function") - } - - sig := new(packet.Signature) - sig.SigType = sigType - sig.PubKeyAlgo = signingKey.PrivateKey.PubKeyAlgo - sig.Hash = config.Hash() - sig.CreationTime = config.Now() - sigLifetimeSecs := config.SigLifetime() - sig.SigLifetimeSecs = &sigLifetimeSecs - sig.IssuerKeyId = &signingKey.PrivateKey.KeyId - - h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType) - if err != nil { - return - } - if _, err = io.Copy(wrappedHash, message); err != nil { - return err - } - - err = sig.Sign(h, signingKey.PrivateKey, config) - if err != nil { - return - } - - return sig.Serialize(w) -} - -// FileHints contains metadata about encrypted files. This metadata is, itself, -// encrypted. -type FileHints struct { - // IsBinary can be set to hint that the contents are binary data. - IsBinary bool - // FileName hints at the name of the file that should be written. It's - // truncated to 255 bytes if longer. It may be empty to suggest that the - // file should not be written to disk. It may be equal to "_CONSOLE" to - // suggest the data should not be written to disk. - FileName string - // ModTime contains the modification time of the file, or the zero time if not applicable. - ModTime time.Time -} - -// SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase. -// The resulting WriteCloser must be closed after the contents of the file have -// been written. -// If config is nil, sensible defaults will be used. -func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { - if hints == nil { - hints = &FileHints{} - } - - key, err := packet.SerializeSymmetricKeyEncrypted(ciphertext, passphrase, config) - if err != nil { - return - } - - var w io.WriteCloser - cipherSuite := packet.CipherSuite{ - Cipher: config.Cipher(), - Mode: config.AEAD().Mode(), - } - w, err = packet.SerializeSymmetricallyEncrypted(ciphertext, config.Cipher(), config.AEAD() != nil, cipherSuite, key, config) - if err != nil { - return - } - - literalData := w - if algo := config.Compression(); algo != packet.CompressionNone { - var compConfig *packet.CompressionConfig - if config != nil { - compConfig = config.CompressionConfig - } - literalData, err = packet.SerializeCompressed(w, algo, compConfig) - if err != nil { - return - } - } - - var epochSeconds uint32 - if !hints.ModTime.IsZero() { - epochSeconds = uint32(hints.ModTime.Unix()) - } - return packet.SerializeLiteral(literalData, hints.IsBinary, hints.FileName, epochSeconds) -} - -// intersectPreferences mutates and returns a prefix of a that contains only -// the values in the intersection of a and b. The order of a is preserved. -func intersectPreferences(a []uint8, b []uint8) (intersection []uint8) { - var j int - for _, v := range a { - for _, v2 := range b { - if v == v2 { - a[j] = v - j++ - break - } - } - } - - return a[:j] -} - -// intersectPreferences mutates and returns a prefix of a that contains only -// the values in the intersection of a and b. The order of a is preserved. -func intersectCipherSuites(a [][2]uint8, b [][2]uint8) (intersection [][2]uint8) { - var j int - for _, v := range a { - for _, v2 := range b { - if v[0] == v2[0] && v[1] == v2[1] { - a[j] = v - j++ - break - } - } - } - - return a[:j] -} - -func hashToHashId(h crypto.Hash) uint8 { - v, ok := algorithm.HashToHashId(h) - if !ok { - panic("tried to convert unknown hash") - } - return v -} - -// EncryptText encrypts a message to a number of recipients and, optionally, -// signs it. Optional information is contained in 'hints', also encrypted, that -// aids the recipients in processing the message. The resulting WriteCloser -// must be closed after the contents of the file have been written. If config -// is nil, sensible defaults will be used. The signing is done in text mode. -func EncryptText(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { - return encrypt(ciphertext, ciphertext, to, signed, hints, packet.SigTypeText, config) -} - -// Encrypt encrypts a message to a number of recipients and, optionally, signs -// it. hints contains optional information, that is also encrypted, that aids -// the recipients in processing the message. The resulting WriteCloser must -// be closed after the contents of the file have been written. -// If config is nil, sensible defaults will be used. -func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { - return encrypt(ciphertext, ciphertext, to, signed, hints, packet.SigTypeBinary, config) -} - -// EncryptSplit encrypts a message to a number of recipients and, optionally, signs -// it. hints contains optional information, that is also encrypted, that aids -// the recipients in processing the message. The resulting WriteCloser must -// be closed after the contents of the file have been written. -// If config is nil, sensible defaults will be used. -func EncryptSplit(keyWriter io.Writer, dataWriter io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { - return encrypt(keyWriter, dataWriter, to, signed, hints, packet.SigTypeBinary, config) -} - -// EncryptTextSplit encrypts a message to a number of recipients and, optionally, signs -// it. hints contains optional information, that is also encrypted, that aids -// the recipients in processing the message. The resulting WriteCloser must -// be closed after the contents of the file have been written. -// If config is nil, sensible defaults will be used. -func EncryptTextSplit(keyWriter io.Writer, dataWriter io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) { - return encrypt(keyWriter, dataWriter, to, signed, hints, packet.SigTypeText, config) -} - -// writeAndSign writes the data as a payload package and, optionally, signs -// it. hints contains optional information, that is also encrypted, -// that aids the recipients in processing the message. The resulting -// WriteCloser must be closed after the contents of the file have been -// written. If config is nil, sensible defaults will be used. -func writeAndSign(payload io.WriteCloser, candidateHashes []uint8, signed *Entity, hints *FileHints, sigType packet.SignatureType, config *packet.Config) (plaintext io.WriteCloser, err error) { - var signer *packet.PrivateKey - if signed != nil { - signKey, ok := signed.SigningKeyById(config.Now(), config.SigningKey()) - if !ok { - return nil, errors.InvalidArgumentError("no valid signing keys") - } - signer = signKey.PrivateKey - if signer == nil { - return nil, errors.InvalidArgumentError("no private key in signing key") - } - if signer.Encrypted { - return nil, errors.InvalidArgumentError("signing key must be decrypted") - } - } - - var hash crypto.Hash - for _, hashId := range candidateHashes { - if h, ok := algorithm.HashIdToHash(hashId); ok && h.Available() { - hash = h - break - } - } - - // If the hash specified by config is a candidate, we'll use that. - if configuredHash := config.Hash(); configuredHash.Available() { - for _, hashId := range candidateHashes { - if h, ok := algorithm.HashIdToHash(hashId); ok && h == configuredHash { - hash = h - break - } - } - } - - if hash == 0 { - hashId := candidateHashes[0] - name, ok := algorithm.HashIdToString(hashId) - if !ok { - name = "#" + strconv.Itoa(int(hashId)) - } - return nil, errors.InvalidArgumentError("cannot encrypt because no candidate hash functions are compiled in. (Wanted " + name + " in this case.)") - } - - if signer != nil { - ops := &packet.OnePassSignature{ - SigType: sigType, - Hash: hash, - PubKeyAlgo: signer.PubKeyAlgo, - KeyId: signer.KeyId, - IsLast: true, - } - if err := ops.Serialize(payload); err != nil { - return nil, err - } - } - - if hints == nil { - hints = &FileHints{} - } - - w := payload - if signer != nil { - // If we need to write a signature packet after the literal - // data then we need to stop literalData from closing - // encryptedData. - w = noOpCloser{w} - - } - var epochSeconds uint32 - if !hints.ModTime.IsZero() { - epochSeconds = uint32(hints.ModTime.Unix()) - } - literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds) - if err != nil { - return nil, err - } - - if signer != nil { - h, wrappedHash, err := hashForSignature(hash, sigType) - if err != nil { - return nil, err - } - metadata := &packet.LiteralData{ - Format: 't', - FileName: hints.FileName, - Time: epochSeconds, - } - if hints.IsBinary { - metadata.Format = 'b' - } - return signatureWriter{payload, literalData, hash, wrappedHash, h, signer, sigType, config, metadata}, nil - } - return literalData, nil -} - -// encrypt encrypts a message to a number of recipients and, optionally, signs -// it. hints contains optional information, that is also encrypted, that aids -// the recipients in processing the message. The resulting WriteCloser must -// be closed after the contents of the file have been written. -// If config is nil, sensible defaults will be used. -func encrypt(keyWriter io.Writer, dataWriter io.Writer, to []*Entity, signed *Entity, hints *FileHints, sigType packet.SignatureType, config *packet.Config) (plaintext io.WriteCloser, err error) { - if len(to) == 0 { - return nil, errors.InvalidArgumentError("no encryption recipient provided") - } - - // These are the possible ciphers that we'll use for the message. - candidateCiphers := []uint8{ - uint8(packet.CipherAES256), - uint8(packet.CipherAES128), - } - - // These are the possible hash functions that we'll use for the signature. - candidateHashes := []uint8{ - hashToHashId(crypto.SHA256), - hashToHashId(crypto.SHA384), - hashToHashId(crypto.SHA512), - hashToHashId(crypto.SHA3_256), - hashToHashId(crypto.SHA3_512), - } - - // Prefer GCM if everyone supports it - candidateCipherSuites := [][2]uint8{ - {uint8(packet.CipherAES256), uint8(packet.AEADModeGCM)}, - {uint8(packet.CipherAES256), uint8(packet.AEADModeEAX)}, - {uint8(packet.CipherAES256), uint8(packet.AEADModeOCB)}, - {uint8(packet.CipherAES128), uint8(packet.AEADModeGCM)}, - {uint8(packet.CipherAES128), uint8(packet.AEADModeEAX)}, - {uint8(packet.CipherAES128), uint8(packet.AEADModeOCB)}, - } - - candidateCompression := []uint8{ - uint8(packet.CompressionNone), - uint8(packet.CompressionZIP), - uint8(packet.CompressionZLIB), - } - - encryptKeys := make([]Key, len(to)) - - // AEAD is used only if config enables it and every key supports it - aeadSupported := config.AEAD() != nil - - for i := range to { - var ok bool - encryptKeys[i], ok = to[i].EncryptionKey(config.Now()) - if !ok { - return nil, errors.InvalidArgumentError("cannot encrypt a message to key id " + strconv.FormatUint(to[i].PrimaryKey.KeyId, 16) + " because it has no valid encryption keys") - } - - sig := to[i].PrimaryIdentity().SelfSignature - if sig.SEIPDv2 == false { - aeadSupported = false - } - - candidateCiphers = intersectPreferences(candidateCiphers, sig.PreferredSymmetric) - candidateHashes = intersectPreferences(candidateHashes, sig.PreferredHash) - candidateCipherSuites = intersectCipherSuites(candidateCipherSuites, sig.PreferredCipherSuites) - candidateCompression = intersectPreferences(candidateCompression, sig.PreferredCompression) - } - - // In the event that the intersection of supported algorithms is empty we use the ones - // labelled as MUST that every implementation supports. - if len(candidateCiphers) == 0 { - // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.3 - candidateCiphers = []uint8{uint8(packet.CipherAES128)} - } - if len(candidateHashes) == 0 { - // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#hash-algos - candidateHashes = []uint8{hashToHashId(crypto.SHA256)} - } - if len(candidateCipherSuites) == 0 { - // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.6 - candidateCipherSuites = [][2]uint8{{uint8(packet.CipherAES128), uint8(packet.AEADModeOCB)}} - } - - cipher := packet.CipherFunction(candidateCiphers[0]) - aeadCipherSuite := packet.CipherSuite{ - Cipher: packet.CipherFunction(candidateCipherSuites[0][0]), - Mode: packet.AEADMode(candidateCipherSuites[0][1]), - } - - // If the cipher specified by config is a candidate, we'll use that. - configuredCipher := config.Cipher() - for _, c := range candidateCiphers { - cipherFunc := packet.CipherFunction(c) - if cipherFunc == configuredCipher { - cipher = cipherFunc - break - } - } - - symKey := make([]byte, cipher.KeySize()) - if _, err := io.ReadFull(config.Random(), symKey); err != nil { - return nil, err - } - - for _, key := range encryptKeys { - if err := packet.SerializeEncryptedKey(keyWriter, key.PublicKey, cipher, symKey, config); err != nil { - return nil, err - } - } - - var payload io.WriteCloser - payload, err = packet.SerializeSymmetricallyEncrypted(dataWriter, cipher, aeadSupported, aeadCipherSuite, symKey, config) - if err != nil { - return - } - - payload, err = handleCompression(payload, candidateCompression, config) - if err != nil { - return nil, err - } - - return writeAndSign(payload, candidateHashes, signed, hints, sigType, config) -} - -// Sign signs a message. The resulting WriteCloser must be closed after the -// contents of the file have been written. hints contains optional information -// that aids the recipients in processing the message. -// If config is nil, sensible defaults will be used. -func Sign(output io.Writer, signed *Entity, hints *FileHints, config *packet.Config) (input io.WriteCloser, err error) { - if signed == nil { - return nil, errors.InvalidArgumentError("no signer provided") - } - - // These are the possible hash functions that we'll use for the signature. - candidateHashes := []uint8{ - hashToHashId(crypto.SHA256), - hashToHashId(crypto.SHA384), - hashToHashId(crypto.SHA512), - hashToHashId(crypto.SHA3_256), - hashToHashId(crypto.SHA3_512), - } - defaultHashes := candidateHashes[0:1] - preferredHashes := signed.PrimaryIdentity().SelfSignature.PreferredHash - if len(preferredHashes) == 0 { - preferredHashes = defaultHashes - } - candidateHashes = intersectPreferences(candidateHashes, preferredHashes) - if len(candidateHashes) == 0 { - return nil, errors.InvalidArgumentError("cannot sign because signing key shares no common algorithms with candidate hashes") - } - - return writeAndSign(noOpCloser{output}, candidateHashes, signed, hints, packet.SigTypeBinary, config) -} - -// signatureWriter hashes the contents of a message while passing it along to -// literalData. When closed, it closes literalData, writes a signature packet -// to encryptedData and then also closes encryptedData. -type signatureWriter struct { - encryptedData io.WriteCloser - literalData io.WriteCloser - hashType crypto.Hash - wrappedHash hash.Hash - h hash.Hash - signer *packet.PrivateKey - sigType packet.SignatureType - config *packet.Config - metadata *packet.LiteralData // V5 signatures protect document metadata -} - -func (s signatureWriter) Write(data []byte) (int, error) { - s.wrappedHash.Write(data) - switch s.sigType { - case packet.SigTypeBinary: - return s.literalData.Write(data) - case packet.SigTypeText: - flag := 0 - return writeCanonical(s.literalData, data, &flag) - } - return 0, errors.UnsupportedError("unsupported signature type: " + strconv.Itoa(int(s.sigType))) -} - -func (s signatureWriter) Close() error { - sig := &packet.Signature{ - Version: s.signer.Version, - SigType: s.sigType, - PubKeyAlgo: s.signer.PubKeyAlgo, - Hash: s.hashType, - CreationTime: s.config.Now(), - IssuerKeyId: &s.signer.KeyId, - Metadata: s.metadata, - } - - if err := sig.Sign(s.h, s.signer, s.config); err != nil { - return err - } - if err := s.literalData.Close(); err != nil { - return err - } - if err := sig.Serialize(s.encryptedData); err != nil { - return err - } - return s.encryptedData.Close() -} - -// noOpCloser is like an ioutil.NopCloser, but for an io.Writer. -// TODO: we have two of these in OpenPGP packages alone. This probably needs -// to be promoted somewhere more common. -type noOpCloser struct { - w io.Writer -} - -func (c noOpCloser) Write(data []byte) (n int, err error) { - return c.w.Write(data) -} - -func (c noOpCloser) Close() error { - return nil -} - -func handleCompression(compressed io.WriteCloser, candidateCompression []uint8, config *packet.Config) (data io.WriteCloser, err error) { - data = compressed - confAlgo := config.Compression() - if confAlgo == packet.CompressionNone { - return - } - - // Set algorithm labelled as MUST as fallback - // https://www.ietf.org/archive/id/draft-ietf-openpgp-crypto-refresh-07.html#section-9.4 - finalAlgo := packet.CompressionNone - // if compression specified by config available we will use it - for _, c := range candidateCompression { - if uint8(confAlgo) == c { - finalAlgo = confAlgo - break - } - } - - if finalAlgo != packet.CompressionNone { - var compConfig *packet.CompressionConfig - if config != nil { - compConfig = config.CompressionConfig - } - data, err = packet.SerializeCompressed(compressed, finalAlgo, compConfig) - if err != nil { - return - } - } - return data, nil -} diff --git a/vendor/github.com/aead/argon2/.gitignore b/vendor/github.com/aead/argon2/.gitignore deleted file mode 100644 index a1338d68..00000000 --- a/vendor/github.com/aead/argon2/.gitignore +++ /dev/null @@ -1,14 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.dll -*.so -*.dylib - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 -.glide/ diff --git a/vendor/github.com/aead/argon2/LICENSE b/vendor/github.com/aead/argon2/LICENSE deleted file mode 100644 index 3bfeb723..00000000 --- a/vendor/github.com/aead/argon2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 Andreas Auernhammer - -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/github.com/aead/argon2/README.md b/vendor/github.com/aead/argon2/README.md deleted file mode 100644 index b3d40ca0..00000000 --- a/vendor/github.com/aead/argon2/README.md +++ /dev/null @@ -1,16 +0,0 @@ -[![Godoc Reference](https://godoc.org/github.com/aead/argon2?status.svg)](https://godoc.org/github.com/aead/argon2) - -## The Argon2 password hashing algorithm - -Argon2 is a memory-hard password hashing function and was selected as the winner of the Password Hashing Competition. -Argon2 can be used to derive high-entropy secret keys from low-entropy passwords and is specified at -https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf - -### Recommendation -This Argon2 implementation was submitted to the golang x/crypto repo. -I recommend to use the official [x/crypto/argon2](https://godoc.org/golang.org/x/crypto/argon2) package if possible. -This repository also exports Argon2d and Argon2id. It is recommended to use Argon2id as described in the [RFC draft](https://tools.ietf.org/html/draft-irtf-cfrg-argon2-03). - -### Installation - -Install in your GOPATH: `go get -u github.com/aead/argon2` \ No newline at end of file diff --git a/vendor/github.com/aead/argon2/argon2.go b/vendor/github.com/aead/argon2/argon2.go deleted file mode 100644 index 3cf0c9ee..00000000 --- a/vendor/github.com/aead/argon2/argon2.go +++ /dev/null @@ -1,281 +0,0 @@ -// Copyright (c) 2017 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// Package argon2 implements the key derivation function Argon2. -// Argon2 was selected as the winner of the Password Hashing Competition and can -// be used to derive cryptographic keys from passwords. -// Argon2 is specfifed at https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf -// -// This package implements the three different Argon2 variants: -// - Argon2d: -// This version maximizes the bruteforce cost for an adversary but does not -// prevent information leakage by data-depended memory access. It should only -// be used in trusted environments. -// - Argon2i: -// This version is designed to prevent information leakage through memory access. -// It is the recommended version of the Argon2 paper. However attacks against Argon2i -// exists which reduce the time-memory tradeoff costs depending on used parameters. -// - Argon2id: -// This is version is a combination of Argon2i and Argon2d and combines the advantages -// of both versions. It is the recommended version of the RFC draft: https://tools.ietf.org/html/draft-irtf-cfrg-argon2-03 -package argon2 - -import ( - "encoding/binary" - "sync" - - "golang.org/x/crypto/blake2b" -) - -// The Argon2 version implemented by this package. -const Version = 0x13 - -const ( - argon2d = iota - argon2i - argon2id -) - -// Key derives a key from the password, salt, and cost parameters using Argon2i -// returning a byte slice of length keyLen that can be used as cryptographic key. -// The CPU cost and parallism degree must be greater than zero. -// -// For example, you can get a derived key for e.g. AES-256 (which needs a 32-byte key) by doing: -// `key := argon2.Key([]byte("some password"), salt, 4, 32*1024, 4, 32)` -// -// The recommended parameters for interactive logins as of 2017 are time=4, memory=32*1024. -// The number of threads can be adjusted to the numbers of available CPUs. -// The time parameter specifies the number of passes over the memory and the memory -// parameter specifies the size of the memory in KiB. For example memory=32*1024 sets the -// memory cost to ~32 MB. -// The cost parameters should be increased as memory latency and CPU parallelism increases. -// Remember to get a good random salt. -func Key(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte { - return deriveKey(argon2i, password, salt, nil, nil, time, memory, threads, keyLen) -} - -// Key2d derives a key from the password, salt, and cost parameters using Argon2d -// returning a byte slice of length keyLen that can be used as cryptographic key. -// The CPU cost and parallism degree must be greater than zero. -// -// For example, you can get a derived key for e.g. AES-256 (which needs a 32-byte key) by doing: -// `key := argon2.Key2d([]byte("some password"), salt, 1, 32*1024, 4, 32)` -// -// The recommended parameters for interactive logins as of 2017 are time=1, memory=32*1024. -// According to the RFC draft a time=1 and the maximal available memory maximizes the attack -// cost for a constant time defender. -// The number of threads can be adjusted to the numbers of available CPUs. -// The time parameter specifies the number of passes over the memory and the memory -// parameter specifies the size of the memory in KiB. For example memory=32*1024 sets the -// memory cost to ~32 MB. -// The cost parameters should be increased as memory latency and CPU parallelism increases. -// Remember to get a good random salt. -func Key2d(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte { - return deriveKey(argon2d, password, salt, nil, nil, time, memory, threads, keyLen) -} - -// Key2id derives a key from the password, salt, and cost parameters using Argon2id -// returning a byte slice of length keyLen that can be used as cryptographic key. -// The CPU cost and parallism degree must be greater than zero. -// -// For example, you can get a derived key for e.g. AES-256 (which needs a 32-byte key) by doing: -// `key := argon2.Key2id([]byte("some password"), salt, 1, 32*1024, 4, 32)` -// -// The recommended parameters for interactive logins as of 2017 are time=1, memory=32*1024. -// According to the RFC draft a time=1 and the maximal available memory maximizes the attack -// cost for a constant time defender. -// The number of threads can be adjusted to the numbers of available CPUs. -// The time parameter specifies the number of passes over the memory and the memory -// parameter specifies the size of the memory in KiB. For example memory=32*1024 sets the -// memory cost to ~32 MB. -// The cost parameters should be increased as memory latency and CPU parallelism increases. -// Remember to get a good random salt. -func Key2id(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte { - return deriveKey(argon2id, password, salt, nil, nil, time, memory, threads, keyLen) -} - -func deriveKey(mode int, password, salt, secret, data []byte, time, memory uint32, threads uint8, keyLen uint32) []byte { - if time < 1 { - panic("argon2: number of rounds too small") - } - if threads < 1 { - panic("argon2: parallelism degree too low") - } - h0 := initHash(password, salt, secret, data, time, memory, uint32(threads), keyLen, mode) - - memory = memory / (syncPoints * uint32(threads)) * (syncPoints * uint32(threads)) - if memory < 2*syncPoints*uint32(threads) { - memory = 2 * syncPoints * uint32(threads) - } - B := initBlocks(&h0, memory, uint32(threads)) - processBlocks(B, time, memory, uint32(threads), mode) - return extractKey(B, memory, uint32(threads), keyLen) -} - -const ( - blockLength = 128 - syncPoints = 4 -) - -type block [blockLength]uint64 - -func initHash(password, salt, key, data []byte, time, memory, threads, keyLen uint32, mode int) [blake2b.Size + 8]byte { - var ( - h0 [blake2b.Size + 8]byte - params [24]byte - tmp [4]byte - ) - - b2, _ := blake2b.New512(nil) - binary.LittleEndian.PutUint32(params[0:4], threads) - binary.LittleEndian.PutUint32(params[4:8], keyLen) - binary.LittleEndian.PutUint32(params[8:12], memory) - binary.LittleEndian.PutUint32(params[12:16], time) - binary.LittleEndian.PutUint32(params[16:20], uint32(Version)) - binary.LittleEndian.PutUint32(params[20:24], uint32(mode)) - b2.Write(params[:]) - binary.LittleEndian.PutUint32(tmp[:], uint32(len(password))) - b2.Write(tmp[:]) - b2.Write(password) - binary.LittleEndian.PutUint32(tmp[:], uint32(len(salt))) - b2.Write(tmp[:]) - b2.Write(salt) - binary.LittleEndian.PutUint32(tmp[:], uint32(len(key))) - b2.Write(tmp[:]) - b2.Write(key) - binary.LittleEndian.PutUint32(tmp[:], uint32(len(data))) - b2.Write(tmp[:]) - b2.Write(data) - b2.Sum(h0[:0]) - return h0 -} - -func initBlocks(h0 *[blake2b.Size + 8]byte, memory, threads uint32) []block { - var block0 [1024]byte - B := make([]block, memory) - for lane := uint32(0); lane < threads; lane++ { - j := lane * (memory / threads) - binary.LittleEndian.PutUint32(h0[blake2b.Size+4:], lane) - - binary.LittleEndian.PutUint32(h0[blake2b.Size:], 0) - blake2bHash(block0[:], h0[:]) - for i := range B[j+0] { - B[j+0][i] = binary.LittleEndian.Uint64(block0[i*8:]) - } - - binary.LittleEndian.PutUint32(h0[blake2b.Size:], 1) - blake2bHash(block0[:], h0[:]) - for i := range B[j+1] { - B[j+1][i] = binary.LittleEndian.Uint64(block0[i*8:]) - } - } - return B -} - -func processBlocks(B []block, time, memory, threads uint32, mode int) { - lanes := memory / threads - segments := lanes / syncPoints - - processSegment := func(n, slice, lane uint32, wg *sync.WaitGroup) { - var addresses, in, zero block - if mode == argon2i || (mode == argon2id && n == 0 && slice < syncPoints/2) { - in[0] = uint64(n) - in[1] = uint64(lane) - in[2] = uint64(slice) - in[3] = uint64(memory) - in[4] = uint64(time) - in[5] = uint64(mode) - } - - index := uint32(0) - if n == 0 && slice == 0 { - index = 2 // we have already generated the first two blocks - if mode == argon2i || mode == argon2id { - in[6]++ - processBlock(&addresses, &in, &zero) - processBlock(&addresses, &addresses, &zero) - } - } - - offset := lane*lanes + slice*segments + index - var random uint64 - for index < segments { - prev := offset - 1 - if index == 0 && slice == 0 { - prev += lanes // last block in lane - } - if mode == argon2i || (mode == argon2id && n == 0 && slice < syncPoints/2) { - if index%blockLength == 0 { - in[6]++ - processBlock(&addresses, &in, &zero) - processBlock(&addresses, &addresses, &zero) - } - random = addresses[index%blockLength] - } else { - random = B[prev][0] - } - newOffset := indexAlpha(random, lanes, segments, threads, n, slice, lane, index) - processBlockXOR(&B[offset], &B[prev], &B[newOffset]) - index, offset = index+1, offset+1 - } - wg.Done() - } - - for n := uint32(0); n < time; n++ { - for slice := uint32(0); slice < syncPoints; slice++ { - var wg sync.WaitGroup - for lane := uint32(0); lane < threads; lane++ { - wg.Add(1) - go processSegment(n, slice, lane, &wg) - } - wg.Wait() - } - } - -} - -func extractKey(B []block, memory, threads, keyLen uint32) []byte { - lanes := memory / threads - for lane := uint32(0); lane < threads-1; lane++ { - for i, v := range B[(lane*lanes)+lanes-1] { - B[memory-1][i] ^= v - } - } - - var block [1024]byte - for i, v := range B[memory-1] { - binary.LittleEndian.PutUint64(block[i*8:], v) - } - key := make([]byte, keyLen) - blake2bHash(key, block[:]) - return key -} - -func indexAlpha(rand uint64, lanes, segments, threads, n, slice, lane, index uint32) uint32 { - refLane := uint32(rand>>32) % threads - if n == 0 && slice == 0 { - refLane = lane - } - m, s := 3*segments, ((slice+1)%syncPoints)*segments - if lane == refLane { - m += index - } - if n == 0 { - m, s = slice*segments, 0 - if slice == 0 || lane == refLane { - m += index - } - } - if index == 0 || lane == refLane { - m-- - } - return phi(rand, uint64(m), uint64(s), refLane, lanes) -} - -func phi(rand, m, s uint64, lane, lanes uint32) uint32 { - p := rand & 0xFFFFFFFF - p = (p * p) >> 32 - p = (p * m) >> 32 - return lane*lanes + uint32((s+m-(p+1))%uint64(lanes)) -} diff --git a/vendor/github.com/aead/argon2/blake2b.go b/vendor/github.com/aead/argon2/blake2b.go deleted file mode 100644 index 497d93c7..00000000 --- a/vendor/github.com/aead/argon2/blake2b.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2017 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -package argon2 - -import ( - "encoding/binary" - "hash" - - "golang.org/x/crypto/blake2b" -) - -// blake2bHash computes an arbitrary long hash value of in -// and writes the hash to out. -func blake2bHash(out []byte, in []byte) { - var b2 hash.Hash - if n := len(out); n < blake2b.Size { - b2, _ = blake2b.New(n, nil) - } else { - b2, _ = blake2b.New512(nil) - } - - var buffer [blake2b.Size]byte - binary.LittleEndian.PutUint32(buffer[:4], uint32(len(out))) - b2.Write(buffer[:4]) - b2.Write(in) - - if len(out) <= blake2b.Size { - b2.Sum(out[:0]) - return - } - - outLen := len(out) - b2.Sum(buffer[:0]) - b2.Reset() - copy(out, buffer[:32]) - out = out[32:] - for len(out) > blake2b.Size { - b2.Write(buffer[:]) - b2.Sum(buffer[:0]) - copy(out, buffer[:32]) - out = out[32:] - b2.Reset() - } - - if outLen%blake2b.Size > 0 { // outLen > 64 - r := ((outLen + 31) / 32) - 2 // ⌈τ /32⌉-2 - b2, _ = blake2b.New(outLen-32*r, nil) - } - b2.Write(buffer[:]) - b2.Sum(out[:0]) -} diff --git a/vendor/github.com/aead/argon2/blamka_amd64.go b/vendor/github.com/aead/argon2/blamka_amd64.go deleted file mode 100644 index 935ddf2e..00000000 --- a/vendor/github.com/aead/argon2/blamka_amd64.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2017 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -package argon2 - -func init() { - useSSE4 = supportsSSE4() -} - -//go:noescape -func supportsSSE4() bool - -//go:noescape -func mixBlocksSSE2(out, a, b, c *block) - -//go:noescape -func xorBlocksSSE2(out, a, b, c *block) - -//go:noescape -func blamkaSSE4(b *block) - -func processBlockSSE(out, in1, in2 *block, xor bool) { - var t block - mixBlocksSSE2(&t, in1, in2, &t) - if useSSE4 { - blamkaSSE4(&t) - } else { - for i := 0; i < blockLength; i += 16 { - blamkaGeneric( - &t[i+0], &t[i+1], &t[i+2], &t[i+3], - &t[i+4], &t[i+5], &t[i+6], &t[i+7], - &t[i+8], &t[i+9], &t[i+10], &t[i+11], - &t[i+12], &t[i+13], &t[i+14], &t[i+15], - ) - } - for i := 0; i < blockLength/8; i += 2 { - blamkaGeneric( - &t[i], &t[i+1], &t[16+i], &t[16+i+1], - &t[32+i], &t[32+i+1], &t[48+i], &t[48+i+1], - &t[64+i], &t[64+i+1], &t[80+i], &t[80+i+1], - &t[96+i], &t[96+i+1], &t[112+i], &t[112+i+1], - ) - } - } - if xor { - xorBlocksSSE2(out, in1, in2, &t) - } else { - mixBlocksSSE2(out, in1, in2, &t) - } -} - -func processBlock(out, in1, in2 *block) { - processBlockSSE(out, in1, in2, false) -} - -func processBlockXOR(out, in1, in2 *block) { - processBlockSSE(out, in1, in2, true) -} diff --git a/vendor/github.com/aead/argon2/blamka_amd64.s b/vendor/github.com/aead/argon2/blamka_amd64.s deleted file mode 100644 index 65a33c38..00000000 --- a/vendor/github.com/aead/argon2/blamka_amd64.s +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright (c) 2017 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// +build amd64,!gccgo,!appengine - -#include "textflag.h" - -DATA ·c40<>+0x00(SB)/8, $0x0201000706050403 -DATA ·c40<>+0x08(SB)/8, $0x0a09080f0e0d0c0b -GLOBL ·c40<>(SB), (NOPTR+RODATA), $16 - -DATA ·c48<>+0x00(SB)/8, $0x0100070605040302 -DATA ·c48<>+0x08(SB)/8, $0x09080f0e0d0c0b0a -GLOBL ·c48<>(SB), (NOPTR+RODATA), $16 - -#define SHUFFLE(v2, v3, v4, v5, v6, v7, t1, t2) \ - MOVO v4, t1; \ - MOVO v5, v4; \ - MOVO t1, v5; \ - MOVO v6, t1; \ - PUNPCKLQDQ v6, t2; \ - PUNPCKHQDQ v7, v6; \ - PUNPCKHQDQ t2, v6; \ - PUNPCKLQDQ v7, t2; \ - MOVO t1, v7; \ - MOVO v2, t1; \ - PUNPCKHQDQ t2, v7; \ - PUNPCKLQDQ v3, t2; \ - PUNPCKHQDQ t2, v2; \ - PUNPCKLQDQ t1, t2; \ - PUNPCKHQDQ t2, v3 - -#define SHUFFLE_INV(v2, v3, v4, v5, v6, v7, t1, t2) \ - MOVO v4, t1; \ - MOVO v5, v4; \ - MOVO t1, v5; \ - MOVO v2, t1; \ - PUNPCKLQDQ v2, t2; \ - PUNPCKHQDQ v3, v2; \ - PUNPCKHQDQ t2, v2; \ - PUNPCKLQDQ v3, t2; \ - MOVO t1, v3; \ - MOVO v6, t1; \ - PUNPCKHQDQ t2, v3; \ - PUNPCKLQDQ v7, t2; \ - PUNPCKHQDQ t2, v6; \ - PUNPCKLQDQ t1, t2; \ - PUNPCKHQDQ t2, v7 - -#define HALF_ROUND(v0, v1, v2, v3, v4, v5, v6, v7, t0, c40, c48) \ - MOVO v0, t0; \ - PMULULQ v2, t0; \ - PADDQ v2, v0; \ - PADDQ t0, v0; \ - PADDQ t0, v0; \ - PXOR v0, v6; \ - PSHUFD $0xB1, v6, v6; \ - MOVO v4, t0; \ - PMULULQ v6, t0; \ - PADDQ v6, v4; \ - PADDQ t0, v4; \ - PADDQ t0, v4; \ - PXOR v4, v2; \ - PSHUFB c40, v2; \ - MOVO v0, t0; \ - PMULULQ v2, t0; \ - PADDQ v2, v0; \ - PADDQ t0, v0; \ - PADDQ t0, v0; \ - PXOR v0, v6; \ - PSHUFB c48, v6; \ - MOVO v4, t0; \ - PMULULQ v6, t0; \ - PADDQ v6, v4; \ - PADDQ t0, v4; \ - PADDQ t0, v4; \ - PXOR v4, v2; \ - MOVO v2, t0; \ - PADDQ v2, t0; \ - PSRLQ $63, v2; \ - PXOR t0, v2; \ - MOVO v1, t0; \ - PMULULQ v3, t0; \ - PADDQ v3, v1; \ - PADDQ t0, v1; \ - PADDQ t0, v1; \ - PXOR v1, v7; \ - PSHUFD $0xB1, v7, v7; \ - MOVO v5, t0; \ - PMULULQ v7, t0; \ - PADDQ v7, v5; \ - PADDQ t0, v5; \ - PADDQ t0, v5; \ - PXOR v5, v3; \ - PSHUFB c40, v3; \ - MOVO v1, t0; \ - PMULULQ v3, t0; \ - PADDQ v3, v1; \ - PADDQ t0, v1; \ - PADDQ t0, v1; \ - PXOR v1, v7; \ - PSHUFB c48, v7; \ - MOVO v5, t0; \ - PMULULQ v7, t0; \ - PADDQ v7, v5; \ - PADDQ t0, v5; \ - PADDQ t0, v5; \ - PXOR v5, v3; \ - MOVO v3, t0; \ - PADDQ v3, t0; \ - PSRLQ $63, v3; \ - PXOR t0, v3 - -#define LOAD_MSG_0(block, off) \ - MOVOU 8*(off+0)(block), X0; \ - MOVOU 8*(off+2)(block), X1; \ - MOVOU 8*(off+4)(block), X2; \ - MOVOU 8*(off+6)(block), X3; \ - MOVOU 8*(off+8)(block), X4; \ - MOVOU 8*(off+10)(block), X5; \ - MOVOU 8*(off+12)(block), X6; \ - MOVOU 8*(off+14)(block), X7 - -#define STORE_MSG_0(block, off) \ - MOVOU X0, 8*(off+0)(block); \ - MOVOU X1, 8*(off+2)(block); \ - MOVOU X2, 8*(off+4)(block); \ - MOVOU X3, 8*(off+6)(block); \ - MOVOU X4, 8*(off+8)(block); \ - MOVOU X5, 8*(off+10)(block); \ - MOVOU X6, 8*(off+12)(block); \ - MOVOU X7, 8*(off+14)(block) - -#define LOAD_MSG_1(block, off) \ - MOVOU 8*off+0*8(block), X0; \ - MOVOU 8*off+16*8(block), X1; \ - MOVOU 8*off+32*8(block), X2; \ - MOVOU 8*off+48*8(block), X3; \ - MOVOU 8*off+64*8(block), X4; \ - MOVOU 8*off+80*8(block), X5; \ - MOVOU 8*off+96*8(block), X6; \ - MOVOU 8*off+112*8(block), X7 - -#define STORE_MSG_1(block, off) \ - MOVOU X0, 8*off+0*8(block); \ - MOVOU X1, 8*off+16*8(block); \ - MOVOU X2, 8*off+32*8(block); \ - MOVOU X3, 8*off+48*8(block); \ - MOVOU X4, 8*off+64*8(block); \ - MOVOU X5, 8*off+80*8(block); \ - MOVOU X6, 8*off+96*8(block); \ - MOVOU X7, 8*off+112*8(block) - -#define BLAMKA_ROUND_0(block, off, t0, t1, c40, c48) \ - LOAD_MSG_0(block, off); \ - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, t0, c40, c48); \ - SHUFFLE(X2, X3, X4, X5, X6, X7, t0, t1); \ - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, t0, c40, c48); \ - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, t0, t1); \ - STORE_MSG_0(block, off) - -#define BLAMKA_ROUND_1(block, off, t0, t1, c40, c48) \ - LOAD_MSG_1(block, off); \ - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, t0, c40, c48); \ - SHUFFLE(X2, X3, X4, X5, X6, X7, t0, t1); \ - HALF_ROUND(X0, X1, X2, X3, X4, X5, X6, X7, t0, c40, c48); \ - SHUFFLE_INV(X2, X3, X4, X5, X6, X7, t0, t1); \ - STORE_MSG_1(block, off) - -// func blamkaSSE4(b *block) -TEXT ·blamkaSSE4(SB), 4, $0-8 - MOVQ b+0(FP), AX - - MOVOU ·c40<>(SB), X10 - MOVOU ·c48<>(SB), X11 - - BLAMKA_ROUND_0(AX, 0, X8, X9, X10, X11) - BLAMKA_ROUND_0(AX, 16, X8, X9, X10, X11) - BLAMKA_ROUND_0(AX, 32, X8, X9, X10, X11) - BLAMKA_ROUND_0(AX, 48, X8, X9, X10, X11) - BLAMKA_ROUND_0(AX, 64, X8, X9, X10, X11) - BLAMKA_ROUND_0(AX, 80, X8, X9, X10, X11) - BLAMKA_ROUND_0(AX, 96, X8, X9, X10, X11) - BLAMKA_ROUND_0(AX, 112, X8, X9, X10, X11) - - BLAMKA_ROUND_1(AX, 0, X8, X9, X10, X11) - BLAMKA_ROUND_1(AX, 2, X8, X9, X10, X11) - BLAMKA_ROUND_1(AX, 4, X8, X9, X10, X11) - BLAMKA_ROUND_1(AX, 6, X8, X9, X10, X11) - BLAMKA_ROUND_1(AX, 8, X8, X9, X10, X11) - BLAMKA_ROUND_1(AX, 10, X8, X9, X10, X11) - BLAMKA_ROUND_1(AX, 12, X8, X9, X10, X11) - BLAMKA_ROUND_1(AX, 14, X8, X9, X10, X11) - RET - -// func mixBlocksSSE2(out, a, b, c *block) -TEXT ·mixBlocksSSE2(SB), 4, $0-32 - MOVQ out+0(FP), DX - MOVQ a+8(FP), AX - MOVQ b+16(FP), BX - MOVQ a+24(FP), CX - MOVQ $128, BP - -loop: - MOVOU 0(AX), X0 - MOVOU 0(BX), X1 - MOVOU 0(CX), X2 - PXOR X1, X0 - PXOR X2, X0 - MOVOU X0, 0(DX) - ADDQ $16, AX - ADDQ $16, BX - ADDQ $16, CX - ADDQ $16, DX - SUBQ $2, BP - JA loop - RET - -// func xorBlocksSSE2(out, a, b, c *block) -TEXT ·xorBlocksSSE2(SB), 4, $0-32 - MOVQ out+0(FP), DX - MOVQ a+8(FP), AX - MOVQ b+16(FP), BX - MOVQ a+24(FP), CX - MOVQ $128, BP - -loop: - MOVOU 0(AX), X0 - MOVOU 0(BX), X1 - MOVOU 0(CX), X2 - MOVOU 0(DX), X3 - PXOR X1, X0 - PXOR X2, X0 - PXOR X3, X0 - MOVOU X0, 0(DX) - ADDQ $16, AX - ADDQ $16, BX - ADDQ $16, CX - ADDQ $16, DX - SUBQ $2, BP - JA loop - RET - -// func supportsSSE4() bool -TEXT ·supportsSSE4(SB), 4, $0-1 - MOVL $1, AX - CPUID - SHRL $19, CX // Bit 19 indicates SSE4 support - ANDL $1, CX // CX != 0 if support SSE4 - MOVB CX, ret+0(FP) - RET diff --git a/vendor/github.com/aead/argon2/blamka_generic.go b/vendor/github.com/aead/argon2/blamka_generic.go deleted file mode 100644 index a8936c84..00000000 --- a/vendor/github.com/aead/argon2/blamka_generic.go +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) 2017 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -package argon2 - -var useSSE4 bool - -func processBlockGeneric(out, in1, in2 *block, xor bool) { - var t block - for i := range t { - t[i] = in1[i] ^ in2[i] - } - for i := 0; i < blockLength; i += 16 { - blamkaGeneric( - &t[i+0], &t[i+1], &t[i+2], &t[i+3], - &t[i+4], &t[i+5], &t[i+6], &t[i+7], - &t[i+8], &t[i+9], &t[i+10], &t[i+11], - &t[i+12], &t[i+13], &t[i+14], &t[i+15], - ) - } - for i := 0; i < blockLength/8; i += 2 { - blamkaGeneric( - &t[i], &t[i+1], &t[16+i], &t[16+i+1], - &t[32+i], &t[32+i+1], &t[48+i], &t[48+i+1], - &t[64+i], &t[64+i+1], &t[80+i], &t[80+i+1], - &t[96+i], &t[96+i+1], &t[112+i], &t[112+i+1], - ) - } - if xor { - for i := range t { - out[i] ^= in1[i] ^ in2[i] ^ t[i] - } - } else { - for i := range t { - out[i] = in1[i] ^ in2[i] ^ t[i] - } - } -} - -func blamkaGeneric(t00, t01, t02, t03, t04, t05, t06, t07, t08, t09, t10, t11, t12, t13, t14, t15 *uint64) { - v00, v01, v02, v03 := *t00, *t01, *t02, *t03 - v04, v05, v06, v07 := *t04, *t05, *t06, *t07 - v08, v09, v10, v11 := *t08, *t09, *t10, *t11 - v12, v13, v14, v15 := *t12, *t13, *t14, *t15 - - v00 += v04 + 2*uint64(uint32(v00))*uint64(uint32(v04)) - v12 ^= v00 - v12 = v12>>32 | v12<<32 - v08 += v12 + 2*uint64(uint32(v08))*uint64(uint32(v12)) - v04 ^= v08 - v04 = v04>>24 | v04<<40 - - v00 += v04 + 2*uint64(uint32(v00))*uint64(uint32(v04)) - v12 ^= v00 - v12 = v12>>16 | v12<<48 - v08 += v12 + 2*uint64(uint32(v08))*uint64(uint32(v12)) - v04 ^= v08 - v04 = v04>>63 | v04<<1 - - v01 += v05 + 2*uint64(uint32(v01))*uint64(uint32(v05)) - v13 ^= v01 - v13 = v13>>32 | v13<<32 - v09 += v13 + 2*uint64(uint32(v09))*uint64(uint32(v13)) - v05 ^= v09 - v05 = v05>>24 | v05<<40 - - v01 += v05 + 2*uint64(uint32(v01))*uint64(uint32(v05)) - v13 ^= v01 - v13 = v13>>16 | v13<<48 - v09 += v13 + 2*uint64(uint32(v09))*uint64(uint32(v13)) - v05 ^= v09 - v05 = v05>>63 | v05<<1 - - v02 += v06 + 2*uint64(uint32(v02))*uint64(uint32(v06)) - v14 ^= v02 - v14 = v14>>32 | v14<<32 - v10 += v14 + 2*uint64(uint32(v10))*uint64(uint32(v14)) - v06 ^= v10 - v06 = v06>>24 | v06<<40 - - v02 += v06 + 2*uint64(uint32(v02))*uint64(uint32(v06)) - v14 ^= v02 - v14 = v14>>16 | v14<<48 - v10 += v14 + 2*uint64(uint32(v10))*uint64(uint32(v14)) - v06 ^= v10 - v06 = v06>>63 | v06<<1 - - v03 += v07 + 2*uint64(uint32(v03))*uint64(uint32(v07)) - v15 ^= v03 - v15 = v15>>32 | v15<<32 - v11 += v15 + 2*uint64(uint32(v11))*uint64(uint32(v15)) - v07 ^= v11 - v07 = v07>>24 | v07<<40 - - v03 += v07 + 2*uint64(uint32(v03))*uint64(uint32(v07)) - v15 ^= v03 - v15 = v15>>16 | v15<<48 - v11 += v15 + 2*uint64(uint32(v11))*uint64(uint32(v15)) - v07 ^= v11 - v07 = v07>>63 | v07<<1 - - v00 += v05 + 2*uint64(uint32(v00))*uint64(uint32(v05)) - v15 ^= v00 - v15 = v15>>32 | v15<<32 - v10 += v15 + 2*uint64(uint32(v10))*uint64(uint32(v15)) - v05 ^= v10 - v05 = v05>>24 | v05<<40 - - v00 += v05 + 2*uint64(uint32(v00))*uint64(uint32(v05)) - v15 ^= v00 - v15 = v15>>16 | v15<<48 - v10 += v15 + 2*uint64(uint32(v10))*uint64(uint32(v15)) - v05 ^= v10 - v05 = v05>>63 | v05<<1 - - v01 += v06 + 2*uint64(uint32(v01))*uint64(uint32(v06)) - v12 ^= v01 - v12 = v12>>32 | v12<<32 - v11 += v12 + 2*uint64(uint32(v11))*uint64(uint32(v12)) - v06 ^= v11 - v06 = v06>>24 | v06<<40 - - v01 += v06 + 2*uint64(uint32(v01))*uint64(uint32(v06)) - v12 ^= v01 - v12 = v12>>16 | v12<<48 - v11 += v12 + 2*uint64(uint32(v11))*uint64(uint32(v12)) - v06 ^= v11 - v06 = v06>>63 | v06<<1 - - v02 += v07 + 2*uint64(uint32(v02))*uint64(uint32(v07)) - v13 ^= v02 - v13 = v13>>32 | v13<<32 - v08 += v13 + 2*uint64(uint32(v08))*uint64(uint32(v13)) - v07 ^= v08 - v07 = v07>>24 | v07<<40 - - v02 += v07 + 2*uint64(uint32(v02))*uint64(uint32(v07)) - v13 ^= v02 - v13 = v13>>16 | v13<<48 - v08 += v13 + 2*uint64(uint32(v08))*uint64(uint32(v13)) - v07 ^= v08 - v07 = v07>>63 | v07<<1 - - v03 += v04 + 2*uint64(uint32(v03))*uint64(uint32(v04)) - v14 ^= v03 - v14 = v14>>32 | v14<<32 - v09 += v14 + 2*uint64(uint32(v09))*uint64(uint32(v14)) - v04 ^= v09 - v04 = v04>>24 | v04<<40 - - v03 += v04 + 2*uint64(uint32(v03))*uint64(uint32(v04)) - v14 ^= v03 - v14 = v14>>16 | v14<<48 - v09 += v14 + 2*uint64(uint32(v09))*uint64(uint32(v14)) - v04 ^= v09 - v04 = v04>>63 | v04<<1 - - *t00, *t01, *t02, *t03 = v00, v01, v02, v03 - *t04, *t05, *t06, *t07 = v04, v05, v06, v07 - *t08, *t09, *t10, *t11 = v08, v09, v10, v11 - *t12, *t13, *t14, *t15 = v12, v13, v14, v15 -} diff --git a/vendor/github.com/aead/argon2/blamka_ref.go b/vendor/github.com/aead/argon2/blamka_ref.go deleted file mode 100644 index ed495f4e..00000000 --- a/vendor/github.com/aead/argon2/blamka_ref.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) 2017 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// +build !amd64 appengine gccgo - -package argon2 - -func processBlock(out, in1, in2 *block) { - processBlockGeneric(out, in1, in2, false) -} - -func processBlockXOR(out, in1, in2 *block) { - processBlockGeneric(out, in1, in2, true) -} diff --git a/vendor/github.com/aead/chacha20/.gitignore b/vendor/github.com/aead/chacha20/.gitignore deleted file mode 100644 index 9d3d8437..00000000 --- a/vendor/github.com/aead/chacha20/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test -.vscode - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/aead/chacha20/.travis.yml b/vendor/github.com/aead/chacha20/.travis.yml deleted file mode 100644 index 99199e09..00000000 --- a/vendor/github.com/aead/chacha20/.travis.yml +++ /dev/null @@ -1,25 +0,0 @@ -language: go - -go: - - "1.8.x" - - "1.9.x" - - "1.10.x" - -env: - - TRAVIS_GOARCH=amd64 - - TRAVIS_GOARCH=386 - -before_install: -- export GOARCH=$TRAVIS_GOARCH - -branches: - only: - - master - -before_script: -- go get -u github.com/klauspost/asmfmt/cmd/asmfmt - -script: -- diff -au <(gofmt -d .) <(printf "") -- diff -au <(asmfmt -d .) <(printf "") -- go test -v ./... diff --git a/vendor/github.com/aead/chacha20/LICENSE b/vendor/github.com/aead/chacha20/LICENSE deleted file mode 100644 index b6a9210b..00000000 --- a/vendor/github.com/aead/chacha20/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Andreas Auernhammer - -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/github.com/aead/chacha20/README.md b/vendor/github.com/aead/chacha20/README.md deleted file mode 100644 index b3694249..00000000 --- a/vendor/github.com/aead/chacha20/README.md +++ /dev/null @@ -1,82 +0,0 @@ -[![Godoc Reference](https://godoc.org/github.com/aead/chacha20?status.svg)](https://godoc.org/github.com/aead/chacha20) -[![Build Status](https://travis-ci.org/aead/chacha20.svg?branch=master)](https://travis-ci.org/aead/chacha20) -[![Go Report Card](https://goreportcard.com/badge/aead/chacha20)](https://goreportcard.com/report/aead/chacha20) - -## The ChaCha20 stream cipher - -ChaCha is a stream cipher family created by Daniel J. Bernstein. -The most common ChaCha variant is ChaCha20 (20 rounds). ChaCha20 is -standardized in [RFC 7539](https://tools.ietf.org/html/rfc7539 "RFC 7539"). - -This package provides implementations of three ChaCha versions: -- ChaCha20 with a 64 bit nonce (can en/decrypt up to 2^64 * 64 bytes for one key-nonce combination) -- ChaCha20 with a 96 bit nonce (can en/decrypt up to 2^32 * 64 bytes ~ 256 GB for one key-nonce combination) -- XChaCha20 with a 192 bit nonce (can en/decrypt up to 2^64 * 64 bytes for one key-nonce combination) - -Furthermore the chacha sub package implements ChaCha20/12 and ChaCha20/8. -These versions use 12 or 8 rounds instead of 20. -But it's recommended to use ChaCha20 (with 20 rounds) - it will be fast enough for almost all purposes. - -### Installation -Install in your GOPATH: `go get -u github.com/aead/chacha20` - -### Requirements -All go versions >= 1.8.7 are supported. -The code may also work on Go 1.7 but this is not tested. - -### Performance - -#### AMD64 -Hardware: Intel i7-6500U 2.50GHz x 2 -System: Linux Ubuntu 16.04 - kernel: 4.4.0-62-generic -Go version: 1.8.0 -``` -AVX2 -name speed cpb -ChaCha20_64-4 573MB/s ± 0% 4.16 -ChaCha20_1K-4 2.19GB/s ± 0% 1.06 -XChaCha20_64-4 261MB/s ± 0% 9.13 -XChaCha20_1K-4 1.69GB/s ± 4% 1.37 -XORKeyStream64-4 474MB/s ± 2% 5.02 -XORKeyStream1K-4 2.09GB/s ± 1% 1.11 -XChaCha20_XORKeyStream64-4 262MB/s ± 0% 9.09 -XChaCha20_XORKeyStream1K-4 1.71GB/s ± 1% 1.36 - -SSSE3 -name speed cpb -ChaCha20_64-4 583MB/s ± 0% 4.08 -ChaCha20_1K-4 1.15GB/s ± 1% 2.02 -XChaCha20_64-4 267MB/s ± 0% 8.92 -XChaCha20_1K-4 984MB/s ± 5% 2.42 -XORKeyStream64-4 492MB/s ± 1% 4.84 -XORKeyStream1K-4 1.10GB/s ± 5% 2.11 -XChaCha20_XORKeyStream64-4 266MB/s ± 0% 8.96 -XChaCha20_XORKeyStream1K-4 1.00GB/s ± 2% 2.32 -``` -#### 386 -Hardware: Intel i7-6500U 2.50GHz x 2 -System: Linux Ubuntu 16.04 - kernel: 4.4.0-62-generic -Go version: 1.8.0 -``` -SSSE3 -name                        speed cpb -ChaCha20_64-4               570MB/s ± 0% 4.18 -ChaCha20_1K-4               650MB/s ± 0% 3.66 -XChaCha20_64-4              223MB/s ± 0% 10.69 -XChaCha20_1K-4              584MB/s ± 1% 4.08 -XORKeyStream64-4            392MB/s ± 1% 6.08 -XORKeyStream1K-4            629MB/s ± 1% 3.79 -XChaCha20_XORKeyStream64-4  222MB/s ± 0% 10.73 -XChaCha20_XORKeyStream1K-4  585MB/s ± 0% 4.07 - -SSE2 -name speed cpb -ChaCha20_64-4 509MB/s ± 0% 4.68 -ChaCha20_1K-4 553MB/s ± 2% 4.31 -XChaCha20_64-4 201MB/s ± 0% 11.86 -XChaCha20_1K-4 498MB/s ± 4% 4.78 -XORKeyStream64-4 359MB/s ± 1% 6.64 -XORKeyStream1K-4 545MB/s ± 0% 4.37 -XChaCha20_XORKeyStream64-4 201MB/s ± 1% 11.86 -XChaCha20_XORKeyStream1K-4 507MB/s ± 0% 4.70 -``` diff --git a/vendor/github.com/aead/chacha20/chacha/chacha.go b/vendor/github.com/aead/chacha20/chacha/chacha.go deleted file mode 100644 index c2b39da4..00000000 --- a/vendor/github.com/aead/chacha20/chacha/chacha.go +++ /dev/null @@ -1,197 +0,0 @@ -// Copyright (c) 2016 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// Package chacha implements some low-level functions of the -// ChaCha cipher family. -package chacha // import "github.com/aead/chacha20/chacha" - -import ( - "encoding/binary" - "errors" - "math" -) - -const ( - // NonceSize is the size of the ChaCha20 nonce in bytes. - NonceSize = 8 - - // INonceSize is the size of the IETF-ChaCha20 nonce in bytes. - INonceSize = 12 - - // XNonceSize is the size of the XChaCha20 nonce in bytes. - XNonceSize = 24 - - // KeySize is the size of the key in bytes. - KeySize = 32 -) - -var ( - useSSE2 bool - useSSSE3 bool - useAVX bool - useAVX2 bool -) - -var ( - errKeySize = errors.New("chacha20/chacha: bad key length") - errInvalidNonce = errors.New("chacha20/chacha: bad nonce length") -) - -func setup(state *[64]byte, nonce, key []byte) (err error) { - if len(key) != KeySize { - err = errKeySize - return - } - var Nonce [16]byte - switch len(nonce) { - case NonceSize: - copy(Nonce[8:], nonce) - initialize(state, key, &Nonce) - case INonceSize: - copy(Nonce[4:], nonce) - initialize(state, key, &Nonce) - case XNonceSize: - var tmpKey [32]byte - var hNonce [16]byte - - copy(hNonce[:], nonce[:16]) - copy(tmpKey[:], key) - HChaCha20(&tmpKey, &hNonce, &tmpKey) - copy(Nonce[8:], nonce[16:]) - initialize(state, tmpKey[:], &Nonce) - - // BUG(aead): A "good" compiler will remove this (optimizations) - // But using the provided key instead of tmpKey, - // will change the key (-> probably confuses users) - for i := range tmpKey { - tmpKey[i] = 0 - } - default: - err = errInvalidNonce - } - return -} - -// XORKeyStream crypts bytes from src to dst using the given nonce and key. -// The length of the nonce determinds the version of ChaCha20: -// - NonceSize: ChaCha20/r with a 64 bit nonce and a 2^64 * 64 byte period. -// - INonceSize: ChaCha20/r as defined in RFC 7539 and a 2^32 * 64 byte period. -// - XNonceSize: XChaCha20/r with a 192 bit nonce and a 2^64 * 64 byte period. -// The rounds argument specifies the number of rounds performed for keystream -// generation - valid values are 8, 12 or 20. The src and dst may be the same slice -// but otherwise should not overlap. If len(dst) < len(src) this function panics. -// If the nonce is neither 64, 96 nor 192 bits long, this function panics. -func XORKeyStream(dst, src, nonce, key []byte, rounds int) { - if rounds != 20 && rounds != 12 && rounds != 8 { - panic("chacha20/chacha: bad number of rounds") - } - if len(dst) < len(src) { - panic("chacha20/chacha: dst buffer is to small") - } - if len(nonce) == INonceSize && uint64(len(src)) > (1<<38) { - panic("chacha20/chacha: src is too large") - } - - var block, state [64]byte - if err := setup(&state, nonce, key); err != nil { - panic(err) - } - xorKeyStream(dst, src, &block, &state, rounds) -} - -// Cipher implements ChaCha20/r (XChaCha20/r) for a given number of rounds r. -type Cipher struct { - state, block [64]byte - off int - rounds int // 20 for ChaCha20 - noncesize int -} - -// NewCipher returns a new *chacha.Cipher implementing the ChaCha20/r or XChaCha20/r -// (r = 8, 12 or 20) stream cipher. The nonce must be unique for one key for all time. -// The length of the nonce determinds the version of ChaCha20: -// - NonceSize: ChaCha20/r with a 64 bit nonce and a 2^64 * 64 byte period. -// - INonceSize: ChaCha20/r as defined in RFC 7539 and a 2^32 * 64 byte period. -// - XNonceSize: XChaCha20/r with a 192 bit nonce and a 2^64 * 64 byte period. -// If the nonce is neither 64, 96 nor 192 bits long, a non-nil error is returned. -func NewCipher(nonce, key []byte, rounds int) (*Cipher, error) { - if rounds != 20 && rounds != 12 && rounds != 8 { - panic("chacha20/chacha: bad number of rounds") - } - - c := new(Cipher) - if err := setup(&(c.state), nonce, key); err != nil { - return nil, err - } - c.rounds = rounds - - if len(nonce) == INonceSize { - c.noncesize = INonceSize - } else { - c.noncesize = NonceSize - } - - return c, nil -} - -// XORKeyStream crypts bytes from src to dst. Src and dst may be the same slice -// but otherwise should not overlap. If len(dst) < len(src) the function panics. -func (c *Cipher) XORKeyStream(dst, src []byte) { - if len(dst) < len(src) { - panic("chacha20/chacha: dst buffer is to small") - } - - if c.off > 0 { - n := len(c.block[c.off:]) - if len(src) <= n { - for i, v := range src { - dst[i] = v ^ c.block[c.off] - c.off++ - } - if c.off == 64 { - c.off = 0 - } - return - } - - for i, v := range c.block[c.off:] { - dst[i] = src[i] ^ v - } - src = src[n:] - dst = dst[n:] - c.off = 0 - } - - // check for counter overflow - blocksToXOR := len(src) / 64 - if len(src)%64 != 0 { - blocksToXOR++ - } - var overflow bool - if c.noncesize == INonceSize { - overflow = binary.LittleEndian.Uint32(c.state[48:]) > math.MaxUint32-uint32(blocksToXOR) - } else { - overflow = binary.LittleEndian.Uint64(c.state[48:]) > math.MaxUint64-uint64(blocksToXOR) - } - if overflow { - panic("chacha20/chacha: counter overflow") - } - - c.off += xorKeyStream(dst, src, &(c.block), &(c.state), c.rounds) -} - -// SetCounter skips ctr * 64 byte blocks. SetCounter(0) resets the cipher. -// This function always skips the unused keystream of the current 64 byte block. -func (c *Cipher) SetCounter(ctr uint64) { - if c.noncesize == INonceSize { - binary.LittleEndian.PutUint32(c.state[48:], uint32(ctr)) - } else { - binary.LittleEndian.PutUint64(c.state[48:], ctr) - } - c.off = 0 -} - -// HChaCha20 generates 32 pseudo-random bytes from a 128 bit nonce and a 256 bit secret key. -// It can be used as a key-derivation-function (KDF). -func HChaCha20(out *[32]byte, nonce *[16]byte, key *[32]byte) { hChaCha20(out, nonce, key) } diff --git a/vendor/github.com/aead/chacha20/chacha/chachaAVX2_amd64.s b/vendor/github.com/aead/chacha20/chacha/chachaAVX2_amd64.s deleted file mode 100644 index c2b5f52f..00000000 --- a/vendor/github.com/aead/chacha20/chacha/chachaAVX2_amd64.s +++ /dev/null @@ -1,406 +0,0 @@ -// Copyright (c) 2016 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// +build amd64,!gccgo,!appengine,!nacl - -#include "const.s" -#include "macro.s" - -#define TWO 0(SP) -#define C16 32(SP) -#define C8 64(SP) -#define STATE_0 96(SP) -#define STATE_1 128(SP) -#define STATE_2 160(SP) -#define STATE_3 192(SP) -#define TMP_0 224(SP) -#define TMP_1 256(SP) - -// func xorKeyStreamAVX(dst, src []byte, block, state *[64]byte, rounds int) int -TEXT ·xorKeyStreamAVX2(SB), 4, $320-80 - MOVQ dst_base+0(FP), DI - MOVQ src_base+24(FP), SI - MOVQ block+48(FP), BX - MOVQ state+56(FP), AX - MOVQ rounds+64(FP), DX - MOVQ src_len+32(FP), CX - - MOVQ SP, R8 - ADDQ $32, SP - ANDQ $-32, SP - - VMOVDQU 0(AX), Y2 - VMOVDQU 32(AX), Y3 - VPERM2I128 $0x22, Y2, Y0, Y0 - VPERM2I128 $0x33, Y2, Y1, Y1 - VPERM2I128 $0x22, Y3, Y2, Y2 - VPERM2I128 $0x33, Y3, Y3, Y3 - - TESTQ CX, CX - JZ done - - VMOVDQU ·one_AVX2<>(SB), Y4 - VPADDD Y4, Y3, Y3 - - VMOVDQA Y0, STATE_0 - VMOVDQA Y1, STATE_1 - VMOVDQA Y2, STATE_2 - VMOVDQA Y3, STATE_3 - - VMOVDQU ·rol16_AVX2<>(SB), Y4 - VMOVDQU ·rol8_AVX2<>(SB), Y5 - VMOVDQU ·two_AVX2<>(SB), Y6 - VMOVDQA Y4, Y14 - VMOVDQA Y5, Y15 - VMOVDQA Y4, C16 - VMOVDQA Y5, C8 - VMOVDQA Y6, TWO - - CMPQ CX, $64 - JBE between_0_and_64 - CMPQ CX, $192 - JBE between_64_and_192 - CMPQ CX, $320 - JBE between_192_and_320 - CMPQ CX, $448 - JBE between_320_and_448 - -at_least_512: - VMOVDQA Y0, Y4 - VMOVDQA Y1, Y5 - VMOVDQA Y2, Y6 - VPADDQ TWO, Y3, Y7 - VMOVDQA Y0, Y8 - VMOVDQA Y1, Y9 - VMOVDQA Y2, Y10 - VPADDQ TWO, Y7, Y11 - VMOVDQA Y0, Y12 - VMOVDQA Y1, Y13 - VMOVDQA Y2, Y14 - VPADDQ TWO, Y11, Y15 - - MOVQ DX, R9 - -chacha_loop_512: - VMOVDQA Y8, TMP_0 - CHACHA_QROUND_AVX(Y0, Y1, Y2, Y3, Y8, C16, C8) - CHACHA_QROUND_AVX(Y4, Y5, Y6, Y7, Y8, C16, C8) - VMOVDQA TMP_0, Y8 - VMOVDQA Y0, TMP_0 - CHACHA_QROUND_AVX(Y8, Y9, Y10, Y11, Y0, C16, C8) - CHACHA_QROUND_AVX(Y12, Y13, Y14, Y15, Y0, C16, C8) - CHACHA_SHUFFLE_AVX(Y1, Y2, Y3) - CHACHA_SHUFFLE_AVX(Y5, Y6, Y7) - CHACHA_SHUFFLE_AVX(Y9, Y10, Y11) - CHACHA_SHUFFLE_AVX(Y13, Y14, Y15) - - CHACHA_QROUND_AVX(Y12, Y13, Y14, Y15, Y0, C16, C8) - CHACHA_QROUND_AVX(Y8, Y9, Y10, Y11, Y0, C16, C8) - VMOVDQA TMP_0, Y0 - VMOVDQA Y8, TMP_0 - CHACHA_QROUND_AVX(Y4, Y5, Y6, Y7, Y8, C16, C8) - CHACHA_QROUND_AVX(Y0, Y1, Y2, Y3, Y8, C16, C8) - VMOVDQA TMP_0, Y8 - CHACHA_SHUFFLE_AVX(Y3, Y2, Y1) - CHACHA_SHUFFLE_AVX(Y7, Y6, Y5) - CHACHA_SHUFFLE_AVX(Y11, Y10, Y9) - CHACHA_SHUFFLE_AVX(Y15, Y14, Y13) - SUBQ $2, R9 - JA chacha_loop_512 - - VMOVDQA Y12, TMP_0 - VMOVDQA Y13, TMP_1 - VPADDD STATE_0, Y0, Y0 - VPADDD STATE_1, Y1, Y1 - VPADDD STATE_2, Y2, Y2 - VPADDD STATE_3, Y3, Y3 - XOR_AVX2(DI, SI, 0, Y0, Y1, Y2, Y3, Y12, Y13) - VMOVDQA STATE_0, Y0 - VMOVDQA STATE_1, Y1 - VMOVDQA STATE_2, Y2 - VMOVDQA STATE_3, Y3 - VPADDQ TWO, Y3, Y3 - - VPADDD Y0, Y4, Y4 - VPADDD Y1, Y5, Y5 - VPADDD Y2, Y6, Y6 - VPADDD Y3, Y7, Y7 - XOR_AVX2(DI, SI, 128, Y4, Y5, Y6, Y7, Y12, Y13) - VPADDQ TWO, Y3, Y3 - - VPADDD Y0, Y8, Y8 - VPADDD Y1, Y9, Y9 - VPADDD Y2, Y10, Y10 - VPADDD Y3, Y11, Y11 - XOR_AVX2(DI, SI, 256, Y8, Y9, Y10, Y11, Y12, Y13) - VPADDQ TWO, Y3, Y3 - - VPADDD TMP_0, Y0, Y12 - VPADDD TMP_1, Y1, Y13 - VPADDD Y2, Y14, Y14 - VPADDD Y3, Y15, Y15 - VPADDQ TWO, Y3, Y3 - - CMPQ CX, $512 - JB less_than_512 - - XOR_AVX2(DI, SI, 384, Y12, Y13, Y14, Y15, Y4, Y5) - VMOVDQA Y3, STATE_3 - ADDQ $512, SI - ADDQ $512, DI - SUBQ $512, CX - CMPQ CX, $448 - JA at_least_512 - - TESTQ CX, CX - JZ done - - VMOVDQA C16, Y14 - VMOVDQA C8, Y15 - - CMPQ CX, $64 - JBE between_0_and_64 - CMPQ CX, $192 - JBE between_64_and_192 - CMPQ CX, $320 - JBE between_192_and_320 - JMP between_320_and_448 - -less_than_512: - XOR_UPPER_AVX2(DI, SI, 384, Y12, Y13, Y14, Y15, Y4, Y5) - EXTRACT_LOWER(BX, Y12, Y13, Y14, Y15, Y4) - ADDQ $448, SI - ADDQ $448, DI - SUBQ $448, CX - JMP finalize - -between_320_and_448: - VMOVDQA Y0, Y4 - VMOVDQA Y1, Y5 - VMOVDQA Y2, Y6 - VPADDQ TWO, Y3, Y7 - VMOVDQA Y0, Y8 - VMOVDQA Y1, Y9 - VMOVDQA Y2, Y10 - VPADDQ TWO, Y7, Y11 - - MOVQ DX, R9 - -chacha_loop_384: - CHACHA_QROUND_AVX(Y0, Y1, Y2, Y3, Y13, Y14, Y15) - CHACHA_QROUND_AVX(Y4, Y5, Y6, Y7, Y13, Y14, Y15) - CHACHA_QROUND_AVX(Y8, Y9, Y10, Y11, Y13, Y14, Y15) - CHACHA_SHUFFLE_AVX(Y1, Y2, Y3) - CHACHA_SHUFFLE_AVX(Y5, Y6, Y7) - CHACHA_SHUFFLE_AVX(Y9, Y10, Y11) - CHACHA_QROUND_AVX(Y0, Y1, Y2, Y3, Y13, Y14, Y15) - CHACHA_QROUND_AVX(Y4, Y5, Y6, Y7, Y13, Y14, Y15) - CHACHA_QROUND_AVX(Y8, Y9, Y10, Y11, Y13, Y14, Y15) - CHACHA_SHUFFLE_AVX(Y3, Y2, Y1) - CHACHA_SHUFFLE_AVX(Y7, Y6, Y5) - CHACHA_SHUFFLE_AVX(Y11, Y10, Y9) - SUBQ $2, R9 - JA chacha_loop_384 - - VPADDD STATE_0, Y0, Y0 - VPADDD STATE_1, Y1, Y1 - VPADDD STATE_2, Y2, Y2 - VPADDD STATE_3, Y3, Y3 - XOR_AVX2(DI, SI, 0, Y0, Y1, Y2, Y3, Y12, Y13) - VMOVDQA STATE_0, Y0 - VMOVDQA STATE_1, Y1 - VMOVDQA STATE_2, Y2 - VMOVDQA STATE_3, Y3 - VPADDQ TWO, Y3, Y3 - - VPADDD Y0, Y4, Y4 - VPADDD Y1, Y5, Y5 - VPADDD Y2, Y6, Y6 - VPADDD Y3, Y7, Y7 - XOR_AVX2(DI, SI, 128, Y4, Y5, Y6, Y7, Y12, Y13) - VPADDQ TWO, Y3, Y3 - - VPADDD Y0, Y8, Y8 - VPADDD Y1, Y9, Y9 - VPADDD Y2, Y10, Y10 - VPADDD Y3, Y11, Y11 - VPADDQ TWO, Y3, Y3 - - CMPQ CX, $384 - JB less_than_384 - - XOR_AVX2(DI, SI, 256, Y8, Y9, Y10, Y11, Y12, Y13) - SUBQ $384, CX - TESTQ CX, CX - JE done - - ADDQ $384, SI - ADDQ $384, DI - JMP between_0_and_64 - -less_than_384: - XOR_UPPER_AVX2(DI, SI, 256, Y8, Y9, Y10, Y11, Y12, Y13) - EXTRACT_LOWER(BX, Y8, Y9, Y10, Y11, Y12) - ADDQ $320, SI - ADDQ $320, DI - SUBQ $320, CX - JMP finalize - -between_192_and_320: - VMOVDQA Y0, Y4 - VMOVDQA Y1, Y5 - VMOVDQA Y2, Y6 - VMOVDQA Y3, Y7 - VMOVDQA Y0, Y8 - VMOVDQA Y1, Y9 - VMOVDQA Y2, Y10 - VPADDQ TWO, Y3, Y11 - - MOVQ DX, R9 - -chacha_loop_256: - CHACHA_QROUND_AVX(Y4, Y5, Y6, Y7, Y13, Y14, Y15) - CHACHA_QROUND_AVX(Y8, Y9, Y10, Y11, Y13, Y14, Y15) - CHACHA_SHUFFLE_AVX(Y5, Y6, Y7) - CHACHA_SHUFFLE_AVX(Y9, Y10, Y11) - CHACHA_QROUND_AVX(Y4, Y5, Y6, Y7, Y13, Y14, Y15) - CHACHA_QROUND_AVX(Y8, Y9, Y10, Y11, Y13, Y14, Y15) - CHACHA_SHUFFLE_AVX(Y7, Y6, Y5) - CHACHA_SHUFFLE_AVX(Y11, Y10, Y9) - SUBQ $2, R9 - JA chacha_loop_256 - - VPADDD Y0, Y4, Y4 - VPADDD Y1, Y5, Y5 - VPADDD Y2, Y6, Y6 - VPADDD Y3, Y7, Y7 - VPADDQ TWO, Y3, Y3 - XOR_AVX2(DI, SI, 0, Y4, Y5, Y6, Y7, Y12, Y13) - VPADDD Y0, Y8, Y8 - VPADDD Y1, Y9, Y9 - VPADDD Y2, Y10, Y10 - VPADDD Y3, Y11, Y11 - VPADDQ TWO, Y3, Y3 - - CMPQ CX, $256 - JB less_than_256 - - XOR_AVX2(DI, SI, 128, Y8, Y9, Y10, Y11, Y12, Y13) - SUBQ $256, CX - TESTQ CX, CX - JE done - - ADDQ $256, SI - ADDQ $256, DI - JMP between_0_and_64 - -less_than_256: - XOR_UPPER_AVX2(DI, SI, 128, Y8, Y9, Y10, Y11, Y12, Y13) - EXTRACT_LOWER(BX, Y8, Y9, Y10, Y11, Y12) - ADDQ $192, SI - ADDQ $192, DI - SUBQ $192, CX - JMP finalize - -between_64_and_192: - VMOVDQA Y0, Y4 - VMOVDQA Y1, Y5 - VMOVDQA Y2, Y6 - VMOVDQA Y3, Y7 - - MOVQ DX, R9 - -chacha_loop_128: - CHACHA_QROUND_AVX(Y4, Y5, Y6, Y7, Y13, Y14, Y15) - CHACHA_SHUFFLE_AVX(Y5, Y6, Y7) - CHACHA_QROUND_AVX(Y4, Y5, Y6, Y7, Y13, Y14, Y15) - CHACHA_SHUFFLE_AVX(Y7, Y6, Y5) - SUBQ $2, R9 - JA chacha_loop_128 - - VPADDD Y0, Y4, Y4 - VPADDD Y1, Y5, Y5 - VPADDD Y2, Y6, Y6 - VPADDD Y3, Y7, Y7 - VPADDQ TWO, Y3, Y3 - - CMPQ CX, $128 - JB less_than_128 - - XOR_AVX2(DI, SI, 0, Y4, Y5, Y6, Y7, Y12, Y13) - SUBQ $128, CX - TESTQ CX, CX - JE done - - ADDQ $128, SI - ADDQ $128, DI - JMP between_0_and_64 - -less_than_128: - XOR_UPPER_AVX2(DI, SI, 0, Y4, Y5, Y6, Y7, Y12, Y13) - EXTRACT_LOWER(BX, Y4, Y5, Y6, Y7, Y13) - ADDQ $64, SI - ADDQ $64, DI - SUBQ $64, CX - JMP finalize - -between_0_and_64: - VMOVDQA X0, X4 - VMOVDQA X1, X5 - VMOVDQA X2, X6 - VMOVDQA X3, X7 - - MOVQ DX, R9 - -chacha_loop_64: - CHACHA_QROUND_AVX(X4, X5, X6, X7, X13, X14, X15) - CHACHA_SHUFFLE_AVX(X5, X6, X7) - CHACHA_QROUND_AVX(X4, X5, X6, X7, X13, X14, X15) - CHACHA_SHUFFLE_AVX(X7, X6, X5) - SUBQ $2, R9 - JA chacha_loop_64 - - VPADDD X0, X4, X4 - VPADDD X1, X5, X5 - VPADDD X2, X6, X6 - VPADDD X3, X7, X7 - VMOVDQU ·one<>(SB), X0 - VPADDQ X0, X3, X3 - - CMPQ CX, $64 - JB less_than_64 - - XOR_AVX(DI, SI, 0, X4, X5, X6, X7, X13) - SUBQ $64, CX - JMP done - -less_than_64: - VMOVDQU X4, 0(BX) - VMOVDQU X5, 16(BX) - VMOVDQU X6, 32(BX) - VMOVDQU X7, 48(BX) - -finalize: - XORQ R11, R11 - XORQ R12, R12 - MOVQ CX, BP - -xor_loop: - MOVB 0(SI), R11 - MOVB 0(BX), R12 - XORQ R11, R12 - MOVB R12, 0(DI) - INCQ SI - INCQ BX - INCQ DI - DECQ BP - JA xor_loop - -done: - VMOVDQU X3, 48(AX) - VZEROUPPER - MOVQ R8, SP - MOVQ CX, ret+72(FP) - RET - diff --git a/vendor/github.com/aead/chacha20/chacha/chacha_386.go b/vendor/github.com/aead/chacha20/chacha/chacha_386.go deleted file mode 100644 index 97e533d3..00000000 --- a/vendor/github.com/aead/chacha20/chacha/chacha_386.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2016 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// +build 386,!gccgo,!appengine,!nacl - -package chacha - -import ( - "encoding/binary" - - "golang.org/x/sys/cpu" -) - -func init() { - useSSE2 = cpu.X86.HasSSE2 - useSSSE3 = cpu.X86.HasSSSE3 - useAVX = false - useAVX2 = false -} - -func initialize(state *[64]byte, key []byte, nonce *[16]byte) { - binary.LittleEndian.PutUint32(state[0:], sigma[0]) - binary.LittleEndian.PutUint32(state[4:], sigma[1]) - binary.LittleEndian.PutUint32(state[8:], sigma[2]) - binary.LittleEndian.PutUint32(state[12:], sigma[3]) - copy(state[16:], key[:]) - copy(state[48:], nonce[:]) -} - -// This function is implemented in chacha_386.s -//go:noescape -func hChaCha20SSE2(out *[32]byte, nonce *[16]byte, key *[32]byte) - -// This function is implemented in chacha_386.s -//go:noescape -func hChaCha20SSSE3(out *[32]byte, nonce *[16]byte, key *[32]byte) - -// This function is implemented in chacha_386.s -//go:noescape -func xorKeyStreamSSE2(dst, src []byte, block, state *[64]byte, rounds int) int - -func hChaCha20(out *[32]byte, nonce *[16]byte, key *[32]byte) { - switch { - case useSSSE3: - hChaCha20SSSE3(out, nonce, key) - case useSSE2: - hChaCha20SSE2(out, nonce, key) - default: - hChaCha20Generic(out, nonce, key) - } -} - -func xorKeyStream(dst, src []byte, block, state *[64]byte, rounds int) int { - if useSSE2 { - return xorKeyStreamSSE2(dst, src, block, state, rounds) - } else { - return xorKeyStreamGeneric(dst, src, block, state, rounds) - } -} diff --git a/vendor/github.com/aead/chacha20/chacha/chacha_386.s b/vendor/github.com/aead/chacha20/chacha/chacha_386.s deleted file mode 100644 index 262fc869..00000000 --- a/vendor/github.com/aead/chacha20/chacha/chacha_386.s +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) 2016 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// +build 386,!gccgo,!appengine,!nacl - -#include "const.s" -#include "macro.s" - -// FINALIZE xors len bytes from src and block using -// the temp. registers t0 and t1 and writes the result -// to dst. -#define FINALIZE(dst, src, block, len, t0, t1) \ - XORL t0, t0; \ - XORL t1, t1; \ - FINALIZE_LOOP:; \ - MOVB 0(src), t0; \ - MOVB 0(block), t1; \ - XORL t0, t1; \ - MOVB t1, 0(dst); \ - INCL src; \ - INCL block; \ - INCL dst; \ - DECL len; \ - JG FINALIZE_LOOP \ - -#define Dst DI -#define Nonce AX -#define Key BX -#define Rounds DX - -// func hChaCha20SSE2(out *[32]byte, nonce *[16]byte, key *[32]byte) -TEXT ·hChaCha20SSE2(SB), 4, $0-12 - MOVL out+0(FP), Dst - MOVL nonce+4(FP), Nonce - MOVL key+8(FP), Key - - MOVOU ·sigma<>(SB), X0 - MOVOU 0*16(Key), X1 - MOVOU 1*16(Key), X2 - MOVOU 0*16(Nonce), X3 - MOVL $20, Rounds - -chacha_loop: - CHACHA_QROUND_SSE2(X0, X1, X2, X3, X4) - CHACHA_SHUFFLE_SSE(X1, X2, X3) - CHACHA_QROUND_SSE2(X0, X1, X2, X3, X4) - CHACHA_SHUFFLE_SSE(X3, X2, X1) - SUBL $2, Rounds - JNZ chacha_loop - - MOVOU X0, 0*16(Dst) - MOVOU X3, 1*16(Dst) - RET - -// func hChaCha20SSSE3(out *[32]byte, nonce *[16]byte, key *[32]byte) -TEXT ·hChaCha20SSSE3(SB), 4, $0-12 - MOVL out+0(FP), Dst - MOVL nonce+4(FP), Nonce - MOVL key+8(FP), Key - - MOVOU ·sigma<>(SB), X0 - MOVOU 0*16(Key), X1 - MOVOU 1*16(Key), X2 - MOVOU 0*16(Nonce), X3 - MOVL $20, Rounds - - MOVOU ·rol16<>(SB), X5 - MOVOU ·rol8<>(SB), X6 - -chacha_loop: - CHACHA_QROUND_SSSE3(X0, X1, X2, X3, X4, X5, X6) - CHACHA_SHUFFLE_SSE(X1, X2, X3) - CHACHA_QROUND_SSSE3(X0, X1, X2, X3, X4, X5, X6) - CHACHA_SHUFFLE_SSE(X3, X2, X1) - SUBL $2, Rounds - JNZ chacha_loop - - MOVOU X0, 0*16(Dst) - MOVOU X3, 1*16(Dst) - RET - -#undef Dst -#undef Nonce -#undef Key -#undef Rounds - -#define State AX -#define Dst DI -#define Src SI -#define Len DX -#define Tmp0 BX -#define Tmp1 BP - -// func xorKeyStreamSSE2(dst, src []byte, block, state *[64]byte, rounds int) int -TEXT ·xorKeyStreamSSE2(SB), 4, $0-40 - MOVL dst_base+0(FP), Dst - MOVL src_base+12(FP), Src - MOVL state+28(FP), State - MOVL src_len+16(FP), Len - MOVL $0, ret+36(FP) // Number of bytes written to the keystream buffer - 0 iff len mod 64 == 0 - - MOVOU 0*16(State), X0 - MOVOU 1*16(State), X1 - MOVOU 2*16(State), X2 - MOVOU 3*16(State), X3 - TESTL Len, Len - JZ DONE - -GENERATE_KEYSTREAM: - MOVO X0, X4 - MOVO X1, X5 - MOVO X2, X6 - MOVO X3, X7 - MOVL rounds+32(FP), Tmp0 - -CHACHA_LOOP: - CHACHA_QROUND_SSE2(X4, X5, X6, X7, X0) - CHACHA_SHUFFLE_SSE(X5, X6, X7) - CHACHA_QROUND_SSE2(X4, X5, X6, X7, X0) - CHACHA_SHUFFLE_SSE(X7, X6, X5) - SUBL $2, Tmp0 - JA CHACHA_LOOP - - MOVOU 0*16(State), X0 // Restore X0 from state - PADDL X0, X4 - PADDL X1, X5 - PADDL X2, X6 - PADDL X3, X7 - MOVOU ·one<>(SB), X0 - PADDQ X0, X3 - - CMPL Len, $64 - JL BUFFER_KEYSTREAM - - XOR_SSE(Dst, Src, 0, X4, X5, X6, X7, X0) - MOVOU 0*16(State), X0 // Restore X0 from state - ADDL $64, Src - ADDL $64, Dst - SUBL $64, Len - JZ DONE - JMP GENERATE_KEYSTREAM // There is at least one more plaintext byte - -BUFFER_KEYSTREAM: - MOVL block+24(FP), State - MOVOU X4, 0(State) - MOVOU X5, 16(State) - MOVOU X6, 32(State) - MOVOU X7, 48(State) - MOVL Len, ret+36(FP) // Number of bytes written to the keystream buffer - 0 < Len < 64 - FINALIZE(Dst, Src, State, Len, Tmp0, Tmp1) - -DONE: - MOVL state+28(FP), State - MOVOU X3, 3*16(State) - RET - -#undef State -#undef Dst -#undef Src -#undef Len -#undef Tmp0 -#undef Tmp1 diff --git a/vendor/github.com/aead/chacha20/chacha/chacha_amd64.go b/vendor/github.com/aead/chacha20/chacha/chacha_amd64.go deleted file mode 100644 index 635f7de8..00000000 --- a/vendor/github.com/aead/chacha20/chacha/chacha_amd64.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) 2017 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// +build go1.7,amd64,!gccgo,!appengine,!nacl - -package chacha - -import "golang.org/x/sys/cpu" - -func init() { - useSSE2 = cpu.X86.HasSSE2 - useSSSE3 = cpu.X86.HasSSSE3 - useAVX = cpu.X86.HasAVX - useAVX2 = cpu.X86.HasAVX2 -} - -// This function is implemented in chacha_amd64.s -//go:noescape -func initialize(state *[64]byte, key []byte, nonce *[16]byte) - -// This function is implemented in chacha_amd64.s -//go:noescape -func hChaCha20SSE2(out *[32]byte, nonce *[16]byte, key *[32]byte) - -// This function is implemented in chacha_amd64.s -//go:noescape -func hChaCha20SSSE3(out *[32]byte, nonce *[16]byte, key *[32]byte) - -// This function is implemented in chachaAVX2_amd64.s -//go:noescape -func hChaCha20AVX(out *[32]byte, nonce *[16]byte, key *[32]byte) - -// This function is implemented in chacha_amd64.s -//go:noescape -func xorKeyStreamSSE2(dst, src []byte, block, state *[64]byte, rounds int) int - -// This function is implemented in chacha_amd64.s -//go:noescape -func xorKeyStreamSSSE3(dst, src []byte, block, state *[64]byte, rounds int) int - -// This function is implemented in chacha_amd64.s -//go:noescape -func xorKeyStreamAVX(dst, src []byte, block, state *[64]byte, rounds int) int - -// This function is implemented in chachaAVX2_amd64.s -//go:noescape -func xorKeyStreamAVX2(dst, src []byte, block, state *[64]byte, rounds int) int - -func hChaCha20(out *[32]byte, nonce *[16]byte, key *[32]byte) { - switch { - case useAVX: - hChaCha20AVX(out, nonce, key) - case useSSSE3: - hChaCha20SSSE3(out, nonce, key) - case useSSE2: - hChaCha20SSE2(out, nonce, key) - default: - hChaCha20Generic(out, nonce, key) - } -} - -func xorKeyStream(dst, src []byte, block, state *[64]byte, rounds int) int { - switch { - case useAVX2: - return xorKeyStreamAVX2(dst, src, block, state, rounds) - case useAVX: - return xorKeyStreamAVX(dst, src, block, state, rounds) - case useSSSE3: - return xorKeyStreamSSSE3(dst, src, block, state, rounds) - case useSSE2: - return xorKeyStreamSSE2(dst, src, block, state, rounds) - default: - return xorKeyStreamGeneric(dst, src, block, state, rounds) - } -} diff --git a/vendor/github.com/aead/chacha20/chacha/chacha_amd64.s b/vendor/github.com/aead/chacha20/chacha/chacha_amd64.s deleted file mode 100644 index 26a23835..00000000 --- a/vendor/github.com/aead/chacha20/chacha/chacha_amd64.s +++ /dev/null @@ -1,1072 +0,0 @@ -// Copyright (c) 2016 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// +build amd64,!gccgo,!appengine,!nacl - -#include "const.s" -#include "macro.s" - -// FINALIZE xors len bytes from src and block using -// the temp. registers t0 and t1 and writes the result -// to dst. -#define FINALIZE(dst, src, block, len, t0, t1) \ - XORQ t0, t0; \ - XORQ t1, t1; \ - FINALIZE_LOOP:; \ - MOVB 0(src), t0; \ - MOVB 0(block), t1; \ - XORQ t0, t1; \ - MOVB t1, 0(dst); \ - INCQ src; \ - INCQ block; \ - INCQ dst; \ - DECQ len; \ - JG FINALIZE_LOOP \ - -#define Dst DI -#define Nonce AX -#define Key BX -#define Rounds DX - -// func initialize(state *[64]byte, key []byte, nonce *[16]byte) -TEXT ·initialize(SB), 4, $0-40 - MOVQ state+0(FP), Dst - MOVQ key+8(FP), Key - MOVQ nonce+32(FP), Nonce - - MOVOU ·sigma<>(SB), X0 - MOVOU 0*16(Key), X1 - MOVOU 1*16(Key), X2 - MOVOU 0*16(Nonce), X3 - - MOVOU X0, 0*16(Dst) - MOVOU X1, 1*16(Dst) - MOVOU X2, 2*16(Dst) - MOVOU X3, 3*16(Dst) - RET - -// func hChaCha20AVX(out *[32]byte, nonce *[16]byte, key *[32]byte) -TEXT ·hChaCha20AVX(SB), 4, $0-24 - MOVQ out+0(FP), Dst - MOVQ nonce+8(FP), Nonce - MOVQ key+16(FP), Key - - VMOVDQU ·sigma<>(SB), X0 - VMOVDQU 0*16(Key), X1 - VMOVDQU 1*16(Key), X2 - VMOVDQU 0*16(Nonce), X3 - VMOVDQU ·rol16_AVX2<>(SB), X5 - VMOVDQU ·rol8_AVX2<>(SB), X6 - MOVQ $20, Rounds - -CHACHA_LOOP: - CHACHA_QROUND_AVX(X0, X1, X2, X3, X4, X5, X6) - CHACHA_SHUFFLE_AVX(X1, X2, X3) - CHACHA_QROUND_AVX(X0, X1, X2, X3, X4, X5, X6) - CHACHA_SHUFFLE_AVX(X3, X2, X1) - SUBQ $2, Rounds - JNZ CHACHA_LOOP - - VMOVDQU X0, 0*16(Dst) - VMOVDQU X3, 1*16(Dst) - VZEROUPPER - RET - -// func hChaCha20SSE2(out *[32]byte, nonce *[16]byte, key *[32]byte) -TEXT ·hChaCha20SSE2(SB), 4, $0-24 - MOVQ out+0(FP), Dst - MOVQ nonce+8(FP), Nonce - MOVQ key+16(FP), Key - - MOVOU ·sigma<>(SB), X0 - MOVOU 0*16(Key), X1 - MOVOU 1*16(Key), X2 - MOVOU 0*16(Nonce), X3 - MOVQ $20, Rounds - -CHACHA_LOOP: - CHACHA_QROUND_SSE2(X0, X1, X2, X3, X4) - CHACHA_SHUFFLE_SSE(X1, X2, X3) - CHACHA_QROUND_SSE2(X0, X1, X2, X3, X4) - CHACHA_SHUFFLE_SSE(X3, X2, X1) - SUBQ $2, Rounds - JNZ CHACHA_LOOP - - MOVOU X0, 0*16(Dst) - MOVOU X3, 1*16(Dst) - RET - -// func hChaCha20SSSE3(out *[32]byte, nonce *[16]byte, key *[32]byte) -TEXT ·hChaCha20SSSE3(SB), 4, $0-24 - MOVQ out+0(FP), Dst - MOVQ nonce+8(FP), Nonce - MOVQ key+16(FP), Key - - MOVOU ·sigma<>(SB), X0 - MOVOU 0*16(Key), X1 - MOVOU 1*16(Key), X2 - MOVOU 0*16(Nonce), X3 - MOVOU ·rol16<>(SB), X5 - MOVOU ·rol8<>(SB), X6 - MOVQ $20, Rounds - -chacha_loop: - CHACHA_QROUND_SSSE3(X0, X1, X2, X3, X4, X5, X6) - CHACHA_SHUFFLE_SSE(X1, X2, X3) - CHACHA_QROUND_SSSE3(X0, X1, X2, X3, X4, X5, X6) - CHACHA_SHUFFLE_SSE(X3, X2, X1) - SUBQ $2, Rounds - JNZ chacha_loop - - MOVOU X0, 0*16(Dst) - MOVOU X3, 1*16(Dst) - RET - -#undef Dst -#undef Nonce -#undef Key -#undef Rounds - -#define Dst DI -#define Src SI -#define Len R12 -#define Rounds DX -#define Buffer BX -#define State AX -#define Stack SP -#define SavedSP R8 -#define Tmp0 R9 -#define Tmp1 R10 -#define Tmp2 R11 - -// func xorKeyStreamSSE2(dst, src []byte, block, state *[64]byte, rounds int) int -TEXT ·xorKeyStreamSSE2(SB), 4, $112-80 - MOVQ dst_base+0(FP), Dst - MOVQ src_base+24(FP), Src - MOVQ block+48(FP), Buffer - MOVQ state+56(FP), State - MOVQ rounds+64(FP), Rounds - MOVQ src_len+32(FP), Len - - MOVOU 0*16(State), X0 - MOVOU 1*16(State), X1 - MOVOU 2*16(State), X2 - MOVOU 3*16(State), X3 - - MOVQ Stack, SavedSP - ADDQ $16, Stack - ANDQ $-16, Stack - - TESTQ Len, Len - JZ DONE - - MOVOU ·one<>(SB), X4 - MOVO X0, 0*16(Stack) - MOVO X1, 1*16(Stack) - MOVO X2, 2*16(Stack) - MOVO X3, 3*16(Stack) - MOVO X4, 4*16(Stack) - - CMPQ Len, $64 - JLE GENERATE_KEYSTREAM_64 - CMPQ Len, $128 - JLE GENERATE_KEYSTREAM_128 - CMPQ Len, $192 - JLE GENERATE_KEYSTREAM_192 - -GENERATE_KEYSTREAM_256: - MOVO X0, X12 - MOVO X1, X13 - MOVO X2, X14 - MOVO X3, X15 - PADDQ 4*16(Stack), X15 - MOVO X0, X8 - MOVO X1, X9 - MOVO X2, X10 - MOVO X15, X11 - PADDQ 4*16(Stack), X11 - MOVO X0, X4 - MOVO X1, X5 - MOVO X2, X6 - MOVO X11, X7 - PADDQ 4*16(Stack), X7 - MOVQ Rounds, Tmp0 - - MOVO X3, 3*16(Stack) // Save X3 - -CHACHA_LOOP_256: - MOVO X4, 5*16(Stack) - CHACHA_QROUND_SSE2(X0, X1, X2, X3, X4) - CHACHA_QROUND_SSE2(X12, X13, X14, X15, X4) - MOVO 5*16(Stack), X4 - MOVO X0, 5*16(Stack) - CHACHA_QROUND_SSE2(X8, X9, X10, X11, X0) - CHACHA_QROUND_SSE2(X4, X5, X6, X7, X0) - MOVO 5*16(Stack), X0 - CHACHA_SHUFFLE_SSE(X1, X2, X3) - CHACHA_SHUFFLE_SSE(X13, X14, X15) - CHACHA_SHUFFLE_SSE(X9, X10, X11) - CHACHA_SHUFFLE_SSE(X5, X6, X7) - MOVO X4, 5*16(Stack) - CHACHA_QROUND_SSE2(X0, X1, X2, X3, X4) - CHACHA_QROUND_SSE2(X12, X13, X14, X15, X4) - MOVO 5*16(Stack), X4 - MOVO X0, 5*16(Stack) - CHACHA_QROUND_SSE2(X8, X9, X10, X11, X0) - CHACHA_QROUND_SSE2(X4, X5, X6, X7, X0) - MOVO 5*16(Stack), X0 - CHACHA_SHUFFLE_SSE(X3, X2, X1) - CHACHA_SHUFFLE_SSE(X15, X14, X13) - CHACHA_SHUFFLE_SSE(X11, X10, X9) - CHACHA_SHUFFLE_SSE(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_256 - - PADDL 0*16(Stack), X0 - PADDL 1*16(Stack), X1 - PADDL 2*16(Stack), X2 - PADDL 3*16(Stack), X3 - MOVO X4, 5*16(Stack) // Save X4 - XOR_SSE(Dst, Src, 0, X0, X1, X2, X3, X4) - MOVO 5*16(Stack), X4 // Restore X4 - - MOVO 0*16(Stack), X0 - MOVO 1*16(Stack), X1 - MOVO 2*16(Stack), X2 - MOVO 3*16(Stack), X3 - PADDQ 4*16(Stack), X3 - - PADDL X0, X12 - PADDL X1, X13 - PADDL X2, X14 - PADDL X3, X15 - PADDQ 4*16(Stack), X3 - PADDL X0, X8 - PADDL X1, X9 - PADDL X2, X10 - PADDL X3, X11 - PADDQ 4*16(Stack), X3 - PADDL X0, X4 - PADDL X1, X5 - PADDL X2, X6 - PADDL X3, X7 - PADDQ 4*16(Stack), X3 - - XOR_SSE(Dst, Src, 64, X12, X13, X14, X15, X0) - XOR_SSE(Dst, Src, 128, X8, X9, X10, X11, X0) - MOVO 0*16(Stack), X0 // Restore X0 - ADDQ $192, Dst - ADDQ $192, Src - SUBQ $192, Len - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_SSE(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - JZ DONE - CMPQ Len, $64 // If Len <= 64 -> gen. only 64 byte keystream. - JLE GENERATE_KEYSTREAM_64 - CMPQ Len, $128 // If 64 < Len <= 128 -> gen. only 128 byte keystream. - JLE GENERATE_KEYSTREAM_128 - CMPQ Len, $192 // If Len > 192 -> repeat, otherwise Len > 128 && Len <= 192 -> gen. 192 byte keystream - JG GENERATE_KEYSTREAM_256 - -GENERATE_KEYSTREAM_192: - MOVO X0, X12 - MOVO X1, X13 - MOVO X2, X14 - MOVO X3, X15 - MOVO X0, X8 - MOVO X1, X9 - MOVO X2, X10 - MOVO X3, X11 - PADDQ 4*16(Stack), X11 - MOVO X0, X4 - MOVO X1, X5 - MOVO X2, X6 - MOVO X11, X7 - PADDQ 4*16(Stack), X7 - MOVQ Rounds, Tmp0 - -CHACHA_LOOP_192: - CHACHA_QROUND_SSE2(X12, X13, X14, X15, X0) - CHACHA_QROUND_SSE2(X8, X9, X10, X11, X0) - CHACHA_QROUND_SSE2(X4, X5, X6, X7, X0) - CHACHA_SHUFFLE_SSE(X13, X14, X15) - CHACHA_SHUFFLE_SSE(X9, X10, X11) - CHACHA_SHUFFLE_SSE(X5, X6, X7) - CHACHA_QROUND_SSE2(X12, X13, X14, X15, X0) - CHACHA_QROUND_SSE2(X8, X9, X10, X11, X0) - CHACHA_QROUND_SSE2(X4, X5, X6, X7, X0) - CHACHA_SHUFFLE_SSE(X15, X14, X13) - CHACHA_SHUFFLE_SSE(X11, X10, X9) - CHACHA_SHUFFLE_SSE(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_192 - - MOVO 0*16(Stack), X0 // Restore X0 - PADDL X0, X12 - PADDL X1, X13 - PADDL X2, X14 - PADDL X3, X15 - PADDQ 4*16(Stack), X3 - PADDL X0, X8 - PADDL X1, X9 - PADDL X2, X10 - PADDL X3, X11 - PADDQ 4*16(Stack), X3 - PADDL X0, X4 - PADDL X1, X5 - PADDL X2, X6 - PADDL X3, X7 - PADDQ 4*16(Stack), X3 - - XOR_SSE(Dst, Src, 0, X12, X13, X14, X15, X0) - XOR_SSE(Dst, Src, 64, X8, X9, X10, X11, X0) - MOVO 0*16(Stack), X0 // Restore X0 - ADDQ $128, Dst - ADDQ $128, Src - SUBQ $128, Len - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_SSE(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - JZ DONE - CMPQ Len, $64 // If Len <= 64 -> gen. only 64 byte keystream. - JLE GENERATE_KEYSTREAM_64 - -GENERATE_KEYSTREAM_128: - MOVO X0, X8 - MOVO X1, X9 - MOVO X2, X10 - MOVO X3, X11 - MOVO X0, X4 - MOVO X1, X5 - MOVO X2, X6 - MOVO X3, X7 - PADDQ 4*16(Stack), X7 - MOVQ Rounds, Tmp0 - -CHACHA_LOOP_128: - CHACHA_QROUND_SSE2(X8, X9, X10, X11, X12) - CHACHA_QROUND_SSE2(X4, X5, X6, X7, X12) - CHACHA_SHUFFLE_SSE(X9, X10, X11) - CHACHA_SHUFFLE_SSE(X5, X6, X7) - CHACHA_QROUND_SSE2(X8, X9, X10, X11, X12) - CHACHA_QROUND_SSE2(X4, X5, X6, X7, X12) - CHACHA_SHUFFLE_SSE(X11, X10, X9) - CHACHA_SHUFFLE_SSE(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_128 - - PADDL X0, X8 - PADDL X1, X9 - PADDL X2, X10 - PADDL X3, X11 - PADDQ 4*16(Stack), X3 - PADDL X0, X4 - PADDL X1, X5 - PADDL X2, X6 - PADDL X3, X7 - PADDQ 4*16(Stack), X3 - - XOR_SSE(Dst, Src, 0, X8, X9, X10, X11, X12) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_SSE(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - JZ DONE // If Len == 0 -> DONE, otherwise Len <= 64 -> gen 64 byte keystream - -GENERATE_KEYSTREAM_64: - MOVO X0, X4 - MOVO X1, X5 - MOVO X2, X6 - MOVO X3, X7 - MOVQ Rounds, Tmp0 - -CHACHA_LOOP_64: - CHACHA_QROUND_SSE2(X4, X5, X6, X7, X8) - CHACHA_SHUFFLE_SSE(X5, X6, X7) - CHACHA_QROUND_SSE2(X4, X5, X6, X7, X8) - CHACHA_SHUFFLE_SSE(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_64 - - PADDL X0, X4 - PADDL X1, X5 - PADDL X2, X6 - PADDL X3, X7 - PADDQ 4*16(Stack), X3 - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_SSE(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Src - ADDQ $64, Dst - SUBQ $64, Len - JMP DONE // jump directly to DONE - there is no keystream to buffer, Len == 0 always true. - -BUFFER_KEYSTREAM: - MOVOU X4, 0*16(Buffer) - MOVOU X5, 1*16(Buffer) - MOVOU X6, 2*16(Buffer) - MOVOU X7, 3*16(Buffer) - MOVQ Len, Tmp0 - FINALIZE(Dst, Src, Buffer, Tmp0, Tmp1, Tmp2) - -DONE: - MOVQ SavedSP, Stack // Restore stack pointer - MOVOU X3, 3*16(State) - MOVQ Len, ret+72(FP) - RET - -// func xorKeyStreamSSSE3(dst, src []byte, block, state *[64]byte, rounds int) int -TEXT ·xorKeyStreamSSSE3(SB), 4, $144-80 - MOVQ dst_base+0(FP), Dst - MOVQ src_base+24(FP), Src - MOVQ block+48(FP), Buffer - MOVQ state+56(FP), State - MOVQ rounds+64(FP), Rounds - MOVQ src_len+32(FP), Len - - MOVOU 0*16(State), X0 - MOVOU 1*16(State), X1 - MOVOU 2*16(State), X2 - MOVOU 3*16(State), X3 - - MOVQ Stack, SavedSP - ADDQ $16, Stack - ANDQ $-16, Stack - - TESTQ Len, Len - JZ DONE - - MOVOU ·one<>(SB), X4 - MOVOU ·rol16<>(SB), X5 - MOVOU ·rol8<>(SB), X6 - MOVO X0, 0*16(Stack) - MOVO X1, 1*16(Stack) - MOVO X2, 2*16(Stack) - MOVO X3, 3*16(Stack) - MOVO X4, 4*16(Stack) - MOVO X5, 6*16(Stack) - MOVO X6, 7*16(Stack) - - CMPQ Len, $64 - JLE GENERATE_KEYSTREAM_64 - CMPQ Len, $128 - JLE GENERATE_KEYSTREAM_128 - CMPQ Len, $192 - JLE GENERATE_KEYSTREAM_192 - -GENERATE_KEYSTREAM_256: - MOVO X0, X12 - MOVO X1, X13 - MOVO X2, X14 - MOVO X3, X15 - PADDQ 4*16(Stack), X15 - MOVO X0, X8 - MOVO X1, X9 - MOVO X2, X10 - MOVO X15, X11 - PADDQ 4*16(Stack), X11 - MOVO X0, X4 - MOVO X1, X5 - MOVO X2, X6 - MOVO X11, X7 - PADDQ 4*16(Stack), X7 - MOVQ Rounds, Tmp0 - - MOVO X3, 3*16(Stack) // Save X3 - -CHACHA_LOOP_256: - MOVO X4, 5*16(Stack) - CHACHA_QROUND_SSSE3(X0, X1, X2, X3, X4, 6*16(Stack), 7*16(Stack)) - CHACHA_QROUND_SSSE3(X12, X13, X14, X15, X4, 6*16(Stack), 7*16(Stack)) - MOVO 5*16(Stack), X4 - MOVO X0, 5*16(Stack) - CHACHA_QROUND_SSSE3(X8, X9, X10, X11, X0, 6*16(Stack), 7*16(Stack)) - CHACHA_QROUND_SSSE3(X4, X5, X6, X7, X0, 6*16(Stack), 7*16(Stack)) - MOVO 5*16(Stack), X0 - CHACHA_SHUFFLE_SSE(X1, X2, X3) - CHACHA_SHUFFLE_SSE(X13, X14, X15) - CHACHA_SHUFFLE_SSE(X9, X10, X11) - CHACHA_SHUFFLE_SSE(X5, X6, X7) - MOVO X4, 5*16(Stack) - CHACHA_QROUND_SSSE3(X0, X1, X2, X3, X4, 6*16(Stack), 7*16(Stack)) - CHACHA_QROUND_SSSE3(X12, X13, X14, X15, X4, 6*16(Stack), 7*16(Stack)) - MOVO 5*16(Stack), X4 - MOVO X0, 5*16(Stack) - CHACHA_QROUND_SSSE3(X8, X9, X10, X11, X0, 6*16(Stack), 7*16(Stack)) - CHACHA_QROUND_SSSE3(X4, X5, X6, X7, X0, 6*16(Stack), 7*16(Stack)) - MOVO 5*16(Stack), X0 - CHACHA_SHUFFLE_SSE(X3, X2, X1) - CHACHA_SHUFFLE_SSE(X15, X14, X13) - CHACHA_SHUFFLE_SSE(X11, X10, X9) - CHACHA_SHUFFLE_SSE(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_256 - - PADDL 0*16(Stack), X0 - PADDL 1*16(Stack), X1 - PADDL 2*16(Stack), X2 - PADDL 3*16(Stack), X3 - MOVO X4, 5*16(Stack) // Save X4 - XOR_SSE(Dst, Src, 0, X0, X1, X2, X3, X4) - MOVO 5*16(Stack), X4 // Restore X4 - - MOVO 0*16(Stack), X0 - MOVO 1*16(Stack), X1 - MOVO 2*16(Stack), X2 - MOVO 3*16(Stack), X3 - PADDQ 4*16(Stack), X3 - - PADDL X0, X12 - PADDL X1, X13 - PADDL X2, X14 - PADDL X3, X15 - PADDQ 4*16(Stack), X3 - PADDL X0, X8 - PADDL X1, X9 - PADDL X2, X10 - PADDL X3, X11 - PADDQ 4*16(Stack), X3 - PADDL X0, X4 - PADDL X1, X5 - PADDL X2, X6 - PADDL X3, X7 - PADDQ 4*16(Stack), X3 - - XOR_SSE(Dst, Src, 64, X12, X13, X14, X15, X0) - XOR_SSE(Dst, Src, 128, X8, X9, X10, X11, X0) - MOVO 0*16(Stack), X0 // Restore X0 - ADDQ $192, Dst - ADDQ $192, Src - SUBQ $192, Len - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_SSE(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - JZ DONE - CMPQ Len, $64 // If Len <= 64 -> gen. only 64 byte keystream. - JLE GENERATE_KEYSTREAM_64 - CMPQ Len, $128 // If 64 < Len <= 128 -> gen. only 128 byte keystream. - JLE GENERATE_KEYSTREAM_128 - CMPQ Len, $192 // If Len > 192 -> repeat, otherwise Len > 128 && Len <= 192 -> gen. 192 byte keystream - JG GENERATE_KEYSTREAM_256 - -GENERATE_KEYSTREAM_192: - MOVO X0, X12 - MOVO X1, X13 - MOVO X2, X14 - MOVO X3, X15 - MOVO X0, X8 - MOVO X1, X9 - MOVO X2, X10 - MOVO X3, X11 - PADDQ 4*16(Stack), X11 - MOVO X0, X4 - MOVO X1, X5 - MOVO X2, X6 - MOVO X11, X7 - PADDQ 4*16(Stack), X7 - MOVQ Rounds, Tmp0 - - MOVO 6*16(Stack), X1 // Load 16 bit rotate-left constant - MOVO 7*16(Stack), X2 // Load 8 bit rotate-left constant - -CHACHA_LOOP_192: - CHACHA_QROUND_SSSE3(X12, X13, X14, X15, X0, X1, X2) - CHACHA_QROUND_SSSE3(X8, X9, X10, X11, X0, X1, X2) - CHACHA_QROUND_SSSE3(X4, X5, X6, X7, X0, X1, X2) - CHACHA_SHUFFLE_SSE(X13, X14, X15) - CHACHA_SHUFFLE_SSE(X9, X10, X11) - CHACHA_SHUFFLE_SSE(X5, X6, X7) - CHACHA_QROUND_SSSE3(X12, X13, X14, X15, X0, X1, X2) - CHACHA_QROUND_SSSE3(X8, X9, X10, X11, X0, X1, X2) - CHACHA_QROUND_SSSE3(X4, X5, X6, X7, X0, X1, X2) - CHACHA_SHUFFLE_SSE(X15, X14, X13) - CHACHA_SHUFFLE_SSE(X11, X10, X9) - CHACHA_SHUFFLE_SSE(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_192 - - MOVO 0*16(Stack), X0 // Restore X0 - MOVO 1*16(Stack), X1 // Restore X1 - MOVO 2*16(Stack), X2 // Restore X2 - PADDL X0, X12 - PADDL X1, X13 - PADDL X2, X14 - PADDL X3, X15 - PADDQ 4*16(Stack), X3 - PADDL X0, X8 - PADDL X1, X9 - PADDL X2, X10 - PADDL X3, X11 - PADDQ 4*16(Stack), X3 - PADDL X0, X4 - PADDL X1, X5 - PADDL X2, X6 - PADDL X3, X7 - PADDQ 4*16(Stack), X3 - - XOR_SSE(Dst, Src, 0, X12, X13, X14, X15, X0) - XOR_SSE(Dst, Src, 64, X8, X9, X10, X11, X0) - MOVO 0*16(Stack), X0 // Restore X0 - ADDQ $128, Dst - ADDQ $128, Src - SUBQ $128, Len - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_SSE(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - JZ DONE - CMPQ Len, $64 // If Len <= 64 -> gen. only 64 byte keystream. - JLE GENERATE_KEYSTREAM_64 - -GENERATE_KEYSTREAM_128: - MOVO X0, X8 - MOVO X1, X9 - MOVO X2, X10 - MOVO X3, X11 - MOVO X0, X4 - MOVO X1, X5 - MOVO X2, X6 - MOVO X3, X7 - PADDQ 4*16(Stack), X7 - MOVQ Rounds, Tmp0 - - MOVO 6*16(Stack), X13 // Load 16 bit rotate-left constant - MOVO 7*16(Stack), X14 // Load 8 bit rotate-left constant - -CHACHA_LOOP_128: - CHACHA_QROUND_SSSE3(X8, X9, X10, X11, X12, X13, X14) - CHACHA_QROUND_SSSE3(X4, X5, X6, X7, X12, X13, X14) - CHACHA_SHUFFLE_SSE(X9, X10, X11) - CHACHA_SHUFFLE_SSE(X5, X6, X7) - CHACHA_QROUND_SSSE3(X8, X9, X10, X11, X12, X13, X14) - CHACHA_QROUND_SSSE3(X4, X5, X6, X7, X12, X13, X14) - CHACHA_SHUFFLE_SSE(X11, X10, X9) - CHACHA_SHUFFLE_SSE(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_128 - - PADDL X0, X8 - PADDL X1, X9 - PADDL X2, X10 - PADDL X3, X11 - PADDQ 4*16(Stack), X3 - PADDL X0, X4 - PADDL X1, X5 - PADDL X2, X6 - PADDL X3, X7 - PADDQ 4*16(Stack), X3 - - XOR_SSE(Dst, Src, 0, X8, X9, X10, X11, X12) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_SSE(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - JZ DONE // If Len == 0 -> DONE, otherwise Len <= 64 -> gen 64 byte keystream - -GENERATE_KEYSTREAM_64: - MOVO X0, X4 - MOVO X1, X5 - MOVO X2, X6 - MOVO X3, X7 - MOVQ Rounds, Tmp0 - - MOVO 6*16(Stack), X9 // Load 16 bit rotate-left constant - MOVO 7*16(Stack), X10 // Load 8 bit rotate-left constant - -CHACHA_LOOP_64: - CHACHA_QROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10) - CHACHA_SHUFFLE_SSE(X5, X6, X7) - CHACHA_QROUND_SSSE3(X4, X5, X6, X7, X8, X9, X10) - CHACHA_SHUFFLE_SSE(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_64 - - PADDL X0, X4 - PADDL X1, X5 - PADDL X2, X6 - PADDL X3, X7 - PADDQ 4*16(Stack), X3 - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_SSE(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Src - ADDQ $64, Dst - SUBQ $64, Len - JMP DONE // jump directly to DONE - there is no keystream to buffer, Len == 0 always true. - -BUFFER_KEYSTREAM: - MOVOU X4, 0*16(Buffer) - MOVOU X5, 1*16(Buffer) - MOVOU X6, 2*16(Buffer) - MOVOU X7, 3*16(Buffer) - MOVQ Len, Tmp0 - FINALIZE(Dst, Src, Buffer, Tmp0, Tmp1, Tmp2) - -DONE: - MOVQ SavedSP, Stack // Restore stack pointer - MOVOU X3, 3*16(State) - MOVQ Len, ret+72(FP) - RET - -// func xorKeyStreamAVX(dst, src []byte, block, state *[64]byte, rounds int) int -TEXT ·xorKeyStreamAVX(SB), 4, $144-80 - MOVQ dst_base+0(FP), Dst - MOVQ src_base+24(FP), Src - MOVQ block+48(FP), Buffer - MOVQ state+56(FP), State - MOVQ rounds+64(FP), Rounds - MOVQ src_len+32(FP), Len - - VMOVDQU 0*16(State), X0 - VMOVDQU 1*16(State), X1 - VMOVDQU 2*16(State), X2 - VMOVDQU 3*16(State), X3 - - MOVQ Stack, SavedSP - ADDQ $16, Stack - ANDQ $-16, Stack - - TESTQ Len, Len - JZ DONE - - VMOVDQU ·one<>(SB), X4 - VMOVDQU ·rol16<>(SB), X5 - VMOVDQU ·rol8<>(SB), X6 - VMOVDQA X0, 0*16(Stack) - VMOVDQA X1, 1*16(Stack) - VMOVDQA X2, 2*16(Stack) - VMOVDQA X3, 3*16(Stack) - VMOVDQA X4, 4*16(Stack) - VMOVDQA X5, 6*16(Stack) - VMOVDQA X6, 7*16(Stack) - - CMPQ Len, $64 - JLE GENERATE_KEYSTREAM_64 - CMPQ Len, $128 - JLE GENERATE_KEYSTREAM_128 - CMPQ Len, $192 - JLE GENERATE_KEYSTREAM_192 - -GENERATE_KEYSTREAM_256: - VMOVDQA X0, X12 - VMOVDQA X1, X13 - VMOVDQA X2, X14 - VMOVDQA X3, X15 - VPADDQ 4*16(Stack), X15, X15 - VMOVDQA X0, X8 - VMOVDQA X1, X9 - VMOVDQA X2, X10 - VMOVDQA X15, X11 - VPADDQ 4*16(Stack), X11, X11 - VMOVDQA X0, X4 - VMOVDQA X1, X5 - VMOVDQA X2, X6 - VMOVDQA X11, X7 - VPADDQ 4*16(Stack), X7, X7 - MOVQ Rounds, Tmp0 - - VMOVDQA X3, 3*16(Stack) // Save X3 - -CHACHA_LOOP_256: - VMOVDQA X4, 5*16(Stack) - CHACHA_QROUND_AVX(X0, X1, X2, X3, X4, 6*16(Stack), 7*16(Stack)) - CHACHA_QROUND_AVX(X12, X13, X14, X15, X4, 6*16(Stack), 7*16(Stack)) - VMOVDQA 5*16(Stack), X4 - VMOVDQA X0, 5*16(Stack) - CHACHA_QROUND_AVX(X8, X9, X10, X11, X0, 6*16(Stack), 7*16(Stack)) - CHACHA_QROUND_AVX(X4, X5, X6, X7, X0, 6*16(Stack), 7*16(Stack)) - VMOVDQA 5*16(Stack), X0 - CHACHA_SHUFFLE_AVX(X1, X2, X3) - CHACHA_SHUFFLE_AVX(X13, X14, X15) - CHACHA_SHUFFLE_AVX(X9, X10, X11) - CHACHA_SHUFFLE_AVX(X5, X6, X7) - VMOVDQA X4, 5*16(Stack) - CHACHA_QROUND_AVX(X0, X1, X2, X3, X4, 6*16(Stack), 7*16(Stack)) - CHACHA_QROUND_AVX(X12, X13, X14, X15, X4, 6*16(Stack), 7*16(Stack)) - VMOVDQA 5*16(Stack), X4 - VMOVDQA X0, 5*16(Stack) - CHACHA_QROUND_AVX(X8, X9, X10, X11, X0, 6*16(Stack), 7*16(Stack)) - CHACHA_QROUND_AVX(X4, X5, X6, X7, X0, 6*16(Stack), 7*16(Stack)) - VMOVDQA 5*16(Stack), X0 - CHACHA_SHUFFLE_AVX(X3, X2, X1) - CHACHA_SHUFFLE_AVX(X15, X14, X13) - CHACHA_SHUFFLE_AVX(X11, X10, X9) - CHACHA_SHUFFLE_AVX(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_256 - - VPADDD 0*16(Stack), X0, X0 - VPADDD 1*16(Stack), X1, X1 - VPADDD 2*16(Stack), X2, X2 - VPADDD 3*16(Stack), X3, X3 - VMOVDQA X4, 5*16(Stack) // Save X4 - XOR_AVX(Dst, Src, 0, X0, X1, X2, X3, X4) - VMOVDQA 5*16(Stack), X4 // Restore X4 - - VMOVDQA 0*16(Stack), X0 - VMOVDQA 1*16(Stack), X1 - VMOVDQA 2*16(Stack), X2 - VMOVDQA 3*16(Stack), X3 - VPADDQ 4*16(Stack), X3, X3 - - VPADDD X0, X12, X12 - VPADDD X1, X13, X13 - VPADDD X2, X14, X14 - VPADDD X3, X15, X15 - VPADDQ 4*16(Stack), X3, X3 - VPADDD X0, X8, X8 - VPADDD X1, X9, X9 - VPADDD X2, X10, X10 - VPADDD X3, X11, X11 - VPADDQ 4*16(Stack), X3, X3 - VPADDD X0, X4, X4 - VPADDD X1, X5, X5 - VPADDD X2, X6, X6 - VPADDD X3, X7, X7 - VPADDQ 4*16(Stack), X3, X3 - - XOR_AVX(Dst, Src, 64, X12, X13, X14, X15, X0) - XOR_AVX(Dst, Src, 128, X8, X9, X10, X11, X0) - VMOVDQA 0*16(Stack), X0 // Restore X0 - ADDQ $192, Dst - ADDQ $192, Src - SUBQ $192, Len - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_AVX(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - JZ DONE - CMPQ Len, $64 // If Len <= 64 -> gen. only 64 byte keystream. - JLE GENERATE_KEYSTREAM_64 - CMPQ Len, $128 // If 64 < Len <= 128 -> gen. only 128 byte keystream. - JLE GENERATE_KEYSTREAM_128 - CMPQ Len, $192 // If Len > 192 -> repeat, otherwise Len > 128 && Len <= 192 -> gen. 192 byte keystream - JG GENERATE_KEYSTREAM_256 - -GENERATE_KEYSTREAM_192: - VMOVDQA X0, X12 - VMOVDQA X1, X13 - VMOVDQA X2, X14 - VMOVDQA X3, X15 - VMOVDQA X0, X8 - VMOVDQA X1, X9 - VMOVDQA X2, X10 - VMOVDQA X3, X11 - VPADDQ 4*16(Stack), X11, X11 - VMOVDQA X0, X4 - VMOVDQA X1, X5 - VMOVDQA X2, X6 - VMOVDQA X11, X7 - VPADDQ 4*16(Stack), X7, X7 - MOVQ Rounds, Tmp0 - - VMOVDQA 6*16(Stack), X1 // Load 16 bit rotate-left constant - VMOVDQA 7*16(Stack), X2 // Load 8 bit rotate-left constant - -CHACHA_LOOP_192: - CHACHA_QROUND_AVX(X12, X13, X14, X15, X0, X1, X2) - CHACHA_QROUND_AVX(X8, X9, X10, X11, X0, X1, X2) - CHACHA_QROUND_AVX(X4, X5, X6, X7, X0, X1, X2) - CHACHA_SHUFFLE_AVX(X13, X14, X15) - CHACHA_SHUFFLE_AVX(X9, X10, X11) - CHACHA_SHUFFLE_AVX(X5, X6, X7) - CHACHA_QROUND_AVX(X12, X13, X14, X15, X0, X1, X2) - CHACHA_QROUND_AVX(X8, X9, X10, X11, X0, X1, X2) - CHACHA_QROUND_AVX(X4, X5, X6, X7, X0, X1, X2) - CHACHA_SHUFFLE_AVX(X15, X14, X13) - CHACHA_SHUFFLE_AVX(X11, X10, X9) - CHACHA_SHUFFLE_AVX(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_192 - - VMOVDQA 0*16(Stack), X0 // Restore X0 - VMOVDQA 1*16(Stack), X1 // Restore X1 - VMOVDQA 2*16(Stack), X2 // Restore X2 - VPADDD X0, X12, X12 - VPADDD X1, X13, X13 - VPADDD X2, X14, X14 - VPADDD X3, X15, X15 - VPADDQ 4*16(Stack), X3, X3 - VPADDD X0, X8, X8 - VPADDD X1, X9, X9 - VPADDD X2, X10, X10 - VPADDD X3, X11, X11 - VPADDQ 4*16(Stack), X3, X3 - VPADDD X0, X4, X4 - VPADDD X1, X5, X5 - VPADDD X2, X6, X6 - VPADDD X3, X7, X7 - VPADDQ 4*16(Stack), X3, X3 - - XOR_AVX(Dst, Src, 0, X12, X13, X14, X15, X0) - XOR_AVX(Dst, Src, 64, X8, X9, X10, X11, X0) - VMOVDQA 0*16(Stack), X0 // Restore X0 - ADDQ $128, Dst - ADDQ $128, Src - SUBQ $128, Len - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_AVX(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - JZ DONE - CMPQ Len, $64 // If Len <= 64 -> gen. only 64 byte keystream. - JLE GENERATE_KEYSTREAM_64 - -GENERATE_KEYSTREAM_128: - VMOVDQA X0, X8 - VMOVDQA X1, X9 - VMOVDQA X2, X10 - VMOVDQA X3, X11 - VMOVDQA X0, X4 - VMOVDQA X1, X5 - VMOVDQA X2, X6 - VMOVDQA X3, X7 - VPADDQ 4*16(Stack), X7, X7 - MOVQ Rounds, Tmp0 - - VMOVDQA 6*16(Stack), X13 // Load 16 bit rotate-left constant - VMOVDQA 7*16(Stack), X14 // Load 8 bit rotate-left constant - -CHACHA_LOOP_128: - CHACHA_QROUND_AVX(X8, X9, X10, X11, X12, X13, X14) - CHACHA_QROUND_AVX(X4, X5, X6, X7, X12, X13, X14) - CHACHA_SHUFFLE_AVX(X9, X10, X11) - CHACHA_SHUFFLE_AVX(X5, X6, X7) - CHACHA_QROUND_AVX(X8, X9, X10, X11, X12, X13, X14) - CHACHA_QROUND_AVX(X4, X5, X6, X7, X12, X13, X14) - CHACHA_SHUFFLE_AVX(X11, X10, X9) - CHACHA_SHUFFLE_AVX(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_128 - - VPADDD X0, X8, X8 - VPADDD X1, X9, X9 - VPADDD X2, X10, X10 - VPADDD X3, X11, X11 - VPADDQ 4*16(Stack), X3, X3 - VPADDD X0, X4, X4 - VPADDD X1, X5, X5 - VPADDD X2, X6, X6 - VPADDD X3, X7, X7 - VPADDQ 4*16(Stack), X3, X3 - - XOR_AVX(Dst, Src, 0, X8, X9, X10, X11, X12) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_AVX(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Dst - ADDQ $64, Src - SUBQ $64, Len - JZ DONE // If Len == 0 -> DONE, otherwise Len <= 64 -> gen 64 byte keystream - -GENERATE_KEYSTREAM_64: - VMOVDQA X0, X4 - VMOVDQA X1, X5 - VMOVDQA X2, X6 - VMOVDQA X3, X7 - MOVQ Rounds, Tmp0 - - VMOVDQA 6*16(Stack), X9 // Load 16 bit rotate-left constant - VMOVDQA 7*16(Stack), X10 // Load 8 bit rotate-left constant - -CHACHA_LOOP_64: - CHACHA_QROUND_AVX(X4, X5, X6, X7, X8, X9, X10) - CHACHA_SHUFFLE_AVX(X5, X6, X7) - CHACHA_QROUND_AVX(X4, X5, X6, X7, X8, X9, X10) - CHACHA_SHUFFLE_AVX(X7, X6, X5) - SUBQ $2, Tmp0 - JNZ CHACHA_LOOP_64 - - VPADDD X0, X4, X4 - VPADDD X1, X5, X5 - VPADDD X2, X6, X6 - VPADDD X3, X7, X7 - VPADDQ 4*16(Stack), X3, X3 - - CMPQ Len, $64 - JL BUFFER_KEYSTREAM - - XOR_AVX(Dst, Src, 0, X4, X5, X6, X7, X8) - ADDQ $64, Src - ADDQ $64, Dst - SUBQ $64, Len - JMP DONE // jump directly to DONE - there is no keystream to buffer, Len == 0 always true. - -BUFFER_KEYSTREAM: - VMOVDQU X4, 0*16(Buffer) - VMOVDQU X5, 1*16(Buffer) - VMOVDQU X6, 2*16(Buffer) - VMOVDQU X7, 3*16(Buffer) - MOVQ Len, Tmp0 - FINALIZE(Dst, Src, Buffer, Tmp0, Tmp1, Tmp2) - -DONE: - MOVQ SavedSP, Stack // Restore stack pointer - VMOVDQU X3, 3*16(State) - VZEROUPPER - MOVQ Len, ret+72(FP) - RET - -#undef Dst -#undef Src -#undef Len -#undef Rounds -#undef Buffer -#undef State -#undef Stack -#undef SavedSP -#undef Tmp0 -#undef Tmp1 -#undef Tmp2 diff --git a/vendor/github.com/aead/chacha20/chacha/chacha_generic.go b/vendor/github.com/aead/chacha20/chacha/chacha_generic.go deleted file mode 100644 index 8832d5bc..00000000 --- a/vendor/github.com/aead/chacha20/chacha/chacha_generic.go +++ /dev/null @@ -1,319 +0,0 @@ -// Copyright (c) 2016 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -package chacha - -import "encoding/binary" - -var sigma = [4]uint32{0x61707865, 0x3320646e, 0x79622d32, 0x6b206574} - -func xorKeyStreamGeneric(dst, src []byte, block, state *[64]byte, rounds int) int { - for len(src) >= 64 { - chachaGeneric(block, state, rounds) - - for i, v := range block { - dst[i] = src[i] ^ v - } - src = src[64:] - dst = dst[64:] - } - - n := len(src) - if n > 0 { - chachaGeneric(block, state, rounds) - for i, v := range src { - dst[i] = v ^ block[i] - } - } - return n -} - -func chachaGeneric(dst *[64]byte, state *[64]byte, rounds int) { - v00 := binary.LittleEndian.Uint32(state[0:]) - v01 := binary.LittleEndian.Uint32(state[4:]) - v02 := binary.LittleEndian.Uint32(state[8:]) - v03 := binary.LittleEndian.Uint32(state[12:]) - v04 := binary.LittleEndian.Uint32(state[16:]) - v05 := binary.LittleEndian.Uint32(state[20:]) - v06 := binary.LittleEndian.Uint32(state[24:]) - v07 := binary.LittleEndian.Uint32(state[28:]) - v08 := binary.LittleEndian.Uint32(state[32:]) - v09 := binary.LittleEndian.Uint32(state[36:]) - v10 := binary.LittleEndian.Uint32(state[40:]) - v11 := binary.LittleEndian.Uint32(state[44:]) - v12 := binary.LittleEndian.Uint32(state[48:]) - v13 := binary.LittleEndian.Uint32(state[52:]) - v14 := binary.LittleEndian.Uint32(state[56:]) - v15 := binary.LittleEndian.Uint32(state[60:]) - - s00, s01, s02, s03, s04, s05, s06, s07 := v00, v01, v02, v03, v04, v05, v06, v07 - s08, s09, s10, s11, s12, s13, s14, s15 := v08, v09, v10, v11, v12, v13, v14, v15 - - for i := 0; i < rounds; i += 2 { - v00 += v04 - v12 ^= v00 - v12 = (v12 << 16) | (v12 >> 16) - v08 += v12 - v04 ^= v08 - v04 = (v04 << 12) | (v04 >> 20) - v00 += v04 - v12 ^= v00 - v12 = (v12 << 8) | (v12 >> 24) - v08 += v12 - v04 ^= v08 - v04 = (v04 << 7) | (v04 >> 25) - v01 += v05 - v13 ^= v01 - v13 = (v13 << 16) | (v13 >> 16) - v09 += v13 - v05 ^= v09 - v05 = (v05 << 12) | (v05 >> 20) - v01 += v05 - v13 ^= v01 - v13 = (v13 << 8) | (v13 >> 24) - v09 += v13 - v05 ^= v09 - v05 = (v05 << 7) | (v05 >> 25) - v02 += v06 - v14 ^= v02 - v14 = (v14 << 16) | (v14 >> 16) - v10 += v14 - v06 ^= v10 - v06 = (v06 << 12) | (v06 >> 20) - v02 += v06 - v14 ^= v02 - v14 = (v14 << 8) | (v14 >> 24) - v10 += v14 - v06 ^= v10 - v06 = (v06 << 7) | (v06 >> 25) - v03 += v07 - v15 ^= v03 - v15 = (v15 << 16) | (v15 >> 16) - v11 += v15 - v07 ^= v11 - v07 = (v07 << 12) | (v07 >> 20) - v03 += v07 - v15 ^= v03 - v15 = (v15 << 8) | (v15 >> 24) - v11 += v15 - v07 ^= v11 - v07 = (v07 << 7) | (v07 >> 25) - v00 += v05 - v15 ^= v00 - v15 = (v15 << 16) | (v15 >> 16) - v10 += v15 - v05 ^= v10 - v05 = (v05 << 12) | (v05 >> 20) - v00 += v05 - v15 ^= v00 - v15 = (v15 << 8) | (v15 >> 24) - v10 += v15 - v05 ^= v10 - v05 = (v05 << 7) | (v05 >> 25) - v01 += v06 - v12 ^= v01 - v12 = (v12 << 16) | (v12 >> 16) - v11 += v12 - v06 ^= v11 - v06 = (v06 << 12) | (v06 >> 20) - v01 += v06 - v12 ^= v01 - v12 = (v12 << 8) | (v12 >> 24) - v11 += v12 - v06 ^= v11 - v06 = (v06 << 7) | (v06 >> 25) - v02 += v07 - v13 ^= v02 - v13 = (v13 << 16) | (v13 >> 16) - v08 += v13 - v07 ^= v08 - v07 = (v07 << 12) | (v07 >> 20) - v02 += v07 - v13 ^= v02 - v13 = (v13 << 8) | (v13 >> 24) - v08 += v13 - v07 ^= v08 - v07 = (v07 << 7) | (v07 >> 25) - v03 += v04 - v14 ^= v03 - v14 = (v14 << 16) | (v14 >> 16) - v09 += v14 - v04 ^= v09 - v04 = (v04 << 12) | (v04 >> 20) - v03 += v04 - v14 ^= v03 - v14 = (v14 << 8) | (v14 >> 24) - v09 += v14 - v04 ^= v09 - v04 = (v04 << 7) | (v04 >> 25) - } - - v00 += s00 - v01 += s01 - v02 += s02 - v03 += s03 - v04 += s04 - v05 += s05 - v06 += s06 - v07 += s07 - v08 += s08 - v09 += s09 - v10 += s10 - v11 += s11 - v12 += s12 - v13 += s13 - v14 += s14 - v15 += s15 - - s12++ - binary.LittleEndian.PutUint32(state[48:], s12) - if s12 == 0 { // indicates overflow - s13++ - binary.LittleEndian.PutUint32(state[52:], s13) - } - - binary.LittleEndian.PutUint32(dst[0:], v00) - binary.LittleEndian.PutUint32(dst[4:], v01) - binary.LittleEndian.PutUint32(dst[8:], v02) - binary.LittleEndian.PutUint32(dst[12:], v03) - binary.LittleEndian.PutUint32(dst[16:], v04) - binary.LittleEndian.PutUint32(dst[20:], v05) - binary.LittleEndian.PutUint32(dst[24:], v06) - binary.LittleEndian.PutUint32(dst[28:], v07) - binary.LittleEndian.PutUint32(dst[32:], v08) - binary.LittleEndian.PutUint32(dst[36:], v09) - binary.LittleEndian.PutUint32(dst[40:], v10) - binary.LittleEndian.PutUint32(dst[44:], v11) - binary.LittleEndian.PutUint32(dst[48:], v12) - binary.LittleEndian.PutUint32(dst[52:], v13) - binary.LittleEndian.PutUint32(dst[56:], v14) - binary.LittleEndian.PutUint32(dst[60:], v15) -} - -func hChaCha20Generic(out *[32]byte, nonce *[16]byte, key *[32]byte) { - v00 := sigma[0] - v01 := sigma[1] - v02 := sigma[2] - v03 := sigma[3] - v04 := binary.LittleEndian.Uint32(key[0:]) - v05 := binary.LittleEndian.Uint32(key[4:]) - v06 := binary.LittleEndian.Uint32(key[8:]) - v07 := binary.LittleEndian.Uint32(key[12:]) - v08 := binary.LittleEndian.Uint32(key[16:]) - v09 := binary.LittleEndian.Uint32(key[20:]) - v10 := binary.LittleEndian.Uint32(key[24:]) - v11 := binary.LittleEndian.Uint32(key[28:]) - v12 := binary.LittleEndian.Uint32(nonce[0:]) - v13 := binary.LittleEndian.Uint32(nonce[4:]) - v14 := binary.LittleEndian.Uint32(nonce[8:]) - v15 := binary.LittleEndian.Uint32(nonce[12:]) - - for i := 0; i < 20; i += 2 { - v00 += v04 - v12 ^= v00 - v12 = (v12 << 16) | (v12 >> 16) - v08 += v12 - v04 ^= v08 - v04 = (v04 << 12) | (v04 >> 20) - v00 += v04 - v12 ^= v00 - v12 = (v12 << 8) | (v12 >> 24) - v08 += v12 - v04 ^= v08 - v04 = (v04 << 7) | (v04 >> 25) - v01 += v05 - v13 ^= v01 - v13 = (v13 << 16) | (v13 >> 16) - v09 += v13 - v05 ^= v09 - v05 = (v05 << 12) | (v05 >> 20) - v01 += v05 - v13 ^= v01 - v13 = (v13 << 8) | (v13 >> 24) - v09 += v13 - v05 ^= v09 - v05 = (v05 << 7) | (v05 >> 25) - v02 += v06 - v14 ^= v02 - v14 = (v14 << 16) | (v14 >> 16) - v10 += v14 - v06 ^= v10 - v06 = (v06 << 12) | (v06 >> 20) - v02 += v06 - v14 ^= v02 - v14 = (v14 << 8) | (v14 >> 24) - v10 += v14 - v06 ^= v10 - v06 = (v06 << 7) | (v06 >> 25) - v03 += v07 - v15 ^= v03 - v15 = (v15 << 16) | (v15 >> 16) - v11 += v15 - v07 ^= v11 - v07 = (v07 << 12) | (v07 >> 20) - v03 += v07 - v15 ^= v03 - v15 = (v15 << 8) | (v15 >> 24) - v11 += v15 - v07 ^= v11 - v07 = (v07 << 7) | (v07 >> 25) - v00 += v05 - v15 ^= v00 - v15 = (v15 << 16) | (v15 >> 16) - v10 += v15 - v05 ^= v10 - v05 = (v05 << 12) | (v05 >> 20) - v00 += v05 - v15 ^= v00 - v15 = (v15 << 8) | (v15 >> 24) - v10 += v15 - v05 ^= v10 - v05 = (v05 << 7) | (v05 >> 25) - v01 += v06 - v12 ^= v01 - v12 = (v12 << 16) | (v12 >> 16) - v11 += v12 - v06 ^= v11 - v06 = (v06 << 12) | (v06 >> 20) - v01 += v06 - v12 ^= v01 - v12 = (v12 << 8) | (v12 >> 24) - v11 += v12 - v06 ^= v11 - v06 = (v06 << 7) | (v06 >> 25) - v02 += v07 - v13 ^= v02 - v13 = (v13 << 16) | (v13 >> 16) - v08 += v13 - v07 ^= v08 - v07 = (v07 << 12) | (v07 >> 20) - v02 += v07 - v13 ^= v02 - v13 = (v13 << 8) | (v13 >> 24) - v08 += v13 - v07 ^= v08 - v07 = (v07 << 7) | (v07 >> 25) - v03 += v04 - v14 ^= v03 - v14 = (v14 << 16) | (v14 >> 16) - v09 += v14 - v04 ^= v09 - v04 = (v04 << 12) | (v04 >> 20) - v03 += v04 - v14 ^= v03 - v14 = (v14 << 8) | (v14 >> 24) - v09 += v14 - v04 ^= v09 - v04 = (v04 << 7) | (v04 >> 25) - } - - binary.LittleEndian.PutUint32(out[0:], v00) - binary.LittleEndian.PutUint32(out[4:], v01) - binary.LittleEndian.PutUint32(out[8:], v02) - binary.LittleEndian.PutUint32(out[12:], v03) - binary.LittleEndian.PutUint32(out[16:], v12) - binary.LittleEndian.PutUint32(out[20:], v13) - binary.LittleEndian.PutUint32(out[24:], v14) - binary.LittleEndian.PutUint32(out[28:], v15) -} diff --git a/vendor/github.com/aead/chacha20/chacha/chacha_ref.go b/vendor/github.com/aead/chacha20/chacha/chacha_ref.go deleted file mode 100644 index 526877c2..00000000 --- a/vendor/github.com/aead/chacha20/chacha/chacha_ref.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2016 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// +build !amd64,!386 gccgo appengine nacl - -package chacha - -import "encoding/binary" - -func init() { - useSSE2 = false - useSSSE3 = false - useAVX = false - useAVX2 = false -} - -func initialize(state *[64]byte, key []byte, nonce *[16]byte) { - binary.LittleEndian.PutUint32(state[0:], sigma[0]) - binary.LittleEndian.PutUint32(state[4:], sigma[1]) - binary.LittleEndian.PutUint32(state[8:], sigma[2]) - binary.LittleEndian.PutUint32(state[12:], sigma[3]) - copy(state[16:], key[:]) - copy(state[48:], nonce[:]) -} - -func xorKeyStream(dst, src []byte, block, state *[64]byte, rounds int) int { - return xorKeyStreamGeneric(dst, src, block, state, rounds) -} - -func hChaCha20(out *[32]byte, nonce *[16]byte, key *[32]byte) { - hChaCha20Generic(out, nonce, key) -} diff --git a/vendor/github.com/aead/chacha20/chacha/const.s b/vendor/github.com/aead/chacha20/chacha/const.s deleted file mode 100644 index c7a94a47..00000000 --- a/vendor/github.com/aead/chacha20/chacha/const.s +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2018 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// +build 386,!gccgo,!appengine,!nacl amd64,!gccgo,!appengine,!nacl - -#include "textflag.h" - -DATA ·sigma<>+0x00(SB)/4, $0x61707865 -DATA ·sigma<>+0x04(SB)/4, $0x3320646e -DATA ·sigma<>+0x08(SB)/4, $0x79622d32 -DATA ·sigma<>+0x0C(SB)/4, $0x6b206574 -GLOBL ·sigma<>(SB), (NOPTR+RODATA), $16 // The 4 ChaCha initialization constants - -// SSE2/SSE3/AVX constants - -DATA ·one<>+0x00(SB)/8, $1 -DATA ·one<>+0x08(SB)/8, $0 -GLOBL ·one<>(SB), (NOPTR+RODATA), $16 // The constant 1 as 128 bit value - -DATA ·rol16<>+0x00(SB)/8, $0x0504070601000302 -DATA ·rol16<>+0x08(SB)/8, $0x0D0C0F0E09080B0A -GLOBL ·rol16<>(SB), (NOPTR+RODATA), $16 // The PSHUFB 16 bit left rotate constant - -DATA ·rol8<>+0x00(SB)/8, $0x0605040702010003 -DATA ·rol8<>+0x08(SB)/8, $0x0E0D0C0F0A09080B -GLOBL ·rol8<>(SB), (NOPTR+RODATA), $16 // The PSHUFB 8 bit left rotate constant - -// AVX2 constants - -DATA ·one_AVX2<>+0x00(SB)/8, $0 -DATA ·one_AVX2<>+0x08(SB)/8, $0 -DATA ·one_AVX2<>+0x10(SB)/8, $1 -DATA ·one_AVX2<>+0x18(SB)/8, $0 -GLOBL ·one_AVX2<>(SB), (NOPTR+RODATA), $32 // The constant 1 as 256 bit value - -DATA ·two_AVX2<>+0x00(SB)/8, $2 -DATA ·two_AVX2<>+0x08(SB)/8, $0 -DATA ·two_AVX2<>+0x10(SB)/8, $2 -DATA ·two_AVX2<>+0x18(SB)/8, $0 -GLOBL ·two_AVX2<>(SB), (NOPTR+RODATA), $32 - -DATA ·rol16_AVX2<>+0x00(SB)/8, $0x0504070601000302 -DATA ·rol16_AVX2<>+0x08(SB)/8, $0x0D0C0F0E09080B0A -DATA ·rol16_AVX2<>+0x10(SB)/8, $0x0504070601000302 -DATA ·rol16_AVX2<>+0x18(SB)/8, $0x0D0C0F0E09080B0A -GLOBL ·rol16_AVX2<>(SB), (NOPTR+RODATA), $32 // The VPSHUFB 16 bit left rotate constant - -DATA ·rol8_AVX2<>+0x00(SB)/8, $0x0605040702010003 -DATA ·rol8_AVX2<>+0x08(SB)/8, $0x0E0D0C0F0A09080B -DATA ·rol8_AVX2<>+0x10(SB)/8, $0x0605040702010003 -DATA ·rol8_AVX2<>+0x18(SB)/8, $0x0E0D0C0F0A09080B -GLOBL ·rol8_AVX2<>(SB), (NOPTR+RODATA), $32 // The VPSHUFB 8 bit left rotate constant diff --git a/vendor/github.com/aead/chacha20/chacha/macro.s b/vendor/github.com/aead/chacha20/chacha/macro.s deleted file mode 100644 index 780108f8..00000000 --- a/vendor/github.com/aead/chacha20/chacha/macro.s +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) 2018 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// +build 386,!gccgo,!appengine,!nacl amd64,!gccgo,!appengine,!nacl - -// ROTL_SSE rotates all 4 32 bit values of the XMM register v -// left by n bits using SSE2 instructions (0 <= n <= 32). -// The XMM register t is used as a temp. register. -#define ROTL_SSE(n, t, v) \ - MOVO v, t; \ - PSLLL $n, t; \ - PSRLL $(32-n), v; \ - PXOR t, v - -// ROTL_AVX rotates all 4/8 32 bit values of the AVX/AVX2 register v -// left by n bits using AVX/AVX2 instructions (0 <= n <= 32). -// The AVX/AVX2 register t is used as a temp. register. -#define ROTL_AVX(n, t, v) \ - VPSLLD $n, v, t; \ - VPSRLD $(32-n), v, v; \ - VPXOR v, t, v - -// CHACHA_QROUND_SSE2 performs a ChaCha quarter-round using the -// 4 XMM registers v0, v1, v2 and v3. It uses only ROTL_SSE2 for -// rotations. The XMM register t is used as a temp. register. -#define CHACHA_QROUND_SSE2(v0, v1, v2, v3, t) \ - PADDL v1, v0; \ - PXOR v0, v3; \ - ROTL_SSE(16, t, v3); \ - PADDL v3, v2; \ - PXOR v2, v1; \ - ROTL_SSE(12, t, v1); \ - PADDL v1, v0; \ - PXOR v0, v3; \ - ROTL_SSE(8, t, v3); \ - PADDL v3, v2; \ - PXOR v2, v1; \ - ROTL_SSE(7, t, v1) - -// CHACHA_QROUND_SSSE3 performs a ChaCha quarter-round using the -// 4 XMM registers v0, v1, v2 and v3. It uses PSHUFB for 8/16 bit -// rotations. The XMM register t is used as a temp. register. -// -// r16 holds the PSHUFB constant for a 16 bit left rotate. -// r8 holds the PSHUFB constant for a 8 bit left rotate. -#define CHACHA_QROUND_SSSE3(v0, v1, v2, v3, t, r16, r8) \ - PADDL v1, v0; \ - PXOR v0, v3; \ - PSHUFB r16, v3; \ - PADDL v3, v2; \ - PXOR v2, v1; \ - ROTL_SSE(12, t, v1); \ - PADDL v1, v0; \ - PXOR v0, v3; \ - PSHUFB r8, v3; \ - PADDL v3, v2; \ - PXOR v2, v1; \ - ROTL_SSE(7, t, v1) - -// CHACHA_QROUND_AVX performs a ChaCha quarter-round using the -// 4 AVX/AVX2 registers v0, v1, v2 and v3. It uses VPSHUFB for 8/16 bit -// rotations. The AVX/AVX2 register t is used as a temp. register. -// -// r16 holds the VPSHUFB constant for a 16 bit left rotate. -// r8 holds the VPSHUFB constant for a 8 bit left rotate. -#define CHACHA_QROUND_AVX(v0, v1, v2, v3, t, r16, r8) \ - VPADDD v0, v1, v0; \ - VPXOR v3, v0, v3; \ - VPSHUFB r16, v3, v3; \ - VPADDD v2, v3, v2; \ - VPXOR v1, v2, v1; \ - ROTL_AVX(12, t, v1); \ - VPADDD v0, v1, v0; \ - VPXOR v3, v0, v3; \ - VPSHUFB r8, v3, v3; \ - VPADDD v2, v3, v2; \ - VPXOR v1, v2, v1; \ - ROTL_AVX(7, t, v1) - -// CHACHA_SHUFFLE_SSE performs a ChaCha shuffle using the -// 3 XMM registers v1, v2 and v3. The inverse shuffle is -// performed by switching v1 and v3: CHACHA_SHUFFLE_SSE(v3, v2, v1). -#define CHACHA_SHUFFLE_SSE(v1, v2, v3) \ - PSHUFL $0x39, v1, v1; \ - PSHUFL $0x4E, v2, v2; \ - PSHUFL $0x93, v3, v3 - -// CHACHA_SHUFFLE_AVX performs a ChaCha shuffle using the -// 3 AVX/AVX2 registers v1, v2 and v3. The inverse shuffle is -// performed by switching v1 and v3: CHACHA_SHUFFLE_AVX(v3, v2, v1). -#define CHACHA_SHUFFLE_AVX(v1, v2, v3) \ - VPSHUFD $0x39, v1, v1; \ - VPSHUFD $0x4E, v2, v2; \ - VPSHUFD $0x93, v3, v3 - -// XOR_SSE extracts 4x16 byte vectors from src at -// off, xors all vectors with the corresponding XMM -// register (v0 - v3) and writes the result to dst -// at off. -// The XMM register t is used as a temp. register. -#define XOR_SSE(dst, src, off, v0, v1, v2, v3, t) \ - MOVOU 0+off(src), t; \ - PXOR v0, t; \ - MOVOU t, 0+off(dst); \ - MOVOU 16+off(src), t; \ - PXOR v1, t; \ - MOVOU t, 16+off(dst); \ - MOVOU 32+off(src), t; \ - PXOR v2, t; \ - MOVOU t, 32+off(dst); \ - MOVOU 48+off(src), t; \ - PXOR v3, t; \ - MOVOU t, 48+off(dst) - -// XOR_AVX extracts 4x16 byte vectors from src at -// off, xors all vectors with the corresponding AVX -// register (v0 - v3) and writes the result to dst -// at off. -// The XMM register t is used as a temp. register. -#define XOR_AVX(dst, src, off, v0, v1, v2, v3, t) \ - VPXOR 0+off(src), v0, t; \ - VMOVDQU t, 0+off(dst); \ - VPXOR 16+off(src), v1, t; \ - VMOVDQU t, 16+off(dst); \ - VPXOR 32+off(src), v2, t; \ - VMOVDQU t, 32+off(dst); \ - VPXOR 48+off(src), v3, t; \ - VMOVDQU t, 48+off(dst) - -#define XOR_AVX2(dst, src, off, v0, v1, v2, v3, t0, t1) \ - VMOVDQU (0+off)(src), t0; \ - VPERM2I128 $32, v1, v0, t1; \ - VPXOR t0, t1, t0; \ - VMOVDQU t0, (0+off)(dst); \ - VMOVDQU (32+off)(src), t0; \ - VPERM2I128 $32, v3, v2, t1; \ - VPXOR t0, t1, t0; \ - VMOVDQU t0, (32+off)(dst); \ - VMOVDQU (64+off)(src), t0; \ - VPERM2I128 $49, v1, v0, t1; \ - VPXOR t0, t1, t0; \ - VMOVDQU t0, (64+off)(dst); \ - VMOVDQU (96+off)(src), t0; \ - VPERM2I128 $49, v3, v2, t1; \ - VPXOR t0, t1, t0; \ - VMOVDQU t0, (96+off)(dst) - -#define XOR_UPPER_AVX2(dst, src, off, v0, v1, v2, v3, t0, t1) \ - VMOVDQU (0+off)(src), t0; \ - VPERM2I128 $32, v1, v0, t1; \ - VPXOR t0, t1, t0; \ - VMOVDQU t0, (0+off)(dst); \ - VMOVDQU (32+off)(src), t0; \ - VPERM2I128 $32, v3, v2, t1; \ - VPXOR t0, t1, t0; \ - VMOVDQU t0, (32+off)(dst); \ - -#define EXTRACT_LOWER(dst, v0, v1, v2, v3, t0) \ - VPERM2I128 $49, v1, v0, t0; \ - VMOVDQU t0, 0(dst); \ - VPERM2I128 $49, v3, v2, t0; \ - VMOVDQU t0, 32(dst) diff --git a/vendor/github.com/aead/chacha20/chacha20.go b/vendor/github.com/aead/chacha20/chacha20.go deleted file mode 100644 index df6ddd23..00000000 --- a/vendor/github.com/aead/chacha20/chacha20.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) 2016 Andreas Auernhammer. All rights reserved. -// Use of this source code is governed by a license that can be -// found in the LICENSE file. - -// Package chacha20 implements the ChaCha20 / XChaCha20 stream chipher. -// Notice that one specific key-nonce combination must be unique for all time. -// -// There are three versions of ChaCha20: -// - ChaCha20 with a 64 bit nonce (en/decrypt up to 2^64 * 64 bytes for one key-nonce combination) -// - ChaCha20 with a 96 bit nonce (en/decrypt up to 2^32 * 64 bytes (~256 GB) for one key-nonce combination) -// - XChaCha20 with a 192 bit nonce (en/decrypt up to 2^64 * 64 bytes for one key-nonce combination) -package chacha20 // import "github.com/aead/chacha20" - -import ( - "crypto/cipher" - - "github.com/aead/chacha20/chacha" -) - -// XORKeyStream crypts bytes from src to dst using the given nonce and key. -// The length of the nonce determinds the version of ChaCha20: -// - 8 bytes: ChaCha20 with a 64 bit nonce and a 2^64 * 64 byte period. -// - 12 bytes: ChaCha20 as defined in RFC 7539 and a 2^32 * 64 byte period. -// - 24 bytes: XChaCha20 with a 192 bit nonce and a 2^64 * 64 byte period. -// Src and dst may be the same slice but otherwise should not overlap. -// If len(dst) < len(src) this function panics. -// If the nonce is neither 64, 96 nor 192 bits long, this function panics. -func XORKeyStream(dst, src, nonce, key []byte) { - chacha.XORKeyStream(dst, src, nonce, key, 20) -} - -// NewCipher returns a new cipher.Stream implementing a ChaCha20 version. -// The nonce must be unique for one key for all time. -// The length of the nonce determinds the version of ChaCha20: -// - 8 bytes: ChaCha20 with a 64 bit nonce and a 2^64 * 64 byte period. -// - 12 bytes: ChaCha20 as defined in RFC 7539 and a 2^32 * 64 byte period. -// - 24 bytes: XChaCha20 with a 192 bit nonce and a 2^64 * 64 byte period. -// If the nonce is neither 64, 96 nor 192 bits long, a non-nil error is returned. -func NewCipher(nonce, key []byte) (cipher.Stream, error) { - return chacha.NewCipher(nonce, key, 20) -} diff --git a/vendor/github.com/alecthomas/assert/LICENCE.txt b/vendor/github.com/alecthomas/assert/LICENCE.txt deleted file mode 100644 index 7047a2cb..00000000 --- a/vendor/github.com/alecthomas/assert/LICENCE.txt +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell - -Please consider promoting this project if you find it useful. - -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/github.com/alecthomas/assert/README.md b/vendor/github.com/alecthomas/assert/README.md deleted file mode 100644 index 4f56369d..00000000 --- a/vendor/github.com/alecthomas/assert/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# Go assertion library (fork of [stretchr/testify/require](https://github.com/stretchr/testify/tree/master/require)) - -This is a fork of stretchr's assertion library that does two things: - -1. It makes spotting differences in equality much easier. It uses [repr](https://github.com/alecthomas/repr) and - [diffmatchpatch](https://github.com/sergi/go-diff/diffmatchpatch) to display structural differences - in colour. -2. Aborts tests on first assertion failure (the same behaviour as `stretchr/testify/require`). - -## Example - -Given the following test: - -```go -type Person struct { - Name string - Age int -} - -// Use github.com/alecthomas/assert -func TestDiff(t *testing.T) { - expected := []*Person{{"Alec", 20}, {"Bob", 21}, {"Sally", 22}} - actual := []*Person{{"Alex", 20}, {"Bob", 22}, {"Sally", 22}} - assert.Equal(t, expected, actual) -} - -// Use github.com/stretchr/testify/require -func TestTestifyDiff(t *testing.T) { - expected := []*Person{{"Alec", 20}, {"Bob", 21}, {"Sally", 22}} - actual := []*Person{{"Alex", 20}, {"Bob", 22}, {"Sally", 22}} - require.Equal(t, expected, actual) -} -``` - -The following output illustrates the problems this solves. Firstly, it shows -nested structures correctly, and secondly it highlights the differences between -actual and expected text. - - diff --git a/vendor/github.com/alecthomas/assert/assertions.go b/vendor/github.com/alecthomas/assert/assertions.go deleted file mode 100644 index 9b87cad1..00000000 --- a/vendor/github.com/alecthomas/assert/assertions.go +++ /dev/null @@ -1,826 +0,0 @@ -package assert - -import ( - "bufio" - "bytes" - "fmt" - "math" - "reflect" - "regexp" - "runtime" - "strings" - "time" - "unicode" - "unicode/utf8" - - "github.com/alecthomas/repr" -) - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Errorf(format string, args ...interface{}) - FailNow() -} - -// Comparison a custom function that returns true on success and false on failure -type Comparison func() (success bool) - -/* - Helper functions -*/ - -// ObjectsAreEqual determines if two objects are considered equal. -// -// This function does no assertion of any kind. -func ObjectsAreEqual(expected, actual interface{}) bool { - - if expected == nil || actual == nil { - return expected == actual - } - - if reflect.DeepEqual(expected, actual) { - return true - } - - return false - -} - -// ObjectsAreEqualValues gets whether two objects are equal, or if their -// values are equal. -func ObjectsAreEqualValues(expected, actual interface{}) bool { - if ObjectsAreEqual(expected, actual) { - return true - } - - actualType := reflect.TypeOf(actual) - expectedValue := reflect.ValueOf(expected) - if expectedValue.Type().ConvertibleTo(actualType) { - // Attempt comparison after type conversion - if reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) { - return true - } - } - - return false -} - -/* CallerInfo is necessary because the assert functions use the testing object -internally, causing it to print the file:line of the assert method, rather than where -the problem actually occured in calling code.*/ - -// CallerInfo returns an array of strings containing the file and line number -// of each stack frame leading from the current test to the assert call that -// failed. -func CallerInfo() []string { - - pc := uintptr(0) - file := "" - line := 0 - ok := false - name := "" - - callers := []string{} - for i := 0; ; i++ { - pc, file, line, ok = runtime.Caller(i) - if !ok { - return nil - } - - // This is a huge edge case, but it will panic if this is the case, see #180 - if file == "" { - break - } - - parts := strings.Split(file, "/") - dir := parts[len(parts)-2] - file = parts[len(parts)-1] - if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { - callers = append(callers, fmt.Sprintf("%s:%d", file, line)) - } - - f := runtime.FuncForPC(pc) - if f == nil { - break - } - name = f.Name() - // Drop the package - segments := strings.Split(name, ".") - name = segments[len(segments)-1] - if isTest(name, "Test") || - isTest(name, "Benchmark") || - isTest(name, "Example") { - break - } - } - - return callers -} - -// Stolen from the `go test` tool. -// isTest tells whether name looks like a test (or benchmark, according to prefix). -// It is a Test (say) if there is a character after Test that is not a lower-case letter. -// We don't want TesticularCancer. -func isTest(name, prefix string) bool { - if !strings.HasPrefix(name, prefix) { - return false - } - if len(name) == len(prefix) { // "Test" is ok - return true - } - rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) - return !unicode.IsLower(rune) -} - -// getWhitespaceString returns a string that is long enough to overwrite the default -// output from the go testing framework. -func getWhitespaceString() string { - - _, file, line, ok := runtime.Caller(1) - if !ok { - return "" - } - parts := strings.Split(file, "/") - file = parts[len(parts)-1] - - return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line))) - -} - -func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { - if len(msgAndArgs) == 0 || msgAndArgs == nil { - return "" - } - if len(msgAndArgs) == 1 { - return msgAndArgs[0].(string) - } - if len(msgAndArgs) > 1 { - return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) - } - return "" -} - -// Indents all lines of the message by appending a number of tabs to each line, in an output format compatible with Go's -// test printing (see inner comment for specifics) -func indentMessageLines(message string, tabs int) string { - outBuf := new(bytes.Buffer) - - for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { - if i != 0 { - outBuf.WriteRune('\n') - } - for ii := 0; ii < tabs; ii++ { - outBuf.WriteRune('\t') - // Bizarrely, all lines except the first need one fewer tabs prepended, so deliberately advance the counter - // by 1 prematurely. - if ii == 0 && i > 0 { - ii++ - } - } - outBuf.WriteString(scanner.Text()) - } - - return outBuf.String() -} - -// Fail reports a failure through -func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) { - - message := messageFromMsgAndArgs(msgAndArgs...) - - errorTrace := strings.Join(CallerInfo(), "\n\r\t\t\t") - if len(message) > 0 { - t.Errorf("\r%s\r\tError Trace:\t%s\n"+ - "\r\tError:%s\n"+ - "\r\tMessages:\t%s\n\r", - getWhitespaceString(), - errorTrace, - indentMessageLines(failureMessage, 2), - message) - } else { - t.Errorf("\r%s\r\tError Trace:\t%s\n"+ - "\r\tError:%s\n\r", - getWhitespaceString(), - errorTrace, - indentMessageLines(failureMessage, 2)) - } - - t.FailNow() -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") -func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { - - interfaceType := reflect.TypeOf(interfaceObject).Elem() - - if !reflect.TypeOf(object).Implements(interfaceType) { - Fail(t, fmt.Sprintf("Object must implement %v", interfaceType), msgAndArgs...) - } - -} - -// IsType asserts that the specified objects are of the same type. -func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { - - if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { - Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) - } -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(t, 123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { - - if !ObjectsAreEqual(expected, actual) { - Fail(t, fmt.Sprintf("Not equal: %s", DiffValues(expected, actual)), msgAndArgs...) - } -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { - - if !ObjectsAreEqualValues(expected, actual) { - Fail(t, fmt.Sprintf("Not equal: %s", DiffValues(expected, actual)), msgAndArgs...) - } -} - -// Exactly asserts that two objects are equal is value and type. -// -// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { - - aType := reflect.TypeOf(expected) - bType := reflect.TypeOf(actual) - - if aType != bType { - Fail(t, "Types expected to match exactly", "%v != %v", aType, bType) - } - - Equal(t, expected, actual, msgAndArgs...) - -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(t, err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if !isNil(object) { - return - } - Fail(t, "Expected value not to be nil.", msgAndArgs...) -} - -// isNil checks if a specified object is nil or not, without Failing. -func isNil(object interface{}) bool { - if object == nil { - return true - } - - value := reflect.ValueOf(object) - kind := value.Kind() - if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { - return true - } - - return false -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(t, err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if isNil(object) { - return - } - Fail(t, fmt.Sprintf("Expected nil, but got: %s", repr.String(object, repr.OmitEmpty(true))), msgAndArgs...) -} - -var numericZeros = []interface{}{ - int(0), - int8(0), - int16(0), - int32(0), - int64(0), - uint(0), - uint8(0), - uint16(0), - uint32(0), - uint64(0), - float32(0), - float64(0), -} - -// isEmpty gets whether the specified object is considered empty or not. -func isEmpty(object interface{}) bool { - - if object == nil { - return true - } else if object == "" { - return true - } else if object == false { - return true - } - - for _, v := range numericZeros { - if object == v { - return true - } - } - - objValue := reflect.ValueOf(object) - - switch objValue.Kind() { - case reflect.Map: - fallthrough - case reflect.Slice, reflect.Chan: - { - return (objValue.Len() == 0) - } - case reflect.Ptr: - { - switch object.(type) { - case *time.Time: - return object.(*time.Time).IsZero() - default: - return false - } - } - } - return false -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Empty(t, obj) -// -// Returns whether the assertion was successful (true) or not (false). -func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { - - pass := isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) - } -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.NotEmpty(t, obj) -// assert.Equal(t, "two", obj[1]) -// -// Returns whether the assertion was successful (true) or not (false). -func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { - - pass := !isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) - } -} - -// getLen try to get length of object. -// return (false, 0) if impossible. -func getLen(x interface{}) (ok bool, length int) { - v := reflect.ValueOf(x) - defer func() { - if e := recover(); e != nil { - ok = false - } - }() - return true, v.Len() -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(t, mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { - ok, l := getLen(object) - if !ok { - Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) - } - - if l != length { - Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) - } -} - -// True asserts that the specified value is true. -// -// assert.True(t, myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func True(t TestingT, value bool, msgAndArgs ...interface{}) { - - if value != true { - Fail(t, "Should be true", msgAndArgs...) - } -} - -// False asserts that the specified value is true. -// -// assert.False(t, myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func False(t TestingT, value bool, msgAndArgs ...interface{}) { - - if value != false { - Fail(t, "Should be false", msgAndArgs...) - } -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) { - - if ObjectsAreEqual(expected, actual) { - Fail(t, fmt.Sprintf("Should not be: %s\n", repr.String(actual, repr.OmitEmpty(true))), msgAndArgs...) - } -} - -// containsElement try loop over the list check if the list includes the element. -// return (false, false) if impossible. -// return (true, false) if element was not found. -// return (true, true) if element was found. -func includeElement(list interface{}, element interface{}) (ok, found bool) { - - listValue := reflect.ValueOf(list) - elementValue := reflect.ValueOf(element) - defer func() { - if e := recover(); e != nil { - ok = false - found = false - } - }() - - if reflect.TypeOf(list).Kind() == reflect.String { - return true, strings.Contains(listValue.String(), elementValue.String()) - } - - for i := 0; i < listValue.Len(); i++ { - if ObjectsAreEqual(listValue.Index(i).Interface(), element) { - return true, true - } - } - return true, false - -} - -// Contains asserts that the specified string or list(array, slice...) contains the -// specified substring or element. -// -// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") -// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// -// Returns whether the assertion was successful (true) or not (false). -func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) { - - ok, found := includeElement(s, contains) - if !ok { - Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if !found { - Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) - } -} - -// NotContains asserts that the specified string or list(array, slice...) does NOT contain the -// specified substring or element. -// -// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) { - - ok, found := includeElement(s, contains) - if !ok { - Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if found { - Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) - } -} - -// Condition uses a Comparison to assert a complex condition. -func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) { - result := comp() - if !result { - Fail(t, "Condition failed!", msgAndArgs...) - } -} - -// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics -// methods, and represents a simple func that takes no arguments, and returns nothing. -type PanicTestFunc func() - -// didPanic returns true if the function passed to it panics. Otherwise, it returns false. -func didPanic(f PanicTestFunc) (bool, interface{}) { - - didPanic := false - var message interface{} - func() { - - defer func() { - if message = recover(); message != nil { - didPanic = true - } - }() - - // call the target function - f() - - }() - - return didPanic, message - -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(t, func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) { - - if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { - Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) - } -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(t, func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) { - - if funcDidPanic, panicValue := didPanic(f); funcDidPanic { - Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) - } -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { - - dt := expected.Sub(actual) - if dt < -delta || dt > delta { - Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } -} - -func toFloat(x interface{}) (float64, bool) { - var xf float64 - xok := true - - switch xn := x.(type) { - case uint8: - xf = float64(xn) - case uint16: - xf = float64(xn) - case uint32: - xf = float64(xn) - case uint64: - xf = float64(xn) - case int: - xf = float64(xn) - case int8: - xf = float64(xn) - case int16: - xf = float64(xn) - case int32: - xf = float64(xn) - case int64: - xf = float64(xn) - case float32: - xf = float64(xn) - case float64: - xf = float64(xn) - default: - xok = false - } - - return xf, xok -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) { - - af, aok := toFloat(expected) - bf, bok := toFloat(actual) - - if !aok || !bok { - Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) - } - - if math.IsNaN(af) { - Fail(t, fmt.Sprintf("Actual must not be NaN"), msgAndArgs...) - } - - if math.IsNaN(bf) { - Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) - } - - dt := af - bf - if dt < -delta || dt > delta { - Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta) - } -} - -// min(|expected|, |actual|) * epsilon -func calcEpsilonDelta(expected, actual interface{}, epsilon float64) float64 { - af, aok := toFloat(expected) - bf, bok := toFloat(actual) - - if !aok || !bok { - // invalid input - return 0 - } - - if af < 0 { - af = -af - } - if bf < 0 { - bf = -bf - } - var delta float64 - if af < bf { - delta = af * epsilon - } else { - delta = bf * epsilon - } - return delta -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - delta := calcEpsilonDelta(expected, actual, epsilon) - InDelta(t, expected, actual, delta, msgAndArgs...) -} - -// InEpsilonSlice is the same as InEpsilon, except it compares two slices. -func InEpsilonSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta) - } -} - -/* - Errors -*/ - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// assert.NoError(t, err) -// assert.Equal(t, actualObj, expectedObj) -// -// Returns whether the assertion was successful (true) or not (false). -func NoError(t TestingT, err error, msgAndArgs ...interface{}) { - if isNil(err) { - return - } - - Fail(t, fmt.Sprintf("No error is expected but got %v", err), msgAndArgs...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// assert.Error(t, err, "An error was expected") -// assert.Equal(t, err, expectedError) -// -// Returns whether the assertion was successful (true) or not (false). -func Error(t TestingT, err error, msgAndArgs ...interface{}) { - message := messageFromMsgAndArgs(msgAndArgs...) - NotNil(t, err, "An error is expected but got nil. %s", message) -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// assert.Error(t, err, "An error was expected") -// assert.Equal(t, err, expectedError) -// -// Returns whether the assertion was successful (true) or not (false). -func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { - message := messageFromMsgAndArgs(msgAndArgs...) - NotNil(t, theError, "An error is expected but got nil. %s", message) - s := "An error with value \"%s\" is expected but got \"%s\". %s" - Equal(t, errString, theError.Error(), s, errString, theError.Error(), message) -} - -// matchRegexp return true if a specified regexp matches a string. -func matchRegexp(rx interface{}, str interface{}) bool { - - var r *regexp.Regexp - if rr, ok := rx.(*regexp.Regexp); ok { - r = rr - } else { - r = regexp.MustCompile(fmt.Sprint(rx)) - } - - return (r.FindStringIndex(fmt.Sprint(str)) != nil) - -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { - match := matchRegexp(rx, str) - if !match { - Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) - } -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { - match := matchRegexp(rx, str) - if match { - Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) - } -} - -// Zero asserts that i is the zero value for its type and returns the truth. -func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { - if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) - } -} - -// NotZero asserts that i is not the zero value for its type and returns the truth. -func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { - if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) - } -} diff --git a/vendor/github.com/alecthomas/assert/diff.go b/vendor/github.com/alecthomas/assert/diff.go deleted file mode 100644 index 10a24537..00000000 --- a/vendor/github.com/alecthomas/assert/diff.go +++ /dev/null @@ -1,56 +0,0 @@ -package assert - -import ( - "bytes" - "fmt" - - "github.com/alecthomas/colour" - "github.com/alecthomas/repr" - "github.com/sergi/go-diff/diffmatchpatch" -) - -func DiffValues(a, b interface{}) string { - printer := colour.String() - diff := diffmatchpatch.New() - at := repr.String(a, repr.OmitEmpty(true)) - bt := repr.String(b, repr.OmitEmpty(true)) - diffs := diff.DiffMain(at, bt, true) - for _, d := range diffs { - switch d.Type { - case diffmatchpatch.DiffEqual: - if len(d.Text) <= 40 { - printer.Print(d.Text) - } else { - printer.Printf("%s^B...^R%s", d.Text[:15], d.Text[len(d.Text)-15:]) - } - case diffmatchpatch.DiffDelete: - printer.Printf("^9%s^R", d.Text) - case diffmatchpatch.DiffInsert: - printer.Printf("^a%s^R", d.Text) - } - } - return printer.String() -} - -func DiffValuesDefault(a, b interface{}) string { - diff := diffmatchpatch.New() - at := repr.String(a) - bt := repr.String(b) - diffs := diff.DiffMain(at, bt, true) - w := bytes.NewBuffer(nil) - for _, d := range diffs { - switch d.Type { - case diffmatchpatch.DiffEqual: - if len(d.Text) <= 40 { - w.WriteString(d.Text) - } else { - fmt.Fprintf(w, "%s...%s", d.Text[:15], d.Text[len(d.Text)-15:]) - } - case diffmatchpatch.DiffDelete: - fmt.Fprintf(w, "-{{%s}}", d.Text) - case diffmatchpatch.DiffInsert: - fmt.Fprintf(w, "+{{%s}}", d.Text) - } - } - return w.String() -} diff --git a/vendor/github.com/alecthomas/assert/doc.go b/vendor/github.com/alecthomas/assert/doc.go deleted file mode 100644 index c9dccc4d..00000000 --- a/vendor/github.com/alecthomas/assert/doc.go +++ /dev/null @@ -1,45 +0,0 @@ -// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. -// -// Example Usage -// -// The following is a complete example using assert in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(t, a, b, "The two words should be the same.") -// -// } -// -// if you assert many times, use the format below: -// -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// assert := assert.New(t) -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(a, b, "The two words should be the same.") -// } -// -// Assertions -// -// Assertions allow you to easily write test code, and are global funcs in the `assert` package. -// All assertion functions take, as the first argument, the `*testing.T` object provided by the -// testing framework. This allows the assertion funcs to write the failings and other details to -// the correct place. -// -// Every assertion function also takes an optional string message as the final argument, -// allowing custom error messages to be appended to the message the assertion method outputs. -package assert diff --git a/vendor/github.com/alecthomas/assert/errors.go b/vendor/github.com/alecthomas/assert/errors.go deleted file mode 100644 index ac9dc9d1..00000000 --- a/vendor/github.com/alecthomas/assert/errors.go +++ /dev/null @@ -1,10 +0,0 @@ -package assert - -import ( - "errors" -) - -// AnError is an error instance useful for testing. If the code does not care -// about error specifics, and only needs to return the error for example, this -// error should be used to make the test code more readable. -var AnError = errors.New("assert.AnError general error for testing") diff --git a/vendor/github.com/alecthomas/assert/forward_assertions.go b/vendor/github.com/alecthomas/assert/forward_assertions.go deleted file mode 100644 index d862511d..00000000 --- a/vendor/github.com/alecthomas/assert/forward_assertions.go +++ /dev/null @@ -1,275 +0,0 @@ -package assert - -import "time" - -// Assertions provides assertion methods around the -// TestingT interface. -type Assertions struct { - t TestingT -} - -// New makes a new Assertions object for the specified TestingT. -func New(t TestingT) *Assertions { - return &Assertions{ - t: t, - } -} - -// Fail reports a failure through -func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { - Fail(a.t, failureMessage, msgAndArgs...) -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements((*MyInterface)(nil), new(MyObject), "MyObject") -func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { - Implements(a.t, interfaceObject, object, msgAndArgs...) -} - -// IsType asserts that the specified objects are of the same type. -func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { - IsType(a.t, expectedType, object, msgAndArgs...) -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Equal(expected, actual interface{}, msgAndArgs ...interface{}) { - Equal(a.t, expected, actual, msgAndArgs...) -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualValues(expected, actual interface{}, msgAndArgs ...interface{}) { - EqualValues(a.t, expected, actual, msgAndArgs...) -} - -// Exactly asserts that two objects are equal is value and type. -// -// assert.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Exactly(expected, actual interface{}, msgAndArgs ...interface{}) { - Exactly(a.t, expected, actual, msgAndArgs...) -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { - NotNil(a.t, object, msgAndArgs...) -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { - Nil(a.t, object, msgAndArgs...) -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or a -// slice with len == 0. -// -// assert.Empty(obj) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { - Empty(a.t, object, msgAndArgs...) -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or a -// slice with len == 0. -// -// if assert.NotEmpty(obj) { -// assert.Equal("two", obj[1]) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { - NotEmpty(a.t, object, msgAndArgs...) -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { - Len(a.t, object, length, msgAndArgs...) -} - -// True asserts that the specified value is true. -// -// assert.True(myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { - True(a.t, value, msgAndArgs...) -} - -// False asserts that the specified value is true. -// -// assert.False(myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { - False(a.t, value, msgAndArgs...) -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotEqual(expected, actual interface{}, msgAndArgs ...interface{}) { - NotEqual(a.t, expected, actual, msgAndArgs...) -} - -// Contains asserts that the specified string contains the specified substring. -// -// assert.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Contains(s, contains interface{}, msgAndArgs ...interface{}) { - Contains(a.t, s, contains, msgAndArgs...) -} - -// NotContains asserts that the specified string does NOT contain the specified substring. -// -// assert.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotContains(s, contains interface{}, msgAndArgs ...interface{}) { - NotContains(a.t, s, contains, msgAndArgs...) -} - -// Condition uses a Comparison to assert a complex condition. -func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) { - Condition(a.t, comp, msgAndArgs...) -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) { - Panics(a.t, f, msgAndArgs...) -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) { - NotPanics(a.t, f, msgAndArgs...) -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) WithinDuration(expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { - WithinDuration(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InDelta(expected, actual interface{}, delta float64, msgAndArgs ...interface{}) { - InDelta(a.t, expected, actual, delta, msgAndArgs...) -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InEpsilon(expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(err) { -// assert.Equal(actualObj, expectedObj) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NoError(theError error, msgAndArgs ...interface{}) { - NoError(a.t, theError, msgAndArgs...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(err, "An error was expected") { -// assert.Equal(err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Error(theError error, msgAndArgs ...interface{}) { - Error(a.t, theError, msgAndArgs...) -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// if assert.Error(err, "An error was expected") { -// assert.Equal(err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { - EqualError(a.t, theError, errString, msgAndArgs...) -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { - Regexp(a.t, rx, str, msgAndArgs...) -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { - NotRegexp(a.t, rx, str, msgAndArgs...) -} - -// Zero asserts that i is the zero value for its type and returns the truth. -func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) { - Zero(a.t, i, msgAndArgs...) -} - -// NotZero asserts that i is not the zero value for its type and returns the truth. -func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) { - NotZero(a.t, i, msgAndArgs...) -} diff --git a/vendor/github.com/alecthomas/assert/http_assertions.go b/vendor/github.com/alecthomas/assert/http_assertions.go deleted file mode 100644 index 437a86ce..00000000 --- a/vendor/github.com/alecthomas/assert/http_assertions.go +++ /dev/null @@ -1,157 +0,0 @@ -package assert - -import ( - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "strings" -) - -// httpCode is a helper that returns HTTP code of the response. It returns -1 -// if building a new request fails. -func httpCode(handler http.HandlerFunc, method, url string, values url.Values) int { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) - if err != nil { - return -1 - } - handler(w, req) - return w.Code -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusOK && code <= http.StatusPartialContent -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusBadRequest -} - -// HTTPBody is a helper that returns HTTP body of the response. It returns -// empty string if building a new request fails. -func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) - if err != nil { - return "" - } - handler(w, req) - return w.Body.String() -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if !contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) - } - - return contains -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if contains { - Fail(t, "Expected response body for %s to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body) - } - - return !contains -} - -// -// Assertions Wrappers -// - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method, url string, values url.Values) bool { - return HTTPSuccess(a.t, handler, method, url, values) -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method, url string, values url.Values) bool { - return HTTPRedirect(a.t, handler, method, url, values) -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPError(handler http.HandlerFunc, method, url string, values url.Values) bool { - return HTTPError(a.t, handler, method, url, values) -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - return HTTPBodyContains(a.t, handler, method, url, values, str) -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - return HTTPBodyNotContains(a.t, handler, method, url, values, str) -} diff --git a/vendor/github.com/alecthomas/colour/.travis.yml b/vendor/github.com/alecthomas/colour/.travis.yml deleted file mode 100644 index e564b743..00000000 --- a/vendor/github.com/alecthomas/colour/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -sudo: false -language: go -install: go get -t -v ./... -go: 1.2 diff --git a/vendor/github.com/alecthomas/colour/COPYING b/vendor/github.com/alecthomas/colour/COPYING deleted file mode 100644 index e477b078..00000000 --- a/vendor/github.com/alecthomas/colour/COPYING +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Alec Thomas - -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/github.com/alecthomas/colour/README.md b/vendor/github.com/alecthomas/colour/README.md deleted file mode 100644 index d24690b4..00000000 --- a/vendor/github.com/alecthomas/colour/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# Colour terminal text for Go (Golang) [![](https://godoc.org/github.com/alecthomas/colour?status.svg)](http://godoc.org/github.com/alecthomas/colour) [![Build Status](https://travis-ci.org/alecthomas/colour.png)](https://travis-ci.org/alecthomas/colour) - -Package colour provides [Quake-style colour formatting][2] for Unix terminals. - -The package level functions can be used to write to stdout (or strings or -other files). If stdout is not a terminal, colour formatting will be -stripped. - -eg. - - colour.Printf("^0black ^1red ^2green ^3yellow ^4blue ^5magenta ^6cyan ^7white^R\n") - - -For more control a Printer object can be created with various helper -functions. This can be used to do useful things such as strip formatting, -write to strings, and so on. - -The following sequences are converted to their equivalent ANSI colours: - -| Sequence | Effect | -| -------- | ------ | -| ^0 | Black | -| ^1 | Red | -| ^2 | Green | -| ^3 | Yellow | -| ^4 | Blue | -| ^5 | Cyan (light blue) | -| ^6 | Magenta (purple) | -| ^7 | White | -| ^8 | Black Background | -| ^9 | Red Background | -| ^a | Green Background | -| ^b | Yellow Background | -| ^c | Blue Background | -| ^d | Cyan (light blue) Background | -| ^e | Magenta (purple) Background | -| ^f | White Background | -| ^R | Reset | -| ^U | Underline | -| ^D | Dim | -| ^B | Bold | -| ^S | Strikethrough | - -[1]: http://godoc.org/github.com/alecthomas/colour -[2]: http://www.holysh1t.net/quake-live-colors-nickname/ diff --git a/vendor/github.com/alecthomas/colour/colour.go b/vendor/github.com/alecthomas/colour/colour.go deleted file mode 100644 index 9b823705..00000000 --- a/vendor/github.com/alecthomas/colour/colour.go +++ /dev/null @@ -1,259 +0,0 @@ -// Package colour ([docs][1]) provides [Quake-style colour formatting][2] for Unix terminals. -// -// It is a drop-in replacement for the fmt package. -// -// The package level functions can be used to write to stdout (or strings or -// other files). If stdout is not a terminal, colour formatting will be -// stripped. -// -// eg. -// -// colour.Printf("^0black ^1red ^2green ^3yellow ^4blue ^5magenta ^6cyan ^7white^R\n") -// -// -// For more control a Printer object can be created with various helper -// functions. This can be used to do useful things such as strip formatting, -// write to strings, and so on. -// -// The following sequences are converted to their equivalent ANSI colours: -// -// ^0 = Black -// ^1 = Red -// ^2 = Green -// ^3 = Yellow -// ^4 = Blue -// ^5 = Cyan (light blue) -// ^6 = Magenta (purple) -// ^7 = White -// ^8 = Black Background -// ^9 = Red Background -// ^a = Green Background -// ^b = Yellow Background -// ^c = Blue Background -// ^d = Cyan (light blue) Background -// ^e = Magenta (purple) Background -// ^f = White Background -// ^R = Reset -// ^U = Underline -// ^B = Bold -// ^S = Strikethrough -// -// [1]: http://godoc.org/github.com/alecthomas/colour -// [2]: http://www.holysh1t.net/quake-live-colors-nickname/ -package colour - -import ( - "bytes" - "fmt" - "io" - "os" - "regexp" - - "github.com/mattn/go-isatty" -) - -var ( - extract = regexp.MustCompile(`(\^[0-9a-fRDUBS])|(\^\^)|([^^]+)`) - colours = map[byte]string{ - '0': "\033[30m", - '1': "\033[31m", - '2': "\033[32m", - '3': "\033[33m", - '4': "\033[34m", - '5': "\033[35m", - '6': "\033[36m", - '7': "\033[37m", - - '8': "\033[40m", - '9': "\033[41m", - 'a': "\033[42m", - 'b': "\033[43m", - 'c': "\033[44m", - 'd': "\033[45m", - 'e': "\033[46m", - 'f': "\033[47m", - - 'R': "\033[0m", // reset - 'B': "\033[1m", // bold - 'D': "\033[2m", // dim - 'U': "\033[4m", // underline - 'S': "\033[9m", // strikethrough - } - - // Stdout is an conditional colour writer for os.Stdout. - Stdout = TTY(os.Stdout) - // Stderr is an conditional colour writer for os.Stderr. - Stderr = TTY(os.Stderr) -) - -func Println(args ...interface{}) (n int, err error) { - return Stdout.Println(args...) -} - -func Sprintln(args ...interface{}) string { - s := String() - _, _ = s.Println(args...) - return s.String() -} - -func Fprintln(w io.Writer, args ...interface{}) (n int, err error) { - return TTY(w).Println(args...) -} - -func Print(args ...interface{}) (n int, err error) { - return Stdout.Print(args...) -} - -func Sprint(args ...interface{}) string { - s := String() - _, _ = s.Print(args...) - return s.String() -} - -func Fprint(w io.Writer, args ...interface{}) (n int, err error) { - return TTY(w).Print(args...) -} - -func Printf(format string, args ...interface{}) (n int, err error) { - return Stdout.Printf(format, args...) -} - -func Sprintf(format string, args ...interface{}) string { - s := String() - _, _ = s.Printf(format, args...) - return s.String() -} - -func Fprintf(w io.Writer, format string, args ...interface{}) (n int, err error) { - return TTY(w).Printf(format, args...) -} - -// A Printer implements functions that accept Quake-style colour formatting -// and print coloured text. -type Printer interface { - Println(args ...interface{}) (n int, err error) - Print(args ...interface{}) (n int, err error) - Printf(format string, args ...interface{}) (n int, err error) -} - -// TTY creates a Printer that colourises output if w is a terminal, or strips -// formatting if it is not. -func TTY(w io.Writer) Printer { - if f, ok := w.(*os.File); ok && isatty.IsTerminal(f.Fd()) { - return &colourPrinter{w} - } - return &stripPrinter{w} -} - -// Colour creats a new ANSI colour Printer on w. -func Colour(w io.Writer) Printer { - return &colourPrinter{w} -} - -// Strip returns a Printer that strips all colour codes from printed strings before writing to w. -func Strip(w io.Writer) Printer { - return &stripPrinter{w} -} - -type StringPrinter struct { - Printer - w *bytes.Buffer -} - -// String creates a new Printer that writes ANSI coloured text to a buffer. -// Use the String() method to return the printed string. -func String() *StringPrinter { - w := &bytes.Buffer{} - f := Colour(w) - return &StringPrinter{f, w} -} - -// StringStripper writes text stripped of colour formatting codes to a string. -// Use the String() method to return the printed string. -func StringStripper() *StringPrinter { - w := &bytes.Buffer{} - f := Strip(w) - return &StringPrinter{f, w} -} - -func (s *StringPrinter) String() string { - return s.w.String() -} - -type colourPrinter struct { - w io.Writer -} - -func (c *colourPrinter) Println(args ...interface{}) (n int, err error) { - for i, arg := range args { - if s, ok := arg.(string); ok { - args[i] = FormatString(s) - } - } - return fmt.Fprintln(c.w, args...) -} - -func (c *colourPrinter) Print(args ...interface{}) (n int, err error) { - for i, arg := range args { - if s, ok := arg.(string); ok { - args[i] = FormatString(s) - } - } - return fmt.Fprint(c.w, args...) -} - -func (c *colourPrinter) Printf(format string, args ...interface{}) (n int, err error) { - return fmt.Fprintf(c.w, FormatString(format), args...) -} - -type stripPrinter struct { - w io.Writer -} - -func (p *stripPrinter) Println(args ...interface{}) (n int, err error) { - return fmt.Fprintln(p.w, stripArgs(args...)...) -} - -func (p *stripPrinter) Print(args ...interface{}) (n int, err error) { - return fmt.Fprint(p.w, stripArgs(args...)...) -} - -func (p *stripPrinter) Printf(format string, args ...interface{}) (n int, err error) { - return fmt.Fprintf(p.w, StripFormatting(format), args...) -} - -func FormatString(s string) string { - out := &bytes.Buffer{} - for _, match := range extract.FindAllStringSubmatch(s, -1) { - if match[1] != "" { - n := match[1][1] - out.WriteString(colours[n]) - } else if match[2] != "" { - out.WriteString("^") - } else { - out.WriteString(match[3]) - } - } - return out.String() -} - -func StripFormatting(s string) string { - out := &bytes.Buffer{} - for _, match := range extract.FindAllStringSubmatch(s, -1) { - if match[2] != "" { - out.WriteString("^") - } else if match[1] == "" { - out.WriteString(match[3]) - } - } - return out.String() -} - -func stripArgs(args ...interface{}) []interface{} { - for i, arg := range args { - if s, ok := arg.(string); ok { - args[i] = StripFormatting(s) - } - } - return args -} diff --git a/vendor/github.com/alecthomas/kong/.gitignore b/vendor/github.com/alecthomas/kong/.gitignore deleted file mode 100644 index ba077a40..00000000 --- a/vendor/github.com/alecthomas/kong/.gitignore +++ /dev/null @@ -1 +0,0 @@ -bin diff --git a/vendor/github.com/alecthomas/kong/.golangci.yml b/vendor/github.com/alecthomas/kong/.golangci.yml deleted file mode 100644 index af552572..00000000 --- a/vendor/github.com/alecthomas/kong/.golangci.yml +++ /dev/null @@ -1,42 +0,0 @@ -run: - tests: true - -output: - print-issued-lines: false - -linters: - enable-all: true - disable: - - maligned - - lll - - gochecknoglobals - - wsl - - funlen - - gocognit - - gomnd - - goprintffuncname - -linters-settings: - govet: - check-shadowing: true - dupl: - threshold: 100 - goconst: - min-len: 5 - min-occurrences: 3 - gocyclo: - min-complexity: 20 - -issues: - max-per-linter: 0 - max-same: 0 - exclude-use-default: false - exclude: - - '^(G104|G204):' - # Very commonly not checked. - - 'Error return value of .(.*\.Help|.*\.MarkFlagRequired|(os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*printf?|os\.(Un)?Setenv). is not checked' - - 'exported method (.*\.MarshalJSON|.*\.UnmarshalJSON) should have comment or be unexported' - - 'composite literal uses unkeyed fields' - - 'bad syntax for struct tag key' - - 'bad syntax for struct tag pair' - - 'result .* \(error\) is always nil' diff --git a/vendor/github.com/alecthomas/kong/COPYING b/vendor/github.com/alecthomas/kong/COPYING deleted file mode 100644 index 22707acf..00000000 --- a/vendor/github.com/alecthomas/kong/COPYING +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2018 Alec Thomas - -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/github.com/alecthomas/kong/README.md b/vendor/github.com/alecthomas/kong/README.md deleted file mode 100644 index f0b7a30b..00000000 --- a/vendor/github.com/alecthomas/kong/README.md +++ /dev/null @@ -1,600 +0,0 @@ - -

- -# Kong is a command-line parser for Go -[![](https://godoc.org/github.com/alecthomas/kong?status.svg)](http://godoc.org/github.com/alecthomas/kong) [![CircleCI](https://img.shields.io/circleci/project/github/alecthomas/kong.svg)](https://circleci.com/gh/alecthomas/kong) [![Go Report Card](https://goreportcard.com/badge/github.com/alecthomas/kong)](https://goreportcard.com/report/github.com/alecthomas/kong) [![Slack chat](https://img.shields.io/static/v1?logo=slack&style=flat&label=slack&color=green&message=gophers)](https://gophers.slack.com/messages/CN9DS8YF3) - - - -- [Introduction](#introduction) -- [Help](#help) - - [Help as a user of a Kong application](#help-as-a-user-of-a-kong-application) - - [Defining help in Kong](#defining-help-in-kong) -- [Command handling](#command-handling) - - [Switch on the command string](#switch-on-the-command-string) - - [Attach a Run... error method to each command](#attach-a-run-error-method-to-each-command) -- [Hooks: BeforeResolve, BeforeApply, AfterApply and the Bind option](#hooks-beforeresolve-beforeapply-afterapply-and-the-bind-option) -- [Flags](#flags) -- [Commands and sub-commands](#commands-and-sub-commands) -- [Branching positional arguments](#branching-positional-arguments) -- [Terminating positional arguments](#terminating-positional-arguments) -- [Slices](#slices) -- [Maps](#maps) -- [Custom named decoders](#custom-named-decoders) -- [Supported field types](#supported-field-types) -- [Custom decoders mappers](#custom-decoders-mappers) -- [Supported tags](#supported-tags) -- [Plugins](#plugins) -- [Variable interpolation](#variable-interpolation) -- [Validation](#validation) -- [Modifying Kong's behaviour](#modifying-kongs-behaviour) - - [Namehelp and Descriptionhelp - set the application name description](#namehelp-and-descriptionhelp---set-the-application-name-description) - - [Configurationloader, paths... - load defaults from configuration files](#configurationloader-paths---load-defaults-from-configuration-files) - - [Resolver... - support for default values from external sources](#resolver---support-for-default-values-from-external-sources) - - [*Mapper... - customising how the command-line is mapped to Go values](#mapper---customising-how-the-command-line-is-mapped-to-go-values) - - [ConfigureHelpHelpOptions and HelpHelpFunc - customising help](#configurehelphelpoptions-and-helphelpfunc---customising-help) - - [Bind... - bind values for callback hooks and Run methods](#bind---bind-values-for-callback-hooks-and-run-methods) - - [Other options](#other-options) - - - -## Introduction - -Kong aims to support arbitrarily complex command-line structures with as little developer effort as possible. - -To achieve that, command-lines are expressed as Go types, with the structure and tags directing how the command line is mapped onto the struct. - -For example, the following command-line: - - shell rm [-f] [-r] ... - shell ls [ ...] - -Can be represented by the following command-line structure: - -```go -package main - -import "github.com/alecthomas/kong" - -var CLI struct { - Rm struct { - Force bool `help:"Force removal."` - Recursive bool `help:"Recursively remove files."` - - Paths []string `arg name:"path" help:"Paths to remove." type:"path"` - } `cmd help:"Remove files."` - - Ls struct { - Paths []string `arg optional name:"path" help:"Paths to list." type:"path"` - } `cmd help:"List paths."` -} - -func main() { - ctx := kong.Parse(&CLI) - switch ctx.Command() { - case "rm ": - case "ls": - default: - panic(ctx.Command()) - } -} -``` - -## Help - -### Help as a user of a Kong application - -Every Kong application includes a `--help` flag that will display auto-generated help. - -eg. - - $ shell --help - usage: shell - - A shell-like example app. - - Flags: - --help Show context-sensitive help. - --debug Debug mode. - - Commands: - rm ... - Remove files. - - ls [ ...] - List paths. - -If a command is provided, the help will show full detail on the command including all available flags. - -eg. - - $ shell --help rm - usage: shell rm ... - - Remove files. - - Arguments: - ... Paths to remove. - - Flags: - --debug Debug mode. - - -f, --force Force removal. - -r, --recursive Recursively remove files. - -### Defining help in Kong - -Help is automatically generated from the command-line structure itself, -including `help:""` and other tags. [Variables](#variable-interpolation) will -also be interpolated into the help string. - -Finally, any command, argument, or flag type implementing the interface -`Help() string` will have this function called to retrieve the help string. -This allows for much more descriptive text than can fit in Go tags. - -## Command handling - -There are two ways to handle commands in Kong. - -### Switch on the command string - -When you call `kong.Parse()` it will return a unique string representation of the command. Each command branch in the hierarchy will be a bare word and each branching argument or required positional argument will be the name surrounded by angle brackets. Here's an example: - -There's an example of this pattern [here](https://github.com/alecthomas/kong/blob/master/_examples/shell/main.go). - -eg. - -```go -package main - -import "github.com/alecthomas/kong" - -var CLI struct { - Rm struct { - Force bool `help:"Force removal."` - Recursive bool `help:"Recursively remove files."` - - Paths []string `arg name:"path" help:"Paths to remove." type:"path"` - } `cmd help:"Remove files."` - - Ls struct { - Paths []string `arg optional name:"path" help:"Paths to list." type:"path"` - } `cmd help:"List paths."` -} - -func main() { - ctx := kong.Parse(&CLI) - switch ctx.Command() { - case "rm ": - case "ls": - default: - panic(ctx.Command()) - } -} -``` - -This has the advantage that it is convenient, but the downside that if you modify your CLI structure, the strings may change. This can be fragile. - -### Attach a `Run(...) error` method to each command - -A more robust approach is to break each command out into their own structs: - -1. Break leaf commands out into separate structs. -2. Attach a `Run(...) error` method to all leaf commands. -3. Call `kong.Kong.Parse()` to obtain a `kong.Context`. -4. Call `kong.Context.Run(bindings...)` to call the selected parsed command. - -Once a command node is selected by Kong it will search from that node back to the root. Each -encountered command node with a `Run(...) error` will be called in reverse order. This allows -sub-trees to be re-used fairly conveniently. - -In addition to values bound with the `kong.Bind(...)` option, any values -passed through to `kong.Context.Run(...)` are also bindable to the target's -`Run()` arguments. - -Finally, hooks can also contribute bindings via `kong.Context.Bind()` and `kong.Context.BindTo()`. - -There's a full example emulating part of the Docker CLI [here](https://github.com/alecthomas/kong/tree/master/_examples/docker). - -eg. - -```go -type Context struct { - Debug bool -} - -type RmCmd struct { - Force bool `help:"Force removal."` - Recursive bool `help:"Recursively remove files."` - - Paths []string `arg name:"path" help:"Paths to remove." type:"path"` -} - -func (r *RmCmd) Run(ctx *Context) error { - fmt.Println("rm", r.Paths) - return nil -} - -type LsCmd struct { - Paths []string `arg optional name:"path" help:"Paths to list." type:"path"` -} - -func (l *LsCmd) Run(ctx *Context) error { - fmt.Println("ls", l.Paths) - return nil -} - -var cli struct { - Debug bool `help:"Enable debug mode."` - - Rm RmCmd `cmd help:"Remove files."` - Ls LsCmd `cmd help:"List paths."` -} - -func main() { - ctx := kong.Parse(&cli) - // Call the Run() method of the selected parsed command. - err := ctx.Run(&Context{Debug: cli.Debug}) - ctx.FatalIfErrorf(err) -} - -``` - -## Hooks: BeforeResolve(), BeforeApply(), AfterApply() and the Bind() option - -If a node in the grammar has a `BeforeResolve(...)`, `BeforeApply(...) error` and/or `AfterApply(...) error` method, those methods will be called before validation/assignment and after validation/assignment, respectively. - -The `--help` flag is implemented with a `BeforeApply` hook. - -Arguments to hooks are provided via the `Run(...)` method or `Bind(...)` option. `*Kong`, `*Context` and `*Path` are also bound and finally, hooks can also contribute bindings via `kong.Context.Bind()` and `kong.Context.BindTo()`. - -eg. - -```go -// A flag with a hook that, if triggered, will set the debug loggers output to stdout. -type debugFlag bool - -func (d debugFlag) BeforeApply(logger *log.Logger) error { - logger.SetOutput(os.Stdout) - return nil -} - -var cli struct { - Debug debugFlag `help:"Enable debug logging."` -} - -func main() { - // Debug logger going to discard. - logger := log.New(ioutil.Discard, "", log.LstdFlags) - - ctx := kong.Parse(&cli, kong.Bind(logger)) - - // ... -} -``` - -## Flags - -Any [mapped](#mapper---customising-how-the-command-line-is-mapped-to-go-values) field in the command structure *not* tagged with `cmd` or `arg` will be a flag. Flags are optional by default. - -eg. The command-line `app [--flag="foo"]` can be represented by the following. - -```go -type CLI struct { - Flag string -} -``` - -## Commands and sub-commands - -Sub-commands are specified by tagging a struct field with `cmd`. Kong supports arbitrarily nested commands. - -eg. The following struct represents the CLI structure `command [--flag="str"] sub-command`. - -```go -type CLI struct { - Command struct { - Flag string - - SubCommand struct { - } `cmd` - } `cmd` -} -``` - -If a sub-command is tagged with `default:"1"` it will be selected if there are no further arguments. - -## Branching positional arguments - -In addition to sub-commands, structs can also be configured as branching positional arguments. - -This is achieved by tagging an [unmapped](#mapper---customising-how-the-command-line-is-mapped-to-go-values) nested struct field with `arg`, then including a positional argument field inside that struct _with the same name_. For example, the following command structure: - - app rename to - -Can be represented with the following: - -```go -var CLI struct { - Rename struct { - Name struct { - Name string `arg` // <-- NOTE: identical name to enclosing struct field. - To struct { - Name struct { - Name string `arg` - } `arg` - } `cmd` - } `arg` - } `cmd` -} -``` - -This looks a little verbose in this contrived example, but typically this will not be the case. - -## Terminating positional arguments - -If a [mapped type](#mapper---customising-how-the-command-line-is-mapped-to-go-values) is tagged with `arg` it will be treated as the final positional values to be parsed on the command line. - -If a positional argument is a slice, all remaining arguments will be appended to that slice. - -## Slices - -Slice values are treated specially. First the input is split on the `sep:""` tag (defaults to `,`), then each element is parsed by the slice element type and appended to the slice. If the same value is encountered multiple times, elements continue to be appended. - -To represent the following command-line: - - cmd ls ... - -You would use the following: - -```go -var CLI struct { - Ls struct { - Files []string `arg type:"existingfile"` - } `cmd` -} -``` - -## Maps - -Maps are similar to slices except that only one key/value pair can be assigned per value, and the `sep` tag denotes the assignment character and defaults to `=`. - -To represent the following command-line: - - cmd config set = = ... - -You would use the following: - -```go -var CLI struct { - Config struct { - Set struct { - Config map[string]float64 `arg type:"file:"` - } `cmd` - } `cmd` -} -``` - -For flags, multiple key+value pairs should be separated by `mapsep:"rune"` tag (defaults to `;`) eg. `--set="key1=value1;key2=value2"`. - -## Custom named decoders - -Kong includes a number of builtin custom type mappers. These can be used by -specifying the tag `type:""`. They are registered with the option -function `NamedMapper(name, mapper)`. - -| Name | Description -|-------------------|--------------------------------------------------- -| `path` | A path. ~ expansion is applied. -| `existingfile` | An existing file. ~ expansion is applied. `-` is accepted for stdin. -| `existingdir` | An existing directory. ~ expansion is applied. -| `counter` | Increment a numeric field. Useful for `-vvv`. Can accept `-s`, `--long` or `--long=N`. - - -Slices and maps treat type tags specially. For slices, the `type:""` tag -specifies the element type. For maps, the tag has the format -`tag:"[]:[]"` where either may be omitted. - -## Supported field types - - -## Custom decoders (mappers) - - -Any field implementing `encoding.TextUnmarshaler` or `json.Unmarshaler` will use those interfaces -for decoding values. Kong also includes builtin support for many common Go types: - -| Type | Description -|---------------------|-------------------------------------------- -| `time.Duration` | Populated using `time.ParseDuration()`. -| `time.Time` | Populated using `time.Parse()`. Format defaults to RFC3339 but can be overridden with the `format:"X"` tag. -| `*os.File` | Path to a file that will be opened, or `-` for `os.Stdin`. File must be closed by the user. -| `*url.URL` | Populated with `url.Parse()`. - -For more fine-grained control, if a field implements the -[MapperValue](https://godoc.org/github.com/alecthomas/kong#MapperValue) -interface it will be used to decode arguments into the field. - -## Supported tags - -Tags can be in two forms: - -1. Standard Go syntax, eg. `kong:"required,name='foo'"`. -2. Bare tags, eg. `required name:"foo"` - -Both can coexist with standard Tag parsing. - -Tag | Description ------------------------| ------------------------------------------- -`cmd` | If present, struct is a command. -`arg` | If present, field is an argument. -`env:"X"` | Specify envar to use for default value. -`name:"X"` | Long name, for overriding field name. -`help:"X"` | Help text. -`type:"X"` | Specify [named types](#custom-named-decoders) to use. -`placeholder:"X"` | Placeholder text. -`default:"X"` | Default value. -`default:"1"` | On a command, make it the default. -`short:"X"` | Short name, if flag. -`aliases:"X,Y"` | One or more aliases (for cmd). -`required` | If present, flag/arg is required. -`optional` | If present, flag/arg is optional. -`hidden` | If present, command or flag is hidden. -`format:"X"` | Format for parsing input, if supported. -`sep:"X"` | Separator for sequences (defaults to ","). May be `none` to disable splitting. -`mapsep:"X"` | Separator for maps (defaults to ";"). May be `none` to disable splitting. -`enum:"X,Y,..."` | Set of valid values allowed for this flag. -`group:"X"` | Logical group for a flag or command. -`xor:"X"` | Exclusive OR group for flags. Only one flag in the group can be used which is restricted within the same command. -`prefix:"X"` | Prefix for all sub-flags. -`set:"K=V"` | Set a variable for expansion by child elements. Multiples can occur. -`embed` | If present, this field's children will be embedded in the parent. Useful for composition. -`-` | Ignore the field. Useful for adding non-CLI fields to a configuration struct. - -## Plugins - -Kong CLI's can be extended by embedding the `kong.Plugin` type and populating it with pointers to Kong annotated structs. For example: - -```go -var pluginOne struct { - PluginOneFlag string -} -var pluginTwo struct { - PluginTwoFlag string -} -var cli struct { - BaseFlag string - kong.Plugins -} -cli.Plugins = kong.Plugins{&pluginOne, &pluginTwo} -``` - -Additionally if an interface type is embedded, it can also be populated with a Kong annotated struct. - -## Variable interpolation - -Kong supports limited variable interpolation into help strings, enum lists and -default values. - -Variables are in the form: - - ${} - ${=} - -Variables are set with the `Vars{"key": "value", ...}` option. Undefined -variable references in the grammar without a default will result in an error at -construction time. - -Variables can also be set via the `set:"K=V"` tag. In this case, those variables will be available for that -node and all children. This is useful for composition by allowing the same struct to be reused. - -When interpolating into flag or argument help strings, some extra variables -are defined from the value itself: - - ${default} - ${enum} - -For flags with associated environment variables, the variable `${env}` can be -interpolated into the help string. In the absence of this variable in the -help string, Kong will append `($$${env})` to the help string. - -eg. - -```go -type cli struct { - Config string `type:"path" default:"${config_file}"` -} - -func main() { - kong.Parse(&cli, - kong.Vars{ - "config_file": "~/.app.conf", - }) -} -``` - -## Validation - -Kong does validation on the structure of a command-line, but also supports -extensible validation. Any node in the tree may implement the following -interface: - -```go -type Validatable interface { - Validate() error - } - ``` - -+If one of these nodes is in the active command-line it will be called during -+normal validation. - -## Modifying Kong's behaviour - -Each Kong parser can be configured via functional options passed to `New(cli interface{}, options...Option)`. - -The full set of options can be found [here](https://godoc.org/github.com/alecthomas/kong#Option). - -### `Name(help)` and `Description(help)` - set the application name description - -Set the application name and/or description. - -The name of the application will default to the binary name, but can be overridden with `Name(name)`. - -As with all help in Kong, text will be wrapped to the terminal. - -### `Configuration(loader, paths...)` - load defaults from configuration files - -This option provides Kong with support for loading defaults from a set of configuration files. Each file is opened, if possible, and the loader called to create a resolver for that file. - -eg. - -```go -kong.Parse(&cli, kong.Configuration(kong.JSON, "/etc/myapp.json", "~/.myapp.json")) -``` - -[See the tests](https://github.com/alecthomas/kong/blob/master/resolver_test.go#L103) for an example of how the JSON file is structured. - -### `Resolver(...)` - support for default values from external sources - -Resolvers are Kong's extension point for providing default values from external sources. As an example, support for environment variables via the `env` tag is provided by a resolver. There's also a builtin resolver for JSON configuration files. - -Example resolvers can be found in [resolver.go](https://github.com/alecthomas/kong/blob/master/resolver.go). - -### `*Mapper(...)` - customising how the command-line is mapped to Go values - -Command-line arguments are mapped to Go values via the Mapper interface: - -```go -// A Mapper knows how to map command-line input to Go. -type Mapper interface { - // Decode scan into target. - // - // "ctx" contains context about the value being decoded that may be useful - // to some mappers. - Decode(ctx *MapperContext, scan *Scanner, target reflect.Value) error -} -``` - -All builtin Go types (as well as a bunch of useful stdlib types like `time.Time`) have mappers registered by default. Mappers for custom types can be added using `kong.??Mapper(...)` options. Mappers are applied to fields in four ways: - -1. `NamedMapper(string, Mapper)` and using the tag key `type:""`. -2. `KindMapper(reflect.Kind, Mapper)`. -3. `TypeMapper(reflect.Type, Mapper)`. -4. `ValueMapper(interface{}, Mapper)`, passing in a pointer to a field of the grammar. - -### `ConfigureHelp(HelpOptions)` and `Help(HelpFunc)` - customising help - -The default help output is usually sufficient, but if not there are two solutions. - -1. Use `ConfigureHelp(HelpOptions)` to configure how help is formatted (see [HelpOptions](https://godoc.org/github.com/alecthomas/kong#HelpOptions) for details). -2. Custom help can be wired into Kong via the `Help(HelpFunc)` option. The `HelpFunc` is passed a `Context`, which contains the parsed context for the current command-line. See the implementation of `PrintHelp` for an example. -3. Use `HelpFormatter(HelpValueFormatter)` if you want to just customize the help text that is accompanied by flags and arguments. -4. Use `Groups([]Group)` if you want to customize group titles or add a header. - -### `Bind(...)` - bind values for callback hooks and Run() methods - -See the [section on hooks](#hooks-beforeresolve-beforeapply-afterapply-and-the-bind-option) for details. - -### Other options - -The full set of options can be found [here](https://godoc.org/github.com/alecthomas/kong#Option). diff --git a/vendor/github.com/alecthomas/kong/build.go b/vendor/github.com/alecthomas/kong/build.go deleted file mode 100644 index 0e3bc5f7..00000000 --- a/vendor/github.com/alecthomas/kong/build.go +++ /dev/null @@ -1,240 +0,0 @@ -package kong - -import ( - "fmt" - "reflect" - "strings" -) - -// Plugins are dynamically embedded command-line structures. -// -// Each element in the Plugins list *must* be a pointer to a structure. -type Plugins []interface{} - -func build(k *Kong, ast interface{}) (app *Application, err error) { - defer catch(&err) - v := reflect.ValueOf(ast) - iv := reflect.Indirect(v) - if v.Kind() != reflect.Ptr || iv.Kind() != reflect.Struct { - return nil, fmt.Errorf("expected a pointer to a struct but got %T", ast) - } - - app = &Application{} - extraFlags := k.extraFlags() - seenFlags := map[string]bool{} - for _, flag := range extraFlags { - seenFlags[flag.Name] = true - } - node := buildNode(k, iv, ApplicationNode, seenFlags) - if len(node.Positional) > 0 && len(node.Children) > 0 { - return nil, fmt.Errorf("can't mix positional arguments and branching arguments on %T", ast) - } - app.Node = node - app.Node.Flags = append(extraFlags, app.Node.Flags...) - app.Tag = newEmptyTag() - app.Tag.Vars = k.vars - return app, nil -} - -func dashedString(s string) string { - return strings.Join(camelCase(s), "-") -} - -type flattenedField struct { - field reflect.StructField - value reflect.Value - tag *Tag -} - -func flattenedFields(v reflect.Value) (out []flattenedField) { - v = reflect.Indirect(v) - for i := 0; i < v.NumField(); i++ { - ft := v.Type().Field(i) - fv := v.Field(i) - tag := parseTag(fv, ft) - if tag.Ignored { - continue - } - if !ft.Anonymous && !tag.Embed { - if fv.CanSet() { - out = append(out, flattenedField{field: ft, value: fv, tag: tag}) - } - continue - } - - // Embedded type. - if fv.Kind() == reflect.Interface { - fv = fv.Elem() - } else if fv.Type() == reflect.TypeOf(Plugins{}) { - for i := 0; i < fv.Len(); i++ { - out = append(out, flattenedFields(fv.Index(i).Elem())...) - } - continue - } - sub := flattenedFields(fv) - for _, subf := range sub { - // Assign parent if it's not already set. - if subf.tag.Group == "" { - subf.tag.Group = tag.Group - } - // Accumulate prefixes. - subf.tag.Prefix = tag.Prefix + subf.tag.Prefix - // Combine parent vars. - subf.tag.Vars = tag.Vars.CloneWith(subf.tag.Vars) - } - out = append(out, sub...) - } - return out -} - -func buildNode(k *Kong, v reflect.Value, typ NodeType, seenFlags map[string]bool) *Node { - node := &Node{ - Type: typ, - Target: v, - Tag: newEmptyTag(), - } - for _, field := range flattenedFields(v) { - ft := field.field - fv := field.value - - tag := field.tag - name := tag.Name - if name == "" { - name = tag.Prefix + strings.ToLower(dashedString(ft.Name)) - } else { - name = tag.Prefix + name - } - - // Nested structs are either commands or args, unless they implement the Mapper interface. - if ft.Type.Kind() == reflect.Struct && (tag.Cmd || tag.Arg) && k.registry.ForValue(fv) == nil { - typ := CommandNode - if tag.Arg { - typ = ArgumentNode - } - buildChild(k, node, typ, v, ft, fv, tag, name, seenFlags) - } else { - buildField(k, node, v, ft, fv, tag, name, seenFlags) - } - } - - // "Unsee" flags. - for _, flag := range node.Flags { - delete(seenFlags, flag.Name) - } - - // Scan through argument positionals to ensure optional is never before a required. - last := true - for i, p := range node.Positional { - if !last && p.Required { - fail("argument %q can not be required after an optional", p.Name) - } - - last = p.Required - p.Position = i - } - - return node -} - -func buildChild(k *Kong, node *Node, typ NodeType, v reflect.Value, ft reflect.StructField, fv reflect.Value, tag *Tag, name string, seenFlags map[string]bool) { - child := buildNode(k, fv, typ, seenFlags) - child.Tag = tag - child.Parent = node - child.Help = tag.Help - child.Hidden = tag.Hidden - child.Group = buildGroupForKey(k, tag.Group) - child.Aliases = tag.Aliases - - if provider, ok := fv.Addr().Interface().(HelpProvider); ok { - child.Detail = provider.Help() - } - - // A branching argument. This is a bit hairy, as we let buildNode() do the parsing, then check that - // a positional argument is provided to the child, and move it to the branching argument field. - if tag.Arg { - if len(child.Positional) == 0 { - fail("positional branch %s.%s must have at least one child positional argument named %q", - v.Type().Name(), ft.Name, name) - } - - value := child.Positional[0] - child.Positional = child.Positional[1:] - if child.Help == "" { - child.Help = value.Help - } - - child.Name = value.Name - if child.Name != name { - fail("first field in positional branch %s.%s must have the same name as the parent field (%s).", - v.Type().Name(), ft.Name, child.Name) - } - - child.Argument = value - } else { - child.Name = name - } - node.Children = append(node.Children, child) - - if len(child.Positional) > 0 && len(child.Children) > 0 { - fail("can't mix positional arguments and branching arguments on %s.%s", v.Type().Name(), ft.Name) - } -} - -func buildField(k *Kong, node *Node, v reflect.Value, ft reflect.StructField, fv reflect.Value, tag *Tag, name string, seenFlags map[string]bool) { - mapper := k.registry.ForNamedValue(tag.Type, fv) - if mapper == nil { - fail("unsupported field type %s.%s (of type %s), perhaps missing a cmd:\"\" tag?", v.Type(), ft.Name, ft.Type) - } - - value := &Value{ - Name: name, - Help: tag.Help, - Default: tag.Default, - DefaultValue: reflect.New(fv.Type()).Elem(), - Mapper: mapper, - Tag: tag, - Target: fv, - Enum: tag.Enum, - - // Flags are optional by default, and args are required by default. - Required: (!tag.Arg && tag.Required) || (tag.Arg && !tag.Optional), - Format: tag.Format, - } - - if tag.Arg { - node.Positional = append(node.Positional, value) - } else { - if seenFlags[value.Name] { - fail("duplicate flag --%s", value.Name) - } - seenFlags[value.Name] = true - flag := &Flag{ - Value: value, - Short: tag.Short, - PlaceHolder: tag.PlaceHolder, - Env: tag.Env, - Group: buildGroupForKey(k, tag.Group), - Xor: tag.Xor, - Hidden: tag.Hidden, - } - value.Flag = flag - node.Flags = append(node.Flags, flag) - } -} - -func buildGroupForKey(k *Kong, key string) *Group { - if key == "" { - return nil - } - for _, group := range k.groups { - if group.Key == key { - return &group - } - } - - // No group provided with kong.ExplicitGroups. We create one ad-hoc for this key. - return &Group{ - Key: key, - Title: key, - } -} diff --git a/vendor/github.com/alecthomas/kong/callbacks.go b/vendor/github.com/alecthomas/kong/callbacks.go deleted file mode 100644 index 139a83bf..00000000 --- a/vendor/github.com/alecthomas/kong/callbacks.go +++ /dev/null @@ -1,76 +0,0 @@ -package kong - -import ( - "fmt" - "reflect" - "strings" -) - -type bindings map[reflect.Type]func() (reflect.Value, error) - -func (b bindings) String() string { - out := []string{} - for k := range b { - out = append(out, k.String()) - } - return "bindings{" + strings.Join(out, ", ") + "}" -} - -func (b bindings) add(values ...interface{}) bindings { - for _, v := range values { - v := v - b[reflect.TypeOf(v)] = func() (reflect.Value, error) { return reflect.ValueOf(v), nil } - } - return b -} - -// Clone and add values. -func (b bindings) clone() bindings { - out := make(bindings, len(b)) - for k, v := range b { - out[k] = v - } - return out -} - -func (b bindings) merge(other bindings) bindings { - for k, v := range other { - b[k] = v - } - return b -} - -func getMethod(value reflect.Value, name string) reflect.Value { - method := value.MethodByName(name) - if !method.IsValid() { - if value.CanAddr() { - method = value.Addr().MethodByName(name) - } - } - return method -} - -func callMethod(name string, v, f reflect.Value, bindings bindings) error { - in := []reflect.Value{} - t := f.Type() - if t.NumOut() != 1 || t.Out(0) != callbackReturnSignature { - return fmt.Errorf("return value of %T.%s() must be exactly \"error\"", v.Type(), name) - } - for i := 0; i < t.NumIn(); i++ { - pt := t.In(i) - if argf, ok := bindings[pt]; ok { - argv, err := argf() - if err != nil { - return err - } - in = append(in, argv) - } else { - return fmt.Errorf("couldn't find binding of type %s for parameter %d of %s.%s(), use kong.Bind(%s)", pt, i, v.Type(), name, pt) - } - } - out := f.Call(in) - if out[0].IsNil() { - return nil - } - return out[0].Interface().(error) -} diff --git a/vendor/github.com/alecthomas/kong/camelcase.go b/vendor/github.com/alecthomas/kong/camelcase.go deleted file mode 100644 index acf29f75..00000000 --- a/vendor/github.com/alecthomas/kong/camelcase.go +++ /dev/null @@ -1,90 +0,0 @@ -package kong - -// NOTE: This code is from https://github.com/fatih/camelcase. MIT license. - -import ( - "unicode" - "unicode/utf8" -) - -// Split splits the camelcase word and returns a list of words. It also -// supports digits. Both lower camel case and upper camel case are supported. -// For more info please check: http://en.wikipedia.org/wiki/CamelCase -// -// Examples -// -// "" => [""] -// "lowercase" => ["lowercase"] -// "Class" => ["Class"] -// "MyClass" => ["My", "Class"] -// "MyC" => ["My", "C"] -// "HTML" => ["HTML"] -// "PDFLoader" => ["PDF", "Loader"] -// "AString" => ["A", "String"] -// "SimpleXMLParser" => ["Simple", "XML", "Parser"] -// "vimRPCPlugin" => ["vim", "RPC", "Plugin"] -// "GL11Version" => ["GL", "11", "Version"] -// "99Bottles" => ["99", "Bottles"] -// "May5" => ["May", "5"] -// "BFG9000" => ["BFG", "9000"] -// "BöseÜberraschung" => ["Böse", "Überraschung"] -// "Two spaces" => ["Two", " ", "spaces"] -// "BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"] -// -// Splitting rules -// -// 1) If string is not valid UTF-8, return it without splitting as -// single item array. -// 2) Assign all unicode characters into one of 4 sets: lower case -// letters, upper case letters, numbers, and all other characters. -// 3) Iterate through characters of string, introducing splits -// between adjacent characters that belong to different sets. -// 4) Iterate through array of split strings, and if a given string -// is upper case: -// if subsequent string is lower case: -// move last character of upper case string to beginning of -// lower case string -func camelCase(src string) (entries []string) { - // don't split invalid utf8 - if !utf8.ValidString(src) { - return []string{src} - } - entries = []string{} - var runes [][]rune - lastClass := 0 - // split into fields based on class of unicode character - for _, r := range src { - var class int - switch { - case unicode.IsLower(r): - class = 1 - case unicode.IsUpper(r): - class = 2 - case unicode.IsDigit(r): - class = 3 - default: - class = 4 - } - if class == lastClass { - runes[len(runes)-1] = append(runes[len(runes)-1], r) - } else { - runes = append(runes, []rune{r}) - } - lastClass = class - } - // handle upper case -> lower case sequences, e.g. - // "PDFL", "oader" -> "PDF", "Loader" - for i := 0; i < len(runes)-1; i++ { - if unicode.IsUpper(runes[i][0]) && unicode.IsLower(runes[i+1][0]) { - runes[i+1] = append([]rune{runes[i][len(runes[i])-1]}, runes[i+1]...) - runes[i] = runes[i][:len(runes[i])-1] - } - } - // construct []string from results - for _, s := range runes { - if len(s) > 0 { - entries = append(entries, string(s)) - } - } - return entries -} diff --git a/vendor/github.com/alecthomas/kong/context.go b/vendor/github.com/alecthomas/kong/context.go deleted file mode 100644 index 4d241613..00000000 --- a/vendor/github.com/alecthomas/kong/context.go +++ /dev/null @@ -1,888 +0,0 @@ -package kong - -import ( - "fmt" - "os" - "reflect" - "sort" - "strconv" - "strings" - - "github.com/pkg/errors" -) - -// Path records the nodes and parsed values from the current command-line. -type Path struct { - Parent *Node - - // One of these will be non-nil. - App *Application - Positional *Positional - Flag *Flag - Argument *Argument - Command *Command - - // Flags added by this node. - Flags []*Flag - - // True if this Path element was created as the result of a resolver. - Resolved bool -} - -// Node returns the Node associated with this Path, or nil if Path is a non-Node. -func (p *Path) Node() *Node { - switch { - case p.App != nil: - return p.App.Node - - case p.Argument != nil: - return p.Argument - - case p.Command != nil: - return p.Command - } - return nil -} - -// Visitable returns the Visitable for this path element. -func (p *Path) Visitable() Visitable { - switch { - case p.App != nil: - return p.App - - case p.Argument != nil: - return p.Argument - - case p.Command != nil: - return p.Command - - case p.Flag != nil: - return p.Flag - - case p.Positional != nil: - return p.Positional - } - return nil -} - -// Context contains the current parse context. -type Context struct { - *Kong - // A trace through parsed nodes. - Path []*Path - // Original command-line arguments. - Args []string - // Error that occurred during trace, if any. - Error error - - values map[*Value]reflect.Value // Temporary values during tracing. - bindings bindings - resolvers []Resolver // Extra context-specific resolvers. - scan *Scanner -} - -// Trace path of "args" through the grammar tree. -// -// The returned Context will include a Path of all commands, arguments, positionals and flags. -// -// This just constructs a new trace. To fully apply the trace you must call Reset(), Resolve(), -// Validate() and Apply(). -func Trace(k *Kong, args []string) (*Context, error) { - c := &Context{ - Kong: k, - Args: args, - Path: []*Path{ - {App: k.Model, Flags: k.Model.Flags}, - }, - values: map[*Value]reflect.Value{}, - scan: Scan(args...), - bindings: bindings{}, - } - c.Error = c.trace(c.Model.Node) - return c, nil -} - -// Bind adds bindings to the Context. -func (c *Context) Bind(args ...interface{}) { - c.bindings.add(args...) -} - -// BindTo adds a binding to the Context. -// -// This will typically have to be called like so: -// -// BindTo(impl, (*MyInterface)(nil)) -func (c *Context) BindTo(impl, iface interface{}) { - valueOf := reflect.ValueOf(impl) - c.bindings[reflect.TypeOf(iface).Elem()] = func() (reflect.Value, error) { return valueOf, nil } -} - -// Value returns the value for a particular path element. -func (c *Context) Value(path *Path) reflect.Value { - switch { - case path.Positional != nil: - return c.values[path.Positional] - case path.Flag != nil: - return c.values[path.Flag.Value] - case path.Argument != nil: - return c.values[path.Argument.Argument] - } - panic("can only retrieve value for flag, argument or positional") -} - -// Selected command or argument. -func (c *Context) Selected() *Node { - var selected *Node - for _, path := range c.Path { - switch { - case path.Command != nil: - selected = path.Command - case path.Argument != nil: - selected = path.Argument - } - } - return selected -} - -// Empty returns true if there were no arguments provided. -func (c *Context) Empty() bool { - for _, path := range c.Path { - if !path.Resolved && path.App == nil { - return false - } - } - return true -} - -// Validate the current context. -func (c *Context) Validate() error { // nolint: gocyclo - err := Visit(c.Model, func(node Visitable, next Next) error { - switch node := node.(type) { - case *Value: - _, ok := os.LookupEnv(node.Tag.Env) - if node.Enum != "" && (!node.Required || node.Default != "" || (node.Tag.Env != "" && ok)) { - if err := checkEnum(node, node.Target); err != nil { - return err - } - } - - case *Flag: - _, ok := os.LookupEnv(node.Tag.Env) - if node.Enum != "" && (!node.Required || node.Default != "" || (node.Tag.Env != "" && ok)) { - if err := checkEnum(node.Value, node.Target); err != nil { - return err - } - } - } - return next(nil) - }) - if err != nil { - return err - } - for _, el := range c.Path { - var ( - value reflect.Value - desc string - ) - switch node := el.Visitable().(type) { - case *Value: - value = node.Target - desc = node.ShortSummary() - - case *Flag: - value = node.Target - desc = node.ShortSummary() - - case *Application: - value = node.Target - desc = node.Name - - case *Node: - value = node.Target - desc = node.Path() - } - if validate := isValidatable(value); validate != nil { - err := validate.Validate() - if err != nil { - return errors.Wrap(err, desc) - } - } - } - for _, resolver := range c.combineResolvers() { - if err := resolver.Validate(c.Model); err != nil { - return err - } - } - for _, path := range c.Path { - var value *Value - switch { - case path.Flag != nil: - value = path.Flag.Value - - case path.Positional != nil: - value = path.Positional - } - if value != nil && value.Tag.Enum != "" { - if err := checkEnum(value, value.Target); err != nil { - return err - } - } - if err := checkMissingFlags(path.Flags); err != nil { - return err - } - } - // Check the terminal node. - node := c.Selected() - if node == nil { - node = c.Model.Node - } - - // Find deepest positional argument so we can check if all required positionals have been provided. - positionals := 0 - for _, path := range c.Path { - if path.Positional != nil { - positionals = path.Positional.Position + 1 - } - } - - if err := checkMissingChildren(node); err != nil { - return err - } - if err := checkMissingPositionals(positionals, node.Positional); err != nil { - return err - } - if err := checkXorDuplicates(c.Path); err != nil { - return err - } - - if node.Type == ArgumentNode { - value := node.Argument - if value.Required && !value.Set { - return fmt.Errorf("%s is required", node.Summary()) - } - } - return nil -} - -// Flags returns the accumulated available flags. -func (c *Context) Flags() (flags []*Flag) { - for _, trace := range c.Path { - flags = append(flags, trace.Flags...) - } - return -} - -// Command returns the full command path. -func (c *Context) Command() string { - command := []string{} - for _, trace := range c.Path { - switch { - case trace.Positional != nil: - command = append(command, "<"+trace.Positional.Name+">") - - case trace.Argument != nil: - command = append(command, "<"+trace.Argument.Name+">") - - case trace.Command != nil: - command = append(command, trace.Command.Name) - } - } - return strings.Join(command, " ") -} - -// AddResolver adds a context-specific resolver. -// -// This is most useful in the BeforeResolve() hook. -func (c *Context) AddResolver(resolver Resolver) { - c.resolvers = append(c.resolvers, resolver) -} - -// FlagValue returns the set value of a flag if it was encountered and exists, or its default value. -func (c *Context) FlagValue(flag *Flag) interface{} { - for _, trace := range c.Path { - if trace.Flag == flag { - v, ok := c.values[trace.Flag.Value] - if !ok { - break - } - return v.Interface() - } - } - if flag.Target.IsValid() { - return flag.Target.Interface() - } - return flag.DefaultValue.Interface() -} - -// Reset recursively resets values to defaults (as specified in the grammar) or the zero value. -func (c *Context) Reset() error { - return Visit(c.Model.Node, func(node Visitable, next Next) error { - if value, ok := node.(*Value); ok { - return next(value.Reset()) - } - return next(nil) - }) -} - -func (c *Context) trace(node *Node) (err error) { // nolint: gocyclo - positional := 0 - - flags := []*Flag{} - for _, group := range node.AllFlags(false) { - flags = append(flags, group...) - } - - for !c.scan.Peek().IsEOL() { - token := c.scan.Peek() - switch token.Type { - case UntypedToken: - switch v := token.Value.(type) { - case string: - - switch { - case v == "-": - fallthrough - default: // nolint - c.scan.Pop() - c.scan.PushTyped(token.Value, PositionalArgumentToken) - - // Indicates end of parsing. All remaining arguments are treated as positional arguments only. - case v == "--": - c.scan.Pop() - args := []string{} - for { - token = c.scan.Pop() - if token.Type == EOLToken { - break - } - args = append(args, token.String()) - } - // Note: tokens must be pushed in reverse order. - for i := range args { - c.scan.PushTyped(args[len(args)-1-i], PositionalArgumentToken) - } - - // Long flag. - case strings.HasPrefix(v, "--"): - c.scan.Pop() - // Parse it and push the tokens. - parts := strings.SplitN(v[2:], "=", 2) - if len(parts) > 1 { - c.scan.PushTyped(parts[1], FlagValueToken) - } - c.scan.PushTyped(parts[0], FlagToken) - - // Short flag. - case strings.HasPrefix(v, "-"): - c.scan.Pop() - // Note: tokens must be pushed in reverse order. - if tail := v[2:]; tail != "" { - c.scan.PushTyped(tail, ShortFlagTailToken) - } - c.scan.PushTyped(v[1:2], ShortFlagToken) - } - default: - c.scan.Pop() - c.scan.PushTyped(token.Value, PositionalArgumentToken) - } - - case ShortFlagTailToken: - c.scan.Pop() - // Note: tokens must be pushed in reverse order. - if tail := token.String()[1:]; tail != "" { - c.scan.PushTyped(tail, ShortFlagTailToken) - } - c.scan.PushTyped(token.String()[0:1], ShortFlagToken) - - case FlagToken: - if err := c.parseFlag(flags, token.String()); err != nil { - return err - } - - case ShortFlagToken: - if err := c.parseFlag(flags, token.String()); err != nil { - return err - } - - case FlagValueToken: - return fmt.Errorf("unexpected flag argument %q", token.Value) - - case PositionalArgumentToken: - candidates := []string{} - - // Ensure we've consumed all positional arguments. - if positional < len(node.Positional) { - arg := node.Positional[positional] - err := arg.Parse(c.scan, c.getValue(arg)) - if err != nil { - return err - } - c.Path = append(c.Path, &Path{ - Parent: node, - Positional: arg, - }) - positional++ - break - } - - // Assign token value to a branch name if tagged as an alias - // An alias will be ignored in the case of an existing command - cmds := make(map[string]bool) - for _, branch := range node.Children { - if branch.Type == CommandNode { - cmds[branch.Name] = true - } - } - for _, branch := range node.Children { - for _, a := range branch.Aliases { - _, ok := cmds[a] - if token.Value == a && !ok { - token.Value = branch.Name - break - } - } - } - - // After positional arguments have been consumed, check commands next... - for _, branch := range node.Children { - if branch.Type == CommandNode && !branch.Hidden { - candidates = append(candidates, branch.Name) - } - if branch.Type == CommandNode && branch.Name == token.Value { - c.scan.Pop() - c.Path = append(c.Path, &Path{ - Parent: node, - Command: branch, - Flags: branch.Flags, - }) - return c.trace(branch) - } - } - - // Finally, check arguments. - for _, branch := range node.Children { - if branch.Type == ArgumentNode { - arg := branch.Argument - if err := arg.Parse(c.scan, c.getValue(arg)); err == nil { - c.Path = append(c.Path, &Path{ - Parent: node, - Argument: branch, - Flags: branch.Flags, - }) - return c.trace(branch) - } - } - } - - return findPotentialCandidates(token.String(), candidates, "unexpected argument %s", token) - default: - return fmt.Errorf("unexpected token %s", token) - } - } - return c.maybeSelectDefault(flags, node) -} - -// End of the line, check for a default command, but only if we're not displaying help, -// otherwise we'd only ever display the help for the default command. -func (c *Context) maybeSelectDefault(flags []*Flag, node *Node) error { - for _, flag := range flags { - if flag.Name == "help" && flag.Set { - return nil - } - } - var defaultNode *Path - for _, child := range node.Children { - if child.Type == CommandNode && child.Tag.Default != "" { - if defaultNode != nil { - return fmt.Errorf("can't have more than one default command under %s", node.Summary()) - } - defaultNode = &Path{ - Parent: child, - Command: child, - Flags: child.Flags, - } - } - } - if defaultNode != nil { - c.Path = append(c.Path, defaultNode) - } - return nil -} - -// Resolve walks through the traced path, applying resolvers to any unset flags. -func (c *Context) Resolve() error { - resolvers := c.combineResolvers() - if len(resolvers) == 0 { - return nil - } - - inserted := []*Path{} - for _, path := range c.Path { - for _, flag := range path.Flags { - // Flag has already been set on the command-line. - if _, ok := c.values[flag.Value]; ok { - continue - } - - // Pick the last resolved value. - var selected interface{} - for _, resolver := range resolvers { - s, err := resolver.Resolve(c, path, flag) - if err != nil { - return errors.Wrap(err, flag.ShortSummary()) - } - if s == nil { - continue - } - selected = s - } - - if selected == nil { - continue - } - - scan := Scan().PushTyped(selected, FlagValueToken) - delete(c.values, flag.Value) - err := flag.Parse(scan, c.getValue(flag.Value)) - if err != nil { - return err - } - inserted = append(inserted, &Path{ - Flag: flag, - Resolved: true, - }) - } - } - c.Path = append(inserted, c.Path...) - return nil -} - -// Combine application-level resolvers and context resolvers. -func (c *Context) combineResolvers() []Resolver { - resolvers := []Resolver{} - resolvers = append(resolvers, c.Kong.resolvers...) - resolvers = append(resolvers, c.resolvers...) - return resolvers -} - -func (c *Context) getValue(value *Value) reflect.Value { - v, ok := c.values[value] - if !ok { - v = reflect.New(value.Target.Type()).Elem() - switch v.Kind() { - case reflect.Ptr: - v.Set(reflect.New(v.Type().Elem())) - case reflect.Slice: - v.Set(reflect.MakeSlice(v.Type(), 0, 0)) - case reflect.Map: - v.Set(reflect.MakeMap(v.Type())) - } - c.values[value] = v - } - return v -} - -// ApplyDefaults if they are not already set. -func (c *Context) ApplyDefaults() error { - return Visit(c.Model.Node, func(node Visitable, next Next) error { - var value *Value - switch node := node.(type) { - case *Flag: - value = node.Value - case *Node: - value = node.Argument - case *Value: - value = node - default: - } - if value != nil { - if err := value.ApplyDefault(); err != nil { - return err - } - } - return next(nil) - }) -} - -// Apply traced context to the target grammar. -func (c *Context) Apply() (string, error) { - path := []string{} - - for _, trace := range c.Path { - var value *Value - switch { - case trace.App != nil: - case trace.Argument != nil: - path = append(path, "<"+trace.Argument.Name+">") - value = trace.Argument.Argument - case trace.Command != nil: - path = append(path, trace.Command.Name) - case trace.Flag != nil: - value = trace.Flag.Value - case trace.Positional != nil: - path = append(path, "<"+trace.Positional.Name+">") - value = trace.Positional - default: - panic("unsupported path ?!") - } - if value != nil { - value.Apply(c.getValue(value)) - } - } - - return strings.Join(path, " "), nil -} - -func (c *Context) parseFlag(flags []*Flag, match string) (err error) { - defer catch(&err) - candidates := []string{} - for _, flag := range flags { - long := "--" + flag.Name - short := "-" + string(flag.Short) - candidates = append(candidates, long) - if flag.Short != 0 { - candidates = append(candidates, short) - } - if short != match && long != match { - continue - } - // Found a matching flag. - c.scan.Pop() - err := flag.Parse(c.scan, c.getValue(flag.Value)) - if err != nil { - if e, ok := errors.Cause(err).(*expectedError); ok && e.token.InferredType().IsAny(FlagToken, ShortFlagToken) { - return errors.Errorf("%s; perhaps try %s=%q?", err, flag.ShortSummary(), e.token) - } - return err - } - c.Path = append(c.Path, &Path{Flag: flag}) - return nil - } - return findPotentialCandidates(match, candidates, "unknown flag %s", match) -} - -// RunNode calls the Run() method on an arbitrary node. -// -// This is useful in conjunction with Visit(), for dynamically running commands. -// -// Any passed values will be bindable to arguments of the target Run() method. Additionally, -// all parent nodes in the command structure will be bound. -func (c *Context) RunNode(node *Node, binds ...interface{}) (err error) { - type targetMethod struct { - node *Node - method reflect.Value - binds bindings - } - methodBinds := c.Kong.bindings.clone().add(binds...).add(c).merge(c.bindings) - methods := []targetMethod{} - for i := 0; node != nil; i, node = i+1, node.Parent { - method := getMethod(node.Target, "Run") - methodBinds = methodBinds.clone() - for p := node; p != nil; p = p.Parent { - methodBinds = methodBinds.add(p.Target.Addr().Interface()) - } - if method.IsValid() { - methods = append(methods, targetMethod{node, method, methodBinds}) - } - } - if len(methods) == 0 { - return fmt.Errorf("no Run() method found in hierarchy of %s", c.Selected().Summary()) - } - _, err = c.Apply() - if err != nil { - return err - } - - for _, method := range methods { - if err = callMethod("Run", method.node.Target, method.method, method.binds); err != nil { - return err - } - } - return nil -} - -// Run executes the Run() method on the selected command, which must exist. -// -// Any passed values will be bindable to arguments of the target Run() method. Additionally, -// all parent nodes in the command structure will be bound. -func (c *Context) Run(binds ...interface{}) (err error) { - defer catch(&err) - node := c.Selected() - if node == nil { - return fmt.Errorf("no command selected") - } - return c.RunNode(node, binds...) -} - -// PrintUsage to Kong's stdout. -// -// If summary is true, a summarised version of the help will be output. -func (c *Context) PrintUsage(summary bool) error { - options := c.helpOptions - options.Summary = summary - return c.help(options, c) -} - -func checkMissingFlags(flags []*Flag) error { - missing := []string{} - for _, flag := range flags { - if !flag.Required || flag.Set { - continue - } - missing = append(missing, flag.Summary()) - } - if len(missing) == 0 { - return nil - } - - return fmt.Errorf("missing flags: %s", strings.Join(missing, ", ")) -} - -func checkMissingChildren(node *Node) error { - missing := []string{} - - missingArgs := []string{} - for _, arg := range node.Positional { - if arg.Required && !arg.Set { - missingArgs = append(missingArgs, arg.Summary()) - } - } - if len(missingArgs) > 0 { - missing = append(missing, strconv.Quote(strings.Join(missingArgs, " "))) - } - - haveDefault := 0 - for _, child := range node.Children { - if child.Hidden { - continue - } - if child.Argument != nil { - if !child.Argument.Required { - continue - } - missing = append(missing, strconv.Quote(child.Summary())) - } else { - if child.Tag.Default != "" { - if len(child.Children) > 0 { - return fmt.Errorf("default command %s must not have subcommands or arguments", child.Summary()) - } - haveDefault++ - } - missing = append(missing, strconv.Quote(child.Name)) - } - } - if haveDefault > 1 { - return fmt.Errorf("more than one default command found under %s", node.Summary()) - } - if len(missing) == 0 || haveDefault > 0 { - return nil - } - - if len(missing) > 5 { - missing = append(missing[:5], "...") - } - if len(missing) == 1 { - return fmt.Errorf("expected %s", missing[0]) - } - return fmt.Errorf("expected one of %s", strings.Join(missing, ", ")) -} - -// If we're missing any positionals and they're required, return an error. -func checkMissingPositionals(positional int, values []*Value) error { - // All the positionals are in. - if positional >= len(values) { - return nil - } - - // We're low on supplied positionals, but the missing one is optional. - if !values[positional].Required { - return nil - } - - missing := []string{} - for ; positional < len(values); positional++ { - missing = append(missing, "<"+values[positional].Name+">") - } - return fmt.Errorf("missing positional arguments %s", strings.Join(missing, " ")) -} - -func checkEnum(value *Value, target reflect.Value) error { - switch target.Kind() { - case reflect.Slice, reflect.Array: - for i := 0; i < target.Len(); i++ { - if err := checkEnum(value, target.Index(i)); err != nil { - return err - } - } - return nil - - case reflect.Map, reflect.Struct: - return errors.Errorf("enum can only be applied to a slice or value") - - default: - enumMap := value.EnumMap() - v := fmt.Sprintf("%v", target) - if enumMap[v] { - return nil - } - enums := []string{} - for enum := range enumMap { - enums = append(enums, fmt.Sprintf("%q", enum)) - } - sort.Strings(enums) - return fmt.Errorf("%s must be one of %s but got %q", value.ShortSummary(), strings.Join(enums, ","), target.Interface()) - } -} - -func checkXorDuplicates(paths []*Path) error { - for _, path := range paths { - seen := map[string]*Flag{} - for _, flag := range path.Flags { - if !flag.Set { - continue - } - if flag.Xor == "" { - continue - } - if seen[flag.Xor] != nil { - return fmt.Errorf("--%s and --%s can't be used together", seen[flag.Xor].Name, flag.Name) - } - seen[flag.Xor] = flag - } - } - return nil -} - -func findPotentialCandidates(needle string, haystack []string, format string, args ...interface{}) error { - if len(haystack) == 0 { - return fmt.Errorf(format, args...) - } - closestCandidates := []string{} - for _, candidate := range haystack { - if strings.HasPrefix(candidate, needle) || levenshtein(candidate, needle) <= 2 { - closestCandidates = append(closestCandidates, fmt.Sprintf("%q", candidate)) - } - } - prefix := fmt.Sprintf(format, args...) - if len(closestCandidates) == 1 { - return fmt.Errorf("%s, did you mean %s?", prefix, closestCandidates[0]) - } else if len(closestCandidates) > 1 { - return fmt.Errorf("%s, did you mean one of %s?", prefix, strings.Join(closestCandidates, ", ")) - } - return fmt.Errorf("%s", prefix) -} - -type validatable interface{ Validate() error } - -func isValidatable(v reflect.Value) validatable { - if !v.IsValid() || (v.Kind() == reflect.Ptr || v.Kind() == reflect.Slice || v.Kind() == reflect.Map) && v.IsNil() { - return nil - } - if validate, ok := v.Interface().(validatable); ok { - return validate - } - if v.CanAddr() { - return isValidatable(v.Addr()) - } - return nil -} diff --git a/vendor/github.com/alecthomas/kong/defaults.go b/vendor/github.com/alecthomas/kong/defaults.go deleted file mode 100644 index f6728d79..00000000 --- a/vendor/github.com/alecthomas/kong/defaults.go +++ /dev/null @@ -1,21 +0,0 @@ -package kong - -// ApplyDefaults if they are not already set. -func ApplyDefaults(target interface{}, options ...Option) error { - app, err := New(target, options...) - if err != nil { - return err - } - ctx, err := Trace(app, nil) - if err != nil { - return err - } - err = ctx.Resolve() - if err != nil { - return err - } - if err = ctx.ApplyDefaults(); err != nil { - return err - } - return ctx.Validate() -} diff --git a/vendor/github.com/alecthomas/kong/doc.go b/vendor/github.com/alecthomas/kong/doc.go deleted file mode 100644 index 78c4d110..00000000 --- a/vendor/github.com/alecthomas/kong/doc.go +++ /dev/null @@ -1,32 +0,0 @@ -// Package kong aims to support arbitrarily complex command-line structures with as little developer effort as possible. -// -// Here's an example: -// -// shell rm [-f] [-r] ... -// shell ls [ ...] -// -// This can be represented by the following command-line structure: -// -// package main -// -// import "github.com/alecthomas/kong" -// -// var CLI struct { -// Rm struct { -// Force bool `short:"f" help:"Force removal."` -// Recursive bool `short:"r" help:"Recursively remove files."` -// -// Paths []string `arg help:"Paths to remove." type:"path"` -// } `cmd help:"Remove files."` -// -// Ls struct { -// Paths []string `arg optional help:"Paths to list." type:"path"` -// } `cmd help:"List paths."` -// } -// -// func main() { -// kong.Parse(&CLI) -// } -// -// See https://github.com/alecthomas/kong for details. -package kong diff --git a/vendor/github.com/alecthomas/kong/error.go b/vendor/github.com/alecthomas/kong/error.go deleted file mode 100644 index 30b88589..00000000 --- a/vendor/github.com/alecthomas/kong/error.go +++ /dev/null @@ -1,12 +0,0 @@ -package kong - -// ParseError is the error type returned by Kong.Parse(). -// -// It contains the parse Context that triggered the error. -type ParseError struct { - error - Context *Context -} - -// Cause returns the original cause of the error. -func (p *ParseError) Cause() error { return p.error } diff --git a/vendor/github.com/alecthomas/kong/global.go b/vendor/github.com/alecthomas/kong/global.go deleted file mode 100644 index d4b3cb56..00000000 --- a/vendor/github.com/alecthomas/kong/global.go +++ /dev/null @@ -1,16 +0,0 @@ -package kong - -import ( - "os" -) - -// Parse constructs a new parser and parses the default command-line. -func Parse(cli interface{}, options ...Option) *Context { - parser, err := New(cli, options...) - if err != nil { - panic(err) - } - ctx, err := parser.Parse(os.Args[1:]) - parser.FatalIfErrorf(err) - return ctx -} diff --git a/vendor/github.com/alecthomas/kong/guesswidth.go b/vendor/github.com/alecthomas/kong/guesswidth.go deleted file mode 100644 index 46768e68..00000000 --- a/vendor/github.com/alecthomas/kong/guesswidth.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build appengine !linux,!freebsd,!darwin,!dragonfly,!netbsd,!openbsd - -package kong - -import "io" - -func guessWidth(w io.Writer) int { - return 80 -} diff --git a/vendor/github.com/alecthomas/kong/guesswidth_unix.go b/vendor/github.com/alecthomas/kong/guesswidth_unix.go deleted file mode 100644 index 41d54e64..00000000 --- a/vendor/github.com/alecthomas/kong/guesswidth_unix.go +++ /dev/null @@ -1,41 +0,0 @@ -// +build !appengine,linux freebsd darwin dragonfly netbsd openbsd - -package kong - -import ( - "io" - "os" - "strconv" - "syscall" - "unsafe" -) - -func guessWidth(w io.Writer) int { - // check if COLUMNS env is set to comply with - // http://pubs.opengroup.org/onlinepubs/009604499/basedefs/xbd_chap08.html - colsStr := os.Getenv("COLUMNS") - if colsStr != "" { - if cols, err := strconv.Atoi(colsStr); err == nil { - return cols - } - } - - if t, ok := w.(*os.File); ok { - fd := t.Fd() - var dimensions [4]uint16 - - if _, _, err := syscall.Syscall6( - syscall.SYS_IOCTL, - uintptr(fd), // nolint: unconvert - uintptr(syscall.TIOCGWINSZ), - uintptr(unsafe.Pointer(&dimensions)), // nolint: gas - 0, 0, 0, - ); err == 0 { - if dimensions[1] == 0 { - return 80 - } - return int(dimensions[1]) - } - } - return 80 -} diff --git a/vendor/github.com/alecthomas/kong/help.go b/vendor/github.com/alecthomas/kong/help.go deleted file mode 100644 index e1077240..00000000 --- a/vendor/github.com/alecthomas/kong/help.go +++ /dev/null @@ -1,503 +0,0 @@ -package kong - -import ( - "bytes" - "fmt" - "go/doc" - "io" - "strings" -) - -const ( - defaultIndent = 2 - defaultColumnPadding = 4 -) - -// Help flag. -type helpValue bool - -func (h helpValue) BeforeApply(ctx *Context) error { - options := ctx.Kong.helpOptions - options.Summary = false - err := ctx.Kong.help(options, ctx) - if err != nil { - return err - } - ctx.Kong.Exit(0) - return nil -} - -// HelpOptions for HelpPrinters. -type HelpOptions struct { - // Don't print top-level usage summary. - NoAppSummary bool - - // Write a one-line summary of the context. - Summary bool - - // Write help in a more compact, but still fully-specified, form. - Compact bool - - // Tree writes command chains in a tree structure instead of listing them separately. - Tree bool - - // Indenter modulates the given prefix for the next layer in the tree view. - // The following exported templates can be used: kong.SpaceIndenter, kong.LineIndenter, kong.TreeIndenter - // The kong.SpaceIndenter will be used by default. - Indenter HelpIndenter -} - -// Apply options to Kong as a configuration option. -func (h HelpOptions) Apply(k *Kong) error { - k.helpOptions = h - return nil -} - -// HelpProvider can be implemented by commands/args to provide detailed help. -type HelpProvider interface { - // This string is formatted by go/doc and thus has the same formatting rules. - Help() string -} - -// HelpIndenter is used to indent new layers in the help tree. -type HelpIndenter func(prefix string) string - -// HelpPrinter is used to print context-sensitive help. -type HelpPrinter func(options HelpOptions, ctx *Context) error - -// HelpValueFormatter is used to format the help text of flags and positional arguments. -type HelpValueFormatter func(value *Value) string - -// DefaultHelpValueFormatter is the default HelpValueFormatter. -func DefaultHelpValueFormatter(value *Value) string { - if value.Tag.Env == "" { - return value.Help - } - suffix := "($" + value.Tag.Env + ")" - switch { - case strings.HasSuffix(value.Help, "."): - return value.Help[:len(value.Help)-1] + " " + suffix + "." - case value.Help == "": - return suffix - default: - return value.Help + " " + suffix - } -} - -// DefaultHelpPrinter is the default HelpPrinter. -func DefaultHelpPrinter(options HelpOptions, ctx *Context) error { - if ctx.Empty() { - options.Summary = false - } - w := newHelpWriter(ctx, options) - selected := ctx.Selected() - if selected == nil { - printApp(w, ctx.Model) - } else { - printCommand(w, ctx.Model, selected) - } - return w.Write(ctx.Stdout) -} - -func printApp(w *helpWriter, app *Application) { - if !w.NoAppSummary { - w.Printf("Usage: %s%s", app.Name, app.Summary()) - } - printNodeDetail(w, app.Node, true) - cmds := app.Leaves(true) - if len(cmds) > 0 && app.HelpFlag != nil { - w.Print("") - if w.Summary { - w.Printf(`Run "%s --help" for more information.`, app.Name) - } else { - w.Printf(`Run "%s --help" for more information on a command.`, app.Name) - } - } -} - -func printCommand(w *helpWriter, app *Application, cmd *Command) { - if !w.NoAppSummary { - w.Printf("Usage: %s %s", app.Name, cmd.Summary()) - } - printNodeDetail(w, cmd, true) - if w.Summary && app.HelpFlag != nil { - w.Print("") - w.Printf(`Run "%s --help" for more information.`, cmd.FullPath()) - } -} - -func printNodeDetail(w *helpWriter, node *Node, hide bool) { - if node.Help != "" { - w.Print("") - w.Wrap(node.Help) - } - if w.Summary { - return - } - if node.Detail != "" { - w.Print("") - w.Wrap(node.Detail) - } - if len(node.Positional) > 0 { - w.Print("") - w.Print("Arguments:") - writePositionals(w.Indent(), node.Positional) - } - if flags := node.AllFlags(true); len(flags) > 0 { - groupedFlags := collectFlagGroups(flags) - for _, group := range groupedFlags { - w.Print("") - if group.Metadata.Title != "" { - w.Wrap(group.Metadata.Title) - } - if group.Metadata.Description != "" { - w.Indent().Wrap(group.Metadata.Description) - w.Print("") - } - writeFlags(w.Indent(), group.Flags) - } - } - cmds := node.Leaves(hide) - if len(cmds) > 0 { - iw := w.Indent() - if w.Tree { - w.Print("") - w.Print("Commands:") - writeCommandTree(iw, node) - } else { - groupedCmds := collectCommandGroups(cmds) - for _, group := range groupedCmds { - w.Print("") - if group.Metadata.Title != "" { - w.Wrap(group.Metadata.Title) - } - if group.Metadata.Description != "" { - w.Indent().Wrap(group.Metadata.Description) - w.Print("") - } - - if w.Compact { - writeCompactCommandList(group.Commands, iw) - } else { - writeCommandList(group.Commands, iw) - } - } - } - } -} - -func writeCommandList(cmds []*Node, iw *helpWriter) { - for i, cmd := range cmds { - if cmd.Hidden { - continue - } - printCommandSummary(iw, cmd) - if i != len(cmds)-1 { - iw.Print("") - } - } -} - -func writeCompactCommandList(cmds []*Node, iw *helpWriter) { - rows := [][2]string{} - for _, cmd := range cmds { - if cmd.Hidden { - continue - } - rows = append(rows, [2]string{cmd.Path(), cmd.Help}) - } - writeTwoColumns(iw, rows) -} - -func writeCommandTree(w *helpWriter, node *Node) { - rows := make([][2]string, 0, len(node.Children)*2) - for i, cmd := range node.Children { - if cmd.Hidden { - continue - } - rows = append(rows, w.CommandTree(cmd, "")...) - if i != len(node.Children)-1 { - rows = append(rows, [2]string{"", ""}) - } - } - writeTwoColumns(w, rows) -} - -type helpFlagGroup struct { - Metadata *Group - Flags [][]*Flag -} - -func collectFlagGroups(flags [][]*Flag) []helpFlagGroup { - // Group keys in order of appearance. - groups := []*Group{} - // Flags grouped by their group key. - flagsByGroup := map[string][][]*Flag{} - - for _, levelFlags := range flags { - levelFlagsByGroup := map[string][]*Flag{} - - for _, flag := range levelFlags { - key := "" - if flag.Group != nil { - key = flag.Group.Key - groupAlreadySeen := false - for _, group := range groups { - if key == group.Key { - groupAlreadySeen = true - break - } - } - if !groupAlreadySeen { - groups = append(groups, flag.Group) - } - } - - levelFlagsByGroup[key] = append(levelFlagsByGroup[key], flag) - } - - for key, flags := range levelFlagsByGroup { - flagsByGroup[key] = append(flagsByGroup[key], flags) - } - } - - out := []helpFlagGroup{} - // Ungrouped flags are always displayed first. - if ungroupedFlags, ok := flagsByGroup[""]; ok { - out = append(out, helpFlagGroup{ - Metadata: &Group{Title: "Flags:"}, - Flags: ungroupedFlags, - }) - } - for _, group := range groups { - out = append(out, helpFlagGroup{Metadata: group, Flags: flagsByGroup[group.Key]}) - } - return out -} - -type helpCommandGroup struct { - Metadata *Group - Commands []*Node -} - -func collectCommandGroups(nodes []*Node) []helpCommandGroup { - // Groups in order of appearance. - groups := []*Group{} - // Nodes grouped by their group key. - nodesByGroup := map[string][]*Node{} - - for _, node := range nodes { - key := "" - if group := node.ClosestGroup(); group != nil { - key = group.Key - if _, ok := nodesByGroup[key]; !ok { - groups = append(groups, group) - } - } - nodesByGroup[key] = append(nodesByGroup[key], node) - } - - out := []helpCommandGroup{} - // Ungrouped nodes are always displayed first. - if ungroupedNodes, ok := nodesByGroup[""]; ok { - out = append(out, helpCommandGroup{ - Metadata: &Group{Title: "Commands:"}, - Commands: ungroupedNodes, - }) - } - for _, group := range groups { - out = append(out, helpCommandGroup{Metadata: group, Commands: nodesByGroup[group.Key]}) - } - return out -} - -func printCommandSummary(w *helpWriter, cmd *Command) { - w.Print(cmd.Summary()) - if cmd.Help != "" { - w.Indent().Wrap(cmd.Help) - } -} - -type helpWriter struct { - indent string - width int - lines *[]string - helpFormatter HelpValueFormatter - HelpOptions -} - -func newHelpWriter(ctx *Context, options HelpOptions) *helpWriter { - lines := []string{} - w := &helpWriter{ - indent: "", - width: guessWidth(ctx.Stdout), - lines: &lines, - helpFormatter: ctx.Kong.helpFormatter, - HelpOptions: options, - } - return w -} - -func (h *helpWriter) Printf(format string, args ...interface{}) { - h.Print(fmt.Sprintf(format, args...)) -} - -func (h *helpWriter) Print(text string) { - *h.lines = append(*h.lines, strings.TrimRight(h.indent+text, " ")) -} - -// Indent returns a new helpWriter indented by two characters. -func (h *helpWriter) Indent() *helpWriter { - return &helpWriter{indent: h.indent + " ", lines: h.lines, width: h.width - 2, HelpOptions: h.HelpOptions, helpFormatter: h.helpFormatter} -} - -func (h *helpWriter) String() string { - return strings.Join(*h.lines, "\n") -} - -func (h *helpWriter) Write(w io.Writer) error { - for _, line := range *h.lines { - _, err := io.WriteString(w, line+"\n") - if err != nil { - return err - } - } - return nil -} - -func (h *helpWriter) Wrap(text string) { - w := bytes.NewBuffer(nil) - doc.ToText(w, strings.TrimSpace(text), "", " ", h.width) - for _, line := range strings.Split(strings.TrimSpace(w.String()), "\n") { - h.Print(line) - } -} - -func writePositionals(w *helpWriter, args []*Positional) { - rows := [][2]string{} - for _, arg := range args { - rows = append(rows, [2]string{arg.Summary(), w.helpFormatter(arg)}) - } - writeTwoColumns(w, rows) -} - -func writeFlags(w *helpWriter, groups [][]*Flag) { - rows := [][2]string{} - haveShort := false - for _, group := range groups { - for _, flag := range group { - if flag.Short != 0 { - haveShort = true - break - } - } - } - for i, group := range groups { - if i > 0 { - rows = append(rows, [2]string{"", ""}) - } - for _, flag := range group { - if !flag.Hidden { - rows = append(rows, [2]string{formatFlag(haveShort, flag), w.helpFormatter(flag.Value)}) - } - } - } - writeTwoColumns(w, rows) -} - -func writeTwoColumns(w *helpWriter, rows [][2]string) { - maxLeft := 375 * w.width / 1000 - if maxLeft < 30 { - maxLeft = 30 - } - // Find size of first column. - leftSize := 0 - for _, row := range rows { - if c := len(row[0]); c > leftSize && c < maxLeft { - leftSize = c - } - } - - offsetStr := strings.Repeat(" ", leftSize+defaultColumnPadding) - - for _, row := range rows { - buf := bytes.NewBuffer(nil) - doc.ToText(buf, row[1], "", strings.Repeat(" ", defaultIndent), w.width-leftSize-defaultColumnPadding) - lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n") - - line := fmt.Sprintf("%-*s", leftSize, row[0]) - if len(row[0]) < maxLeft { - line += fmt.Sprintf("%*s%s", defaultColumnPadding, "", lines[0]) - lines = lines[1:] - } - w.Print(line) - for _, line := range lines { - w.Printf("%s%s", offsetStr, line) - } - } -} - -// haveShort will be true if there are short flags present at all in the help. Useful for column alignment. -func formatFlag(haveShort bool, flag *Flag) string { - flagString := "" - name := flag.Name - isBool := flag.IsBool() - if flag.Short != 0 { - flagString += fmt.Sprintf("-%c, --%s", flag.Short, name) - } else { - if haveShort { - flagString += fmt.Sprintf(" --%s", name) - } else { - flagString += fmt.Sprintf("--%s", name) - } - } - if !isBool { - flagString += fmt.Sprintf("=%s", flag.FormatPlaceHolder()) - } - return flagString -} - -// CommandTree creates a tree with the given node name as root and its children's arguments and sub commands as leaves. -func (h *HelpOptions) CommandTree(node *Node, prefix string) (rows [][2]string) { - var nodeName string - switch node.Type { - default: - nodeName += prefix + node.Name - case ArgumentNode: - nodeName += prefix + "<" + node.Name + ">" - } - rows = append(rows, [2]string{nodeName, node.Help}) - if h.Indenter == nil { - prefix = SpaceIndenter(prefix) - } else { - prefix = h.Indenter(prefix) - } - for _, arg := range node.Positional { - rows = append(rows, [2]string{prefix + arg.Summary(), arg.Help}) - } - for _, subCmd := range node.Children { - rows = append(rows, h.CommandTree(subCmd, prefix)...) - } - return -} - -// SpaceIndenter adds a space indent to the given prefix. -func SpaceIndenter(prefix string) string { - return prefix + strings.Repeat(" ", defaultIndent) -} - -// LineIndenter adds line points to every new indent. -func LineIndenter(prefix string) string { - if prefix == "" { - return "- " - } - return strings.Repeat(" ", defaultIndent) + prefix -} - -// TreeIndenter adds line points to every new indent and vertical lines to every layer. -func TreeIndenter(prefix string) string { - if prefix == "" { - return "|- " - } - return "|" + strings.Repeat(" ", defaultIndent) + prefix -} diff --git a/vendor/github.com/alecthomas/kong/hooks.go b/vendor/github.com/alecthomas/kong/hooks.go deleted file mode 100644 index d166b088..00000000 --- a/vendor/github.com/alecthomas/kong/hooks.go +++ /dev/null @@ -1,19 +0,0 @@ -package kong - -// BeforeResolve is a documentation-only interface describing hooks that run before resolvers are applied. -type BeforeResolve interface { - // This is not the correct signature - see README for details. - BeforeResolve(args ...interface{}) error -} - -// BeforeApply is a documentation-only interface describing hooks that run before values are set. -type BeforeApply interface { - // This is not the correct signature - see README for details. - BeforeApply(args ...interface{}) error -} - -// AfterApply is a documentation-only interface describing hooks that run after values are set. -type AfterApply interface { - // This is not the correct signature - see README for details. - AfterApply(args ...interface{}) error -} diff --git a/vendor/github.com/alecthomas/kong/interpolate.go b/vendor/github.com/alecthomas/kong/interpolate.go deleted file mode 100644 index 8c6f7424..00000000 --- a/vendor/github.com/alecthomas/kong/interpolate.go +++ /dev/null @@ -1,39 +0,0 @@ -package kong - -import ( - "fmt" - "regexp" -) - -var interpolationRegex = regexp.MustCompile(`((?:\${([[:alpha:]_][[:word:]]*))(?:=([^}]+))?})|(\$)|([^$]+)`) - -// Interpolate variables from vars into s for substrings in the form ${var} or ${var=default}. -func interpolate(s string, vars Vars, updatedVars map[string]string) (string, error) { - out := "" - matches := interpolationRegex.FindAllStringSubmatch(s, -1) - if len(matches) == 0 { - return s, nil - } - for key, val := range updatedVars { - if vars[key] != val { - vars = vars.CloneWith(updatedVars) - break - } - } - for _, match := range matches { - if name := match[2]; name != "" { - value, ok := vars[name] - if !ok { - // No default value. - if match[3] == "" { - return "", fmt.Errorf("undefined variable ${%s}", name) - } - value = match[3] - } - out += value - } else { - out += match[0] - } - } - return out, nil -} diff --git a/vendor/github.com/alecthomas/kong/kong.go b/vendor/github.com/alecthomas/kong/kong.go deleted file mode 100644 index 9b67db93..00000000 --- a/vendor/github.com/alecthomas/kong/kong.go +++ /dev/null @@ -1,368 +0,0 @@ -package kong - -import ( - "fmt" - "io" - "os" - "path/filepath" - "reflect" - "strings" -) - -var ( - callbackReturnSignature = reflect.TypeOf((*error)(nil)).Elem() -) - -// Error reported by Kong. -type Error struct{ msg string } - -func (e Error) Error() string { return e.msg } - -func fail(format string, args ...interface{}) { - panic(Error{msg: fmt.Sprintf(format, args...)}) -} - -// Must creates a new Parser or panics if there is an error. -func Must(ast interface{}, options ...Option) *Kong { - k, err := New(ast, options...) - if err != nil { - panic(err) - } - return k -} - -// Kong is the main parser type. -type Kong struct { - // Grammar model. - Model *Application - - // Termination function (defaults to os.Exit) - Exit func(int) - - Stdout io.Writer - Stderr io.Writer - - bindings bindings - loader ConfigurationLoader - resolvers []Resolver - registry *Registry - - noDefaultHelp bool - usageOnError bool - help HelpPrinter - helpFormatter HelpValueFormatter - helpOptions HelpOptions - helpFlag *Flag - groups []Group - vars Vars - - // Set temporarily by Options. These are applied after build(). - postBuildOptions []Option -} - -// New creates a new Kong parser on grammar. -// -// See the README (https://github.com/alecthomas/kong) for usage instructions. -func New(grammar interface{}, options ...Option) (*Kong, error) { - k := &Kong{ - Exit: os.Exit, - Stdout: os.Stdout, - Stderr: os.Stderr, - registry: NewRegistry().RegisterDefaults(), - vars: Vars{}, - bindings: bindings{}, - helpFormatter: DefaultHelpValueFormatter, - } - - options = append(options, Bind(k)) - - for _, option := range options { - if err := option.Apply(k); err != nil { - return nil, err - } - } - - if k.help == nil { - k.help = DefaultHelpPrinter - } - - model, err := build(k, grammar) - if err != nil { - return k, err - } - model.Name = filepath.Base(os.Args[0]) - k.Model = model - k.Model.HelpFlag = k.helpFlag - - for _, option := range k.postBuildOptions { - if err = option.Apply(k); err != nil { - return nil, err - } - } - k.postBuildOptions = nil - - if err = k.interpolate(k.Model.Node); err != nil { - return nil, err - } - - k.bindings.add(k.vars) - - return k, nil -} - -type varStack []Vars - -func (v *varStack) head() Vars { return (*v)[len(*v)-1] } -func (v *varStack) pop() { *v = (*v)[:len(*v)-1] } -func (v *varStack) push(vars Vars) Vars { - if len(*v) != 0 { - vars = (*v)[len(*v)-1].CloneWith(vars) - } - *v = append(*v, vars) - return vars -} - -// Interpolate variables into model. -func (k *Kong) interpolate(node *Node) (err error) { - stack := varStack{} - return Visit(node, func(node Visitable, next Next) error { - switch node := node.(type) { - case *Node: - vars := stack.push(node.Vars()) - node.Help, err = interpolate(node.Help, vars, nil) - if err != nil { - return fmt.Errorf("help for %s: %s", node.Path(), err) - } - err = next(nil) - stack.pop() - return err - - case *Value: - return next(k.interpolateValue(node, stack.head())) - } - return next(nil) - }) -} - -func (k *Kong) interpolateValue(value *Value, vars Vars) (err error) { - if len(value.Tag.Vars) > 0 { - vars = vars.CloneWith(value.Tag.Vars) - } - if value.Default, err = interpolate(value.Default, vars, nil); err != nil { - return fmt.Errorf("default value for %s: %s", value.Summary(), err) - } - if value.Enum, err = interpolate(value.Enum, vars, nil); err != nil { - return fmt.Errorf("enum value for %s: %s", value.Summary(), err) - } - value.Help, err = interpolate(value.Help, vars, map[string]string{ - "default": value.Default, - "enum": value.Enum, - }) - if err != nil { - return fmt.Errorf("help for %s: %s", value.Summary(), err) - } - return nil -} - -// Provide additional builtin flags, if any. -func (k *Kong) extraFlags() []*Flag { - if k.noDefaultHelp { - return nil - } - var helpTarget helpValue - value := reflect.ValueOf(&helpTarget).Elem() - helpFlag := &Flag{ - Short: 'h', - Value: &Value{ - Name: "help", - Help: "Show context-sensitive help.", - Target: value, - Tag: &Tag{}, - Mapper: k.registry.ForValue(value), - DefaultValue: reflect.ValueOf(false), - }, - } - helpFlag.Flag = helpFlag - k.helpFlag = helpFlag - return []*Flag{helpFlag} -} - -// Parse arguments into target. -// -// The return Context can be used to further inspect the parsed command-line, to format help, to find the -// selected command, to run command Run() methods, and so on. See Context and README for more information. -// -// Will return a ParseError if a *semantically* invalid command-line is encountered (as opposed to a syntactically -// invalid one, which will report a normal error). -func (k *Kong) Parse(args []string) (ctx *Context, err error) { - defer catch(&err) - ctx, err = Trace(k, args) - if err != nil { - return nil, err - } - if ctx.Error != nil { - return nil, &ParseError{error: ctx.Error, Context: ctx} - } - if err = ctx.Reset(); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - if err = k.applyHook(ctx, "BeforeResolve"); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - if err = ctx.Resolve(); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - if err = k.applyHook(ctx, "BeforeApply"); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - if _, err = ctx.Apply(); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - if err = ctx.Validate(); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - if err = k.applyHook(ctx, "AfterApply"); err != nil { - return nil, &ParseError{error: err, Context: ctx} - } - return ctx, nil -} - -func (k *Kong) applyHook(ctx *Context, name string) error { - for _, trace := range ctx.Path { - var value reflect.Value - switch { - case trace.App != nil: - value = trace.App.Target - case trace.Argument != nil: - value = trace.Argument.Target - case trace.Command != nil: - value = trace.Command.Target - case trace.Positional != nil: - value = trace.Positional.Target - case trace.Flag != nil: - value = trace.Flag.Value.Target - default: - panic("unsupported Path") - } - method := getMethod(value, name) - if !method.IsValid() { - continue - } - binds := k.bindings.clone() - binds.add(ctx, trace) - binds.add(trace.Node().Vars().CloneWith(k.vars)) - binds.merge(ctx.bindings) - if err := callMethod(name, value, method, binds); err != nil { - return err - } - } - // Path[0] will always be the app root. - return k.applyHookToDefaultFlags(ctx, ctx.Path[0].Node(), name) -} - -// Call hook on any unset flags with default values. -func (k *Kong) applyHookToDefaultFlags(ctx *Context, node *Node, name string) error { - if node == nil { - return nil - } - return Visit(node, func(n Visitable, next Next) error { - node, ok := n.(*Node) - if !ok { - return next(nil) - } - binds := k.bindings.clone().add(ctx).add(node.Vars().CloneWith(k.vars)) - for _, flag := range node.Flags { - if flag.Default == "" || ctx.values[flag.Value].IsValid() || !flag.Target.IsValid() { - continue - } - method := getMethod(flag.Target, name) - if !method.IsValid() { - continue - } - path := &Path{Flag: flag} - if err := callMethod(name, flag.Target, method, binds.clone().add(path)); err != nil { - return next(err) - } - } - return next(nil) - }) -} - -func formatMultilineMessage(w io.Writer, leaders []string, format string, args ...interface{}) { - lines := strings.Split(fmt.Sprintf(format, args...), "\n") - leader := "" - for _, l := range leaders { - if l == "" { - continue - } - leader += l + ": " - } - fmt.Fprintf(w, "%s%s\n", leader, lines[0]) - for _, line := range lines[1:] { - fmt.Fprintf(w, "%*s%s\n", len(leader), " ", line) - } -} - -// Printf writes a message to Kong.Stdout with the application name prefixed. -func (k *Kong) Printf(format string, args ...interface{}) *Kong { - formatMultilineMessage(k.Stdout, []string{k.Model.Name}, format, args...) - return k -} - -// Errorf writes a message to Kong.Stderr with the application name prefixed. -func (k *Kong) Errorf(format string, args ...interface{}) *Kong { - formatMultilineMessage(k.Stderr, []string{k.Model.Name, "error"}, format, args...) - return k -} - -// Fatalf writes a message to Kong.Stderr with the application name prefixed then exits with a non-zero status. -func (k *Kong) Fatalf(format string, args ...interface{}) { - k.Errorf(format, args...) - k.Exit(1) -} - -// FatalIfErrorf terminates with an error message if err != nil. -func (k *Kong) FatalIfErrorf(err error, args ...interface{}) { - if err == nil { - return - } - msg := err.Error() - if len(args) > 0 { - msg = fmt.Sprintf(args[0].(string), args[1:]...) + ": " + err.Error() - } - // Maybe display usage information. - if err, ok := err.(*ParseError); ok && k.usageOnError { - options := k.helpOptions - _ = k.help(options, err.Context) - fmt.Fprintln(k.Stdout) - } - k.Fatalf("%s", msg) -} - -// LoadConfig from path using the loader configured via Configuration(loader). -// -// "path" will have ~ and any variables expanded. -func (k *Kong) LoadConfig(path string) (Resolver, error) { - var err error - path = ExpandPath(path) - path, err = interpolate(path, k.vars, nil) - if err != nil { - return nil, err - } - r, err := os.Open(path) // nolint: gas - if err != nil { - return nil, err - } - defer r.Close() - - return k.loader(r) -} - -func catch(err *error) { - msg := recover() - if test, ok := msg.(Error); ok { - *err = test - } else if msg != nil { - panic(msg) - } -} diff --git a/vendor/github.com/alecthomas/kong/kong.png b/vendor/github.com/alecthomas/kong/kong.png deleted file mode 100644 index 151fb08d..00000000 Binary files a/vendor/github.com/alecthomas/kong/kong.png and /dev/null differ diff --git a/vendor/github.com/alecthomas/kong/kong.sketch b/vendor/github.com/alecthomas/kong/kong.sketch deleted file mode 100644 index 38816d5f..00000000 Binary files a/vendor/github.com/alecthomas/kong/kong.sketch and /dev/null differ diff --git a/vendor/github.com/alecthomas/kong/levenshtein.go b/vendor/github.com/alecthomas/kong/levenshtein.go deleted file mode 100644 index 1816f301..00000000 --- a/vendor/github.com/alecthomas/kong/levenshtein.go +++ /dev/null @@ -1,39 +0,0 @@ -package kong - -import "unicode/utf8" - -// https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Go -// License: https://creativecommons.org/licenses/by-sa/3.0/ -func levenshtein(a, b string) int { - f := make([]int, utf8.RuneCountInString(b)+1) - - for j := range f { - f[j] = j - } - - for _, ca := range a { - j := 1 - fj1 := f[0] // fj1 is the value of f[j - 1] in last iteration - f[0]++ - for _, cb := range b { - mn := min(f[j]+1, f[j-1]+1) // delete & insert - if cb != ca { - mn = min(mn, fj1+1) // change - } else { - mn = min(mn, fj1) // matched - } - - fj1, f[j] = f[j], mn // save f[j] to fj1(j is about to increase), update f[j] to mn - j++ - } - } - - return f[len(f)-1] -} - -func min(a, b int) int { - if a <= b { - return a - } - return b -} diff --git a/vendor/github.com/alecthomas/kong/mapper.go b/vendor/github.com/alecthomas/kong/mapper.go deleted file mode 100644 index 183ec09b..00000000 --- a/vendor/github.com/alecthomas/kong/mapper.go +++ /dev/null @@ -1,798 +0,0 @@ -package kong - -import ( - "encoding" - "encoding/json" - "fmt" - "io/ioutil" - "math/bits" - "net/url" - "os" - "reflect" - "strconv" - "strings" - "time" - - "github.com/pkg/errors" -) - -var ( - mapperValueType = reflect.TypeOf((*MapperValue)(nil)).Elem() - boolMapperType = reflect.TypeOf((*BoolMapper)(nil)).Elem() - jsonUnmarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() - textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() - binaryUnmarshalerType = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem() -) - -// DecodeContext is passed to a Mapper's Decode(). -// -// It contains the Value being decoded into and the Scanner to parse from. -type DecodeContext struct { - // Value being decoded into. - Value *Value - // Scan contains the input to scan into Target. - Scan *Scanner -} - -// WithScanner creates a clone of this context with a new Scanner. -func (r *DecodeContext) WithScanner(scan *Scanner) *DecodeContext { - return &DecodeContext{ - Value: r.Value, - Scan: scan, - } -} - -// MapperValue may be implemented by fields in order to provide custom mapping. -type MapperValue interface { - Decode(ctx *DecodeContext) error -} - -type mapperValueAdapter struct { - isBool bool -} - -func (m *mapperValueAdapter) Decode(ctx *DecodeContext, target reflect.Value) error { - if target.Type().Implements(mapperValueType) { - return target.Interface().(MapperValue).Decode(ctx) - } - return target.Addr().Interface().(MapperValue).Decode(ctx) -} - -func (m *mapperValueAdapter) IsBool() bool { - return m.isBool -} - -type textUnmarshalerAdapter struct{} - -func (m *textUnmarshalerAdapter) Decode(ctx *DecodeContext, target reflect.Value) error { - var value string - err := ctx.Scan.PopValueInto("value", &value) - if err != nil { - return err - } - if target.Type().Implements(textUnmarshalerType) { - return target.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)) - } - return target.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)) -} - -type binaryUnmarshalerAdapter struct{} - -func (m *binaryUnmarshalerAdapter) Decode(ctx *DecodeContext, target reflect.Value) error { - var value string - err := ctx.Scan.PopValueInto("value", &value) - if err != nil { - return err - } - if target.Type().Implements(textUnmarshalerType) { - return target.Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary([]byte(value)) - } - return target.Addr().Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary([]byte(value)) -} - -type jsonUnmarshalerAdapter struct{} - -func (j *jsonUnmarshalerAdapter) Decode(ctx *DecodeContext, target reflect.Value) error { - var value string - err := ctx.Scan.PopValueInto("value", &value) - if err != nil { - return err - } - if target.Type().Implements(jsonUnmarshalerType) { - return target.Interface().(json.Unmarshaler).UnmarshalJSON([]byte(value)) - } - return target.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(value)) -} - -// A Mapper represents how a field is mapped from command-line values to Go. -// -// Mappers can be associated with concrete fields via pointer, reflect.Type, reflect.Kind, or via a "type" tag. -// -// Additionally, if a type implements the MapperValue interface, it will be used. -type Mapper interface { - // Decode ctx.Value with ctx.Scanner into target. - Decode(ctx *DecodeContext, target reflect.Value) error -} - -// A BoolMapper is a Mapper to a value that is a boolean. -// -// This is used solely for formatting help. -type BoolMapper interface { - IsBool() bool -} - -// A MapperFunc is a single function that complies with the Mapper interface. -type MapperFunc func(ctx *DecodeContext, target reflect.Value) error - -func (m MapperFunc) Decode(ctx *DecodeContext, target reflect.Value) error { // nolint: golint - return m(ctx, target) -} - -// A Registry contains a set of mappers and supporting lookup methods. -type Registry struct { - names map[string]Mapper - types map[reflect.Type]Mapper - kinds map[reflect.Kind]Mapper - values map[reflect.Value]Mapper -} - -// NewRegistry creates a new (empty) Registry. -func NewRegistry() *Registry { - return &Registry{ - names: map[string]Mapper{}, - types: map[reflect.Type]Mapper{}, - kinds: map[reflect.Kind]Mapper{}, - values: map[reflect.Value]Mapper{}, - } -} - -// ForNamedValue finds a mapper for a value with a user-specified name. -// -// Will return nil if a mapper can not be determined. -func (r *Registry) ForNamedValue(name string, value reflect.Value) Mapper { - if mapper, ok := r.names[name]; ok { - return mapper - } - return r.ForValue(value) -} - -// ForValue looks up the Mapper for a reflect.Value. -func (r *Registry) ForValue(value reflect.Value) Mapper { - if mapper, ok := r.values[value]; ok { - return mapper - } - return r.ForType(value.Type()) -} - -// ForNamedType finds a mapper for a type with a user-specified name. -// -// Will return nil if a mapper can not be determined. -func (r *Registry) ForNamedType(name string, typ reflect.Type) Mapper { - if mapper, ok := r.names[name]; ok { - return mapper - } - return r.ForType(typ) -} - -// ForType finds a mapper from a type, by type, then kind. -// -// Will return nil if a mapper can not be determined. -func (r *Registry) ForType(typ reflect.Type) Mapper { - // Check if the type implements MapperValue. - for _, impl := range []reflect.Type{typ, reflect.PtrTo(typ)} { - if impl.Implements(mapperValueType) { - return &mapperValueAdapter{impl.Implements(boolMapperType)} - } - } - // Next, try explicitly registered types. - var mapper Mapper - var ok bool - if mapper, ok = r.types[typ]; ok { - return mapper - } - // Next try stdlib unmarshaler interfaces. - for _, impl := range []reflect.Type{typ, reflect.PtrTo(typ)} { - switch { - case impl.Implements(textUnmarshalerType): - return &textUnmarshalerAdapter{} - case impl.Implements(binaryUnmarshalerType): - return &binaryUnmarshalerAdapter{} - case impl.Implements(jsonUnmarshalerType): - return &jsonUnmarshalerAdapter{} - } - } - // Finally try registered kinds. - if mapper, ok = r.kinds[typ.Kind()]; ok { - return mapper - } - return nil -} - -// RegisterKind registers a Mapper for a reflect.Kind. -func (r *Registry) RegisterKind(kind reflect.Kind, mapper Mapper) *Registry { - r.kinds[kind] = mapper - return r -} - -// RegisterName registers a mapper to be used if the value mapper has a "type" tag matching name. -// -// eg. -// -// Mapper string `kong:"type='colour'` -// registry.RegisterName("colour", ...) -func (r *Registry) RegisterName(name string, mapper Mapper) *Registry { - r.names[name] = mapper - return r -} - -// RegisterType registers a Mapper for a reflect.Type. -func (r *Registry) RegisterType(typ reflect.Type, mapper Mapper) *Registry { - r.types[typ] = mapper - return r -} - -// RegisterValue registers a Mapper by pointer to the field value. -func (r *Registry) RegisterValue(ptr interface{}, mapper Mapper) *Registry { - key := reflect.ValueOf(ptr) - if key.Kind() != reflect.Ptr { - panic("expected a pointer") - } - key = key.Elem() - r.values[key] = mapper - return r -} - -// RegisterDefaults registers Mappers for all builtin supported Go types and some common stdlib types. -func (r *Registry) RegisterDefaults() *Registry { - return r.RegisterKind(reflect.Int, intDecoder(bits.UintSize)). - RegisterKind(reflect.Int8, intDecoder(8)). - RegisterKind(reflect.Int16, intDecoder(16)). - RegisterKind(reflect.Int32, intDecoder(32)). - RegisterKind(reflect.Int64, intDecoder(64)). - RegisterKind(reflect.Uint, uintDecoder(bits.UintSize)). - RegisterKind(reflect.Uint8, uintDecoder(8)). - RegisterKind(reflect.Uint16, uintDecoder(16)). - RegisterKind(reflect.Uint32, uintDecoder(32)). - RegisterKind(reflect.Uint64, uintDecoder(64)). - RegisterKind(reflect.Float32, floatDecoder(32)). - RegisterKind(reflect.Float64, floatDecoder(64)). - RegisterKind(reflect.String, MapperFunc(func(ctx *DecodeContext, target reflect.Value) error { - err := ctx.Scan.PopValueInto("string", target.Addr().Interface()) - return err - })). - RegisterKind(reflect.Bool, boolMapper{}). - RegisterKind(reflect.Slice, sliceDecoder(r)). - RegisterKind(reflect.Map, mapDecoder(r)). - RegisterType(reflect.TypeOf(time.Time{}), timeDecoder()). - RegisterType(reflect.TypeOf(time.Duration(0)), durationDecoder()). - RegisterType(reflect.TypeOf(&url.URL{}), urlMapper()). - RegisterType(reflect.TypeOf(&os.File{}), fileMapper(r)). - RegisterName("path", pathMapper(r)). - RegisterName("existingfile", existingFileMapper(r)). - RegisterName("existingdir", existingDirMapper(r)). - RegisterName("counter", counterMapper()) -} - -type boolMapper struct{} - -func (boolMapper) Decode(ctx *DecodeContext, target reflect.Value) error { - if ctx.Scan.Peek().Type == FlagValueToken { - token := ctx.Scan.Pop() - switch v := token.Value.(type) { - case string: - v = strings.ToLower(v) - switch v { - case "true", "1", "yes": - target.SetBool(true) - - case "false", "0", "no": - target.SetBool(false) - - default: - return errors.Errorf("bool value must be true, 1, yes, false, 0 or no but got %q", v) - } - - case bool: - target.SetBool(v) - - default: - return errors.Errorf("expected bool but got %q (%T)", token.Value, token.Value) - } - } else { - target.SetBool(true) - } - return nil -} -func (boolMapper) IsBool() bool { return true } - -func durationDecoder() MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - var value string - if err := ctx.Scan.PopValueInto("duration", &value); err != nil { - return err - } - r, err := time.ParseDuration(value) - if err != nil { - return errors.Errorf("expected duration but got %q: %s", value, err) - } - target.Set(reflect.ValueOf(r)) - return nil - } -} - -func timeDecoder() MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - format := time.RFC3339 - if ctx.Value.Format != "" { - format = ctx.Value.Format - } - var value string - if err := ctx.Scan.PopValueInto("time", &value); err != nil { - return err - } - t, err := time.Parse(format, value) - if err != nil { - return err - } - target.Set(reflect.ValueOf(t)) - return nil - } -} - -func intDecoder(bits int) MapperFunc { // nolint: dupl - return func(ctx *DecodeContext, target reflect.Value) error { - t, err := ctx.Scan.PopValue("int") - if err != nil { - return err - } - var sv string - switch v := t.Value.(type) { - case string: - sv = v - - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64: - sv = fmt.Sprintf("%v", v) - - default: - return errors.Errorf("expected an int but got %q (%T)", t, t.Value) - } - n, err := strconv.ParseInt(sv, 10, bits) - if err != nil { - return errors.Errorf("expected a valid %d bit int but got %q", bits, sv) - } - target.SetInt(n) - return nil - } -} - -func uintDecoder(bits int) MapperFunc { // nolint: dupl - return func(ctx *DecodeContext, target reflect.Value) error { - t, err := ctx.Scan.PopValue("uint") - if err != nil { - return err - } - var sv string - switch v := t.Value.(type) { - case string: - sv = v - - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64: - sv = fmt.Sprintf("%v", v) - - default: - return errors.Errorf("expected an int but got %q (%T)", t, t.Value) - } - n, err := strconv.ParseUint(sv, 10, bits) - if err != nil { - return errors.Errorf("expected a valid %d bit uint but got %q", bits, sv) - } - target.SetUint(n) - return nil - } -} - -func floatDecoder(bits int) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - t, err := ctx.Scan.PopValue("float") - if err != nil { - return err - } - switch v := t.Value.(type) { - case string: - n, err := strconv.ParseFloat(v, bits) - if err != nil { - return errors.Errorf("expected a float but got %q (%T)", t, t.Value) - } - target.SetFloat(n) - - case float32: - target.SetFloat(float64(v)) - - case float64: - target.SetFloat(v) - - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: - target.Set(reflect.ValueOf(v)) - - default: - return errors.Errorf("expected an int but got %q (%T)", t, t.Value) - } - return nil - } -} - -func mapDecoder(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if target.IsNil() { - target.Set(reflect.MakeMap(target.Type())) - } - el := target.Type() - sep := ctx.Value.Tag.MapSep - var childScanner *Scanner - if ctx.Value.Flag != nil { - t := ctx.Scan.Pop() - // If decoding a flag, we need an argument. - if t.IsEOL() { - return errors.Errorf("unexpected EOL") - } - switch v := t.Value.(type) { - case string: - childScanner = Scan(SplitEscaped(v, sep)...) - - case []map[string]interface{}: - for _, m := range v { - err := jsonTranscode(m, target.Addr().Interface()) - if err != nil { - return errors.WithStack(err) - } - } - return nil - - case map[string]interface{}: - return jsonTranscode(v, target.Addr().Interface()) - - default: - return errors.Errorf("invalid map value %q (of type %T)", t, t.Value) - } - } else { - tokens := ctx.Scan.PopWhile(func(t Token) bool { return t.IsValue() }) - childScanner = ScanFromTokens(tokens...) - } - for !childScanner.Peek().IsEOL() { - var token string - err := childScanner.PopValueInto("map", &token) - if err != nil { - return err - } - parts := strings.SplitN(token, "=", 2) - if len(parts) != 2 { - return errors.Errorf("expected \"=\" but got %q", token) - } - key, value := parts[0], parts[1] - - keyTypeName, valueTypeName := "", "" - if typ := ctx.Value.Tag.Type; typ != "" { - parts := strings.Split(typ, ":") - if len(parts) != 2 { - return errors.Errorf("type:\"\" on map field must be in the form \"[]:[]\"") - } - keyTypeName, valueTypeName = parts[0], parts[1] - } - - keyScanner := Scan(key) - keyDecoder := r.ForNamedType(keyTypeName, el.Key()) - keyValue := reflect.New(el.Key()).Elem() - if err := keyDecoder.Decode(ctx.WithScanner(keyScanner), keyValue); err != nil { - return errors.Errorf("invalid map key %q", key) - } - - valueScanner := Scan(value) - valueDecoder := r.ForNamedType(valueTypeName, el.Elem()) - valueValue := reflect.New(el.Elem()).Elem() - if err := valueDecoder.Decode(ctx.WithScanner(valueScanner), valueValue); err != nil { - return errors.Errorf("invalid map value %q", value) - } - - target.SetMapIndex(keyValue, valueValue) - } - return nil - } -} - -func sliceDecoder(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - el := target.Type().Elem() - sep := ctx.Value.Tag.Sep - var childScanner *Scanner - if ctx.Value.Flag != nil { - t := ctx.Scan.Pop() - // If decoding a flag, we need an argument. - if t.IsEOL() { - return errors.Errorf("unexpected EOL") - } - switch v := t.Value.(type) { - case string: - childScanner = Scan(SplitEscaped(v, sep)...) - - case []interface{}: - return jsonTranscode(v, target.Addr().Interface()) - - default: - v = []interface{}{v} - return jsonTranscode(v, target.Addr().Interface()) - } - } else { - tokens := ctx.Scan.PopWhile(func(t Token) bool { return t.IsValue() }) - childScanner = ScanFromTokens(tokens...) - } - childDecoder := r.ForNamedType(ctx.Value.Tag.Type, el) - if childDecoder == nil { - return errors.Errorf("no mapper for element type of %s", target.Type()) - } - for !childScanner.Peek().IsEOL() { - childValue := reflect.New(el).Elem() - err := childDecoder.Decode(ctx.WithScanner(childScanner), childValue) - if err != nil { - return errors.WithStack(err) - } - target.Set(reflect.Append(target, childValue)) - } - return nil - } -} - -func pathMapper(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if target.Kind() == reflect.Slice { - return sliceDecoder(r)(ctx, target) - } - if target.Kind() != reflect.String { - return errors.Errorf("\"path\" type must be applied to a string not %s", target.Type()) - } - var path string - err := ctx.Scan.PopValueInto("file", &path) - if err != nil { - return err - } - path = ExpandPath(path) - target.SetString(path) - return nil - } -} - -func fileMapper(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if target.Kind() == reflect.Slice { - return sliceDecoder(r)(ctx, target) - } - var path string - err := ctx.Scan.PopValueInto("file", &path) - if err != nil { - return err - } - var file *os.File - if path == "-" { - file = os.Stdin - } else { - path = ExpandPath(path) - file, err = os.Open(path) // nolint: gosec - if err != nil { - return err - } - } - target.Set(reflect.ValueOf(file)) - return nil - } -} - -func existingFileMapper(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if target.Kind() == reflect.Slice { - return sliceDecoder(r)(ctx, target) - } - if target.Kind() != reflect.String { - return errors.Errorf("\"existingfile\" type must be applied to a string not %s", target.Type()) - } - var path string - err := ctx.Scan.PopValueInto("file", &path) - if err != nil { - return err - } - if path != "-" { - path = ExpandPath(path) - stat, err := os.Stat(path) - if err != nil { - return err - } - if stat.IsDir() { - return errors.Errorf("%q exists but is a directory", path) - } - } - target.SetString(path) - return nil - } -} - -func existingDirMapper(r *Registry) MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if target.Kind() == reflect.Slice { - return sliceDecoder(r)(ctx, target) - } - if target.Kind() != reflect.String { - return errors.Errorf("\"existingdir\" must be applied to a string not %s", target.Type()) - } - var path string - err := ctx.Scan.PopValueInto("file", &path) - if err != nil { - return err - } - path = ExpandPath(path) - stat, err := os.Stat(path) - if err != nil { - return err - } - if !stat.IsDir() { - return errors.Errorf("%q exists but is not a directory", path) - } - target.SetString(path) - return nil - } -} - -func counterMapper() MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - if ctx.Scan.Peek().Type == FlagValueToken { - t, err := ctx.Scan.PopValue("counter") - if err != nil { - return err - } - switch v := t.Value.(type) { - case string: - n, err := strconv.ParseInt(v, 10, 64) - if err != nil { - return errors.Errorf("expected a counter but got %q (%T)", t, t.Value) - } - target.SetInt(n) - - case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: - target.Set(reflect.ValueOf(v)) - - default: - return errors.Errorf("expected a counter but got %q (%T)", t, t.Value) - } - return nil - } - - switch target.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - target.SetInt(target.Int() + 1) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - target.SetUint(target.Uint() + 1) - - case reflect.Float32, reflect.Float64: - target.SetFloat(target.Float() + 1) - - default: - return errors.Errorf("type:\"counter\" must be used with a numeric field") - } - return nil - } -} - -func urlMapper() MapperFunc { - return func(ctx *DecodeContext, target reflect.Value) error { - var urlStr string - err := ctx.Scan.PopValueInto("url", &urlStr) - if err != nil { - return err - } - url, err := url.Parse(urlStr) - if err != nil { - return errors.WithStack(err) - } - target.Set(reflect.ValueOf(url)) - return nil - } -} - -// SplitEscaped splits a string on a separator. -// -// It differs from strings.Split() in that the separator can exist in a field by escaping it with a \. eg. -// -// SplitEscaped(`hello\,there,bob`, ',') == []string{"hello,there", "bob"} -func SplitEscaped(s string, sep rune) (out []string) { - if sep == -1 { - return []string{s} - } - escaped := false - token := "" - for _, ch := range s { - switch { - case escaped: - token += string(ch) - escaped = false - case ch == '\\': - escaped = true - case ch == sep && !escaped: - out = append(out, token) - token = "" - escaped = false - default: - token += string(ch) - } - } - if token != "" { - out = append(out, token) - } - return -} - -// JoinEscaped joins a slice of strings on sep, but also escapes any instances of sep in the fields with \. eg. -// -// JoinEscaped([]string{"hello,there", "bob"}, ',') == `hello\,there,bob` -func JoinEscaped(s []string, sep rune) string { - escaped := []string{} - for _, e := range s { - escaped = append(escaped, strings.Replace(e, string(sep), `\`+string(sep), -1)) - } - return strings.Join(escaped, string(sep)) -} - -// NamedFileContentFlag is a flag value that loads a file's contents and filename into its value. -type NamedFileContentFlag struct { - Filename string - Contents []byte -} - -func (f *NamedFileContentFlag) Decode(ctx *DecodeContext) error { // nolint: golint - var filename string - err := ctx.Scan.PopValueInto("filename", &filename) - if err != nil { - return err - } - // This allows unsetting of file content flags. - if filename == "" { - *f = NamedFileContentFlag{} - return nil - } - filename = ExpandPath(filename) - data, err := ioutil.ReadFile(filename) // nolint: gosec - if err != nil { - return errors.Errorf("failed to open %q: %s", filename, err) - } - f.Contents = data - f.Filename = filename - return nil -} - -// FileContentFlag is a flag value that loads a file's contents into its value. -type FileContentFlag []byte - -func (f *FileContentFlag) Decode(ctx *DecodeContext) error { // nolint: golint - var filename string - err := ctx.Scan.PopValueInto("filename", &filename) - if err != nil { - return err - } - // This allows unsetting of file content flags. - if filename == "" { - *f = nil - return nil - } - filename = ExpandPath(filename) - data, err := ioutil.ReadFile(filename) // nolint: gosec - if err != nil { - return errors.Errorf("failed to open %q: %s", filename, err) - } - *f = data - return nil -} - -func jsonTranscode(in, out interface{}) error { - data, err := json.Marshal(in) - if err != nil { - return errors.WithStack(err) - } - return errors.Wrapf(json.Unmarshal(data, out), "%#v -> %T", in, out) -} diff --git a/vendor/github.com/alecthomas/kong/model.go b/vendor/github.com/alecthomas/kong/model.go deleted file mode 100644 index c64cab3e..00000000 --- a/vendor/github.com/alecthomas/kong/model.go +++ /dev/null @@ -1,457 +0,0 @@ -package kong - -import ( - "fmt" - "math" - "os" - "reflect" - "strconv" - "strings" - - "github.com/pkg/errors" -) - -// A Visitable component in the model. -type Visitable interface { - node() -} - -// Application is the root of the Kong model. -type Application struct { - *Node - // Help flag, if the NoDefaultHelp() option is not specified. - HelpFlag *Flag -} - -// Argument represents a branching positional argument. -type Argument = Node - -// Command represents a command in the CLI. -type Command = Node - -// NodeType is an enum representing the type of a Node. -type NodeType int - -// Node type enumerations. -const ( - ApplicationNode NodeType = iota - CommandNode - ArgumentNode -) - -// Node is a branch in the CLI. ie. a command or positional argument. -type Node struct { - Type NodeType - Parent *Node - Name string - Help string // Short help displayed in summaries. - Detail string // Detailed help displayed when describing command/arg alone. - Group *Group - Hidden bool - Flags []*Flag - Positional []*Positional - Children []*Node - Target reflect.Value // Pointer to the value in the grammar that this Node is associated with. - Tag *Tag - Aliases []string - - Argument *Value // Populated when Type is ArgumentNode. -} - -func (*Node) node() {} - -// Leaf returns true if this Node is a leaf node. -func (n *Node) Leaf() bool { - return len(n.Children) == 0 -} - -// Find a command/argument/flag by pointer to its field. -// -// Returns nil if not found. Panics if ptr is not a pointer. -func (n *Node) Find(ptr interface{}) *Node { - key := reflect.ValueOf(ptr) - if key.Kind() != reflect.Ptr { - panic("expected a pointer") - } - return n.findNode(key) -} - -func (n *Node) findNode(key reflect.Value) *Node { - if n.Target == key { - return n - } - for _, child := range n.Children { - if found := child.findNode(key); found != nil { - return found - } - } - return nil -} - -// AllFlags returns flags from all ancestor branches encountered. -// -// If "hide" is true hidden flags will be omitted. -func (n *Node) AllFlags(hide bool) (out [][]*Flag) { - if n.Parent != nil { - out = append(out, n.Parent.AllFlags(hide)...) - } - group := []*Flag{} - for _, flag := range n.Flags { - if !hide || !flag.Hidden { - group = append(group, flag) - } - } - if len(group) > 0 { - out = append(out, group) - } - return -} - -// Leaves returns the leaf commands/arguments under Node. -// -// If "hidden" is true hidden leaves will be omitted. -func (n *Node) Leaves(hide bool) (out []*Node) { - _ = Visit(n, func(nd Visitable, next Next) error { - if nd == n { - return next(nil) - } - if node, ok := nd.(*Node); ok { - if hide && node.Hidden { - return nil - } - if len(node.Children) == 0 && node.Type != ApplicationNode { - out = append(out, node) - } - } - return next(nil) - }) - return -} - -// Depth of the command from the application root. -func (n *Node) Depth() int { - depth := 0 - p := n.Parent - for p != nil && p.Type != ApplicationNode { - depth++ - p = p.Parent - } - return depth -} - -// Summary help string for the node (not including application name). -func (n *Node) Summary() string { - summary := n.Path() - if flags := n.FlagSummary(true); flags != "" { - summary += " " + flags - } - args := []string{} - for _, arg := range n.Positional { - args = append(args, arg.Summary()) - } - if len(args) != 0 { - summary += " " + strings.Join(args, " ") - } else if len(n.Children) > 0 { - summary += " " - } - return summary -} - -// FlagSummary for the node. -func (n *Node) FlagSummary(hide bool) string { - required := []string{} - count := 0 - for _, group := range n.AllFlags(hide) { - for _, flag := range group { - count++ - if flag.Required { - required = append(required, flag.Summary()) - } - } - } - return strings.Join(required, " ") -} - -// FullPath is like Path() but includes the Application root node. -func (n *Node) FullPath() string { - root := n - for root.Parent != nil { - root = root.Parent - } - return strings.TrimSpace(root.Name + " " + n.Path()) -} - -// Vars returns the combined Vars defined by all ancestors of this Node. -func (n *Node) Vars() Vars { - if n == nil { - return Vars{} - } - return n.Parent.Vars().CloneWith(n.Tag.Vars) -} - -// Path through ancestors to this Node. -func (n *Node) Path() (out string) { - if n.Parent != nil { - out += " " + n.Parent.Path() - } - switch n.Type { - case CommandNode: - out += " " + n.Name - case ArgumentNode: - out += " " + "<" + n.Name + ">" - } - return strings.TrimSpace(out) -} - -// ClosestGroup finds the first non-nil group in this node and its ancestors. -func (n *Node) ClosestGroup() *Group { - switch { - case n.Group != nil: - return n.Group - case n.Parent != nil: - return n.Parent.ClosestGroup() - default: - return nil - } -} - -// A Value is either a flag or a variable positional argument. -type Value struct { - Flag *Flag // Nil if positional argument. - Name string - Help string - Default string - DefaultValue reflect.Value - Enum string - Mapper Mapper - Tag *Tag - Target reflect.Value - Required bool - Set bool // Set to true when this value is set through some mechanism. - Format string // Formatting directive, if applicable. - Position int // Position (for positional arguments). -} - -// EnumMap returns a map of the enums in this value. -func (v *Value) EnumMap() map[string]bool { - parts := strings.Split(v.Enum, ",") - out := make(map[string]bool, len(parts)) - for _, part := range parts { - out[strings.TrimSpace(part)] = true - } - return out -} - -// ShortSummary returns a human-readable summary of the value, not including any placeholders/defaults. -func (v *Value) ShortSummary() string { - if v.Flag != nil { - return fmt.Sprintf("--%s", v.Name) - } - argText := "<" + v.Name + ">" - if v.IsCumulative() { - argText += " ..." - } - if !v.Required { - argText = "[" + argText + "]" - } - return argText -} - -// Summary returns a human-readable summary of the value. -func (v *Value) Summary() string { - if v.Flag != nil { - if v.IsBool() { - return fmt.Sprintf("--%s", v.Name) - } - return fmt.Sprintf("--%s=%s", v.Name, v.Flag.FormatPlaceHolder()) - } - argText := "<" + v.Name + ">" - if v.IsCumulative() { - argText += " ..." - } - if !v.Required { - argText = "[" + argText + "]" - } - return argText -} - -// IsCumulative returns true if the type can be accumulated into. -func (v *Value) IsCumulative() bool { - return v.IsSlice() || v.IsMap() -} - -// IsSlice returns true if the value is a slice. -func (v *Value) IsSlice() bool { - return v.Target.Type().Name() == "" && v.Target.Kind() == reflect.Slice -} - -// IsMap returns true if the value is a map. -func (v *Value) IsMap() bool { - return v.Target.Kind() == reflect.Map -} - -// IsBool returns true if the underlying value is a boolean. -func (v *Value) IsBool() bool { - if m, ok := v.Mapper.(BoolMapper); ok && m.IsBool() { - return true - } - return v.Target.Kind() == reflect.Bool -} - -// Parse tokens into value, parse, and validate, but do not write to the field. -func (v *Value) Parse(scan *Scanner, target reflect.Value) (err error) { - defer func() { - if rerr := recover(); rerr != nil { - switch rerr := rerr.(type) { - case Error: - err = errors.Wrap(rerr, v.ShortSummary()) - default: - panic(fmt.Sprintf("mapper %T failed to apply to %s: %s", v.Mapper, v.Summary(), rerr)) - } - } - }() - err = v.Mapper.Decode(&DecodeContext{Value: v, Scan: scan}, target) - if err != nil { - return errors.Wrap(err, v.ShortSummary()) - } - v.Set = true - return nil -} - -// Apply value to field. -func (v *Value) Apply(value reflect.Value) { - v.Target.Set(value) - v.Set = true -} - -// ApplyDefault value to field if it is not already set. -func (v *Value) ApplyDefault() error { - if reflectValueIsZero(v.Target) { - return v.Reset() - } - v.Set = true - return nil -} - -// Reset this value to its default, either the zero value or the parsed result of its envar, -// or its "default" tag. -// -// Does not include resolvers. -func (v *Value) Reset() error { - v.Target.Set(reflect.Zero(v.Target.Type())) - if v.Tag.Env != "" { - envar := os.Getenv(v.Tag.Env) - if envar != "" { - err := v.Parse(ScanFromTokens(Token{Type: FlagValueToken, Value: envar}), v.Target) - if err != nil { - return fmt.Errorf("%s (from envar %s=%q)", err, v.Tag.Env, envar) - } - return nil - } - } - if v.Default != "" { - return v.Parse(ScanFromTokens(Token{Type: FlagValueToken, Value: v.Default}), v.Target) - } - return nil -} - -func (*Value) node() {} - -// A Positional represents a non-branching command-line positional argument. -type Positional = Value - -// A Flag represents a command-line flag. -type Flag struct { - *Value - Group *Group // Logical grouping when displaying. May also be used by configuration loaders to group options logically. - Xor string - PlaceHolder string - Env string - Short rune - Hidden bool -} - -func (f *Flag) String() string { - out := "--" + f.Name - if f.Short != 0 { - out = fmt.Sprintf("-%c, %s", f.Short, out) - } - if !f.IsBool() { - out += "=" + f.FormatPlaceHolder() - } - return out -} - -// FormatPlaceHolder formats the placeholder string for a Flag. -func (f *Flag) FormatPlaceHolder() string { - tail := "" - if f.Value.IsSlice() && f.Value.Tag.Sep != -1 { - tail += string(f.Value.Tag.Sep) + "..." - } - if f.Default != "" { - if f.Value.Target.Kind() == reflect.String { - return strconv.Quote(f.Default) + tail - } - return f.Default + tail - } - if f.PlaceHolder != "" { - return f.PlaceHolder + tail - } - if f.Value.IsMap() { - if f.Value.Tag.MapSep != -1 { - tail = string(f.Value.Tag.MapSep) + "..." - } - return "KEY=VALUE" + tail - } - return strings.ToUpper(f.Name) + tail -} - -// Group holds metadata about a command or flag group used when printing help. -type Group struct { - // Key is the `group` field tag value used to identify this group. - Key string - // Title is displayed above the grouped items. - Title string - // Description is optional and displayed under the Title when non empty. - // It can be used to introduce the group's purpose to the user. - Description string -} - -// This is directly from the Go 1.13 source code. -func reflectValueIsZero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return math.Float64bits(v.Float()) == 0 - case reflect.Complex64, reflect.Complex128: - c := v.Complex() - return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0 - case reflect.Array: - for i := 0; i < v.Len(); i++ { - if !reflectValueIsZero(v.Index(i)) { - return false - } - } - return true - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer: - return v.IsNil() - case reflect.String: - return v.Len() == 0 - case reflect.Struct: - for i := 0; i < v.NumField(); i++ { - if !reflectValueIsZero(v.Field(i)) { - return false - } - } - return true - default: - // This should never happens, but will act as a safeguard for - // later, as a default value doesn't makes sense here. - panic(&reflect.ValueError{"reflect.Value.IsZero", v.Kind()}) - } -} diff --git a/vendor/github.com/alecthomas/kong/options.go b/vendor/github.com/alecthomas/kong/options.go deleted file mode 100644 index bdb57f63..00000000 --- a/vendor/github.com/alecthomas/kong/options.go +++ /dev/null @@ -1,323 +0,0 @@ -package kong - -import ( - "io" - "os" - "os/user" - "path/filepath" - "reflect" - "strings" - - "github.com/pkg/errors" -) - -// An Option applies optional changes to the Kong application. -type Option interface { - Apply(k *Kong) error -} - -// OptionFunc is function that adheres to the Option interface. -type OptionFunc func(k *Kong) error - -func (o OptionFunc) Apply(k *Kong) error { return o(k) } // nolint: golint - -// Vars sets the variables to use for interpolation into help strings and default values. -// -// See README for details. -type Vars map[string]string - -// Apply lets Vars act as an Option. -func (v Vars) Apply(k *Kong) error { - for key, value := range v { - k.vars[key] = value - } - return nil -} - -// CloneWith clones the current Vars and merges "vars" onto the clone. -func (v Vars) CloneWith(vars Vars) Vars { - out := make(Vars, len(v)+len(vars)) - for key, value := range v { - out[key] = value - } - for key, value := range vars { - out[key] = value - } - return out -} - -// Exit overrides the function used to terminate. This is useful for testing or interactive use. -func Exit(exit func(int)) Option { - return OptionFunc(func(k *Kong) error { - k.Exit = exit - return nil - }) -} - -// NoDefaultHelp disables the default help flags. -func NoDefaultHelp() Option { - return OptionFunc(func(k *Kong) error { - k.noDefaultHelp = true - return nil - }) -} - -// PostBuild provides read/write access to kong.Kong after initial construction of the model is complete but before -// parsing occurs. -// -// This is useful for, e.g., adding short options to flags, updating help, etc. -func PostBuild(fn func(*Kong) error) Option { - return OptionFunc(func(k *Kong) error { - k.postBuildOptions = append(k.postBuildOptions, OptionFunc(fn)) - return nil - }) -} - -// Name overrides the application name. -func Name(name string) Option { - return PostBuild(func(k *Kong) error { - k.Model.Name = name - return nil - }) -} - -// Description sets the application description. -func Description(description string) Option { - return PostBuild(func(k *Kong) error { - k.Model.Help = description - return nil - }) -} - -// TypeMapper registers a mapper to a type. -func TypeMapper(typ reflect.Type, mapper Mapper) Option { - return OptionFunc(func(k *Kong) error { - k.registry.RegisterType(typ, mapper) - return nil - }) -} - -// KindMapper registers a mapper to a kind. -func KindMapper(kind reflect.Kind, mapper Mapper) Option { - return OptionFunc(func(k *Kong) error { - k.registry.RegisterKind(kind, mapper) - return nil - }) -} - -// ValueMapper registers a mapper to a field value. -func ValueMapper(ptr interface{}, mapper Mapper) Option { - return OptionFunc(func(k *Kong) error { - k.registry.RegisterValue(ptr, mapper) - return nil - }) -} - -// NamedMapper registers a mapper to a name. -func NamedMapper(name string, mapper Mapper) Option { - return OptionFunc(func(k *Kong) error { - k.registry.RegisterName(name, mapper) - return nil - }) -} - -// Writers overrides the default writers. Useful for testing or interactive use. -func Writers(stdout, stderr io.Writer) Option { - return OptionFunc(func(k *Kong) error { - k.Stdout = stdout - k.Stderr = stderr - return nil - }) -} - -// Bind binds values for hooks and Run() function arguments. -// -// Any arguments passed will be available to the receiving hook functions, but may be omitted. Additionally, *Kong and -// the current *Context will also be made available. -// -// There are two hook points: -// -// BeforeApply(...) error -// AfterApply(...) error -// -// Called before validation/assignment, and immediately after validation/assignment, respectively. -func Bind(args ...interface{}) Option { - return OptionFunc(func(k *Kong) error { - k.bindings.add(args...) - return nil - }) -} - -// BindTo allows binding of implementations to interfaces. -// -// BindTo(impl, (*iface)(nil)) -func BindTo(impl, iface interface{}) Option { - return OptionFunc(func(k *Kong) error { - valueOf := reflect.ValueOf(impl) - k.bindings[reflect.TypeOf(iface).Elem()] = func() (reflect.Value, error) { return valueOf, nil } - return nil - }) -} - -// BindToProvider allows binding of provider functions. -// -// This is useful when the Run() function of different commands require different values that may -// not all be initialisable from the main() function. -func BindToProvider(provider interface{}) Option { - return OptionFunc(func(k *Kong) error { - pv := reflect.ValueOf(provider) - t := pv.Type() - if t.Kind() != reflect.Func || t.NumIn() != 0 || t.NumOut() != 2 || t.Out(1) != reflect.TypeOf((*error)(nil)).Elem() { - return errors.Errorf("%T must be a function with the signature func()(T, error)", provider) - } - rt := pv.Type().Out(0) - k.bindings[rt] = func() (reflect.Value, error) { - out := pv.Call(nil) - errv := out[1] - var err error - if !errv.IsNil() { - err = errv.Interface().(error) - } - return out[0], err - } - return nil - }) -} - -// Help printer to use. -func Help(help HelpPrinter) Option { - return OptionFunc(func(k *Kong) error { - k.help = help - return nil - }) -} - -// HelpFormatter configures how the help text is formatted. -func HelpFormatter(helpFormatter HelpValueFormatter) Option { - return OptionFunc(func(k *Kong) error { - k.helpFormatter = helpFormatter - return nil - }) -} - -// ConfigureHelp sets the HelpOptions to use for printing help. -func ConfigureHelp(options HelpOptions) Option { - return OptionFunc(func(k *Kong) error { - k.helpOptions = options - return nil - }) -} - -// Groups associates `group` field tags with group metadata. -// -// This option is used to simplify Kong tags while providing -// rich group information such as title and optional description. -// -// Each key in the "groups" map corresponds to the value of a -// `group` Kong tag, while the first line of the value will be -// the title, and subsequent lines if any will be the description of -// the group. -// -// See also ExplicitGroups for a more structured alternative. -type Groups map[string]string - -func (g Groups) Apply(k *Kong) error { // nolint: golint - for key, info := range g { - lines := strings.Split(info, "\n") - title := strings.TrimSpace(lines[0]) - description := "" - if len(lines) > 1 { - description = strings.TrimSpace(strings.Join(lines[1:], "\n")) - } - k.groups = append(k.groups, Group{ - Key: key, - Title: title, - Description: description, - }) - } - return nil -} - -// ExplicitGroups associates `group` field tags with their metadata. -// -// It can be used to provide a title or header to a command or flag group. -func ExplicitGroups(groups []Group) Option { - return OptionFunc(func(k *Kong) error { - k.groups = groups - return nil - }) -} - -// UsageOnError configures Kong to display context-sensitive usage if FatalIfErrorf is called with an error. -func UsageOnError() Option { - return OptionFunc(func(k *Kong) error { - k.usageOnError = true - return nil - }) -} - -// ClearResolvers clears all existing resolvers. -func ClearResolvers() Option { - return OptionFunc(func(k *Kong) error { - k.resolvers = nil - return nil - }) -} - -// Resolvers registers flag resolvers. -func Resolvers(resolvers ...Resolver) Option { - return OptionFunc(func(k *Kong) error { - k.resolvers = append(k.resolvers, resolvers...) - return nil - }) -} - -// ConfigurationLoader is a function that builds a resolver from a file. -type ConfigurationLoader func(r io.Reader) (Resolver, error) - -// Configuration provides Kong with support for loading defaults from a set of configuration files. -// -// Paths will be opened in order, and "loader" will be used to provide a Resolver which is registered with Kong. -// -// Note: The JSON function is a ConfigurationLoader. -// -// ~ and variable expansion will occur on the provided paths. -func Configuration(loader ConfigurationLoader, paths ...string) Option { - return OptionFunc(func(k *Kong) error { - k.loader = loader - for _, path := range paths { - if _, err := os.Stat(ExpandPath(path)); os.IsNotExist(err) { - continue - } - resolver, err := k.LoadConfig(path) - if err != nil { - return errors.Wrap(err, path) - } - if resolver != nil { - k.resolvers = append(k.resolvers, resolver) - } - } - return nil - }) -} - -// ExpandPath is a helper function to expand a relative or home-relative path to an absolute path. -// -// eg. ~/.someconf -> /home/alec/.someconf -func ExpandPath(path string) string { - if filepath.IsAbs(path) { - return path - } - if strings.HasPrefix(path, "~/") { - user, err := user.Current() - if err != nil { - return path - } - return filepath.Join(user.HomeDir, path[2:]) - } - abspath, err := filepath.Abs(path) - if err != nil { - return path - } - return abspath -} diff --git a/vendor/github.com/alecthomas/kong/resolver.go b/vendor/github.com/alecthomas/kong/resolver.go deleted file mode 100644 index 8ef764dd..00000000 --- a/vendor/github.com/alecthomas/kong/resolver.go +++ /dev/null @@ -1,49 +0,0 @@ -package kong - -import ( - "encoding/json" - "io" - "strings" -) - -// A Resolver resolves a Flag value from an external source. -type Resolver interface { - // Validate configuration against Application. - // - // This can be used to validate that all provided configuration is valid within this application. - Validate(app *Application) error - - // Resolve the value for a Flag. - Resolve(context *Context, parent *Path, flag *Flag) (interface{}, error) -} - -// ResolverFunc is a convenience type for non-validating Resolvers. -type ResolverFunc func(context *Context, parent *Path, flag *Flag) (interface{}, error) - -var _ Resolver = ResolverFunc(nil) - -func (r ResolverFunc) Resolve(context *Context, parent *Path, flag *Flag) (interface{}, error) { // nolint: golint - return r(context, parent, flag) -} -func (r ResolverFunc) Validate(app *Application) error { return nil } // nolint: golint - -// JSON returns a Resolver that retrieves values from a JSON source. -// -// Hyphens in flag names are replaced with underscores. -func JSON(r io.Reader) (Resolver, error) { - values := map[string]interface{}{} - err := json.NewDecoder(r).Decode(&values) - if err != nil { - return nil, err - } - var f ResolverFunc = func(context *Context, parent *Path, flag *Flag) (interface{}, error) { - name := strings.Replace(flag.Name, "-", "_", -1) - raw, ok := values[name] - if !ok { - return nil, nil - } - return raw, nil - } - - return f, nil -} diff --git a/vendor/github.com/alecthomas/kong/scanner.go b/vendor/github.com/alecthomas/kong/scanner.go deleted file mode 100644 index 11b78c38..00000000 --- a/vendor/github.com/alecthomas/kong/scanner.go +++ /dev/null @@ -1,217 +0,0 @@ -package kong - -import ( - "fmt" - "strings" -) - -// TokenType is the type of a token. -type TokenType int - -// Token types. -const ( - UntypedToken TokenType = iota - EOLToken - FlagToken // -- - FlagValueToken // = - ShortFlagToken // -[ - PositionalArgumentToken // -) - -func (t TokenType) String() string { - switch t { - case UntypedToken: - return "untyped" - case EOLToken: - return "" - case FlagToken: // -- - return "long flag" - case FlagValueToken: // = - return "flag value" - case ShortFlagToken: // -[ - return "short flag remainder" - case PositionalArgumentToken: // - return "positional argument" - } - panic("unsupported type") -} - -// Token created by Scanner. -type Token struct { - Value interface{} - Type TokenType -} - -func (t Token) String() string { - switch t.Type { - case FlagToken: - return fmt.Sprintf("--%v", t.Value) - - case ShortFlagToken: - return fmt.Sprintf("-%v", t.Value) - - case EOLToken: - return "EOL" - - default: - return fmt.Sprintf("%v", t.Value) - } -} - -// IsEOL returns true if this Token is past the end of the line. -func (t Token) IsEOL() bool { - return t.Type == EOLToken -} - -// IsAny returns true if the token's type is any of those provided. -func (t TokenType) IsAny(types ...TokenType) bool { - for _, typ := range types { - if t == typ { - return true - } - } - return false -} - -// InferredType tries to infer the type of a token. -func (t Token) InferredType() TokenType { - if t.Type != UntypedToken { - return t.Type - } - if v, ok := t.Value.(string); ok { - if strings.HasPrefix(v, "--") { // nolint: gocritic - return FlagToken - } else if v == "-" { - return PositionalArgumentToken - } else if strings.HasPrefix(v, "-") { - return ShortFlagToken - } - } - return t.Type -} - -// IsValue returns true if token is usable as a parseable value. -// -// A parseable value is either a value typed token, or an untyped token NOT starting with a hyphen. -func (t Token) IsValue() bool { - tt := t.InferredType() - return tt.IsAny(FlagValueToken, ShortFlagTailToken, PositionalArgumentToken) || - (tt == UntypedToken && !strings.HasPrefix(t.String(), "-")) -} - -// Scanner is a stack-based scanner over command-line tokens. -// -// Initially all tokens are untyped. As the parser consumes tokens it assigns types, splits tokens, and pushes them back -// onto the stream. -// -// For example, the token "--foo=bar" will be split into the following by the parser: -// -// [{FlagToken, "foo"}, {FlagValueToken, "bar"}] -type Scanner struct { - args []Token -} - -// Scan creates a new Scanner from args with untyped tokens. -func Scan(args ...string) *Scanner { - s := &Scanner{} - for _, arg := range args { - s.args = append(s.args, Token{Value: arg}) - } - return s -} - -// ScanFromTokens creates a new Scanner from a slice of tokens. -func ScanFromTokens(tokens ...Token) *Scanner { - return &Scanner{args: tokens} -} - -// Len returns the number of input arguments. -func (s *Scanner) Len() int { - return len(s.args) -} - -// Pop the front token off the Scanner. -func (s *Scanner) Pop() Token { - if len(s.args) == 0 { - return Token{Type: EOLToken} - } - arg := s.args[0] - s.args = s.args[1:] - return arg -} - -type expectedError struct { - context string - token Token -} - -func (e *expectedError) Error() string { - return fmt.Sprintf("expected %s value but got %q (%s)", e.context, e.token, e.token.InferredType()) -} - -// PopValue pops a value token, or returns an error. -// -// "context" is used to assist the user if the value can not be popped, eg. "expected value but got " -func (s *Scanner) PopValue(context string) (Token, error) { - t := s.Pop() - if !t.IsValue() { - return t, &expectedError{context, t} - } - return t, nil -} - -// PopValueInto pops a value token into target or returns an error. -// -// "context" is used to assist the user if the value can not be popped, eg. "expected value but got " -func (s *Scanner) PopValueInto(context string, target interface{}) error { - t, err := s.PopValue(context) - if err != nil { - return err - } - return jsonTranscode(t.Value, target) -} - -// PopWhile predicate returns true. -func (s *Scanner) PopWhile(predicate func(Token) bool) (values []Token) { - for predicate(s.Peek()) { - values = append(values, s.Pop()) - } - return -} - -// PopUntil predicate returns true. -func (s *Scanner) PopUntil(predicate func(Token) bool) (values []Token) { - for !predicate(s.Peek()) { - values = append(values, s.Pop()) - } - return -} - -// Peek at the next Token or return an EOLToken. -func (s *Scanner) Peek() Token { - if len(s.args) == 0 { - return Token{Type: EOLToken} - } - return s.args[0] -} - -// Push an untyped Token onto the front of the Scanner. -func (s *Scanner) Push(arg interface{}) *Scanner { - s.PushToken(Token{Value: arg}) - return s -} - -// PushTyped pushes a typed token onto the front of the Scanner. -func (s *Scanner) PushTyped(arg interface{}, typ TokenType) *Scanner { - s.PushToken(Token{Value: arg, Type: typ}) - return s -} - -// PushToken pushes a preconstructed Token onto the front of the Scanner. -func (s *Scanner) PushToken(token Token) *Scanner { - s.args = append([]Token{token}, s.args...) - return s -} diff --git a/vendor/github.com/alecthomas/kong/tag.go b/vendor/github.com/alecthomas/kong/tag.go deleted file mode 100644 index b780000c..00000000 --- a/vendor/github.com/alecthomas/kong/tag.go +++ /dev/null @@ -1,248 +0,0 @@ -package kong - -import ( - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" -) - -// Tag represents the parsed state of Kong tags in a struct field tag. -type Tag struct { - Ignored bool // Field is ignored by Kong. ie. kong:"-" - Cmd bool - Arg bool - Required bool - Optional bool - Name string - Help string - Type string - Default string - Format string - PlaceHolder string - Env string - Short rune - Hidden bool - Sep rune - MapSep rune - Enum string - Group string - Xor string - Vars Vars - Prefix string // Optional prefix on anonymous structs. All sub-flags will have this prefix. - Embed bool - Aliases []string - - // Storage for all tag keys for arbitrary lookups. - items map[string][]string -} - -type tagChars struct { - sep, quote, assign rune -} - -var kongChars = tagChars{sep: ',', quote: '\'', assign: '='} -var bareChars = tagChars{sep: ' ', quote: '"', assign: ':'} - -func parseTagItems(tagString string, chr tagChars) map[string][]string { - d := map[string][]string{} - key := []rune{} - value := []rune{} - quotes := false - inKey := true - - add := func() { - d[string(key)] = append(d[string(key)], string(value)) - key = []rune{} - value = []rune{} - inKey = true - } - - runes := []rune(tagString) - for idx := 0; idx < len(runes); idx++ { - r := runes[idx] - next := rune(0) - eof := false - if idx < len(runes)-1 { - next = runes[idx+1] - } else { - eof = true - } - if !quotes && r == chr.sep { - add() - continue - } - if r == chr.assign && inKey { - inKey = false - continue - } - if r == '\\' { - if next == chr.quote { - idx++ - r = chr.quote - } - } else if r == chr.quote { - if quotes { - quotes = false - if next == chr.sep || eof { - continue - } - fail("%v has an unexpected char at pos %v", tagString, idx) - } else { - quotes = true - continue - } - } - if inKey { - key = append(key, r) - } else { - value = append(value, r) - } - } - if quotes { - fail("%v is not quoted properly", tagString) - } - - add() - - return d -} - -func getTagInfo(ft reflect.StructField) (string, tagChars) { - s, ok := ft.Tag.Lookup("kong") - if ok { - return s, kongChars - } - - return string(ft.Tag), bareChars -} - -func newEmptyTag() *Tag { - return &Tag{items: map[string][]string{}} -} - -func parseTag(fv reflect.Value, ft reflect.StructField) *Tag { - if ft.Tag.Get("kong") == "-" { - t := newEmptyTag() - t.Ignored = true - return t - } - t := &Tag{ - items: parseTagItems(getTagInfo(ft)), - } - t.Cmd = t.Has("cmd") - t.Arg = t.Has("arg") - required := t.Has("required") - optional := t.Has("optional") - if required && optional { - fail("can't specify both required and optional") - } - t.Required = required - t.Optional = optional - t.Default = t.Get("default") - // Arguments with defaults are always optional. - if t.Arg && t.Default != "" { - t.Optional = true - } - t.Name = t.Get("name") - t.Help = t.Get("help") - t.Type = t.Get("type") - t.Env = t.Get("env") - t.Short, _ = t.GetRune("short") - t.Hidden = t.Has("hidden") - t.Format = t.Get("format") - t.Sep, _ = t.GetSep("sep", ',') - t.MapSep, _ = t.GetSep("mapsep", ';') - t.Group = t.Get("group") - t.Xor = t.Get("xor") - t.Prefix = t.Get("prefix") - t.Embed = t.Has("embed") - splitFn := func(r rune) bool { - return r == ',' || r == ' ' - } - aliases := t.Get("aliases") - if len(aliases) > 0 { - t.Aliases = append(t.Aliases, strings.FieldsFunc(aliases, splitFn)...) - } - t.Vars = Vars{} - for _, set := range t.GetAll("set") { - parts := strings.SplitN(set, "=", 2) - if len(parts) == 0 { - fail("set should be in the form key=value but got %q", set) - } - t.Vars[parts[0]] = parts[1] - } - t.PlaceHolder = t.Get("placeholder") - if t.PlaceHolder == "" { - t.PlaceHolder = strings.ToUpper(dashedString(fv.Type().Name())) - } - t.Enum = t.Get("enum") - return t -} - -// Has returns true if the tag contained the given key. -func (t *Tag) Has(k string) bool { - _, ok := t.items[k] - return ok -} - -// Get returns the value of the given tag. -// -// Note that this will return the empty string if the tag is missing. -func (t *Tag) Get(k string) string { - values := t.items[k] - if len(values) == 0 { - return "" - } - return values[0] -} - -// GetAll returns all encountered values for a tag, in the case of multiple occurrences. -func (t *Tag) GetAll(k string) []string { - return t.items[k] -} - -// GetBool returns true if the given tag looks like a boolean truth string. -func (t *Tag) GetBool(k string) (bool, error) { - return strconv.ParseBool(t.Get(k)) -} - -// GetFloat parses the given tag as a float64. -func (t *Tag) GetFloat(k string) (float64, error) { - return strconv.ParseFloat(t.Get(k), 64) -} - -// GetInt parses the given tag as an int64. -func (t *Tag) GetInt(k string) (int64, error) { - return strconv.ParseInt(t.Get(k), 10, 64) -} - -// GetRune parses the given tag as a rune. -func (t *Tag) GetRune(k string) (rune, error) { - r, _ := utf8.DecodeRuneInString(t.Get(k)) - if r == utf8.RuneError { - return 0, fmt.Errorf("%v has a rune error", t.Get(k)) - } - return r, nil -} - -// GetSep parses the given tag as a rune separator, allowing for a default or none. -// The separator is returned, or -1 if "none" is specified. If the tag value is an -// invalid utf8 sequence, the default rune is returned as well as an error. If the -// tag value is more than one rune, the first rune is returned as well as an error. -func (t *Tag) GetSep(k string, dflt rune) (rune, error) { - tv := t.Get(k) - if tv == "none" { - return -1, nil - } else if tv == "" { - return dflt, nil - } - r, size := utf8.DecodeRuneInString(tv) - if r == utf8.RuneError { - return dflt, fmt.Errorf(`%v:"%v" has a rune error`, k, tv) - } else if size != len(tv) { - return r, fmt.Errorf(`%v:"%v" is more than a single rune`, k, tv) - } - return r, nil -} diff --git a/vendor/github.com/alecthomas/kong/util.go b/vendor/github.com/alecthomas/kong/util.go deleted file mode 100644 index 154aebcc..00000000 --- a/vendor/github.com/alecthomas/kong/util.go +++ /dev/null @@ -1,35 +0,0 @@ -package kong - -import ( - "fmt" -) - -// ConfigFlag uses the configured (via kong.Configuration(loader)) configuration loader to load configuration -// from a file specified by a flag. -// -// Use this as a flag value to support loading of custom configuration via a flag. -type ConfigFlag string - -// BeforeResolve adds a resolver. -func (c ConfigFlag) BeforeResolve(kong *Kong, ctx *Context, trace *Path) error { - if kong.loader == nil { - return fmt.Errorf("kong must be configured with kong.Configuration(...)") - } - path := string(ctx.FlagValue(trace.Flag).(ConfigFlag)) - resolver, err := kong.LoadConfig(path) - if err != nil { - return err - } - ctx.AddResolver(resolver) - return nil -} - -// VersionFlag is a flag type that can be used to display a version number, stored in the "version" variable. -type VersionFlag bool - -// BeforeApply writes the version variable and terminates with a 0 exit status. -func (v VersionFlag) BeforeApply(app *Kong, vars Vars) error { - fmt.Fprintln(app.Stdout, vars["version"]) - app.Exit(0) - return nil -} diff --git a/vendor/github.com/alecthomas/kong/visit.go b/vendor/github.com/alecthomas/kong/visit.go deleted file mode 100644 index f7dab532..00000000 --- a/vendor/github.com/alecthomas/kong/visit.go +++ /dev/null @@ -1,58 +0,0 @@ -package kong - -import ( - "fmt" -) - -// Next should be called by Visitor to proceed with the walk. -// -// The walk will terminate if "err" is non-nil. -type Next func(err error) error - -// Visitor can be used to walk all nodes in the model. -type Visitor func(node Visitable, next Next) error - -// Visit all nodes. -func Visit(node Visitable, visitor Visitor) error { - return visitor(node, func(err error) error { - if err != nil { - return err - } - switch node := node.(type) { - case *Application: - return visitNodeChildren(node.Node, visitor) - case *Node: - return visitNodeChildren(node, visitor) - case *Value: - case *Flag: - return Visit(node.Value, visitor) - default: - panic(fmt.Sprintf("unsupported node type %T", node)) - } - return nil - }) -} - -func visitNodeChildren(node *Node, visitor Visitor) error { - if node.Argument != nil { - if err := Visit(node.Argument, visitor); err != nil { - return err - } - } - for _, flag := range node.Flags { - if err := Visit(flag, visitor); err != nil { - return err - } - } - for _, pos := range node.Positional { - if err := Visit(pos, visitor); err != nil { - return err - } - } - for _, child := range node.Children { - if err := Visit(child, visitor); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/alecthomas/repr/COPYING b/vendor/github.com/alecthomas/repr/COPYING deleted file mode 100644 index e477b078..00000000 --- a/vendor/github.com/alecthomas/repr/COPYING +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Alec Thomas - -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/github.com/alecthomas/repr/README.md b/vendor/github.com/alecthomas/repr/README.md deleted file mode 100644 index 1957b2fc..00000000 --- a/vendor/github.com/alecthomas/repr/README.md +++ /dev/null @@ -1,90 +0,0 @@ -# Python's repr() for Go [![](https://godoc.org/github.com/alecthomas/repr?status.svg)](http://godoc.org/github.com/alecthomas/repr) [![CircleCI](https://img.shields.io/circleci/project/github/alecthomas/repr.svg)](https://circleci.com/gh/alecthomas/repr) - -This package attempts to represent Go values in a form that can be used almost directly in Go source -code. - -Unfortunately, some values (such as pointers to basic types) can not be represented directly in Go. -These values will be represented as `&`. eg. `&23` - -## Example - -```go -type test struct { - S string - I int - A []int -} - -func main() { - repr.Print(&test{ - S: "String", - I: 123, - A: []int{1, 2, 3}, - }) -} -``` - -Outputs - -``` -&main.test{S: "String", I: 123, A: []int{1, 2, 3}} -``` - -## Why repr and not [pp](https://github.com/k0kubun/pp)? - -pp is designed for printing coloured output to consoles, with (seemingly?) no way to disable this. If you don't want coloured output (eg. for use in diffs, logs, etc.) repr is for you. - -## Why repr and not [go-spew](https://github.com/davecgh/go-spew)? - -Repr deliberately contains much less metadata about values. It is designed to (generally) be copyable directly into source code. - -Compare go-spew: - -```go -(parser.expression) (len=1 cap=1) { - (parser.alternative) (len=1 cap=1) { - ([]interface {}) (len=1 cap=1) { - (*parser.repitition)(0xc82000b220)({ - expression: (parser.expression) (len=2 cap=2) { - (parser.alternative) (len=1 cap=1) { - ([]interface {}) (len=1 cap=1) { - (parser.str) (len=1) "a" - } - }, - (parser.alternative) (len=1 cap=1) { - ([]interface {}) (len=1 cap=1) { - (*parser.self)(0x593ef0)({ - }) - } - } - } - }) - } - } -} -``` - -To repr: - -```go -parser.expression{ - parser.alternative{ - []interface {}{ - &parser.repitition{ - expression: parser.expression{ - parser.alternative{ - []interface {}{ - parser.str("a"), - }, - }, - parser.alternative{ - []interface {}{ - &parser.self{ }, - }, - }, - }, - }, - }, - }, -} -``` diff --git a/vendor/github.com/alecthomas/repr/repr.go b/vendor/github.com/alecthomas/repr/repr.go deleted file mode 100644 index 6bc21511..00000000 --- a/vendor/github.com/alecthomas/repr/repr.go +++ /dev/null @@ -1,366 +0,0 @@ -// Package repr attempts to represent Go values in a form that can be copy-and-pasted into source -// code directly. -// -// Some values (such as pointers to basic types) can not be represented directly in -// Go. These values will be output as `&`. eg. `&23` -package repr - -import ( - "bytes" - "fmt" - "io" - "os" - "reflect" - "sort" - "time" - "unsafe" -) - -var ( - // "Real" names of basic kinds, used to differentiate type aliases. - realKindName = map[reflect.Kind]string{ - reflect.Bool: "bool", - reflect.Int: "int", - reflect.Int8: "int8", - reflect.Int16: "int16", - reflect.Int32: "int32", - reflect.Int64: "int64", - reflect.Uint: "uint", - reflect.Uint8: "uint8", - reflect.Uint16: "uint16", - reflect.Uint32: "uint32", - reflect.Uint64: "uint64", - reflect.Uintptr: "uintptr", - reflect.Float32: "float32", - reflect.Float64: "float64", - reflect.Complex64: "complex64", - reflect.Complex128: "complex128", - reflect.Array: "array", - reflect.Chan: "chan", - reflect.Func: "func", - reflect.Map: "map", - reflect.Slice: "slice", - reflect.String: "string", - } - - goStringerType = reflect.TypeOf((*fmt.GoStringer)(nil)).Elem() - - byteSliceType = reflect.TypeOf([]byte{}) -) - -// Default prints to os.Stdout with two space indentation. -var Default = New(os.Stdout, Indent(" ")) - -// An Option modifies the default behaviour of a Printer. -type Option func(o *Printer) - -// Indent output by this much. -func Indent(indent string) Option { return func(o *Printer) { o.indent = indent } } - -// NoIndent disables indenting. -func NoIndent() Option { return Indent("") } - -// OmitEmpty sets whether empty field members should be omitted from output. -func OmitEmpty(omitEmpty bool) Option { return func(o *Printer) { o.omitEmpty = omitEmpty } } - -// ExplicitTypes adds explicit typing to slice and map struct values that would normally be inferred by Go. -func ExplicitTypes(ok bool) Option { return func(o *Printer) { o.explicitTypes = true } } - -// IgnoreGoStringer disables use of the .GoString() method. -func IgnoreGoStringer() Option { return func(o *Printer) { o.ignoreGoStringer = true } } - -// Hide excludes the given types from representation, instead just printing the name of the type. -func Hide(ts ...interface{}) Option { - return func(o *Printer) { - for _, t := range ts { - rt := reflect.Indirect(reflect.ValueOf(t)).Type() - o.exclude[rt] = true - } - } -} - -// AlwaysIncludeType always includes explicit type information for each item. -func AlwaysIncludeType() Option { return func(o *Printer) { o.alwaysIncludeType = true } } - -// Printer represents structs in a printable manner. -type Printer struct { - indent string - omitEmpty bool - ignoreGoStringer bool - alwaysIncludeType bool - explicitTypes bool - exclude map[reflect.Type]bool - w io.Writer -} - -// New creates a new Printer on w with the given Options. -func New(w io.Writer, options ...Option) *Printer { - p := &Printer{ - w: w, - indent: " ", - omitEmpty: true, - exclude: map[reflect.Type]bool{}, - } - for _, option := range options { - option(p) - } - return p -} - -func (p *Printer) nextIndent(indent string) string { - if p.indent != "" { - return indent + p.indent - } - return "" -} - -func (p *Printer) thisIndent(indent string) string { - if p.indent != "" { - return indent - } - return "" -} - -// Print the values. -func (p *Printer) Print(vs ...interface{}) { - for i, v := range vs { - if i > 0 { - fmt.Fprint(p.w, " ") - } - p.reprValue(map[reflect.Value]bool{}, reflect.ValueOf(v), "", true) - } -} - -// Println prints each value on a new line. -func (p *Printer) Println(vs ...interface{}) { - for i, v := range vs { - if i > 0 { - fmt.Fprint(p.w, " ") - } - p.reprValue(map[reflect.Value]bool{}, reflect.ValueOf(v), "", true) - } - fmt.Fprintln(p.w) -} - -func (p *Printer) reprValue(seen map[reflect.Value]bool, v reflect.Value, indent string, showType bool) { // nolint: gocyclo - if seen[v] { - fmt.Fprint(p.w, "...") - return - } - seen[v] = true - defer delete(seen, v) - - if v.Kind() == reflect.Invalid || (v.Kind() == reflect.Ptr || v.Kind() == reflect.Map || v.Kind() == reflect.Chan || v.Kind() == reflect.Slice || v.Kind() == reflect.Func || v.Kind() == reflect.Interface) && v.IsNil() { - fmt.Fprint(p.w, "nil") - return - } - if p.exclude[v.Type()] { - fmt.Fprintf(p.w, "%s...", v.Type().Name()) - return - } - t := v.Type() - - if t == byteSliceType { - fmt.Fprintf(p.w, "[]byte(%q)", v.Bytes()) - return - } - - // If we can't access a private field directly with reflection, try and do so via unsafe. - if !v.CanInterface() && v.CanAddr() { - uv := reflect.NewAt(t, unsafe.Pointer(v.UnsafeAddr())).Elem() - if uv.CanInterface() { - v = uv - } - } - // Attempt to use fmt.GoStringer interface. - if !p.ignoreGoStringer && t.Implements(goStringerType) { - fmt.Fprint(p.w, v.Interface().(fmt.GoStringer).GoString()) - return - } - in := p.thisIndent(indent) - ni := p.nextIndent(indent) - switch v.Kind() { - case reflect.Slice, reflect.Array: - if p.omitEmpty && v.Len() == 0 { - return - } - fmt.Fprintf(p.w, "%s{", v.Type()) - if v.Len() == 0 { - fmt.Fprint(p.w, "}") - } else { - if p.indent != "" { - fmt.Fprintf(p.w, "\n") - } - for i := 0; i < v.Len(); i++ { - e := v.Index(i) - fmt.Fprintf(p.w, "%s", ni) - p.reprValue(seen, e, ni, p.alwaysIncludeType || p.explicitTypes) - if p.indent != "" { - fmt.Fprintf(p.w, ",\n") - } else if i < v.Len()-1 { - fmt.Fprintf(p.w, ", ") - } - } - fmt.Fprintf(p.w, "%s}", in) - } - - case reflect.Chan: - fmt.Fprintf(p.w, "make(") - fmt.Fprintf(p.w, "%s", v.Type()) - fmt.Fprintf(p.w, ", %d)", v.Cap()) - - case reflect.Map: - fmt.Fprintf(p.w, "%s{", v.Type()) - if p.indent != "" && v.Len() != 0 { - fmt.Fprintf(p.w, "\n") - } - keys := v.MapKeys() - sort.Slice(keys, func(i, j int) bool { - return fmt.Sprint(keys[i]) < fmt.Sprint(keys[j]) - }) - for i, k := range keys { - kv := v.MapIndex(k) - fmt.Fprintf(p.w, "%s", ni) - p.reprValue(seen, k, ni, p.alwaysIncludeType || p.explicitTypes) - fmt.Fprintf(p.w, ": ") - p.reprValue(seen, kv, ni, true) - if p.indent != "" { - fmt.Fprintf(p.w, ",\n") - } else if i < v.Len()-1 { - fmt.Fprintf(p.w, ", ") - } - } - fmt.Fprintf(p.w, "%s}", in) - - case reflect.Struct: - if td, ok := v.Interface().(time.Time); ok { - timeToGo(p.w, td) - } else { - if showType { - fmt.Fprintf(p.w, "%s{", v.Type()) - } else { - fmt.Fprint(p.w, "{") - } - if p.indent != "" && v.NumField() != 0 { - fmt.Fprintf(p.w, "\n") - } - for i := 0; i < v.NumField(); i++ { - t := v.Type().Field(i) - f := v.Field(i) - if p.omitEmpty && isZero(f) { - continue - } - fmt.Fprintf(p.w, "%s%s: ", ni, t.Name) - p.reprValue(seen, f, ni, true) - if p.indent != "" { - fmt.Fprintf(p.w, ",\n") - } else if i < v.NumField()-1 { - fmt.Fprintf(p.w, ", ") - } - } - fmt.Fprintf(p.w, "%s}", indent) - } - case reflect.Ptr: - if v.IsNil() { - fmt.Fprintf(p.w, "nil") - return - } - if showType { - fmt.Fprintf(p.w, "&") - } - p.reprValue(seen, v.Elem(), indent, showType) - - case reflect.String: - if t.Name() != "string" || p.alwaysIncludeType { - fmt.Fprintf(p.w, "%s(%q)", t, v.String()) - } else { - fmt.Fprintf(p.w, "%q", v.String()) - } - - case reflect.Interface: - if v.IsNil() { - fmt.Fprintf(p.w, "interface {}(nil)") - } else { - p.reprValue(seen, v.Elem(), indent, true) - } - - default: - if t.Name() != realKindName[t.Kind()] || p.alwaysIncludeType { - fmt.Fprintf(p.w, "%s(%v)", t, v) - } else { - fmt.Fprintf(p.w, "%v", v) - } - } -} - -// String returns a string representing v. -func String(v interface{}, options ...Option) string { - w := bytes.NewBuffer(nil) - options = append([]Option{NoIndent()}, options...) - p := New(w, options...) - p.Print(v) - return w.String() -} - -func extractOptions(vs ...interface{}) (args []interface{}, options []Option) { - for _, v := range vs { - if o, ok := v.(Option); ok { - options = append(options, o) - } else { - args = append(args, v) - } - } - return -} - -// Println prints v to os.Stdout, one per line. -func Println(vs ...interface{}) { - args, options := extractOptions(vs...) - New(os.Stdout, options...).Println(args...) -} - -// Print writes a representation of v to os.Stdout, separated by spaces. -func Print(vs ...interface{}) { - args, options := extractOptions(vs...) - New(os.Stdout, options...).Print(args...) -} - -func isZero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - return false -} - -func timeToGo(w io.Writer, t time.Time) { - if t.IsZero() { - fmt.Fprint(w, "time.Time{}") - return - } - - var zone string - switch loc := t.Location(); loc { - case nil: - zone = "nil" - case time.UTC: - zone = "time.UTC" - case time.Local: - zone = "time.Local" - default: - n, off := t.Zone() - zone = fmt.Sprintf("time.FixedZone(%q, %d)", n, off) - } - y, m, d := t.Date() - fmt.Fprintf(w, `time.Date(%d, %d, %d, %d, %d, %d, %d, %s)`, y, m, d, t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), zone) -} diff --git a/vendor/github.com/alessio/shellescape/.gitignore b/vendor/github.com/alessio/shellescape/.gitignore deleted file mode 100644 index 4ba7c2d1..00000000 --- a/vendor/github.com/alessio/shellescape/.gitignore +++ /dev/null @@ -1,28 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -.idea/ - -escargs diff --git a/vendor/github.com/alessio/shellescape/.golangci.yml b/vendor/github.com/alessio/shellescape/.golangci.yml deleted file mode 100644 index cd4a17e4..00000000 --- a/vendor/github.com/alessio/shellescape/.golangci.yml +++ /dev/null @@ -1,64 +0,0 @@ -# run: -# # timeout for analysis, e.g. 30s, 5m, default is 1m -# timeout: 5m - -linters: - disable-all: true - enable: - - bodyclose - - deadcode - - depguard - - dogsled - - goconst - - gocritic - - gofmt - - goimports - - golint - - gosec - - gosimple - - govet - - ineffassign - - interfacer - - maligned - - misspell - - prealloc - - scopelint - - staticcheck - - structcheck - - stylecheck - - typecheck - - unconvert - - unparam - - unused - - misspell - - wsl - -issues: - exclude-rules: - - text: "Use of weak random number generator" - linters: - - gosec - - text: "comment on exported var" - linters: - - golint - - text: "don't use an underscore in package name" - linters: - - golint - - text: "ST1003:" - linters: - - stylecheck - # FIXME: Disabled until golangci-lint updates stylecheck with this fix: - # https://github.com/dominikh/go-tools/issues/389 - - text: "ST1016:" - linters: - - stylecheck - -linters-settings: - dogsled: - max-blank-identifiers: 3 - maligned: - # print struct with more effective memory layout or not, false by default - suggest-new: true - -run: - tests: false diff --git a/vendor/github.com/alessio/shellescape/.goreleaser.yml b/vendor/github.com/alessio/shellescape/.goreleaser.yml deleted file mode 100644 index 064c9374..00000000 --- a/vendor/github.com/alessio/shellescape/.goreleaser.yml +++ /dev/null @@ -1,33 +0,0 @@ -# This is an example goreleaser.yaml file with some sane defaults. -# Make sure to check the documentation at http://goreleaser.com -before: - hooks: - # You may remove this if you don't use go modules. - - go mod download - # you may remove this if you don't need go generate - - go generate ./... -builds: - - env: - - CGO_ENABLED=0 - main: ./cmd/escargs - goos: - - linux - - windows - - darwin -archives: - - replacements: - darwin: Darwin - linux: Linux - windows: Windows - 386: i386 - amd64: x86_64 -checksum: - name_template: 'checksums.txt' -snapshot: - name_template: "{{ .Tag }}-next" -changelog: - sort: asc - filters: - exclude: - - '^docs:' - - '^test:' diff --git a/vendor/github.com/alessio/shellescape/AUTHORS b/vendor/github.com/alessio/shellescape/AUTHORS deleted file mode 100644 index 4a647a6f..00000000 --- a/vendor/github.com/alessio/shellescape/AUTHORS +++ /dev/null @@ -1 +0,0 @@ -Alessio Treglia diff --git a/vendor/github.com/alessio/shellescape/CODE_OF_CONDUCT.md b/vendor/github.com/alessio/shellescape/CODE_OF_CONDUCT.md deleted file mode 100644 index e8eda606..00000000 --- a/vendor/github.com/alessio/shellescape/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,76 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, sex characteristics, gender identity and expression, -level of experience, education, socio-economic status, nationality, personal -appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at alessio@debian.org. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see -https://www.contributor-covenant.org/faq diff --git a/vendor/github.com/alessio/shellescape/LICENSE b/vendor/github.com/alessio/shellescape/LICENSE deleted file mode 100644 index 9f760679..00000000 --- a/vendor/github.com/alessio/shellescape/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Alessio Treglia - -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/github.com/alessio/shellescape/README.md b/vendor/github.com/alessio/shellescape/README.md deleted file mode 100644 index 910bb253..00000000 --- a/vendor/github.com/alessio/shellescape/README.md +++ /dev/null @@ -1,61 +0,0 @@ -![Build](https://github.com/alessio/shellescape/workflows/Build/badge.svg) -[![GoDoc](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/github.com/alessio/shellescape?tab=overview) -[![sourcegraph](https://sourcegraph.com/github.com/alessio/shellescape/-/badge.svg)](https://sourcegraph.com/github.com/alessio/shellescape) -[![codecov](https://codecov.io/gh/alessio/shellescape/branch/master/graph/badge.svg)](https://codecov.io/gh/alessio/shellescape) -[![Coverage](https://gocover.io/_badge/github.com/alessio/shellescape)](https://gocover.io/github.com/alessio/shellescape) -[![Go Report Card](https://goreportcard.com/badge/github.com/alessio/shellescape)](https://goreportcard.com/report/github.com/alessio/shellescape) - -# shellescape -Escape arbitrary strings for safe use as command line arguments. -## Contents of the package - -This package provides the `shellescape.Quote()` function that returns a -shell-escaped copy of a string. This functionality could be helpful -in those cases where it is known that the output of a Go program will -be appended to/used in the context of shell programs' command line arguments. - -This work was inspired by the Python original package -[shellescape](https://pypi.python.org/pypi/shellescape). - -## Usage - -The following snippet shows a typical unsafe idiom: - -```go -package main - -import ( - "fmt" - "os" -) - -func main() { - fmt.Printf("ls -l %s\n", os.Args[1]) -} -``` -_[See in Go Playground](https://play.golang.org/p/Wj2WoUfH_d)_ - -Especially when creating pipeline of commands which might end up being -executed by a shell interpreter, it is particularly unsafe to not -escape arguments. - -`shellescape.Quote()` comes in handy and to safely escape strings: - -```go -package main - -import ( - "fmt" - "os" - - "gopkg.in/alessio/shellescape.v1" -) - -func main() { - fmt.Printf("ls -l %s\n", shellescape.Quote(os.Args[1])) -} -``` -_[See in Go Playground](https://play.golang.org/p/HJ_CXgSrmp)_ - -## The escargs utility -__escargs__ reads lines from the standard input and prints shell-escaped versions. Unlinke __xargs__, blank lines on the standard input are not discarded. diff --git a/vendor/github.com/alessio/shellescape/shellescape.go b/vendor/github.com/alessio/shellescape/shellescape.go deleted file mode 100644 index dc34a556..00000000 --- a/vendor/github.com/alessio/shellescape/shellescape.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Package shellescape provides the shellescape.Quote to escape arbitrary -strings for a safe use as command line arguments in the most common -POSIX shells. - -The original Python package which this work was inspired by can be found -at https://pypi.python.org/pypi/shellescape. -*/ -package shellescape // "import gopkg.in/alessio/shellescape.v1" - -/* -The functionality provided by shellescape.Quote could be helpful -in those cases where it is known that the output of a Go program will -be appended to/used in the context of shell programs' command line arguments. -*/ - -import ( - "regexp" - "strings" - "unicode" -) - -var pattern *regexp.Regexp - -func init() { - pattern = regexp.MustCompile(`[^\w@%+=:,./-]`) -} - -// Quote returns a shell-escaped version of the string s. The returned value -// is a string that can safely be used as one token in a shell command line. -func Quote(s string) string { - if len(s) == 0 { - return "''" - } - - if pattern.MatchString(s) { - return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'" - } - - return s -} - -// QuoteCommand returns a shell-escaped version of the slice of strings. -// The returned value is a string that can safely be used as shell command arguments. -func QuoteCommand(args []string) string { - l := make([]string, len(args)) - - for i, s := range args { - l[i] = Quote(s) - } - - return strings.Join(l, " ") -} - -// StripUnsafe remove non-printable runes, e.g. control characters in -// a string that is meant for consumption by terminals that support -// control characters. -func StripUnsafe(s string) string { - return strings.Map(func(r rune) rune { - if unicode.IsPrint(r) { - return r - } - - return -1 - }, s) -} diff --git a/vendor/github.com/armon/go-metrics/.gitignore b/vendor/github.com/armon/go-metrics/.gitignore deleted file mode 100644 index 8c03ec11..00000000 --- a/vendor/github.com/armon/go-metrics/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe - -/metrics.out diff --git a/vendor/github.com/armon/go-metrics/LICENSE b/vendor/github.com/armon/go-metrics/LICENSE deleted file mode 100644 index 106569e5..00000000 --- a/vendor/github.com/armon/go-metrics/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Armon Dadgar - -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/github.com/armon/go-metrics/README.md b/vendor/github.com/armon/go-metrics/README.md deleted file mode 100644 index aa73348c..00000000 --- a/vendor/github.com/armon/go-metrics/README.md +++ /dev/null @@ -1,91 +0,0 @@ -go-metrics -========== - -This library provides a `metrics` package which can be used to instrument code, -expose application metrics, and profile runtime performance in a flexible manner. - -Current API: [![GoDoc](https://godoc.org/github.com/armon/go-metrics?status.svg)](https://godoc.org/github.com/armon/go-metrics) - -Sinks ------ - -The `metrics` package makes use of a `MetricSink` interface to support delivery -to any type of backend. Currently the following sinks are provided: - -* StatsiteSink : Sinks to a [statsite](https://github.com/armon/statsite/) instance (TCP) -* StatsdSink: Sinks to a [StatsD](https://github.com/etsy/statsd/) / statsite instance (UDP) -* PrometheusSink: Sinks to a [Prometheus](http://prometheus.io/) metrics endpoint (exposed via HTTP for scrapes) -* InmemSink : Provides in-memory aggregation, can be used to export stats -* FanoutSink : Sinks to multiple sinks. Enables writing to multiple statsite instances for example. -* BlackholeSink : Sinks to nowhere - -In addition to the sinks, the `InmemSignal` can be used to catch a signal, -and dump a formatted output of recent metrics. For example, when a process gets -a SIGUSR1, it can dump to stderr recent performance metrics for debugging. - -Labels ------- - -Most metrics do have an equivalent ending with `WithLabels`, such methods -allow to push metrics with labels and use some features of underlying Sinks -(ex: translated into Prometheus labels). - -Since some of these labels may increase greatly cardinality of metrics, the -library allow to filter labels using a blacklist/whitelist filtering system -which is global to all metrics. - -* If `Config.AllowedLabels` is not nil, then only labels specified in this value will be sent to underlying Sink, otherwise, all labels are sent by default. -* If `Config.BlockedLabels` is not nil, any label specified in this value will not be sent to underlying Sinks. - -By default, both `Config.AllowedLabels` and `Config.BlockedLabels` are nil, meaning that -no tags are filetered at all, but it allow to a user to globally block some tags with high -cardinality at application level. - -Examples --------- - -Here is an example of using the package: - -```go -func SlowMethod() { - // Profiling the runtime of a method - defer metrics.MeasureSince([]string{"SlowMethod"}, time.Now()) -} - -// Configure a statsite sink as the global metrics sink -sink, _ := metrics.NewStatsiteSink("statsite:8125") -metrics.NewGlobal(metrics.DefaultConfig("service-name"), sink) - -// Emit a Key/Value pair -metrics.EmitKey([]string{"questions", "meaning of life"}, 42) -``` - -Here is an example of setting up a signal handler: - -```go -// Setup the inmem sink and signal handler -inm := metrics.NewInmemSink(10*time.Second, time.Minute) -sig := metrics.DefaultInmemSignal(inm) -metrics.NewGlobal(metrics.DefaultConfig("service-name"), inm) - -// Run some code -inm.SetGauge([]string{"foo"}, 42) -inm.EmitKey([]string{"bar"}, 30) - -inm.IncrCounter([]string{"baz"}, 42) -inm.IncrCounter([]string{"baz"}, 1) -inm.IncrCounter([]string{"baz"}, 80) - -inm.AddSample([]string{"method", "wow"}, 42) -inm.AddSample([]string{"method", "wow"}, 100) -inm.AddSample([]string{"method", "wow"}, 22) - -.... -``` - -When a signal comes in, output like the following will be dumped to stderr: - - [2014-01-28 14:57:33.04 -0800 PST][G] 'foo': 42.000 - [2014-01-28 14:57:33.04 -0800 PST][P] 'bar': 30.000 - [2014-01-28 14:57:33.04 -0800 PST][C] 'baz': Count: 3 Min: 1.000 Mean: 41.000 Max: 80.000 Stddev: 39.509 - [2014-01-28 14:57:33.04 -0800 PST][S] 'method.wow': Count: 3 Min: 22.000 Mean: 54.667 Max: 100.000 Stddev: 40.513 \ No newline at end of file diff --git a/vendor/github.com/armon/go-metrics/const_unix.go b/vendor/github.com/armon/go-metrics/const_unix.go deleted file mode 100644 index 31098dd5..00000000 --- a/vendor/github.com/armon/go-metrics/const_unix.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !windows - -package metrics - -import ( - "syscall" -) - -const ( - // DefaultSignal is used with DefaultInmemSignal - DefaultSignal = syscall.SIGUSR1 -) diff --git a/vendor/github.com/armon/go-metrics/const_windows.go b/vendor/github.com/armon/go-metrics/const_windows.go deleted file mode 100644 index 38136af3..00000000 --- a/vendor/github.com/armon/go-metrics/const_windows.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build windows - -package metrics - -import ( - "syscall" -) - -const ( - // DefaultSignal is used with DefaultInmemSignal - // Windows has no SIGUSR1, use SIGBREAK - DefaultSignal = syscall.Signal(21) -) diff --git a/vendor/github.com/armon/go-metrics/inmem.go b/vendor/github.com/armon/go-metrics/inmem.go deleted file mode 100644 index 4e2d6a70..00000000 --- a/vendor/github.com/armon/go-metrics/inmem.go +++ /dev/null @@ -1,348 +0,0 @@ -package metrics - -import ( - "bytes" - "fmt" - "math" - "net/url" - "strings" - "sync" - "time" -) - -// InmemSink provides a MetricSink that does in-memory aggregation -// without sending metrics over a network. It can be embedded within -// an application to provide profiling information. -type InmemSink struct { - // How long is each aggregation interval - interval time.Duration - - // Retain controls how many metrics interval we keep - retain time.Duration - - // maxIntervals is the maximum length of intervals. - // It is retain / interval. - maxIntervals int - - // intervals is a slice of the retained intervals - intervals []*IntervalMetrics - intervalLock sync.RWMutex - - rateDenom float64 -} - -// IntervalMetrics stores the aggregated metrics -// for a specific interval -type IntervalMetrics struct { - sync.RWMutex - - // The start time of the interval - Interval time.Time - - // Gauges maps the key to the last set value - Gauges map[string]GaugeValue - - // Points maps the string to the list of emitted values - // from EmitKey - Points map[string][]float32 - - // Counters maps the string key to a sum of the counter - // values - Counters map[string]SampledValue - - // Samples maps the key to an AggregateSample, - // which has the rolled up view of a sample - Samples map[string]SampledValue -} - -// NewIntervalMetrics creates a new IntervalMetrics for a given interval -func NewIntervalMetrics(intv time.Time) *IntervalMetrics { - return &IntervalMetrics{ - Interval: intv, - Gauges: make(map[string]GaugeValue), - Points: make(map[string][]float32), - Counters: make(map[string]SampledValue), - Samples: make(map[string]SampledValue), - } -} - -// AggregateSample is used to hold aggregate metrics -// about a sample -type AggregateSample struct { - Count int // The count of emitted pairs - Rate float64 // The values rate per time unit (usually 1 second) - Sum float64 // The sum of values - SumSq float64 `json:"-"` // The sum of squared values - Min float64 // Minimum value - Max float64 // Maximum value - LastUpdated time.Time `json:"-"` // When value was last updated -} - -// Computes a Stddev of the values -func (a *AggregateSample) Stddev() float64 { - num := (float64(a.Count) * a.SumSq) - math.Pow(a.Sum, 2) - div := float64(a.Count * (a.Count - 1)) - if div == 0 { - return 0 - } - return math.Sqrt(num / div) -} - -// Computes a mean of the values -func (a *AggregateSample) Mean() float64 { - if a.Count == 0 { - return 0 - } - return a.Sum / float64(a.Count) -} - -// Ingest is used to update a sample -func (a *AggregateSample) Ingest(v float64, rateDenom float64) { - a.Count++ - a.Sum += v - a.SumSq += (v * v) - if v < a.Min || a.Count == 1 { - a.Min = v - } - if v > a.Max || a.Count == 1 { - a.Max = v - } - a.Rate = float64(a.Sum) / rateDenom - a.LastUpdated = time.Now() -} - -func (a *AggregateSample) String() string { - if a.Count == 0 { - return "Count: 0" - } else if a.Stddev() == 0 { - return fmt.Sprintf("Count: %d Sum: %0.3f LastUpdated: %s", a.Count, a.Sum, a.LastUpdated) - } else { - return fmt.Sprintf("Count: %d Min: %0.3f Mean: %0.3f Max: %0.3f Stddev: %0.3f Sum: %0.3f LastUpdated: %s", - a.Count, a.Min, a.Mean(), a.Max, a.Stddev(), a.Sum, a.LastUpdated) - } -} - -// NewInmemSinkFromURL creates an InmemSink from a URL. It is used -// (and tested) from NewMetricSinkFromURL. -func NewInmemSinkFromURL(u *url.URL) (MetricSink, error) { - params := u.Query() - - interval, err := time.ParseDuration(params.Get("interval")) - if err != nil { - return nil, fmt.Errorf("Bad 'interval' param: %s", err) - } - - retain, err := time.ParseDuration(params.Get("retain")) - if err != nil { - return nil, fmt.Errorf("Bad 'retain' param: %s", err) - } - - return NewInmemSink(interval, retain), nil -} - -// NewInmemSink is used to construct a new in-memory sink. -// Uses an aggregation interval and maximum retention period. -func NewInmemSink(interval, retain time.Duration) *InmemSink { - rateTimeUnit := time.Second - i := &InmemSink{ - interval: interval, - retain: retain, - maxIntervals: int(retain / interval), - rateDenom: float64(interval.Nanoseconds()) / float64(rateTimeUnit.Nanoseconds()), - } - i.intervals = make([]*IntervalMetrics, 0, i.maxIntervals) - return i -} - -func (i *InmemSink) SetGauge(key []string, val float32) { - i.SetGaugeWithLabels(key, val, nil) -} - -func (i *InmemSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - k, name := i.flattenKeyLabels(key, labels) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - intv.Gauges[k] = GaugeValue{Name: name, Value: val, Labels: labels} -} - -func (i *InmemSink) EmitKey(key []string, val float32) { - k := i.flattenKey(key) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - vals := intv.Points[k] - intv.Points[k] = append(vals, val) -} - -func (i *InmemSink) IncrCounter(key []string, val float32) { - i.IncrCounterWithLabels(key, val, nil) -} - -func (i *InmemSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - k, name := i.flattenKeyLabels(key, labels) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - - agg, ok := intv.Counters[k] - if !ok { - agg = SampledValue{ - Name: name, - AggregateSample: &AggregateSample{}, - Labels: labels, - } - intv.Counters[k] = agg - } - agg.Ingest(float64(val), i.rateDenom) -} - -func (i *InmemSink) AddSample(key []string, val float32) { - i.AddSampleWithLabels(key, val, nil) -} - -func (i *InmemSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - k, name := i.flattenKeyLabels(key, labels) - intv := i.getInterval() - - intv.Lock() - defer intv.Unlock() - - agg, ok := intv.Samples[k] - if !ok { - agg = SampledValue{ - Name: name, - AggregateSample: &AggregateSample{}, - Labels: labels, - } - intv.Samples[k] = agg - } - agg.Ingest(float64(val), i.rateDenom) -} - -// Data is used to retrieve all the aggregated metrics -// Intervals may be in use, and a read lock should be acquired -func (i *InmemSink) Data() []*IntervalMetrics { - // Get the current interval, forces creation - i.getInterval() - - i.intervalLock.RLock() - defer i.intervalLock.RUnlock() - - n := len(i.intervals) - intervals := make([]*IntervalMetrics, n) - - copy(intervals[:n-1], i.intervals[:n-1]) - current := i.intervals[n-1] - - // make its own copy for current interval - intervals[n-1] = &IntervalMetrics{} - copyCurrent := intervals[n-1] - current.RLock() - *copyCurrent = *current - - copyCurrent.Gauges = make(map[string]GaugeValue, len(current.Gauges)) - for k, v := range current.Gauges { - copyCurrent.Gauges[k] = v - } - // saved values will be not change, just copy its link - copyCurrent.Points = make(map[string][]float32, len(current.Points)) - for k, v := range current.Points { - copyCurrent.Points[k] = v - } - copyCurrent.Counters = make(map[string]SampledValue, len(current.Counters)) - for k, v := range current.Counters { - copyCurrent.Counters[k] = v - } - copyCurrent.Samples = make(map[string]SampledValue, len(current.Samples)) - for k, v := range current.Samples { - copyCurrent.Samples[k] = v - } - current.RUnlock() - - return intervals -} - -func (i *InmemSink) getExistingInterval(intv time.Time) *IntervalMetrics { - i.intervalLock.RLock() - defer i.intervalLock.RUnlock() - - n := len(i.intervals) - if n > 0 && i.intervals[n-1].Interval == intv { - return i.intervals[n-1] - } - return nil -} - -func (i *InmemSink) createInterval(intv time.Time) *IntervalMetrics { - i.intervalLock.Lock() - defer i.intervalLock.Unlock() - - // Check for an existing interval - n := len(i.intervals) - if n > 0 && i.intervals[n-1].Interval == intv { - return i.intervals[n-1] - } - - // Add the current interval - current := NewIntervalMetrics(intv) - i.intervals = append(i.intervals, current) - n++ - - // Truncate the intervals if they are too long - if n >= i.maxIntervals { - copy(i.intervals[0:], i.intervals[n-i.maxIntervals:]) - i.intervals = i.intervals[:i.maxIntervals] - } - return current -} - -// getInterval returns the current interval to write to -func (i *InmemSink) getInterval() *IntervalMetrics { - intv := time.Now().Truncate(i.interval) - if m := i.getExistingInterval(intv); m != nil { - return m - } - return i.createInterval(intv) -} - -// Flattens the key for formatting, removes spaces -func (i *InmemSink) flattenKey(parts []string) string { - buf := &bytes.Buffer{} - replacer := strings.NewReplacer(" ", "_") - - if len(parts) > 0 { - replacer.WriteString(buf, parts[0]) - } - for _, part := range parts[1:] { - replacer.WriteString(buf, ".") - replacer.WriteString(buf, part) - } - - return buf.String() -} - -// Flattens the key for formatting along with its labels, removes spaces -func (i *InmemSink) flattenKeyLabels(parts []string, labels []Label) (string, string) { - buf := &bytes.Buffer{} - replacer := strings.NewReplacer(" ", "_") - - if len(parts) > 0 { - replacer.WriteString(buf, parts[0]) - } - for _, part := range parts[1:] { - replacer.WriteString(buf, ".") - replacer.WriteString(buf, part) - } - - key := buf.String() - - for _, label := range labels { - replacer.WriteString(buf, fmt.Sprintf(";%s=%s", label.Name, label.Value)) - } - - return buf.String(), key -} diff --git a/vendor/github.com/armon/go-metrics/inmem_endpoint.go b/vendor/github.com/armon/go-metrics/inmem_endpoint.go deleted file mode 100644 index 504f1b37..00000000 --- a/vendor/github.com/armon/go-metrics/inmem_endpoint.go +++ /dev/null @@ -1,118 +0,0 @@ -package metrics - -import ( - "fmt" - "net/http" - "sort" - "time" -) - -// MetricsSummary holds a roll-up of metrics info for a given interval -type MetricsSummary struct { - Timestamp string - Gauges []GaugeValue - Points []PointValue - Counters []SampledValue - Samples []SampledValue -} - -type GaugeValue struct { - Name string - Hash string `json:"-"` - Value float32 - - Labels []Label `json:"-"` - DisplayLabels map[string]string `json:"Labels"` -} - -type PointValue struct { - Name string - Points []float32 -} - -type SampledValue struct { - Name string - Hash string `json:"-"` - *AggregateSample - Mean float64 - Stddev float64 - - Labels []Label `json:"-"` - DisplayLabels map[string]string `json:"Labels"` -} - -// DisplayMetrics returns a summary of the metrics from the most recent finished interval. -func (i *InmemSink) DisplayMetrics(resp http.ResponseWriter, req *http.Request) (interface{}, error) { - data := i.Data() - - var interval *IntervalMetrics - n := len(data) - switch { - case n == 0: - return nil, fmt.Errorf("no metric intervals have been initialized yet") - case n == 1: - // Show the current interval if it's all we have - interval = i.intervals[0] - default: - // Show the most recent finished interval if we have one - interval = i.intervals[n-2] - } - - summary := MetricsSummary{ - Timestamp: interval.Interval.Round(time.Second).UTC().String(), - Gauges: make([]GaugeValue, 0, len(interval.Gauges)), - Points: make([]PointValue, 0, len(interval.Points)), - } - - // Format and sort the output of each metric type, so it gets displayed in a - // deterministic order. - for name, points := range interval.Points { - summary.Points = append(summary.Points, PointValue{name, points}) - } - sort.Slice(summary.Points, func(i, j int) bool { - return summary.Points[i].Name < summary.Points[j].Name - }) - - for hash, value := range interval.Gauges { - value.Hash = hash - value.DisplayLabels = make(map[string]string) - for _, label := range value.Labels { - value.DisplayLabels[label.Name] = label.Value - } - value.Labels = nil - - summary.Gauges = append(summary.Gauges, value) - } - sort.Slice(summary.Gauges, func(i, j int) bool { - return summary.Gauges[i].Hash < summary.Gauges[j].Hash - }) - - summary.Counters = formatSamples(interval.Counters) - summary.Samples = formatSamples(interval.Samples) - - return summary, nil -} - -func formatSamples(source map[string]SampledValue) []SampledValue { - output := make([]SampledValue, 0, len(source)) - for hash, sample := range source { - displayLabels := make(map[string]string) - for _, label := range sample.Labels { - displayLabels[label.Name] = label.Value - } - - output = append(output, SampledValue{ - Name: sample.Name, - Hash: hash, - AggregateSample: sample.AggregateSample, - Mean: sample.AggregateSample.Mean(), - Stddev: sample.AggregateSample.Stddev(), - DisplayLabels: displayLabels, - }) - } - sort.Slice(output, func(i, j int) bool { - return output[i].Hash < output[j].Hash - }) - - return output -} diff --git a/vendor/github.com/armon/go-metrics/inmem_signal.go b/vendor/github.com/armon/go-metrics/inmem_signal.go deleted file mode 100644 index 0937f4ae..00000000 --- a/vendor/github.com/armon/go-metrics/inmem_signal.go +++ /dev/null @@ -1,117 +0,0 @@ -package metrics - -import ( - "bytes" - "fmt" - "io" - "os" - "os/signal" - "strings" - "sync" - "syscall" -) - -// InmemSignal is used to listen for a given signal, and when received, -// to dump the current metrics from the InmemSink to an io.Writer -type InmemSignal struct { - signal syscall.Signal - inm *InmemSink - w io.Writer - sigCh chan os.Signal - - stop bool - stopCh chan struct{} - stopLock sync.Mutex -} - -// NewInmemSignal creates a new InmemSignal which listens for a given signal, -// and dumps the current metrics out to a writer -func NewInmemSignal(inmem *InmemSink, sig syscall.Signal, w io.Writer) *InmemSignal { - i := &InmemSignal{ - signal: sig, - inm: inmem, - w: w, - sigCh: make(chan os.Signal, 1), - stopCh: make(chan struct{}), - } - signal.Notify(i.sigCh, sig) - go i.run() - return i -} - -// DefaultInmemSignal returns a new InmemSignal that responds to SIGUSR1 -// and writes output to stderr. Windows uses SIGBREAK -func DefaultInmemSignal(inmem *InmemSink) *InmemSignal { - return NewInmemSignal(inmem, DefaultSignal, os.Stderr) -} - -// Stop is used to stop the InmemSignal from listening -func (i *InmemSignal) Stop() { - i.stopLock.Lock() - defer i.stopLock.Unlock() - - if i.stop { - return - } - i.stop = true - close(i.stopCh) - signal.Stop(i.sigCh) -} - -// run is a long running routine that handles signals -func (i *InmemSignal) run() { - for { - select { - case <-i.sigCh: - i.dumpStats() - case <-i.stopCh: - return - } - } -} - -// dumpStats is used to dump the data to output writer -func (i *InmemSignal) dumpStats() { - buf := bytes.NewBuffer(nil) - - data := i.inm.Data() - // Skip the last period which is still being aggregated - for j := 0; j < len(data)-1; j++ { - intv := data[j] - intv.RLock() - for _, val := range intv.Gauges { - name := i.flattenLabels(val.Name, val.Labels) - fmt.Fprintf(buf, "[%v][G] '%s': %0.3f\n", intv.Interval, name, val.Value) - } - for name, vals := range intv.Points { - for _, val := range vals { - fmt.Fprintf(buf, "[%v][P] '%s': %0.3f\n", intv.Interval, name, val) - } - } - for _, agg := range intv.Counters { - name := i.flattenLabels(agg.Name, agg.Labels) - fmt.Fprintf(buf, "[%v][C] '%s': %s\n", intv.Interval, name, agg.AggregateSample) - } - for _, agg := range intv.Samples { - name := i.flattenLabels(agg.Name, agg.Labels) - fmt.Fprintf(buf, "[%v][S] '%s': %s\n", intv.Interval, name, agg.AggregateSample) - } - intv.RUnlock() - } - - // Write out the bytes - i.w.Write(buf.Bytes()) -} - -// Flattens the key for formatting along with its labels, removes spaces -func (i *InmemSignal) flattenLabels(name string, labels []Label) string { - buf := bytes.NewBufferString(name) - replacer := strings.NewReplacer(" ", "_", ":", "_") - - for _, label := range labels { - replacer.WriteString(buf, ".") - replacer.WriteString(buf, label.Value) - } - - return buf.String() -} diff --git a/vendor/github.com/armon/go-metrics/metrics.go b/vendor/github.com/armon/go-metrics/metrics.go deleted file mode 100644 index cf9def74..00000000 --- a/vendor/github.com/armon/go-metrics/metrics.go +++ /dev/null @@ -1,278 +0,0 @@ -package metrics - -import ( - "runtime" - "strings" - "time" - - "github.com/hashicorp/go-immutable-radix" -) - -type Label struct { - Name string - Value string -} - -func (m *Metrics) SetGauge(key []string, val float32) { - m.SetGaugeWithLabels(key, val, nil) -} - -func (m *Metrics) SetGaugeWithLabels(key []string, val float32, labels []Label) { - if m.HostName != "" { - if m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } else if m.EnableHostname { - key = insert(0, m.HostName, key) - } - } - if m.EnableTypePrefix { - key = insert(0, "gauge", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - m.sink.SetGaugeWithLabels(key, val, labelsFiltered) -} - -func (m *Metrics) EmitKey(key []string, val float32) { - if m.EnableTypePrefix { - key = insert(0, "kv", key) - } - if m.ServiceName != "" { - key = insert(0, m.ServiceName, key) - } - allowed, _ := m.allowMetric(key, nil) - if !allowed { - return - } - m.sink.EmitKey(key, val) -} - -func (m *Metrics) IncrCounter(key []string, val float32) { - m.IncrCounterWithLabels(key, val, nil) -} - -func (m *Metrics) IncrCounterWithLabels(key []string, val float32, labels []Label) { - if m.HostName != "" && m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } - if m.EnableTypePrefix { - key = insert(0, "counter", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - m.sink.IncrCounterWithLabels(key, val, labelsFiltered) -} - -func (m *Metrics) AddSample(key []string, val float32) { - m.AddSampleWithLabels(key, val, nil) -} - -func (m *Metrics) AddSampleWithLabels(key []string, val float32, labels []Label) { - if m.HostName != "" && m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } - if m.EnableTypePrefix { - key = insert(0, "sample", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - m.sink.AddSampleWithLabels(key, val, labelsFiltered) -} - -func (m *Metrics) MeasureSince(key []string, start time.Time) { - m.MeasureSinceWithLabels(key, start, nil) -} - -func (m *Metrics) MeasureSinceWithLabels(key []string, start time.Time, labels []Label) { - if m.HostName != "" && m.EnableHostnameLabel { - labels = append(labels, Label{"host", m.HostName}) - } - if m.EnableTypePrefix { - key = insert(0, "timer", key) - } - if m.ServiceName != "" { - if m.EnableServiceLabel { - labels = append(labels, Label{"service", m.ServiceName}) - } else { - key = insert(0, m.ServiceName, key) - } - } - allowed, labelsFiltered := m.allowMetric(key, labels) - if !allowed { - return - } - now := time.Now() - elapsed := now.Sub(start) - msec := float32(elapsed.Nanoseconds()) / float32(m.TimerGranularity) - m.sink.AddSampleWithLabels(key, msec, labelsFiltered) -} - -// UpdateFilter overwrites the existing filter with the given rules. -func (m *Metrics) UpdateFilter(allow, block []string) { - m.UpdateFilterAndLabels(allow, block, m.AllowedLabels, m.BlockedLabels) -} - -// UpdateFilterAndLabels overwrites the existing filter with the given rules. -func (m *Metrics) UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels []string) { - m.filterLock.Lock() - defer m.filterLock.Unlock() - - m.AllowedPrefixes = allow - m.BlockedPrefixes = block - - if allowedLabels == nil { - // Having a white list means we take only elements from it - m.allowedLabels = nil - } else { - m.allowedLabels = make(map[string]bool) - for _, v := range allowedLabels { - m.allowedLabels[v] = true - } - } - m.blockedLabels = make(map[string]bool) - for _, v := range blockedLabels { - m.blockedLabels[v] = true - } - m.AllowedLabels = allowedLabels - m.BlockedLabels = blockedLabels - - m.filter = iradix.New() - for _, prefix := range m.AllowedPrefixes { - m.filter, _, _ = m.filter.Insert([]byte(prefix), true) - } - for _, prefix := range m.BlockedPrefixes { - m.filter, _, _ = m.filter.Insert([]byte(prefix), false) - } -} - -// labelIsAllowed return true if a should be included in metric -// the caller should lock m.filterLock while calling this method -func (m *Metrics) labelIsAllowed(label *Label) bool { - labelName := (*label).Name - if m.blockedLabels != nil { - _, ok := m.blockedLabels[labelName] - if ok { - // If present, let's remove this label - return false - } - } - if m.allowedLabels != nil { - _, ok := m.allowedLabels[labelName] - return ok - } - // Allow by default - return true -} - -// filterLabels return only allowed labels -// the caller should lock m.filterLock while calling this method -func (m *Metrics) filterLabels(labels []Label) []Label { - if labels == nil { - return nil - } - toReturn := labels[:0] - for _, label := range labels { - if m.labelIsAllowed(&label) { - toReturn = append(toReturn, label) - } - } - return toReturn -} - -// Returns whether the metric should be allowed based on configured prefix filters -// Also return the applicable labels -func (m *Metrics) allowMetric(key []string, labels []Label) (bool, []Label) { - m.filterLock.RLock() - defer m.filterLock.RUnlock() - - if m.filter == nil || m.filter.Len() == 0 { - return m.Config.FilterDefault, m.filterLabels(labels) - } - - _, allowed, ok := m.filter.Root().LongestPrefix([]byte(strings.Join(key, "."))) - if !ok { - return m.Config.FilterDefault, m.filterLabels(labels) - } - - return allowed.(bool), m.filterLabels(labels) -} - -// Periodically collects runtime stats to publish -func (m *Metrics) collectStats() { - for { - time.Sleep(m.ProfileInterval) - m.emitRuntimeStats() - } -} - -// Emits various runtime statsitics -func (m *Metrics) emitRuntimeStats() { - // Export number of Goroutines - numRoutines := runtime.NumGoroutine() - m.SetGauge([]string{"runtime", "num_goroutines"}, float32(numRoutines)) - - // Export memory stats - var stats runtime.MemStats - runtime.ReadMemStats(&stats) - m.SetGauge([]string{"runtime", "alloc_bytes"}, float32(stats.Alloc)) - m.SetGauge([]string{"runtime", "sys_bytes"}, float32(stats.Sys)) - m.SetGauge([]string{"runtime", "malloc_count"}, float32(stats.Mallocs)) - m.SetGauge([]string{"runtime", "free_count"}, float32(stats.Frees)) - m.SetGauge([]string{"runtime", "heap_objects"}, float32(stats.HeapObjects)) - m.SetGauge([]string{"runtime", "total_gc_pause_ns"}, float32(stats.PauseTotalNs)) - m.SetGauge([]string{"runtime", "total_gc_runs"}, float32(stats.NumGC)) - - // Export info about the last few GC runs - num := stats.NumGC - - // Handle wrap around - if num < m.lastNumGC { - m.lastNumGC = 0 - } - - // Ensure we don't scan more than 256 - if num-m.lastNumGC >= 256 { - m.lastNumGC = num - 255 - } - - for i := m.lastNumGC; i < num; i++ { - pause := stats.PauseNs[i%256] - m.AddSample([]string{"runtime", "gc_pause_ns"}, float32(pause)) - } - m.lastNumGC = num -} - -// Inserts a string value at an index into the slice -func insert(i int, v string, s []string) []string { - s = append(s, "") - copy(s[i+1:], s[i:]) - s[i] = v - return s -} diff --git a/vendor/github.com/armon/go-metrics/sink.go b/vendor/github.com/armon/go-metrics/sink.go deleted file mode 100644 index 0b7d6e4b..00000000 --- a/vendor/github.com/armon/go-metrics/sink.go +++ /dev/null @@ -1,115 +0,0 @@ -package metrics - -import ( - "fmt" - "net/url" -) - -// The MetricSink interface is used to transmit metrics information -// to an external system -type MetricSink interface { - // A Gauge should retain the last value it is set to - SetGauge(key []string, val float32) - SetGaugeWithLabels(key []string, val float32, labels []Label) - - // Should emit a Key/Value pair for each call - EmitKey(key []string, val float32) - - // Counters should accumulate values - IncrCounter(key []string, val float32) - IncrCounterWithLabels(key []string, val float32, labels []Label) - - // Samples are for timing information, where quantiles are used - AddSample(key []string, val float32) - AddSampleWithLabels(key []string, val float32, labels []Label) -} - -// BlackholeSink is used to just blackhole messages -type BlackholeSink struct{} - -func (*BlackholeSink) SetGauge(key []string, val float32) {} -func (*BlackholeSink) SetGaugeWithLabels(key []string, val float32, labels []Label) {} -func (*BlackholeSink) EmitKey(key []string, val float32) {} -func (*BlackholeSink) IncrCounter(key []string, val float32) {} -func (*BlackholeSink) IncrCounterWithLabels(key []string, val float32, labels []Label) {} -func (*BlackholeSink) AddSample(key []string, val float32) {} -func (*BlackholeSink) AddSampleWithLabels(key []string, val float32, labels []Label) {} - -// FanoutSink is used to sink to fanout values to multiple sinks -type FanoutSink []MetricSink - -func (fh FanoutSink) SetGauge(key []string, val float32) { - fh.SetGaugeWithLabels(key, val, nil) -} - -func (fh FanoutSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - for _, s := range fh { - s.SetGaugeWithLabels(key, val, labels) - } -} - -func (fh FanoutSink) EmitKey(key []string, val float32) { - for _, s := range fh { - s.EmitKey(key, val) - } -} - -func (fh FanoutSink) IncrCounter(key []string, val float32) { - fh.IncrCounterWithLabels(key, val, nil) -} - -func (fh FanoutSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - for _, s := range fh { - s.IncrCounterWithLabels(key, val, labels) - } -} - -func (fh FanoutSink) AddSample(key []string, val float32) { - fh.AddSampleWithLabels(key, val, nil) -} - -func (fh FanoutSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - for _, s := range fh { - s.AddSampleWithLabels(key, val, labels) - } -} - -// sinkURLFactoryFunc is an generic interface around the *SinkFromURL() function provided -// by each sink type -type sinkURLFactoryFunc func(*url.URL) (MetricSink, error) - -// sinkRegistry supports the generic NewMetricSink function by mapping URL -// schemes to metric sink factory functions -var sinkRegistry = map[string]sinkURLFactoryFunc{ - "statsd": NewStatsdSinkFromURL, - "statsite": NewStatsiteSinkFromURL, - "inmem": NewInmemSinkFromURL, -} - -// NewMetricSinkFromURL allows a generic URL input to configure any of the -// supported sinks. The scheme of the URL identifies the type of the sink, the -// and query parameters are used to set options. -// -// "statsd://" - Initializes a StatsdSink. The host and port are passed through -// as the "addr" of the sink -// -// "statsite://" - Initializes a StatsiteSink. The host and port become the -// "addr" of the sink -// -// "inmem://" - Initializes an InmemSink. The host and port are ignored. The -// "interval" and "duration" query parameters must be specified with valid -// durations, see NewInmemSink for details. -func NewMetricSinkFromURL(urlStr string) (MetricSink, error) { - u, err := url.Parse(urlStr) - if err != nil { - return nil, err - } - - sinkURLFactoryFunc := sinkRegistry[u.Scheme] - if sinkURLFactoryFunc == nil { - return nil, fmt.Errorf( - "cannot create metric sink, unrecognized sink name: %q", u.Scheme) - } - - return sinkURLFactoryFunc(u) -} diff --git a/vendor/github.com/armon/go-metrics/start.go b/vendor/github.com/armon/go-metrics/start.go deleted file mode 100644 index 32a28c48..00000000 --- a/vendor/github.com/armon/go-metrics/start.go +++ /dev/null @@ -1,141 +0,0 @@ -package metrics - -import ( - "os" - "sync" - "sync/atomic" - "time" - - "github.com/hashicorp/go-immutable-radix" -) - -// Config is used to configure metrics settings -type Config struct { - ServiceName string // Prefixed with keys to separate services - HostName string // Hostname to use. If not provided and EnableHostname, it will be os.Hostname - EnableHostname bool // Enable prefixing gauge values with hostname - EnableHostnameLabel bool // Enable adding hostname to labels - EnableServiceLabel bool // Enable adding service to labels - EnableRuntimeMetrics bool // Enables profiling of runtime metrics (GC, Goroutines, Memory) - EnableTypePrefix bool // Prefixes key with a type ("counter", "gauge", "timer") - TimerGranularity time.Duration // Granularity of timers. - ProfileInterval time.Duration // Interval to profile runtime metrics - - AllowedPrefixes []string // A list of metric prefixes to allow, with '.' as the separator - BlockedPrefixes []string // A list of metric prefixes to block, with '.' as the separator - AllowedLabels []string // A list of metric labels to allow, with '.' as the separator - BlockedLabels []string // A list of metric labels to block, with '.' as the separator - FilterDefault bool // Whether to allow metrics by default -} - -// Metrics represents an instance of a metrics sink that can -// be used to emit -type Metrics struct { - Config - lastNumGC uint32 - sink MetricSink - filter *iradix.Tree - allowedLabels map[string]bool - blockedLabels map[string]bool - filterLock sync.RWMutex // Lock filters and allowedLabels/blockedLabels access -} - -// Shared global metrics instance -var globalMetrics atomic.Value // *Metrics - -func init() { - // Initialize to a blackhole sink to avoid errors - globalMetrics.Store(&Metrics{sink: &BlackholeSink{}}) -} - -// DefaultConfig provides a sane default configuration -func DefaultConfig(serviceName string) *Config { - c := &Config{ - ServiceName: serviceName, // Use client provided service - HostName: "", - EnableHostname: true, // Enable hostname prefix - EnableRuntimeMetrics: true, // Enable runtime profiling - EnableTypePrefix: false, // Disable type prefix - TimerGranularity: time.Millisecond, // Timers are in milliseconds - ProfileInterval: time.Second, // Poll runtime every second - FilterDefault: true, // Don't filter metrics by default - } - - // Try to get the hostname - name, _ := os.Hostname() - c.HostName = name - return c -} - -// New is used to create a new instance of Metrics -func New(conf *Config, sink MetricSink) (*Metrics, error) { - met := &Metrics{} - met.Config = *conf - met.sink = sink - met.UpdateFilterAndLabels(conf.AllowedPrefixes, conf.BlockedPrefixes, conf.AllowedLabels, conf.BlockedLabels) - - // Start the runtime collector - if conf.EnableRuntimeMetrics { - go met.collectStats() - } - return met, nil -} - -// NewGlobal is the same as New, but it assigns the metrics object to be -// used globally as well as returning it. -func NewGlobal(conf *Config, sink MetricSink) (*Metrics, error) { - metrics, err := New(conf, sink) - if err == nil { - globalMetrics.Store(metrics) - } - return metrics, err -} - -// Proxy all the methods to the globalMetrics instance -func SetGauge(key []string, val float32) { - globalMetrics.Load().(*Metrics).SetGauge(key, val) -} - -func SetGaugeWithLabels(key []string, val float32, labels []Label) { - globalMetrics.Load().(*Metrics).SetGaugeWithLabels(key, val, labels) -} - -func EmitKey(key []string, val float32) { - globalMetrics.Load().(*Metrics).EmitKey(key, val) -} - -func IncrCounter(key []string, val float32) { - globalMetrics.Load().(*Metrics).IncrCounter(key, val) -} - -func IncrCounterWithLabels(key []string, val float32, labels []Label) { - globalMetrics.Load().(*Metrics).IncrCounterWithLabels(key, val, labels) -} - -func AddSample(key []string, val float32) { - globalMetrics.Load().(*Metrics).AddSample(key, val) -} - -func AddSampleWithLabels(key []string, val float32, labels []Label) { - globalMetrics.Load().(*Metrics).AddSampleWithLabels(key, val, labels) -} - -func MeasureSince(key []string, start time.Time) { - globalMetrics.Load().(*Metrics).MeasureSince(key, start) -} - -func MeasureSinceWithLabels(key []string, start time.Time, labels []Label) { - globalMetrics.Load().(*Metrics).MeasureSinceWithLabels(key, start, labels) -} - -func UpdateFilter(allow, block []string) { - globalMetrics.Load().(*Metrics).UpdateFilter(allow, block) -} - -// UpdateFilterAndLabels set allow/block prefixes of metrics while allowedLabels -// and blockedLabels - when not nil - allow filtering of labels in order to -// block/allow globally labels (especially useful when having large number of -// values for a given label). See README.md for more information about usage. -func UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels []string) { - globalMetrics.Load().(*Metrics).UpdateFilterAndLabels(allow, block, allowedLabels, blockedLabels) -} diff --git a/vendor/github.com/armon/go-metrics/statsd.go b/vendor/github.com/armon/go-metrics/statsd.go deleted file mode 100644 index 1bfffce4..00000000 --- a/vendor/github.com/armon/go-metrics/statsd.go +++ /dev/null @@ -1,184 +0,0 @@ -package metrics - -import ( - "bytes" - "fmt" - "log" - "net" - "net/url" - "strings" - "time" -) - -const ( - // statsdMaxLen is the maximum size of a packet - // to send to statsd - statsdMaxLen = 1400 -) - -// StatsdSink provides a MetricSink that can be used -// with a statsite or statsd metrics server. It uses -// only UDP packets, while StatsiteSink uses TCP. -type StatsdSink struct { - addr string - metricQueue chan string -} - -// NewStatsdSinkFromURL creates an StatsdSink from a URL. It is used -// (and tested) from NewMetricSinkFromURL. -func NewStatsdSinkFromURL(u *url.URL) (MetricSink, error) { - return NewStatsdSink(u.Host) -} - -// NewStatsdSink is used to create a new StatsdSink -func NewStatsdSink(addr string) (*StatsdSink, error) { - s := &StatsdSink{ - addr: addr, - metricQueue: make(chan string, 4096), - } - go s.flushMetrics() - return s, nil -} - -// Close is used to stop flushing to statsd -func (s *StatsdSink) Shutdown() { - close(s.metricQueue) -} - -func (s *StatsdSink) SetGauge(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsdSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsdSink) EmitKey(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|kv\n", flatKey, val)) -} - -func (s *StatsdSink) IncrCounter(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsdSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsdSink) AddSample(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -func (s *StatsdSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -// Flattens the key for formatting, removes spaces -func (s *StatsdSink) flattenKey(parts []string) string { - joined := strings.Join(parts, ".") - return strings.Map(func(r rune) rune { - switch r { - case ':': - fallthrough - case ' ': - return '_' - default: - return r - } - }, joined) -} - -// Flattens the key along with labels for formatting, removes spaces -func (s *StatsdSink) flattenKeyLabels(parts []string, labels []Label) string { - for _, label := range labels { - parts = append(parts, label.Value) - } - return s.flattenKey(parts) -} - -// Does a non-blocking push to the metrics queue -func (s *StatsdSink) pushMetric(m string) { - select { - case s.metricQueue <- m: - default: - } -} - -// Flushes metrics -func (s *StatsdSink) flushMetrics() { - var sock net.Conn - var err error - var wait <-chan time.Time - ticker := time.NewTicker(flushInterval) - defer ticker.Stop() - -CONNECT: - // Create a buffer - buf := bytes.NewBuffer(nil) - - // Attempt to connect - sock, err = net.Dial("udp", s.addr) - if err != nil { - log.Printf("[ERR] Error connecting to statsd! Err: %s", err) - goto WAIT - } - - for { - select { - case metric, ok := <-s.metricQueue: - // Get a metric from the queue - if !ok { - goto QUIT - } - - // Check if this would overflow the packet size - if len(metric)+buf.Len() > statsdMaxLen { - _, err := sock.Write(buf.Bytes()) - buf.Reset() - if err != nil { - log.Printf("[ERR] Error writing to statsd! Err: %s", err) - goto WAIT - } - } - - // Append to the buffer - buf.WriteString(metric) - - case <-ticker.C: - if buf.Len() == 0 { - continue - } - - _, err := sock.Write(buf.Bytes()) - buf.Reset() - if err != nil { - log.Printf("[ERR] Error flushing to statsd! Err: %s", err) - goto WAIT - } - } - } - -WAIT: - // Wait for a while - wait = time.After(time.Duration(5) * time.Second) - for { - select { - // Dequeue the messages to avoid backlog - case _, ok := <-s.metricQueue: - if !ok { - goto QUIT - } - case <-wait: - goto CONNECT - } - } -QUIT: - s.metricQueue = nil -} diff --git a/vendor/github.com/armon/go-metrics/statsite.go b/vendor/github.com/armon/go-metrics/statsite.go deleted file mode 100644 index 6c0d284d..00000000 --- a/vendor/github.com/armon/go-metrics/statsite.go +++ /dev/null @@ -1,172 +0,0 @@ -package metrics - -import ( - "bufio" - "fmt" - "log" - "net" - "net/url" - "strings" - "time" -) - -const ( - // We force flush the statsite metrics after this period of - // inactivity. Prevents stats from getting stuck in a buffer - // forever. - flushInterval = 100 * time.Millisecond -) - -// NewStatsiteSinkFromURL creates an StatsiteSink from a URL. It is used -// (and tested) from NewMetricSinkFromURL. -func NewStatsiteSinkFromURL(u *url.URL) (MetricSink, error) { - return NewStatsiteSink(u.Host) -} - -// StatsiteSink provides a MetricSink that can be used with a -// statsite metrics server -type StatsiteSink struct { - addr string - metricQueue chan string -} - -// NewStatsiteSink is used to create a new StatsiteSink -func NewStatsiteSink(addr string) (*StatsiteSink, error) { - s := &StatsiteSink{ - addr: addr, - metricQueue: make(chan string, 4096), - } - go s.flushMetrics() - return s, nil -} - -// Close is used to stop flushing to statsite -func (s *StatsiteSink) Shutdown() { - close(s.metricQueue) -} - -func (s *StatsiteSink) SetGauge(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsiteSink) SetGaugeWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|g\n", flatKey, val)) -} - -func (s *StatsiteSink) EmitKey(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|kv\n", flatKey, val)) -} - -func (s *StatsiteSink) IncrCounter(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsiteSink) IncrCounterWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|c\n", flatKey, val)) -} - -func (s *StatsiteSink) AddSample(key []string, val float32) { - flatKey := s.flattenKey(key) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -func (s *StatsiteSink) AddSampleWithLabels(key []string, val float32, labels []Label) { - flatKey := s.flattenKeyLabels(key, labels) - s.pushMetric(fmt.Sprintf("%s:%f|ms\n", flatKey, val)) -} - -// Flattens the key for formatting, removes spaces -func (s *StatsiteSink) flattenKey(parts []string) string { - joined := strings.Join(parts, ".") - return strings.Map(func(r rune) rune { - switch r { - case ':': - fallthrough - case ' ': - return '_' - default: - return r - } - }, joined) -} - -// Flattens the key along with labels for formatting, removes spaces -func (s *StatsiteSink) flattenKeyLabels(parts []string, labels []Label) string { - for _, label := range labels { - parts = append(parts, label.Value) - } - return s.flattenKey(parts) -} - -// Does a non-blocking push to the metrics queue -func (s *StatsiteSink) pushMetric(m string) { - select { - case s.metricQueue <- m: - default: - } -} - -// Flushes metrics -func (s *StatsiteSink) flushMetrics() { - var sock net.Conn - var err error - var wait <-chan time.Time - var buffered *bufio.Writer - ticker := time.NewTicker(flushInterval) - defer ticker.Stop() - -CONNECT: - // Attempt to connect - sock, err = net.Dial("tcp", s.addr) - if err != nil { - log.Printf("[ERR] Error connecting to statsite! Err: %s", err) - goto WAIT - } - - // Create a buffered writer - buffered = bufio.NewWriter(sock) - - for { - select { - case metric, ok := <-s.metricQueue: - // Get a metric from the queue - if !ok { - goto QUIT - } - - // Try to send to statsite - _, err := buffered.Write([]byte(metric)) - if err != nil { - log.Printf("[ERR] Error writing to statsite! Err: %s", err) - goto WAIT - } - case <-ticker.C: - if err := buffered.Flush(); err != nil { - log.Printf("[ERR] Error flushing to statsite! Err: %s", err) - goto WAIT - } - } - } - -WAIT: - // Wait for a while - wait = time.After(time.Duration(5) * time.Second) - for { - select { - // Dequeue the messages to avoid backlog - case _, ok := <-s.metricQueue: - if !ok { - goto QUIT - } - case <-wait: - goto CONNECT - } - } -QUIT: - s.metricQueue = nil -} diff --git a/vendor/github.com/atotto/clipboard/.travis.yml b/vendor/github.com/atotto/clipboard/.travis.yml deleted file mode 100644 index 23f21d83..00000000 --- a/vendor/github.com/atotto/clipboard/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ -language: go - -os: - - linux - - osx - - windows - -go: - - go1.13.x - - go1.x - -services: - - xvfb - -before_install: - - export DISPLAY=:99.0 - -script: - - if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo apt-get install xsel; fi - - go test -v . - - if [ "$TRAVIS_OS_NAME" = "linux" ]; then sudo apt-get install xclip; fi - - go test -v . diff --git a/vendor/github.com/atotto/clipboard/LICENSE b/vendor/github.com/atotto/clipboard/LICENSE deleted file mode 100644 index dee3257b..00000000 --- a/vendor/github.com/atotto/clipboard/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2013 Ato Araki. 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 @atotto. 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/atotto/clipboard/README.md b/vendor/github.com/atotto/clipboard/README.md deleted file mode 100644 index 41fdd57b..00000000 --- a/vendor/github.com/atotto/clipboard/README.md +++ /dev/null @@ -1,48 +0,0 @@ -[![Build Status](https://travis-ci.org/atotto/clipboard.svg?branch=master)](https://travis-ci.org/atotto/clipboard) - -[![GoDoc](https://godoc.org/github.com/atotto/clipboard?status.svg)](http://godoc.org/github.com/atotto/clipboard) - -# Clipboard for Go - -Provide copying and pasting to the Clipboard for Go. - -Build: - - $ go get github.com/atotto/clipboard - -Platforms: - -* OSX -* Windows 7 (probably work on other Windows) -* Linux, Unix (requires 'xclip' or 'xsel' command to be installed) - - -Document: - -* http://godoc.org/github.com/atotto/clipboard - -Notes: - -* Text string only -* UTF-8 text encoding only (no conversion) - -TODO: - -* Clipboard watcher(?) - -## Commands: - -paste shell command: - - $ go get github.com/atotto/clipboard/cmd/gopaste - $ # example: - $ gopaste > document.txt - -copy shell command: - - $ go get github.com/atotto/clipboard/cmd/gocopy - $ # example: - $ cat document.txt | gocopy - - - diff --git a/vendor/github.com/atotto/clipboard/clipboard.go b/vendor/github.com/atotto/clipboard/clipboard.go deleted file mode 100644 index d7907d3a..00000000 --- a/vendor/github.com/atotto/clipboard/clipboard.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2013 @atotto. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package clipboard read/write on clipboard -package clipboard - -// ReadAll read string from clipboard -func ReadAll() (string, error) { - return readAll() -} - -// WriteAll write string to clipboard -func WriteAll(text string) error { - return writeAll(text) -} - -// Unsupported might be set true during clipboard init, to help callers decide -// whether or not to offer clipboard options. -var Unsupported bool diff --git a/vendor/github.com/atotto/clipboard/clipboard_darwin.go b/vendor/github.com/atotto/clipboard/clipboard_darwin.go deleted file mode 100644 index 6f33078d..00000000 --- a/vendor/github.com/atotto/clipboard/clipboard_darwin.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2013 @atotto. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin - -package clipboard - -import ( - "os/exec" -) - -var ( - pasteCmdArgs = "pbpaste" - copyCmdArgs = "pbcopy" -) - -func getPasteCommand() *exec.Cmd { - return exec.Command(pasteCmdArgs) -} - -func getCopyCommand() *exec.Cmd { - return exec.Command(copyCmdArgs) -} - -func readAll() (string, error) { - pasteCmd := getPasteCommand() - out, err := pasteCmd.Output() - if err != nil { - return "", err - } - return string(out), nil -} - -func writeAll(text string) error { - copyCmd := getCopyCommand() - in, err := copyCmd.StdinPipe() - if err != nil { - return err - } - - if err := copyCmd.Start(); err != nil { - return err - } - if _, err := in.Write([]byte(text)); err != nil { - return err - } - if err := in.Close(); err != nil { - return err - } - return copyCmd.Wait() -} diff --git a/vendor/github.com/atotto/clipboard/clipboard_plan9.go b/vendor/github.com/atotto/clipboard/clipboard_plan9.go deleted file mode 100644 index 9d2fef4e..00000000 --- a/vendor/github.com/atotto/clipboard/clipboard_plan9.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2013 @atotto. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build plan9 - -package clipboard - -import ( - "os" - "io/ioutil" -) - -func readAll() (string, error) { - f, err := os.Open("/dev/snarf") - if err != nil { - return "", err - } - defer f.Close() - - str, err := ioutil.ReadAll(f) - if err != nil { - return "", err - } - - return string(str), nil -} - -func writeAll(text string) error { - f, err := os.OpenFile("/dev/snarf", os.O_WRONLY, 0666) - if err != nil { - return err - } - defer f.Close() - - _, err = f.Write([]byte(text)) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/atotto/clipboard/clipboard_unix.go b/vendor/github.com/atotto/clipboard/clipboard_unix.go deleted file mode 100644 index d9f6a561..00000000 --- a/vendor/github.com/atotto/clipboard/clipboard_unix.go +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2013 @atotto. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build freebsd linux netbsd openbsd solaris dragonfly - -package clipboard - -import ( - "errors" - "os" - "os/exec" -) - -const ( - xsel = "xsel" - xclip = "xclip" - powershellExe = "powershell.exe" - clipExe = "clip.exe" - wlcopy = "wl-copy" - wlpaste = "wl-paste" - termuxClipboardGet = "termux-clipboard-get" - termuxClipboardSet = "termux-clipboard-set" -) - -var ( - Primary bool - trimDos bool - - pasteCmdArgs []string - copyCmdArgs []string - - xselPasteArgs = []string{xsel, "--output", "--clipboard"} - xselCopyArgs = []string{xsel, "--input", "--clipboard"} - - xclipPasteArgs = []string{xclip, "-out", "-selection", "clipboard"} - xclipCopyArgs = []string{xclip, "-in", "-selection", "clipboard"} - - powershellExePasteArgs = []string{powershellExe, "Get-Clipboard"} - clipExeCopyArgs = []string{clipExe} - - wlpasteArgs = []string{wlpaste, "--no-newline"} - wlcopyArgs = []string{wlcopy} - - termuxPasteArgs = []string{termuxClipboardGet} - termuxCopyArgs = []string{termuxClipboardSet} - - missingCommands = errors.New("No clipboard utilities available. Please install xsel, xclip, wl-clipboard or Termux:API add-on for termux-clipboard-get/set.") -) - -func init() { - if os.Getenv("WAYLAND_DISPLAY") != "" { - pasteCmdArgs = wlpasteArgs - copyCmdArgs = wlcopyArgs - - if _, err := exec.LookPath(wlcopy); err == nil { - if _, err := exec.LookPath(wlpaste); err == nil { - return - } - } - } - - pasteCmdArgs = xclipPasteArgs - copyCmdArgs = xclipCopyArgs - - if _, err := exec.LookPath(xclip); err == nil { - return - } - - pasteCmdArgs = xselPasteArgs - copyCmdArgs = xselCopyArgs - - if _, err := exec.LookPath(xsel); err == nil { - return - } - - pasteCmdArgs = termuxPasteArgs - copyCmdArgs = termuxCopyArgs - - if _, err := exec.LookPath(termuxClipboardSet); err == nil { - if _, err := exec.LookPath(termuxClipboardGet); err == nil { - return - } - } - - pasteCmdArgs = powershellExePasteArgs - copyCmdArgs = clipExeCopyArgs - trimDos = true - - if _, err := exec.LookPath(clipExe); err == nil { - if _, err := exec.LookPath(powershellExe); err == nil { - return - } - } - - Unsupported = true -} - -func getPasteCommand() *exec.Cmd { - if Primary { - pasteCmdArgs = pasteCmdArgs[:1] - } - return exec.Command(pasteCmdArgs[0], pasteCmdArgs[1:]...) -} - -func getCopyCommand() *exec.Cmd { - if Primary { - copyCmdArgs = copyCmdArgs[:1] - } - return exec.Command(copyCmdArgs[0], copyCmdArgs[1:]...) -} - -func readAll() (string, error) { - if Unsupported { - return "", missingCommands - } - pasteCmd := getPasteCommand() - out, err := pasteCmd.Output() - if err != nil { - return "", err - } - result := string(out) - if trimDos && len(result) > 1 { - result = result[:len(result)-2] - } - return result, nil -} - -func writeAll(text string) error { - if Unsupported { - return missingCommands - } - copyCmd := getCopyCommand() - in, err := copyCmd.StdinPipe() - if err != nil { - return err - } - - if err := copyCmd.Start(); err != nil { - return err - } - if _, err := in.Write([]byte(text)); err != nil { - return err - } - if err := in.Close(); err != nil { - return err - } - return copyCmd.Wait() -} diff --git a/vendor/github.com/atotto/clipboard/clipboard_windows.go b/vendor/github.com/atotto/clipboard/clipboard_windows.go deleted file mode 100644 index 253bb932..00000000 --- a/vendor/github.com/atotto/clipboard/clipboard_windows.go +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2013 @atotto. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package clipboard - -import ( - "runtime" - "syscall" - "time" - "unsafe" -) - -const ( - cfUnicodetext = 13 - gmemMoveable = 0x0002 -) - -var ( - user32 = syscall.MustLoadDLL("user32") - isClipboardFormatAvailable = user32.MustFindProc("IsClipboardFormatAvailable") - openClipboard = user32.MustFindProc("OpenClipboard") - closeClipboard = user32.MustFindProc("CloseClipboard") - emptyClipboard = user32.MustFindProc("EmptyClipboard") - getClipboardData = user32.MustFindProc("GetClipboardData") - setClipboardData = user32.MustFindProc("SetClipboardData") - - kernel32 = syscall.NewLazyDLL("kernel32") - globalAlloc = kernel32.NewProc("GlobalAlloc") - globalFree = kernel32.NewProc("GlobalFree") - globalLock = kernel32.NewProc("GlobalLock") - globalUnlock = kernel32.NewProc("GlobalUnlock") - lstrcpy = kernel32.NewProc("lstrcpyW") -) - -// waitOpenClipboard opens the clipboard, waiting for up to a second to do so. -func waitOpenClipboard() error { - started := time.Now() - limit := started.Add(time.Second) - var r uintptr - var err error - for time.Now().Before(limit) { - r, _, err = openClipboard.Call(0) - if r != 0 { - return nil - } - time.Sleep(time.Millisecond) - } - return err -} - -func readAll() (string, error) { - // LockOSThread ensure that the whole method will keep executing on the same thread from begin to end (it actually locks the goroutine thread attribution). - // Otherwise if the goroutine switch thread during execution (which is a common practice), the OpenClipboard and CloseClipboard will happen on two different threads, and it will result in a clipboard deadlock. - runtime.LockOSThread() - defer runtime.UnlockOSThread() - if formatAvailable, _, err := isClipboardFormatAvailable.Call(cfUnicodetext); formatAvailable == 0 { - return "", err - } - err := waitOpenClipboard() - if err != nil { - return "", err - } - - h, _, err := getClipboardData.Call(cfUnicodetext) - if h == 0 { - _, _, _ = closeClipboard.Call() - return "", err - } - - l, _, err := globalLock.Call(h) - if l == 0 { - _, _, _ = closeClipboard.Call() - return "", err - } - - text := syscall.UTF16ToString((*[1 << 20]uint16)(unsafe.Pointer(l))[:]) - - r, _, err := globalUnlock.Call(h) - if r == 0 { - _, _, _ = closeClipboard.Call() - return "", err - } - - closed, _, err := closeClipboard.Call() - if closed == 0 { - return "", err - } - return text, nil -} - -func writeAll(text string) error { - // LockOSThread ensure that the whole method will keep executing on the same thread from begin to end (it actually locks the goroutine thread attribution). - // Otherwise if the goroutine switch thread during execution (which is a common practice), the OpenClipboard and CloseClipboard will happen on two different threads, and it will result in a clipboard deadlock. - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - err := waitOpenClipboard() - if err != nil { - return err - } - - r, _, err := emptyClipboard.Call(0) - if r == 0 { - _, _, _ = closeClipboard.Call() - return err - } - - data := syscall.StringToUTF16(text) - - // "If the hMem parameter identifies a memory object, the object must have - // been allocated using the function with the GMEM_MOVEABLE flag." - h, _, err := globalAlloc.Call(gmemMoveable, uintptr(len(data)*int(unsafe.Sizeof(data[0])))) - if h == 0 { - _, _, _ = closeClipboard.Call() - return err - } - defer func() { - if h != 0 { - globalFree.Call(h) - } - }() - - l, _, err := globalLock.Call(h) - if l == 0 { - _, _, _ = closeClipboard.Call() - return err - } - - r, _, err = lstrcpy.Call(l, uintptr(unsafe.Pointer(&data[0]))) - if r == 0 { - _, _, _ = closeClipboard.Call() - return err - } - - r, _, err = globalUnlock.Call(h) - if r == 0 { - if err.(syscall.Errno) != 0 { - _, _, _ = closeClipboard.Call() - return err - } - } - - r, _, err = setClipboardData.Call(cfUnicodetext, h) - if r == 0 { - _, _, _ = closeClipboard.Call() - return err - } - h = 0 // suppress deferred cleanup - closed, _, err := closeClipboard.Call() - if closed == 0 { - return err - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/NOTICE.txt b/vendor/github.com/aws/aws-sdk-go-v2/NOTICE.txt deleted file mode 100644 index 899129ec..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/NOTICE.txt +++ /dev/null @@ -1,3 +0,0 @@ -AWS SDK for Go -Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. -Copyright 2014-2015 Stripe, Inc. 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 deleted file mode 100644 index 2264200c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/config.go +++ /dev/null @@ -1,208 +0,0 @@ -package aws - -import ( - "net/http" - - smithybearer "github.com/aws/smithy-go/auth/bearer" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" -) - -// HTTPClient provides the interface to provide custom HTTPClients. Generally -// *http.Client is sufficient for most use cases. The HTTPClient should not -// follow 301 or 302 redirects. -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// A Config provides service configuration for service clients. -type Config struct { - // The region to send requests to. This parameter is required and must - // be configured globally or on a per-client basis unless otherwise - // noted. A full list of regions is found in the "Regions and Endpoints" - // document. - // - // See http://docs.aws.amazon.com/general/latest/gr/rande.html for - // information on AWS regions. - Region string - - // The credentials object to use when signing requests. - // Use the LoadDefaultConfig to load configuration from all the SDK's supported - // sources, and resolve credentials using the SDK's default credential chain. - Credentials CredentialsProvider - - // The Bearer Authentication token provider to use for authenticating API - // operation calls with a Bearer Authentication token. The API clients and - // operation must support Bearer Authentication scheme in order for the - // token provider to be used. API clients created with NewFromConfig will - // automatically be configured with this option, if the API client support - // Bearer Authentication. - // - // The SDK's config.LoadDefaultConfig can automatically populate this - // option for external configuration options such as SSO session. - // https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html - BearerAuthTokenProvider smithybearer.TokenProvider - - // The HTTP Client the SDK's API clients will use to invoke HTTP requests. - // The SDK defaults to a BuildableClient allowing API clients to create - // copies of the HTTP Client for service specific customizations. - // - // Use a (*http.Client) for custom behavior. Using a custom http.Client - // will prevent the SDK from modifying the HTTP client. - HTTPClient HTTPClient - - // An endpoint resolver that can be used to provide or override an endpoint - // for the given service and region. - // - // See the `aws.EndpointResolver` documentation for additional usage - // information. - // - // Deprecated: See Config.EndpointResolverWithOptions - EndpointResolver EndpointResolver - - // An endpoint resolver that can be used to provide or override an endpoint - // for the given service and region. - // - // When EndpointResolverWithOptions is specified, it will be used by a - // service client rather than using EndpointResolver if also specified. - // - // See the `aws.EndpointResolverWithOptions` documentation for additional - // usage information. - // - // Deprecated: with the release of endpoint resolution v2 in API clients, - // EndpointResolver and EndpointResolverWithOptions are deprecated. - // Providing a value for this field will likely prevent you from using - // newer endpoint-related service features. See API client options - // EndpointResolverV2 and BaseEndpoint. - EndpointResolverWithOptions EndpointResolverWithOptions - - // RetryMaxAttempts specifies the maximum number attempts an API client - // will call an operation that fails with a retryable error. - // - // API Clients will only use this value to construct a retryer if the - // Config.Retryer member is not nil. This value will be ignored if - // Retryer is not nil. - RetryMaxAttempts int - - // RetryMode specifies the retry model the API client will be created with. - // - // API Clients will only use this value to construct a retryer if the - // Config.Retryer member is not nil. This value will be ignored if - // Retryer is not nil. - RetryMode RetryMode - - // Retryer is a function that provides a Retryer implementation. A Retryer - // guides how HTTP requests should be retried in case of recoverable - // failures. When nil the API client will use a default retryer. - // - // In general, the provider function should return a new instance of a - // Retryer if you are attempting to provide a consistent Retryer - // configuration across all clients. This will ensure that each client will - // be provided a new instance of the Retryer implementation, and will avoid - // issues such as sharing the same retry token bucket across services. - // - // If not nil, RetryMaxAttempts, and RetryMode will be ignored by API - // clients. - Retryer func() Retryer - - // ConfigSources are the sources that were used to construct the Config. - // Allows for additional configuration to be loaded by clients. - ConfigSources []interface{} - - // APIOptions provides the set of middleware mutations modify how the API - // client requests will be handled. This is useful for adding additional - // tracing data to a request, or changing behavior of the SDK's client. - APIOptions []func(*middleware.Stack) error - - // The logger writer interface to write logging messages to. Defaults to - // standard error. - Logger logging.Logger - - // Configures the events that will be sent to the configured logger. This - // can be used to configure the logging of signing, retries, request, and - // responses of the SDK clients. - // - // See the ClientLogMode type documentation for the complete set of logging - // modes and available configuration. - ClientLogMode ClientLogMode - - // The configured DefaultsMode. If not specified, service clients will - // default to legacy. - // - // Supported modes are: auto, cross-region, in-region, legacy, mobile, - // standard - DefaultsMode DefaultsMode - - // The RuntimeEnvironment configuration, only populated if the DefaultsMode - // is set to DefaultsModeAuto and is initialized by - // `config.LoadDefaultConfig`. You should not populate this structure - // programmatically, or rely on the values here within your applications. - RuntimeEnvironment RuntimeEnvironment - - // AppId is an optional application specific identifier that can be set. - // When set it will be appended to the User-Agent header of every request - // in the form of App/{AppId}. This variable is sourced from environment - // variable AWS_SDK_UA_APP_ID or the shared config profile attribute sdk_ua_app_id. - // See https://docs.aws.amazon.com/sdkref/latest/guide/settings-reference.html for - // more information on environment variables and shared config settings. - AppID string - - // BaseEndpoint is an intermediary transfer location to a service specific - // BaseEndpoint on a service's Options. - BaseEndpoint *string - - // DisableRequestCompression toggles if an operation request could be - // compressed or not. Will be set to false by default. This variable is sourced from - // environment variable AWS_DISABLE_REQUEST_COMPRESSION or the shared config profile attribute - // disable_request_compression - DisableRequestCompression bool - - // RequestMinCompressSizeBytes sets the inclusive min bytes of a request body that could be - // compressed. Will be set to 10240 by default and must be within 0 and 10485760 bytes inclusively. - // This variable is sourced from environment variable AWS_REQUEST_MIN_COMPRESSION_SIZE_BYTES or - // the shared config profile attribute request_min_compression_size_bytes - RequestMinCompressSizeBytes int64 -} - -// NewConfig returns a new Config pointer that can be chained with builder -// methods to set multiple configuration values inline without using pointers. -func NewConfig() *Config { - return &Config{} -} - -// Copy will return a shallow copy of the Config object. -func (c Config) Copy() Config { - cp := c - return cp -} - -// EndpointDiscoveryEnableState indicates if endpoint discovery is -// enabled, disabled, auto or unset state. -// -// Default behavior (Auto or Unset) indicates operations that require endpoint -// discovery will use Endpoint Discovery by default. Operations that -// optionally use Endpoint Discovery will not use Endpoint Discovery -// unless EndpointDiscovery is explicitly enabled. -type EndpointDiscoveryEnableState uint - -// Enumeration values for EndpointDiscoveryEnableState -const ( - // EndpointDiscoveryUnset represents EndpointDiscoveryEnableState is unset. - // Users do not need to use this value explicitly. The behavior for unset - // is the same as for EndpointDiscoveryAuto. - EndpointDiscoveryUnset EndpointDiscoveryEnableState = iota - - // EndpointDiscoveryAuto represents an AUTO state that allows endpoint - // discovery only when required by the api. This is the default - // configuration resolved by the client if endpoint discovery is neither - // enabled or disabled. - EndpointDiscoveryAuto // default state - - // EndpointDiscoveryDisabled indicates client MUST not perform endpoint - // discovery even when required. - EndpointDiscoveryDisabled - - // EndpointDiscoveryEnabled indicates client MUST always perform endpoint - // discovery if supported for the operation. - EndpointDiscoveryEnabled -) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/context.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/context.go deleted file mode 100644 index 4d8e26ef..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/context.go +++ /dev/null @@ -1,22 +0,0 @@ -package aws - -import ( - "context" - "time" -) - -type suppressedContext struct { - context.Context -} - -func (s *suppressedContext) Deadline() (deadline time.Time, ok bool) { - return time.Time{}, false -} - -func (s *suppressedContext) Done() <-chan struct{} { - return nil -} - -func (s *suppressedContext) Err() error { - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/credential_cache.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/credential_cache.go deleted file mode 100644 index 781ac0ae..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/credential_cache.go +++ /dev/null @@ -1,224 +0,0 @@ -package aws - -import ( - "context" - "fmt" - "sync/atomic" - "time" - - sdkrand "github.com/aws/aws-sdk-go-v2/internal/rand" - "github.com/aws/aws-sdk-go-v2/internal/sync/singleflight" -) - -// CredentialsCacheOptions are the options -type CredentialsCacheOptions struct { - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // An ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. This can cause an - // increased number of requests to refresh the credentials to occur. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration - - // ExpiryWindowJitterFrac provides a mechanism for randomizing the - // expiration of credentials within the configured ExpiryWindow by a random - // percentage. Valid values are between 0.0 and 1.0. - // - // As an example if ExpiryWindow is 60 seconds and ExpiryWindowJitterFrac - // is 0.5 then credentials will be set to expire between 30 to 60 seconds - // prior to their actual expiration time. - // - // If ExpiryWindow is 0 or less then ExpiryWindowJitterFrac is ignored. - // If ExpiryWindowJitterFrac is 0 then no randomization will be applied to the window. - // If ExpiryWindowJitterFrac < 0 the value will be treated as 0. - // If ExpiryWindowJitterFrac > 1 the value will be treated as 1. - ExpiryWindowJitterFrac float64 -} - -// CredentialsCache provides caching and concurrency safe credentials retrieval -// via the provider's retrieve method. -// -// CredentialsCache will look for optional interfaces on the Provider to adjust -// how the credential cache handles credentials caching. -// -// - HandleFailRefreshCredentialsCacheStrategy - Allows provider to handle -// credential refresh failures. This could return an updated Credentials -// value, or attempt another means of retrieving credentials. -// -// - AdjustExpiresByCredentialsCacheStrategy - Allows provider to adjust how -// credentials Expires is modified. This could modify how the Credentials -// Expires is adjusted based on the CredentialsCache ExpiryWindow option. -// Such as providing a floor not to reduce the Expires below. -type CredentialsCache struct { - provider CredentialsProvider - - options CredentialsCacheOptions - creds atomic.Value - sf singleflight.Group -} - -// NewCredentialsCache returns a CredentialsCache that wraps provider. Provider -// is expected to not be nil. A variadic list of one or more functions can be -// provided to modify the CredentialsCache configuration. This allows for -// configuration of credential expiry window and jitter. -func NewCredentialsCache(provider CredentialsProvider, optFns ...func(options *CredentialsCacheOptions)) *CredentialsCache { - options := CredentialsCacheOptions{} - - for _, fn := range optFns { - fn(&options) - } - - if options.ExpiryWindow < 0 { - options.ExpiryWindow = 0 - } - - if options.ExpiryWindowJitterFrac < 0 { - options.ExpiryWindowJitterFrac = 0 - } else if options.ExpiryWindowJitterFrac > 1 { - options.ExpiryWindowJitterFrac = 1 - } - - return &CredentialsCache{ - provider: provider, - options: options, - } -} - -// Retrieve returns the credentials. If the credentials have already been -// retrieved, and not expired the cached credentials will be returned. If the -// credentials have not been retrieved yet, or expired the provider's Retrieve -// method will be called. -// -// Returns and error if the provider's retrieve method returns an error. -func (p *CredentialsCache) Retrieve(ctx context.Context) (Credentials, error) { - if creds, ok := p.getCreds(); ok && !creds.Expired() { - return creds, nil - } - - resCh := p.sf.DoChan("", func() (interface{}, error) { - return p.singleRetrieve(&suppressedContext{ctx}) - }) - select { - case res := <-resCh: - return res.Val.(Credentials), res.Err - case <-ctx.Done(): - return Credentials{}, &RequestCanceledError{Err: ctx.Err()} - } -} - -func (p *CredentialsCache) singleRetrieve(ctx context.Context) (interface{}, error) { - currCreds, ok := p.getCreds() - if ok && !currCreds.Expired() { - return currCreds, nil - } - - newCreds, err := p.provider.Retrieve(ctx) - if err != nil { - handleFailToRefresh := defaultHandleFailToRefresh - if cs, ok := p.provider.(HandleFailRefreshCredentialsCacheStrategy); ok { - handleFailToRefresh = cs.HandleFailToRefresh - } - newCreds, err = handleFailToRefresh(ctx, currCreds, err) - if err != nil { - return Credentials{}, fmt.Errorf("failed to refresh cached credentials, %w", err) - } - } - - if newCreds.CanExpire && p.options.ExpiryWindow > 0 { - adjustExpiresBy := defaultAdjustExpiresBy - if cs, ok := p.provider.(AdjustExpiresByCredentialsCacheStrategy); ok { - adjustExpiresBy = cs.AdjustExpiresBy - } - - randFloat64, err := sdkrand.CryptoRandFloat64() - if err != nil { - return Credentials{}, fmt.Errorf("failed to get random provider, %w", err) - } - - var jitter time.Duration - if p.options.ExpiryWindowJitterFrac > 0 { - jitter = time.Duration(randFloat64 * - p.options.ExpiryWindowJitterFrac * float64(p.options.ExpiryWindow)) - } - - newCreds, err = adjustExpiresBy(newCreds, -(p.options.ExpiryWindow - jitter)) - if err != nil { - return Credentials{}, fmt.Errorf("failed to adjust credentials expires, %w", err) - } - } - - p.creds.Store(&newCreds) - return newCreds, nil -} - -// getCreds returns the currently stored credentials and true. Returning false -// if no credentials were stored. -func (p *CredentialsCache) getCreds() (Credentials, bool) { - v := p.creds.Load() - if v == nil { - return Credentials{}, false - } - - c := v.(*Credentials) - if c == nil || !c.HasKeys() { - return Credentials{}, false - } - - return *c, true -} - -// Invalidate will invalidate the cached credentials. The next call to Retrieve -// will cause the provider's Retrieve method to be called. -func (p *CredentialsCache) Invalidate() { - p.creds.Store((*Credentials)(nil)) -} - -// IsCredentialsProvider returns whether credential provider wrapped by CredentialsCache -// matches the target provider type. -func (p *CredentialsCache) IsCredentialsProvider(target CredentialsProvider) bool { - return IsCredentialsProvider(p.provider, target) -} - -// HandleFailRefreshCredentialsCacheStrategy is an interface for -// CredentialsCache to allow CredentialsProvider how failed to refresh -// credentials is handled. -type HandleFailRefreshCredentialsCacheStrategy interface { - // Given the previously cached Credentials, if any, and refresh error, may - // returns new or modified set of Credentials, or error. - // - // Credential caches may use default implementation if nil. - HandleFailToRefresh(context.Context, Credentials, error) (Credentials, error) -} - -// defaultHandleFailToRefresh returns the passed in error. -func defaultHandleFailToRefresh(ctx context.Context, _ Credentials, err error) (Credentials, error) { - return Credentials{}, err -} - -// AdjustExpiresByCredentialsCacheStrategy is an interface for CredentialCache -// to allow CredentialsProvider to intercept adjustments to Credentials expiry -// based on expectations and use cases of CredentialsProvider. -// -// Credential caches may use default implementation if nil. -type AdjustExpiresByCredentialsCacheStrategy interface { - // Given a Credentials as input, applying any mutations and - // returning the potentially updated Credentials, or error. - AdjustExpiresBy(Credentials, time.Duration) (Credentials, error) -} - -// defaultAdjustExpiresBy adds the duration to the passed in credentials Expires, -// and returns the updated credentials value. If Credentials value's CanExpire -// is false, the passed in credentials are returned unchanged. -func defaultAdjustExpiresBy(creds Credentials, dur time.Duration) (Credentials, error) { - if !creds.CanExpire { - return creds, nil - } - - creds.Expires = creds.Expires.Add(dur) - return creds, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go deleted file mode 100644 index 714d4ad8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/credentials.go +++ /dev/null @@ -1,170 +0,0 @@ -package aws - -import ( - "context" - "fmt" - "reflect" - "time" - - "github.com/aws/aws-sdk-go-v2/internal/sdk" -) - -// AnonymousCredentials provides a sentinel CredentialsProvider that should be -// used to instruct the SDK's signing middleware to not sign the request. -// -// Using `nil` credentials when configuring an API client will achieve the same -// result. The AnonymousCredentials type allows you to configure the SDK's -// external config loading to not attempt to source credentials from the shared -// config or environment. -// -// For example you can use this CredentialsProvider with an API client's -// Options to instruct the client not to sign a request for accessing public -// S3 bucket objects. -// -// The following example demonstrates using the AnonymousCredentials to prevent -// SDK's external config loading attempt to resolve credentials. -// -// cfg, err := config.LoadDefaultConfig(context.TODO(), -// config.WithCredentialsProvider(aws.AnonymousCredentials{}), -// ) -// if err != nil { -// log.Fatalf("failed to load config, %v", err) -// } -// -// client := s3.NewFromConfig(cfg) -// -// Alternatively you can leave the API client Option's `Credential` member to -// nil. If using the `NewFromConfig` constructor you'll need to explicitly set -// the `Credentials` member to nil, if the external config resolved a -// credential provider. -// -// client := s3.New(s3.Options{ -// // Credentials defaults to a nil value. -// }) -// -// This can also be configured for specific operations calls too. -// -// cfg, err := config.LoadDefaultConfig(context.TODO()) -// if err != nil { -// log.Fatalf("failed to load config, %v", err) -// } -// -// client := s3.NewFromConfig(config) -// -// result, err := client.GetObject(context.TODO(), s3.GetObject{ -// Bucket: aws.String("example-bucket"), -// Key: aws.String("example-key"), -// }, func(o *s3.Options) { -// o.Credentials = nil -// // Or -// o.Credentials = aws.AnonymousCredentials{} -// }) -type AnonymousCredentials struct{} - -// Retrieve implements the CredentialsProvider interface, but will always -// return error, and cannot be used to sign a request. The AnonymousCredentials -// type is used as a sentinel type instructing the AWS request signing -// middleware to not sign a request. -func (AnonymousCredentials) Retrieve(context.Context) (Credentials, error) { - return Credentials{Source: "AnonymousCredentials"}, - fmt.Errorf("the AnonymousCredentials is not a valid credential provider, and cannot be used to sign AWS requests with") -} - -// A Credentials is the AWS credentials value for individual credential fields. -type Credentials struct { - // AWS Access key ID - AccessKeyID string - - // AWS Secret Access Key - SecretAccessKey string - - // AWS Session Token - SessionToken string - - // Source of the credentials - Source string - - // States if the credentials can expire or not. - CanExpire bool - - // The time the credentials will expire at. Should be ignored if CanExpire - // is false. - Expires time.Time -} - -// Expired returns if the credentials have expired. -func (v Credentials) Expired() bool { - if v.CanExpire { - // Calling Round(0) on the current time will truncate the monotonic - // reading only. Ensures credential expiry time is always based on - // reported wall-clock time. - return !v.Expires.After(sdk.NowTime().Round(0)) - } - - return false -} - -// HasKeys returns if the credentials keys are set. -func (v Credentials) HasKeys() bool { - return len(v.AccessKeyID) > 0 && len(v.SecretAccessKey) > 0 -} - -// A CredentialsProvider is the interface for any component which will provide -// credentials Credentials. A CredentialsProvider is required to manage its own -// Expired state, and what to be expired means. -// -// A credentials provider implementation can be wrapped with a CredentialCache -// to cache the credential value retrieved. Without the cache the SDK will -// attempt to retrieve the credentials for every request. -type CredentialsProvider interface { - // Retrieve returns nil if it successfully retrieved the value. - // Error is returned if the value were not obtainable, or empty. - Retrieve(ctx context.Context) (Credentials, error) -} - -// CredentialsProviderFunc provides a helper wrapping a function value to -// satisfy the CredentialsProvider interface. -type CredentialsProviderFunc func(context.Context) (Credentials, error) - -// Retrieve delegates to the function value the CredentialsProviderFunc wraps. -func (fn CredentialsProviderFunc) Retrieve(ctx context.Context) (Credentials, error) { - return fn(ctx) -} - -type isCredentialsProvider interface { - IsCredentialsProvider(CredentialsProvider) bool -} - -// IsCredentialsProvider returns whether the target CredentialProvider is the same type as provider when comparing the -// implementation type. -// -// If provider has a method IsCredentialsProvider(CredentialsProvider) bool it will be responsible for validating -// whether target matches the credential provider type. -// -// When comparing the CredentialProvider implementations provider and target for equality, the following rules are used: -// -// If provider is of type T and target is of type V, true if type *T is the same as type *V, otherwise false -// If provider is of type *T and target is of type V, true if type *T is the same as type *V, otherwise false -// If provider is of type T and target is of type *V, true if type *T is the same as type *V, otherwise false -// If provider is of type *T and target is of type *V,true if type *T is the same as type *V, otherwise false -func IsCredentialsProvider(provider, target CredentialsProvider) bool { - if target == nil || provider == nil { - return provider == target - } - - if x, ok := provider.(isCredentialsProvider); ok { - return x.IsCredentialsProvider(target) - } - - targetType := reflect.TypeOf(target) - if targetType.Kind() != reflect.Ptr { - targetType = reflect.PtrTo(targetType) - } - - providerType := reflect.TypeOf(provider) - if providerType.Kind() != reflect.Ptr { - providerType = reflect.PtrTo(providerType) - } - - return targetType.AssignableTo(providerType) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/auto.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/auto.go deleted file mode 100644 index fd408e51..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/auto.go +++ /dev/null @@ -1,38 +0,0 @@ -package defaults - -import ( - "github.com/aws/aws-sdk-go-v2/aws" - "runtime" - "strings" -) - -var getGOOS = func() string { - return runtime.GOOS -} - -// ResolveDefaultsModeAuto is used to determine the effective aws.DefaultsMode when the mode -// is set to aws.DefaultsModeAuto. -func ResolveDefaultsModeAuto(region string, environment aws.RuntimeEnvironment) aws.DefaultsMode { - goos := getGOOS() - if goos == "android" || goos == "ios" { - return aws.DefaultsModeMobile - } - - var currentRegion string - if len(environment.EnvironmentIdentifier) > 0 { - currentRegion = environment.Region - } - - if len(currentRegion) == 0 && len(environment.EC2InstanceMetadataRegion) > 0 { - currentRegion = environment.EC2InstanceMetadataRegion - } - - if len(region) > 0 && len(currentRegion) > 0 { - if strings.EqualFold(region, currentRegion) { - return aws.DefaultsModeInRegion - } - return aws.DefaultsModeCrossRegion - } - - return aws.DefaultsModeStandard -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/configuration.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/configuration.go deleted file mode 100644 index 8b7e01fa..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/configuration.go +++ /dev/null @@ -1,43 +0,0 @@ -package defaults - -import ( - "time" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// Configuration is the set of SDK configuration options that are determined based -// on the configured DefaultsMode. -type Configuration struct { - // RetryMode is the configuration's default retry mode API clients should - // use for constructing a Retryer. - RetryMode aws.RetryMode - - // ConnectTimeout is the maximum amount of time a dial will wait for - // a connect to complete. - // - // See https://pkg.go.dev/net#Dialer.Timeout - ConnectTimeout *time.Duration - - // TLSNegotiationTimeout specifies the maximum amount of time waiting to - // wait for a TLS handshake. - // - // See https://pkg.go.dev/net/http#Transport.TLSHandshakeTimeout - TLSNegotiationTimeout *time.Duration -} - -// GetConnectTimeout returns the ConnectTimeout value, returns false if the value is not set. -func (c *Configuration) GetConnectTimeout() (time.Duration, bool) { - if c.ConnectTimeout == nil { - return 0, false - } - return *c.ConnectTimeout, true -} - -// GetTLSNegotiationTimeout returns the TLSNegotiationTimeout value, returns false if the value is not set. -func (c *Configuration) GetTLSNegotiationTimeout() (time.Duration, bool) { - if c.TLSNegotiationTimeout == nil { - return 0, false - } - return *c.TLSNegotiationTimeout, true -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/defaults.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/defaults.go deleted file mode 100644 index dbaa873d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/defaults.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by github.com/aws/aws-sdk-go-v2/internal/codegen/cmd/defaultsconfig. DO NOT EDIT. - -package defaults - -import ( - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "time" -) - -// GetModeConfiguration returns the default Configuration descriptor for the given mode. -// -// Supports the following modes: cross-region, in-region, mobile, standard -func GetModeConfiguration(mode aws.DefaultsMode) (Configuration, error) { - var mv aws.DefaultsMode - mv.SetFromString(string(mode)) - - switch mv { - case aws.DefaultsModeCrossRegion: - settings := Configuration{ - ConnectTimeout: aws.Duration(3100 * time.Millisecond), - RetryMode: aws.RetryMode("standard"), - TLSNegotiationTimeout: aws.Duration(3100 * time.Millisecond), - } - return settings, nil - case aws.DefaultsModeInRegion: - settings := Configuration{ - ConnectTimeout: aws.Duration(1100 * time.Millisecond), - RetryMode: aws.RetryMode("standard"), - TLSNegotiationTimeout: aws.Duration(1100 * time.Millisecond), - } - return settings, nil - case aws.DefaultsModeMobile: - settings := Configuration{ - ConnectTimeout: aws.Duration(30000 * time.Millisecond), - RetryMode: aws.RetryMode("standard"), - TLSNegotiationTimeout: aws.Duration(30000 * time.Millisecond), - } - return settings, nil - case aws.DefaultsModeStandard: - settings := Configuration{ - ConnectTimeout: aws.Duration(3100 * time.Millisecond), - RetryMode: aws.RetryMode("standard"), - TLSNegotiationTimeout: aws.Duration(3100 * time.Millisecond), - } - return settings, nil - default: - return Configuration{}, fmt.Errorf("unsupported defaults mode: %v", mode) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/doc.go deleted file mode 100644 index 2d90011b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaults/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package defaults provides recommended configuration values for AWS SDKs and CLIs. -package defaults diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaultsmode.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/defaultsmode.go deleted file mode 100644 index fcf9387c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/defaultsmode.go +++ /dev/null @@ -1,95 +0,0 @@ -// Code generated by github.com/aws/aws-sdk-go-v2/internal/codegen/cmd/defaultsmode. DO NOT EDIT. - -package aws - -import ( - "strings" -) - -// DefaultsMode is the SDK defaults mode setting. -type DefaultsMode string - -// The DefaultsMode constants. -const ( - // DefaultsModeAuto is an experimental mode that builds on the standard mode. - // The SDK will attempt to discover the execution environment to determine the - // appropriate settings automatically. - // - // Note that the auto detection is heuristics-based and does not guarantee 100% - // accuracy. STANDARD mode will be used if the execution environment cannot - // be determined. The auto detection might query EC2 Instance Metadata service - // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html), - // which might introduce latency. Therefore we recommend choosing an explicit - // defaults_mode instead if startup latency is critical to your application - DefaultsModeAuto DefaultsMode = "auto" - - // DefaultsModeCrossRegion builds on the standard mode and includes optimization - // tailored for applications which call AWS services in a different region - // - // Note that the default values vended from this mode might change as best practices - // may evolve. As a result, it is encouraged to perform tests when upgrading - // the SDK - DefaultsModeCrossRegion DefaultsMode = "cross-region" - - // DefaultsModeInRegion builds on the standard mode and includes optimization - // tailored for applications which call AWS services from within the same AWS - // region - // - // Note that the default values vended from this mode might change as best practices - // may evolve. As a result, it is encouraged to perform tests when upgrading - // the SDK - DefaultsModeInRegion DefaultsMode = "in-region" - - // DefaultsModeLegacy provides default settings that vary per SDK and were used - // prior to establishment of defaults_mode - DefaultsModeLegacy DefaultsMode = "legacy" - - // DefaultsModeMobile builds on the standard mode and includes optimization - // tailored for mobile applications - // - // Note that the default values vended from this mode might change as best practices - // may evolve. As a result, it is encouraged to perform tests when upgrading - // the SDK - DefaultsModeMobile DefaultsMode = "mobile" - - // DefaultsModeStandard provides the latest recommended default values that - // should be safe to run in most scenarios - // - // Note that the default values vended from this mode might change as best practices - // may evolve. As a result, it is encouraged to perform tests when upgrading - // the SDK - DefaultsModeStandard DefaultsMode = "standard" -) - -// SetFromString sets the DefaultsMode value to one of the pre-defined constants that matches -// the provided string when compared using EqualFold. If the value does not match a known -// constant it will be set to as-is and the function will return false. As a special case, if the -// provided value is a zero-length string, the mode will be set to LegacyDefaultsMode. -func (d *DefaultsMode) SetFromString(v string) (ok bool) { - switch { - case strings.EqualFold(v, string(DefaultsModeAuto)): - *d = DefaultsModeAuto - ok = true - case strings.EqualFold(v, string(DefaultsModeCrossRegion)): - *d = DefaultsModeCrossRegion - ok = true - case strings.EqualFold(v, string(DefaultsModeInRegion)): - *d = DefaultsModeInRegion - ok = true - case strings.EqualFold(v, string(DefaultsModeLegacy)): - *d = DefaultsModeLegacy - ok = true - case strings.EqualFold(v, string(DefaultsModeMobile)): - *d = DefaultsModeMobile - ok = true - case strings.EqualFold(v, string(DefaultsModeStandard)): - *d = DefaultsModeStandard - ok = true - case len(v) == 0: - *d = DefaultsModeLegacy - ok = true - default: - *d = DefaultsMode(v) - } - return ok -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/doc.go deleted file mode 100644 index d8b6e09e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/doc.go +++ /dev/null @@ -1,62 +0,0 @@ -// Package aws provides the core SDK's utilities and shared types. Use this package's -// utilities to simplify setting and reading API operations parameters. -// -// # Value and Pointer Conversion Utilities -// -// This package includes a helper conversion utility for each scalar type the SDK's -// API use. These utilities make getting a pointer of the scalar, and dereferencing -// a pointer easier. -// -// Each conversion utility comes in two forms. Value to Pointer and Pointer to Value. -// The Pointer to value will safely dereference the pointer and return its value. -// If the pointer was nil, the scalar's zero value will be returned. -// -// The value to pointer functions will be named after the scalar type. So get a -// *string from a string value use the "String" function. This makes it easy to -// to get pointer of a literal string value, because getting the address of a -// literal requires assigning the value to a variable first. -// -// var strPtr *string -// -// // Without the SDK's conversion functions -// str := "my string" -// strPtr = &str -// -// // With the SDK's conversion functions -// strPtr = aws.String("my string") -// -// // Convert *string to string value -// str = aws.ToString(strPtr) -// -// In addition to scalars the aws package also includes conversion utilities for -// map and slice for commonly types used in API parameters. The map and slice -// conversion functions use similar naming pattern as the scalar conversion -// functions. -// -// var strPtrs []*string -// var strs []string = []string{"Go", "Gophers", "Go"} -// -// // Convert []string to []*string -// strPtrs = aws.StringSlice(strs) -// -// // Convert []*string to []string -// strs = aws.ToStringSlice(strPtrs) -// -// # SDK Default HTTP Client -// -// The SDK will use the http.DefaultClient if a HTTP client is not provided to -// the SDK's Session, or service client constructor. This means that if the -// http.DefaultClient is modified by other components of your application the -// modifications will be picked up by the SDK as well. -// -// In some cases this might be intended, but it is a better practice to create -// a custom HTTP Client to share explicitly through your application. You can -// configure the SDK to use the custom HTTP Client by setting the HTTPClient -// value of the SDK's Config type when creating a Session or service client. -package aws - -// generate.go uses a build tag of "ignore", go run doesn't need to specify -// this because go run ignores all build flags when running a go file directly. -//go:generate go run -tags codegen generate.go -//go:generate go run -tags codegen logging_generate.go -//go:generate gofmt -w -s . diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/endpoints.go deleted file mode 100644 index aa10a9b4..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/endpoints.go +++ /dev/null @@ -1,229 +0,0 @@ -package aws - -import ( - "fmt" -) - -// DualStackEndpointState is a constant to describe the dual-stack endpoint resolution behavior. -type DualStackEndpointState uint - -const ( - // DualStackEndpointStateUnset is the default value behavior for dual-stack endpoint resolution. - DualStackEndpointStateUnset DualStackEndpointState = iota - - // DualStackEndpointStateEnabled enables dual-stack endpoint resolution for service endpoints. - DualStackEndpointStateEnabled - - // DualStackEndpointStateDisabled disables dual-stack endpoint resolution for endpoints. - DualStackEndpointStateDisabled -) - -// GetUseDualStackEndpoint takes a service's EndpointResolverOptions and returns the UseDualStackEndpoint value. -// Returns boolean false if the provided options does not have a method to retrieve the DualStackEndpointState. -func GetUseDualStackEndpoint(options ...interface{}) (value DualStackEndpointState, found bool) { - type iface interface { - GetUseDualStackEndpoint() DualStackEndpointState - } - for _, option := range options { - if i, ok := option.(iface); ok { - value = i.GetUseDualStackEndpoint() - found = true - break - } - } - return value, found -} - -// FIPSEndpointState is a constant to describe the FIPS endpoint resolution behavior. -type FIPSEndpointState uint - -const ( - // FIPSEndpointStateUnset is the default value behavior for FIPS endpoint resolution. - FIPSEndpointStateUnset FIPSEndpointState = iota - - // FIPSEndpointStateEnabled enables FIPS endpoint resolution for service endpoints. - FIPSEndpointStateEnabled - - // FIPSEndpointStateDisabled disables FIPS endpoint resolution for endpoints. - FIPSEndpointStateDisabled -) - -// GetUseFIPSEndpoint takes a service's EndpointResolverOptions and returns the UseDualStackEndpoint value. -// Returns boolean false if the provided options does not have a method to retrieve the DualStackEndpointState. -func GetUseFIPSEndpoint(options ...interface{}) (value FIPSEndpointState, found bool) { - type iface interface { - GetUseFIPSEndpoint() FIPSEndpointState - } - for _, option := range options { - if i, ok := option.(iface); ok { - value = i.GetUseFIPSEndpoint() - found = true - break - } - } - return value, found -} - -// Endpoint represents the endpoint a service client should make API operation -// calls to. -// -// The SDK will automatically resolve these endpoints per API client using an -// internal endpoint resolvers. If you'd like to provide custom endpoint -// resolving behavior you can implement the EndpointResolver interface. -type Endpoint struct { - // The base URL endpoint the SDK API clients will use to make API calls to. - // The SDK will suffix URI path and query elements to this endpoint. - URL string - - // Specifies if the endpoint's hostname can be modified by the SDK's API - // client. - // - // If the hostname is mutable the SDK API clients may modify any part of - // the hostname based on the requirements of the API, (e.g. adding, or - // removing content in the hostname). Such as, Amazon S3 API client - // prefixing "bucketname" to the hostname, or changing the - // hostname service name component from "s3." to "s3-accesspoint.dualstack." - // for the dualstack endpoint of an S3 Accesspoint resource. - // - // Care should be taken when providing a custom endpoint for an API. If the - // endpoint hostname is mutable, and the client cannot modify the endpoint - // correctly, the operation call will most likely fail, or have undefined - // behavior. - // - // If hostname is immutable, the SDK API clients will not modify the - // hostname of the URL. This may cause the API client not to function - // correctly if the API requires the operation specific hostname values - // to be used by the client. - // - // This flag does not modify the API client's behavior if this endpoint - // will be used instead of Endpoint Discovery, or if the endpoint will be - // used to perform Endpoint Discovery. That behavior is configured via the - // API Client's Options. - HostnameImmutable bool - - // The AWS partition the endpoint belongs to. - PartitionID string - - // The service name that should be used for signing the requests to the - // endpoint. - SigningName string - - // The region that should be used for signing the request to the endpoint. - SigningRegion string - - // The signing method that should be used for signing the requests to the - // endpoint. - SigningMethod string - - // The source of the Endpoint. By default, this will be EndpointSourceServiceMetadata. - // When providing a custom endpoint, you should set the source as EndpointSourceCustom. - // If source is not provided when providing a custom endpoint, the SDK may not - // perform required host mutations correctly. Source should be used along with - // HostnameImmutable property as per the usage requirement. - Source EndpointSource -} - -// EndpointSource is the endpoint source type. -type EndpointSource int - -const ( - // EndpointSourceServiceMetadata denotes service modeled endpoint metadata is used as Endpoint Source. - EndpointSourceServiceMetadata EndpointSource = iota - - // EndpointSourceCustom denotes endpoint is a custom endpoint. This source should be used when - // user provides a custom endpoint to be used by the SDK. - EndpointSourceCustom -) - -// EndpointNotFoundError is a sentinel error to indicate that the -// EndpointResolver implementation was unable to resolve an endpoint for the -// given service and region. Resolvers should use this to indicate that an API -// client should fallback and attempt to use it's internal default resolver to -// resolve the endpoint. -type EndpointNotFoundError struct { - Err error -} - -// Error is the error message. -func (e *EndpointNotFoundError) Error() string { - return fmt.Sprintf("endpoint not found, %v", e.Err) -} - -// Unwrap returns the underlying error. -func (e *EndpointNotFoundError) Unwrap() error { - return e.Err -} - -// EndpointResolver is an endpoint resolver that can be used to provide or -// override an endpoint for the given service and region. API clients will -// attempt to use the EndpointResolver first to resolve an endpoint if -// available. If the EndpointResolver returns an EndpointNotFoundError error, -// API clients will fallback to attempting to resolve the endpoint using its -// internal default endpoint resolver. -// -// Deprecated: See EndpointResolverWithOptions -type EndpointResolver interface { - ResolveEndpoint(service, region string) (Endpoint, error) -} - -// EndpointResolverFunc wraps a function to satisfy the EndpointResolver interface. -// -// Deprecated: See EndpointResolverWithOptionsFunc -type EndpointResolverFunc func(service, region string) (Endpoint, error) - -// ResolveEndpoint calls the wrapped function and returns the results. -// -// Deprecated: See EndpointResolverWithOptions.ResolveEndpoint -func (e EndpointResolverFunc) ResolveEndpoint(service, region string) (Endpoint, error) { - return e(service, region) -} - -// EndpointResolverWithOptions is an endpoint resolver that can be used to provide or -// override an endpoint for the given service, region, and the service client's EndpointOptions. API clients will -// attempt to use the EndpointResolverWithOptions first to resolve an endpoint if -// available. If the EndpointResolverWithOptions returns an EndpointNotFoundError error, -// API clients will fallback to attempting to resolve the endpoint using its -// internal default endpoint resolver. -type EndpointResolverWithOptions interface { - ResolveEndpoint(service, region string, options ...interface{}) (Endpoint, error) -} - -// EndpointResolverWithOptionsFunc wraps a function to satisfy the EndpointResolverWithOptions interface. -type EndpointResolverWithOptionsFunc func(service, region string, options ...interface{}) (Endpoint, error) - -// ResolveEndpoint calls the wrapped function and returns the results. -func (e EndpointResolverWithOptionsFunc) ResolveEndpoint(service, region string, options ...interface{}) (Endpoint, error) { - return e(service, region, options...) -} - -// GetDisableHTTPS takes a service's EndpointResolverOptions and returns the DisableHTTPS value. -// Returns boolean false if the provided options does not have a method to retrieve the DisableHTTPS. -func GetDisableHTTPS(options ...interface{}) (value bool, found bool) { - type iface interface { - GetDisableHTTPS() bool - } - for _, option := range options { - if i, ok := option.(iface); ok { - value = i.GetDisableHTTPS() - found = true - break - } - } - return value, found -} - -// GetResolvedRegion takes a service's EndpointResolverOptions and returns the ResolvedRegion value. -// Returns boolean false if the provided options does not have a method to retrieve the ResolvedRegion. -func GetResolvedRegion(options ...interface{}) (value string, found bool) { - type iface interface { - GetResolvedRegion() string - } - for _, option := range options { - if i, ok := option.(iface); ok { - value = i.GetResolvedRegion() - found = true - break - } - } - return value, found -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/errors.go deleted file mode 100644 index f390a08f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/errors.go +++ /dev/null @@ -1,9 +0,0 @@ -package aws - -// MissingRegionError is an error that is returned if region configuration -// value was not found. -type MissingRegionError struct{} - -func (*MissingRegionError) Error() string { - return "an AWS region is required, but was not found" -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/from_ptr.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/from_ptr.go deleted file mode 100644 index 2394418e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/from_ptr.go +++ /dev/null @@ -1,365 +0,0 @@ -// Code generated by aws/generate.go DO NOT EDIT. - -package aws - -import ( - "github.com/aws/smithy-go/ptr" - "time" -) - -// ToBool returns bool value dereferenced if the passed -// in pointer was not nil. Returns a bool zero value if the -// pointer was nil. -func ToBool(p *bool) (v bool) { - return ptr.ToBool(p) -} - -// ToBoolSlice returns a slice of bool values, that are -// dereferenced if the passed in pointer was not nil. Returns a bool -// zero value if the pointer was nil. -func ToBoolSlice(vs []*bool) []bool { - return ptr.ToBoolSlice(vs) -} - -// ToBoolMap returns a map of bool values, that are -// dereferenced if the passed in pointer was not nil. The bool -// zero value is used if the pointer was nil. -func ToBoolMap(vs map[string]*bool) map[string]bool { - return ptr.ToBoolMap(vs) -} - -// ToByte returns byte value dereferenced if the passed -// in pointer was not nil. Returns a byte zero value if the -// pointer was nil. -func ToByte(p *byte) (v byte) { - return ptr.ToByte(p) -} - -// ToByteSlice returns a slice of byte values, that are -// dereferenced if the passed in pointer was not nil. Returns a byte -// zero value if the pointer was nil. -func ToByteSlice(vs []*byte) []byte { - return ptr.ToByteSlice(vs) -} - -// ToByteMap returns a map of byte values, that are -// dereferenced if the passed in pointer was not nil. The byte -// zero value is used if the pointer was nil. -func ToByteMap(vs map[string]*byte) map[string]byte { - return ptr.ToByteMap(vs) -} - -// ToString returns string value dereferenced if the passed -// in pointer was not nil. Returns a string zero value if the -// pointer was nil. -func ToString(p *string) (v string) { - return ptr.ToString(p) -} - -// ToStringSlice returns a slice of string values, that are -// dereferenced if the passed in pointer was not nil. Returns a string -// zero value if the pointer was nil. -func ToStringSlice(vs []*string) []string { - return ptr.ToStringSlice(vs) -} - -// ToStringMap returns a map of string values, that are -// dereferenced if the passed in pointer was not nil. The string -// zero value is used if the pointer was nil. -func ToStringMap(vs map[string]*string) map[string]string { - return ptr.ToStringMap(vs) -} - -// ToInt returns int value dereferenced if the passed -// in pointer was not nil. Returns a int zero value if the -// pointer was nil. -func ToInt(p *int) (v int) { - return ptr.ToInt(p) -} - -// ToIntSlice returns a slice of int values, that are -// dereferenced if the passed in pointer was not nil. Returns a int -// zero value if the pointer was nil. -func ToIntSlice(vs []*int) []int { - return ptr.ToIntSlice(vs) -} - -// ToIntMap returns a map of int values, that are -// dereferenced if the passed in pointer was not nil. The int -// zero value is used if the pointer was nil. -func ToIntMap(vs map[string]*int) map[string]int { - return ptr.ToIntMap(vs) -} - -// ToInt8 returns int8 value dereferenced if the passed -// in pointer was not nil. Returns a int8 zero value if the -// pointer was nil. -func ToInt8(p *int8) (v int8) { - return ptr.ToInt8(p) -} - -// ToInt8Slice returns a slice of int8 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int8 -// zero value if the pointer was nil. -func ToInt8Slice(vs []*int8) []int8 { - return ptr.ToInt8Slice(vs) -} - -// ToInt8Map returns a map of int8 values, that are -// dereferenced if the passed in pointer was not nil. The int8 -// zero value is used if the pointer was nil. -func ToInt8Map(vs map[string]*int8) map[string]int8 { - return ptr.ToInt8Map(vs) -} - -// ToInt16 returns int16 value dereferenced if the passed -// in pointer was not nil. Returns a int16 zero value if the -// pointer was nil. -func ToInt16(p *int16) (v int16) { - return ptr.ToInt16(p) -} - -// ToInt16Slice returns a slice of int16 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int16 -// zero value if the pointer was nil. -func ToInt16Slice(vs []*int16) []int16 { - return ptr.ToInt16Slice(vs) -} - -// ToInt16Map returns a map of int16 values, that are -// dereferenced if the passed in pointer was not nil. The int16 -// zero value is used if the pointer was nil. -func ToInt16Map(vs map[string]*int16) map[string]int16 { - return ptr.ToInt16Map(vs) -} - -// ToInt32 returns int32 value dereferenced if the passed -// in pointer was not nil. Returns a int32 zero value if the -// pointer was nil. -func ToInt32(p *int32) (v int32) { - return ptr.ToInt32(p) -} - -// ToInt32Slice returns a slice of int32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int32 -// zero value if the pointer was nil. -func ToInt32Slice(vs []*int32) []int32 { - return ptr.ToInt32Slice(vs) -} - -// ToInt32Map returns a map of int32 values, that are -// dereferenced if the passed in pointer was not nil. The int32 -// zero value is used if the pointer was nil. -func ToInt32Map(vs map[string]*int32) map[string]int32 { - return ptr.ToInt32Map(vs) -} - -// ToInt64 returns int64 value dereferenced if the passed -// in pointer was not nil. Returns a int64 zero value if the -// pointer was nil. -func ToInt64(p *int64) (v int64) { - return ptr.ToInt64(p) -} - -// ToInt64Slice returns a slice of int64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int64 -// zero value if the pointer was nil. -func ToInt64Slice(vs []*int64) []int64 { - return ptr.ToInt64Slice(vs) -} - -// ToInt64Map returns a map of int64 values, that are -// dereferenced if the passed in pointer was not nil. The int64 -// zero value is used if the pointer was nil. -func ToInt64Map(vs map[string]*int64) map[string]int64 { - return ptr.ToInt64Map(vs) -} - -// ToUint returns uint value dereferenced if the passed -// in pointer was not nil. Returns a uint zero value if the -// pointer was nil. -func ToUint(p *uint) (v uint) { - return ptr.ToUint(p) -} - -// ToUintSlice returns a slice of uint values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint -// zero value if the pointer was nil. -func ToUintSlice(vs []*uint) []uint { - return ptr.ToUintSlice(vs) -} - -// ToUintMap returns a map of uint values, that are -// dereferenced if the passed in pointer was not nil. The uint -// zero value is used if the pointer was nil. -func ToUintMap(vs map[string]*uint) map[string]uint { - return ptr.ToUintMap(vs) -} - -// ToUint8 returns uint8 value dereferenced if the passed -// in pointer was not nil. Returns a uint8 zero value if the -// pointer was nil. -func ToUint8(p *uint8) (v uint8) { - return ptr.ToUint8(p) -} - -// ToUint8Slice returns a slice of uint8 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint8 -// zero value if the pointer was nil. -func ToUint8Slice(vs []*uint8) []uint8 { - return ptr.ToUint8Slice(vs) -} - -// ToUint8Map returns a map of uint8 values, that are -// dereferenced if the passed in pointer was not nil. The uint8 -// zero value is used if the pointer was nil. -func ToUint8Map(vs map[string]*uint8) map[string]uint8 { - return ptr.ToUint8Map(vs) -} - -// ToUint16 returns uint16 value dereferenced if the passed -// in pointer was not nil. Returns a uint16 zero value if the -// pointer was nil. -func ToUint16(p *uint16) (v uint16) { - return ptr.ToUint16(p) -} - -// ToUint16Slice returns a slice of uint16 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint16 -// zero value if the pointer was nil. -func ToUint16Slice(vs []*uint16) []uint16 { - return ptr.ToUint16Slice(vs) -} - -// ToUint16Map returns a map of uint16 values, that are -// dereferenced if the passed in pointer was not nil. The uint16 -// zero value is used if the pointer was nil. -func ToUint16Map(vs map[string]*uint16) map[string]uint16 { - return ptr.ToUint16Map(vs) -} - -// ToUint32 returns uint32 value dereferenced if the passed -// in pointer was not nil. Returns a uint32 zero value if the -// pointer was nil. -func ToUint32(p *uint32) (v uint32) { - return ptr.ToUint32(p) -} - -// ToUint32Slice returns a slice of uint32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint32 -// zero value if the pointer was nil. -func ToUint32Slice(vs []*uint32) []uint32 { - return ptr.ToUint32Slice(vs) -} - -// ToUint32Map returns a map of uint32 values, that are -// dereferenced if the passed in pointer was not nil. The uint32 -// zero value is used if the pointer was nil. -func ToUint32Map(vs map[string]*uint32) map[string]uint32 { - return ptr.ToUint32Map(vs) -} - -// ToUint64 returns uint64 value dereferenced if the passed -// in pointer was not nil. Returns a uint64 zero value if the -// pointer was nil. -func ToUint64(p *uint64) (v uint64) { - return ptr.ToUint64(p) -} - -// ToUint64Slice returns a slice of uint64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint64 -// zero value if the pointer was nil. -func ToUint64Slice(vs []*uint64) []uint64 { - return ptr.ToUint64Slice(vs) -} - -// ToUint64Map returns a map of uint64 values, that are -// dereferenced if the passed in pointer was not nil. The uint64 -// zero value is used if the pointer was nil. -func ToUint64Map(vs map[string]*uint64) map[string]uint64 { - return ptr.ToUint64Map(vs) -} - -// ToFloat32 returns float32 value dereferenced if the passed -// in pointer was not nil. Returns a float32 zero value if the -// pointer was nil. -func ToFloat32(p *float32) (v float32) { - return ptr.ToFloat32(p) -} - -// ToFloat32Slice returns a slice of float32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a float32 -// zero value if the pointer was nil. -func ToFloat32Slice(vs []*float32) []float32 { - return ptr.ToFloat32Slice(vs) -} - -// ToFloat32Map returns a map of float32 values, that are -// dereferenced if the passed in pointer was not nil. The float32 -// zero value is used if the pointer was nil. -func ToFloat32Map(vs map[string]*float32) map[string]float32 { - return ptr.ToFloat32Map(vs) -} - -// ToFloat64 returns float64 value dereferenced if the passed -// in pointer was not nil. Returns a float64 zero value if the -// pointer was nil. -func ToFloat64(p *float64) (v float64) { - return ptr.ToFloat64(p) -} - -// ToFloat64Slice returns a slice of float64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a float64 -// zero value if the pointer was nil. -func ToFloat64Slice(vs []*float64) []float64 { - return ptr.ToFloat64Slice(vs) -} - -// ToFloat64Map returns a map of float64 values, that are -// dereferenced if the passed in pointer was not nil. The float64 -// zero value is used if the pointer was nil. -func ToFloat64Map(vs map[string]*float64) map[string]float64 { - return ptr.ToFloat64Map(vs) -} - -// ToTime returns time.Time value dereferenced if the passed -// in pointer was not nil. Returns a time.Time zero value if the -// pointer was nil. -func ToTime(p *time.Time) (v time.Time) { - return ptr.ToTime(p) -} - -// ToTimeSlice returns a slice of time.Time values, that are -// dereferenced if the passed in pointer was not nil. Returns a time.Time -// zero value if the pointer was nil. -func ToTimeSlice(vs []*time.Time) []time.Time { - return ptr.ToTimeSlice(vs) -} - -// ToTimeMap returns a map of time.Time values, that are -// dereferenced if the passed in pointer was not nil. The time.Time -// zero value is used if the pointer was nil. -func ToTimeMap(vs map[string]*time.Time) map[string]time.Time { - return ptr.ToTimeMap(vs) -} - -// ToDuration returns time.Duration value dereferenced if the passed -// in pointer was not nil. Returns a time.Duration zero value if the -// pointer was nil. -func ToDuration(p *time.Duration) (v time.Duration) { - return ptr.ToDuration(p) -} - -// ToDurationSlice returns a slice of time.Duration values, that are -// dereferenced if the passed in pointer was not nil. Returns a time.Duration -// zero value if the pointer was nil. -func ToDurationSlice(vs []*time.Duration) []time.Duration { - return ptr.ToDurationSlice(vs) -} - -// ToDurationMap returns a map of time.Duration values, that are -// dereferenced if the passed in pointer was not nil. The time.Duration -// zero value is used if the pointer was nil. -func ToDurationMap(vs map[string]*time.Duration) map[string]time.Duration { - return ptr.ToDurationMap(vs) -} 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 deleted file mode 100644 index 66d09630..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package aws - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.24.1" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/logging.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/logging.go deleted file mode 100644 index 91c94d98..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/logging.go +++ /dev/null @@ -1,119 +0,0 @@ -// Code generated by aws/logging_generate.go DO NOT EDIT. - -package aws - -// ClientLogMode represents the logging mode of SDK clients. The client logging mode is a bit-field where -// each bit is a flag that describes the logging behavior for one or more client components. -// The entire 64-bit group is reserved for later expansion by the SDK. -// -// Example: Setting ClientLogMode to enable logging of retries and requests -// -// clientLogMode := aws.LogRetries | aws.LogRequest -// -// Example: Adding an additional log mode to an existing ClientLogMode value -// -// clientLogMode |= aws.LogResponse -type ClientLogMode uint64 - -// Supported ClientLogMode bits that can be configured to toggle logging of specific SDK events. -const ( - LogSigning ClientLogMode = 1 << (64 - 1 - iota) - LogRetries - LogRequest - LogRequestWithBody - LogResponse - LogResponseWithBody - LogDeprecatedUsage - LogRequestEventMessage - LogResponseEventMessage -) - -// IsSigning returns whether the Signing logging mode bit is set -func (m ClientLogMode) IsSigning() bool { - return m&LogSigning != 0 -} - -// IsRetries returns whether the Retries logging mode bit is set -func (m ClientLogMode) IsRetries() bool { - return m&LogRetries != 0 -} - -// IsRequest returns whether the Request logging mode bit is set -func (m ClientLogMode) IsRequest() bool { - return m&LogRequest != 0 -} - -// IsRequestWithBody returns whether the RequestWithBody logging mode bit is set -func (m ClientLogMode) IsRequestWithBody() bool { - return m&LogRequestWithBody != 0 -} - -// IsResponse returns whether the Response logging mode bit is set -func (m ClientLogMode) IsResponse() bool { - return m&LogResponse != 0 -} - -// IsResponseWithBody returns whether the ResponseWithBody logging mode bit is set -func (m ClientLogMode) IsResponseWithBody() bool { - return m&LogResponseWithBody != 0 -} - -// IsDeprecatedUsage returns whether the DeprecatedUsage logging mode bit is set -func (m ClientLogMode) IsDeprecatedUsage() bool { - return m&LogDeprecatedUsage != 0 -} - -// IsRequestEventMessage returns whether the RequestEventMessage logging mode bit is set -func (m ClientLogMode) IsRequestEventMessage() bool { - return m&LogRequestEventMessage != 0 -} - -// IsResponseEventMessage returns whether the ResponseEventMessage logging mode bit is set -func (m ClientLogMode) IsResponseEventMessage() bool { - return m&LogResponseEventMessage != 0 -} - -// ClearSigning clears the Signing logging mode bit -func (m *ClientLogMode) ClearSigning() { - *m &^= LogSigning -} - -// ClearRetries clears the Retries logging mode bit -func (m *ClientLogMode) ClearRetries() { - *m &^= LogRetries -} - -// ClearRequest clears the Request logging mode bit -func (m *ClientLogMode) ClearRequest() { - *m &^= LogRequest -} - -// ClearRequestWithBody clears the RequestWithBody logging mode bit -func (m *ClientLogMode) ClearRequestWithBody() { - *m &^= LogRequestWithBody -} - -// ClearResponse clears the Response logging mode bit -func (m *ClientLogMode) ClearResponse() { - *m &^= LogResponse -} - -// ClearResponseWithBody clears the ResponseWithBody logging mode bit -func (m *ClientLogMode) ClearResponseWithBody() { - *m &^= LogResponseWithBody -} - -// ClearDeprecatedUsage clears the DeprecatedUsage logging mode bit -func (m *ClientLogMode) ClearDeprecatedUsage() { - *m &^= LogDeprecatedUsage -} - -// ClearRequestEventMessage clears the RequestEventMessage logging mode bit -func (m *ClientLogMode) ClearRequestEventMessage() { - *m &^= LogRequestEventMessage -} - -// ClearResponseEventMessage clears the ResponseEventMessage logging mode bit -func (m *ClientLogMode) ClearResponseEventMessage() { - *m &^= LogResponseEventMessage -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/logging_generate.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/logging_generate.go deleted file mode 100644 index 6ecc2231..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/logging_generate.go +++ /dev/null @@ -1,95 +0,0 @@ -//go:build clientlogmode -// +build clientlogmode - -package main - -import ( - "fmt" - "log" - "os" - "strings" - "text/template" -) - -var config = struct { - ModeBits []string -}{ - // Items should be appended only to keep bit-flag positions stable - ModeBits: []string{ - "Signing", - "Retries", - "Request", - "RequestWithBody", - "Response", - "ResponseWithBody", - "DeprecatedUsage", - "RequestEventMessage", - "ResponseEventMessage", - }, -} - -func bitName(name string) string { - return strings.ToUpper(name[:1]) + name[1:] -} - -var tmpl = template.Must(template.New("ClientLogMode").Funcs(map[string]interface{}{ - "symbolName": func(name string) string { - return "Log" + bitName(name) - }, - "bitName": bitName, -}).Parse(`// Code generated by aws/logging_generate.go DO NOT EDIT. - -package aws - -// ClientLogMode represents the logging mode of SDK clients. The client logging mode is a bit-field where -// each bit is a flag that describes the logging behavior for one or more client components. -// The entire 64-bit group is reserved for later expansion by the SDK. -// -// Example: Setting ClientLogMode to enable logging of retries and requests -// clientLogMode := aws.LogRetries | aws.LogRequest -// -// Example: Adding an additional log mode to an existing ClientLogMode value -// clientLogMode |= aws.LogResponse -type ClientLogMode uint64 - -// Supported ClientLogMode bits that can be configured to toggle logging of specific SDK events. -const ( -{{- range $index, $field := .ModeBits }} - {{ (symbolName $field) }}{{- if (eq 0 $index) }} ClientLogMode = 1 << (64 - 1 - iota){{- end }} -{{- end }} -) -{{ range $_, $field := .ModeBits }} -// Is{{- bitName $field }} returns whether the {{ bitName $field }} logging mode bit is set -func (m ClientLogMode) Is{{- bitName $field }}() bool { - return m&{{- (symbolName $field) }} != 0 -} -{{ end }} -{{- range $_, $field := .ModeBits }} -// Clear{{- bitName $field }} clears the {{ bitName $field }} logging mode bit -func (m *ClientLogMode) Clear{{- bitName $field }}() { - *m &^= {{ (symbolName $field) }} -} -{{ end -}} -`)) - -func main() { - uniqueBitFields := make(map[string]struct{}) - - for _, bitName := range config.ModeBits { - if _, ok := uniqueBitFields[strings.ToLower(bitName)]; ok { - panic(fmt.Sprintf("duplicate bit field: %s", bitName)) - } - uniqueBitFields[bitName] = struct{}{} - } - - file, err := os.Create("logging.go") - if err != nil { - log.Fatal(err) - } - defer file.Close() - - err = tmpl.Execute(file, config) - if err != nil { - log.Fatal(err) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/metadata.go deleted file mode 100644 index d66f0960..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/metadata.go +++ /dev/null @@ -1,213 +0,0 @@ -package middleware - -import ( - "context" - - "github.com/aws/aws-sdk-go-v2/aws" - - "github.com/aws/smithy-go/middleware" -) - -// RegisterServiceMetadata registers metadata about the service and operation into the middleware context -// so that it is available at runtime for other middleware to introspect. -type RegisterServiceMetadata struct { - ServiceID string - SigningName string - Region string - OperationName string -} - -// ID returns the middleware identifier. -func (s *RegisterServiceMetadata) ID() string { - return "RegisterServiceMetadata" -} - -// HandleInitialize registers service metadata information into the middleware context, allowing for introspection. -func (s RegisterServiceMetadata) HandleInitialize( - ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, -) (out middleware.InitializeOutput, metadata middleware.Metadata, err error) { - if len(s.ServiceID) > 0 { - ctx = SetServiceID(ctx, s.ServiceID) - } - if len(s.SigningName) > 0 { - ctx = SetSigningName(ctx, s.SigningName) - } - if len(s.Region) > 0 { - ctx = setRegion(ctx, s.Region) - } - if len(s.OperationName) > 0 { - ctx = setOperationName(ctx, s.OperationName) - } - return next.HandleInitialize(ctx, in) -} - -// service metadata keys for storing and lookup of runtime stack information. -type ( - serviceIDKey struct{} - signingNameKey struct{} - signingRegionKey struct{} - regionKey struct{} - operationNameKey struct{} - partitionIDKey struct{} - requiresLegacyEndpointsKey struct{} -) - -// GetServiceID retrieves the service id from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetServiceID(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, serviceIDKey{}).(string) - return v -} - -// GetSigningName retrieves the service signing name from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -// -// Deprecated: This value is unstable. The resolved signing name is available -// in the signer properties object passed to the signer. -func GetSigningName(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, signingNameKey{}).(string) - return v -} - -// GetSigningRegion retrieves the region from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -// -// Deprecated: This value is unstable. The resolved signing region is available -// in the signer properties object passed to the signer. -func GetSigningRegion(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, signingRegionKey{}).(string) - return v -} - -// GetRegion retrieves the endpoint region from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetRegion(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, regionKey{}).(string) - return v -} - -// GetOperationName retrieves the service operation metadata from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetOperationName(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, operationNameKey{}).(string) - return v -} - -// GetPartitionID retrieves the endpoint partition id from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetPartitionID(ctx context.Context) string { - v, _ := middleware.GetStackValue(ctx, partitionIDKey{}).(string) - return v -} - -// GetRequiresLegacyEndpoints the flag used to indicate if legacy endpoint -// customizations need to be executed. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetRequiresLegacyEndpoints(ctx context.Context) bool { - v, _ := middleware.GetStackValue(ctx, requiresLegacyEndpointsKey{}).(bool) - return v -} - -// SetRequiresLegacyEndpoints set or modifies the flag indicated that -// legacy endpoint customizations are needed. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetRequiresLegacyEndpoints(ctx context.Context, value bool) context.Context { - return middleware.WithStackValue(ctx, requiresLegacyEndpointsKey{}, value) -} - -// SetSigningName set or modifies the sigv4 or sigv4a signing name on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -// -// Deprecated: This value is unstable. Use WithSigV4SigningName client option -// funcs instead. -func SetSigningName(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, signingNameKey{}, value) -} - -// SetSigningRegion sets or modifies the region on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -// -// Deprecated: This value is unstable. Use WithSigV4SigningRegion client option -// funcs instead. -func SetSigningRegion(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, signingRegionKey{}, value) -} - -// SetServiceID sets the service id on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetServiceID(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, serviceIDKey{}, value) -} - -// setRegion sets the endpoint region on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func setRegion(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, regionKey{}, value) -} - -// setOperationName sets the service operation on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func setOperationName(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, operationNameKey{}, value) -} - -// SetPartitionID sets the partition id of a resolved region on the context -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetPartitionID(ctx context.Context, value string) context.Context { - return middleware.WithStackValue(ctx, partitionIDKey{}, value) -} - -// EndpointSource key -type endpointSourceKey struct{} - -// GetEndpointSource returns an endpoint source if set on context -func GetEndpointSource(ctx context.Context) (v aws.EndpointSource) { - v, _ = middleware.GetStackValue(ctx, endpointSourceKey{}).(aws.EndpointSource) - return v -} - -// SetEndpointSource sets endpoint source on context -func SetEndpointSource(ctx context.Context, value aws.EndpointSource) context.Context { - return middleware.WithStackValue(ctx, endpointSourceKey{}, value) -} - -type signingCredentialsKey struct{} - -// GetSigningCredentials returns the credentials that were used for signing if set on context. -func GetSigningCredentials(ctx context.Context) (v aws.Credentials) { - v, _ = middleware.GetStackValue(ctx, signingCredentialsKey{}).(aws.Credentials) - return v -} - -// SetSigningCredentials sets the credentails used for signing on the context. -func SetSigningCredentials(ctx context.Context, value aws.Credentials) context.Context { - return middleware.WithStackValue(ctx, signingCredentialsKey{}, value) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/middleware.go deleted file mode 100644 index 9bd0dfb1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/middleware.go +++ /dev/null @@ -1,168 +0,0 @@ -package middleware - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/internal/rand" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyrand "github.com/aws/smithy-go/rand" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// ClientRequestID is a Smithy BuildMiddleware that will generate a unique ID for logical API operation -// invocation. -type ClientRequestID struct{} - -// ID the identifier for the ClientRequestID -func (r *ClientRequestID) ID() string { - return "ClientRequestID" -} - -// HandleBuild attaches a unique operation invocation id for the operation to the request -func (r ClientRequestID) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", req) - } - - invocationID, err := smithyrand.NewUUID(rand.Reader).GetUUID() - if err != nil { - return out, metadata, err - } - - const invocationIDHeader = "Amz-Sdk-Invocation-Id" - req.Header[invocationIDHeader] = append(req.Header[invocationIDHeader][:0], invocationID) - - return next.HandleBuild(ctx, in) -} - -// RecordResponseTiming records the response timing for the SDK client requests. -type RecordResponseTiming struct{} - -// ID is the middleware identifier -func (a *RecordResponseTiming) ID() string { - return "RecordResponseTiming" -} - -// HandleDeserialize calculates response metadata and clock skew -func (a RecordResponseTiming) 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) - responseAt := sdk.NowTime() - setResponseAt(&metadata, responseAt) - - var serverTime time.Time - - switch resp := out.RawResponse.(type) { - case *smithyhttp.Response: - respDateHeader := resp.Header.Get("Date") - if len(respDateHeader) == 0 { - break - } - var parseErr error - serverTime, parseErr = smithyhttp.ParseTime(respDateHeader) - if parseErr != nil { - logger := middleware.GetLogger(ctx) - logger.Logf(logging.Warn, "failed to parse response Date header value, got %v", - parseErr.Error()) - break - } - setServerTime(&metadata, serverTime) - } - - if !serverTime.IsZero() { - attemptSkew := serverTime.Sub(responseAt) - setAttemptSkew(&metadata, attemptSkew) - } - - return out, metadata, err -} - -type responseAtKey struct{} - -// GetResponseAt returns the time response was received at. -func GetResponseAt(metadata middleware.Metadata) (v time.Time, ok bool) { - v, ok = metadata.Get(responseAtKey{}).(time.Time) - return v, ok -} - -// setResponseAt sets the response time on the metadata. -func setResponseAt(metadata *middleware.Metadata, v time.Time) { - metadata.Set(responseAtKey{}, v) -} - -type serverTimeKey struct{} - -// GetServerTime returns the server time for response. -func GetServerTime(metadata middleware.Metadata) (v time.Time, ok bool) { - v, ok = metadata.Get(serverTimeKey{}).(time.Time) - return v, ok -} - -// setServerTime sets the server time on the metadata. -func setServerTime(metadata *middleware.Metadata, v time.Time) { - metadata.Set(serverTimeKey{}, v) -} - -type attemptSkewKey struct{} - -// GetAttemptSkew returns Attempt clock skew for response from metadata. -func GetAttemptSkew(metadata middleware.Metadata) (v time.Duration, ok bool) { - v, ok = metadata.Get(attemptSkewKey{}).(time.Duration) - return v, ok -} - -// setAttemptSkew sets the attempt clock skew on the metadata. -func setAttemptSkew(metadata *middleware.Metadata, v time.Duration) { - metadata.Set(attemptSkewKey{}, v) -} - -// AddClientRequestIDMiddleware adds ClientRequestID to the middleware stack -func AddClientRequestIDMiddleware(stack *middleware.Stack) error { - return stack.Build.Add(&ClientRequestID{}, middleware.After) -} - -// AddRecordResponseTiming adds RecordResponseTiming middleware to the -// middleware stack. -func AddRecordResponseTiming(stack *middleware.Stack) error { - return stack.Deserialize.Add(&RecordResponseTiming{}, middleware.After) -} - -// rawResponseKey is the accessor key used to store and access the -// raw response within the response metadata. -type rawResponseKey struct{} - -// addRawResponse middleware adds raw response on to the metadata -type addRawResponse struct{} - -// ID the identifier for the ClientRequestID -func (m *addRawResponse) ID() string { - return "AddRawResponseToMetadata" -} - -// HandleDeserialize adds raw response on the middleware metadata -func (m addRawResponse) 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) - metadata.Set(rawResponseKey{}, out.RawResponse) - return out, metadata, err -} - -// AddRawResponseToMetadata adds middleware to the middleware stack that -// store raw response on to the metadata. -func AddRawResponseToMetadata(stack *middleware.Stack) error { - return stack.Deserialize.Add(&addRawResponse{}, middleware.Before) -} - -// GetRawResponse returns raw response set on metadata -func GetRawResponse(metadata middleware.Metadata) interface{} { - return metadata.Get(rawResponseKey{}) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname.go deleted file mode 100644 index ba262dad..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build go1.16 -// +build go1.16 - -package middleware - -import "runtime" - -func getNormalizedOSName() (os string) { - switch runtime.GOOS { - case "android": - os = "android" - case "linux": - os = "linux" - case "windows": - os = "windows" - case "darwin": - os = "macos" - case "ios": - os = "ios" - default: - os = "other" - } - return os -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname_go115.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname_go115.go deleted file mode 100644 index e14a1e4e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/osname_go115.go +++ /dev/null @@ -1,24 +0,0 @@ -//go:build !go1.16 -// +build !go1.16 - -package middleware - -import "runtime" - -func getNormalizedOSName() (os string) { - switch runtime.GOOS { - case "android": - os = "android" - case "linux": - os = "linux" - case "windows": - os = "windows" - case "darwin": - // Due to Apple M1 we can't distinguish between macOS and iOS when GOOS/GOARCH is darwin/amd64 - // For now declare this as "other" until we have a better detection mechanism. - fallthrough - default: - os = "other" - } - return os -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/private/metrics/metrics.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/private/metrics/metrics.go deleted file mode 100644 index b0133f4c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/private/metrics/metrics.go +++ /dev/null @@ -1,319 +0,0 @@ -// Package metrics implements metrics gathering for SDK development purposes. -// -// This package is designated as private and is intended for use only by the -// AWS client runtime. The exported API therein is not considered stable and -// is subject to breaking changes without notice. -package metrics - -import ( - "context" - "encoding/json" - "fmt" - "sync" - "time" - - "github.com/aws/smithy-go/middleware" -) - -const ( - // ServiceIDKey is the key for the service ID metric. - ServiceIDKey = "ServiceId" - // OperationNameKey is the key for the operation name metric. - OperationNameKey = "OperationName" - // ClientRequestIDKey is the key for the client request ID metric. - ClientRequestIDKey = "ClientRequestId" - // APICallDurationKey is the key for the API call duration metric. - APICallDurationKey = "ApiCallDuration" - // APICallSuccessfulKey is the key for the API call successful metric. - APICallSuccessfulKey = "ApiCallSuccessful" - // MarshallingDurationKey is the key for the marshalling duration metric. - MarshallingDurationKey = "MarshallingDuration" - // InThroughputKey is the key for the input throughput metric. - InThroughputKey = "InThroughput" - // OutThroughputKey is the key for the output throughput metric. - OutThroughputKey = "OutThroughput" - // RetryCountKey is the key for the retry count metric. - RetryCountKey = "RetryCount" - // HTTPStatusCodeKey is the key for the HTTP status code metric. - HTTPStatusCodeKey = "HttpStatusCode" - // AWSExtendedRequestIDKey is the key for the AWS extended request ID metric. - AWSExtendedRequestIDKey = "AwsExtendedRequestId" - // AWSRequestIDKey is the key for the AWS request ID metric. - AWSRequestIDKey = "AwsRequestId" - // BackoffDelayDurationKey is the key for the backoff delay duration metric. - BackoffDelayDurationKey = "BackoffDelayDuration" - // StreamThroughputKey is the key for the stream throughput metric. - StreamThroughputKey = "Throughput" - // ConcurrencyAcquireDurationKey is the key for the concurrency acquire duration metric. - ConcurrencyAcquireDurationKey = "ConcurrencyAcquireDuration" - // PendingConcurrencyAcquiresKey is the key for the pending concurrency acquires metric. - PendingConcurrencyAcquiresKey = "PendingConcurrencyAcquires" - // SigningDurationKey is the key for the signing duration metric. - SigningDurationKey = "SigningDuration" - // UnmarshallingDurationKey is the key for the unmarshalling duration metric. - UnmarshallingDurationKey = "UnmarshallingDuration" - // TimeToFirstByteKey is the key for the time to first byte metric. - TimeToFirstByteKey = "TimeToFirstByte" - // ServiceCallDurationKey is the key for the service call duration metric. - ServiceCallDurationKey = "ServiceCallDuration" - // EndpointResolutionDurationKey is the key for the endpoint resolution duration metric. - EndpointResolutionDurationKey = "EndpointResolutionDuration" - // AttemptNumberKey is the key for the attempt number metric. - AttemptNumberKey = "AttemptNumber" - // MaxConcurrencyKey is the key for the max concurrency metric. - MaxConcurrencyKey = "MaxConcurrency" - // AvailableConcurrencyKey is the key for the available concurrency metric. - AvailableConcurrencyKey = "AvailableConcurrency" -) - -// MetricPublisher provides the interface to provide custom MetricPublishers. -// PostRequestMetrics will be invoked by the MetricCollection middleware to post request. -// PostStreamMetrics will be invoked by ReadCloserWithMetrics to post stream metrics. -type MetricPublisher interface { - PostRequestMetrics(*MetricData) error - PostStreamMetrics(*MetricData) error -} - -// Serializer provides the interface to provide custom Serializers. -// Serialize will transform any input object in its corresponding string representation. -type Serializer interface { - Serialize(obj interface{}) (string, error) -} - -// DefaultSerializer is an implementation of the Serializer interface. -type DefaultSerializer struct{} - -// Serialize uses the default JSON serializer to obtain the string representation of an object. -func (DefaultSerializer) Serialize(obj interface{}) (string, error) { - bytes, err := json.Marshal(obj) - if err != nil { - return "", err - } - return string(bytes), nil -} - -type metricContextKey struct{} - -// MetricContext contains fields to store metric-related information. -type MetricContext struct { - connectionCounter *SharedConnectionCounter - publisher MetricPublisher - data *MetricData -} - -// MetricData stores the collected metric data. -type MetricData struct { - RequestStartTime time.Time - RequestEndTime time.Time - APICallDuration time.Duration - SerializeStartTime time.Time - SerializeEndTime time.Time - MarshallingDuration time.Duration - ResolveEndpointStartTime time.Time - ResolveEndpointEndTime time.Time - EndpointResolutionDuration time.Duration - InThroughput float64 - OutThroughput float64 - RetryCount int - Success uint8 - StatusCode int - ClientRequestID string - ServiceID string - OperationName string - PartitionID string - Region string - RequestContentLength int64 - Stream StreamMetrics - Attempts []AttemptMetrics -} - -// StreamMetrics stores metrics related to streaming data. -type StreamMetrics struct { - ReadDuration time.Duration - ReadBytes int64 - Throughput float64 -} - -// AttemptMetrics stores metrics related to individual attempts. -type AttemptMetrics struct { - ServiceCallStart time.Time - ServiceCallEnd time.Time - ServiceCallDuration time.Duration - FirstByteTime time.Time - TimeToFirstByte time.Duration - ConnRequestedTime time.Time - ConnObtainedTime time.Time - ConcurrencyAcquireDuration time.Duration - CredentialFetchStartTime time.Time - CredentialFetchEndTime time.Time - SignStartTime time.Time - SignEndTime time.Time - SigningDuration time.Duration - DeserializeStartTime time.Time - DeserializeEndTime time.Time - UnMarshallingDuration time.Duration - RetryDelay time.Duration - ResponseContentLength int64 - StatusCode int - RequestID string - ExtendedRequestID string - HTTPClient string - MaxConcurrency int - PendingConnectionAcquires int - AvailableConcurrency int - ActiveRequests int - ReusedConnection bool -} - -// Data returns the MetricData associated with the MetricContext. -func (mc *MetricContext) Data() *MetricData { - return mc.data -} - -// ConnectionCounter returns the SharedConnectionCounter associated with the MetricContext. -func (mc *MetricContext) ConnectionCounter() *SharedConnectionCounter { - return mc.connectionCounter -} - -// Publisher returns the MetricPublisher associated with the MetricContext. -func (mc *MetricContext) Publisher() MetricPublisher { - return mc.publisher -} - -// ComputeRequestMetrics calculates and populates derived metrics based on the collected data. -func (md *MetricData) ComputeRequestMetrics() { - - for idx := range md.Attempts { - attempt := &md.Attempts[idx] - attempt.ConcurrencyAcquireDuration = attempt.ConnObtainedTime.Sub(attempt.ConnRequestedTime) - attempt.SigningDuration = attempt.SignEndTime.Sub(attempt.SignStartTime) - attempt.UnMarshallingDuration = attempt.DeserializeEndTime.Sub(attempt.DeserializeStartTime) - attempt.TimeToFirstByte = attempt.FirstByteTime.Sub(attempt.ServiceCallStart) - attempt.ServiceCallDuration = attempt.ServiceCallEnd.Sub(attempt.ServiceCallStart) - } - - md.APICallDuration = md.RequestEndTime.Sub(md.RequestStartTime) - md.MarshallingDuration = md.SerializeEndTime.Sub(md.SerializeStartTime) - md.EndpointResolutionDuration = md.ResolveEndpointEndTime.Sub(md.ResolveEndpointStartTime) - - md.RetryCount = len(md.Attempts) - 1 - - latestAttempt, err := md.LatestAttempt() - - if err != nil { - fmt.Printf("error retrieving attempts data due to: %s. Skipping Throughput metrics", err.Error()) - } else { - - md.StatusCode = latestAttempt.StatusCode - - if md.Success == 1 { - if latestAttempt.ResponseContentLength > 0 && latestAttempt.ServiceCallDuration > 0 { - md.InThroughput = float64(latestAttempt.ResponseContentLength) / latestAttempt.ServiceCallDuration.Seconds() - } - if md.RequestContentLength > 0 && latestAttempt.ServiceCallDuration > 0 { - md.OutThroughput = float64(md.RequestContentLength) / latestAttempt.ServiceCallDuration.Seconds() - } - } - } -} - -// LatestAttempt returns the latest attempt metrics. -// It returns an error if no attempts are initialized. -func (md *MetricData) LatestAttempt() (*AttemptMetrics, error) { - if md.Attempts == nil || len(md.Attempts) == 0 { - return nil, fmt.Errorf("no attempts initialized. NewAttempt() should be called first") - } - return &md.Attempts[len(md.Attempts)-1], nil -} - -// NewAttempt initializes new attempt metrics. -func (md *MetricData) NewAttempt() { - if md.Attempts == nil { - md.Attempts = []AttemptMetrics{} - } - md.Attempts = append(md.Attempts, AttemptMetrics{}) -} - -// SharedConnectionCounter is a counter shared across API calls. -type SharedConnectionCounter struct { - mu sync.Mutex - - activeRequests int - pendingConnectionAcquire int -} - -// ActiveRequests returns the count of active requests. -func (cc *SharedConnectionCounter) ActiveRequests() int { - cc.mu.Lock() - defer cc.mu.Unlock() - - return cc.activeRequests -} - -// PendingConnectionAcquire returns the count of pending connection acquires. -func (cc *SharedConnectionCounter) PendingConnectionAcquire() int { - cc.mu.Lock() - defer cc.mu.Unlock() - - return cc.pendingConnectionAcquire -} - -// AddActiveRequest increments the count of active requests. -func (cc *SharedConnectionCounter) AddActiveRequest() { - cc.mu.Lock() - defer cc.mu.Unlock() - - cc.activeRequests++ -} - -// RemoveActiveRequest decrements the count of active requests. -func (cc *SharedConnectionCounter) RemoveActiveRequest() { - cc.mu.Lock() - defer cc.mu.Unlock() - - cc.activeRequests-- -} - -// AddPendingConnectionAcquire increments the count of pending connection acquires. -func (cc *SharedConnectionCounter) AddPendingConnectionAcquire() { - cc.mu.Lock() - defer cc.mu.Unlock() - - cc.pendingConnectionAcquire++ -} - -// RemovePendingConnectionAcquire decrements the count of pending connection acquires. -func (cc *SharedConnectionCounter) RemovePendingConnectionAcquire() { - cc.mu.Lock() - defer cc.mu.Unlock() - - cc.pendingConnectionAcquire-- -} - -// InitMetricContext initializes the metric context with the provided counter and publisher. -// It returns the updated context. -func InitMetricContext( - ctx context.Context, counter *SharedConnectionCounter, publisher MetricPublisher, -) context.Context { - if middleware.GetStackValue(ctx, metricContextKey{}) == nil { - ctx = middleware.WithStackValue(ctx, metricContextKey{}, &MetricContext{ - connectionCounter: counter, - publisher: publisher, - data: &MetricData{ - Attempts: []AttemptMetrics{}, - Stream: StreamMetrics{}, - }, - }) - } - return ctx -} - -// Context returns the metric context from the given context. -// It returns nil if the metric context is not found. -func Context(ctx context.Context) *MetricContext { - mctx := middleware.GetStackValue(ctx, metricContextKey{}) - if mctx == nil { - return nil - } - return mctx.(*MetricContext) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/recursion_detection.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/recursion_detection.go deleted file mode 100644 index 3f6aaf23..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/recursion_detection.go +++ /dev/null @@ -1,94 +0,0 @@ -package middleware - -import ( - "context" - "fmt" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "os" -) - -const envAwsLambdaFunctionName = "AWS_LAMBDA_FUNCTION_NAME" -const envAmznTraceID = "_X_AMZN_TRACE_ID" -const amznTraceIDHeader = "X-Amzn-Trace-Id" - -// AddRecursionDetection adds recursionDetection to the middleware stack -func AddRecursionDetection(stack *middleware.Stack) error { - return stack.Build.Add(&RecursionDetection{}, middleware.After) -} - -// RecursionDetection detects Lambda environment and sets its X-Ray trace ID to request header if absent -// to avoid recursion invocation in Lambda -type RecursionDetection struct{} - -// ID returns the middleware identifier -func (m *RecursionDetection) ID() string { - return "RecursionDetection" -} - -// HandleBuild detects Lambda environment and adds its trace ID to request header if absent -func (m *RecursionDetection) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown request type %T", req) - } - - _, hasLambdaEnv := os.LookupEnv(envAwsLambdaFunctionName) - xAmznTraceID, hasTraceID := os.LookupEnv(envAmznTraceID) - value := req.Header.Get(amznTraceIDHeader) - // only set the X-Amzn-Trace-Id header when it is not set initially, the - // current environment is Lambda and the _X_AMZN_TRACE_ID env variable exists - if value != "" || !hasLambdaEnv || !hasTraceID { - return next.HandleBuild(ctx, in) - } - - req.Header.Set(amznTraceIDHeader, percentEncode(xAmznTraceID)) - return next.HandleBuild(ctx, in) -} - -func percentEncode(s string) string { - upperhex := "0123456789ABCDEF" - hexCount := 0 - for i := 0; i < len(s); i++ { - c := s[i] - if shouldEncode(c) { - hexCount++ - } - } - - if hexCount == 0 { - return s - } - - required := len(s) + 2*hexCount - t := make([]byte, required) - j := 0 - for i := 0; i < len(s); i++ { - if c := s[i]; shouldEncode(c) { - t[j] = '%' - t[j+1] = upperhex[c>>4] - t[j+2] = upperhex[c&15] - j += 3 - } else { - t[j] = c - j++ - } - } - return string(t) -} - -func shouldEncode(c byte) bool { - if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { - return false - } - switch c { - case '-', '=', ';', ':', '+', '&', '[', ']', '{', '}', '"', '\'', ',': - return false - default: - return true - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id.go deleted file mode 100644 index dd3391fe..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id.go +++ /dev/null @@ -1,27 +0,0 @@ -package middleware - -import ( - "github.com/aws/smithy-go/middleware" -) - -// requestIDKey is used to retrieve request id from response metadata -type requestIDKey struct{} - -// SetRequestIDMetadata sets the provided request id over middleware metadata -func SetRequestIDMetadata(metadata *middleware.Metadata, id string) { - metadata.Set(requestIDKey{}, id) -} - -// GetRequestIDMetadata retrieves the request id from middleware metadata -// returns string and bool indicating value of request id, whether request id was set. -func GetRequestIDMetadata(metadata middleware.Metadata) (string, bool) { - if !metadata.Has(requestIDKey{}) { - return "", false - } - - v, ok := metadata.Get(requestIDKey{}).(string) - if !ok { - return "", true - } - return v, true -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id_retriever.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id_retriever.go deleted file mode 100644 index 7ce48c61..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/request_id_retriever.go +++ /dev/null @@ -1,49 +0,0 @@ -package middleware - -import ( - "context" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// AddRequestIDRetrieverMiddleware adds request id retriever middleware -func AddRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - // add error wrapper middleware before operation deserializers so that it can wrap the error response - // returned by operation deserializers - return stack.Deserialize.Insert(&requestIDRetriever{}, "OperationDeserializer", middleware.Before) -} - -type requestIDRetriever struct { -} - -// ID returns the middleware identifier -func (m *requestIDRetriever) ID() string { - return "RequestIDRetriever" -} - -func (m *requestIDRetriever) 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) - - resp, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - // No raw response to wrap with. - return out, metadata, err - } - - // Different header which can map to request id - requestIDHeaderList := []string{"X-Amzn-Requestid", "X-Amz-RequestId"} - - for _, h := range requestIDHeaderList { - // check for headers known to contain Request id - if v := resp.Header.Get(h); len(v) != 0 { - // set reqID on metadata for successful responses. - SetRequestIDMetadata(&metadata, v) - break - } - } - - return out, metadata, err -} 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 deleted file mode 100644 index af3447dd..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/middleware/user_agent.go +++ /dev/null @@ -1,261 +0,0 @@ -package middleware - -import ( - "context" - "fmt" - "os" - "runtime" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -var languageVersion = strings.TrimPrefix(runtime.Version(), "go") - -// SDKAgentKeyType is the metadata type to add to the SDK agent string -type SDKAgentKeyType int - -// The set of valid SDKAgentKeyType constants. If an unknown value is assigned for SDKAgentKeyType it will -// be mapped to AdditionalMetadata. -const ( - _ SDKAgentKeyType = iota - APIMetadata - OperatingSystemMetadata - LanguageMetadata - EnvironmentMetadata - FeatureMetadata - ConfigMetadata - FrameworkMetadata - AdditionalMetadata - ApplicationIdentifier -) - -func (k SDKAgentKeyType) string() string { - switch k { - case APIMetadata: - return "api" - case OperatingSystemMetadata: - return "os" - case LanguageMetadata: - return "lang" - case EnvironmentMetadata: - return "exec-env" - case FeatureMetadata: - return "ft" - case ConfigMetadata: - return "cfg" - case FrameworkMetadata: - return "lib" - case ApplicationIdentifier: - return "app" - case AdditionalMetadata: - fallthrough - default: - return "md" - } -} - -const execEnvVar = `AWS_EXECUTION_ENV` - -var validChars = map[rune]bool{ - '!': true, '#': true, '$': true, '%': true, '&': true, '\'': true, '*': true, '+': true, - '-': true, '.': true, '^': true, '_': true, '`': true, '|': true, '~': true, -} - -// requestUserAgent is a build middleware that set the User-Agent for the request. -type requestUserAgent struct { - sdkAgent, userAgent *smithyhttp.UserAgentBuilder -} - -// newRequestUserAgent returns a new requestUserAgent which will set the User-Agent and X-Amz-User-Agent for the -// request. -// -// User-Agent example: -// -// aws-sdk-go-v2/1.2.3 -// -// X-Amz-User-Agent example: -// -// aws-sdk-go-v2/1.2.3 md/GOOS/linux md/GOARCH/amd64 lang/go/1.15 -func newRequestUserAgent() *requestUserAgent { - userAgent, sdkAgent := smithyhttp.NewUserAgentBuilder(), smithyhttp.NewUserAgentBuilder() - addProductName(userAgent) - addProductName(sdkAgent) - - r := &requestUserAgent{ - sdkAgent: sdkAgent, - userAgent: userAgent, - } - - addSDKMetadata(r) - - return r -} - -func addSDKMetadata(r *requestUserAgent) { - r.AddSDKAgentKey(OperatingSystemMetadata, getNormalizedOSName()) - r.AddSDKAgentKeyValue(LanguageMetadata, "go", languageVersion) - r.AddSDKAgentKeyValue(AdditionalMetadata, "GOOS", runtime.GOOS) - r.AddSDKAgentKeyValue(AdditionalMetadata, "GOARCH", runtime.GOARCH) - if ev := os.Getenv(execEnvVar); len(ev) > 0 { - r.AddSDKAgentKey(EnvironmentMetadata, ev) - } -} - -func addProductName(builder *smithyhttp.UserAgentBuilder) { - builder.AddKeyValue(aws.SDKName, aws.SDKVersion) -} - -// AddUserAgentKey retrieves a requestUserAgent from the provided stack, or initializes one. -func AddUserAgentKey(key string) func(*middleware.Stack) error { - return func(stack *middleware.Stack) error { - requestUserAgent, err := getOrAddRequestUserAgent(stack) - if err != nil { - return err - } - requestUserAgent.AddUserAgentKey(key) - return nil - } -} - -// AddUserAgentKeyValue retrieves a requestUserAgent from the provided stack, or initializes one. -func AddUserAgentKeyValue(key, value string) func(*middleware.Stack) error { - return func(stack *middleware.Stack) error { - requestUserAgent, err := getOrAddRequestUserAgent(stack) - if err != nil { - return err - } - requestUserAgent.AddUserAgentKeyValue(key, value) - return nil - } -} - -// AddSDKAgentKey retrieves a requestUserAgent from the provided stack, or initializes one. -func AddSDKAgentKey(keyType SDKAgentKeyType, key string) func(*middleware.Stack) error { - return func(stack *middleware.Stack) error { - requestUserAgent, err := getOrAddRequestUserAgent(stack) - if err != nil { - return err - } - requestUserAgent.AddSDKAgentKey(keyType, key) - return nil - } -} - -// AddSDKAgentKeyValue retrieves a requestUserAgent from the provided stack, or initializes one. -func AddSDKAgentKeyValue(keyType SDKAgentKeyType, key, value string) func(*middleware.Stack) error { - return func(stack *middleware.Stack) error { - requestUserAgent, err := getOrAddRequestUserAgent(stack) - if err != nil { - return err - } - requestUserAgent.AddSDKAgentKeyValue(keyType, key, value) - return nil - } -} - -// AddRequestUserAgentMiddleware registers a requestUserAgent middleware on the stack if not present. -func AddRequestUserAgentMiddleware(stack *middleware.Stack) error { - _, err := getOrAddRequestUserAgent(stack) - return err -} - -func getOrAddRequestUserAgent(stack *middleware.Stack) (*requestUserAgent, error) { - id := (*requestUserAgent)(nil).ID() - bm, ok := stack.Build.Get(id) - if !ok { - bm = newRequestUserAgent() - err := stack.Build.Add(bm, middleware.After) - if err != nil { - return nil, err - } - } - - requestUserAgent, ok := bm.(*requestUserAgent) - if !ok { - return nil, fmt.Errorf("%T for %s middleware did not match expected type", bm, id) - } - - return requestUserAgent, nil -} - -// AddUserAgentKey adds the component identified by name to the User-Agent string. -func (u *requestUserAgent) AddUserAgentKey(key string) { - u.userAgent.AddKey(strings.Map(rules, key)) -} - -// AddUserAgentKeyValue adds the key identified by the given name and value to the User-Agent string. -func (u *requestUserAgent) AddUserAgentKeyValue(key, value string) { - u.userAgent.AddKeyValue(strings.Map(rules, key), strings.Map(rules, value)) -} - -// AddUserAgentKey adds the component identified by name to the User-Agent string. -func (u *requestUserAgent) AddSDKAgentKey(keyType SDKAgentKeyType, key string) { - // TODO: should target sdkAgent - u.userAgent.AddKey(keyType.string() + "/" + strings.Map(rules, key)) -} - -// AddUserAgentKeyValue adds the key identified by the given name and value to the User-Agent string. -func (u *requestUserAgent) AddSDKAgentKeyValue(keyType SDKAgentKeyType, key, value string) { - // TODO: should target sdkAgent - u.userAgent.AddKeyValue(keyType.string(), strings.Map(rules, key)+"#"+strings.Map(rules, value)) -} - -// ID the name of the middleware. -func (u *requestUserAgent) ID() string { - return "UserAgent" -} - -// HandleBuild adds or appends the constructed user agent to the request. -func (u *requestUserAgent) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - switch req := in.Request.(type) { - case *smithyhttp.Request: - u.addHTTPUserAgent(req) - // TODO: To be re-enabled - // u.addHTTPSDKAgent(req) - default: - return out, metadata, fmt.Errorf("unknown transport type %T", in) - } - - return next.HandleBuild(ctx, in) -} - -func (u *requestUserAgent) addHTTPUserAgent(request *smithyhttp.Request) { - const userAgent = "User-Agent" - updateHTTPHeader(request, userAgent, u.userAgent.Build()) -} - -func (u *requestUserAgent) addHTTPSDKAgent(request *smithyhttp.Request) { - const sdkAgent = "X-Amz-User-Agent" - updateHTTPHeader(request, sdkAgent, u.sdkAgent.Build()) -} - -func updateHTTPHeader(request *smithyhttp.Request, header string, value string) { - var current string - if v := request.Header[header]; len(v) > 0 { - current = v[0] - } - if len(current) > 0 { - current = value + " " + current - } else { - current = value - } - request.Header[header] = append(request.Header[header][:0], current) -} - -func rules(r rune) rune { - switch { - case r >= '0' && r <= '9': - return r - case r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z': - return r - case validChars[r]: - return r - default: - return '-' - } -} 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 deleted file mode 100644 index 47ebc0f5..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/array.go +++ /dev/null @@ -1,72 +0,0 @@ -package query - -import ( - "fmt" - "net/url" -) - -// Array represents the encoding of Query lists and sets. A Query array is a -// representation of a list of values of a fixed type. A serialized array might -// look like the following: -// -// ListName.member.1=foo -// &ListName.member.2=bar -// &Listname.member.3=baz -type Array struct { - // The query values to add the array to. - values url.Values - // The array's prefix, which includes the names of all parent structures - // and ends with the name of the list. For example, the prefix might be - // "ParentStructure.ListName". This prefix will be used to form the full - // 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. - 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 - // remove this encoding - emptyValue Value -} - -func newArray(values url.Values, prefix string, flat bool, memberName string) *Array { - emptyValue := newValue(values, prefix, flat) - emptyValue.String("") - - return &Array{ - values: values, - prefix: prefix, - flat: flat, - memberName: memberName, - emptyValue: emptyValue, - } -} - -// Value adds a new element to the Query Array. Returns a Value type used to -// encode the array element. -func (a *Array) Value() Value { - if a.size == 0 { - delete(a.values, a.emptyValue.key) - } - - // 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) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/encoder.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/encoder.go deleted file mode 100644 index 2ecf9241..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/encoder.go +++ /dev/null @@ -1,80 +0,0 @@ -package query - -import ( - "io" - "net/url" - "sort" -) - -// Encoder is a Query encoder that supports construction of Query body -// values using methods. -type Encoder struct { - // The query values that will be built up to manage encoding. - values url.Values - // The writer that the encoded body will be written to. - writer io.Writer - Value -} - -// NewEncoder returns a new Query body encoder -func NewEncoder(writer io.Writer) *Encoder { - values := url.Values{} - return &Encoder{ - values: values, - writer: writer, - Value: newBaseValue(values), - } -} - -// Encode returns the []byte slice representing the current -// state of the Query encoder. -func (e Encoder) Encode() error { - ws, ok := e.writer.(interface{ WriteString(string) (int, error) }) - if !ok { - // Fall back to less optimal byte slice casting if WriteString isn't available. - ws = &wrapWriteString{writer: e.writer} - } - - // Get the keys and sort them to have a stable output - keys := make([]string, 0, len(e.values)) - for k := range e.values { - keys = append(keys, k) - } - sort.Strings(keys) - isFirstEntry := true - for _, key := range keys { - queryValues := e.values[key] - escapedKey := url.QueryEscape(key) - for _, value := range queryValues { - if !isFirstEntry { - if _, err := ws.WriteString(`&`); err != nil { - return err - } - } else { - isFirstEntry = false - } - if _, err := ws.WriteString(escapedKey); err != nil { - return err - } - if _, err := ws.WriteString(`=`); err != nil { - return err - } - if _, err := ws.WriteString(url.QueryEscape(value)); err != nil { - return err - } - } - } - return nil -} - -// wrapWriteString wraps an io.Writer to provide a WriteString method -// where one is not available. -type wrapWriteString struct { - writer io.Writer -} - -// WriteString writes a string to the wrapped writer by casting it to -// a byte array first. -func (w wrapWriteString) WriteString(v string) (int, error) { - return w.writer.Write([]byte(v)) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/map.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/map.go deleted file mode 100644 index dea242b8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/map.go +++ /dev/null @@ -1,78 +0,0 @@ -package query - -import ( - "fmt" - "net/url" -) - -// Map represents the encoding of Query maps. A Query map is a representation -// of a mapping of arbitrary string keys to arbitrary values of a fixed type. -// A Map differs from an Object in that the set of keys is not fixed, in that -// the values must all be of the same type, and that map entries are ordered. -// A serialized map might look like the following: -// -// MapName.entry.1.key=Foo -// &MapName.entry.1.value=spam -// &MapName.entry.2.key=Bar -// &MapName.entry.2.value=eggs -type Map struct { - // The query values to add the map to. - values url.Values - // The map's prefix, which includes the names of all parent structures - // and ends with the name of the object. For example, the prefix might be - // "ParentStructure.MapName". This prefix will be used to form the full - // keys for each key-value pair of the map. For example, a value might have - // the key "ParentStructure.MapName.1.value". - // - // 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. - prefix string - // Whether the map is flat or not. A map that is not flat will produce the - // following entries to the url.Values for a given key-value pair: - // MapName.entry.1.KeyLocationName=mykey - // MapName.entry.1.ValueLocationName=myvalue - // A map that is flat will produce the following: - // MapName.1.KeyLocationName=mykey - // MapName.1.ValueLocationName=myvalue - flat bool - // The location name of the key. In most cases this should be "key". - keyLocationName string - // The location name of the value. In most cases this should be "value". - valueLocationName string - // Elements are stored in values, so we keep track of the list size here. - size int32 -} - -func newMap(values url.Values, prefix string, flat bool, keyLocationName string, valueLocationName string) *Map { - return &Map{ - values: values, - prefix: prefix, - flat: flat, - keyLocationName: keyLocationName, - valueLocationName: valueLocationName, - } -} - -// Key adds the given named key to the Query map. -// Returns a Value encoder that should be used to encode a Query value type. -func (m *Map) Key(name string) Value { - // Query lists start a 1, so adjust the size first - m.size++ - var key string - var value string - if m.flat { - key = fmt.Sprintf("%s.%d.%s", m.prefix, m.size, m.keyLocationName) - value = fmt.Sprintf("%s.%d.%s", m.prefix, m.size, m.valueLocationName) - } else { - key = fmt.Sprintf("%s.entry.%d.%s", m.prefix, m.size, m.keyLocationName) - value = fmt.Sprintf("%s.entry.%d.%s", m.prefix, m.size, m.valueLocationName) - } - - // The key can only be a string, so we just go ahead and set it here - newValue(m.values, key, false).String(name) - - // Maps can't have flat members - return newValue(m.values, value, false) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/middleware.go deleted file mode 100644 index 36034479..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/middleware.go +++ /dev/null @@ -1,62 +0,0 @@ -package query - -import ( - "context" - "fmt" - "io/ioutil" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// AddAsGetRequestMiddleware adds a middleware to the Serialize stack after the -// operation serializer that will convert the query request body to a GET -// operation with the query message in the HTTP request querystring. -func AddAsGetRequestMiddleware(stack *middleware.Stack) error { - return stack.Serialize.Insert(&asGetRequest{}, "OperationSerializer", middleware.After) -} - -type asGetRequest struct{} - -func (*asGetRequest) ID() string { return "Query:AsGetRequest" } - -func (m *asGetRequest) HandleSerialize( - ctx context.Context, input middleware.SerializeInput, next middleware.SerializeHandler, -) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - req, ok := input.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("expect smithy HTTP Request, got %T", input.Request) - } - - req.Method = "GET" - - // If the stream is not set, nothing else to do. - stream := req.GetStream() - if stream == nil { - return next.HandleSerialize(ctx, input) - } - - // Clear the stream since there will not be any body. - req.Header.Del("Content-Type") - req, err = req.SetStream(nil) - if err != nil { - return out, metadata, fmt.Errorf("unable update request body %w", err) - } - input.Request = req - - // Update request query with the body's query string value. - delim := "" - if len(req.URL.RawQuery) != 0 { - delim = "&" - } - - b, err := ioutil.ReadAll(stream) - if err != nil { - return out, metadata, fmt.Errorf("unable to get request body %w", err) - } - req.URL.RawQuery += delim + string(b) - - return next.HandleSerialize(ctx, input) -} 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 deleted file mode 100644 index 455b9251..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/object.go +++ /dev/null @@ -1,69 +0,0 @@ -package query - -import ( - "fmt" - "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 -// values where there is a fixed set of keys whose values each have their -// own known type. A serialized object might look like the following: -// -// ObjectName.Foo=value -// &ObjectName.Bar=5 -type Object struct { - // The query values to add the object to. - values url.Values - // The object's prefix, which includes the names of all parent structures - // and ends with the name of the object. For example, the prefix might be - // "ParentStructure.ObjectName". This prefix will be used to form the full - // keys for each member of the object. For example, a member might have the - // key "ParentStructure.ObjectName.MemberName". - // - // 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. - prefix string -} - -func newObject(values url.Values, prefix string) *Object { - return &Object{ - values: values, - prefix: prefix, - } -} - -// Key adds the given named key to the Query object. -// Returns a Value encoder that should be used to encode a Query value type. -func (o *Object) Key(name string) Value { - return o.key(name, false) -} - -// KeyWithValues adds the given named key to the Query object. -// Returns a Value encoder that should be used to encode a Query list of values. -func (o *Object) KeyWithValues(name string) Value { - return o.keyWithValues(name, false) -} - -// FlatKey adds the given named key to the Query object. -// Returns a Value encoder that should be used to encode a Query value type. The -// value will be flattened if it is a map or array. -func (o *Object) FlatKey(name string) Value { - return o.key(name, true) -} - -func (o *Object) key(name string, flatValue bool) Value { - if o.prefix != "" { - return newValue(o.values, fmt.Sprintf("%s.%s", o.prefix, 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) - } - 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 deleted file mode 100644 index a9251521..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/query/value.go +++ /dev/null @@ -1,115 +0,0 @@ -package query - -import ( - "math/big" - "net/url" - - "github.com/aws/smithy-go/encoding/httpbinding" -) - -// Value represents a Query Value type. -type Value struct { - // The query values to add the value to. - values url.Values - // The value's key, which will form the prefix for complex types. - key string - // Whether the value should be flattened or not if it's a flattenable type. - flat bool - queryValue httpbinding.QueryValue -} - -func newValue(values url.Values, key string, flat bool) Value { - return Value{ - values: values, - key: key, - flat: flat, - queryValue: httpbinding.NewQueryValue(values, key, false), - } -} - -func newAppendValue(values url.Values, key string, flat bool) Value { - return Value{ - values: values, - key: key, - flat: flat, - queryValue: httpbinding.NewQueryValue(values, key, true), - } -} - -func newBaseValue(values url.Values) Value { - return Value{ - values: values, - queryValue: httpbinding.NewQueryValue(nil, "", false), - } -} - -// Array returns a new Array encoder. -func (qv Value) Array(locationName string) *Array { - return newArray(qv.values, qv.key, qv.flat, locationName) -} - -// Object returns a new Object encoder. -func (qv Value) Object() *Object { - return newObject(qv.values, qv.key) -} - -// Map returns a new Map encoder. -func (qv Value) Map(keyLocationName string, valueLocationName string) *Map { - return newMap(qv.values, qv.key, qv.flat, keyLocationName, valueLocationName) -} - -// Base64EncodeBytes encodes v as a base64 query string value. -// This is intended to enable compatibility with the JSON encoder. -func (qv Value) Base64EncodeBytes(v []byte) { - qv.queryValue.Blob(v) -} - -// Boolean encodes v as a query string value -func (qv Value) Boolean(v bool) { - qv.queryValue.Boolean(v) -} - -// String encodes v as a query string value -func (qv Value) String(v string) { - qv.queryValue.String(v) -} - -// Byte encodes v as a query string value -func (qv Value) Byte(v int8) { - qv.queryValue.Byte(v) -} - -// Short encodes v as a query string value -func (qv Value) Short(v int16) { - qv.queryValue.Short(v) -} - -// Integer encodes v as a query string value -func (qv Value) Integer(v int32) { - qv.queryValue.Integer(v) -} - -// Long encodes v as a query string value -func (qv Value) Long(v int64) { - qv.queryValue.Long(v) -} - -// Float encodes v as a query string value -func (qv Value) Float(v float32) { - qv.queryValue.Float(v) -} - -// Double encodes v as a query string value -func (qv Value) Double(v float64) { - qv.queryValue.Double(v) -} - -// BigInteger encodes v as a query string value -func (qv Value) BigInteger(v *big.Int) { - qv.queryValue.BigInteger(v) -} - -// BigDecimal encodes v as a query string value -func (qv Value) BigDecimal(v *big.Float) { - qv.queryValue.BigDecimal(v) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/restjson/decoder_util.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/restjson/decoder_util.go deleted file mode 100644 index 1bce78a4..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/restjson/decoder_util.go +++ /dev/null @@ -1,85 +0,0 @@ -package restjson - -import ( - "encoding/json" - "io" - "strings" - - "github.com/aws/smithy-go" -) - -// GetErrorInfo util looks for code, __type, and message members in the -// json body. These members are optionally available, and the function -// returns the value of member if it is available. This function is useful to -// identify the error code, msg in a REST JSON error response. -func GetErrorInfo(decoder *json.Decoder) (errorType string, message string, err error) { - var errInfo struct { - Code string - Type string `json:"__type"` - Message string - } - - err = decoder.Decode(&errInfo) - if err != nil { - if err == io.EOF { - return errorType, message, nil - } - return errorType, message, err - } - - // assign error type - if len(errInfo.Code) != 0 { - errorType = errInfo.Code - } else if len(errInfo.Type) != 0 { - errorType = errInfo.Type - } - - // assign error message - if len(errInfo.Message) != 0 { - message = errInfo.Message - } - - // sanitize error - if len(errorType) != 0 { - errorType = SanitizeErrorCode(errorType) - } - - return errorType, message, nil -} - -// SanitizeErrorCode sanitizes the errorCode string . -// The rule for sanitizing is if a `:` character is present, then take only the -// contents before the first : character in the value. -// If a # character is present, then take only the contents after the -// first # character in the value. -func SanitizeErrorCode(errorCode string) string { - if strings.ContainsAny(errorCode, ":") { - errorCode = strings.SplitN(errorCode, ":", 2)[0] - } - - if strings.ContainsAny(errorCode, "#") { - errorCode = strings.SplitN(errorCode, "#", 2)[1] - } - - return errorCode -} - -// GetSmithyGenericAPIError returns smithy generic api error and an error interface. -// Takes in json decoder, and error Code string as args. The function retrieves error message -// and error code from the decoder body. If errorCode of length greater than 0 is passed in as -// an argument, it is used instead. -func GetSmithyGenericAPIError(decoder *json.Decoder, errorCode string) (*smithy.GenericAPIError, error) { - errorType, message, err := GetErrorInfo(decoder) - if err != nil { - return nil, err - } - - if len(errorCode) == 0 { - errorCode = errorType - } - - return &smithy.GenericAPIError{ - Code: errorCode, - Message: message, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/xml/error_utils.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/xml/error_utils.go deleted file mode 100644 index 6975ce65..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/protocol/xml/error_utils.go +++ /dev/null @@ -1,48 +0,0 @@ -package xml - -import ( - "encoding/xml" - "fmt" - "io" -) - -// ErrorComponents represents the error response fields -// that will be deserialized from an xml error response body -type ErrorComponents struct { - Code string - Message string - RequestID string -} - -// GetErrorResponseComponents returns the error fields from an xml error response body -func GetErrorResponseComponents(r io.Reader, noErrorWrapping bool) (ErrorComponents, error) { - if noErrorWrapping { - var errResponse noWrappedErrorResponse - if err := xml.NewDecoder(r).Decode(&errResponse); err != nil && err != io.EOF { - return ErrorComponents{}, fmt.Errorf("error while deserializing xml error response: %w", err) - } - return ErrorComponents(errResponse), nil - } - - var errResponse wrappedErrorResponse - if err := xml.NewDecoder(r).Decode(&errResponse); err != nil && err != io.EOF { - return ErrorComponents{}, fmt.Errorf("error while deserializing xml error response: %w", err) - } - return ErrorComponents(errResponse), nil -} - -// noWrappedErrorResponse represents the error response body with -// no internal Error wrapping -type noWrappedErrorResponse struct { - Code string `xml:"Code"` - Message string `xml:"Message"` - RequestID string `xml:"RequestId"` -} - -// wrappedErrorResponse represents the error response body -// wrapped within Error -type wrappedErrorResponse struct { - Code string `xml:"Error>Code"` - Message string `xml:"Error>Message"` - RequestID string `xml:"RequestId"` -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_bucket.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_bucket.go deleted file mode 100644 index 974ef594..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_bucket.go +++ /dev/null @@ -1,96 +0,0 @@ -package ratelimit - -import ( - "sync" -) - -// TokenBucket provides a concurrency safe utility for adding and removing -// tokens from the available token bucket. -type TokenBucket struct { - remainingTokens uint - maxCapacity uint - minCapacity uint - mu sync.Mutex -} - -// NewTokenBucket returns an initialized TokenBucket with the capacity -// specified. -func NewTokenBucket(i uint) *TokenBucket { - return &TokenBucket{ - remainingTokens: i, - maxCapacity: i, - minCapacity: 1, - } -} - -// Retrieve attempts to reduce the available tokens by the amount requested. If -// there are tokens available true will be returned along with the number of -// available tokens remaining. If amount requested is larger than the available -// capacity, false will be returned along with the available capacity. If the -// amount is less than the available capacity, the capacity will be reduced by -// that amount, and the remaining capacity and true will be returned. -func (t *TokenBucket) Retrieve(amount uint) (available uint, retrieved bool) { - t.mu.Lock() - defer t.mu.Unlock() - - if amount > t.remainingTokens { - return t.remainingTokens, false - } - - t.remainingTokens -= amount - return t.remainingTokens, true -} - -// Refund returns the amount of tokens back to the available token bucket, up -// to the initial capacity. -func (t *TokenBucket) Refund(amount uint) { - t.mu.Lock() - defer t.mu.Unlock() - - // Capacity cannot exceed max capacity. - t.remainingTokens = uintMin(t.remainingTokens+amount, t.maxCapacity) -} - -// Capacity returns the maximum capacity of tokens that the bucket could -// contain. -func (t *TokenBucket) Capacity() uint { - t.mu.Lock() - defer t.mu.Unlock() - - return t.maxCapacity -} - -// Remaining returns the number of tokens that remaining in the bucket. -func (t *TokenBucket) Remaining() uint { - t.mu.Lock() - defer t.mu.Unlock() - - return t.remainingTokens -} - -// Resize adjusts the size of the token bucket. Returns the capacity remaining. -func (t *TokenBucket) Resize(size uint) uint { - t.mu.Lock() - defer t.mu.Unlock() - - t.maxCapacity = uintMax(size, t.minCapacity) - - // Capacity needs to be capped at max capacity, if max size reduced. - t.remainingTokens = uintMin(t.remainingTokens, t.maxCapacity) - - return t.remainingTokens -} - -func uintMin(a, b uint) uint { - if a < b { - return a - } - return b -} - -func uintMax(a, b uint) uint { - if a > b { - return a - } - return b -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_rate_limit.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_rate_limit.go deleted file mode 100644 index d89090ad..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/ratelimit/token_rate_limit.go +++ /dev/null @@ -1,83 +0,0 @@ -package ratelimit - -import ( - "context" - "fmt" -) - -type rateToken struct { - tokenCost uint - bucket *TokenBucket -} - -func (t rateToken) release() error { - t.bucket.Refund(t.tokenCost) - return nil -} - -// TokenRateLimit provides a Token Bucket RateLimiter implementation -// that limits the overall number of retry attempts that can be made across -// operation invocations. -type TokenRateLimit struct { - bucket *TokenBucket -} - -// NewTokenRateLimit returns an TokenRateLimit with default values. -// Functional options can configure the retry rate limiter. -func NewTokenRateLimit(tokens uint) *TokenRateLimit { - return &TokenRateLimit{ - bucket: NewTokenBucket(tokens), - } -} - -type canceledError struct { - Err error -} - -func (c canceledError) CanceledError() bool { return true } -func (c canceledError) Unwrap() error { return c.Err } -func (c canceledError) Error() string { - return fmt.Sprintf("canceled, %v", c.Err) -} - -// GetToken may cause a available pool of retry quota to be -// decremented. Will return an error if the decremented value can not be -// reduced from the retry quota. -func (l *TokenRateLimit) GetToken(ctx context.Context, cost uint) (func() error, error) { - select { - case <-ctx.Done(): - return nil, canceledError{Err: ctx.Err()} - default: - } - if avail, ok := l.bucket.Retrieve(cost); !ok { - return nil, QuotaExceededError{Available: avail, Requested: cost} - } - - return rateToken{ - tokenCost: cost, - bucket: l.bucket, - }.release, nil -} - -// AddTokens increments the token bucket by a fixed amount. -func (l *TokenRateLimit) AddTokens(v uint) error { - l.bucket.Refund(v) - return nil -} - -// Remaining returns the number of remaining tokens in the bucket. -func (l *TokenRateLimit) Remaining() uint { - return l.bucket.Remaining() -} - -// QuotaExceededError provides the SDK error when the retries for a given -// token bucket have been exhausted. -type QuotaExceededError struct { - Available uint - Requested uint -} - -func (e QuotaExceededError) Error() string { - return fmt.Sprintf("retry quota exceeded, %d available, %d requested", - e.Available, e.Requested) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/request.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/request.go deleted file mode 100644 index d8d00e61..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/request.go +++ /dev/null @@ -1,25 +0,0 @@ -package aws - -import ( - "fmt" -) - -// TODO remove replace with smithy.CanceledError - -// RequestCanceledError is the error that will be returned by an API request -// that was canceled. Requests given a Context may return this error when -// canceled. -type RequestCanceledError struct { - Err error -} - -// CanceledError returns true to satisfy interfaces checking for canceled errors. -func (*RequestCanceledError) CanceledError() bool { return true } - -// Unwrap returns the underlying error, if there was one. -func (e *RequestCanceledError) Unwrap() error { - return e.Err -} -func (e *RequestCanceledError) Error() string { - return fmt.Sprintf("request canceled, %v", e.Err) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive.go deleted file mode 100644 index 4dfde857..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive.go +++ /dev/null @@ -1,156 +0,0 @@ -package retry - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/internal/sdk" -) - -const ( - // DefaultRequestCost is the cost of a single request from the adaptive - // rate limited token bucket. - DefaultRequestCost uint = 1 -) - -// DefaultThrottles provides the set of errors considered throttle errors that -// are checked by default. -var DefaultThrottles = []IsErrorThrottle{ - ThrottleErrorCode{ - Codes: DefaultThrottleErrorCodes, - }, -} - -// AdaptiveModeOptions provides the functional options for configuring the -// adaptive retry mode, and delay behavior. -type AdaptiveModeOptions struct { - // If the adaptive token bucket is empty, when an attempt will be made - // AdaptiveMode will sleep until a token is available. This can occur when - // attempts fail with throttle errors. Use this option to disable the sleep - // until token is available, and return error immediately. - FailOnNoAttemptTokens bool - - // The cost of an attempt from the AdaptiveMode's adaptive token bucket. - RequestCost uint - - // Set of strategies to determine if the attempt failed due to a throttle - // error. - // - // It is safe to append to this list in NewAdaptiveMode's functional options. - Throttles []IsErrorThrottle - - // Set of options for standard retry mode that AdaptiveMode is built on top - // of. AdaptiveMode may apply its own defaults to Standard retry mode that - // are different than the defaults of NewStandard. Use these options to - // override the default options. - StandardOptions []func(*StandardOptions) -} - -// AdaptiveMode provides an experimental retry strategy that expands on the -// Standard retry strategy, adding client attempt rate limits. The attempt rate -// limit is initially unrestricted, but becomes restricted when the attempt -// fails with for a throttle error. When restricted AdaptiveMode may need to -// sleep before an attempt is made, if too many throttles have been received. -// AdaptiveMode's sleep can be canceled with context cancel. Set -// AdaptiveModeOptions FailOnNoAttemptTokens to change the behavior from sleep, -// to fail fast. -// -// Eventually unrestricted attempt rate limit will be restored once attempts no -// longer are failing due to throttle errors. -type AdaptiveMode struct { - options AdaptiveModeOptions - throttles IsErrorThrottles - - retryer aws.RetryerV2 - rateLimit *adaptiveRateLimit -} - -// NewAdaptiveMode returns an initialized AdaptiveMode retry strategy. -func NewAdaptiveMode(optFns ...func(*AdaptiveModeOptions)) *AdaptiveMode { - o := AdaptiveModeOptions{ - RequestCost: DefaultRequestCost, - Throttles: append([]IsErrorThrottle{}, DefaultThrottles...), - } - for _, fn := range optFns { - fn(&o) - } - - return &AdaptiveMode{ - options: o, - throttles: IsErrorThrottles(o.Throttles), - retryer: NewStandard(o.StandardOptions...), - rateLimit: newAdaptiveRateLimit(), - } -} - -// IsErrorRetryable returns if the failed attempt is retryable. This check -// should determine if the error can be retried, or if the error is -// terminal. -func (a *AdaptiveMode) IsErrorRetryable(err error) bool { - return a.retryer.IsErrorRetryable(err) -} - -// MaxAttempts returns the maximum number of attempts that can be made for -// an attempt before failing. A value of 0 implies that the attempt should -// be retried until it succeeds if the errors are retryable. -func (a *AdaptiveMode) MaxAttempts() int { - return a.retryer.MaxAttempts() -} - -// RetryDelay returns the delay that should be used before retrying the -// attempt. Will return error if the if the delay could not be determined. -func (a *AdaptiveMode) RetryDelay(attempt int, opErr error) ( - time.Duration, error, -) { - return a.retryer.RetryDelay(attempt, opErr) -} - -// GetRetryToken attempts to deduct the retry cost from the retry token pool. -// Returning the token release function, or error. -func (a *AdaptiveMode) GetRetryToken(ctx context.Context, opErr error) ( - releaseToken func(error) error, err error, -) { - return a.retryer.GetRetryToken(ctx, opErr) -} - -// GetInitialToken returns the initial attempt token that can increment the -// retry token pool if the attempt is successful. -// -// Deprecated: This method does not provide a way to block using Context, -// nor can it return an error. Use RetryerV2, and GetAttemptToken instead. Only -// present to implement Retryer interface. -func (a *AdaptiveMode) GetInitialToken() (releaseToken func(error) error) { - return nopRelease -} - -// GetAttemptToken returns the attempt token that can be used to rate limit -// attempt calls. Will be used by the SDK's retry package's Attempt -// middleware to get an attempt token prior to calling the temp and releasing -// the attempt token after the attempt has been made. -func (a *AdaptiveMode) GetAttemptToken(ctx context.Context) (func(error) error, error) { - for { - acquiredToken, waitTryAgain := a.rateLimit.AcquireToken(a.options.RequestCost) - if acquiredToken { - break - } - if a.options.FailOnNoAttemptTokens { - return nil, fmt.Errorf( - "unable to get attempt token, and FailOnNoAttemptTokens enables") - } - - if err := sdk.SleepWithContext(ctx, waitTryAgain); err != nil { - return nil, fmt.Errorf("failed to wait for token to be available, %w", err) - } - } - - return a.handleResponse, nil -} - -func (a *AdaptiveMode) handleResponse(opErr error) error { - throttled := a.throttles.IsErrorThrottle(opErr).Bool() - - a.rateLimit.Update(throttled) - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_ratelimit.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_ratelimit.go deleted file mode 100644 index ad96d9b8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_ratelimit.go +++ /dev/null @@ -1,158 +0,0 @@ -package retry - -import ( - "math" - "sync" - "time" - - "github.com/aws/aws-sdk-go-v2/internal/sdk" -) - -type adaptiveRateLimit struct { - tokenBucketEnabled bool - - smooth float64 - beta float64 - scaleConstant float64 - minFillRate float64 - - fillRate float64 - calculatedRate float64 - lastRefilled time.Time - measuredTxRate float64 - lastTxRateBucket float64 - requestCount int64 - lastMaxRate float64 - lastThrottleTime time.Time - timeWindow float64 - - tokenBucket *adaptiveTokenBucket - - mu sync.Mutex -} - -func newAdaptiveRateLimit() *adaptiveRateLimit { - now := sdk.NowTime() - return &adaptiveRateLimit{ - smooth: 0.8, - beta: 0.7, - scaleConstant: 0.4, - - minFillRate: 0.5, - - lastTxRateBucket: math.Floor(timeFloat64Seconds(now)), - lastThrottleTime: now, - - tokenBucket: newAdaptiveTokenBucket(0), - } -} - -func (a *adaptiveRateLimit) Enable(v bool) { - a.mu.Lock() - defer a.mu.Unlock() - - a.tokenBucketEnabled = v -} - -func (a *adaptiveRateLimit) AcquireToken(amount uint) ( - tokenAcquired bool, waitTryAgain time.Duration, -) { - a.mu.Lock() - defer a.mu.Unlock() - - if !a.tokenBucketEnabled { - return true, 0 - } - - a.tokenBucketRefill() - - available, ok := a.tokenBucket.Retrieve(float64(amount)) - if !ok { - waitDur := float64Seconds((float64(amount) - available) / a.fillRate) - return false, waitDur - } - - return true, 0 -} - -func (a *adaptiveRateLimit) Update(throttled bool) { - a.mu.Lock() - defer a.mu.Unlock() - - a.updateMeasuredRate() - - if throttled { - rateToUse := a.measuredTxRate - if a.tokenBucketEnabled { - rateToUse = math.Min(a.measuredTxRate, a.fillRate) - } - - a.lastMaxRate = rateToUse - a.calculateTimeWindow() - a.lastThrottleTime = sdk.NowTime() - a.calculatedRate = a.cubicThrottle(rateToUse) - a.tokenBucketEnabled = true - } else { - a.calculateTimeWindow() - a.calculatedRate = a.cubicSuccess(sdk.NowTime()) - } - - newRate := math.Min(a.calculatedRate, 2*a.measuredTxRate) - a.tokenBucketUpdateRate(newRate) -} - -func (a *adaptiveRateLimit) cubicSuccess(t time.Time) float64 { - dt := secondsFloat64(t.Sub(a.lastThrottleTime)) - return (a.scaleConstant * math.Pow(dt-a.timeWindow, 3)) + a.lastMaxRate -} - -func (a *adaptiveRateLimit) cubicThrottle(rateToUse float64) float64 { - return rateToUse * a.beta -} - -func (a *adaptiveRateLimit) calculateTimeWindow() { - a.timeWindow = math.Pow((a.lastMaxRate*(1.-a.beta))/a.scaleConstant, 1./3.) -} - -func (a *adaptiveRateLimit) tokenBucketUpdateRate(newRPS float64) { - a.tokenBucketRefill() - a.fillRate = math.Max(newRPS, a.minFillRate) - a.tokenBucket.Resize(newRPS) -} - -func (a *adaptiveRateLimit) updateMeasuredRate() { - now := sdk.NowTime() - timeBucket := math.Floor(timeFloat64Seconds(now)*2.) / 2. - a.requestCount++ - - if timeBucket > a.lastTxRateBucket { - currentRate := float64(a.requestCount) / (timeBucket - a.lastTxRateBucket) - a.measuredTxRate = (currentRate * a.smooth) + (a.measuredTxRate * (1. - a.smooth)) - a.requestCount = 0 - a.lastTxRateBucket = timeBucket - } -} - -func (a *adaptiveRateLimit) tokenBucketRefill() { - now := sdk.NowTime() - if a.lastRefilled.IsZero() { - a.lastRefilled = now - return - } - - fillAmount := secondsFloat64(now.Sub(a.lastRefilled)) * a.fillRate - a.tokenBucket.Refund(fillAmount) - a.lastRefilled = now -} - -func float64Seconds(v float64) time.Duration { - return time.Duration(v * float64(time.Second)) -} - -func secondsFloat64(v time.Duration) float64 { - return float64(v) / float64(time.Second) -} - -func timeFloat64Seconds(v time.Time) float64 { - return float64(v.UnixNano()) / float64(time.Second) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_token_bucket.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_token_bucket.go deleted file mode 100644 index 052723e8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/adaptive_token_bucket.go +++ /dev/null @@ -1,83 +0,0 @@ -package retry - -import ( - "math" - "sync" -) - -// adaptiveTokenBucket provides a concurrency safe utility for adding and -// removing tokens from the available token bucket. -type adaptiveTokenBucket struct { - remainingTokens float64 - maxCapacity float64 - minCapacity float64 - mu sync.Mutex -} - -// newAdaptiveTokenBucket returns an initialized adaptiveTokenBucket with the -// capacity specified. -func newAdaptiveTokenBucket(i float64) *adaptiveTokenBucket { - return &adaptiveTokenBucket{ - remainingTokens: i, - maxCapacity: i, - minCapacity: 1, - } -} - -// Retrieve attempts to reduce the available tokens by the amount requested. If -// there are tokens available true will be returned along with the number of -// available tokens remaining. If amount requested is larger than the available -// capacity, false will be returned along with the available capacity. If the -// amount is less than the available capacity, the capacity will be reduced by -// that amount, and the remaining capacity and true will be returned. -func (t *adaptiveTokenBucket) Retrieve(amount float64) (available float64, retrieved bool) { - t.mu.Lock() - defer t.mu.Unlock() - - if amount > t.remainingTokens { - return t.remainingTokens, false - } - - t.remainingTokens -= amount - return t.remainingTokens, true -} - -// Refund returns the amount of tokens back to the available token bucket, up -// to the initial capacity. -func (t *adaptiveTokenBucket) Refund(amount float64) { - t.mu.Lock() - defer t.mu.Unlock() - - // Capacity cannot exceed max capacity. - t.remainingTokens = math.Min(t.remainingTokens+amount, t.maxCapacity) -} - -// Capacity returns the maximum capacity of tokens that the bucket could -// contain. -func (t *adaptiveTokenBucket) Capacity() float64 { - t.mu.Lock() - defer t.mu.Unlock() - - return t.maxCapacity -} - -// Remaining returns the number of tokens that remaining in the bucket. -func (t *adaptiveTokenBucket) Remaining() float64 { - t.mu.Lock() - defer t.mu.Unlock() - - return t.remainingTokens -} - -// Resize adjusts the size of the token bucket. Returns the capacity remaining. -func (t *adaptiveTokenBucket) Resize(size float64) float64 { - t.mu.Lock() - defer t.mu.Unlock() - - t.maxCapacity = math.Max(size, t.minCapacity) - - // Capacity needs to be capped at max capacity, if max size reduced. - t.remainingTokens = math.Min(t.remainingTokens, t.maxCapacity) - - return t.remainingTokens -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/doc.go deleted file mode 100644 index 3a08ebe0..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/doc.go +++ /dev/null @@ -1,80 +0,0 @@ -// Package retry provides interfaces and implementations for SDK request retry behavior. -// -// # Retryer Interface and Implementations -// -// This package defines Retryer interface that is used to either implement custom retry behavior -// or to extend the existing retry implementations provided by the SDK. This package provides a single -// retry implementation: Standard. -// -// # Standard -// -// Standard is the default retryer implementation used by service clients. The standard retryer is a rate limited -// retryer that has a configurable max attempts to limit the number of retry attempts when a retryable error occurs. -// In addition, the retryer uses a configurable token bucket to rate limit the retry attempts across the client, -// and uses an additional delay policy to limit the time between a requests subsequent attempts. -// -// By default the standard retryer uses the DefaultRetryables slice of IsErrorRetryable types to determine whether -// a given error is retryable. By default this list of retryables includes the following: -// - Retrying errors that implement the RetryableError method, and return true. -// - Connection Errors -// - Errors that implement a ConnectionError, Temporary, or Timeout method that return true. -// - Connection Reset Errors. -// - net.OpErr types that are dialing errors or are temporary. -// - HTTP Status Codes: 500, 502, 503, and 504. -// - API Error Codes -// - RequestTimeout, RequestTimeoutException -// - Throttling, ThrottlingException, ThrottledException, RequestThrottledException, TooManyRequestsException, -// RequestThrottled, SlowDown, EC2ThrottledException -// - ProvisionedThroughputExceededException, RequestLimitExceeded, BandwidthLimitExceeded, LimitExceededException -// - TransactionInProgressException, PriorRequestNotComplete -// -// The standard retryer will not retry a request in the event if the context associated with the request -// has been cancelled. Applications must handle this case explicitly if they wish to retry with a different context -// value. -// -// You can configure the standard retryer implementation to fit your applications by constructing a standard retryer -// using the NewStandard function, and providing one more functional argument that mutate the StandardOptions -// structure. StandardOptions provides the ability to modify the token bucket rate limiter, retryable error conditions, -// and the retry delay policy. -// -// For example to modify the default retry attempts for the standard retryer: -// -// // configure the custom retryer -// customRetry := retry.NewStandard(func(o *retry.StandardOptions) { -// o.MaxAttempts = 5 -// }) -// -// // create a service client with the retryer -// s3.NewFromConfig(cfg, func(o *s3.Options) { -// o.Retryer = customRetry -// }) -// -// # Utilities -// -// A number of package functions have been provided to easily wrap retryer implementations in an implementation agnostic -// way. These are: -// -// AddWithErrorCodes - Provides the ability to add additional API error codes that should be considered retryable -// in addition to those considered retryable by the provided retryer. -// -// AddWithMaxAttempts - Provides the ability to set the max number of attempts for retrying a request by wrapping -// a retryer implementation. -// -// AddWithMaxBackoffDelay - Provides the ability to set the max back off delay that can occur before retrying a -// request by wrapping a retryer implementation. -// -// The following package functions have been provided to easily satisfy different retry interfaces to further customize -// a given retryer's behavior: -// -// BackoffDelayerFunc - Can be used to wrap a function to satisfy the BackoffDelayer interface. For example, -// you can use this method to easily create custom back off policies to be used with the -// standard retryer. -// -// IsErrorRetryableFunc - Can be used to wrap a function to satisfy the IsErrorRetryable interface. For example, -// this can be used to extend the standard retryer to add additional logic to determine if an -// error should be retried. -// -// IsErrorTimeoutFunc - Can be used to wrap a function to satisfy IsErrorTimeout interface. For example, -// this can be used to extend the standard retryer to add additional logic to determine if an -// error should be considered a timeout. -package retry diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/errors.go deleted file mode 100644 index 3e432eef..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/errors.go +++ /dev/null @@ -1,20 +0,0 @@ -package retry - -import "fmt" - -// MaxAttemptsError provides the error when the maximum number of attempts have -// been exceeded. -type MaxAttemptsError struct { - Attempt int - Err error -} - -func (e *MaxAttemptsError) Error() string { - return fmt.Sprintf("exceeded maximum number of attempts, %d, %v", e.Attempt, e.Err) -} - -// Unwrap returns the nested error causing the max attempts error. Provides the -// implementation for errors.Is and errors.As to unwrap nested errors. -func (e *MaxAttemptsError) Unwrap() error { - return e.Err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/jitter_backoff.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/jitter_backoff.go deleted file mode 100644 index c266996d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/jitter_backoff.go +++ /dev/null @@ -1,49 +0,0 @@ -package retry - -import ( - "math" - "time" - - "github.com/aws/aws-sdk-go-v2/internal/rand" - "github.com/aws/aws-sdk-go-v2/internal/timeconv" -) - -// ExponentialJitterBackoff provides backoff delays with jitter based on the -// number of attempts. -type ExponentialJitterBackoff struct { - maxBackoff time.Duration - // precomputed number of attempts needed to reach max backoff. - maxBackoffAttempts float64 - - randFloat64 func() (float64, error) -} - -// NewExponentialJitterBackoff returns an ExponentialJitterBackoff configured -// for the max backoff. -func NewExponentialJitterBackoff(maxBackoff time.Duration) *ExponentialJitterBackoff { - return &ExponentialJitterBackoff{ - maxBackoff: maxBackoff, - maxBackoffAttempts: math.Log2( - float64(maxBackoff) / float64(time.Second)), - randFloat64: rand.CryptoRandFloat64, - } -} - -// BackoffDelay returns the duration to wait before the next attempt should be -// made. Returns an error if unable get a duration. -func (j *ExponentialJitterBackoff) BackoffDelay(attempt int, err error) (time.Duration, error) { - if attempt > int(j.maxBackoffAttempts) { - return j.maxBackoff, nil - } - - b, err := j.randFloat64() - if err != nil { - return 0, err - } - - // [0.0, 1.0) * 2 ^ attempts - ri := int64(1 << uint64(attempt)) - delaySeconds := b * float64(ri) - - return timeconv.FloatSecondsDur(delaySeconds), nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/metadata.go deleted file mode 100644 index 7a3f1830..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/metadata.go +++ /dev/null @@ -1,52 +0,0 @@ -package retry - -import ( - awsmiddle "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/smithy-go/middleware" -) - -// attemptResultsKey is a metadata accessor key to retrieve metadata -// for all request attempts. -type attemptResultsKey struct { -} - -// GetAttemptResults retrieves attempts results from middleware metadata. -func GetAttemptResults(metadata middleware.Metadata) (AttemptResults, bool) { - m, ok := metadata.Get(attemptResultsKey{}).(AttemptResults) - return m, ok -} - -// AttemptResults represents struct containing metadata returned by all request attempts. -type AttemptResults struct { - - // Results is a slice consisting attempt result from all request attempts. - // Results are stored in order request attempt is made. - Results []AttemptResult -} - -// AttemptResult represents attempt result returned by a single request attempt. -type AttemptResult struct { - - // Err is the error if received for the request attempt. - Err error - - // Retryable denotes if request may be retried. This states if an - // error is considered retryable. - Retryable bool - - // Retried indicates if this request was retried. - Retried bool - - // ResponseMetadata is any existing metadata passed via the response middlewares. - ResponseMetadata middleware.Metadata -} - -// addAttemptResults adds attempt results to middleware metadata -func addAttemptResults(metadata *middleware.Metadata, v AttemptResults) { - metadata.Set(attemptResultsKey{}, v) -} - -// GetRawResponse returns raw response recorded for the attempt result -func (a AttemptResult) GetRawResponse() interface{} { - return awsmiddle.GetRawResponse(a.ResponseMetadata) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/middleware.go deleted file mode 100644 index dc703d48..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/middleware.go +++ /dev/null @@ -1,340 +0,0 @@ -package retry - -import ( - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws/middleware/private/metrics" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - awsmiddle "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/smithy-go/logging" - smithymiddle "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/transport/http" -) - -// RequestCloner is a function that can take an input request type and clone -// the request for use in a subsequent retry attempt. -type RequestCloner func(interface{}) interface{} - -type retryMetadata struct { - AttemptNum int - AttemptTime time.Time - MaxAttempts int - AttemptClockSkew time.Duration -} - -// Attempt is a Smithy Finalize middleware that handles retry attempts using -// the provided Retryer implementation. -type Attempt struct { - // Enable the logging of retry attempts performed by the SDK. This will - // include logging retry attempts, unretryable errors, and when max - // attempts are reached. - LogAttempts bool - - retryer aws.RetryerV2 - requestCloner RequestCloner -} - -// NewAttemptMiddleware returns a new Attempt retry middleware. -func NewAttemptMiddleware(retryer aws.Retryer, requestCloner RequestCloner, optFns ...func(*Attempt)) *Attempt { - m := &Attempt{ - retryer: wrapAsRetryerV2(retryer), - requestCloner: requestCloner, - } - for _, fn := range optFns { - fn(m) - } - return m -} - -// ID returns the middleware identifier -func (r *Attempt) ID() string { return "Retry" } - -func (r Attempt) logf(logger logging.Logger, classification logging.Classification, format string, v ...interface{}) { - if !r.LogAttempts { - return - } - logger.Logf(classification, format, v...) -} - -// HandleFinalize utilizes the provider Retryer implementation to attempt -// retries over the next handler -func (r *Attempt) HandleFinalize(ctx context.Context, in smithymiddle.FinalizeInput, next smithymiddle.FinalizeHandler) ( - out smithymiddle.FinalizeOutput, metadata smithymiddle.Metadata, err error, -) { - var attemptNum int - var attemptClockSkew time.Duration - var attemptResults AttemptResults - - maxAttempts := r.retryer.MaxAttempts() - releaseRetryToken := nopRelease - - for { - attemptNum++ - attemptInput := in - attemptInput.Request = r.requestCloner(attemptInput.Request) - - // Record the metadata for the for attempt being started. - attemptCtx := setRetryMetadata(ctx, retryMetadata{ - AttemptNum: attemptNum, - AttemptTime: sdk.NowTime().UTC(), - MaxAttempts: maxAttempts, - AttemptClockSkew: attemptClockSkew, - }) - - var attemptResult AttemptResult - out, attemptResult, releaseRetryToken, err = r.handleAttempt(attemptCtx, attemptInput, releaseRetryToken, next) - attemptClockSkew, _ = awsmiddle.GetAttemptSkew(attemptResult.ResponseMetadata) - - // AttemptResult Retried states that the attempt was not successful, and - // should be retried. - shouldRetry := attemptResult.Retried - - // Add attempt metadata to list of all attempt metadata - attemptResults.Results = append(attemptResults.Results, attemptResult) - - if !shouldRetry { - // Ensure the last response's metadata is used as the bases for result - // metadata returned by the stack. The Slice of attempt results - // will be added to this cloned metadata. - metadata = attemptResult.ResponseMetadata.Clone() - - break - } - } - - addAttemptResults(&metadata, attemptResults) - return out, metadata, err -} - -// handleAttempt handles an individual request attempt. -func (r *Attempt) handleAttempt( - ctx context.Context, in smithymiddle.FinalizeInput, releaseRetryToken func(error) error, next smithymiddle.FinalizeHandler, -) ( - out smithymiddle.FinalizeOutput, attemptResult AttemptResult, _ func(error) error, err error, -) { - defer func() { - attemptResult.Err = err - }() - - // Short circuit if this attempt never can succeed because the context is - // canceled. This reduces the chance of token pools being modified for - // attempts that will not be made - select { - case <-ctx.Done(): - return out, attemptResult, nopRelease, ctx.Err() - default: - } - - //------------------------------ - // Get Attempt Token - //------------------------------ - releaseAttemptToken, err := r.retryer.GetAttemptToken(ctx) - if err != nil { - return out, attemptResult, nopRelease, fmt.Errorf( - "failed to get retry Send token, %w", err) - } - - //------------------------------ - // Send Attempt - //------------------------------ - logger := smithymiddle.GetLogger(ctx) - service, operation := awsmiddle.GetServiceID(ctx), awsmiddle.GetOperationName(ctx) - retryMetadata, _ := getRetryMetadata(ctx) - attemptNum := retryMetadata.AttemptNum - maxAttempts := retryMetadata.MaxAttempts - - // Following attempts must ensure the request payload stream starts in a - // rewound state. - if attemptNum > 1 { - if rewindable, ok := in.Request.(interface{ RewindStream() error }); ok { - if rewindErr := rewindable.RewindStream(); rewindErr != nil { - return out, attemptResult, nopRelease, fmt.Errorf( - "failed to rewind transport stream for retry, %w", rewindErr) - } - } - - r.logf(logger, logging.Debug, "retrying request %s/%s, attempt %d", - service, operation, attemptNum) - } - - var metadata smithymiddle.Metadata - out, metadata, err = next.HandleFinalize(ctx, in) - attemptResult.ResponseMetadata = metadata - - //------------------------------ - // Bookkeeping - //------------------------------ - // Release the retry token based on the state of the attempt's error (if any). - if releaseError := releaseRetryToken(err); releaseError != nil && err != nil { - return out, attemptResult, nopRelease, fmt.Errorf( - "failed to release retry token after request error, %w", err) - } - // Release the attempt token based on the state of the attempt's error (if any). - if releaseError := releaseAttemptToken(err); releaseError != nil && err != nil { - return out, attemptResult, nopRelease, fmt.Errorf( - "failed to release initial token after request error, %w", err) - } - // If there was no error making the attempt, nothing further to do. There - // will be nothing to retry. - if err == nil { - return out, attemptResult, nopRelease, err - } - - //------------------------------ - // Is Retryable and Should Retry - //------------------------------ - // If the attempt failed with an unretryable error, nothing further to do - // but return, and inform the caller about the terminal failure. - retryable := r.retryer.IsErrorRetryable(err) - if !retryable { - r.logf(logger, logging.Debug, "request failed with unretryable error %v", err) - return out, attemptResult, nopRelease, err - } - - // set retryable to true - attemptResult.Retryable = true - - // Once the maximum number of attempts have been exhausted there is nothing - // further to do other than inform the caller about the terminal failure. - if maxAttempts > 0 && attemptNum >= maxAttempts { - r.logf(logger, logging.Debug, "max retry attempts exhausted, max %d", maxAttempts) - err = &MaxAttemptsError{ - Attempt: attemptNum, - Err: err, - } - return out, attemptResult, nopRelease, err - } - - //------------------------------ - // Get Retry (aka Retry Quota) Token - //------------------------------ - // Get a retry token that will be released after the - releaseRetryToken, retryTokenErr := r.retryer.GetRetryToken(ctx, err) - if retryTokenErr != nil { - return out, attemptResult, nopRelease, retryTokenErr - } - - //------------------------------ - // Retry Delay and Sleep - //------------------------------ - // Get the retry delay before another attempt can be made, and sleep for - // that time. Potentially early exist if the sleep is canceled via the - // context. - retryDelay, reqErr := r.retryer.RetryDelay(attemptNum, err) - mctx := metrics.Context(ctx) - if mctx != nil { - attempt, err := mctx.Data().LatestAttempt() - if err != nil { - attempt.RetryDelay = retryDelay - } - } - if reqErr != nil { - return out, attemptResult, releaseRetryToken, reqErr - } - if reqErr = sdk.SleepWithContext(ctx, retryDelay); reqErr != nil { - err = &aws.RequestCanceledError{Err: reqErr} - return out, attemptResult, releaseRetryToken, err - } - - // The request should be re-attempted. - attemptResult.Retried = true - - return out, attemptResult, releaseRetryToken, err -} - -// MetricsHeader attaches SDK request metric header for retries to the transport -type MetricsHeader struct{} - -// ID returns the middleware identifier -func (r *MetricsHeader) ID() string { - return "RetryMetricsHeader" -} - -// HandleFinalize attaches the SDK request metric header to the transport layer -func (r MetricsHeader) HandleFinalize(ctx context.Context, in smithymiddle.FinalizeInput, next smithymiddle.FinalizeHandler) ( - out smithymiddle.FinalizeOutput, metadata smithymiddle.Metadata, err error, -) { - retryMetadata, _ := getRetryMetadata(ctx) - - const retryMetricHeader = "Amz-Sdk-Request" - var parts []string - - parts = append(parts, "attempt="+strconv.Itoa(retryMetadata.AttemptNum)) - if retryMetadata.MaxAttempts != 0 { - parts = append(parts, "max="+strconv.Itoa(retryMetadata.MaxAttempts)) - } - - var ttl time.Time - if deadline, ok := ctx.Deadline(); ok { - ttl = deadline - } - - // Only append the TTL if it can be determined. - if !ttl.IsZero() && retryMetadata.AttemptClockSkew > 0 { - const unixTimeFormat = "20060102T150405Z" - ttl = ttl.Add(retryMetadata.AttemptClockSkew) - parts = append(parts, "ttl="+ttl.Format(unixTimeFormat)) - } - - switch req := in.Request.(type) { - case *http.Request: - req.Header[retryMetricHeader] = append(req.Header[retryMetricHeader][:0], strings.Join(parts, "; ")) - default: - return out, metadata, fmt.Errorf("unknown transport type %T", req) - } - - return next.HandleFinalize(ctx, in) -} - -type retryMetadataKey struct{} - -// getRetryMetadata retrieves retryMetadata from the context and a bool -// indicating if it was set. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func getRetryMetadata(ctx context.Context) (metadata retryMetadata, ok bool) { - metadata, ok = smithymiddle.GetStackValue(ctx, retryMetadataKey{}).(retryMetadata) - return metadata, ok -} - -// setRetryMetadata sets the retryMetadata on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func setRetryMetadata(ctx context.Context, metadata retryMetadata) context.Context { - return smithymiddle.WithStackValue(ctx, retryMetadataKey{}, metadata) -} - -// AddRetryMiddlewaresOptions is the set of options that can be passed to -// AddRetryMiddlewares for configuring retry associated middleware. -type AddRetryMiddlewaresOptions struct { - Retryer aws.Retryer - - // Enable the logging of retry attempts performed by the SDK. This will - // include logging retry attempts, unretryable errors, and when max - // attempts are reached. - LogRetryAttempts bool -} - -// AddRetryMiddlewares adds retry middleware to operation middleware stack -func AddRetryMiddlewares(stack *smithymiddle.Stack, options AddRetryMiddlewaresOptions) error { - attempt := NewAttemptMiddleware(options.Retryer, http.RequestCloner, func(middleware *Attempt) { - middleware.LogAttempts = options.LogRetryAttempts - }) - - // index retry to before signing, if signing exists - if err := stack.Finalize.Insert(attempt, "Signing", smithymiddle.Before); err != nil { - return err - } - - if err := stack.Finalize.Insert(&MetricsHeader{}, attempt.ID(), smithymiddle.After); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retry.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retry.go deleted file mode 100644 index af81635b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retry.go +++ /dev/null @@ -1,90 +0,0 @@ -package retry - -import ( - "context" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// AddWithErrorCodes returns a Retryer with additional error codes considered -// for determining if the error should be retried. -func AddWithErrorCodes(r aws.Retryer, codes ...string) aws.Retryer { - retryable := &RetryableErrorCode{ - Codes: map[string]struct{}{}, - } - for _, c := range codes { - retryable.Codes[c] = struct{}{} - } - - return &withIsErrorRetryable{ - RetryerV2: wrapAsRetryerV2(r), - Retryable: retryable, - } -} - -type withIsErrorRetryable struct { - aws.RetryerV2 - Retryable IsErrorRetryable -} - -func (r *withIsErrorRetryable) IsErrorRetryable(err error) bool { - if v := r.Retryable.IsErrorRetryable(err); v != aws.UnknownTernary { - return v.Bool() - } - return r.RetryerV2.IsErrorRetryable(err) -} - -// AddWithMaxAttempts returns a Retryer with MaxAttempts set to the value -// specified. -func AddWithMaxAttempts(r aws.Retryer, max int) aws.Retryer { - return &withMaxAttempts{ - RetryerV2: wrapAsRetryerV2(r), - Max: max, - } -} - -type withMaxAttempts struct { - aws.RetryerV2 - Max int -} - -func (w *withMaxAttempts) MaxAttempts() int { - return w.Max -} - -// AddWithMaxBackoffDelay returns a retryer wrapping the passed in retryer -// overriding the RetryDelay behavior for a alternate minimum initial backoff -// delay. -func AddWithMaxBackoffDelay(r aws.Retryer, delay time.Duration) aws.Retryer { - return &withMaxBackoffDelay{ - RetryerV2: wrapAsRetryerV2(r), - backoff: NewExponentialJitterBackoff(delay), - } -} - -type withMaxBackoffDelay struct { - aws.RetryerV2 - backoff *ExponentialJitterBackoff -} - -func (r *withMaxBackoffDelay) RetryDelay(attempt int, err error) (time.Duration, error) { - return r.backoff.BackoffDelay(attempt, err) -} - -type wrappedAsRetryerV2 struct { - aws.Retryer -} - -func wrapAsRetryerV2(r aws.Retryer) aws.RetryerV2 { - v, ok := r.(aws.RetryerV2) - if !ok { - v = wrappedAsRetryerV2{Retryer: r} - } - - return v -} - -func (w wrappedAsRetryerV2) GetAttemptToken(context.Context) (func(error) error, error) { - return w.Retryer.GetInitialToken(), nil -} 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 deleted file mode 100644 index 987affdd..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/retryable_error.go +++ /dev/null @@ -1,201 +0,0 @@ -package retry - -import ( - "errors" - "net" - "net/url" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// IsErrorRetryable provides the interface of an implementation to determine if -// a error as the result of an operation is retryable. -type IsErrorRetryable interface { - IsErrorRetryable(error) aws.Ternary -} - -// IsErrorRetryables is a collection of checks to determine of the error is -// retryable. Iterates through the checks and returns the state of retryable -// if any check returns something other than unknown. -type IsErrorRetryables []IsErrorRetryable - -// IsErrorRetryable returns if the error is retryable if any of the checks in -// the list return a value other than unknown. -func (r IsErrorRetryables) IsErrorRetryable(err error) aws.Ternary { - for _, re := range r { - if v := re.IsErrorRetryable(err); v != aws.UnknownTernary { - return v - } - } - return aws.UnknownTernary -} - -// IsErrorRetryableFunc wraps a function with the IsErrorRetryable interface. -type IsErrorRetryableFunc func(error) aws.Ternary - -// IsErrorRetryable returns if the error is retryable. -func (fn IsErrorRetryableFunc) IsErrorRetryable(err error) aws.Ternary { - return fn(err) -} - -// RetryableError is an IsErrorRetryable implementation which uses the -// optional interface Retryable on the error value to determine if the error is -// retryable. -type RetryableError struct{} - -// IsErrorRetryable returns if the error is retryable if it satisfies the -// Retryable interface, and returns if the attempt should be retried. -func (RetryableError) IsErrorRetryable(err error) aws.Ternary { - var v interface{ RetryableError() bool } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - return aws.BoolTernary(v.RetryableError()) -} - -// NoRetryCanceledError detects if the error was an request canceled error and -// returns if so. -type NoRetryCanceledError struct{} - -// IsErrorRetryable returns the error is not retryable if the request was -// canceled. -func (NoRetryCanceledError) IsErrorRetryable(err error) aws.Ternary { - var v interface{ CanceledError() bool } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - if v.CanceledError() { - return aws.FalseTernary - } - return aws.UnknownTernary -} - -// RetryableConnectionError determines if the underlying error is an HTTP -// connection and returns if it should be retried. -// -// Includes errors such as connection reset, connection refused, net dial, -// temporary, and timeout errors. -type RetryableConnectionError struct{} - -// IsErrorRetryable returns if the error is caused by and HTTP connection -// error, and should be retried. -func (r RetryableConnectionError) IsErrorRetryable(err error) aws.Ternary { - if err == nil { - return aws.UnknownTernary - } - var retryable bool - - var conErr interface{ ConnectionError() bool } - var tempErr interface{ Temporary() bool } - var timeoutErr interface{ Timeout() bool } - var urlErr *url.Error - var netOpErr *net.OpError - var dnsError *net.DNSError - - if errors.As(err, &dnsError) { - // NXDOMAIN errors should not be retried - if dnsError.IsNotFound { - return aws.BoolTernary(false) - } - - // if !dnsError.Temporary(), error may or may not be temporary, - // (i.e. !Temporary() =/=> !retryable) so we should fall through to - // remaining checks - if dnsError.Temporary() { - return aws.BoolTernary(true) - } - } - - switch { - case errors.As(err, &conErr) && conErr.ConnectionError(): - retryable = true - - case strings.Contains(err.Error(), "connection reset"): - retryable = true - - case errors.As(err, &urlErr): - // Refused connections should be retried as the service may not yet be - // running on the port. Go TCP dial considers refused connections as - // not temporary. - if strings.Contains(urlErr.Error(), "connection refused") { - retryable = true - } else { - return r.IsErrorRetryable(errors.Unwrap(urlErr)) - } - - case errors.As(err, &netOpErr): - // Network dial, or temporary network errors are always retryable. - if strings.EqualFold(netOpErr.Op, "dial") || netOpErr.Temporary() { - retryable = true - } else { - return r.IsErrorRetryable(errors.Unwrap(netOpErr)) - } - - case errors.As(err, &tempErr) && tempErr.Temporary(): - // Fallback to the generic temporary check, with temporary errors - // retryable. - retryable = true - - case errors.As(err, &timeoutErr) && timeoutErr.Timeout(): - // Fallback to the generic timeout check, with timeout errors - // retryable. - retryable = true - - default: - return aws.UnknownTernary - } - - return aws.BoolTernary(retryable) - -} - -// RetryableHTTPStatusCode provides a IsErrorRetryable based on HTTP status -// codes. -type RetryableHTTPStatusCode struct { - Codes map[int]struct{} -} - -// IsErrorRetryable return if the passed in error is retryable based on the -// HTTP status code. -func (r RetryableHTTPStatusCode) IsErrorRetryable(err error) aws.Ternary { - var v interface{ HTTPStatusCode() int } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - _, ok := r.Codes[v.HTTPStatusCode()] - if !ok { - return aws.UnknownTernary - } - - return aws.TrueTernary -} - -// RetryableErrorCode determines if an attempt should be retried based on the -// API error code. -type RetryableErrorCode struct { - Codes map[string]struct{} -} - -// IsErrorRetryable return if the error is retryable based on the error codes. -// Returns unknown if the error doesn't have a code or it is unknown. -func (r RetryableErrorCode) IsErrorRetryable(err error) aws.Ternary { - var v interface{ ErrorCode() string } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - _, ok := r.Codes[v.ErrorCode()] - if !ok { - return aws.UnknownTernary - } - - return aws.TrueTernary -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/standard.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/standard.go deleted file mode 100644 index 25abffc8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/standard.go +++ /dev/null @@ -1,258 +0,0 @@ -package retry - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/aws/ratelimit" -) - -// BackoffDelayer provides the interface for determining the delay to before -// another request attempt, that previously failed. -type BackoffDelayer interface { - BackoffDelay(attempt int, err error) (time.Duration, error) -} - -// BackoffDelayerFunc provides a wrapper around a function to determine the -// backoff delay of an attempt retry. -type BackoffDelayerFunc func(int, error) (time.Duration, error) - -// BackoffDelay returns the delay before attempt to retry a request. -func (fn BackoffDelayerFunc) BackoffDelay(attempt int, err error) (time.Duration, error) { - return fn(attempt, err) -} - -const ( - // DefaultMaxAttempts is the maximum of attempts for an API request - DefaultMaxAttempts int = 3 - - // DefaultMaxBackoff is the maximum back off delay between attempts - DefaultMaxBackoff time.Duration = 20 * time.Second -) - -// Default retry token quota values. -const ( - DefaultRetryRateTokens uint = 500 - DefaultRetryCost uint = 5 - DefaultRetryTimeoutCost uint = 10 - DefaultNoRetryIncrement uint = 1 -) - -// DefaultRetryableHTTPStatusCodes is the default set of HTTP status codes the SDK -// should consider as retryable errors. -var DefaultRetryableHTTPStatusCodes = map[int]struct{}{ - 500: {}, - 502: {}, - 503: {}, - 504: {}, -} - -// DefaultRetryableErrorCodes provides the set of API error codes that should -// be retried. -var DefaultRetryableErrorCodes = map[string]struct{}{ - "RequestTimeout": {}, - "RequestTimeoutException": {}, -} - -// DefaultThrottleErrorCodes provides the set of API error codes that are -// considered throttle errors. -var DefaultThrottleErrorCodes = map[string]struct{}{ - "Throttling": {}, - "ThrottlingException": {}, - "ThrottledException": {}, - "RequestThrottledException": {}, - "TooManyRequestsException": {}, - "ProvisionedThroughputExceededException": {}, - "TransactionInProgressException": {}, - "RequestLimitExceeded": {}, - "BandwidthLimitExceeded": {}, - "LimitExceededException": {}, - "RequestThrottled": {}, - "SlowDown": {}, - "PriorRequestNotComplete": {}, - "EC2ThrottledException": {}, -} - -// DefaultRetryables provides the set of retryable checks that are used by -// default. -var DefaultRetryables = []IsErrorRetryable{ - NoRetryCanceledError{}, - RetryableError{}, - RetryableConnectionError{}, - RetryableHTTPStatusCode{ - Codes: DefaultRetryableHTTPStatusCodes, - }, - RetryableErrorCode{ - Codes: DefaultRetryableErrorCodes, - }, - RetryableErrorCode{ - Codes: DefaultThrottleErrorCodes, - }, -} - -// DefaultTimeouts provides the set of timeout checks that are used by default. -var DefaultTimeouts = []IsErrorTimeout{ - TimeouterError{}, -} - -// StandardOptions provides the functional options for configuring the standard -// retryable, and delay behavior. -type StandardOptions struct { - // Maximum number of attempts that should be made. - MaxAttempts int - - // MaxBackoff duration between retried attempts. - MaxBackoff time.Duration - - // Provides the backoff strategy the retryer will use to determine the - // delay between retry attempts. - Backoff BackoffDelayer - - // Set of strategies to determine if the attempt should be retried based on - // the error response received. - // - // It is safe to append to this list in NewStandard's functional options. - Retryables []IsErrorRetryable - - // Set of strategies to determine if the attempt failed due to a timeout - // error. - // - // It is safe to append to this list in NewStandard's functional options. - Timeouts []IsErrorTimeout - - // Provides the rate limiting strategy for rate limiting attempt retries - // across all attempts the retryer is being used with. - RateLimiter RateLimiter - - // The cost to deduct from the RateLimiter's token bucket per retry. - RetryCost uint - - // The cost to deduct from the RateLimiter's token bucket per retry caused - // by timeout error. - RetryTimeoutCost uint - - // The cost to payback to the RateLimiter's token bucket for successful - // attempts. - NoRetryIncrement uint -} - -// RateLimiter provides the interface for limiting the rate of attempt retries -// allowed by the retryer. -type RateLimiter interface { - GetToken(ctx context.Context, cost uint) (releaseToken func() error, err error) - AddTokens(uint) error -} - -// Standard is the standard retry pattern for the SDK. It uses a set of -// retryable checks to determine of the failed attempt should be retried, and -// what retry delay should be used. -type Standard struct { - options StandardOptions - - timeout IsErrorTimeout - retryable IsErrorRetryable - backoff BackoffDelayer -} - -// NewStandard initializes a standard retry behavior with defaults that can be -// overridden via functional options. -func NewStandard(fnOpts ...func(*StandardOptions)) *Standard { - o := StandardOptions{ - MaxAttempts: DefaultMaxAttempts, - MaxBackoff: DefaultMaxBackoff, - Retryables: append([]IsErrorRetryable{}, DefaultRetryables...), - Timeouts: append([]IsErrorTimeout{}, DefaultTimeouts...), - - RateLimiter: ratelimit.NewTokenRateLimit(DefaultRetryRateTokens), - RetryCost: DefaultRetryCost, - RetryTimeoutCost: DefaultRetryTimeoutCost, - NoRetryIncrement: DefaultNoRetryIncrement, - } - for _, fn := range fnOpts { - fn(&o) - } - if o.MaxAttempts <= 0 { - o.MaxAttempts = DefaultMaxAttempts - } - - backoff := o.Backoff - if backoff == nil { - backoff = NewExponentialJitterBackoff(o.MaxBackoff) - } - - return &Standard{ - options: o, - backoff: backoff, - retryable: IsErrorRetryables(o.Retryables), - timeout: IsErrorTimeouts(o.Timeouts), - } -} - -// MaxAttempts returns the maximum number of attempts that can be made for a -// request before failing. -func (s *Standard) MaxAttempts() int { - return s.options.MaxAttempts -} - -// IsErrorRetryable returns if the error is can be retried or not. Should not -// consider the number of attempts made. -func (s *Standard) IsErrorRetryable(err error) bool { - return s.retryable.IsErrorRetryable(err).Bool() -} - -// RetryDelay returns the delay to use before another request attempt is made. -func (s *Standard) RetryDelay(attempt int, err error) (time.Duration, error) { - return s.backoff.BackoffDelay(attempt, err) -} - -// GetAttemptToken returns the token to be released after then attempt completes. -// The release token will add NoRetryIncrement to the RateLimiter token pool if -// the attempt was successful. If the attempt failed, nothing will be done. -func (s *Standard) GetAttemptToken(context.Context) (func(error) error, error) { - return s.GetInitialToken(), nil -} - -// GetInitialToken returns a token for adding the NoRetryIncrement to the -// RateLimiter token if the attempt completed successfully without error. -// -// InitialToken applies to result of the each attempt, including the first. -// Whereas the RetryToken applies to the result of subsequent attempts. -// -// Deprecated: use GetAttemptToken instead. -func (s *Standard) GetInitialToken() func(error) error { - return releaseToken(s.noRetryIncrement).release -} - -func (s *Standard) noRetryIncrement() error { - return s.options.RateLimiter.AddTokens(s.options.NoRetryIncrement) -} - -// GetRetryToken attempts to deduct the retry cost from the retry token pool. -// Returning the token release function, or error. -func (s *Standard) GetRetryToken(ctx context.Context, opErr error) (func(error) error, error) { - cost := s.options.RetryCost - - if s.timeout.IsErrorTimeout(opErr).Bool() { - cost = s.options.RetryTimeoutCost - } - - fn, err := s.options.RateLimiter.GetToken(ctx, cost) - if err != nil { - return nil, fmt.Errorf("failed to get rate limit token, %w", err) - } - - return releaseToken(fn).release, nil -} - -func nopRelease(error) error { return nil } - -type releaseToken func() error - -func (f releaseToken) release(err error) error { - if err != nil { - return nil - } - - return f() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/throttle_error.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/throttle_error.go deleted file mode 100644 index c4b844d1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/throttle_error.go +++ /dev/null @@ -1,60 +0,0 @@ -package retry - -import ( - "errors" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// IsErrorThrottle provides the interface of an implementation to determine if -// a error response from an operation is a throttling error. -type IsErrorThrottle interface { - IsErrorThrottle(error) aws.Ternary -} - -// IsErrorThrottles is a collection of checks to determine of the error a -// throttle error. Iterates through the checks and returns the state of -// throttle if any check returns something other than unknown. -type IsErrorThrottles []IsErrorThrottle - -// IsErrorThrottle returns if the error is a throttle error if any of the -// checks in the list return a value other than unknown. -func (r IsErrorThrottles) IsErrorThrottle(err error) aws.Ternary { - for _, re := range r { - if v := re.IsErrorThrottle(err); v != aws.UnknownTernary { - return v - } - } - return aws.UnknownTernary -} - -// IsErrorThrottleFunc wraps a function with the IsErrorThrottle interface. -type IsErrorThrottleFunc func(error) aws.Ternary - -// IsErrorThrottle returns if the error is a throttle error. -func (fn IsErrorThrottleFunc) IsErrorThrottle(err error) aws.Ternary { - return fn(err) -} - -// ThrottleErrorCode determines if an attempt should be retried based on the -// API error code. -type ThrottleErrorCode struct { - Codes map[string]struct{} -} - -// IsErrorThrottle return if the error is a throttle error based on the error -// codes. Returns unknown if the error doesn't have a code or it is unknown. -func (r ThrottleErrorCode) IsErrorThrottle(err error) aws.Ternary { - var v interface{ ErrorCode() string } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - _, ok := r.Codes[v.ErrorCode()] - if !ok { - return aws.UnknownTernary - } - - return aws.TrueTernary -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/timeout_error.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/timeout_error.go deleted file mode 100644 index 3d47870d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retry/timeout_error.go +++ /dev/null @@ -1,52 +0,0 @@ -package retry - -import ( - "errors" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// IsErrorTimeout provides the interface of an implementation to determine if -// a error matches. -type IsErrorTimeout interface { - IsErrorTimeout(err error) aws.Ternary -} - -// IsErrorTimeouts is a collection of checks to determine of the error is -// retryable. Iterates through the checks and returns the state of retryable -// if any check returns something other than unknown. -type IsErrorTimeouts []IsErrorTimeout - -// IsErrorTimeout returns if the error is retryable if any of the checks in -// the list return a value other than unknown. -func (ts IsErrorTimeouts) IsErrorTimeout(err error) aws.Ternary { - for _, t := range ts { - if v := t.IsErrorTimeout(err); v != aws.UnknownTernary { - return v - } - } - return aws.UnknownTernary -} - -// IsErrorTimeoutFunc wraps a function with the IsErrorTimeout interface. -type IsErrorTimeoutFunc func(error) aws.Ternary - -// IsErrorTimeout returns if the error is retryable. -func (fn IsErrorTimeoutFunc) IsErrorTimeout(err error) aws.Ternary { - return fn(err) -} - -// TimeouterError provides the IsErrorTimeout implementation for determining if -// an error is a timeout based on type with the Timeout method. -type TimeouterError struct{} - -// IsErrorTimeout returns if the error is a timeout error. -func (t TimeouterError) IsErrorTimeout(err error) aws.Ternary { - var v interface{ Timeout() bool } - - if !errors.As(err, &v) { - return aws.UnknownTernary - } - - return aws.BoolTernary(v.Timeout()) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/retryer.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/retryer.go deleted file mode 100644 index b0ba4cb2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/retryer.go +++ /dev/null @@ -1,127 +0,0 @@ -package aws - -import ( - "context" - "fmt" - "time" -) - -// RetryMode provides the mode the API client will use to create a retryer -// based on. -type RetryMode string - -const ( - // RetryModeStandard model provides rate limited retry attempts with - // exponential backoff delay. - RetryModeStandard RetryMode = "standard" - - // RetryModeAdaptive model provides attempt send rate limiting on throttle - // responses in addition to standard mode's retry rate limiting. - // - // Adaptive retry mode is experimental and is subject to change in the - // future. - RetryModeAdaptive RetryMode = "adaptive" -) - -// ParseRetryMode attempts to parse a RetryMode from the given string. -// Returning error if the value is not a known RetryMode. -func ParseRetryMode(v string) (mode RetryMode, err error) { - switch v { - case "standard": - return RetryModeStandard, nil - case "adaptive": - return RetryModeAdaptive, nil - default: - return mode, fmt.Errorf("unknown RetryMode, %v", v) - } -} - -func (m RetryMode) String() string { return string(m) } - -// Retryer is an interface to determine if a given error from a -// attempt should be retried, and if so what backoff delay to apply. The -// default implementation used by most services is the retry package's Standard -// type. Which contains basic retry logic using exponential backoff. -type Retryer interface { - // IsErrorRetryable returns if the failed attempt is retryable. This check - // should determine if the error can be retried, or if the error is - // terminal. - IsErrorRetryable(error) bool - - // MaxAttempts returns the maximum number of attempts that can be made for - // an attempt before failing. A value of 0 implies that the attempt should - // be retried until it succeeds if the errors are retryable. - MaxAttempts() int - - // RetryDelay returns the delay that should be used before retrying the - // attempt. Will return error if the delay could not be determined. - RetryDelay(attempt int, opErr error) (time.Duration, error) - - // GetRetryToken attempts to deduct the retry cost from the retry token pool. - // Returning the token release function, or error. - GetRetryToken(ctx context.Context, opErr error) (releaseToken func(error) error, err error) - - // GetInitialToken returns the initial attempt token that can increment the - // retry token pool if the attempt is successful. - GetInitialToken() (releaseToken func(error) error) -} - -// RetryerV2 is an interface to determine if a given error from an attempt -// should be retried, and if so what backoff delay to apply. The default -// implementation used by most services is the retry package's Standard type. -// Which contains basic retry logic using exponential backoff. -// -// RetryerV2 replaces the Retryer interface, deprecating the GetInitialToken -// method in favor of GetAttemptToken which takes a context, and can return an error. -// -// The SDK's retry package's Attempt middleware, and utilities will always -// wrap a Retryer as a RetryerV2. Delegating to GetInitialToken, only if -// GetAttemptToken is not implemented. -type RetryerV2 interface { - Retryer - - // GetInitialToken returns the initial attempt token that can increment the - // retry token pool if the attempt is successful. - // - // Deprecated: This method does not provide a way to block using Context, - // nor can it return an error. Use RetryerV2, and GetAttemptToken instead. - GetInitialToken() (releaseToken func(error) error) - - // GetAttemptToken returns the send token that can be used to rate limit - // attempt calls. Will be used by the SDK's retry package's Attempt - // middleware to get a send token prior to calling the temp and releasing - // the send token after the attempt has been made. - GetAttemptToken(context.Context) (func(error) error, error) -} - -// NopRetryer provides a RequestRetryDecider implementation that will flag -// all attempt errors as not retryable, with a max attempts of 1. -type NopRetryer struct{} - -// IsErrorRetryable returns false for all error values. -func (NopRetryer) IsErrorRetryable(error) bool { return false } - -// MaxAttempts always returns 1 for the original attempt. -func (NopRetryer) MaxAttempts() int { return 1 } - -// RetryDelay is not valid for the NopRetryer. Will always return error. -func (NopRetryer) RetryDelay(int, error) (time.Duration, error) { - return 0, fmt.Errorf("not retrying any attempt errors") -} - -// GetRetryToken returns a stub function that does nothing. -func (NopRetryer) GetRetryToken(context.Context, error) (func(error) error, error) { - return nopReleaseToken, nil -} - -// GetInitialToken returns a stub function that does nothing. -func (NopRetryer) GetInitialToken() func(error) error { - return nopReleaseToken -} - -// GetAttemptToken returns a stub function that does nothing. -func (NopRetryer) GetAttemptToken(context.Context) (func(error) error, error) { - return nopReleaseToken, nil -} - -func nopReleaseToken(error) error { return nil } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/runtime.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/runtime.go deleted file mode 100644 index 3af9b2b3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/runtime.go +++ /dev/null @@ -1,14 +0,0 @@ -package aws - -// ExecutionEnvironmentID is the AWS execution environment runtime identifier. -type ExecutionEnvironmentID string - -// RuntimeEnvironment is a collection of values that are determined at runtime -// based on the environment that the SDK is executing in. Some of these values -// may or may not be present based on the executing environment and certain SDK -// configuration properties that drive whether these values are populated.. -type RuntimeEnvironment struct { - EnvironmentIdentifier ExecutionEnvironmentID - Region string - EC2InstanceMetadataRegion string -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/cache.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/cache.go deleted file mode 100644 index cbf22f1d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/cache.go +++ /dev/null @@ -1,115 +0,0 @@ -package v4 - -import ( - "strings" - "sync" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -func lookupKey(service, region string) string { - var s strings.Builder - s.Grow(len(region) + len(service) + 3) - s.WriteString(region) - s.WriteRune('/') - s.WriteString(service) - return s.String() -} - -type derivedKey struct { - AccessKey string - Date time.Time - Credential []byte -} - -type derivedKeyCache struct { - values map[string]derivedKey - mutex sync.RWMutex -} - -func newDerivedKeyCache() derivedKeyCache { - return derivedKeyCache{ - values: make(map[string]derivedKey), - } -} - -func (s *derivedKeyCache) Get(credentials aws.Credentials, service, region string, signingTime SigningTime) []byte { - key := lookupKey(service, region) - s.mutex.RLock() - if cred, ok := s.get(key, credentials, signingTime.Time); ok { - s.mutex.RUnlock() - return cred - } - s.mutex.RUnlock() - - s.mutex.Lock() - if cred, ok := s.get(key, credentials, signingTime.Time); ok { - s.mutex.Unlock() - return cred - } - cred := deriveKey(credentials.SecretAccessKey, service, region, signingTime) - entry := derivedKey{ - AccessKey: credentials.AccessKeyID, - Date: signingTime.Time, - Credential: cred, - } - s.values[key] = entry - s.mutex.Unlock() - - return cred -} - -func (s *derivedKeyCache) get(key string, credentials aws.Credentials, signingTime time.Time) ([]byte, bool) { - cacheEntry, ok := s.retrieveFromCache(key) - if ok && cacheEntry.AccessKey == credentials.AccessKeyID && isSameDay(signingTime, cacheEntry.Date) { - return cacheEntry.Credential, true - } - return nil, false -} - -func (s *derivedKeyCache) retrieveFromCache(key string) (derivedKey, bool) { - if v, ok := s.values[key]; ok { - return v, true - } - return derivedKey{}, false -} - -// SigningKeyDeriver derives a signing key from a set of credentials -type SigningKeyDeriver struct { - cache derivedKeyCache -} - -// NewSigningKeyDeriver returns a new SigningKeyDeriver -func NewSigningKeyDeriver() *SigningKeyDeriver { - return &SigningKeyDeriver{ - cache: newDerivedKeyCache(), - } -} - -// DeriveKey returns a derived signing key from the given credentials to be used with SigV4 signing. -func (k *SigningKeyDeriver) DeriveKey(credential aws.Credentials, service, region string, signingTime SigningTime) []byte { - return k.cache.Get(credential, service, region, signingTime) -} - -func deriveKey(secret, service, region string, t SigningTime) []byte { - hmacDate := HMACSHA256([]byte("AWS4"+secret), []byte(t.ShortTimeFormat())) - hmacRegion := HMACSHA256(hmacDate, []byte(region)) - hmacService := HMACSHA256(hmacRegion, []byte(service)) - return HMACSHA256(hmacService, []byte("aws4_request")) -} - -func isSameDay(x, y time.Time) bool { - xYear, xMonth, xDay := x.Date() - yYear, yMonth, yDay := y.Date() - - if xYear != yYear { - return false - } - - if xMonth != yMonth { - return false - } - - return xDay == yDay -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/const.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/const.go deleted file mode 100644 index a23cb003..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/const.go +++ /dev/null @@ -1,40 +0,0 @@ -package v4 - -// Signature Version 4 (SigV4) Constants -const ( - // EmptyStringSHA256 is the hex encoded sha256 value of an empty string - EmptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` - - // UnsignedPayload indicates that the request payload body is unsigned - UnsignedPayload = "UNSIGNED-PAYLOAD" - - // AmzAlgorithmKey indicates the signing algorithm - AmzAlgorithmKey = "X-Amz-Algorithm" - - // AmzSecurityTokenKey indicates the security token to be used with temporary credentials - AmzSecurityTokenKey = "X-Amz-Security-Token" - - // AmzDateKey is the UTC timestamp for the request in the format YYYYMMDD'T'HHMMSS'Z' - AmzDateKey = "X-Amz-Date" - - // AmzCredentialKey is the access key ID and credential scope - AmzCredentialKey = "X-Amz-Credential" - - // AmzSignedHeadersKey is the set of headers signed for the request - AmzSignedHeadersKey = "X-Amz-SignedHeaders" - - // AmzSignatureKey is the query parameter to store the SigV4 signature - AmzSignatureKey = "X-Amz-Signature" - - // TimeFormat is the time format to be used in the X-Amz-Date header or query parameter - TimeFormat = "20060102T150405Z" - - // ShortTimeFormat is the shorten time format used in the credential scope - ShortTimeFormat = "20060102" - - // ContentSHAKey is the SHA256 of request body - ContentSHAKey = "X-Amz-Content-Sha256" - - // StreamingEventsPayload indicates that the request payload body is a signed event stream. - StreamingEventsPayload = "STREAMING-AWS4-HMAC-SHA256-EVENTS" -) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/header_rules.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/header_rules.go deleted file mode 100644 index c61955ad..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/header_rules.go +++ /dev/null @@ -1,82 +0,0 @@ -package v4 - -import ( - sdkstrings "github.com/aws/aws-sdk-go-v2/internal/strings" -) - -// Rules houses a set of Rule needed for validation of a -// string value -type Rules []Rule - -// Rule interface allows for more flexible rules and just simply -// checks whether or not a value adheres to that Rule -type Rule interface { - IsValid(value string) bool -} - -// IsValid will iterate through all rules and see if any rules -// apply to the value and supports nested rules -func (r Rules) IsValid(value string) bool { - for _, rule := range r { - if rule.IsValid(value) { - return true - } - } - return false -} - -// MapRule generic Rule for maps -type MapRule map[string]struct{} - -// IsValid for the map Rule satisfies whether it exists in the map -func (m MapRule) IsValid(value string) bool { - _, ok := m[value] - return ok -} - -// AllowList is a generic Rule for include listing -type AllowList struct { - Rule -} - -// IsValid for AllowList checks if the value is within the AllowList -func (w AllowList) IsValid(value string) bool { - return w.Rule.IsValid(value) -} - -// ExcludeList is a generic Rule for exclude listing -type ExcludeList struct { - Rule -} - -// IsValid for AllowList checks if the value is within the AllowList -func (b ExcludeList) IsValid(value string) bool { - return !b.Rule.IsValid(value) -} - -// Patterns is a list of strings to match against -type Patterns []string - -// IsValid for Patterns checks each pattern and returns if a match has -// been found -func (p Patterns) IsValid(value string) bool { - for _, pattern := range p { - if sdkstrings.HasPrefixFold(value, pattern) { - return true - } - } - return false -} - -// InclusiveRules rules allow for rules to depend on one another -type InclusiveRules []Rule - -// IsValid will return true if all rules are true -func (r InclusiveRules) IsValid(value string) bool { - for _, rule := range r { - if !rule.IsValid(value) { - return false - } - } - return true -} 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 deleted file mode 100644 index ca738f23..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/headers.go +++ /dev/null @@ -1,71 +0,0 @@ -package v4 - -// IgnoredHeaders is a list of headers that are ignored during signing -var IgnoredHeaders = Rules{ - ExcludeList{ - MapRule{ - "Authorization": struct{}{}, - "User-Agent": struct{}{}, - "X-Amzn-Trace-Id": struct{}{}, - "Expect": struct{}{}, - }, - }, -} - -// RequiredSignedHeaders is a allow list for Build canonical headers. -var RequiredSignedHeaders = Rules{ - AllowList{ - MapRule{ - "Cache-Control": struct{}{}, - "Content-Disposition": struct{}{}, - "Content-Encoding": struct{}{}, - "Content-Language": struct{}{}, - "Content-Md5": struct{}{}, - "Content-Type": struct{}{}, - "Expires": struct{}{}, - "If-Match": struct{}{}, - "If-Modified-Since": struct{}{}, - "If-None-Match": struct{}{}, - "If-Unmodified-Since": struct{}{}, - "Range": struct{}{}, - "X-Amz-Acl": struct{}{}, - "X-Amz-Copy-Source": struct{}{}, - "X-Amz-Copy-Source-If-Match": struct{}{}, - "X-Amz-Copy-Source-If-Modified-Since": struct{}{}, - "X-Amz-Copy-Source-If-None-Match": struct{}{}, - "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{}, - "X-Amz-Copy-Source-Range": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, - "X-Amz-Expected-Bucket-Owner": struct{}{}, - "X-Amz-Grant-Full-control": struct{}{}, - "X-Amz-Grant-Read": struct{}{}, - "X-Amz-Grant-Read-Acp": struct{}{}, - "X-Amz-Grant-Write": struct{}{}, - "X-Amz-Grant-Write-Acp": struct{}{}, - "X-Amz-Metadata-Directive": struct{}{}, - "X-Amz-Mfa": struct{}{}, - "X-Amz-Request-Payer": struct{}{}, - "X-Amz-Server-Side-Encryption": struct{}{}, - "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{}, - "X-Amz-Server-Side-Encryption-Context": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, - "X-Amz-Storage-Class": struct{}{}, - "X-Amz-Website-Redirect-Location": struct{}{}, - "X-Amz-Content-Sha256": struct{}{}, - "X-Amz-Tagging": struct{}{}, - }, - }, - Patterns{"X-Amz-Object-Lock-"}, - Patterns{"X-Amz-Meta-"}, -} - -// AllowedQueryHoisting is a allowed list for Build query headers. The boolean value -// represents whether or not it is a pattern. -var AllowedQueryHoisting = InclusiveRules{ - ExcludeList{RequiredSignedHeaders}, - Patterns{"X-Amz-"}, -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/hmac.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/hmac.go deleted file mode 100644 index e7fa7a1b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/hmac.go +++ /dev/null @@ -1,13 +0,0 @@ -package v4 - -import ( - "crypto/hmac" - "crypto/sha256" -) - -// HMACSHA256 computes a HMAC-SHA256 of data given the provided key. -func HMACSHA256(key []byte, data []byte) []byte { - hash := hmac.New(sha256.New, key) - hash.Write(data) - return hash.Sum(nil) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/host.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/host.go deleted file mode 100644 index bf93659a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/host.go +++ /dev/null @@ -1,75 +0,0 @@ -package v4 - -import ( - "net/http" - "strings" -) - -// SanitizeHostForHeader removes default port from host and updates request.Host -func SanitizeHostForHeader(r *http.Request) { - host := getHost(r) - port := portOnly(host) - if port != "" && isDefaultPort(r.URL.Scheme, port) { - r.Host = stripPort(host) - } -} - -// Returns host from request -func getHost(r *http.Request) string { - if r.Host != "" { - return r.Host - } - - return r.URL.Host -} - -// Hostname returns u.Host, without any port number. -// -// If Host is an IPv6 literal with a port number, Hostname returns the -// IPv6 literal without the square brackets. IPv6 literals may include -// a zone identifier. -// -// Copied from the Go 1.8 standard library (net/url) -func stripPort(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return hostport - } - if i := strings.IndexByte(hostport, ']'); i != -1 { - return strings.TrimPrefix(hostport[:i], "[") - } - return hostport[:colon] -} - -// Port returns the port part of u.Host, without the leading colon. -// If u.Host doesn't contain a port, Port returns an empty string. -// -// Copied from the Go 1.8 standard library (net/url) -func portOnly(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return "" - } - if i := strings.Index(hostport, "]:"); i != -1 { - return hostport[i+len("]:"):] - } - if strings.Contains(hostport, "]") { - return "" - } - return hostport[colon+len(":"):] -} - -// Returns true if the specified URI is using the standard port -// (i.e. port 80 for HTTP URIs or 443 for HTTPS URIs) -func isDefaultPort(scheme, port string) bool { - if port == "" { - return true - } - - lowerCaseScheme := strings.ToLower(scheme) - if (lowerCaseScheme == "http" && port == "80") || (lowerCaseScheme == "https" && port == "443") { - return true - } - - return false -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/scope.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/scope.go deleted file mode 100644 index fc788790..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/scope.go +++ /dev/null @@ -1,13 +0,0 @@ -package v4 - -import "strings" - -// BuildCredentialScope builds the Signature Version 4 (SigV4) signing scope -func BuildCredentialScope(signingTime SigningTime, region, service string) string { - return strings.Join([]string{ - signingTime.ShortTimeFormat(), - region, - service, - "aws4_request", - }, "/") -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/time.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/time.go deleted file mode 100644 index 1de06a76..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/time.go +++ /dev/null @@ -1,36 +0,0 @@ -package v4 - -import "time" - -// SigningTime provides a wrapper around a time.Time which provides cached values for SigV4 signing. -type SigningTime struct { - time.Time - timeFormat string - shortTimeFormat string -} - -// NewSigningTime creates a new SigningTime given a time.Time -func NewSigningTime(t time.Time) SigningTime { - return SigningTime{ - Time: t, - } -} - -// TimeFormat provides a time formatted in the X-Amz-Date format. -func (m *SigningTime) TimeFormat() string { - return m.format(&m.timeFormat, TimeFormat) -} - -// ShortTimeFormat provides a time formatted of 20060102. -func (m *SigningTime) ShortTimeFormat() string { - return m.format(&m.shortTimeFormat, ShortTimeFormat) -} - -func (m *SigningTime) format(target *string, format string) string { - if len(*target) > 0 { - return *target - } - v := m.Time.Format(format) - *target = v - return v -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/util.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/util.go deleted file mode 100644 index d025dbaa..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4/util.go +++ /dev/null @@ -1,80 +0,0 @@ -package v4 - -import ( - "net/url" - "strings" -) - -const doubleSpace = " " - -// StripExcessSpaces will rewrite the passed in slice's string values to not -// contain multiple side-by-side spaces. -func StripExcessSpaces(str string) string { - var j, k, l, m, spaces int - // Trim trailing spaces - for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- { - } - - // Trim leading spaces - for k = 0; k < j && str[k] == ' '; k++ { - } - str = str[k : j+1] - - // Strip multiple spaces. - j = strings.Index(str, doubleSpace) - if j < 0 { - return str - } - - buf := []byte(str) - for k, m, l = j, j, len(buf); k < l; k++ { - if buf[k] == ' ' { - if spaces == 0 { - // First space. - buf[m] = buf[k] - m++ - } - spaces++ - } else { - // End of multiple spaces. - spaces = 0 - buf[m] = buf[k] - m++ - } - } - - return string(buf[:m]) -} - -// GetURIPath returns the escaped URI component from the provided URL. -func GetURIPath(u *url.URL) string { - var uriPath string - - if len(u.Opaque) > 0 { - const schemeSep, pathSep, queryStart = "//", "/", "?" - - opaque := u.Opaque - // Cut off the query string if present. - if idx := strings.Index(opaque, queryStart); idx >= 0 { - opaque = opaque[:idx] - } - - // Cutout the scheme separator if present. - if strings.Index(opaque, schemeSep) == 0 { - opaque = opaque[len(schemeSep):] - } - - // capture URI path starting with first path separator. - if idx := strings.Index(opaque, pathSep); idx >= 0 { - uriPath = opaque[idx:] - } - } else { - uriPath = u.EscapedPath() - } - - if len(uriPath) == 0 { - uriPath = "/" - } - - return uriPath -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/middleware.go deleted file mode 100644 index f39a369a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/middleware.go +++ /dev/null @@ -1,440 +0,0 @@ -package v4 - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "fmt" - "io" - "net/http" - "strings" - - "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/middleware/private/metrics" - v4Internal "github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4" - internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const computePayloadHashMiddlewareID = "ComputePayloadHash" - -// HashComputationError indicates an error occurred while computing the signing hash -type HashComputationError struct { - Err error -} - -// Error is the error message -func (e *HashComputationError) Error() string { - return fmt.Sprintf("failed to compute payload hash: %v", e.Err) -} - -// Unwrap returns the underlying error if one is set -func (e *HashComputationError) Unwrap() error { - return e.Err -} - -// SigningError indicates an error condition occurred while performing SigV4 signing -type SigningError struct { - Err error -} - -func (e *SigningError) Error() string { - return fmt.Sprintf("failed to sign request: %v", e.Err) -} - -// Unwrap returns the underlying error cause -func (e *SigningError) Unwrap() error { - return e.Err -} - -// UseDynamicPayloadSigningMiddleware swaps the compute payload sha256 middleware with a resolver middleware that -// switches between unsigned and signed payload based on TLS state for request. -// This middleware should not be used for AWS APIs that do not support unsigned payload signing auth. -// By default, SDK uses this middleware for known AWS APIs that support such TLS based auth selection . -// -// Usage example - -// S3 PutObject API allows unsigned payload signing auth usage when TLS is enabled, and uses this middleware to -// dynamically switch between unsigned and signed payload based on TLS state for request. -func UseDynamicPayloadSigningMiddleware(stack *middleware.Stack) error { - _, err := stack.Finalize.Swap(computePayloadHashMiddlewareID, &dynamicPayloadSigningMiddleware{}) - return err -} - -// dynamicPayloadSigningMiddleware dynamically resolves the middleware that computes and set payload sha256 middleware. -type dynamicPayloadSigningMiddleware struct { -} - -// ID returns the resolver identifier -func (m *dynamicPayloadSigningMiddleware) ID() string { - return computePayloadHashMiddlewareID -} - -// HandleFinalize delegates SHA256 computation according to whether the request -// is TLS-enabled. -func (m *dynamicPayloadSigningMiddleware) 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 req.IsHTTPS() { - return (&unsignedPayload{}).HandleFinalize(ctx, in, next) - } - return (&computePayloadSHA256{}).HandleFinalize(ctx, in, next) -} - -// unsignedPayload sets the SigV4 request payload hash to unsigned. -// -// Will not set the Unsigned Payload magic SHA value, if a SHA has already been -// stored in the context. (e.g. application pre-computed SHA256 before making -// API call). -// -// This middleware does not check the X-Amz-Content-Sha256 header, if that -// header is serialized a middleware must translate it into the context. -type unsignedPayload struct{} - -// AddUnsignedPayloadMiddleware adds unsignedPayload to the operation -// middleware stack -func AddUnsignedPayloadMiddleware(stack *middleware.Stack) error { - return stack.Finalize.Insert(&unsignedPayload{}, "ResolveEndpointV2", middleware.After) -} - -// ID returns the unsignedPayload identifier -func (m *unsignedPayload) ID() string { - return computePayloadHashMiddlewareID -} - -// HandleFinalize sets the payload hash magic value to the unsigned sentinel. -func (m *unsignedPayload) HandleFinalize( - ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler, -) ( - out middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - if GetPayloadHash(ctx) == "" { - ctx = SetPayloadHash(ctx, v4Internal.UnsignedPayload) - } - return next.HandleFinalize(ctx, in) -} - -// computePayloadSHA256 computes SHA256 payload hash to sign. -// -// Will not set the Unsigned Payload magic SHA value, if a SHA has already been -// stored in the context. (e.g. application pre-computed SHA256 before making -// API call). -// -// This middleware does not check the X-Amz-Content-Sha256 header, if that -// header is serialized a middleware must translate it into the context. -type computePayloadSHA256 struct{} - -// AddComputePayloadSHA256Middleware adds computePayloadSHA256 to the -// operation middleware stack -func AddComputePayloadSHA256Middleware(stack *middleware.Stack) error { - return stack.Finalize.Insert(&computePayloadSHA256{}, "ResolveEndpointV2", middleware.After) -} - -// RemoveComputePayloadSHA256Middleware removes computePayloadSHA256 from the -// operation middleware stack -func RemoveComputePayloadSHA256Middleware(stack *middleware.Stack) error { - _, err := stack.Finalize.Remove(computePayloadHashMiddlewareID) - return err -} - -// ID is the middleware name -func (m *computePayloadSHA256) ID() string { - return computePayloadHashMiddlewareID -} - -// HandleFinalize computes the payload hash for the request, storing it to the -// context. This is a no-op if a caller has previously set that value. -func (m *computePayloadSHA256) HandleFinalize( - ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler, -) ( - out middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - if GetPayloadHash(ctx) != "" { - return next.HandleFinalize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &HashComputationError{ - Err: fmt.Errorf("unexpected request middleware type %T", in.Request), - } - } - - hash := sha256.New() - if stream := req.GetStream(); stream != nil { - _, err = io.Copy(hash, stream) - if err != nil { - return out, metadata, &HashComputationError{ - Err: fmt.Errorf("failed to compute payload hash, %w", err), - } - } - - if err := req.RewindStream(); err != nil { - return out, metadata, &HashComputationError{ - Err: fmt.Errorf("failed to seek body to start, %w", err), - } - } - } - - ctx = SetPayloadHash(ctx, hex.EncodeToString(hash.Sum(nil))) - - return next.HandleFinalize(ctx, in) -} - -// SwapComputePayloadSHA256ForUnsignedPayloadMiddleware replaces the -// ComputePayloadSHA256 middleware with the UnsignedPayload middleware. -// -// Use this to disable computing the Payload SHA256 checksum and instead use -// UNSIGNED-PAYLOAD for the SHA256 value. -func SwapComputePayloadSHA256ForUnsignedPayloadMiddleware(stack *middleware.Stack) error { - _, err := stack.Finalize.Swap(computePayloadHashMiddlewareID, &unsignedPayload{}) - return err -} - -// contentSHA256Header sets the X-Amz-Content-Sha256 header value to -// the Payload hash stored in the context. -type contentSHA256Header struct{} - -// AddContentSHA256HeaderMiddleware adds ContentSHA256Header to the -// operation middleware stack -func AddContentSHA256HeaderMiddleware(stack *middleware.Stack) error { - return stack.Finalize.Insert(&contentSHA256Header{}, computePayloadHashMiddlewareID, middleware.After) -} - -// RemoveContentSHA256HeaderMiddleware removes contentSHA256Header middleware -// from the operation middleware stack -func RemoveContentSHA256HeaderMiddleware(stack *middleware.Stack) error { - _, err := stack.Finalize.Remove((*contentSHA256Header)(nil).ID()) - return err -} - -// ID returns the ContentSHA256HeaderMiddleware identifier -func (m *contentSHA256Header) ID() string { - return "SigV4ContentSHA256Header" -} - -// HandleFinalize sets the X-Amz-Content-Sha256 header value to the Payload hash -// stored in the context. -func (m *contentSHA256Header) 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, &HashComputationError{Err: fmt.Errorf("unexpected request middleware type %T", in.Request)} - } - - req.Header.Set(v4Internal.ContentSHAKey, GetPayloadHash(ctx)) - return next.HandleFinalize(ctx, in) -} - -// SignHTTPRequestMiddlewareOptions is the configuration options for -// [SignHTTPRequestMiddleware]. -// -// Deprecated: [SignHTTPRequestMiddleware] is deprecated. -type SignHTTPRequestMiddlewareOptions struct { - CredentialsProvider aws.CredentialsProvider - Signer HTTPSigner - LogSigning bool -} - -// SignHTTPRequestMiddleware is a `FinalizeMiddleware` implementation for SigV4 -// HTTP Signing. -// -// Deprecated: AWS service clients no longer use this middleware. Signing as an -// SDK operation is now performed through an internal per-service middleware -// which opaquely selects and uses the signer from the resolved auth scheme. -type SignHTTPRequestMiddleware struct { - credentialsProvider aws.CredentialsProvider - signer HTTPSigner - logSigning bool -} - -// NewSignHTTPRequestMiddleware constructs a [SignHTTPRequestMiddleware] using -// the given [Signer] for signing requests. -// -// Deprecated: SignHTTPRequestMiddleware is deprecated. -func NewSignHTTPRequestMiddleware(options SignHTTPRequestMiddlewareOptions) *SignHTTPRequestMiddleware { - return &SignHTTPRequestMiddleware{ - credentialsProvider: options.CredentialsProvider, - signer: options.Signer, - logSigning: options.LogSigning, - } -} - -// ID is the SignHTTPRequestMiddleware identifier. -// -// Deprecated: SignHTTPRequestMiddleware is deprecated. -func (s *SignHTTPRequestMiddleware) ID() string { - return "Signing" -} - -// HandleFinalize will take the provided input and sign the request using the -// SigV4 authentication scheme. -// -// Deprecated: SignHTTPRequestMiddleware is deprecated. -func (s *SignHTTPRequestMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( - out middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - if !haveCredentialProvider(s.credentialsProvider) { - return next.HandleFinalize(ctx, in) - } - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, &SigningError{Err: fmt.Errorf("unexpected request middleware type %T", in.Request)} - } - - signingName, signingRegion := awsmiddleware.GetSigningName(ctx), awsmiddleware.GetSigningRegion(ctx) - payloadHash := GetPayloadHash(ctx) - if len(payloadHash) == 0 { - return out, metadata, &SigningError{Err: fmt.Errorf("computed payload hash missing from context")} - } - - mctx := metrics.Context(ctx) - - if mctx != nil { - if attempt, err := mctx.Data().LatestAttempt(); err == nil { - attempt.CredentialFetchStartTime = sdk.NowTime() - } - } - - credentials, err := s.credentialsProvider.Retrieve(ctx) - - if mctx != nil { - if attempt, err := mctx.Data().LatestAttempt(); err == nil { - attempt.CredentialFetchEndTime = sdk.NowTime() - } - } - - if err != nil { - return out, metadata, &SigningError{Err: fmt.Errorf("failed to retrieve credentials: %w", err)} - } - - signerOptions := []func(o *SignerOptions){ - func(o *SignerOptions) { - o.Logger = middleware.GetLogger(ctx) - o.LogSigning = s.logSigning - }, - } - - // existing DisableURIPathEscaping is equivalent in purpose - // to authentication scheme property DisableDoubleEncoding - disableDoubleEncoding, overridden := internalauth.GetDisableDoubleEncoding(ctx) - if overridden { - signerOptions = append(signerOptions, func(o *SignerOptions) { - o.DisableURIPathEscaping = disableDoubleEncoding - }) - } - - if mctx != nil { - if attempt, err := mctx.Data().LatestAttempt(); err == nil { - attempt.SignStartTime = sdk.NowTime() - } - } - - err = s.signer.SignHTTP(ctx, credentials, req.Request, payloadHash, signingName, signingRegion, sdk.NowTime(), signerOptions...) - - if mctx != nil { - if attempt, err := mctx.Data().LatestAttempt(); err == nil { - attempt.SignEndTime = sdk.NowTime() - } - } - - if err != nil { - return out, metadata, &SigningError{Err: fmt.Errorf("failed to sign http request, %w", err)} - } - - ctx = awsmiddleware.SetSigningCredentials(ctx, credentials) - - return next.HandleFinalize(ctx, in) -} - -type streamingEventsPayload struct{} - -// AddStreamingEventsPayload adds the streamingEventsPayload middleware to the stack. -func AddStreamingEventsPayload(stack *middleware.Stack) error { - return stack.Finalize.Add(&streamingEventsPayload{}, middleware.Before) -} - -func (s *streamingEventsPayload) ID() string { - return computePayloadHashMiddlewareID -} - -func (s *streamingEventsPayload) HandleFinalize( - ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler, -) ( - out middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - contentSHA := GetPayloadHash(ctx) - if len(contentSHA) == 0 { - contentSHA = v4Internal.StreamingEventsPayload - } - - ctx = SetPayloadHash(ctx, contentSHA) - - return next.HandleFinalize(ctx, in) -} - -// GetSignedRequestSignature attempts to extract the signature of the request. -// Returning an error if the request is unsigned, or unable to extract the -// signature. -func GetSignedRequestSignature(r *http.Request) ([]byte, error) { - const authHeaderSignatureElem = "Signature=" - - if auth := r.Header.Get(authorizationHeader); len(auth) != 0 { - ps := strings.Split(auth, ", ") - for _, p := range ps { - if idx := strings.Index(p, authHeaderSignatureElem); idx >= 0 { - sig := p[len(authHeaderSignatureElem):] - if len(sig) == 0 { - return nil, fmt.Errorf("invalid request signature authorization header") - } - return hex.DecodeString(sig) - } - } - } - - if sig := r.URL.Query().Get("X-Amz-Signature"); len(sig) != 0 { - return hex.DecodeString(sig) - } - - return nil, fmt.Errorf("request not signed") -} - -func haveCredentialProvider(p aws.CredentialsProvider) bool { - if p == nil { - return false - } - - return !aws.IsCredentialsProvider(p, (*aws.AnonymousCredentials)(nil)) -} - -type payloadHashKey struct{} - -// GetPayloadHash retrieves the payload hash to use for signing -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetPayloadHash(ctx context.Context) (v string) { - v, _ = middleware.GetStackValue(ctx, payloadHashKey{}).(string) - return v -} - -// SetPayloadHash sets the payload hash to be used for signing the request -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetPayloadHash(ctx context.Context, hash string) context.Context { - return middleware.WithStackValue(ctx, payloadHashKey{}, hash) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/presign_middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/presign_middleware.go deleted file mode 100644 index e1a06651..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/presign_middleware.go +++ /dev/null @@ -1,127 +0,0 @@ -package v4 - -import ( - "context" - "fmt" - "net/http" - "time" - - "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/internal/sdk" - "github.com/aws/smithy-go/middleware" - smithyHTTP "github.com/aws/smithy-go/transport/http" -) - -// HTTPPresigner is an interface to a SigV4 signer that can sign create a -// presigned URL for a HTTP requests. -type HTTPPresigner interface { - PresignHTTP( - ctx context.Context, credentials aws.Credentials, r *http.Request, - payloadHash string, service string, region string, signingTime time.Time, - optFns ...func(*SignerOptions), - ) (url string, signedHeader http.Header, err error) -} - -// PresignedHTTPRequest provides the URL and signed headers that are included -// in the presigned URL. -type PresignedHTTPRequest struct { - URL string - Method string - SignedHeader http.Header -} - -// PresignHTTPRequestMiddlewareOptions is the options for the PresignHTTPRequestMiddleware middleware. -type PresignHTTPRequestMiddlewareOptions struct { - CredentialsProvider aws.CredentialsProvider - Presigner HTTPPresigner - LogSigning bool -} - -// PresignHTTPRequestMiddleware provides the Finalize middleware for creating a -// presigned URL for an HTTP request. -// -// Will short circuit the middleware stack and not forward onto the next -// Finalize handler. -type PresignHTTPRequestMiddleware struct { - credentialsProvider aws.CredentialsProvider - presigner HTTPPresigner - logSigning bool -} - -// NewPresignHTTPRequestMiddleware returns a new PresignHTTPRequestMiddleware -// initialized with the presigner. -func NewPresignHTTPRequestMiddleware(options PresignHTTPRequestMiddlewareOptions) *PresignHTTPRequestMiddleware { - return &PresignHTTPRequestMiddleware{ - credentialsProvider: options.CredentialsProvider, - presigner: options.Presigner, - logSigning: options.LogSigning, - } -} - -// ID provides the middleware ID. -func (*PresignHTTPRequestMiddleware) ID() string { return "PresignHTTPRequest" } - -// HandleFinalize will take the provided input and create a presigned url for -// the http request using the SigV4 presign authentication scheme. -// -// Since the signed request is not a valid HTTP request -func (s *PresignHTTPRequestMiddleware) 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, &SigningError{ - Err: fmt.Errorf("unexpected request middleware type %T", in.Request), - } - } - - httpReq := req.Build(ctx) - if !haveCredentialProvider(s.credentialsProvider) { - out.Result = &PresignedHTTPRequest{ - URL: httpReq.URL.String(), - Method: httpReq.Method, - SignedHeader: http.Header{}, - } - - return out, metadata, nil - } - - signingName := awsmiddleware.GetSigningName(ctx) - signingRegion := awsmiddleware.GetSigningRegion(ctx) - payloadHash := GetPayloadHash(ctx) - if len(payloadHash) == 0 { - return out, metadata, &SigningError{ - Err: fmt.Errorf("computed payload hash missing from context"), - } - } - - credentials, err := s.credentialsProvider.Retrieve(ctx) - if err != nil { - return out, metadata, &SigningError{ - Err: fmt.Errorf("failed to retrieve credentials: %w", err), - } - } - - u, h, err := s.presigner.PresignHTTP(ctx, credentials, - httpReq, payloadHash, signingName, signingRegion, sdk.NowTime(), - func(o *SignerOptions) { - o.Logger = middleware.GetLogger(ctx) - o.LogSigning = s.logSigning - }) - if err != nil { - return out, metadata, &SigningError{ - Err: fmt.Errorf("failed to sign http request, %w", err), - } - } - - out.Result = &PresignedHTTPRequest{ - URL: u, - Method: httpReq.Method, - SignedHeader: h, - } - - return out, metadata, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/stream.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/stream.go deleted file mode 100644 index 66aa2bd6..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/stream.go +++ /dev/null @@ -1,86 +0,0 @@ -package v4 - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "github.com/aws/aws-sdk-go-v2/aws" - v4Internal "github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4" - "strings" - "time" -) - -// EventStreamSigner is an AWS EventStream protocol signer. -type EventStreamSigner interface { - GetSignature(ctx context.Context, headers, payload []byte, signingTime time.Time, optFns ...func(*StreamSignerOptions)) ([]byte, error) -} - -// StreamSignerOptions is the configuration options for StreamSigner. -type StreamSignerOptions struct{} - -// StreamSigner implements Signature Version 4 (SigV4) signing of event stream encoded payloads. -type StreamSigner struct { - options StreamSignerOptions - - credentials aws.Credentials - service string - region string - - prevSignature []byte - - signingKeyDeriver *v4Internal.SigningKeyDeriver -} - -// NewStreamSigner returns a new AWS EventStream protocol signer. -func NewStreamSigner(credentials aws.Credentials, service, region string, seedSignature []byte, optFns ...func(*StreamSignerOptions)) *StreamSigner { - o := StreamSignerOptions{} - - for _, fn := range optFns { - fn(&o) - } - - return &StreamSigner{ - options: o, - credentials: credentials, - service: service, - region: region, - signingKeyDeriver: v4Internal.NewSigningKeyDeriver(), - prevSignature: seedSignature, - } -} - -// GetSignature signs the provided header and payload bytes. -func (s *StreamSigner) GetSignature(ctx context.Context, headers, payload []byte, signingTime time.Time, optFns ...func(*StreamSignerOptions)) ([]byte, error) { - options := s.options - - for _, fn := range optFns { - fn(&options) - } - - prevSignature := s.prevSignature - - st := v4Internal.NewSigningTime(signingTime) - - sigKey := s.signingKeyDeriver.DeriveKey(s.credentials, s.service, s.region, st) - - scope := v4Internal.BuildCredentialScope(st, s.region, s.service) - - stringToSign := s.buildEventStreamStringToSign(headers, payload, prevSignature, scope, &st) - - signature := v4Internal.HMACSHA256(sigKey, []byte(stringToSign)) - s.prevSignature = signature - - return signature, nil -} - -func (s *StreamSigner) buildEventStreamStringToSign(headers, payload, previousSignature []byte, credentialScope string, signingTime *v4Internal.SigningTime) string { - hash := sha256.New() - return strings.Join([]string{ - "AWS4-HMAC-SHA256-PAYLOAD", - signingTime.TimeFormat(), - credentialScope, - hex.EncodeToString(previousSignature), - hex.EncodeToString(makeHash(hash, headers)), - hex.EncodeToString(makeHash(hash, payload)), - }, "\n") -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/v4.go deleted file mode 100644 index bb61904e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/signer/v4/v4.go +++ /dev/null @@ -1,560 +0,0 @@ -// Package v4 implements signing for AWS V4 signer -// -// Provides request signing for request that need to be signed with -// AWS V4 Signatures. -// -// # Standalone Signer -// -// Generally using the signer outside of the SDK should not require any additional -// -// The signer does this by taking advantage of the URL.EscapedPath method. If your request URI requires -// -// additional escaping you many need to use the URL.Opaque to define what the raw URI should be sent -// to the service as. -// -// The signer will first check the URL.Opaque field, and use its value if set. -// The signer does require the URL.Opaque field to be set in the form of: -// -// "///" -// -// // e.g. -// "//example.com/some/path" -// -// The leading "//" and hostname are required or the URL.Opaque escaping will -// not work correctly. -// -// If URL.Opaque is not set the signer will fallback to the URL.EscapedPath() -// method and using the returned value. -// -// AWS v4 signature validation requires that the canonical string's URI path -// element must be the URI escaped form of the HTTP request's path. -// http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html -// -// The Go HTTP client will perform escaping automatically on the request. Some -// of these escaping may cause signature validation errors because the HTTP -// request differs from the URI path or query that the signature was generated. -// https://golang.org/pkg/net/url/#URL.EscapedPath -// -// Because of this, it is recommended that when using the signer outside of the -// SDK that explicitly escaping the request prior to being signed is preferable, -// and will help prevent signature validation errors. This can be done by setting -// the URL.Opaque or URL.RawPath. The SDK will use URL.Opaque first and then -// call URL.EscapedPath() if Opaque is not set. -// -// Test `TestStandaloneSign` provides a complete example of using the signer -// outside of the SDK and pre-escaping the URI path. -package v4 - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "fmt" - "hash" - "net/http" - "net/textproto" - "net/url" - "sort" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - v4Internal "github.com/aws/aws-sdk-go-v2/aws/signer/internal/v4" - "github.com/aws/smithy-go/encoding/httpbinding" - "github.com/aws/smithy-go/logging" -) - -const ( - signingAlgorithm = "AWS4-HMAC-SHA256" - authorizationHeader = "Authorization" - - // Version of signing v4 - Version = "SigV4" -) - -// HTTPSigner is an interface to a SigV4 signer that can sign HTTP requests -type HTTPSigner interface { - SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*SignerOptions)) error -} - -type keyDerivator interface { - DeriveKey(credential aws.Credentials, service, region string, signingTime v4Internal.SigningTime) []byte -} - -// SignerOptions is the SigV4 Signer options. -type SignerOptions struct { - // Disables the Signer's moving HTTP header key/value pairs from the HTTP - // request header to the request's query string. This is most commonly used - // with pre-signed requests preventing headers from being added to the - // request's query string. - DisableHeaderHoisting bool - - // Disables the automatic escaping of the URI path of the request for the - // siganture's canonical string's path. For services that do not need additional - // escaping then use this to disable the signer escaping the path. - // - // S3 is an example of a service that does not need additional escaping. - // - // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html - DisableURIPathEscaping bool - - // The logger to send log messages to. - Logger logging.Logger - - // Enable logging of signed requests. - // This will enable logging of the canonical request, the string to sign, and for presigning the subsequent - // presigned URL. - LogSigning bool - - // Disables setting the session token on the request as part of signing - // through X-Amz-Security-Token. This is needed for variations of v4 that - // present the token elsewhere. - DisableSessionToken bool -} - -// Signer applies AWS v4 signing to given request. Use this to sign requests -// that need to be signed with AWS V4 Signatures. -type Signer struct { - options SignerOptions - keyDerivator keyDerivator -} - -// NewSigner returns a new SigV4 Signer -func NewSigner(optFns ...func(signer *SignerOptions)) *Signer { - options := SignerOptions{} - - for _, fn := range optFns { - fn(&options) - } - - return &Signer{options: options, keyDerivator: v4Internal.NewSigningKeyDeriver()} -} - -type httpSigner struct { - Request *http.Request - ServiceName string - Region string - Time v4Internal.SigningTime - Credentials aws.Credentials - KeyDerivator keyDerivator - IsPreSign bool - - PayloadHash string - - DisableHeaderHoisting bool - DisableURIPathEscaping bool - DisableSessionToken bool -} - -func (s *httpSigner) Build() (signedRequest, error) { - req := s.Request - - query := req.URL.Query() - headers := req.Header - - s.setRequiredSigningFields(headers, query) - - // Sort Each Query Key's Values - for key := range query { - sort.Strings(query[key]) - } - - v4Internal.SanitizeHostForHeader(req) - - credentialScope := s.buildCredentialScope() - credentialStr := s.Credentials.AccessKeyID + "/" + credentialScope - if s.IsPreSign { - query.Set(v4Internal.AmzCredentialKey, credentialStr) - } - - unsignedHeaders := headers - if s.IsPreSign && !s.DisableHeaderHoisting { - var urlValues url.Values - urlValues, unsignedHeaders = buildQuery(v4Internal.AllowedQueryHoisting, headers) - for k := range urlValues { - query[k] = urlValues[k] - } - } - - host := req.URL.Host - if len(req.Host) > 0 { - host = req.Host - } - - signedHeaders, signedHeadersStr, canonicalHeaderStr := s.buildCanonicalHeaders(host, v4Internal.IgnoredHeaders, unsignedHeaders, s.Request.ContentLength) - - if s.IsPreSign { - query.Set(v4Internal.AmzSignedHeadersKey, signedHeadersStr) - } - - var rawQuery strings.Builder - rawQuery.WriteString(strings.Replace(query.Encode(), "+", "%20", -1)) - - canonicalURI := v4Internal.GetURIPath(req.URL) - if !s.DisableURIPathEscaping { - canonicalURI = httpbinding.EscapePath(canonicalURI, false) - } - - canonicalString := s.buildCanonicalString( - req.Method, - canonicalURI, - rawQuery.String(), - signedHeadersStr, - canonicalHeaderStr, - ) - - strToSign := s.buildStringToSign(credentialScope, canonicalString) - signingSignature, err := s.buildSignature(strToSign) - if err != nil { - return signedRequest{}, err - } - - if s.IsPreSign { - rawQuery.WriteString("&X-Amz-Signature=") - rawQuery.WriteString(signingSignature) - } else { - headers[authorizationHeader] = append(headers[authorizationHeader][:0], buildAuthorizationHeader(credentialStr, signedHeadersStr, signingSignature)) - } - - req.URL.RawQuery = rawQuery.String() - - return signedRequest{ - Request: req, - SignedHeaders: signedHeaders, - CanonicalString: canonicalString, - StringToSign: strToSign, - PreSigned: s.IsPreSign, - }, nil -} - -func buildAuthorizationHeader(credentialStr, signedHeadersStr, signingSignature string) string { - const credential = "Credential=" - const signedHeaders = "SignedHeaders=" - const signature = "Signature=" - const commaSpace = ", " - - var parts strings.Builder - parts.Grow(len(signingAlgorithm) + 1 + - len(credential) + len(credentialStr) + 2 + - len(signedHeaders) + len(signedHeadersStr) + 2 + - len(signature) + len(signingSignature), - ) - parts.WriteString(signingAlgorithm) - parts.WriteRune(' ') - parts.WriteString(credential) - parts.WriteString(credentialStr) - parts.WriteString(commaSpace) - parts.WriteString(signedHeaders) - parts.WriteString(signedHeadersStr) - parts.WriteString(commaSpace) - parts.WriteString(signature) - parts.WriteString(signingSignature) - return parts.String() -} - -// SignHTTP signs AWS v4 requests with the provided payload hash, service name, region the -// request is made to, and time the request is signed at. The signTime allows -// you to specify that a request is signed for the future, and cannot be -// used until then. -// -// The payloadHash is the hex encoded SHA-256 hash of the request payload, and -// must be provided. Even if the request has no payload (aka body). If the -// request has no payload you should use the hex encoded SHA-256 of an empty -// string as the payloadHash value. -// -// "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" -// -// Some services such as Amazon S3 accept alternative values for the payload -// hash, such as "UNSIGNED-PAYLOAD" for requests where the body will not be -// included in the request signature. -// -// https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html -// -// Sign differs from Presign in that it will sign the request using HTTP -// header values. This type of signing is intended for http.Request values that -// will not be shared, or are shared in a way the header values on the request -// will not be lost. -// -// The passed in request will be modified in place. -func (s Signer) SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(options *SignerOptions)) error { - options := s.options - - for _, fn := range optFns { - fn(&options) - } - - signer := &httpSigner{ - Request: r, - PayloadHash: payloadHash, - ServiceName: service, - Region: region, - Credentials: credentials, - Time: v4Internal.NewSigningTime(signingTime.UTC()), - DisableHeaderHoisting: options.DisableHeaderHoisting, - DisableURIPathEscaping: options.DisableURIPathEscaping, - DisableSessionToken: options.DisableSessionToken, - KeyDerivator: s.keyDerivator, - } - - signedRequest, err := signer.Build() - if err != nil { - return err - } - - logSigningInfo(ctx, options, &signedRequest, false) - - return nil -} - -// PresignHTTP signs AWS v4 requests with the payload hash, service name, region -// the request is made to, and time the request is signed at. The signTime -// allows you to specify that a request is signed for the future, and cannot -// be used until then. -// -// Returns the signed URL and the map of HTTP headers that were included in the -// signature or an error if signing the request failed. For presigned requests -// these headers and their values must be included on the HTTP request when it -// is made. This is helpful to know what header values need to be shared with -// the party the presigned request will be distributed to. -// -// The payloadHash is the hex encoded SHA-256 hash of the request payload, and -// must be provided. Even if the request has no payload (aka body). If the -// request has no payload you should use the hex encoded SHA-256 of an empty -// string as the payloadHash value. -// -// "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" -// -// Some services such as Amazon S3 accept alternative values for the payload -// hash, such as "UNSIGNED-PAYLOAD" for requests where the body will not be -// included in the request signature. -// -// https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html -// -// PresignHTTP differs from SignHTTP in that it will sign the request using -// query string instead of header values. This allows you to share the -// Presigned Request's URL with third parties, or distribute it throughout your -// system with minimal dependencies. -// -// PresignHTTP will not set the expires time of the presigned request -// automatically. To specify the expire duration for a request add the -// "X-Amz-Expires" query parameter on the request with the value as the -// duration in seconds the presigned URL should be considered valid for. This -// parameter is not used by all AWS services, and is most notable used by -// Amazon S3 APIs. -// -// expires := 20 * time.Minute -// query := req.URL.Query() -// query.Set("X-Amz-Expires", strconv.FormatInt(int64(expires/time.Second), 10)) -// req.URL.RawQuery = query.Encode() -// -// This method does not modify the provided request. -func (s *Signer) PresignHTTP( - ctx context.Context, credentials aws.Credentials, r *http.Request, - payloadHash string, service string, region string, signingTime time.Time, - optFns ...func(*SignerOptions), -) (signedURI string, signedHeaders http.Header, err error) { - options := s.options - - for _, fn := range optFns { - fn(&options) - } - - signer := &httpSigner{ - Request: r.Clone(r.Context()), - PayloadHash: payloadHash, - ServiceName: service, - Region: region, - Credentials: credentials, - Time: v4Internal.NewSigningTime(signingTime.UTC()), - IsPreSign: true, - DisableHeaderHoisting: options.DisableHeaderHoisting, - DisableURIPathEscaping: options.DisableURIPathEscaping, - DisableSessionToken: options.DisableSessionToken, - KeyDerivator: s.keyDerivator, - } - - signedRequest, err := signer.Build() - if err != nil { - return "", nil, err - } - - logSigningInfo(ctx, options, &signedRequest, true) - - signedHeaders = make(http.Header) - - // For the signed headers we canonicalize the header keys in the returned map. - // This avoids situations where can standard library double headers like host header. For example the standard - // library will set the Host header, even if it is present in lower-case form. - for k, v := range signedRequest.SignedHeaders { - key := textproto.CanonicalMIMEHeaderKey(k) - signedHeaders[key] = append(signedHeaders[key], v...) - } - - return signedRequest.Request.URL.String(), signedHeaders, nil -} - -func (s *httpSigner) buildCredentialScope() string { - return v4Internal.BuildCredentialScope(s.Time, s.Region, s.ServiceName) -} - -func buildQuery(r v4Internal.Rule, header http.Header) (url.Values, http.Header) { - query := url.Values{} - unsignedHeaders := http.Header{} - for k, h := range header { - if r.IsValid(k) { - query[k] = h - } else { - unsignedHeaders[k] = h - } - } - - return query, unsignedHeaders -} - -func (s *httpSigner) buildCanonicalHeaders(host string, rule v4Internal.Rule, header http.Header, length int64) (signed http.Header, signedHeaders, canonicalHeadersStr string) { - signed = make(http.Header) - - var headers []string - const hostHeader = "host" - headers = append(headers, hostHeader) - signed[hostHeader] = append(signed[hostHeader], host) - - const contentLengthHeader = "content-length" - if length > 0 { - headers = append(headers, contentLengthHeader) - signed[contentLengthHeader] = append(signed[contentLengthHeader], strconv.FormatInt(length, 10)) - } - - for k, v := range header { - if !rule.IsValid(k) { - continue // ignored header - } - if strings.EqualFold(k, contentLengthHeader) { - // prevent signing already handled content-length header. - continue - } - - lowerCaseKey := strings.ToLower(k) - if _, ok := signed[lowerCaseKey]; ok { - // include additional values - signed[lowerCaseKey] = append(signed[lowerCaseKey], v...) - continue - } - - headers = append(headers, lowerCaseKey) - signed[lowerCaseKey] = v - } - sort.Strings(headers) - - signedHeaders = strings.Join(headers, ";") - - var canonicalHeaders strings.Builder - n := len(headers) - const colon = ':' - for i := 0; i < n; i++ { - if headers[i] == hostHeader { - canonicalHeaders.WriteString(hostHeader) - canonicalHeaders.WriteRune(colon) - canonicalHeaders.WriteString(v4Internal.StripExcessSpaces(host)) - } else { - canonicalHeaders.WriteString(headers[i]) - canonicalHeaders.WriteRune(colon) - // Trim out leading, trailing, and dedup inner spaces from signed header values. - values := signed[headers[i]] - for j, v := range values { - cleanedValue := strings.TrimSpace(v4Internal.StripExcessSpaces(v)) - canonicalHeaders.WriteString(cleanedValue) - if j < len(values)-1 { - canonicalHeaders.WriteRune(',') - } - } - } - canonicalHeaders.WriteRune('\n') - } - canonicalHeadersStr = canonicalHeaders.String() - - return signed, signedHeaders, canonicalHeadersStr -} - -func (s *httpSigner) buildCanonicalString(method, uri, query, signedHeaders, canonicalHeaders string) string { - return strings.Join([]string{ - method, - uri, - query, - canonicalHeaders, - signedHeaders, - s.PayloadHash, - }, "\n") -} - -func (s *httpSigner) buildStringToSign(credentialScope, canonicalRequestString string) string { - return strings.Join([]string{ - signingAlgorithm, - s.Time.TimeFormat(), - credentialScope, - hex.EncodeToString(makeHash(sha256.New(), []byte(canonicalRequestString))), - }, "\n") -} - -func makeHash(hash hash.Hash, b []byte) []byte { - hash.Reset() - hash.Write(b) - return hash.Sum(nil) -} - -func (s *httpSigner) buildSignature(strToSign string) (string, error) { - key := s.KeyDerivator.DeriveKey(s.Credentials, s.ServiceName, s.Region, s.Time) - return hex.EncodeToString(v4Internal.HMACSHA256(key, []byte(strToSign))), nil -} - -func (s *httpSigner) setRequiredSigningFields(headers http.Header, query url.Values) { - amzDate := s.Time.TimeFormat() - - if s.IsPreSign { - query.Set(v4Internal.AmzAlgorithmKey, signingAlgorithm) - sessionToken := s.Credentials.SessionToken - if !s.DisableSessionToken && len(sessionToken) > 0 { - query.Set("X-Amz-Security-Token", sessionToken) - } - - query.Set(v4Internal.AmzDateKey, amzDate) - return - } - - headers[v4Internal.AmzDateKey] = append(headers[v4Internal.AmzDateKey][:0], amzDate) - - if !s.DisableSessionToken && len(s.Credentials.SessionToken) > 0 { - headers[v4Internal.AmzSecurityTokenKey] = append(headers[v4Internal.AmzSecurityTokenKey][:0], s.Credentials.SessionToken) - } -} - -func logSigningInfo(ctx context.Context, options SignerOptions, request *signedRequest, isPresign bool) { - if !options.LogSigning { - return - } - signedURLMsg := "" - if isPresign { - signedURLMsg = fmt.Sprintf(logSignedURLMsg, request.Request.URL.String()) - } - logger := logging.WithContext(ctx, options.Logger) - logger.Logf(logging.Debug, logSignInfoMsg, request.CanonicalString, request.StringToSign, signedURLMsg) -} - -type signedRequest struct { - Request *http.Request - SignedHeaders http.Header - CanonicalString string - StringToSign string - PreSigned bool -} - -const logSignInfoMsg = `Request Signature: ----[ CANONICAL STRING ]----------------------------- -%s ----[ STRING TO SIGN ]-------------------------------- -%s%s ------------------------------------------------------` -const logSignedURLMsg = ` ----[ SIGNED URL ]------------------------------------ -%s` diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/to_ptr.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/to_ptr.go deleted file mode 100644 index f3fc4d61..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/to_ptr.go +++ /dev/null @@ -1,297 +0,0 @@ -// Code generated by aws/generate.go DO NOT EDIT. - -package aws - -import ( - "github.com/aws/smithy-go/ptr" - "time" -) - -// Bool returns a pointer value for the bool value passed in. -func Bool(v bool) *bool { - return ptr.Bool(v) -} - -// BoolSlice returns a slice of bool pointers from the values -// passed in. -func BoolSlice(vs []bool) []*bool { - return ptr.BoolSlice(vs) -} - -// BoolMap returns a map of bool pointers from the values -// passed in. -func BoolMap(vs map[string]bool) map[string]*bool { - return ptr.BoolMap(vs) -} - -// Byte returns a pointer value for the byte value passed in. -func Byte(v byte) *byte { - return ptr.Byte(v) -} - -// ByteSlice returns a slice of byte pointers from the values -// passed in. -func ByteSlice(vs []byte) []*byte { - return ptr.ByteSlice(vs) -} - -// ByteMap returns a map of byte pointers from the values -// passed in. -func ByteMap(vs map[string]byte) map[string]*byte { - return ptr.ByteMap(vs) -} - -// String returns a pointer value for the string value passed in. -func String(v string) *string { - return ptr.String(v) -} - -// StringSlice returns a slice of string pointers from the values -// passed in. -func StringSlice(vs []string) []*string { - return ptr.StringSlice(vs) -} - -// StringMap returns a map of string pointers from the values -// passed in. -func StringMap(vs map[string]string) map[string]*string { - return ptr.StringMap(vs) -} - -// Int returns a pointer value for the int value passed in. -func Int(v int) *int { - return ptr.Int(v) -} - -// IntSlice returns a slice of int pointers from the values -// passed in. -func IntSlice(vs []int) []*int { - return ptr.IntSlice(vs) -} - -// IntMap returns a map of int pointers from the values -// passed in. -func IntMap(vs map[string]int) map[string]*int { - return ptr.IntMap(vs) -} - -// Int8 returns a pointer value for the int8 value passed in. -func Int8(v int8) *int8 { - return ptr.Int8(v) -} - -// Int8Slice returns a slice of int8 pointers from the values -// passed in. -func Int8Slice(vs []int8) []*int8 { - return ptr.Int8Slice(vs) -} - -// Int8Map returns a map of int8 pointers from the values -// passed in. -func Int8Map(vs map[string]int8) map[string]*int8 { - return ptr.Int8Map(vs) -} - -// Int16 returns a pointer value for the int16 value passed in. -func Int16(v int16) *int16 { - return ptr.Int16(v) -} - -// Int16Slice returns a slice of int16 pointers from the values -// passed in. -func Int16Slice(vs []int16) []*int16 { - return ptr.Int16Slice(vs) -} - -// Int16Map returns a map of int16 pointers from the values -// passed in. -func Int16Map(vs map[string]int16) map[string]*int16 { - return ptr.Int16Map(vs) -} - -// Int32 returns a pointer value for the int32 value passed in. -func Int32(v int32) *int32 { - return ptr.Int32(v) -} - -// Int32Slice returns a slice of int32 pointers from the values -// passed in. -func Int32Slice(vs []int32) []*int32 { - return ptr.Int32Slice(vs) -} - -// Int32Map returns a map of int32 pointers from the values -// passed in. -func Int32Map(vs map[string]int32) map[string]*int32 { - return ptr.Int32Map(vs) -} - -// Int64 returns a pointer value for the int64 value passed in. -func Int64(v int64) *int64 { - return ptr.Int64(v) -} - -// Int64Slice returns a slice of int64 pointers from the values -// passed in. -func Int64Slice(vs []int64) []*int64 { - return ptr.Int64Slice(vs) -} - -// Int64Map returns a map of int64 pointers from the values -// passed in. -func Int64Map(vs map[string]int64) map[string]*int64 { - return ptr.Int64Map(vs) -} - -// Uint returns a pointer value for the uint value passed in. -func Uint(v uint) *uint { - return ptr.Uint(v) -} - -// UintSlice returns a slice of uint pointers from the values -// passed in. -func UintSlice(vs []uint) []*uint { - return ptr.UintSlice(vs) -} - -// UintMap returns a map of uint pointers from the values -// passed in. -func UintMap(vs map[string]uint) map[string]*uint { - return ptr.UintMap(vs) -} - -// Uint8 returns a pointer value for the uint8 value passed in. -func Uint8(v uint8) *uint8 { - return ptr.Uint8(v) -} - -// Uint8Slice returns a slice of uint8 pointers from the values -// passed in. -func Uint8Slice(vs []uint8) []*uint8 { - return ptr.Uint8Slice(vs) -} - -// Uint8Map returns a map of uint8 pointers from the values -// passed in. -func Uint8Map(vs map[string]uint8) map[string]*uint8 { - return ptr.Uint8Map(vs) -} - -// Uint16 returns a pointer value for the uint16 value passed in. -func Uint16(v uint16) *uint16 { - return ptr.Uint16(v) -} - -// Uint16Slice returns a slice of uint16 pointers from the values -// passed in. -func Uint16Slice(vs []uint16) []*uint16 { - return ptr.Uint16Slice(vs) -} - -// Uint16Map returns a map of uint16 pointers from the values -// passed in. -func Uint16Map(vs map[string]uint16) map[string]*uint16 { - return ptr.Uint16Map(vs) -} - -// Uint32 returns a pointer value for the uint32 value passed in. -func Uint32(v uint32) *uint32 { - return ptr.Uint32(v) -} - -// Uint32Slice returns a slice of uint32 pointers from the values -// passed in. -func Uint32Slice(vs []uint32) []*uint32 { - return ptr.Uint32Slice(vs) -} - -// Uint32Map returns a map of uint32 pointers from the values -// passed in. -func Uint32Map(vs map[string]uint32) map[string]*uint32 { - return ptr.Uint32Map(vs) -} - -// Uint64 returns a pointer value for the uint64 value passed in. -func Uint64(v uint64) *uint64 { - return ptr.Uint64(v) -} - -// Uint64Slice returns a slice of uint64 pointers from the values -// passed in. -func Uint64Slice(vs []uint64) []*uint64 { - return ptr.Uint64Slice(vs) -} - -// Uint64Map returns a map of uint64 pointers from the values -// passed in. -func Uint64Map(vs map[string]uint64) map[string]*uint64 { - return ptr.Uint64Map(vs) -} - -// Float32 returns a pointer value for the float32 value passed in. -func Float32(v float32) *float32 { - return ptr.Float32(v) -} - -// Float32Slice returns a slice of float32 pointers from the values -// passed in. -func Float32Slice(vs []float32) []*float32 { - return ptr.Float32Slice(vs) -} - -// Float32Map returns a map of float32 pointers from the values -// passed in. -func Float32Map(vs map[string]float32) map[string]*float32 { - return ptr.Float32Map(vs) -} - -// Float64 returns a pointer value for the float64 value passed in. -func Float64(v float64) *float64 { - return ptr.Float64(v) -} - -// Float64Slice returns a slice of float64 pointers from the values -// passed in. -func Float64Slice(vs []float64) []*float64 { - return ptr.Float64Slice(vs) -} - -// Float64Map returns a map of float64 pointers from the values -// passed in. -func Float64Map(vs map[string]float64) map[string]*float64 { - return ptr.Float64Map(vs) -} - -// Time returns a pointer value for the time.Time value passed in. -func Time(v time.Time) *time.Time { - return ptr.Time(v) -} - -// TimeSlice returns a slice of time.Time pointers from the values -// passed in. -func TimeSlice(vs []time.Time) []*time.Time { - return ptr.TimeSlice(vs) -} - -// TimeMap returns a map of time.Time pointers from the values -// passed in. -func TimeMap(vs map[string]time.Time) map[string]*time.Time { - return ptr.TimeMap(vs) -} - -// Duration returns a pointer value for the time.Duration value passed in. -func Duration(v time.Duration) *time.Duration { - return ptr.Duration(v) -} - -// DurationSlice returns a slice of time.Duration pointers from the values -// passed in. -func DurationSlice(vs []time.Duration) []*time.Duration { - return ptr.DurationSlice(vs) -} - -// DurationMap returns a map of time.Duration pointers from the values -// passed in. -func DurationMap(vs map[string]time.Duration) map[string]*time.Duration { - return ptr.DurationMap(vs) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/client.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/client.go deleted file mode 100644 index 26d90719..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/client.go +++ /dev/null @@ -1,310 +0,0 @@ -package http - -import ( - "crypto/tls" - "github.com/aws/aws-sdk-go-v2/aws" - "net" - "net/http" - "reflect" - "sync" - "time" -) - -// Defaults for the HTTPTransportBuilder. -var ( - // Default connection pool options - DefaultHTTPTransportMaxIdleConns = 100 - DefaultHTTPTransportMaxIdleConnsPerHost = 10 - - // Default connection timeouts - DefaultHTTPTransportIdleConnTimeout = 90 * time.Second - DefaultHTTPTransportTLSHandleshakeTimeout = 10 * time.Second - DefaultHTTPTransportExpectContinueTimeout = 1 * time.Second - - // Default to TLS 1.2 for all HTTPS requests. - DefaultHTTPTransportTLSMinVersion uint16 = tls.VersionTLS12 -) - -// Timeouts for net.Dialer's network connection. -var ( - DefaultDialConnectTimeout = 30 * time.Second - DefaultDialKeepAliveTimeout = 30 * time.Second -) - -// BuildableClient provides a HTTPClient implementation with options to -// create copies of the HTTPClient when additional configuration is provided. -// -// The client's methods will not share the http.Transport value between copies -// of the BuildableClient. Only exported member values of the Transport and -// optional Dialer will be copied between copies of BuildableClient. -type BuildableClient struct { - transport *http.Transport - dialer *net.Dialer - - initOnce sync.Once - - clientTimeout time.Duration - client *http.Client -} - -// NewBuildableClient returns an initialized client for invoking HTTP -// requests. -func NewBuildableClient() *BuildableClient { - return &BuildableClient{} -} - -// Do implements the HTTPClient interface's Do method to invoke a HTTP request, -// and receive the response. Uses the BuildableClient's current -// configuration to invoke the http.Request. -// -// If connection pooling is enabled (aka HTTP KeepAlive) the client will only -// share pooled connections with its own instance. Copies of the -// BuildableClient will have their own connection pools. -// -// Redirect (3xx) responses will not be followed, the HTTP response received -// will returned instead. -func (b *BuildableClient) Do(req *http.Request) (*http.Response, error) { - b.initOnce.Do(b.build) - - return b.client.Do(req) -} - -// Freeze returns a frozen aws.HTTPClient implementation that is no longer a BuildableClient. -// Use this to prevent the SDK from applying DefaultMode configuration values to a buildable client. -func (b *BuildableClient) Freeze() aws.HTTPClient { - cpy := b.clone() - cpy.build() - return cpy.client -} - -func (b *BuildableClient) build() { - b.client = wrapWithLimitedRedirect(&http.Client{ - Timeout: b.clientTimeout, - Transport: b.GetTransport(), - }) -} - -func (b *BuildableClient) clone() *BuildableClient { - cpy := NewBuildableClient() - cpy.transport = b.GetTransport() - cpy.dialer = b.GetDialer() - cpy.clientTimeout = b.clientTimeout - - return cpy -} - -// WithTransportOptions copies the BuildableClient and returns it with the -// http.Transport options applied. -// -// If a non (*http.Transport) was set as the round tripper, the round tripper -// will be replaced with a default Transport value before invoking the option -// functions. -func (b *BuildableClient) WithTransportOptions(opts ...func(*http.Transport)) *BuildableClient { - cpy := b.clone() - - tr := cpy.GetTransport() - for _, opt := range opts { - opt(tr) - } - cpy.transport = tr - - return cpy -} - -// WithDialerOptions copies the BuildableClient and returns it with the -// net.Dialer options applied. Will set the client's http.Transport DialContext -// member. -func (b *BuildableClient) WithDialerOptions(opts ...func(*net.Dialer)) *BuildableClient { - cpy := b.clone() - - dialer := cpy.GetDialer() - for _, opt := range opts { - opt(dialer) - } - cpy.dialer = dialer - - tr := cpy.GetTransport() - tr.DialContext = cpy.dialer.DialContext - cpy.transport = tr - - return cpy -} - -// WithTimeout Sets the timeout used by the client for all requests. -func (b *BuildableClient) WithTimeout(timeout time.Duration) *BuildableClient { - cpy := b.clone() - cpy.clientTimeout = timeout - return cpy -} - -// GetTransport returns a copy of the client's HTTP Transport. -func (b *BuildableClient) GetTransport() *http.Transport { - var tr *http.Transport - if b.transport != nil { - tr = b.transport.Clone() - } else { - tr = defaultHTTPTransport() - } - - return tr -} - -// GetDialer returns a copy of the client's network dialer. -func (b *BuildableClient) GetDialer() *net.Dialer { - var dialer *net.Dialer - if b.dialer != nil { - dialer = shallowCopyStruct(b.dialer).(*net.Dialer) - } else { - dialer = defaultDialer() - } - - return dialer -} - -// GetTimeout returns a copy of the client's timeout to cancel requests with. -func (b *BuildableClient) GetTimeout() time.Duration { - return b.clientTimeout -} - -func defaultDialer() *net.Dialer { - return &net.Dialer{ - Timeout: DefaultDialConnectTimeout, - KeepAlive: DefaultDialKeepAliveTimeout, - DualStack: true, - } -} - -func defaultHTTPTransport() *http.Transport { - dialer := defaultDialer() - - tr := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: dialer.DialContext, - TLSHandshakeTimeout: DefaultHTTPTransportTLSHandleshakeTimeout, - MaxIdleConns: DefaultHTTPTransportMaxIdleConns, - MaxIdleConnsPerHost: DefaultHTTPTransportMaxIdleConnsPerHost, - IdleConnTimeout: DefaultHTTPTransportIdleConnTimeout, - ExpectContinueTimeout: DefaultHTTPTransportExpectContinueTimeout, - ForceAttemptHTTP2: true, - TLSClientConfig: &tls.Config{ - MinVersion: DefaultHTTPTransportTLSMinVersion, - }, - } - - return tr -} - -// shallowCopyStruct creates a shallow copy of the passed in source struct, and -// returns that copy of the same struct type. -func shallowCopyStruct(src interface{}) interface{} { - srcVal := reflect.ValueOf(src) - srcValType := srcVal.Type() - - var returnAsPtr bool - if srcValType.Kind() == reflect.Ptr { - srcVal = srcVal.Elem() - srcValType = srcValType.Elem() - returnAsPtr = true - } - dstVal := reflect.New(srcValType).Elem() - - for i := 0; i < srcValType.NumField(); i++ { - ft := srcValType.Field(i) - if len(ft.PkgPath) != 0 { - // unexported fields have a PkgPath - continue - } - - dstVal.Field(i).Set(srcVal.Field(i)) - } - - if returnAsPtr { - dstVal = dstVal.Addr() - } - - return dstVal.Interface() -} - -// wrapWithLimitedRedirect updates the Client's Transport and CheckRedirect to -// not follow any redirect other than 307 and 308. No other redirect will be -// followed. -// -// If the client does not have a Transport defined will use a new SDK default -// http.Transport configuration. -func wrapWithLimitedRedirect(c *http.Client) *http.Client { - tr := c.Transport - if tr == nil { - tr = defaultHTTPTransport() - } - - cc := *c - cc.CheckRedirect = limitedRedirect - cc.Transport = suppressBadHTTPRedirectTransport{ - tr: tr, - } - - return &cc -} - -// limitedRedirect is a CheckRedirect that prevents the client from following -// any non 307/308 HTTP status code redirects. -// -// The 307 and 308 redirects are allowed because the client must use the -// original HTTP method for the redirected to location. Whereas 301 and 302 -// allow the client to switch to GET for the redirect. -// -// Suppresses all redirect requests with a URL of badHTTPRedirectLocation. -func limitedRedirect(r *http.Request, via []*http.Request) error { - // Request.Response, in CheckRedirect is the response that is triggering - // the redirect. - resp := r.Response - if r.URL.String() == badHTTPRedirectLocation { - resp.Header.Del(badHTTPRedirectLocation) - return http.ErrUseLastResponse - } - - switch resp.StatusCode { - case 307, 308: - // Only allow 307 and 308 redirects as they preserve the method. - return nil - } - - return http.ErrUseLastResponse -} - -// suppressBadHTTPRedirectTransport provides an http.RoundTripper -// implementation that wraps another http.RoundTripper to prevent HTTP client -// receiving 301 and 302 HTTP responses redirects without the required location -// header. -// -// Clients using this utility must have a CheckRedirect, e.g. limitedRedirect, -// that check for responses with having a URL of baseHTTPRedirectLocation, and -// suppress the redirect. -type suppressBadHTTPRedirectTransport struct { - tr http.RoundTripper -} - -const badHTTPRedirectLocation = `https://amazonaws.com/badhttpredirectlocation` - -// RoundTrip backfills a stub location when a 301/302 response is received -// without a location. This stub location is used by limitedRedirect to prevent -// the HTTP client from failing attempting to use follow a redirect without a -// location value. -func (t suppressBadHTTPRedirectTransport) RoundTrip(r *http.Request) (*http.Response, error) { - resp, err := t.tr.RoundTrip(r) - if err != nil { - return resp, err - } - - // S3 is the only known service to return 301 without location header. - // The Go standard library HTTP client will return an opaque error if it - // tries to follow a 301/302 response missing the location header. - switch resp.StatusCode { - case 301, 302: - if v := resp.Header.Get("Location"); len(v) == 0 { - resp.Header.Set("Location", badHTTPRedirectLocation) - } - } - - return resp, err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/content_type.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/content_type.go deleted file mode 100644 index 556f54a7..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/content_type.go +++ /dev/null @@ -1,42 +0,0 @@ -package http - -import ( - "context" - "fmt" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// removeContentTypeHeader is a build middleware that removes -// content type header if content-length header is unset or -// is set to zero, -type removeContentTypeHeader struct { -} - -// ID the name of the middleware. -func (m *removeContentTypeHeader) ID() string { - return "RemoveContentTypeHeader" -} - -// HandleBuild adds or appends the constructed user agent to the request. -func (m *removeContentTypeHeader) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in) - } - - // remove contentTypeHeader when content-length is zero - if req.ContentLength == 0 { - req.Header.Del("content-type") - } - - return next.HandleBuild(ctx, in) -} - -// RemoveContentTypeHeader removes content-type header if -// content length is unset or equal to zero. -func RemoveContentTypeHeader(stack *middleware.Stack) error { - return stack.Build.Add(&removeContentTypeHeader{}, middleware.After) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error.go deleted file mode 100644 index 44651c99..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error.go +++ /dev/null @@ -1,33 +0,0 @@ -package http - -import ( - "errors" - "fmt" - - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// ResponseError provides the HTTP centric error type wrapping the underlying error -// with the HTTP response value and the deserialized RequestID. -type ResponseError struct { - *smithyhttp.ResponseError - - // RequestID associated with response error - RequestID string -} - -// ServiceRequestID returns the request id associated with Response Error -func (e *ResponseError) ServiceRequestID() string { return e.RequestID } - -// Error returns the formatted error -func (e *ResponseError) Error() string { - return fmt.Sprintf( - "https response error StatusCode: %d, RequestID: %s, %v", - e.Response.StatusCode, e.RequestID, e.Err) -} - -// As populates target and returns true if the type of target is a error type that -// the ResponseError embeds, (e.g.AWS HTTP ResponseError) -func (e *ResponseError) As(target interface{}) bool { - return errors.As(e.ResponseError, target) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error_middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error_middleware.go deleted file mode 100644 index 8fd14cec..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/response_error_middleware.go +++ /dev/null @@ -1,54 +0,0 @@ -package http - -import ( - "context" - - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// AddResponseErrorMiddleware adds response error wrapper middleware -func AddResponseErrorMiddleware(stack *middleware.Stack) error { - // add error wrapper middleware before request id retriever middleware so that it can wrap the error response - // returned by operation deserializers - return stack.Deserialize.Insert(&responseErrorWrapper{}, "RequestIDRetriever", middleware.Before) -} - -type responseErrorWrapper struct { -} - -// ID returns the middleware identifier -func (m *responseErrorWrapper) ID() string { - return "ResponseErrorWrapper" -} - -func (m *responseErrorWrapper) 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 { - // Nothing to do when there is no error. - return out, metadata, err - } - - resp, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - // No raw response to wrap with. - return out, metadata, err - } - - // look for request id in metadata - reqID, _ := awsmiddleware.GetRequestIDMetadata(metadata) - - // Wrap the returned smithy error with the request id retrieved from the metadata - err = &ResponseError{ - ResponseError: &smithyhttp.ResponseError{ - Response: resp, - Err: err, - }, - RequestID: reqID, - } - - return out, metadata, err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/timeout_read_closer.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/timeout_read_closer.go deleted file mode 100644 index 993929bd..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/transport/http/timeout_read_closer.go +++ /dev/null @@ -1,104 +0,0 @@ -package http - -import ( - "context" - "fmt" - "io" - "time" - - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -type readResult struct { - n int - err error -} - -// ResponseTimeoutError is an error when the reads from the response are -// delayed longer than the timeout the read was configured for. -type ResponseTimeoutError struct { - TimeoutDur time.Duration -} - -// Timeout returns that the error is was caused by a timeout, and can be -// retried. -func (*ResponseTimeoutError) Timeout() bool { return true } - -func (e *ResponseTimeoutError) Error() string { - return fmt.Sprintf("read on body reach timeout limit, %v", e.TimeoutDur) -} - -// timeoutReadCloser will handle body reads that take too long. -// We will return a ErrReadTimeout error if a timeout occurs. -type timeoutReadCloser struct { - reader io.ReadCloser - duration time.Duration -} - -// Read will spin off a goroutine to call the reader's Read method. We will -// select on the timer's channel or the read's channel. Whoever completes first -// will be returned. -func (r *timeoutReadCloser) Read(b []byte) (int, error) { - timer := time.NewTimer(r.duration) - c := make(chan readResult, 1) - - go func() { - n, err := r.reader.Read(b) - timer.Stop() - c <- readResult{n: n, err: err} - }() - - select { - case data := <-c: - return data.n, data.err - case <-timer.C: - return 0, &ResponseTimeoutError{TimeoutDur: r.duration} - } -} - -func (r *timeoutReadCloser) Close() error { - return r.reader.Close() -} - -// AddResponseReadTimeoutMiddleware adds a middleware to the stack that wraps the -// response body so that a read that takes too long will return an error. -func AddResponseReadTimeoutMiddleware(stack *middleware.Stack, duration time.Duration) error { - return stack.Deserialize.Add(&readTimeout{duration: duration}, middleware.After) -} - -// readTimeout wraps the response body with a timeoutReadCloser -type readTimeout struct { - duration time.Duration -} - -// ID returns the id of the middleware -func (*readTimeout) ID() string { - return "ReadResponseTimeout" -} - -// HandleDeserialize implements the DeserializeMiddleware interface -func (m *readTimeout) 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 - } - - response, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)} - } - - response.Body = &timeoutReadCloser{ - reader: response.Body, - duration: m.duration, - } - out.RawResponse = response - - return out, metadata, err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/types.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/types.go deleted file mode 100644 index cc3ae811..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/types.go +++ /dev/null @@ -1,42 +0,0 @@ -package aws - -import ( - "fmt" -) - -// Ternary is an enum allowing an unknown or none state in addition to a bool's -// true and false. -type Ternary int - -func (t Ternary) String() string { - switch t { - case UnknownTernary: - return "unknown" - case FalseTernary: - return "false" - case TrueTernary: - return "true" - default: - return fmt.Sprintf("unknown value, %d", int(t)) - } -} - -// Bool returns true if the value is TrueTernary, false otherwise. -func (t Ternary) Bool() bool { - return t == TrueTernary -} - -// Enumerations for the values of the Ternary type. -const ( - UnknownTernary Ternary = iota - FalseTernary - TrueTernary -) - -// BoolTernary returns a true or false Ternary value for the bool provided. -func BoolTernary(v bool) Ternary { - if v { - return TrueTernary - } - return FalseTernary -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/aws/version.go b/vendor/github.com/aws/aws-sdk-go-v2/aws/version.go deleted file mode 100644 index 5f729d45..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/aws/version.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package aws provides core functionality for making requests to AWS services. -package aws - -// SDKName is the name of this AWS SDK -const SDKName = "aws-sdk-go-v2" - -// SDKVersion is the version of this SDK -const SDKVersion = goModuleVersion 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 deleted file mode 100644 index 52437367..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/CHANGELOG.md +++ /dev/null @@ -1,558 +0,0 @@ -# v1.26.5 (2024-01-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.26.4 (2024-01-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.26.3 (2024-01-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.26.2 (2023-12-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.26.1 (2023-12-08) - -* **Bug Fix**: Correct loading of [services *] sections into shared config. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.26.0 (2023-12-07) - -* **Feature**: Support modeled request compression. The only algorithm supported at this time is `gzip`. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.12 (2023-12-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.11 (2023-12-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.10 (2023-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.9 (2023-11-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.8 (2023-11-28.3) - -* **Bug Fix**: Correct resolution of S3Express auth disable toggle. - -# v1.25.7 (2023-11-28.2) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.6 (2023-11-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.5 (2023-11-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.4 (2023-11-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.3 (2023-11-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.2 (2023-11-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.1 (2023-11-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.0 (2023-11-14) - -* **Feature**: Add support for dynamic auth token from file and EKS container host in absolute/relative URIs in the HTTP credential provider. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.24.0 (2023-11-13) - -* **Feature**: Replace the legacy config parser with a modern, less-strict implementation. Parsing failures within a section will now simply ignore the invalid line rather than silently drop the entire section. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.23.0 (2023-11-09.2) - -* **Feature**: BREAKFIX: In order to support subproperty parsing, invalid property definitions must not be ignored -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.22.3 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.22.2 (2023-11-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.22.1 (2023-11-06) - -* No change notes available for this release. - -# v1.22.0 (2023-11-02) - -* **Feature**: Add env and shared config settings for disabling IMDSv1 fallback. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.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.20.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.19.1 (2023-10-24) - -* No change notes available for this release. - -# v1.19.0 (2023-10-16) - -* **Feature**: Modify logic of retrieving user agent appID from env config - -# v1.18.45 (2023-10-12) - -* **Bug Fix**: Fail to load config if an explicitly provided profile doesn't exist. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.44 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.43 (2023-10-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.42 (2023-09-22) - -* **Bug Fix**: Fixed a bug where merging `max_attempts` or `duration_seconds` fields across shared config files with invalid values would silently default them to 0. -* **Bug Fix**: Move type assertion of config values out of the parsing stage, which resolves an issue where the contents of a profile would silently be dropped with certain numeric formats. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.41 (2023-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.40 (2023-09-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.39 (2023-09-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.38 (2023-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.37 (2023-08-23) - -* No change notes available for this release. - -# v1.18.36 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.35 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.34 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.33 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.32 (2023-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.31 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.30 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.29 (2023-07-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.28 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.27 (2023-06-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.26 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.25 (2023-05-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.24 (2023-05-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.23 (2023-05-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.22 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.21 (2023-04-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.20 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.19 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.18 (2023-03-16) - -* **Bug Fix**: Allow RoleARN to be set as functional option on STS WebIdentityRoleOptions. Fixes aws/aws-sdk-go-v2#2015. - -# v1.18.17 (2023-03-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.16 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.15 (2023-02-22) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.14 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.13 (2023-02-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.12 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.11 (2023-02-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.10 (2023-01-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.9 (2023-01-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.8 (2023-01-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.7 (2022-12-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.6 (2022-12-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.5 (2022-12-15) - -* **Bug Fix**: Unify logic between shared config and in finding home directory -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.4 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.3 (2022-11-22) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.2 (2022-11-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.1 (2022-11-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.0 (2022-11-11) - -* **Announcement**: When using the SSOTokenProvider, a previous implementation incorrectly compensated for invalid SSOTokenProvider configurations in the shared profile. This has been fixed via PR #1903 and tracked in issue #1846 -* **Feature**: Adds token refresh support (via SSOTokenProvider) when using the SSOCredentialProvider -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.11 (2022-11-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.10 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.9 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.8 (2022-09-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.7 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.6 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.5 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.4 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.3 (2022-08-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.2 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.1 (2022-08-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.0 (2022-08-14) - -* **Feature**: Add alternative mechanism for determning the users `$HOME` or `%USERPROFILE%` location when the environment variables are not present. - -# v1.16.1 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.0 (2022-08-10) - -* **Feature**: Adds support for the following settings in the `~/.aws/credentials` file: `sso_account_id`, `sso_region`, `sso_role_name`, `sso_start_url`, and `ca_bundle`. - -# v1.15.17 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.16 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.15 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.14 (2022-07-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.13 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.12 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.11 (2022-06-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.10 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.9 (2022-05-26) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.8 (2022-05-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.7 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.6 (2022-05-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.5 (2022-05-09) - -* **Bug Fix**: Fixes a bug in LoadDefaultConfig to correctly assign ConfigSources so all config resolvers have access to the config sources. This fixes the feature/ec2/imds client not having configuration applied via config.LoadOptions such as EC2IMDSClientEnableState. PR [#1682](https://github.com/aws/aws-sdk-go-v2/pull/1682) - -# v1.15.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.0 (2022-02-24) - -* **Feature**: Adds support for loading RetryMaxAttempts and RetryMod from the environment and shared configuration files. These parameters drive how the SDK's API client will initialize its default retryer, if custome retryer has not been specified. See [config](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/config) module and [aws.Config](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws#Config) for more information about and how to use these new options. -* **Feature**: Adds support for the `ca_bundle` parameter in shared config and credentials files. The usage of the file is the same as environment variable, `AWS_CA_BUNDLE`, but sourced from shared config. Fixes [#1589](https://github.com/aws/aws-sdk-go-v2/issues/1589) -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.1 (2022-01-28) - -* **Bug Fix**: Fixes LoadDefaultConfig handling of errors returned by passed in functional options. Previously errors returned from the LoadOptions passed into LoadDefaultConfig were incorrectly ignored. [#1562](https://github.com/aws/aws-sdk-go-v2/pull/1562). Thanks to [Pinglei Guo](https://github.com/pingleig) for submitting this PR. -* **Bug Fix**: Fixes the SDK's handling of `duration_sections` in the shared credentials file or specified in multiple shared config and shared credentials files under the same profile. [#1568](https://github.com/aws/aws-sdk-go-v2/pull/1568). Thanks to [Amir Szekely](https://github.com/kichik) for help reproduce this bug. -* **Bug Fix**: Updates `config` module to use os.UserHomeDir instead of hard coded environment variable for OS. [#1563](https://github.com/aws/aws-sdk-go-v2/pull/1563) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2022-01-07) - -* **Feature**: Add load option for CredentialCache. Adds a new member to the LoadOptions struct, CredentialsCacheOptions. This member allows specifying a function that will be used to configure the CredentialsCache. The CredentialsCacheOptions will only be used if the configuration loader will wrap the underlying credential provider in the CredentialsCache. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.1 (2021-12-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2021-12-02) - -* **Feature**: Add support for specifying `EndpointResolverWithOptions` on `LoadOptions`, and associated `WithEndpointResolverWithOptions`. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.3 (2021-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.2 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.1 (2021-11-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.3 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.2 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.1 (2021-09-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2021-09-02) - -* **Feature**: Add support for S3 Multi-Region Access Point ARNs. - -# v1.7.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.1 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-08-04) - -* **Feature**: adds error handling for defered close calls -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-07-15) - -* **Feature**: Support has been added for EC2 IPv6-enabled Instance Metadata Service Endpoints. -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.1 (2021-07-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-06-25) - -* **Feature**: Adds configuration setting for enabling endpoint discovery. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-05-20) - -* **Feature**: SSO credentials can now be defined alongside other credential providers within the same configuration profile. -* **Bug Fix**: Profile names were incorrectly normalized to lower-case, which could result in unexpected profile configurations. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/config/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/config/config.go b/vendor/github.com/aws/aws-sdk-go-v2/config/config.go deleted file mode 100644 index 50582d89..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/config.go +++ /dev/null @@ -1,219 +0,0 @@ -package config - -import ( - "context" - "os" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// defaultAWSConfigResolvers are a slice of functions that will resolve external -// configuration values into AWS configuration values. -// -// This will setup the AWS configuration's Region, -var defaultAWSConfigResolvers = []awsConfigResolver{ - // Resolves the default configuration the SDK's aws.Config will be - // initialized with. - resolveDefaultAWSConfig, - - // Sets the logger to be used. Could be user provided logger, and client - // logging mode. - resolveLogger, - resolveClientLogMode, - - // Sets the HTTP client and configuration to use for making requests using - // the HTTP transport. - resolveHTTPClient, - resolveCustomCABundle, - - // Sets the endpoint resolving behavior the API Clients will use for making - // requests to. Clients default to their own clients this allows overrides - // to be specified. The resolveEndpointResolver option is deprecated, but - // we still need to set it for backwards compatibility on config - // construction. - resolveEndpointResolver, - resolveEndpointResolverWithOptions, - - // Sets the retry behavior API clients will use within their retry attempt - // middleware. Defaults to unset, allowing API clients to define their own - // retry behavior. - resolveRetryer, - - // Sets the region the API Clients should use for making requests to. - resolveRegion, - resolveEC2IMDSRegion, - resolveDefaultRegion, - - // Sets the additional set of middleware stack mutators that will custom - // API client request pipeline middleware. - resolveAPIOptions, - - // Resolves the DefaultsMode that should be used by SDK clients. If this - // mode is set to DefaultsModeAuto. - // - // Comes after HTTPClient and CustomCABundle to ensure the HTTP client is - // configured if provided before invoking IMDS if mode is auto. Comes - // before resolving credentials so that those subsequent clients use the - // configured auto mode. - resolveDefaultsModeOptions, - - // Sets the resolved credentials the API clients will use for - // authentication. Provides the SDK's default credential chain. - // - // Should probably be the last step in the resolve chain to ensure that all - // other configurations are resolved first in case downstream credentials - // implementations depend on or can be configured with earlier resolved - // configuration options. - resolveCredentials, - - // Sets the resolved bearer authentication token API clients will use for - // httpBearerAuth authentication scheme. - resolveBearerAuthToken, - - // Sets the sdk app ID if present in env var or shared config profile - resolveAppID, - - resolveBaseEndpoint, - - // Sets the DisableRequestCompression if present in env var or shared config profile - resolveDisableRequestCompression, - - // Sets the RequestMinCompressSizeBytes if present in env var or shared config profile - resolveRequestMinCompressSizeBytes, -} - -// A Config represents a generic configuration value or set of values. This type -// will be used by the AWSConfigResolvers to extract -// -// General the Config type will use type assertion against the Provider interfaces -// to extract specific data from the Config. -type Config interface{} - -// A loader is used to load external configuration data and returns it as -// a generic Config type. -// -// The loader should return an error if it fails to load the external configuration -// or the configuration data is malformed, or required components missing. -type loader func(context.Context, configs) (Config, error) - -// An awsConfigResolver will extract configuration data from the configs slice -// using the provider interfaces to extract specific functionality. The extracted -// configuration values will be written to the AWS Config value. -// -// The resolver should return an error if it it fails to extract the data, the -// data is malformed, or incomplete. -type awsConfigResolver func(ctx context.Context, cfg *aws.Config, configs configs) error - -// configs is a slice of Config values. These values will be used by the -// AWSConfigResolvers to extract external configuration values to populate the -// AWS Config type. -// -// Use AppendFromLoaders to add additional external Config values that are -// loaded from external sources. -// -// Use ResolveAWSConfig after external Config values have been added or loaded -// to extract the loaded configuration values into the AWS Config. -type configs []Config - -// AppendFromLoaders iterates over the slice of loaders passed in calling each -// loader function in order. The external config value returned by the loader -// will be added to the returned configs slice. -// -// If a loader returns an error this method will stop iterating and return -// that error. -func (cs configs) AppendFromLoaders(ctx context.Context, loaders []loader) (configs, error) { - for _, fn := range loaders { - cfg, err := fn(ctx, cs) - if err != nil { - return nil, err - } - - cs = append(cs, cfg) - } - - return cs, nil -} - -// ResolveAWSConfig returns a AWS configuration populated with values by calling -// the resolvers slice passed in. Each resolver is called in order. Any resolver -// may overwrite the AWS Configuration value of a previous resolver. -// -// If an resolver returns an error this method will return that error, and stop -// iterating over the resolvers. -func (cs configs) ResolveAWSConfig(ctx context.Context, resolvers []awsConfigResolver) (aws.Config, error) { - var cfg aws.Config - - for _, fn := range resolvers { - if err := fn(ctx, &cfg, cs); err != nil { - return aws.Config{}, err - } - } - - return cfg, nil -} - -// ResolveConfig calls the provide function passing slice of configuration sources. -// This implements the aws.ConfigResolver interface. -func (cs configs) ResolveConfig(f func(configs []interface{}) error) error { - var cfgs []interface{} - for i := range cs { - cfgs = append(cfgs, cs[i]) - } - return f(cfgs) -} - -// LoadDefaultConfig reads the SDK's default external configurations, and -// populates an AWS Config with the values from the external configurations. -// -// An optional variadic set of additional Config values can be provided as input -// that will be prepended to the configs slice. Use this to add custom configuration. -// The custom configurations must satisfy the respective providers for their data -// or the custom data will be ignored by the resolvers and config loaders. -// -// cfg, err := config.LoadDefaultConfig( context.TODO(), -// config.WithSharedConfigProfile("test-profile"), -// ) -// if err != nil { -// panic(fmt.Sprintf("failed loading config, %v", err)) -// } -// -// The default configuration sources are: -// * Environment Variables -// * Shared Configuration and Shared Credentials files. -func LoadDefaultConfig(ctx context.Context, optFns ...func(*LoadOptions) error) (cfg aws.Config, err error) { - var options LoadOptions - for _, optFn := range optFns { - if err := optFn(&options); err != nil { - return aws.Config{}, err - } - } - - // assign Load Options to configs - var cfgCpy = configs{options} - - cfgCpy, err = cfgCpy.AppendFromLoaders(ctx, resolveConfigLoaders(&options)) - if err != nil { - return aws.Config{}, err - } - - cfg, err = cfgCpy.ResolveAWSConfig(ctx, defaultAWSConfigResolvers) - if err != nil { - return aws.Config{}, err - } - - return cfg, nil -} - -func resolveConfigLoaders(options *LoadOptions) []loader { - loaders := make([]loader, 2) - loaders[0] = loadEnvConfig - - // specification of a profile should cause a load failure if it doesn't exist - if os.Getenv(awsProfileEnvVar) != "" || options.SharedConfigProfile != "" { - loaders[1] = loadSharedConfig - } else { - loaders[1] = loadSharedConfigIgnoreNotExist - } - - return loaders -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/defaultsmode.go b/vendor/github.com/aws/aws-sdk-go-v2/config/defaultsmode.go deleted file mode 100644 index 20b66367..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/defaultsmode.go +++ /dev/null @@ -1,47 +0,0 @@ -package config - -import ( - "context" - "os" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" -) - -const execEnvVar = "AWS_EXECUTION_ENV" - -// DefaultsModeOptions is the set of options that are used to configure -type DefaultsModeOptions struct { - // The SDK configuration defaults mode. Defaults to legacy if not specified. - // - // Supported modes are: auto, cross-region, in-region, legacy, mobile, standard - Mode aws.DefaultsMode - - // The EC2 Instance Metadata Client that should be used when performing environment - // discovery when aws.DefaultsModeAuto is set. - // - // If not specified the SDK will construct a client if the instance metadata service has not been disabled by - // the AWS_EC2_METADATA_DISABLED environment variable. - IMDSClient *imds.Client -} - -func resolveDefaultsModeRuntimeEnvironment(ctx context.Context, envConfig *EnvConfig, client *imds.Client) (aws.RuntimeEnvironment, error) { - getRegionOutput, err := client.GetRegion(ctx, &imds.GetRegionInput{}) - // honor context timeouts, but if we couldn't talk to IMDS don't fail runtime environment introspection. - select { - case <-ctx.Done(): - return aws.RuntimeEnvironment{}, err - default: - } - - var imdsRegion string - if err == nil { - imdsRegion = getRegionOutput.Region - } - - return aws.RuntimeEnvironment{ - EnvironmentIdentifier: aws.ExecutionEnvironmentID(os.Getenv(execEnvVar)), - Region: envConfig.Region, - EC2InstanceMetadataRegion: imdsRegion, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/config/doc.go deleted file mode 100644 index aab7164e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/doc.go +++ /dev/null @@ -1,20 +0,0 @@ -// Package config provides utilities for loading configuration from multiple -// sources that can be used to configure the SDK's API clients, and utilities. -// -// The config package will load configuration from environment variables, AWS -// shared configuration file (~/.aws/config), and AWS shared credentials file -// (~/.aws/credentials). -// -// Use the LoadDefaultConfig to load configuration from all the SDK's supported -// sources, and resolve credentials using the SDK's default credential chain. -// -// LoadDefaultConfig allows for a variadic list of additional Config sources that can -// provide one or more configuration values which can be used to programmatically control the resolution -// of a specific value, or allow for broader range of additional configuration sources not supported by the SDK. -// A Config source implements one or more provider interfaces defined in this package. Config sources passed in will -// take precedence over the default environment and shared config sources used by the SDK. If one or more Config sources -// implement the same provider interface, priority will be handled by the order in which the sources were passed in. -// -// A number of helpers (prefixed by “With“) are provided in this package that implement their respective provider -// interface. These helpers should be used for overriding configuration programmatically at runtime. -package config 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 deleted file mode 100644 index 88550198..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/env_config.go +++ /dev/null @@ -1,819 +0,0 @@ -package config - -import ( - "bytes" - "context" - "fmt" - "io" - "io/ioutil" - "os" - "strconv" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" - smithyrequestcompression "github.com/aws/smithy-go/private/requestcompression" -) - -// CredentialsSourceName provides a name of the provider when config is -// loaded from environment. -const CredentialsSourceName = "EnvConfigCredentials" - -// Environment variables that will be read for configuration values. -const ( - awsAccessKeyIDEnvVar = "AWS_ACCESS_KEY_ID" - awsAccessKeyEnvVar = "AWS_ACCESS_KEY" - - awsSecretAccessKeyEnvVar = "AWS_SECRET_ACCESS_KEY" - awsSecretKeyEnvVar = "AWS_SECRET_KEY" - - awsSessionTokenEnvVar = "AWS_SESSION_TOKEN" - - awsContainerCredentialsEndpointEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" - awsContainerCredentialsRelativePathEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" - awsContainerPProviderAuthorizationEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN" - - awsRegionEnvVar = "AWS_REGION" - awsDefaultRegionEnvVar = "AWS_DEFAULT_REGION" - - awsProfileEnvVar = "AWS_PROFILE" - awsDefaultProfileEnvVar = "AWS_DEFAULT_PROFILE" - - awsSharedCredentialsFileEnvVar = "AWS_SHARED_CREDENTIALS_FILE" - - awsConfigFileEnvVar = "AWS_CONFIG_FILE" - - awsCustomCABundleEnvVar = "AWS_CA_BUNDLE" - - awsWebIdentityTokenFilePathEnvVar = "AWS_WEB_IDENTITY_TOKEN_FILE" - - awsRoleARNEnvVar = "AWS_ROLE_ARN" - awsRoleSessionNameEnvVar = "AWS_ROLE_SESSION_NAME" - - awsEnableEndpointDiscoveryEnvVar = "AWS_ENABLE_ENDPOINT_DISCOVERY" - - awsS3UseARNRegionEnvVar = "AWS_S3_USE_ARN_REGION" - - awsEc2MetadataServiceEndpointModeEnvVar = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE" - - awsEc2MetadataServiceEndpointEnvVar = "AWS_EC2_METADATA_SERVICE_ENDPOINT" - - awsEc2MetadataDisabled = "AWS_EC2_METADATA_DISABLED" - awsEc2MetadataV1DisabledEnvVar = "AWS_EC2_METADATA_V1_DISABLED" - - awsS3DisableMultiRegionAccessPointEnvVar = "AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS" - - awsUseDualStackEndpoint = "AWS_USE_DUALSTACK_ENDPOINT" - - awsUseFIPSEndpoint = "AWS_USE_FIPS_ENDPOINT" - - awsDefaultMode = "AWS_DEFAULTS_MODE" - - awsRetryMaxAttempts = "AWS_MAX_ATTEMPTS" - awsRetryMode = "AWS_RETRY_MODE" - awsSdkAppID = "AWS_SDK_UA_APP_ID" - - awsIgnoreConfiguredEndpoints = "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS" - awsEndpointURL = "AWS_ENDPOINT_URL" - - awsDisableRequestCompression = "AWS_DISABLE_REQUEST_COMPRESSION" - awsRequestMinCompressionSizeBytes = "AWS_REQUEST_MIN_COMPRESSION_SIZE_BYTES" - - awsS3DisableExpressSessionAuthEnv = "AWS_S3_DISABLE_EXPRESS_SESSION_AUTH" -) - -var ( - credAccessEnvKeys = []string{ - awsAccessKeyIDEnvVar, - awsAccessKeyEnvVar, - } - credSecretEnvKeys = []string{ - awsSecretAccessKeyEnvVar, - awsSecretKeyEnvVar, - } - regionEnvKeys = []string{ - awsRegionEnvVar, - awsDefaultRegionEnvVar, - } - profileEnvKeys = []string{ - awsProfileEnvVar, - awsDefaultProfileEnvVar, - } -) - -// EnvConfig is a collection of environment values the SDK will read -// setup config from. All environment values are optional. But some values -// such as credentials require multiple values to be complete or the values -// will be ignored. -type EnvConfig struct { - // Environment configuration values. If set both Access Key ID and Secret Access - // Key must be provided. Session Token and optionally also be provided, but is - // not required. - // - // # Access Key ID - // AWS_ACCESS_KEY_ID=AKID - // AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set. - // - // # Secret Access Key - // AWS_SECRET_ACCESS_KEY=SECRET - // AWS_SECRET_KEY=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. - // - // # Session Token - // AWS_SESSION_TOKEN=TOKEN - Credentials aws.Credentials - - // ContainerCredentialsEndpoint value is the HTTP enabled endpoint to retrieve credentials - // using the endpointcreds.Provider - ContainerCredentialsEndpoint string - - // ContainerCredentialsRelativePath is the relative URI path that will be used when attempting to retrieve - // credentials from the container endpoint. - ContainerCredentialsRelativePath string - - // ContainerAuthorizationToken is the authorization token that will be included in the HTTP Authorization - // header when attempting to retrieve credentials from the container credentials endpoint. - ContainerAuthorizationToken string - - // Region value will instruct the SDK where to make service API requests to. If is - // not provided in the environment the region must be provided before a service - // client request is made. - // - // AWS_REGION=us-west-2 - // AWS_DEFAULT_REGION=us-west-2 - Region string - - // Profile name the SDK should load use when loading shared configuration from the - // shared configuration files. If not provided "default" will be used as the - // profile name. - // - // AWS_PROFILE=my_profile - // AWS_DEFAULT_PROFILE=my_profile - SharedConfigProfile string - - // Shared credentials file path can be set to instruct the SDK to use an alternate - // file for the shared credentials. If not set the file will be loaded from - // $HOME/.aws/credentials on Linux/Unix based systems, and - // %USERPROFILE%\.aws\credentials on Windows. - // - // AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials - SharedCredentialsFile string - - // Shared config file path can be set to instruct the SDK to use an alternate - // file for the shared config. If not set the file will be loaded from - // $HOME/.aws/config on Linux/Unix based systems, and - // %USERPROFILE%\.aws\config on Windows. - // - // AWS_CONFIG_FILE=$HOME/my_shared_config - SharedConfigFile string - - // Sets the path to a custom Credentials Authority (CA) Bundle PEM file - // that the SDK will use instead of the system's root CA bundle. - // Only use this if you want to configure the SDK to use a custom set - // of CAs. - // - // Enabling this option will attempt to merge the Transport - // into the SDK's HTTP client. If the client's Transport is - // not a http.Transport an error will be returned. If the - // Transport's TLS config is set this option will cause the - // SDK to overwrite the Transport's TLS config's RootCAs value. - // - // Setting a custom HTTPClient in the aws.Config options will override this setting. - // To use this option and custom HTTP client, the HTTP client needs to be provided - // when creating the config. Not the service client. - // - // AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle - CustomCABundle string - - // Enables endpoint discovery via environment variables. - // - // AWS_ENABLE_ENDPOINT_DISCOVERY=true - EnableEndpointDiscovery aws.EndpointDiscoveryEnableState - - // Specifies the WebIdentity token the SDK should use to assume a role - // with. - // - // AWS_WEB_IDENTITY_TOKEN_FILE=file_path - WebIdentityTokenFilePath string - - // Specifies the IAM role arn to use when assuming an role. - // - // AWS_ROLE_ARN=role_arn - RoleARN string - - // Specifies the IAM role session name to use when assuming a role. - // - // AWS_ROLE_SESSION_NAME=session_name - RoleSessionName string - - // Specifies if the S3 service should allow ARNs to direct the region - // the client's requests are sent to. - // - // AWS_S3_USE_ARN_REGION=true - S3UseARNRegion *bool - - // Specifies if the EC2 IMDS service client is enabled. - // - // AWS_EC2_METADATA_DISABLED=true - EC2IMDSClientEnableState imds.ClientEnableState - - // Specifies if EC2 IMDSv1 fallback is disabled. - // - // AWS_EC2_METADATA_V1_DISABLED=true - EC2IMDSv1Disabled *bool - - // Specifies the EC2 Instance Metadata Service default endpoint selection mode (IPv4 or IPv6) - // - // AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE=IPv6 - EC2IMDSEndpointMode imds.EndpointModeState - - // Specifies the EC2 Instance Metadata Service endpoint to use. If specified it overrides EC2IMDSEndpointMode. - // - // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://fd00:ec2::254 - EC2IMDSEndpoint string - - // Specifies if the S3 service should disable multi-region access points - // support. - // - // AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS=true - S3DisableMultiRegionAccessPoints *bool - - // Specifies that SDK clients must resolve a dual-stack endpoint for - // services. - // - // AWS_USE_DUALSTACK_ENDPOINT=true - UseDualStackEndpoint aws.DualStackEndpointState - - // Specifies that SDK clients must resolve a FIPS endpoint for - // services. - // - // AWS_USE_FIPS_ENDPOINT=true - UseFIPSEndpoint aws.FIPSEndpointState - - // Specifies the SDK Defaults Mode used by services. - // - // AWS_DEFAULTS_MODE=standard - DefaultsMode aws.DefaultsMode - - // Specifies the maximum number attempts an API client will call an - // operation that fails with a retryable error. - // - // AWS_MAX_ATTEMPTS=3 - RetryMaxAttempts int - - // Specifies the retry model the API client will be created with. - // - // aws_retry_mode=standard - RetryMode aws.RetryMode - - // aws sdk app ID that can be added to user agent header string - AppID string - - // Flag used to disable configured endpoints. - IgnoreConfiguredEndpoints *bool - - // Value to contain configured endpoints to be propagated to - // corresponding endpoint resolution field. - BaseEndpoint string - - // determine if request compression is allowed, default to false - // retrieved from env var AWS_DISABLE_REQUEST_COMPRESSION - DisableRequestCompression *bool - - // inclusive threshold request body size to trigger compression, - // default to 10240 and must be within 0 and 10485760 bytes inclusive - // retrieved from env var AWS_REQUEST_MIN_COMPRESSION_SIZE_BYTES - RequestMinCompressSizeBytes *int64 - - // Whether S3Express auth is disabled. - // - // This will NOT prevent requests from being made to S3Express buckets, it - // will only bypass the modified endpoint routing and signing behaviors - // associated with the feature. - S3DisableExpressAuth *bool -} - -// loadEnvConfig reads configuration values from the OS's environment variables. -// Returning the a Config typed EnvConfig to satisfy the ConfigLoader func type. -func loadEnvConfig(ctx context.Context, cfgs configs) (Config, error) { - return NewEnvConfig() -} - -// NewEnvConfig retrieves the SDK's environment configuration. -// See `EnvConfig` for the values that will be retrieved. -func NewEnvConfig() (EnvConfig, error) { - var cfg EnvConfig - - creds := aws.Credentials{ - Source: CredentialsSourceName, - } - setStringFromEnvVal(&creds.AccessKeyID, credAccessEnvKeys) - setStringFromEnvVal(&creds.SecretAccessKey, credSecretEnvKeys) - if creds.HasKeys() { - creds.SessionToken = os.Getenv(awsSessionTokenEnvVar) - cfg.Credentials = creds - } - - cfg.ContainerCredentialsEndpoint = os.Getenv(awsContainerCredentialsEndpointEnvVar) - cfg.ContainerCredentialsRelativePath = os.Getenv(awsContainerCredentialsRelativePathEnvVar) - cfg.ContainerAuthorizationToken = os.Getenv(awsContainerPProviderAuthorizationEnvVar) - - setStringFromEnvVal(&cfg.Region, regionEnvKeys) - setStringFromEnvVal(&cfg.SharedConfigProfile, profileEnvKeys) - - cfg.SharedCredentialsFile = os.Getenv(awsSharedCredentialsFileEnvVar) - cfg.SharedConfigFile = os.Getenv(awsConfigFileEnvVar) - - cfg.CustomCABundle = os.Getenv(awsCustomCABundleEnvVar) - - cfg.WebIdentityTokenFilePath = os.Getenv(awsWebIdentityTokenFilePathEnvVar) - - cfg.RoleARN = os.Getenv(awsRoleARNEnvVar) - cfg.RoleSessionName = os.Getenv(awsRoleSessionNameEnvVar) - - cfg.AppID = os.Getenv(awsSdkAppID) - - if err := setBoolPtrFromEnvVal(&cfg.DisableRequestCompression, []string{awsDisableRequestCompression}); err != nil { - return cfg, err - } - if err := setInt64PtrFromEnvVal(&cfg.RequestMinCompressSizeBytes, []string{awsRequestMinCompressionSizeBytes}, smithyrequestcompression.MaxRequestMinCompressSizeBytes); err != nil { - return cfg, err - } - - if err := setEndpointDiscoveryTypeFromEnvVal(&cfg.EnableEndpointDiscovery, []string{awsEnableEndpointDiscoveryEnvVar}); err != nil { - return cfg, err - } - - if err := setBoolPtrFromEnvVal(&cfg.S3UseARNRegion, []string{awsS3UseARNRegionEnvVar}); err != nil { - return cfg, err - } - - setEC2IMDSClientEnableState(&cfg.EC2IMDSClientEnableState, []string{awsEc2MetadataDisabled}) - if err := setEC2IMDSEndpointMode(&cfg.EC2IMDSEndpointMode, []string{awsEc2MetadataServiceEndpointModeEnvVar}); err != nil { - return cfg, err - } - cfg.EC2IMDSEndpoint = os.Getenv(awsEc2MetadataServiceEndpointEnvVar) - if err := setBoolPtrFromEnvVal(&cfg.EC2IMDSv1Disabled, []string{awsEc2MetadataV1DisabledEnvVar}); err != nil { - return cfg, err - } - - if err := setBoolPtrFromEnvVal(&cfg.S3DisableMultiRegionAccessPoints, []string{awsS3DisableMultiRegionAccessPointEnvVar}); err != nil { - return cfg, err - } - - if err := setUseDualStackEndpointFromEnvVal(&cfg.UseDualStackEndpoint, []string{awsUseDualStackEndpoint}); err != nil { - return cfg, err - } - - if err := setUseFIPSEndpointFromEnvVal(&cfg.UseFIPSEndpoint, []string{awsUseFIPSEndpoint}); err != nil { - return cfg, err - } - - if err := setDefaultsModeFromEnvVal(&cfg.DefaultsMode, []string{awsDefaultMode}); err != nil { - return cfg, err - } - - if err := setIntFromEnvVal(&cfg.RetryMaxAttempts, []string{awsRetryMaxAttempts}); err != nil { - return cfg, err - } - if err := setRetryModeFromEnvVal(&cfg.RetryMode, []string{awsRetryMode}); err != nil { - return cfg, err - } - - setStringFromEnvVal(&cfg.BaseEndpoint, []string{awsEndpointURL}) - - if err := setBoolPtrFromEnvVal(&cfg.IgnoreConfiguredEndpoints, []string{awsIgnoreConfiguredEndpoints}); err != nil { - return cfg, err - } - - if err := setBoolPtrFromEnvVal(&cfg.S3DisableExpressAuth, []string{awsS3DisableExpressSessionAuthEnv}); err != nil { - return cfg, err - } - - return cfg, nil -} - -func (c EnvConfig) getDefaultsMode(ctx context.Context) (aws.DefaultsMode, bool, error) { - if len(c.DefaultsMode) == 0 { - return "", false, nil - } - return c.DefaultsMode, true, nil -} - -func (c EnvConfig) getAppID(context.Context) (string, bool, error) { - return c.AppID, len(c.AppID) > 0, nil -} - -func (c EnvConfig) getDisableRequestCompression(context.Context) (bool, bool, error) { - if c.DisableRequestCompression == nil { - return false, false, nil - } - return *c.DisableRequestCompression, true, nil -} - -func (c EnvConfig) getRequestMinCompressSizeBytes(context.Context) (int64, bool, error) { - if c.RequestMinCompressSizeBytes == nil { - return 0, false, nil - } - return *c.RequestMinCompressSizeBytes, true, 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) { - if c.RetryMaxAttempts == 0 { - return 0, false, nil - } - return c.RetryMaxAttempts, true, nil -} - -// GetRetryMode returns the RetryMode of AWS_RETRY_MODE if was specified, and a -// valid value. -func (c EnvConfig) GetRetryMode(ctx context.Context) (aws.RetryMode, bool, error) { - if len(c.RetryMode) == 0 { - return "", false, nil - } - return c.RetryMode, true, nil -} - -func setEC2IMDSClientEnableState(state *imds.ClientEnableState, keys []string) { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue - } - switch { - case strings.EqualFold(value, "true"): - *state = imds.ClientDisabled - case strings.EqualFold(value, "false"): - *state = imds.ClientEnabled - default: - continue - } - break - } -} - -func setDefaultsModeFromEnvVal(mode *aws.DefaultsMode, keys []string) error { - for _, k := range keys { - if value := os.Getenv(k); len(value) > 0 { - if ok := mode.SetFromString(value); !ok { - return fmt.Errorf("invalid %s value: %s", k, value) - } - break - } - } - return nil -} - -func setRetryModeFromEnvVal(mode *aws.RetryMode, keys []string) (err error) { - for _, k := range keys { - if value := os.Getenv(k); len(value) > 0 { - *mode, err = aws.ParseRetryMode(value) - if err != nil { - return fmt.Errorf("invalid %s value, %w", k, err) - } - break - } - } - return nil -} - -func setEC2IMDSEndpointMode(mode *imds.EndpointModeState, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue - } - if err := mode.SetFromString(value); err != nil { - return fmt.Errorf("invalid value for environment variable, %s=%s, %v", k, value, err) - } - } - 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) { - if len(c.Region) == 0 { - return "", false, nil - } - return c.Region, true, nil -} - -// GetSharedConfigProfile returns the shared config profile if set in the -// environment. Returns an empty string if not set. -func (c EnvConfig) getSharedConfigProfile(ctx context.Context) (string, bool, error) { - if len(c.SharedConfigProfile) == 0 { - return "", false, nil - } - - return c.SharedConfigProfile, true, nil -} - -// getSharedConfigFiles returns a slice of filenames set in the environment. -// -// Will return the filenames in the order of: -// * Shared Config -func (c EnvConfig) getSharedConfigFiles(context.Context) ([]string, bool, error) { - var files []string - if v := c.SharedConfigFile; len(v) > 0 { - files = append(files, v) - } - - if len(files) == 0 { - return nil, false, nil - } - return files, true, nil -} - -// getSharedCredentialsFiles returns a slice of filenames set in the environment. -// -// Will return the filenames in the order of: -// * Shared Credentials -func (c EnvConfig) getSharedCredentialsFiles(context.Context) ([]string, bool, error) { - var files []string - if v := c.SharedCredentialsFile; len(v) > 0 { - files = append(files, v) - } - if len(files) == 0 { - return nil, false, nil - } - return files, true, nil -} - -// GetCustomCABundle returns the custom CA bundle's PEM bytes if the file was -func (c EnvConfig) getCustomCABundle(context.Context) (io.Reader, bool, error) { - if len(c.CustomCABundle) == 0 { - return nil, false, nil - } - - b, err := ioutil.ReadFile(c.CustomCABundle) - if err != nil { - return nil, false, err - } - return bytes.NewReader(b), true, nil -} - -// GetIgnoreConfiguredEndpoints is used in knowing when to disable configured -// endpoints feature. -func (c EnvConfig) GetIgnoreConfiguredEndpoints(context.Context) (bool, bool, error) { - if c.IgnoreConfiguredEndpoints == nil { - return false, false, nil - } - - return *c.IgnoreConfiguredEndpoints, true, nil -} - -func (c EnvConfig) getBaseEndpoint(context.Context) (string, bool, error) { - return c.BaseEndpoint, len(c.BaseEndpoint) > 0, nil -} - -// 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 != "" { - return endpt, true, nil - } - return "", false, nil -} - -func normalizeEnv(sdkID string) string { - upper := strings.ToUpper(sdkID) - return strings.ReplaceAll(upper, " ", "_") -} - -// GetS3UseARNRegion returns whether to allow ARNs to direct the region -// the S3 client's requests are sent to. -func (c EnvConfig) GetS3UseARNRegion(ctx context.Context) (value, ok bool, err error) { - if c.S3UseARNRegion == nil { - return false, false, nil - } - - return *c.S3UseARNRegion, true, nil -} - -// GetS3DisableMultiRegionAccessPoints returns whether to disable multi-region access point -// support for the S3 client. -func (c EnvConfig) GetS3DisableMultiRegionAccessPoints(ctx context.Context) (value, ok bool, err error) { - if c.S3DisableMultiRegionAccessPoints == nil { - return false, false, nil - } - - return *c.S3DisableMultiRegionAccessPoints, true, nil -} - -// GetUseDualStackEndpoint returns whether the service's dual-stack endpoint should be -// used for requests. -func (c EnvConfig) GetUseDualStackEndpoint(ctx context.Context) (value aws.DualStackEndpointState, found bool, err error) { - if c.UseDualStackEndpoint == aws.DualStackEndpointStateUnset { - return aws.DualStackEndpointStateUnset, false, nil - } - - return c.UseDualStackEndpoint, true, nil -} - -// GetUseFIPSEndpoint returns whether the service's FIPS endpoint should be -// used for requests. -func (c EnvConfig) GetUseFIPSEndpoint(ctx context.Context) (value aws.FIPSEndpointState, found bool, err error) { - if c.UseFIPSEndpoint == aws.FIPSEndpointStateUnset { - return aws.FIPSEndpointStateUnset, false, nil - } - - return c.UseFIPSEndpoint, true, nil -} - -func setStringFromEnvVal(dst *string, keys []string) { - for _, k := range keys { - if v := os.Getenv(k); len(v) > 0 { - *dst = v - break - } - } -} - -func setIntFromEnvVal(dst *int, keys []string) error { - for _, k := range keys { - if v := os.Getenv(k); len(v) > 0 { - i, err := strconv.ParseInt(v, 10, 64) - if err != nil { - return fmt.Errorf("invalid value %s=%s, %w", k, v, err) - } - *dst = int(i) - break - } - } - - return nil -} - -func setBoolPtrFromEnvVal(dst **bool, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue - } - - if *dst == nil { - *dst = new(bool) - } - - switch { - case strings.EqualFold(value, "false"): - **dst = false - case strings.EqualFold(value, "true"): - **dst = true - default: - return fmt.Errorf( - "invalid value for environment variable, %s=%s, need true or false", - k, value) - } - break - } - - return nil -} - -func setInt64PtrFromEnvVal(dst **int64, keys []string, max int64) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue - } - - v, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return fmt.Errorf("invalid value for env var, %s=%s, need int64", k, value) - } else if v < 0 || v > max { - return fmt.Errorf("invalid range for env var min request compression size bytes %q, must be within 0 and 10485760 inclusively", v) - } - if *dst == nil { - *dst = new(int64) - } - - **dst = v - break - } - - return nil -} - -func setEndpointDiscoveryTypeFromEnvVal(dst *aws.EndpointDiscoveryEnableState, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue // skip if empty - } - - switch { - case strings.EqualFold(value, endpointDiscoveryDisabled): - *dst = aws.EndpointDiscoveryDisabled - case strings.EqualFold(value, endpointDiscoveryEnabled): - *dst = aws.EndpointDiscoveryEnabled - case strings.EqualFold(value, endpointDiscoveryAuto): - *dst = aws.EndpointDiscoveryAuto - default: - return fmt.Errorf( - "invalid value for environment variable, %s=%s, need true, false or auto", - k, value) - } - } - return nil -} - -func setUseDualStackEndpointFromEnvVal(dst *aws.DualStackEndpointState, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue // skip if empty - } - - switch { - case strings.EqualFold(value, "true"): - *dst = aws.DualStackEndpointStateEnabled - case strings.EqualFold(value, "false"): - *dst = aws.DualStackEndpointStateDisabled - default: - return fmt.Errorf( - "invalid value for environment variable, %s=%s, need true, false", - k, value) - } - } - return nil -} - -func setUseFIPSEndpointFromEnvVal(dst *aws.FIPSEndpointState, keys []string) error { - for _, k := range keys { - value := os.Getenv(k) - if len(value) == 0 { - continue // skip if empty - } - - switch { - case strings.EqualFold(value, "true"): - *dst = aws.FIPSEndpointStateEnabled - case strings.EqualFold(value, "false"): - *dst = aws.FIPSEndpointStateDisabled - default: - return fmt.Errorf( - "invalid value for environment variable, %s=%s, need true, false", - k, value) - } - } - return nil -} - -// GetEnableEndpointDiscovery returns resolved value for EnableEndpointDiscovery env variable setting. -func (c EnvConfig) GetEnableEndpointDiscovery(ctx context.Context) (value aws.EndpointDiscoveryEnableState, found bool, err error) { - if c.EnableEndpointDiscovery == aws.EndpointDiscoveryUnset { - return aws.EndpointDiscoveryUnset, false, nil - } - - return c.EnableEndpointDiscovery, true, nil -} - -// GetEC2IMDSClientEnableState implements a EC2IMDSClientEnableState options resolver interface. -func (c EnvConfig) GetEC2IMDSClientEnableState() (imds.ClientEnableState, bool, error) { - if c.EC2IMDSClientEnableState == imds.ClientDefaultEnableState { - return imds.ClientDefaultEnableState, false, nil - } - - return c.EC2IMDSClientEnableState, true, nil -} - -// GetEC2IMDSEndpointMode implements a EC2IMDSEndpointMode option resolver interface. -func (c EnvConfig) GetEC2IMDSEndpointMode() (imds.EndpointModeState, bool, error) { - if c.EC2IMDSEndpointMode == imds.EndpointModeStateUnset { - return imds.EndpointModeStateUnset, false, nil - } - - return c.EC2IMDSEndpointMode, true, nil -} - -// GetEC2IMDSEndpoint implements a EC2IMDSEndpoint option resolver interface. -func (c EnvConfig) GetEC2IMDSEndpoint() (string, bool, error) { - if len(c.EC2IMDSEndpoint) == 0 { - return "", false, nil - } - - return c.EC2IMDSEndpoint, true, nil -} - -// GetEC2IMDSV1FallbackDisabled implements an EC2IMDSV1FallbackDisabled option -// resolver interface. -func (c EnvConfig) GetEC2IMDSV1FallbackDisabled() (bool, bool) { - if c.EC2IMDSv1Disabled == nil { - return false, false - } - - return *c.EC2IMDSv1Disabled, true -} - -// GetS3DisableExpressAuth returns the configured value for -// [EnvConfig.S3DisableExpressAuth]. -func (c EnvConfig) GetS3DisableExpressAuth() (value, ok bool) { - if c.S3DisableExpressAuth == nil { - return false, false - } - - return *c.S3DisableExpressAuth, true -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/generate.go b/vendor/github.com/aws/aws-sdk-go-v2/config/generate.go deleted file mode 100644 index 654a7a77..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/generate.go +++ /dev/null @@ -1,4 +0,0 @@ -package config - -//go:generate go run -tags codegen ./codegen -output=provider_assert_test.go -//go:generate gofmt -s -w ./ 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 deleted file mode 100644 index 6fc8acb0..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package config - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.26.5" 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 deleted file mode 100644 index 06596c1b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/load_options.go +++ /dev/null @@ -1,1114 +0,0 @@ -package config - -import ( - "context" - "io" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds" - "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" - smithybearer "github.com/aws/smithy-go/auth/bearer" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" -) - -// LoadOptionsFunc is a type alias for LoadOptions functional option -type LoadOptionsFunc func(*LoadOptions) error - -// LoadOptions are discrete set of options that are valid for loading the -// configuration -type LoadOptions struct { - - // Region is the region to send requests to. - Region string - - // Credentials object to use when signing requests. - Credentials aws.CredentialsProvider - - // Token provider for authentication operations with bearer authentication. - BearerAuthTokenProvider smithybearer.TokenProvider - - // HTTPClient the SDK's API clients will use to invoke HTTP requests. - HTTPClient HTTPClient - - // EndpointResolver that can be used to provide or override an endpoint for - // the given service and region. - // - // See the `aws.EndpointResolver` documentation on usage. - // - // Deprecated: See EndpointResolverWithOptions - EndpointResolver aws.EndpointResolver - - // EndpointResolverWithOptions that can be used to provide or override an - // endpoint for the given service and region. - // - // See the `aws.EndpointResolverWithOptions` documentation on usage. - EndpointResolverWithOptions aws.EndpointResolverWithOptions - - // RetryMaxAttempts specifies the maximum number attempts an API client - // will call an operation that fails with a retryable error. - // - // This value will only be used if Retryer option is nil. - RetryMaxAttempts int - - // RetryMode specifies the retry model the API client will be created with. - // - // This value will only be used if Retryer option is nil. - RetryMode aws.RetryMode - - // Retryer is a function that provides a Retryer implementation. A Retryer - // guides how HTTP requests should be retried in case of recoverable - // failures. - // - // If not nil, RetryMaxAttempts, and RetryMode will be ignored. - Retryer func() aws.Retryer - - // APIOptions provides the set of middleware mutations modify how the API - // client requests will be handled. This is useful for adding additional - // tracing data to a request, or changing behavior of the SDK's client. - APIOptions []func(*middleware.Stack) error - - // Logger writer interface to write logging messages to. - Logger logging.Logger - - // ClientLogMode is used to configure the events that will be sent to the - // configured logger. This can be used to configure the logging of signing, - // retries, request, and responses of the SDK clients. - // - // See the ClientLogMode type documentation for the complete set of logging - // modes and available configuration. - ClientLogMode *aws.ClientLogMode - - // SharedConfigProfile is the profile to be used when loading the SharedConfig - SharedConfigProfile string - - // SharedConfigFiles is the slice of custom shared config files to use when - // loading the SharedConfig. A non-default profile used within config file - // must have name defined with prefix 'profile '. eg [profile xyz] - // indicates a profile with name 'xyz'. To read more on the format of the - // config file, please refer the documentation at - // https://docs.aws.amazon.com/credref/latest/refdocs/file-format.html#file-format-config - // - // If duplicate profiles are provided within the same, or across multiple - // shared config files, the next parsed profile will override only the - // properties that conflict with the previously defined profile. Note that - // if duplicate profiles are provided within the SharedCredentialsFiles and - // SharedConfigFiles, the properties defined in shared credentials file - // take precedence. - SharedConfigFiles []string - - // SharedCredentialsFile is the slice of custom shared credentials files to - // use when loading the SharedConfig. The profile name used within - // credentials file must not prefix 'profile '. eg [xyz] indicates a - // profile with name 'xyz'. Profile declared as [profile xyz] will be - // ignored. To read more on the format of the credentials file, please - // refer the documentation at - // https://docs.aws.amazon.com/credref/latest/refdocs/file-format.html#file-format-creds - // - // If duplicate profiles are provided with a same, or across multiple - // shared credentials files, the next parsed profile will override only - // properties that conflict with the previously defined profile. Note that - // if duplicate profiles are provided within the SharedCredentialsFiles and - // SharedConfigFiles, the properties defined in shared credentials file - // take precedence. - SharedCredentialsFiles []string - - // CustomCABundle is CA bundle PEM bytes reader - CustomCABundle io.Reader - - // DefaultRegion is the fall back region, used if a region was not resolved - // from other sources - DefaultRegion string - - // UseEC2IMDSRegion indicates if SDK should retrieve the region - // from the EC2 Metadata service - UseEC2IMDSRegion *UseEC2IMDSRegion - - // CredentialsCacheOptions is a function for setting the - // aws.CredentialsCacheOptions - CredentialsCacheOptions func(*aws.CredentialsCacheOptions) - - // BearerAuthTokenCacheOptions is a function for setting the smithy-go - // auth/bearer#TokenCacheOptions - BearerAuthTokenCacheOptions func(*smithybearer.TokenCacheOptions) - - // SSOTokenProviderOptions is a function for setting the - // credentials/ssocreds.SSOTokenProviderOptions - SSOTokenProviderOptions func(*ssocreds.SSOTokenProviderOptions) - - // ProcessCredentialOptions is a function for setting - // the processcreds.Options - ProcessCredentialOptions func(*processcreds.Options) - - // EC2RoleCredentialOptions is a function for setting - // the ec2rolecreds.Options - EC2RoleCredentialOptions func(*ec2rolecreds.Options) - - // EndpointCredentialOptions is a function for setting - // the endpointcreds.Options - EndpointCredentialOptions func(*endpointcreds.Options) - - // WebIdentityRoleCredentialOptions is a function for setting - // the stscreds.WebIdentityRoleOptions - WebIdentityRoleCredentialOptions func(*stscreds.WebIdentityRoleOptions) - - // AssumeRoleCredentialOptions is a function for setting the - // stscreds.AssumeRoleOptions - AssumeRoleCredentialOptions func(*stscreds.AssumeRoleOptions) - - // SSOProviderOptions is a function for setting - // the ssocreds.Options - SSOProviderOptions func(options *ssocreds.Options) - - // LogConfigurationWarnings when set to true, enables logging - // configuration warnings - LogConfigurationWarnings *bool - - // S3UseARNRegion specifies if the S3 service should allow ARNs to direct - // the region, the client's requests are sent to. - S3UseARNRegion *bool - - // S3DisableMultiRegionAccessPoints specifies if the S3 service should disable - // the S3 Multi-Region access points feature. - S3DisableMultiRegionAccessPoints *bool - - // EnableEndpointDiscovery specifies if endpoint discovery is enable for - // the client. - EnableEndpointDiscovery aws.EndpointDiscoveryEnableState - - // Specifies if the EC2 IMDS service client is enabled. - // - // AWS_EC2_METADATA_DISABLED=true - EC2IMDSClientEnableState imds.ClientEnableState - - // Specifies the EC2 Instance Metadata Service default endpoint selection - // mode (IPv4 or IPv6) - EC2IMDSEndpointMode imds.EndpointModeState - - // Specifies the EC2 Instance Metadata Service endpoint to use. If - // specified it overrides EC2IMDSEndpointMode. - EC2IMDSEndpoint string - - // Specifies that SDK clients must resolve a dual-stack endpoint for - // services. - UseDualStackEndpoint aws.DualStackEndpointState - - // Specifies that SDK clients must resolve a FIPS endpoint for - // services. - UseFIPSEndpoint aws.FIPSEndpointState - - // Specifies the SDK configuration mode for defaults. - DefaultsModeOptions DefaultsModeOptions - - // The sdk app ID retrieved from env var or shared config to be added to request user agent header - AppID string - - // Specifies whether an operation request could be compressed - DisableRequestCompression *bool - - // The inclusive min bytes of a request body that could be compressed - RequestMinCompressSizeBytes *int64 - - // Whether S3 Express auth is disabled. - S3DisableExpressAuth *bool -} - -func (o LoadOptions) getDefaultsMode(ctx context.Context) (aws.DefaultsMode, bool, error) { - if len(o.DefaultsModeOptions.Mode) == 0 { - return "", false, nil - } - return o.DefaultsModeOptions.Mode, true, nil -} - -// GetRetryMaxAttempts returns the RetryMaxAttempts if specified in the -// LoadOptions and not 0. -func (o LoadOptions) GetRetryMaxAttempts(ctx context.Context) (int, bool, error) { - if o.RetryMaxAttempts == 0 { - return 0, false, nil - } - return o.RetryMaxAttempts, true, nil -} - -// GetRetryMode returns the RetryMode specified in the LoadOptions. -func (o LoadOptions) GetRetryMode(ctx context.Context) (aws.RetryMode, bool, error) { - if len(o.RetryMode) == 0 { - return "", false, nil - } - return o.RetryMode, true, nil -} - -func (o LoadOptions) getDefaultsModeIMDSClient(ctx context.Context) (*imds.Client, bool, error) { - if o.DefaultsModeOptions.IMDSClient == nil { - return nil, false, nil - } - return o.DefaultsModeOptions.IMDSClient, true, nil -} - -// getRegion returns Region from config's LoadOptions -func (o LoadOptions) getRegion(ctx context.Context) (string, bool, error) { - if len(o.Region) == 0 { - return "", false, nil - } - - return o.Region, true, nil -} - -// getAppID returns AppID from config's LoadOptions -func (o LoadOptions) getAppID(ctx context.Context) (string, bool, error) { - return o.AppID, len(o.AppID) > 0, nil -} - -// getDisableRequestCompression returns DisableRequestCompression from config's LoadOptions -func (o LoadOptions) getDisableRequestCompression(ctx context.Context) (bool, bool, error) { - if o.DisableRequestCompression == nil { - return false, false, nil - } - return *o.DisableRequestCompression, true, nil -} - -// getRequestMinCompressSizeBytes returns RequestMinCompressSizeBytes from config's LoadOptions -func (o LoadOptions) getRequestMinCompressSizeBytes(ctx context.Context) (int64, bool, error) { - if o.RequestMinCompressSizeBytes == nil { - return 0, false, nil - } - return *o.RequestMinCompressSizeBytes, true, nil -} - -// WithRegion is a helper function to construct functional options -// that sets Region on config's LoadOptions. Setting the region to -// an empty string, will result in the region value being ignored. -// If multiple WithRegion calls are made, the last call overrides -// the previous call values. -func WithRegion(v string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.Region = v - return nil - } -} - -// WithAppID is a helper function to construct functional options -// that sets AppID on config's LoadOptions. -func WithAppID(ID string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.AppID = ID - return nil - } -} - -// WithDisableRequestCompression is a helper function to construct functional options -// that sets DisableRequestCompression on config's LoadOptions. -func WithDisableRequestCompression(DisableRequestCompression *bool) LoadOptionsFunc { - return func(o *LoadOptions) error { - if DisableRequestCompression == nil { - return nil - } - o.DisableRequestCompression = DisableRequestCompression - return nil - } -} - -// WithRequestMinCompressSizeBytes is a helper function to construct functional options -// that sets RequestMinCompressSizeBytes on config's LoadOptions. -func WithRequestMinCompressSizeBytes(RequestMinCompressSizeBytes *int64) LoadOptionsFunc { - return func(o *LoadOptions) error { - if RequestMinCompressSizeBytes == nil { - return nil - } - o.RequestMinCompressSizeBytes = RequestMinCompressSizeBytes - return nil - } -} - -// getDefaultRegion returns DefaultRegion from config's LoadOptions -func (o LoadOptions) getDefaultRegion(ctx context.Context) (string, bool, error) { - if len(o.DefaultRegion) == 0 { - return "", false, nil - } - - return o.DefaultRegion, true, nil -} - -// WithDefaultRegion is a helper function to construct functional options -// that sets a DefaultRegion on config's LoadOptions. Setting the default -// region to an empty string, will result in the default region value -// being ignored. If multiple WithDefaultRegion calls are made, the last -// call overrides the previous call values. Note that both WithRegion and -// WithEC2IMDSRegion call takes precedence over WithDefaultRegion call -// when resolving region. -func WithDefaultRegion(v string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.DefaultRegion = v - return nil - } -} - -// getSharedConfigProfile returns SharedConfigProfile from config's LoadOptions -func (o LoadOptions) getSharedConfigProfile(ctx context.Context) (string, bool, error) { - if len(o.SharedConfigProfile) == 0 { - return "", false, nil - } - - return o.SharedConfigProfile, true, nil -} - -// WithSharedConfigProfile is a helper function to construct functional options -// that sets SharedConfigProfile on config's LoadOptions. Setting the shared -// config profile to an empty string, will result in the shared config profile -// value being ignored. -// If multiple WithSharedConfigProfile calls are made, the last call overrides -// the previous call values. -func WithSharedConfigProfile(v string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.SharedConfigProfile = v - return nil - } -} - -// getSharedConfigFiles returns SharedConfigFiles set on config's LoadOptions -func (o LoadOptions) getSharedConfigFiles(ctx context.Context) ([]string, bool, error) { - if o.SharedConfigFiles == nil { - return nil, false, nil - } - - return o.SharedConfigFiles, true, nil -} - -// WithSharedConfigFiles is a helper function to construct functional options -// that sets slice of SharedConfigFiles on config's LoadOptions. -// Setting the shared config files to an nil string slice, will result in the -// shared config files value being ignored. -// If multiple WithSharedConfigFiles calls are made, the last call overrides -// the previous call values. -func WithSharedConfigFiles(v []string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.SharedConfigFiles = v - return nil - } -} - -// getSharedCredentialsFiles returns SharedCredentialsFiles set on config's LoadOptions -func (o LoadOptions) getSharedCredentialsFiles(ctx context.Context) ([]string, bool, error) { - if o.SharedCredentialsFiles == nil { - return nil, false, nil - } - - return o.SharedCredentialsFiles, true, nil -} - -// WithSharedCredentialsFiles is a helper function to construct functional options -// that sets slice of SharedCredentialsFiles on config's LoadOptions. -// Setting the shared credentials files to an nil string slice, will result in the -// shared credentials files value being ignored. -// If multiple WithSharedCredentialsFiles calls are made, the last call overrides -// the previous call values. -func WithSharedCredentialsFiles(v []string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.SharedCredentialsFiles = v - return nil - } -} - -// getCustomCABundle returns CustomCABundle from LoadOptions -func (o LoadOptions) getCustomCABundle(ctx context.Context) (io.Reader, bool, error) { - if o.CustomCABundle == nil { - return nil, false, nil - } - - return o.CustomCABundle, true, nil -} - -// WithCustomCABundle is a helper function to construct functional options -// that sets CustomCABundle on config's LoadOptions. Setting the custom CA Bundle -// to nil will result in custom CA Bundle value being ignored. -// If multiple WithCustomCABundle calls are made, the last call overrides the -// previous call values. -func WithCustomCABundle(v io.Reader) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.CustomCABundle = v - return nil - } -} - -// UseEC2IMDSRegion provides a regionProvider that retrieves the region -// from the EC2 Metadata service. -type UseEC2IMDSRegion struct { - // If unset will default to generic EC2 IMDS client. - Client *imds.Client -} - -// getRegion attempts to retrieve the region from EC2 Metadata service. -func (p *UseEC2IMDSRegion) getRegion(ctx context.Context) (string, bool, error) { - if ctx == nil { - ctx = context.Background() - } - - client := p.Client - if client == nil { - client = imds.New(imds.Options{}) - } - - result, err := client.GetRegion(ctx, nil) - if err != nil { - return "", false, err - } - if len(result.Region) != 0 { - return result.Region, true, nil - } - return "", false, nil -} - -// getEC2IMDSRegion returns the value of EC2 IMDS region. -func (o LoadOptions) getEC2IMDSRegion(ctx context.Context) (string, bool, error) { - if o.UseEC2IMDSRegion == nil { - return "", false, nil - } - - return o.UseEC2IMDSRegion.getRegion(ctx) -} - -// WithEC2IMDSRegion is a helper function to construct functional options -// that enables resolving EC2IMDS region. The function takes -// in a UseEC2IMDSRegion functional option, and can be used to set the -// EC2IMDS client which will be used to resolve EC2IMDSRegion. -// If no functional option is provided, an EC2IMDS client is built and used -// by the resolver. If multiple WithEC2IMDSRegion calls are made, the last -// call overrides the previous call values. Note that the WithRegion calls takes -// precedence over WithEC2IMDSRegion when resolving region. -func WithEC2IMDSRegion(fnOpts ...func(o *UseEC2IMDSRegion)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.UseEC2IMDSRegion = &UseEC2IMDSRegion{} - - for _, fn := range fnOpts { - fn(o.UseEC2IMDSRegion) - } - return nil - } -} - -// getCredentialsProvider returns the credentials value -func (o LoadOptions) getCredentialsProvider(ctx context.Context) (aws.CredentialsProvider, bool, error) { - if o.Credentials == nil { - return nil, false, nil - } - - return o.Credentials, true, nil -} - -// WithCredentialsProvider is a helper function to construct functional options -// that sets Credential provider value on config's LoadOptions. If credentials -// provider is set to nil, the credentials provider value will be ignored. -// If multiple WithCredentialsProvider calls are made, the last call overrides -// the previous call values. -func WithCredentialsProvider(v aws.CredentialsProvider) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.Credentials = v - return nil - } -} - -// getCredentialsCacheOptionsProvider returns the wrapped function to set aws.CredentialsCacheOptions -func (o LoadOptions) getCredentialsCacheOptions(ctx context.Context) (func(*aws.CredentialsCacheOptions), bool, error) { - if o.CredentialsCacheOptions == nil { - return nil, false, nil - } - - return o.CredentialsCacheOptions, true, nil -} - -// WithCredentialsCacheOptions is a helper function to construct functional -// options that sets a function to modify the aws.CredentialsCacheOptions the -// aws.CredentialsCache will be configured with, if the CredentialsCache is used -// by the configuration loader. -// -// If multiple WithCredentialsCacheOptions calls are made, the last call -// overrides the previous call values. -func WithCredentialsCacheOptions(v func(*aws.CredentialsCacheOptions)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.CredentialsCacheOptions = v - return nil - } -} - -// getBearerAuthTokenProvider returns the credentials value -func (o LoadOptions) getBearerAuthTokenProvider(ctx context.Context) (smithybearer.TokenProvider, bool, error) { - if o.BearerAuthTokenProvider == nil { - return nil, false, nil - } - - return o.BearerAuthTokenProvider, true, nil -} - -// WithBearerAuthTokenProvider is a helper function to construct functional options -// that sets Credential provider value on config's LoadOptions. If credentials -// provider is set to nil, the credentials provider value will be ignored. -// If multiple WithBearerAuthTokenProvider calls are made, the last call overrides -// the previous call values. -func WithBearerAuthTokenProvider(v smithybearer.TokenProvider) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.BearerAuthTokenProvider = v - return nil - } -} - -// getBearerAuthTokenCacheOptionsProvider returns the wrapped function to set smithybearer.TokenCacheOptions -func (o LoadOptions) getBearerAuthTokenCacheOptions(ctx context.Context) (func(*smithybearer.TokenCacheOptions), bool, error) { - if o.BearerAuthTokenCacheOptions == nil { - return nil, false, nil - } - - return o.BearerAuthTokenCacheOptions, true, nil -} - -// WithBearerAuthTokenCacheOptions is a helper function to construct functional options -// that sets a function to modify the TokenCacheOptions the smithy-go -// auth/bearer#TokenCache will be configured with, if the TokenCache is used by -// the configuration loader. -// -// If multiple WithBearerAuthTokenCacheOptions calls are made, the last call overrides -// the previous call values. -func WithBearerAuthTokenCacheOptions(v func(*smithybearer.TokenCacheOptions)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.BearerAuthTokenCacheOptions = v - return nil - } -} - -// getSSOTokenProviderOptionsProvider returns the wrapped function to set smithybearer.TokenCacheOptions -func (o LoadOptions) getSSOTokenProviderOptions(ctx context.Context) (func(*ssocreds.SSOTokenProviderOptions), bool, error) { - if o.SSOTokenProviderOptions == nil { - return nil, false, nil - } - - return o.SSOTokenProviderOptions, true, nil -} - -// WithSSOTokenProviderOptions is a helper function to construct functional -// options that sets a function to modify the SSOtokenProviderOptions the SDK's -// credentials/ssocreds#SSOProvider will be configured with, if the -// SSOTokenProvider is used by the configuration loader. -// -// If multiple WithSSOTokenProviderOptions calls are made, the last call overrides -// the previous call values. -func WithSSOTokenProviderOptions(v func(*ssocreds.SSOTokenProviderOptions)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.SSOTokenProviderOptions = v - return nil - } -} - -// getProcessCredentialOptions returns the wrapped function to set processcreds.Options -func (o LoadOptions) getProcessCredentialOptions(ctx context.Context) (func(*processcreds.Options), bool, error) { - if o.ProcessCredentialOptions == nil { - return nil, false, nil - } - - return o.ProcessCredentialOptions, true, nil -} - -// WithProcessCredentialOptions is a helper function to construct functional options -// that sets a function to use processcreds.Options on config's LoadOptions. -// If process credential options is set to nil, the process credential value will -// be ignored. If multiple WithProcessCredentialOptions calls are made, the last call -// overrides the previous call values. -func WithProcessCredentialOptions(v func(*processcreds.Options)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.ProcessCredentialOptions = v - return nil - } -} - -// getEC2RoleCredentialOptions returns the wrapped function to set the ec2rolecreds.Options -func (o LoadOptions) getEC2RoleCredentialOptions(ctx context.Context) (func(*ec2rolecreds.Options), bool, error) { - if o.EC2RoleCredentialOptions == nil { - return nil, false, nil - } - - return o.EC2RoleCredentialOptions, true, nil -} - -// WithEC2RoleCredentialOptions is a helper function to construct functional options -// that sets a function to use ec2rolecreds.Options on config's LoadOptions. If -// EC2 role credential options is set to nil, the EC2 role credential options value -// will be ignored. If multiple WithEC2RoleCredentialOptions calls are made, -// the last call overrides the previous call values. -func WithEC2RoleCredentialOptions(v func(*ec2rolecreds.Options)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EC2RoleCredentialOptions = v - return nil - } -} - -// getEndpointCredentialOptions returns the wrapped function to set endpointcreds.Options -func (o LoadOptions) getEndpointCredentialOptions(context.Context) (func(*endpointcreds.Options), bool, error) { - if o.EndpointCredentialOptions == nil { - return nil, false, nil - } - - return o.EndpointCredentialOptions, true, nil -} - -// WithEndpointCredentialOptions is a helper function to construct functional options -// that sets a function to use endpointcreds.Options on config's LoadOptions. If -// endpoint credential options is set to nil, the endpoint credential options -// value will be ignored. If multiple WithEndpointCredentialOptions calls are made, -// the last call overrides the previous call values. -func WithEndpointCredentialOptions(v func(*endpointcreds.Options)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EndpointCredentialOptions = v - return nil - } -} - -// getWebIdentityRoleCredentialOptions returns the wrapped function -func (o LoadOptions) getWebIdentityRoleCredentialOptions(context.Context) (func(*stscreds.WebIdentityRoleOptions), bool, error) { - if o.WebIdentityRoleCredentialOptions == nil { - return nil, false, nil - } - - return o.WebIdentityRoleCredentialOptions, true, nil -} - -// WithWebIdentityRoleCredentialOptions is a helper function to construct -// functional options that sets a function to use stscreds.WebIdentityRoleOptions -// on config's LoadOptions. If web identity role credentials options is set to nil, -// the web identity role credentials value will be ignored. If multiple -// WithWebIdentityRoleCredentialOptions calls are made, the last call -// overrides the previous call values. -func WithWebIdentityRoleCredentialOptions(v func(*stscreds.WebIdentityRoleOptions)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.WebIdentityRoleCredentialOptions = v - return nil - } -} - -// getAssumeRoleCredentialOptions returns AssumeRoleCredentialOptions from LoadOptions -func (o LoadOptions) getAssumeRoleCredentialOptions(context.Context) (func(options *stscreds.AssumeRoleOptions), bool, error) { - if o.AssumeRoleCredentialOptions == nil { - return nil, false, nil - } - - return o.AssumeRoleCredentialOptions, true, nil -} - -// WithAssumeRoleCredentialOptions is a helper function to construct -// functional options that sets a function to use stscreds.AssumeRoleOptions -// on config's LoadOptions. If assume role credentials options is set to nil, -// the assume role credentials value will be ignored. If multiple -// WithAssumeRoleCredentialOptions calls are made, the last call overrides -// the previous call values. -func WithAssumeRoleCredentialOptions(v func(*stscreds.AssumeRoleOptions)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.AssumeRoleCredentialOptions = v - return nil - } -} - -func (o LoadOptions) getHTTPClient(ctx context.Context) (HTTPClient, bool, error) { - if o.HTTPClient == nil { - return nil, false, nil - } - - return o.HTTPClient, true, nil -} - -// WithHTTPClient is a helper function to construct functional options -// that sets HTTPClient on LoadOptions. If HTTPClient is set to nil, -// the HTTPClient value will be ignored. -// If multiple WithHTTPClient calls are made, the last call overrides -// the previous call values. -func WithHTTPClient(v HTTPClient) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.HTTPClient = v - return nil - } -} - -func (o LoadOptions) getAPIOptions(ctx context.Context) ([]func(*middleware.Stack) error, bool, error) { - if o.APIOptions == nil { - return nil, false, nil - } - - return o.APIOptions, true, nil -} - -// WithAPIOptions is a helper function to construct functional options -// that sets APIOptions on LoadOptions. If APIOptions is set to nil, the -// APIOptions value is ignored. If multiple WithAPIOptions calls are -// made, the last call overrides the previous call values. -func WithAPIOptions(v []func(*middleware.Stack) error) LoadOptionsFunc { - return func(o *LoadOptions) error { - if v == nil { - return nil - } - - o.APIOptions = append(o.APIOptions, v...) - return nil - } -} - -func (o LoadOptions) getRetryMaxAttempts(ctx context.Context) (int, bool, error) { - if o.RetryMaxAttempts == 0 { - return 0, false, nil - } - - return o.RetryMaxAttempts, true, nil -} - -// WithRetryMaxAttempts is a helper function to construct functional options that sets -// RetryMaxAttempts on LoadOptions. If RetryMaxAttempts is unset, the RetryMaxAttempts value is -// ignored. If multiple WithRetryMaxAttempts calls are made, the last call overrides -// the previous call values. -// -// Will be ignored of LoadOptions.Retryer or WithRetryer are used. -func WithRetryMaxAttempts(v int) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.RetryMaxAttempts = v - return nil - } -} - -func (o LoadOptions) getRetryMode(ctx context.Context) (aws.RetryMode, bool, error) { - if o.RetryMode == "" { - return "", false, nil - } - - return o.RetryMode, true, nil -} - -// WithRetryMode is a helper function to construct functional options that sets -// RetryMode on LoadOptions. If RetryMode is unset, the RetryMode value is -// ignored. If multiple WithRetryMode calls are made, the last call overrides -// the previous call values. -// -// Will be ignored of LoadOptions.Retryer or WithRetryer are used. -func WithRetryMode(v aws.RetryMode) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.RetryMode = v - return nil - } -} - -func (o LoadOptions) getRetryer(ctx context.Context) (func() aws.Retryer, bool, error) { - if o.Retryer == nil { - return nil, false, nil - } - - return o.Retryer, true, nil -} - -// WithRetryer is a helper function to construct functional options -// that sets Retryer on LoadOptions. If Retryer is set to nil, the -// Retryer value is ignored. If multiple WithRetryer calls are -// made, the last call overrides the previous call values. -func WithRetryer(v func() aws.Retryer) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.Retryer = v - return nil - } -} - -func (o LoadOptions) getEndpointResolver(ctx context.Context) (aws.EndpointResolver, bool, error) { - if o.EndpointResolver == nil { - return nil, false, nil - } - - return o.EndpointResolver, true, nil -} - -// WithEndpointResolver is a helper function to construct functional options -// that sets the EndpointResolver on LoadOptions. If the EndpointResolver is set to nil, -// the EndpointResolver value is ignored. If multiple WithEndpointResolver calls -// are made, the last call overrides the previous call values. -// -// Deprecated: See WithEndpointResolverWithOptions -func WithEndpointResolver(v aws.EndpointResolver) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EndpointResolver = v - return nil - } -} - -func (o LoadOptions) getEndpointResolverWithOptions(ctx context.Context) (aws.EndpointResolverWithOptions, bool, error) { - if o.EndpointResolverWithOptions == nil { - return nil, false, nil - } - - return o.EndpointResolverWithOptions, true, nil -} - -// WithEndpointResolverWithOptions is a helper function to construct functional options -// that sets the EndpointResolverWithOptions on LoadOptions. If the EndpointResolverWithOptions is set to nil, -// the EndpointResolver value is ignored. If multiple WithEndpointResolver calls -// are made, the last call overrides the previous call values. -func WithEndpointResolverWithOptions(v aws.EndpointResolverWithOptions) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EndpointResolverWithOptions = v - return nil - } -} - -func (o LoadOptions) getLogger(ctx context.Context) (logging.Logger, bool, error) { - if o.Logger == nil { - return nil, false, nil - } - - return o.Logger, true, nil -} - -// WithLogger is a helper function to construct functional options -// that sets Logger on LoadOptions. If Logger is set to nil, the -// Logger value will be ignored. If multiple WithLogger calls are made, -// the last call overrides the previous call values. -func WithLogger(v logging.Logger) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.Logger = v - return nil - } -} - -func (o LoadOptions) getClientLogMode(ctx context.Context) (aws.ClientLogMode, bool, error) { - if o.ClientLogMode == nil { - return 0, false, nil - } - - return *o.ClientLogMode, true, nil -} - -// WithClientLogMode is a helper function to construct functional options -// that sets client log mode on LoadOptions. If client log mode is set to nil, -// the client log mode value will be ignored. If multiple WithClientLogMode calls are made, -// the last call overrides the previous call values. -func WithClientLogMode(v aws.ClientLogMode) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.ClientLogMode = &v - return nil - } -} - -func (o LoadOptions) getLogConfigurationWarnings(ctx context.Context) (v bool, found bool, err error) { - if o.LogConfigurationWarnings == nil { - return false, false, nil - } - return *o.LogConfigurationWarnings, true, nil -} - -// WithLogConfigurationWarnings is a helper function to construct -// functional options that can be used to set LogConfigurationWarnings -// on LoadOptions. -// -// If multiple WithLogConfigurationWarnings calls are made, the last call -// overrides the previous call values. -func WithLogConfigurationWarnings(v bool) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.LogConfigurationWarnings = &v - return nil - } -} - -// GetS3UseARNRegion returns whether to allow ARNs to direct the region -// the S3 client's requests are sent to. -func (o LoadOptions) GetS3UseARNRegion(ctx context.Context) (v bool, found bool, err error) { - if o.S3UseARNRegion == nil { - return false, false, nil - } - return *o.S3UseARNRegion, true, nil -} - -// WithS3UseARNRegion is a helper function to construct functional options -// that can be used to set S3UseARNRegion on LoadOptions. -// If multiple WithS3UseARNRegion calls are made, the last call overrides -// the previous call values. -func WithS3UseARNRegion(v bool) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.S3UseARNRegion = &v - return nil - } -} - -// GetS3DisableMultiRegionAccessPoints returns whether to disable -// the S3 multi-region access points feature. -func (o LoadOptions) GetS3DisableMultiRegionAccessPoints(ctx context.Context) (v bool, found bool, err error) { - if o.S3DisableMultiRegionAccessPoints == nil { - return false, false, nil - } - return *o.S3DisableMultiRegionAccessPoints, true, nil -} - -// WithS3DisableMultiRegionAccessPoints is a helper function to construct functional options -// that can be used to set S3DisableMultiRegionAccessPoints on LoadOptions. -// If multiple WithS3DisableMultiRegionAccessPoints calls are made, the last call overrides -// the previous call values. -func WithS3DisableMultiRegionAccessPoints(v bool) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.S3DisableMultiRegionAccessPoints = &v - return nil - } -} - -// GetEnableEndpointDiscovery returns if the EnableEndpointDiscovery flag is set. -func (o LoadOptions) GetEnableEndpointDiscovery(ctx context.Context) (value aws.EndpointDiscoveryEnableState, ok bool, err error) { - if o.EnableEndpointDiscovery == aws.EndpointDiscoveryUnset { - return aws.EndpointDiscoveryUnset, false, nil - } - return o.EnableEndpointDiscovery, true, nil -} - -// WithEndpointDiscovery is a helper function to construct functional options -// that can be used to enable endpoint discovery on LoadOptions for supported clients. -// If multiple WithEndpointDiscovery calls are made, the last call overrides -// the previous call values. -func WithEndpointDiscovery(v aws.EndpointDiscoveryEnableState) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EnableEndpointDiscovery = v - return nil - } -} - -// getSSOProviderOptions returns AssumeRoleCredentialOptions from LoadOptions -func (o LoadOptions) getSSOProviderOptions(context.Context) (func(options *ssocreds.Options), bool, error) { - if o.SSOProviderOptions == nil { - return nil, false, nil - } - - return o.SSOProviderOptions, true, nil -} - -// WithSSOProviderOptions is a helper function to construct -// functional options that sets a function to use ssocreds.Options -// on config's LoadOptions. If the SSO credential provider options is set to nil, -// the sso provider options value will be ignored. If multiple -// WithSSOProviderOptions calls are made, the last call overrides -// the previous call values. -func WithSSOProviderOptions(v func(*ssocreds.Options)) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.SSOProviderOptions = v - return nil - } -} - -// GetEC2IMDSClientEnableState implements a EC2IMDSClientEnableState options resolver interface. -func (o LoadOptions) GetEC2IMDSClientEnableState() (imds.ClientEnableState, bool, error) { - if o.EC2IMDSClientEnableState == imds.ClientDefaultEnableState { - return imds.ClientDefaultEnableState, false, nil - } - - return o.EC2IMDSClientEnableState, true, nil -} - -// GetEC2IMDSEndpointMode implements a EC2IMDSEndpointMode option resolver interface. -func (o LoadOptions) GetEC2IMDSEndpointMode() (imds.EndpointModeState, bool, error) { - if o.EC2IMDSEndpointMode == imds.EndpointModeStateUnset { - return imds.EndpointModeStateUnset, false, nil - } - - return o.EC2IMDSEndpointMode, true, nil -} - -// GetEC2IMDSEndpoint implements a EC2IMDSEndpoint option resolver interface. -func (o LoadOptions) GetEC2IMDSEndpoint() (string, bool, error) { - if len(o.EC2IMDSEndpoint) == 0 { - return "", false, nil - } - - return o.EC2IMDSEndpoint, true, nil -} - -// WithEC2IMDSClientEnableState is a helper function to construct functional options that sets the EC2IMDSClientEnableState. -func WithEC2IMDSClientEnableState(v imds.ClientEnableState) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EC2IMDSClientEnableState = v - return nil - } -} - -// WithEC2IMDSEndpointMode is a helper function to construct functional options that sets the EC2IMDSEndpointMode. -func WithEC2IMDSEndpointMode(v imds.EndpointModeState) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EC2IMDSEndpointMode = v - return nil - } -} - -// WithEC2IMDSEndpoint is a helper function to construct functional options that sets the EC2IMDSEndpoint. -func WithEC2IMDSEndpoint(v string) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.EC2IMDSEndpoint = v - return nil - } -} - -// WithUseDualStackEndpoint is a helper function to construct -// functional options that can be used to set UseDualStackEndpoint on LoadOptions. -func WithUseDualStackEndpoint(v aws.DualStackEndpointState) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.UseDualStackEndpoint = v - return nil - } -} - -// GetUseDualStackEndpoint returns whether the service's dual-stack endpoint should be -// used for requests. -func (o LoadOptions) GetUseDualStackEndpoint(ctx context.Context) (value aws.DualStackEndpointState, found bool, err error) { - if o.UseDualStackEndpoint == aws.DualStackEndpointStateUnset { - return aws.DualStackEndpointStateUnset, false, nil - } - return o.UseDualStackEndpoint, true, nil -} - -// WithUseFIPSEndpoint is a helper function to construct -// functional options that can be used to set UseFIPSEndpoint on LoadOptions. -func WithUseFIPSEndpoint(v aws.FIPSEndpointState) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.UseFIPSEndpoint = v - return nil - } -} - -// GetUseFIPSEndpoint returns whether the service's FIPS endpoint should be -// used for requests. -func (o LoadOptions) GetUseFIPSEndpoint(ctx context.Context) (value aws.FIPSEndpointState, found bool, err error) { - if o.UseFIPSEndpoint == aws.FIPSEndpointStateUnset { - return aws.FIPSEndpointStateUnset, false, nil - } - return o.UseFIPSEndpoint, true, nil -} - -// WithDefaultsMode sets the SDK defaults configuration mode to the value provided. -// -// Zero or more functional options can be provided to provide configuration options for performing -// environment discovery when using aws.DefaultsModeAuto. -func WithDefaultsMode(mode aws.DefaultsMode, optFns ...func(options *DefaultsModeOptions)) LoadOptionsFunc { - do := DefaultsModeOptions{ - Mode: mode, - } - for _, fn := range optFns { - fn(&do) - } - return func(options *LoadOptions) error { - options.DefaultsModeOptions = do - return nil - } -} - -// GetS3DisableExpressAuth returns the configured value for -// [EnvConfig.S3DisableExpressAuth]. -func (o LoadOptions) GetS3DisableExpressAuth() (value, ok bool) { - if o.S3DisableExpressAuth == nil { - return false, false - } - - return *o.S3DisableExpressAuth, true -} - -// WithS3DisableExpressAuth sets [LoadOptions.S3DisableExpressAuth] -// to the value provided. -func WithS3DisableExpressAuth(v bool) LoadOptionsFunc { - return func(o *LoadOptions) error { - o.S3DisableExpressAuth = &v - return nil - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/local.go b/vendor/github.com/aws/aws-sdk-go-v2/config/local.go deleted file mode 100644 index b629137c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/local.go +++ /dev/null @@ -1,51 +0,0 @@ -package config - -import ( - "fmt" - "net" - "net/url" -) - -var lookupHostFn = net.LookupHost - -func isLoopbackHost(host string) (bool, error) { - ip := net.ParseIP(host) - if ip != nil { - return ip.IsLoopback(), nil - } - - // Host is not an ip, perform lookup - addrs, err := lookupHostFn(host) - if err != nil { - return false, err - } - if len(addrs) == 0 { - return false, fmt.Errorf("no addrs found for host, %s", host) - } - - for _, addr := range addrs { - if !net.ParseIP(addr).IsLoopback() { - return false, nil - } - } - - return true, nil -} - -func validateLocalURL(v string) error { - u, err := url.Parse(v) - if err != nil { - return err - } - - host := u.Hostname() - if len(host) == 0 { - return fmt.Errorf("unable to parse host from local HTTP cred provider URL") - } else if isLoopback, err := isLoopbackHost(host); err != nil { - return fmt.Errorf("failed to resolve host %q, %v", host, err) - } else if !isLoopback { - return fmt.Errorf("invalid endpoint host, %q, only host resolving to loopback addresses are allowed", host) - } - - return nil -} 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 deleted file mode 100644 index 13745fc9..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/provider.go +++ /dev/null @@ -1,704 +0,0 @@ -package config - -import ( - "context" - "io" - "net/http" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds" - "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" - smithybearer "github.com/aws/smithy-go/auth/bearer" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" -) - -// sharedConfigProfileProvider provides access to the shared config profile -// name external configuration value. -type sharedConfigProfileProvider interface { - getSharedConfigProfile(ctx context.Context) (string, bool, error) -} - -// getSharedConfigProfile searches the configs for a sharedConfigProfileProvider -// and returns the value if found. Returns an error if a provider fails before a -// value is found. -func getSharedConfigProfile(ctx context.Context, configs configs) (value string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(sharedConfigProfileProvider); ok { - value, found, err = p.getSharedConfigProfile(ctx) - if err != nil || found { - break - } - } - } - return -} - -// sharedConfigFilesProvider provides access to the shared config filesnames -// external configuration value. -type sharedConfigFilesProvider interface { - getSharedConfigFiles(ctx context.Context) ([]string, bool, error) -} - -// getSharedConfigFiles searches the configs for a sharedConfigFilesProvider -// and returns the value if found. Returns an error if a provider fails before a -// value is found. -func getSharedConfigFiles(ctx context.Context, configs configs) (value []string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(sharedConfigFilesProvider); ok { - value, found, err = p.getSharedConfigFiles(ctx) - if err != nil || found { - break - } - } - } - - return -} - -// sharedCredentialsFilesProvider provides access to the shared credentials filesnames -// external configuration value. -type sharedCredentialsFilesProvider interface { - getSharedCredentialsFiles(ctx context.Context) ([]string, bool, error) -} - -// getSharedCredentialsFiles searches the configs for a sharedCredentialsFilesProvider -// and returns the value if found. Returns an error if a provider fails before a -// value is found. -func getSharedCredentialsFiles(ctx context.Context, configs configs) (value []string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(sharedCredentialsFilesProvider); ok { - value, found, err = p.getSharedCredentialsFiles(ctx) - if err != nil || found { - break - } - } - } - - return -} - -// customCABundleProvider provides access to the custom CA bundle PEM bytes. -type customCABundleProvider interface { - getCustomCABundle(ctx context.Context) (io.Reader, bool, error) -} - -// getCustomCABundle searches the configs for a customCABundleProvider -// and returns the value if found. Returns an error if a provider fails before a -// value is found. -func getCustomCABundle(ctx context.Context, configs configs) (value io.Reader, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(customCABundleProvider); ok { - value, found, err = p.getCustomCABundle(ctx) - if err != nil || found { - break - } - } - } - - return -} - -// regionProvider provides access to the region external configuration value. -type regionProvider interface { - getRegion(ctx context.Context) (string, bool, error) -} - -// getRegion searches the configs for a regionProvider and returns the value -// if found. Returns an error if a provider fails before a value is found. -func getRegion(ctx context.Context, configs configs) (value string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(regionProvider); ok { - value, found, err = p.getRegion(ctx) - if err != nil || found { - break - } - } - } - return -} - -// IgnoreConfiguredEndpointsProvider is needed to search for all providers -// that provide a flag to disable configured endpoints. -type IgnoreConfiguredEndpointsProvider interface { - GetIgnoreConfiguredEndpoints(ctx context.Context) (bool, bool, error) -} - -// GetIgnoreConfiguredEndpoints is used in knowing when to disable configured -// endpoints feature. -func GetIgnoreConfiguredEndpoints(ctx context.Context, configs []interface{}) (value bool, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(IgnoreConfiguredEndpointsProvider); ok { - value, found, err = p.GetIgnoreConfiguredEndpoints(ctx) - if err != nil || found { - break - } - } - } - return -} - -type baseEndpointProvider interface { - getBaseEndpoint(ctx context.Context) (string, bool, error) -} - -func getBaseEndpoint(ctx context.Context, configs configs) (value string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(baseEndpointProvider); ok { - value, found, err = p.getBaseEndpoint(ctx) - if err != nil || found { - break - } - } - } - return -} - -type servicesObjectProvider interface { - getServicesObject(ctx context.Context) (map[string]map[string]string, bool, error) -} - -func getServicesObject(ctx context.Context, configs configs) (value map[string]map[string]string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(servicesObjectProvider); ok { - value, found, err = p.getServicesObject(ctx) - if err != nil || found { - break - } - } - } - return -} - -// appIDProvider provides access to the sdk app ID value -type appIDProvider interface { - getAppID(ctx context.Context) (string, bool, error) -} - -func getAppID(ctx context.Context, configs configs) (value string, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(appIDProvider); ok { - value, found, err = p.getAppID(ctx) - if err != nil || found { - break - } - } - } - return -} - -// disableRequestCompressionProvider provides access to the DisableRequestCompression -type disableRequestCompressionProvider interface { - getDisableRequestCompression(context.Context) (bool, bool, error) -} - -func getDisableRequestCompression(ctx context.Context, configs configs) (value bool, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(disableRequestCompressionProvider); ok { - value, found, err = p.getDisableRequestCompression(ctx) - if err != nil || found { - break - } - } - } - return -} - -// requestMinCompressSizeBytesProvider provides access to the MinCompressSizeBytes -type requestMinCompressSizeBytesProvider interface { - getRequestMinCompressSizeBytes(context.Context) (int64, bool, error) -} - -func getRequestMinCompressSizeBytes(ctx context.Context, configs configs) (value int64, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(requestMinCompressSizeBytesProvider); ok { - value, found, err = p.getRequestMinCompressSizeBytes(ctx) - if err != nil || found { - break - } - } - } - return -} - -// ec2IMDSRegionProvider provides access to the ec2 imds region -// configuration value -type ec2IMDSRegionProvider interface { - getEC2IMDSRegion(ctx context.Context) (string, bool, error) -} - -// getEC2IMDSRegion searches the configs for a ec2IMDSRegionProvider and -// returns the value if found. Returns an error if a provider fails before -// a value is found. -func getEC2IMDSRegion(ctx context.Context, configs configs) (region string, found bool, err error) { - for _, cfg := range configs { - if provider, ok := cfg.(ec2IMDSRegionProvider); ok { - region, found, err = provider.getEC2IMDSRegion(ctx) - if err != nil || found { - break - } - } - } - return -} - -// credentialsProviderProvider provides access to the credentials external -// configuration value. -type credentialsProviderProvider interface { - getCredentialsProvider(ctx context.Context) (aws.CredentialsProvider, bool, error) -} - -// getCredentialsProvider searches the configs for a credentialsProviderProvider -// and returns the value if found. Returns an error if a provider fails before a -// value is found. -func getCredentialsProvider(ctx context.Context, configs configs) (p aws.CredentialsProvider, found bool, err error) { - for _, cfg := range configs { - if provider, ok := cfg.(credentialsProviderProvider); ok { - p, found, err = provider.getCredentialsProvider(ctx) - if err != nil || found { - break - } - } - } - return -} - -// credentialsCacheOptionsProvider is an interface for retrieving a function for setting -// the aws.CredentialsCacheOptions. -type credentialsCacheOptionsProvider interface { - getCredentialsCacheOptions(ctx context.Context) (func(*aws.CredentialsCacheOptions), bool, error) -} - -// getCredentialsCacheOptionsProvider is an interface for retrieving a function for setting -// the aws.CredentialsCacheOptions. -func getCredentialsCacheOptionsProvider(ctx context.Context, configs configs) ( - f func(*aws.CredentialsCacheOptions), found bool, err error, -) { - for _, config := range configs { - if p, ok := config.(credentialsCacheOptionsProvider); ok { - f, found, err = p.getCredentialsCacheOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// bearerAuthTokenProviderProvider provides access to the bearer authentication -// token external configuration value. -type bearerAuthTokenProviderProvider interface { - getBearerAuthTokenProvider(context.Context) (smithybearer.TokenProvider, bool, error) -} - -// getBearerAuthTokenProvider searches the config sources for a -// bearerAuthTokenProviderProvider and returns the value if found. Returns an -// error if a provider fails before a value is found. -func getBearerAuthTokenProvider(ctx context.Context, configs configs) (p smithybearer.TokenProvider, found bool, err error) { - for _, cfg := range configs { - if provider, ok := cfg.(bearerAuthTokenProviderProvider); ok { - p, found, err = provider.getBearerAuthTokenProvider(ctx) - if err != nil || found { - break - } - } - } - return -} - -// bearerAuthTokenCacheOptionsProvider is an interface for retrieving a function for -// setting the smithy-go auth/bearer#TokenCacheOptions. -type bearerAuthTokenCacheOptionsProvider interface { - getBearerAuthTokenCacheOptions(context.Context) (func(*smithybearer.TokenCacheOptions), bool, error) -} - -// getBearerAuthTokenCacheOptionsProvider is an interface for retrieving a function for -// setting the smithy-go auth/bearer#TokenCacheOptions. -func getBearerAuthTokenCacheOptions(ctx context.Context, configs configs) ( - f func(*smithybearer.TokenCacheOptions), found bool, err error, -) { - for _, config := range configs { - if p, ok := config.(bearerAuthTokenCacheOptionsProvider); ok { - f, found, err = p.getBearerAuthTokenCacheOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// ssoTokenProviderOptionsProvider is an interface for retrieving a function for -// setting the SDK's credentials/ssocreds#SSOTokenProviderOptions. -type ssoTokenProviderOptionsProvider interface { - getSSOTokenProviderOptions(context.Context) (func(*ssocreds.SSOTokenProviderOptions), bool, error) -} - -// getSSOTokenProviderOptions is an interface for retrieving a function for -// setting the SDK's credentials/ssocreds#SSOTokenProviderOptions. -func getSSOTokenProviderOptions(ctx context.Context, configs configs) ( - f func(*ssocreds.SSOTokenProviderOptions), found bool, err error, -) { - for _, config := range configs { - if p, ok := config.(ssoTokenProviderOptionsProvider); ok { - f, found, err = p.getSSOTokenProviderOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// ssoTokenProviderOptionsProvider - -// processCredentialOptions is an interface for retrieving a function for setting -// the processcreds.Options. -type processCredentialOptions interface { - getProcessCredentialOptions(ctx context.Context) (func(*processcreds.Options), bool, error) -} - -// getProcessCredentialOptions searches the slice of configs and returns the first function found -func getProcessCredentialOptions(ctx context.Context, configs configs) (f func(*processcreds.Options), found bool, err error) { - for _, config := range configs { - if p, ok := config.(processCredentialOptions); ok { - f, found, err = p.getProcessCredentialOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// ec2RoleCredentialOptionsProvider is an interface for retrieving a function -// for setting the ec2rolecreds.Provider options. -type ec2RoleCredentialOptionsProvider interface { - getEC2RoleCredentialOptions(ctx context.Context) (func(*ec2rolecreds.Options), bool, error) -} - -// getEC2RoleCredentialProviderOptions searches the slice of configs and returns the first function found -func getEC2RoleCredentialProviderOptions(ctx context.Context, configs configs) (f func(*ec2rolecreds.Options), found bool, err error) { - for _, config := range configs { - if p, ok := config.(ec2RoleCredentialOptionsProvider); ok { - f, found, err = p.getEC2RoleCredentialOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// defaultRegionProvider is an interface for retrieving a default region if a region was not resolved from other sources -type defaultRegionProvider interface { - getDefaultRegion(ctx context.Context) (string, bool, error) -} - -// getDefaultRegion searches the slice of configs and returns the first fallback region found -func getDefaultRegion(ctx context.Context, configs configs) (value string, found bool, err error) { - for _, config := range configs { - if p, ok := config.(defaultRegionProvider); ok { - value, found, err = p.getDefaultRegion(ctx) - if err != nil || found { - break - } - } - } - return -} - -// endpointCredentialOptionsProvider is an interface for retrieving a function for setting -// the endpointcreds.ProviderOptions. -type endpointCredentialOptionsProvider interface { - getEndpointCredentialOptions(ctx context.Context) (func(*endpointcreds.Options), bool, error) -} - -// getEndpointCredentialProviderOptions searches the slice of configs and returns the first function found -func getEndpointCredentialProviderOptions(ctx context.Context, configs configs) (f func(*endpointcreds.Options), found bool, err error) { - for _, config := range configs { - if p, ok := config.(endpointCredentialOptionsProvider); ok { - f, found, err = p.getEndpointCredentialOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// webIdentityRoleCredentialOptionsProvider is an interface for retrieving a function for setting -// the stscreds.WebIdentityRoleProvider. -type webIdentityRoleCredentialOptionsProvider interface { - getWebIdentityRoleCredentialOptions(ctx context.Context) (func(*stscreds.WebIdentityRoleOptions), bool, error) -} - -// getWebIdentityCredentialProviderOptions searches the slice of configs and returns the first function found -func getWebIdentityCredentialProviderOptions(ctx context.Context, configs configs) (f func(*stscreds.WebIdentityRoleOptions), found bool, err error) { - for _, config := range configs { - if p, ok := config.(webIdentityRoleCredentialOptionsProvider); ok { - f, found, err = p.getWebIdentityRoleCredentialOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// assumeRoleCredentialOptionsProvider is an interface for retrieving a function for setting -// the stscreds.AssumeRoleOptions. -type assumeRoleCredentialOptionsProvider interface { - getAssumeRoleCredentialOptions(ctx context.Context) (func(*stscreds.AssumeRoleOptions), bool, error) -} - -// getAssumeRoleCredentialProviderOptions searches the slice of configs and returns the first function found -func getAssumeRoleCredentialProviderOptions(ctx context.Context, configs configs) (f func(*stscreds.AssumeRoleOptions), found bool, err error) { - for _, config := range configs { - if p, ok := config.(assumeRoleCredentialOptionsProvider); ok { - f, found, err = p.getAssumeRoleCredentialOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// HTTPClient is an HTTP client implementation -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// httpClientProvider is an interface for retrieving HTTPClient -type httpClientProvider interface { - getHTTPClient(ctx context.Context) (HTTPClient, bool, error) -} - -// getHTTPClient searches the slice of configs and returns the HTTPClient set on configs -func getHTTPClient(ctx context.Context, configs configs) (client HTTPClient, found bool, err error) { - for _, config := range configs { - if p, ok := config.(httpClientProvider); ok { - client, found, err = p.getHTTPClient(ctx) - if err != nil || found { - break - } - } - } - return -} - -// apiOptionsProvider is an interface for retrieving APIOptions -type apiOptionsProvider interface { - getAPIOptions(ctx context.Context) ([]func(*middleware.Stack) error, bool, error) -} - -// getAPIOptions searches the slice of configs and returns the APIOptions set on configs -func getAPIOptions(ctx context.Context, configs configs) (apiOptions []func(*middleware.Stack) error, found bool, err error) { - for _, config := range configs { - if p, ok := config.(apiOptionsProvider); ok { - // retrieve APIOptions from configs and set it on cfg - apiOptions, found, err = p.getAPIOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// endpointResolverProvider is an interface for retrieving an aws.EndpointResolver from a configuration source -type endpointResolverProvider interface { - getEndpointResolver(ctx context.Context) (aws.EndpointResolver, bool, error) -} - -// getEndpointResolver searches the provided config sources for a EndpointResolverFunc that can be used -// to configure the aws.Config.EndpointResolver value. -func getEndpointResolver(ctx context.Context, configs configs) (f aws.EndpointResolver, found bool, err error) { - for _, c := range configs { - if p, ok := c.(endpointResolverProvider); ok { - f, found, err = p.getEndpointResolver(ctx) - if err != nil || found { - break - } - } - } - return -} - -// endpointResolverWithOptionsProvider is an interface for retrieving an aws.EndpointResolverWithOptions from a configuration source -type endpointResolverWithOptionsProvider interface { - getEndpointResolverWithOptions(ctx context.Context) (aws.EndpointResolverWithOptions, bool, error) -} - -// getEndpointResolver searches the provided config sources for a EndpointResolverFunc that can be used -// to configure the aws.Config.EndpointResolver value. -func getEndpointResolverWithOptions(ctx context.Context, configs configs) (f aws.EndpointResolverWithOptions, found bool, err error) { - for _, c := range configs { - if p, ok := c.(endpointResolverWithOptionsProvider); ok { - f, found, err = p.getEndpointResolverWithOptions(ctx) - if err != nil || found { - break - } - } - } - return -} - -// loggerProvider is an interface for retrieving a logging.Logger from a configuration source. -type loggerProvider interface { - getLogger(ctx context.Context) (logging.Logger, bool, error) -} - -// getLogger searches the provided config sources for a logging.Logger that can be used -// to configure the aws.Config.Logger value. -func getLogger(ctx context.Context, configs configs) (l logging.Logger, found bool, err error) { - for _, c := range configs { - if p, ok := c.(loggerProvider); ok { - l, found, err = p.getLogger(ctx) - if err != nil || found { - break - } - } - } - return -} - -// clientLogModeProvider is an interface for retrieving the aws.ClientLogMode from a configuration source. -type clientLogModeProvider interface { - getClientLogMode(ctx context.Context) (aws.ClientLogMode, bool, error) -} - -func getClientLogMode(ctx context.Context, configs configs) (m aws.ClientLogMode, found bool, err error) { - for _, c := range configs { - if p, ok := c.(clientLogModeProvider); ok { - m, found, err = p.getClientLogMode(ctx) - if err != nil || found { - break - } - } - } - return -} - -// retryProvider is an configuration provider for custom Retryer. -type retryProvider interface { - getRetryer(ctx context.Context) (func() aws.Retryer, bool, error) -} - -func getRetryer(ctx context.Context, configs configs) (v func() aws.Retryer, found bool, err error) { - for _, c := range configs { - if p, ok := c.(retryProvider); ok { - v, found, err = p.getRetryer(ctx) - if err != nil || found { - break - } - } - } - return -} - -// logConfigurationWarningsProvider is an configuration provider for -// retrieving a boolean indicating whether configuration issues should -// be logged when loading from config sources -type logConfigurationWarningsProvider interface { - getLogConfigurationWarnings(ctx context.Context) (bool, bool, error) -} - -func getLogConfigurationWarnings(ctx context.Context, configs configs) (v bool, found bool, err error) { - for _, c := range configs { - if p, ok := c.(logConfigurationWarningsProvider); ok { - v, found, err = p.getLogConfigurationWarnings(ctx) - if err != nil || found { - break - } - } - } - return -} - -// ssoCredentialOptionsProvider is an interface for retrieving a function for setting -// the ssocreds.Options. -type ssoCredentialOptionsProvider interface { - getSSOProviderOptions(context.Context) (func(*ssocreds.Options), bool, error) -} - -func getSSOProviderOptions(ctx context.Context, configs configs) (v func(options *ssocreds.Options), found bool, err error) { - for _, c := range configs { - if p, ok := c.(ssoCredentialOptionsProvider); ok { - v, found, err = p.getSSOProviderOptions(ctx) - if err != nil || found { - break - } - } - } - return v, found, err -} - -type defaultsModeIMDSClientProvider interface { - getDefaultsModeIMDSClient(context.Context) (*imds.Client, bool, error) -} - -func getDefaultsModeIMDSClient(ctx context.Context, configs configs) (v *imds.Client, found bool, err error) { - for _, c := range configs { - if p, ok := c.(defaultsModeIMDSClientProvider); ok { - v, found, err = p.getDefaultsModeIMDSClient(ctx) - if err != nil || found { - break - } - } - } - return v, found, err -} - -type defaultsModeProvider interface { - getDefaultsMode(context.Context) (aws.DefaultsMode, bool, error) -} - -func getDefaultsMode(ctx context.Context, configs configs) (v aws.DefaultsMode, found bool, err error) { - for _, c := range configs { - if p, ok := c.(defaultsModeProvider); ok { - v, found, err = p.getDefaultsMode(ctx) - if err != nil || found { - break - } - } - } - return v, found, err -} - -type retryMaxAttemptsProvider interface { - GetRetryMaxAttempts(context.Context) (int, bool, error) -} - -func getRetryMaxAttempts(ctx context.Context, configs configs) (v int, found bool, err error) { - for _, c := range configs { - if p, ok := c.(retryMaxAttemptsProvider); ok { - v, found, err = p.GetRetryMaxAttempts(ctx) - if err != nil || found { - break - } - } - } - return v, found, err -} - -type retryModeProvider interface { - GetRetryMode(context.Context) (aws.RetryMode, bool, error) -} - -func getRetryMode(ctx context.Context, configs configs) (v aws.RetryMode, found bool, err error) { - for _, c := range configs { - if p, ok := c.(retryModeProvider); ok { - v, found, err = p.GetRetryMode(ctx) - if err != nil || found { - break - } - } - } - return v, found, err -} 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 deleted file mode 100644 index fde2e398..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve.go +++ /dev/null @@ -1,367 +0,0 @@ -package config - -import ( - "context" - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "net/http" - "os" - - "github.com/aws/aws-sdk-go-v2/aws" - awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" - "github.com/aws/smithy-go/logging" -) - -// resolveDefaultAWSConfig will write default configuration values into the cfg -// value. It will write the default values, overwriting any previous value. -// -// This should be used as the first resolver in the slice of resolvers when -// resolving external configuration. -func resolveDefaultAWSConfig(ctx context.Context, cfg *aws.Config, cfgs configs) error { - var sources []interface{} - for _, s := range cfgs { - sources = append(sources, s) - } - - *cfg = aws.Config{ - Logger: logging.NewStandardLogger(os.Stderr), - ConfigSources: sources, - } - return nil -} - -// resolveCustomCABundle extracts the first instance of a custom CA bundle filename -// from the external configurations. It will update the HTTP Client's builder -// to be configured with the custom CA bundle. -// -// Config provider used: -// * customCABundleProvider -func resolveCustomCABundle(ctx context.Context, cfg *aws.Config, cfgs configs) error { - pemCerts, found, err := getCustomCABundle(ctx, cfgs) - if err != nil { - // TODO error handling, What is the best way to handle this? - // capture previous errors continue. error out if all errors - return err - } - if !found { - return nil - } - - if cfg.HTTPClient == nil { - cfg.HTTPClient = awshttp.NewBuildableClient() - } - - trOpts, ok := cfg.HTTPClient.(*awshttp.BuildableClient) - if !ok { - return fmt.Errorf("unable to add custom RootCAs HTTPClient, "+ - "has no WithTransportOptions, %T", cfg.HTTPClient) - } - - var appendErr error - client := trOpts.WithTransportOptions(func(tr *http.Transport) { - if tr.TLSClientConfig == nil { - tr.TLSClientConfig = &tls.Config{} - } - if tr.TLSClientConfig.RootCAs == nil { - tr.TLSClientConfig.RootCAs = x509.NewCertPool() - } - - b, err := ioutil.ReadAll(pemCerts) - if err != nil { - appendErr = fmt.Errorf("failed to read custom CA bundle PEM file") - } - - if !tr.TLSClientConfig.RootCAs.AppendCertsFromPEM(b) { - appendErr = fmt.Errorf("failed to load custom CA bundle PEM file") - } - }) - if appendErr != nil { - return appendErr - } - - cfg.HTTPClient = client - return err -} - -// resolveRegion extracts the first instance of a Region from the configs slice. -// -// Config providers used: -// * regionProvider -func resolveRegion(ctx context.Context, cfg *aws.Config, configs configs) error { - v, found, err := getRegion(ctx, configs) - if err != nil { - // TODO error handling, What is the best way to handle this? - // capture previous errors continue. error out if all errors - return err - } - if !found { - return nil - } - - cfg.Region = v - return nil -} - -func resolveBaseEndpoint(ctx context.Context, cfg *aws.Config, configs configs) error { - var downcastCfgSources []interface{} - for _, cs := range configs { - downcastCfgSources = append(downcastCfgSources, interface{}(cs)) - } - - if val, found, err := GetIgnoreConfiguredEndpoints(ctx, downcastCfgSources); found && val && err == nil { - cfg.BaseEndpoint = nil - return nil - } - - v, found, err := getBaseEndpoint(ctx, configs) - if err != nil { - return err - } - - if !found { - return nil - } - cfg.BaseEndpoint = aws.String(v) - return nil -} - -// resolveAppID extracts the sdk app ID from the configs slice's SharedConfig or env var -func resolveAppID(ctx context.Context, cfg *aws.Config, configs configs) error { - ID, _, err := getAppID(ctx, configs) - if err != nil { - return err - } - - cfg.AppID = ID - return nil -} - -// resolveDisableRequestCompression extracts the DisableRequestCompression from the configs slice's -// SharedConfig or EnvConfig -func resolveDisableRequestCompression(ctx context.Context, cfg *aws.Config, configs configs) error { - disable, _, err := getDisableRequestCompression(ctx, configs) - if err != nil { - return err - } - - cfg.DisableRequestCompression = disable - return nil -} - -// resolveRequestMinCompressSizeBytes extracts the RequestMinCompressSizeBytes from the configs slice's -// SharedConfig or EnvConfig -func resolveRequestMinCompressSizeBytes(ctx context.Context, cfg *aws.Config, configs configs) error { - minBytes, found, err := getRequestMinCompressSizeBytes(ctx, configs) - if err != nil { - return err - } - // must set a default min size 10240 if not configured - if !found { - minBytes = 10240 - } - cfg.RequestMinCompressSizeBytes = minBytes - 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 { - if len(cfg.Region) > 0 { - return nil - } - - v, found, err := getDefaultRegion(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.Region = v - - return nil -} - -// resolveHTTPClient extracts the first instance of a HTTPClient and sets `aws.Config.HTTPClient` to the HTTPClient instance -// if one has not been resolved from other sources. -func resolveHTTPClient(ctx context.Context, cfg *aws.Config, configs configs) error { - c, found, err := getHTTPClient(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.HTTPClient = c - return nil -} - -// resolveAPIOptions extracts the first instance of APIOptions and sets `aws.Config.APIOptions` to the resolved API options -// if one has not been resolved from other sources. -func resolveAPIOptions(ctx context.Context, cfg *aws.Config, configs configs) error { - o, found, err := getAPIOptions(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.APIOptions = o - - return nil -} - -// resolveEndpointResolver extracts the first instance of a EndpointResolverFunc from the config slice -// and sets the functions result on the aws.Config.EndpointResolver -func resolveEndpointResolver(ctx context.Context, cfg *aws.Config, configs configs) error { - endpointResolver, found, err := getEndpointResolver(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.EndpointResolver = endpointResolver - - return nil -} - -// resolveEndpointResolver extracts the first instance of a EndpointResolverFunc from the config slice -// and sets the functions result on the aws.Config.EndpointResolver -func resolveEndpointResolverWithOptions(ctx context.Context, cfg *aws.Config, configs configs) error { - endpointResolver, found, err := getEndpointResolverWithOptions(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.EndpointResolverWithOptions = endpointResolver - - return nil -} - -func resolveLogger(ctx context.Context, cfg *aws.Config, configs configs) error { - logger, found, err := getLogger(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.Logger = logger - - return nil -} - -func resolveClientLogMode(ctx context.Context, cfg *aws.Config, configs configs) error { - mode, found, err := getClientLogMode(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.ClientLogMode = mode - - return nil -} - -func resolveRetryer(ctx context.Context, cfg *aws.Config, configs configs) error { - retryer, found, err := getRetryer(ctx, configs) - if err != nil { - return err - } - - if found { - cfg.Retryer = retryer - return nil - } - - // Only load the retry options if a custom retryer has not be specified. - if err = resolveRetryMaxAttempts(ctx, cfg, configs); err != nil { - return err - } - return resolveRetryMode(ctx, cfg, configs) -} - -func resolveEC2IMDSRegion(ctx context.Context, cfg *aws.Config, configs configs) error { - if len(cfg.Region) > 0 { - return nil - } - - region, found, err := getEC2IMDSRegion(ctx, configs) - if err != nil { - return err - } - if !found { - return nil - } - - cfg.Region = region - - return nil -} - -func resolveDefaultsModeOptions(ctx context.Context, cfg *aws.Config, configs configs) error { - defaultsMode, found, err := getDefaultsMode(ctx, configs) - if err != nil { - return err - } - if !found { - defaultsMode = aws.DefaultsModeLegacy - } - - var environment aws.RuntimeEnvironment - if defaultsMode == aws.DefaultsModeAuto { - envConfig, _, _ := getAWSConfigSources(configs) - - client, found, err := getDefaultsModeIMDSClient(ctx, configs) - if err != nil { - return err - } - if !found { - client = imds.NewFromConfig(*cfg) - } - - environment, err = resolveDefaultsModeRuntimeEnvironment(ctx, envConfig, client) - if err != nil { - return err - } - } - - cfg.DefaultsMode = defaultsMode - cfg.RuntimeEnvironment = environment - - return nil -} - -func resolveRetryMaxAttempts(ctx context.Context, cfg *aws.Config, configs configs) error { - maxAttempts, found, err := getRetryMaxAttempts(ctx, configs) - if err != nil || !found { - return err - } - cfg.RetryMaxAttempts = maxAttempts - - return nil -} - -func resolveRetryMode(ctx context.Context, cfg *aws.Config, configs configs) error { - retryMode, found, err := getRetryMode(ctx, configs) - if err != nil || !found { - return err - } - cfg.RetryMode = retryMode - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_bearer_token.go b/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_bearer_token.go deleted file mode 100644 index a8ebb3c0..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_bearer_token.go +++ /dev/null @@ -1,122 +0,0 @@ -package config - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" - "github.com/aws/aws-sdk-go-v2/service/ssooidc" - smithybearer "github.com/aws/smithy-go/auth/bearer" -) - -// resolveBearerAuthToken extracts a token provider from the config sources. -// -// If an explicit bearer authentication token provider is not found the -// resolver will fallback to resolving token provider via other config sources -// such as SharedConfig. -func resolveBearerAuthToken(ctx context.Context, cfg *aws.Config, configs configs) error { - found, err := resolveBearerAuthTokenProvider(ctx, cfg, configs) - if found || err != nil { - return err - } - - return resolveBearerAuthTokenProviderChain(ctx, cfg, configs) -} - -// resolveBearerAuthTokenProvider extracts the first instance of -// BearerAuthTokenProvider from the config sources. -// -// The resolved BearerAuthTokenProvider will be wrapped in a cache to ensure -// the Token is only refreshed when needed. This also protects the -// TokenProvider so it can be used concurrently. -// -// Config providers used: -// * bearerAuthTokenProviderProvider -func resolveBearerAuthTokenProvider(ctx context.Context, cfg *aws.Config, configs configs) (bool, error) { - tokenProvider, found, err := getBearerAuthTokenProvider(ctx, configs) - if !found || err != nil { - return false, err - } - - cfg.BearerAuthTokenProvider, err = wrapWithBearerAuthTokenCache( - ctx, configs, tokenProvider) - if err != nil { - return false, err - } - - return true, nil -} - -func resolveBearerAuthTokenProviderChain(ctx context.Context, cfg *aws.Config, configs configs) (err error) { - _, sharedConfig, _ := getAWSConfigSources(configs) - - var provider smithybearer.TokenProvider - - if sharedConfig.SSOSession != nil { - provider, err = resolveBearerAuthSSOTokenProvider( - ctx, cfg, sharedConfig.SSOSession, configs) - } - - if err == nil && provider != nil { - cfg.BearerAuthTokenProvider, err = wrapWithBearerAuthTokenCache( - ctx, configs, provider) - } - - return err -} - -func resolveBearerAuthSSOTokenProvider(ctx context.Context, cfg *aws.Config, session *SSOSession, configs configs) (*ssocreds.SSOTokenProvider, error) { - ssoTokenProviderOptionsFn, found, err := getSSOTokenProviderOptions(ctx, configs) - if err != nil { - return nil, fmt.Errorf("failed to get SSOTokenProviderOptions from config sources, %w", err) - } - - var optFns []func(*ssocreds.SSOTokenProviderOptions) - if found { - optFns = append(optFns, ssoTokenProviderOptionsFn) - } - - cachePath, err := ssocreds.StandardCachedTokenFilepath(session.Name) - if err != nil { - return nil, fmt.Errorf("failed to get SSOTokenProvider's cache path, %w", err) - } - - client := ssooidc.NewFromConfig(*cfg) - provider := ssocreds.NewSSOTokenProvider(client, cachePath, optFns...) - - return provider, nil -} - -// wrapWithBearerAuthTokenCache will wrap provider with an smithy-go -// bearer/auth#TokenCache with the provided options if the provider is not -// already a TokenCache. -func wrapWithBearerAuthTokenCache( - ctx context.Context, - cfgs configs, - provider smithybearer.TokenProvider, - optFns ...func(*smithybearer.TokenCacheOptions), -) (smithybearer.TokenProvider, error) { - _, ok := provider.(*smithybearer.TokenCache) - if ok { - return provider, nil - } - - tokenCacheConfigOptions, optionsFound, err := getBearerAuthTokenCacheOptions(ctx, cfgs) - if err != nil { - return nil, err - } - - opts := make([]func(*smithybearer.TokenCacheOptions), 0, 2+len(optFns)) - opts = append(opts, func(o *smithybearer.TokenCacheOptions) { - o.RefreshBeforeExpires = 5 * time.Minute - o.RetrieveBearerTokenTimeout = 30 * time.Second - }) - opts = append(opts, optFns...) - if optionsFound { - opts = append(opts, tokenCacheConfigOptions) - } - - return smithybearer.NewTokenCache(provider, opts...), nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_credentials.go b/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_credentials.go deleted file mode 100644 index 89368520..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/resolve_credentials.go +++ /dev/null @@ -1,566 +0,0 @@ -package config - -import ( - "context" - "fmt" - "io/ioutil" - "net" - "net/url" - "os" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/credentials" - "github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds" - "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" - "github.com/aws/aws-sdk-go-v2/service/sso" - "github.com/aws/aws-sdk-go-v2/service/ssooidc" - "github.com/aws/aws-sdk-go-v2/service/sts" -) - -const ( - // valid credential source values - credSourceEc2Metadata = "Ec2InstanceMetadata" - credSourceEnvironment = "Environment" - credSourceECSContainer = "EcsContainer" - httpProviderAuthFileEnvVar = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE" -) - -// direct representation of the IPv4 address for the ECS container -// "169.254.170.2" -var ecsContainerIPv4 net.IP = []byte{ - 169, 254, 170, 2, -} - -// direct representation of the IPv4 address for the EKS container -// "169.254.170.23" -var eksContainerIPv4 net.IP = []byte{ - 169, 254, 170, 23, -} - -// direct representation of the IPv6 address for the EKS container -// "fd00:ec2::23" -var eksContainerIPv6 net.IP = []byte{ - 0xFD, 0, 0xE, 0xC2, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0x23, -} - -var ( - ecsContainerEndpoint = "http://169.254.170.2" // not constant to allow for swapping during unit-testing -) - -// resolveCredentials extracts a credential provider from slice of config -// sources. -// -// If an explicit credential provider is not found the resolver will fallback -// to resolving credentials by extracting a credential provider from EnvConfig -// and SharedConfig. -func resolveCredentials(ctx context.Context, cfg *aws.Config, configs configs) error { - found, err := resolveCredentialProvider(ctx, cfg, configs) - if found || err != nil { - return err - } - - return resolveCredentialChain(ctx, cfg, configs) -} - -// resolveCredentialProvider extracts the first instance of Credentials from the -// config slices. -// -// The resolved CredentialProvider will be wrapped in a cache to ensure the -// credentials are only refreshed when needed. This also protects the -// credential provider to be used concurrently. -// -// Config providers used: -// * credentialsProviderProvider -func resolveCredentialProvider(ctx context.Context, cfg *aws.Config, configs configs) (bool, error) { - credProvider, found, err := getCredentialsProvider(ctx, configs) - if !found || err != nil { - return false, err - } - - cfg.Credentials, err = wrapWithCredentialsCache(ctx, configs, credProvider) - if err != nil { - return false, err - } - - return true, nil -} - -// resolveCredentialChain resolves a credential provider chain using EnvConfig -// and SharedConfig if present in the slice of provided configs. -// -// The resolved CredentialProvider will be wrapped in a cache to ensure the -// credentials are only refreshed when needed. This also protects the -// credential provider to be used concurrently. -func resolveCredentialChain(ctx context.Context, cfg *aws.Config, configs configs) (err error) { - envConfig, sharedConfig, other := getAWSConfigSources(configs) - - // When checking if a profile was specified programmatically we should only consider the "other" - // configuration sources that have been provided. This ensures we correctly honor the expected credential - // hierarchy. - _, sharedProfileSet, err := getSharedConfigProfile(ctx, other) - if err != nil { - return err - } - - switch { - case sharedProfileSet: - err = resolveCredsFromProfile(ctx, cfg, envConfig, sharedConfig, other) - case envConfig.Credentials.HasKeys(): - cfg.Credentials = credentials.StaticCredentialsProvider{Value: envConfig.Credentials} - case len(envConfig.WebIdentityTokenFilePath) > 0: - err = assumeWebIdentity(ctx, cfg, envConfig.WebIdentityTokenFilePath, envConfig.RoleARN, envConfig.RoleSessionName, configs) - default: - err = resolveCredsFromProfile(ctx, cfg, envConfig, sharedConfig, other) - } - if err != nil { - return err - } - - // Wrap the resolved provider in a cache so the SDK will cache credentials. - cfg.Credentials, err = wrapWithCredentialsCache(ctx, configs, cfg.Credentials) - if err != nil { - return err - } - - return nil -} - -func resolveCredsFromProfile(ctx context.Context, cfg *aws.Config, envConfig *EnvConfig, sharedConfig *SharedConfig, configs configs) (err error) { - - switch { - case sharedConfig.Source != nil: - // Assume IAM role with credentials source from a different profile. - err = resolveCredsFromProfile(ctx, cfg, envConfig, sharedConfig.Source, configs) - - case sharedConfig.Credentials.HasKeys(): - // Static Credentials from Shared Config/Credentials file. - cfg.Credentials = credentials.StaticCredentialsProvider{ - Value: sharedConfig.Credentials, - } - - case len(sharedConfig.CredentialSource) != 0: - err = resolveCredsFromSource(ctx, cfg, envConfig, sharedConfig, configs) - - case len(sharedConfig.WebIdentityTokenFile) != 0: - // Credentials from Assume Web Identity token require an IAM Role, and - // that roll will be assumed. May be wrapped with another assume role - // via SourceProfile. - return assumeWebIdentity(ctx, cfg, sharedConfig.WebIdentityTokenFile, sharedConfig.RoleARN, sharedConfig.RoleSessionName, configs) - - case sharedConfig.hasSSOConfiguration(): - err = resolveSSOCredentials(ctx, cfg, sharedConfig, configs) - - case len(sharedConfig.CredentialProcess) != 0: - // Get credentials from CredentialProcess - err = processCredentials(ctx, cfg, sharedConfig, configs) - - case len(envConfig.ContainerCredentialsEndpoint) != 0: - err = resolveLocalHTTPCredProvider(ctx, cfg, envConfig.ContainerCredentialsEndpoint, envConfig.ContainerAuthorizationToken, configs) - - case len(envConfig.ContainerCredentialsRelativePath) != 0: - err = resolveHTTPCredProvider(ctx, cfg, ecsContainerURI(envConfig.ContainerCredentialsRelativePath), envConfig.ContainerAuthorizationToken, configs) - - default: - err = resolveEC2RoleCredentials(ctx, cfg, configs) - } - if err != nil { - return err - } - - if len(sharedConfig.RoleARN) > 0 { - return credsFromAssumeRole(ctx, cfg, sharedConfig, configs) - } - - return nil -} - -func resolveSSOCredentials(ctx context.Context, cfg *aws.Config, sharedConfig *SharedConfig, configs configs) error { - if err := sharedConfig.validateSSOConfiguration(); err != nil { - return err - } - - var options []func(*ssocreds.Options) - v, found, err := getSSOProviderOptions(ctx, configs) - if err != nil { - return err - } - if found { - options = append(options, v) - } - - cfgCopy := cfg.Copy() - - if sharedConfig.SSOSession != nil { - ssoTokenProviderOptionsFn, found, err := getSSOTokenProviderOptions(ctx, configs) - if err != nil { - return fmt.Errorf("failed to get SSOTokenProviderOptions from config sources, %w", err) - } - var optFns []func(*ssocreds.SSOTokenProviderOptions) - if found { - optFns = append(optFns, ssoTokenProviderOptionsFn) - } - cfgCopy.Region = sharedConfig.SSOSession.SSORegion - cachedPath, err := ssocreds.StandardCachedTokenFilepath(sharedConfig.SSOSession.Name) - if err != nil { - return err - } - oidcClient := ssooidc.NewFromConfig(cfgCopy) - tokenProvider := ssocreds.NewSSOTokenProvider(oidcClient, cachedPath, optFns...) - options = append(options, func(o *ssocreds.Options) { - o.SSOTokenProvider = tokenProvider - o.CachedTokenFilepath = cachedPath - }) - } else { - cfgCopy.Region = sharedConfig.SSORegion - } - - cfg.Credentials = ssocreds.New(sso.NewFromConfig(cfgCopy), sharedConfig.SSOAccountID, sharedConfig.SSORoleName, sharedConfig.SSOStartURL, options...) - - return nil -} - -func ecsContainerURI(path string) string { - return fmt.Sprintf("%s%s", ecsContainerEndpoint, path) -} - -func processCredentials(ctx context.Context, cfg *aws.Config, sharedConfig *SharedConfig, configs configs) error { - var opts []func(*processcreds.Options) - - options, found, err := getProcessCredentialOptions(ctx, configs) - if err != nil { - return err - } - if found { - opts = append(opts, options) - } - - cfg.Credentials = processcreds.NewProvider(sharedConfig.CredentialProcess, opts...) - - return nil -} - -// isAllowedHost allows host to be loopback or known ECS/EKS container IPs -// -// host can either be an IP address OR an unresolved hostname - resolution will -// be automatically performed in the latter case -func isAllowedHost(host string) (bool, error) { - if ip := net.ParseIP(host); ip != nil { - return isIPAllowed(ip), nil - } - - addrs, err := lookupHostFn(host) - if err != nil { - return false, err - } - - for _, addr := range addrs { - if ip := net.ParseIP(addr); ip == nil || !isIPAllowed(ip) { - return false, nil - } - } - - return true, nil -} - -func isIPAllowed(ip net.IP) bool { - return ip.IsLoopback() || - ip.Equal(ecsContainerIPv4) || - ip.Equal(eksContainerIPv4) || - ip.Equal(eksContainerIPv6) -} - -func resolveLocalHTTPCredProvider(ctx context.Context, cfg *aws.Config, endpointURL, authToken string, configs configs) error { - var resolveErr error - - parsed, err := url.Parse(endpointURL) - if err != nil { - resolveErr = fmt.Errorf("invalid URL, %w", err) - } else { - host := parsed.Hostname() - if len(host) == 0 { - resolveErr = fmt.Errorf("unable to parse host from local HTTP cred provider URL") - } else if parsed.Scheme == "http" { - if isAllowedHost, allowHostErr := isAllowedHost(host); allowHostErr != nil { - resolveErr = fmt.Errorf("failed to resolve host %q, %v", host, allowHostErr) - } else if !isAllowedHost { - resolveErr = fmt.Errorf("invalid endpoint host, %q, only loopback/ecs/eks hosts are allowed", host) - } - } - } - - if resolveErr != nil { - return resolveErr - } - - return resolveHTTPCredProvider(ctx, cfg, endpointURL, authToken, configs) -} - -func resolveHTTPCredProvider(ctx context.Context, cfg *aws.Config, url, authToken string, configs configs) error { - optFns := []func(*endpointcreds.Options){ - func(options *endpointcreds.Options) { - if len(authToken) != 0 { - options.AuthorizationToken = authToken - } - if authFilePath := os.Getenv(httpProviderAuthFileEnvVar); authFilePath != "" { - options.AuthorizationTokenProvider = endpointcreds.TokenProviderFunc(func() (string, error) { - var contents []byte - var err error - if contents, err = ioutil.ReadFile(authFilePath); err != nil { - return "", fmt.Errorf("failed to read authorization token from %v: %v", authFilePath, err) - } - return string(contents), nil - }) - } - options.APIOptions = cfg.APIOptions - if cfg.Retryer != nil { - options.Retryer = cfg.Retryer() - } - }, - } - - optFn, found, err := getEndpointCredentialProviderOptions(ctx, configs) - if err != nil { - return err - } - if found { - optFns = append(optFns, optFn) - } - - provider := endpointcreds.New(url, optFns...) - - cfg.Credentials, err = wrapWithCredentialsCache(ctx, configs, provider, func(options *aws.CredentialsCacheOptions) { - options.ExpiryWindow = 5 * time.Minute - }) - if err != nil { - return err - } - - return nil -} - -func resolveCredsFromSource(ctx context.Context, cfg *aws.Config, envConfig *EnvConfig, sharedCfg *SharedConfig, configs configs) (err error) { - switch sharedCfg.CredentialSource { - case credSourceEc2Metadata: - return resolveEC2RoleCredentials(ctx, cfg, configs) - - case credSourceEnvironment: - cfg.Credentials = credentials.StaticCredentialsProvider{Value: envConfig.Credentials} - - case credSourceECSContainer: - if len(envConfig.ContainerCredentialsRelativePath) == 0 { - return fmt.Errorf("EcsContainer was specified as the credential_source, but 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI' was not set") - } - return resolveHTTPCredProvider(ctx, cfg, ecsContainerURI(envConfig.ContainerCredentialsRelativePath), envConfig.ContainerAuthorizationToken, configs) - - default: - return fmt.Errorf("credential_source values must be EcsContainer, Ec2InstanceMetadata, or Environment") - } - - return nil -} - -func resolveEC2RoleCredentials(ctx context.Context, cfg *aws.Config, configs configs) error { - optFns := make([]func(*ec2rolecreds.Options), 0, 2) - - optFn, found, err := getEC2RoleCredentialProviderOptions(ctx, configs) - if err != nil { - return err - } - if found { - optFns = append(optFns, optFn) - } - - optFns = append(optFns, func(o *ec2rolecreds.Options) { - // Only define a client from config if not already defined. - if o.Client == nil { - o.Client = imds.NewFromConfig(*cfg) - } - }) - - provider := ec2rolecreds.New(optFns...) - - cfg.Credentials, err = wrapWithCredentialsCache(ctx, configs, provider) - if err != nil { - return err - } - - return nil -} - -func getAWSConfigSources(cfgs configs) (*EnvConfig, *SharedConfig, configs) { - var ( - envConfig *EnvConfig - sharedConfig *SharedConfig - other configs - ) - - for i := range cfgs { - switch c := cfgs[i].(type) { - case EnvConfig: - if envConfig == nil { - envConfig = &c - } - case *EnvConfig: - if envConfig == nil { - envConfig = c - } - case SharedConfig: - if sharedConfig == nil { - sharedConfig = &c - } - case *SharedConfig: - if envConfig == nil { - sharedConfig = c - } - default: - other = append(other, c) - } - } - - if envConfig == nil { - envConfig = &EnvConfig{} - } - - if sharedConfig == nil { - sharedConfig = &SharedConfig{} - } - - return envConfig, sharedConfig, other -} - -// AssumeRoleTokenProviderNotSetError is an error returned when creating a -// session when the MFAToken option is not set when shared config is configured -// load assume a role with an MFA token. -type AssumeRoleTokenProviderNotSetError struct{} - -// Error is the error message -func (e AssumeRoleTokenProviderNotSetError) Error() string { - return fmt.Sprintf("assume role with MFA enabled, but AssumeRoleTokenProvider session option not set.") -} - -func assumeWebIdentity(ctx context.Context, cfg *aws.Config, filepath string, roleARN, sessionName string, configs configs) error { - if len(filepath) == 0 { - return fmt.Errorf("token file path is not set") - } - - optFns := []func(*stscreds.WebIdentityRoleOptions){ - func(options *stscreds.WebIdentityRoleOptions) { - options.RoleSessionName = sessionName - }, - } - - optFn, found, err := getWebIdentityCredentialProviderOptions(ctx, configs) - if err != nil { - return err - } - - if found { - optFns = append(optFns, optFn) - } - - opts := stscreds.WebIdentityRoleOptions{ - RoleARN: roleARN, - } - - for _, fn := range optFns { - fn(&opts) - } - - if len(opts.RoleARN) == 0 { - return fmt.Errorf("role ARN is not set") - } - - client := opts.Client - if client == nil { - client = sts.NewFromConfig(*cfg) - } - - provider := stscreds.NewWebIdentityRoleProvider(client, roleARN, stscreds.IdentityTokenFile(filepath), optFns...) - - cfg.Credentials = provider - - return nil -} - -func credsFromAssumeRole(ctx context.Context, cfg *aws.Config, sharedCfg *SharedConfig, configs configs) (err error) { - optFns := []func(*stscreds.AssumeRoleOptions){ - func(options *stscreds.AssumeRoleOptions) { - options.RoleSessionName = sharedCfg.RoleSessionName - if sharedCfg.RoleDurationSeconds != nil { - if *sharedCfg.RoleDurationSeconds/time.Minute > 15 { - options.Duration = *sharedCfg.RoleDurationSeconds - } - } - // Assume role with external ID - if len(sharedCfg.ExternalID) > 0 { - options.ExternalID = aws.String(sharedCfg.ExternalID) - } - - // Assume role with MFA - if len(sharedCfg.MFASerial) != 0 { - options.SerialNumber = aws.String(sharedCfg.MFASerial) - } - }, - } - - optFn, found, err := getAssumeRoleCredentialProviderOptions(ctx, configs) - if err != nil { - return err - } - if found { - optFns = append(optFns, optFn) - } - - { - // Synthesize options early to validate configuration errors sooner to ensure a token provider - // is present if the SerialNumber was set. - var o stscreds.AssumeRoleOptions - for _, fn := range optFns { - fn(&o) - } - if o.TokenProvider == nil && o.SerialNumber != nil { - return AssumeRoleTokenProviderNotSetError{} - } - } - - cfg.Credentials = stscreds.NewAssumeRoleProvider(sts.NewFromConfig(*cfg), sharedCfg.RoleARN, optFns...) - - return nil -} - -// wrapWithCredentialsCache will wrap provider with an aws.CredentialsCache -// with the provided options if the provider is not already a -// aws.CredentialsCache. -func wrapWithCredentialsCache( - ctx context.Context, - cfgs configs, - provider aws.CredentialsProvider, - optFns ...func(options *aws.CredentialsCacheOptions), -) (aws.CredentialsProvider, error) { - _, ok := provider.(*aws.CredentialsCache) - if ok { - return provider, nil - } - - credCacheOptions, optionsFound, err := getCredentialsCacheOptionsProvider(ctx, cfgs) - if err != nil { - return nil, err - } - - // force allocation of a new slice if the additional options are - // needed, to prevent overwriting the passed in slice of options. - optFns = optFns[:len(optFns):len(optFns)] - if optionsFound { - optFns = append(optFns, credCacheOptions) - } - - return aws.NewCredentialsCache(provider, optFns...), nil -} 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 deleted file mode 100644 index c546cb7d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/config/shared_config.go +++ /dev/null @@ -1,1584 +0,0 @@ -package config - -import ( - "bytes" - "context" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" - "github.com/aws/aws-sdk-go-v2/internal/ini" - "github.com/aws/aws-sdk-go-v2/internal/shareddefaults" - "github.com/aws/smithy-go/logging" - smithyrequestcompression "github.com/aws/smithy-go/private/requestcompression" -) - -const ( - // Prefix to use for filtering profiles. The profile prefix should only - // exist in the shared config file, not the credentials file. - profilePrefix = `profile ` - - // Prefix to be used for SSO sections. These are supposed to only exist in - // the shared config file, not the credentials file. - ssoSectionPrefix = `sso-session ` - - // Prefix for services section. It is referenced in profile via the services - // parameter to configure clients for service-specific parameters. - servicesPrefix = `services ` - - // string equivalent for boolean - endpointDiscoveryDisabled = `false` - endpointDiscoveryEnabled = `true` - endpointDiscoveryAuto = `auto` - - // Static Credentials group - accessKeyIDKey = `aws_access_key_id` // group required - secretAccessKey = `aws_secret_access_key` // group required - sessionTokenKey = `aws_session_token` // optional - - // Assume Role Credentials group - roleArnKey = `role_arn` // group required - sourceProfileKey = `source_profile` // group required - credentialSourceKey = `credential_source` // group required (or source_profile) - externalIDKey = `external_id` // optional - mfaSerialKey = `mfa_serial` // optional - roleSessionNameKey = `role_session_name` // optional - roleDurationSecondsKey = "duration_seconds" // optional - - // AWS Single Sign-On (AWS SSO) group - ssoSessionNameKey = "sso_session" - - ssoRegionKey = "sso_region" - ssoStartURLKey = "sso_start_url" - - ssoAccountIDKey = "sso_account_id" - ssoRoleNameKey = "sso_role_name" - - // Additional Config fields - regionKey = `region` - - // endpoint discovery group - enableEndpointDiscoveryKey = `endpoint_discovery_enabled` // optional - - // External Credential process - credentialProcessKey = `credential_process` // optional - - // Web Identity Token File - webIdentityTokenFileKey = `web_identity_token_file` // optional - - // S3 ARN Region Usage - s3UseARNRegionKey = "s3_use_arn_region" - - ec2MetadataServiceEndpointModeKey = "ec2_metadata_service_endpoint_mode" - - ec2MetadataServiceEndpointKey = "ec2_metadata_service_endpoint" - - ec2MetadataV1DisabledKey = "ec2_metadata_v1_disabled" - - // Use DualStack Endpoint Resolution - useDualStackEndpoint = "use_dualstack_endpoint" - - // DefaultSharedConfigProfile is the default profile to be used when - // loading configuration from the config files if another profile name - // is not provided. - DefaultSharedConfigProfile = `default` - - // S3 Disable Multi-Region AccessPoints - s3DisableMultiRegionAccessPointsKey = `s3_disable_multiregion_access_points` - - useFIPSEndpointKey = "use_fips_endpoint" - - defaultsModeKey = "defaults_mode" - - // Retry options - retryMaxAttemptsKey = "max_attempts" - retryModeKey = "retry_mode" - - caBundleKey = "ca_bundle" - - sdkAppID = "sdk_ua_app_id" - - ignoreConfiguredEndpoints = "ignore_configured_endpoint_urls" - - endpointURL = "endpoint_url" - - servicesSectionKey = "services" - - disableRequestCompression = "disable_request_compression" - requestMinCompressionSizeBytes = "request_min_compression_size_bytes" - - s3DisableExpressSessionAuthKey = "s3_disable_express_session_auth" -) - -// defaultSharedConfigProfile allows for swapping the default profile for testing -var defaultSharedConfigProfile = DefaultSharedConfigProfile - -// DefaultSharedCredentialsFilename returns the SDK's default file path -// for the shared credentials file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/credentials -// - Windows: %USERPROFILE%\.aws\credentials -func DefaultSharedCredentialsFilename() string { - return filepath.Join(shareddefaults.UserHomeDir(), ".aws", "credentials") -} - -// DefaultSharedConfigFilename returns the SDK's default file path for -// the shared config file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/config -// - Windows: %USERPROFILE%\.aws\config -func DefaultSharedConfigFilename() string { - return filepath.Join(shareddefaults.UserHomeDir(), ".aws", "config") -} - -// DefaultSharedConfigFiles is a slice of the default shared config files that -// the will be used in order to load the SharedConfig. -var DefaultSharedConfigFiles = []string{ - DefaultSharedConfigFilename(), -} - -// DefaultSharedCredentialsFiles is a slice of the default shared credentials -// files that the will be used in order to load the SharedConfig. -var DefaultSharedCredentialsFiles = []string{ - DefaultSharedCredentialsFilename(), -} - -// SSOSession provides the shared configuration parameters of the sso-session -// section. -type SSOSession struct { - Name string - SSORegion string - SSOStartURL string -} - -func (s *SSOSession) setFromIniSection(section ini.Section) { - updateString(&s.Name, section, ssoSessionNameKey) - updateString(&s.SSORegion, section, ssoRegionKey) - updateString(&s.SSOStartURL, section, ssoStartURLKey) -} - -// Services contains values configured in the services section -// of the AWS configuration file. -type Services struct { - // Services section values - // {"serviceId": {"key": "value"}} - // e.g. {"s3": {"endpoint_url": "example.com"}} - ServiceValues map[string]map[string]string -} - -func (s *Services) setFromIniSection(section ini.Section) { - if s.ServiceValues == nil { - s.ServiceValues = make(map[string]map[string]string) - } - for _, service := range section.List() { - s.ServiceValues[service] = section.Map(service) - } -} - -// SharedConfig represents the configuration fields of the SDK config files. -type SharedConfig struct { - Profile string - - // Credentials values from the config file. Both aws_access_key_id - // and aws_secret_access_key must be provided together in the same file - // to be considered valid. The values will be ignored if not a complete group. - // aws_session_token is an optional field that can be provided if both of the - // other two fields are also provided. - // - // aws_access_key_id - // aws_secret_access_key - // aws_session_token - Credentials aws.Credentials - - CredentialSource string - CredentialProcess string - WebIdentityTokenFile string - - // SSO session options - SSOSessionName string - SSOSession *SSOSession - - // Legacy SSO session options - SSORegion string - SSOStartURL string - - // SSO fields not used - SSOAccountID string - SSORoleName string - - RoleARN string - ExternalID string - MFASerial string - RoleSessionName string - RoleDurationSeconds *time.Duration - - SourceProfileName string - Source *SharedConfig - - // Region is the region the SDK should use for looking up AWS service endpoints - // and signing requests. - // - // region = us-west-2 - Region string - - // EnableEndpointDiscovery can be enabled or disabled in the shared config - // by setting endpoint_discovery_enabled to true, or false respectively. - // - // endpoint_discovery_enabled = true - EnableEndpointDiscovery aws.EndpointDiscoveryEnableState - - // Specifies if the S3 service should allow ARNs to direct the region - // the client's requests are sent to. - // - // s3_use_arn_region=true - S3UseARNRegion *bool - - // Specifies the EC2 Instance Metadata Service default endpoint selection - // mode (IPv4 or IPv6) - // - // ec2_metadata_service_endpoint_mode=IPv6 - EC2IMDSEndpointMode imds.EndpointModeState - - // Specifies the EC2 Instance Metadata Service endpoint to use. If - // specified it overrides EC2IMDSEndpointMode. - // - // ec2_metadata_service_endpoint=http://fd00:ec2::254 - EC2IMDSEndpoint string - - // Specifies that IMDS clients should not fallback to IMDSv1 if token - // requests fail. - // - // ec2_metadata_v1_disabled=true - EC2IMDSv1Disabled *bool - - // Specifies if the S3 service should disable support for Multi-Region - // access-points - // - // s3_disable_multiregion_access_points=true - S3DisableMultiRegionAccessPoints *bool - - // Specifies that SDK clients must resolve a dual-stack endpoint for - // services. - // - // use_dualstack_endpoint=true - UseDualStackEndpoint aws.DualStackEndpointState - - // Specifies that SDK clients must resolve a FIPS endpoint for - // services. - // - // use_fips_endpoint=true - UseFIPSEndpoint aws.FIPSEndpointState - - // Specifies which defaults mode should be used by services. - // - // defaults_mode=standard - DefaultsMode aws.DefaultsMode - - // Specifies the maximum number attempts an API client will call an - // operation that fails with a retryable error. - // - // max_attempts=3 - RetryMaxAttempts int - - // Specifies the retry model the API client will be created with. - // - // retry_mode=standard - RetryMode aws.RetryMode - - // Sets the path to a custom Credentials Authority (CA) Bundle PEM file - // that the SDK will use instead of the system's root CA bundle. Only use - // this if you want to configure the SDK to use a custom set of CAs. - // - // Enabling this option will attempt to merge the Transport into the SDK's - // HTTP client. If the client's Transport is not a http.Transport an error - // will be returned. If the Transport's TLS config is set this option will - // cause the SDK to overwrite the Transport's TLS config's RootCAs value. - // - // Setting a custom HTTPClient in the aws.Config options will override this - // setting. To use this option and custom HTTP client, the HTTP client - // needs to be provided when creating the config. Not the service client. - // - // ca_bundle=$HOME/my_custom_ca_bundle - CustomCABundle string - - // aws sdk app ID that can be added to user agent header string - AppID string - - // Flag used to disable configured endpoints. - IgnoreConfiguredEndpoints *bool - - // Value to contain configured endpoints to be propagated to - // corresponding endpoint resolution field. - BaseEndpoint string - - // Services section config. - ServicesSectionName string - Services Services - - // determine if request compression is allowed, default to false - // retrieved from config file's profile field disable_request_compression - DisableRequestCompression *bool - - // inclusive threshold request body size to trigger compression, - // default to 10240 and must be within 0 and 10485760 bytes inclusive - // retrieved from config file's profile field request_min_compression_size_bytes - RequestMinCompressSizeBytes *int64 - - // Whether S3Express auth is disabled. - // - // This will NOT prevent requests from being made to S3Express buckets, it - // will only bypass the modified endpoint routing and signing behaviors - // associated with the feature. - S3DisableExpressAuth *bool -} - -func (c SharedConfig) getDefaultsMode(ctx context.Context) (value aws.DefaultsMode, ok bool, err error) { - if len(c.DefaultsMode) == 0 { - return "", false, nil - } - - return c.DefaultsMode, true, nil -} - -// GetRetryMaxAttempts returns the maximum number of attempts an API client -// created Retryer should attempt an operation call before failing. -func (c SharedConfig) GetRetryMaxAttempts(ctx context.Context) (value int, ok bool, err error) { - if c.RetryMaxAttempts == 0 { - return 0, false, nil - } - - return c.RetryMaxAttempts, true, nil -} - -// GetRetryMode returns the model the API client should create its Retryer in. -func (c SharedConfig) GetRetryMode(ctx context.Context) (value aws.RetryMode, ok bool, err error) { - if len(c.RetryMode) == 0 { - return "", false, nil - } - - return c.RetryMode, true, nil -} - -// GetS3UseARNRegion returns if the S3 service should allow ARNs to direct the region -// the client's requests are sent to. -func (c SharedConfig) GetS3UseARNRegion(ctx context.Context) (value, ok bool, err error) { - if c.S3UseARNRegion == nil { - return false, false, nil - } - - return *c.S3UseARNRegion, true, nil -} - -// GetEnableEndpointDiscovery returns if the enable_endpoint_discovery is set. -func (c SharedConfig) GetEnableEndpointDiscovery(ctx context.Context) (value aws.EndpointDiscoveryEnableState, ok bool, err error) { - if c.EnableEndpointDiscovery == aws.EndpointDiscoveryUnset { - return aws.EndpointDiscoveryUnset, false, nil - } - - return c.EnableEndpointDiscovery, true, nil -} - -// GetS3DisableMultiRegionAccessPoints returns if the S3 service should disable support for Multi-Region -// access-points. -func (c SharedConfig) GetS3DisableMultiRegionAccessPoints(ctx context.Context) (value, ok bool, err error) { - if c.S3DisableMultiRegionAccessPoints == nil { - return false, false, nil - } - - return *c.S3DisableMultiRegionAccessPoints, true, nil -} - -// GetRegion returns the region for the profile if a region is set. -func (c SharedConfig) getRegion(ctx context.Context) (string, bool, error) { - if len(c.Region) == 0 { - return "", false, nil - } - return c.Region, true, nil -} - -// GetCredentialsProvider returns the credentials for a profile if they were set. -func (c SharedConfig) getCredentialsProvider() (aws.Credentials, bool, error) { - return c.Credentials, true, nil -} - -// GetEC2IMDSEndpointMode implements a EC2IMDSEndpointMode option resolver interface. -func (c SharedConfig) GetEC2IMDSEndpointMode() (imds.EndpointModeState, bool, error) { - if c.EC2IMDSEndpointMode == imds.EndpointModeStateUnset { - return imds.EndpointModeStateUnset, false, nil - } - - return c.EC2IMDSEndpointMode, true, nil -} - -// GetEC2IMDSEndpoint implements a EC2IMDSEndpoint option resolver interface. -func (c SharedConfig) GetEC2IMDSEndpoint() (string, bool, error) { - if len(c.EC2IMDSEndpoint) == 0 { - return "", false, nil - } - - return c.EC2IMDSEndpoint, true, nil -} - -// GetEC2IMDSV1FallbackDisabled implements an EC2IMDSV1FallbackDisabled option -// resolver interface. -func (c SharedConfig) GetEC2IMDSV1FallbackDisabled() (bool, bool) { - if c.EC2IMDSv1Disabled == nil { - return false, false - } - - return *c.EC2IMDSv1Disabled, true -} - -// GetUseDualStackEndpoint returns whether the service's dual-stack endpoint should be -// used for requests. -func (c SharedConfig) GetUseDualStackEndpoint(ctx context.Context) (value aws.DualStackEndpointState, found bool, err error) { - if c.UseDualStackEndpoint == aws.DualStackEndpointStateUnset { - return aws.DualStackEndpointStateUnset, false, nil - } - - return c.UseDualStackEndpoint, true, nil -} - -// GetUseFIPSEndpoint returns whether the service's FIPS endpoint should be -// used for requests. -func (c SharedConfig) GetUseFIPSEndpoint(ctx context.Context) (value aws.FIPSEndpointState, found bool, err error) { - if c.UseFIPSEndpoint == aws.FIPSEndpointStateUnset { - return aws.FIPSEndpointStateUnset, false, nil - } - - return c.UseFIPSEndpoint, true, nil -} - -// GetS3DisableExpressAuth returns the configured value for -// [SharedConfig.S3DisableExpressAuth]. -func (c SharedConfig) GetS3DisableExpressAuth() (value, ok bool) { - if c.S3DisableExpressAuth == nil { - return false, false - } - - return *c.S3DisableExpressAuth, true -} - -// GetCustomCABundle returns the custom CA bundle's PEM bytes if the file was -func (c SharedConfig) getCustomCABundle(context.Context) (io.Reader, bool, error) { - if len(c.CustomCABundle) == 0 { - return nil, false, nil - } - - b, err := ioutil.ReadFile(c.CustomCABundle) - if err != nil { - return nil, false, err - } - return bytes.NewReader(b), true, nil -} - -// getAppID returns the sdk app ID if set in shared config profile -func (c SharedConfig) getAppID(context.Context) (string, bool, error) { - return c.AppID, len(c.AppID) > 0, nil -} - -// GetIgnoreConfiguredEndpoints is used in knowing when to disable configured -// endpoints feature. -func (c SharedConfig) GetIgnoreConfiguredEndpoints(context.Context) (bool, bool, error) { - if c.IgnoreConfiguredEndpoints == nil { - return false, false, nil - } - - return *c.IgnoreConfiguredEndpoints, true, nil -} - -func (c SharedConfig) getBaseEndpoint(context.Context) (string, bool, error) { - return c.BaseEndpoint, len(c.BaseEndpoint) > 0, nil -} - -// GetServiceBaseEndpoint is used to retrieve a normalized SDK ID for use -// with configured endpoints. -func (c SharedConfig) GetServiceBaseEndpoint(ctx context.Context, sdkID string) (string, bool, error) { - if service, ok := c.Services.ServiceValues[normalizeShared(sdkID)]; ok { - if endpt, ok := service[endpointURL]; ok { - return endpt, true, nil - } - } - return "", false, nil -} - -func normalizeShared(sdkID string) string { - lower := strings.ToLower(sdkID) - return strings.ReplaceAll(lower, " ", "_") -} - -func (c SharedConfig) getServicesObject(context.Context) (map[string]map[string]string, bool, error) { - return c.Services.ServiceValues, c.Services.ServiceValues != nil, nil -} - -// loadSharedConfigIgnoreNotExist is an alias for loadSharedConfig with the -// addition of ignoring when none of the files exist or when the profile -// is not found in any of the files. -func loadSharedConfigIgnoreNotExist(ctx context.Context, configs configs) (Config, error) { - cfg, err := loadSharedConfig(ctx, configs) - if err != nil { - if _, ok := err.(SharedConfigProfileNotExistError); ok { - return SharedConfig{}, nil - } - return nil, err - } - - return cfg, nil -} - -// loadSharedConfig uses the configs passed in to load the SharedConfig from file -// The file names and profile name are sourced from the configs. -// -// If profile name is not provided DefaultSharedConfigProfile (default) will -// be used. -// -// If shared config filenames are not provided DefaultSharedConfigFiles will -// be used. -// -// Config providers used: -// * sharedConfigProfileProvider -// * sharedConfigFilesProvider -func loadSharedConfig(ctx context.Context, configs configs) (Config, error) { - var profile string - var configFiles []string - var credentialsFiles []string - var ok bool - var err error - - profile, ok, err = getSharedConfigProfile(ctx, configs) - if err != nil { - return nil, err - } - if !ok { - profile = defaultSharedConfigProfile - } - - configFiles, ok, err = getSharedConfigFiles(ctx, configs) - if err != nil { - return nil, err - } - - credentialsFiles, ok, err = getSharedCredentialsFiles(ctx, configs) - if err != nil { - return nil, err - } - - // setup logger if log configuration warning is seti - var logger logging.Logger - logWarnings, found, err := getLogConfigurationWarnings(ctx, configs) - if err != nil { - return SharedConfig{}, err - } - if found && logWarnings { - logger, found, err = getLogger(ctx, configs) - if err != nil { - return SharedConfig{}, err - } - if !found { - logger = logging.NewStandardLogger(os.Stderr) - } - } - - return LoadSharedConfigProfile(ctx, profile, - func(o *LoadSharedConfigOptions) { - o.Logger = logger - o.ConfigFiles = configFiles - o.CredentialsFiles = credentialsFiles - }, - ) -} - -// LoadSharedConfigOptions struct contains optional values that can be used to load the config. -type LoadSharedConfigOptions struct { - - // CredentialsFiles are the shared credentials files - CredentialsFiles []string - - // ConfigFiles are the shared config files - ConfigFiles []string - - // Logger is the logger used to log shared config behavior - Logger logging.Logger -} - -// LoadSharedConfigProfile retrieves the configuration from the list of files -// using the profile provided. The order the files are listed will determine -// precedence. Values in subsequent files will overwrite values defined in -// earlier files. -// -// For example, given two files A and B. Both define credentials. If the order -// of the files are A then B, B's credential values will be used instead of A's. -// -// If config files are not set, SDK will default to using a file at location `.aws/config` if present. -// If credentials files are not set, SDK will default to using a file at location `.aws/credentials` if present. -// No default files are set, if files set to an empty slice. -// -// You can read more about shared config and credentials file location at -// https://docs.aws.amazon.com/credref/latest/refdocs/file-location.html#file-location -func LoadSharedConfigProfile(ctx context.Context, profile string, optFns ...func(*LoadSharedConfigOptions)) (SharedConfig, error) { - var option LoadSharedConfigOptions - for _, fn := range optFns { - fn(&option) - } - - if option.ConfigFiles == nil { - option.ConfigFiles = DefaultSharedConfigFiles - } - - if option.CredentialsFiles == nil { - option.CredentialsFiles = DefaultSharedCredentialsFiles - } - - // load shared configuration sections from shared configuration INI options - configSections, err := loadIniFiles(option.ConfigFiles) - if err != nil { - return SharedConfig{}, err - } - - // check for profile prefix and drop duplicates or invalid profiles - err = processConfigSections(ctx, &configSections, option.Logger) - if err != nil { - return SharedConfig{}, err - } - - // load shared credentials sections from shared credentials INI options - credentialsSections, err := loadIniFiles(option.CredentialsFiles) - if err != nil { - return SharedConfig{}, err - } - - // check for profile prefix and drop duplicates or invalid profiles - err = processCredentialsSections(ctx, &credentialsSections, option.Logger) - if err != nil { - return SharedConfig{}, err - } - - err = mergeSections(&configSections, credentialsSections) - if err != nil { - return SharedConfig{}, err - } - - cfg := SharedConfig{} - profiles := map[string]struct{}{} - - if err = cfg.setFromIniSections(profiles, profile, configSections, option.Logger); err != nil { - return SharedConfig{}, err - } - - return cfg, nil -} - -func processConfigSections(ctx context.Context, sections *ini.Sections, logger logging.Logger) error { - skipSections := map[string]struct{}{} - - for _, section := range sections.List() { - if _, ok := skipSections[section]; ok { - continue - } - - // drop sections from config file that do not have expected prefixes. - switch { - case strings.HasPrefix(section, profilePrefix): - // Rename sections to remove "profile " prefixing to match with - // credentials file. If default is already present, it will be - // dropped. - newName, err := renameProfileSection(section, sections, logger) - if err != nil { - return fmt.Errorf("failed to rename profile section, %w", err) - } - skipSections[newName] = struct{}{} - - case strings.HasPrefix(section, ssoSectionPrefix): - case strings.HasPrefix(section, servicesPrefix): - case strings.EqualFold(section, "default"): - default: - // drop this section, as invalid profile name - sections.DeleteSection(section) - - if logger != nil { - logger.Logf(logging.Debug, "A profile defined with name `%v` is ignored. "+ - "For use within a shared configuration file, "+ - "a non-default profile must have `profile ` "+ - "prefixed to the profile name.", - section, - ) - } - } - } - return nil -} - -func renameProfileSection(section string, sections *ini.Sections, logger logging.Logger) (string, error) { - v, ok := sections.GetSection(section) - if !ok { - return "", fmt.Errorf("error processing profiles within the shared configuration files") - } - - // delete section with profile as prefix - sections.DeleteSection(section) - - // set the value to non-prefixed name in sections. - section = strings.TrimPrefix(section, profilePrefix) - if sections.HasSection(section) { - oldSection, _ := sections.GetSection(section) - v.Logs = append(v.Logs, - fmt.Sprintf("A non-default profile not prefixed with `profile ` found in %s, "+ - "overriding non-default profile from %s", - v.SourceFile, oldSection.SourceFile)) - sections.DeleteSection(section) - } - - // assign non-prefixed name to section - v.Name = section - sections.SetSection(section, v) - - return section, nil -} - -func processCredentialsSections(ctx context.Context, sections *ini.Sections, logger logging.Logger) error { - for _, section := range sections.List() { - // drop profiles with prefix for credential files - if strings.HasPrefix(section, profilePrefix) { - // drop this section, as invalid profile name - sections.DeleteSection(section) - - if logger != nil { - logger.Logf(logging.Debug, - "The profile defined with name `%v` is ignored. A profile with the `profile ` prefix is invalid "+ - "for the shared credentials file.\n", - section, - ) - } - } - } - return nil -} - -func loadIniFiles(filenames []string) (ini.Sections, error) { - mergedSections := ini.NewSections() - - for _, filename := range filenames { - sections, err := ini.OpenFile(filename) - var v *ini.UnableToReadFile - if ok := errors.As(err, &v); ok { - // Skip files which can't be opened and read for whatever reason. - // We treat such files as empty, and do not fall back to other locations. - continue - } else if err != nil { - return ini.Sections{}, SharedConfigLoadError{Filename: filename, Err: err} - } - - // mergeSections into mergedSections - err = mergeSections(&mergedSections, sections) - if err != nil { - return ini.Sections{}, SharedConfigLoadError{Filename: filename, Err: err} - } - } - - return mergedSections, nil -} - -// mergeSections merges source section properties into destination section properties -func mergeSections(dst *ini.Sections, src ini.Sections) error { - for _, sectionName := range src.List() { - srcSection, _ := src.GetSection(sectionName) - - if (!srcSection.Has(accessKeyIDKey) && srcSection.Has(secretAccessKey)) || - (srcSection.Has(accessKeyIDKey) && !srcSection.Has(secretAccessKey)) { - srcSection.Errors = append(srcSection.Errors, - fmt.Errorf("partial credentials found for profile %v", sectionName)) - } - - if !dst.HasSection(sectionName) { - dst.SetSection(sectionName, srcSection) - continue - } - - // merge with destination srcSection - dstSection, _ := dst.GetSection(sectionName) - - // errors should be overriden if any - dstSection.Errors = srcSection.Errors - - // Access key id update - if srcSection.Has(accessKeyIDKey) && srcSection.Has(secretAccessKey) { - accessKey := srcSection.String(accessKeyIDKey) - secretKey := srcSection.String(secretAccessKey) - - if dstSection.Has(accessKeyIDKey) { - dstSection.Logs = append(dstSection.Logs, newMergeKeyLogMessage(sectionName, accessKeyIDKey, - dstSection.SourceFile[accessKeyIDKey], srcSection.SourceFile[accessKeyIDKey])) - } - - // update access key - v, err := ini.NewStringValue(accessKey) - if err != nil { - return fmt.Errorf("error merging access key, %w", err) - } - dstSection.UpdateValue(accessKeyIDKey, v) - - // update secret key - v, err = ini.NewStringValue(secretKey) - if err != nil { - return fmt.Errorf("error merging secret key, %w", err) - } - dstSection.UpdateValue(secretAccessKey, v) - - // update session token - if err = mergeStringKey(&srcSection, &dstSection, sectionName, sessionTokenKey); err != nil { - return err - } - - // update source file to reflect where the static creds came from - dstSection.UpdateSourceFile(accessKeyIDKey, srcSection.SourceFile[accessKeyIDKey]) - dstSection.UpdateSourceFile(secretAccessKey, srcSection.SourceFile[secretAccessKey]) - } - - stringKeys := []string{ - roleArnKey, - sourceProfileKey, - credentialSourceKey, - externalIDKey, - mfaSerialKey, - roleSessionNameKey, - regionKey, - enableEndpointDiscoveryKey, - credentialProcessKey, - webIdentityTokenFileKey, - s3UseARNRegionKey, - s3DisableMultiRegionAccessPointsKey, - ec2MetadataServiceEndpointModeKey, - ec2MetadataServiceEndpointKey, - ec2MetadataV1DisabledKey, - useDualStackEndpoint, - useFIPSEndpointKey, - defaultsModeKey, - retryModeKey, - caBundleKey, - roleDurationSecondsKey, - retryMaxAttemptsKey, - - ssoSessionNameKey, - ssoAccountIDKey, - ssoRegionKey, - ssoRoleNameKey, - ssoStartURLKey, - } - for i := range stringKeys { - if err := mergeStringKey(&srcSection, &dstSection, sectionName, stringKeys[i]); err != nil { - return err - } - } - - // set srcSection on dst srcSection - *dst = dst.SetSection(sectionName, dstSection) - } - - return nil -} - -func mergeStringKey(srcSection *ini.Section, dstSection *ini.Section, sectionName, key string) error { - if srcSection.Has(key) { - srcValue := srcSection.String(key) - val, err := ini.NewStringValue(srcValue) - if err != nil { - return fmt.Errorf("error merging %s, %w", key, err) - } - - if dstSection.Has(key) { - dstSection.Logs = append(dstSection.Logs, newMergeKeyLogMessage(sectionName, key, - dstSection.SourceFile[key], srcSection.SourceFile[key])) - } - - dstSection.UpdateValue(key, val) - dstSection.UpdateSourceFile(key, srcSection.SourceFile[key]) - } - return nil -} - -func newMergeKeyLogMessage(sectionName, key, dstSourceFile, srcSourceFile string) string { - return fmt.Sprintf("For profile: %v, overriding %v value, defined in %v "+ - "with a %v value found in a duplicate profile defined at file %v. \n", - sectionName, key, dstSourceFile, key, srcSourceFile) -} - -// Returns an error if all of the files fail to load. If at least one file is -// successfully loaded and contains the profile, no error will be returned. -func (c *SharedConfig) setFromIniSections(profiles map[string]struct{}, profile string, - sections ini.Sections, logger logging.Logger) error { - c.Profile = profile - - section, ok := sections.GetSection(profile) - if !ok { - return SharedConfigProfileNotExistError{ - Profile: profile, - } - } - - // if logs are appended to the section, log them - if section.Logs != nil && logger != nil { - for _, log := range section.Logs { - logger.Logf(logging.Debug, log) - } - } - - // set config from the provided INI section - err := c.setFromIniSection(profile, section) - if err != nil { - return fmt.Errorf("error fetching config from profile, %v, %w", profile, err) - } - - if _, ok := profiles[profile]; ok { - // if this is the second instance of the profile the Assume Role - // options must be cleared because they are only valid for the - // first reference of a profile. The self linked instance of the - // profile only have credential provider options. - c.clearAssumeRoleOptions() - } else { - // First time a profile has been seen. Assert if the credential type - // requires a role ARN, the ARN is also set - if err := c.validateCredentialsConfig(profile); err != nil { - return err - } - } - - // if not top level profile and has credentials, return with credentials. - if len(profiles) != 0 && c.Credentials.HasKeys() { - return nil - } - - profiles[profile] = struct{}{} - - // validate no colliding credentials type are present - if err := c.validateCredentialType(); err != nil { - return err - } - - // Link source profiles for assume roles - if len(c.SourceProfileName) != 0 { - // Linked profile via source_profile ignore credential provider - // options, the source profile must provide the credentials. - c.clearCredentialOptions() - - srcCfg := &SharedConfig{} - err := srcCfg.setFromIniSections(profiles, c.SourceProfileName, sections, logger) - if err != nil { - // SourceProfileName that doesn't exist is an error in configuration. - if _, ok := err.(SharedConfigProfileNotExistError); ok { - err = SharedConfigAssumeRoleError{ - RoleARN: c.RoleARN, - Profile: c.SourceProfileName, - Err: err, - } - } - return err - } - - if !srcCfg.hasCredentials() { - return SharedConfigAssumeRoleError{ - RoleARN: c.RoleARN, - Profile: c.SourceProfileName, - } - } - - c.Source = srcCfg - } - - // If the profile contains an SSO session parameter, the session MUST exist - // as a section in the config file. Load the SSO session using the name - // provided. If the session section is not found or incomplete an error - // will be returned. - if c.hasSSOTokenProviderConfiguration() { - section, ok := sections.GetSection(ssoSectionPrefix + strings.TrimSpace(c.SSOSessionName)) - if !ok { - return fmt.Errorf("failed to find SSO session section, %v", c.SSOSessionName) - } - var ssoSession SSOSession - ssoSession.setFromIniSection(section) - ssoSession.Name = c.SSOSessionName - c.SSOSession = &ssoSession - } - - if len(c.ServicesSectionName) > 0 { - if section, ok := sections.GetSection(servicesPrefix + c.ServicesSectionName); ok { - var svcs Services - svcs.setFromIniSection(section) - c.Services = svcs - } - } - - return nil -} - -// setFromIniSection loads the configuration from the profile section defined in -// the provided INI file. A SharedConfig pointer type value is used so that -// multiple config file loadings can be chained. -// -// Only loads complete logically grouped values, and will not set fields in cfg -// for incomplete grouped values in the config. Such as credentials. For example -// if a config file only includes aws_access_key_id but no aws_secret_access_key -// the aws_access_key_id will be ignored. -func (c *SharedConfig) setFromIniSection(profile string, section ini.Section) error { - if len(section.Name) == 0 { - sources := make([]string, 0) - for _, v := range section.SourceFile { - sources = append(sources, v) - } - - return fmt.Errorf("parsing error : could not find profile section name after processing files: %v", sources) - } - - if len(section.Errors) != 0 { - var errStatement string - for i, e := range section.Errors { - errStatement = fmt.Sprintf("%d, %v\n", i+1, e.Error()) - } - return fmt.Errorf("Error using profile: \n %v", errStatement) - } - - // Assume Role - updateString(&c.RoleARN, section, roleArnKey) - updateString(&c.ExternalID, section, externalIDKey) - updateString(&c.MFASerial, section, mfaSerialKey) - updateString(&c.RoleSessionName, section, roleSessionNameKey) - updateString(&c.SourceProfileName, section, sourceProfileKey) - updateString(&c.CredentialSource, section, credentialSourceKey) - updateString(&c.Region, section, regionKey) - - // AWS Single Sign-On (AWS SSO) - // SSO session options - updateString(&c.SSOSessionName, section, ssoSessionNameKey) - - // Legacy SSO session options - updateString(&c.SSORegion, section, ssoRegionKey) - updateString(&c.SSOStartURL, section, ssoStartURLKey) - - // SSO fields not used - updateString(&c.SSOAccountID, section, ssoAccountIDKey) - updateString(&c.SSORoleName, section, ssoRoleNameKey) - - // we're retaining a behavioral quirk with this field that existed before - // the removal of literal parsing for #2276: - // - if the key is missing, the config field will not be set - // - if the key is set to a non-numeric, the config field will be set to 0 - if section.Has(roleDurationSecondsKey) { - if v, ok := section.Int(roleDurationSecondsKey); ok { - c.RoleDurationSeconds = aws.Duration(time.Duration(v) * time.Second) - } else { - c.RoleDurationSeconds = aws.Duration(time.Duration(0)) - } - } - - updateString(&c.CredentialProcess, section, credentialProcessKey) - updateString(&c.WebIdentityTokenFile, section, webIdentityTokenFileKey) - - updateEndpointDiscoveryType(&c.EnableEndpointDiscovery, section, enableEndpointDiscoveryKey) - updateBoolPtr(&c.S3UseARNRegion, section, s3UseARNRegionKey) - updateBoolPtr(&c.S3DisableMultiRegionAccessPoints, section, s3DisableMultiRegionAccessPointsKey) - updateBoolPtr(&c.S3DisableExpressAuth, section, s3DisableExpressSessionAuthKey) - - if err := updateEC2MetadataServiceEndpointMode(&c.EC2IMDSEndpointMode, section, ec2MetadataServiceEndpointModeKey); err != nil { - return fmt.Errorf("failed to load %s from shared config, %v", ec2MetadataServiceEndpointModeKey, err) - } - updateString(&c.EC2IMDSEndpoint, section, ec2MetadataServiceEndpointKey) - updateBoolPtr(&c.EC2IMDSv1Disabled, section, ec2MetadataV1DisabledKey) - - updateUseDualStackEndpoint(&c.UseDualStackEndpoint, section, useDualStackEndpoint) - updateUseFIPSEndpoint(&c.UseFIPSEndpoint, section, useFIPSEndpointKey) - - if err := updateDefaultsMode(&c.DefaultsMode, section, defaultsModeKey); err != nil { - return fmt.Errorf("failed to load %s from shared config, %w", defaultsModeKey, err) - } - - if err := updateInt(&c.RetryMaxAttempts, section, retryMaxAttemptsKey); err != nil { - return fmt.Errorf("failed to load %s from shared config, %w", retryMaxAttemptsKey, err) - } - if err := updateRetryMode(&c.RetryMode, section, retryModeKey); err != nil { - return fmt.Errorf("failed to load %s from shared config, %w", retryModeKey, err) - } - - updateString(&c.CustomCABundle, section, caBundleKey) - - // user agent app ID added to request User-Agent header - updateString(&c.AppID, section, sdkAppID) - - updateBoolPtr(&c.IgnoreConfiguredEndpoints, section, ignoreConfiguredEndpoints) - - updateString(&c.BaseEndpoint, section, endpointURL) - - if err := updateDisableRequestCompression(&c.DisableRequestCompression, section, disableRequestCompression); err != nil { - return fmt.Errorf("failed to load %s from shared config, %w", disableRequestCompression, err) - } - if err := updateRequestMinCompressSizeBytes(&c.RequestMinCompressSizeBytes, section, requestMinCompressionSizeBytes); err != nil { - return fmt.Errorf("failed to load %s from shared config, %w", requestMinCompressionSizeBytes, err) - } - - // Shared Credentials - creds := aws.Credentials{ - AccessKeyID: section.String(accessKeyIDKey), - SecretAccessKey: section.String(secretAccessKey), - SessionToken: section.String(sessionTokenKey), - Source: fmt.Sprintf("SharedConfigCredentials: %s", section.SourceFile[accessKeyIDKey]), - } - - if creds.HasKeys() { - c.Credentials = creds - } - - updateString(&c.ServicesSectionName, section, servicesSectionKey) - - return nil -} - -func updateRequestMinCompressSizeBytes(bytes **int64, sec ini.Section, key string) error { - if !sec.Has(key) { - return nil - } - - v, ok := sec.Int(key) - if !ok { - return fmt.Errorf("invalid value for min request compression size bytes %s, need int64", sec.String(key)) - } - if v < 0 || v > smithyrequestcompression.MaxRequestMinCompressSizeBytes { - return fmt.Errorf("invalid range for min request compression size bytes %d, must be within 0 and 10485760 inclusively", v) - } - *bytes = new(int64) - **bytes = v - return nil -} - -func updateDisableRequestCompression(disable **bool, sec ini.Section, key string) error { - if !sec.Has(key) { - return nil - } - - v := sec.String(key) - switch { - case v == "true": - *disable = new(bool) - **disable = true - case v == "false": - *disable = new(bool) - **disable = false - default: - return fmt.Errorf("invalid value for shared config profile field, %s=%s, need true or false", key, v) - } - return nil -} - -func (c SharedConfig) getRequestMinCompressSizeBytes(ctx context.Context) (int64, bool, error) { - if c.RequestMinCompressSizeBytes == nil { - return 0, false, nil - } - return *c.RequestMinCompressSizeBytes, true, nil -} - -func (c SharedConfig) getDisableRequestCompression(ctx context.Context) (bool, bool, error) { - if c.DisableRequestCompression == nil { - return false, false, nil - } - return *c.DisableRequestCompression, true, nil -} - -func updateDefaultsMode(mode *aws.DefaultsMode, section ini.Section, key string) error { - if !section.Has(key) { - return nil - } - value := section.String(key) - if ok := mode.SetFromString(value); !ok { - return fmt.Errorf("invalid value: %s", value) - } - return nil -} - -func updateRetryMode(mode *aws.RetryMode, section ini.Section, key string) (err error) { - if !section.Has(key) { - return nil - } - value := section.String(key) - if *mode, err = aws.ParseRetryMode(value); err != nil { - return err - } - return nil -} - -func updateEC2MetadataServiceEndpointMode(endpointMode *imds.EndpointModeState, section ini.Section, key string) error { - if !section.Has(key) { - return nil - } - value := section.String(key) - return endpointMode.SetFromString(value) -} - -func (c *SharedConfig) validateCredentialsConfig(profile string) error { - if err := c.validateCredentialsRequireARN(profile); err != nil { - return err - } - - return nil -} - -func (c *SharedConfig) validateCredentialsRequireARN(profile string) error { - var credSource string - - switch { - case len(c.SourceProfileName) != 0: - credSource = sourceProfileKey - case len(c.CredentialSource) != 0: - credSource = credentialSourceKey - case len(c.WebIdentityTokenFile) != 0: - credSource = webIdentityTokenFileKey - } - - if len(credSource) != 0 && len(c.RoleARN) == 0 { - return CredentialRequiresARNError{ - Type: credSource, - Profile: profile, - } - } - - return nil -} - -func (c *SharedConfig) validateCredentialType() error { - // Only one or no credential type can be defined. - if !oneOrNone( - len(c.SourceProfileName) != 0, - len(c.CredentialSource) != 0, - len(c.CredentialProcess) != 0, - len(c.WebIdentityTokenFile) != 0, - ) { - return fmt.Errorf("only one credential type may be specified per profile: source profile, credential source, credential process, web identity token") - } - - return nil -} - -func (c *SharedConfig) validateSSOConfiguration() error { - if c.hasSSOTokenProviderConfiguration() { - err := c.validateSSOTokenProviderConfiguration() - if err != nil { - return err - } - return nil - } - - if c.hasLegacySSOConfiguration() { - err := c.validateLegacySSOConfiguration() - if err != nil { - return err - } - } - return nil -} - -func (c *SharedConfig) validateSSOTokenProviderConfiguration() error { - var missing []string - - if len(c.SSOSessionName) == 0 { - missing = append(missing, ssoSessionNameKey) - } - - if c.SSOSession == nil { - missing = append(missing, ssoSectionPrefix) - } else { - if len(c.SSOSession.SSORegion) == 0 { - missing = append(missing, ssoRegionKey) - } - - if len(c.SSOSession.SSOStartURL) == 0 { - missing = append(missing, ssoStartURLKey) - } - } - - if len(missing) > 0 { - return fmt.Errorf("profile %q is configured to use SSO but is missing required configuration: %s", - c.Profile, strings.Join(missing, ", ")) - } - - if len(c.SSORegion) > 0 && c.SSORegion != c.SSOSession.SSORegion { - return fmt.Errorf("%s in profile %q must match %s in %s", ssoRegionKey, c.Profile, ssoRegionKey, ssoSectionPrefix) - } - - if len(c.SSOStartURL) > 0 && c.SSOStartURL != c.SSOSession.SSOStartURL { - return fmt.Errorf("%s in profile %q must match %s in %s", ssoStartURLKey, c.Profile, ssoStartURLKey, ssoSectionPrefix) - } - - return nil -} - -func (c *SharedConfig) validateLegacySSOConfiguration() error { - var missing []string - - if len(c.SSORegion) == 0 { - missing = append(missing, ssoRegionKey) - } - - if len(c.SSOStartURL) == 0 { - missing = append(missing, ssoStartURLKey) - } - - if len(c.SSOAccountID) == 0 { - missing = append(missing, ssoAccountIDKey) - } - - if len(c.SSORoleName) == 0 { - missing = append(missing, ssoRoleNameKey) - } - - if len(missing) > 0 { - return fmt.Errorf("profile %q is configured to use SSO but is missing required configuration: %s", - c.Profile, strings.Join(missing, ", ")) - } - return nil -} - -func (c *SharedConfig) hasCredentials() bool { - switch { - case len(c.SourceProfileName) != 0: - case len(c.CredentialSource) != 0: - case len(c.CredentialProcess) != 0: - case len(c.WebIdentityTokenFile) != 0: - case c.hasSSOConfiguration(): - case c.Credentials.HasKeys(): - default: - return false - } - - return true -} - -func (c *SharedConfig) hasSSOConfiguration() bool { - return c.hasSSOTokenProviderConfiguration() || c.hasLegacySSOConfiguration() -} - -func (c *SharedConfig) hasSSOTokenProviderConfiguration() bool { - return len(c.SSOSessionName) > 0 -} - -func (c *SharedConfig) hasLegacySSOConfiguration() bool { - return len(c.SSORegion) > 0 || len(c.SSOAccountID) > 0 || len(c.SSOStartURL) > 0 || len(c.SSORoleName) > 0 -} - -func (c *SharedConfig) clearAssumeRoleOptions() { - c.RoleARN = "" - c.ExternalID = "" - c.MFASerial = "" - c.RoleSessionName = "" - c.SourceProfileName = "" -} - -func (c *SharedConfig) clearCredentialOptions() { - c.CredentialSource = "" - c.CredentialProcess = "" - c.WebIdentityTokenFile = "" - c.Credentials = aws.Credentials{} - c.SSOAccountID = "" - c.SSORegion = "" - c.SSORoleName = "" - c.SSOStartURL = "" -} - -// SharedConfigLoadError is an error for the shared config file failed to load. -type SharedConfigLoadError struct { - Filename string - Err error -} - -// Unwrap returns the underlying error that caused the failure. -func (e SharedConfigLoadError) Unwrap() error { - return e.Err -} - -func (e SharedConfigLoadError) Error() string { - return fmt.Sprintf("failed to load shared config file, %s, %v", e.Filename, e.Err) -} - -// SharedConfigProfileNotExistError is an error for the shared config when -// the profile was not find in the config file. -type SharedConfigProfileNotExistError struct { - Filename []string - Profile string - Err error -} - -// Unwrap returns the underlying error that caused the failure. -func (e SharedConfigProfileNotExistError) Unwrap() error { - return e.Err -} - -func (e SharedConfigProfileNotExistError) Error() string { - return fmt.Sprintf("failed to get shared config profile, %s", e.Profile) -} - -// SharedConfigAssumeRoleError is an error for the shared config when the -// profile contains assume role information, but that information is invalid -// or not complete. -type SharedConfigAssumeRoleError struct { - Profile string - RoleARN string - Err error -} - -// Unwrap returns the underlying error that caused the failure. -func (e SharedConfigAssumeRoleError) Unwrap() error { - return e.Err -} - -func (e SharedConfigAssumeRoleError) Error() string { - return fmt.Sprintf("failed to load assume role %s, of profile %s, %v", - e.RoleARN, e.Profile, e.Err) -} - -// CredentialRequiresARNError provides the error for shared config credentials -// that are incorrectly configured in the shared config or credentials file. -type CredentialRequiresARNError struct { - // type of credentials that were configured. - Type string - - // Profile name the credentials were in. - Profile string -} - -// Error satisfies the error interface. -func (e CredentialRequiresARNError) Error() string { - return fmt.Sprintf( - "credential type %s requires role_arn, profile %s", - e.Type, e.Profile, - ) -} - -func oneOrNone(bs ...bool) bool { - var count int - - for _, b := range bs { - if b { - count++ - if count > 1 { - return false - } - } - } - - return true -} - -// updateString will only update the dst with the value in the section key, key -// is present in the section. -func updateString(dst *string, section ini.Section, key string) { - if !section.Has(key) { - return - } - *dst = section.String(key) -} - -// updateInt will only update the dst with the value in the section key, key -// is present in the section. -// -// Down casts the INI integer value from a int64 to an int, which could be -// different bit size depending on platform. -func updateInt(dst *int, section ini.Section, key string) error { - if !section.Has(key) { - return nil - } - - v, ok := section.Int(key) - if !ok { - return fmt.Errorf("invalid value %s=%s, expect integer", key, section.String(key)) - } - - *dst = int(v) - return nil -} - -// updateBool will only update the dst with the value in the section key, key -// is present in the section. -func updateBool(dst *bool, section ini.Section, key string) { - if !section.Has(key) { - return - } - - // retains pre-#2276 behavior where non-bool value would resolve to false - v, _ := section.Bool(key) - *dst = v -} - -// updateBoolPtr will only update the dst with the value in the section key, -// key is present in the section. -func updateBoolPtr(dst **bool, section ini.Section, key string) { - if !section.Has(key) { - return - } - - // retains pre-#2276 behavior where non-bool value would resolve to false - v, _ := section.Bool(key) - *dst = new(bool) - **dst = v -} - -// updateEndpointDiscoveryType will only update the dst with the value in the section, if -// a valid key and corresponding EndpointDiscoveryType is found. -func updateEndpointDiscoveryType(dst *aws.EndpointDiscoveryEnableState, section ini.Section, key string) { - if !section.Has(key) { - return - } - - value := section.String(key) - if len(value) == 0 { - return - } - - switch { - case strings.EqualFold(value, endpointDiscoveryDisabled): - *dst = aws.EndpointDiscoveryDisabled - case strings.EqualFold(value, endpointDiscoveryEnabled): - *dst = aws.EndpointDiscoveryEnabled - case strings.EqualFold(value, endpointDiscoveryAuto): - *dst = aws.EndpointDiscoveryAuto - } -} - -// updateEndpointDiscoveryType will only update the dst with the value in the section, if -// a valid key and corresponding EndpointDiscoveryType is found. -func updateUseDualStackEndpoint(dst *aws.DualStackEndpointState, section ini.Section, key string) { - if !section.Has(key) { - return - } - - // retains pre-#2276 behavior where non-bool value would resolve to false - if v, _ := section.Bool(key); v { - *dst = aws.DualStackEndpointStateEnabled - } else { - *dst = aws.DualStackEndpointStateDisabled - } - - return -} - -// updateEndpointDiscoveryType will only update the dst with the value in the section, if -// a valid key and corresponding EndpointDiscoveryType is found. -func updateUseFIPSEndpoint(dst *aws.FIPSEndpointState, section ini.Section, key string) { - if !section.Has(key) { - return - } - - // retains pre-#2276 behavior where non-bool value would resolve to false - if v, _ := section.Bool(key); v { - *dst = aws.FIPSEndpointStateEnabled - } else { - *dst = aws.FIPSEndpointStateDisabled - } - - return -} 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 deleted file mode 100644 index 989c4ea3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/CHANGELOG.md +++ /dev/null @@ -1,477 +0,0 @@ -# v1.16.16 (2024-01-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.15 (2024-01-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.14 (2024-01-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.13 (2023-12-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.12 (2023-12-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.11 (2023-12-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.10 (2023-12-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.9 (2023-12-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.8 (2023-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.7 (2023-11-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.6 (2023-11-28.2) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.5 (2023-11-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.4 (2023-11-21) - -* **Bug Fix**: Don't expect error responses to have a JSON payload in the endpointcreds provider. - -# v1.16.3 (2023-11-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.2 (2023-11-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.1 (2023-11-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.0 (2023-11-14) - -* **Feature**: Add support for dynamic auth token from file and EKS container host in absolute/relative URIs in the HTTP credential provider. - -# v1.15.2 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.1 (2023-11-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.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.14.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.13.43 (2023-10-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.42 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.41 (2023-10-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.40 (2023-09-22) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.39 (2023-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.38 (2023-09-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.37 (2023-09-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.36 (2023-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.35 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.34 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.33 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.32 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.31 (2023-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.30 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.29 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.28 (2023-07-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.27 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.26 (2023-06-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.25 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.24 (2023-05-09) - -* No change notes available for this release. - -# v1.13.23 (2023-05-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.22 (2023-05-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.21 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.20 (2023-04-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.19 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.18 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.17 (2023-03-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.16 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.15 (2023-02-22) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.14 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.13 (2023-02-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.12 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.11 (2023-02-01) - -* No change notes available for this release. - -# v1.13.10 (2023-01-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.9 (2023-01-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.8 (2023-01-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.7 (2022-12-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.6 (2022-12-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.5 (2022-12-15) - -* **Bug Fix**: Unify logic between shared config and in finding home directory -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.4 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.3 (2022-11-22) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.2 (2022-11-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.1 (2022-11-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2022-11-11) - -* **Announcement**: When using the SSOTokenProvider, a previous implementation incorrectly compensated for invalid SSOTokenProvider configurations in the shared profile. This has been fixed via PR #1903 and tracked in issue #1846 -* **Feature**: Adds token refresh support (via SSOTokenProvider) when using the SSOCredentialProvider - -# v1.12.24 (2022-11-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.23 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.22 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.21 (2022-09-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.20 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.19 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.18 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.17 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.16 (2022-08-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.15 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.14 (2022-08-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.13 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.12 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.11 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.10 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.9 (2022-07-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.8 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.7 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.6 (2022-06-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.5 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.4 (2022-05-26) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.3 (2022-05-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.2 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.1 (2022-05-16) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2022-04-25) - -* **Feature**: Adds Duration and Policy options that can be used when creating stscreds.WebIdentityRoleProvider credentials provider. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.2 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.1 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2022-03-23) - -* **Feature**: Update `ec2rolecreds` package's `Provider` to implememnt support for CredentialsCache new optional caching strategy interfaces, HandleFailRefreshCredentialsCacheStrategy and AdjustExpiresByCredentialsCacheStrategy. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2022-02-24) - -* **Feature**: Adds support for `SourceIdentity` to `stscreds.AssumeRoleProvider` [#1588](https://github.com/aws/aws-sdk-go-v2/pull/1588). Fixes [#1575](https://github.com/aws/aws-sdk-go-v2/issues/1575) -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.5 (2021-12-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.4 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.3 (2021-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.2 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.1 (2021-11-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.3 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.2 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.1 (2021-09-10) - -* **Documentation**: Fixes the AssumeRoleProvider's documentation for using custom TokenProviders. - -# v1.4.0 (2021-08-27) - -* **Feature**: Adds support for Tags and TransitiveTagKeys to stscreds.AssumeRoleProvider. Closes https://github.com/aws/aws-sdk-go-v2/issues/723 -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.3 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.2 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.1 (2021-07-15) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Bug Fix**: Fixed example usages of aws.CredentialsCache ([#1275](https://github.com/aws/aws-sdk-go-v2/pull/1275)) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/credentials/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/credentials/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/doc.go deleted file mode 100644 index f6e2873a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -/* -Package credentials provides types for retrieving credentials from credentials sources. -*/ -package credentials diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/doc.go deleted file mode 100644 index 6ed71b42..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/doc.go +++ /dev/null @@ -1,58 +0,0 @@ -// Package ec2rolecreds provides the credentials provider implementation for -// retrieving AWS credentials from Amazon EC2 Instance Roles via Amazon EC2 IMDS. -// -// # Concurrency and caching -// -// The Provider is not safe to be used concurrently, and does not provide any -// caching of credentials retrieved. You should wrap the Provider with a -// `aws.CredentialsCache` to provide concurrency safety, and caching of -// credentials. -// -// # Loading credentials with the SDK's AWS Config -// -// The EC2 Instance role credentials provider will automatically be the resolved -// credential provider in the credential chain if no other credential provider is -// resolved first. -// -// To explicitly instruct the SDK's credentials resolving to use the EC2 Instance -// role for credentials, you specify a `credentials_source` property in the config -// profile the SDK will load. -// -// [default] -// credential_source = Ec2InstanceMetadata -// -// # Loading credentials with the Provider directly -// -// Another way to use the EC2 Instance role credentials provider is to create it -// directly and assign it as the credentials provider for an API client. -// -// The following example creates a credentials provider for a command, and wraps -// it with the CredentialsCache before assigning the provider to the Amazon S3 API -// client's Credentials option. -// -// provider := imds.New(imds.Options{}) -// -// // Create the service client value configured for credentials. -// svc := s3.New(s3.Options{ -// Credentials: aws.NewCredentialsCache(provider), -// }) -// -// If you need more control, you can set the configuration options on the -// credentials provider using the imds.Options type to configure the EC2 IMDS -// API Client and ExpiryWindow of the retrieved credentials. -// -// provider := imds.New(imds.Options{ -// // See imds.Options type's documentation for more options available. -// Client: imds.New(Options{ -// HTTPClient: customHTTPClient, -// }), -// -// // Modify how soon credentials expire prior to their original expiry time. -// ExpiryWindow: 5 * time.Minute, -// }) -// -// # EC2 IMDS API Client -// -// See the github.com/aws/aws-sdk-go-v2/feature/ec2/imds module for more details on -// configuring the client, and options available. -package ec2rolecreds diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/provider.go deleted file mode 100644 index 5c699f16..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds/provider.go +++ /dev/null @@ -1,229 +0,0 @@ -package ec2rolecreds - -import ( - "bufio" - "context" - "encoding/json" - "fmt" - "math" - "path" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" - sdkrand "github.com/aws/aws-sdk-go-v2/internal/rand" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" -) - -// ProviderName provides a name of EC2Role provider -const ProviderName = "EC2RoleProvider" - -// GetMetadataAPIClient provides the interface for an EC2 IMDS API client for the -// GetMetadata operation. -type GetMetadataAPIClient interface { - GetMetadata(context.Context, *imds.GetMetadataInput, ...func(*imds.Options)) (*imds.GetMetadataOutput, error) -} - -// A Provider retrieves credentials from the EC2 service, and keeps track if -// those credentials are expired. -// -// The New function must be used to create the with a custom EC2 IMDS client. -// -// p := &ec2rolecreds.New(func(o *ec2rolecreds.Options{ -// o.Client = imds.New(imds.Options{/* custom options */}) -// }) -type Provider struct { - options Options -} - -// Options is a list of user settable options for setting the behavior of the Provider. -type Options struct { - // The API client that will be used by the provider to make GetMetadata API - // calls to EC2 IMDS. - // - // If nil, the provider will default to the EC2 IMDS client. - Client GetMetadataAPIClient -} - -// New returns an initialized Provider value configured to retrieve -// credentials from EC2 Instance Metadata service. -func New(optFns ...func(*Options)) *Provider { - options := Options{} - - for _, fn := range optFns { - fn(&options) - } - - if options.Client == nil { - options.Client = imds.New(imds.Options{}) - } - - return &Provider{ - options: options, - } -} - -// Retrieve retrieves credentials from the EC2 service. Error will be returned -// if the request fails, or unable to extract the desired credentials. -func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error) { - credsList, err := requestCredList(ctx, p.options.Client) - if err != nil { - return aws.Credentials{Source: ProviderName}, err - } - - if len(credsList) == 0 { - return aws.Credentials{Source: ProviderName}, - fmt.Errorf("unexpected empty EC2 IMDS role list") - } - credsName := credsList[0] - - roleCreds, err := requestCred(ctx, p.options.Client, credsName) - if err != nil { - return aws.Credentials{Source: ProviderName}, err - } - - creds := aws.Credentials{ - AccessKeyID: roleCreds.AccessKeyID, - SecretAccessKey: roleCreds.SecretAccessKey, - SessionToken: roleCreds.Token, - Source: ProviderName, - - CanExpire: true, - Expires: roleCreds.Expiration, - } - - // Cap role credentials Expires to 1 hour so they can be refreshed more - // often. Jitter will be applied credentials cache if being used. - if anHour := sdk.NowTime().Add(1 * time.Hour); creds.Expires.After(anHour) { - creds.Expires = anHour - } - - return creds, nil -} - -// HandleFailToRefresh will extend the credentials Expires time if it it is -// expired. If the credentials will not expire within the minimum time, they -// will be returned. -// -// If the credentials cannot expire, the original error will be returned. -func (p *Provider) HandleFailToRefresh(ctx context.Context, prevCreds aws.Credentials, err error) ( - aws.Credentials, error, -) { - if !prevCreds.CanExpire { - return aws.Credentials{}, err - } - - if prevCreds.Expires.After(sdk.NowTime().Add(5 * time.Minute)) { - return prevCreds, nil - } - - newCreds := prevCreds - randFloat64, err := sdkrand.CryptoRandFloat64() - if err != nil { - return aws.Credentials{}, fmt.Errorf("failed to get random float, %w", err) - } - - // Random distribution of [5,15) minutes. - expireOffset := time.Duration(randFloat64*float64(10*time.Minute)) + 5*time.Minute - newCreds.Expires = sdk.NowTime().Add(expireOffset) - - logger := middleware.GetLogger(ctx) - logger.Logf(logging.Warn, "Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted again in %v minutes.", math.Floor(expireOffset.Minutes())) - - return newCreds, nil -} - -// AdjustExpiresBy will adds the passed in duration to the passed in -// credential's Expires time, unless the time until Expires is less than 15 -// minutes. Returns the credentials, even if not updated. -func (p *Provider) AdjustExpiresBy(creds aws.Credentials, dur time.Duration) ( - aws.Credentials, error, -) { - if !creds.CanExpire { - return creds, nil - } - if creds.Expires.Before(sdk.NowTime().Add(15 * time.Minute)) { - return creds, nil - } - - creds.Expires = creds.Expires.Add(dur) - return creds, nil -} - -// ec2RoleCredRespBody provides the shape for unmarshaling credential -// request responses. -type ec2RoleCredRespBody struct { - // Success State - Expiration time.Time - AccessKeyID string - SecretAccessKey string - Token string - - // Error state - Code string - Message string -} - -const iamSecurityCredsPath = "/iam/security-credentials/" - -// requestCredList requests a list of credentials from the EC2 service. If -// there are no credentials, or there is an error making or receiving the -// request -func requestCredList(ctx context.Context, client GetMetadataAPIClient) ([]string, error) { - resp, err := client.GetMetadata(ctx, &imds.GetMetadataInput{ - Path: iamSecurityCredsPath, - }) - if err != nil { - return nil, fmt.Errorf("no EC2 IMDS role found, %w", err) - } - defer resp.Content.Close() - - credsList := []string{} - s := bufio.NewScanner(resp.Content) - for s.Scan() { - credsList = append(credsList, s.Text()) - } - - if err := s.Err(); err != nil { - return nil, fmt.Errorf("failed to read EC2 IMDS role, %w", err) - } - - return credsList, nil -} - -// requestCred requests the credentials for a specific credentials from the EC2 service. -// -// If the credentials cannot be found, or there is an error reading the response -// and error will be returned. -func requestCred(ctx context.Context, client GetMetadataAPIClient, credsName string) (ec2RoleCredRespBody, error) { - resp, err := client.GetMetadata(ctx, &imds.GetMetadataInput{ - Path: path.Join(iamSecurityCredsPath, credsName), - }) - if err != nil { - return ec2RoleCredRespBody{}, - fmt.Errorf("failed to get %s EC2 IMDS role credentials, %w", - credsName, err) - } - defer resp.Content.Close() - - var respCreds ec2RoleCredRespBody - if err := json.NewDecoder(resp.Content).Decode(&respCreds); err != nil { - return ec2RoleCredRespBody{}, - fmt.Errorf("failed to decode %s EC2 IMDS role credentials, %w", - credsName, err) - } - - if !strings.EqualFold(respCreds.Code, "Success") { - // If an error code was returned something failed requesting the role. - return ec2RoleCredRespBody{}, - fmt.Errorf("failed to get %s EC2 IMDS role credentials, %w", - credsName, - &smithy.GenericAPIError{Code: respCreds.Code, Message: respCreds.Message}) - } - - return respCreds, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/auth.go deleted file mode 100644 index c3f5dadc..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/auth.go +++ /dev/null @@ -1,48 +0,0 @@ -package client - -import ( - "context" - "github.com/aws/smithy-go/middleware" -) - -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, -) { - return next.HandleFinalize(ctx, in) -} - -type signRequestMiddleware struct { -} - -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, -) { - return next.HandleFinalize(ctx, in) -} - -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, -) { - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/client.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/client.go deleted file mode 100644 index 9a869f89..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/client.go +++ /dev/null @@ -1,164 +0,0 @@ -package client - -import ( - "context" - "fmt" - "net/http" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/retry" - awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" - "github.com/aws/smithy-go" - smithymiddleware "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// ServiceID is the client identifer -const ServiceID = "endpoint-credentials" - -// HTTPClient is a client for sending HTTP requests -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// Options is the endpoint client configurable options -type Options struct { - // The endpoint to retrieve credentials from - Endpoint string - - // The HTTP client to invoke API calls with. Defaults to client's default HTTP - // implementation if nil. - HTTPClient HTTPClient - - // Retryer guides how HTTP requests should be retried in case of recoverable - // failures. When nil the API client will use a default retryer. - Retryer aws.Retryer - - // Set of options to modify how the credentials operation is invoked. - APIOptions []func(*smithymiddleware.Stack) error -} - -// Copy creates a copy of the API options. -func (o Options) Copy() Options { - to := o - to.APIOptions = make([]func(*smithymiddleware.Stack) error, len(o.APIOptions)) - copy(to.APIOptions, o.APIOptions) - return to -} - -// Client is an client for retrieving AWS credentials from an endpoint -type Client struct { - options Options -} - -// New constructs a new Client from the given options -func New(options Options, optFns ...func(*Options)) *Client { - options = options.Copy() - - if options.HTTPClient == nil { - options.HTTPClient = awshttp.NewBuildableClient() - } - - if options.Retryer == nil { - // Amazon-owned implementations of this endpoint are known to sometimes - // return plaintext responses (i.e. no Code) like normal, add a few - // additional status codes - options.Retryer = retry.NewStandard(func(o *retry.StandardOptions) { - o.Retryables = append(o.Retryables, retry.RetryableHTTPStatusCode{ - Codes: map[int]struct{}{ - http.StatusTooManyRequests: {}, - }, - }) - }) - } - - for _, fn := range optFns { - fn(&options) - } - - client := &Client{ - options: options, - } - - return client -} - -// GetCredentialsInput is the input to send with the endpoint service to receive credentials. -type GetCredentialsInput struct { - AuthorizationToken string -} - -// GetCredentials retrieves credentials from credential endpoint -func (c *Client) GetCredentials(ctx context.Context, params *GetCredentialsInput, optFns ...func(*Options)) (*GetCredentialsOutput, error) { - stack := smithymiddleware.NewStack("GetCredentials", smithyhttp.NewStackRequest) - options := c.options.Copy() - for _, fn := range optFns { - fn(&options) - } - - stack.Serialize.Add(&serializeOpGetCredential{}, smithymiddleware.After) - stack.Build.Add(&buildEndpoint{Endpoint: options.Endpoint}, smithymiddleware.After) - stack.Deserialize.Add(&deserializeOpGetCredential{}, smithymiddleware.After) - addProtocolFinalizerMiddlewares(stack, options, "GetCredentials") - retry.AddRetryMiddlewares(stack, retry.AddRetryMiddlewaresOptions{Retryer: options.Retryer}) - middleware.AddSDKAgentKey(middleware.FeatureMetadata, ServiceID) - smithyhttp.AddErrorCloseResponseBodyMiddleware(stack) - smithyhttp.AddCloseResponseBodyMiddleware(stack) - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, err - } - } - - handler := smithymiddleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, _, err := handler.Handle(ctx, params) - if err != nil { - return nil, err - } - - return result.(*GetCredentialsOutput), err -} - -// GetCredentialsOutput is the response from the credential endpoint -type GetCredentialsOutput struct { - Expiration *time.Time - AccessKeyID string - SecretAccessKey string - Token string -} - -// EndpointError is an error returned from the endpoint service -type EndpointError struct { - Code string `json:"code"` - Message string `json:"message"` - Fault smithy.ErrorFault `json:"-"` - statusCode int `json:"-"` -} - -// Error is the error mesage string -func (e *EndpointError) Error() string { - return fmt.Sprintf("%s: %s", e.Code, e.Message) -} - -// ErrorCode is the error code returned by the endpoint -func (e *EndpointError) ErrorCode() string { - return e.Code -} - -// ErrorMessage is the error message returned by the endpoint -func (e *EndpointError) ErrorMessage() string { - return e.Message -} - -// ErrorFault indicates error fault classification -func (e *EndpointError) ErrorFault() smithy.ErrorFault { - return e.Fault -} - -// HTTPStatusCode implements retry.HTTPStatusCode. -func (e *EndpointError) HTTPStatusCode() int { - return e.statusCode -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/endpoints.go deleted file mode 100644 index 748ee672..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/endpoints.go +++ /dev/null @@ -1,20 +0,0 @@ -package client - -import ( - "context" - "github.com/aws/smithy-go/middleware" -) - -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, -) { - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/middleware.go deleted file mode 100644 index f2820d20..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client/middleware.go +++ /dev/null @@ -1,164 +0,0 @@ -package client - -import ( - "context" - "encoding/json" - "fmt" - "io" - "net/url" - - "github.com/aws/smithy-go" - smithymiddleware "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -type buildEndpoint struct { - Endpoint string -} - -func (b *buildEndpoint) ID() string { - return "BuildEndpoint" -} - -func (b *buildEndpoint) HandleBuild(ctx context.Context, in smithymiddleware.BuildInput, next smithymiddleware.BuildHandler) ( - out smithymiddleware.BuildOutput, metadata smithymiddleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport, %T", in.Request) - } - - if len(b.Endpoint) == 0 { - return out, metadata, fmt.Errorf("endpoint not provided") - } - - parsed, err := url.Parse(b.Endpoint) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint, %w", err) - } - - request.URL = parsed - - return next.HandleBuild(ctx, in) -} - -type serializeOpGetCredential struct{} - -func (s *serializeOpGetCredential) ID() string { - return "OperationSerializer" -} - -func (s *serializeOpGetCredential) HandleSerialize(ctx context.Context, in smithymiddleware.SerializeInput, next smithymiddleware.SerializeHandler) ( - out smithymiddleware.SerializeOutput, metadata smithymiddleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type, %T", in.Request) - } - - params, ok := in.Parameters.(*GetCredentialsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters, %T", in.Parameters) - } - - const acceptHeader = "Accept" - request.Header[acceptHeader] = append(request.Header[acceptHeader][:0], "application/json") - - if len(params.AuthorizationToken) > 0 { - const authHeader = "Authorization" - request.Header[authHeader] = append(request.Header[authHeader][:0], params.AuthorizationToken) - } - - return next.HandleSerialize(ctx, in) -} - -type deserializeOpGetCredential struct{} - -func (d *deserializeOpGetCredential) ID() string { - return "OperationDeserializer" -} - -func (d *deserializeOpGetCredential) HandleDeserialize(ctx context.Context, in smithymiddleware.DeserializeInput, next smithymiddleware.DeserializeHandler) ( - out smithymiddleware.DeserializeOutput, metadata smithymiddleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, in) - if err != nil { - return out, metadata, err - } - - 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, deserializeError(response) - } - - var shape *GetCredentialsOutput - if err = json.NewDecoder(response.Body).Decode(&shape); err != nil { - return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("failed to deserialize json response, %w", err)} - } - - out.Result = shape - return out, metadata, err -} - -func deserializeError(response *smithyhttp.Response) error { - // we could be talking to anything, json isn't guaranteed - // see https://github.com/aws/aws-sdk-go-v2/issues/2316 - if response.Header.Get("Content-Type") == "application/json" { - return deserializeJSONError(response) - } - - msg, err := io.ReadAll(response.Body) - if err != nil { - return &smithy.DeserializationError{ - Err: fmt.Errorf("read response, %w", err), - } - } - - return &EndpointError{ - // no sensible value for Code - Message: string(msg), - Fault: stof(response.StatusCode), - statusCode: response.StatusCode, - } -} - -func deserializeJSONError(response *smithyhttp.Response) error { - var errShape *EndpointError - if err := json.NewDecoder(response.Body).Decode(&errShape); err != nil { - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode error message, %w", err), - } - } - - errShape.Fault = stof(response.StatusCode) - errShape.statusCode = response.StatusCode - return errShape -} - -// maps HTTP status code to smithy ErrorFault -func stof(code int) smithy.ErrorFault { - if code >= 500 { - return smithy.FaultServer - } - return smithy.FaultClient -} - -func addProtocolFinalizerMiddlewares(stack *smithymiddleware.Stack, options Options, operation string) error { - if err := stack.Finalize.Add(&resolveAuthSchemeMiddleware{operation: operation, options: options}, smithymiddleware.Before); err != nil { - return fmt.Errorf("add ResolveAuthScheme: %w", err) - } - if err := stack.Finalize.Insert(&getIdentityMiddleware{options: options}, "ResolveAuthScheme", smithymiddleware.After); err != nil { - return fmt.Errorf("add GetIdentity: %w", err) - } - if err := stack.Finalize.Insert(&resolveEndpointV2Middleware{options: options}, "GetIdentity", smithymiddleware.After); err != nil { - return fmt.Errorf("add ResolveEndpointV2: %w", err) - } - if err := stack.Finalize.Insert(&signRequestMiddleware{}, "ResolveEndpointV2", smithymiddleware.After); err != nil { - return fmt.Errorf("add Signing: %w", err) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/provider.go deleted file mode 100644 index 0c3c4d68..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/provider.go +++ /dev/null @@ -1,192 +0,0 @@ -// Package endpointcreds provides support for retrieving credentials from an -// arbitrary HTTP endpoint. -// -// The credentials endpoint Provider can receive both static and refreshable -// credentials that will expire. Credentials are static when an "Expiration" -// value is not provided in the endpoint's response. -// -// Static credentials will never expire once they have been retrieved. The format -// of the static credentials response: -// -// { -// "AccessKeyId" : "MUA...", -// "SecretAccessKey" : "/7PC5om....", -// } -// -// Refreshable credentials will expire within the "ExpiryWindow" of the Expiration -// value in the response. The format of the refreshable credentials response: -// -// { -// "AccessKeyId" : "MUA...", -// "SecretAccessKey" : "/7PC5om....", -// "Token" : "AQoDY....=", -// "Expiration" : "2016-02-25T06:03:31Z" -// } -// -// Errors should be returned in the following format and only returned with 400 -// or 500 HTTP status codes. -// -// { -// "code": "ErrorCode", -// "message": "Helpful error message." -// } -package endpointcreds - -import ( - "context" - "fmt" - "net/http" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds/internal/client" - "github.com/aws/smithy-go/middleware" -) - -// ProviderName is the name of the credentials provider. -const ProviderName = `CredentialsEndpointProvider` - -type getCredentialsAPIClient interface { - GetCredentials(context.Context, *client.GetCredentialsInput, ...func(*client.Options)) (*client.GetCredentialsOutput, error) -} - -// Provider satisfies the aws.CredentialsProvider interface, and is a client to -// retrieve credentials from an arbitrary endpoint. -type Provider struct { - // The AWS Client to make HTTP requests to the endpoint with. The endpoint - // the request will be made to is provided by the aws.Config's - // EndpointResolver. - client getCredentialsAPIClient - - options Options -} - -// HTTPClient is a client for sending HTTP requests -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// Options is structure of configurable options for Provider -type Options struct { - // Endpoint to retrieve credentials from. Required - Endpoint string - - // HTTPClient to handle sending HTTP requests to the target endpoint. - HTTPClient HTTPClient - - // Set of options to modify how the credentials operation is invoked. - APIOptions []func(*middleware.Stack) error - - // The Retryer to be used for determining whether a failed requested should be retried - Retryer aws.Retryer - - // Optional authorization token value if set will be used as the value of - // the Authorization header of the endpoint credential request. - // - // When constructed from environment, the provider will use the value of - // AWS_CONTAINER_AUTHORIZATION_TOKEN environment variable as the token - // - // Will be overridden if AuthorizationTokenProvider is configured - AuthorizationToken string - - // Optional auth provider func to dynamically load the auth token from a file - // everytime a credential is retrieved - // - // When constructed from environment, the provider will read and use the content - // of the file pointed to by AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE environment variable - // as the auth token everytime credentials are retrieved - // - // Will override AuthorizationToken if configured - AuthorizationTokenProvider AuthTokenProvider -} - -// AuthTokenProvider defines an interface to dynamically load a value to be passed -// for the Authorization header of a credentials request. -type AuthTokenProvider interface { - GetToken() (string, error) -} - -// TokenProviderFunc is a func type implementing AuthTokenProvider interface -// and enables customizing token provider behavior -type TokenProviderFunc func() (string, error) - -// GetToken func retrieves auth token according to TokenProviderFunc implementation -func (p TokenProviderFunc) GetToken() (string, error) { - return p() -} - -// New returns a credentials Provider for retrieving AWS credentials -// from arbitrary endpoint. -func New(endpoint string, optFns ...func(*Options)) *Provider { - o := Options{ - Endpoint: endpoint, - } - - for _, fn := range optFns { - fn(&o) - } - - p := &Provider{ - client: client.New(client.Options{ - HTTPClient: o.HTTPClient, - Endpoint: o.Endpoint, - APIOptions: o.APIOptions, - Retryer: o.Retryer, - }), - options: o, - } - - return p -} - -// Retrieve will attempt to request the credentials from the endpoint the Provider -// was configured for. And error will be returned if the retrieval fails. -func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error) { - resp, err := p.getCredentials(ctx) - if err != nil { - return aws.Credentials{}, fmt.Errorf("failed to load credentials, %w", err) - } - - creds := aws.Credentials{ - AccessKeyID: resp.AccessKeyID, - SecretAccessKey: resp.SecretAccessKey, - SessionToken: resp.Token, - Source: ProviderName, - } - - if resp.Expiration != nil { - creds.CanExpire = true - creds.Expires = *resp.Expiration - } - - return creds, nil -} - -func (p *Provider) getCredentials(ctx context.Context) (*client.GetCredentialsOutput, error) { - authToken, err := p.resolveAuthToken() - if err != nil { - return nil, fmt.Errorf("resolve auth token: %v", err) - } - - return p.client.GetCredentials(ctx, &client.GetCredentialsInput{ - AuthorizationToken: authToken, - }) -} - -func (p *Provider) resolveAuthToken() (string, error) { - authToken := p.options.AuthorizationToken - - var err error - if p.options.AuthorizationTokenProvider != nil { - authToken, err = p.options.AuthorizationTokenProvider.GetToken() - if err != nil { - return "", err - } - } - - if strings.ContainsAny(authToken, "\r\n") { - return "", fmt.Errorf("authorization token contains invalid newline sequence") - } - - return authToken, nil -} 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 deleted file mode 100644 index fe92184d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package credentials - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.16.16" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/doc.go deleted file mode 100644 index a3137b8f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/doc.go +++ /dev/null @@ -1,92 +0,0 @@ -// Package processcreds is a credentials provider to retrieve credentials from a -// external CLI invoked process. -// -// WARNING: The following describes a method of sourcing credentials from an external -// process. This can potentially be dangerous, so proceed with caution. Other -// credential providers should be preferred if at all possible. If using this -// option, you should make sure that the config file is as locked down as possible -// using security best practices for your operating system. -// -// # Concurrency and caching -// -// The Provider is not safe to be used concurrently, and does not provide any -// caching of credentials retrieved. You should wrap the Provider with a -// `aws.CredentialsCache` to provide concurrency safety, and caching of -// credentials. -// -// # Loading credentials with the SDKs AWS Config -// -// You can use credentials from a AWS shared config `credential_process` in a -// variety of ways. -// -// One way is to setup your shared config file, located in the default -// location, with the `credential_process` key and the command you want to be -// called. You also need to set the AWS_SDK_LOAD_CONFIG environment variable -// (e.g., `export AWS_SDK_LOAD_CONFIG=1`) to use the shared config file. -// -// [default] -// credential_process = /command/to/call -// -// Loading configuration using external will use the credential process to -// retrieve credentials. NOTE: If there are credentials in the profile you are -// using, the credential process will not be used. -// -// // Initialize a session to load credentials. -// cfg, _ := config.LoadDefaultConfig(context.TODO()) -// -// // Create S3 service client to use the credentials. -// svc := s3.NewFromConfig(cfg) -// -// # Loading credentials with the Provider directly -// -// Another way to use the credentials process provider is by using the -// `NewProvider` constructor to create the provider and providing a it with a -// command to be executed to retrieve credentials. -// -// The following example creates a credentials provider for a command, and wraps -// it with the CredentialsCache before assigning the provider to the Amazon S3 API -// client's Credentials option. -// -// // Create credentials using the Provider. -// provider := processcreds.NewProvider("/path/to/command") -// -// // Create the service client value configured for credentials. -// svc := s3.New(s3.Options{ -// Credentials: aws.NewCredentialsCache(provider), -// }) -// -// If you need more control, you can set any configurable options in the -// credentials using one or more option functions. -// -// provider := processcreds.NewProvider("/path/to/command", -// func(o *processcreds.Options) { -// // Override the provider's default timeout -// o.Timeout = 2 * time.Minute -// }) -// -// You can also use your own `exec.Cmd` value by satisfying a value that satisfies -// the `NewCommandBuilder` interface and use the `NewProviderCommand` constructor. -// -// // Create an exec.Cmd -// cmdBuilder := processcreds.NewCommandBuilderFunc( -// func(ctx context.Context) (*exec.Cmd, error) { -// cmd := exec.CommandContext(ctx, -// "customCLICommand", -// "-a", "argument", -// ) -// cmd.Env = []string{ -// "ENV_VAR_FOO=value", -// "ENV_VAR_BAR=other_value", -// } -// -// return cmd, nil -// }, -// ) -// -// // Create credentials using your exec.Cmd and custom timeout -// provider := processcreds.NewProviderCommand(cmdBuilder, -// func(opt *processcreds.Provider) { -// // optionally override the provider's default timeout -// opt.Timeout = 1 * time.Second -// }) -package processcreds diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/provider.go deleted file mode 100644 index fe9345e2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/processcreds/provider.go +++ /dev/null @@ -1,281 +0,0 @@ -package processcreds - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "os" - "os/exec" - "runtime" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/internal/sdkio" -) - -const ( - // ProviderName is the name this credentials provider will label any - // returned credentials Value with. - ProviderName = `ProcessProvider` - - // DefaultTimeout default limit on time a process can run. - DefaultTimeout = time.Duration(1) * time.Minute -) - -// ProviderError is an error indicating failure initializing or executing the -// process credentials provider -type ProviderError struct { - Err error -} - -// Error returns the error message. -func (e *ProviderError) Error() string { - return fmt.Sprintf("process provider error: %v", e.Err) -} - -// Unwrap returns the underlying error the provider error wraps. -func (e *ProviderError) Unwrap() error { - return e.Err -} - -// Provider satisfies the credentials.Provider interface, and is a -// client to retrieve credentials from a process. -type Provider struct { - // Provides a constructor for exec.Cmd that are invoked by the provider for - // retrieving credentials. Use this to provide custom creation of exec.Cmd - // with things like environment variables, or other configuration. - // - // The provider defaults to the DefaultNewCommand function. - commandBuilder NewCommandBuilder - - options Options -} - -// Options is the configuration options for configuring the Provider. -type Options struct { - // Timeout limits the time a process can run. - Timeout time.Duration -} - -// NewCommandBuilder provides the interface for specifying how command will be -// created that the Provider will use to retrieve credentials with. -type NewCommandBuilder interface { - NewCommand(context.Context) (*exec.Cmd, error) -} - -// NewCommandBuilderFunc provides a wrapper type around a function pointer to -// satisfy the NewCommandBuilder interface. -type NewCommandBuilderFunc func(context.Context) (*exec.Cmd, error) - -// NewCommand calls the underlying function pointer the builder was initialized with. -func (fn NewCommandBuilderFunc) NewCommand(ctx context.Context) (*exec.Cmd, error) { - return fn(ctx) -} - -// DefaultNewCommandBuilder provides the default NewCommandBuilder -// implementation used by the provider. It takes a command and arguments to -// invoke. The command will also be initialized with the current process -// environment variables, stderr, and stdin pipes. -type DefaultNewCommandBuilder struct { - Args []string -} - -// NewCommand returns an initialized exec.Cmd with the builder's initialized -// Args. The command is also initialized current process environment variables, -// stderr, and stdin pipes. -func (b DefaultNewCommandBuilder) NewCommand(ctx context.Context) (*exec.Cmd, error) { - var cmdArgs []string - if runtime.GOOS == "windows" { - cmdArgs = []string{"cmd.exe", "/C"} - } else { - cmdArgs = []string{"sh", "-c"} - } - - if len(b.Args) == 0 { - return nil, &ProviderError{ - Err: fmt.Errorf("failed to prepare command: command must not be empty"), - } - } - - cmdArgs = append(cmdArgs, b.Args...) - cmd := exec.CommandContext(ctx, cmdArgs[0], cmdArgs[1:]...) - cmd.Env = os.Environ() - - cmd.Stderr = os.Stderr // display stderr on console for MFA - cmd.Stdin = os.Stdin // enable stdin for MFA - - return cmd, nil -} - -// NewProvider returns a pointer to a new Credentials object wrapping the -// Provider. -// -// The provider defaults to the DefaultNewCommandBuilder for creating command -// the Provider will use to retrieve credentials with. -func NewProvider(command string, options ...func(*Options)) *Provider { - var args []string - - // Ensure that the command arguments are not set if the provided command is - // empty. This will error out when the command is executed since no - // arguments are specified. - if len(command) > 0 { - args = []string{command} - } - - commanBuilder := DefaultNewCommandBuilder{ - Args: args, - } - return NewProviderCommand(commanBuilder, options...) -} - -// NewProviderCommand returns a pointer to a new Credentials object with the -// specified command, and default timeout duration. Use this to provide custom -// creation of exec.Cmd for options like environment variables, or other -// configuration. -func NewProviderCommand(builder NewCommandBuilder, options ...func(*Options)) *Provider { - p := &Provider{ - commandBuilder: builder, - options: Options{ - Timeout: DefaultTimeout, - }, - } - - for _, option := range options { - option(&p.options) - } - - return p -} - -// A CredentialProcessResponse is the AWS credentials format that must be -// returned when executing an external credential_process. -type CredentialProcessResponse struct { - // As of this writing, the Version key must be set to 1. This might - // increment over time as the structure evolves. - Version int - - // The access key ID that identifies the temporary security credentials. - AccessKeyID string `json:"AccessKeyId"` - - // The secret access key that can be used to sign requests. - SecretAccessKey string - - // The token that users must pass to the service API to use the temporary credentials. - SessionToken string - - // The date on which the current credentials expire. - Expiration *time.Time -} - -// Retrieve executes the credential process command and returns the -// credentials, or error if the command fails. -func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error) { - out, err := p.executeCredentialProcess(ctx) - if err != nil { - return aws.Credentials{Source: ProviderName}, err - } - - // Serialize and validate response - resp := &CredentialProcessResponse{} - if err = json.Unmarshal(out, resp); err != nil { - return aws.Credentials{Source: ProviderName}, &ProviderError{ - Err: fmt.Errorf("parse failed of process output: %s, error: %w", out, err), - } - } - - if resp.Version != 1 { - return aws.Credentials{Source: ProviderName}, &ProviderError{ - Err: fmt.Errorf("wrong version in process output (not 1)"), - } - } - - if len(resp.AccessKeyID) == 0 { - return aws.Credentials{Source: ProviderName}, &ProviderError{ - Err: fmt.Errorf("missing AccessKeyId in process output"), - } - } - - if len(resp.SecretAccessKey) == 0 { - return aws.Credentials{Source: ProviderName}, &ProviderError{ - Err: fmt.Errorf("missing SecretAccessKey in process output"), - } - } - - creds := aws.Credentials{ - Source: ProviderName, - AccessKeyID: resp.AccessKeyID, - SecretAccessKey: resp.SecretAccessKey, - SessionToken: resp.SessionToken, - } - - // Handle expiration - if resp.Expiration != nil { - creds.CanExpire = true - creds.Expires = *resp.Expiration - } - - return creds, nil -} - -// executeCredentialProcess starts the credential process on the OS and -// returns the results or an error. -func (p *Provider) executeCredentialProcess(ctx context.Context) ([]byte, error) { - if p.options.Timeout >= 0 { - var cancelFunc func() - ctx, cancelFunc = context.WithTimeout(ctx, p.options.Timeout) - defer cancelFunc() - } - - cmd, err := p.commandBuilder.NewCommand(ctx) - if err != nil { - return nil, err - } - - // get creds json on process's stdout - output := bytes.NewBuffer(make([]byte, 0, int(8*sdkio.KibiByte))) - if cmd.Stdout != nil { - cmd.Stdout = io.MultiWriter(cmd.Stdout, output) - } else { - cmd.Stdout = output - } - - execCh := make(chan error, 1) - go executeCommand(cmd, execCh) - - select { - case execError := <-execCh: - if execError == nil { - break - } - select { - case <-ctx.Done(): - return output.Bytes(), &ProviderError{ - Err: fmt.Errorf("credential process timed out: %w", execError), - } - default: - return output.Bytes(), &ProviderError{ - Err: fmt.Errorf("error in credential_process: %w", execError), - } - } - } - - out := output.Bytes() - if runtime.GOOS == "windows" { - // windows adds slashes to quotes - out = bytes.ReplaceAll(out, []byte(`\"`), []byte(`"`)) - } - - return out, nil -} - -func executeCommand(cmd *exec.Cmd, exec chan error) { - // Start the command - err := cmd.Start() - if err == nil { - err = cmd.Wait() - } - - exec <- err -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/doc.go deleted file mode 100644 index ece1e65f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/doc.go +++ /dev/null @@ -1,81 +0,0 @@ -// Package ssocreds provides a credential provider for retrieving temporary AWS -// credentials using an SSO access token. -// -// IMPORTANT: The provider in this package does not initiate or perform the AWS -// SSO login flow. The SDK provider expects that you have already performed the -// SSO login flow using AWS CLI using the "aws sso login" command, or by some -// other mechanism. The provider must find a valid non-expired access token for -// the AWS SSO user portal URL in ~/.aws/sso/cache. If a cached token is not -// found, it is expired, or the file is malformed an error will be returned. -// -// # Loading AWS SSO credentials with the AWS shared configuration file -// -// You can use configure AWS SSO credentials from the AWS shared configuration file by -// specifying the required keys in the profile and referencing an sso-session: -// -// sso_session -// sso_account_id -// sso_role_name -// -// For example, the following defines a profile "devsso" and specifies the AWS -// SSO parameters that defines the target account, role, sign-on portal, and -// the region where the user portal is located. Note: all SSO arguments must be -// provided, or an error will be returned. -// -// [profile devsso] -// sso_session = dev-session -// sso_role_name = SSOReadOnlyRole -// sso_account_id = 123456789012 -// -// [sso-session dev-session] -// sso_start_url = https://my-sso-portal.awsapps.com/start -// sso_region = us-east-1 -// sso_registration_scopes = sso:account:access -// -// Using the config module, you can load the AWS SDK shared configuration, and -// specify that this profile be used to retrieve credentials. For example: -// -// config, err := config.LoadDefaultConfig(context.TODO(), config.WithSharedConfigProfile("devsso")) -// if err != nil { -// return err -// } -// -// # Programmatically loading AWS SSO credentials directly -// -// You can programmatically construct the AWS SSO Provider in your application, -// and provide the necessary information to load and retrieve temporary -// credentials using an access token from ~/.aws/sso/cache. -// -// ssoClient := sso.NewFromConfig(cfg) -// ssoOidcClient := ssooidc.NewFromConfig(cfg) -// tokenPath, err := ssocreds.StandardCachedTokenFilepath("dev-session") -// if err != nil { -// return err -// } -// -// var provider aws.CredentialsProvider -// provider = ssocreds.New(ssoClient, "123456789012", "SSOReadOnlyRole", "https://my-sso-portal.awsapps.com/start", func(options *ssocreds.Options) { -// options.SSOTokenProvider = ssocreds.NewSSOTokenProvider(ssoOidcClient, tokenPath) -// }) -// -// // Wrap the provider with aws.CredentialsCache to cache the credentials until their expire time -// provider = aws.NewCredentialsCache(provider) -// -// credentials, err := provider.Retrieve(context.TODO()) -// if err != nil { -// return err -// } -// -// It is important that you wrap the Provider with aws.CredentialsCache if you -// are programmatically constructing the provider directly. This prevents your -// application from accessing the cached access token and requesting new -// credentials each time the credentials are used. -// -// # Additional Resources -// -// Configuring the AWS CLI to use AWS Single Sign-On: -// https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html -// -// AWS Single Sign-On User Guide: -// https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html -package ssocreds diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_cached_token.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_cached_token.go deleted file mode 100644 index 3b97e6dd..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_cached_token.go +++ /dev/null @@ -1,233 +0,0 @@ -package ssocreds - -import ( - "crypto/sha1" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/aws-sdk-go-v2/internal/shareddefaults" -) - -var osUserHomeDur = shareddefaults.UserHomeDir - -// StandardCachedTokenFilepath returns the filepath for the cached SSO token file, or -// error if unable get derive the path. Key that will be used to compute a SHA1 -// value that is hex encoded. -// -// Derives the filepath using the Key as: -// -// ~/.aws/sso/cache/.json -func StandardCachedTokenFilepath(key string) (string, error) { - homeDir := osUserHomeDur() - if len(homeDir) == 0 { - return "", fmt.Errorf("unable to get USER's home directory for cached token") - } - hash := sha1.New() - if _, err := hash.Write([]byte(key)); err != nil { - return "", fmt.Errorf("unable to compute cached token filepath key SHA1 hash, %w", err) - } - - cacheFilename := strings.ToLower(hex.EncodeToString(hash.Sum(nil))) + ".json" - - return filepath.Join(homeDir, ".aws", "sso", "cache", cacheFilename), nil -} - -type tokenKnownFields struct { - AccessToken string `json:"accessToken,omitempty"` - ExpiresAt *rfc3339 `json:"expiresAt,omitempty"` - - RefreshToken string `json:"refreshToken,omitempty"` - ClientID string `json:"clientId,omitempty"` - ClientSecret string `json:"clientSecret,omitempty"` -} - -type token struct { - tokenKnownFields - UnknownFields map[string]interface{} `json:"-"` -} - -func (t token) MarshalJSON() ([]byte, error) { - fields := map[string]interface{}{} - - setTokenFieldString(fields, "accessToken", t.AccessToken) - setTokenFieldRFC3339(fields, "expiresAt", t.ExpiresAt) - - setTokenFieldString(fields, "refreshToken", t.RefreshToken) - setTokenFieldString(fields, "clientId", t.ClientID) - setTokenFieldString(fields, "clientSecret", t.ClientSecret) - - for k, v := range t.UnknownFields { - if _, ok := fields[k]; ok { - return nil, fmt.Errorf("unknown token field %v, duplicates known field", k) - } - fields[k] = v - } - - return json.Marshal(fields) -} - -func setTokenFieldString(fields map[string]interface{}, key, value string) { - if value == "" { - return - } - fields[key] = value -} -func setTokenFieldRFC3339(fields map[string]interface{}, key string, value *rfc3339) { - if value == nil { - return - } - fields[key] = value -} - -func (t *token) UnmarshalJSON(b []byte) error { - var fields map[string]interface{} - if err := json.Unmarshal(b, &fields); err != nil { - return nil - } - - t.UnknownFields = map[string]interface{}{} - - for k, v := range fields { - var err error - switch k { - case "accessToken": - err = getTokenFieldString(v, &t.AccessToken) - case "expiresAt": - err = getTokenFieldRFC3339(v, &t.ExpiresAt) - case "refreshToken": - err = getTokenFieldString(v, &t.RefreshToken) - case "clientId": - err = getTokenFieldString(v, &t.ClientID) - case "clientSecret": - err = getTokenFieldString(v, &t.ClientSecret) - default: - t.UnknownFields[k] = v - } - - if err != nil { - return fmt.Errorf("field %q, %w", k, err) - } - } - - return nil -} - -func getTokenFieldString(v interface{}, value *string) error { - var ok bool - *value, ok = v.(string) - if !ok { - return fmt.Errorf("expect value to be string, got %T", v) - } - return nil -} - -func getTokenFieldRFC3339(v interface{}, value **rfc3339) error { - var stringValue string - if err := getTokenFieldString(v, &stringValue); err != nil { - return err - } - - timeValue, err := parseRFC3339(stringValue) - if err != nil { - return err - } - - *value = &timeValue - return nil -} - -func loadCachedToken(filename string) (token, error) { - fileBytes, err := ioutil.ReadFile(filename) - if err != nil { - return token{}, fmt.Errorf("failed to read cached SSO token file, %w", err) - } - - var t token - if err := json.Unmarshal(fileBytes, &t); err != nil { - return token{}, fmt.Errorf("failed to parse cached SSO token file, %w", err) - } - - if len(t.AccessToken) == 0 || t.ExpiresAt == nil || time.Time(*t.ExpiresAt).IsZero() { - return token{}, fmt.Errorf( - "cached SSO token must contain accessToken and expiresAt fields") - } - - return t, nil -} - -func storeCachedToken(filename string, t token, fileMode os.FileMode) (err error) { - tmpFilename := filename + ".tmp-" + strconv.FormatInt(sdk.NowTime().UnixNano(), 10) - if err := writeCacheFile(tmpFilename, fileMode, t); err != nil { - return err - } - - if err := os.Rename(tmpFilename, filename); err != nil { - return fmt.Errorf("failed to replace old cached SSO token file, %w", err) - } - - return nil -} - -func writeCacheFile(filename string, fileMode os.FileMode, t token) (err error) { - var f *os.File - f, err = os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_RDWR, fileMode) - if err != nil { - return fmt.Errorf("failed to create cached SSO token file %w", err) - } - - defer func() { - closeErr := f.Close() - if err == nil && closeErr != nil { - err = fmt.Errorf("failed to close cached SSO token file, %w", closeErr) - } - }() - - encoder := json.NewEncoder(f) - - if err = encoder.Encode(t); err != nil { - return fmt.Errorf("failed to serialize cached SSO token, %w", err) - } - - return nil -} - -type rfc3339 time.Time - -func parseRFC3339(v string) (rfc3339, error) { - parsed, err := time.Parse(time.RFC3339, v) - if err != nil { - return rfc3339{}, fmt.Errorf("expected RFC3339 timestamp: %w", err) - } - - return rfc3339(parsed), nil -} - -func (r *rfc3339) UnmarshalJSON(bytes []byte) (err error) { - var value string - - // Use JSON unmarshal to unescape the quoted value making use of JSON's - // unquoting rules. - if err = json.Unmarshal(bytes, &value); err != nil { - return err - } - - *r, err = parseRFC3339(value) - - return nil -} - -func (r *rfc3339) MarshalJSON() ([]byte, error) { - value := time.Time(*r).Format(time.RFC3339) - - // Use JSON unmarshal to unescape the quoted value making use of JSON's - // quoting rules. - return json.Marshal(value) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_credentials_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_credentials_provider.go deleted file mode 100644 index b3cf7853..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_credentials_provider.go +++ /dev/null @@ -1,152 +0,0 @@ -package ssocreds - -import ( - "context" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/aws-sdk-go-v2/service/sso" -) - -// ProviderName is the name of the provider used to specify the source of -// credentials. -const ProviderName = "SSOProvider" - -// GetRoleCredentialsAPIClient is a API client that implements the -// GetRoleCredentials operation. -type GetRoleCredentialsAPIClient interface { - GetRoleCredentials(context.Context, *sso.GetRoleCredentialsInput, ...func(*sso.Options)) ( - *sso.GetRoleCredentialsOutput, error, - ) -} - -// Options is the Provider options structure. -type Options struct { - // The Client which is configured for the AWS Region where the AWS SSO user - // portal is located. - Client GetRoleCredentialsAPIClient - - // The AWS account that is assigned to the user. - AccountID string - - // The role name that is assigned to the user. - RoleName string - - // The URL that points to the organization's AWS Single Sign-On (AWS SSO) - // user portal. - StartURL string - - // The filepath the cached token will be retrieved from. If unset Provider will - // use the startURL to determine the filepath at. - // - // ~/.aws/sso/cache/.json - // - // If custom cached token filepath is used, the Provider's startUrl - // parameter will be ignored. - CachedTokenFilepath string - - // Used by the SSOCredentialProvider if a token configuration - // profile is used in the shared config - SSOTokenProvider *SSOTokenProvider -} - -// Provider is an AWS credential provider that retrieves temporary AWS -// credentials by exchanging an SSO login token. -type Provider struct { - options Options - - cachedTokenFilepath string -} - -// New returns a new AWS Single Sign-On (AWS SSO) credential provider. The -// provided client is expected to be configured for the AWS Region where the -// AWS SSO user portal is located. -func New(client GetRoleCredentialsAPIClient, accountID, roleName, startURL string, optFns ...func(options *Options)) *Provider { - options := Options{ - Client: client, - AccountID: accountID, - RoleName: roleName, - StartURL: startURL, - } - - for _, fn := range optFns { - fn(&options) - } - - return &Provider{ - options: options, - cachedTokenFilepath: options.CachedTokenFilepath, - } -} - -// Retrieve retrieves temporary AWS credentials from the configured Amazon -// Single Sign-On (AWS SSO) user portal by exchanging the accessToken present -// in ~/.aws/sso/cache. However, if a token provider configuration exists -// in the shared config, then we ought to use the token provider rather then -// direct access on the cached token. -func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error) { - var accessToken *string - if p.options.SSOTokenProvider != nil { - token, err := p.options.SSOTokenProvider.RetrieveBearerToken(ctx) - if err != nil { - return aws.Credentials{}, err - } - accessToken = &token.Value - } else { - if p.cachedTokenFilepath == "" { - cachedTokenFilepath, err := StandardCachedTokenFilepath(p.options.StartURL) - if err != nil { - return aws.Credentials{}, &InvalidTokenError{Err: err} - } - p.cachedTokenFilepath = cachedTokenFilepath - } - - tokenFile, err := loadCachedToken(p.cachedTokenFilepath) - if err != nil { - return aws.Credentials{}, &InvalidTokenError{Err: err} - } - - if tokenFile.ExpiresAt == nil || sdk.NowTime().After(time.Time(*tokenFile.ExpiresAt)) { - return aws.Credentials{}, &InvalidTokenError{} - } - accessToken = &tokenFile.AccessToken - } - - output, err := p.options.Client.GetRoleCredentials(ctx, &sso.GetRoleCredentialsInput{ - AccessToken: accessToken, - AccountId: &p.options.AccountID, - RoleName: &p.options.RoleName, - }) - if err != nil { - return aws.Credentials{}, err - } - - return aws.Credentials{ - AccessKeyID: aws.ToString(output.RoleCredentials.AccessKeyId), - SecretAccessKey: aws.ToString(output.RoleCredentials.SecretAccessKey), - SessionToken: aws.ToString(output.RoleCredentials.SessionToken), - CanExpire: true, - Expires: time.Unix(0, output.RoleCredentials.Expiration*int64(time.Millisecond)).UTC(), - Source: ProviderName, - }, nil -} - -// InvalidTokenError is the error type that is returned if loaded token has -// expired or is otherwise invalid. To refresh the SSO session run AWS SSO -// login with the corresponding profile. -type InvalidTokenError struct { - Err error -} - -func (i *InvalidTokenError) Unwrap() error { - return i.Err -} - -func (i *InvalidTokenError) Error() string { - const msg = "the SSO session has expired or is invalid" - if i.Err == nil { - return msg - } - return msg + ": " + i.Err.Error() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_token_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_token_provider.go deleted file mode 100644 index 7f4fc546..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/ssocreds/sso_token_provider.go +++ /dev/null @@ -1,147 +0,0 @@ -package ssocreds - -import ( - "context" - "fmt" - "os" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/aws-sdk-go-v2/service/ssooidc" - "github.com/aws/smithy-go/auth/bearer" -) - -// CreateTokenAPIClient provides the interface for the SSOTokenProvider's API -// client for calling CreateToken operation to refresh the SSO token. -type CreateTokenAPIClient interface { - CreateToken(context.Context, *ssooidc.CreateTokenInput, ...func(*ssooidc.Options)) ( - *ssooidc.CreateTokenOutput, error, - ) -} - -// SSOTokenProviderOptions provides the options for configuring the -// SSOTokenProvider. -type SSOTokenProviderOptions struct { - // Client that can be overridden - Client CreateTokenAPIClient - - // The set of API Client options to be applied when invoking the - // CreateToken operation. - ClientOptions []func(*ssooidc.Options) - - // The path the file containing the cached SSO token will be read from. - // Initialized the NewSSOTokenProvider's cachedTokenFilepath parameter. - CachedTokenFilepath string -} - -// SSOTokenProvider provides an utility for refreshing SSO AccessTokens for -// Bearer Authentication. The SSOTokenProvider can only be used to refresh -// already cached SSO Tokens. This utility cannot perform the initial SSO -// create token. -// -// The SSOTokenProvider is not safe to use concurrently. It must be wrapped in -// a utility such as smithy-go's auth/bearer#TokenCache. The SDK's -// config.LoadDefaultConfig will automatically wrap the SSOTokenProvider with -// the smithy-go TokenCache, if the external configuration loaded configured -// for an SSO session. -// -// The initial SSO create token should be preformed with the AWS CLI before the -// Go application using the SSOTokenProvider will need to retrieve the SSO -// token. If the AWS CLI has not created the token cache file, this provider -// will return an error when attempting to retrieve the cached token. -// -// This provider will attempt to refresh the cached SSO token periodically if -// needed when RetrieveBearerToken is called. -// -// A utility such as the AWS CLI must be used to initially create the SSO -// session and cached token file. -// https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html -type SSOTokenProvider struct { - options SSOTokenProviderOptions -} - -var _ bearer.TokenProvider = (*SSOTokenProvider)(nil) - -// NewSSOTokenProvider returns an initialized SSOTokenProvider that will -// periodically refresh the SSO token cached stored in the cachedTokenFilepath. -// The cachedTokenFilepath file's content will be rewritten by the token -// provider when the token is refreshed. -// -// The client must be configured for the AWS region the SSO token was created for. -func NewSSOTokenProvider(client CreateTokenAPIClient, cachedTokenFilepath string, optFns ...func(o *SSOTokenProviderOptions)) *SSOTokenProvider { - options := SSOTokenProviderOptions{ - Client: client, - CachedTokenFilepath: cachedTokenFilepath, - } - for _, fn := range optFns { - fn(&options) - } - - provider := &SSOTokenProvider{ - options: options, - } - - return provider -} - -// RetrieveBearerToken returns the SSO token stored in the cachedTokenFilepath -// the SSOTokenProvider was created with. If the token has expired -// RetrieveBearerToken will attempt to refresh it. If the token cannot be -// refreshed or is not present an error will be returned. -// -// A utility such as the AWS CLI must be used to initially create the SSO -// session and cached token file. https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html -func (p SSOTokenProvider) RetrieveBearerToken(ctx context.Context) (bearer.Token, error) { - cachedToken, err := loadCachedToken(p.options.CachedTokenFilepath) - if err != nil { - return bearer.Token{}, err - } - - if cachedToken.ExpiresAt != nil && sdk.NowTime().After(time.Time(*cachedToken.ExpiresAt)) { - cachedToken, err = p.refreshToken(ctx, cachedToken) - if err != nil { - return bearer.Token{}, fmt.Errorf("refresh cached SSO token failed, %w", err) - } - } - - expiresAt := aws.ToTime((*time.Time)(cachedToken.ExpiresAt)) - return bearer.Token{ - Value: cachedToken.AccessToken, - CanExpire: !expiresAt.IsZero(), - Expires: expiresAt, - }, nil -} - -func (p SSOTokenProvider) refreshToken(ctx context.Context, cachedToken token) (token, error) { - if cachedToken.ClientSecret == "" || cachedToken.ClientID == "" || cachedToken.RefreshToken == "" { - return token{}, fmt.Errorf("cached SSO token is expired, or not present, and cannot be refreshed") - } - - createResult, err := p.options.Client.CreateToken(ctx, &ssooidc.CreateTokenInput{ - ClientId: &cachedToken.ClientID, - ClientSecret: &cachedToken.ClientSecret, - RefreshToken: &cachedToken.RefreshToken, - GrantType: aws.String("refresh_token"), - }, p.options.ClientOptions...) - if err != nil { - return token{}, fmt.Errorf("unable to refresh SSO token, %w", err) - } - - expiresAt := sdk.NowTime().Add(time.Duration(createResult.ExpiresIn) * time.Second) - - cachedToken.AccessToken = aws.ToString(createResult.AccessToken) - cachedToken.ExpiresAt = (*rfc3339)(&expiresAt) - cachedToken.RefreshToken = aws.ToString(createResult.RefreshToken) - - fileInfo, err := os.Stat(p.options.CachedTokenFilepath) - if err != nil { - return token{}, fmt.Errorf("failed to stat cached SSO token file %w", err) - } - - if err = storeCachedToken(p.options.CachedTokenFilepath, cachedToken, fileInfo.Mode()); err != nil { - return token{}, fmt.Errorf("unable to cache refreshed SSO token, %w", err) - } - - return cachedToken, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/static_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/static_provider.go deleted file mode 100644 index d525cac0..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/static_provider.go +++ /dev/null @@ -1,53 +0,0 @@ -package credentials - -import ( - "context" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -const ( - // StaticCredentialsName provides a name of Static provider - StaticCredentialsName = "StaticCredentials" -) - -// StaticCredentialsEmptyError is emitted when static credentials are empty. -type StaticCredentialsEmptyError struct{} - -func (*StaticCredentialsEmptyError) Error() string { - return "static credentials are empty" -} - -// A StaticCredentialsProvider is a set of credentials which are set, and will -// never expire. -type StaticCredentialsProvider struct { - Value aws.Credentials -} - -// NewStaticCredentialsProvider return a StaticCredentialsProvider initialized with the AWS -// credentials passed in. -func NewStaticCredentialsProvider(key, secret, session string) StaticCredentialsProvider { - return StaticCredentialsProvider{ - Value: aws.Credentials{ - AccessKeyID: key, - SecretAccessKey: secret, - SessionToken: session, - }, - } -} - -// Retrieve returns the credentials or error if the credentials are invalid. -func (s StaticCredentialsProvider) Retrieve(_ context.Context) (aws.Credentials, error) { - v := s.Value - if v.AccessKeyID == "" || v.SecretAccessKey == "" { - return aws.Credentials{ - Source: StaticCredentialsName, - }, &StaticCredentialsEmptyError{} - } - - if len(v.Source) == 0 { - v.Source = StaticCredentialsName - } - - return v, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/assume_role_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/assume_role_provider.go deleted file mode 100644 index 289707b6..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/assume_role_provider.go +++ /dev/null @@ -1,320 +0,0 @@ -// Package stscreds are credential Providers to retrieve STS AWS credentials. -// -// STS provides multiple ways to retrieve credentials which can be used when making -// future AWS service API operation calls. -// -// The SDK will ensure that per instance of credentials.Credentials all requests -// to refresh the credentials will be synchronized. But, the SDK is unable to -// ensure synchronous usage of the AssumeRoleProvider if the value is shared -// between multiple Credentials or service clients. -// -// # Assume Role -// -// To assume an IAM role using STS with the SDK you can create a new Credentials -// with the SDKs's stscreds package. -// -// // Initial credentials loaded from SDK's default credential chain. Such as -// // the environment, shared credentials (~/.aws/credentials), or EC2 Instance -// // Role. These credentials will be used to to make the STS Assume Role API. -// cfg, err := config.LoadDefaultConfig(context.TODO()) -// if err != nil { -// panic(err) -// } -// -// // Create the credentials from AssumeRoleProvider to assume the role -// // referenced by the "myRoleARN" ARN. -// stsSvc := sts.NewFromConfig(cfg) -// creds := stscreds.NewAssumeRoleProvider(stsSvc, "myRoleArn") -// -// cfg.Credentials = aws.NewCredentialsCache(creds) -// -// // Create service client value configured for credentials -// // from assumed role. -// svc := s3.NewFromConfig(cfg) -// -// # Assume Role with custom MFA Token provider -// -// To assume an IAM role with a MFA token you can either specify a custom MFA -// token provider or use the SDK's built in StdinTokenProvider that will prompt -// the user for a token code each time the credentials need to to be refreshed. -// Specifying a custom token provider allows you to control where the token -// code is retrieved from, and how it is refreshed. -// -// With a custom token provider, the provider is responsible for refreshing the -// token code when called. -// -// cfg, err := config.LoadDefaultConfig(context.TODO()) -// if err != nil { -// panic(err) -// } -// -// staticTokenProvider := func() (string, error) { -// return someTokenCode, nil -// } -// -// // Create the credentials from AssumeRoleProvider to assume the role -// // referenced by the "myRoleARN" ARN using the MFA token code provided. -// creds := stscreds.NewAssumeRoleProvider(sts.NewFromConfig(cfg), "myRoleArn", func(o *stscreds.AssumeRoleOptions) { -// o.SerialNumber = aws.String("myTokenSerialNumber") -// o.TokenProvider = staticTokenProvider -// }) -// -// cfg.Credentials = aws.NewCredentialsCache(creds) -// -// // Create service client value configured for credentials -// // from assumed role. -// svc := s3.NewFromConfig(cfg) -// -// # Assume Role with MFA Token Provider -// -// To assume an IAM role with MFA for longer running tasks where the credentials -// may need to be refreshed setting the TokenProvider field of AssumeRoleProvider -// will allow the credential provider to prompt for new MFA token code when the -// role's credentials need to be refreshed. -// -// The StdinTokenProvider function is available to prompt on stdin to retrieve -// the MFA token code from the user. You can also implement custom prompts by -// satisfying the TokenProvider function signature. -// -// Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -// have undesirable results as the StdinTokenProvider will not be synchronized. A -// single Credentials with an AssumeRoleProvider can be shared safely. -// -// cfg, err := config.LoadDefaultConfig(context.TODO()) -// if err != nil { -// panic(err) -// } -// -// // Create the credentials from AssumeRoleProvider to assume the role -// // referenced by the "myRoleARN" ARN using the MFA token code provided. -// creds := stscreds.NewAssumeRoleProvider(sts.NewFromConfig(cfg), "myRoleArn", func(o *stscreds.AssumeRoleOptions) { -// o.SerialNumber = aws.String("myTokenSerialNumber") -// o.TokenProvider = stscreds.StdinTokenProvider -// }) -// -// cfg.Credentials = aws.NewCredentialsCache(creds) -// -// // Create service client value configured for credentials -// // from assumed role. -// svc := s3.NewFromConfig(cfg) -package stscreds - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/service/sts" - "github.com/aws/aws-sdk-go-v2/service/sts/types" -) - -// StdinTokenProvider will prompt on stdout and read from stdin for a string value. -// An error is returned if reading from stdin fails. -// -// Use this function go read MFA tokens from stdin. The function makes no attempt -// to make atomic prompts from stdin across multiple gorouties. -// -// Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -// have undesirable results as the StdinTokenProvider will not be synchronized. A -// single Credentials with an AssumeRoleProvider can be shared safely -// -// Will wait forever until something is provided on the stdin. -func StdinTokenProvider() (string, error) { - var v string - fmt.Printf("Assume Role MFA token code: ") - _, err := fmt.Scanln(&v) - - return v, err -} - -// ProviderName provides a name of AssumeRole provider -const ProviderName = "AssumeRoleProvider" - -// AssumeRoleAPIClient is a client capable of the STS AssumeRole operation. -type AssumeRoleAPIClient interface { - AssumeRole(ctx context.Context, params *sts.AssumeRoleInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleOutput, error) -} - -// DefaultDuration is the default amount of time in minutes that the -// credentials will be valid for. This value is only used by AssumeRoleProvider -// for specifying the default expiry duration of an assume role. -// -// Other providers such as WebIdentityRoleProvider do not use this value, and -// instead rely on STS API's default parameter handing to assign a default -// value. -var DefaultDuration = time.Duration(15) * time.Minute - -// AssumeRoleProvider retrieves temporary credentials from the STS service, and -// keeps track of their expiration time. -// -// This credential provider will be used by the SDKs default credential change -// when shared configuration is enabled, and the shared config or shared credentials -// file configure assume role. See Session docs for how to do this. -// -// AssumeRoleProvider does not provide any synchronization and it is not safe -// to share this value across multiple Credentials, Sessions, or service clients -// without also sharing the same Credentials instance. -type AssumeRoleProvider struct { - options AssumeRoleOptions -} - -// AssumeRoleOptions is the configurable options for AssumeRoleProvider -type AssumeRoleOptions struct { - // Client implementation of the AssumeRole operation. Required - Client AssumeRoleAPIClient - - // IAM Role ARN to be assumed. Required - RoleARN string - - // Session name, if you wish to uniquely identify this session. - RoleSessionName string - - // Expiry duration of the STS credentials. Defaults to 15 minutes if not set. - Duration time.Duration - - // Optional ExternalID to pass along, defaults to nil if not set. - ExternalID *string - - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - Policy *string - - // The ARNs of IAM managed policies you want to use as managed session policies. - // The policies must exist in the same account as the role. - // - // This parameter is optional. You can provide up to 10 managed policy ARNs. - // However, the plain text that you use for both inline and managed session - // policies can't exceed 2,048 characters. - // - // An AWS conversion compresses the passed session policies and session tags - // into a packed binary format that has a separate limit. Your request can fail - // for this limit even if your plain text meets the other requirements. The - // PackedPolicySize response element indicates by percentage how close the policies - // and tags for your request are to the upper size limit. - // - // Passing policies to this operation returns new temporary credentials. The - // resulting session's permissions are the intersection of the role's identity-based - // policy and the session policies. You can use the role's temporary credentials - // in subsequent AWS API calls to access resources in the account that owns - // the role. You cannot use session policies to grant more permissions than - // those allowed by the identity-based policy of the role that is being assumed. - // For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyARNs []types.PolicyDescriptorType - - // The identification number of the MFA device that is associated with the user - // who is making the AssumeRole call. Specify this value if the trust policy - // of the role being assumed includes a condition that requires MFA authentication. - // The value is either the serial number for a hardware device (such as GAHT12345678) - // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). - SerialNumber *string - - // The source identity specified by the principal that is calling the AssumeRole - // operation. You can require users to specify a source identity when they assume a - // role. You do this by using the sts:SourceIdentity condition key in a role trust - // policy. You can use source identity information in CloudTrail logs to determine - // who took actions with a role. You can use the aws:SourceIdentity condition key - // to further control access to Amazon Web Services resources based on the value of - // source identity. For more information about using source identity, see Monitor - // and control actions taken with assumed roles - // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. - SourceIdentity *string - - // Async method of providing MFA token code for assuming an IAM role with MFA. - // The value returned by the function will be used as the TokenCode in the Retrieve - // call. See StdinTokenProvider for a provider that prompts and reads from stdin. - // - // This token provider will be called when ever the assumed role's - // credentials need to be refreshed when SerialNumber is set. - TokenProvider func() (string, error) - - // A list of session tags that you want to pass. Each session tag consists of a key - // name and an associated value. For more information about session tags, see - // Tagging STS Sessions - // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) in the - // IAM User Guide. This parameter is optional. You can pass up to 50 session tags. - Tags []types.Tag - - // A list of keys for session tags that you want to set as transitive. If you set a - // tag key as transitive, the corresponding key and value passes to subsequent - // sessions in a role chain. For more information, see Chaining Roles with Session - // Tags - // (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) - // in the IAM User Guide. This parameter is optional. - TransitiveTagKeys []string -} - -// NewAssumeRoleProvider constructs and returns a credentials provider that -// will retrieve credentials by assuming a IAM role using STS. -func NewAssumeRoleProvider(client AssumeRoleAPIClient, roleARN string, optFns ...func(*AssumeRoleOptions)) *AssumeRoleProvider { - o := AssumeRoleOptions{ - Client: client, - RoleARN: roleARN, - } - - for _, fn := range optFns { - fn(&o) - } - - return &AssumeRoleProvider{ - options: o, - } -} - -// Retrieve generates a new set of temporary credentials using STS. -func (p *AssumeRoleProvider) Retrieve(ctx context.Context) (aws.Credentials, error) { - // Apply defaults where parameters are not set. - if len(p.options.RoleSessionName) == 0 { - // Try to work out a role name that will hopefully end up unique. - p.options.RoleSessionName = fmt.Sprintf("aws-go-sdk-%d", time.Now().UTC().UnixNano()) - } - if p.options.Duration == 0 { - // Expire as often as AWS permits. - p.options.Duration = DefaultDuration - } - input := &sts.AssumeRoleInput{ - DurationSeconds: aws.Int32(int32(p.options.Duration / time.Second)), - PolicyArns: p.options.PolicyARNs, - RoleArn: aws.String(p.options.RoleARN), - RoleSessionName: aws.String(p.options.RoleSessionName), - ExternalId: p.options.ExternalID, - SourceIdentity: p.options.SourceIdentity, - Tags: p.options.Tags, - TransitiveTagKeys: p.options.TransitiveTagKeys, - } - if p.options.Policy != nil { - input.Policy = p.options.Policy - } - if p.options.SerialNumber != nil { - if p.options.TokenProvider != nil { - input.SerialNumber = p.options.SerialNumber - code, err := p.options.TokenProvider() - if err != nil { - return aws.Credentials{}, err - } - input.TokenCode = aws.String(code) - } else { - return aws.Credentials{}, fmt.Errorf("assume role with MFA enabled, but TokenProvider is not set") - } - } - - resp, err := p.options.Client.AssumeRole(ctx, input) - if err != nil { - return aws.Credentials{Source: ProviderName}, err - } - - return aws.Credentials{ - AccessKeyID: *resp.Credentials.AccessKeyId, - SecretAccessKey: *resp.Credentials.SecretAccessKey, - SessionToken: *resp.Credentials.SessionToken, - Source: ProviderName, - - CanExpire: true, - Expires: *resp.Credentials.Expiration, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/web_identity_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/web_identity_provider.go deleted file mode 100644 index ddaf6df6..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/credentials/stscreds/web_identity_provider.go +++ /dev/null @@ -1,150 +0,0 @@ -package stscreds - -import ( - "context" - "fmt" - "io/ioutil" - "strconv" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/retry" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/aws-sdk-go-v2/service/sts" - "github.com/aws/aws-sdk-go-v2/service/sts/types" -) - -var invalidIdentityTokenExceptionCode = (&types.InvalidIdentityTokenException{}).ErrorCode() - -const ( - // WebIdentityProviderName is the web identity provider name - WebIdentityProviderName = "WebIdentityCredentials" -) - -// AssumeRoleWithWebIdentityAPIClient is a client capable of the STS AssumeRoleWithWebIdentity operation. -type AssumeRoleWithWebIdentityAPIClient interface { - AssumeRoleWithWebIdentity(ctx context.Context, params *sts.AssumeRoleWithWebIdentityInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleWithWebIdentityOutput, error) -} - -// WebIdentityRoleProvider is used to retrieve credentials using -// an OIDC token. -type WebIdentityRoleProvider struct { - options WebIdentityRoleOptions -} - -// WebIdentityRoleOptions is a structure of configurable options for WebIdentityRoleProvider -type WebIdentityRoleOptions struct { - // Client implementation of the AssumeRoleWithWebIdentity operation. Required - Client AssumeRoleWithWebIdentityAPIClient - - // JWT Token Provider. Required - TokenRetriever IdentityTokenRetriever - - // IAM Role ARN to assume. Required - RoleARN string - - // Session name, if you wish to uniquely identify this session. - RoleSessionName string - - // Expiry duration of the STS credentials. STS will assign a default expiry - // duration if this value is unset. This is different from the Duration - // option of AssumeRoleProvider, which automatically assigns 15 minutes if - // Duration is unset. - // - // See the STS AssumeRoleWithWebIdentity API reference guide for more - // information on defaults. - // https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html - Duration time.Duration - - // An IAM policy in JSON format that you want to use as an inline session policy. - Policy *string - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you - // want to use as managed session policies. The policies must exist in the - // same account as the role. - PolicyARNs []types.PolicyDescriptorType -} - -// IdentityTokenRetriever is an interface for retrieving a JWT -type IdentityTokenRetriever interface { - GetIdentityToken() ([]byte, error) -} - -// IdentityTokenFile is for retrieving an identity token from the given file name -type IdentityTokenFile string - -// GetIdentityToken retrieves the JWT token from the file and returns the contents as a []byte -func (j IdentityTokenFile) GetIdentityToken() ([]byte, error) { - b, err := ioutil.ReadFile(string(j)) - if err != nil { - return nil, fmt.Errorf("unable to read file at %s: %v", string(j), err) - } - - return b, nil -} - -// NewWebIdentityRoleProvider will return a new WebIdentityRoleProvider with the -// provided stsiface.ClientAPI -func NewWebIdentityRoleProvider(client AssumeRoleWithWebIdentityAPIClient, roleARN string, tokenRetriever IdentityTokenRetriever, optFns ...func(*WebIdentityRoleOptions)) *WebIdentityRoleProvider { - o := WebIdentityRoleOptions{ - Client: client, - RoleARN: roleARN, - TokenRetriever: tokenRetriever, - } - - for _, fn := range optFns { - fn(&o) - } - - return &WebIdentityRoleProvider{options: o} -} - -// Retrieve will attempt to assume a role from a token which is located at -// 'WebIdentityTokenFilePath' specified destination and if that is empty an -// error will be returned. -func (p *WebIdentityRoleProvider) Retrieve(ctx context.Context) (aws.Credentials, error) { - b, err := p.options.TokenRetriever.GetIdentityToken() - if err != nil { - return aws.Credentials{}, fmt.Errorf("failed to retrieve jwt from provide source, %w", err) - } - - sessionName := p.options.RoleSessionName - if len(sessionName) == 0 { - // session name is used to uniquely identify a session. This simply - // uses unix time in nanoseconds to uniquely identify sessions. - sessionName = strconv.FormatInt(sdk.NowTime().UnixNano(), 10) - } - input := &sts.AssumeRoleWithWebIdentityInput{ - PolicyArns: p.options.PolicyARNs, - RoleArn: &p.options.RoleARN, - RoleSessionName: &sessionName, - WebIdentityToken: aws.String(string(b)), - } - if p.options.Duration != 0 { - // If set use the value, otherwise STS will assign a default expiration duration. - input.DurationSeconds = aws.Int32(int32(p.options.Duration / time.Second)) - } - if p.options.Policy != nil { - input.Policy = p.options.Policy - } - - resp, err := p.options.Client.AssumeRoleWithWebIdentity(ctx, input, func(options *sts.Options) { - options.Retryer = retry.AddWithErrorCodes(options.Retryer, invalidIdentityTokenExceptionCode) - }) - if err != nil { - return aws.Credentials{}, fmt.Errorf("failed to retrieve credentials, %w", err) - } - - // InvalidIdentityToken error is a temporary error that can occur - // when assuming an Role with a JWT web identity token. - - value := aws.Credentials{ - AccessKeyID: aws.ToString(resp.Credentials.AccessKeyId), - SecretAccessKey: aws.ToString(resp.Credentials.SecretAccessKey), - SessionToken: aws.ToString(resp.Credentials.SessionToken), - Source: WebIdentityProviderName, - CanExpire: true, - Expires: *resp.Credentials.Expiration, - } - return value, nil -} 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 deleted file mode 100644 index 40c317a9..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/CHANGELOG.md +++ /dev/null @@ -1,285 +0,0 @@ -# v1.14.11 (2024-01-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.10 (2023-12-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.9 (2023-12-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.8 (2023-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.7 (2023-11-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.6 (2023-11-28.2) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.5 (2023-11-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.4 (2023-11-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.3 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.2 (2023-11-02) - -* No change notes available for this release. - -# v1.14.1 (2023-11-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.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.13.13 (2023-10-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.12 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.11 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.10 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.9 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.8 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.7 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.6 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.5 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.4 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.3 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.2 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.1 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2023-03-14) - -* **Feature**: Add flag to disable IMDSv1 fallback - -# v1.12.24 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.23 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.22 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.21 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.20 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.19 (2022-10-24) - -* **Bug Fix**: Fixes an issue that prevented logging of the API request or responses when the respective log modes were enabled. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.18 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.17 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.16 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.15 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.14 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.13 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.12 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.11 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.10 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.9 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.8 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.7 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.6 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.5 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2022-02-24) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.2 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2021-11-06) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-10-11) - -* **Feature**: Respect passed in Context Deadline/Timeout. Updates the IMDS Client operations to not override the passed in Context's Deadline or Timeout options. If an Client operation is called with a Context with a Deadline or Timeout, the client will no longer override it with the client's default timeout. -* **Bug Fix**: Fix IMDS client's response handling and operation timeout race. Fixes #1253 -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.1 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.1 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-08-04) - -* **Feature**: adds error handling for defered close calls -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-07-15) - -* **Feature**: Support has been added for EC2 IPv6-enabled Instance Metadata Service Endpoints. -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/feature/ec2/imds/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_client.go deleted file mode 100644 index 46e144d9..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_client.go +++ /dev/null @@ -1,348 +0,0 @@ -package imds - -import ( - "context" - "fmt" - "net" - "net/http" - "os" - "strings" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/retry" - awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" - internalconfig "github.com/aws/aws-sdk-go-v2/feature/ec2/imds/internal/config" - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// ServiceID provides the unique name of this API client -const ServiceID = "ec2imds" - -// Client provides the API client for interacting with the Amazon EC2 Instance -// Metadata Service API. -type Client struct { - options Options -} - -// ClientEnableState provides an enumeration if the client is enabled, -// disabled, or default behavior. -type ClientEnableState = internalconfig.ClientEnableState - -// Enumeration values for ClientEnableState -const ( - ClientDefaultEnableState ClientEnableState = internalconfig.ClientDefaultEnableState // default behavior - ClientDisabled ClientEnableState = internalconfig.ClientDisabled // client disabled - ClientEnabled ClientEnableState = internalconfig.ClientEnabled // client enabled -) - -// EndpointModeState is an enum configuration variable describing the client endpoint mode. -// Not configurable directly, but used when using the NewFromConfig. -type EndpointModeState = internalconfig.EndpointModeState - -// Enumeration values for EndpointModeState -const ( - EndpointModeStateUnset EndpointModeState = internalconfig.EndpointModeStateUnset - EndpointModeStateIPv4 EndpointModeState = internalconfig.EndpointModeStateIPv4 - EndpointModeStateIPv6 EndpointModeState = internalconfig.EndpointModeStateIPv6 -) - -const ( - disableClientEnvVar = "AWS_EC2_METADATA_DISABLED" - - // Client endpoint options - endpointEnvVar = "AWS_EC2_METADATA_SERVICE_ENDPOINT" - - defaultIPv4Endpoint = "http://169.254.169.254" - defaultIPv6Endpoint = "http://[fd00:ec2::254]" -) - -// 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() - - for _, fn := range optFns { - fn(&options) - } - - options.HTTPClient = resolveHTTPClient(options.HTTPClient) - - if options.Retryer == nil { - options.Retryer = retry.NewStandard() - } - options.Retryer = retry.AddWithMaxBackoffDelay(options.Retryer, 1*time.Second) - - if options.ClientEnableState == ClientDefaultEnableState { - if v := os.Getenv(disableClientEnvVar); strings.EqualFold(v, "true") { - options.ClientEnableState = ClientDisabled - } - } - - if len(options.Endpoint) == 0 { - if v := os.Getenv(endpointEnvVar); len(v) != 0 { - options.Endpoint = v - } - } - - client := &Client{ - options: options, - } - - if client.options.tokenProvider == nil && !client.options.disableAPIToken { - client.options.tokenProvider = newTokenProvider(client, defaultTokenTTL) - } - - return client -} - -// NewFromConfig returns an initialized Client based the AWS SDK config, and -// 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 NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { - opts := Options{ - APIOptions: append([]func(*middleware.Stack) error{}, cfg.APIOptions...), - HTTPClient: cfg.HTTPClient, - ClientLogMode: cfg.ClientLogMode, - Logger: cfg.Logger, - } - - if cfg.Retryer != nil { - opts.Retryer = cfg.Retryer() - } - - resolveClientEnableState(cfg, &opts) - resolveEndpointConfig(cfg, &opts) - resolveEndpointModeConfig(cfg, &opts) - resolveEnableFallback(cfg, &opts) - - return New(opts, optFns...) -} - -// Options provides the fields for configuring the API client's behavior. -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 endpoint the client will use to retrieve EC2 instance metadata. - // - // Specifies the EC2 Instance Metadata Service endpoint to use. If specified it overrides EndpointMode. - // - // If unset, and the environment variable AWS_EC2_METADATA_SERVICE_ENDPOINT - // has a value the client will use the value of the environment variable as - // the endpoint for operation calls. - // - // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] - Endpoint string - - // The endpoint selection mode the client will use if no explicit endpoint is provided using the Endpoint field. - // - // Setting EndpointMode to EndpointModeStateIPv4 will configure the client to use the default EC2 IPv4 endpoint. - // Setting EndpointMode to EndpointModeStateIPv6 will configure the client to use the default EC2 IPv6 endpoint. - // - // By default if EndpointMode is not set (EndpointModeStateUnset) than the default endpoint selection mode EndpointModeStateIPv4. - EndpointMode EndpointModeState - - // The HTTP client to invoke API calls with. Defaults to client's default - // HTTP implementation if nil. - HTTPClient HTTPClient - - // Retryer guides how HTTP requests should be retried in case of recoverable - // failures. When nil the API client will use a default retryer. - Retryer aws.Retryer - - // Changes if the EC2 Instance Metadata client is enabled or not. Client - // will default to enabled if not set to ClientDisabled. When the client is - // disabled it will return an error for all operation calls. - // - // If ClientEnableState value is ClientDefaultEnableState (default value), - // and the environment variable "AWS_EC2_METADATA_DISABLED" is set to - // "true", the client will be disabled. - // - // AWS_EC2_METADATA_DISABLED=true - ClientEnableState ClientEnableState - - // Configures the events that will be sent to the configured logger. - ClientLogMode aws.ClientLogMode - - // The logger writer interface to write logging messages to. - Logger logging.Logger - - // Configure IMDSv1 fallback behavior. By default, the client will attempt - // to fall back to IMDSv1 as needed for backwards compatibility. When set to [aws.FalseTernary] - // the client will return any errors encountered from attempting to fetch a token - // instead of silently using the insecure data flow of IMDSv1. - // - // See [configuring IMDS] for more information. - // - // [configuring IMDS]: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html - EnableFallback aws.Ternary - - // provides the caching of API tokens used for operation calls. If unset, - // the API token will not be retrieved for the operation. - tokenProvider *tokenProvider - - // option to disable the API token provider for testing. - disableAPIToken bool -} - -// HTTPClient provides the interface for a client making HTTP requests with the -// API. -type HTTPClient interface { - Do(*http.Request) (*http.Response, error) -} - -// Copy creates a copy of the API options. -func (o Options) Copy() Options { - to := o - to.APIOptions = append([]func(*middleware.Stack) error{}, o.APIOptions...) - return to -} - -// WithAPIOptions wraps the API middleware functions, as a functional option -// for the API Client Options. Use this helper to add additional functional -// options to the API client, or operation calls. -func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) { - return func(o *Options) { - o.APIOptions = append(o.APIOptions, optFns...) - } -} - -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, -) { - stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) - options := c.options.Copy() - for _, fn := range optFns { - fn(&options) - } - - if options.ClientEnableState == ClientDisabled { - return nil, metadata, &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: fmt.Errorf( - "access disabled to EC2 IMDS via client option, or %q environment variable", - disableClientEnvVar), - } - } - - for _, fn := range stackFns { - if err := fn(stack, options); err != nil { - return nil, metadata, err - } - } - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, metadata, err - } - } - - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) - if err != nil { - return nil, metadata, &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: err, - } - } - - return result, metadata, err -} - -const ( - // HTTP client constants - defaultDialerTimeout = 250 * time.Millisecond - defaultResponseHeaderTimeout = 500 * time.Millisecond -) - -func resolveHTTPClient(client HTTPClient) HTTPClient { - if client == nil { - client = awshttp.NewBuildableClient() - } - - if c, ok := client.(*awshttp.BuildableClient); ok { - client = c. - WithDialerOptions(func(d *net.Dialer) { - // Use a custom Dial timeout for the EC2 Metadata service to account - // for the possibility the application might not be running in an - // environment with the service present. The client should fail fast in - // this case. - d.Timeout = defaultDialerTimeout - }). - WithTransportOptions(func(tr *http.Transport) { - // Use a custom Transport timeout for the EC2 Metadata service to - // account for the possibility that the application might be running in - // a container, and EC2Metadata service drops the connection after a - // single IP Hop. The client should fail fast in this case. - tr.ResponseHeaderTimeout = defaultResponseHeaderTimeout - }) - } - - return client -} - -func resolveClientEnableState(cfg aws.Config, options *Options) error { - if options.ClientEnableState != ClientDefaultEnableState { - return nil - } - value, found, err := internalconfig.ResolveClientEnableState(cfg.ConfigSources) - if err != nil || !found { - return err - } - options.ClientEnableState = value - return nil -} - -func resolveEndpointModeConfig(cfg aws.Config, options *Options) error { - if options.EndpointMode != EndpointModeStateUnset { - return nil - } - value, found, err := internalconfig.ResolveEndpointModeConfig(cfg.ConfigSources) - if err != nil || !found { - return err - } - options.EndpointMode = value - return nil -} - -func resolveEndpointConfig(cfg aws.Config, options *Options) error { - if len(options.Endpoint) != 0 { - return nil - } - value, found, err := internalconfig.ResolveEndpointConfig(cfg.ConfigSources) - if err != nil || !found { - return err - } - options.Endpoint = value - return nil -} - -func resolveEnableFallback(cfg aws.Config, options *Options) { - if options.EnableFallback != aws.UnknownTernary { - return - } - - disabled, ok := internalconfig.ResolveV1FallbackDisabled(cfg.ConfigSources) - if !ok { - return - } - - if disabled { - options.EnableFallback = aws.FalseTernary - } else { - options.EnableFallback = aws.TrueTernary - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetDynamicData.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetDynamicData.go deleted file mode 100644 index af58b6bb..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetDynamicData.go +++ /dev/null @@ -1,77 +0,0 @@ -package imds - -import ( - "context" - "fmt" - "io" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getDynamicDataPath = "/latest/dynamic" - -// GetDynamicData uses the path provided to request information from the EC2 -// instance metadata service for dynamic data. The content will be returned -// as a string, or error if the request failed. -func (c *Client) GetDynamicData(ctx context.Context, params *GetDynamicDataInput, optFns ...func(*Options)) (*GetDynamicDataOutput, error) { - if params == nil { - params = &GetDynamicDataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetDynamicData", params, optFns, - addGetDynamicDataMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetDynamicDataOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetDynamicDataInput provides the input parameters for the GetDynamicData -// operation. -type GetDynamicDataInput struct { - // The relative dynamic data path to retrieve. Can be empty string to - // retrieve a response containing a new line separated list of dynamic data - // resources available. - // - // Must not include the dynamic data base path. - // - // May include leading slash. If Path includes trailing slash the trailing - // slash will be included in the request for the resource. - Path string -} - -// GetDynamicDataOutput provides the output parameters for the GetDynamicData -// operation. -type GetDynamicDataOutput struct { - Content io.ReadCloser - - ResultMetadata middleware.Metadata -} - -func addGetDynamicDataMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - "GetDynamicData", - buildGetDynamicDataPath, - buildGetDynamicDataOutput) -} - -func buildGetDynamicDataPath(params interface{}) (string, error) { - p, ok := params.(*GetDynamicDataInput) - if !ok { - return "", fmt.Errorf("unknown parameter type %T", params) - } - - return appendURIPath(getDynamicDataPath, p.Path), nil -} - -func buildGetDynamicDataOutput(resp *smithyhttp.Response) (interface{}, error) { - return &GetDynamicDataOutput{ - Content: resp.Body, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetIAMInfo.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetIAMInfo.go deleted file mode 100644 index 5111cc90..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetIAMInfo.go +++ /dev/null @@ -1,103 +0,0 @@ -package imds - -import ( - "context" - "encoding/json" - "fmt" - "io" - "strings" - "time" - - "github.com/aws/smithy-go" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getIAMInfoPath = getMetadataPath + "/iam/info" - -// GetIAMInfo retrieves an identity document describing an -// instance. Error is returned if the request fails or is unable to parse -// the response. -func (c *Client) GetIAMInfo( - ctx context.Context, params *GetIAMInfoInput, optFns ...func(*Options), -) ( - *GetIAMInfoOutput, error, -) { - if params == nil { - params = &GetIAMInfoInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetIAMInfo", params, optFns, - addGetIAMInfoMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetIAMInfoOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetIAMInfoInput provides the input parameters for GetIAMInfo operation. -type GetIAMInfoInput struct{} - -// GetIAMInfoOutput provides the output parameters for GetIAMInfo operation. -type GetIAMInfoOutput struct { - IAMInfo - - ResultMetadata middleware.Metadata -} - -func addGetIAMInfoMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - "GetIAMInfo", - buildGetIAMInfoPath, - buildGetIAMInfoOutput, - ) -} - -func buildGetIAMInfoPath(params interface{}) (string, error) { - return getIAMInfoPath, nil -} - -func buildGetIAMInfoOutput(resp *smithyhttp.Response) (v interface{}, err error) { - defer func() { - closeErr := resp.Body.Close() - if err == nil { - err = closeErr - } else if closeErr != nil { - err = fmt.Errorf("response body close error: %v, original error: %w", closeErr, err) - } - }() - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(resp.Body, ringBuffer) - - imdsResult := &GetIAMInfoOutput{} - if err = json.NewDecoder(body).Decode(&imdsResult.IAMInfo); err != nil { - return nil, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode instance identity document, %w", err), - Snapshot: ringBuffer.Bytes(), - } - } - // Any code other success is an error - if !strings.EqualFold(imdsResult.Code, "success") { - return nil, fmt.Errorf("failed to get EC2 IMDS IAM info, %s", - imdsResult.Code) - } - - return imdsResult, nil -} - -// IAMInfo provides the shape for unmarshaling an IAM info from the metadata -// API. -type IAMInfo struct { - Code string - LastUpdated time.Time - InstanceProfileArn string - InstanceProfileID string -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetInstanceIdentityDocument.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetInstanceIdentityDocument.go deleted file mode 100644 index dc8c09ed..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetInstanceIdentityDocument.go +++ /dev/null @@ -1,110 +0,0 @@ -package imds - -import ( - "context" - "encoding/json" - "fmt" - "io" - "time" - - "github.com/aws/smithy-go" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getInstanceIdentityDocumentPath = getDynamicDataPath + "/instance-identity/document" - -// GetInstanceIdentityDocument retrieves an identity document describing an -// instance. Error is returned if the request fails or is unable to parse -// the response. -func (c *Client) GetInstanceIdentityDocument( - ctx context.Context, params *GetInstanceIdentityDocumentInput, optFns ...func(*Options), -) ( - *GetInstanceIdentityDocumentOutput, error, -) { - if params == nil { - params = &GetInstanceIdentityDocumentInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetInstanceIdentityDocument", params, optFns, - addGetInstanceIdentityDocumentMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetInstanceIdentityDocumentOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetInstanceIdentityDocumentInput provides the input parameters for -// GetInstanceIdentityDocument operation. -type GetInstanceIdentityDocumentInput struct{} - -// GetInstanceIdentityDocumentOutput provides the output parameters for -// GetInstanceIdentityDocument operation. -type GetInstanceIdentityDocumentOutput struct { - InstanceIdentityDocument - - ResultMetadata middleware.Metadata -} - -func addGetInstanceIdentityDocumentMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - "GetInstanceIdentityDocument", - buildGetInstanceIdentityDocumentPath, - buildGetInstanceIdentityDocumentOutput, - ) -} - -func buildGetInstanceIdentityDocumentPath(params interface{}) (string, error) { - return getInstanceIdentityDocumentPath, nil -} - -func buildGetInstanceIdentityDocumentOutput(resp *smithyhttp.Response) (v interface{}, err error) { - defer func() { - closeErr := resp.Body.Close() - if err == nil { - err = closeErr - } else if closeErr != nil { - err = fmt.Errorf("response body close error: %v, original error: %w", closeErr, err) - } - }() - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(resp.Body, ringBuffer) - - output := &GetInstanceIdentityDocumentOutput{} - if err = json.NewDecoder(body).Decode(&output.InstanceIdentityDocument); err != nil { - return nil, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode instance identity document, %w", err), - Snapshot: ringBuffer.Bytes(), - } - } - - return output, nil -} - -// InstanceIdentityDocument provides the shape for unmarshaling -// an instance identity document -type InstanceIdentityDocument struct { - DevpayProductCodes []string `json:"devpayProductCodes"` - MarketplaceProductCodes []string `json:"marketplaceProductCodes"` - AvailabilityZone string `json:"availabilityZone"` - PrivateIP string `json:"privateIp"` - Version string `json:"version"` - Region string `json:"region"` - InstanceID string `json:"instanceId"` - BillingProducts []string `json:"billingProducts"` - InstanceType string `json:"instanceType"` - AccountID string `json:"accountId"` - PendingTime time.Time `json:"pendingTime"` - ImageID string `json:"imageId"` - KernelID string `json:"kernelId"` - RamdiskID string `json:"ramdiskId"` - Architecture string `json:"architecture"` -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetMetadata.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetMetadata.go deleted file mode 100644 index 869bfc9f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetMetadata.go +++ /dev/null @@ -1,77 +0,0 @@ -package imds - -import ( - "context" - "fmt" - "io" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getMetadataPath = "/latest/meta-data" - -// GetMetadata uses the path provided to request information from the Amazon -// EC2 Instance Metadata Service. The content will be returned as a string, or -// error if the request failed. -func (c *Client) GetMetadata(ctx context.Context, params *GetMetadataInput, optFns ...func(*Options)) (*GetMetadataOutput, error) { - if params == nil { - params = &GetMetadataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetMetadata", params, optFns, - addGetMetadataMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetMetadataOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetMetadataInput provides the input parameters for the GetMetadata -// operation. -type GetMetadataInput struct { - // The relative metadata path to retrieve. Can be empty string to retrieve - // a response containing a new line separated list of metadata resources - // available. - // - // Must not include the metadata base path. - // - // May include leading slash. If Path includes trailing slash the trailing slash - // will be included in the request for the resource. - Path string -} - -// GetMetadataOutput provides the output parameters for the GetMetadata -// operation. -type GetMetadataOutput struct { - Content io.ReadCloser - - ResultMetadata middleware.Metadata -} - -func addGetMetadataMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - "GetMetadata", - buildGetMetadataPath, - buildGetMetadataOutput) -} - -func buildGetMetadataPath(params interface{}) (string, error) { - p, ok := params.(*GetMetadataInput) - if !ok { - return "", fmt.Errorf("unknown parameter type %T", params) - } - - return appendURIPath(getMetadataPath, p.Path), nil -} - -func buildGetMetadataOutput(resp *smithyhttp.Response) (interface{}, error) { - return &GetMetadataOutput{ - Content: resp.Body, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetRegion.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetRegion.go deleted file mode 100644 index 8c0572bb..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetRegion.go +++ /dev/null @@ -1,73 +0,0 @@ -package imds - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// GetRegion retrieves an identity document describing an -// instance. Error is returned if the request fails or is unable to parse -// the response. -func (c *Client) GetRegion( - ctx context.Context, params *GetRegionInput, optFns ...func(*Options), -) ( - *GetRegionOutput, error, -) { - if params == nil { - params = &GetRegionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetRegion", params, optFns, - addGetRegionMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetRegionOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetRegionInput provides the input parameters for GetRegion operation. -type GetRegionInput struct{} - -// GetRegionOutput provides the output parameters for GetRegion operation. -type GetRegionOutput struct { - Region string - - ResultMetadata middleware.Metadata -} - -func addGetRegionMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - "GetRegion", - buildGetInstanceIdentityDocumentPath, - buildGetRegionOutput, - ) -} - -func buildGetRegionOutput(resp *smithyhttp.Response) (interface{}, error) { - out, err := buildGetInstanceIdentityDocumentOutput(resp) - if err != nil { - return nil, err - } - - result, ok := out.(*GetInstanceIdentityDocumentOutput) - if !ok { - return nil, fmt.Errorf("unexpected instance identity document type, %T", out) - } - - region := result.Region - if len(region) == 0 { - return "", fmt.Errorf("instance metadata did not return a region value") - } - - return &GetRegionOutput{ - Region: region, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetToken.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetToken.go deleted file mode 100644 index 1f9ee97a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetToken.go +++ /dev/null @@ -1,119 +0,0 @@ -package imds - -import ( - "context" - "fmt" - "io" - "strconv" - "strings" - "time" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getTokenPath = "/latest/api/token" -const tokenTTLHeader = "X-Aws-Ec2-Metadata-Token-Ttl-Seconds" - -// getToken uses the duration to return a token for EC2 IMDS, or an error if -// the request failed. -func (c *Client) getToken(ctx context.Context, params *getTokenInput, optFns ...func(*Options)) (*getTokenOutput, error) { - if params == nil { - params = &getTokenInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "getToken", params, optFns, - addGetTokenMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*getTokenOutput) - out.ResultMetadata = metadata - return out, nil -} - -type getTokenInput struct { - TokenTTL time.Duration -} - -type getTokenOutput struct { - Token string - TokenTTL time.Duration - - ResultMetadata middleware.Metadata -} - -func addGetTokenMiddleware(stack *middleware.Stack, options Options) error { - err := addRequestMiddleware(stack, - options, - "PUT", - "GetToken", - buildGetTokenPath, - buildGetTokenOutput) - if err != nil { - return err - } - - err = stack.Serialize.Add(&tokenTTLRequestHeader{}, middleware.After) - if err != nil { - return err - } - - return nil -} - -func buildGetTokenPath(interface{}) (string, error) { - return getTokenPath, nil -} - -func buildGetTokenOutput(resp *smithyhttp.Response) (v interface{}, err error) { - defer func() { - closeErr := resp.Body.Close() - if err == nil { - err = closeErr - } else if closeErr != nil { - err = fmt.Errorf("response body close error: %v, original error: %w", closeErr, err) - } - }() - - ttlHeader := resp.Header.Get(tokenTTLHeader) - tokenTTL, err := strconv.ParseInt(ttlHeader, 10, 64) - if err != nil { - return nil, fmt.Errorf("unable to parse API token, %w", err) - } - - var token strings.Builder - if _, err = io.Copy(&token, resp.Body); err != nil { - return nil, fmt.Errorf("unable to read API token, %w", err) - } - - return &getTokenOutput{ - Token: token.String(), - TokenTTL: time.Duration(tokenTTL) * time.Second, - }, nil -} - -type tokenTTLRequestHeader struct{} - -func (*tokenTTLRequestHeader) ID() string { return "tokenTTLRequestHeader" } -func (*tokenTTLRequestHeader) HandleSerialize( - ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, -) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("expect HTTP transport, got %T", in.Request) - } - - input, ok := in.Parameters.(*getTokenInput) - if !ok { - return out, metadata, fmt.Errorf("expect getTokenInput, got %T", in.Parameters) - } - - req.Header.Set(tokenTTLHeader, strconv.Itoa(int(input.TokenTTL/time.Second))) - - return next.HandleSerialize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetUserData.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetUserData.go deleted file mode 100644 index 89036972..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/api_op_GetUserData.go +++ /dev/null @@ -1,61 +0,0 @@ -package imds - -import ( - "context" - "io" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const getUserDataPath = "/latest/user-data" - -// GetUserData uses the path provided to request information from the EC2 -// instance metadata service for dynamic data. The content will be returned -// as a string, or error if the request failed. -func (c *Client) GetUserData(ctx context.Context, params *GetUserDataInput, optFns ...func(*Options)) (*GetUserDataOutput, error) { - if params == nil { - params = &GetUserDataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetUserData", params, optFns, - addGetUserDataMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*GetUserDataOutput) - out.ResultMetadata = metadata - return out, nil -} - -// GetUserDataInput provides the input parameters for the GetUserData -// operation. -type GetUserDataInput struct{} - -// GetUserDataOutput provides the output parameters for the GetUserData -// operation. -type GetUserDataOutput struct { - Content io.ReadCloser - - ResultMetadata middleware.Metadata -} - -func addGetUserDataMiddleware(stack *middleware.Stack, options Options) error { - return addAPIRequestMiddleware(stack, - options, - "GetUserData", - buildGetUserDataPath, - buildGetUserDataOutput) -} - -func buildGetUserDataPath(params interface{}) (string, error) { - return getUserDataPath, nil -} - -func buildGetUserDataOutput(resp *smithyhttp.Response) (interface{}, error) { - return &GetUserDataOutput{ - Content: resp.Body, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/auth.go deleted file mode 100644 index ad283cf8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/auth.go +++ /dev/null @@ -1,48 +0,0 @@ -package imds - -import ( - "context" - "github.com/aws/smithy-go/middleware" -) - -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, -) { - return next.HandleFinalize(ctx, in) -} - -type signRequestMiddleware struct { -} - -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, -) { - return next.HandleFinalize(ctx, in) -} - -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, -) { - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/doc.go deleted file mode 100644 index bacdb5d2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/doc.go +++ /dev/null @@ -1,11 +0,0 @@ -// Package imds provides the API client for interacting with the Amazon EC2 -// Instance Metadata Service. -// -// All Client operation calls have a default timeout. If the operation is not -// completed before this timeout expires, the operation will be canceled. This -// timeout can be overridden by providing Context with a timeout or deadline -// with calling the client's operations. -// -// See the EC2 IMDS user guide for more information on using the API. -// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html -package imds diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/endpoints.go deleted file mode 100644 index d7540da3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/endpoints.go +++ /dev/null @@ -1,20 +0,0 @@ -package imds - -import ( - "context" - "github.com/aws/smithy-go/middleware" -) - -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, -) { - return next.HandleFinalize(ctx, in) -} 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 deleted file mode 100644 index 0d747b21..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package imds - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.14.11" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/internal/config/resolvers.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/internal/config/resolvers.go deleted file mode 100644 index ce774558..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/internal/config/resolvers.go +++ /dev/null @@ -1,114 +0,0 @@ -package config - -import ( - "fmt" - "strings" -) - -// ClientEnableState provides an enumeration if the client is enabled, -// disabled, or default behavior. -type ClientEnableState uint - -// Enumeration values for ClientEnableState -const ( - ClientDefaultEnableState ClientEnableState = iota - ClientDisabled - ClientEnabled -) - -// EndpointModeState is the EC2 IMDS Endpoint Configuration Mode -type EndpointModeState uint - -// Enumeration values for ClientEnableState -const ( - EndpointModeStateUnset EndpointModeState = iota - EndpointModeStateIPv4 - EndpointModeStateIPv6 -) - -// SetFromString sets the EndpointModeState based on the provided string value. Unknown values will default to EndpointModeStateUnset -func (e *EndpointModeState) SetFromString(v string) error { - v = strings.TrimSpace(v) - - switch { - case len(v) == 0: - *e = EndpointModeStateUnset - case strings.EqualFold(v, "IPv6"): - *e = EndpointModeStateIPv6 - case strings.EqualFold(v, "IPv4"): - *e = EndpointModeStateIPv4 - default: - return fmt.Errorf("unknown EC2 IMDS endpoint mode, must be either IPv6 or IPv4") - } - return nil -} - -// ClientEnableStateResolver is a config resolver interface for retrieving whether the IMDS client is disabled. -type ClientEnableStateResolver interface { - GetEC2IMDSClientEnableState() (ClientEnableState, bool, error) -} - -// EndpointModeResolver is a config resolver interface for retrieving the EndpointModeState configuration. -type EndpointModeResolver interface { - GetEC2IMDSEndpointMode() (EndpointModeState, bool, error) -} - -// EndpointResolver is a config resolver interface for retrieving the endpoint. -type EndpointResolver interface { - GetEC2IMDSEndpoint() (string, bool, error) -} - -type v1FallbackDisabledResolver interface { - GetEC2IMDSV1FallbackDisabled() (bool, bool) -} - -// ResolveClientEnableState resolves the ClientEnableState from a list of configuration sources. -func ResolveClientEnableState(sources []interface{}) (value ClientEnableState, found bool, err error) { - for _, source := range sources { - if resolver, ok := source.(ClientEnableStateResolver); ok { - value, found, err = resolver.GetEC2IMDSClientEnableState() - if err != nil || found { - return value, found, err - } - } - } - return value, found, err -} - -// ResolveEndpointModeConfig resolves the EndpointModeState from a list of configuration sources. -func ResolveEndpointModeConfig(sources []interface{}) (value EndpointModeState, found bool, err error) { - for _, source := range sources { - if resolver, ok := source.(EndpointModeResolver); ok { - value, found, err = resolver.GetEC2IMDSEndpointMode() - if err != nil || found { - return value, found, err - } - } - } - return value, found, err -} - -// ResolveEndpointConfig resolves the endpoint from a list of configuration sources. -func ResolveEndpointConfig(sources []interface{}) (value string, found bool, err error) { - for _, source := range sources { - if resolver, ok := source.(EndpointResolver); ok { - value, found, err = resolver.GetEC2IMDSEndpoint() - if err != nil || found { - return value, found, err - } - } - } - return value, found, err -} - -// ResolveV1FallbackDisabled ... -func ResolveV1FallbackDisabled(sources []interface{}) (bool, bool) { - for _, source := range sources { - if resolver, ok := source.(v1FallbackDisabledResolver); ok { - if v, found := resolver.GetEC2IMDSV1FallbackDisabled(); found { - return v, true - } - } - } - return false, false -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/request_middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/request_middleware.go deleted file mode 100644 index fc948c27..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/request_middleware.go +++ /dev/null @@ -1,307 +0,0 @@ -package imds - -import ( - "bytes" - "context" - "fmt" - "io/ioutil" - "net/url" - "path" - "time" - - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/retry" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -func addAPIRequestMiddleware(stack *middleware.Stack, - options Options, - operation string, - getPath func(interface{}) (string, error), - getOutput func(*smithyhttp.Response) (interface{}, error), -) (err error) { - err = addRequestMiddleware(stack, options, "GET", operation, getPath, getOutput) - if err != nil { - return err - } - - // Token Serializer build and state management. - if !options.disableAPIToken { - err = stack.Finalize.Insert(options.tokenProvider, (*retry.Attempt)(nil).ID(), middleware.After) - if err != nil { - return err - } - - err = stack.Deserialize.Insert(options.tokenProvider, "OperationDeserializer", middleware.Before) - if err != nil { - return err - } - } - - return nil -} - -func addRequestMiddleware(stack *middleware.Stack, - options Options, - method string, - operation string, - getPath func(interface{}) (string, error), - getOutput func(*smithyhttp.Response) (interface{}, error), -) (err error) { - err = awsmiddleware.AddSDKAgentKey(awsmiddleware.FeatureMetadata, "ec2-imds")(stack) - if err != nil { - return err - } - - // Operation timeout - err = stack.Initialize.Add(&operationTimeout{ - DefaultTimeout: defaultOperationTimeout, - }, middleware.Before) - if err != nil { - return err - } - - // Operation Serializer - err = stack.Serialize.Add(&serializeRequest{ - GetPath: getPath, - Method: method, - }, middleware.After) - if err != nil { - return err - } - - // Operation endpoint resolver - err = stack.Serialize.Insert(&resolveEndpoint{ - Endpoint: options.Endpoint, - EndpointMode: options.EndpointMode, - }, "OperationSerializer", middleware.Before) - if err != nil { - return err - } - - // Operation Deserializer - err = stack.Deserialize.Add(&deserializeResponse{ - GetOutput: getOutput, - }, middleware.After) - if err != nil { - return err - } - - err = stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ - LogRequest: options.ClientLogMode.IsRequest(), - LogRequestWithBody: options.ClientLogMode.IsRequestWithBody(), - LogResponse: options.ClientLogMode.IsResponse(), - LogResponseWithBody: options.ClientLogMode.IsResponseWithBody(), - }, middleware.After) - if err != nil { - return err - } - - err = addSetLoggerMiddleware(stack, options) - if err != nil { - return err - } - - if err := addProtocolFinalizerMiddlewares(stack, options, operation); err != nil { - return fmt.Errorf("add protocol finalizers: %w", err) - } - - // Retry support - return retry.AddRetryMiddlewares(stack, retry.AddRetryMiddlewaresOptions{ - Retryer: options.Retryer, - LogRetryAttempts: options.ClientLogMode.IsRetries(), - }) -} - -func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { - return middleware.AddSetLoggerMiddleware(stack, o.Logger) -} - -type serializeRequest struct { - GetPath func(interface{}) (string, error) - Method string -} - -func (*serializeRequest) ID() string { - return "OperationSerializer" -} - -func (m *serializeRequest) HandleSerialize( - ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, -) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - reqPath, err := m.GetPath(in.Parameters) - if err != nil { - return out, metadata, fmt.Errorf("unable to get request URL path, %w", err) - } - - request.Request.URL.Path = reqPath - request.Request.Method = m.Method - - return next.HandleSerialize(ctx, in) -} - -type deserializeResponse struct { - GetOutput func(*smithyhttp.Response) (interface{}, error) -} - -func (*deserializeResponse) ID() string { - return "OperationDeserializer" -} - -func (m *deserializeResponse) 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 - } - - resp, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, fmt.Errorf( - "unexpected transport response type, %T, want %T", out.RawResponse, resp) - } - defer resp.Body.Close() - - // read the full body so that any operation timeouts cleanup will not race - // the body being read. - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return out, metadata, fmt.Errorf("read response body failed, %w", err) - } - resp.Body = ioutil.NopCloser(bytes.NewReader(body)) - - // Anything that's not 200 |< 300 is error - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return out, metadata, &smithyhttp.ResponseError{ - Response: resp, - Err: fmt.Errorf("request to EC2 IMDS failed"), - } - } - - result, err := m.GetOutput(resp) - if err != nil { - return out, metadata, fmt.Errorf( - "unable to get deserialized result for response, %w", err, - ) - } - out.Result = result - - return out, metadata, err -} - -type resolveEndpoint struct { - Endpoint string - EndpointMode EndpointModeState -} - -func (*resolveEndpoint) ID() string { - return "ResolveEndpoint" -} - -func (m *resolveEndpoint) HandleSerialize( - ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, -) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - - req, ok := in.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - var endpoint string - if len(m.Endpoint) > 0 { - endpoint = m.Endpoint - } else { - switch m.EndpointMode { - case EndpointModeStateIPv6: - endpoint = defaultIPv6Endpoint - case EndpointModeStateIPv4: - fallthrough - case EndpointModeStateUnset: - endpoint = defaultIPv4Endpoint - default: - return out, metadata, fmt.Errorf("unsupported IMDS endpoint mode") - } - } - - req.URL, err = url.Parse(endpoint) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) - } - - return next.HandleSerialize(ctx, in) -} - -const ( - defaultOperationTimeout = 5 * time.Second -) - -// operationTimeout adds a timeout on the middleware stack if the Context the -// stack was called with does not have a deadline. The next middleware must -// complete before the timeout, or the context will be canceled. -// -// If DefaultTimeout is zero, no default timeout will be used if the Context -// does not have a timeout. -// -// The next middleware must also ensure that any resources that are also -// canceled by the stack's context are completely consumed before returning. -// Otherwise the timeout cleanup will race the resource being consumed -// upstream. -type operationTimeout struct { - DefaultTimeout time.Duration -} - -func (*operationTimeout) ID() string { return "OperationTimeout" } - -func (m *operationTimeout) HandleInitialize( - ctx context.Context, input middleware.InitializeInput, next middleware.InitializeHandler, -) ( - output middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if _, ok := ctx.Deadline(); !ok && m.DefaultTimeout != 0 { - var cancelFn func() - ctx, cancelFn = context.WithTimeout(ctx, m.DefaultTimeout) - defer cancelFn() - } - - return next.HandleInitialize(ctx, input) -} - -// appendURIPath joins a URI path component to the existing path with `/` -// separators between the path components. If the path being added ends with a -// trailing `/` that slash will be maintained. -func appendURIPath(base, add string) string { - reqPath := path.Join(base, add) - if len(add) != 0 && add[len(add)-1] == '/' { - reqPath += "/" - } - return reqPath -} - -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: %w", err) - } - if err := stack.Finalize.Insert(&resolveEndpointV2Middleware{options: options}, "GetIdentity", middleware.After); err != nil { - return fmt.Errorf("add ResolveEndpointV2: %w", err) - } - if err := stack.Finalize.Insert(&signRequestMiddleware{}, "ResolveEndpointV2", middleware.After); err != nil { - return fmt.Errorf("add Signing: %w", err) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/token_provider.go b/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/token_provider.go deleted file mode 100644 index 5703c6e1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/feature/ec2/imds/token_provider.go +++ /dev/null @@ -1,261 +0,0 @@ -package imds - -import ( - "context" - "errors" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/logging" - "net/http" - "sync" - "sync/atomic" - "time" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const ( - // Headers for Token and TTL - tokenHeader = "x-aws-ec2-metadata-token" - defaultTokenTTL = 5 * time.Minute -) - -type tokenProvider struct { - client *Client - tokenTTL time.Duration - - token *apiToken - tokenMux sync.RWMutex - - disabled uint32 // Atomic updated -} - -func newTokenProvider(client *Client, ttl time.Duration) *tokenProvider { - return &tokenProvider{ - client: client, - tokenTTL: ttl, - } -} - -// apiToken provides the API token used by all operation calls for th EC2 -// Instance metadata service. -type apiToken struct { - token string - expires time.Time -} - -var timeNow = time.Now - -// Expired returns if the token is expired. -func (t *apiToken) Expired() bool { - // Calling Round(0) on the current time will truncate the monotonic reading only. Ensures credential expiry - // time is always based on reported wall-clock time. - return timeNow().Round(0).After(t.expires) -} - -func (t *tokenProvider) ID() string { return "APITokenProvider" } - -// HandleFinalize is the finalize stack middleware, that if the token provider is -// enabled, will attempt to add the cached API token to the request. If the API -// token is not cached, it will be retrieved in a separate API call, getToken. -// -// For retry attempts, handler must be added after attempt retryer. -// -// If request for getToken fails the token provider may be disabled from future -// requests, depending on the response status code. -func (t *tokenProvider) HandleFinalize( - ctx context.Context, input middleware.FinalizeInput, next middleware.FinalizeHandler, -) ( - out middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - if t.fallbackEnabled() && !t.enabled() { - // short-circuits to insecure data flow if token provider is disabled. - return next.HandleFinalize(ctx, input) - } - - req, ok := input.Request.(*smithyhttp.Request) - if !ok { - return out, metadata, fmt.Errorf("unexpected transport request type %T", input.Request) - } - - tok, err := t.getToken(ctx) - if err != nil { - // If the error allows the token to downgrade to insecure flow allow that. - var bypassErr *bypassTokenRetrievalError - if errors.As(err, &bypassErr) { - return next.HandleFinalize(ctx, input) - } - - return out, metadata, fmt.Errorf("failed to get API token, %w", err) - } - - req.Header.Set(tokenHeader, tok.token) - - return next.HandleFinalize(ctx, input) -} - -// HandleDeserialize is the deserialize stack middleware for determining if the -// operation the token provider is decorating failed because of a 401 -// unauthorized status code. If the operation failed for that reason the token -// provider needs to be re-enabled so that it can start adding the API token to -// operation calls. -func (t *tokenProvider) HandleDeserialize( - ctx context.Context, input middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err = next.HandleDeserialize(ctx, input) - if err == nil { - return out, metadata, err - } - - resp, ok := out.RawResponse.(*smithyhttp.Response) - if !ok { - return out, metadata, fmt.Errorf("expect HTTP transport, got %T", out.RawResponse) - } - - if resp.StatusCode == http.StatusUnauthorized { // unauthorized - t.enable() - err = &retryableError{Err: err, isRetryable: true} - } - - return out, metadata, err -} - -func (t *tokenProvider) getToken(ctx context.Context) (tok *apiToken, err error) { - if t.fallbackEnabled() && !t.enabled() { - return nil, &bypassTokenRetrievalError{ - Err: fmt.Errorf("cannot get API token, provider disabled"), - } - } - - t.tokenMux.RLock() - tok = t.token - t.tokenMux.RUnlock() - - if tok != nil && !tok.Expired() { - return tok, nil - } - - tok, err = t.updateToken(ctx) - if err != nil { - return nil, err - } - - return tok, nil -} - -func (t *tokenProvider) updateToken(ctx context.Context) (*apiToken, error) { - t.tokenMux.Lock() - defer t.tokenMux.Unlock() - - // Prevent multiple requests to update retrieving the token. - if t.token != nil && !t.token.Expired() { - tok := t.token - return tok, nil - } - - result, err := t.client.getToken(ctx, &getTokenInput{ - TokenTTL: t.tokenTTL, - }) - if err != nil { - var statusErr interface{ HTTPStatusCode() int } - if errors.As(err, &statusErr) { - switch statusErr.HTTPStatusCode() { - // Disable future get token if failed because of 403, 404, or 405 - case http.StatusForbidden, - http.StatusNotFound, - http.StatusMethodNotAllowed: - - if t.fallbackEnabled() { - logger := middleware.GetLogger(ctx) - logger.Logf(logging.Warn, "falling back to IMDSv1: %v", err) - t.disable() - } - - // 400 errors are terminal, and need to be upstreamed - case http.StatusBadRequest: - return nil, err - } - } - - // Disable if request send failed or timed out getting response - var re *smithyhttp.RequestSendError - var ce *smithy.CanceledError - if errors.As(err, &re) || errors.As(err, &ce) { - atomic.StoreUint32(&t.disabled, 1) - } - - if !t.fallbackEnabled() { - // NOTE: getToken() is an implementation detail of some outer operation - // (e.g. GetMetadata). It has its own retries that have already been exhausted. - // Mark the underlying error as a terminal error. - err = &retryableError{Err: err, isRetryable: false} - return nil, err - } - - // Token couldn't be retrieved, fallback to IMDSv1 insecure flow for this request - // and allow the request to proceed. Future requests _may_ re-attempt fetching a - // token if not disabled. - return nil, &bypassTokenRetrievalError{Err: err} - } - - tok := &apiToken{ - token: result.Token, - expires: timeNow().Add(result.TokenTTL), - } - t.token = tok - - return tok, nil -} - -// enabled returns if the token provider is current enabled or not. -func (t *tokenProvider) enabled() bool { - return atomic.LoadUint32(&t.disabled) == 0 -} - -// fallbackEnabled returns false if EnableFallback is [aws.FalseTernary], true otherwise -func (t *tokenProvider) fallbackEnabled() bool { - switch t.client.options.EnableFallback { - case aws.FalseTernary: - return false - default: - return true - } -} - -// disable disables the token provider and it will no longer attempt to inject -// the token, nor request updates. -func (t *tokenProvider) disable() { - atomic.StoreUint32(&t.disabled, 1) -} - -// enable enables the token provide to start refreshing tokens, and adding them -// to the pending request. -func (t *tokenProvider) enable() { - t.tokenMux.Lock() - t.token = nil - t.tokenMux.Unlock() - atomic.StoreUint32(&t.disabled, 0) -} - -type bypassTokenRetrievalError struct { - Err error -} - -func (e *bypassTokenRetrievalError) Error() string { - return fmt.Sprintf("bypass token retrieval, %v", e.Err) -} - -func (e *bypassTokenRetrievalError) Unwrap() error { return e.Err } - -type retryableError struct { - Err error - isRetryable bool -} - -func (e *retryableError) RetryableError() bool { return e.isRetryable } - -func (e *retryableError) Error() string { return e.Err.Error() } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/auth.go deleted file mode 100644 index 0b81db54..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/auth.go +++ /dev/null @@ -1,45 +0,0 @@ -package auth - -import ( - "github.com/aws/smithy-go/auth" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// HTTPAuthScheme is the SDK's internal implementation of smithyhttp.AuthScheme -// for pre-existing implementations where the signer was added to client -// config. SDK clients will key off of this type and ensure per-operation -// updates to those signers persist on the scheme itself. -type HTTPAuthScheme struct { - schemeID string - signer smithyhttp.Signer -} - -var _ smithyhttp.AuthScheme = (*HTTPAuthScheme)(nil) - -// NewHTTPAuthScheme returns an auth scheme instance with the given config. -func NewHTTPAuthScheme(schemeID string, signer smithyhttp.Signer) *HTTPAuthScheme { - return &HTTPAuthScheme{ - schemeID: schemeID, - signer: signer, - } -} - -// SchemeID identifies the auth scheme. -func (s *HTTPAuthScheme) SchemeID() string { - return s.schemeID -} - -// IdentityResolver gets the identity resolver for the auth scheme. -func (s *HTTPAuthScheme) IdentityResolver(o auth.IdentityResolverOptions) auth.IdentityResolver { - return o.GetIdentityResolver(s.schemeID) -} - -// Signer gets the signer for the auth scheme. -func (s *HTTPAuthScheme) Signer() smithyhttp.Signer { - return s.signer -} - -// WithSigner returns a new instance of the auth scheme with the updated signer. -func (s *HTTPAuthScheme) WithSigner(signer smithyhttp.Signer) *HTTPAuthScheme { - return NewHTTPAuthScheme(s.schemeID, signer) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/scheme.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/scheme.go deleted file mode 100644 index bbc2ec06..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/scheme.go +++ /dev/null @@ -1,191 +0,0 @@ -package auth - -import ( - "context" - "fmt" - - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -// SigV4 is a constant representing -// Authentication Scheme Signature Version 4 -const SigV4 = "sigv4" - -// SigV4A is a constant representing -// Authentication Scheme Signature Version 4A -const SigV4A = "sigv4a" - -// SigV4S3Express identifies the S3 S3Express auth scheme. -const SigV4S3Express = "sigv4-s3express" - -// None is a constant representing the -// None Authentication Scheme -const None = "none" - -// SupportedSchemes is a data structure -// that indicates the list of supported AWS -// authentication schemes -var SupportedSchemes = map[string]bool{ - SigV4: true, - SigV4A: true, - SigV4S3Express: true, - None: true, -} - -// AuthenticationScheme is a representation of -// AWS authentication schemes -type AuthenticationScheme interface { - isAuthenticationScheme() -} - -// AuthenticationSchemeV4 is a AWS SigV4 representation -type AuthenticationSchemeV4 struct { - Name string - SigningName *string - SigningRegion *string - DisableDoubleEncoding *bool -} - -func (a *AuthenticationSchemeV4) isAuthenticationScheme() {} - -// AuthenticationSchemeV4A is a AWS SigV4A representation -type AuthenticationSchemeV4A struct { - Name string - SigningName *string - SigningRegionSet []string - DisableDoubleEncoding *bool -} - -func (a *AuthenticationSchemeV4A) isAuthenticationScheme() {} - -// AuthenticationSchemeNone is a representation for the none auth scheme -type AuthenticationSchemeNone struct{} - -func (a *AuthenticationSchemeNone) isAuthenticationScheme() {} - -// NoAuthenticationSchemesFoundError is used in signaling -// that no authentication schemes have been specified. -type NoAuthenticationSchemesFoundError struct{} - -func (e *NoAuthenticationSchemesFoundError) Error() string { - return fmt.Sprint("No authentication schemes specified.") -} - -// UnSupportedAuthenticationSchemeSpecifiedError is used in -// signaling that only unsupported authentication schemes -// were specified. -type UnSupportedAuthenticationSchemeSpecifiedError struct { - UnsupportedSchemes []string -} - -func (e *UnSupportedAuthenticationSchemeSpecifiedError) Error() string { - return fmt.Sprint("Unsupported authentication scheme specified.") -} - -// GetAuthenticationSchemes extracts the relevant authentication scheme data -// into a custom strongly typed Go data structure. -func GetAuthenticationSchemes(p *smithy.Properties) ([]AuthenticationScheme, error) { - var result []AuthenticationScheme - if !p.Has("authSchemes") { - return nil, &NoAuthenticationSchemesFoundError{} - } - - authSchemes, _ := p.Get("authSchemes").([]interface{}) - - var unsupportedSchemes []string - for _, scheme := range authSchemes { - authScheme, _ := scheme.(map[string]interface{}) - - version := authScheme["name"].(string) - switch version { - case SigV4, SigV4S3Express: - v4Scheme := AuthenticationSchemeV4{ - Name: version, - SigningName: getSigningName(authScheme), - SigningRegion: getSigningRegion(authScheme), - DisableDoubleEncoding: getDisableDoubleEncoding(authScheme), - } - result = append(result, AuthenticationScheme(&v4Scheme)) - case SigV4A: - v4aScheme := AuthenticationSchemeV4A{ - Name: SigV4A, - SigningName: getSigningName(authScheme), - SigningRegionSet: getSigningRegionSet(authScheme), - DisableDoubleEncoding: getDisableDoubleEncoding(authScheme), - } - result = append(result, AuthenticationScheme(&v4aScheme)) - case None: - noneScheme := AuthenticationSchemeNone{} - result = append(result, AuthenticationScheme(&noneScheme)) - default: - unsupportedSchemes = append(unsupportedSchemes, authScheme["name"].(string)) - continue - } - } - - if len(result) == 0 { - return nil, &UnSupportedAuthenticationSchemeSpecifiedError{ - UnsupportedSchemes: unsupportedSchemes, - } - } - - return result, nil -} - -type disableDoubleEncoding struct{} - -// SetDisableDoubleEncoding sets or modifies the disable double encoding option -// on the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func SetDisableDoubleEncoding(ctx context.Context, value bool) context.Context { - return middleware.WithStackValue(ctx, disableDoubleEncoding{}, value) -} - -// GetDisableDoubleEncoding retrieves the disable double encoding option -// from the context. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetDisableDoubleEncoding(ctx context.Context) (value bool, ok bool) { - value, ok = middleware.GetStackValue(ctx, disableDoubleEncoding{}).(bool) - return value, ok -} - -func getSigningName(authScheme map[string]interface{}) *string { - signingName, ok := authScheme["signingName"].(string) - if !ok || signingName == "" { - return nil - } - return &signingName -} - -func getSigningRegionSet(authScheme map[string]interface{}) []string { - untypedSigningRegionSet, ok := authScheme["signingRegionSet"].([]interface{}) - if !ok { - return nil - } - signingRegionSet := []string{} - for _, item := range untypedSigningRegionSet { - signingRegionSet = append(signingRegionSet, item.(string)) - } - return signingRegionSet -} - -func getSigningRegion(authScheme map[string]interface{}) *string { - signingRegion, ok := authScheme["signingRegion"].(string) - if !ok || signingRegion == "" { - return nil - } - return &signingRegion -} - -func getDisableDoubleEncoding(authScheme map[string]interface{}) *bool { - disableDoubleEncoding, ok := authScheme["disableDoubleEncoding"].(bool) - if !ok { - return nil - } - return &disableDoubleEncoding -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/bearer_token_adapter.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/bearer_token_adapter.go deleted file mode 100644 index f059b5d3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/bearer_token_adapter.go +++ /dev/null @@ -1,43 +0,0 @@ -package smithy - -import ( - "context" - "fmt" - "time" - - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/auth" - "github.com/aws/smithy-go/auth/bearer" -) - -// BearerTokenAdapter adapts smithy bearer.Token to smithy auth.Identity. -type BearerTokenAdapter struct { - Token bearer.Token -} - -var _ auth.Identity = (*BearerTokenAdapter)(nil) - -// Expiration returns the time of expiration for the token. -func (v *BearerTokenAdapter) Expiration() time.Time { - return v.Token.Expires -} - -// BearerTokenProviderAdapter adapts smithy bearer.TokenProvider to smithy -// auth.IdentityResolver. -type BearerTokenProviderAdapter struct { - Provider bearer.TokenProvider -} - -var _ (auth.IdentityResolver) = (*BearerTokenProviderAdapter)(nil) - -// GetIdentity retrieves a bearer token using the underlying provider. -func (v *BearerTokenProviderAdapter) GetIdentity(ctx context.Context, _ smithy.Properties) ( - auth.Identity, error, -) { - token, err := v.Provider.RetrieveBearerToken(ctx) - if err != nil { - return nil, fmt.Errorf("get token: %w", err) - } - - return &BearerTokenAdapter{Token: token}, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/bearer_token_signer_adapter.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/bearer_token_signer_adapter.go deleted file mode 100644 index a8828152..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/bearer_token_signer_adapter.go +++ /dev/null @@ -1,35 +0,0 @@ -package smithy - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/auth" - "github.com/aws/smithy-go/auth/bearer" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// BearerTokenSignerAdapter adapts smithy bearer.Signer to smithy http -// auth.Signer. -type BearerTokenSignerAdapter struct { - Signer bearer.Signer -} - -var _ (smithyhttp.Signer) = (*BearerTokenSignerAdapter)(nil) - -// SignRequest signs the request with the provided bearer token. -func (v *BearerTokenSignerAdapter) SignRequest(ctx context.Context, r *smithyhttp.Request, identity auth.Identity, _ smithy.Properties) error { - ca, ok := identity.(*BearerTokenAdapter) - if !ok { - return fmt.Errorf("unexpected identity type: %T", identity) - } - - signed, err := v.Signer.SignWithBearerToken(ctx, ca.Token, r) - if err != nil { - return fmt.Errorf("sign request: %w", err) - } - - *r = *signed.(*smithyhttp.Request) - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/credentials_adapter.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/credentials_adapter.go deleted file mode 100644 index f926c4aa..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/credentials_adapter.go +++ /dev/null @@ -1,46 +0,0 @@ -package smithy - -import ( - "context" - "fmt" - "time" - - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/auth" -) - -// CredentialsAdapter adapts aws.Credentials to auth.Identity. -type CredentialsAdapter struct { - Credentials aws.Credentials -} - -var _ auth.Identity = (*CredentialsAdapter)(nil) - -// Expiration returns the time of expiration for the credentials. -func (v *CredentialsAdapter) Expiration() time.Time { - return v.Credentials.Expires -} - -// CredentialsProviderAdapter adapts aws.CredentialsProvider to auth.IdentityResolver. -type CredentialsProviderAdapter struct { - Provider aws.CredentialsProvider -} - -var _ (auth.IdentityResolver) = (*CredentialsProviderAdapter)(nil) - -// GetIdentity retrieves AWS credentials using the underlying provider. -func (v *CredentialsProviderAdapter) GetIdentity(ctx context.Context, _ smithy.Properties) ( - auth.Identity, error, -) { - if v.Provider == nil { - return &CredentialsAdapter{Credentials: aws.Credentials{}}, nil - } - - creds, err := v.Provider.Retrieve(ctx) - if err != nil { - return nil, fmt.Errorf("get credentials: %w", err) - } - - return &CredentialsAdapter{Credentials: creds}, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/smithy.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/smithy.go deleted file mode 100644 index 42b45867..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/smithy.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package smithy adapts concrete AWS auth and signing types to the generic smithy versions. -package smithy diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/v4signer_adapter.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/v4signer_adapter.go deleted file mode 100644 index 0c5a2d40..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/auth/smithy/v4signer_adapter.go +++ /dev/null @@ -1,53 +0,0 @@ -package smithy - -import ( - "context" - "fmt" - - v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/internal/sdk" - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/auth" - "github.com/aws/smithy-go/logging" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// V4SignerAdapter adapts v4.HTTPSigner to smithy http.Signer. -type V4SignerAdapter struct { - Signer v4.HTTPSigner - Logger logging.Logger - LogSigning bool -} - -var _ (smithyhttp.Signer) = (*V4SignerAdapter)(nil) - -// SignRequest signs the request with the provided identity. -func (v *V4SignerAdapter) SignRequest(ctx context.Context, r *smithyhttp.Request, identity auth.Identity, props smithy.Properties) error { - ca, ok := identity.(*CredentialsAdapter) - if !ok { - return fmt.Errorf("unexpected identity type: %T", identity) - } - - name, ok := smithyhttp.GetSigV4SigningName(&props) - if !ok { - return fmt.Errorf("sigv4 signing name is required") - } - - region, ok := smithyhttp.GetSigV4SigningRegion(&props) - if !ok { - return fmt.Errorf("sigv4 signing region is required") - } - - hash := v4.GetPayloadHash(ctx) - err := v.Signer.SignHTTP(ctx, ca.Credentials, r.Request, hash, name, region, sdk.NowTime(), func(o *v4.SignerOptions) { - o.DisableURIPathEscaping, _ = smithyhttp.GetDisableDoubleEncoding(&props) - - o.Logger = v.Logger - o.LogSigning = v.LogSigning - }) - if err != nil { - return fmt.Errorf("sign http: %w", err) - } - - return nil -} 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 deleted file mode 100644 index dc87ec41..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/CHANGELOG.md +++ /dev/null @@ -1,255 +0,0 @@ -# v1.2.10 (2024-01-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.9 (2023-12-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.8 (2023-12-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.7 (2023-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.6 (2023-11-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.5 (2023-11-28.2) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.4 (2023-11-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.3 (2023-11-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.2 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.1 (2023-11-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.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.1.43 (2023-10-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.42 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.41 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.40 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.39 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.38 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.37 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.36 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.35 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.34 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.33 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.32 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.31 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.30 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.29 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.28 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.27 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.26 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.25 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.24 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.23 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.22 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.21 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.20 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.19 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.18 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.17 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.16 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.15 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.14 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.13 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.12 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.11 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.10 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.9 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.8 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.7 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.6 (2022-03-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.5 (2022-02-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.4 (2022-01-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.3 (2022-01-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.2 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.7 (2021-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.6 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.5 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.4 (2021-08-27) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.3 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.2 (2021-08-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.1 (2021-07-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.0 (2021-06-25) - -* **Release**: Release new modules -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/internal/configsources/config.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/config.go deleted file mode 100644 index cd4d19b8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/config.go +++ /dev/null @@ -1,65 +0,0 @@ -package configsources - -import ( - "context" - "github.com/aws/aws-sdk-go-v2/aws" -) - -// EnableEndpointDiscoveryProvider is an interface for retrieving external configuration value -// for Enable Endpoint Discovery -type EnableEndpointDiscoveryProvider interface { - GetEnableEndpointDiscovery(ctx context.Context) (value aws.EndpointDiscoveryEnableState, found bool, err error) -} - -// ResolveEnableEndpointDiscovery extracts the first instance of a EnableEndpointDiscoveryProvider from the config slice. -// Additionally returns a aws.EndpointDiscoveryEnableState to indicate if the value was found in provided configs, -// and error if one is encountered. -func ResolveEnableEndpointDiscovery(ctx context.Context, configs []interface{}) (value aws.EndpointDiscoveryEnableState, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(EnableEndpointDiscoveryProvider); ok { - value, found, err = p.GetEnableEndpointDiscovery(ctx) - if err != nil || found { - break - } - } - } - return -} - -// UseDualStackEndpointProvider is an interface for retrieving external configuration values for UseDualStackEndpoint -type UseDualStackEndpointProvider interface { - GetUseDualStackEndpoint(context.Context) (value aws.DualStackEndpointState, found bool, err error) -} - -// ResolveUseDualStackEndpoint extracts the first instance of a UseDualStackEndpoint from the config slice. -// Additionally returns a boolean to indicate if the value was found in provided configs, and error if one is encountered. -func ResolveUseDualStackEndpoint(ctx context.Context, configs []interface{}) (value aws.DualStackEndpointState, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(UseDualStackEndpointProvider); ok { - value, found, err = p.GetUseDualStackEndpoint(ctx) - if err != nil || found { - break - } - } - } - return -} - -// UseFIPSEndpointProvider is an interface for retrieving external configuration values for UseFIPSEndpoint -type UseFIPSEndpointProvider interface { - GetUseFIPSEndpoint(context.Context) (value aws.FIPSEndpointState, found bool, err error) -} - -// ResolveUseFIPSEndpoint extracts the first instance of a UseFIPSEndpointProvider from the config slice. -// Additionally, returns a boolean to indicate if the value was found in provided configs, and error if one is encountered. -func ResolveUseFIPSEndpoint(ctx context.Context, configs []interface{}) (value aws.FIPSEndpointState, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(UseFIPSEndpointProvider); ok { - value, found, err = p.GetUseFIPSEndpoint(ctx) - if err != nil || found { - break - } - } - } - return -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/endpoints.go deleted file mode 100644 index e7835f85..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/endpoints.go +++ /dev/null @@ -1,57 +0,0 @@ -package configsources - -import ( - "context" -) - -// ServiceBaseEndpointProvider is needed to search for all providers -// that provide a configured service endpoint -type ServiceBaseEndpointProvider interface { - GetServiceBaseEndpoint(ctx context.Context, sdkID string) (string, bool, error) -} - -// IgnoreConfiguredEndpointsProvider is needed to search for all providers -// that provide a flag to disable configured endpoints. -// -// Currently duplicated from github.com/aws/aws-sdk-go-v2/config because -// service packages cannot import github.com/aws/aws-sdk-go-v2/config -// due to result import cycle error. -type IgnoreConfiguredEndpointsProvider interface { - GetIgnoreConfiguredEndpoints(ctx context.Context) (bool, bool, error) -} - -// GetIgnoreConfiguredEndpoints is used in knowing when to disable configured -// endpoints feature. -// -// Currently duplicated from github.com/aws/aws-sdk-go-v2/config because -// service packages cannot import github.com/aws/aws-sdk-go-v2/config -// due to result import cycle error. -func GetIgnoreConfiguredEndpoints(ctx context.Context, configs []interface{}) (value bool, found bool, err error) { - for _, cfg := range configs { - if p, ok := cfg.(IgnoreConfiguredEndpointsProvider); ok { - value, found, err = p.GetIgnoreConfiguredEndpoints(ctx) - if err != nil || found { - break - } - } - } - return -} - -// ResolveServiceBaseEndpoint is used to retrieve service endpoints from configured sources -// while allowing for configured endpoints to be disabled -func ResolveServiceBaseEndpoint(ctx context.Context, sdkID string, configs []interface{}) (value string, found bool, err error) { - if val, found, _ := GetIgnoreConfiguredEndpoints(ctx, configs); found && val { - return "", false, nil - } - - for _, cs := range configs { - if p, ok := cs.(ServiceBaseEndpointProvider); ok { - value, found, err = p.GetServiceBaseEndpoint(context.Background(), sdkID) - if err != nil || found { - break - } - } - } - return -} 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 deleted file mode 100644 index 41ee0bfb..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/configsources/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package configsources - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.2.10" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/arn.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/arn.go deleted file mode 100644 index e6223dd3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/arn.go +++ /dev/null @@ -1,94 +0,0 @@ -package awsrulesfn - -import ( - "strings" -) - -// ARN provides AWS ARN components broken out into a data structure. -type ARN struct { - Partition string - Service string - Region string - AccountId string - ResourceId OptionalStringSlice -} - -const ( - arnDelimiters = ":" - resourceDelimiters = "/:" - arnSections = 6 - arnPrefix = "arn:" - - // zero-indexed - sectionPartition = 1 - sectionService = 2 - sectionRegion = 3 - sectionAccountID = 4 - sectionResource = 5 -) - -// ParseARN returns an [ARN] value parsed from the input string provided. If -// the ARN cannot be parsed nil will be returned, and error added to -// [ErrorCollector]. -func ParseARN(input string) *ARN { - if !strings.HasPrefix(input, arnPrefix) { - return nil - } - - sections := strings.SplitN(input, arnDelimiters, arnSections) - if numSections := len(sections); numSections != arnSections { - return nil - } - - if sections[sectionPartition] == "" { - return nil - } - if sections[sectionService] == "" { - return nil - } - if sections[sectionResource] == "" { - return nil - } - - return &ARN{ - Partition: sections[sectionPartition], - Service: sections[sectionService], - Region: sections[sectionRegion], - AccountId: sections[sectionAccountID], - ResourceId: splitResource(sections[sectionResource]), - } -} - -// splitResource splits the resource components by the ARN resource delimiters. -func splitResource(v string) []string { - var parts []string - var offset int - - for offset <= len(v) { - idx := strings.IndexAny(v[offset:], "/:") - if idx < 0 { - parts = append(parts, v[offset:]) - break - } - parts = append(parts, v[offset:idx+offset]) - offset += idx + 1 - } - - return parts -} - -// OptionalStringSlice provides a helper to safely get the index of a string -// slice that may be out of bounds. Returns pointer to string if index is -// valid. Otherwise returns nil. -type OptionalStringSlice []string - -// Get returns a string pointer of the string at index i if the index is valid. -// Otherwise returns nil. -func (s OptionalStringSlice) Get(i int) *string { - if i < 0 || i >= len(s) { - return nil - } - - v := s[i] - return &v -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/doc.go deleted file mode 100644 index d5a36585..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package awsrulesfn provides AWS focused endpoint rule functions for -// evaluating endpoint resolution rules. -package awsrulesfn diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/generate.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/generate.go deleted file mode 100644 index df72da97..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/generate.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build codegen -// +build codegen - -package awsrulesfn - -//go:generate go run -tags codegen ./internal/partition/codegen.go -model partitions.json -output partitions.go -//go:generate gofmt -w -s . diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/host.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/host.go deleted file mode 100644 index 637e5fc1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/host.go +++ /dev/null @@ -1,51 +0,0 @@ -package awsrulesfn - -import ( - "net" - "strings" - - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// IsVirtualHostableS3Bucket returns if the input is a DNS compatible bucket -// name and can be used with Amazon S3 virtual hosted style addressing. Similar -// to [rulesfn.IsValidHostLabel] with the added restriction that the length of label -// must be [3:63] characters long, all lowercase, and not formatted as an IP -// address. -func IsVirtualHostableS3Bucket(input string, allowSubDomains bool) bool { - // input should not be formatted as an IP address - // NOTE: this will technically trip up on IPv6 hosts with zone IDs, but - // validation further down will catch that anyway (it's guaranteed to have - // unfriendly characters % and : if that's the case) - if net.ParseIP(input) != nil { - return false - } - - var labels []string - if allowSubDomains { - labels = strings.Split(input, ".") - } else { - labels = []string{input} - } - - for _, label := range labels { - // validate special length constraints - if l := len(label); l < 3 || l > 63 { - return false - } - - // Validate no capital letters - for _, r := range label { - if r >= 'A' && r <= 'Z' { - return false - } - } - - // Validate valid host label - if !smithyhttp.ValidHostLabel(label) { - return false - } - } - - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partition.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partition.go deleted file mode 100644 index ba603275..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partition.go +++ /dev/null @@ -1,75 +0,0 @@ -package awsrulesfn - -import "regexp" - -// Partition provides the metadata describing an AWS partition. -type Partition struct { - ID string `json:"id"` - Regions map[string]RegionOverrides `json:"regions"` - RegionRegex string `json:"regionRegex"` - DefaultConfig PartitionConfig `json:"outputs"` -} - -// PartitionConfig provides the endpoint metadata for an AWS region or partition. -type PartitionConfig struct { - Name string `json:"name"` - DnsSuffix string `json:"dnsSuffix"` - DualStackDnsSuffix string `json:"dualStackDnsSuffix"` - SupportsFIPS bool `json:"supportsFIPS"` - SupportsDualStack bool `json:"supportsDualStack"` -} - -type RegionOverrides struct { - Name *string `json:"name"` - DnsSuffix *string `json:"dnsSuffix"` - DualStackDnsSuffix *string `json:"dualStackDnsSuffix"` - SupportsFIPS *bool `json:"supportsFIPS"` - SupportsDualStack *bool `json:"supportsDualStack"` -} - -const defaultPartition = "aws" - -func getPartition(partitions []Partition, region string) *PartitionConfig { - for _, partition := range partitions { - if v, ok := partition.Regions[region]; ok { - p := mergeOverrides(partition.DefaultConfig, v) - return &p - } - } - - for _, partition := range partitions { - regionRegex := regexp.MustCompile(partition.RegionRegex) - if regionRegex.MatchString(region) { - v := partition.DefaultConfig - return &v - } - } - - for _, partition := range partitions { - if partition.ID == defaultPartition { - v := partition.DefaultConfig - return &v - } - } - - return nil -} - -func mergeOverrides(into PartitionConfig, from RegionOverrides) PartitionConfig { - if from.Name != nil { - into.Name = *from.Name - } - if from.DnsSuffix != nil { - into.DnsSuffix = *from.DnsSuffix - } - if from.DualStackDnsSuffix != nil { - into.DualStackDnsSuffix = *from.DualStackDnsSuffix - } - if from.SupportsFIPS != nil { - into.SupportsFIPS = *from.SupportsFIPS - } - if from.SupportsDualStack != nil { - into.SupportsDualStack = *from.SupportsDualStack - } - return into -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.go deleted file mode 100644 index 849beffd..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.go +++ /dev/null @@ -1,381 +0,0 @@ -// Code generated by endpoint/awsrulesfn/internal/partition. DO NOT EDIT. - -package awsrulesfn - -// GetPartition returns an AWS [Partition] for the region provided. If the -// partition cannot be determined nil will be returned. -func GetPartition(region string) *PartitionConfig { - return getPartition(partitions, region) -} - -var partitions = []Partition{ - { - ID: "aws", - RegionRegex: "^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws", - DnsSuffix: "amazonaws.com", - DualStackDnsSuffix: "api.aws", - SupportsFIPS: true, - SupportsDualStack: true, - }, - Regions: map[string]RegionOverrides{ - "af-south-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-northeast-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-northeast-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-northeast-3": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-south-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-south-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-southeast-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-southeast-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-southeast-3": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ap-southeast-4": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "aws-global": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "ca-central-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-central-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-central-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-north-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-south-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-south-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-west-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-west-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "eu-west-3": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "il-central-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "me-central-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "me-south-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "sa-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-east-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-west-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-west-2": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - }, - }, - { - ID: "aws-cn", - RegionRegex: "^cn\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws-cn", - DnsSuffix: "amazonaws.com.cn", - DualStackDnsSuffix: "api.amazonwebservices.com.cn", - SupportsFIPS: true, - SupportsDualStack: true, - }, - Regions: map[string]RegionOverrides{ - "aws-cn-global": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "cn-north-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "cn-northwest-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - }, - }, - { - ID: "aws-us-gov", - RegionRegex: "^us\\-gov\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws-us-gov", - DnsSuffix: "amazonaws.com", - DualStackDnsSuffix: "api.aws", - SupportsFIPS: true, - SupportsDualStack: true, - }, - Regions: map[string]RegionOverrides{ - "aws-us-gov-global": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-gov-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-gov-west-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - }, - }, - { - ID: "aws-iso", - RegionRegex: "^us\\-iso\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws-iso", - DnsSuffix: "c2s.ic.gov", - DualStackDnsSuffix: "c2s.ic.gov", - SupportsFIPS: true, - SupportsDualStack: false, - }, - Regions: map[string]RegionOverrides{ - "aws-iso-global": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-iso-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-iso-west-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - }, - }, - { - ID: "aws-iso-b", - RegionRegex: "^us\\-isob\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws-iso-b", - DnsSuffix: "sc2s.sgov.gov", - DualStackDnsSuffix: "sc2s.sgov.gov", - SupportsFIPS: true, - SupportsDualStack: false, - }, - Regions: map[string]RegionOverrides{ - "aws-iso-b-global": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - "us-isob-east-1": { - Name: nil, - DnsSuffix: nil, - DualStackDnsSuffix: nil, - SupportsFIPS: nil, - SupportsDualStack: nil, - }, - }, - }, - { - ID: "aws-iso-e", - RegionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws-iso-e", - DnsSuffix: "cloud.adc-e.uk", - DualStackDnsSuffix: "cloud.adc-e.uk", - SupportsFIPS: true, - SupportsDualStack: false, - }, - Regions: map[string]RegionOverrides{}, - }, - { - ID: "aws-iso-f", - RegionRegex: "^us\\-isof\\-\\w+\\-\\d+$", - DefaultConfig: PartitionConfig{ - Name: "aws-iso-f", - DnsSuffix: "csp.hci.ic.gov", - DualStackDnsSuffix: "csp.hci.ic.gov", - SupportsFIPS: true, - SupportsDualStack: false, - }, - Regions: map[string]RegionOverrides{}, - }, -} 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 deleted file mode 100644 index f376f690..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/awsrulesfn/partitions.json +++ /dev/null @@ -1,216 +0,0 @@ -{ - "partitions" : [ { - "id" : "aws", - "outputs" : { - "dnsSuffix" : "amazonaws.com", - "dualStackDnsSuffix" : "api.aws", - "implicitGlobalRegion" : "us-east-1", - "name" : "aws", - "supportsDualStack" : true, - "supportsFIPS" : true - }, - "regionRegex" : "^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$", - "regions" : { - "af-south-1" : { - "description" : "Africa (Cape Town)" - }, - "ap-east-1" : { - "description" : "Asia Pacific (Hong Kong)" - }, - "ap-northeast-1" : { - "description" : "Asia Pacific (Tokyo)" - }, - "ap-northeast-2" : { - "description" : "Asia Pacific (Seoul)" - }, - "ap-northeast-3" : { - "description" : "Asia Pacific (Osaka)" - }, - "ap-south-1" : { - "description" : "Asia Pacific (Mumbai)" - }, - "ap-south-2" : { - "description" : "Asia Pacific (Hyderabad)" - }, - "ap-southeast-1" : { - "description" : "Asia Pacific (Singapore)" - }, - "ap-southeast-2" : { - "description" : "Asia Pacific (Sydney)" - }, - "ap-southeast-3" : { - "description" : "Asia Pacific (Jakarta)" - }, - "ap-southeast-4" : { - "description" : "Asia Pacific (Melbourne)" - }, - "aws-global" : { - "description" : "AWS Standard global region" - }, - "ca-central-1" : { - "description" : "Canada (Central)" - }, - "ca-west-1" : { - "description" : "Canada West (Calgary)" - }, - "eu-central-1" : { - "description" : "Europe (Frankfurt)" - }, - "eu-central-2" : { - "description" : "Europe (Zurich)" - }, - "eu-north-1" : { - "description" : "Europe (Stockholm)" - }, - "eu-south-1" : { - "description" : "Europe (Milan)" - }, - "eu-south-2" : { - "description" : "Europe (Spain)" - }, - "eu-west-1" : { - "description" : "Europe (Ireland)" - }, - "eu-west-2" : { - "description" : "Europe (London)" - }, - "eu-west-3" : { - "description" : "Europe (Paris)" - }, - "il-central-1" : { - "description" : "Israel (Tel Aviv)" - }, - "me-central-1" : { - "description" : "Middle East (UAE)" - }, - "me-south-1" : { - "description" : "Middle East (Bahrain)" - }, - "sa-east-1" : { - "description" : "South America (Sao Paulo)" - }, - "us-east-1" : { - "description" : "US East (N. Virginia)" - }, - "us-east-2" : { - "description" : "US East (Ohio)" - }, - "us-west-1" : { - "description" : "US West (N. California)" - }, - "us-west-2" : { - "description" : "US West (Oregon)" - } - } - }, { - "id" : "aws-cn", - "outputs" : { - "dnsSuffix" : "amazonaws.com.cn", - "dualStackDnsSuffix" : "api.amazonwebservices.com.cn", - "implicitGlobalRegion" : "cn-northwest-1", - "name" : "aws-cn", - "supportsDualStack" : true, - "supportsFIPS" : true - }, - "regionRegex" : "^cn\\-\\w+\\-\\d+$", - "regions" : { - "aws-cn-global" : { - "description" : "AWS China global region" - }, - "cn-north-1" : { - "description" : "China (Beijing)" - }, - "cn-northwest-1" : { - "description" : "China (Ningxia)" - } - } - }, { - "id" : "aws-us-gov", - "outputs" : { - "dnsSuffix" : "amazonaws.com", - "dualStackDnsSuffix" : "api.aws", - "implicitGlobalRegion" : "us-gov-west-1", - "name" : "aws-us-gov", - "supportsDualStack" : true, - "supportsFIPS" : true - }, - "regionRegex" : "^us\\-gov\\-\\w+\\-\\d+$", - "regions" : { - "aws-us-gov-global" : { - "description" : "AWS GovCloud (US) global region" - }, - "us-gov-east-1" : { - "description" : "AWS GovCloud (US-East)" - }, - "us-gov-west-1" : { - "description" : "AWS GovCloud (US-West)" - } - } - }, { - "id" : "aws-iso", - "outputs" : { - "dnsSuffix" : "c2s.ic.gov", - "dualStackDnsSuffix" : "c2s.ic.gov", - "implicitGlobalRegion" : "us-iso-east-1", - "name" : "aws-iso", - "supportsDualStack" : false, - "supportsFIPS" : true - }, - "regionRegex" : "^us\\-iso\\-\\w+\\-\\d+$", - "regions" : { - "aws-iso-global" : { - "description" : "AWS ISO (US) global region" - }, - "us-iso-east-1" : { - "description" : "US ISO East" - }, - "us-iso-west-1" : { - "description" : "US ISO WEST" - } - } - }, { - "id" : "aws-iso-b", - "outputs" : { - "dnsSuffix" : "sc2s.sgov.gov", - "dualStackDnsSuffix" : "sc2s.sgov.gov", - "implicitGlobalRegion" : "us-isob-east-1", - "name" : "aws-iso-b", - "supportsDualStack" : false, - "supportsFIPS" : true - }, - "regionRegex" : "^us\\-isob\\-\\w+\\-\\d+$", - "regions" : { - "aws-iso-b-global" : { - "description" : "AWS ISOB (US) global region" - }, - "us-isob-east-1" : { - "description" : "US ISOB East (Ohio)" - } - } - }, { - "id" : "aws-iso-e", - "outputs" : { - "dnsSuffix" : "cloud.adc-e.uk", - "dualStackDnsSuffix" : "cloud.adc-e.uk", - "implicitGlobalRegion" : "eu-isoe-west-1", - "name" : "aws-iso-e", - "supportsDualStack" : false, - "supportsFIPS" : true - }, - "regionRegex" : "^eu\\-isoe\\-\\w+\\-\\d+$", - "regions" : { } - }, { - "id" : "aws-iso-f", - "outputs" : { - "dnsSuffix" : "csp.hci.ic.gov", - "dualStackDnsSuffix" : "csp.hci.ic.gov", - "implicitGlobalRegion" : "us-isof-south-1", - "name" : "aws-iso-f", - "supportsDualStack" : false, - "supportsFIPS" : true - }, - "regionRegex" : "^us\\-isof\\-\\w+\\-\\d+$", - "regions" : { } - } ], - "version" : "1.1" -} \ No newline at end of file diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/endpoints.go deleted file mode 100644 index 67950ca3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/endpoints.go +++ /dev/null @@ -1,201 +0,0 @@ -package endpoints - -import ( - "fmt" - "regexp" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -const ( - defaultProtocol = "https" - defaultSigner = "v4" -) - -var ( - protocolPriority = []string{"https", "http"} - signerPriority = []string{"v4"} -) - -// Options provide configuration needed to direct how endpoints are resolved. -type Options struct { - // Disable usage of HTTPS (TLS / SSL) - DisableHTTPS bool -} - -// Partitions is a slice of partition -type Partitions []Partition - -// ResolveEndpoint resolves a service endpoint for the given region and options. -func (ps Partitions) ResolveEndpoint(region string, opts Options) (aws.Endpoint, error) { - if len(ps) == 0 { - return aws.Endpoint{}, fmt.Errorf("no partitions found") - } - - for i := 0; i < len(ps); i++ { - if !ps[i].canResolveEndpoint(region) { - continue - } - - return ps[i].ResolveEndpoint(region, opts) - } - - // fallback to first partition format to use when resolving the endpoint. - return ps[0].ResolveEndpoint(region, opts) -} - -// Partition is an AWS partition description for a service and its' region endpoints. -type Partition struct { - ID string - RegionRegex *regexp.Regexp - PartitionEndpoint string - IsRegionalized bool - Defaults Endpoint - Endpoints Endpoints -} - -func (p Partition) canResolveEndpoint(region string) bool { - _, ok := p.Endpoints[region] - return ok || p.RegionRegex.MatchString(region) -} - -// ResolveEndpoint resolves and service endpoint for the given region and options. -func (p Partition) ResolveEndpoint(region string, options Options) (resolved aws.Endpoint, err error) { - if len(region) == 0 && len(p.PartitionEndpoint) != 0 { - region = p.PartitionEndpoint - } - - e, _ := p.endpointForRegion(region) - - return e.resolve(p.ID, region, p.Defaults, options), nil -} - -func (p Partition) endpointForRegion(region string) (Endpoint, bool) { - if e, ok := p.Endpoints[region]; ok { - return e, true - } - - if !p.IsRegionalized { - return p.Endpoints[p.PartitionEndpoint], region == p.PartitionEndpoint - } - - // Unable to find any matching endpoint, return - // blank that will be used for generic endpoint creation. - return Endpoint{}, false -} - -// Endpoints is a map of service config regions to endpoints -type Endpoints map[string]Endpoint - -// CredentialScope is the credential scope of a region and service -type CredentialScope struct { - Region string - Service string -} - -// Endpoint is a service endpoint description -type Endpoint struct { - // True if the endpoint cannot be resolved for this partition/region/service - Unresolveable aws.Ternary - - Hostname string - Protocols []string - - CredentialScope CredentialScope - - SignatureVersions []string `json:"signatureVersions"` -} - -func (e Endpoint) resolve(partition, region string, def Endpoint, options Options) aws.Endpoint { - var merged Endpoint - merged.mergeIn(def) - merged.mergeIn(e) - e = merged - - var u string - if e.Unresolveable != aws.TrueTernary { - // Only attempt to resolve the endpoint if it can be resolved. - hostname := strings.Replace(e.Hostname, "{region}", region, 1) - - scheme := getEndpointScheme(e.Protocols, options.DisableHTTPS) - u = scheme + "://" + hostname - } - - signingRegion := e.CredentialScope.Region - if len(signingRegion) == 0 { - signingRegion = region - } - signingName := e.CredentialScope.Service - - return aws.Endpoint{ - URL: u, - PartitionID: partition, - SigningRegion: signingRegion, - SigningName: signingName, - SigningMethod: getByPriority(e.SignatureVersions, signerPriority, defaultSigner), - } -} - -func (e *Endpoint) mergeIn(other Endpoint) { - if other.Unresolveable != aws.UnknownTernary { - e.Unresolveable = other.Unresolveable - } - if len(other.Hostname) > 0 { - e.Hostname = other.Hostname - } - if len(other.Protocols) > 0 { - e.Protocols = other.Protocols - } - if len(other.CredentialScope.Region) > 0 { - e.CredentialScope.Region = other.CredentialScope.Region - } - if len(other.CredentialScope.Service) > 0 { - e.CredentialScope.Service = other.CredentialScope.Service - } - if len(other.SignatureVersions) > 0 { - e.SignatureVersions = other.SignatureVersions - } -} - -func getEndpointScheme(protocols []string, disableHTTPS bool) string { - if disableHTTPS { - return "http" - } - - return getByPriority(protocols, protocolPriority, defaultProtocol) -} - -func getByPriority(s []string, p []string, def string) string { - if len(s) == 0 { - return def - } - - for i := 0; i < len(p); i++ { - for j := 0; j < len(s); j++ { - if s[j] == p[i] { - return s[j] - } - } - } - - return s[0] -} - -// MapFIPSRegion extracts the intrinsic AWS region from one that may have an -// embedded FIPS microformat. -func MapFIPSRegion(region string) string { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(region, fipsInfix) || - strings.Contains(region, fipsPrefix) || - strings.Contains(region, fipsSuffix) { - region = strings.ReplaceAll(region, fipsInfix, "-") - region = strings.ReplaceAll(region, fipsPrefix, "") - region = strings.ReplaceAll(region, fipsSuffix, "") - } - - return region -} 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 deleted file mode 100644 index e0265474..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/CHANGELOG.md +++ /dev/null @@ -1,228 +0,0 @@ -# v2.5.10 (2024-01-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.5.9 (2023-12-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.5.8 (2023-12-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.5.7 (2023-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.5.6 (2023-11-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.5.5 (2023-11-28.2) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.5.4 (2023-11-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.5.3 (2023-11-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.5.2 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.5.1 (2023-11-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.5.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 - -# v2.4.37 (2023-10-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.36 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.35 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.34 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.33 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.32 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.31 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.30 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.29 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.28 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.27 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.26 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.25 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.24 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.23 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.22 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.21 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.20 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.19 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.18 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.17 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.16 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.15 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.14 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.13 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.12 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.11 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.10 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.9 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.8 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.7 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.6 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.5 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.4.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.3.0 (2022-02-24) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.2.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.1.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.0.2 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.0.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v2.0.0 (2021-11-06) - -* **Release**: Endpoint Variant Model Support -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/internal/endpoints/v2/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/endpoints.go deleted file mode 100644 index 32251a7e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/endpoints.go +++ /dev/null @@ -1,302 +0,0 @@ -package endpoints - -import ( - "fmt" - "github.com/aws/smithy-go/logging" - "regexp" - "strings" - - "github.com/aws/aws-sdk-go-v2/aws" -) - -// DefaultKey is a compound map key of a variant and other values. -type DefaultKey struct { - Variant EndpointVariant - ServiceVariant ServiceVariant -} - -// EndpointKey is a compound map key of a region and associated variant value. -type EndpointKey struct { - Region string - Variant EndpointVariant - ServiceVariant ServiceVariant -} - -// EndpointVariant is a bit field to describe the endpoints attributes. -type EndpointVariant uint64 - -const ( - // FIPSVariant indicates that the endpoint is FIPS capable. - FIPSVariant EndpointVariant = 1 << (64 - 1 - iota) - - // DualStackVariant indicates that the endpoint is DualStack capable. - DualStackVariant -) - -// ServiceVariant is a bit field to describe the service endpoint attributes. -type ServiceVariant uint64 - -const ( - defaultProtocol = "https" - defaultSigner = "v4" -) - -var ( - protocolPriority = []string{"https", "http"} - signerPriority = []string{"v4", "s3v4"} -) - -// Options provide configuration needed to direct how endpoints are resolved. -type Options struct { - // Logger is a logging implementation that log events should be sent to. - Logger logging.Logger - - // LogDeprecated indicates that deprecated endpoints should be logged to the provided logger. - LogDeprecated bool - - // ResolvedRegion is the resolved region string. If provided (non-zero length) it takes priority - // over the region name passed to the ResolveEndpoint call. - ResolvedRegion string - - // Disable usage of HTTPS (TLS / SSL) - DisableHTTPS bool - - // Instruct the resolver to use a service endpoint that supports dual-stack. - // If a service does not have a dual-stack endpoint an error will be returned by the resolver. - UseDualStackEndpoint aws.DualStackEndpointState - - // Instruct the resolver to use a service endpoint that supports FIPS. - // If a service does not have a FIPS endpoint an error will be returned by the resolver. - UseFIPSEndpoint aws.FIPSEndpointState - - // ServiceVariant is a bitfield of service specified endpoint variant data. - ServiceVariant ServiceVariant -} - -// GetEndpointVariant returns the EndpointVariant for the variant associated options. -func (o Options) GetEndpointVariant() (v EndpointVariant) { - if o.UseDualStackEndpoint == aws.DualStackEndpointStateEnabled { - v |= DualStackVariant - } - if o.UseFIPSEndpoint == aws.FIPSEndpointStateEnabled { - v |= FIPSVariant - } - return v -} - -// Partitions is a slice of partition -type Partitions []Partition - -// ResolveEndpoint resolves a service endpoint for the given region and options. -func (ps Partitions) ResolveEndpoint(region string, opts Options) (aws.Endpoint, error) { - if len(ps) == 0 { - return aws.Endpoint{}, fmt.Errorf("no partitions found") - } - - if opts.Logger == nil { - opts.Logger = logging.Nop{} - } - - if len(opts.ResolvedRegion) > 0 { - region = opts.ResolvedRegion - } - - for i := 0; i < len(ps); i++ { - if !ps[i].canResolveEndpoint(region, opts) { - continue - } - - return ps[i].ResolveEndpoint(region, opts) - } - - // fallback to first partition format to use when resolving the endpoint. - return ps[0].ResolveEndpoint(region, opts) -} - -// Partition is an AWS partition description for a service and its' region endpoints. -type Partition struct { - ID string - RegionRegex *regexp.Regexp - PartitionEndpoint string - IsRegionalized bool - Defaults map[DefaultKey]Endpoint - Endpoints Endpoints -} - -func (p Partition) canResolveEndpoint(region string, opts Options) bool { - _, ok := p.Endpoints[EndpointKey{ - Region: region, - Variant: opts.GetEndpointVariant(), - }] - return ok || p.RegionRegex.MatchString(region) -} - -// ResolveEndpoint resolves and service endpoint for the given region and options. -func (p Partition) ResolveEndpoint(region string, options Options) (resolved aws.Endpoint, err error) { - if len(region) == 0 && len(p.PartitionEndpoint) != 0 { - region = p.PartitionEndpoint - } - - endpoints := p.Endpoints - - variant := options.GetEndpointVariant() - serviceVariant := options.ServiceVariant - - defaults := p.Defaults[DefaultKey{ - Variant: variant, - ServiceVariant: serviceVariant, - }] - - return p.endpointForRegion(region, variant, serviceVariant, endpoints).resolve(p.ID, region, defaults, options) -} - -func (p Partition) endpointForRegion(region string, variant EndpointVariant, serviceVariant ServiceVariant, endpoints Endpoints) Endpoint { - key := EndpointKey{ - Region: region, - Variant: variant, - } - - if e, ok := endpoints[key]; ok { - return e - } - - if !p.IsRegionalized { - return endpoints[EndpointKey{ - Region: p.PartitionEndpoint, - Variant: variant, - ServiceVariant: serviceVariant, - }] - } - - // Unable to find any matching endpoint, return - // blank that will be used for generic endpoint creation. - return Endpoint{} -} - -// Endpoints is a map of service config regions to endpoints -type Endpoints map[EndpointKey]Endpoint - -// CredentialScope is the credential scope of a region and service -type CredentialScope struct { - Region string - Service string -} - -// Endpoint is a service endpoint description -type Endpoint struct { - // True if the endpoint cannot be resolved for this partition/region/service - Unresolveable aws.Ternary - - Hostname string - Protocols []string - - CredentialScope CredentialScope - - SignatureVersions []string - - // Indicates that this endpoint is deprecated. - Deprecated aws.Ternary -} - -// IsZero returns whether the endpoint structure is an empty (zero) value. -func (e Endpoint) IsZero() bool { - switch { - case e.Unresolveable != aws.UnknownTernary: - return false - case len(e.Hostname) != 0: - return false - case len(e.Protocols) != 0: - return false - case e.CredentialScope != (CredentialScope{}): - return false - case len(e.SignatureVersions) != 0: - return false - } - return true -} - -func (e Endpoint) resolve(partition, region string, def Endpoint, options Options) (aws.Endpoint, error) { - var merged Endpoint - merged.mergeIn(def) - merged.mergeIn(e) - e = merged - - if e.IsZero() { - return aws.Endpoint{}, fmt.Errorf("unable to resolve endpoint for region: %v", region) - } - - var u string - if e.Unresolveable != aws.TrueTernary { - // Only attempt to resolve the endpoint if it can be resolved. - hostname := strings.Replace(e.Hostname, "{region}", region, 1) - - scheme := getEndpointScheme(e.Protocols, options.DisableHTTPS) - u = scheme + "://" + hostname - } - - signingRegion := e.CredentialScope.Region - if len(signingRegion) == 0 { - signingRegion = region - } - signingName := e.CredentialScope.Service - - if e.Deprecated == aws.TrueTernary && options.LogDeprecated { - options.Logger.Logf(logging.Warn, "endpoint identifier %q, url %q marked as deprecated", region, u) - } - - return aws.Endpoint{ - URL: u, - PartitionID: partition, - SigningRegion: signingRegion, - SigningName: signingName, - SigningMethod: getByPriority(e.SignatureVersions, signerPriority, defaultSigner), - }, nil -} - -func (e *Endpoint) mergeIn(other Endpoint) { - if other.Unresolveable != aws.UnknownTernary { - e.Unresolveable = other.Unresolveable - } - if len(other.Hostname) > 0 { - e.Hostname = other.Hostname - } - if len(other.Protocols) > 0 { - e.Protocols = other.Protocols - } - if len(other.CredentialScope.Region) > 0 { - e.CredentialScope.Region = other.CredentialScope.Region - } - if len(other.CredentialScope.Service) > 0 { - e.CredentialScope.Service = other.CredentialScope.Service - } - if len(other.SignatureVersions) > 0 { - e.SignatureVersions = other.SignatureVersions - } - if other.Deprecated != aws.UnknownTernary { - e.Deprecated = other.Deprecated - } -} - -func getEndpointScheme(protocols []string, disableHTTPS bool) string { - if disableHTTPS { - return "http" - } - - return getByPriority(protocols, protocolPriority, defaultProtocol) -} - -func getByPriority(s []string, p []string, def string) string { - if len(s) == 0 { - return def - } - - for i := 0; i < len(p); i++ { - for j := 0; j < len(s); j++ { - if s[j] == p[i] { - return s[j] - } - } - } - - return s[0] -} 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 deleted file mode 100644 index bec2c6a1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/endpoints/v2/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package endpoints - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "2.5.10" 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 deleted file mode 100644 index adbbf4ad..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/CHANGELOG.md +++ /dev/null @@ -1,263 +0,0 @@ -# v1.7.2 (2023-12-08) - -* **Bug Fix**: Correct loading of [services *] sections into shared config. - -# v1.7.1 (2023-11-16) - -* **Bug Fix**: Fix recognition of trailing comments in shared config properties. # or ; separators that aren't preceded by whitespace at the end of a property value should be considered part of it. - -# v1.7.0 (2023-11-13) - -* **Feature**: Replace the legacy config parser with a modern, less-strict implementation. Parsing failures within a section will now simply ignore the invalid line rather than silently drop the entire section. - -# v1.6.0 (2023-11-09.2) - -* **Feature**: BREAKFIX: In order to support subproperty parsing, invalid property definitions must not be ignored - -# v1.5.2 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.1 (2023-11-07) - -* **Bug Fix**: Fix subproperty performance regression - -# v1.5.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.4.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.3.45 (2023-10-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.44 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.43 (2023-09-22) - -* **Bug Fix**: Fixed a bug where merging `max_attempts` or `duration_seconds` fields across shared config files with invalid values would silently default them to 0. -* **Bug Fix**: Move type assertion of config values out of the parsing stage, which resolves an issue where the contents of a profile would silently be dropped with certain numeric formats. - -# v1.3.42 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.41 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.40 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.39 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.38 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.37 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.36 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.35 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.34 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.33 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.32 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.31 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.30 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.29 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.28 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.27 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.26 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.25 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.24 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.23 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.22 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.21 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.20 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.19 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.18 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.17 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.16 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.15 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.14 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.13 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.12 (2022-05-17) - -* **Bug Fix**: Removes the fuzz testing files from the module, as they are invalid and not used. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.11 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.10 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.9 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.8 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.7 (2022-03-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.6 (2022-02-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.5 (2022-01-28) - -* **Bug Fix**: Fixes the SDK's handling of `duration_sections` in the shared credentials file or specified in multiple shared config and shared credentials files under the same profile. [#1568](https://github.com/aws/aws-sdk-go-v2/pull/1568). Thanks to [Amir Szekely](https://github.com/kichik) for help reproduce this bug. - -# v1.3.4 (2022-01-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.3 (2022-01-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.2 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.5 (2021-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.4 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.3 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.2 (2021-08-27) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.1 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-08-04) - -* **Feature**: adds error handling for defered close calls -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.1 (2021-07-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.0 (2021-07-01) - -* **Feature**: Support for `:`, `=`, `[`, `]` being present in expression values. - -# v1.0.1 (2021-06-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.0.0 (2021-05-20) - -* **Release**: The `github.com/aws/aws-sdk-go-v2/internal/ini` package is now a Go Module. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/internal/ini/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/errors.go deleted file mode 100644 index 0f278d55..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/errors.go +++ /dev/null @@ -1,22 +0,0 @@ -package ini - -import "fmt" - -// UnableToReadFile is an error indicating that a ini file could not be read -type UnableToReadFile struct { - Err error -} - -// Error returns an error message and the underlying error message if present -func (e *UnableToReadFile) Error() string { - base := "unable to read file" - if e.Err == nil { - return base - } - return fmt.Sprintf("%s: %v", base, e.Err) -} - -// Unwrap returns the underlying error -func (e *UnableToReadFile) Unwrap() error { - return e.Err -} 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 deleted file mode 100644 index f0673f3a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package ini - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.7.2" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini.go deleted file mode 100644 index cefcce91..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/ini.go +++ /dev/null @@ -1,56 +0,0 @@ -// Package ini implements parsing of the AWS shared config file. -// -// Example: -// sections, err := ini.OpenFile("/path/to/file") -// if err != nil { -// panic(err) -// } -// -// profile := "foo" -// section, ok := sections.GetSection(profile) -// if !ok { -// fmt.Printf("section %q could not be found", profile) -// } -package ini - -import ( - "fmt" - "io" - "os" - "strings" -) - -// OpenFile parses shared config from the given file path. -func OpenFile(path string) (sections Sections, err error) { - f, oerr := os.Open(path) - if oerr != nil { - return Sections{}, &UnableToReadFile{Err: oerr} - } - - defer func() { - closeErr := f.Close() - if err == nil { - err = closeErr - } else if closeErr != nil { - err = fmt.Errorf("close error: %v, original error: %w", closeErr, err) - } - }() - - return Parse(f, path) -} - -// Parse parses shared config from the given reader. -func Parse(r io.Reader, path string) (Sections, error) { - contents, err := io.ReadAll(r) - if err != nil { - return Sections{}, fmt.Errorf("read all: %v", err) - } - - lines := strings.Split(string(contents), "\n") - tokens, err := tokenize(lines) - if err != nil { - return Sections{}, fmt.Errorf("tokenize: %v", err) - } - - return parse(tokens, path), nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/parse.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/parse.go deleted file mode 100644 index 2422d904..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/parse.go +++ /dev/null @@ -1,109 +0,0 @@ -package ini - -import ( - "fmt" - "strings" -) - -func parse(tokens []lineToken, path string) Sections { - parser := &parser{ - path: path, - sections: NewSections(), - } - parser.parse(tokens) - return parser.sections -} - -type parser struct { - csection, ckey string // current state - path string // source file path - sections Sections // parse result -} - -func (p *parser) parse(tokens []lineToken) { - for _, otok := range tokens { - switch tok := otok.(type) { - case *lineTokenProfile: - p.handleProfile(tok) - case *lineTokenProperty: - p.handleProperty(tok) - case *lineTokenSubProperty: - p.handleSubProperty(tok) - case *lineTokenContinuation: - p.handleContinuation(tok) - } - } -} - -func (p *parser) handleProfile(tok *lineTokenProfile) { - name := tok.Name - if tok.Type != "" { - name = fmt.Sprintf("%s %s", tok.Type, tok.Name) - } - p.ckey = "" - p.csection = name - if _, ok := p.sections.container[name]; !ok { - p.sections.container[name] = NewSection(name) - } -} - -func (p *parser) handleProperty(tok *lineTokenProperty) { - if p.csection == "" { - return // LEGACY: don't error on "global" properties - } - - p.ckey = tok.Key - if _, ok := p.sections.container[p.csection].values[tok.Key]; ok { - section := p.sections.container[p.csection] - section.Logs = append(p.sections.container[p.csection].Logs, - fmt.Sprintf( - "For profile: %v, overriding %v value, with a %v value found in a duplicate profile defined later in the same file %v. \n", - p.csection, tok.Key, tok.Key, p.path, - ), - ) - p.sections.container[p.csection] = section - } - - p.sections.container[p.csection].values[tok.Key] = Value{ - str: tok.Value, - } - p.sections.container[p.csection].SourceFile[tok.Key] = p.path -} - -func (p *parser) handleSubProperty(tok *lineTokenSubProperty) { - if p.csection == "" { - return // LEGACY: don't error on "global" properties - } - - if p.ckey == "" || p.sections.container[p.csection].values[p.ckey].str != "" { - // This is an "orphaned" subproperty, either because it's at - // the beginning of a section or because the last property's - // value isn't empty. Either way we're lenient here and - // "promote" this to a normal property. - p.handleProperty(&lineTokenProperty{ - Key: tok.Key, - Value: strings.TrimSpace(trimPropertyComment(tok.Value)), - }) - return - } - - if p.sections.container[p.csection].values[p.ckey].mp == nil { - p.sections.container[p.csection].values[p.ckey] = Value{ - mp: map[string]string{}, - } - } - p.sections.container[p.csection].values[p.ckey].mp[tok.Key] = tok.Value -} - -func (p *parser) handleContinuation(tok *lineTokenContinuation) { - if p.ckey == "" { - return - } - - value, _ := p.sections.container[p.csection].values[p.ckey] - if value.str != "" && value.mp == nil { - value.str = fmt.Sprintf("%s\n%s", value.str, tok.Value) - } - - p.sections.container[p.csection].values[p.ckey] = value -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/sections.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/sections.go deleted file mode 100644 index dd89848e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/sections.go +++ /dev/null @@ -1,157 +0,0 @@ -package ini - -import ( - "sort" -) - -// Sections is a map of Section structures that represent -// a configuration. -type Sections struct { - container map[string]Section -} - -// NewSections returns empty ini Sections -func NewSections() Sections { - return Sections{ - container: make(map[string]Section, 0), - } -} - -// GetSection will return section p. If section p does not exist, -// false will be returned in the second parameter. -func (t Sections) GetSection(p string) (Section, bool) { - v, ok := t.container[p] - return v, ok -} - -// HasSection denotes if Sections consist of a section with -// provided name. -func (t Sections) HasSection(p string) bool { - _, ok := t.container[p] - return ok -} - -// SetSection sets a section value for provided section name. -func (t Sections) SetSection(p string, v Section) Sections { - t.container[p] = v - return t -} - -// DeleteSection deletes a section entry/value for provided section name./ -func (t Sections) DeleteSection(p string) { - delete(t.container, p) -} - -// values represents a map of union values. -type values map[string]Value - -// List will return a list of all sections that were successfully -// parsed. -func (t Sections) List() []string { - keys := make([]string, len(t.container)) - i := 0 - for k := range t.container { - keys[i] = k - i++ - } - - sort.Strings(keys) - return keys -} - -// Section contains a name and values. This represent -// a sectioned entry in a configuration file. -type Section struct { - // Name is the Section profile name - Name string - - // values are the values within parsed profile - values values - - // Errors is the list of errors - Errors []error - - // Logs is the list of logs - Logs []string - - // SourceFile is the INI Source file from where this section - // was retrieved. They key is the property, value is the - // source file the property was retrieved from. - SourceFile map[string]string -} - -// NewSection returns an initialize section for the name -func NewSection(name string) Section { - return Section{ - Name: name, - values: values{}, - SourceFile: map[string]string{}, - } -} - -// List will return a list of all -// services in values -func (t Section) List() []string { - keys := make([]string, len(t.values)) - i := 0 - for k := range t.values { - keys[i] = k - i++ - } - - sort.Strings(keys) - return keys -} - -// UpdateSourceFile updates source file for a property to provided filepath. -func (t Section) UpdateSourceFile(property string, filepath string) { - t.SourceFile[property] = filepath -} - -// UpdateValue updates value for a provided key with provided value -func (t Section) UpdateValue(k string, v Value) error { - t.values[k] = v - return nil -} - -// Has will return whether or not an entry exists in a given section -func (t Section) Has(k string) bool { - _, ok := t.values[k] - return ok -} - -// ValueType will returned what type the union is set to. If -// k was not found, the NoneType will be returned. -func (t Section) ValueType(k string) (ValueType, bool) { - v, ok := t.values[k] - return v.Type, ok -} - -// Bool returns a bool value at k -func (t Section) Bool(k string) (bool, bool) { - return t.values[k].BoolValue() -} - -// Int returns an integer value at k -func (t Section) Int(k string) (int64, bool) { - return t.values[k].IntValue() -} - -// Map returns a map value at k -func (t Section) Map(k string) map[string]string { - return t.values[k].MapValue() -} - -// Float64 returns a float value at k -func (t Section) Float64(k string) (float64, bool) { - return t.values[k].FloatValue() -} - -// String returns the string value at k -func (t Section) String(k string) string { - _, ok := t.values[k] - if !ok { - return "" - } - return t.values[k].StringValue() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/strings.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/strings.go deleted file mode 100644 index 661588c2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/strings.go +++ /dev/null @@ -1,93 +0,0 @@ -package ini - -import ( - "strings" -) - -func trimProfileComment(s string) string { - r, _, _ := strings.Cut(s, "#") - r, _, _ = strings.Cut(r, ";") - return r -} - -func trimPropertyComment(s string) string { - r, _, _ := strings.Cut(s, " #") - r, _, _ = strings.Cut(r, " ;") - r, _, _ = strings.Cut(r, "\t#") - r, _, _ = strings.Cut(r, "\t;") - return r -} - -// assumes no surrounding comment -func splitProperty(s string) (string, string, bool) { - equalsi := strings.Index(s, "=") - coloni := strings.Index(s, ":") // LEGACY: also supported for property assignment - sep := "=" - if equalsi == -1 || coloni != -1 && coloni < equalsi { - sep = ":" - } - - k, v, ok := strings.Cut(s, sep) - if !ok { - return "", "", false - } - return strings.TrimSpace(k), strings.TrimSpace(v), true -} - -// assumes no surrounding comment, whitespace, or profile brackets -func splitProfile(s string) (string, string) { - var first int - for i, r := range s { - if isLineSpace(r) { - if first == 0 { - first = i - } - } else { - if first != 0 { - return s[:first], s[i:] - } - } - } - if first == 0 { - return "", s // type component is effectively blank - } - return "", "" -} - -func isLineSpace(r rune) bool { - return r == ' ' || r == '\t' -} - -func unquote(s string) string { - if isSingleQuoted(s) || isDoubleQuoted(s) { - return s[1 : len(s)-1] - } - return s -} - -// applies various legacy conversions to property values: -// - remote wrapping single/doublequotes -// - expand escaped quote and newline sequences -func legacyStrconv(s string) string { - s = unquote(s) - s = strings.ReplaceAll(s, `\"`, `"`) - s = strings.ReplaceAll(s, `\'`, `'`) - s = strings.ReplaceAll(s, `\n`, "\n") - return s -} - -func isSingleQuoted(s string) bool { - return hasAffixes(s, "'", "'") -} - -func isDoubleQuoted(s string) bool { - return hasAffixes(s, `"`, `"`) -} - -func isBracketed(s string) bool { - return hasAffixes(s, "[", "]") -} - -func hasAffixes(s, left, right string) bool { - return strings.HasPrefix(s, left) && strings.HasSuffix(s, right) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/token.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/token.go deleted file mode 100644 index 6e9a0374..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/token.go +++ /dev/null @@ -1,32 +0,0 @@ -package ini - -type lineToken interface { - isLineToken() -} - -type lineTokenProfile struct { - Type string - Name string -} - -func (*lineTokenProfile) isLineToken() {} - -type lineTokenProperty struct { - Key string - Value string -} - -func (*lineTokenProperty) isLineToken() {} - -type lineTokenContinuation struct { - Value string -} - -func (*lineTokenContinuation) isLineToken() {} - -type lineTokenSubProperty struct { - Key string - Value string -} - -func (*lineTokenSubProperty) isLineToken() {} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/tokenize.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/tokenize.go deleted file mode 100644 index 89a77368..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/tokenize.go +++ /dev/null @@ -1,92 +0,0 @@ -package ini - -import ( - "strings" -) - -func tokenize(lines []string) ([]lineToken, error) { - tokens := make([]lineToken, 0, len(lines)) - for _, line := range lines { - if len(strings.TrimSpace(line)) == 0 || isLineComment(line) { - continue - } - - if tok := asProfile(line); tok != nil { - tokens = append(tokens, tok) - } else if tok := asProperty(line); tok != nil { - tokens = append(tokens, tok) - } else if tok := asSubProperty(line); tok != nil { - tokens = append(tokens, tok) - } else if tok := asContinuation(line); tok != nil { - tokens = append(tokens, tok) - } // unrecognized tokens are effectively ignored - } - return tokens, nil -} - -func isLineComment(line string) bool { - trimmed := strings.TrimLeft(line, " \t") - return strings.HasPrefix(trimmed, "#") || strings.HasPrefix(trimmed, ";") -} - -func asProfile(line string) *lineTokenProfile { // " [ type name ] ; comment" - trimmed := strings.TrimSpace(trimProfileComment(line)) // "[ type name ]" - if !isBracketed(trimmed) { - return nil - } - trimmed = trimmed[1 : len(trimmed)-1] // " type name " (or just " name ") - trimmed = strings.TrimSpace(trimmed) // "type name" / "name" - typ, name := splitProfile(trimmed) - return &lineTokenProfile{ - Type: typ, - Name: name, - } -} - -func asProperty(line string) *lineTokenProperty { - if isLineSpace(rune(line[0])) { - return nil - } - - trimmed := trimPropertyComment(line) - trimmed = strings.TrimRight(trimmed, " \t") - k, v, ok := splitProperty(trimmed) - if !ok { - return nil - } - - return &lineTokenProperty{ - Key: strings.ToLower(k), // LEGACY: normalize key case - Value: legacyStrconv(v), // LEGACY: see func docs - } -} - -func asSubProperty(line string) *lineTokenSubProperty { - if !isLineSpace(rune(line[0])) { - return nil - } - - // comments on sub-properties are included in the value - trimmed := strings.TrimLeft(line, " \t") - k, v, ok := splitProperty(trimmed) - if !ok { - return nil - } - - return &lineTokenSubProperty{ // same LEGACY constraints as in normal property - Key: strings.ToLower(k), - Value: legacyStrconv(v), - } -} - -func asContinuation(line string) *lineTokenContinuation { - if !isLineSpace(rune(line[0])) { - return nil - } - - // includes comments like sub-properties - trimmed := strings.TrimLeft(line, " \t") - return &lineTokenContinuation{ - Value: trimmed, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/value.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/value.go deleted file mode 100644 index e3706b3c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/ini/value.go +++ /dev/null @@ -1,93 +0,0 @@ -package ini - -import ( - "fmt" - "strconv" - "strings" -) - -// ValueType is an enum that will signify what type -// the Value is -type ValueType int - -func (v ValueType) String() string { - switch v { - case NoneType: - return "NONE" - case StringType: - return "STRING" - } - - return "" -} - -// ValueType enums -const ( - NoneType = ValueType(iota) - StringType - QuotedStringType -) - -// Value is a union container -type Value struct { - Type ValueType - - str string - mp map[string]string -} - -// NewStringValue returns a Value type generated using a string input. -func NewStringValue(str string) (Value, error) { - return Value{str: str}, nil -} - -func (v Value) String() string { - switch v.Type { - case StringType: - return fmt.Sprintf("string: %s", string(v.str)) - case QuotedStringType: - return fmt.Sprintf("quoted string: %s", string(v.str)) - default: - return "union not set" - } -} - -// MapValue returns a map value for sub properties -func (v Value) MapValue() map[string]string { - return v.mp -} - -// IntValue returns an integer value -func (v Value) IntValue() (int64, bool) { - i, err := strconv.ParseInt(string(v.str), 0, 64) - if err != nil { - return 0, false - } - return i, true -} - -// FloatValue returns a float value -func (v Value) FloatValue() (float64, bool) { - f, err := strconv.ParseFloat(string(v.str), 64) - if err != nil { - return 0, false - } - return f, true -} - -// BoolValue returns a bool value -func (v Value) BoolValue() (bool, bool) { - // we don't use ParseBool as it recognizes more than what we've - // historically supported - if strings.EqualFold(v.str, "true") { - return true, true - } else if strings.EqualFold(v.str, "false") { - return false, true - } - return false, false -} - -// StringValue returns the string value -func (v Value) StringValue() string { - return v.str -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/rand/rand.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/rand/rand.go deleted file mode 100644 index c8484dcd..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/rand/rand.go +++ /dev/null @@ -1,33 +0,0 @@ -package rand - -import ( - "crypto/rand" - "fmt" - "io" - "math/big" -) - -func init() { - Reader = rand.Reader -} - -// Reader provides a random reader that can reset during testing. -var Reader io.Reader - -var floatMaxBigInt = big.NewInt(1 << 53) - -// Float64 returns a float64 read from an io.Reader source. The returned float will be between [0.0, 1.0). -func Float64(reader io.Reader) (float64, error) { - bi, err := rand.Int(reader, floatMaxBigInt) - if err != nil { - return 0, fmt.Errorf("failed to read random value, %v", err) - } - - return float64(bi.Int64()) / (1 << 53), nil -} - -// CryptoRandFloat64 returns a random float64 obtained from the crypto rand -// source. -func CryptoRandFloat64() (float64, error) { - return Float64(Reader) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/interfaces.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/interfaces.go deleted file mode 100644 index 2b42cbe6..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/interfaces.go +++ /dev/null @@ -1,9 +0,0 @@ -package sdk - -// Invalidator provides access to a type's invalidate method to make it -// invalidate it cache. -// -// e.g aws.SafeCredentialsProvider's Invalidate method. -type Invalidator interface { - Invalidate() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/time.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/time.go deleted file mode 100644 index 8e8dabad..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdk/time.go +++ /dev/null @@ -1,74 +0,0 @@ -package sdk - -import ( - "context" - "time" -) - -func init() { - NowTime = time.Now - Sleep = time.Sleep - SleepWithContext = sleepWithContext -} - -// NowTime is a value for getting the current time. This value can be overridden -// for testing mocking out current time. -var NowTime func() time.Time - -// Sleep is a value for sleeping for a duration. This value can be overridden -// for testing and mocking out sleep duration. -var Sleep func(time.Duration) - -// SleepWithContext will wait for the timer duration to expire, or the context -// is canceled. Which ever happens first. If the context is canceled the Context's -// error will be returned. -// -// This value can be overridden for testing and mocking out sleep duration. -var SleepWithContext func(context.Context, time.Duration) error - -// sleepWithContext will wait for the timer duration to expire, or the context -// is canceled. Which ever happens first. If the context is canceled the -// Context's error will be returned. -func sleepWithContext(ctx context.Context, dur time.Duration) error { - t := time.NewTimer(dur) - defer t.Stop() - - select { - case <-t.C: - break - case <-ctx.Done(): - return ctx.Err() - } - - return nil -} - -// noOpSleepWithContext does nothing, returns immediately. -func noOpSleepWithContext(context.Context, time.Duration) error { - return nil -} - -func noOpSleep(time.Duration) {} - -// TestingUseNopSleep is a utility for disabling sleep across the SDK for -// testing. -func TestingUseNopSleep() func() { - SleepWithContext = noOpSleepWithContext - Sleep = noOpSleep - - return func() { - SleepWithContext = sleepWithContext - Sleep = time.Sleep - } -} - -// TestingUseReferenceTime is a utility for swapping the time function across the SDK to return a specific reference time -// for testing purposes. -func TestingUseReferenceTime(referenceTime time.Time) func() { - NowTime = func() time.Time { - return referenceTime - } - return func() { - NowTime = time.Now - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdkio/byte.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sdkio/byte.go deleted file mode 100644 index 6c443988..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sdkio/byte.go +++ /dev/null @@ -1,12 +0,0 @@ -package sdkio - -const ( - // Byte is 8 bits - Byte int64 = 1 - // KibiByte (KiB) is 1024 Bytes - KibiByte = Byte * 1024 - // MebiByte (MiB) is 1024 KiB - MebiByte = KibiByte * 1024 - // GibiByte (GiB) is 1024 MiB - GibiByte = MebiByte * 1024 -) diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/shareddefaults/shared_config.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/shareddefaults/shared_config.go deleted file mode 100644 index c96b717e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/shareddefaults/shared_config.go +++ /dev/null @@ -1,47 +0,0 @@ -package shareddefaults - -import ( - "os" - "os/user" - "path/filepath" -) - -// SharedCredentialsFilename returns the SDK's default file path -// for the shared credentials file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/credentials -// - Windows: %USERPROFILE%\.aws\credentials -func SharedCredentialsFilename() string { - return filepath.Join(UserHomeDir(), ".aws", "credentials") -} - -// SharedConfigFilename returns the SDK's default file path for -// the shared config file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/config -// - Windows: %USERPROFILE%\.aws\config -func SharedConfigFilename() string { - return filepath.Join(UserHomeDir(), ".aws", "config") -} - -// UserHomeDir returns the home directory for the user the process is -// running under. -func UserHomeDir() string { - // Ignore errors since we only care about Windows and *nix. - home, _ := os.UserHomeDir() - - if len(home) > 0 { - return home - } - - currUser, _ := user.Current() - if currUser != nil { - home = currUser.HomeDir - } - - return home -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/strings/strings.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/strings/strings.go deleted file mode 100644 index d008ae27..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/strings/strings.go +++ /dev/null @@ -1,11 +0,0 @@ -package strings - -import ( - "strings" -) - -// HasPrefixFold tests whether the string s begins with prefix, interpreted as UTF-8 strings, -// under Unicode case-folding. -func HasPrefixFold(s, prefix string) bool { - return len(s) >= len(prefix) && strings.EqualFold(s[0:len(prefix)], prefix) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/LICENSE b/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/LICENSE deleted file mode 100644 index fe6a6200..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/LICENSE +++ /dev/null @@ -1,28 +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 COPYIGHT 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/aws/aws-sdk-go-v2/internal/sync/singleflight/docs.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/docs.go deleted file mode 100644 index cb70616e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/docs.go +++ /dev/null @@ -1,7 +0,0 @@ -// Package singleflight provides a duplicate function call suppression -// mechanism. This package is a fork of the Go golang.org/x/sync/singleflight -// package. The package is forked, because the package a part of the unstable -// and unversioned golang.org/x/sync module. -// -// https://github.com/golang/sync/tree/67f06af15bc961c363a7260195bcd53487529a21/singleflight -package singleflight diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/singleflight.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/singleflight.go deleted file mode 100644 index e8a1b17d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/sync/singleflight/singleflight.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2013 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 singleflight - -import ( - "bytes" - "errors" - "fmt" - "runtime" - "runtime/debug" - "sync" -) - -// errGoexit indicates the runtime.Goexit was called in -// the user given function. -var errGoexit = errors.New("runtime.Goexit was called") - -// A panicError is an arbitrary value recovered from a panic -// with the stack trace during the execution of given function. -type panicError struct { - value interface{} - stack []byte -} - -// Error implements error interface. -func (p *panicError) Error() string { - return fmt.Sprintf("%v\n\n%s", p.value, p.stack) -} - -func newPanicError(v interface{}) error { - stack := debug.Stack() - - // The first line of the stack trace is of the form "goroutine N [status]:" - // but by the time the panic reaches Do the goroutine may no longer exist - // and its status will have changed. Trim out the misleading line. - if line := bytes.IndexByte(stack[:], '\n'); line >= 0 { - stack = stack[line+1:] - } - return &panicError{value: v, stack: stack} -} - -// call is an in-flight or completed singleflight.Do call -type call struct { - wg sync.WaitGroup - - // These fields are written once before the WaitGroup is done - // and are only read after the WaitGroup is done. - val interface{} - err error - - // forgotten indicates whether Forget was called with this call's key - // while the call was still in flight. - forgotten bool - - // These fields are read and written with the singleflight - // mutex held before the WaitGroup is done, and are read but - // not written after the WaitGroup is done. - dups int - chans []chan<- Result -} - -// Group represents a class of work and forms a namespace in -// which units of work can be executed with duplicate suppression. -type Group struct { - mu sync.Mutex // protects m - m map[string]*call // lazily initialized -} - -// Result holds the results of Do, so they can be passed -// on a channel. -type Result struct { - Val interface{} - Err error - Shared bool -} - -// Do executes and returns the results of the given function, making -// sure that only one execution is in-flight for a given key at a -// time. If a duplicate comes in, the duplicate caller waits for the -// original to complete and receives the same results. -// The return value shared indicates whether v was given to multiple callers. -func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) { - g.mu.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - g.mu.Unlock() - c.wg.Wait() - - if e, ok := c.err.(*panicError); ok { - panic(e) - } else if c.err == errGoexit { - runtime.Goexit() - } - return c.val, c.err, true - } - c := new(call) - c.wg.Add(1) - g.m[key] = c - g.mu.Unlock() - - g.doCall(c, key, fn) - return c.val, c.err, c.dups > 0 -} - -// DoChan is like Do but returns a channel that will receive the -// results when they are ready. -// -// The returned channel will not be closed. -func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result { - ch := make(chan Result, 1) - g.mu.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - c.chans = append(c.chans, ch) - g.mu.Unlock() - return ch - } - c := &call{chans: []chan<- Result{ch}} - c.wg.Add(1) - g.m[key] = c - g.mu.Unlock() - - go g.doCall(c, key, fn) - - return ch -} - -// doCall handles the single call for a key. -func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) { - normalReturn := false - recovered := false - - // use double-defer to distinguish panic from runtime.Goexit, - // more details see https://golang.org/cl/134395 - defer func() { - // the given function invoked runtime.Goexit - if !normalReturn && !recovered { - c.err = errGoexit - } - - c.wg.Done() - g.mu.Lock() - defer g.mu.Unlock() - if !c.forgotten { - delete(g.m, key) - } - - if e, ok := c.err.(*panicError); ok { - // In order to prevent the waiting channels from being blocked forever, - // needs to ensure that this panic cannot be recovered. - if len(c.chans) > 0 { - go panic(e) - select {} // Keep this goroutine around so that it will appear in the crash dump. - } else { - panic(e) - } - } else if c.err == errGoexit { - // Already in the process of goexit, no need to call again - } else { - // Normal return - for _, ch := range c.chans { - ch <- Result{c.val, c.err, c.dups > 0} - } - } - }() - - func() { - defer func() { - if !normalReturn { - // Ideally, we would wait to take a stack trace until we've determined - // whether this is a panic or a runtime.Goexit. - // - // Unfortunately, the only way we can distinguish the two is to see - // whether the recover stopped the goroutine from terminating, and by - // the time we know that, the part of the stack trace relevant to the - // panic has been discarded. - if r := recover(); r != nil { - c.err = newPanicError(r) - } - } - }() - - c.val, c.err = fn() - normalReturn = true - }() - - if !normalReturn { - recovered = true - } -} - -// Forget tells the singleflight to forget about a key. Future calls -// to Do for this key will call the function rather than waiting for -// an earlier call to complete. -func (g *Group) Forget(key string) { - g.mu.Lock() - if c, ok := g.m[key]; ok { - c.forgotten = true - } - delete(g.m, key) - g.mu.Unlock() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/internal/timeconv/duration.go b/vendor/github.com/aws/aws-sdk-go-v2/internal/timeconv/duration.go deleted file mode 100644 index 5d69db5f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/internal/timeconv/duration.go +++ /dev/null @@ -1,13 +0,0 @@ -package timeconv - -import "time" - -// FloatSecondsDur converts a fractional seconds to duration. -func FloatSecondsDur(v float64) time.Duration { - return time.Duration(v * float64(time.Second)) -} - -// DurSecondsFloat converts a duration into fractional seconds. -func DurSecondsFloat(d time.Duration) float64 { - return float64(d) / float64(time.Second) -} 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 deleted file mode 100644 index c3525fd2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/CHANGELOG.md +++ /dev/null @@ -1,124 +0,0 @@ -# v1.10.4 (2023-12-07) - -* No change notes available for this release. - -# v1.10.3 (2023-11-30) - -* No change notes available for this release. - -# v1.10.2 (2023-11-29) - -* No change notes available for this release. - -# v1.10.1 (2023-11-15) - -* No change notes available for this release. - -# v1.10.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/). - -# v1.9.15 (2023-10-06) - -* No change notes available for this release. - -# v1.9.14 (2023-08-18) - -* No change notes available for this release. - -# v1.9.13 (2023-08-07) - -* No change notes available for this release. - -# v1.9.12 (2023-07-31) - -* No change notes available for this release. - -# v1.9.11 (2022-12-02) - -* No change notes available for this release. - -# v1.9.10 (2022-10-24) - -* No change notes available for this release. - -# v1.9.9 (2022-09-14) - -* No change notes available for this release. - -# v1.9.8 (2022-09-02) - -* No change notes available for this release. - -# v1.9.7 (2022-08-31) - -* No change notes available for this release. - -# v1.9.6 (2022-08-29) - -* No change notes available for this release. - -# v1.9.5 (2022-08-11) - -* No change notes available for this release. - -# v1.9.4 (2022-08-09) - -* No change notes available for this release. - -# v1.9.3 (2022-06-29) - -* No change notes available for this release. - -# v1.9.2 (2022-06-07) - -* No change notes available for this release. - -# v1.9.1 (2022-03-24) - -* No change notes available for this release. - -# v1.9.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version - -# v1.8.0 (2022-02-24) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version - -# v1.7.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version - -# v1.6.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version - -# v1.5.0 (2021-11-06) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version - -# v1.4.0 (2021-10-21) - -* **Feature**: Updated to latest version - -# v1.3.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version - -# v1.2.2 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. - -# v1.2.1 (2021-07-15) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version - -# v1.2.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version - -# v1.1.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/service/internal/accept-encoding/accept_encoding_gzip.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/accept_encoding_gzip.go deleted file mode 100644 index 3f451fc9..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/accept_encoding_gzip.go +++ /dev/null @@ -1,176 +0,0 @@ -package acceptencoding - -import ( - "compress/gzip" - "context" - "fmt" - "io" - - "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -const acceptEncodingHeaderKey = "Accept-Encoding" -const contentEncodingHeaderKey = "Content-Encoding" - -// AddAcceptEncodingGzipOptions provides the options for the -// AddAcceptEncodingGzip middleware setup. -type AddAcceptEncodingGzipOptions struct { - Enable bool -} - -// AddAcceptEncodingGzip explicitly adds handling for accept-encoding GZIP -// middleware to the operation stack. This allows checksums to be correctly -// computed without disabling GZIP support. -func AddAcceptEncodingGzip(stack *middleware.Stack, options AddAcceptEncodingGzipOptions) error { - if options.Enable { - if err := stack.Finalize.Add(&EnableGzip{}, middleware.Before); err != nil { - return err - } - if err := stack.Deserialize.Insert(&DecompressGzip{}, "OperationDeserializer", middleware.After); err != nil { - return err - } - return nil - } - - return stack.Finalize.Add(&DisableGzip{}, middleware.Before) -} - -// DisableGzip provides the middleware that will -// disable the underlying http client automatically enabling for gzip -// decompress content-encoding support. -type DisableGzip struct{} - -// ID returns the id for the middleware. -func (*DisableGzip) ID() string { - return "DisableAcceptEncodingGzip" -} - -// HandleFinalize implements the FinalizeMiddleware interface. -func (*DisableGzip) HandleFinalize( - ctx context.Context, input middleware.FinalizeInput, next middleware.FinalizeHandler, -) ( - output middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - req, ok := input.Request.(*smithyhttp.Request) - if !ok { - return output, metadata, &smithy.SerializationError{ - Err: fmt.Errorf("unknown request type %T", input.Request), - } - } - - // Explicitly enable gzip support, this will prevent the http client from - // auto extracting the zipped content. - req.Header.Set(acceptEncodingHeaderKey, "identity") - - return next.HandleFinalize(ctx, input) -} - -// EnableGzip provides a middleware to enable support for -// gzip responses, with manual decompression. This prevents the underlying HTTP -// client from performing the gzip decompression automatically. -type EnableGzip struct{} - -// ID returns the id for the middleware. -func (*EnableGzip) ID() string { - return "AcceptEncodingGzip" -} - -// HandleFinalize implements the FinalizeMiddleware interface. -func (*EnableGzip) HandleFinalize( - ctx context.Context, input middleware.FinalizeInput, next middleware.FinalizeHandler, -) ( - output middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - req, ok := input.Request.(*smithyhttp.Request) - if !ok { - return output, metadata, &smithy.SerializationError{ - Err: fmt.Errorf("unknown request type %T", input.Request), - } - } - - // Explicitly enable gzip support, this will prevent the http client from - // auto extracting the zipped content. - req.Header.Set(acceptEncodingHeaderKey, "gzip") - - return next.HandleFinalize(ctx, input) -} - -// DecompressGzip provides the middleware for decompressing a gzip -// response from the service. -type DecompressGzip struct{} - -// ID returns the id for the middleware. -func (*DecompressGzip) ID() string { - return "DecompressGzip" -} - -// HandleDeserialize implements the DeserializeMiddlware interface. -func (*DecompressGzip) HandleDeserialize( - ctx context.Context, input middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - output middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - output, metadata, err = next.HandleDeserialize(ctx, input) - if err != nil { - return output, metadata, err - } - - resp, ok := output.RawResponse.(*smithyhttp.Response) - if !ok { - return output, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("unknown response type %T", output.RawResponse), - } - } - if v := resp.Header.Get(contentEncodingHeaderKey); v != "gzip" { - return output, metadata, err - } - - // Clear content length since it will no longer be valid once the response - // body is decompressed. - resp.Header.Del("Content-Length") - resp.ContentLength = -1 - - resp.Body = wrapGzipReader(resp.Body) - - return output, metadata, err -} - -type gzipReader struct { - reader io.ReadCloser - gzip *gzip.Reader -} - -func wrapGzipReader(reader io.ReadCloser) *gzipReader { - return &gzipReader{ - reader: reader, - } -} - -// Read wraps the gzip reader around the underlying io.Reader to extract the -// response bytes on the fly. -func (g *gzipReader) Read(b []byte) (n int, err error) { - if g.gzip == nil { - g.gzip, err = gzip.NewReader(g.reader) - if err != nil { - g.gzip = nil // ensure uninitialized gzip value isn't used in close. - return 0, fmt.Errorf("failed to decompress gzip response, %w", err) - } - } - - return g.gzip.Read(b) -} - -func (g *gzipReader) Close() error { - if g.gzip == nil { - return nil - } - - if err := g.gzip.Close(); err != nil { - g.reader.Close() - return fmt.Errorf("failed to decompress gzip response, %w", err) - } - - return g.reader.Close() -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/doc.go deleted file mode 100644 index 7056d9bf..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/doc.go +++ /dev/null @@ -1,22 +0,0 @@ -/* -Package acceptencoding provides customizations associated with Accept Encoding Header. - -# Accept encoding gzip - -The Go HTTP client automatically supports accept-encoding and content-encoding -gzip by default. This default behavior is not desired by the SDK, and prevents -validating the response body's checksum. To prevent this the SDK must manually -control usage of content-encoding gzip. - -To control content-encoding, the SDK must always set the `Accept-Encoding` -header to a value. This prevents the HTTP client from using gzip automatically. -When gzip is enabled on the API client, the SDK's customization will control -decompressing the gzip data in order to not break the checksum validation. When -gzip is disabled, the API client will disable gzip, preventing the HTTP -client's default behavior. - -An `EnableAcceptEncodingGzip` option may or may not be present depending on the client using -the below middleware. The option if present can be used to enable auto decompressing -gzip by the SDK. -*/ -package acceptencoding 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 deleted file mode 100644 index cc638400..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package acceptencoding - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.10.4" 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 deleted file mode 100644 index a65890b5..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/CHANGELOG.md +++ /dev/null @@ -1,272 +0,0 @@ -# v1.10.10 (2024-01-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.9 (2023-12-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.8 (2023-12-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.7 (2023-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.6 (2023-11-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.5 (2023-11-28.2) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.4 (2023-11-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.3 (2023-11-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.2 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.1 (2023-11-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.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.9.37 (2023-10-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.36 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.35 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.34 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.33 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.32 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.31 (2023-07-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.30 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.29 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.28 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.27 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.26 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.25 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.24 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.23 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.22 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.21 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.20 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.19 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.18 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.17 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.16 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.15 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.14 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.13 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.12 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.11 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.10 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.9 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.8 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.7 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.6 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.5 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2022-02-24) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.2 (2021-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-11-06) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.2 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.1 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.3 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.2 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.1 (2021-07-15) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.1.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/service/internal/presigned-url/context.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/context.go deleted file mode 100644 index cc919701..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/context.go +++ /dev/null @@ -1,48 +0,0 @@ -package presignedurl - -import ( - "context" - - "github.com/aws/smithy-go/middleware" -) - -// WithIsPresigning adds the isPresigning sentinel value to a context to signal -// that the middleware stack is using the presign flow. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func WithIsPresigning(ctx context.Context) context.Context { - return middleware.WithStackValue(ctx, isPresigningKey{}, true) -} - -// GetIsPresigning returns if the context contains the isPresigning sentinel -// value for presigning flows. -// -// Scoped to stack values. Use github.com/aws/smithy-go/middleware#ClearStackValues -// to clear all stack values. -func GetIsPresigning(ctx context.Context) bool { - v, _ := middleware.GetStackValue(ctx, isPresigningKey{}).(bool) - return v -} - -type isPresigningKey struct{} - -// AddAsIsPresigingMiddleware adds a middleware to the head of the stack that -// will update the stack's context to be flagged as being invoked for the -// purpose of presigning. -func AddAsIsPresigingMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(asIsPresigningMiddleware{}, middleware.Before) -} - -type asIsPresigningMiddleware struct{} - -func (asIsPresigningMiddleware) ID() string { return "AsIsPresigningMiddleware" } - -func (asIsPresigningMiddleware) HandleInitialize( - ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler, -) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - ctx = WithIsPresigning(ctx) - return next.HandleInitialize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/doc.go deleted file mode 100644 index 1b85375c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package presignedurl provides the customizations for API clients to fill in -// presigned URLs into input parameters. -package presignedurl 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 deleted file mode 100644 index 073e8866..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package presignedurl - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.10.10" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/middleware.go b/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/middleware.go deleted file mode 100644 index 1e2f5c81..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/internal/presigned-url/middleware.go +++ /dev/null @@ -1,110 +0,0 @@ -package presignedurl - -import ( - "context" - "fmt" - - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - - "github.com/aws/smithy-go/middleware" -) - -// URLPresigner provides the interface to presign the input parameters in to a -// presigned URL. -type URLPresigner interface { - // PresignURL presigns a URL. - PresignURL(ctx context.Context, srcRegion string, params interface{}) (*v4.PresignedHTTPRequest, error) -} - -// ParameterAccessor provides an collection of accessor to for retrieving and -// setting the values needed to PresignedURL generation -type ParameterAccessor struct { - // GetPresignedURL accessor points to a function that retrieves a presigned url if present - GetPresignedURL func(interface{}) (string, bool, error) - - // GetSourceRegion accessor points to a function that retrieves source region for presigned url - GetSourceRegion func(interface{}) (string, bool, error) - - // CopyInput accessor points to a function that takes in an input, and returns a copy. - CopyInput func(interface{}) (interface{}, error) - - // SetDestinationRegion accessor points to a function that sets destination region on api input struct - SetDestinationRegion func(interface{}, string) error - - // SetPresignedURL accessor points to a function that sets presigned url on api input struct - SetPresignedURL func(interface{}, string) error -} - -// Options provides the set of options needed by the presigned URL middleware. -type Options struct { - // Accessor are the parameter accessors used by this middleware - Accessor ParameterAccessor - - // Presigner is the URLPresigner used by the middleware - Presigner URLPresigner -} - -// AddMiddleware adds the Presign URL middleware to the middleware stack. -func AddMiddleware(stack *middleware.Stack, opts Options) error { - return stack.Initialize.Add(&presign{options: opts}, middleware.Before) -} - -// RemoveMiddleware removes the Presign URL middleware from the stack. -func RemoveMiddleware(stack *middleware.Stack) error { - _, err := stack.Initialize.Remove((*presign)(nil).ID()) - return err -} - -type presign struct { - options Options -} - -func (m *presign) ID() string { return "Presign" } - -func (m *presign) HandleInitialize( - ctx context.Context, input middleware.InitializeInput, next middleware.InitializeHandler, -) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - // If PresignedURL is already set ignore middleware. - if _, ok, err := m.options.Accessor.GetPresignedURL(input.Parameters); err != nil { - return out, metadata, fmt.Errorf("presign middleware failed, %w", err) - } else if ok { - return next.HandleInitialize(ctx, input) - } - - // If have source region is not set ignore middleware. - srcRegion, ok, err := m.options.Accessor.GetSourceRegion(input.Parameters) - if err != nil { - return out, metadata, fmt.Errorf("presign middleware failed, %w", err) - } else if !ok || len(srcRegion) == 0 { - return next.HandleInitialize(ctx, input) - } - - // Create a copy of the original input so the destination region value can - // be added. This ensures that value does not leak into the original - // request parameters. - paramCpy, err := m.options.Accessor.CopyInput(input.Parameters) - if err != nil { - return out, metadata, fmt.Errorf("unable to create presigned URL, %w", err) - } - - // Destination region is the API client's configured region. - dstRegion := awsmiddleware.GetRegion(ctx) - if err = m.options.Accessor.SetDestinationRegion(paramCpy, dstRegion); err != nil { - return out, metadata, fmt.Errorf("presign middleware failed, %w", err) - } - - presignedReq, err := m.options.Presigner.PresignURL(ctx, srcRegion, paramCpy) - if err != nil { - return out, metadata, fmt.Errorf("unable to create presigned URL, %w", err) - } - - // Update the original input with the presigned URL value. - if err = m.options.Accessor.SetPresignedURL(input.Parameters, presignedReq.URL); err != nil { - return out, metadata, fmt.Errorf("presign middleware failed, %w", err) - } - - return next.HandleInitialize(ctx, input) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/CHANGELOG.md deleted file mode 100644 index 8c65e338..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/CHANGELOG.md +++ /dev/null @@ -1,441 +0,0 @@ -# v1.26.2 (2024-01-11) - -* **Documentation**: Doc only update for Secrets Manager - -# v1.26.1 (2024-01-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.26.0 (2023-12-22) - -* **Feature**: Update endpoint rules and examples. - -# v1.25.6 (2023-12-20) - -* No change notes available for this release. - -# v1.25.5 (2023-12-08) - -* **Bug Fix**: Reinstate presence of default Retryer in functional options, but still respect max attempts set therein. - -# v1.25.4 (2023-12-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.3 (2023-12-06) - -* **Bug Fix**: Restore pre-refactor auth behavior where all operations could technically be performed anonymously. - -# v1.25.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.25.1 (2023-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.0 (2023-11-29) - -* **Feature**: Expose Options() accessor on service clients. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.24.2 (2023-11-28.2) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.24.1 (2023-11-28) - -* **Bug Fix**: Respect setting RetryMaxAttempts in functional options at client construction. - -# v1.24.0 (2023-11-27) - -* **Feature**: AWS Secrets Manager has released the BatchGetSecretValue API, which allows customers to fetch up to 20 Secrets with a single request using a list of secret names or filters. - -# v1.23.3 (2023-11-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.23.2 (2023-11-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.23.1 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.23.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.22.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.21.6 (2023-10-19) - -* **Documentation**: Documentation updates for Secrets Manager - -# v1.21.5 (2023-10-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.4 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.3 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.2 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.1 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.0 (2023-08-10) - -* **Feature**: Add additional InvalidRequestException to list of possible exceptions for ListSecret. - -# v1.20.2 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.20.1 (2023-08-01) - -* No change notes available for this release. - -# v1.20.0 (2023-07-31) - -* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.12 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.11 (2023-07-13) - -* **Documentation**: Documentation updates for Secrets Manager -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.10 (2023-06-15) - -* No change notes available for this release. - -# v1.19.9 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.8 (2023-05-16) - -* **Documentation**: Documentation updates for Secrets Manager - -# v1.19.7 (2023-05-04) - -* No change notes available for this release. - -# v1.19.6 (2023-04-27) - -* No change notes available for this release. - -# v1.19.5 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.4 (2023-04-19) - -* **Documentation**: Documentation updates for Secrets Manager - -# v1.19.3 (2023-04-10) - -* No change notes available for this release. - -# v1.19.2 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.1 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.0 (2023-03-10) - -* **Feature**: The type definitions of SecretString and SecretBinary now have a minimum length of 1 in the model to match the exception thrown when you pass in empty values. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.7 (2023-03-02) - -* No change notes available for this release. - -# v1.18.6 (2023-02-22) - -* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes. - -# v1.18.5 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.4 (2023-02-15) - -* **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. -* **Bug Fix**: Correct error type parsing for restJson services. - -# v1.18.3 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.2 (2023-01-23) - -* No change notes available for this release. - -# v1.18.1 (2023-01-12) - -* **Documentation**: Update documentation for new ListSecrets and DescribeSecret parameters - -# v1.18.0 (2023-01-05) - -* **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - -# v1.17.0 (2022-12-29) - -* **Feature**: Added owning service filter, include planned deletion flag, and next rotation date response parameter in ListSecrets. - -# v1.16.11 (2022-12-22) - -* **Documentation**: Documentation updates for Secrets Manager - -# v1.16.10 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.9 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.8 (2022-11-22) - -* No change notes available for this release. - -# v1.16.7 (2022-11-17) - -* **Documentation**: Documentation updates for Secrets Manager. - -# v1.16.6 (2022-11-16) - -* No change notes available for this release. - -# v1.16.5 (2022-11-10) - -* No change notes available for this release. - -# v1.16.4 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.3 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.2 (2022-09-29) - -* **Documentation**: Documentation updates for Secrets Manager - -# v1.16.1 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.0 (2022-09-14) - -* **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.22 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.21 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.20 (2022-08-30) - -* No change notes available for this release. - -# v1.15.19 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.18 (2022-08-17) - -* **Documentation**: Documentation updates for Secrets Manager. - -# v1.15.17 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.16 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.15 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.14 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.13 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.12 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.11 (2022-06-16) - -* **Documentation**: Documentation updates for Secrets Manager - -# v1.15.10 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.9 (2022-05-25) - -* **Documentation**: Documentation updates for Secrets Manager - -# v1.15.8 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.7 (2022-05-11) - -* **Documentation**: Doc only update for Secrets Manager that fixes several customer-reported issues. - -# v1.15.6 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.5 (2022-04-21) - -* **Documentation**: Documentation updates for Secrets Manager - -# v1.15.4 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.3 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.2 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.1 (2022-03-11) - -* **Documentation**: Documentation updates for Secrets Manager. - -# v1.15.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.0 (2022-02-24) - -* **Feature**: API client updated -* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2022-01-07) - -* **Feature**: API client updated -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2021-12-21) - -* **Feature**: API Paginators now support specifying the initial starting token, and support stopping on empty string tokens. -* **Documentation**: API client updated - -# v1.10.2 (2021-12-02) - -* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514)) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2021-11-12) - -* **Feature**: Service clients now support custom endpoints that have an initial URI path defined. - -# v1.9.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2021-10-11) - -* **Feature**: API client updated -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.1 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.1 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-08-04) - -* **Feature**: Updated to latest API model. -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.1 (2021-07-15) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/service/secretsmanager/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_client.go deleted file mode 100644 index 99c25849..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_client.go +++ /dev/null @@ -1,491 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - cryptorand "crypto/rand" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/defaults" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "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" - smithy "github.com/aws/smithy-go" - smithydocument "github.com/aws/smithy-go/document" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyrand "github.com/aws/smithy-go/rand" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net" - "net/http" - "time" -) - -const ServiceID = "Secrets Manager" -const ServiceAPIVersion = "2017-10-17" - -// Client provides the API client to make operations call for AWS Secrets Manager. -type Client struct { - options Options -} - -// 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() - - resolveDefaultLogger(&options) - - setResolvedDefaultsMode(&options) - - resolveRetryer(&options) - - resolveHTTPClient(&options) - - resolveHTTPSignerV4(&options) - - resolveIdempotencyTokenProvider(&options) - - resolveEndpointResolverV2(&options) - - resolveAuthSchemeResolver(&options) - - for _, fn := range optFns { - fn(&options) - } - - finalizeRetryMaxAttempts(&options) - - ignoreAnonymousAuth(&options) - - wrapWithAnonymousAuth(&options) - - resolveAuthSchemes(&options) - - client := &Client{ - options: options, - } - - return client -} - -// 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) { - ctx = middleware.ClearStackValues(ctx) - stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) - options := c.options.Copy() - - for _, fn := range optFns { - fn(&options) - } - - finalizeOperationRetryMaxAttempts(&options, *c) - - finalizeClientEndpointResolverOptions(&options) - - for _, fn := range stackFns { - if err := fn(stack, options); err != nil { - return nil, metadata, err - } - } - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, metadata, err - } - } - - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) - if err != nil { - err = &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: err, - } - } - 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{}, "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 { - LegacyResolver EndpointResolver -} - -func (*legacyEndpointContextSetter) ID() string { - return "legacyEndpointContextSetter" -} - -func (m *legacyEndpointContextSetter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.LegacyResolver != nil { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true) - } - - return next.HandleInitialize(ctx, in) - -} -func addlegacyEndpointContextSetter(stack *middleware.Stack, o Options) error { - return stack.Initialize.Add(&legacyEndpointContextSetter{ - LegacyResolver: o.EndpointResolver, - }, middleware.Before) -} - -func resolveDefaultLogger(o *Options) { - if o.Logger != nil { - return - } - o.Logger = logging.Nop{} -} - -func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { - return middleware.AddSetLoggerMiddleware(stack, o.Logger) -} - -func setResolvedDefaultsMode(o *Options) { - if len(o.resolvedDefaultsMode) > 0 { - return - } - - var mode aws.DefaultsMode - mode.SetFromString(string(o.DefaultsMode)) - - if mode == aws.DefaultsModeAuto { - mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment) - } - - o.resolvedDefaultsMode = mode -} - -// NewFromConfig returns a new client from the provided config. -func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { - opts := Options{ - Region: cfg.Region, - DefaultsMode: cfg.DefaultsMode, - RuntimeEnvironment: cfg.RuntimeEnvironment, - HTTPClient: cfg.HTTPClient, - Credentials: cfg.Credentials, - APIOptions: cfg.APIOptions, - Logger: cfg.Logger, - ClientLogMode: cfg.ClientLogMode, - AppID: cfg.AppID, - } - resolveAWSRetryerProvider(cfg, &opts) - resolveAWSRetryMaxAttempts(cfg, &opts) - resolveAWSRetryMode(cfg, &opts) - resolveAWSEndpointResolver(cfg, &opts) - resolveUseDualStackEndpoint(cfg, &opts) - resolveUseFIPSEndpoint(cfg, &opts) - resolveBaseEndpoint(cfg, &opts) - return New(opts, optFns...) -} - -func resolveHTTPClient(o *Options) { - var buildable *awshttp.BuildableClient - - if o.HTTPClient != nil { - var ok bool - buildable, ok = o.HTTPClient.(*awshttp.BuildableClient) - if !ok { - return - } - } else { - buildable = awshttp.NewBuildableClient() - } - - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) { - if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok { - dialer.Timeout = dialerTimeout - } - }) - - buildable = buildable.WithTransportOptions(func(transport *http.Transport) { - if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok { - transport.TLSHandshakeTimeout = tlsHandshakeTimeout - } - }) - } - - o.HTTPClient = buildable -} - -func resolveRetryer(o *Options) { - if o.Retryer != nil { - return - } - - if len(o.RetryMode) == 0 { - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - o.RetryMode = modeConfig.RetryMode - } - } - if len(o.RetryMode) == 0 { - o.RetryMode = aws.RetryModeStandard - } - - var standardOptions []func(*retry.StandardOptions) - if v := o.RetryMaxAttempts; v != 0 { - standardOptions = append(standardOptions, func(so *retry.StandardOptions) { - so.MaxAttempts = v - }) - } - - switch o.RetryMode { - case aws.RetryModeAdaptive: - var adaptiveOptions []func(*retry.AdaptiveModeOptions) - if len(standardOptions) != 0 { - adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) { - ao.StandardOptions = append(ao.StandardOptions, standardOptions...) - }) - } - o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...) - - default: - o.Retryer = retry.NewStandard(standardOptions...) - } -} - -func resolveAWSRetryerProvider(cfg aws.Config, o *Options) { - if cfg.Retryer == nil { - return - } - o.Retryer = cfg.Retryer() -} - -func resolveAWSRetryMode(cfg aws.Config, o *Options) { - if len(cfg.RetryMode) == 0 { - return - } - o.RetryMode = cfg.RetryMode -} -func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { - if cfg.RetryMaxAttempts == 0 { - return - } - o.RetryMaxAttempts = cfg.RetryMaxAttempts -} - -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 - } - - o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) -} - -func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { - if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil { - return - } - o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions) -} - -func addClientUserAgent(stack *middleware.Stack, options Options) error { - if err := awsmiddleware.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "secretsmanager", goModuleVersion)(stack); err != nil { - return err - } - - if len(options.AppID) > 0 { - return awsmiddleware.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID)(stack) - } - - return nil -} - -type HTTPSignerV4 interface { - SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error -} - -func resolveHTTPSignerV4(o *Options) { - if o.HTTPSignerV4 != nil { - return - } - o.HTTPSignerV4 = newDefaultV4Signer(*o) -} - -func newDefaultV4Signer(o Options) *v4.Signer { - return v4.NewSigner(func(so *v4.SignerOptions) { - so.Logger = o.Logger - so.LogSigning = o.ClientLogMode.IsSigning() - }) -} - -func resolveIdempotencyTokenProvider(o *Options) { - if o.IdempotencyTokenProvider != nil { - return - } - o.IdempotencyTokenProvider = smithyrand.NewUUIDIdempotencyToken(cryptorand.Reader) -} - -func addRetryMiddlewares(stack *middleware.Stack, o Options) error { - mo := retry.AddRetryMiddlewaresOptions{ - Retryer: o.Retryer, - LogRetryAttempts: o.ClientLogMode.IsRetries(), - } - return retry.AddRetryMiddlewares(stack, mo) -} - -// resolves dual-stack endpoint configuration -func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseDualStackEndpoint = value - } - return nil -} - -// resolves FIPS endpoint configuration -func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseFIPSEndpoint = value - } - return nil -} - -// IdempotencyTokenProvider interface for providing idempotency token -type IdempotencyTokenProvider interface { - GetIdempotencyToken() (string, error) -} - -func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - return awsmiddleware.AddRequestIDRetrieverMiddleware(stack) -} - -func addResponseErrorMiddleware(stack *middleware.Stack) error { - return awshttp.AddResponseErrorMiddleware(stack) -} - -func addRequestResponseLogging(stack *middleware.Stack, o Options) error { - return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ - LogRequest: o.ClientLogMode.IsRequest(), - LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(), - LogResponse: o.ClientLogMode.IsResponse(), - LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(), - }, middleware.After) -} - -type disableHTTPSMiddleware struct { - DisableHTTPS bool -} - -func (*disableHTTPSMiddleware) ID() string { - return "disableHTTPS" -} - -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.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) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_BatchGetSecretValue.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_BatchGetSecretValue.go deleted file mode 100644 index 35dcda76..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_BatchGetSecretValue.go +++ /dev/null @@ -1,267 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the contents of the encrypted fields SecretString or SecretBinary for -// up to 20 secrets. To retrieve a single secret, call GetSecretValue . To choose -// which secrets to retrieve, you can specify a list of secrets by name or ARN, or -// you can use filters. If Secrets Manager encounters errors such as -// AccessDeniedException while attempting to retrieve any of the secrets, you can -// see the errors in Errors in the response. Secrets Manager generates CloudTrail -// GetSecretValue log entries for each secret you request when you call this -// action. Do not include sensitive information in request parameters because it -// might be logged. For more information, see Logging Secrets Manager events with -// CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:BatchGetSecretValue , and you must have -// secretsmanager:GetSecretValue for each secret. If you use filters, you must also -// have secretsmanager:ListSecrets . If the secrets are encrypted using -// customer-managed keys instead of the Amazon Web Services managed key -// aws/secretsmanager , then you also need kms:Decrypt permissions for the keys. -// For more information, see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) BatchGetSecretValue(ctx context.Context, params *BatchGetSecretValueInput, optFns ...func(*Options)) (*BatchGetSecretValueOutput, error) { - if params == nil { - params = &BatchGetSecretValueInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "BatchGetSecretValue", params, optFns, c.addOperationBatchGetSecretValueMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*BatchGetSecretValueOutput) - out.ResultMetadata = metadata - return out, nil -} - -type BatchGetSecretValueInput struct { - - // The filters to choose which secrets to retrieve. You must include Filters or - // SecretIdList , but not both. - Filters []types.Filter - - // The number of results to include in the response. If there are more results - // available, in the response, Secrets Manager includes NextToken . To get the next - // results, call BatchGetSecretValue again with the value from NextToken . - MaxResults *int32 - - // A token that indicates where the output should continue from, if a previous - // call did not show all results. To get the next results, call BatchGetSecretValue - // again with this value. - NextToken *string - - // The ARN or names of the secrets to retrieve. You must include Filters or - // SecretIdList , but not both. - SecretIdList []string - - noSmithyDocumentSerde -} - -type BatchGetSecretValueOutput struct { - - // A list of errors Secrets Manager encountered while attempting to retrieve - // individual secrets. - Errors []types.APIErrorType - - // Secrets Manager includes this value if there's more output available than what - // is included in the current response. This can occur even when the response - // includes no values at all, such as when you ask for a filtered view of a long - // list. To get the next results, call BatchGetSecretValue again with this value. - NextToken *string - - // A list of secret values. - SecretValues []types.SecretValueEntry - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationBatchGetSecretValueMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpBatchGetSecretValue{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpBatchGetSecretValue{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "BatchGetSecretValue"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opBatchGetSecretValue(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// BatchGetSecretValueAPIClient is a client that implements the -// BatchGetSecretValue operation. -type BatchGetSecretValueAPIClient interface { - BatchGetSecretValue(context.Context, *BatchGetSecretValueInput, ...func(*Options)) (*BatchGetSecretValueOutput, error) -} - -var _ BatchGetSecretValueAPIClient = (*Client)(nil) - -// BatchGetSecretValuePaginatorOptions is the paginator options for -// BatchGetSecretValue -type BatchGetSecretValuePaginatorOptions struct { - // The number of results to include in the response. If there are more results - // available, in the response, Secrets Manager includes NextToken . To get the next - // results, call BatchGetSecretValue again with the value from NextToken . - 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 -} - -// BatchGetSecretValuePaginator is a paginator for BatchGetSecretValue -type BatchGetSecretValuePaginator struct { - options BatchGetSecretValuePaginatorOptions - client BatchGetSecretValueAPIClient - params *BatchGetSecretValueInput - nextToken *string - firstPage bool -} - -// NewBatchGetSecretValuePaginator returns a new BatchGetSecretValuePaginator -func NewBatchGetSecretValuePaginator(client BatchGetSecretValueAPIClient, params *BatchGetSecretValueInput, optFns ...func(*BatchGetSecretValuePaginatorOptions)) *BatchGetSecretValuePaginator { - if params == nil { - params = &BatchGetSecretValueInput{} - } - - options := BatchGetSecretValuePaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &BatchGetSecretValuePaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *BatchGetSecretValuePaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next BatchGetSecretValue page. -func (p *BatchGetSecretValuePaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*BatchGetSecretValueOutput, 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 - - result, err := p.client.BatchGetSecretValue(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 -} - -func newServiceMetadataMiddleware_opBatchGetSecretValue(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "BatchGetSecretValue", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_CancelRotateSecret.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_CancelRotateSecret.go deleted file mode 100644 index 1baab024..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_CancelRotateSecret.go +++ /dev/null @@ -1,164 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Turns off automatic rotation, and if a rotation is currently in progress, -// cancels the rotation. If you cancel a rotation in progress, it can leave the -// VersionStage labels in an unexpected state. You might need to remove the staging -// label AWSPENDING from the partially created version. You also need to determine -// whether to roll back to the previous version of the secret by moving the staging -// label AWSCURRENT to the version that has AWSPENDING . To determine which version -// has a specific staging label, call ListSecretVersionIds . Then use -// UpdateSecretVersionStage to change staging labels. For more information, see -// How rotation works (https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotate-secrets_how.html) -// . To turn on automatic rotation again, call RotateSecret . Secrets Manager -// generates a CloudTrail log entry when you call this action. Do not include -// sensitive information in request parameters because it might be logged. For more -// information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:CancelRotateSecret . For more -// information, see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) CancelRotateSecret(ctx context.Context, params *CancelRotateSecretInput, optFns ...func(*Options)) (*CancelRotateSecretOutput, error) { - if params == nil { - params = &CancelRotateSecretInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CancelRotateSecret", params, optFns, c.addOperationCancelRotateSecretMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CancelRotateSecretOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CancelRotateSecretInput struct { - - // The ARN or name of the secret. For an ARN, we recommend that you specify a - // complete ARN rather than a partial ARN. See Finding a secret from a partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - noSmithyDocumentSerde -} - -type CancelRotateSecretOutput struct { - - // The ARN of the secret. - ARN *string - - // The name of the secret. - Name *string - - // The unique identifier of the version of the secret created during the rotation. - // This version might not be complete, and should be evaluated for possible - // deletion. We recommend that you remove the VersionStage value AWSPENDING from - // this version so that Secrets Manager can delete it. Failing to clean up a - // cancelled rotation can block you from starting future rotations. - VersionId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCancelRotateSecretMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCancelRotateSecret{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCancelRotateSecret{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CancelRotateSecret"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCancelRotateSecretValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCancelRotateSecret(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCancelRotateSecret(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CancelRotateSecret", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_CreateSecret.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_CreateSecret.go deleted file mode 100644 index a783c39d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_CreateSecret.go +++ /dev/null @@ -1,310 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Creates a new secret. A secret can be a password, a set of credentials such as -// a user name and password, an OAuth token, or other secret information that you -// store in an encrypted form in Secrets Manager. The secret also includes the -// connection information to access a database or other service, which Secrets -// Manager doesn't encrypt. A secret in Secrets Manager consists of both the -// protected secret data and the important information needed to manage the secret. -// For secrets that use managed rotation, you need to create the secret through the -// managing service. For more information, see Secrets Manager secrets managed by -// other Amazon Web Services services (https://docs.aws.amazon.com/secretsmanager/latest/userguide/service-linked-secrets.html) -// . For information about creating a secret in the console, see Create a secret (https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html) -// . To create a secret, you can provide the secret value to be encrypted in either -// the SecretString parameter or the SecretBinary parameter, but not both. If you -// include SecretString or SecretBinary then Secrets Manager creates an initial -// secret version and automatically attaches the staging label AWSCURRENT to it. -// For database credentials you want to rotate, for Secrets Manager to be able to -// rotate the secret, you must make sure the JSON you store in the SecretString -// matches the JSON structure of a database secret (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_secret_json_structure.html) -// . If you don't specify an KMS encryption key, Secrets Manager uses the Amazon -// Web Services managed key aws/secretsmanager . If this key doesn't already exist -// in your account, then Secrets Manager creates it for you automatically. All -// users and roles in the Amazon Web Services account automatically have access to -// use aws/secretsmanager . Creating aws/secretsmanager can result in a one-time -// significant delay in returning the result. If the secret is in a different -// Amazon Web Services account from the credentials calling the API, then you can't -// use aws/secretsmanager to encrypt the secret, and you must create and use a -// customer managed KMS key. Secrets Manager generates a CloudTrail log entry when -// you call this action. Do not include sensitive information in request parameters -// except SecretBinary or SecretString because it might be logged. For more -// information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:CreateSecret . If you include tags in the -// secret, you also need secretsmanager:TagResource . For more information, see -// IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . To encrypt the secret with a KMS key other than aws/secretsmanager , you need -// kms:GenerateDataKey and kms:Decrypt permission to the key. -func (c *Client) CreateSecret(ctx context.Context, params *CreateSecretInput, optFns ...func(*Options)) (*CreateSecretOutput, error) { - if params == nil { - params = &CreateSecretInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateSecret", params, optFns, c.addOperationCreateSecretMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateSecretOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateSecretInput struct { - - // The name of the new secret. The secret name can contain ASCII letters, numbers, - // and the following characters: /_+=.@- Do not end your secret name with a hyphen - // followed by six characters. If you do so, you risk confusion and unexpected - // results when searching for a secret by partial ARN. Secrets Manager - // automatically adds a hyphen and six random characters after the secret name at - // the end of the ARN. - // - // This member is required. - Name *string - - // A list of Regions and KMS keys to replicate secrets. - AddReplicaRegions []types.ReplicaRegionType - - // If you include SecretString or SecretBinary , then Secrets Manager creates an - // initial version for the secret, and this parameter specifies the unique - // identifier for the new version. If you use the Amazon Web Services CLI or one of - // the Amazon Web Services SDKs to call this operation, then you can leave this - // parameter empty. The CLI or SDK generates a random UUID for you and includes it - // as the value for this parameter in the request. If you generate a raw HTTP - // request to the Secrets Manager service endpoint, then you must generate a - // ClientRequestToken and include it in the request. This value helps ensure - // idempotency. Secrets Manager uses this value to prevent the accidental creation - // of duplicate versions if there are failures and retries during a rotation. We - // recommend that you generate a UUID-type (https://wikipedia.org/wiki/Universally_unique_identifier) - // value to ensure uniqueness of your versions within the specified secret. - // - If the ClientRequestToken value isn't already associated with a version of - // the secret then a new version of the secret is created. - // - If a version with this value already exists and the version SecretString and - // SecretBinary values are the same as those in the request, then the request is - // ignored. - // - If a version with this value already exists and that version's SecretString - // and SecretBinary values are different from those in the request, then the - // request fails because you cannot modify an existing version. Instead, use - // PutSecretValue to create a new version. - // This value becomes the VersionId of the new version. - ClientRequestToken *string - - // The description of the secret. - Description *string - - // Specifies whether to overwrite a secret with the same name in the destination - // Region. By default, secrets aren't overwritten. - ForceOverwriteReplicaSecret bool - - // The ARN, key ID, or alias of the KMS key that Secrets Manager uses to encrypt - // the secret value in the secret. An alias is always prefixed by alias/ , for - // example alias/aws/secretsmanager . For more information, see About aliases (https://docs.aws.amazon.com/kms/latest/developerguide/alias-about.html) - // . To use a KMS key in a different account, use the key ARN or the alias ARN. If - // you don't specify this value, then Secrets Manager uses the key - // aws/secretsmanager . If that key doesn't yet exist, then Secrets Manager creates - // it for you automatically the first time it encrypts the secret value. If the - // secret is in a different Amazon Web Services account from the credentials - // calling the API, then you can't use aws/secretsmanager to encrypt the secret, - // and you must create and use a customer managed KMS key. - KmsKeyId *string - - // The binary data to encrypt and store in the new version of the secret. We - // recommend that you store your binary data in a file and then pass the contents - // of the file as a parameter. Either SecretString or SecretBinary must have a - // value, but not both. This parameter is not available in the Secrets Manager - // console. - SecretBinary []byte - - // The text data to encrypt and store in this new version of the secret. We - // recommend you use a JSON structure of key/value pairs for your secret value. - // Either SecretString or SecretBinary must have a value, but not both. If you - // create a secret by using the Secrets Manager console then Secrets Manager puts - // the protected secret text in only the SecretString parameter. The Secrets - // Manager console stores the information as a JSON structure of key/value pairs - // that a Lambda rotation function can parse. - SecretString *string - - // A list of tags to attach to the secret. Each tag is a key and value pair of - // strings in a JSON text string, for example: - // [{"Key":"CostCenter","Value":"12345"},{"Key":"environment","Value":"production"}] - // Secrets Manager tag key names are case sensitive. A tag with the key "ABC" is a - // different tag from one with key "abc". If you check tags in permissions policies - // as part of your security strategy, then adding or removing a tag can change - // permissions. If the completion of this operation would result in you losing your - // permissions for this secret, then Secrets Manager blocks the operation and - // returns an Access Denied error. For more information, see Control access to - // secrets using tags (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_examples.html#tag-secrets-abac) - // and Limit access to identities with tags that match secrets' tags (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_examples.html#auth-and-access_tags2) - // . For information about how to format a JSON parameter for the various command - // line tool environments, see Using JSON for Parameters (https://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#cli-using-param-json) - // . If your command-line tool or SDK requires quotation marks around the - // parameter, you should use single quotes to avoid confusion with the double - // quotes required in the JSON text. For tag quotas and naming restrictions, see - // Service quotas for Tagging (https://docs.aws.amazon.com/general/latest/gr/arg.html#taged-reference-quotas) - // in the Amazon Web Services General Reference guide. - Tags []types.Tag - - noSmithyDocumentSerde -} - -type CreateSecretOutput struct { - - // The ARN of the new secret. The ARN includes the name of the secret followed by - // six random characters. This ensures that if you create a new secret with the - // same name as a deleted secret, then users with access to the old secret don't - // get access to the new secret because the ARNs are different. - ARN *string - - // The name of the new secret. - Name *string - - // A list of the replicas of this secret and their status: - // - Failed , which indicates that the replica was not created. - // - InProgress , which indicates that Secrets Manager is in the process of - // creating the replica. - // - InSync , which indicates that the replica was created. - ReplicationStatus []types.ReplicationStatusType - - // The unique identifier associated with the version of the new secret. - VersionId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateSecretMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateSecret{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateSecret{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreateSecret"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addIdempotencyToken_opCreateSecretMiddleware(stack, options); err != nil { - return err - } - if err = addOpCreateSecretValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateSecret(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -type idempotencyToken_initializeOpCreateSecret struct { - tokenProvider IdempotencyTokenProvider -} - -func (*idempotencyToken_initializeOpCreateSecret) ID() string { - return "OperationIdempotencyTokenAutoFill" -} - -func (m *idempotencyToken_initializeOpCreateSecret) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.tokenProvider == nil { - return next.HandleInitialize(ctx, in) - } - - input, ok := in.Parameters.(*CreateSecretInput) - if !ok { - return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateSecretInput ") - } - - if input.ClientRequestToken == nil { - t, err := m.tokenProvider.GetIdempotencyToken() - if err != nil { - return out, metadata, err - } - input.ClientRequestToken = &t - } - return next.HandleInitialize(ctx, in) -} -func addIdempotencyToken_opCreateSecretMiddleware(stack *middleware.Stack, cfg Options) error { - return stack.Initialize.Add(&idempotencyToken_initializeOpCreateSecret{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) -} - -func newServiceMetadataMiddleware_opCreateSecret(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateSecret", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_DeleteResourcePolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_DeleteResourcePolicy.go deleted file mode 100644 index 451ebd04..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_DeleteResourcePolicy.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Deletes the resource-based permission policy attached to the secret. To attach -// a policy to a secret, use PutResourcePolicy . Secrets Manager generates a -// CloudTrail log entry when you call this action. Do not include sensitive -// information in request parameters because it might be logged. For more -// information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:DeleteResourcePolicy . For more -// information, see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) DeleteResourcePolicy(ctx context.Context, params *DeleteResourcePolicyInput, optFns ...func(*Options)) (*DeleteResourcePolicyOutput, error) { - if params == nil { - params = &DeleteResourcePolicyInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteResourcePolicy", params, optFns, c.addOperationDeleteResourcePolicyMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteResourcePolicyOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteResourcePolicyInput struct { - - // The ARN or name of the secret to delete the attached resource-based policy for. - // For an ARN, we recommend that you specify a complete ARN rather than a partial - // ARN. See Finding a secret from a partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - noSmithyDocumentSerde -} - -type DeleteResourcePolicyOutput struct { - - // The ARN of the secret that the resource-based policy was deleted for. - ARN *string - - // The name of the secret that the resource-based policy was deleted for. - Name *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteResourcePolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteResourcePolicy{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteResourcePolicy{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteResourcePolicy"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeleteResourcePolicyValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteResourcePolicy(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteResourcePolicy(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteResourcePolicy", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_DeleteSecret.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_DeleteSecret.go deleted file mode 100644 index 62ec00a2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_DeleteSecret.go +++ /dev/null @@ -1,198 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Deletes a secret and all of its versions. You can specify a recovery window -// during which you can restore the secret. The minimum recovery window is 7 days. -// The default recovery window is 30 days. Secrets Manager attaches a DeletionDate -// stamp to the secret that specifies the end of the recovery window. At the end of -// the recovery window, Secrets Manager deletes the secret permanently. You can't -// delete a primary secret that is replicated to other Regions. You must first -// delete the replicas using RemoveRegionsFromReplication , and then delete the -// primary secret. When you delete a replica, it is deleted immediately. You can't -// directly delete a version of a secret. Instead, you remove all staging labels -// from the version using UpdateSecretVersionStage . This marks the version as -// deprecated, and then Secrets Manager can automatically delete the version in the -// background. To determine whether an application still uses a secret, you can -// create an Amazon CloudWatch alarm to alert you to any attempts to access a -// secret during the recovery window. For more information, see Monitor secrets -// scheduled for deletion (https://docs.aws.amazon.com/secretsmanager/latest/userguide/monitoring_cloudwatch_deleted-secrets.html) -// . Secrets Manager performs the permanent secret deletion at the end of the -// waiting period as a background task with low priority. There is no guarantee of -// a specific time after the recovery window for the permanent delete to occur. At -// any time before recovery window ends, you can use RestoreSecret to remove the -// DeletionDate and cancel the deletion of the secret. When a secret is scheduled -// for deletion, you cannot retrieve the secret value. You must first cancel the -// deletion with RestoreSecret and then you can retrieve the secret. Secrets -// Manager generates a CloudTrail log entry when you call this action. Do not -// include sensitive information in request parameters because it might be logged. -// For more information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:DeleteSecret . For more information, see -// IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) DeleteSecret(ctx context.Context, params *DeleteSecretInput, optFns ...func(*Options)) (*DeleteSecretOutput, error) { - if params == nil { - params = &DeleteSecretInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteSecret", params, optFns, c.addOperationDeleteSecretMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteSecretOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteSecretInput struct { - - // The ARN or name of the secret to delete. For an ARN, we recommend that you - // specify a complete ARN rather than a partial ARN. See Finding a secret from a - // partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - // Specifies whether to delete the secret without any recovery window. You can't - // use both this parameter and RecoveryWindowInDays in the same call. If you don't - // use either, then by default Secrets Manager uses a 30 day recovery window. - // Secrets Manager performs the actual deletion with an asynchronous background - // process, so there might be a short delay before the secret is permanently - // deleted. If you delete a secret and then immediately create a secret with the - // same name, use appropriate back off and retry logic. If you forcibly delete an - // already deleted or nonexistent secret, the operation does not return - // ResourceNotFoundException . Use this parameter with caution. This parameter - // causes the operation to skip the normal recovery window before the permanent - // deletion that Secrets Manager would normally impose with the - // RecoveryWindowInDays parameter. If you delete a secret with the - // ForceDeleteWithoutRecovery parameter, then you have no opportunity to recover - // the secret. You lose the secret permanently. - ForceDeleteWithoutRecovery *bool - - // The number of days from 7 to 30 that Secrets Manager waits before permanently - // deleting the secret. You can't use both this parameter and - // ForceDeleteWithoutRecovery in the same call. If you don't use either, then by - // default Secrets Manager uses a 30 day recovery window. - RecoveryWindowInDays *int64 - - noSmithyDocumentSerde -} - -type DeleteSecretOutput struct { - - // The ARN of the secret. - ARN *string - - // The date and time after which this secret Secrets Manager can permanently - // delete this secret, and it can no longer be restored. This value is the date and - // time of the delete request plus the number of days in RecoveryWindowInDays . - DeletionDate *time.Time - - // The name of the secret. - Name *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteSecretMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteSecret{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteSecret{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteSecret"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeleteSecretValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteSecret(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteSecret(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteSecret", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_DescribeSecret.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_DescribeSecret.go deleted file mode 100644 index 2e714de6..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_DescribeSecret.go +++ /dev/null @@ -1,240 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Retrieves the details of a secret. It does not include the encrypted secret -// value. Secrets Manager only returns fields that have a value in the response. -// Secrets Manager generates a CloudTrail log entry when you call this action. Do -// not include sensitive information in request parameters because it might be -// logged. For more information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:DescribeSecret . For more information, -// see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) DescribeSecret(ctx context.Context, params *DescribeSecretInput, optFns ...func(*Options)) (*DescribeSecretOutput, error) { - if params == nil { - params = &DescribeSecretInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeSecret", params, optFns, c.addOperationDescribeSecretMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeSecretOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeSecretInput struct { - - // The ARN or name of the secret. For an ARN, we recommend that you specify a - // complete ARN rather than a partial ARN. See Finding a secret from a partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - noSmithyDocumentSerde -} - -type DescribeSecretOutput struct { - - // The ARN of the secret. - ARN *string - - // The date the secret was created. - CreatedDate *time.Time - - // The date the secret is scheduled for deletion. If it is not scheduled for - // deletion, this field is omitted. When you delete a secret, Secrets Manager - // requires a recovery window of at least 7 days before deleting the secret. Some - // time after the deleted date, Secrets Manager deletes the secret, including all - // of its versions. If a secret is scheduled for deletion, then its details, - // including the encrypted secret value, is not accessible. To cancel a scheduled - // deletion and restore access to the secret, use RestoreSecret . - DeletedDate *time.Time - - // The description of the secret. - Description *string - - // The key ID or alias ARN of the KMS key that Secrets Manager uses to encrypt the - // secret value. If the secret is encrypted with the Amazon Web Services managed - // key aws/secretsmanager , this field is omitted. Secrets created using the - // console use an KMS key ID. - KmsKeyId *string - - // The date that the secret was last accessed in the Region. This field is omitted - // if the secret has never been retrieved in the Region. - LastAccessedDate *time.Time - - // The last date and time that this secret was modified in any way. - LastChangedDate *time.Time - - // The last date and time that Secrets Manager rotated the secret. If the secret - // isn't configured for rotation or rotation has been disabled, Secrets Manager - // returns null. - LastRotatedDate *time.Time - - // The name of the secret. - Name *string - - // The next rotation is scheduled to occur on or before this date. If the secret - // isn't configured for rotation or rotation has been disabled, Secrets Manager - // returns null. - NextRotationDate *time.Time - - // The ID of the service that created this secret. For more information, see - // Secrets managed by other Amazon Web Services services (https://docs.aws.amazon.com/secretsmanager/latest/userguide/service-linked-secrets.html) - // . - OwningService *string - - // The Region the secret is in. If a secret is replicated to other Regions, the - // replicas are listed in ReplicationStatus . - PrimaryRegion *string - - // A list of the replicas of this secret and their status: - // - Failed , which indicates that the replica was not created. - // - InProgress , which indicates that Secrets Manager is in the process of - // creating the replica. - // - InSync , which indicates that the replica was created. - ReplicationStatus []types.ReplicationStatusType - - // Specifies whether automatic rotation is turned on for this secret. To turn on - // rotation, use RotateSecret . To turn off rotation, use CancelRotateSecret . - RotationEnabled *bool - - // The ARN of the Lambda function that Secrets Manager invokes to rotate the - // secret. - RotationLambdaARN *string - - // The rotation schedule and Lambda function for this secret. If the secret - // previously had rotation turned on, but it is now turned off, this field shows - // the previous rotation schedule and rotation function. If the secret never had - // rotation turned on, this field is omitted. - RotationRules *types.RotationRulesType - - // The list of tags attached to the secret. To add tags to a secret, use - // TagResource . To remove tags, use UntagResource . - Tags []types.Tag - - // A list of the versions of the secret that have staging labels attached. - // Versions that don't have staging labels are considered deprecated and Secrets - // Manager can delete them. Secrets Manager uses staging labels to indicate the - // status of a secret version during rotation. The three staging labels for - // rotation are: - // - AWSCURRENT , which indicates the current version of the secret. - // - AWSPENDING , which indicates the version of the secret that contains new - // secret information that will become the next current version when rotation - // finishes. During rotation, Secrets Manager creates an AWSPENDING version ID - // before creating the new secret version. To check if a secret version exists, - // call GetSecretValue . - // - AWSPREVIOUS , which indicates the previous current version of the secret. - // You can use this as the last known good version. - // For more information about rotation and staging labels, see How rotation works (https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotate-secrets_how.html) - // . - VersionIdsToStages map[string][]string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeSecretMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeSecret{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeSecret{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeSecret"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeSecretValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeSecret(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDescribeSecret(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeSecret", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_GetRandomPassword.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_GetRandomPassword.go deleted file mode 100644 index a9b2deaa..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_GetRandomPassword.go +++ /dev/null @@ -1,172 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Generates a random password. We recommend that you specify the maximum length -// and include every character type that the system you are generating a password -// for can support. By default, Secrets Manager uses uppercase and lowercase -// letters, numbers, and the following characters in passwords: -// !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ Secrets Manager generates a CloudTrail log -// entry when you call this action. Do not include sensitive information in request -// parameters because it might be logged. For more information, see Logging -// Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:GetRandomPassword . For more information, -// see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) GetRandomPassword(ctx context.Context, params *GetRandomPasswordInput, optFns ...func(*Options)) (*GetRandomPasswordOutput, error) { - if params == nil { - params = &GetRandomPasswordInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetRandomPassword", params, optFns, c.addOperationGetRandomPasswordMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetRandomPasswordOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetRandomPasswordInput struct { - - // A string of the characters that you don't want in the password. - ExcludeCharacters *string - - // Specifies whether to exclude lowercase letters from the password. If you don't - // include this switch, the password can contain lowercase letters. - ExcludeLowercase *bool - - // Specifies whether to exclude numbers from the password. If you don't include - // this switch, the password can contain numbers. - ExcludeNumbers *bool - - // Specifies whether to exclude the following punctuation characters from the - // password: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~ . If - // you don't include this switch, the password can contain punctuation. - ExcludePunctuation *bool - - // Specifies whether to exclude uppercase letters from the password. If you don't - // include this switch, the password can contain uppercase letters. - ExcludeUppercase *bool - - // Specifies whether to include the space character. If you include this switch, - // the password can contain space characters. - IncludeSpace *bool - - // The length of the password. If you don't include this parameter, the default - // length is 32 characters. - PasswordLength *int64 - - // Specifies whether to include at least one upper and lowercase letter, one - // number, and one punctuation. If you don't include this switch, the password - // contains at least one of every character type. - RequireEachIncludedType *bool - - noSmithyDocumentSerde -} - -type GetRandomPasswordOutput struct { - - // A string with the password. - RandomPassword *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetRandomPasswordMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetRandomPassword{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetRandomPassword{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetRandomPassword"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opGetRandomPassword(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetRandomPassword(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetRandomPassword", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_GetResourcePolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_GetResourcePolicy.go deleted file mode 100644 index d2331cc8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_GetResourcePolicy.go +++ /dev/null @@ -1,157 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the JSON text of the resource-based policy document attached to the -// secret. For more information about permissions policies attached to a secret, -// see Permissions policies attached to a secret (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_resource-policies.html) -// . Secrets Manager generates a CloudTrail log entry when you call this action. Do -// not include sensitive information in request parameters because it might be -// logged. For more information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:GetResourcePolicy . For more information, -// see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) GetResourcePolicy(ctx context.Context, params *GetResourcePolicyInput, optFns ...func(*Options)) (*GetResourcePolicyOutput, error) { - if params == nil { - params = &GetResourcePolicyInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetResourcePolicy", params, optFns, c.addOperationGetResourcePolicyMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetResourcePolicyOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetResourcePolicyInput struct { - - // The ARN or name of the secret to retrieve the attached resource-based policy - // for. For an ARN, we recommend that you specify a complete ARN rather than a - // partial ARN. See Finding a secret from a partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - noSmithyDocumentSerde -} - -type GetResourcePolicyOutput struct { - - // The ARN of the secret that the resource-based policy was retrieved for. - ARN *string - - // The name of the secret that the resource-based policy was retrieved for. - Name *string - - // A JSON-formatted string that contains the permissions policy attached to the - // secret. For more information about permissions policies, see Authentication and - // access control for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) - // . - ResourcePolicy *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetResourcePolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetResourcePolicy{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetResourcePolicy{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetResourcePolicy"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetResourcePolicyValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetResourcePolicy(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetResourcePolicy(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetResourcePolicy", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_GetSecretValue.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_GetSecretValue.go deleted file mode 100644 index 11ecfcd3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_GetSecretValue.go +++ /dev/null @@ -1,202 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Retrieves the contents of the encrypted fields SecretString or SecretBinary -// from the specified version of a secret, whichever contains content. To retrieve -// the values for a group of secrets, call BatchGetSecretValue . We recommend that -// you cache your secret values by using client-side caching. Caching secrets -// improves speed and reduces your costs. For more information, see Cache secrets -// for your applications (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets.html) -// . To retrieve the previous version of a secret, use VersionStage and specify -// AWSPREVIOUS. To revert to the previous version of a secret, call -// UpdateSecretVersionStage (https://docs.aws.amazon.com/cli/latest/reference/secretsmanager/update-secret-version-stage.html) -// . Secrets Manager generates a CloudTrail log entry when you call this action. Do -// not include sensitive information in request parameters because it might be -// logged. For more information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:GetSecretValue . If the secret is -// encrypted using a customer-managed key instead of the Amazon Web Services -// managed key aws/secretsmanager , then you also need kms:Decrypt permissions for -// that key. For more information, see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) GetSecretValue(ctx context.Context, params *GetSecretValueInput, optFns ...func(*Options)) (*GetSecretValueOutput, error) { - if params == nil { - params = &GetSecretValueInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetSecretValue", params, optFns, c.addOperationGetSecretValueMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetSecretValueOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetSecretValueInput struct { - - // The ARN or name of the secret to retrieve. For an ARN, we recommend that you - // specify a complete ARN rather than a partial ARN. See Finding a secret from a - // partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - // The unique identifier of the version of the secret to retrieve. If you include - // both this parameter and VersionStage , the two parameters must refer to the same - // secret version. If you don't specify either a VersionStage or VersionId , then - // Secrets Manager returns the AWSCURRENT version. This value is typically a - // UUID-type (https://wikipedia.org/wiki/Universally_unique_identifier) value with - // 32 hexadecimal digits. - VersionId *string - - // The staging label of the version of the secret to retrieve. Secrets Manager - // uses staging labels to keep track of different versions during the rotation - // process. If you include both this parameter and VersionId , the two parameters - // must refer to the same secret version. If you don't specify either a - // VersionStage or VersionId , Secrets Manager returns the AWSCURRENT version. - VersionStage *string - - noSmithyDocumentSerde -} - -type GetSecretValueOutput struct { - - // The ARN of the secret. - ARN *string - - // The date and time that this version of the secret was created. If you don't - // specify which version in VersionId or VersionStage , then Secrets Manager uses - // the AWSCURRENT version. - CreatedDate *time.Time - - // The friendly name of the secret. - Name *string - - // The decrypted secret value, if the secret value was originally provided as - // binary data in the form of a byte array. When you retrieve a SecretBinary using - // the HTTP API, the Python SDK, or the Amazon Web Services CLI, the value is - // Base64-encoded. Otherwise, it is not encoded. If the secret was created by using - // the Secrets Manager console, or if the secret value was originally provided as a - // string, then this field is omitted. The secret value appears in SecretString - // instead. - SecretBinary []byte - - // The decrypted secret value, if the secret value was originally provided as a - // string or through the Secrets Manager console. If this secret was created by - // using the console, then Secrets Manager stores the information as a JSON - // structure of key/value pairs. - SecretString *string - - // The unique identifier of this version of the secret. - VersionId *string - - // A list of all of the staging labels currently attached to this version of the - // secret. - VersionStages []string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetSecretValueMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetSecretValue{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetSecretValue{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetSecretValue"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetSecretValueValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetSecretValue(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetSecretValue(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetSecretValue", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ListSecretVersionIds.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ListSecretVersionIds.go deleted file mode 100644 index 62af6310..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ListSecretVersionIds.go +++ /dev/null @@ -1,271 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists the versions of a secret. Secrets Manager uses staging labels to indicate -// the different versions of a secret. For more information, see Secrets Manager -// concepts: Versions (https://docs.aws.amazon.com/secretsmanager/latest/userguide/getting-started.html#term_version) -// . To list the secrets in the account, use ListSecrets . Secrets Manager -// generates a CloudTrail log entry when you call this action. Do not include -// sensitive information in request parameters because it might be logged. For more -// information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:ListSecretVersionIds . For more -// information, see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) ListSecretVersionIds(ctx context.Context, params *ListSecretVersionIdsInput, optFns ...func(*Options)) (*ListSecretVersionIdsOutput, error) { - if params == nil { - params = &ListSecretVersionIdsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListSecretVersionIds", params, optFns, c.addOperationListSecretVersionIdsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListSecretVersionIdsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListSecretVersionIdsInput struct { - - // The ARN or name of the secret whose versions you want to list. For an ARN, we - // recommend that you specify a complete ARN rather than a partial ARN. See - // Finding a secret from a partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - // Specifies whether to include versions of secrets that don't have any staging - // labels attached to them. Versions without staging labels are considered - // deprecated and are subject to deletion by Secrets Manager. By default, versions - // without staging labels aren't included. - IncludeDeprecated *bool - - // The number of results to include in the response. If there are more results - // available, in the response, Secrets Manager includes NextToken . To get the next - // results, call ListSecretVersionIds again with the value from NextToken . - MaxResults *int32 - - // A token that indicates where the output should continue from, if a previous - // call did not show all results. To get the next results, call - // ListSecretVersionIds again with this value. - NextToken *string - - noSmithyDocumentSerde -} - -type ListSecretVersionIdsOutput struct { - - // The ARN of the secret. - ARN *string - - // The name of the secret. - Name *string - - // Secrets Manager includes this value if there's more output available than what - // is included in the current response. This can occur even when the response - // includes no values at all, such as when you ask for a filtered view of a long - // list. To get the next results, call ListSecretVersionIds again with this value. - NextToken *string - - // A list of the versions of the secret. - Versions []types.SecretVersionsListEntry - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListSecretVersionIdsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListSecretVersionIds{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListSecretVersionIds{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListSecretVersionIds"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListSecretVersionIdsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListSecretVersionIds(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListSecretVersionIdsAPIClient is a client that implements the -// ListSecretVersionIds operation. -type ListSecretVersionIdsAPIClient interface { - ListSecretVersionIds(context.Context, *ListSecretVersionIdsInput, ...func(*Options)) (*ListSecretVersionIdsOutput, error) -} - -var _ ListSecretVersionIdsAPIClient = (*Client)(nil) - -// ListSecretVersionIdsPaginatorOptions is the paginator options for -// ListSecretVersionIds -type ListSecretVersionIdsPaginatorOptions struct { - // The number of results to include in the response. If there are more results - // available, in the response, Secrets Manager includes NextToken . To get the next - // results, call ListSecretVersionIds again with the value from NextToken . - 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 -} - -// ListSecretVersionIdsPaginator is a paginator for ListSecretVersionIds -type ListSecretVersionIdsPaginator struct { - options ListSecretVersionIdsPaginatorOptions - client ListSecretVersionIdsAPIClient - params *ListSecretVersionIdsInput - nextToken *string - firstPage bool -} - -// NewListSecretVersionIdsPaginator returns a new ListSecretVersionIdsPaginator -func NewListSecretVersionIdsPaginator(client ListSecretVersionIdsAPIClient, params *ListSecretVersionIdsInput, optFns ...func(*ListSecretVersionIdsPaginatorOptions)) *ListSecretVersionIdsPaginator { - if params == nil { - params = &ListSecretVersionIdsInput{} - } - - options := ListSecretVersionIdsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListSecretVersionIdsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListSecretVersionIdsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListSecretVersionIds page. -func (p *ListSecretVersionIdsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListSecretVersionIdsOutput, 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 - - result, err := p.client.ListSecretVersionIds(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 -} - -func newServiceMetadataMiddleware_opListSecretVersionIds(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListSecretVersionIds", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ListSecrets.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ListSecrets.go deleted file mode 100644 index 3ae0e70b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ListSecrets.go +++ /dev/null @@ -1,260 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists the secrets that are stored by Secrets Manager in the Amazon Web Services -// account, not including secrets that are marked for deletion. To see secrets -// marked for deletion, use the Secrets Manager console. ListSecrets is eventually -// consistent, however it might not reflect changes from the last five minutes. To -// get the latest information for a specific secret, use DescribeSecret . To list -// the versions of a secret, use ListSecretVersionIds . To retrieve the values for -// the secrets, call BatchGetSecretValue or GetSecretValue . For information about -// finding secrets in the console, see Find secrets in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_search-secret.html) -// . Secrets Manager generates a CloudTrail log entry when you call this action. Do -// not include sensitive information in request parameters because it might be -// logged. For more information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:ListSecrets . For more information, see -// IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) ListSecrets(ctx context.Context, params *ListSecretsInput, optFns ...func(*Options)) (*ListSecretsOutput, error) { - if params == nil { - params = &ListSecretsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListSecrets", params, optFns, c.addOperationListSecretsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListSecretsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListSecretsInput struct { - - // The filters to apply to the list of secrets. - Filters []types.Filter - - // Specifies whether to include secrets scheduled for deletion. By default, - // secrets scheduled for deletion aren't included. - IncludePlannedDeletion *bool - - // The number of results to include in the response. If there are more results - // available, in the response, Secrets Manager includes NextToken . To get the next - // results, call ListSecrets again with the value from NextToken . - MaxResults *int32 - - // A token that indicates where the output should continue from, if a previous - // call did not show all results. To get the next results, call ListSecrets again - // with this value. - NextToken *string - - // Secrets are listed by CreatedDate . - SortOrder types.SortOrderType - - noSmithyDocumentSerde -} - -type ListSecretsOutput struct { - - // Secrets Manager includes this value if there's more output available than what - // is included in the current response. This can occur even when the response - // includes no values at all, such as when you ask for a filtered view of a long - // list. To get the next results, call ListSecrets again with this value. - NextToken *string - - // A list of the secrets in the account. - SecretList []types.SecretListEntry - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListSecretsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListSecrets{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListSecrets{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListSecrets"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opListSecrets(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListSecretsAPIClient is a client that implements the ListSecrets operation. -type ListSecretsAPIClient interface { - ListSecrets(context.Context, *ListSecretsInput, ...func(*Options)) (*ListSecretsOutput, error) -} - -var _ ListSecretsAPIClient = (*Client)(nil) - -// ListSecretsPaginatorOptions is the paginator options for ListSecrets -type ListSecretsPaginatorOptions struct { - // The number of results to include in the response. If there are more results - // available, in the response, Secrets Manager includes NextToken . To get the next - // results, call ListSecrets again with the value from NextToken . - 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 -} - -// ListSecretsPaginator is a paginator for ListSecrets -type ListSecretsPaginator struct { - options ListSecretsPaginatorOptions - client ListSecretsAPIClient - params *ListSecretsInput - nextToken *string - firstPage bool -} - -// NewListSecretsPaginator returns a new ListSecretsPaginator -func NewListSecretsPaginator(client ListSecretsAPIClient, params *ListSecretsInput, optFns ...func(*ListSecretsPaginatorOptions)) *ListSecretsPaginator { - if params == nil { - params = &ListSecretsInput{} - } - - options := ListSecretsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListSecretsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListSecretsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListSecrets page. -func (p *ListSecretsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListSecretsOutput, 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 - - result, err := p.client.ListSecrets(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 -} - -func newServiceMetadataMiddleware_opListSecrets(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListSecrets", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_PutResourcePolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_PutResourcePolicy.go deleted file mode 100644 index b6632d0a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_PutResourcePolicy.go +++ /dev/null @@ -1,165 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Attaches a resource-based permission policy to a secret. A resource-based -// policy is optional. For more information, see Authentication and access control -// for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// For information about attaching a policy in the console, see Attach a -// permissions policy to a secret (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_resource-based-policies.html) -// . Secrets Manager generates a CloudTrail log entry when you call this action. Do -// not include sensitive information in request parameters because it might be -// logged. For more information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:PutResourcePolicy . For more information, -// see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) PutResourcePolicy(ctx context.Context, params *PutResourcePolicyInput, optFns ...func(*Options)) (*PutResourcePolicyOutput, error) { - if params == nil { - params = &PutResourcePolicyInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "PutResourcePolicy", params, optFns, c.addOperationPutResourcePolicyMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*PutResourcePolicyOutput) - out.ResultMetadata = metadata - return out, nil -} - -type PutResourcePolicyInput struct { - - // A JSON-formatted string for an Amazon Web Services resource-based policy. For - // example policies, see Permissions policy examples (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_examples.html) - // . - // - // This member is required. - ResourcePolicy *string - - // The ARN or name of the secret to attach the resource-based policy. For an ARN, - // we recommend that you specify a complete ARN rather than a partial ARN. See - // Finding a secret from a partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - // Specifies whether to block resource-based policies that allow broad access to - // the secret, for example those that use a wildcard for the principal. By default, - // public policies aren't blocked. - BlockPublicPolicy *bool - - noSmithyDocumentSerde -} - -type PutResourcePolicyOutput struct { - - // The ARN of the secret. - ARN *string - - // The name of the secret. - Name *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationPutResourcePolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutResourcePolicy{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpPutResourcePolicy{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "PutResourcePolicy"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpPutResourcePolicyValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutResourcePolicy(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opPutResourcePolicy(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "PutResourcePolicy", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_PutSecretValue.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_PutSecretValue.go deleted file mode 100644 index 862437ac..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_PutSecretValue.go +++ /dev/null @@ -1,258 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Creates a new version with a new encrypted secret value and attaches it to the -// secret. The version can contain a new SecretString value or a new SecretBinary -// value. We recommend you avoid calling PutSecretValue at a sustained rate of -// more than once every 10 minutes. When you update the secret value, Secrets -// Manager creates a new version of the secret. Secrets Manager removes outdated -// versions when there are more than 100, but it does not remove versions created -// less than 24 hours ago. If you call PutSecretValue more than once every 10 -// minutes, you create more versions than Secrets Manager removes, and you will -// reach the quota for secret versions. You can specify the staging labels to -// attach to the new version in VersionStages . If you don't include VersionStages -// , then Secrets Manager automatically moves the staging label AWSCURRENT to this -// version. If this operation creates the first version for the secret, then -// Secrets Manager automatically attaches the staging label AWSCURRENT to it. If -// this operation moves the staging label AWSCURRENT from another version to this -// version, then Secrets Manager also automatically moves the staging label -// AWSPREVIOUS to the version that AWSCURRENT was removed from. This operation is -// idempotent. If you call this operation with a ClientRequestToken that matches -// an existing version's VersionId, and you specify the same secret data, the -// operation succeeds but does nothing. However, if the secret data is different, -// then the operation fails because you can't modify an existing version; you can -// only create new ones. Secrets Manager generates a CloudTrail log entry when you -// call this action. Do not include sensitive information in request parameters -// except SecretBinary or SecretString because it might be logged. For more -// information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:PutSecretValue . For more information, -// see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) PutSecretValue(ctx context.Context, params *PutSecretValueInput, optFns ...func(*Options)) (*PutSecretValueOutput, error) { - if params == nil { - params = &PutSecretValueInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "PutSecretValue", params, optFns, c.addOperationPutSecretValueMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*PutSecretValueOutput) - out.ResultMetadata = metadata - return out, nil -} - -type PutSecretValueInput struct { - - // The ARN or name of the secret to add a new version to. For an ARN, we recommend - // that you specify a complete ARN rather than a partial ARN. See Finding a secret - // from a partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . If the secret doesn't already exist, use CreateSecret instead. - // - // This member is required. - SecretId *string - - // A unique identifier for the new version of the secret. If you use the Amazon - // Web Services CLI or one of the Amazon Web Services SDKs to call this operation, - // then you can leave this parameter empty. The CLI or SDK generates a random UUID - // for you and includes it as the value for this parameter in the request. If you - // generate a raw HTTP request to the Secrets Manager service endpoint, then you - // must generate a ClientRequestToken and include it in the request. This value - // helps ensure idempotency. Secrets Manager uses this value to prevent the - // accidental creation of duplicate versions if there are failures and retries - // during a rotation. We recommend that you generate a UUID-type (https://wikipedia.org/wiki/Universally_unique_identifier) - // value to ensure uniqueness of your versions within the specified secret. - // - If the ClientRequestToken value isn't already associated with a version of - // the secret then a new version of the secret is created. - // - If a version with this value already exists and that version's SecretString - // or SecretBinary values are the same as those in the request then the request - // is ignored. The operation is idempotent. - // - If a version with this value already exists and the version of the - // SecretString and SecretBinary values are different from those in the request, - // then the request fails because you can't modify a secret version. You can only - // create new versions to store new secret values. - // This value becomes the VersionId of the new version. - ClientRequestToken *string - - // The binary data to encrypt and store in the new version of the secret. To use - // this parameter in the command-line tools, we recommend that you store your - // binary data in a file and then pass the contents of the file as a parameter. You - // must include SecretBinary or SecretString , but not both. You can't access this - // value from the Secrets Manager console. - SecretBinary []byte - - // The text to encrypt and store in the new version of the secret. You must - // include SecretBinary or SecretString , but not both. We recommend you create the - // secret string as JSON key/value pairs, as shown in the example. - SecretString *string - - // A list of staging labels to attach to this version of the secret. Secrets - // Manager uses staging labels to track versions of a secret through the rotation - // process. If you specify a staging label that's already associated with a - // different version of the same secret, then Secrets Manager removes the label - // from the other version and attaches it to this version. If you specify - // AWSCURRENT , and it is already attached to another version, then Secrets Manager - // also moves the staging label AWSPREVIOUS to the version that AWSCURRENT was - // removed from. If you don't include VersionStages , then Secrets Manager - // automatically moves the staging label AWSCURRENT to this version. - VersionStages []string - - noSmithyDocumentSerde -} - -type PutSecretValueOutput struct { - - // The ARN of the secret. - ARN *string - - // The name of the secret. - Name *string - - // The unique identifier of the version of the secret. - VersionId *string - - // The list of staging labels that are currently attached to this version of the - // secret. Secrets Manager uses staging labels to track a version as it progresses - // through the secret rotation process. - VersionStages []string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationPutSecretValueMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutSecretValue{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpPutSecretValue{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "PutSecretValue"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addIdempotencyToken_opPutSecretValueMiddleware(stack, options); err != nil { - return err - } - if err = addOpPutSecretValueValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutSecretValue(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -type idempotencyToken_initializeOpPutSecretValue struct { - tokenProvider IdempotencyTokenProvider -} - -func (*idempotencyToken_initializeOpPutSecretValue) ID() string { - return "OperationIdempotencyTokenAutoFill" -} - -func (m *idempotencyToken_initializeOpPutSecretValue) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.tokenProvider == nil { - return next.HandleInitialize(ctx, in) - } - - input, ok := in.Parameters.(*PutSecretValueInput) - if !ok { - return out, metadata, fmt.Errorf("expected middleware input to be of type *PutSecretValueInput ") - } - - if input.ClientRequestToken == nil { - t, err := m.tokenProvider.GetIdempotencyToken() - if err != nil { - return out, metadata, err - } - input.ClientRequestToken = &t - } - return next.HandleInitialize(ctx, in) -} -func addIdempotencyToken_opPutSecretValueMiddleware(stack *middleware.Stack, cfg Options) error { - return stack.Initialize.Add(&idempotencyToken_initializeOpPutSecretValue{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) -} - -func newServiceMetadataMiddleware_opPutSecretValue(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "PutSecretValue", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_RemoveRegionsFromReplication.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_RemoveRegionsFromReplication.go deleted file mode 100644 index 772f8c85..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_RemoveRegionsFromReplication.go +++ /dev/null @@ -1,153 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// For a secret that is replicated to other Regions, deletes the secret replicas -// from the Regions you specify. Secrets Manager generates a CloudTrail log entry -// when you call this action. Do not include sensitive information in request -// parameters because it might be logged. For more information, see Logging -// Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:RemoveRegionsFromReplication . For more -// information, see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) RemoveRegionsFromReplication(ctx context.Context, params *RemoveRegionsFromReplicationInput, optFns ...func(*Options)) (*RemoveRegionsFromReplicationOutput, error) { - if params == nil { - params = &RemoveRegionsFromReplicationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "RemoveRegionsFromReplication", params, optFns, c.addOperationRemoveRegionsFromReplicationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*RemoveRegionsFromReplicationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type RemoveRegionsFromReplicationInput struct { - - // The Regions of the replicas to remove. - // - // This member is required. - RemoveReplicaRegions []string - - // The ARN or name of the secret. - // - // This member is required. - SecretId *string - - noSmithyDocumentSerde -} - -type RemoveRegionsFromReplicationOutput struct { - - // The ARN of the primary secret. - ARN *string - - // The status of replicas for this secret after you remove Regions. - ReplicationStatus []types.ReplicationStatusType - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationRemoveRegionsFromReplicationMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpRemoveRegionsFromReplication{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpRemoveRegionsFromReplication{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "RemoveRegionsFromReplication"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpRemoveRegionsFromReplicationValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRemoveRegionsFromReplication(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opRemoveRegionsFromReplication(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "RemoveRegionsFromReplication", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ReplicateSecretToRegions.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ReplicateSecretToRegions.go deleted file mode 100644 index 44d3acb0..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ReplicateSecretToRegions.go +++ /dev/null @@ -1,159 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Replicates the secret to a new Regions. See Multi-Region secrets (https://docs.aws.amazon.com/secretsmanager/latest/userguide/create-manage-multi-region-secrets.html) -// . Secrets Manager generates a CloudTrail log entry when you call this action. Do -// not include sensitive information in request parameters because it might be -// logged. For more information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:ReplicateSecretToRegions . If the primary -// secret is encrypted with a KMS key other than aws/secretsmanager , you also need -// kms:Decrypt permission to the key. To encrypt the replicated secret with a KMS -// key other than aws/secretsmanager , you need kms:GenerateDataKey and kms:Encrypt -// to the key. For more information, see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) ReplicateSecretToRegions(ctx context.Context, params *ReplicateSecretToRegionsInput, optFns ...func(*Options)) (*ReplicateSecretToRegionsOutput, error) { - if params == nil { - params = &ReplicateSecretToRegionsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ReplicateSecretToRegions", params, optFns, c.addOperationReplicateSecretToRegionsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ReplicateSecretToRegionsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ReplicateSecretToRegionsInput struct { - - // A list of Regions in which to replicate the secret. - // - // This member is required. - AddReplicaRegions []types.ReplicaRegionType - - // The ARN or name of the secret to replicate. - // - // This member is required. - SecretId *string - - // Specifies whether to overwrite a secret with the same name in the destination - // Region. By default, secrets aren't overwritten. - ForceOverwriteReplicaSecret bool - - noSmithyDocumentSerde -} - -type ReplicateSecretToRegionsOutput struct { - - // The ARN of the primary secret. - ARN *string - - // The status of replication. - ReplicationStatus []types.ReplicationStatusType - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationReplicateSecretToRegionsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpReplicateSecretToRegions{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpReplicateSecretToRegions{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ReplicateSecretToRegions"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpReplicateSecretToRegionsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opReplicateSecretToRegions(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opReplicateSecretToRegions(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ReplicateSecretToRegions", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_RestoreSecret.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_RestoreSecret.go deleted file mode 100644 index e722e170..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_RestoreSecret.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Cancels the scheduled deletion of a secret by removing the DeletedDate time -// stamp. You can access a secret again after it has been restored. Secrets Manager -// generates a CloudTrail log entry when you call this action. Do not include -// sensitive information in request parameters because it might be logged. For more -// information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:RestoreSecret . For more information, see -// IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) RestoreSecret(ctx context.Context, params *RestoreSecretInput, optFns ...func(*Options)) (*RestoreSecretOutput, error) { - if params == nil { - params = &RestoreSecretInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "RestoreSecret", params, optFns, c.addOperationRestoreSecretMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*RestoreSecretOutput) - out.ResultMetadata = metadata - return out, nil -} - -type RestoreSecretInput struct { - - // The ARN or name of the secret to restore. For an ARN, we recommend that you - // specify a complete ARN rather than a partial ARN. See Finding a secret from a - // partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - noSmithyDocumentSerde -} - -type RestoreSecretOutput struct { - - // The ARN of the secret that was restored. - ARN *string - - // The name of the secret that was restored. - Name *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationRestoreSecretMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpRestoreSecret{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpRestoreSecret{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "RestoreSecret"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpRestoreSecretValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRestoreSecret(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opRestoreSecret(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "RestoreSecret", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_RotateSecret.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_RotateSecret.go deleted file mode 100644 index 686d06e3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_RotateSecret.go +++ /dev/null @@ -1,237 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Configures and starts the asynchronous process of rotating the secret. For -// information about rotation, see Rotate secrets (https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html) -// in the Secrets Manager User Guide. If you include the configuration parameters, -// the operation sets the values for the secret and then immediately starts a -// rotation. If you don't include the configuration parameters, the operation -// starts a rotation with the values already stored in the secret. When rotation is -// successful, the AWSPENDING staging label might be attached to the same version -// as the AWSCURRENT version, or it might not be attached to any version. If the -// AWSPENDING staging label is present but not attached to the same version as -// AWSCURRENT , then any later invocation of RotateSecret assumes that a previous -// rotation request is still in progress and returns an error. When rotation is -// unsuccessful, the AWSPENDING staging label might be attached to an empty secret -// version. For more information, see Troubleshoot rotation (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot_rotation.html) -// in the Secrets Manager User Guide. Secrets Manager generates a CloudTrail log -// entry when you call this action. Do not include sensitive information in request -// parameters because it might be logged. For more information, see Logging -// Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:RotateSecret . For more information, see -// IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . You also need lambda:InvokeFunction permissions on the rotation function. For -// more information, see Permissions for rotation (https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets-required-permissions-function.html) -// . -func (c *Client) RotateSecret(ctx context.Context, params *RotateSecretInput, optFns ...func(*Options)) (*RotateSecretOutput, error) { - if params == nil { - params = &RotateSecretInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "RotateSecret", params, optFns, c.addOperationRotateSecretMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*RotateSecretOutput) - out.ResultMetadata = metadata - return out, nil -} - -type RotateSecretInput struct { - - // The ARN or name of the secret to rotate. For an ARN, we recommend that you - // specify a complete ARN rather than a partial ARN. See Finding a secret from a - // partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - // A unique identifier for the new version of the secret. You only need to specify - // this value if you implement your own retry logic and you want to ensure that - // Secrets Manager doesn't attempt to create a secret version twice. If you use the - // Amazon Web Services CLI or one of the Amazon Web Services SDKs to call this - // operation, then you can leave this parameter empty. The CLI or SDK generates a - // random UUID for you and includes it as the value for this parameter in the - // request. If you generate a raw HTTP request to the Secrets Manager service - // endpoint, then you must generate a ClientRequestToken and include it in the - // request. This value helps ensure idempotency. Secrets Manager uses this value to - // prevent the accidental creation of duplicate versions if there are failures and - // retries during a rotation. We recommend that you generate a UUID-type (https://wikipedia.org/wiki/Universally_unique_identifier) - // value to ensure uniqueness of your versions within the specified secret. - ClientRequestToken *string - - // Specifies whether to rotate the secret immediately or wait until the next - // scheduled rotation window. The rotation schedule is defined in - // RotateSecretRequest$RotationRules . For secrets that use a Lambda rotation - // function to rotate, if you don't immediately rotate the secret, Secrets Manager - // tests the rotation configuration by running the testSecret step (https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotate-secrets_how.html) - // of the Lambda rotation function. The test creates an AWSPENDING version of the - // secret and then removes it. By default, Secrets Manager rotates the secret - // immediately. - RotateImmediately *bool - - // For secrets that use a Lambda rotation function to rotate, the ARN of the - // Lambda rotation function. For secrets that use managed rotation, omit this - // field. For more information, see Managed rotation (https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotate-secrets_managed.html) - // in the Secrets Manager User Guide. - RotationLambdaARN *string - - // A structure that defines the rotation configuration for this secret. - RotationRules *types.RotationRulesType - - noSmithyDocumentSerde -} - -type RotateSecretOutput struct { - - // The ARN of the secret. - ARN *string - - // The name of the secret. - Name *string - - // The ID of the new version of the secret. - VersionId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationRotateSecretMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpRotateSecret{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpRotateSecret{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "RotateSecret"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addIdempotencyToken_opRotateSecretMiddleware(stack, options); err != nil { - return err - } - if err = addOpRotateSecretValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRotateSecret(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -type idempotencyToken_initializeOpRotateSecret struct { - tokenProvider IdempotencyTokenProvider -} - -func (*idempotencyToken_initializeOpRotateSecret) ID() string { - return "OperationIdempotencyTokenAutoFill" -} - -func (m *idempotencyToken_initializeOpRotateSecret) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.tokenProvider == nil { - return next.HandleInitialize(ctx, in) - } - - input, ok := in.Parameters.(*RotateSecretInput) - if !ok { - return out, metadata, fmt.Errorf("expected middleware input to be of type *RotateSecretInput ") - } - - if input.ClientRequestToken == nil { - t, err := m.tokenProvider.GetIdempotencyToken() - if err != nil { - return out, metadata, err - } - input.ClientRequestToken = &t - } - return next.HandleInitialize(ctx, in) -} -func addIdempotencyToken_opRotateSecretMiddleware(stack *middleware.Stack, cfg Options) error { - return stack.Initialize.Add(&idempotencyToken_initializeOpRotateSecret{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) -} - -func newServiceMetadataMiddleware_opRotateSecret(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "RotateSecret", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_StopReplicationToReplica.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_StopReplicationToReplica.go deleted file mode 100644 index 45870101..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_StopReplicationToReplica.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Removes the link between the replica secret and the primary secret and promotes -// the replica to a primary secret in the replica Region. You must call this -// operation from the Region in which you want to promote the replica to a primary -// secret. Secrets Manager generates a CloudTrail log entry when you call this -// action. Do not include sensitive information in request parameters because it -// might be logged. For more information, see Logging Secrets Manager events with -// CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:StopReplicationToReplica . For more -// information, see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) StopReplicationToReplica(ctx context.Context, params *StopReplicationToReplicaInput, optFns ...func(*Options)) (*StopReplicationToReplicaOutput, error) { - if params == nil { - params = &StopReplicationToReplicaInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "StopReplicationToReplica", params, optFns, c.addOperationStopReplicationToReplicaMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*StopReplicationToReplicaOutput) - out.ResultMetadata = metadata - return out, nil -} - -type StopReplicationToReplicaInput struct { - - // The ARN of the primary secret. - // - // This member is required. - SecretId *string - - noSmithyDocumentSerde -} - -type StopReplicationToReplicaOutput struct { - - // The ARN of the promoted secret. The ARN is the same as the original primary - // secret except the Region is changed. - ARN *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationStopReplicationToReplicaMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpStopReplicationToReplica{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStopReplicationToReplica{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "StopReplicationToReplica"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpStopReplicationToReplicaValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStopReplicationToReplica(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opStopReplicationToReplica(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "StopReplicationToReplica", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_TagResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_TagResource.go deleted file mode 100644 index 594db9b5..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_TagResource.go +++ /dev/null @@ -1,162 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Attaches tags to a secret. Tags consist of a key name and a value. Tags are -// part of the secret's metadata. They are not associated with specific versions of -// the secret. This operation appends tags to the existing list of tags. For tag -// quotas and naming restrictions, see Service quotas for Tagging (https://docs.aws.amazon.com/general/latest/gr/arg.html#taged-reference-quotas) -// in the Amazon Web Services General Reference guide. If you use tags as part of -// your security strategy, then adding or removing a tag can change permissions. If -// successfully completing this operation would result in you losing your -// permissions for this secret, then the operation is blocked and returns an Access -// Denied error. Secrets Manager generates a CloudTrail log entry when you call -// this action. Do not include sensitive information in request parameters because -// it might be logged. For more information, see Logging Secrets Manager events -// with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:TagResource . For more information, see -// IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) TagResource(ctx context.Context, params *TagResourceInput, optFns ...func(*Options)) (*TagResourceOutput, error) { - if params == nil { - params = &TagResourceInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "TagResource", params, optFns, c.addOperationTagResourceMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*TagResourceOutput) - out.ResultMetadata = metadata - return out, nil -} - -type TagResourceInput struct { - - // The identifier for the secret to attach tags to. You can specify either the - // Amazon Resource Name (ARN) or the friendly name of the secret. For an ARN, we - // recommend that you specify a complete ARN rather than a partial ARN. See - // Finding a secret from a partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - // The tags to attach to the secret as a JSON text string argument. Each element - // in the list consists of a Key and a Value . For storing multiple values, we - // recommend that you use a JSON text string argument and specify key/value pairs. - // For more information, see Specifying parameter values for the Amazon Web - // Services CLI (https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters.html) - // in the Amazon Web Services CLI User Guide. - // - // This member is required. - Tags []types.Tag - - noSmithyDocumentSerde -} - -type TagResourceOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -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 - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpTagResource{}, middleware.After) - 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpTagResourceValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opTagResource(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opTagResource(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "TagResource", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_UntagResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_UntagResource.go deleted file mode 100644 index ab5d7ecb..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_UntagResource.go +++ /dev/null @@ -1,156 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Removes specific tags from a secret. This operation is idempotent. If a -// requested tag is not attached to the secret, no error is returned and the secret -// metadata is unchanged. If you use tags as part of your security strategy, then -// removing a tag can change permissions. If successfully completing this operation -// would result in you losing your permissions for this secret, then the operation -// is blocked and returns an Access Denied error. Secrets Manager generates a -// CloudTrail log entry when you call this action. Do not include sensitive -// information in request parameters because it might be logged. For more -// information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:UntagResource . For more information, see -// IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) UntagResource(ctx context.Context, params *UntagResourceInput, optFns ...func(*Options)) (*UntagResourceOutput, error) { - if params == nil { - params = &UntagResourceInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UntagResource", params, optFns, c.addOperationUntagResourceMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UntagResourceOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UntagResourceInput struct { - - // The ARN or name of the secret. For an ARN, we recommend that you specify a - // complete ARN rather than a partial ARN. See Finding a secret from a partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - // A list of tag key names to remove from the secret. You don't specify the value. - // Both the key and its associated value are removed. This parameter requires a - // JSON text string argument. For storing multiple values, we recommend that you - // use a JSON text string argument and specify key/value pairs. For more - // information, see Specifying parameter values for the Amazon Web Services CLI (https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters.html) - // in the Amazon Web Services CLI User Guide. - // - // This member is required. - TagKeys []string - - noSmithyDocumentSerde -} - -type UntagResourceOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -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 - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUntagResource{}, middleware.After) - 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUntagResourceValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUntagResource(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUntagResource(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UntagResource", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_UpdateSecret.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_UpdateSecret.go deleted file mode 100644 index 9599a211..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_UpdateSecret.go +++ /dev/null @@ -1,263 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Modifies the details of a secret, including metadata and the secret value. To -// change the secret value, you can also use PutSecretValue . To change the -// rotation configuration of a secret, use RotateSecret instead. To change a -// secret so that it is managed by another service, you need to recreate the secret -// in that service. See Secrets Manager secrets managed by other Amazon Web -// Services services (https://docs.aws.amazon.com/secretsmanager/latest/userguide/service-linked-secrets.html) -// . We recommend you avoid calling UpdateSecret at a sustained rate of more than -// once every 10 minutes. When you call UpdateSecret to update the secret value, -// Secrets Manager creates a new version of the secret. Secrets Manager removes -// outdated versions when there are more than 100, but it does not remove versions -// created less than 24 hours ago. If you update the secret value more than once -// every 10 minutes, you create more versions than Secrets Manager removes, and you -// will reach the quota for secret versions. If you include SecretString or -// SecretBinary to create a new secret version, Secrets Manager automatically moves -// the staging label AWSCURRENT to the new version. Then it attaches the label -// AWSPREVIOUS to the version that AWSCURRENT was removed from. If you call this -// operation with a ClientRequestToken that matches an existing version's VersionId -// , the operation results in an error. You can't modify an existing version, you -// can only create a new version. To remove a version, remove all staging labels -// from it. See UpdateSecretVersionStage . Secrets Manager generates a CloudTrail -// log entry when you call this action. Do not include sensitive information in -// request parameters except SecretBinary or SecretString because it might be -// logged. For more information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:UpdateSecret . For more information, see -// IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . If you use a customer managed key, you must also have kms:GenerateDataKey , -// kms:Encrypt , and kms:Decrypt permissions on the key. If you change the KMS key -// and you don't have kms:Encrypt permission to the new key, Secrets Manager does -// not re-ecrypt existing secret versions with the new key. For more information, -// see Secret encryption and decryption (https://docs.aws.amazon.com/secretsmanager/latest/userguide/security-encryption.html) -// . -func (c *Client) UpdateSecret(ctx context.Context, params *UpdateSecretInput, optFns ...func(*Options)) (*UpdateSecretOutput, error) { - if params == nil { - params = &UpdateSecretInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateSecret", params, optFns, c.addOperationUpdateSecretMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateSecretOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateSecretInput struct { - - // The ARN or name of the secret. For an ARN, we recommend that you specify a - // complete ARN rather than a partial ARN. See Finding a secret from a partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - // If you include SecretString or SecretBinary , then Secrets Manager creates a new - // version for the secret, and this parameter specifies the unique identifier for - // the new version. If you use the Amazon Web Services CLI or one of the Amazon Web - // Services SDKs to call this operation, then you can leave this parameter empty. - // The CLI or SDK generates a random UUID for you and includes it as the value for - // this parameter in the request. If you generate a raw HTTP request to the Secrets - // Manager service endpoint, then you must generate a ClientRequestToken and - // include it in the request. This value helps ensure idempotency. Secrets Manager - // uses this value to prevent the accidental creation of duplicate versions if - // there are failures and retries during a rotation. We recommend that you generate - // a UUID-type (https://wikipedia.org/wiki/Universally_unique_identifier) value to - // ensure uniqueness of your versions within the specified secret. - ClientRequestToken *string - - // The description of the secret. - Description *string - - // The ARN, key ID, or alias of the KMS key that Secrets Manager uses to encrypt - // new secret versions as well as any existing versions with the staging labels - // AWSCURRENT , AWSPENDING , or AWSPREVIOUS . If you don't have kms:Encrypt - // permission to the new key, Secrets Manager does not re-ecrypt existing secret - // versions with the new key. For more information about versions and staging - // labels, see Concepts: Version (https://docs.aws.amazon.com/secretsmanager/latest/userguide/getting-started.html#term_version) - // . A key alias is always prefixed by alias/ , for example - // alias/aws/secretsmanager . For more information, see About aliases (https://docs.aws.amazon.com/kms/latest/developerguide/alias-about.html) - // . If you set this to an empty string, Secrets Manager uses the Amazon Web - // Services managed key aws/secretsmanager . If this key doesn't already exist in - // your account, then Secrets Manager creates it for you automatically. All users - // and roles in the Amazon Web Services account automatically have access to use - // aws/secretsmanager . Creating aws/secretsmanager can result in a one-time - // significant delay in returning the result. You can only use the Amazon Web - // Services managed key aws/secretsmanager if you call this operation using - // credentials from the same Amazon Web Services account that owns the secret. If - // the secret is in a different account, then you must use a customer managed key - // and provide the ARN of that KMS key in this field. The user making the call must - // have permissions to both the secret and the KMS key in their respective - // accounts. - KmsKeyId *string - - // The binary data to encrypt and store in the new version of the secret. We - // recommend that you store your binary data in a file and then pass the contents - // of the file as a parameter. Either SecretBinary or SecretString must have a - // value, but not both. You can't access this parameter in the Secrets Manager - // console. - SecretBinary []byte - - // The text data to encrypt and store in the new version of the secret. We - // recommend you use a JSON structure of key/value pairs for your secret value. - // Either SecretBinary or SecretString must have a value, but not both. - SecretString *string - - noSmithyDocumentSerde -} - -type UpdateSecretOutput struct { - - // The ARN of the secret that was updated. - ARN *string - - // The name of the secret that was updated. - Name *string - - // If Secrets Manager created a new version of the secret during this operation, - // then VersionId contains the unique identifier of the new version. - VersionId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateSecretMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateSecret{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateSecret{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateSecret"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addIdempotencyToken_opUpdateSecretMiddleware(stack, options); err != nil { - return err - } - if err = addOpUpdateSecretValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateSecret(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -type idempotencyToken_initializeOpUpdateSecret struct { - tokenProvider IdempotencyTokenProvider -} - -func (*idempotencyToken_initializeOpUpdateSecret) ID() string { - return "OperationIdempotencyTokenAutoFill" -} - -func (m *idempotencyToken_initializeOpUpdateSecret) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.tokenProvider == nil { - return next.HandleInitialize(ctx, in) - } - - input, ok := in.Parameters.(*UpdateSecretInput) - if !ok { - return out, metadata, fmt.Errorf("expected middleware input to be of type *UpdateSecretInput ") - } - - if input.ClientRequestToken == nil { - t, err := m.tokenProvider.GetIdempotencyToken() - if err != nil { - return out, metadata, err - } - input.ClientRequestToken = &t - } - return next.HandleInitialize(ctx, in) -} -func addIdempotencyToken_opUpdateSecretMiddleware(stack *middleware.Stack, cfg Options) error { - return stack.Initialize.Add(&idempotencyToken_initializeOpUpdateSecret{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) -} - -func newServiceMetadataMiddleware_opUpdateSecret(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateSecret", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_UpdateSecretVersionStage.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_UpdateSecretVersionStage.go deleted file mode 100644 index 77e308ae..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_UpdateSecretVersionStage.go +++ /dev/null @@ -1,181 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Modifies the staging labels attached to a version of a secret. Secrets Manager -// uses staging labels to track a version as it progresses through the secret -// rotation process. Each staging label can be attached to only one version at a -// time. To add a staging label to a version when it is already attached to another -// version, Secrets Manager first removes it from the other version first and then -// attaches it to this one. For more information about versions and staging labels, -// see Concepts: Version (https://docs.aws.amazon.com/secretsmanager/latest/userguide/getting-started.html#term_version) -// . The staging labels that you specify in the VersionStage parameter are added -// to the existing list of staging labels for the version. You can move the -// AWSCURRENT staging label to this version by including it in this call. Whenever -// you move AWSCURRENT , Secrets Manager automatically moves the label AWSPREVIOUS -// to the version that AWSCURRENT was removed from. If this action results in the -// last label being removed from a version, then the version is considered to be -// 'deprecated' and can be deleted by Secrets Manager. Secrets Manager generates a -// CloudTrail log entry when you call this action. Do not include sensitive -// information in request parameters because it might be logged. For more -// information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:UpdateSecretVersionStage . For more -// information, see IAM policy actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) UpdateSecretVersionStage(ctx context.Context, params *UpdateSecretVersionStageInput, optFns ...func(*Options)) (*UpdateSecretVersionStageOutput, error) { - if params == nil { - params = &UpdateSecretVersionStageInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateSecretVersionStage", params, optFns, c.addOperationUpdateSecretVersionStageMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateSecretVersionStageOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateSecretVersionStageInput struct { - - // The ARN or the name of the secret with the version and staging labelsto modify. - // For an ARN, we recommend that you specify a complete ARN rather than a partial - // ARN. See Finding a secret from a partial ARN (https://docs.aws.amazon.com/secretsmanager/latest/userguide/troubleshoot.html#ARN_secretnamehyphen) - // . - // - // This member is required. - SecretId *string - - // The staging label to add to this version. - // - // This member is required. - VersionStage *string - - // The ID of the version to add the staging label to. To remove a label from a - // version, then do not specify this parameter. If the staging label is already - // attached to a different version of the secret, then you must also specify the - // RemoveFromVersionId parameter. - MoveToVersionId *string - - // The ID of the version that the staging label is to be removed from. If the - // staging label you are trying to attach to one version is already attached to a - // different version, then you must include this parameter and specify the version - // that the label is to be removed from. If the label is attached and you either do - // not specify this parameter, or the version ID does not match, then the operation - // fails. - RemoveFromVersionId *string - - noSmithyDocumentSerde -} - -type UpdateSecretVersionStageOutput struct { - - // The ARN of the secret that was updated. - ARN *string - - // The name of the secret that was updated. - Name *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateSecretVersionStageMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateSecretVersionStage{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateSecretVersionStage{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateSecretVersionStage"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateSecretVersionStageValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateSecretVersionStage(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateSecretVersionStage(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateSecretVersionStage", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ValidateResourcePolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ValidateResourcePolicy.go deleted file mode 100644 index 0de3d3f1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/api_op_ValidateResourcePolicy.go +++ /dev/null @@ -1,163 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Validates that a resource policy does not grant a wide range of principals -// access to your secret. A resource-based policy is optional for secrets. The API -// performs three checks when validating the policy: -// - Sends a call to Zelkova (https://aws.amazon.com/blogs/security/protect-sensitive-data-in-the-cloud-with-automated-reasoning-zelkova/) -// , an automated reasoning engine, to ensure your resource policy does not allow -// broad access to your secret, for example policies that use a wildcard for the -// principal. -// - Checks for correct syntax in a policy. -// - Verifies the policy does not lock out a caller. -// -// Secrets Manager generates a CloudTrail log entry when you call this action. Do -// not include sensitive information in request parameters because it might be -// logged. For more information, see Logging Secrets Manager events with CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieve-ct-entries.html) -// . Required permissions: secretsmanager:ValidateResourcePolicy and -// secretsmanager:PutResourcePolicy . For more information, see IAM policy -// actions for Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#reference_iam-permissions_actions) -// and Authentication and access control in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html) -// . -func (c *Client) ValidateResourcePolicy(ctx context.Context, params *ValidateResourcePolicyInput, optFns ...func(*Options)) (*ValidateResourcePolicyOutput, error) { - if params == nil { - params = &ValidateResourcePolicyInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ValidateResourcePolicy", params, optFns, c.addOperationValidateResourcePolicyMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ValidateResourcePolicyOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ValidateResourcePolicyInput struct { - - // A JSON-formatted string that contains an Amazon Web Services resource-based - // policy. The policy in the string identifies who can access or manage this secret - // and its versions. For example policies, see Permissions policy examples (https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_examples.html) - // . - // - // This member is required. - ResourcePolicy *string - - // This field is reserved for internal use. - SecretId *string - - noSmithyDocumentSerde -} - -type ValidateResourcePolicyOutput struct { - - // True if your policy passes validation, otherwise false. - PolicyValidationPassed bool - - // Validation errors if your policy didn't pass validation. - ValidationErrors []types.ValidationErrorsEntry - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationValidateResourcePolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpValidateResourcePolicy{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpValidateResourcePolicy{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ValidateResourcePolicy"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpValidateResourcePolicyValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opValidateResourcePolicy(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opValidateResourcePolicy(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ValidateResourcePolicy", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/auth.go deleted file mode 100644 index ff911710..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/auth.go +++ /dev/null @@ -1,284 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -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/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -func bindAuthParamsRegion(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(operation string, input interface{}, options Options) *AuthResolverParameters { - params := &AuthResolverParameters{ - Operation: operation, - } - - bindAuthParamsRegion(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, "secretsmanager") - 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, -) { - params := bindAuthResolverParams(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) - 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, -) { - rscheme := getResolvedAuthScheme(ctx) - 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 := resolver.GetIdentity(ctx, rscheme.IdentityProperties) - if err != nil { - return out, metadata, fmt.Errorf("get identity: %w", err) - } - - ctx = setIdentity(ctx, identity) - 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 { -} - -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, -) { - 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") - } - - if err := signer.SignRequest(ctx, req, identity, rscheme.SignerProperties); err != nil { - return out, metadata, fmt.Errorf("sign request: %w", err) - } - - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/deserializers.go deleted file mode 100644 index 5e0d8b27..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/deserializers.go +++ /dev/null @@ -1,6055 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "bytes" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws/protocol/restjson" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - smithy "github.com/aws/smithy-go" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/ptr" - smithytime "github.com/aws/smithy-go/time" - smithyhttp "github.com/aws/smithy-go/transport/http" - "io" - "io/ioutil" - "strings" -) - -type awsAwsjson11_deserializeOpBatchGetSecretValue struct { -} - -func (*awsAwsjson11_deserializeOpBatchGetSecretValue) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpBatchGetSecretValue) 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 - } - - 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_deserializeOpErrorBatchGetSecretValue(response, &metadata) - } - output := &BatchGetSecretValueOutput{} - 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_deserializeOpDocumentBatchGetSecretValueOutput(&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_deserializeOpErrorBatchGetSecretValue(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DecryptionFailure", errorCode): - return awsAwsjson11_deserializeErrorDecryptionFailure(response, errorBody) - - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidNextTokenException", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextTokenException(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCancelRotateSecret struct { -} - -func (*awsAwsjson11_deserializeOpCancelRotateSecret) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCancelRotateSecret) 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 - } - - 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_deserializeOpErrorCancelRotateSecret(response, &metadata) - } - output := &CancelRotateSecretOutput{} - 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_deserializeOpDocumentCancelRotateSecretOutput(&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_deserializeOpErrorCancelRotateSecret(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCreateSecret struct { -} - -func (*awsAwsjson11_deserializeOpCreateSecret) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCreateSecret) 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 - } - - 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_deserializeOpErrorCreateSecret(response, &metadata) - } - output := &CreateSecretOutput{} - 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_deserializeOpDocumentCreateSecretOutput(&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_deserializeOpErrorCreateSecret(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DecryptionFailure", errorCode): - return awsAwsjson11_deserializeErrorDecryptionFailure(response, errorBody) - - case strings.EqualFold("EncryptionFailure", errorCode): - return awsAwsjson11_deserializeErrorEncryptionFailure(response, errorBody) - - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("LimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) - - case strings.EqualFold("MalformedPolicyDocumentException", errorCode): - return awsAwsjson11_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("PreconditionNotMetException", errorCode): - return awsAwsjson11_deserializeErrorPreconditionNotMetException(response, errorBody) - - case strings.EqualFold("ResourceExistsException", errorCode): - return awsAwsjson11_deserializeErrorResourceExistsException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteResourcePolicy struct { -} - -func (*awsAwsjson11_deserializeOpDeleteResourcePolicy) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteResourcePolicy) 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 - } - - 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_deserializeOpErrorDeleteResourcePolicy(response, &metadata) - } - output := &DeleteResourcePolicyOutput{} - 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_deserializeOpDocumentDeleteResourcePolicyOutput(&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_deserializeOpErrorDeleteResourcePolicy(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteSecret struct { -} - -func (*awsAwsjson11_deserializeOpDeleteSecret) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteSecret) 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 - } - - 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_deserializeOpErrorDeleteSecret(response, &metadata) - } - output := &DeleteSecretOutput{} - 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_deserializeOpDocumentDeleteSecretOutput(&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_deserializeOpErrorDeleteSecret(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeSecret struct { -} - -func (*awsAwsjson11_deserializeOpDescribeSecret) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeSecret) 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 - } - - 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_deserializeOpErrorDescribeSecret(response, &metadata) - } - output := &DescribeSecretOutput{} - 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_deserializeOpDocumentDescribeSecretOutput(&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_deserializeOpErrorDescribeSecret(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetRandomPassword struct { -} - -func (*awsAwsjson11_deserializeOpGetRandomPassword) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetRandomPassword) 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 - } - - 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_deserializeOpErrorGetRandomPassword(response, &metadata) - } - output := &GetRandomPasswordOutput{} - 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_deserializeOpDocumentGetRandomPasswordOutput(&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_deserializeOpErrorGetRandomPassword(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetResourcePolicy struct { -} - -func (*awsAwsjson11_deserializeOpGetResourcePolicy) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetResourcePolicy) 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 - } - - 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_deserializeOpErrorGetResourcePolicy(response, &metadata) - } - output := &GetResourcePolicyOutput{} - 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_deserializeOpDocumentGetResourcePolicyOutput(&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_deserializeOpErrorGetResourcePolicy(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetSecretValue struct { -} - -func (*awsAwsjson11_deserializeOpGetSecretValue) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetSecretValue) 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 - } - - 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_deserializeOpErrorGetSecretValue(response, &metadata) - } - output := &GetSecretValueOutput{} - 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_deserializeOpDocumentGetSecretValueOutput(&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_deserializeOpErrorGetSecretValue(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DecryptionFailure", errorCode): - return awsAwsjson11_deserializeErrorDecryptionFailure(response, errorBody) - - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListSecrets struct { -} - -func (*awsAwsjson11_deserializeOpListSecrets) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListSecrets) 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 - } - - 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_deserializeOpErrorListSecrets(response, &metadata) - } - output := &ListSecretsOutput{} - 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_deserializeOpDocumentListSecretsOutput(&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_deserializeOpErrorListSecrets(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidNextTokenException", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextTokenException(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListSecretVersionIds struct { -} - -func (*awsAwsjson11_deserializeOpListSecretVersionIds) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListSecretVersionIds) 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 - } - - 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_deserializeOpErrorListSecretVersionIds(response, &metadata) - } - output := &ListSecretVersionIdsOutput{} - 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_deserializeOpDocumentListSecretVersionIdsOutput(&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_deserializeOpErrorListSecretVersionIds(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidNextTokenException", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextTokenException(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpPutResourcePolicy struct { -} - -func (*awsAwsjson11_deserializeOpPutResourcePolicy) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpPutResourcePolicy) 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 - } - - 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_deserializeOpErrorPutResourcePolicy(response, &metadata) - } - output := &PutResourcePolicyOutput{} - 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_deserializeOpDocumentPutResourcePolicyOutput(&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_deserializeOpErrorPutResourcePolicy(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("MalformedPolicyDocumentException", errorCode): - return awsAwsjson11_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("PublicPolicyException", errorCode): - return awsAwsjson11_deserializeErrorPublicPolicyException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpPutSecretValue struct { -} - -func (*awsAwsjson11_deserializeOpPutSecretValue) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpPutSecretValue) 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 - } - - 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_deserializeOpErrorPutSecretValue(response, &metadata) - } - output := &PutSecretValueOutput{} - 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_deserializeOpDocumentPutSecretValueOutput(&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_deserializeOpErrorPutSecretValue(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DecryptionFailure", errorCode): - return awsAwsjson11_deserializeErrorDecryptionFailure(response, errorBody) - - case strings.EqualFold("EncryptionFailure", errorCode): - return awsAwsjson11_deserializeErrorEncryptionFailure(response, errorBody) - - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("LimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) - - case strings.EqualFold("ResourceExistsException", errorCode): - return awsAwsjson11_deserializeErrorResourceExistsException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpRemoveRegionsFromReplication struct { -} - -func (*awsAwsjson11_deserializeOpRemoveRegionsFromReplication) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpRemoveRegionsFromReplication) 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 - } - - 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_deserializeOpErrorRemoveRegionsFromReplication(response, &metadata) - } - output := &RemoveRegionsFromReplicationOutput{} - 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_deserializeOpDocumentRemoveRegionsFromReplicationOutput(&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_deserializeOpErrorRemoveRegionsFromReplication(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpReplicateSecretToRegions struct { -} - -func (*awsAwsjson11_deserializeOpReplicateSecretToRegions) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpReplicateSecretToRegions) 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 - } - - 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_deserializeOpErrorReplicateSecretToRegions(response, &metadata) - } - output := &ReplicateSecretToRegionsOutput{} - 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_deserializeOpDocumentReplicateSecretToRegionsOutput(&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_deserializeOpErrorReplicateSecretToRegions(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpRestoreSecret struct { -} - -func (*awsAwsjson11_deserializeOpRestoreSecret) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpRestoreSecret) 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 - } - - 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_deserializeOpErrorRestoreSecret(response, &metadata) - } - output := &RestoreSecretOutput{} - 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_deserializeOpDocumentRestoreSecretOutput(&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_deserializeOpErrorRestoreSecret(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpRotateSecret struct { -} - -func (*awsAwsjson11_deserializeOpRotateSecret) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpRotateSecret) 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 - } - - 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_deserializeOpErrorRotateSecret(response, &metadata) - } - output := &RotateSecretOutput{} - 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_deserializeOpDocumentRotateSecretOutput(&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_deserializeOpErrorRotateSecret(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpStopReplicationToReplica struct { -} - -func (*awsAwsjson11_deserializeOpStopReplicationToReplica) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpStopReplicationToReplica) 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 - } - - 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_deserializeOpErrorStopReplicationToReplica(response, &metadata) - } - output := &StopReplicationToReplicaOutput{} - 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_deserializeOpDocumentStopReplicationToReplicaOutput(&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_deserializeOpErrorStopReplicationToReplica(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpTagResource struct { -} - -func (*awsAwsjson11_deserializeOpTagResource) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpTagResource) 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 - } - - 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_deserializeOpErrorTagResource(response, &metadata) - } - output := &TagResourceOutput{} - out.Result = output - - if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to discard response body, %w", err), - } - } - - return out, metadata, err -} - -func awsAwsjson11_deserializeOpErrorTagResource(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUntagResource struct { -} - -func (*awsAwsjson11_deserializeOpUntagResource) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUntagResource) 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 - } - - 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_deserializeOpErrorUntagResource(response, &metadata) - } - output := &UntagResourceOutput{} - out.Result = output - - if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to discard response body, %w", err), - } - } - - return out, metadata, err -} - -func awsAwsjson11_deserializeOpErrorUntagResource(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateSecret struct { -} - -func (*awsAwsjson11_deserializeOpUpdateSecret) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateSecret) 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 - } - - 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_deserializeOpErrorUpdateSecret(response, &metadata) - } - output := &UpdateSecretOutput{} - 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_deserializeOpDocumentUpdateSecretOutput(&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_deserializeOpErrorUpdateSecret(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DecryptionFailure", errorCode): - return awsAwsjson11_deserializeErrorDecryptionFailure(response, errorBody) - - case strings.EqualFold("EncryptionFailure", errorCode): - return awsAwsjson11_deserializeErrorEncryptionFailure(response, errorBody) - - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("LimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) - - case strings.EqualFold("MalformedPolicyDocumentException", errorCode): - return awsAwsjson11_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("PreconditionNotMetException", errorCode): - return awsAwsjson11_deserializeErrorPreconditionNotMetException(response, errorBody) - - case strings.EqualFold("ResourceExistsException", errorCode): - return awsAwsjson11_deserializeErrorResourceExistsException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateSecretVersionStage struct { -} - -func (*awsAwsjson11_deserializeOpUpdateSecretVersionStage) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateSecretVersionStage) 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 - } - - 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_deserializeOpErrorUpdateSecretVersionStage(response, &metadata) - } - output := &UpdateSecretVersionStageOutput{} - 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_deserializeOpDocumentUpdateSecretVersionStageOutput(&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_deserializeOpErrorUpdateSecretVersionStage(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("LimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpValidateResourcePolicy struct { -} - -func (*awsAwsjson11_deserializeOpValidateResourcePolicy) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpValidateResourcePolicy) 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 - } - - 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_deserializeOpErrorValidateResourcePolicy(response, &metadata) - } - output := &ValidateResourcePolicyOutput{} - 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_deserializeOpDocumentValidateResourcePolicyOutput(&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_deserializeOpErrorValidateResourcePolicy(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServiceError", errorCode): - return awsAwsjson11_deserializeErrorInternalServiceError(response, errorBody) - - case strings.EqualFold("InvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameterException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("MalformedPolicyDocumentException", errorCode): - return awsAwsjson11_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsAwsjson11_deserializeErrorDecryptionFailure(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.DecryptionFailure{} - err := awsAwsjson11_deserializeDocumentDecryptionFailure(&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_deserializeErrorEncryptionFailure(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.EncryptionFailure{} - err := awsAwsjson11_deserializeDocumentEncryptionFailure(&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_deserializeErrorInternalServiceError(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.InternalServiceError{} - err := awsAwsjson11_deserializeDocumentInternalServiceError(&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_deserializeErrorInvalidNextTokenException(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.InvalidNextTokenException{} - err := awsAwsjson11_deserializeDocumentInvalidNextTokenException(&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_deserializeErrorInvalidParameterException(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.InvalidParameterException{} - err := awsAwsjson11_deserializeDocumentInvalidParameterException(&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_deserializeErrorInvalidRequestException(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.InvalidRequestException{} - err := awsAwsjson11_deserializeDocumentInvalidRequestException(&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_deserializeErrorLimitExceededException(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.LimitExceededException{} - err := awsAwsjson11_deserializeDocumentLimitExceededException(&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_deserializeErrorMalformedPolicyDocumentException(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.MalformedPolicyDocumentException{} - err := awsAwsjson11_deserializeDocumentMalformedPolicyDocumentException(&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_deserializeErrorPreconditionNotMetException(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.PreconditionNotMetException{} - err := awsAwsjson11_deserializeDocumentPreconditionNotMetException(&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_deserializeErrorPublicPolicyException(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.PublicPolicyException{} - err := awsAwsjson11_deserializeDocumentPublicPolicyException(&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_deserializeErrorResourceExistsException(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.ResourceExistsException{} - err := awsAwsjson11_deserializeDocumentResourceExistsException(&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_deserializeErrorResourceNotFoundException(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.ResourceNotFoundException{} - err := awsAwsjson11_deserializeDocumentResourceNotFoundException(&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_deserializeDocumentAPIErrorListType(v *[]types.APIErrorType, 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.APIErrorType - if *v == nil { - cv = []types.APIErrorType{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.APIErrorType - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAPIErrorType(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAPIErrorType(v **types.APIErrorType, 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.APIErrorType - if *v == nil { - sv = &types.APIErrorType{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ErrorCode": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorCode to be of type string, got %T instead", value) - } - sv.ErrorCode = ptr.String(jtv) - } - - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "SecretId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretIdType to be of type string, got %T instead", value) - } - sv.SecretId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDecryptionFailure(v **types.DecryptionFailure, 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.DecryptionFailure - if *v == nil { - sv = &types.DecryptionFailure{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentEncryptionFailure(v **types.EncryptionFailure, 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.EncryptionFailure - if *v == nil { - sv = &types.EncryptionFailure{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInternalServiceError(v **types.InternalServiceError, 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.InternalServiceError - if *v == nil { - sv = &types.InternalServiceError{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidNextTokenException(v **types.InvalidNextTokenException, 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.InvalidNextTokenException - if *v == nil { - sv = &types.InvalidNextTokenException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidParameterException(v **types.InvalidParameterException, 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.InvalidParameterException - if *v == nil { - sv = &types.InvalidParameterException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidRequestException(v **types.InvalidRequestException, 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.InvalidRequestException - if *v == nil { - sv = &types.InvalidRequestException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentKmsKeyIdListType(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected KmsKeyIdType to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentLimitExceededException(v **types.LimitExceededException, 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.LimitExceededException - if *v == nil { - sv = &types.LimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMalformedPolicyDocumentException(v **types.MalformedPolicyDocumentException, 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.MalformedPolicyDocumentException - if *v == nil { - sv = &types.MalformedPolicyDocumentException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPreconditionNotMetException(v **types.PreconditionNotMetException, 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.PreconditionNotMetException - if *v == nil { - sv = &types.PreconditionNotMetException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPublicPolicyException(v **types.PublicPolicyException, 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.PublicPolicyException - if *v == nil { - sv = &types.PublicPolicyException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentReplicationStatusListType(v *[]types.ReplicationStatusType, 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.ReplicationStatusType - if *v == nil { - cv = []types.ReplicationStatusType{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ReplicationStatusType - destAddr := &col - if err := awsAwsjson11_deserializeDocumentReplicationStatusType(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentReplicationStatusType(v **types.ReplicationStatusType, 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.ReplicationStatusType - if *v == nil { - sv = &types.ReplicationStatusType{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "KmsKeyId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected KmsKeyIdType to be of type string, got %T instead", value) - } - sv.KmsKeyId = ptr.String(jtv) - } - - case "LastAccessedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastAccessedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected LastAccessedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "Region": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RegionType to be of type string, got %T instead", value) - } - sv.Region = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusType to be of type string, got %T instead", value) - } - sv.Status = types.StatusType(jtv) - } - - case "StatusMessage": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusMessageType to be of type string, got %T instead", value) - } - sv.StatusMessage = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceExistsException(v **types.ResourceExistsException, 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.ResourceExistsException - if *v == nil { - sv = &types.ResourceExistsException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceNotFoundException(v **types.ResourceNotFoundException, 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.ResourceNotFoundException - if *v == nil { - sv = &types.ResourceNotFoundException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentRotationRulesType(v **types.RotationRulesType, 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.RotationRulesType - if *v == nil { - sv = &types.RotationRulesType{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AutomaticallyAfterDays": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected AutomaticallyRotateAfterDaysType to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.AutomaticallyAfterDays = ptr.Int64(i64) - } - - case "Duration": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DurationType to be of type string, got %T instead", value) - } - sv.Duration = ptr.String(jtv) - } - - case "ScheduleExpression": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ScheduleExpressionType to be of type string, got %T instead", value) - } - sv.ScheduleExpression = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentSecretListEntry(v **types.SecretListEntry, 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.SecretListEntry - if *v == nil { - sv = &types.SecretListEntry{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected TimestampType to be a JSON Number, got %T instead", value) - - } - } - - case "DeletedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.DeletedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DeletedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DescriptionType to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "KmsKeyId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected KmsKeyIdType to be of type string, got %T instead", value) - } - sv.KmsKeyId = ptr.String(jtv) - } - - case "LastAccessedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastAccessedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected LastAccessedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "LastChangedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastChangedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected LastChangedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "LastRotatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastRotatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected LastRotatedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "NextRotationDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.NextRotationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected NextRotationDateType to be a JSON Number, got %T instead", value) - - } - } - - case "OwningService": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OwningServiceType to be of type string, got %T instead", value) - } - sv.OwningService = ptr.String(jtv) - } - - case "PrimaryRegion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RegionType to be of type string, got %T instead", value) - } - sv.PrimaryRegion = ptr.String(jtv) - } - - case "RotationEnabled": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected RotationEnabledType to be of type *bool, got %T instead", value) - } - sv.RotationEnabled = ptr.Bool(jtv) - } - - case "RotationLambdaARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RotationLambdaARNType to be of type string, got %T instead", value) - } - sv.RotationLambdaARN = ptr.String(jtv) - } - - case "RotationRules": - if err := awsAwsjson11_deserializeDocumentRotationRulesType(&sv.RotationRules, value); err != nil { - return err - } - - case "SecretVersionsToStages": - if err := awsAwsjson11_deserializeDocumentSecretVersionsToStagesMapType(&sv.SecretVersionsToStages, value); err != nil { - return err - } - - case "Tags": - if err := awsAwsjson11_deserializeDocumentTagListType(&sv.Tags, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentSecretListType(v *[]types.SecretListEntry, 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.SecretListEntry - if *v == nil { - cv = []types.SecretListEntry{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.SecretListEntry - destAddr := &col - if err := awsAwsjson11_deserializeDocumentSecretListEntry(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentSecretValueEntry(v **types.SecretValueEntry, 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.SecretValueEntry - if *v == nil { - sv = &types.SecretValueEntry{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected CreatedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "SecretBinary": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretBinaryType to be []byte, got %T instead", value) - } - dv, err := base64.StdEncoding.DecodeString(jtv) - if err != nil { - return fmt.Errorf("failed to base64 decode SecretBinaryType, %w", err) - } - sv.SecretBinary = dv - } - - case "SecretString": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretStringType to be of type string, got %T instead", value) - } - sv.SecretString = ptr.String(jtv) - } - - case "VersionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretVersionIdType to be of type string, got %T instead", value) - } - sv.VersionId = ptr.String(jtv) - } - - case "VersionStages": - if err := awsAwsjson11_deserializeDocumentSecretVersionStagesType(&sv.VersionStages, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentSecretValuesType(v *[]types.SecretValueEntry, 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.SecretValueEntry - if *v == nil { - cv = []types.SecretValueEntry{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.SecretValueEntry - destAddr := &col - if err := awsAwsjson11_deserializeDocumentSecretValueEntry(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentSecretVersionsListEntry(v **types.SecretVersionsListEntry, 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.SecretVersionsListEntry - if *v == nil { - sv = &types.SecretVersionsListEntry{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected CreatedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "KmsKeyIds": - if err := awsAwsjson11_deserializeDocumentKmsKeyIdListType(&sv.KmsKeyIds, value); err != nil { - return err - } - - case "LastAccessedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastAccessedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected LastAccessedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "VersionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretVersionIdType to be of type string, got %T instead", value) - } - sv.VersionId = ptr.String(jtv) - } - - case "VersionStages": - if err := awsAwsjson11_deserializeDocumentSecretVersionStagesType(&sv.VersionStages, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentSecretVersionsListType(v *[]types.SecretVersionsListEntry, 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.SecretVersionsListEntry - if *v == nil { - cv = []types.SecretVersionsListEntry{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.SecretVersionsListEntry - destAddr := &col - if err := awsAwsjson11_deserializeDocumentSecretVersionsListEntry(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentSecretVersionStagesType(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretVersionStageType to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentSecretVersionsToStagesMapType(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 - mapVar := parsedVal - if err := awsAwsjson11_deserializeDocumentSecretVersionStagesType(&mapVar, value); err != nil { - return err - } - parsedVal = mapVar - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentTag(v **types.Tag, 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.Tag - if *v == nil { - sv = &types.Tag{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Key": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TagKeyType to be of type string, got %T instead", value) - } - sv.Key = ptr.String(jtv) - } - - case "Value": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TagValueType to be of type string, got %T instead", value) - } - sv.Value = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentTagListType(v *[]types.Tag, 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.Tag - if *v == nil { - 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_deserializeDocumentValidationErrorsEntry(v **types.ValidationErrorsEntry, 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.ValidationErrorsEntry - if *v == nil { - sv = &types.ValidationErrorsEntry{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CheckName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NameType to be of type string, got %T instead", value) - } - sv.CheckName = ptr.String(jtv) - } - - case "ErrorMessage": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorMessage to be of type string, got %T instead", value) - } - sv.ErrorMessage = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentValidationErrorsType(v *[]types.ValidationErrorsEntry, 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.ValidationErrorsEntry - if *v == nil { - cv = []types.ValidationErrorsEntry{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ValidationErrorsEntry - destAddr := &col - if err := awsAwsjson11_deserializeDocumentValidationErrorsEntry(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeOpDocumentBatchGetSecretValueOutput(v **BatchGetSecretValueOutput, 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 *BatchGetSecretValueOutput - if *v == nil { - sv = &BatchGetSecretValueOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Errors": - if err := awsAwsjson11_deserializeDocumentAPIErrorListType(&sv.Errors, value); err != nil { - return err - } - - case "NextToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NextTokenType to be of type string, got %T instead", value) - } - sv.NextToken = ptr.String(jtv) - } - - case "SecretValues": - if err := awsAwsjson11_deserializeDocumentSecretValuesType(&sv.SecretValues, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCancelRotateSecretOutput(v **CancelRotateSecretOutput, 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 *CancelRotateSecretOutput - if *v == nil { - sv = &CancelRotateSecretOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "VersionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretVersionIdType to be of type string, got %T instead", value) - } - sv.VersionId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCreateSecretOutput(v **CreateSecretOutput, 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 *CreateSecretOutput - if *v == nil { - sv = &CreateSecretOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "ReplicationStatus": - if err := awsAwsjson11_deserializeDocumentReplicationStatusListType(&sv.ReplicationStatus, value); err != nil { - return err - } - - case "VersionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretVersionIdType to be of type string, got %T instead", value) - } - sv.VersionId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteResourcePolicyOutput(v **DeleteResourcePolicyOutput, 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 *DeleteResourcePolicyOutput - if *v == nil { - sv = &DeleteResourcePolicyOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteSecretOutput(v **DeleteSecretOutput, 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 *DeleteSecretOutput - if *v == nil { - sv = &DeleteSecretOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "DeletionDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.DeletionDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DeletionDateType to be a JSON Number, got %T instead", value) - - } - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeSecretOutput(v **DescribeSecretOutput, 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 *DescribeSecretOutput - if *v == nil { - sv = &DescribeSecretOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected TimestampType to be a JSON Number, got %T instead", value) - - } - } - - case "DeletedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.DeletedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DeletedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DescriptionType to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "KmsKeyId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected KmsKeyIdType to be of type string, got %T instead", value) - } - sv.KmsKeyId = ptr.String(jtv) - } - - case "LastAccessedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastAccessedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected LastAccessedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "LastChangedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastChangedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected LastChangedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "LastRotatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastRotatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected LastRotatedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "NextRotationDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.NextRotationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected NextRotationDateType to be a JSON Number, got %T instead", value) - - } - } - - case "OwningService": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OwningServiceType to be of type string, got %T instead", value) - } - sv.OwningService = ptr.String(jtv) - } - - case "PrimaryRegion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RegionType to be of type string, got %T instead", value) - } - sv.PrimaryRegion = ptr.String(jtv) - } - - case "ReplicationStatus": - if err := awsAwsjson11_deserializeDocumentReplicationStatusListType(&sv.ReplicationStatus, value); err != nil { - return err - } - - case "RotationEnabled": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected RotationEnabledType to be of type *bool, got %T instead", value) - } - sv.RotationEnabled = ptr.Bool(jtv) - } - - case "RotationLambdaARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RotationLambdaARNType to be of type string, got %T instead", value) - } - sv.RotationLambdaARN = ptr.String(jtv) - } - - case "RotationRules": - if err := awsAwsjson11_deserializeDocumentRotationRulesType(&sv.RotationRules, value); err != nil { - return err - } - - case "Tags": - if err := awsAwsjson11_deserializeDocumentTagListType(&sv.Tags, value); err != nil { - return err - } - - case "VersionIdsToStages": - if err := awsAwsjson11_deserializeDocumentSecretVersionsToStagesMapType(&sv.VersionIdsToStages, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetRandomPasswordOutput(v **GetRandomPasswordOutput, 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 *GetRandomPasswordOutput - if *v == nil { - sv = &GetRandomPasswordOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "RandomPassword": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RandomPasswordType to be of type string, got %T instead", value) - } - sv.RandomPassword = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetResourcePolicyOutput(v **GetResourcePolicyOutput, 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 *GetResourcePolicyOutput - if *v == nil { - sv = &GetResourcePolicyOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "ResourcePolicy": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NonEmptyResourcePolicyType to be of type string, got %T instead", value) - } - sv.ResourcePolicy = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetSecretValueOutput(v **GetSecretValueOutput, 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 *GetSecretValueOutput - if *v == nil { - sv = &GetSecretValueOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected CreatedDateType to be a JSON Number, got %T instead", value) - - } - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "SecretBinary": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretBinaryType to be []byte, got %T instead", value) - } - dv, err := base64.StdEncoding.DecodeString(jtv) - if err != nil { - return fmt.Errorf("failed to base64 decode SecretBinaryType, %w", err) - } - sv.SecretBinary = dv - } - - case "SecretString": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretStringType to be of type string, got %T instead", value) - } - sv.SecretString = ptr.String(jtv) - } - - case "VersionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretVersionIdType to be of type string, got %T instead", value) - } - sv.VersionId = ptr.String(jtv) - } - - case "VersionStages": - if err := awsAwsjson11_deserializeDocumentSecretVersionStagesType(&sv.VersionStages, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListSecretsOutput(v **ListSecretsOutput, 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 *ListSecretsOutput - if *v == nil { - sv = &ListSecretsOutput{} - } 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 NextTokenType to be of type string, got %T instead", value) - } - sv.NextToken = ptr.String(jtv) - } - - case "SecretList": - if err := awsAwsjson11_deserializeDocumentSecretListType(&sv.SecretList, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListSecretVersionIdsOutput(v **ListSecretVersionIdsOutput, 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 *ListSecretVersionIdsOutput - if *v == nil { - sv = &ListSecretVersionIdsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "NextToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NextTokenType to be of type string, got %T instead", value) - } - sv.NextToken = ptr.String(jtv) - } - - case "Versions": - if err := awsAwsjson11_deserializeDocumentSecretVersionsListType(&sv.Versions, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentPutResourcePolicyOutput(v **PutResourcePolicyOutput, 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 *PutResourcePolicyOutput - if *v == nil { - sv = &PutResourcePolicyOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentPutSecretValueOutput(v **PutSecretValueOutput, 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 *PutSecretValueOutput - if *v == nil { - sv = &PutSecretValueOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "VersionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretVersionIdType to be of type string, got %T instead", value) - } - sv.VersionId = ptr.String(jtv) - } - - case "VersionStages": - if err := awsAwsjson11_deserializeDocumentSecretVersionStagesType(&sv.VersionStages, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentRemoveRegionsFromReplicationOutput(v **RemoveRegionsFromReplicationOutput, 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 *RemoveRegionsFromReplicationOutput - if *v == nil { - sv = &RemoveRegionsFromReplicationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "ReplicationStatus": - if err := awsAwsjson11_deserializeDocumentReplicationStatusListType(&sv.ReplicationStatus, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentReplicateSecretToRegionsOutput(v **ReplicateSecretToRegionsOutput, 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 *ReplicateSecretToRegionsOutput - if *v == nil { - sv = &ReplicateSecretToRegionsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "ReplicationStatus": - if err := awsAwsjson11_deserializeDocumentReplicationStatusListType(&sv.ReplicationStatus, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentRestoreSecretOutput(v **RestoreSecretOutput, 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 *RestoreSecretOutput - if *v == nil { - sv = &RestoreSecretOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentRotateSecretOutput(v **RotateSecretOutput, 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 *RotateSecretOutput - if *v == nil { - sv = &RotateSecretOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "VersionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretVersionIdType to be of type string, got %T instead", value) - } - sv.VersionId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentStopReplicationToReplicaOutput(v **StopReplicationToReplicaOutput, 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 *StopReplicationToReplicaOutput - if *v == nil { - sv = &StopReplicationToReplicaOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateSecretOutput(v **UpdateSecretOutput, 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 *UpdateSecretOutput - if *v == nil { - sv = &UpdateSecretOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "VersionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretVersionIdType to be of type string, got %T instead", value) - } - sv.VersionId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateSecretVersionStageOutput(v **UpdateSecretVersionStageOutput, 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 *UpdateSecretVersionStageOutput - if *v == nil { - sv = &UpdateSecretVersionStageOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretARNType to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretNameType to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentValidateResourcePolicyOutput(v **ValidateResourcePolicyOutput, 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 *ValidateResourcePolicyOutput - if *v == nil { - sv = &ValidateResourcePolicyOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "PolicyValidationPassed": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected BooleanType to be of type *bool, got %T instead", value) - } - sv.PolicyValidationPassed = jtv - } - - case "ValidationErrors": - if err := awsAwsjson11_deserializeDocumentValidationErrorsType(&sv.ValidationErrors, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/doc.go deleted file mode 100644 index e3e68d83..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/doc.go +++ /dev/null @@ -1,31 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -// Package secretsmanager provides the API client, operations, and parameter types -// for AWS Secrets Manager. -// -// Amazon Web Services Secrets Manager Amazon Web Services Secrets Manager -// provides a service to enable you to store, manage, and retrieve, secrets. This -// guide provides descriptions of the Secrets Manager API. For more information -// about using this service, see the Amazon Web Services Secrets Manager User Guide (https://docs.aws.amazon.com/secretsmanager/latest/userguide/introduction.html) -// . API Version This version of the Secrets Manager API Reference documents the -// Secrets Manager API version 2017-10-17. For a list of endpoints, see Amazon Web -// Services Secrets Manager endpoints (https://docs.aws.amazon.com/secretsmanager/latest/userguide/asm_access.html#endpoints) -// . Support and Feedback for Amazon Web Services Secrets Manager We welcome your -// feedback. Send your comments to awssecretsmanager-feedback@amazon.com (mailto:awssecretsmanager-feedback@amazon.com) -// , or post your feedback and questions in the Amazon Web Services Secrets -// Manager Discussion Forum (http://forums.aws.amazon.com/forum.jspa?forumID=296) . -// For more information about the Amazon Web Services Discussion Forums, see -// Forums Help (http://forums.aws.amazon.com/help.jspa) . Logging API Requests -// Amazon Web Services Secrets Manager supports Amazon Web Services CloudTrail, a -// service that records Amazon Web Services API calls for your Amazon Web Services -// account and delivers log files to an Amazon S3 bucket. By using information -// that's collected by Amazon Web Services CloudTrail, you can determine the -// requests successfully made to Secrets Manager, who made the request, when it was -// made, and so on. For more about Amazon Web Services Secrets Manager and support -// for Amazon Web Services CloudTrail, see Logging Amazon Web Services Secrets -// Manager Events with Amazon Web Services CloudTrail (https://docs.aws.amazon.com/secretsmanager/latest/userguide/monitoring.html#monitoring_cloudtrail) -// in the Amazon Web Services Secrets Manager User Guide. To learn more about -// CloudTrail, including enabling it and find your log files, see the Amazon Web -// Services CloudTrail User Guide (https://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html) -// . -package secretsmanager diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/endpoints.go deleted file mode 100644 index 347bcf0d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/endpoints.go +++ /dev/null @@ -1,604 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "errors" - "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/secretsmanager/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" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net/http" - "net/url" - "os" - "strings" -) - -// EndpointResolverOptions is the service endpoint resolver options -type EndpointResolverOptions = internalendpoints.Options - -// EndpointResolver interface for resolving service endpoints. -type EndpointResolver interface { - ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) -} - -var _ EndpointResolver = &internalendpoints.Resolver{} - -// NewDefaultEndpointResolver constructs a new service endpoint resolver -func NewDefaultEndpointResolver() *internalendpoints.Resolver { - return internalendpoints.New() -} - -// EndpointResolverFunc is a helper utility that wraps a function so it satisfies -// the EndpointResolver interface. This is useful when you want to add additional -// endpoint resolving logic, or stub out specific endpoints with custom values. -type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) - -func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return fn(region, options) -} - -// EndpointResolverFromURL returns an EndpointResolver configured using the -// provided endpoint url. By default, the resolved endpoint resolver uses the -// client region as signing region, and the endpoint source is set to -// EndpointSourceCustom.You can provide functional options to configure endpoint -// values for the resolved endpoint. -func EndpointResolverFromURL(url string, optFns ...func(*aws.Endpoint)) EndpointResolver { - e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom} - for _, fn := range optFns { - fn(&e) - } - - return EndpointResolverFunc( - func(region string, options EndpointResolverOptions) (aws.Endpoint, error) { - if len(e.SigningRegion) == 0 { - e.SigningRegion = region - } - return e, nil - }, - ) -} - -type ResolveEndpoint struct { - Resolver EndpointResolver - Options EndpointResolverOptions -} - -func (*ResolveEndpoint) ID() string { - return "ResolveEndpoint" -} - -func (m *ResolveEndpoint) 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.Resolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - eo := m.Options - eo.Logger = middleware.GetLogger(ctx) - - var endpoint aws.Endpoint - endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), eo) - if err != nil { - nf := (&aws.EndpointNotFoundError{}) - if errors.As(err, &nf) { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, false) - return next.HandleSerialize(ctx, in) - } - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL, err = url.Parse(endpoint.URL) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) - } - - if len(awsmiddleware.GetSigningName(ctx)) == 0 { - signingName := endpoint.SigningName - if len(signingName) == 0 { - signingName = "secretsmanager" - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - } - ctx = awsmiddleware.SetEndpointSource(ctx, endpoint.Source) - ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) - ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) - ctx = awsmiddleware.SetPartitionID(ctx, endpoint.PartitionID) - return next.HandleSerialize(ctx, in) -} -func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&ResolveEndpoint{ - Resolver: o.EndpointResolver, - Options: o.EndpointOptions, - }, "OperationSerializer", middleware.Before) -} - -func removeResolveEndpointMiddleware(stack *middleware.Stack) error { - _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) - return err -} - -type wrappedEndpointResolver struct { - awsResolver aws.EndpointResolverWithOptions -} - -func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return w.awsResolver.ResolveEndpoint(ServiceID, region, options) -} - -type awsEndpointResolverAdaptor func(service, region string) (aws.Endpoint, error) - -func (a awsEndpointResolverAdaptor) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { - return a(service, region) -} - -var _ aws.EndpointResolverWithOptions = awsEndpointResolverAdaptor(nil) - -// withEndpointResolver returns an aws.EndpointResolverWithOptions that first delegates endpoint resolution to the awsResolver. -// If awsResolver returns aws.EndpointNotFoundError error, the v1 resolver middleware will swallow the error, -// and set an appropriate context flag such that fallback will occur when EndpointResolverV2 is invoked -// via its middleware. -// -// If another error (besides aws.EndpointNotFoundError) is returned, then that error will be propagated. -func withEndpointResolver(awsResolver aws.EndpointResolver, awsResolverWithOptions aws.EndpointResolverWithOptions) EndpointResolver { - var resolver aws.EndpointResolverWithOptions - - if awsResolverWithOptions != nil { - resolver = awsResolverWithOptions - } else if awsResolver != nil { - resolver = awsEndpointResolverAdaptor(awsResolver.ResolveEndpoint) - } - - return &wrappedEndpointResolver{ - awsResolver: resolver, - } -} - -func finalizeClientEndpointResolverOptions(options *Options) { - options.EndpointOptions.LogDeprecated = options.ClientLogMode.IsDeprecatedUsage() - - if len(options.EndpointOptions.ResolvedRegion) == 0 { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(options.Region, fipsInfix) || - strings.Contains(options.Region, fipsPrefix) || - strings.Contains(options.Region, fipsSuffix) { - options.EndpointOptions.ResolvedRegion = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - options.Region, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - options.EndpointOptions.UseFIPSEndpoint = aws.FIPSEndpointStateEnabled - } - } - -} - -func resolveEndpointResolverV2(options *Options) { - if options.EndpointResolverV2 == nil { - options.EndpointResolverV2 = NewDefaultEndpointResolverV2() - } -} - -func resolveBaseEndpoint(cfg aws.Config, o *Options) { - if cfg.BaseEndpoint != nil { - o.BaseEndpoint = cfg.BaseEndpoint - } - - _, g := os.LookupEnv("AWS_ENDPOINT_URL") - _, s := os.LookupEnv("AWS_ENDPOINT_URL_SECRETS_MANAGER") - - if g && !s { - return - } - - value, found, err := internalConfig.ResolveServiceBaseEndpoint(context.Background(), "Secrets Manager", cfg.ConfigSources) - if found && err == nil { - o.BaseEndpoint = &value - } -} - -// EndpointParameters provides the parameters that influence how endpoints are -// resolved. -type EndpointParameters struct { - // The AWS region used to dispatch the request. - // - // Parameter is - // required. - // - // AWS::Region - Region *string - - // When true, use the dual-stack endpoint. If the configured endpoint does not - // support dual-stack, dispatching the request MAY return an error. - // - // Defaults to - // false if no value is provided. - // - // AWS::UseDualStack - UseDualStack *bool - - // When true, send this request to the FIPS-compliant regional endpoint. If the - // configured endpoint does not have a FIPS compliant endpoint, dispatching the - // request will return an error. - // - // Defaults to false if no value is - // provided. - // - // AWS::UseFIPS - UseFIPS *bool - - // Override the endpoint used to send this request - // - // Parameter is - // required. - // - // SDK::Endpoint - Endpoint *string -} - -// ValidateRequired validates required parameters are set. -func (p EndpointParameters) ValidateRequired() error { - if p.UseDualStack == nil { - return fmt.Errorf("parameter UseDualStack is required") - } - - if p.UseFIPS == nil { - return fmt.Errorf("parameter UseFIPS is required") - } - - return nil -} - -// WithDefaults returns a shallow copy of EndpointParameterswith default values -// applied to members where applicable. -func (p EndpointParameters) WithDefaults() EndpointParameters { - if p.UseDualStack == nil { - p.UseDualStack = ptr.Bool(false) - } - - if p.UseFIPS == nil { - p.UseFIPS = ptr.Bool(false) - } - return p -} - -// EndpointResolverV2 provides the interface for resolving service endpoints. -type EndpointResolverV2 interface { - // ResolveEndpoint attempts to resolve the endpoint with the provided options, - // returning the endpoint if found. Otherwise an error is returned. - ResolveEndpoint(ctx context.Context, params EndpointParameters) ( - smithyendpoints.Endpoint, error, - ) -} - -// resolver provides the implementation for resolving endpoints. -type resolver struct{} - -func NewDefaultEndpointResolverV2() EndpointResolverV2 { - return &resolver{} -} - -// ResolveEndpoint attempts to resolve the endpoint with the provided options, -// returning the endpoint if found. Otherwise an error is returned. -func (r *resolver) ResolveEndpoint( - ctx context.Context, params EndpointParameters, -) ( - endpoint smithyendpoints.Endpoint, err error, -) { - params = params.WithDefaults() - if err = params.ValidateRequired(); err != nil { - return endpoint, fmt.Errorf("endpoint parameters are not valid, %w", err) - } - _UseDualStack := *params.UseDualStack - _UseFIPS := *params.UseFIPS - - if exprVal := params.Endpoint; exprVal != nil { - _Endpoint := *exprVal - _ = _Endpoint - if _UseFIPS == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: FIPS and custom endpoint are not supported") - } - if _UseDualStack == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Dualstack and custom endpoint are not supported") - } - uriString := _Endpoint - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if exprVal := params.Region; exprVal != nil { - _Region := *exprVal - _ = _Region - if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { - _PartitionResult := *exprVal - _ = _PartitionResult - if _UseFIPS == true { - if _UseDualStack == true { - if true == _PartitionResult.SupportsFIPS { - if true == _PartitionResult.SupportsDualStack { - if "aws" == _PartitionResult.Name { - uriString := func() string { - var out strings.Builder - out.WriteString("https://secretsmanager-fips.") - out.WriteString(_Region) - out.WriteString(".amazonaws.com") - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if "aws-us-gov" == _PartitionResult.Name { - uriString := func() string { - var out strings.Builder - out.WriteString("https://secretsmanager-fips.") - out.WriteString(_Region) - out.WriteString(".amazonaws.com") - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://secretsmanager-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS and DualStack are enabled, but this partition does not support one or both") - } - } - if _UseFIPS == true { - if _PartitionResult.SupportsFIPS == true { - uriString := func() string { - var out strings.Builder - out.WriteString("https://secretsmanager-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS is enabled but this partition does not support FIPS") - } - if _UseDualStack == true { - if true == _PartitionResult.SupportsDualStack { - if "aws" == _PartitionResult.Name { - uriString := func() string { - var out strings.Builder - out.WriteString("https://secretsmanager.") - out.WriteString(_Region) - out.WriteString(".amazonaws.com") - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if "aws-cn" == _PartitionResult.Name { - uriString := func() string { - var out strings.Builder - out.WriteString("https://secretsmanager.") - out.WriteString(_Region) - out.WriteString(".amazonaws.com.cn") - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if "aws-us-gov" == _PartitionResult.Name { - uriString := func() string { - var out strings.Builder - out.WriteString("https://secretsmanager.") - out.WriteString(_Region) - out.WriteString(".amazonaws.com") - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://secretsmanager.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "DualStack is enabled but this partition does not support DualStack") - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://secretsmanager.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("Endpoint resolution failed. Invalid operation or environment input.") - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") -} - -type endpointParamsBinder interface { - bindEndpointParams(*EndpointParameters) -} - -func bindEndpointParams(input interface{}, options Options) *EndpointParameters { - params := &EndpointParameters{} - - params.Region = aws.String(endpoints.MapFIPSRegion(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, -) { - 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(getOperationInput(ctx), m.options) - endpt, err := m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - 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) - } - - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/generated.json deleted file mode 100644 index eba7c923..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/generated.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "dependencies": { - "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" - }, - "files": [ - "api_client.go", - "api_client_test.go", - "api_op_BatchGetSecretValue.go", - "api_op_CancelRotateSecret.go", - "api_op_CreateSecret.go", - "api_op_DeleteResourcePolicy.go", - "api_op_DeleteSecret.go", - "api_op_DescribeSecret.go", - "api_op_GetRandomPassword.go", - "api_op_GetResourcePolicy.go", - "api_op_GetSecretValue.go", - "api_op_ListSecretVersionIds.go", - "api_op_ListSecrets.go", - "api_op_PutResourcePolicy.go", - "api_op_PutSecretValue.go", - "api_op_RemoveRegionsFromReplication.go", - "api_op_ReplicateSecretToRegions.go", - "api_op_RestoreSecret.go", - "api_op_RotateSecret.go", - "api_op_StopReplicationToReplica.go", - "api_op_TagResource.go", - "api_op_UntagResource.go", - "api_op_UpdateSecret.go", - "api_op_UpdateSecretVersionStage.go", - "api_op_ValidateResourcePolicy.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", - "types/enums.go", - "types/errors.go", - "types/types.go", - "validators.go" - ], - "go": "1.15", - "module": "github.com/aws/aws-sdk-go-v2/service/secretsmanager", - "unstable": false -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/go_module_metadata.go deleted file mode 100644 index 06f6ae94..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package secretsmanager - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.26.2" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/internal/endpoints/endpoints.go deleted file mode 100644 index 4181a93f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/internal/endpoints/endpoints.go +++ /dev/null @@ -1,650 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package endpoints - -import ( - "github.com/aws/aws-sdk-go-v2/aws" - endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" - "github.com/aws/smithy-go/logging" - "regexp" -) - -// Options is the endpoint resolver configuration options -type Options struct { - // Logger is a logging implementation that log events should be sent to. - Logger logging.Logger - - // LogDeprecated indicates that deprecated endpoints should be logged to the - // provided logger. - LogDeprecated bool - - // ResolvedRegion is used to override the region to be resolved, rather then the - // using the value passed to the ResolveEndpoint method. This value is used by the - // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative - // name. You must not set this value directly in your application. - ResolvedRegion string - - // DisableHTTPS informs the resolver to return an endpoint that does not use the - // HTTPS scheme. - DisableHTTPS bool - - // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. - UseDualStackEndpoint aws.DualStackEndpointState - - // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. - UseFIPSEndpoint aws.FIPSEndpointState -} - -func (o Options) GetResolvedRegion() string { - return o.ResolvedRegion -} - -func (o Options) GetDisableHTTPS() bool { - return o.DisableHTTPS -} - -func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { - return o.UseDualStackEndpoint -} - -func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { - return o.UseFIPSEndpoint -} - -func transformToSharedOptions(options Options) endpoints.Options { - return endpoints.Options{ - Logger: options.Logger, - LogDeprecated: options.LogDeprecated, - ResolvedRegion: options.ResolvedRegion, - DisableHTTPS: options.DisableHTTPS, - UseDualStackEndpoint: options.UseDualStackEndpoint, - UseFIPSEndpoint: options.UseFIPSEndpoint, - } -} - -// Resolver Secrets Manager endpoint resolver -type Resolver struct { - partitions endpoints.Partitions -} - -// ResolveEndpoint resolves the service endpoint for the given region and options -func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { - if len(region) == 0 { - return endpoint, &aws.MissingRegionError{} - } - - opt := transformToSharedOptions(options) - return r.partitions.ResolveEndpoint(region, opt) -} - -// New returns a new Resolver -func New() *Resolver { - return &Resolver{ - partitions: defaultPartitions, - } -} - -var partitionRegexp = struct { - Aws *regexp.Regexp - AwsCn *regexp.Regexp - AwsIso *regexp.Regexp - AwsIsoB *regexp.Regexp - AwsIsoE *regexp.Regexp - AwsIsoF *regexp.Regexp - AwsUsGov *regexp.Regexp -}{ - - Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$"), - AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), - AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), - AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), - AwsIsoE: regexp.MustCompile("^eu\\-isoe\\-\\w+\\-\\d+$"), - AwsIsoF: regexp.MustCompile("^us\\-isof\\-\\w+\\-\\d+$"), - AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), -} - -var defaultPartitions = endpoints.Partitions{ - { - ID: "aws", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "secretsmanager.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "secretsmanager-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "secretsmanager-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "secretsmanager.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.Aws, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "af-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "af-south-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ap-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-east-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ap-northeast-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ap-northeast-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-2", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ap-northeast-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-3", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ap-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-south-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ap-south-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-south-2", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ap-southeast-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ap-southeast-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-2", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ap-southeast-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-3", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ap-southeast-4", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-4", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ca-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ca-central-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ca-central-1", - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ca-central-1", - Variant: endpoints.FIPSVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ca-central-1-fips", - }: endpoints.Endpoint{ - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "ca-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ca-west-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ca-west-1", - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ca-west-1", - Variant: endpoints.FIPSVariant, - }: {}, - endpoints.EndpointKey{ - Region: "ca-west-1-fips", - }: endpoints.Endpoint{ - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "eu-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-central-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "eu-central-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-central-2", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "eu-north-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-north-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "eu-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-south-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "eu-south-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-south-2", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "eu-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "eu-west-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-2", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "eu-west-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-3", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "il-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "il-central-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "me-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "me-central-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "me-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "me-south-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "sa-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "sa-east-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-east-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-east-1", - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-east-1", - Variant: endpoints.FIPSVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-east-1-fips", - }: endpoints.Endpoint{ - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-east-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-east-2", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-east-2", - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-east-2", - Variant: endpoints.FIPSVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-east-2-fips", - }: endpoints.Endpoint{ - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-west-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-west-1", - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-west-1", - Variant: endpoints.FIPSVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-west-1-fips", - }: endpoints.Endpoint{ - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-west-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-west-2", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-west-2", - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-west-2", - Variant: endpoints.FIPSVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-west-2-fips", - }: endpoints.Endpoint{ - Deprecated: aws.TrueTernary, - }, - }, - }, - { - ID: "aws-cn", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "secretsmanager.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "secretsmanager-fips.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "secretsmanager-fips.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "secretsmanager.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsCn, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "cn-north-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "cn-north-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "cn-northwest-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "cn-northwest-1", - Variant: endpoints.DualStackVariant, - }: {}, - }, - }, - { - ID: "aws-iso", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "secretsmanager-fips.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "secretsmanager.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIso, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-iso-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-iso-west-1", - }: endpoints.Endpoint{}, - }, - }, - { - ID: "aws-iso-b", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "secretsmanager-fips.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "secretsmanager.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoB, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-isob-east-1", - }: endpoints.Endpoint{}, - }, - }, - { - ID: "aws-iso-e", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "secretsmanager-fips.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "secretsmanager.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoE, - IsRegionalized: true, - }, - { - ID: "aws-iso-f", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "secretsmanager-fips.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "secretsmanager.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoF, - IsRegionalized: true, - }, - { - ID: "aws-us-gov", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "secretsmanager.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "secretsmanager-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "secretsmanager-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "secretsmanager.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsUsGov, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-gov-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-gov-east-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-gov-east-1", - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-gov-east-1", - Variant: endpoints.FIPSVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-gov-east-1-fips", - }: endpoints.Endpoint{ - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - Variant: endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - Variant: endpoints.FIPSVariant, - }: {}, - endpoints.EndpointKey{ - Region: "us-gov-west-1-fips", - }: endpoints.Endpoint{ - Deprecated: aws.TrueTernary, - }, - }, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/options.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/options.go deleted file mode 100644 index a8817523..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/options.go +++ /dev/null @@ -1,221 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -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/middleware" - 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 - - // Provides idempotency tokens values that will be automatically populated into - // idempotent API operations. - IdempotencyTokenProvider IdempotencyTokenProvider - - // The logger writer interface to write logging messages to. - Logger logging.Logger - - // 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 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/secretsmanager/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/serializers.go deleted file mode 100644 index 564feb18..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/serializers.go +++ /dev/null @@ -1,2012 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "bytes" - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/encoding/httpbinding" - smithyjson "github.com/aws/smithy-go/encoding/json" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "path" -) - -type awsAwsjson11_serializeOpBatchGetSecretValue struct { -} - -func (*awsAwsjson11_serializeOpBatchGetSecretValue) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpBatchGetSecretValue) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*BatchGetSecretValueInput) - _ = 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("secretsmanager.BatchGetSecretValue") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentBatchGetSecretValueInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCancelRotateSecret struct { -} - -func (*awsAwsjson11_serializeOpCancelRotateSecret) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCancelRotateSecret) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CancelRotateSecretInput) - _ = 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("secretsmanager.CancelRotateSecret") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCancelRotateSecretInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCreateSecret struct { -} - -func (*awsAwsjson11_serializeOpCreateSecret) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCreateSecret) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreateSecretInput) - _ = 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("secretsmanager.CreateSecret") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCreateSecretInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteResourcePolicy struct { -} - -func (*awsAwsjson11_serializeOpDeleteResourcePolicy) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteResourcePolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteResourcePolicyInput) - _ = 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("secretsmanager.DeleteResourcePolicy") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteResourcePolicyInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteSecret struct { -} - -func (*awsAwsjson11_serializeOpDeleteSecret) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteSecret) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteSecretInput) - _ = 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("secretsmanager.DeleteSecret") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteSecretInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeSecret struct { -} - -func (*awsAwsjson11_serializeOpDescribeSecret) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeSecret) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeSecretInput) - _ = 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("secretsmanager.DescribeSecret") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeSecretInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetRandomPassword struct { -} - -func (*awsAwsjson11_serializeOpGetRandomPassword) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetRandomPassword) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetRandomPasswordInput) - _ = 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("secretsmanager.GetRandomPassword") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetRandomPasswordInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetResourcePolicy struct { -} - -func (*awsAwsjson11_serializeOpGetResourcePolicy) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetResourcePolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetResourcePolicyInput) - _ = 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("secretsmanager.GetResourcePolicy") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetResourcePolicyInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetSecretValue struct { -} - -func (*awsAwsjson11_serializeOpGetSecretValue) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetSecretValue) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetSecretValueInput) - _ = 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("secretsmanager.GetSecretValue") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetSecretValueInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListSecrets struct { -} - -func (*awsAwsjson11_serializeOpListSecrets) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListSecrets) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListSecretsInput) - _ = 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("secretsmanager.ListSecrets") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListSecretsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListSecretVersionIds struct { -} - -func (*awsAwsjson11_serializeOpListSecretVersionIds) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListSecretVersionIds) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListSecretVersionIdsInput) - _ = 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("secretsmanager.ListSecretVersionIds") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListSecretVersionIdsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpPutResourcePolicy struct { -} - -func (*awsAwsjson11_serializeOpPutResourcePolicy) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpPutResourcePolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*PutResourcePolicyInput) - _ = 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("secretsmanager.PutResourcePolicy") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentPutResourcePolicyInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpPutSecretValue struct { -} - -func (*awsAwsjson11_serializeOpPutSecretValue) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpPutSecretValue) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*PutSecretValueInput) - _ = 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("secretsmanager.PutSecretValue") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentPutSecretValueInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpRemoveRegionsFromReplication struct { -} - -func (*awsAwsjson11_serializeOpRemoveRegionsFromReplication) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpRemoveRegionsFromReplication) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*RemoveRegionsFromReplicationInput) - _ = 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("secretsmanager.RemoveRegionsFromReplication") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentRemoveRegionsFromReplicationInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpReplicateSecretToRegions struct { -} - -func (*awsAwsjson11_serializeOpReplicateSecretToRegions) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpReplicateSecretToRegions) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ReplicateSecretToRegionsInput) - _ = 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("secretsmanager.ReplicateSecretToRegions") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentReplicateSecretToRegionsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpRestoreSecret struct { -} - -func (*awsAwsjson11_serializeOpRestoreSecret) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpRestoreSecret) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*RestoreSecretInput) - _ = 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("secretsmanager.RestoreSecret") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentRestoreSecretInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpRotateSecret struct { -} - -func (*awsAwsjson11_serializeOpRotateSecret) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpRotateSecret) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*RotateSecretInput) - _ = 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("secretsmanager.RotateSecret") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentRotateSecretInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpStopReplicationToReplica struct { -} - -func (*awsAwsjson11_serializeOpStopReplicationToReplica) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpStopReplicationToReplica) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*StopReplicationToReplicaInput) - _ = 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("secretsmanager.StopReplicationToReplica") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentStopReplicationToReplicaInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpTagResource struct { -} - -func (*awsAwsjson11_serializeOpTagResource) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpTagResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*TagResourceInput) - _ = 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("secretsmanager.TagResource") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentTagResourceInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUntagResource struct { -} - -func (*awsAwsjson11_serializeOpUntagResource) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUntagResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UntagResourceInput) - _ = 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("secretsmanager.UntagResource") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUntagResourceInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateSecret struct { -} - -func (*awsAwsjson11_serializeOpUpdateSecret) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateSecret) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateSecretInput) - _ = 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("secretsmanager.UpdateSecret") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateSecretInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateSecretVersionStage struct { -} - -func (*awsAwsjson11_serializeOpUpdateSecretVersionStage) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateSecretVersionStage) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateSecretVersionStageInput) - _ = 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("secretsmanager.UpdateSecretVersionStage") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateSecretVersionStageInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpValidateResourcePolicy struct { -} - -func (*awsAwsjson11_serializeOpValidateResourcePolicy) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpValidateResourcePolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ValidateResourcePolicyInput) - _ = 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("secretsmanager.ValidateResourcePolicy") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentValidateResourcePolicyInput(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 - - return next.HandleSerialize(ctx, in) -} -func awsAwsjson11_serializeDocumentAddReplicaRegionListType(v []types.ReplicaRegionType, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentReplicaRegionType(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentFilter(v *types.Filter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("Key") - ok.String(string(v.Key)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentFilterValuesStringList(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentFiltersListType(v []types.Filter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentFilterValuesStringList(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_serializeDocumentRemoveReplicaRegionListType(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_serializeDocumentReplicaRegionType(v *types.ReplicaRegionType, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.KmsKeyId != nil { - ok := object.Key("KmsKeyId") - ok.String(*v.KmsKeyId) - } - - if v.Region != nil { - ok := object.Key("Region") - ok.String(*v.Region) - } - - return nil -} - -func awsAwsjson11_serializeDocumentRotationRulesType(v *types.RotationRulesType, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AutomaticallyAfterDays != nil { - ok := object.Key("AutomaticallyAfterDays") - ok.Long(*v.AutomaticallyAfterDays) - } - - if v.Duration != nil { - ok := object.Key("Duration") - ok.String(*v.Duration) - } - - if v.ScheduleExpression != nil { - ok := object.Key("ScheduleExpression") - ok.String(*v.ScheduleExpression) - } - - return nil -} - -func awsAwsjson11_serializeDocumentSecretIdListType(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_serializeDocumentSecretVersionStagesType(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_serializeDocumentTag(v *types.Tag, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if v.Value != nil { - ok := object.Key("Value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeDocumentTagKeyListType(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_serializeDocumentTagListType(v []types.Tag, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentTag(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeOpDocumentBatchGetSecretValueInput(v *BatchGetSecretValueInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentFiltersListType(v.Filters, ok); err != nil { - return err - } - } - - 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.SecretIdList != nil { - ok := object.Key("SecretIdList") - if err := awsAwsjson11_serializeDocumentSecretIdListType(v.SecretIdList, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCancelRotateSecretInput(v *CancelRotateSecretInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCreateSecretInput(v *CreateSecretInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AddReplicaRegions != nil { - ok := object.Key("AddReplicaRegions") - if err := awsAwsjson11_serializeDocumentAddReplicaRegionListType(v.AddReplicaRegions, ok); err != nil { - return err - } - } - - if v.ClientRequestToken != nil { - ok := object.Key("ClientRequestToken") - ok.String(*v.ClientRequestToken) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.ForceOverwriteReplicaSecret { - ok := object.Key("ForceOverwriteReplicaSecret") - ok.Boolean(v.ForceOverwriteReplicaSecret) - } - - if v.KmsKeyId != nil { - ok := object.Key("KmsKeyId") - ok.String(*v.KmsKeyId) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.SecretBinary != nil { - ok := object.Key("SecretBinary") - ok.Base64EncodeBytes(v.SecretBinary) - } - - if v.SecretString != nil { - ok := object.Key("SecretString") - ok.String(*v.SecretString) - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagListType(v.Tags, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteResourcePolicyInput(v *DeleteResourcePolicyInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteSecretInput(v *DeleteSecretInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ForceDeleteWithoutRecovery != nil { - ok := object.Key("ForceDeleteWithoutRecovery") - ok.Boolean(*v.ForceDeleteWithoutRecovery) - } - - if v.RecoveryWindowInDays != nil { - ok := object.Key("RecoveryWindowInDays") - ok.Long(*v.RecoveryWindowInDays) - } - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeSecretInput(v *DescribeSecretInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetRandomPasswordInput(v *GetRandomPasswordInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ExcludeCharacters != nil { - ok := object.Key("ExcludeCharacters") - ok.String(*v.ExcludeCharacters) - } - - if v.ExcludeLowercase != nil { - ok := object.Key("ExcludeLowercase") - ok.Boolean(*v.ExcludeLowercase) - } - - if v.ExcludeNumbers != nil { - ok := object.Key("ExcludeNumbers") - ok.Boolean(*v.ExcludeNumbers) - } - - if v.ExcludePunctuation != nil { - ok := object.Key("ExcludePunctuation") - ok.Boolean(*v.ExcludePunctuation) - } - - if v.ExcludeUppercase != nil { - ok := object.Key("ExcludeUppercase") - ok.Boolean(*v.ExcludeUppercase) - } - - if v.IncludeSpace != nil { - ok := object.Key("IncludeSpace") - ok.Boolean(*v.IncludeSpace) - } - - if v.PasswordLength != nil { - ok := object.Key("PasswordLength") - ok.Long(*v.PasswordLength) - } - - if v.RequireEachIncludedType != nil { - ok := object.Key("RequireEachIncludedType") - ok.Boolean(*v.RequireEachIncludedType) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetResourcePolicyInput(v *GetResourcePolicyInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetSecretValueInput(v *GetSecretValueInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - if v.VersionId != nil { - ok := object.Key("VersionId") - ok.String(*v.VersionId) - } - - if v.VersionStage != nil { - ok := object.Key("VersionStage") - ok.String(*v.VersionStage) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListSecretsInput(v *ListSecretsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentFiltersListType(v.Filters, ok); err != nil { - return err - } - } - - if v.IncludePlannedDeletion != nil { - ok := object.Key("IncludePlannedDeletion") - ok.Boolean(*v.IncludePlannedDeletion) - } - - 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 len(v.SortOrder) > 0 { - ok := object.Key("SortOrder") - ok.String(string(v.SortOrder)) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListSecretVersionIdsInput(v *ListSecretVersionIdsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.IncludeDeprecated != nil { - ok := object.Key("IncludeDeprecated") - ok.Boolean(*v.IncludeDeprecated) - } - - 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.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentPutResourcePolicyInput(v *PutResourcePolicyInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.BlockPublicPolicy != nil { - ok := object.Key("BlockPublicPolicy") - ok.Boolean(*v.BlockPublicPolicy) - } - - if v.ResourcePolicy != nil { - ok := object.Key("ResourcePolicy") - ok.String(*v.ResourcePolicy) - } - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentPutSecretValueInput(v *PutSecretValueInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientRequestToken != nil { - ok := object.Key("ClientRequestToken") - ok.String(*v.ClientRequestToken) - } - - if v.SecretBinary != nil { - ok := object.Key("SecretBinary") - ok.Base64EncodeBytes(v.SecretBinary) - } - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - if v.SecretString != nil { - ok := object.Key("SecretString") - ok.String(*v.SecretString) - } - - if v.VersionStages != nil { - ok := object.Key("VersionStages") - if err := awsAwsjson11_serializeDocumentSecretVersionStagesType(v.VersionStages, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentRemoveRegionsFromReplicationInput(v *RemoveRegionsFromReplicationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.RemoveReplicaRegions != nil { - ok := object.Key("RemoveReplicaRegions") - if err := awsAwsjson11_serializeDocumentRemoveReplicaRegionListType(v.RemoveReplicaRegions, ok); err != nil { - return err - } - } - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentReplicateSecretToRegionsInput(v *ReplicateSecretToRegionsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AddReplicaRegions != nil { - ok := object.Key("AddReplicaRegions") - if err := awsAwsjson11_serializeDocumentAddReplicaRegionListType(v.AddReplicaRegions, ok); err != nil { - return err - } - } - - if v.ForceOverwriteReplicaSecret { - ok := object.Key("ForceOverwriteReplicaSecret") - ok.Boolean(v.ForceOverwriteReplicaSecret) - } - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentRestoreSecretInput(v *RestoreSecretInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentRotateSecretInput(v *RotateSecretInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientRequestToken != nil { - ok := object.Key("ClientRequestToken") - ok.String(*v.ClientRequestToken) - } - - if v.RotateImmediately != nil { - ok := object.Key("RotateImmediately") - ok.Boolean(*v.RotateImmediately) - } - - if v.RotationLambdaARN != nil { - ok := object.Key("RotationLambdaARN") - ok.String(*v.RotationLambdaARN) - } - - if v.RotationRules != nil { - ok := object.Key("RotationRules") - if err := awsAwsjson11_serializeDocumentRotationRulesType(v.RotationRules, ok); err != nil { - return err - } - } - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentStopReplicationToReplicaInput(v *StopReplicationToReplicaInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentTagResourceInput(v *TagResourceInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagListType(v.Tags, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUntagResourceInput(v *UntagResourceInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - if v.TagKeys != nil { - ok := object.Key("TagKeys") - if err := awsAwsjson11_serializeDocumentTagKeyListType(v.TagKeys, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateSecretInput(v *UpdateSecretInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientRequestToken != nil { - ok := object.Key("ClientRequestToken") - ok.String(*v.ClientRequestToken) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.KmsKeyId != nil { - ok := object.Key("KmsKeyId") - ok.String(*v.KmsKeyId) - } - - if v.SecretBinary != nil { - ok := object.Key("SecretBinary") - ok.Base64EncodeBytes(v.SecretBinary) - } - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - if v.SecretString != nil { - ok := object.Key("SecretString") - ok.String(*v.SecretString) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateSecretVersionStageInput(v *UpdateSecretVersionStageInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.MoveToVersionId != nil { - ok := object.Key("MoveToVersionId") - ok.String(*v.MoveToVersionId) - } - - if v.RemoveFromVersionId != nil { - ok := object.Key("RemoveFromVersionId") - ok.String(*v.RemoveFromVersionId) - } - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - if v.VersionStage != nil { - ok := object.Key("VersionStage") - ok.String(*v.VersionStage) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentValidateResourcePolicyInput(v *ValidateResourcePolicyInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ResourcePolicy != nil { - ok := object.Key("ResourcePolicy") - ok.String(*v.ResourcePolicy) - } - - if v.SecretId != nil { - ok := object.Key("SecretId") - ok.String(*v.SecretId) - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/types/enums.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/types/enums.go deleted file mode 100644 index 84f46d0b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/types/enums.go +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -type FilterNameStringType string - -// Enum values for FilterNameStringType -const ( - FilterNameStringTypeDescription FilterNameStringType = "description" - FilterNameStringTypeName FilterNameStringType = "name" - FilterNameStringTypeTagKey FilterNameStringType = "tag-key" - FilterNameStringTypeTagValue FilterNameStringType = "tag-value" - FilterNameStringTypePrimaryRegion FilterNameStringType = "primary-region" - FilterNameStringTypeOwningService FilterNameStringType = "owning-service" - FilterNameStringTypeAll FilterNameStringType = "all" -) - -// Values returns all known values for FilterNameStringType. 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 (FilterNameStringType) Values() []FilterNameStringType { - return []FilterNameStringType{ - "description", - "name", - "tag-key", - "tag-value", - "primary-region", - "owning-service", - "all", - } -} - -type SortOrderType string - -// Enum values for SortOrderType -const ( - SortOrderTypeAsc SortOrderType = "asc" - SortOrderTypeDesc SortOrderType = "desc" -) - -// Values returns all known values for SortOrderType. 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 (SortOrderType) Values() []SortOrderType { - return []SortOrderType{ - "asc", - "desc", - } -} - -type StatusType string - -// Enum values for StatusType -const ( - StatusTypeInSync StatusType = "InSync" - StatusTypeFailed StatusType = "Failed" - StatusTypeInProgress StatusType = "InProgress" -) - -// Values returns all known values for StatusType. 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 (StatusType) Values() []StatusType { - return []StatusType{ - "InSync", - "Failed", - "InProgress", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/types/errors.go deleted file mode 100644 index aff130bb..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/types/errors.go +++ /dev/null @@ -1,334 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - "fmt" - smithy "github.com/aws/smithy-go" -) - -// Secrets Manager can't decrypt the protected secret text using the provided KMS -// key. -type DecryptionFailure struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *DecryptionFailure) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *DecryptionFailure) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *DecryptionFailure) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "DecryptionFailure" - } - return *e.ErrorCodeOverride -} -func (e *DecryptionFailure) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Secrets Manager can't encrypt the protected secret text using the provided KMS -// key. Check that the KMS key is available, enabled, and not in an invalid state. -// For more information, see Key state: Effect on your KMS key (https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) -// . -type EncryptionFailure struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *EncryptionFailure) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *EncryptionFailure) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *EncryptionFailure) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "EncryptionFailure" - } - return *e.ErrorCodeOverride -} -func (e *EncryptionFailure) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// An error occurred on the server side. -type InternalServiceError struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InternalServiceError) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InternalServiceError) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InternalServiceError) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InternalServiceError" - } - return *e.ErrorCodeOverride -} -func (e *InternalServiceError) ErrorFault() smithy.ErrorFault { return smithy.FaultServer } - -// The NextToken value is invalid. -type InvalidNextTokenException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidNextTokenException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidNextTokenException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidNextTokenException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidNextTokenException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidNextTokenException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The parameter name or value is invalid. -type InvalidParameterException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidParameterException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidParameterException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidParameterException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidParameterException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidParameterException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// A parameter value is not valid for the current state of the resource. Possible -// causes: -// - The secret is scheduled for deletion. -// - You tried to enable rotation on a secret that doesn't already have a Lambda -// function ARN configured and you didn't include such an ARN as a parameter in -// this call. -// - The secret is managed by another service, and you must use that service to -// update it. For more information, see Secrets managed by other Amazon Web -// Services services (https://docs.aws.amazon.com/secretsmanager/latest/userguide/service-linked-secrets.html) -// . -type InvalidRequestException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidRequestException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidRequestException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidRequestException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidRequestException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidRequestException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The request failed because it would exceed one of the Secrets Manager quotas. -type LimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *LimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *LimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *LimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "LimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *LimitExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The resource policy has syntax errors. -type MalformedPolicyDocumentException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *MalformedPolicyDocumentException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *MalformedPolicyDocumentException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *MalformedPolicyDocumentException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "MalformedPolicyDocumentException" - } - return *e.ErrorCodeOverride -} -func (e *MalformedPolicyDocumentException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The request failed because you did not complete all the prerequisite steps. -type PreconditionNotMetException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *PreconditionNotMetException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *PreconditionNotMetException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *PreconditionNotMetException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "PreconditionNotMetException" - } - return *e.ErrorCodeOverride -} -func (e *PreconditionNotMetException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The BlockPublicPolicy parameter is set to true, and the resource policy did not -// prevent broad access to the secret. -type PublicPolicyException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *PublicPolicyException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *PublicPolicyException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *PublicPolicyException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "PublicPolicyException" - } - return *e.ErrorCodeOverride -} -func (e *PublicPolicyException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// A resource with the ID you requested already exists. -type ResourceExistsException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ResourceExistsException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourceExistsException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourceExistsException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourceExistsException" - } - return *e.ErrorCodeOverride -} -func (e *ResourceExistsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Secrets Manager can't find the resource that you asked for. -type ResourceNotFoundException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ResourceNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourceNotFoundException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourceNotFoundException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourceNotFoundException" - } - return *e.ErrorCodeOverride -} -func (e *ResourceNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/types/types.go deleted file mode 100644 index e04e17e7..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/types/types.go +++ /dev/null @@ -1,298 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - smithydocument "github.com/aws/smithy-go/document" - "time" -) - -// The error Secrets Manager encountered while retrieving an individual secret as -// part of BatchGetSecretValue . -type APIErrorType struct { - - // The error Secrets Manager encountered while retrieving an individual secret as - // part of BatchGetSecretValue , for example ResourceNotFoundException , - // InvalidParameterException , InvalidRequestException , DecryptionFailure , or - // AccessDeniedException . - ErrorCode *string - - // A message describing the error. - Message *string - - // The ARN or name of the secret. - SecretId *string - - noSmithyDocumentSerde -} - -// Allows you to add filters when you use the search function in Secrets Manager. -// For more information, see Find secrets in Secrets Manager (https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_search-secret.html) -// . -type Filter struct { - - // The following are keys you can use: - // - description: Prefix match, not case-sensitive. - // - name: Prefix match, case-sensitive. - // - tag-key: Prefix match, case-sensitive. - // - tag-value: Prefix match, case-sensitive. - // - primary-region: Prefix match, case-sensitive. - // - owning-service: Prefix match, case-sensitive. - // - all: Breaks the filter value string into words and then searches all - // attributes for matches. Not case-sensitive. - Key FilterNameStringType - - // The keyword to filter for. You can prefix your search value with an exclamation - // mark ( ! ) in order to perform negation filters. - Values []string - - noSmithyDocumentSerde -} - -// A custom type that specifies a Region and the KmsKeyId for a replica secret. -type ReplicaRegionType struct { - - // The ARN, key ID, or alias of the KMS key to encrypt the secret. If you don't - // include this field, Secrets Manager uses aws/secretsmanager . - KmsKeyId *string - - // A Region code. For a list of Region codes, see Name and code of Regions (https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints) - // . - Region *string - - noSmithyDocumentSerde -} - -// A replication object consisting of a RegionReplicationStatus object and -// includes a Region, KMSKeyId, status, and status message. -type ReplicationStatusType struct { - - // Can be an ARN , Key ID , or Alias . - KmsKeyId *string - - // The date that the secret was last accessed in the Region. This field is omitted - // if the secret has never been retrieved in the Region. - LastAccessedDate *time.Time - - // The Region where replication occurs. - Region *string - - // The status can be InProgress , Failed , or InSync . - Status StatusType - - // Status message such as "Secret with this name already exists in this region". - StatusMessage *string - - noSmithyDocumentSerde -} - -// A structure that defines the rotation configuration for the secret. -type RotationRulesType struct { - - // The number of days between rotations of the secret. You can use this value to - // check that your secret meets your compliance guidelines for how often secrets - // must be rotated. If you use this field to set the rotation schedule, Secrets - // Manager calculates the next rotation date based on the previous rotation. - // Manually updating the secret value by calling PutSecretValue or UpdateSecret is - // considered a valid rotation. In DescribeSecret and ListSecrets , this value is - // calculated from the rotation schedule after every successful rotation. In - // RotateSecret , you can set the rotation schedule in RotationRules with - // AutomaticallyAfterDays or ScheduleExpression , but not both. To set a rotation - // schedule in hours, use ScheduleExpression . - AutomaticallyAfterDays *int64 - - // The length of the rotation window in hours, for example 3h for a three hour - // window. Secrets Manager rotates your secret at any time during this window. The - // window must not extend into the next rotation window or the next UTC day. The - // window starts according to the ScheduleExpression . If you don't specify a - // Duration , for a ScheduleExpression in hours, the window automatically closes - // after one hour. For a ScheduleExpression in days, the window automatically - // closes at the end of the UTC day. For more information, including examples, see - // Schedule expressions in Secrets Manager rotation (https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotate-secrets_schedule.html) - // in the Secrets Manager Users Guide. - Duration *string - - // A cron() or rate() expression that defines the schedule for rotating your - // secret. Secrets Manager rotation schedules use UTC time zone. Secrets Manager - // rotates your secret any time during a rotation window. Secrets Manager rate() - // expressions represent the interval in hours or days that you want to rotate your - // secret, for example rate(12 hours) or rate(10 days) . You can rotate a secret as - // often as every four hours. If you use a rate() expression, the rotation window - // starts at midnight. For a rate in hours, the default rotation window closes - // after one hour. For a rate in days, the default rotation window closes at the - // end of the day. You can set the Duration to change the rotation window. The - // rotation window must not extend into the next UTC day or into the next rotation - // window. You can use a cron() expression to create a rotation schedule that is - // more detailed than a rotation interval. For more information, including - // examples, see Schedule expressions in Secrets Manager rotation (https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotate-secrets_schedule.html) - // in the Secrets Manager Users Guide. For a cron expression that represents a - // schedule in hours, the default rotation window closes after one hour. For a cron - // expression that represents a schedule in days, the default rotation window - // closes at the end of the day. You can set the Duration to change the rotation - // window. The rotation window must not extend into the next UTC day or into the - // next rotation window. - ScheduleExpression *string - - noSmithyDocumentSerde -} - -// A structure that contains the details about a secret. It does not include the -// encrypted SecretString and SecretBinary values. To get those values, use -// GetSecretValue (https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html) -// . -type SecretListEntry struct { - - // The Amazon Resource Name (ARN) of the secret. - ARN *string - - // The date and time when a secret was created. - CreatedDate *time.Time - - // The date and time the deletion of the secret occurred. Not present on active - // secrets. The secret can be recovered until the number of days in the recovery - // window has passed, as specified in the RecoveryWindowInDays parameter of the - // DeleteSecret (https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_DeleteSecret.html) - // operation. - DeletedDate *time.Time - - // The user-provided description of the secret. - Description *string - - // The ARN of the KMS key that Secrets Manager uses to encrypt the secret value. - // If the secret is encrypted with the Amazon Web Services managed key - // aws/secretsmanager , this field is omitted. - KmsKeyId *string - - // The date that the secret was last accessed in the Region. This field is omitted - // if the secret has never been retrieved in the Region. - LastAccessedDate *time.Time - - // The last date and time that this secret was modified in any way. - LastChangedDate *time.Time - - // The most recent date and time that the Secrets Manager rotation process was - // successfully completed. This value is null if the secret hasn't ever rotated. - LastRotatedDate *time.Time - - // The friendly name of the secret. - Name *string - - // The next rotation is scheduled to occur on or before this date. If the secret - // isn't configured for rotation or rotation has been disabled, Secrets Manager - // returns null. - NextRotationDate *time.Time - - // Returns the name of the service that created the secret. - OwningService *string - - // The Region where Secrets Manager originated the secret. - PrimaryRegion *string - - // Indicates whether automatic, scheduled rotation is enabled for this secret. - RotationEnabled *bool - - // The ARN of an Amazon Web Services Lambda function invoked by Secrets Manager to - // rotate and expire the secret either automatically per the schedule or manually - // by a call to RotateSecret (https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_RotateSecret.html) - // . - RotationLambdaARN *string - - // A structure that defines the rotation configuration for the secret. - RotationRules *RotationRulesType - - // A list of all of the currently assigned SecretVersionStage staging labels and - // the SecretVersionId attached to each one. Staging labels are used to keep track - // of the different versions during the rotation process. A version that does not - // have any SecretVersionStage is considered deprecated and subject to deletion. - // Such versions are not included in this list. - SecretVersionsToStages map[string][]string - - // The list of user-defined tags associated with the secret. To add tags to a - // secret, use TagResource (https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_TagResource.html) - // . To remove tags, use UntagResource (https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_UntagResource.html) - // . - Tags []Tag - - noSmithyDocumentSerde -} - -// A structure that contains the secret value and other details for a secret. -type SecretValueEntry struct { - - // The Amazon Resource Name (ARN) of the secret. - ARN *string - - // The date the secret was created. - CreatedDate *time.Time - - // The friendly name of the secret. - Name *string - - // The decrypted secret value, if the secret value was originally provided as - // binary data in the form of a byte array. The parameter represents the binary - // data as a base64-encoded (https://tools.ietf.org/html/rfc4648#section-4) string. - SecretBinary []byte - - // The decrypted secret value, if the secret value was originally provided as a - // string or through the Secrets Manager console. - SecretString *string - - // The unique version identifier of this version of the secret. - VersionId *string - - // A list of all of the staging labels currently attached to this version of the - // secret. - VersionStages []string - - noSmithyDocumentSerde -} - -// A structure that contains information about one version of a secret. -type SecretVersionsListEntry struct { - - // The date and time this version of the secret was created. - CreatedDate *time.Time - - // The KMS keys used to encrypt the secret version. - KmsKeyIds []string - - // The date that this version of the secret was last accessed. Note that the - // resolution of this field is at the date level and does not include the time. - LastAccessedDate *time.Time - - // The unique version identifier of this version of the secret. - VersionId *string - - // An array of staging labels that are currently associated with this version of - // the secret. - VersionStages []string - - noSmithyDocumentSerde -} - -// A structure that contains information about a tag. -type Tag struct { - - // The key identifier, or name, of the tag. - Key *string - - // The string value associated with the key of the tag. - Value *string - - noSmithyDocumentSerde -} - -// Displays errors that occurred during validation of the resource policy. -type ValidationErrorsEntry struct { - - // Checks the name of the policy. - CheckName *string - - // Displays error messages if validation encounters problems during validation of - // the resource policy. - ErrorMessage *string - - noSmithyDocumentSerde -} - -type noSmithyDocumentSerde = smithydocument.NoSerde diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/validators.go deleted file mode 100644 index 90159c6c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/secretsmanager/validators.go +++ /dev/null @@ -1,808 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package secretsmanager - -import ( - "context" - "fmt" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -type validateOpCancelRotateSecret struct { -} - -func (*validateOpCancelRotateSecret) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCancelRotateSecret) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CancelRotateSecretInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCancelRotateSecretInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCreateSecret struct { -} - -func (*validateOpCreateSecret) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateSecret) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateSecretInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateSecretInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteResourcePolicy struct { -} - -func (*validateOpDeleteResourcePolicy) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteResourcePolicy) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteResourcePolicyInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteResourcePolicyInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteSecret struct { -} - -func (*validateOpDeleteSecret) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteSecret) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteSecretInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteSecretInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeSecret struct { -} - -func (*validateOpDescribeSecret) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeSecret) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeSecretInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeSecretInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetResourcePolicy struct { -} - -func (*validateOpGetResourcePolicy) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetResourcePolicy) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetResourcePolicyInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetResourcePolicyInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetSecretValue struct { -} - -func (*validateOpGetSecretValue) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetSecretValue) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetSecretValueInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetSecretValueInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListSecretVersionIds struct { -} - -func (*validateOpListSecretVersionIds) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListSecretVersionIds) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListSecretVersionIdsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListSecretVersionIdsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpPutResourcePolicy struct { -} - -func (*validateOpPutResourcePolicy) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpPutResourcePolicy) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*PutResourcePolicyInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpPutResourcePolicyInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpPutSecretValue struct { -} - -func (*validateOpPutSecretValue) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpPutSecretValue) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*PutSecretValueInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpPutSecretValueInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpRemoveRegionsFromReplication struct { -} - -func (*validateOpRemoveRegionsFromReplication) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpRemoveRegionsFromReplication) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*RemoveRegionsFromReplicationInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpRemoveRegionsFromReplicationInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpReplicateSecretToRegions struct { -} - -func (*validateOpReplicateSecretToRegions) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpReplicateSecretToRegions) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ReplicateSecretToRegionsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpReplicateSecretToRegionsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpRestoreSecret struct { -} - -func (*validateOpRestoreSecret) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpRestoreSecret) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*RestoreSecretInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpRestoreSecretInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpRotateSecret struct { -} - -func (*validateOpRotateSecret) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpRotateSecret) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*RotateSecretInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpRotateSecretInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpStopReplicationToReplica struct { -} - -func (*validateOpStopReplicationToReplica) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpStopReplicationToReplica) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*StopReplicationToReplicaInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpStopReplicationToReplicaInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpTagResource struct { -} - -func (*validateOpTagResource) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpTagResource) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*TagResourceInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpTagResourceInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUntagResource struct { -} - -func (*validateOpUntagResource) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUntagResource) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UntagResourceInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUntagResourceInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateSecret struct { -} - -func (*validateOpUpdateSecret) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateSecret) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateSecretInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateSecretInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateSecretVersionStage struct { -} - -func (*validateOpUpdateSecretVersionStage) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateSecretVersionStage) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateSecretVersionStageInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateSecretVersionStageInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpValidateResourcePolicy struct { -} - -func (*validateOpValidateResourcePolicy) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpValidateResourcePolicy) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ValidateResourcePolicyInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpValidateResourcePolicyInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -func addOpCancelRotateSecretValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCancelRotateSecret{}, middleware.After) -} - -func addOpCreateSecretValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateSecret{}, middleware.After) -} - -func addOpDeleteResourcePolicyValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteResourcePolicy{}, middleware.After) -} - -func addOpDeleteSecretValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteSecret{}, middleware.After) -} - -func addOpDescribeSecretValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeSecret{}, middleware.After) -} - -func addOpGetResourcePolicyValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetResourcePolicy{}, middleware.After) -} - -func addOpGetSecretValueValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetSecretValue{}, middleware.After) -} - -func addOpListSecretVersionIdsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListSecretVersionIds{}, middleware.After) -} - -func addOpPutResourcePolicyValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpPutResourcePolicy{}, middleware.After) -} - -func addOpPutSecretValueValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpPutSecretValue{}, middleware.After) -} - -func addOpRemoveRegionsFromReplicationValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpRemoveRegionsFromReplication{}, middleware.After) -} - -func addOpReplicateSecretToRegionsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpReplicateSecretToRegions{}, middleware.After) -} - -func addOpRestoreSecretValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpRestoreSecret{}, middleware.After) -} - -func addOpRotateSecretValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpRotateSecret{}, middleware.After) -} - -func addOpStopReplicationToReplicaValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpStopReplicationToReplica{}, middleware.After) -} - -func addOpTagResourceValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpTagResource{}, middleware.After) -} - -func addOpUntagResourceValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUntagResource{}, middleware.After) -} - -func addOpUpdateSecretValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateSecret{}, middleware.After) -} - -func addOpUpdateSecretVersionStageValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateSecretVersionStage{}, middleware.After) -} - -func addOpValidateResourcePolicyValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpValidateResourcePolicy{}, middleware.After) -} - -func validateOpCancelRotateSecretInput(v *CancelRotateSecretInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CancelRotateSecretInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCreateSecretInput(v *CreateSecretInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateSecretInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteResourcePolicyInput(v *DeleteResourcePolicyInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteResourcePolicyInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteSecretInput(v *DeleteSecretInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteSecretInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeSecretInput(v *DescribeSecretInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeSecretInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetResourcePolicyInput(v *GetResourcePolicyInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetResourcePolicyInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetSecretValueInput(v *GetSecretValueInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetSecretValueInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListSecretVersionIdsInput(v *ListSecretVersionIdsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListSecretVersionIdsInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpPutResourcePolicyInput(v *PutResourcePolicyInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PutResourcePolicyInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if v.ResourcePolicy == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourcePolicy")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpPutSecretValueInput(v *PutSecretValueInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PutSecretValueInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpRemoveRegionsFromReplicationInput(v *RemoveRegionsFromReplicationInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RemoveRegionsFromReplicationInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if v.RemoveReplicaRegions == nil { - invalidParams.Add(smithy.NewErrParamRequired("RemoveReplicaRegions")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpReplicateSecretToRegionsInput(v *ReplicateSecretToRegionsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ReplicateSecretToRegionsInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if v.AddReplicaRegions == nil { - invalidParams.Add(smithy.NewErrParamRequired("AddReplicaRegions")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpRestoreSecretInput(v *RestoreSecretInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RestoreSecretInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpRotateSecretInput(v *RotateSecretInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RotateSecretInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpStopReplicationToReplicaInput(v *StopReplicationToReplicaInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "StopReplicationToReplicaInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpTagResourceInput(v *TagResourceInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "TagResourceInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if v.Tags == nil { - invalidParams.Add(smithy.NewErrParamRequired("Tags")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUntagResourceInput(v *UntagResourceInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UntagResourceInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if v.TagKeys == nil { - invalidParams.Add(smithy.NewErrParamRequired("TagKeys")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateSecretInput(v *UpdateSecretInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateSecretInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateSecretVersionStageInput(v *UpdateSecretVersionStageInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateSecretVersionStageInput"} - if v.SecretId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SecretId")) - } - if v.VersionStage == nil { - invalidParams.Add(smithy.NewErrParamRequired("VersionStage")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpValidateResourcePolicyInput(v *ValidateResourcePolicyInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ValidateResourcePolicyInput"} - if v.ResourcePolicy == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourcePolicy")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/CHANGELOG.md deleted file mode 100644 index 0238ce1f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/CHANGELOG.md +++ /dev/null @@ -1,454 +0,0 @@ -# v1.44.7 (2024-01-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.44.6 (2023-12-20) - -* No change notes available for this release. - -# v1.44.5 (2023-12-08) - -* **Bug Fix**: Reinstate presence of default Retryer in functional options, but still respect max attempts set therein. - -# v1.44.4 (2023-12-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.44.3 (2023-12-06) - -* **Bug Fix**: Restore pre-refactor auth behavior where all operations could technically be performed anonymously. - -# v1.44.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.44.1 (2023-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.44.0 (2023-11-29) - -* **Feature**: Expose Options() accessor on service clients. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.43.3 (2023-11-28.2) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.43.2 (2023-11-28) - -* **Bug Fix**: Respect setting RetryMaxAttempts in functional options at client construction. - -# v1.43.1 (2023-11-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.43.0 (2023-11-16) - -* **Feature**: This release introduces the ability to filter automation execution steps which have parent steps. In addition, runbook variable information is returned by GetAutomationExecution and parent step information is returned by the DescribeAutomationStepExecutions API. - -# v1.42.2 (2023-11-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.42.1 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.42.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.41.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.40.0 (2023-10-24) - -* **Feature**: **BREAKFIX**: Correct nullability and default value representation of various input fields across a large number of services. Calling code that references one or more of the affected fields will need to update usage accordingly. See [2162](https://github.com/aws/aws-sdk-go-v2/issues/2162). - -# v1.39.0 (2023-10-20) - -* **Feature**: This release introduces a new API: DeleteOpsItem. This allows deletion of an OpsItem. - -# v1.38.2 (2023-10-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.38.1 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.38.0 (2023-09-25) - -* **Feature**: This release updates the enum values for ResourceType in SSM DescribeInstanceInformation input and ConnectionStatus in GetConnectionStatus output. - -# v1.37.5 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.37.4 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.37.3 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.37.2 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.37.1 (2023-08-01) - -* No change notes available for this release. - -# v1.37.0 (2023-07-31) - -* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.36.9 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.36.8 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.36.7 (2023-06-27) - -* **Documentation**: Systems Manager doc-only update for June 2023. - -# v1.36.6 (2023-06-15) - -* No change notes available for this release. - -# v1.36.5 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.36.4 (2023-05-04) - -* No change notes available for this release. - -# v1.36.3 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.36.2 (2023-04-10) - -* No change notes available for this release. - -# v1.36.1 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.36.0 (2023-03-22) - -* **Feature**: This Patch Manager release supports creating, updating, and deleting Patch Baselines for AmazonLinux2023, AlmaLinux. - -# v1.35.7 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.35.6 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.35.5 (2023-02-22) - -* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes. -* **Documentation**: Document only update for Feb 2023 - -# v1.35.4 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.35.3 (2023-02-15) - -* **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. -* **Bug Fix**: Correct error type parsing for restJson services. - -# v1.35.2 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.35.1 (2023-01-23) - -* No change notes available for this release. - -# v1.35.0 (2023-01-05) - -* **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - -# v1.34.0 (2023-01-04) - -* **Feature**: Adding support for QuickSetup Document Type in Systems Manager - -# v1.33.4 (2022-12-21) - -* **Documentation**: Doc-only updates for December 2022. - -# v1.33.3 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.33.2 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.33.1 (2022-11-22) - -* No change notes available for this release. - -# v1.33.0 (2022-11-16) - -* **Feature**: This release adds support for cross account access in CreateOpsItem, UpdateOpsItem and GetOpsItem. It introduces new APIs to setup resource policies for SSM resources: PutResourcePolicy, GetResourcePolicies and DeleteResourcePolicy. - -# v1.32.1 (2022-11-10) - -* No change notes available for this release. - -# v1.32.0 (2022-11-07) - -* **Feature**: This release includes support for applying a CloudWatch alarm to multi account multi region Systems Manager Automation - -# v1.31.3 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.31.2 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.31.1 (2022-10-20) - -* No change notes available for this release. - -# v1.31.0 (2022-10-13) - -* **Feature**: Support of AmazonLinux2022 by Patch Manager - -# v1.30.0 (2022-09-26) - -* **Feature**: This release includes support for applying a CloudWatch alarm to Systems Manager capabilities like Automation, Run Command, State Manager, and Maintenance Windows. - -# v1.29.0 (2022-09-23) - -* **Feature**: This release adds new SSM document types ConformancePackTemplate and CloudFormation - -# v1.28.1 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.28.0 (2022-09-14) - -* **Feature**: Fixed a bug in the API client generation which caused some operation parameters to be incorrectly generated as value types instead of pointer types. The service API always required these affected parameters to be nilable. This fixes the SDK client to match the expectations of the the service API. -* **Feature**: This release adds support for Systems Manager State Manager Association tagging. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.13 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.12 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.11 (2022-08-30) - -* No change notes available for this release. - -# v1.27.10 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.9 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.8 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.7 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.6 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.5 (2022-07-27) - -* **Documentation**: Adding doc updates for OpsCenter support in Service Setting actions. - -# v1.27.4 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.3 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.2 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.1 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.27.0 (2022-05-04) - -* **Feature**: This release adds the TargetMaps parameter in SSM State Manager API. - -# v1.26.0 (2022-04-29) - -* **Feature**: Update the StartChangeRequestExecution, adding TargetMaps to the Runbook parameter - -# v1.25.1 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.0 (2022-04-19) - -* **Feature**: Added offset support for specifying the number of days to wait after the date and time specified by a CRON expression when creating SSM association. - -# v1.24.1 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.24.0 (2022-03-25) - -* **Feature**: This Patch Manager release supports creating, updating, and deleting Patch Baselines for Rocky Linux OS. - -# v1.23.1 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.23.0 (2022-03-23) - -* **Feature**: Update AddTagsToResource, ListTagsForResource, and RemoveTagsFromResource APIs to reflect the support for tagging Automation resources. Includes other minor documentation updates. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.22.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.0 (2022-02-24) - -* **Feature**: API client updated -* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.20.0 (2022-01-14) - -* **Feature**: Updated API models -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.0 (2021-12-21) - -* **Feature**: API Paginators now support specifying the initial starting token, and support stopping on empty string tokens. -* **Feature**: Updated to latest service endpoints - -# v1.17.1 (2021-12-02) - -* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514)) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.0 (2021-11-30) - -* **Feature**: API client updated - -# v1.16.0 (2021-11-19) - -* **Feature**: API client updated -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.0 (2021-11-12) - -* **Feature**: Service clients now support custom endpoints that have an initial URI path defined. -* **Feature**: Waiters now have a `WaitForOutput` method, which can be used to retrieve the output of the successful wait operation. Thank you to [Andrew Haines](https://github.com/haines) for contributing this feature. - -# v1.14.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2021-10-11) - -* **Feature**: API client updated -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2021-09-24) - -* **Feature**: API client updated - -# v1.10.1 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.1 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2021-08-12) - -* **Feature**: API client updated - -# v1.8.1 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2021-07-15) - -* **Feature**: Updated service model to latest version. -* **Documentation**: Updated service model to latest revision. -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.2 (2021-06-04) - -* **Documentation**: Updated service client to latest API model. - -# v1.6.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Feature**: Updated to latest service API model. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/service/ssm/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_client.go deleted file mode 100644 index 973f468d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_client.go +++ /dev/null @@ -1,492 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - cryptorand "crypto/rand" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/defaults" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "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" - smithy "github.com/aws/smithy-go" - smithydocument "github.com/aws/smithy-go/document" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyrand "github.com/aws/smithy-go/rand" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net" - "net/http" - "time" -) - -const ServiceID = "SSM" -const ServiceAPIVersion = "2014-11-06" - -// Client provides the API client to make operations call for Amazon Simple -// Systems Manager (SSM). -type Client struct { - options Options -} - -// 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() - - resolveDefaultLogger(&options) - - setResolvedDefaultsMode(&options) - - resolveRetryer(&options) - - resolveHTTPClient(&options) - - resolveHTTPSignerV4(&options) - - resolveIdempotencyTokenProvider(&options) - - resolveEndpointResolverV2(&options) - - resolveAuthSchemeResolver(&options) - - for _, fn := range optFns { - fn(&options) - } - - finalizeRetryMaxAttempts(&options) - - ignoreAnonymousAuth(&options) - - wrapWithAnonymousAuth(&options) - - resolveAuthSchemes(&options) - - client := &Client{ - options: options, - } - - return client -} - -// 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) { - ctx = middleware.ClearStackValues(ctx) - stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) - options := c.options.Copy() - - for _, fn := range optFns { - fn(&options) - } - - finalizeOperationRetryMaxAttempts(&options, *c) - - finalizeClientEndpointResolverOptions(&options) - - for _, fn := range stackFns { - if err := fn(stack, options); err != nil { - return nil, metadata, err - } - } - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, metadata, err - } - } - - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) - if err != nil { - err = &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: err, - } - } - 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{}, "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 { - LegacyResolver EndpointResolver -} - -func (*legacyEndpointContextSetter) ID() string { - return "legacyEndpointContextSetter" -} - -func (m *legacyEndpointContextSetter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.LegacyResolver != nil { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true) - } - - return next.HandleInitialize(ctx, in) - -} -func addlegacyEndpointContextSetter(stack *middleware.Stack, o Options) error { - return stack.Initialize.Add(&legacyEndpointContextSetter{ - LegacyResolver: o.EndpointResolver, - }, middleware.Before) -} - -func resolveDefaultLogger(o *Options) { - if o.Logger != nil { - return - } - o.Logger = logging.Nop{} -} - -func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { - return middleware.AddSetLoggerMiddleware(stack, o.Logger) -} - -func setResolvedDefaultsMode(o *Options) { - if len(o.resolvedDefaultsMode) > 0 { - return - } - - var mode aws.DefaultsMode - mode.SetFromString(string(o.DefaultsMode)) - - if mode == aws.DefaultsModeAuto { - mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment) - } - - o.resolvedDefaultsMode = mode -} - -// NewFromConfig returns a new client from the provided config. -func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { - opts := Options{ - Region: cfg.Region, - DefaultsMode: cfg.DefaultsMode, - RuntimeEnvironment: cfg.RuntimeEnvironment, - HTTPClient: cfg.HTTPClient, - Credentials: cfg.Credentials, - APIOptions: cfg.APIOptions, - Logger: cfg.Logger, - ClientLogMode: cfg.ClientLogMode, - AppID: cfg.AppID, - } - resolveAWSRetryerProvider(cfg, &opts) - resolveAWSRetryMaxAttempts(cfg, &opts) - resolveAWSRetryMode(cfg, &opts) - resolveAWSEndpointResolver(cfg, &opts) - resolveUseDualStackEndpoint(cfg, &opts) - resolveUseFIPSEndpoint(cfg, &opts) - resolveBaseEndpoint(cfg, &opts) - return New(opts, optFns...) -} - -func resolveHTTPClient(o *Options) { - var buildable *awshttp.BuildableClient - - if o.HTTPClient != nil { - var ok bool - buildable, ok = o.HTTPClient.(*awshttp.BuildableClient) - if !ok { - return - } - } else { - buildable = awshttp.NewBuildableClient() - } - - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) { - if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok { - dialer.Timeout = dialerTimeout - } - }) - - buildable = buildable.WithTransportOptions(func(transport *http.Transport) { - if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok { - transport.TLSHandshakeTimeout = tlsHandshakeTimeout - } - }) - } - - o.HTTPClient = buildable -} - -func resolveRetryer(o *Options) { - if o.Retryer != nil { - return - } - - if len(o.RetryMode) == 0 { - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - o.RetryMode = modeConfig.RetryMode - } - } - if len(o.RetryMode) == 0 { - o.RetryMode = aws.RetryModeStandard - } - - var standardOptions []func(*retry.StandardOptions) - if v := o.RetryMaxAttempts; v != 0 { - standardOptions = append(standardOptions, func(so *retry.StandardOptions) { - so.MaxAttempts = v - }) - } - - switch o.RetryMode { - case aws.RetryModeAdaptive: - var adaptiveOptions []func(*retry.AdaptiveModeOptions) - if len(standardOptions) != 0 { - adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) { - ao.StandardOptions = append(ao.StandardOptions, standardOptions...) - }) - } - o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...) - - default: - o.Retryer = retry.NewStandard(standardOptions...) - } -} - -func resolveAWSRetryerProvider(cfg aws.Config, o *Options) { - if cfg.Retryer == nil { - return - } - o.Retryer = cfg.Retryer() -} - -func resolveAWSRetryMode(cfg aws.Config, o *Options) { - if len(cfg.RetryMode) == 0 { - return - } - o.RetryMode = cfg.RetryMode -} -func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { - if cfg.RetryMaxAttempts == 0 { - return - } - o.RetryMaxAttempts = cfg.RetryMaxAttempts -} - -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 - } - - o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) -} - -func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { - if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil { - return - } - o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions) -} - -func addClientUserAgent(stack *middleware.Stack, options Options) error { - if err := awsmiddleware.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "ssm", goModuleVersion)(stack); err != nil { - return err - } - - if len(options.AppID) > 0 { - return awsmiddleware.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID)(stack) - } - - return nil -} - -type HTTPSignerV4 interface { - SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error -} - -func resolveHTTPSignerV4(o *Options) { - if o.HTTPSignerV4 != nil { - return - } - o.HTTPSignerV4 = newDefaultV4Signer(*o) -} - -func newDefaultV4Signer(o Options) *v4.Signer { - return v4.NewSigner(func(so *v4.SignerOptions) { - so.Logger = o.Logger - so.LogSigning = o.ClientLogMode.IsSigning() - }) -} - -func resolveIdempotencyTokenProvider(o *Options) { - if o.IdempotencyTokenProvider != nil { - return - } - o.IdempotencyTokenProvider = smithyrand.NewUUIDIdempotencyToken(cryptorand.Reader) -} - -func addRetryMiddlewares(stack *middleware.Stack, o Options) error { - mo := retry.AddRetryMiddlewaresOptions{ - Retryer: o.Retryer, - LogRetryAttempts: o.ClientLogMode.IsRetries(), - } - return retry.AddRetryMiddlewares(stack, mo) -} - -// resolves dual-stack endpoint configuration -func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseDualStackEndpoint = value - } - return nil -} - -// resolves FIPS endpoint configuration -func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseFIPSEndpoint = value - } - return nil -} - -// IdempotencyTokenProvider interface for providing idempotency token -type IdempotencyTokenProvider interface { - GetIdempotencyToken() (string, error) -} - -func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - return awsmiddleware.AddRequestIDRetrieverMiddleware(stack) -} - -func addResponseErrorMiddleware(stack *middleware.Stack) error { - return awshttp.AddResponseErrorMiddleware(stack) -} - -func addRequestResponseLogging(stack *middleware.Stack, o Options) error { - return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ - LogRequest: o.ClientLogMode.IsRequest(), - LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(), - LogResponse: o.ClientLogMode.IsResponse(), - LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(), - }, middleware.After) -} - -type disableHTTPSMiddleware struct { - DisableHTTPS bool -} - -func (*disableHTTPSMiddleware) ID() string { - return "disableHTTPS" -} - -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.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) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_AddTagsToResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_AddTagsToResource.go deleted file mode 100644 index e1b972cf..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_AddTagsToResource.go +++ /dev/null @@ -1,183 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Adds or overwrites one or more tags for the specified resource. Tags are -// metadata that you can assign to your automations, documents, managed nodes, -// maintenance windows, Parameter Store parameters, and patch baselines. Tags -// enable you to categorize your resources in different ways, for example, by -// purpose, owner, or environment. Each tag consists of a key and an optional -// value, both of which you define. For example, you could define a set of tags for -// your account's managed nodes that helps you track each node's owner and stack -// level. For example: -// - Key=Owner,Value=DbAdmin -// - Key=Owner,Value=SysAdmin -// - Key=Owner,Value=Dev -// - Key=Stack,Value=Production -// - Key=Stack,Value=Pre-Production -// - Key=Stack,Value=Test -// -// Most resources can have a maximum of 50 tags. Automations can have a maximum of -// 5 tags. We recommend that you devise a set of tag keys that meets your needs for -// each resource type. Using a consistent set of tag keys makes it easier for you -// to manage your resources. You can search and filter the resources based on the -// tags you add. Tags don't have any semantic meaning to and are interpreted -// strictly as a string of characters. For more information about using tags with -// Amazon Elastic Compute Cloud (Amazon EC2) instances, see Tagging your Amazon -// EC2 resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) -// in the Amazon EC2 User Guide. -func (c *Client) AddTagsToResource(ctx context.Context, params *AddTagsToResourceInput, optFns ...func(*Options)) (*AddTagsToResourceOutput, error) { - if params == nil { - params = &AddTagsToResourceInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "AddTagsToResource", params, optFns, c.addOperationAddTagsToResourceMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*AddTagsToResourceOutput) - out.ResultMetadata = metadata - return out, nil -} - -type AddTagsToResourceInput struct { - - // The resource ID you want to tag. Use the ID of the resource. Here are some - // examples: MaintenanceWindow : mw-012345abcde PatchBaseline : pb-012345abcde - // Automation : example-c160-4567-8519-012345abcde OpsMetadata object: ResourceID - // for tagging is created from the Amazon Resource Name (ARN) for the object. - // Specifically, ResourceID is created from the strings that come after the word - // opsmetadata in the ARN. For example, an OpsMetadata object with an ARN of - // arn:aws:ssm:us-east-2:1234567890:opsmetadata/aws/ssm/MyGroup/appmanager has a - // ResourceID of either aws/ssm/MyGroup/appmanager or /aws/ssm/MyGroup/appmanager . - // For the Document and Parameter values, use the name of the resource. If you're - // tagging a shared document, you must use the full ARN of the document. - // ManagedInstance : mi-012345abcde The ManagedInstance type for this API - // operation is only for on-premises managed nodes. You must specify the name of - // the managed node in the following format: mi-ID_number . For example, - // mi-1a2b3c4d5e6f . - // - // This member is required. - ResourceId *string - - // Specifies the type of resource you are tagging. The ManagedInstance type for - // this API operation is for on-premises managed nodes. You must specify the name - // of the managed node in the following format: mi-ID_number . For example, - // mi-1a2b3c4d5e6f . - // - // This member is required. - ResourceType types.ResourceTypeForTagging - - // One or more tags. The value parameter is required. Don't enter personally - // identifiable information in this field. - // - // This member is required. - Tags []types.Tag - - noSmithyDocumentSerde -} - -type AddTagsToResourceOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationAddTagsToResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpAddTagsToResource{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAddTagsToResource{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "AddTagsToResource"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpAddTagsToResourceValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAddTagsToResource(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opAddTagsToResource(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "AddTagsToResource", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_AssociateOpsItemRelatedItem.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_AssociateOpsItemRelatedItem.go deleted file mode 100644 index 90104d79..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_AssociateOpsItemRelatedItem.go +++ /dev/null @@ -1,159 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Associates a related item to a Systems Manager OpsCenter OpsItem. For example, -// you can associate an Incident Manager incident or analysis with an OpsItem. -// Incident Manager and OpsCenter are capabilities of Amazon Web Services Systems -// Manager. -func (c *Client) AssociateOpsItemRelatedItem(ctx context.Context, params *AssociateOpsItemRelatedItemInput, optFns ...func(*Options)) (*AssociateOpsItemRelatedItemOutput, error) { - if params == nil { - params = &AssociateOpsItemRelatedItemInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "AssociateOpsItemRelatedItem", params, optFns, c.addOperationAssociateOpsItemRelatedItemMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*AssociateOpsItemRelatedItemOutput) - out.ResultMetadata = metadata - return out, nil -} - -type AssociateOpsItemRelatedItemInput struct { - - // The type of association that you want to create between an OpsItem and a - // resource. OpsCenter supports IsParentOf and RelatesTo association types. - // - // This member is required. - AssociationType *string - - // The ID of the OpsItem to which you want to associate a resource as a related - // item. - // - // This member is required. - OpsItemId *string - - // The type of resource that you want to associate with an OpsItem. OpsCenter - // supports the following types: AWS::SSMIncidents::IncidentRecord : an Incident - // Manager incident. AWS::SSM::Document : a Systems Manager (SSM) document. - // - // This member is required. - ResourceType *string - - // The Amazon Resource Name (ARN) of the Amazon Web Services resource that you - // want to associate with the OpsItem. - // - // This member is required. - ResourceUri *string - - noSmithyDocumentSerde -} - -type AssociateOpsItemRelatedItemOutput struct { - - // The association ID. - AssociationId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationAssociateOpsItemRelatedItemMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpAssociateOpsItemRelatedItem{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpAssociateOpsItemRelatedItem{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "AssociateOpsItemRelatedItem"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpAssociateOpsItemRelatedItemValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAssociateOpsItemRelatedItem(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opAssociateOpsItemRelatedItem(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "AssociateOpsItemRelatedItem", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CancelCommand.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CancelCommand.go deleted file mode 100644 index 278ec729..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CancelCommand.go +++ /dev/null @@ -1,141 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Attempts to cancel the command specified by the Command ID. There is no -// guarantee that the command will be terminated and the underlying process -// stopped. -func (c *Client) CancelCommand(ctx context.Context, params *CancelCommandInput, optFns ...func(*Options)) (*CancelCommandOutput, error) { - if params == nil { - params = &CancelCommandInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CancelCommand", params, optFns, c.addOperationCancelCommandMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CancelCommandOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CancelCommandInput struct { - - // The ID of the command you want to cancel. - // - // This member is required. - CommandId *string - - // (Optional) A list of managed node IDs on which you want to cancel the command. - // If not provided, the command is canceled on every node on which it was - // requested. - InstanceIds []string - - noSmithyDocumentSerde -} - -// Whether or not the command was successfully canceled. There is no guarantee -// that a request can be canceled. -type CancelCommandOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCancelCommandMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCancelCommand{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCancelCommand{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CancelCommand"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCancelCommandValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCancelCommand(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCancelCommand(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CancelCommand", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CancelMaintenanceWindowExecution.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CancelMaintenanceWindowExecution.go deleted file mode 100644 index 0b887cbf..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CancelMaintenanceWindowExecution.go +++ /dev/null @@ -1,138 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Stops a maintenance window execution that is already in progress and cancels -// any tasks in the window that haven't already starting running. Tasks already in -// progress will continue to completion. -func (c *Client) CancelMaintenanceWindowExecution(ctx context.Context, params *CancelMaintenanceWindowExecutionInput, optFns ...func(*Options)) (*CancelMaintenanceWindowExecutionOutput, error) { - if params == nil { - params = &CancelMaintenanceWindowExecutionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CancelMaintenanceWindowExecution", params, optFns, c.addOperationCancelMaintenanceWindowExecutionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CancelMaintenanceWindowExecutionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CancelMaintenanceWindowExecutionInput struct { - - // The ID of the maintenance window execution to stop. - // - // This member is required. - WindowExecutionId *string - - noSmithyDocumentSerde -} - -type CancelMaintenanceWindowExecutionOutput struct { - - // The ID of the maintenance window execution that has been stopped. - WindowExecutionId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCancelMaintenanceWindowExecutionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCancelMaintenanceWindowExecution{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCancelMaintenanceWindowExecution{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CancelMaintenanceWindowExecution"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCancelMaintenanceWindowExecutionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCancelMaintenanceWindowExecution(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCancelMaintenanceWindowExecution(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CancelMaintenanceWindowExecution", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateActivation.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateActivation.go deleted file mode 100644 index 9aad0ee4..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateActivation.go +++ /dev/null @@ -1,200 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Generates an activation code and activation ID you can use to register your -// on-premises servers, edge devices, or virtual machine (VM) with Amazon Web -// Services Systems Manager. Registering these machines with Systems Manager makes -// it possible to manage them using Systems Manager capabilities. You use the -// activation code and ID when installing SSM Agent on machines in your hybrid -// environment. For more information about requirements for managing on-premises -// machines using Systems Manager, see Setting up Amazon Web Services Systems -// Manager for hybrid environments (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances.html) -// in the Amazon Web Services Systems Manager User Guide. Amazon Elastic Compute -// Cloud (Amazon EC2) instances, edge devices, and on-premises servers and VMs that -// are configured for Systems Manager are all called managed nodes. -func (c *Client) CreateActivation(ctx context.Context, params *CreateActivationInput, optFns ...func(*Options)) (*CreateActivationOutput, error) { - if params == nil { - params = &CreateActivationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateActivation", params, optFns, c.addOperationCreateActivationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateActivationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateActivationInput struct { - - // The name of the Identity and Access Management (IAM) role that you want to - // assign to the managed node. This IAM role must provide AssumeRole permissions - // for the Amazon Web Services Systems Manager service principal ssm.amazonaws.com - // . For more information, see Create an IAM service role for a hybrid environment (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-service-role.html) - // in the Amazon Web Services Systems Manager User Guide. You can't specify an IAM - // service-linked role for this parameter. You must create a unique role. - // - // This member is required. - IamRole *string - - // The name of the registered, managed node as it will appear in the Amazon Web - // Services Systems Manager console or when you use the Amazon Web Services command - // line tools to list Systems Manager resources. Don't enter personally - // identifiable information in this field. - DefaultInstanceName *string - - // A user-defined description of the resource that you want to register with - // Systems Manager. Don't enter personally identifiable information in this field. - Description *string - - // The date by which this activation request should expire, in timestamp format, - // such as "2021-07-07T00:00:00". You can specify a date up to 30 days in advance. - // If you don't provide an expiration date, the activation code expires in 24 - // hours. - ExpirationDate *time.Time - - // Specify the maximum number of managed nodes you want to register. The default - // value is 1 . - RegistrationLimit *int32 - - // Reserved for internal use. - RegistrationMetadata []types.RegistrationMetadataItem - - // Optional metadata that you assign to a resource. Tags enable you to categorize - // a resource in different ways, such as by purpose, owner, or environment. For - // example, you might want to tag an activation to identify which servers or - // virtual machines (VMs) in your on-premises environment you intend to activate. - // In this case, you could specify the following key-value pairs: - // - Key=OS,Value=Windows - // - Key=Environment,Value=Production - // When you install SSM Agent on your on-premises servers and VMs, you specify an - // activation ID and code. When you specify the activation ID and code, tags - // assigned to the activation are automatically applied to the on-premises servers - // or VMs. You can't add tags to or delete tags from an existing activation. You - // can tag your on-premises servers, edge devices, and VMs after they connect to - // Systems Manager for the first time and are assigned a managed node ID. This - // means they are listed in the Amazon Web Services Systems Manager console with an - // ID that is prefixed with "mi-". For information about how to add tags to your - // managed nodes, see AddTagsToResource . For information about how to remove tags - // from your managed nodes, see RemoveTagsFromResource . - Tags []types.Tag - - noSmithyDocumentSerde -} - -type CreateActivationOutput struct { - - // The code the system generates when it processes the activation. The activation - // code functions like a password to validate the activation ID. - ActivationCode *string - - // The ID number generated by the system when it processed the activation. The - // activation ID functions like a user name. - ActivationId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateActivationMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateActivation{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateActivation{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreateActivation"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCreateActivationValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateActivation(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCreateActivation(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateActivation", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateAssociation.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateAssociation.go deleted file mode 100644 index 4468b485..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateAssociation.go +++ /dev/null @@ -1,286 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// A State Manager association defines the state that you want to maintain on your -// managed nodes. For example, an association can specify that anti-virus software -// must be installed and running on your managed nodes, or that certain ports must -// be closed. For static targets, the association specifies a schedule for when the -// configuration is reapplied. For dynamic targets, such as an Amazon Web Services -// resource group or an Amazon Web Services autoscaling group, State Manager, a -// capability of Amazon Web Services Systems Manager applies the configuration when -// new managed nodes are added to the group. The association also specifies actions -// to take when applying the configuration. For example, an association for -// anti-virus software might run once a day. If the software isn't installed, then -// State Manager installs it. If the software is installed, but the service isn't -// running, then the association might instruct State Manager to start the service. -func (c *Client) CreateAssociation(ctx context.Context, params *CreateAssociationInput, optFns ...func(*Options)) (*CreateAssociationOutput, error) { - if params == nil { - params = &CreateAssociationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateAssociation", params, optFns, c.addOperationCreateAssociationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateAssociationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateAssociationInput struct { - - // The name of the SSM Command document or Automation runbook that contains the - // configuration information for the managed node. You can specify Amazon Web - // Services-predefined documents, documents you created, or a document that is - // shared with you from another Amazon Web Services account. For Systems Manager - // documents (SSM documents) that are shared with you from other Amazon Web - // Services accounts, you must specify the complete SSM document ARN, in the - // following format: arn:partition:ssm:region:account-id:document/document-name - // For example: arn:aws:ssm:us-east-2:12345678912:document/My-Shared-Document For - // Amazon Web Services-predefined documents and SSM documents you created in your - // account, you only need to specify the document name. For example, - // AWS-ApplyPatchBaseline or My-Document . - // - // This member is required. - Name *string - - // The details for the CloudWatch alarm you want to apply to an automation or - // command. - AlarmConfiguration *types.AlarmConfiguration - - // By default, when you create a new association, the system runs it immediately - // after it is created and then according to the schedule you specified. Specify - // this option if you don't want an association to run immediately after you create - // it. This parameter isn't supported for rate expressions. - ApplyOnlyAtCronInterval bool - - // Specify a descriptive name for the association. - AssociationName *string - - // Choose the parameter that will define how your automation will branch out. This - // target is required for associations that use an Automation runbook and target - // resources by using rate controls. Automation is a capability of Amazon Web - // Services Systems Manager. - AutomationTargetParameterName *string - - // The names or Amazon Resource Names (ARNs) of the Change Calendar type documents - // you want to gate your associations under. The associations only run when that - // change calendar is open. For more information, see Amazon Web Services Systems - // Manager Change Calendar (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-change-calendar) - // . - CalendarNames []string - - // The severity level to assign to the association. - ComplianceSeverity types.AssociationComplianceSeverity - - // The document version you want to associate with the target(s). Can be a - // specific version or the default version. State Manager doesn't support running - // associations that use a new version of a document if that document is shared - // from another account. State Manager always runs the default version of a - // document if shared from another account, even though the Systems Manager console - // shows that a new version was processed. If you want to run an association using - // a new version of a document shared form another account, you must set the - // document version to default . - DocumentVersion *string - - // The managed node ID. InstanceId has been deprecated. To specify a managed node - // ID for an association, use the Targets parameter. Requests that include the - // parameter InstanceID with Systems Manager documents (SSM documents) that use - // schema version 2.0 or later will fail. In addition, if you use the parameter - // InstanceId , you can't use the parameters AssociationName , DocumentVersion , - // MaxErrors , MaxConcurrency , OutputLocation , or ScheduleExpression . To use - // these parameters, you must use the Targets parameter. - InstanceId *string - - // The maximum number of targets allowed to run the association at the same time. - // You can specify a number, for example 10, or a percentage of the target set, for - // example 10%. The default value is 100%, which means all targets run the - // association at the same time. If a new managed node starts and attempts to run - // an association while Systems Manager is running MaxConcurrency associations, - // the association is allowed to run. During the next association interval, the new - // managed node will process its association within the limit specified for - // MaxConcurrency . - MaxConcurrency *string - - // The number of errors that are allowed before the system stops sending requests - // to run the association on additional targets. You can specify either an absolute - // number of errors, for example 10, or a percentage of the target set, for example - // 10%. If you specify 3, for example, the system stops sending requests when the - // fourth error is received. If you specify 0, then the system stops sending - // requests after the first error is returned. If you run an association on 50 - // managed nodes and set MaxError to 10%, then the system stops sending the - // request when the sixth error is received. Executions that are already running an - // association when MaxErrors is reached are allowed to complete, but some of - // these executions may fail as well. If you need to ensure that there won't be - // more than max-errors failed executions, set MaxConcurrency to 1 so that - // executions proceed one at a time. - MaxErrors *string - - // An Amazon Simple Storage Service (Amazon S3) bucket where you want to store the - // output details of the request. - OutputLocation *types.InstanceAssociationOutputLocation - - // The parameters for the runtime configuration of the document. - Parameters map[string][]string - - // A cron expression when the association will be applied to the target(s). - ScheduleExpression *string - - // Number of days to wait after the scheduled day to run an association. For - // example, if you specified a cron schedule of cron(0 0 ? * THU#2 *) , you could - // specify an offset of 3 to run the association each Sunday after the second - // Thursday of the month. For more information about cron schedules for - // associations, see Reference: Cron and rate expressions for Systems Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/reference-cron-and-rate-expressions.html) - // in the Amazon Web Services Systems Manager User Guide. To use offsets, you must - // specify the ApplyOnlyAtCronInterval parameter. This option tells the system not - // to run an association immediately after you create it. - ScheduleOffset *int32 - - // The mode for generating association compliance. You can specify AUTO or MANUAL . - // In AUTO mode, the system uses the status of the association execution to - // determine the compliance status. If the association execution runs successfully, - // then the association is COMPLIANT . If the association execution doesn't run - // successfully, the association is NON-COMPLIANT . In MANUAL mode, you must - // specify the AssociationId as a parameter for the PutComplianceItems API - // operation. In this case, compliance data isn't managed by State Manager. It is - // managed by your direct call to the PutComplianceItems API operation. By - // default, all associations use AUTO mode. - SyncCompliance types.AssociationSyncCompliance - - // Adds or overwrites one or more tags for a State Manager association. Tags are - // metadata that you can assign to your Amazon Web Services resources. Tags enable - // you to categorize your resources in different ways, for example, by purpose, - // owner, or environment. Each tag consists of a key and an optional value, both of - // which you define. - Tags []types.Tag - - // A location is a combination of Amazon Web Services Regions and Amazon Web - // Services accounts where you want to run the association. Use this action to - // create an association in multiple Regions and multiple accounts. - TargetLocations []types.TargetLocation - - // A key-value mapping of document parameters to target resources. Both Targets - // and TargetMaps can't be specified together. - TargetMaps []map[string][]string - - // The targets for the association. You can target managed nodes by using tags, - // Amazon Web Services resource groups, all managed nodes in an Amazon Web Services - // account, or individual managed node IDs. You can target all managed nodes in an - // Amazon Web Services account by specifying the InstanceIds key with a value of * - // . For more information about choosing targets for an association, see Using - // targets and rate controls with State Manager associations (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-state-manager-targets-and-rate-controls.html) - // in the Amazon Web Services Systems Manager User Guide. - Targets []types.Target - - noSmithyDocumentSerde -} - -type CreateAssociationOutput struct { - - // Information about the association. - AssociationDescription *types.AssociationDescription - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateAssociationMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateAssociation{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateAssociation{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreateAssociation"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCreateAssociationValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateAssociation(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCreateAssociation(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateAssociation", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateAssociationBatch.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateAssociationBatch.go deleted file mode 100644 index 9d42a187..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateAssociationBatch.go +++ /dev/null @@ -1,146 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Associates the specified Amazon Web Services Systems Manager document (SSM -// document) with the specified managed nodes or targets. When you associate a -// document with one or more managed nodes using IDs or tags, Amazon Web Services -// Systems Manager Agent (SSM Agent) running on the managed node processes the -// document and configures the node as specified. If you associate a document with -// a managed node that already has an associated document, the system returns the -// AssociationAlreadyExists exception. -func (c *Client) CreateAssociationBatch(ctx context.Context, params *CreateAssociationBatchInput, optFns ...func(*Options)) (*CreateAssociationBatchOutput, error) { - if params == nil { - params = &CreateAssociationBatchInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateAssociationBatch", params, optFns, c.addOperationCreateAssociationBatchMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateAssociationBatchOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateAssociationBatchInput struct { - - // One or more associations. - // - // This member is required. - Entries []types.CreateAssociationBatchRequestEntry - - noSmithyDocumentSerde -} - -type CreateAssociationBatchOutput struct { - - // Information about the associations that failed. - Failed []types.FailedCreateAssociation - - // Information about the associations that succeeded. - Successful []types.AssociationDescription - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateAssociationBatchMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateAssociationBatch{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateAssociationBatch{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreateAssociationBatch"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCreateAssociationBatchValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateAssociationBatch(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCreateAssociationBatch(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateAssociationBatch", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateDocument.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateDocument.go deleted file mode 100644 index ef56324e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateDocument.go +++ /dev/null @@ -1,208 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Creates a Amazon Web Services Systems Manager (SSM document). An SSM document -// defines the actions that Systems Manager performs on your managed nodes. For -// more information about SSM documents, including information about supported -// schemas, features, and syntax, see Amazon Web Services Systems Manager Documents (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-ssm-docs.html) -// in the Amazon Web Services Systems Manager User Guide. -func (c *Client) CreateDocument(ctx context.Context, params *CreateDocumentInput, optFns ...func(*Options)) (*CreateDocumentOutput, error) { - if params == nil { - params = &CreateDocumentInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateDocument", params, optFns, c.addOperationCreateDocumentMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateDocumentOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateDocumentInput struct { - - // The content for the new SSM document in JSON or YAML format. The content of the - // document must not exceed 64KB. This quota also includes the content specified - // for input parameters at runtime. We recommend storing the contents for your new - // document in an external JSON or YAML file and referencing the file in a command. - // For examples, see the following topics in the Amazon Web Services Systems - // Manager User Guide. - // - Create an SSM document (Amazon Web Services API) (https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-document-api.html) - // - Create an SSM document (Amazon Web Services CLI) (https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-document-cli.html) - // - Create an SSM document (API) (https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-document-api.html) - // - // This member is required. - Content *string - - // A name for the SSM document. You can't use the following strings as document - // name prefixes. These are reserved by Amazon Web Services for use as document - // name prefixes: - // - aws - // - amazon - // - amzn - // - // This member is required. - Name *string - - // A list of key-value pairs that describe attachments to a version of a document. - Attachments []types.AttachmentsSource - - // An optional field where you can specify a friendly name for the SSM document. - // This value can differ for each version of the document. You can update this - // value at a later time using the UpdateDocument operation. - DisplayName *string - - // Specify the document format for the request. The document format can be JSON, - // YAML, or TEXT. JSON is the default format. - DocumentFormat types.DocumentFormat - - // The type of document to create. The DeploymentStrategy document type is an - // internal-use-only document type reserved for AppConfig. - DocumentType types.DocumentType - - // A list of SSM documents required by a document. This parameter is used - // exclusively by AppConfig. When a user creates an AppConfig configuration in an - // SSM document, the user must also specify a required document for validation - // purposes. In this case, an ApplicationConfiguration document requires an - // ApplicationConfigurationSchema document for validation purposes. For more - // information, see What is AppConfig? (https://docs.aws.amazon.com/appconfig/latest/userguide/what-is-appconfig.html) - // in the AppConfig User Guide. - Requires []types.DocumentRequires - - // Optional metadata that you assign to a resource. Tags enable you to categorize - // a resource in different ways, such as by purpose, owner, or environment. For - // example, you might want to tag an SSM document to identify the types of targets - // or the environment where it will run. In this case, you could specify the - // following key-value pairs: - // - Key=OS,Value=Windows - // - Key=Environment,Value=Production - // To add tags to an existing SSM document, use the AddTagsToResource operation. - Tags []types.Tag - - // Specify a target type to define the kinds of resources the document can run on. - // For example, to run a document on EC2 instances, specify the following value: - // /AWS::EC2::Instance . If you specify a value of '/' the document can run on all - // types of resources. If you don't specify a value, the document can't run on any - // resources. For a list of valid resource types, see Amazon Web Services resource - // and property types reference (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) - // in the CloudFormation User Guide. - TargetType *string - - // An optional field specifying the version of the artifact you are creating with - // the document. For example, Release12.1 . This value is unique across all - // versions of a document, and can't be changed. - VersionName *string - - noSmithyDocumentSerde -} - -type CreateDocumentOutput struct { - - // Information about the SSM document. - DocumentDescription *types.DocumentDescription - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateDocumentMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateDocument{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateDocument{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreateDocument"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCreateDocumentValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateDocument(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCreateDocument(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateDocument", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateMaintenanceWindow.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateMaintenanceWindow.go deleted file mode 100644 index ba9b5296..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateMaintenanceWindow.go +++ /dev/null @@ -1,247 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Creates a new maintenance window. The value you specify for Duration determines -// the specific end time for the maintenance window based on the time it begins. No -// maintenance window tasks are permitted to start after the resulting endtime -// minus the number of hours you specify for Cutoff . For example, if the -// maintenance window starts at 3 PM, the duration is three hours, and the value -// you specify for Cutoff is one hour, no maintenance window tasks can start after -// 5 PM. -func (c *Client) CreateMaintenanceWindow(ctx context.Context, params *CreateMaintenanceWindowInput, optFns ...func(*Options)) (*CreateMaintenanceWindowOutput, error) { - if params == nil { - params = &CreateMaintenanceWindowInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateMaintenanceWindow", params, optFns, c.addOperationCreateMaintenanceWindowMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateMaintenanceWindowOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateMaintenanceWindowInput struct { - - // Enables a maintenance window task to run on managed nodes, even if you haven't - // registered those nodes as targets. If enabled, then you must specify the - // unregistered managed nodes (by node ID) when you register a task with the - // maintenance window. If you don't enable this option, then you must specify - // previously-registered targets when you register a task with the maintenance - // window. - // - // This member is required. - AllowUnassociatedTargets bool - - // The number of hours before the end of the maintenance window that Amazon Web - // Services Systems Manager stops scheduling new tasks for execution. - // - // This member is required. - Cutoff int32 - - // The duration of the maintenance window in hours. - // - // This member is required. - Duration *int32 - - // The name of the maintenance window. - // - // This member is required. - Name *string - - // The schedule of the maintenance window in the form of a cron or rate expression. - // - // This member is required. - Schedule *string - - // User-provided idempotency token. - ClientToken *string - - // An optional description for the maintenance window. We recommend specifying a - // description to help you organize your maintenance windows. - Description *string - - // The date and time, in ISO-8601 Extended format, for when you want the - // maintenance window to become inactive. EndDate allows you to set a date and - // time in the future when the maintenance window will no longer run. - EndDate *string - - // The number of days to wait after the date and time specified by a cron - // expression before running the maintenance window. For example, the following - // cron expression schedules a maintenance window to run on the third Tuesday of - // every month at 11:30 PM. cron(30 23 ? * TUE#3 *) If the schedule offset is 2 , - // the maintenance window won't run until two days later. - ScheduleOffset *int32 - - // The time zone that the scheduled maintenance window executions are based on, in - // Internet Assigned Numbers Authority (IANA) format. For example: - // "America/Los_Angeles", "UTC", or "Asia/Seoul". For more information, see the - // Time Zone Database (https://www.iana.org/time-zones) on the IANA website. - ScheduleTimezone *string - - // The date and time, in ISO-8601 Extended format, for when you want the - // maintenance window to become active. StartDate allows you to delay activation - // of the maintenance window until the specified future date. - StartDate *string - - // Optional metadata that you assign to a resource. Tags enable you to categorize - // a resource in different ways, such as by purpose, owner, or environment. For - // example, you might want to tag a maintenance window to identify the type of - // tasks it will run, the types of targets, and the environment it will run in. In - // this case, you could specify the following key-value pairs: - // - Key=TaskType,Value=AgentUpdate - // - Key=OS,Value=Windows - // - Key=Environment,Value=Production - // To add tags to an existing maintenance window, use the AddTagsToResource - // operation. - Tags []types.Tag - - noSmithyDocumentSerde -} - -type CreateMaintenanceWindowOutput struct { - - // The ID of the created maintenance window. - WindowId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateMaintenanceWindowMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreateMaintenanceWindow"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addIdempotencyToken_opCreateMaintenanceWindowMiddleware(stack, options); err != nil { - return err - } - if err = addOpCreateMaintenanceWindowValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateMaintenanceWindow(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -type idempotencyToken_initializeOpCreateMaintenanceWindow struct { - tokenProvider IdempotencyTokenProvider -} - -func (*idempotencyToken_initializeOpCreateMaintenanceWindow) ID() string { - return "OperationIdempotencyTokenAutoFill" -} - -func (m *idempotencyToken_initializeOpCreateMaintenanceWindow) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.tokenProvider == nil { - return next.HandleInitialize(ctx, in) - } - - input, ok := in.Parameters.(*CreateMaintenanceWindowInput) - if !ok { - return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateMaintenanceWindowInput ") - } - - if input.ClientToken == nil { - t, err := m.tokenProvider.GetIdempotencyToken() - if err != nil { - return out, metadata, err - } - input.ClientToken = &t - } - return next.HandleInitialize(ctx, in) -} -func addIdempotencyToken_opCreateMaintenanceWindowMiddleware(stack *middleware.Stack, cfg Options) error { - return stack.Initialize.Add(&idempotencyToken_initializeOpCreateMaintenanceWindow{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) -} - -func newServiceMetadataMiddleware_opCreateMaintenanceWindow(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateMaintenanceWindow", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateOpsItem.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateOpsItem.go deleted file mode 100644 index cd081f91..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateOpsItem.go +++ /dev/null @@ -1,239 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Creates a new OpsItem. You must have permission in Identity and Access -// Management (IAM) to create a new OpsItem. For more information, see Set up -// OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-setup.html) -// in the Amazon Web Services Systems Manager User Guide. Operations engineers and -// IT professionals use Amazon Web Services Systems Manager OpsCenter to view, -// investigate, and remediate operational issues impacting the performance and -// health of their Amazon Web Services resources. For more information, see Amazon -// Web Services Systems Manager OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) -// in the Amazon Web Services Systems Manager User Guide. -func (c *Client) CreateOpsItem(ctx context.Context, params *CreateOpsItemInput, optFns ...func(*Options)) (*CreateOpsItemOutput, error) { - if params == nil { - params = &CreateOpsItemInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateOpsItem", params, optFns, c.addOperationCreateOpsItemMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateOpsItemOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateOpsItemInput struct { - - // User-defined text that contains information about the OpsItem, in Markdown - // format. Provide enough information so that users viewing this OpsItem for the - // first time understand the issue. - // - // This member is required. - Description *string - - // The origin of the OpsItem, such as Amazon EC2 or Systems Manager. The source - // name can't contain the following strings: aws , amazon , and amzn . - // - // This member is required. - Source *string - - // A short heading that describes the nature of the OpsItem and the impacted - // resource. - // - // This member is required. - Title *string - - // The target Amazon Web Services account where you want to create an OpsItem. To - // make this call, your account must be configured to work with OpsItems across - // accounts. For more information, see Set up OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-setup.html) - // in the Amazon Web Services Systems Manager User Guide. - AccountId *string - - // The time a runbook workflow ended. Currently reported only for the OpsItem type - // /aws/changerequest . - ActualEndTime *time.Time - - // The time a runbook workflow started. Currently reported only for the OpsItem - // type /aws/changerequest . - ActualStartTime *time.Time - - // Specify a category to assign to an OpsItem. - Category *string - - // The Amazon Resource Name (ARN) of an SNS topic where notifications are sent - // when this OpsItem is edited or changed. - Notifications []types.OpsItemNotification - - // Operational data is custom data that provides useful reference details about - // the OpsItem. For example, you can specify log files, error strings, license - // keys, troubleshooting tips, or other relevant data. You enter operational data - // as key-value pairs. The key has a maximum length of 128 characters. The value - // has a maximum size of 20 KB. Operational data keys can't begin with the - // following: amazon , aws , amzn , ssm , /amazon , /aws , /amzn , /ssm . You can - // choose to make the data searchable by other users in the account or you can - // restrict search access. Searchable data means that all users with access to the - // OpsItem Overview page (as provided by the DescribeOpsItems API operation) can - // view and search on the specified data. Operational data that isn't searchable is - // only viewable by users who have access to the OpsItem (as provided by the - // GetOpsItem API operation). Use the /aws/resources key in OperationalData to - // specify a related resource in the request. Use the /aws/automations key in - // OperationalData to associate an Automation runbook with the OpsItem. To view - // Amazon Web Services CLI example commands that use these keys, see Creating - // OpsItems manually (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-manually-create-OpsItems.html) - // in the Amazon Web Services Systems Manager User Guide. - OperationalData map[string]types.OpsItemDataValue - - // The type of OpsItem to create. Systems Manager supports the following types of - // OpsItems: - // - /aws/issue This type of OpsItem is used for default OpsItems created by - // OpsCenter. - // - /aws/changerequest This type of OpsItem is used by Change Manager for - // reviewing and approving or rejecting change requests. - // - /aws/insight This type of OpsItem is used by OpsCenter for aggregating and - // reporting on duplicate OpsItems. - OpsItemType *string - - // The time specified in a change request for a runbook workflow to end. Currently - // supported only for the OpsItem type /aws/changerequest . - PlannedEndTime *time.Time - - // The time specified in a change request for a runbook workflow to start. - // Currently supported only for the OpsItem type /aws/changerequest . - PlannedStartTime *time.Time - - // The importance of this OpsItem in relation to other OpsItems in the system. - Priority *int32 - - // One or more OpsItems that share something in common with the current OpsItems. - // For example, related OpsItems can include OpsItems with similar error messages, - // impacted resources, or statuses for the impacted resource. - RelatedOpsItems []types.RelatedOpsItem - - // Specify a severity to assign to an OpsItem. - Severity *string - - // Optional metadata that you assign to a resource. Tags use a key-value pair. For - // example: Key=Department,Value=Finance To add tags to a new OpsItem, a user must - // have IAM permissions for both the ssm:CreateOpsItems operation and the - // ssm:AddTagsToResource operation. To add tags to an existing OpsItem, use the - // AddTagsToResource operation. - Tags []types.Tag - - noSmithyDocumentSerde -} - -type CreateOpsItemOutput struct { - - // The OpsItem Amazon Resource Name (ARN). - OpsItemArn *string - - // The ID of the OpsItem. - OpsItemId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateOpsItemMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateOpsItem{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateOpsItem{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreateOpsItem"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCreateOpsItemValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateOpsItem(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCreateOpsItem(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateOpsItem", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateOpsMetadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateOpsMetadata.go deleted file mode 100644 index dc87bc24..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateOpsMetadata.go +++ /dev/null @@ -1,153 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// If you create a new application in Application Manager, Amazon Web Services -// Systems Manager calls this API operation to specify information about the new -// application, including the application type. -func (c *Client) CreateOpsMetadata(ctx context.Context, params *CreateOpsMetadataInput, optFns ...func(*Options)) (*CreateOpsMetadataOutput, error) { - if params == nil { - params = &CreateOpsMetadataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateOpsMetadata", params, optFns, c.addOperationCreateOpsMetadataMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateOpsMetadataOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateOpsMetadataInput struct { - - // A resource ID for a new Application Manager application. - // - // This member is required. - ResourceId *string - - // Metadata for a new Application Manager application. - Metadata map[string]types.MetadataValue - - // Optional metadata that you assign to a resource. You can specify a maximum of - // five tags for an OpsMetadata object. Tags enable you to categorize a resource in - // different ways, such as by purpose, owner, or environment. For example, you - // might want to tag an OpsMetadata object to identify an environment or target - // Amazon Web Services Region. In this case, you could specify the following - // key-value pairs: - // - Key=Environment,Value=Production - // - Key=Region,Value=us-east-2 - Tags []types.Tag - - noSmithyDocumentSerde -} - -type CreateOpsMetadataOutput struct { - - // The Amazon Resource Name (ARN) of the OpsMetadata Object or blob created by the - // call. - OpsMetadataArn *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateOpsMetadataMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateOpsMetadata{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateOpsMetadata{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreateOpsMetadata"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCreateOpsMetadataValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateOpsMetadata(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCreateOpsMetadata(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateOpsMetadata", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreatePatchBaseline.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreatePatchBaseline.go deleted file mode 100644 index d1f8cc0e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreatePatchBaseline.go +++ /dev/null @@ -1,240 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Creates a patch baseline. For information about valid key-value pairs in -// PatchFilters for each supported operating system type, see PatchFilter . -func (c *Client) CreatePatchBaseline(ctx context.Context, params *CreatePatchBaselineInput, optFns ...func(*Options)) (*CreatePatchBaselineOutput, error) { - if params == nil { - params = &CreatePatchBaselineInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreatePatchBaseline", params, optFns, c.addOperationCreatePatchBaselineMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreatePatchBaselineOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreatePatchBaselineInput struct { - - // The name of the patch baseline. - // - // This member is required. - Name *string - - // A set of rules used to include patches in the baseline. - ApprovalRules *types.PatchRuleGroup - - // A list of explicitly approved patches for the baseline. For information about - // accepted formats for lists of approved patches and rejected patches, see About - // package name formats for approved and rejected patch lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) - // in the Amazon Web Services Systems Manager User Guide. - ApprovedPatches []string - - // Defines the compliance level for approved patches. When an approved patch is - // reported as missing, this value describes the severity of the compliance - // violation. The default value is UNSPECIFIED . - ApprovedPatchesComplianceLevel types.PatchComplianceLevel - - // Indicates whether the list of approved patches includes non-security updates - // that should be applied to the managed nodes. The default value is false . - // Applies to Linux managed nodes only. - ApprovedPatchesEnableNonSecurity *bool - - // User-provided idempotency token. - ClientToken *string - - // A description of the patch baseline. - Description *string - - // A set of global filters used to include patches in the baseline. - GlobalFilters *types.PatchFilterGroup - - // Defines the operating system the patch baseline applies to. The default value - // is WINDOWS . - OperatingSystem types.OperatingSystem - - // A list of explicitly rejected patches for the baseline. For information about - // accepted formats for lists of approved patches and rejected patches, see About - // package name formats for approved and rejected patch lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) - // in the Amazon Web Services Systems Manager User Guide. - RejectedPatches []string - - // The action for Patch Manager to take on patches included in the RejectedPackages - // list. - // - ALLOW_AS_DEPENDENCY : A package in the Rejected patches list is installed - // only if it is a dependency of another package. It is considered compliant with - // the patch baseline, and its status is reported as InstalledOther . This is the - // default action if no option is specified. - // - BLOCK : Packages in the RejectedPatches list, and packages that include them - // as dependencies, aren't installed under any circumstances. If a package was - // installed before it was added to the Rejected patches list, it is considered - // non-compliant with the patch baseline, and its status is reported as - // InstalledRejected . - RejectedPatchesAction types.PatchAction - - // Information about the patches to use to update the managed nodes, including - // target operating systems and source repositories. Applies to Linux managed nodes - // only. - Sources []types.PatchSource - - // Optional metadata that you assign to a resource. Tags enable you to categorize - // a resource in different ways, such as by purpose, owner, or environment. For - // example, you might want to tag a patch baseline to identify the severity level - // of patches it specifies and the operating system family it applies to. In this - // case, you could specify the following key-value pairs: - // - Key=PatchSeverity,Value=Critical - // - Key=OS,Value=Windows - // To add tags to an existing patch baseline, use the AddTagsToResource operation. - Tags []types.Tag - - noSmithyDocumentSerde -} - -type CreatePatchBaselineOutput struct { - - // The ID of the created patch baseline. - BaselineId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreatePatchBaselineMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreatePatchBaseline{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreatePatchBaseline{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreatePatchBaseline"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addIdempotencyToken_opCreatePatchBaselineMiddleware(stack, options); err != nil { - return err - } - if err = addOpCreatePatchBaselineValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreatePatchBaseline(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -type idempotencyToken_initializeOpCreatePatchBaseline struct { - tokenProvider IdempotencyTokenProvider -} - -func (*idempotencyToken_initializeOpCreatePatchBaseline) ID() string { - return "OperationIdempotencyTokenAutoFill" -} - -func (m *idempotencyToken_initializeOpCreatePatchBaseline) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.tokenProvider == nil { - return next.HandleInitialize(ctx, in) - } - - input, ok := in.Parameters.(*CreatePatchBaselineInput) - if !ok { - return out, metadata, fmt.Errorf("expected middleware input to be of type *CreatePatchBaselineInput ") - } - - if input.ClientToken == nil { - t, err := m.tokenProvider.GetIdempotencyToken() - if err != nil { - return out, metadata, err - } - input.ClientToken = &t - } - return next.HandleInitialize(ctx, in) -} -func addIdempotencyToken_opCreatePatchBaselineMiddleware(stack *middleware.Stack, cfg Options) error { - return stack.Initialize.Add(&idempotencyToken_initializeOpCreatePatchBaseline{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) -} - -func newServiceMetadataMiddleware_opCreatePatchBaseline(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreatePatchBaseline", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateResourceDataSync.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateResourceDataSync.go deleted file mode 100644 index 69343cec..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_CreateResourceDataSync.go +++ /dev/null @@ -1,171 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// A resource data sync helps you view data from multiple sources in a single -// location. Amazon Web Services Systems Manager offers two types of resource data -// sync: SyncToDestination and SyncFromSource . You can configure Systems Manager -// Inventory to use the SyncToDestination type to synchronize Inventory data from -// multiple Amazon Web Services Regions to a single Amazon Simple Storage Service -// (Amazon S3) bucket. For more information, see Configuring resource data sync -// for Inventory (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-datasync.html) -// in the Amazon Web Services Systems Manager User Guide. You can configure Systems -// Manager Explorer to use the SyncFromSource type to synchronize operational work -// items (OpsItems) and operational data (OpsData) from multiple Amazon Web -// Services Regions to a single Amazon S3 bucket. This type can synchronize -// OpsItems and OpsData from multiple Amazon Web Services accounts and Amazon Web -// Services Regions or EntireOrganization by using Organizations. For more -// information, see Setting up Systems Manager Explorer to display data from -// multiple accounts and Regions (https://docs.aws.amazon.com/systems-manager/latest/userguide/Explorer-resource-data-sync.html) -// in the Amazon Web Services Systems Manager User Guide. A resource data sync is -// an asynchronous operation that returns immediately. After a successful initial -// sync is completed, the system continuously syncs data. To check the status of a -// sync, use the ListResourceDataSync . By default, data isn't encrypted in Amazon -// S3. We strongly recommend that you enable encryption in Amazon S3 to ensure -// secure data storage. We also recommend that you secure access to the Amazon S3 -// bucket by creating a restrictive bucket policy. -func (c *Client) CreateResourceDataSync(ctx context.Context, params *CreateResourceDataSyncInput, optFns ...func(*Options)) (*CreateResourceDataSyncOutput, error) { - if params == nil { - params = &CreateResourceDataSyncInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateResourceDataSync", params, optFns, c.addOperationCreateResourceDataSyncMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateResourceDataSyncOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateResourceDataSyncInput struct { - - // A name for the configuration. - // - // This member is required. - SyncName *string - - // Amazon S3 configuration details for the sync. This parameter is required if the - // SyncType value is SyncToDestination. - S3Destination *types.ResourceDataSyncS3Destination - - // Specify information about the data sources to synchronize. This parameter is - // required if the SyncType value is SyncFromSource. - SyncSource *types.ResourceDataSyncSource - - // Specify SyncToDestination to create a resource data sync that synchronizes data - // to an S3 bucket for Inventory. If you specify SyncToDestination , you must - // provide a value for S3Destination . Specify SyncFromSource to synchronize data - // from a single account and multiple Regions, or multiple Amazon Web Services - // accounts and Amazon Web Services Regions, as listed in Organizations for - // Explorer. If you specify SyncFromSource , you must provide a value for - // SyncSource . The default value is SyncToDestination . - SyncType *string - - noSmithyDocumentSerde -} - -type CreateResourceDataSyncOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateResourceDataSyncMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpCreateResourceDataSync{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpCreateResourceDataSync{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreateResourceDataSync"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCreateResourceDataSyncValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateResourceDataSync(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCreateResourceDataSync(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateResourceDataSync", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteActivation.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteActivation.go deleted file mode 100644 index 1f5d44d2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteActivation.go +++ /dev/null @@ -1,135 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Deletes an activation. You aren't required to delete an activation. If you -// delete an activation, you can no longer use it to register additional managed -// nodes. Deleting an activation doesn't de-register managed nodes. You must -// manually de-register managed nodes. -func (c *Client) DeleteActivation(ctx context.Context, params *DeleteActivationInput, optFns ...func(*Options)) (*DeleteActivationOutput, error) { - if params == nil { - params = &DeleteActivationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteActivation", params, optFns, c.addOperationDeleteActivationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteActivationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteActivationInput struct { - - // The ID of the activation that you want to delete. - // - // This member is required. - ActivationId *string - - noSmithyDocumentSerde -} - -type DeleteActivationOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteActivationMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteActivation{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteActivation{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteActivation"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeleteActivationValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteActivation(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteActivation(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteActivation", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteAssociation.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteAssociation.go deleted file mode 100644 index 5309e986..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteAssociation.go +++ /dev/null @@ -1,145 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Disassociates the specified Amazon Web Services Systems Manager document (SSM -// document) from the specified managed node. If you created the association by -// using the Targets parameter, then you must delete the association by using the -// association ID. When you disassociate a document from a managed node, it doesn't -// change the configuration of the node. To change the configuration state of a -// managed node after you disassociate a document, you must create a new document -// with the desired configuration and associate it with the node. -func (c *Client) DeleteAssociation(ctx context.Context, params *DeleteAssociationInput, optFns ...func(*Options)) (*DeleteAssociationOutput, error) { - if params == nil { - params = &DeleteAssociationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteAssociation", params, optFns, c.addOperationDeleteAssociationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteAssociationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteAssociationInput struct { - - // The association ID that you want to delete. - AssociationId *string - - // The managed node ID. InstanceId has been deprecated. To specify a managed node - // ID for an association, use the Targets parameter. Requests that include the - // parameter InstanceID with Systems Manager documents (SSM documents) that use - // schema version 2.0 or later will fail. In addition, if you use the parameter - // InstanceId , you can't use the parameters AssociationName , DocumentVersion , - // MaxErrors , MaxConcurrency , OutputLocation , or ScheduleExpression . To use - // these parameters, you must use the Targets parameter. - InstanceId *string - - // The name of the SSM document. - Name *string - - noSmithyDocumentSerde -} - -type DeleteAssociationOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteAssociationMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteAssociation{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteAssociation{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteAssociation"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteAssociation(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteAssociation(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteAssociation", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteDocument.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteDocument.go deleted file mode 100644 index 22c5089b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteDocument.go +++ /dev/null @@ -1,149 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Deletes the Amazon Web Services Systems Manager document (SSM document) and all -// managed node associations to the document. Before you delete the document, we -// recommend that you use DeleteAssociation to disassociate all managed nodes that -// are associated with the document. -func (c *Client) DeleteDocument(ctx context.Context, params *DeleteDocumentInput, optFns ...func(*Options)) (*DeleteDocumentOutput, error) { - if params == nil { - params = &DeleteDocumentInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteDocument", params, optFns, c.addOperationDeleteDocumentMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteDocumentOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteDocumentInput struct { - - // The name of the document. - // - // This member is required. - Name *string - - // The version of the document that you want to delete. If not provided, all - // versions of the document are deleted. - DocumentVersion *string - - // Some SSM document types require that you specify a Force flag before you can - // delete the document. For example, you must specify a Force flag to delete a - // document of type ApplicationConfigurationSchema . You can restrict access to the - // Force flag in an Identity and Access Management (IAM) policy. - Force bool - - // The version name of the document that you want to delete. If not provided, all - // versions of the document are deleted. - VersionName *string - - noSmithyDocumentSerde -} - -type DeleteDocumentOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteDocumentMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteDocument{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteDocument{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteDocument"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeleteDocumentValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteDocument(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteDocument(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteDocument", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteInventory.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteInventory.go deleted file mode 100644 index af8a0108..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteInventory.go +++ /dev/null @@ -1,207 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Delete a custom inventory type or the data associated with a custom Inventory -// type. Deleting a custom inventory type is also referred to as deleting a custom -// inventory schema. -func (c *Client) DeleteInventory(ctx context.Context, params *DeleteInventoryInput, optFns ...func(*Options)) (*DeleteInventoryOutput, error) { - if params == nil { - params = &DeleteInventoryInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteInventory", params, optFns, c.addOperationDeleteInventoryMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteInventoryOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteInventoryInput struct { - - // The name of the custom inventory type for which you want to delete either all - // previously collected data or the inventory type itself. - // - // This member is required. - TypeName *string - - // User-provided idempotency token. - ClientToken *string - - // Use this option to view a summary of the deletion request without deleting any - // data or the data type. This option is useful when you only want to understand - // what will be deleted. Once you validate that the data to be deleted is what you - // intend to delete, you can run the same command without specifying the DryRun - // option. - DryRun bool - - // Use the SchemaDeleteOption to delete a custom inventory type (schema). If you - // don't choose this option, the system only deletes existing inventory data - // associated with the custom inventory type. Choose one of the following options: - // DisableSchema: If you choose this option, the system ignores all inventory data - // for the specified version, and any earlier versions. To enable this schema - // again, you must call the PutInventory operation for a version greater than the - // disabled version. DeleteSchema: This option deletes the specified custom type - // from the Inventory service. You can recreate the schema later, if you want. - SchemaDeleteOption types.InventorySchemaDeleteOption - - noSmithyDocumentSerde -} - -type DeleteInventoryOutput struct { - - // Every DeleteInventory operation is assigned a unique ID. This option returns a - // unique ID. You can use this ID to query the status of a delete operation. This - // option is useful for ensuring that a delete operation has completed before you - // begin other operations. - DeletionId *string - - // A summary of the delete operation. For more information about this summary, see - // Deleting custom inventory (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-custom.html#sysman-inventory-delete-summary) - // in the Amazon Web Services Systems Manager User Guide. - DeletionSummary *types.InventoryDeletionSummary - - // The name of the inventory data type specified in the request. - TypeName *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteInventoryMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteInventory{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteInventory{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteInventory"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addIdempotencyToken_opDeleteInventoryMiddleware(stack, options); err != nil { - return err - } - if err = addOpDeleteInventoryValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteInventory(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -type idempotencyToken_initializeOpDeleteInventory struct { - tokenProvider IdempotencyTokenProvider -} - -func (*idempotencyToken_initializeOpDeleteInventory) ID() string { - return "OperationIdempotencyTokenAutoFill" -} - -func (m *idempotencyToken_initializeOpDeleteInventory) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.tokenProvider == nil { - return next.HandleInitialize(ctx, in) - } - - input, ok := in.Parameters.(*DeleteInventoryInput) - if !ok { - return out, metadata, fmt.Errorf("expected middleware input to be of type *DeleteInventoryInput ") - } - - if input.ClientToken == nil { - t, err := m.tokenProvider.GetIdempotencyToken() - if err != nil { - return out, metadata, err - } - input.ClientToken = &t - } - return next.HandleInitialize(ctx, in) -} -func addIdempotencyToken_opDeleteInventoryMiddleware(stack *middleware.Stack, cfg Options) error { - return stack.Initialize.Add(&idempotencyToken_initializeOpDeleteInventory{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) -} - -func newServiceMetadataMiddleware_opDeleteInventory(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteInventory", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteMaintenanceWindow.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteMaintenanceWindow.go deleted file mode 100644 index bc6c70aa..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteMaintenanceWindow.go +++ /dev/null @@ -1,136 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Deletes a maintenance window. -func (c *Client) DeleteMaintenanceWindow(ctx context.Context, params *DeleteMaintenanceWindowInput, optFns ...func(*Options)) (*DeleteMaintenanceWindowOutput, error) { - if params == nil { - params = &DeleteMaintenanceWindowInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteMaintenanceWindow", params, optFns, c.addOperationDeleteMaintenanceWindowMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteMaintenanceWindowOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteMaintenanceWindowInput struct { - - // The ID of the maintenance window to delete. - // - // This member is required. - WindowId *string - - noSmithyDocumentSerde -} - -type DeleteMaintenanceWindowOutput struct { - - // The ID of the deleted maintenance window. - WindowId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteMaintenanceWindowMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteMaintenanceWindow"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeleteMaintenanceWindowValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteMaintenanceWindow(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteMaintenanceWindow(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteMaintenanceWindow", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteOpsItem.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteOpsItem.go deleted file mode 100644 index 173debc5..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteOpsItem.go +++ /dev/null @@ -1,149 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Delete an OpsItem. You must have permission in Identity and Access Management -// (IAM) to delete an OpsItem. Note the following important information about this -// operation. -// - Deleting an OpsItem is irreversible. You can't restore a deleted OpsItem. -// - This operation uses an eventual consistency model, which means the system -// can take a few minutes to complete this operation. If you delete an OpsItem and -// immediately call, for example, GetOpsItem , the deleted OpsItem might still -// appear in the response. -// - This operation is idempotent. The system doesn't throw an exception if you -// repeatedly call this operation for the same OpsItem. If the first call is -// successful, all additional calls return the same successful response as the -// first call. -// - This operation doesn't support cross-account calls. A delegated -// administrator or management account can't delete OpsItems in other accounts, -// even if OpsCenter has been set up for cross-account administration. For more -// information about cross-account administration, see Setting up OpsCenter to -// centrally manage OpsItems across accounts (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-setting-up-cross-account.html) -// in the Systems Manager User Guide. -func (c *Client) DeleteOpsItem(ctx context.Context, params *DeleteOpsItemInput, optFns ...func(*Options)) (*DeleteOpsItemOutput, error) { - if params == nil { - params = &DeleteOpsItemInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteOpsItem", params, optFns, c.addOperationDeleteOpsItemMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteOpsItemOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteOpsItemInput struct { - - // The ID of the OpsItem that you want to delete. - // - // This member is required. - OpsItemId *string - - noSmithyDocumentSerde -} - -type DeleteOpsItemOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteOpsItemMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteOpsItem{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteOpsItem{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteOpsItem"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeleteOpsItemValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteOpsItem(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteOpsItem(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteOpsItem", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteOpsMetadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteOpsMetadata.go deleted file mode 100644 index 04e28268..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteOpsMetadata.go +++ /dev/null @@ -1,132 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Delete OpsMetadata related to an application. -func (c *Client) DeleteOpsMetadata(ctx context.Context, params *DeleteOpsMetadataInput, optFns ...func(*Options)) (*DeleteOpsMetadataOutput, error) { - if params == nil { - params = &DeleteOpsMetadataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteOpsMetadata", params, optFns, c.addOperationDeleteOpsMetadataMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteOpsMetadataOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteOpsMetadataInput struct { - - // The Amazon Resource Name (ARN) of an OpsMetadata Object to delete. - // - // This member is required. - OpsMetadataArn *string - - noSmithyDocumentSerde -} - -type DeleteOpsMetadataOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteOpsMetadataMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteOpsMetadata{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteOpsMetadata{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteOpsMetadata"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeleteOpsMetadataValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteOpsMetadata(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteOpsMetadata(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteOpsMetadata", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteParameter.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteParameter.go deleted file mode 100644 index 066e055d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteParameter.go +++ /dev/null @@ -1,133 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Delete a parameter from the system. After deleting a parameter, wait for at -// least 30 seconds to create a parameter with the same name. -func (c *Client) DeleteParameter(ctx context.Context, params *DeleteParameterInput, optFns ...func(*Options)) (*DeleteParameterOutput, error) { - if params == nil { - params = &DeleteParameterInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteParameter", params, optFns, c.addOperationDeleteParameterMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteParameterOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteParameterInput struct { - - // The name of the parameter to delete. - // - // This member is required. - Name *string - - noSmithyDocumentSerde -} - -type DeleteParameterOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteParameterMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteParameter{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteParameter{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteParameter"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeleteParameterValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteParameter(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteParameter(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteParameter", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteParameters.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteParameters.go deleted file mode 100644 index ce6c9da3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteParameters.go +++ /dev/null @@ -1,142 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Delete a list of parameters. After deleting a parameter, wait for at least 30 -// seconds to create a parameter with the same name. -func (c *Client) DeleteParameters(ctx context.Context, params *DeleteParametersInput, optFns ...func(*Options)) (*DeleteParametersOutput, error) { - if params == nil { - params = &DeleteParametersInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteParameters", params, optFns, c.addOperationDeleteParametersMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteParametersOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteParametersInput struct { - - // The names of the parameters to delete. After deleting a parameter, wait for at - // least 30 seconds to create a parameter with the same name. - // - // This member is required. - Names []string - - noSmithyDocumentSerde -} - -type DeleteParametersOutput struct { - - // The names of the deleted parameters. - DeletedParameters []string - - // The names of parameters that weren't deleted because the parameters aren't - // valid. - InvalidParameters []string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteParametersMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteParameters{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteParameters{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteParameters"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeleteParametersValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteParameters(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteParameters(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteParameters", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeletePatchBaseline.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeletePatchBaseline.go deleted file mode 100644 index 7320e697..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeletePatchBaseline.go +++ /dev/null @@ -1,136 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Deletes a patch baseline. -func (c *Client) DeletePatchBaseline(ctx context.Context, params *DeletePatchBaselineInput, optFns ...func(*Options)) (*DeletePatchBaselineOutput, error) { - if params == nil { - params = &DeletePatchBaselineInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeletePatchBaseline", params, optFns, c.addOperationDeletePatchBaselineMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeletePatchBaselineOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeletePatchBaselineInput struct { - - // The ID of the patch baseline to delete. - // - // This member is required. - BaselineId *string - - noSmithyDocumentSerde -} - -type DeletePatchBaselineOutput struct { - - // The ID of the deleted patch baseline. - BaselineId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeletePatchBaselineMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeletePatchBaseline{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeletePatchBaseline{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeletePatchBaseline"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeletePatchBaselineValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeletePatchBaseline(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeletePatchBaseline(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeletePatchBaseline", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteResourceDataSync.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteResourceDataSync.go deleted file mode 100644 index a2584fa0..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteResourceDataSync.go +++ /dev/null @@ -1,137 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Deletes a resource data sync configuration. After the configuration is deleted, -// changes to data on managed nodes are no longer synced to or from the target. -// Deleting a sync configuration doesn't delete data. -func (c *Client) DeleteResourceDataSync(ctx context.Context, params *DeleteResourceDataSyncInput, optFns ...func(*Options)) (*DeleteResourceDataSyncOutput, error) { - if params == nil { - params = &DeleteResourceDataSyncInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteResourceDataSync", params, optFns, c.addOperationDeleteResourceDataSyncMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteResourceDataSyncOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteResourceDataSyncInput struct { - - // The name of the configuration to delete. - // - // This member is required. - SyncName *string - - // Specify the type of resource data sync to delete. - SyncType *string - - noSmithyDocumentSerde -} - -type DeleteResourceDataSyncOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteResourceDataSyncMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteResourceDataSync{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteResourceDataSync{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteResourceDataSync"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeleteResourceDataSyncValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteResourceDataSync(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteResourceDataSync(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteResourceDataSync", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteResourcePolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteResourcePolicy.go deleted file mode 100644 index c290f837..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeleteResourcePolicy.go +++ /dev/null @@ -1,148 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Deletes a Systems Manager resource policy. A resource policy helps you to -// define the IAM entity (for example, an Amazon Web Services account) that can -// manage your Systems Manager resources. Currently, OpsItemGroup is the only -// resource that supports Systems Manager resource policies. The resource policy -// for OpsItemGroup enables Amazon Web Services accounts to view and interact with -// OpsCenter operational work items (OpsItems). -func (c *Client) DeleteResourcePolicy(ctx context.Context, params *DeleteResourcePolicyInput, optFns ...func(*Options)) (*DeleteResourcePolicyOutput, error) { - if params == nil { - params = &DeleteResourcePolicyInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeleteResourcePolicy", params, optFns, c.addOperationDeleteResourcePolicyMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeleteResourcePolicyOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeleteResourcePolicyInput struct { - - // ID of the current policy version. The hash helps to prevent multiple calls from - // attempting to overwrite a policy. - // - // This member is required. - PolicyHash *string - - // The policy ID. - // - // This member is required. - PolicyId *string - - // Amazon Resource Name (ARN) of the resource to which the policies are attached. - // - // This member is required. - ResourceArn *string - - noSmithyDocumentSerde -} - -type DeleteResourcePolicyOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeleteResourcePolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeleteResourcePolicy{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeleteResourcePolicy{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeleteResourcePolicy"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeleteResourcePolicyValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeleteResourcePolicy(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeleteResourcePolicy(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeleteResourcePolicy", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterManagedInstance.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterManagedInstance.go deleted file mode 100644 index 8c199abc..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterManagedInstance.go +++ /dev/null @@ -1,135 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Removes the server or virtual machine from the list of registered servers. You -// can reregister the node again at any time. If you don't plan to use Run Command -// on the server, we suggest uninstalling SSM Agent first. -func (c *Client) DeregisterManagedInstance(ctx context.Context, params *DeregisterManagedInstanceInput, optFns ...func(*Options)) (*DeregisterManagedInstanceOutput, error) { - if params == nil { - params = &DeregisterManagedInstanceInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeregisterManagedInstance", params, optFns, c.addOperationDeregisterManagedInstanceMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeregisterManagedInstanceOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeregisterManagedInstanceInput struct { - - // The ID assigned to the managed node when you registered it using the activation - // process. - // - // This member is required. - InstanceId *string - - noSmithyDocumentSerde -} - -type DeregisterManagedInstanceOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeregisterManagedInstanceMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeregisterManagedInstance{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeregisterManagedInstance{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeregisterManagedInstance"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeregisterManagedInstanceValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeregisterManagedInstance(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeregisterManagedInstance(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeregisterManagedInstance", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterPatchBaselineForPatchGroup.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterPatchBaselineForPatchGroup.go deleted file mode 100644 index 4e2fadca..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterPatchBaselineForPatchGroup.go +++ /dev/null @@ -1,144 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Removes a patch group from a patch baseline. -func (c *Client) DeregisterPatchBaselineForPatchGroup(ctx context.Context, params *DeregisterPatchBaselineForPatchGroupInput, optFns ...func(*Options)) (*DeregisterPatchBaselineForPatchGroupOutput, error) { - if params == nil { - params = &DeregisterPatchBaselineForPatchGroupInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeregisterPatchBaselineForPatchGroup", params, optFns, c.addOperationDeregisterPatchBaselineForPatchGroupMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeregisterPatchBaselineForPatchGroupOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeregisterPatchBaselineForPatchGroupInput struct { - - // The ID of the patch baseline to deregister the patch group from. - // - // This member is required. - BaselineId *string - - // The name of the patch group that should be deregistered from the patch baseline. - // - // This member is required. - PatchGroup *string - - noSmithyDocumentSerde -} - -type DeregisterPatchBaselineForPatchGroupOutput struct { - - // The ID of the patch baseline the patch group was deregistered from. - BaselineId *string - - // The name of the patch group deregistered from the patch baseline. - PatchGroup *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeregisterPatchBaselineForPatchGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeregisterPatchBaselineForPatchGroup{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeregisterPatchBaselineForPatchGroup{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeregisterPatchBaselineForPatchGroup"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeregisterPatchBaselineForPatchGroupValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeregisterPatchBaselineForPatchGroup(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeregisterPatchBaselineForPatchGroup(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeregisterPatchBaselineForPatchGroup", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterTargetFromMaintenanceWindow.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterTargetFromMaintenanceWindow.go deleted file mode 100644 index e2b33cf6..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterTargetFromMaintenanceWindow.go +++ /dev/null @@ -1,149 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Removes a target from a maintenance window. -func (c *Client) DeregisterTargetFromMaintenanceWindow(ctx context.Context, params *DeregisterTargetFromMaintenanceWindowInput, optFns ...func(*Options)) (*DeregisterTargetFromMaintenanceWindowOutput, error) { - if params == nil { - params = &DeregisterTargetFromMaintenanceWindowInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeregisterTargetFromMaintenanceWindow", params, optFns, c.addOperationDeregisterTargetFromMaintenanceWindowMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeregisterTargetFromMaintenanceWindowOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeregisterTargetFromMaintenanceWindowInput struct { - - // The ID of the maintenance window the target should be removed from. - // - // This member is required. - WindowId *string - - // The ID of the target definition to remove. - // - // This member is required. - WindowTargetId *string - - // The system checks if the target is being referenced by a task. If the target is - // being referenced, the system returns an error and doesn't deregister the target - // from the maintenance window. - Safe *bool - - noSmithyDocumentSerde -} - -type DeregisterTargetFromMaintenanceWindowOutput struct { - - // The ID of the maintenance window the target was removed from. - WindowId *string - - // The ID of the removed target definition. - WindowTargetId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeregisterTargetFromMaintenanceWindowMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeregisterTargetFromMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeregisterTargetFromMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeregisterTargetFromMaintenanceWindow"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeregisterTargetFromMaintenanceWindowValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeregisterTargetFromMaintenanceWindow(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeregisterTargetFromMaintenanceWindow(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeregisterTargetFromMaintenanceWindow", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterTaskFromMaintenanceWindow.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterTaskFromMaintenanceWindow.go deleted file mode 100644 index 8aa5233b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DeregisterTaskFromMaintenanceWindow.go +++ /dev/null @@ -1,144 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Removes a task from a maintenance window. -func (c *Client) DeregisterTaskFromMaintenanceWindow(ctx context.Context, params *DeregisterTaskFromMaintenanceWindowInput, optFns ...func(*Options)) (*DeregisterTaskFromMaintenanceWindowOutput, error) { - if params == nil { - params = &DeregisterTaskFromMaintenanceWindowInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DeregisterTaskFromMaintenanceWindow", params, optFns, c.addOperationDeregisterTaskFromMaintenanceWindowMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DeregisterTaskFromMaintenanceWindowOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DeregisterTaskFromMaintenanceWindowInput struct { - - // The ID of the maintenance window the task should be removed from. - // - // This member is required. - WindowId *string - - // The ID of the task to remove from the maintenance window. - // - // This member is required. - WindowTaskId *string - - noSmithyDocumentSerde -} - -type DeregisterTaskFromMaintenanceWindowOutput struct { - - // The ID of the maintenance window the task was removed from. - WindowId *string - - // The ID of the task removed from the maintenance window. - WindowTaskId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDeregisterTaskFromMaintenanceWindowMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDeregisterTaskFromMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDeregisterTaskFromMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DeregisterTaskFromMaintenanceWindow"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDeregisterTaskFromMaintenanceWindowValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDeregisterTaskFromMaintenanceWindow(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDeregisterTaskFromMaintenanceWindow(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DeregisterTaskFromMaintenanceWindow", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeActivations.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeActivations.go deleted file mode 100644 index f844c5fb..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeActivations.go +++ /dev/null @@ -1,238 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Describes details about the activation, such as the date and time the -// activation was created, its expiration date, the Identity and Access Management -// (IAM) role assigned to the managed nodes in the activation, and the number of -// nodes registered by using this activation. -func (c *Client) DescribeActivations(ctx context.Context, params *DescribeActivationsInput, optFns ...func(*Options)) (*DescribeActivationsOutput, error) { - if params == nil { - params = &DescribeActivationsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeActivations", params, optFns, c.addOperationDescribeActivationsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeActivationsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeActivationsInput struct { - - // A filter to view information about your activations. - Filters []types.DescribeActivationsFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeActivationsOutput struct { - - // A list of activations for your Amazon Web Services account. - ActivationList []types.Activation - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeActivationsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeActivations{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeActivations{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeActivations"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeActivations(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeActivationsAPIClient is a client that implements the -// DescribeActivations operation. -type DescribeActivationsAPIClient interface { - DescribeActivations(context.Context, *DescribeActivationsInput, ...func(*Options)) (*DescribeActivationsOutput, error) -} - -var _ DescribeActivationsAPIClient = (*Client)(nil) - -// DescribeActivationsPaginatorOptions is the paginator options for -// DescribeActivations -type DescribeActivationsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeActivationsPaginator is a paginator for DescribeActivations -type DescribeActivationsPaginator struct { - options DescribeActivationsPaginatorOptions - client DescribeActivationsAPIClient - params *DescribeActivationsInput - nextToken *string - firstPage bool -} - -// NewDescribeActivationsPaginator returns a new DescribeActivationsPaginator -func NewDescribeActivationsPaginator(client DescribeActivationsAPIClient, params *DescribeActivationsInput, optFns ...func(*DescribeActivationsPaginatorOptions)) *DescribeActivationsPaginator { - if params == nil { - params = &DescribeActivationsInput{} - } - - options := DescribeActivationsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeActivationsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeActivationsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeActivations page. -func (p *DescribeActivationsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeActivationsOutput, 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 - - result, err := p.client.DescribeActivations(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 -} - -func newServiceMetadataMiddleware_opDescribeActivations(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeActivations", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAssociation.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAssociation.go deleted file mode 100644 index 16a63ed1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAssociation.go +++ /dev/null @@ -1,146 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Describes the association for the specified target or managed node. If you -// created the association by using the Targets parameter, then you must retrieve -// the association by using the association ID. -func (c *Client) DescribeAssociation(ctx context.Context, params *DescribeAssociationInput, optFns ...func(*Options)) (*DescribeAssociationOutput, error) { - if params == nil { - params = &DescribeAssociationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeAssociation", params, optFns, c.addOperationDescribeAssociationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeAssociationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeAssociationInput struct { - - // The association ID for which you want information. - AssociationId *string - - // Specify the association version to retrieve. To view the latest version, either - // specify $LATEST for this parameter, or omit this parameter. To view a list of - // all associations for a managed node, use ListAssociations . To get a list of - // versions for a specific association, use ListAssociationVersions . - AssociationVersion *string - - // The managed node ID. - InstanceId *string - - // The name of the SSM document. - Name *string - - noSmithyDocumentSerde -} - -type DescribeAssociationOutput struct { - - // Information about the association. - AssociationDescription *types.AssociationDescription - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeAssociationMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeAssociation{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeAssociation{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeAssociation"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeAssociation(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDescribeAssociation(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeAssociation", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAssociationExecutionTargets.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAssociationExecutionTargets.go deleted file mode 100644 index 620edf4a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAssociationExecutionTargets.go +++ /dev/null @@ -1,252 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Views information about a specific execution of a specific association. -func (c *Client) DescribeAssociationExecutionTargets(ctx context.Context, params *DescribeAssociationExecutionTargetsInput, optFns ...func(*Options)) (*DescribeAssociationExecutionTargetsOutput, error) { - if params == nil { - params = &DescribeAssociationExecutionTargetsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeAssociationExecutionTargets", params, optFns, c.addOperationDescribeAssociationExecutionTargetsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeAssociationExecutionTargetsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeAssociationExecutionTargetsInput struct { - - // The association ID that includes the execution for which you want to view - // details. - // - // This member is required. - AssociationId *string - - // The execution ID for which you want to view details. - // - // This member is required. - ExecutionId *string - - // Filters for the request. You can specify the following filters and values. - // Status (EQUAL) ResourceId (EQUAL) ResourceType (EQUAL) - Filters []types.AssociationExecutionTargetsFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeAssociationExecutionTargetsOutput struct { - - // Information about the execution. - AssociationExecutionTargets []types.AssociationExecutionTarget - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeAssociationExecutionTargetsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeAssociationExecutionTargets{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeAssociationExecutionTargets{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeAssociationExecutionTargets"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeAssociationExecutionTargetsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeAssociationExecutionTargets(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeAssociationExecutionTargetsAPIClient is a client that implements the -// DescribeAssociationExecutionTargets operation. -type DescribeAssociationExecutionTargetsAPIClient interface { - DescribeAssociationExecutionTargets(context.Context, *DescribeAssociationExecutionTargetsInput, ...func(*Options)) (*DescribeAssociationExecutionTargetsOutput, error) -} - -var _ DescribeAssociationExecutionTargetsAPIClient = (*Client)(nil) - -// DescribeAssociationExecutionTargetsPaginatorOptions is the paginator options -// for DescribeAssociationExecutionTargets -type DescribeAssociationExecutionTargetsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeAssociationExecutionTargetsPaginator is a paginator for -// DescribeAssociationExecutionTargets -type DescribeAssociationExecutionTargetsPaginator struct { - options DescribeAssociationExecutionTargetsPaginatorOptions - client DescribeAssociationExecutionTargetsAPIClient - params *DescribeAssociationExecutionTargetsInput - nextToken *string - firstPage bool -} - -// NewDescribeAssociationExecutionTargetsPaginator returns a new -// DescribeAssociationExecutionTargetsPaginator -func NewDescribeAssociationExecutionTargetsPaginator(client DescribeAssociationExecutionTargetsAPIClient, params *DescribeAssociationExecutionTargetsInput, optFns ...func(*DescribeAssociationExecutionTargetsPaginatorOptions)) *DescribeAssociationExecutionTargetsPaginator { - if params == nil { - params = &DescribeAssociationExecutionTargetsInput{} - } - - options := DescribeAssociationExecutionTargetsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeAssociationExecutionTargetsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeAssociationExecutionTargetsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeAssociationExecutionTargets page. -func (p *DescribeAssociationExecutionTargetsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeAssociationExecutionTargetsOutput, 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 - - result, err := p.client.DescribeAssociationExecutionTargets(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 -} - -func newServiceMetadataMiddleware_opDescribeAssociationExecutionTargets(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeAssociationExecutionTargets", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAssociationExecutions.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAssociationExecutions.go deleted file mode 100644 index 9cf86d17..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAssociationExecutions.go +++ /dev/null @@ -1,246 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Views all executions for a specific association ID. -func (c *Client) DescribeAssociationExecutions(ctx context.Context, params *DescribeAssociationExecutionsInput, optFns ...func(*Options)) (*DescribeAssociationExecutionsOutput, error) { - if params == nil { - params = &DescribeAssociationExecutionsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeAssociationExecutions", params, optFns, c.addOperationDescribeAssociationExecutionsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeAssociationExecutionsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeAssociationExecutionsInput struct { - - // The association ID for which you want to view execution history details. - // - // This member is required. - AssociationId *string - - // Filters for the request. You can specify the following filters and values. - // ExecutionId (EQUAL) Status (EQUAL) CreatedTime (EQUAL, GREATER_THAN, LESS_THAN) - Filters []types.AssociationExecutionFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeAssociationExecutionsOutput struct { - - // A list of the executions for the specified association ID. - AssociationExecutions []types.AssociationExecution - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeAssociationExecutionsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeAssociationExecutions{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeAssociationExecutions{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeAssociationExecutions"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeAssociationExecutionsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeAssociationExecutions(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeAssociationExecutionsAPIClient is a client that implements the -// DescribeAssociationExecutions operation. -type DescribeAssociationExecutionsAPIClient interface { - DescribeAssociationExecutions(context.Context, *DescribeAssociationExecutionsInput, ...func(*Options)) (*DescribeAssociationExecutionsOutput, error) -} - -var _ DescribeAssociationExecutionsAPIClient = (*Client)(nil) - -// DescribeAssociationExecutionsPaginatorOptions is the paginator options for -// DescribeAssociationExecutions -type DescribeAssociationExecutionsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeAssociationExecutionsPaginator is a paginator for -// DescribeAssociationExecutions -type DescribeAssociationExecutionsPaginator struct { - options DescribeAssociationExecutionsPaginatorOptions - client DescribeAssociationExecutionsAPIClient - params *DescribeAssociationExecutionsInput - nextToken *string - firstPage bool -} - -// NewDescribeAssociationExecutionsPaginator returns a new -// DescribeAssociationExecutionsPaginator -func NewDescribeAssociationExecutionsPaginator(client DescribeAssociationExecutionsAPIClient, params *DescribeAssociationExecutionsInput, optFns ...func(*DescribeAssociationExecutionsPaginatorOptions)) *DescribeAssociationExecutionsPaginator { - if params == nil { - params = &DescribeAssociationExecutionsInput{} - } - - options := DescribeAssociationExecutionsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeAssociationExecutionsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeAssociationExecutionsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeAssociationExecutions page. -func (p *DescribeAssociationExecutionsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeAssociationExecutionsOutput, 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 - - result, err := p.client.DescribeAssociationExecutions(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 -} - -func newServiceMetadataMiddleware_opDescribeAssociationExecutions(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeAssociationExecutions", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAutomationExecutions.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAutomationExecutions.go deleted file mode 100644 index c40bc79c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAutomationExecutions.go +++ /dev/null @@ -1,242 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Provides details about all active and terminated Automation executions. -func (c *Client) DescribeAutomationExecutions(ctx context.Context, params *DescribeAutomationExecutionsInput, optFns ...func(*Options)) (*DescribeAutomationExecutionsOutput, error) { - if params == nil { - params = &DescribeAutomationExecutionsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeAutomationExecutions", params, optFns, c.addOperationDescribeAutomationExecutionsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeAutomationExecutionsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeAutomationExecutionsInput struct { - - // Filters used to limit the scope of executions that are requested. - Filters []types.AutomationExecutionFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeAutomationExecutionsOutput struct { - - // The list of details about each automation execution which has occurred which - // matches the filter specification, if any. - AutomationExecutionMetadataList []types.AutomationExecutionMetadata - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeAutomationExecutionsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeAutomationExecutions{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeAutomationExecutions{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeAutomationExecutions"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeAutomationExecutionsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeAutomationExecutions(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeAutomationExecutionsAPIClient is a client that implements the -// DescribeAutomationExecutions operation. -type DescribeAutomationExecutionsAPIClient interface { - DescribeAutomationExecutions(context.Context, *DescribeAutomationExecutionsInput, ...func(*Options)) (*DescribeAutomationExecutionsOutput, error) -} - -var _ DescribeAutomationExecutionsAPIClient = (*Client)(nil) - -// DescribeAutomationExecutionsPaginatorOptions is the paginator options for -// DescribeAutomationExecutions -type DescribeAutomationExecutionsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeAutomationExecutionsPaginator is a paginator for -// DescribeAutomationExecutions -type DescribeAutomationExecutionsPaginator struct { - options DescribeAutomationExecutionsPaginatorOptions - client DescribeAutomationExecutionsAPIClient - params *DescribeAutomationExecutionsInput - nextToken *string - firstPage bool -} - -// NewDescribeAutomationExecutionsPaginator returns a new -// DescribeAutomationExecutionsPaginator -func NewDescribeAutomationExecutionsPaginator(client DescribeAutomationExecutionsAPIClient, params *DescribeAutomationExecutionsInput, optFns ...func(*DescribeAutomationExecutionsPaginatorOptions)) *DescribeAutomationExecutionsPaginator { - if params == nil { - params = &DescribeAutomationExecutionsInput{} - } - - options := DescribeAutomationExecutionsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeAutomationExecutionsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeAutomationExecutionsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeAutomationExecutions page. -func (p *DescribeAutomationExecutionsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeAutomationExecutionsOutput, 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 - - result, err := p.client.DescribeAutomationExecutions(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 -} - -func newServiceMetadataMiddleware_opDescribeAutomationExecutions(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeAutomationExecutions", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAutomationStepExecutions.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAutomationStepExecutions.go deleted file mode 100644 index dac34018..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAutomationStepExecutions.go +++ /dev/null @@ -1,253 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Information about all active and terminated step executions in an Automation -// workflow. -func (c *Client) DescribeAutomationStepExecutions(ctx context.Context, params *DescribeAutomationStepExecutionsInput, optFns ...func(*Options)) (*DescribeAutomationStepExecutionsOutput, error) { - if params == nil { - params = &DescribeAutomationStepExecutionsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeAutomationStepExecutions", params, optFns, c.addOperationDescribeAutomationStepExecutionsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeAutomationStepExecutionsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeAutomationStepExecutionsInput struct { - - // The Automation execution ID for which you want step execution descriptions. - // - // This member is required. - AutomationExecutionId *string - - // One or more filters to limit the number of step executions returned by the - // request. - Filters []types.StepExecutionFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - // Indicates whether to list step executions in reverse order by start time. The - // default value is 'false'. - ReverseOrder *bool - - noSmithyDocumentSerde -} - -type DescribeAutomationStepExecutionsOutput struct { - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // A list of details about the current state of all steps that make up an - // execution. - StepExecutions []types.StepExecution - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeAutomationStepExecutionsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeAutomationStepExecutions{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeAutomationStepExecutions{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeAutomationStepExecutions"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeAutomationStepExecutionsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeAutomationStepExecutions(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeAutomationStepExecutionsAPIClient is a client that implements the -// DescribeAutomationStepExecutions operation. -type DescribeAutomationStepExecutionsAPIClient interface { - DescribeAutomationStepExecutions(context.Context, *DescribeAutomationStepExecutionsInput, ...func(*Options)) (*DescribeAutomationStepExecutionsOutput, error) -} - -var _ DescribeAutomationStepExecutionsAPIClient = (*Client)(nil) - -// DescribeAutomationStepExecutionsPaginatorOptions is the paginator options for -// DescribeAutomationStepExecutions -type DescribeAutomationStepExecutionsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeAutomationStepExecutionsPaginator is a paginator for -// DescribeAutomationStepExecutions -type DescribeAutomationStepExecutionsPaginator struct { - options DescribeAutomationStepExecutionsPaginatorOptions - client DescribeAutomationStepExecutionsAPIClient - params *DescribeAutomationStepExecutionsInput - nextToken *string - firstPage bool -} - -// NewDescribeAutomationStepExecutionsPaginator returns a new -// DescribeAutomationStepExecutionsPaginator -func NewDescribeAutomationStepExecutionsPaginator(client DescribeAutomationStepExecutionsAPIClient, params *DescribeAutomationStepExecutionsInput, optFns ...func(*DescribeAutomationStepExecutionsPaginatorOptions)) *DescribeAutomationStepExecutionsPaginator { - if params == nil { - params = &DescribeAutomationStepExecutionsInput{} - } - - options := DescribeAutomationStepExecutionsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeAutomationStepExecutionsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeAutomationStepExecutionsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeAutomationStepExecutions page. -func (p *DescribeAutomationStepExecutionsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeAutomationStepExecutionsOutput, 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 - - result, err := p.client.DescribeAutomationStepExecutions(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 -} - -func newServiceMetadataMiddleware_opDescribeAutomationStepExecutions(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeAutomationStepExecutions", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAvailablePatches.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAvailablePatches.go deleted file mode 100644 index cd57e0ca..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeAvailablePatches.go +++ /dev/null @@ -1,263 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists all patches eligible to be included in a patch baseline. -func (c *Client) DescribeAvailablePatches(ctx context.Context, params *DescribeAvailablePatchesInput, optFns ...func(*Options)) (*DescribeAvailablePatchesOutput, error) { - if params == nil { - params = &DescribeAvailablePatchesInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeAvailablePatches", params, optFns, c.addOperationDescribeAvailablePatchesMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeAvailablePatchesOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeAvailablePatchesInput struct { - - // Each element in the array is a structure containing a key-value pair. Windows - // Server Supported keys for Windows Server managed node patches include the - // following: - // - PATCH_SET Sample values: OS | APPLICATION - // - PRODUCT Sample values: WindowsServer2012 | Office 2010 | - // MicrosoftDefenderAntivirus - // - PRODUCT_FAMILY Sample values: Windows | Office - // - MSRC_SEVERITY Sample values: ServicePacks | Important | Moderate - // - CLASSIFICATION Sample values: ServicePacks | SecurityUpdates | - // DefinitionUpdates - // - PATCH_ID Sample values: KB123456 | KB4516046 - // Linux When specifying filters for Linux patches, you must specify a key-pair - // for PRODUCT . For example, using the Command Line Interface (CLI), the following - // command fails: aws ssm describe-available-patches --filters - // Key=CVE_ID,Values=CVE-2018-3615 However, the following command succeeds: aws - // ssm describe-available-patches --filters Key=PRODUCT,Values=AmazonLinux2018.03 - // Key=CVE_ID,Values=CVE-2018-3615 Supported keys for Linux managed node patches - // include the following: - // - PRODUCT Sample values: AmazonLinux2018.03 | AmazonLinux2.0 - // - NAME Sample values: kernel-headers | samba-python | php - // - SEVERITY Sample values: Critical | Important | Medium | Low - // - EPOCH Sample values: 0 | 1 - // - VERSION Sample values: 78.6.1 | 4.10.16 - // - RELEASE Sample values: 9.56.amzn1 | 1.amzn2 - // - ARCH Sample values: i686 | x86_64 - // - REPOSITORY Sample values: Core | Updates - // - ADVISORY_ID Sample values: ALAS-2018-1058 | ALAS2-2021-1594 - // - CVE_ID Sample values: CVE-2018-3615 | CVE-2020-1472 - // - BUGZILLA_ID Sample values: 1463241 - Filters []types.PatchOrchestratorFilter - - // The maximum number of patches to return (per page). - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeAvailablePatchesOutput struct { - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // An array of patches. Each entry in the array is a patch structure. - Patches []types.Patch - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeAvailablePatchesMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeAvailablePatches{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeAvailablePatches{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeAvailablePatches"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeAvailablePatches(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeAvailablePatchesAPIClient is a client that implements the -// DescribeAvailablePatches operation. -type DescribeAvailablePatchesAPIClient interface { - DescribeAvailablePatches(context.Context, *DescribeAvailablePatchesInput, ...func(*Options)) (*DescribeAvailablePatchesOutput, error) -} - -var _ DescribeAvailablePatchesAPIClient = (*Client)(nil) - -// DescribeAvailablePatchesPaginatorOptions is the paginator options for -// DescribeAvailablePatches -type DescribeAvailablePatchesPaginatorOptions struct { - // The maximum number of patches to return (per page). - 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 -} - -// DescribeAvailablePatchesPaginator is a paginator for DescribeAvailablePatches -type DescribeAvailablePatchesPaginator struct { - options DescribeAvailablePatchesPaginatorOptions - client DescribeAvailablePatchesAPIClient - params *DescribeAvailablePatchesInput - nextToken *string - firstPage bool -} - -// NewDescribeAvailablePatchesPaginator returns a new -// DescribeAvailablePatchesPaginator -func NewDescribeAvailablePatchesPaginator(client DescribeAvailablePatchesAPIClient, params *DescribeAvailablePatchesInput, optFns ...func(*DescribeAvailablePatchesPaginatorOptions)) *DescribeAvailablePatchesPaginator { - if params == nil { - params = &DescribeAvailablePatchesInput{} - } - - options := DescribeAvailablePatchesPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeAvailablePatchesPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeAvailablePatchesPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeAvailablePatches page. -func (p *DescribeAvailablePatchesPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeAvailablePatchesOutput, 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 - - result, err := p.client.DescribeAvailablePatches(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 -} - -func newServiceMetadataMiddleware_opDescribeAvailablePatches(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeAvailablePatches", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeDocument.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeDocument.go deleted file mode 100644 index e5239069..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeDocument.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Describes the specified Amazon Web Services Systems Manager document (SSM -// document). -func (c *Client) DescribeDocument(ctx context.Context, params *DescribeDocumentInput, optFns ...func(*Options)) (*DescribeDocumentOutput, error) { - if params == nil { - params = &DescribeDocumentInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeDocument", params, optFns, c.addOperationDescribeDocumentMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeDocumentOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeDocumentInput struct { - - // The name of the SSM document. - // - // This member is required. - Name *string - - // The document version for which you want information. Can be a specific version - // or the default version. - DocumentVersion *string - - // An optional field specifying the version of the artifact associated with the - // document. For example, "Release 12, Update 6". This value is unique across all - // versions of a document, and can't be changed. - VersionName *string - - noSmithyDocumentSerde -} - -type DescribeDocumentOutput struct { - - // Information about the SSM document. - Document *types.DocumentDescription - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeDocumentMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeDocument{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeDocument{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeDocument"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeDocumentValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeDocument(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDescribeDocument(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeDocument", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeDocumentPermission.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeDocumentPermission.go deleted file mode 100644 index f3f11a38..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeDocumentPermission.go +++ /dev/null @@ -1,162 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Describes the permissions for a Amazon Web Services Systems Manager document -// (SSM document). If you created the document, you are the owner. If a document is -// shared, it can either be shared privately (by specifying a user's Amazon Web -// Services account ID) or publicly (All). -func (c *Client) DescribeDocumentPermission(ctx context.Context, params *DescribeDocumentPermissionInput, optFns ...func(*Options)) (*DescribeDocumentPermissionOutput, error) { - if params == nil { - params = &DescribeDocumentPermissionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeDocumentPermission", params, optFns, c.addOperationDescribeDocumentPermissionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeDocumentPermissionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeDocumentPermissionInput struct { - - // The name of the document for which you are the owner. - // - // This member is required. - Name *string - - // The permission type for the document. The permission type can be Share. - // - // This member is required. - PermissionType types.DocumentPermissionType - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeDocumentPermissionOutput struct { - - // The account IDs that have permission to use this document. The ID can be either - // an Amazon Web Services account or All. - AccountIds []string - - // A list of Amazon Web Services accounts where the current document is shared and - // the version shared with each account. - AccountSharingInfoList []types.AccountSharingInfo - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeDocumentPermissionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeDocumentPermission{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeDocumentPermission{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeDocumentPermission"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeDocumentPermissionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeDocumentPermission(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDescribeDocumentPermission(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeDocumentPermission", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeEffectiveInstanceAssociations.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeEffectiveInstanceAssociations.go deleted file mode 100644 index c84ee26f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeEffectiveInstanceAssociations.go +++ /dev/null @@ -1,243 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// All associations for the managed node(s). -func (c *Client) DescribeEffectiveInstanceAssociations(ctx context.Context, params *DescribeEffectiveInstanceAssociationsInput, optFns ...func(*Options)) (*DescribeEffectiveInstanceAssociationsOutput, error) { - if params == nil { - params = &DescribeEffectiveInstanceAssociationsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeEffectiveInstanceAssociations", params, optFns, c.addOperationDescribeEffectiveInstanceAssociationsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeEffectiveInstanceAssociationsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeEffectiveInstanceAssociationsInput struct { - - // The managed node ID for which you want to view all associations. - // - // This member is required. - InstanceId *string - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeEffectiveInstanceAssociationsOutput struct { - - // The associations for the requested managed node. - Associations []types.InstanceAssociation - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeEffectiveInstanceAssociationsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeEffectiveInstanceAssociations{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeEffectiveInstanceAssociations{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeEffectiveInstanceAssociations"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeEffectiveInstanceAssociationsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeEffectiveInstanceAssociations(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeEffectiveInstanceAssociationsAPIClient is a client that implements the -// DescribeEffectiveInstanceAssociations operation. -type DescribeEffectiveInstanceAssociationsAPIClient interface { - DescribeEffectiveInstanceAssociations(context.Context, *DescribeEffectiveInstanceAssociationsInput, ...func(*Options)) (*DescribeEffectiveInstanceAssociationsOutput, error) -} - -var _ DescribeEffectiveInstanceAssociationsAPIClient = (*Client)(nil) - -// DescribeEffectiveInstanceAssociationsPaginatorOptions is the paginator options -// for DescribeEffectiveInstanceAssociations -type DescribeEffectiveInstanceAssociationsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeEffectiveInstanceAssociationsPaginator is a paginator for -// DescribeEffectiveInstanceAssociations -type DescribeEffectiveInstanceAssociationsPaginator struct { - options DescribeEffectiveInstanceAssociationsPaginatorOptions - client DescribeEffectiveInstanceAssociationsAPIClient - params *DescribeEffectiveInstanceAssociationsInput - nextToken *string - firstPage bool -} - -// NewDescribeEffectiveInstanceAssociationsPaginator returns a new -// DescribeEffectiveInstanceAssociationsPaginator -func NewDescribeEffectiveInstanceAssociationsPaginator(client DescribeEffectiveInstanceAssociationsAPIClient, params *DescribeEffectiveInstanceAssociationsInput, optFns ...func(*DescribeEffectiveInstanceAssociationsPaginatorOptions)) *DescribeEffectiveInstanceAssociationsPaginator { - if params == nil { - params = &DescribeEffectiveInstanceAssociationsInput{} - } - - options := DescribeEffectiveInstanceAssociationsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeEffectiveInstanceAssociationsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeEffectiveInstanceAssociationsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeEffectiveInstanceAssociations page. -func (p *DescribeEffectiveInstanceAssociationsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeEffectiveInstanceAssociationsOutput, 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 - - result, err := p.client.DescribeEffectiveInstanceAssociations(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 -} - -func newServiceMetadataMiddleware_opDescribeEffectiveInstanceAssociations(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeEffectiveInstanceAssociations", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeEffectivePatchesForPatchBaseline.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeEffectivePatchesForPatchBaseline.go deleted file mode 100644 index 72dd9330..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeEffectivePatchesForPatchBaseline.go +++ /dev/null @@ -1,242 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the current effective patches (the patch and the approval state) for -// the specified patch baseline. Applies to patch baselines for Windows only. -func (c *Client) DescribeEffectivePatchesForPatchBaseline(ctx context.Context, params *DescribeEffectivePatchesForPatchBaselineInput, optFns ...func(*Options)) (*DescribeEffectivePatchesForPatchBaselineOutput, error) { - if params == nil { - params = &DescribeEffectivePatchesForPatchBaselineInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeEffectivePatchesForPatchBaseline", params, optFns, c.addOperationDescribeEffectivePatchesForPatchBaselineMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeEffectivePatchesForPatchBaselineOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeEffectivePatchesForPatchBaselineInput struct { - - // The ID of the patch baseline to retrieve the effective patches for. - // - // This member is required. - BaselineId *string - - // The maximum number of patches to return (per page). - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeEffectivePatchesForPatchBaselineOutput struct { - - // An array of patches and patch status. - EffectivePatches []types.EffectivePatch - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeEffectivePatchesForPatchBaselineMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeEffectivePatchesForPatchBaseline{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeEffectivePatchesForPatchBaseline{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeEffectivePatchesForPatchBaseline"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeEffectivePatchesForPatchBaselineValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeEffectivePatchesForPatchBaseline(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeEffectivePatchesForPatchBaselineAPIClient is a client that implements -// the DescribeEffectivePatchesForPatchBaseline operation. -type DescribeEffectivePatchesForPatchBaselineAPIClient interface { - DescribeEffectivePatchesForPatchBaseline(context.Context, *DescribeEffectivePatchesForPatchBaselineInput, ...func(*Options)) (*DescribeEffectivePatchesForPatchBaselineOutput, error) -} - -var _ DescribeEffectivePatchesForPatchBaselineAPIClient = (*Client)(nil) - -// DescribeEffectivePatchesForPatchBaselinePaginatorOptions is the paginator -// options for DescribeEffectivePatchesForPatchBaseline -type DescribeEffectivePatchesForPatchBaselinePaginatorOptions struct { - // The maximum number of patches to return (per page). - 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 -} - -// DescribeEffectivePatchesForPatchBaselinePaginator is a paginator for -// DescribeEffectivePatchesForPatchBaseline -type DescribeEffectivePatchesForPatchBaselinePaginator struct { - options DescribeEffectivePatchesForPatchBaselinePaginatorOptions - client DescribeEffectivePatchesForPatchBaselineAPIClient - params *DescribeEffectivePatchesForPatchBaselineInput - nextToken *string - firstPage bool -} - -// NewDescribeEffectivePatchesForPatchBaselinePaginator returns a new -// DescribeEffectivePatchesForPatchBaselinePaginator -func NewDescribeEffectivePatchesForPatchBaselinePaginator(client DescribeEffectivePatchesForPatchBaselineAPIClient, params *DescribeEffectivePatchesForPatchBaselineInput, optFns ...func(*DescribeEffectivePatchesForPatchBaselinePaginatorOptions)) *DescribeEffectivePatchesForPatchBaselinePaginator { - if params == nil { - params = &DescribeEffectivePatchesForPatchBaselineInput{} - } - - options := DescribeEffectivePatchesForPatchBaselinePaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeEffectivePatchesForPatchBaselinePaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeEffectivePatchesForPatchBaselinePaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeEffectivePatchesForPatchBaseline page. -func (p *DescribeEffectivePatchesForPatchBaselinePaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeEffectivePatchesForPatchBaselineOutput, 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 - - result, err := p.client.DescribeEffectivePatchesForPatchBaseline(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 -} - -func newServiceMetadataMiddleware_opDescribeEffectivePatchesForPatchBaseline(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeEffectivePatchesForPatchBaseline", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstanceAssociationsStatus.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstanceAssociationsStatus.go deleted file mode 100644 index 4f437bbe..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstanceAssociationsStatus.go +++ /dev/null @@ -1,243 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// The status of the associations for the managed node(s). -func (c *Client) DescribeInstanceAssociationsStatus(ctx context.Context, params *DescribeInstanceAssociationsStatusInput, optFns ...func(*Options)) (*DescribeInstanceAssociationsStatusOutput, error) { - if params == nil { - params = &DescribeInstanceAssociationsStatusInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeInstanceAssociationsStatus", params, optFns, c.addOperationDescribeInstanceAssociationsStatusMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeInstanceAssociationsStatusOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeInstanceAssociationsStatusInput struct { - - // The managed node IDs for which you want association status information. - // - // This member is required. - InstanceId *string - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeInstanceAssociationsStatusOutput struct { - - // Status information about the association. - InstanceAssociationStatusInfos []types.InstanceAssociationStatusInfo - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeInstanceAssociationsStatusMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeInstanceAssociationsStatus{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeInstanceAssociationsStatus{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeInstanceAssociationsStatus"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeInstanceAssociationsStatusValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeInstanceAssociationsStatus(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeInstanceAssociationsStatusAPIClient is a client that implements the -// DescribeInstanceAssociationsStatus operation. -type DescribeInstanceAssociationsStatusAPIClient interface { - DescribeInstanceAssociationsStatus(context.Context, *DescribeInstanceAssociationsStatusInput, ...func(*Options)) (*DescribeInstanceAssociationsStatusOutput, error) -} - -var _ DescribeInstanceAssociationsStatusAPIClient = (*Client)(nil) - -// DescribeInstanceAssociationsStatusPaginatorOptions is the paginator options for -// DescribeInstanceAssociationsStatus -type DescribeInstanceAssociationsStatusPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeInstanceAssociationsStatusPaginator is a paginator for -// DescribeInstanceAssociationsStatus -type DescribeInstanceAssociationsStatusPaginator struct { - options DescribeInstanceAssociationsStatusPaginatorOptions - client DescribeInstanceAssociationsStatusAPIClient - params *DescribeInstanceAssociationsStatusInput - nextToken *string - firstPage bool -} - -// NewDescribeInstanceAssociationsStatusPaginator returns a new -// DescribeInstanceAssociationsStatusPaginator -func NewDescribeInstanceAssociationsStatusPaginator(client DescribeInstanceAssociationsStatusAPIClient, params *DescribeInstanceAssociationsStatusInput, optFns ...func(*DescribeInstanceAssociationsStatusPaginatorOptions)) *DescribeInstanceAssociationsStatusPaginator { - if params == nil { - params = &DescribeInstanceAssociationsStatusInput{} - } - - options := DescribeInstanceAssociationsStatusPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeInstanceAssociationsStatusPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeInstanceAssociationsStatusPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeInstanceAssociationsStatus page. -func (p *DescribeInstanceAssociationsStatusPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeInstanceAssociationsStatusOutput, 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 - - result, err := p.client.DescribeInstanceAssociationsStatus(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 -} - -func newServiceMetadataMiddleware_opDescribeInstanceAssociationsStatus(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeInstanceAssociationsStatus", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstanceInformation.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstanceInformation.go deleted file mode 100644 index b133f5ad..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstanceInformation.go +++ /dev/null @@ -1,261 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Provides information about one or more of your managed nodes, including the -// operating system platform, SSM Agent version, association status, and IP -// address. This operation does not return information for nodes that are either -// Stopped or Terminated. If you specify one or more node IDs, the operation -// returns information for those managed nodes. If you don't specify node IDs, it -// returns information for all your managed nodes. If you specify a node ID that -// isn't valid or a node that you don't own, you receive an error. The IamRole -// field returned for this API operation is the Identity and Access Management -// (IAM) role assigned to on-premises managed nodes. This operation does not return -// the IAM role for EC2 instances. -func (c *Client) DescribeInstanceInformation(ctx context.Context, params *DescribeInstanceInformationInput, optFns ...func(*Options)) (*DescribeInstanceInformationOutput, error) { - if params == nil { - params = &DescribeInstanceInformationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeInstanceInformation", params, optFns, c.addOperationDescribeInstanceInformationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeInstanceInformationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeInstanceInformationInput struct { - - // One or more filters. Use a filter to return a more specific list of managed - // nodes. You can filter based on tags applied to your managed nodes. Tag filters - // can't be combined with other filter types. Use this Filters data type instead - // of InstanceInformationFilterList , which is deprecated. - Filters []types.InstanceInformationStringFilter - - // This is a legacy method. We recommend that you don't use this method. Instead, - // use the Filters data type. Filters enables you to return node information by - // filtering based on tags applied to managed nodes. Attempting to use - // InstanceInformationFilterList and Filters leads to an exception error. - InstanceInformationFilterList []types.InstanceInformationFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - // The default value is 10 items. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeInstanceInformationOutput struct { - - // The managed node information list. - InstanceInformationList []types.InstanceInformation - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeInstanceInformationMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeInstanceInformation{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeInstanceInformation{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeInstanceInformation"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeInstanceInformationValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeInstanceInformation(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeInstanceInformationAPIClient is a client that implements the -// DescribeInstanceInformation operation. -type DescribeInstanceInformationAPIClient interface { - DescribeInstanceInformation(context.Context, *DescribeInstanceInformationInput, ...func(*Options)) (*DescribeInstanceInformationOutput, error) -} - -var _ DescribeInstanceInformationAPIClient = (*Client)(nil) - -// DescribeInstanceInformationPaginatorOptions is the paginator options for -// DescribeInstanceInformation -type DescribeInstanceInformationPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - // The default value is 10 items. - 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 -} - -// DescribeInstanceInformationPaginator is a paginator for -// DescribeInstanceInformation -type DescribeInstanceInformationPaginator struct { - options DescribeInstanceInformationPaginatorOptions - client DescribeInstanceInformationAPIClient - params *DescribeInstanceInformationInput - nextToken *string - firstPage bool -} - -// NewDescribeInstanceInformationPaginator returns a new -// DescribeInstanceInformationPaginator -func NewDescribeInstanceInformationPaginator(client DescribeInstanceInformationAPIClient, params *DescribeInstanceInformationInput, optFns ...func(*DescribeInstanceInformationPaginatorOptions)) *DescribeInstanceInformationPaginator { - if params == nil { - params = &DescribeInstanceInformationInput{} - } - - options := DescribeInstanceInformationPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeInstanceInformationPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeInstanceInformationPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeInstanceInformation page. -func (p *DescribeInstanceInformationPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeInstanceInformationOutput, 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 - - result, err := p.client.DescribeInstanceInformation(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 -} - -func newServiceMetadataMiddleware_opDescribeInstanceInformation(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeInstanceInformation", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstancePatchStates.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstancePatchStates.go deleted file mode 100644 index 4c5d69c9..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstancePatchStates.go +++ /dev/null @@ -1,242 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the high-level patch state of one or more managed nodes. -func (c *Client) DescribeInstancePatchStates(ctx context.Context, params *DescribeInstancePatchStatesInput, optFns ...func(*Options)) (*DescribeInstancePatchStatesOutput, error) { - if params == nil { - params = &DescribeInstancePatchStatesInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeInstancePatchStates", params, optFns, c.addOperationDescribeInstancePatchStatesMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeInstancePatchStatesOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeInstancePatchStatesInput struct { - - // The ID of the managed node for which patch state information should be - // retrieved. - // - // This member is required. - InstanceIds []string - - // The maximum number of managed nodes to return (per page). - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeInstancePatchStatesOutput struct { - - // The high-level patch state for the requested managed nodes. - InstancePatchStates []types.InstancePatchState - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeInstancePatchStatesMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeInstancePatchStates{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeInstancePatchStates{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeInstancePatchStates"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeInstancePatchStatesValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeInstancePatchStates(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeInstancePatchStatesAPIClient is a client that implements the -// DescribeInstancePatchStates operation. -type DescribeInstancePatchStatesAPIClient interface { - DescribeInstancePatchStates(context.Context, *DescribeInstancePatchStatesInput, ...func(*Options)) (*DescribeInstancePatchStatesOutput, error) -} - -var _ DescribeInstancePatchStatesAPIClient = (*Client)(nil) - -// DescribeInstancePatchStatesPaginatorOptions is the paginator options for -// DescribeInstancePatchStates -type DescribeInstancePatchStatesPaginatorOptions struct { - // The maximum number of managed nodes to return (per page). - 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 -} - -// DescribeInstancePatchStatesPaginator is a paginator for -// DescribeInstancePatchStates -type DescribeInstancePatchStatesPaginator struct { - options DescribeInstancePatchStatesPaginatorOptions - client DescribeInstancePatchStatesAPIClient - params *DescribeInstancePatchStatesInput - nextToken *string - firstPage bool -} - -// NewDescribeInstancePatchStatesPaginator returns a new -// DescribeInstancePatchStatesPaginator -func NewDescribeInstancePatchStatesPaginator(client DescribeInstancePatchStatesAPIClient, params *DescribeInstancePatchStatesInput, optFns ...func(*DescribeInstancePatchStatesPaginatorOptions)) *DescribeInstancePatchStatesPaginator { - if params == nil { - params = &DescribeInstancePatchStatesInput{} - } - - options := DescribeInstancePatchStatesPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeInstancePatchStatesPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeInstancePatchStatesPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeInstancePatchStates page. -func (p *DescribeInstancePatchStatesPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeInstancePatchStatesOutput, 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 - - result, err := p.client.DescribeInstancePatchStates(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 -} - -func newServiceMetadataMiddleware_opDescribeInstancePatchStates(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeInstancePatchStates", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstancePatchStatesForPatchGroup.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstancePatchStatesForPatchGroup.go deleted file mode 100644 index 48bcb332..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstancePatchStatesForPatchGroup.go +++ /dev/null @@ -1,249 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the high-level patch state for the managed nodes in the specified -// patch group. -func (c *Client) DescribeInstancePatchStatesForPatchGroup(ctx context.Context, params *DescribeInstancePatchStatesForPatchGroupInput, optFns ...func(*Options)) (*DescribeInstancePatchStatesForPatchGroupOutput, error) { - if params == nil { - params = &DescribeInstancePatchStatesForPatchGroupInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeInstancePatchStatesForPatchGroup", params, optFns, c.addOperationDescribeInstancePatchStatesForPatchGroupMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeInstancePatchStatesForPatchGroupOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeInstancePatchStatesForPatchGroupInput struct { - - // The name of the patch group for which the patch state information should be - // retrieved. - // - // This member is required. - PatchGroup *string - - // Each entry in the array is a structure containing: - // - Key (string between 1 and 200 characters) - // - Values (array containing a single string) - // - Type (string "Equal", "NotEqual", "LessThan", "GreaterThan") - Filters []types.InstancePatchStateFilter - - // The maximum number of patches to return (per page). - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeInstancePatchStatesForPatchGroupOutput struct { - - // The high-level patch state for the requested managed nodes. - InstancePatchStates []types.InstancePatchState - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeInstancePatchStatesForPatchGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeInstancePatchStatesForPatchGroup{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeInstancePatchStatesForPatchGroup{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeInstancePatchStatesForPatchGroup"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeInstancePatchStatesForPatchGroupValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeInstancePatchStatesForPatchGroup(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeInstancePatchStatesForPatchGroupAPIClient is a client that implements -// the DescribeInstancePatchStatesForPatchGroup operation. -type DescribeInstancePatchStatesForPatchGroupAPIClient interface { - DescribeInstancePatchStatesForPatchGroup(context.Context, *DescribeInstancePatchStatesForPatchGroupInput, ...func(*Options)) (*DescribeInstancePatchStatesForPatchGroupOutput, error) -} - -var _ DescribeInstancePatchStatesForPatchGroupAPIClient = (*Client)(nil) - -// DescribeInstancePatchStatesForPatchGroupPaginatorOptions is the paginator -// options for DescribeInstancePatchStatesForPatchGroup -type DescribeInstancePatchStatesForPatchGroupPaginatorOptions struct { - // The maximum number of patches to return (per page). - 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 -} - -// DescribeInstancePatchStatesForPatchGroupPaginator is a paginator for -// DescribeInstancePatchStatesForPatchGroup -type DescribeInstancePatchStatesForPatchGroupPaginator struct { - options DescribeInstancePatchStatesForPatchGroupPaginatorOptions - client DescribeInstancePatchStatesForPatchGroupAPIClient - params *DescribeInstancePatchStatesForPatchGroupInput - nextToken *string - firstPage bool -} - -// NewDescribeInstancePatchStatesForPatchGroupPaginator returns a new -// DescribeInstancePatchStatesForPatchGroupPaginator -func NewDescribeInstancePatchStatesForPatchGroupPaginator(client DescribeInstancePatchStatesForPatchGroupAPIClient, params *DescribeInstancePatchStatesForPatchGroupInput, optFns ...func(*DescribeInstancePatchStatesForPatchGroupPaginatorOptions)) *DescribeInstancePatchStatesForPatchGroupPaginator { - if params == nil { - params = &DescribeInstancePatchStatesForPatchGroupInput{} - } - - options := DescribeInstancePatchStatesForPatchGroupPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeInstancePatchStatesForPatchGroupPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeInstancePatchStatesForPatchGroupPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeInstancePatchStatesForPatchGroup page. -func (p *DescribeInstancePatchStatesForPatchGroupPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeInstancePatchStatesForPatchGroupOutput, 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 - - result, err := p.client.DescribeInstancePatchStatesForPatchGroup(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 -} - -func newServiceMetadataMiddleware_opDescribeInstancePatchStatesForPatchGroup(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeInstancePatchStatesForPatchGroup", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstancePatches.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstancePatches.go deleted file mode 100644 index 045aade1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInstancePatches.go +++ /dev/null @@ -1,258 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves information about the patches on the specified managed node and their -// state relative to the patch baseline being used for the node. -func (c *Client) DescribeInstancePatches(ctx context.Context, params *DescribeInstancePatchesInput, optFns ...func(*Options)) (*DescribeInstancePatchesOutput, error) { - if params == nil { - params = &DescribeInstancePatchesInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeInstancePatches", params, optFns, c.addOperationDescribeInstancePatchesMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeInstancePatchesOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeInstancePatchesInput struct { - - // The ID of the managed node whose patch state information should be retrieved. - // - // This member is required. - InstanceId *string - - // Each element in the array is a structure containing a key-value pair. Supported - // keys for DescribeInstancePatches include the following: - // - Classification Sample values: Security | SecurityUpdates - // - KBId Sample values: KB4480056 | java-1.7.0-openjdk.x86_64 - // - Severity Sample values: Important | Medium | Low - // - State Sample values: Installed | InstalledOther | InstalledPendingReboot For - // lists of all State values, see Understanding patch compliance state values (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-compliance-states.html) - // in the Amazon Web Services Systems Manager User Guide. - Filters []types.PatchOrchestratorFilter - - // The maximum number of patches to return (per page). - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeInstancePatchesOutput struct { - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Each entry in the array is a structure containing: - // - Title (string) - // - KBId (string) - // - Classification (string) - // - Severity (string) - // - State (string, such as "INSTALLED" or "FAILED") - // - InstalledTime (DateTime) - // - InstalledBy (string) - Patches []types.PatchComplianceData - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeInstancePatchesMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeInstancePatches{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeInstancePatches{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeInstancePatches"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeInstancePatchesValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeInstancePatches(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeInstancePatchesAPIClient is a client that implements the -// DescribeInstancePatches operation. -type DescribeInstancePatchesAPIClient interface { - DescribeInstancePatches(context.Context, *DescribeInstancePatchesInput, ...func(*Options)) (*DescribeInstancePatchesOutput, error) -} - -var _ DescribeInstancePatchesAPIClient = (*Client)(nil) - -// DescribeInstancePatchesPaginatorOptions is the paginator options for -// DescribeInstancePatches -type DescribeInstancePatchesPaginatorOptions struct { - // The maximum number of patches to return (per page). - 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 -} - -// DescribeInstancePatchesPaginator is a paginator for DescribeInstancePatches -type DescribeInstancePatchesPaginator struct { - options DescribeInstancePatchesPaginatorOptions - client DescribeInstancePatchesAPIClient - params *DescribeInstancePatchesInput - nextToken *string - firstPage bool -} - -// NewDescribeInstancePatchesPaginator returns a new -// DescribeInstancePatchesPaginator -func NewDescribeInstancePatchesPaginator(client DescribeInstancePatchesAPIClient, params *DescribeInstancePatchesInput, optFns ...func(*DescribeInstancePatchesPaginatorOptions)) *DescribeInstancePatchesPaginator { - if params == nil { - params = &DescribeInstancePatchesInput{} - } - - options := DescribeInstancePatchesPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeInstancePatchesPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeInstancePatchesPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeInstancePatches page. -func (p *DescribeInstancePatchesPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeInstancePatchesOutput, 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 - - result, err := p.client.DescribeInstancePatches(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 -} - -func newServiceMetadataMiddleware_opDescribeInstancePatches(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeInstancePatches", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInventoryDeletions.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInventoryDeletions.go deleted file mode 100644 index 06982c26..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeInventoryDeletions.go +++ /dev/null @@ -1,238 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Describes a specific delete inventory operation. -func (c *Client) DescribeInventoryDeletions(ctx context.Context, params *DescribeInventoryDeletionsInput, optFns ...func(*Options)) (*DescribeInventoryDeletionsOutput, error) { - if params == nil { - params = &DescribeInventoryDeletionsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeInventoryDeletions", params, optFns, c.addOperationDescribeInventoryDeletionsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeInventoryDeletionsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeInventoryDeletionsInput struct { - - // Specify the delete inventory ID for which you want information. This ID was - // returned by the DeleteInventory operation. - DeletionId *string - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeInventoryDeletionsOutput struct { - - // A list of status items for deleted inventory. - InventoryDeletions []types.InventoryDeletionStatusItem - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeInventoryDeletionsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeInventoryDeletions{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeInventoryDeletions{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeInventoryDeletions"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeInventoryDeletions(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeInventoryDeletionsAPIClient is a client that implements the -// DescribeInventoryDeletions operation. -type DescribeInventoryDeletionsAPIClient interface { - DescribeInventoryDeletions(context.Context, *DescribeInventoryDeletionsInput, ...func(*Options)) (*DescribeInventoryDeletionsOutput, error) -} - -var _ DescribeInventoryDeletionsAPIClient = (*Client)(nil) - -// DescribeInventoryDeletionsPaginatorOptions is the paginator options for -// DescribeInventoryDeletions -type DescribeInventoryDeletionsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeInventoryDeletionsPaginator is a paginator for -// DescribeInventoryDeletions -type DescribeInventoryDeletionsPaginator struct { - options DescribeInventoryDeletionsPaginatorOptions - client DescribeInventoryDeletionsAPIClient - params *DescribeInventoryDeletionsInput - nextToken *string - firstPage bool -} - -// NewDescribeInventoryDeletionsPaginator returns a new -// DescribeInventoryDeletionsPaginator -func NewDescribeInventoryDeletionsPaginator(client DescribeInventoryDeletionsAPIClient, params *DescribeInventoryDeletionsInput, optFns ...func(*DescribeInventoryDeletionsPaginatorOptions)) *DescribeInventoryDeletionsPaginator { - if params == nil { - params = &DescribeInventoryDeletionsInput{} - } - - options := DescribeInventoryDeletionsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeInventoryDeletionsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeInventoryDeletionsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeInventoryDeletions page. -func (p *DescribeInventoryDeletionsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeInventoryDeletionsOutput, 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 - - result, err := p.client.DescribeInventoryDeletions(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 -} - -func newServiceMetadataMiddleware_opDescribeInventoryDeletions(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeInventoryDeletions", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowExecutionTaskInvocations.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowExecutionTaskInvocations.go deleted file mode 100644 index 7adfd3c1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowExecutionTaskInvocations.go +++ /dev/null @@ -1,256 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the individual task executions (one per target) for a particular task -// run as part of a maintenance window execution. -func (c *Client) DescribeMaintenanceWindowExecutionTaskInvocations(ctx context.Context, params *DescribeMaintenanceWindowExecutionTaskInvocationsInput, optFns ...func(*Options)) (*DescribeMaintenanceWindowExecutionTaskInvocationsOutput, error) { - if params == nil { - params = &DescribeMaintenanceWindowExecutionTaskInvocationsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeMaintenanceWindowExecutionTaskInvocations", params, optFns, c.addOperationDescribeMaintenanceWindowExecutionTaskInvocationsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeMaintenanceWindowExecutionTaskInvocationsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeMaintenanceWindowExecutionTaskInvocationsInput struct { - - // The ID of the specific task in the maintenance window task that should be - // retrieved. - // - // This member is required. - TaskId *string - - // The ID of the maintenance window execution the task is part of. - // - // This member is required. - WindowExecutionId *string - - // Optional filters used to scope down the returned task invocations. The - // supported filter key is STATUS with the corresponding values PENDING , - // IN_PROGRESS , SUCCESS , FAILED , TIMED_OUT , CANCELLING , and CANCELLED . - Filters []types.MaintenanceWindowFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeMaintenanceWindowExecutionTaskInvocationsOutput struct { - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Information about the task invocation results per invocation. - WindowExecutionTaskInvocationIdentities []types.MaintenanceWindowExecutionTaskInvocationIdentity - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeMaintenanceWindowExecutionTaskInvocationsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutionTaskInvocations{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutionTaskInvocations{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeMaintenanceWindowExecutionTaskInvocations"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeMaintenanceWindowExecutionTaskInvocationsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeMaintenanceWindowExecutionTaskInvocations(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeMaintenanceWindowExecutionTaskInvocationsAPIClient is a client that -// implements the DescribeMaintenanceWindowExecutionTaskInvocations operation. -type DescribeMaintenanceWindowExecutionTaskInvocationsAPIClient interface { - DescribeMaintenanceWindowExecutionTaskInvocations(context.Context, *DescribeMaintenanceWindowExecutionTaskInvocationsInput, ...func(*Options)) (*DescribeMaintenanceWindowExecutionTaskInvocationsOutput, error) -} - -var _ DescribeMaintenanceWindowExecutionTaskInvocationsAPIClient = (*Client)(nil) - -// DescribeMaintenanceWindowExecutionTaskInvocationsPaginatorOptions is the -// paginator options for DescribeMaintenanceWindowExecutionTaskInvocations -type DescribeMaintenanceWindowExecutionTaskInvocationsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeMaintenanceWindowExecutionTaskInvocationsPaginator is a paginator for -// DescribeMaintenanceWindowExecutionTaskInvocations -type DescribeMaintenanceWindowExecutionTaskInvocationsPaginator struct { - options DescribeMaintenanceWindowExecutionTaskInvocationsPaginatorOptions - client DescribeMaintenanceWindowExecutionTaskInvocationsAPIClient - params *DescribeMaintenanceWindowExecutionTaskInvocationsInput - nextToken *string - firstPage bool -} - -// NewDescribeMaintenanceWindowExecutionTaskInvocationsPaginator returns a new -// DescribeMaintenanceWindowExecutionTaskInvocationsPaginator -func NewDescribeMaintenanceWindowExecutionTaskInvocationsPaginator(client DescribeMaintenanceWindowExecutionTaskInvocationsAPIClient, params *DescribeMaintenanceWindowExecutionTaskInvocationsInput, optFns ...func(*DescribeMaintenanceWindowExecutionTaskInvocationsPaginatorOptions)) *DescribeMaintenanceWindowExecutionTaskInvocationsPaginator { - if params == nil { - params = &DescribeMaintenanceWindowExecutionTaskInvocationsInput{} - } - - options := DescribeMaintenanceWindowExecutionTaskInvocationsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeMaintenanceWindowExecutionTaskInvocationsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeMaintenanceWindowExecutionTaskInvocationsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeMaintenanceWindowExecutionTaskInvocations -// page. -func (p *DescribeMaintenanceWindowExecutionTaskInvocationsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeMaintenanceWindowExecutionTaskInvocationsOutput, 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 - - result, err := p.client.DescribeMaintenanceWindowExecutionTaskInvocations(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 -} - -func newServiceMetadataMiddleware_opDescribeMaintenanceWindowExecutionTaskInvocations(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeMaintenanceWindowExecutionTaskInvocations", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowExecutionTasks.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowExecutionTasks.go deleted file mode 100644 index b3983b32..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowExecutionTasks.go +++ /dev/null @@ -1,249 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// For a given maintenance window execution, lists the tasks that were run. -func (c *Client) DescribeMaintenanceWindowExecutionTasks(ctx context.Context, params *DescribeMaintenanceWindowExecutionTasksInput, optFns ...func(*Options)) (*DescribeMaintenanceWindowExecutionTasksOutput, error) { - if params == nil { - params = &DescribeMaintenanceWindowExecutionTasksInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeMaintenanceWindowExecutionTasks", params, optFns, c.addOperationDescribeMaintenanceWindowExecutionTasksMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeMaintenanceWindowExecutionTasksOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeMaintenanceWindowExecutionTasksInput struct { - - // The ID of the maintenance window execution whose task executions should be - // retrieved. - // - // This member is required. - WindowExecutionId *string - - // Optional filters used to scope down the returned tasks. The supported filter - // key is STATUS with the corresponding values PENDING , IN_PROGRESS , SUCCESS , - // FAILED , TIMED_OUT , CANCELLING , and CANCELLED . - Filters []types.MaintenanceWindowFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeMaintenanceWindowExecutionTasksOutput struct { - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Information about the task executions. - WindowExecutionTaskIdentities []types.MaintenanceWindowExecutionTaskIdentity - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeMaintenanceWindowExecutionTasksMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutionTasks{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutionTasks{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeMaintenanceWindowExecutionTasks"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeMaintenanceWindowExecutionTasksValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeMaintenanceWindowExecutionTasks(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeMaintenanceWindowExecutionTasksAPIClient is a client that implements -// the DescribeMaintenanceWindowExecutionTasks operation. -type DescribeMaintenanceWindowExecutionTasksAPIClient interface { - DescribeMaintenanceWindowExecutionTasks(context.Context, *DescribeMaintenanceWindowExecutionTasksInput, ...func(*Options)) (*DescribeMaintenanceWindowExecutionTasksOutput, error) -} - -var _ DescribeMaintenanceWindowExecutionTasksAPIClient = (*Client)(nil) - -// DescribeMaintenanceWindowExecutionTasksPaginatorOptions is the paginator -// options for DescribeMaintenanceWindowExecutionTasks -type DescribeMaintenanceWindowExecutionTasksPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeMaintenanceWindowExecutionTasksPaginator is a paginator for -// DescribeMaintenanceWindowExecutionTasks -type DescribeMaintenanceWindowExecutionTasksPaginator struct { - options DescribeMaintenanceWindowExecutionTasksPaginatorOptions - client DescribeMaintenanceWindowExecutionTasksAPIClient - params *DescribeMaintenanceWindowExecutionTasksInput - nextToken *string - firstPage bool -} - -// NewDescribeMaintenanceWindowExecutionTasksPaginator returns a new -// DescribeMaintenanceWindowExecutionTasksPaginator -func NewDescribeMaintenanceWindowExecutionTasksPaginator(client DescribeMaintenanceWindowExecutionTasksAPIClient, params *DescribeMaintenanceWindowExecutionTasksInput, optFns ...func(*DescribeMaintenanceWindowExecutionTasksPaginatorOptions)) *DescribeMaintenanceWindowExecutionTasksPaginator { - if params == nil { - params = &DescribeMaintenanceWindowExecutionTasksInput{} - } - - options := DescribeMaintenanceWindowExecutionTasksPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeMaintenanceWindowExecutionTasksPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeMaintenanceWindowExecutionTasksPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeMaintenanceWindowExecutionTasks page. -func (p *DescribeMaintenanceWindowExecutionTasksPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeMaintenanceWindowExecutionTasksOutput, 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 - - result, err := p.client.DescribeMaintenanceWindowExecutionTasks(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 -} - -func newServiceMetadataMiddleware_opDescribeMaintenanceWindowExecutionTasks(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeMaintenanceWindowExecutionTasks", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowExecutions.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowExecutions.go deleted file mode 100644 index d3da2f1c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowExecutions.go +++ /dev/null @@ -1,253 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists the executions of a maintenance window. This includes information about -// when the maintenance window was scheduled to be active, and information about -// tasks registered and run with the maintenance window. -func (c *Client) DescribeMaintenanceWindowExecutions(ctx context.Context, params *DescribeMaintenanceWindowExecutionsInput, optFns ...func(*Options)) (*DescribeMaintenanceWindowExecutionsOutput, error) { - if params == nil { - params = &DescribeMaintenanceWindowExecutionsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeMaintenanceWindowExecutions", params, optFns, c.addOperationDescribeMaintenanceWindowExecutionsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeMaintenanceWindowExecutionsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeMaintenanceWindowExecutionsInput struct { - - // The ID of the maintenance window whose executions should be retrieved. - // - // This member is required. - WindowId *string - - // Each entry in the array is a structure containing: - // - Key. A string between 1 and 128 characters. Supported keys include - // ExecutedBefore and ExecutedAfter . - // - Values. An array of strings, each between 1 and 256 characters. Supported - // values are date/time strings in a valid ISO 8601 date/time format, such as - // 2021-11-04T05:00:00Z . - Filters []types.MaintenanceWindowFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeMaintenanceWindowExecutionsOutput struct { - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Information about the maintenance window executions. - WindowExecutions []types.MaintenanceWindowExecution - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeMaintenanceWindowExecutionsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutions{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutions{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeMaintenanceWindowExecutions"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeMaintenanceWindowExecutionsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeMaintenanceWindowExecutions(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeMaintenanceWindowExecutionsAPIClient is a client that implements the -// DescribeMaintenanceWindowExecutions operation. -type DescribeMaintenanceWindowExecutionsAPIClient interface { - DescribeMaintenanceWindowExecutions(context.Context, *DescribeMaintenanceWindowExecutionsInput, ...func(*Options)) (*DescribeMaintenanceWindowExecutionsOutput, error) -} - -var _ DescribeMaintenanceWindowExecutionsAPIClient = (*Client)(nil) - -// DescribeMaintenanceWindowExecutionsPaginatorOptions is the paginator options -// for DescribeMaintenanceWindowExecutions -type DescribeMaintenanceWindowExecutionsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeMaintenanceWindowExecutionsPaginator is a paginator for -// DescribeMaintenanceWindowExecutions -type DescribeMaintenanceWindowExecutionsPaginator struct { - options DescribeMaintenanceWindowExecutionsPaginatorOptions - client DescribeMaintenanceWindowExecutionsAPIClient - params *DescribeMaintenanceWindowExecutionsInput - nextToken *string - firstPage bool -} - -// NewDescribeMaintenanceWindowExecutionsPaginator returns a new -// DescribeMaintenanceWindowExecutionsPaginator -func NewDescribeMaintenanceWindowExecutionsPaginator(client DescribeMaintenanceWindowExecutionsAPIClient, params *DescribeMaintenanceWindowExecutionsInput, optFns ...func(*DescribeMaintenanceWindowExecutionsPaginatorOptions)) *DescribeMaintenanceWindowExecutionsPaginator { - if params == nil { - params = &DescribeMaintenanceWindowExecutionsInput{} - } - - options := DescribeMaintenanceWindowExecutionsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeMaintenanceWindowExecutionsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeMaintenanceWindowExecutionsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeMaintenanceWindowExecutions page. -func (p *DescribeMaintenanceWindowExecutionsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeMaintenanceWindowExecutionsOutput, 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 - - result, err := p.client.DescribeMaintenanceWindowExecutions(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 -} - -func newServiceMetadataMiddleware_opDescribeMaintenanceWindowExecutions(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeMaintenanceWindowExecutions", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowSchedule.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowSchedule.go deleted file mode 100644 index 942a9c2f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowSchedule.go +++ /dev/null @@ -1,251 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves information about upcoming executions of a maintenance window. -func (c *Client) DescribeMaintenanceWindowSchedule(ctx context.Context, params *DescribeMaintenanceWindowScheduleInput, optFns ...func(*Options)) (*DescribeMaintenanceWindowScheduleOutput, error) { - if params == nil { - params = &DescribeMaintenanceWindowScheduleInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeMaintenanceWindowSchedule", params, optFns, c.addOperationDescribeMaintenanceWindowScheduleMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeMaintenanceWindowScheduleOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeMaintenanceWindowScheduleInput struct { - - // Filters used to limit the range of results. For example, you can limit - // maintenance window executions to only those scheduled before or after a certain - // date and time. - Filters []types.PatchOrchestratorFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - // The type of resource you want to retrieve information about. For example, - // INSTANCE . - ResourceType types.MaintenanceWindowResourceType - - // The managed node ID or key-value pair to retrieve information about. - Targets []types.Target - - // The ID of the maintenance window to retrieve information about. - WindowId *string - - noSmithyDocumentSerde -} - -type DescribeMaintenanceWindowScheduleOutput struct { - - // The token for the next set of items to return. (You use this token in the next - // call.) - NextToken *string - - // Information about maintenance window executions scheduled for the specified - // time range. - ScheduledWindowExecutions []types.ScheduledWindowExecution - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeMaintenanceWindowScheduleMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeMaintenanceWindowSchedule{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeMaintenanceWindowSchedule{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeMaintenanceWindowSchedule"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeMaintenanceWindowSchedule(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeMaintenanceWindowScheduleAPIClient is a client that implements the -// DescribeMaintenanceWindowSchedule operation. -type DescribeMaintenanceWindowScheduleAPIClient interface { - DescribeMaintenanceWindowSchedule(context.Context, *DescribeMaintenanceWindowScheduleInput, ...func(*Options)) (*DescribeMaintenanceWindowScheduleOutput, error) -} - -var _ DescribeMaintenanceWindowScheduleAPIClient = (*Client)(nil) - -// DescribeMaintenanceWindowSchedulePaginatorOptions is the paginator options for -// DescribeMaintenanceWindowSchedule -type DescribeMaintenanceWindowSchedulePaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeMaintenanceWindowSchedulePaginator is a paginator for -// DescribeMaintenanceWindowSchedule -type DescribeMaintenanceWindowSchedulePaginator struct { - options DescribeMaintenanceWindowSchedulePaginatorOptions - client DescribeMaintenanceWindowScheduleAPIClient - params *DescribeMaintenanceWindowScheduleInput - nextToken *string - firstPage bool -} - -// NewDescribeMaintenanceWindowSchedulePaginator returns a new -// DescribeMaintenanceWindowSchedulePaginator -func NewDescribeMaintenanceWindowSchedulePaginator(client DescribeMaintenanceWindowScheduleAPIClient, params *DescribeMaintenanceWindowScheduleInput, optFns ...func(*DescribeMaintenanceWindowSchedulePaginatorOptions)) *DescribeMaintenanceWindowSchedulePaginator { - if params == nil { - params = &DescribeMaintenanceWindowScheduleInput{} - } - - options := DescribeMaintenanceWindowSchedulePaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeMaintenanceWindowSchedulePaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeMaintenanceWindowSchedulePaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeMaintenanceWindowSchedule page. -func (p *DescribeMaintenanceWindowSchedulePaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeMaintenanceWindowScheduleOutput, 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 - - result, err := p.client.DescribeMaintenanceWindowSchedule(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 -} - -func newServiceMetadataMiddleware_opDescribeMaintenanceWindowSchedule(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeMaintenanceWindowSchedule", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowTargets.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowTargets.go deleted file mode 100644 index 922c3705..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowTargets.go +++ /dev/null @@ -1,248 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists the targets registered with the maintenance window. -func (c *Client) DescribeMaintenanceWindowTargets(ctx context.Context, params *DescribeMaintenanceWindowTargetsInput, optFns ...func(*Options)) (*DescribeMaintenanceWindowTargetsOutput, error) { - if params == nil { - params = &DescribeMaintenanceWindowTargetsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeMaintenanceWindowTargets", params, optFns, c.addOperationDescribeMaintenanceWindowTargetsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeMaintenanceWindowTargetsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeMaintenanceWindowTargetsInput struct { - - // The ID of the maintenance window whose targets should be retrieved. - // - // This member is required. - WindowId *string - - // Optional filters that can be used to narrow down the scope of the returned - // window targets. The supported filter keys are Type , WindowTargetId , and - // OwnerInformation . - Filters []types.MaintenanceWindowFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeMaintenanceWindowTargetsOutput struct { - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Information about the targets in the maintenance window. - Targets []types.MaintenanceWindowTarget - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeMaintenanceWindowTargetsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeMaintenanceWindowTargets{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeMaintenanceWindowTargets{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeMaintenanceWindowTargets"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeMaintenanceWindowTargetsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeMaintenanceWindowTargets(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeMaintenanceWindowTargetsAPIClient is a client that implements the -// DescribeMaintenanceWindowTargets operation. -type DescribeMaintenanceWindowTargetsAPIClient interface { - DescribeMaintenanceWindowTargets(context.Context, *DescribeMaintenanceWindowTargetsInput, ...func(*Options)) (*DescribeMaintenanceWindowTargetsOutput, error) -} - -var _ DescribeMaintenanceWindowTargetsAPIClient = (*Client)(nil) - -// DescribeMaintenanceWindowTargetsPaginatorOptions is the paginator options for -// DescribeMaintenanceWindowTargets -type DescribeMaintenanceWindowTargetsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeMaintenanceWindowTargetsPaginator is a paginator for -// DescribeMaintenanceWindowTargets -type DescribeMaintenanceWindowTargetsPaginator struct { - options DescribeMaintenanceWindowTargetsPaginatorOptions - client DescribeMaintenanceWindowTargetsAPIClient - params *DescribeMaintenanceWindowTargetsInput - nextToken *string - firstPage bool -} - -// NewDescribeMaintenanceWindowTargetsPaginator returns a new -// DescribeMaintenanceWindowTargetsPaginator -func NewDescribeMaintenanceWindowTargetsPaginator(client DescribeMaintenanceWindowTargetsAPIClient, params *DescribeMaintenanceWindowTargetsInput, optFns ...func(*DescribeMaintenanceWindowTargetsPaginatorOptions)) *DescribeMaintenanceWindowTargetsPaginator { - if params == nil { - params = &DescribeMaintenanceWindowTargetsInput{} - } - - options := DescribeMaintenanceWindowTargetsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeMaintenanceWindowTargetsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeMaintenanceWindowTargetsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeMaintenanceWindowTargets page. -func (p *DescribeMaintenanceWindowTargetsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeMaintenanceWindowTargetsOutput, 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 - - result, err := p.client.DescribeMaintenanceWindowTargets(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 -} - -func newServiceMetadataMiddleware_opDescribeMaintenanceWindowTargets(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeMaintenanceWindowTargets", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowTasks.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowTasks.go deleted file mode 100644 index e4824249..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowTasks.go +++ /dev/null @@ -1,251 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists the tasks in a maintenance window. For maintenance window tasks without a -// specified target, you can't supply values for --max-errors and --max-concurrency -// . Instead, the system inserts a placeholder value of 1 , which may be reported -// in the response to this command. These values don't affect the running of your -// task and can be ignored. -func (c *Client) DescribeMaintenanceWindowTasks(ctx context.Context, params *DescribeMaintenanceWindowTasksInput, optFns ...func(*Options)) (*DescribeMaintenanceWindowTasksOutput, error) { - if params == nil { - params = &DescribeMaintenanceWindowTasksInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeMaintenanceWindowTasks", params, optFns, c.addOperationDescribeMaintenanceWindowTasksMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeMaintenanceWindowTasksOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeMaintenanceWindowTasksInput struct { - - // The ID of the maintenance window whose tasks should be retrieved. - // - // This member is required. - WindowId *string - - // Optional filters used to narrow down the scope of the returned tasks. The - // supported filter keys are WindowTaskId , TaskArn , Priority , and TaskType . - Filters []types.MaintenanceWindowFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeMaintenanceWindowTasksOutput struct { - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Information about the tasks in the maintenance window. - Tasks []types.MaintenanceWindowTask - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeMaintenanceWindowTasksMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeMaintenanceWindowTasks{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeMaintenanceWindowTasks{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeMaintenanceWindowTasks"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeMaintenanceWindowTasksValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeMaintenanceWindowTasks(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeMaintenanceWindowTasksAPIClient is a client that implements the -// DescribeMaintenanceWindowTasks operation. -type DescribeMaintenanceWindowTasksAPIClient interface { - DescribeMaintenanceWindowTasks(context.Context, *DescribeMaintenanceWindowTasksInput, ...func(*Options)) (*DescribeMaintenanceWindowTasksOutput, error) -} - -var _ DescribeMaintenanceWindowTasksAPIClient = (*Client)(nil) - -// DescribeMaintenanceWindowTasksPaginatorOptions is the paginator options for -// DescribeMaintenanceWindowTasks -type DescribeMaintenanceWindowTasksPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeMaintenanceWindowTasksPaginator is a paginator for -// DescribeMaintenanceWindowTasks -type DescribeMaintenanceWindowTasksPaginator struct { - options DescribeMaintenanceWindowTasksPaginatorOptions - client DescribeMaintenanceWindowTasksAPIClient - params *DescribeMaintenanceWindowTasksInput - nextToken *string - firstPage bool -} - -// NewDescribeMaintenanceWindowTasksPaginator returns a new -// DescribeMaintenanceWindowTasksPaginator -func NewDescribeMaintenanceWindowTasksPaginator(client DescribeMaintenanceWindowTasksAPIClient, params *DescribeMaintenanceWindowTasksInput, optFns ...func(*DescribeMaintenanceWindowTasksPaginatorOptions)) *DescribeMaintenanceWindowTasksPaginator { - if params == nil { - params = &DescribeMaintenanceWindowTasksInput{} - } - - options := DescribeMaintenanceWindowTasksPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeMaintenanceWindowTasksPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeMaintenanceWindowTasksPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeMaintenanceWindowTasks page. -func (p *DescribeMaintenanceWindowTasksPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeMaintenanceWindowTasksOutput, 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 - - result, err := p.client.DescribeMaintenanceWindowTasks(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 -} - -func newServiceMetadataMiddleware_opDescribeMaintenanceWindowTasks(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeMaintenanceWindowTasks", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindows.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindows.go deleted file mode 100644 index b8929059..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindows.go +++ /dev/null @@ -1,240 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the maintenance windows in an Amazon Web Services account. -func (c *Client) DescribeMaintenanceWindows(ctx context.Context, params *DescribeMaintenanceWindowsInput, optFns ...func(*Options)) (*DescribeMaintenanceWindowsOutput, error) { - if params == nil { - params = &DescribeMaintenanceWindowsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeMaintenanceWindows", params, optFns, c.addOperationDescribeMaintenanceWindowsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeMaintenanceWindowsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeMaintenanceWindowsInput struct { - - // Optional filters used to narrow down the scope of the returned maintenance - // windows. Supported filter keys are Name and Enabled . For example, - // Name=MyMaintenanceWindow and Enabled=True . - Filters []types.MaintenanceWindowFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeMaintenanceWindowsOutput struct { - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Information about the maintenance windows. - WindowIdentities []types.MaintenanceWindowIdentity - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeMaintenanceWindowsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeMaintenanceWindows{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeMaintenanceWindows{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeMaintenanceWindows"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeMaintenanceWindows(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeMaintenanceWindowsAPIClient is a client that implements the -// DescribeMaintenanceWindows operation. -type DescribeMaintenanceWindowsAPIClient interface { - DescribeMaintenanceWindows(context.Context, *DescribeMaintenanceWindowsInput, ...func(*Options)) (*DescribeMaintenanceWindowsOutput, error) -} - -var _ DescribeMaintenanceWindowsAPIClient = (*Client)(nil) - -// DescribeMaintenanceWindowsPaginatorOptions is the paginator options for -// DescribeMaintenanceWindows -type DescribeMaintenanceWindowsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeMaintenanceWindowsPaginator is a paginator for -// DescribeMaintenanceWindows -type DescribeMaintenanceWindowsPaginator struct { - options DescribeMaintenanceWindowsPaginatorOptions - client DescribeMaintenanceWindowsAPIClient - params *DescribeMaintenanceWindowsInput - nextToken *string - firstPage bool -} - -// NewDescribeMaintenanceWindowsPaginator returns a new -// DescribeMaintenanceWindowsPaginator -func NewDescribeMaintenanceWindowsPaginator(client DescribeMaintenanceWindowsAPIClient, params *DescribeMaintenanceWindowsInput, optFns ...func(*DescribeMaintenanceWindowsPaginatorOptions)) *DescribeMaintenanceWindowsPaginator { - if params == nil { - params = &DescribeMaintenanceWindowsInput{} - } - - options := DescribeMaintenanceWindowsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeMaintenanceWindowsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeMaintenanceWindowsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeMaintenanceWindows page. -func (p *DescribeMaintenanceWindowsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeMaintenanceWindowsOutput, 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 - - result, err := p.client.DescribeMaintenanceWindows(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 -} - -func newServiceMetadataMiddleware_opDescribeMaintenanceWindows(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeMaintenanceWindows", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowsForTarget.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowsForTarget.go deleted file mode 100644 index aabf1a53..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeMaintenanceWindowsForTarget.go +++ /dev/null @@ -1,251 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves information about the maintenance window targets or tasks that a -// managed node is associated with. -func (c *Client) DescribeMaintenanceWindowsForTarget(ctx context.Context, params *DescribeMaintenanceWindowsForTargetInput, optFns ...func(*Options)) (*DescribeMaintenanceWindowsForTargetOutput, error) { - if params == nil { - params = &DescribeMaintenanceWindowsForTargetInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeMaintenanceWindowsForTarget", params, optFns, c.addOperationDescribeMaintenanceWindowsForTargetMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeMaintenanceWindowsForTargetOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeMaintenanceWindowsForTargetInput struct { - - // The type of resource you want to retrieve information about. For example, - // INSTANCE . - // - // This member is required. - ResourceType types.MaintenanceWindowResourceType - - // The managed node ID or key-value pair to retrieve information about. - // - // This member is required. - Targets []types.Target - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeMaintenanceWindowsForTargetOutput struct { - - // The token for the next set of items to return. (You use this token in the next - // call.) - NextToken *string - - // Information about the maintenance window targets and tasks a managed node is - // associated with. - WindowIdentities []types.MaintenanceWindowIdentityForTarget - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeMaintenanceWindowsForTargetMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeMaintenanceWindowsForTarget{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeMaintenanceWindowsForTarget{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeMaintenanceWindowsForTarget"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeMaintenanceWindowsForTargetValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeMaintenanceWindowsForTarget(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeMaintenanceWindowsForTargetAPIClient is a client that implements the -// DescribeMaintenanceWindowsForTarget operation. -type DescribeMaintenanceWindowsForTargetAPIClient interface { - DescribeMaintenanceWindowsForTarget(context.Context, *DescribeMaintenanceWindowsForTargetInput, ...func(*Options)) (*DescribeMaintenanceWindowsForTargetOutput, error) -} - -var _ DescribeMaintenanceWindowsForTargetAPIClient = (*Client)(nil) - -// DescribeMaintenanceWindowsForTargetPaginatorOptions is the paginator options -// for DescribeMaintenanceWindowsForTarget -type DescribeMaintenanceWindowsForTargetPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeMaintenanceWindowsForTargetPaginator is a paginator for -// DescribeMaintenanceWindowsForTarget -type DescribeMaintenanceWindowsForTargetPaginator struct { - options DescribeMaintenanceWindowsForTargetPaginatorOptions - client DescribeMaintenanceWindowsForTargetAPIClient - params *DescribeMaintenanceWindowsForTargetInput - nextToken *string - firstPage bool -} - -// NewDescribeMaintenanceWindowsForTargetPaginator returns a new -// DescribeMaintenanceWindowsForTargetPaginator -func NewDescribeMaintenanceWindowsForTargetPaginator(client DescribeMaintenanceWindowsForTargetAPIClient, params *DescribeMaintenanceWindowsForTargetInput, optFns ...func(*DescribeMaintenanceWindowsForTargetPaginatorOptions)) *DescribeMaintenanceWindowsForTargetPaginator { - if params == nil { - params = &DescribeMaintenanceWindowsForTargetInput{} - } - - options := DescribeMaintenanceWindowsForTargetPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeMaintenanceWindowsForTargetPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeMaintenanceWindowsForTargetPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeMaintenanceWindowsForTarget page. -func (p *DescribeMaintenanceWindowsForTargetPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeMaintenanceWindowsForTargetOutput, 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 - - result, err := p.client.DescribeMaintenanceWindowsForTarget(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 -} - -func newServiceMetadataMiddleware_opDescribeMaintenanceWindowsForTarget(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeMaintenanceWindowsForTarget", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeOpsItems.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeOpsItems.go deleted file mode 100644 index a1c4f7ce..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeOpsItems.go +++ /dev/null @@ -1,264 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Query a set of OpsItems. You must have permission in Identity and Access -// Management (IAM) to query a list of OpsItems. For more information, see Set up -// OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-setup.html) -// in the Amazon Web Services Systems Manager User Guide. Operations engineers and -// IT professionals use Amazon Web Services Systems Manager OpsCenter to view, -// investigate, and remediate operational issues impacting the performance and -// health of their Amazon Web Services resources. For more information, see -// OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) -// in the Amazon Web Services Systems Manager User Guide. -func (c *Client) DescribeOpsItems(ctx context.Context, params *DescribeOpsItemsInput, optFns ...func(*Options)) (*DescribeOpsItemsOutput, error) { - if params == nil { - params = &DescribeOpsItemsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeOpsItems", params, optFns, c.addOperationDescribeOpsItemsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeOpsItemsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeOpsItemsInput struct { - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - // One or more filters to limit the response. - // - Key: CreatedTime Operations: GreaterThan, LessThan - // - Key: LastModifiedBy Operations: Contains, Equals - // - Key: LastModifiedTime Operations: GreaterThan, LessThan - // - Key: Priority Operations: Equals - // - Key: Source Operations: Contains, Equals - // - Key: Status Operations: Equals - // - Key: Title* Operations: Equals,Contains - // - Key: OperationalData** Operations: Equals - // - Key: OperationalDataKey Operations: Equals - // - Key: OperationalDataValue Operations: Equals, Contains - // - Key: OpsItemId Operations: Equals - // - Key: ResourceId Operations: Contains - // - Key: AutomationId Operations: Equals - // - Key: AccountId Operations: Equals - // *The Equals operator for Title matches the first 100 characters. If you specify - // more than 100 characters, they system returns an error that the filter value - // exceeds the length limit. **If you filter the response by using the - // OperationalData operator, specify a key-value pair by using the following JSON - // format: {"key":"key_name","value":"a_value"} - OpsItemFilters []types.OpsItemFilter - - noSmithyDocumentSerde -} - -type DescribeOpsItemsOutput struct { - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // A list of OpsItems. - OpsItemSummaries []types.OpsItemSummary - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeOpsItemsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeOpsItems{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeOpsItems{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeOpsItems"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeOpsItemsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeOpsItems(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeOpsItemsAPIClient is a client that implements the DescribeOpsItems -// operation. -type DescribeOpsItemsAPIClient interface { - DescribeOpsItems(context.Context, *DescribeOpsItemsInput, ...func(*Options)) (*DescribeOpsItemsOutput, error) -} - -var _ DescribeOpsItemsAPIClient = (*Client)(nil) - -// DescribeOpsItemsPaginatorOptions is the paginator options for DescribeOpsItems -type DescribeOpsItemsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeOpsItemsPaginator is a paginator for DescribeOpsItems -type DescribeOpsItemsPaginator struct { - options DescribeOpsItemsPaginatorOptions - client DescribeOpsItemsAPIClient - params *DescribeOpsItemsInput - nextToken *string - firstPage bool -} - -// NewDescribeOpsItemsPaginator returns a new DescribeOpsItemsPaginator -func NewDescribeOpsItemsPaginator(client DescribeOpsItemsAPIClient, params *DescribeOpsItemsInput, optFns ...func(*DescribeOpsItemsPaginatorOptions)) *DescribeOpsItemsPaginator { - if params == nil { - params = &DescribeOpsItemsInput{} - } - - options := DescribeOpsItemsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeOpsItemsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeOpsItemsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeOpsItems page. -func (p *DescribeOpsItemsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeOpsItemsOutput, 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 - - result, err := p.client.DescribeOpsItems(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 -} - -func newServiceMetadataMiddleware_opDescribeOpsItems(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeOpsItems", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeParameters.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeParameters.go deleted file mode 100644 index 9da5680a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeParameters.go +++ /dev/null @@ -1,251 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Get information about a parameter. Request results are returned on a -// best-effort basis. If you specify MaxResults in the request, the response -// includes information up to the limit specified. The number of items returned, -// however, can be between zero and the value of MaxResults . If the service -// reaches an internal limit while processing the results, it stops the operation -// and returns the matching values up to that point and a NextToken . You can -// specify the NextToken in a subsequent call to get the next set of results. If -// you change the KMS key alias for the KMS key used to encrypt a parameter, then -// you must also update the key alias the parameter uses to reference KMS. -// Otherwise, DescribeParameters retrieves whatever the original key alias was -// referencing. -func (c *Client) DescribeParameters(ctx context.Context, params *DescribeParametersInput, optFns ...func(*Options)) (*DescribeParametersOutput, error) { - if params == nil { - params = &DescribeParametersInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeParameters", params, optFns, c.addOperationDescribeParametersMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeParametersOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeParametersInput struct { - - // This data type is deprecated. Instead, use ParameterFilters . - Filters []types.ParametersFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - // Filters to limit the request results. - ParameterFilters []types.ParameterStringFilter - - noSmithyDocumentSerde -} - -type DescribeParametersOutput struct { - - // The token to use when requesting the next set of items. - NextToken *string - - // Parameters returned by the request. - Parameters []types.ParameterMetadata - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeParametersMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeParameters{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeParameters{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeParameters"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeParametersValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeParameters(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeParametersAPIClient is a client that implements the DescribeParameters -// operation. -type DescribeParametersAPIClient interface { - DescribeParameters(context.Context, *DescribeParametersInput, ...func(*Options)) (*DescribeParametersOutput, error) -} - -var _ DescribeParametersAPIClient = (*Client)(nil) - -// DescribeParametersPaginatorOptions is the paginator options for -// DescribeParameters -type DescribeParametersPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeParametersPaginator is a paginator for DescribeParameters -type DescribeParametersPaginator struct { - options DescribeParametersPaginatorOptions - client DescribeParametersAPIClient - params *DescribeParametersInput - nextToken *string - firstPage bool -} - -// NewDescribeParametersPaginator returns a new DescribeParametersPaginator -func NewDescribeParametersPaginator(client DescribeParametersAPIClient, params *DescribeParametersInput, optFns ...func(*DescribeParametersPaginatorOptions)) *DescribeParametersPaginator { - if params == nil { - params = &DescribeParametersInput{} - } - - options := DescribeParametersPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeParametersPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeParametersPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeParameters page. -func (p *DescribeParametersPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeParametersOutput, 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 - - result, err := p.client.DescribeParameters(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 -} - -func newServiceMetadataMiddleware_opDescribeParameters(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeParameters", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchBaselines.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchBaselines.go deleted file mode 100644 index 089dd367..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchBaselines.go +++ /dev/null @@ -1,238 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists the patch baselines in your Amazon Web Services account. -func (c *Client) DescribePatchBaselines(ctx context.Context, params *DescribePatchBaselinesInput, optFns ...func(*Options)) (*DescribePatchBaselinesOutput, error) { - if params == nil { - params = &DescribePatchBaselinesInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribePatchBaselines", params, optFns, c.addOperationDescribePatchBaselinesMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribePatchBaselinesOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribePatchBaselinesInput struct { - - // Each element in the array is a structure containing a key-value pair. Supported - // keys for DescribePatchBaselines include the following: - // - NAME_PREFIX Sample values: AWS- | My- - // - OWNER Sample values: AWS | Self - // - OPERATING_SYSTEM Sample values: AMAZON_LINUX | SUSE | WINDOWS - Filters []types.PatchOrchestratorFilter - - // The maximum number of patch baselines to return (per page). - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribePatchBaselinesOutput struct { - - // An array of PatchBaselineIdentity elements. - BaselineIdentities []types.PatchBaselineIdentity - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribePatchBaselinesMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribePatchBaselines{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribePatchBaselines{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribePatchBaselines"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribePatchBaselines(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribePatchBaselinesAPIClient is a client that implements the -// DescribePatchBaselines operation. -type DescribePatchBaselinesAPIClient interface { - DescribePatchBaselines(context.Context, *DescribePatchBaselinesInput, ...func(*Options)) (*DescribePatchBaselinesOutput, error) -} - -var _ DescribePatchBaselinesAPIClient = (*Client)(nil) - -// DescribePatchBaselinesPaginatorOptions is the paginator options for -// DescribePatchBaselines -type DescribePatchBaselinesPaginatorOptions struct { - // The maximum number of patch baselines to return (per page). - 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 -} - -// DescribePatchBaselinesPaginator is a paginator for DescribePatchBaselines -type DescribePatchBaselinesPaginator struct { - options DescribePatchBaselinesPaginatorOptions - client DescribePatchBaselinesAPIClient - params *DescribePatchBaselinesInput - nextToken *string - firstPage bool -} - -// NewDescribePatchBaselinesPaginator returns a new DescribePatchBaselinesPaginator -func NewDescribePatchBaselinesPaginator(client DescribePatchBaselinesAPIClient, params *DescribePatchBaselinesInput, optFns ...func(*DescribePatchBaselinesPaginatorOptions)) *DescribePatchBaselinesPaginator { - if params == nil { - params = &DescribePatchBaselinesInput{} - } - - options := DescribePatchBaselinesPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribePatchBaselinesPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribePatchBaselinesPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribePatchBaselines page. -func (p *DescribePatchBaselinesPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribePatchBaselinesOutput, 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 - - result, err := p.client.DescribePatchBaselines(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 -} - -func newServiceMetadataMiddleware_opDescribePatchBaselines(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribePatchBaselines", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchGroupState.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchGroupState.go deleted file mode 100644 index 80b1615b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchGroupState.go +++ /dev/null @@ -1,189 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns high-level aggregated patch compliance state information for a patch -// group. -func (c *Client) DescribePatchGroupState(ctx context.Context, params *DescribePatchGroupStateInput, optFns ...func(*Options)) (*DescribePatchGroupStateOutput, error) { - if params == nil { - params = &DescribePatchGroupStateInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribePatchGroupState", params, optFns, c.addOperationDescribePatchGroupStateMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribePatchGroupStateOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribePatchGroupStateInput struct { - - // The name of the patch group whose patch snapshot should be retrieved. - // - // This member is required. - PatchGroup *string - - noSmithyDocumentSerde -} - -type DescribePatchGroupStateOutput struct { - - // The number of managed nodes in the patch group. - Instances int32 - - // The number of managed nodes where patches that are specified as Critical for - // compliance reporting in the patch baseline aren't installed. These patches might - // be missing, have failed installation, were rejected, or were installed but - // awaiting a required managed node reboot. The status of these managed nodes is - // NON_COMPLIANT . - InstancesWithCriticalNonCompliantPatches *int32 - - // The number of managed nodes with patches from the patch baseline that failed to - // install. - InstancesWithFailedPatches int32 - - // The number of managed nodes with patches installed that aren't defined in the - // patch baseline. - InstancesWithInstalledOtherPatches int32 - - // The number of managed nodes with installed patches. - InstancesWithInstalledPatches int32 - - // The number of managed nodes with patches installed by Patch Manager that - // haven't been rebooted after the patch installation. The status of these managed - // nodes is NON_COMPLIANT . - InstancesWithInstalledPendingRebootPatches *int32 - - // The number of managed nodes with patches installed that are specified in a - // RejectedPatches list. Patches with a status of INSTALLED_REJECTED were - // typically installed before they were added to a RejectedPatches list. If - // ALLOW_AS_DEPENDENCY is the specified option for RejectedPatchesAction , the - // value of InstancesWithInstalledRejectedPatches will always be 0 (zero). - InstancesWithInstalledRejectedPatches *int32 - - // The number of managed nodes with missing patches from the patch baseline. - InstancesWithMissingPatches int32 - - // The number of managed nodes with patches that aren't applicable. - InstancesWithNotApplicablePatches int32 - - // The number of managed nodes with patches installed that are specified as other - // than Critical or Security but aren't compliant with the patch baseline. The - // status of these managed nodes is NON_COMPLIANT . - InstancesWithOtherNonCompliantPatches *int32 - - // The number of managed nodes where patches that are specified as Security in a - // patch advisory aren't installed. These patches might be missing, have failed - // installation, were rejected, or were installed but awaiting a required managed - // node reboot. The status of these managed nodes is NON_COMPLIANT . - InstancesWithSecurityNonCompliantPatches *int32 - - // The number of managed nodes with NotApplicable patches beyond the supported - // limit, which aren't reported by name to Inventory. Inventory is a capability of - // Amazon Web Services Systems Manager. - InstancesWithUnreportedNotApplicablePatches *int32 - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribePatchGroupStateMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribePatchGroupState{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribePatchGroupState{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribePatchGroupState"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribePatchGroupStateValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribePatchGroupState(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDescribePatchGroupState(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribePatchGroupState", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchGroups.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchGroups.go deleted file mode 100644 index fca09c57..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchGroups.go +++ /dev/null @@ -1,240 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists all patch groups that have been registered with patch baselines. -func (c *Client) DescribePatchGroups(ctx context.Context, params *DescribePatchGroupsInput, optFns ...func(*Options)) (*DescribePatchGroupsOutput, error) { - if params == nil { - params = &DescribePatchGroupsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribePatchGroups", params, optFns, c.addOperationDescribePatchGroupsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribePatchGroupsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribePatchGroupsInput struct { - - // Each element in the array is a structure containing a key-value pair. Supported - // keys for DescribePatchGroups include the following: - // - NAME_PREFIX Sample values: AWS- | My- . - // - OPERATING_SYSTEM Sample values: AMAZON_LINUX | SUSE | WINDOWS - Filters []types.PatchOrchestratorFilter - - // The maximum number of patch groups to return (per page). - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribePatchGroupsOutput struct { - - // Each entry in the array contains: - // - PatchGroup : string (between 1 and 256 characters. Regex: - // ^([\p{L}\p{Z}\p{N}_.:/=+\-@]*)$) - // - PatchBaselineIdentity : A PatchBaselineIdentity element. - Mappings []types.PatchGroupPatchBaselineMapping - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribePatchGroupsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribePatchGroups{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribePatchGroups{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribePatchGroups"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribePatchGroups(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribePatchGroupsAPIClient is a client that implements the -// DescribePatchGroups operation. -type DescribePatchGroupsAPIClient interface { - DescribePatchGroups(context.Context, *DescribePatchGroupsInput, ...func(*Options)) (*DescribePatchGroupsOutput, error) -} - -var _ DescribePatchGroupsAPIClient = (*Client)(nil) - -// DescribePatchGroupsPaginatorOptions is the paginator options for -// DescribePatchGroups -type DescribePatchGroupsPaginatorOptions struct { - // The maximum number of patch groups to return (per page). - 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 -} - -// DescribePatchGroupsPaginator is a paginator for DescribePatchGroups -type DescribePatchGroupsPaginator struct { - options DescribePatchGroupsPaginatorOptions - client DescribePatchGroupsAPIClient - params *DescribePatchGroupsInput - nextToken *string - firstPage bool -} - -// NewDescribePatchGroupsPaginator returns a new DescribePatchGroupsPaginator -func NewDescribePatchGroupsPaginator(client DescribePatchGroupsAPIClient, params *DescribePatchGroupsInput, optFns ...func(*DescribePatchGroupsPaginatorOptions)) *DescribePatchGroupsPaginator { - if params == nil { - params = &DescribePatchGroupsInput{} - } - - options := DescribePatchGroupsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribePatchGroupsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribePatchGroupsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribePatchGroups page. -func (p *DescribePatchGroupsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribePatchGroupsOutput, 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 - - result, err := p.client.DescribePatchGroups(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 -} - -func newServiceMetadataMiddleware_opDescribePatchGroups(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribePatchGroups", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchProperties.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchProperties.go deleted file mode 100644 index c2f74466..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribePatchProperties.go +++ /dev/null @@ -1,265 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists the properties of available patches organized by product, product family, -// classification, severity, and other properties of available patches. You can use -// the reported properties in the filters you specify in requests for operations -// such as CreatePatchBaseline , UpdatePatchBaseline , DescribeAvailablePatches , -// and DescribePatchBaselines . The following section lists the properties that can -// be used in filters for each major operating system type: AMAZON_LINUX Valid -// properties: PRODUCT | CLASSIFICATION | SEVERITY AMAZON_LINUX_2 Valid -// properties: PRODUCT | CLASSIFICATION | SEVERITY CENTOS Valid properties: PRODUCT -// | CLASSIFICATION | SEVERITY DEBIAN Valid properties: PRODUCT | PRIORITY MACOS -// Valid properties: PRODUCT | CLASSIFICATION ORACLE_LINUX Valid properties: -// PRODUCT | CLASSIFICATION | SEVERITY REDHAT_ENTERPRISE_LINUX Valid properties: -// PRODUCT | CLASSIFICATION | SEVERITY SUSE Valid properties: PRODUCT | -// CLASSIFICATION | SEVERITY UBUNTU Valid properties: PRODUCT | PRIORITY WINDOWS -// Valid properties: PRODUCT | PRODUCT_FAMILY | CLASSIFICATION | MSRC_SEVERITY -func (c *Client) DescribePatchProperties(ctx context.Context, params *DescribePatchPropertiesInput, optFns ...func(*Options)) (*DescribePatchPropertiesOutput, error) { - if params == nil { - params = &DescribePatchPropertiesInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribePatchProperties", params, optFns, c.addOperationDescribePatchPropertiesMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribePatchPropertiesOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribePatchPropertiesInput struct { - - // The operating system type for which to list patches. - // - // This member is required. - OperatingSystem types.OperatingSystem - - // The patch property for which you want to view patch details. - // - // This member is required. - Property types.PatchProperty - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - // Indicates whether to list patches for the Windows operating system or for - // applications released by Microsoft. Not applicable for the Linux or macOS - // operating systems. - PatchSet types.PatchSet - - noSmithyDocumentSerde -} - -type DescribePatchPropertiesOutput struct { - - // The token for the next set of items to return. (You use this token in the next - // call.) - NextToken *string - - // A list of the properties for patches matching the filter request parameters. - Properties []map[string]string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribePatchPropertiesMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribePatchProperties{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribePatchProperties{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribePatchProperties"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribePatchPropertiesValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribePatchProperties(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribePatchPropertiesAPIClient is a client that implements the -// DescribePatchProperties operation. -type DescribePatchPropertiesAPIClient interface { - DescribePatchProperties(context.Context, *DescribePatchPropertiesInput, ...func(*Options)) (*DescribePatchPropertiesOutput, error) -} - -var _ DescribePatchPropertiesAPIClient = (*Client)(nil) - -// DescribePatchPropertiesPaginatorOptions is the paginator options for -// DescribePatchProperties -type DescribePatchPropertiesPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribePatchPropertiesPaginator is a paginator for DescribePatchProperties -type DescribePatchPropertiesPaginator struct { - options DescribePatchPropertiesPaginatorOptions - client DescribePatchPropertiesAPIClient - params *DescribePatchPropertiesInput - nextToken *string - firstPage bool -} - -// NewDescribePatchPropertiesPaginator returns a new -// DescribePatchPropertiesPaginator -func NewDescribePatchPropertiesPaginator(client DescribePatchPropertiesAPIClient, params *DescribePatchPropertiesInput, optFns ...func(*DescribePatchPropertiesPaginatorOptions)) *DescribePatchPropertiesPaginator { - if params == nil { - params = &DescribePatchPropertiesInput{} - } - - options := DescribePatchPropertiesPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribePatchPropertiesPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribePatchPropertiesPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribePatchProperties page. -func (p *DescribePatchPropertiesPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribePatchPropertiesOutput, 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 - - result, err := p.client.DescribePatchProperties(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 -} - -func newServiceMetadataMiddleware_opDescribePatchProperties(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribePatchProperties", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeSessions.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeSessions.go deleted file mode 100644 index cb3d1fc5..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DescribeSessions.go +++ /dev/null @@ -1,244 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves a list of all active sessions (both connected and disconnected) or -// terminated sessions from the past 30 days. -func (c *Client) DescribeSessions(ctx context.Context, params *DescribeSessionsInput, optFns ...func(*Options)) (*DescribeSessionsOutput, error) { - if params == nil { - params = &DescribeSessionsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DescribeSessions", params, optFns, c.addOperationDescribeSessionsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DescribeSessionsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DescribeSessionsInput struct { - - // The session status to retrieve a list of sessions for. For example, "Active". - // - // This member is required. - State types.SessionState - - // One or more filters to limit the type of sessions returned by the request. - Filters []types.SessionFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type DescribeSessionsOutput struct { - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - // A list of sessions meeting the request parameters. - Sessions []types.Session - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDescribeSessionsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDescribeSessions{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDescribeSessions{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DescribeSessions"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDescribeSessionsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDescribeSessions(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// DescribeSessionsAPIClient is a client that implements the DescribeSessions -// operation. -type DescribeSessionsAPIClient interface { - DescribeSessions(context.Context, *DescribeSessionsInput, ...func(*Options)) (*DescribeSessionsOutput, error) -} - -var _ DescribeSessionsAPIClient = (*Client)(nil) - -// DescribeSessionsPaginatorOptions is the paginator options for DescribeSessions -type DescribeSessionsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// DescribeSessionsPaginator is a paginator for DescribeSessions -type DescribeSessionsPaginator struct { - options DescribeSessionsPaginatorOptions - client DescribeSessionsAPIClient - params *DescribeSessionsInput - nextToken *string - firstPage bool -} - -// NewDescribeSessionsPaginator returns a new DescribeSessionsPaginator -func NewDescribeSessionsPaginator(client DescribeSessionsAPIClient, params *DescribeSessionsInput, optFns ...func(*DescribeSessionsPaginatorOptions)) *DescribeSessionsPaginator { - if params == nil { - params = &DescribeSessionsInput{} - } - - options := DescribeSessionsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &DescribeSessionsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *DescribeSessionsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next DescribeSessions page. -func (p *DescribeSessionsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*DescribeSessionsOutput, 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 - - result, err := p.client.DescribeSessions(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 -} - -func newServiceMetadataMiddleware_opDescribeSessions(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DescribeSessions", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DisassociateOpsItemRelatedItem.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DisassociateOpsItemRelatedItem.go deleted file mode 100644 index 7c32e8fe..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_DisassociateOpsItemRelatedItem.go +++ /dev/null @@ -1,141 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Deletes the association between an OpsItem and a related item. For example, -// this API operation can delete an Incident Manager incident from an OpsItem. -// Incident Manager is a capability of Amazon Web Services Systems Manager. -func (c *Client) DisassociateOpsItemRelatedItem(ctx context.Context, params *DisassociateOpsItemRelatedItemInput, optFns ...func(*Options)) (*DisassociateOpsItemRelatedItemOutput, error) { - if params == nil { - params = &DisassociateOpsItemRelatedItemInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DisassociateOpsItemRelatedItem", params, optFns, c.addOperationDisassociateOpsItemRelatedItemMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DisassociateOpsItemRelatedItemOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DisassociateOpsItemRelatedItemInput struct { - - // The ID of the association for which you want to delete an association between - // the OpsItem and a related item. - // - // This member is required. - AssociationId *string - - // The ID of the OpsItem for which you want to delete an association between the - // OpsItem and a related item. - // - // This member is required. - OpsItemId *string - - noSmithyDocumentSerde -} - -type DisassociateOpsItemRelatedItemOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDisassociateOpsItemRelatedItemMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpDisassociateOpsItemRelatedItem{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpDisassociateOpsItemRelatedItem{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DisassociateOpsItemRelatedItem"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDisassociateOpsItemRelatedItemValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDisassociateOpsItemRelatedItem(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDisassociateOpsItemRelatedItem(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DisassociateOpsItemRelatedItem", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetAutomationExecution.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetAutomationExecution.go deleted file mode 100644 index cc3a61bf..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetAutomationExecution.go +++ /dev/null @@ -1,139 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Get detailed information about a particular Automation execution. -func (c *Client) GetAutomationExecution(ctx context.Context, params *GetAutomationExecutionInput, optFns ...func(*Options)) (*GetAutomationExecutionOutput, error) { - if params == nil { - params = &GetAutomationExecutionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetAutomationExecution", params, optFns, c.addOperationGetAutomationExecutionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetAutomationExecutionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetAutomationExecutionInput struct { - - // The unique identifier for an existing automation execution to examine. The - // execution ID is returned by StartAutomationExecution when the execution of an - // Automation runbook is initiated. - // - // This member is required. - AutomationExecutionId *string - - noSmithyDocumentSerde -} - -type GetAutomationExecutionOutput struct { - - // Detailed information about the current state of an automation execution. - AutomationExecution *types.AutomationExecution - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetAutomationExecutionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetAutomationExecution{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetAutomationExecution{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetAutomationExecution"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetAutomationExecutionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetAutomationExecution(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetAutomationExecution(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetAutomationExecution", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetCalendarState.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetCalendarState.go deleted file mode 100644 index 11b1f04a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetCalendarState.go +++ /dev/null @@ -1,168 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Gets the state of a Amazon Web Services Systems Manager change calendar at the -// current time or a specified time. If you specify a time, GetCalendarState -// returns the state of the calendar at that specific time, and returns the next -// time that the change calendar state will transition. If you don't specify a -// time, GetCalendarState uses the current time. Change Calendar entries have two -// possible states: OPEN or CLOSED . If you specify more than one calendar in a -// request, the command returns the status of OPEN only if all calendars in the -// request are open. If one or more calendars in the request are closed, the status -// returned is CLOSED . For more information about Change Calendar, a capability of -// Amazon Web Services Systems Manager, see Amazon Web Services Systems Manager -// Change Calendar (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-change-calendar.html) -// in the Amazon Web Services Systems Manager User Guide. -func (c *Client) GetCalendarState(ctx context.Context, params *GetCalendarStateInput, optFns ...func(*Options)) (*GetCalendarStateOutput, error) { - if params == nil { - params = &GetCalendarStateInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetCalendarState", params, optFns, c.addOperationGetCalendarStateMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetCalendarStateOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetCalendarStateInput struct { - - // The names or Amazon Resource Names (ARNs) of the Systems Manager documents (SSM - // documents) that represent the calendar entries for which you want to get the - // state. - // - // This member is required. - CalendarNames []string - - // (Optional) The specific time for which you want to get calendar state - // information, in ISO 8601 (https://en.wikipedia.org/wiki/ISO_8601) format. If - // you don't specify a value or AtTime , the current time is used. - AtTime *string - - noSmithyDocumentSerde -} - -type GetCalendarStateOutput struct { - - // The time, as an ISO 8601 (https://en.wikipedia.org/wiki/ISO_8601) string, that - // you specified in your command. If you don't specify a time, GetCalendarState - // uses the current time. - AtTime *string - - // The time, as an ISO 8601 (https://en.wikipedia.org/wiki/ISO_8601) string, that - // the calendar state will change. If the current calendar state is OPEN , - // NextTransitionTime indicates when the calendar state changes to CLOSED , and - // vice-versa. - NextTransitionTime *string - - // The state of the calendar. An OPEN calendar indicates that actions are allowed - // to proceed, and a CLOSED calendar indicates that actions aren't allowed to - // proceed. - State types.CalendarState - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetCalendarStateMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetCalendarState{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetCalendarState{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetCalendarState"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetCalendarStateValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetCalendarState(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetCalendarState(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetCalendarState", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetCommandInvocation.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetCommandInvocation.go deleted file mode 100644 index 05abba89..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetCommandInvocation.go +++ /dev/null @@ -1,565 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "errors" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "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" -) - -// Returns detailed information about command execution for an invocation or -// plugin. GetCommandInvocation only gives the execution status of a plugin in a -// document. To get the command execution status on a specific managed node, use -// ListCommandInvocations . To get the command execution status across managed -// nodes, use ListCommands . -func (c *Client) GetCommandInvocation(ctx context.Context, params *GetCommandInvocationInput, optFns ...func(*Options)) (*GetCommandInvocationOutput, error) { - if params == nil { - params = &GetCommandInvocationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetCommandInvocation", params, optFns, c.addOperationGetCommandInvocationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetCommandInvocationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetCommandInvocationInput struct { - - // (Required) The parent command ID of the invocation plugin. - // - // This member is required. - CommandId *string - - // (Required) The ID of the managed node targeted by the command. A managed node - // can be an Amazon Elastic Compute Cloud (Amazon EC2) instance, edge device, and - // on-premises server or VM in your hybrid environment that is configured for - // Amazon Web Services Systems Manager. - // - // This member is required. - InstanceId *string - - // The name of the step for which you want detailed results. If the document - // contains only one step, you can omit the name and details for that step. If the - // document contains more than one step, you must specify the name of the step for - // which you want to view details. Be sure to specify the name of the step, not the - // name of a plugin like aws:RunShellScript . To find the PluginName , check the - // document content and find the name of the step you want details for. - // Alternatively, use ListCommandInvocations with the CommandId and Details - // parameters. The PluginName is the Name attribute of the CommandPlugin object in - // the CommandPlugins list. - PluginName *string - - noSmithyDocumentSerde -} - -type GetCommandInvocationOutput struct { - - // Amazon CloudWatch Logs information where Systems Manager sent the command - // output. - CloudWatchOutputConfig *types.CloudWatchOutputConfig - - // The parent command ID of the invocation plugin. - CommandId *string - - // The comment text for the command. - Comment *string - - // The name of the document that was run. For example, AWS-RunShellScript . - DocumentName *string - - // The Systems Manager document (SSM document) version used in the request. - DocumentVersion *string - - // Duration since ExecutionStartDateTime . - ExecutionElapsedTime *string - - // The date and time the plugin finished running. Date and time are written in ISO - // 8601 format. For example, June 7, 2017 is represented as 2017-06-7. The - // following sample Amazon Web Services CLI command uses the InvokedAfter filter. - // aws ssm list-commands --filters key=InvokedAfter,value=2017-06-07T00:00:00Z If - // the plugin hasn't started to run, the string is empty. - ExecutionEndDateTime *string - - // The date and time the plugin started running. Date and time are written in ISO - // 8601 format. For example, June 7, 2017 is represented as 2017-06-7. The - // following sample Amazon Web Services CLI command uses the InvokedBefore filter. - // aws ssm list-commands --filters key=InvokedBefore,value=2017-06-07T00:00:00Z If - // the plugin hasn't started to run, the string is empty. - ExecutionStartDateTime *string - - // The ID of the managed node targeted by the command. A managed node can be an - // Amazon Elastic Compute Cloud (Amazon EC2) instance, edge device, or on-premises - // server or VM in your hybrid environment that is configured for Amazon Web - // Services Systems Manager. - InstanceId *string - - // The name of the plugin, or step name, for which details are reported. For - // example, aws:RunShellScript is a plugin. - PluginName *string - - // The error level response code for the plugin script. If the response code is -1 - // , then the command hasn't started running on the managed node, or it wasn't - // received by the node. - ResponseCode int32 - - // The first 8,000 characters written by the plugin to stderr . If the command - // hasn't finished running, then this string is empty. - StandardErrorContent *string - - // The URL for the complete text written by the plugin to stderr . If the command - // hasn't finished running, then this string is empty. - StandardErrorUrl *string - - // The first 24,000 characters written by the plugin to stdout . If the command - // hasn't finished running, if ExecutionStatus is neither Succeeded nor Failed, - // then this string is empty. - StandardOutputContent *string - - // The URL for the complete text written by the plugin to stdout in Amazon Simple - // Storage Service (Amazon S3). If an S3 bucket wasn't specified, then this string - // is empty. - StandardOutputUrl *string - - // The status of this invocation plugin. This status can be different than - // StatusDetails . - Status types.CommandInvocationStatus - - // A detailed status of the command execution for an invocation. StatusDetails - // includes more information than Status because it includes states resulting from - // error and concurrency control parameters. StatusDetails can show different - // results than Status . For more information about these statuses, see - // Understanding command statuses (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) - // in the Amazon Web Services Systems Manager User Guide. StatusDetails can be one - // of the following values: - // - Pending: The command hasn't been sent to the managed node. - // - In Progress: The command has been sent to the managed node but hasn't - // reached a terminal state. - // - Delayed: The system attempted to send the command to the target, but the - // target wasn't available. The managed node might not be available because of - // network issues, because the node was stopped, or for similar reasons. The system - // will try to send the command again. - // - Success: The command or plugin ran successfully. This is a terminal state. - // - Delivery Timed Out: The command wasn't delivered to the managed node before - // the delivery timeout expired. Delivery timeouts don't count against the parent - // command's MaxErrors limit, but they do contribute to whether the parent - // command status is Success or Incomplete. This is a terminal state. - // - Execution Timed Out: The command started to run on the managed node, but - // the execution wasn't complete before the timeout expired. Execution timeouts - // count against the MaxErrors limit of the parent command. This is a terminal - // state. - // - Failed: The command wasn't run successfully on the managed node. For a - // plugin, this indicates that the result code wasn't zero. For a command - // invocation, this indicates that the result code for one or more plugins wasn't - // zero. Invocation failures count against the MaxErrors limit of the parent - // command. This is a terminal state. - // - Cancelled: The command was terminated before it was completed. This is a - // terminal state. - // - Undeliverable: The command can't be delivered to the managed node. The node - // might not exist or might not be responding. Undeliverable invocations don't - // count against the parent command's MaxErrors limit and don't contribute to - // whether the parent command status is Success or Incomplete. This is a terminal - // state. - // - Terminated: The parent command exceeded its MaxErrors limit and subsequent - // command invocations were canceled by the system. This is a terminal state. - StatusDetails *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetCommandInvocationMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetCommandInvocation{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetCommandInvocation{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetCommandInvocation"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetCommandInvocationValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetCommandInvocation(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// GetCommandInvocationAPIClient is a client that implements the -// GetCommandInvocation operation. -type GetCommandInvocationAPIClient interface { - GetCommandInvocation(context.Context, *GetCommandInvocationInput, ...func(*Options)) (*GetCommandInvocationOutput, error) -} - -var _ GetCommandInvocationAPIClient = (*Client)(nil) - -// CommandExecutedWaiterOptions are waiter options for CommandExecutedWaiter -type CommandExecutedWaiterOptions 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 - - // MinDelay is the minimum amount of time to delay between retries. If unset, - // CommandExecutedWaiter will use default minimum delay of 5 seconds. Note that - // MinDelay must resolve to a value lesser than or equal to the MaxDelay. - MinDelay time.Duration - - // MaxDelay is the maximum amount of time to delay between retries. If unset or - // set to zero, CommandExecutedWaiter will use default max delay of 120 seconds. - // Note that MaxDelay must resolve to value greater than or equal to the MinDelay. - MaxDelay time.Duration - - // LogWaitAttempts is used to enable logging for waiter retry attempts - LogWaitAttempts bool - - // 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. - Retryable func(context.Context, *GetCommandInvocationInput, *GetCommandInvocationOutput, error) (bool, error) -} - -// CommandExecutedWaiter defines the waiters for CommandExecuted -type CommandExecutedWaiter struct { - client GetCommandInvocationAPIClient - - options CommandExecutedWaiterOptions -} - -// NewCommandExecutedWaiter constructs a CommandExecutedWaiter. -func NewCommandExecutedWaiter(client GetCommandInvocationAPIClient, optFns ...func(*CommandExecutedWaiterOptions)) *CommandExecutedWaiter { - options := CommandExecutedWaiterOptions{} - options.MinDelay = 5 * time.Second - options.MaxDelay = 120 * time.Second - options.Retryable = commandExecutedStateRetryable - - for _, fn := range optFns { - fn(&options) - } - return &CommandExecutedWaiter{ - client: client, - options: options, - } -} - -// Wait calls the waiter function for CommandExecuted waiter. The maxWaitDur is -// the maximum wait duration the waiter will wait. The maxWaitDur is required and -// must be greater than zero. -func (w *CommandExecutedWaiter) Wait(ctx context.Context, params *GetCommandInvocationInput, maxWaitDur time.Duration, optFns ...func(*CommandExecutedWaiterOptions)) error { - _, err := w.WaitForOutput(ctx, params, maxWaitDur, optFns...) - return err -} - -// WaitForOutput calls the waiter function for CommandExecuted waiter and returns -// the output of the successful operation. The maxWaitDur is the maximum wait -// duration the waiter will wait. The maxWaitDur is required and must be greater -// than zero. -func (w *CommandExecutedWaiter) WaitForOutput(ctx context.Context, params *GetCommandInvocationInput, maxWaitDur time.Duration, optFns ...func(*CommandExecutedWaiterOptions)) (*GetCommandInvocationOutput, error) { - if maxWaitDur <= 0 { - return nil, fmt.Errorf("maximum wait time for waiter must be greater than zero") - } - - options := w.options - for _, fn := range optFns { - fn(&options) - } - - if options.MaxDelay <= 0 { - options.MaxDelay = 120 * time.Second - } - - if options.MinDelay > options.MaxDelay { - return nil, fmt.Errorf("minimum waiter delay %v must be lesser than or equal to maximum waiter delay of %v.", options.MinDelay, options.MaxDelay) - } - - ctx, cancelFn := context.WithTimeout(ctx, maxWaitDur) - defer cancelFn() - - logger := smithywaiter.Logger{} - remainingTime := maxWaitDur - - var attempt int64 - for { - - attempt++ - apiOptions := options.APIOptions - start := time.Now() - - if options.LogWaitAttempts { - logger.Attempt = attempt - apiOptions = append([]func(*middleware.Stack) error{}, options.APIOptions...) - apiOptions = append(apiOptions, logger.AddLogger) - } - - out, err := w.client.GetCommandInvocation(ctx, params, func(o *Options) { - o.APIOptions = append(o.APIOptions, apiOptions...) - }) - - retryable, err := options.Retryable(ctx, params, out, err) - if err != nil { - return nil, err - } - if !retryable { - return out, nil - } - - remainingTime -= time.Since(start) - if remainingTime < options.MinDelay || remainingTime <= 0 { - break - } - - // compute exponential backoff between waiter retries - delay, err := smithywaiter.ComputeDelay( - attempt, options.MinDelay, options.MaxDelay, remainingTime, - ) - if err != nil { - return nil, fmt.Errorf("error computing waiter delay, %w", err) - } - - remainingTime -= delay - // sleep for the delay amount before invoking a request - if err := smithytime.SleepWithContext(ctx, delay); err != nil { - return nil, fmt.Errorf("request cancelled while waiting, %w", err) - } - } - return nil, fmt.Errorf("exceeded max wait time for CommandExecuted waiter") -} - -func commandExecutedStateRetryable(ctx context.Context, input *GetCommandInvocationInput, output *GetCommandInvocationOutput, 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) - } - - expectedValue := "Pending" - value, ok := pathValue.(types.CommandInvocationStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.CommandInvocationStatus value, got %T", pathValue) - } - - if string(value) == expectedValue { - return true, nil - } - } - - if err == nil { - pathValue, err := jmespath.Search("Status", output) - if err != nil { - return false, fmt.Errorf("error evaluating waiter state: %w", err) - } - - expectedValue := "InProgress" - value, ok := pathValue.(types.CommandInvocationStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.CommandInvocationStatus value, got %T", pathValue) - } - - if string(value) == expectedValue { - return true, nil - } - } - - if err == nil { - pathValue, err := jmespath.Search("Status", output) - if err != nil { - return false, fmt.Errorf("error evaluating waiter state: %w", err) - } - - expectedValue := "Delayed" - value, ok := pathValue.(types.CommandInvocationStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.CommandInvocationStatus value, got %T", pathValue) - } - - if string(value) == expectedValue { - return true, nil - } - } - - if err == nil { - pathValue, err := jmespath.Search("Status", output) - if err != nil { - return false, fmt.Errorf("error evaluating waiter state: %w", err) - } - - expectedValue := "Success" - value, ok := pathValue.(types.CommandInvocationStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.CommandInvocationStatus value, got %T", pathValue) - } - - if string(value) == 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) - } - - expectedValue := "Cancelled" - value, ok := pathValue.(types.CommandInvocationStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.CommandInvocationStatus value, got %T", pathValue) - } - - if string(value) == expectedValue { - return false, fmt.Errorf("waiter state transitioned to Failure") - } - } - - if err == nil { - pathValue, err := jmespath.Search("Status", output) - if err != nil { - return false, fmt.Errorf("error evaluating waiter state: %w", err) - } - - expectedValue := "TimedOut" - value, ok := pathValue.(types.CommandInvocationStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.CommandInvocationStatus value, got %T", pathValue) - } - - if string(value) == expectedValue { - return false, fmt.Errorf("waiter state transitioned to Failure") - } - } - - if err == nil { - pathValue, err := jmespath.Search("Status", output) - if err != nil { - return false, fmt.Errorf("error evaluating waiter state: %w", err) - } - - expectedValue := "Failed" - value, ok := pathValue.(types.CommandInvocationStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.CommandInvocationStatus value, got %T", pathValue) - } - - if string(value) == expectedValue { - return false, fmt.Errorf("waiter state transitioned to Failure") - } - } - - if err == nil { - pathValue, err := jmespath.Search("Status", output) - if err != nil { - return false, fmt.Errorf("error evaluating waiter state: %w", err) - } - - expectedValue := "Cancelling" - value, ok := pathValue.(types.CommandInvocationStatus) - if !ok { - return false, fmt.Errorf("waiter comparator expected types.CommandInvocationStatus value, got %T", pathValue) - } - - if string(value) == expectedValue { - return false, fmt.Errorf("waiter state transitioned to Failure") - } - } - - if err != nil { - var errorType *types.InvocationDoesNotExist - if errors.As(err, &errorType) { - return true, nil - } - } - - return true, nil -} - -func newServiceMetadataMiddleware_opGetCommandInvocation(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetCommandInvocation", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetConnectionStatus.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetConnectionStatus.go deleted file mode 100644 index 60e562de..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetConnectionStatus.go +++ /dev/null @@ -1,142 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the Session Manager connection status for a managed node to determine -// whether it is running and ready to receive Session Manager connections. -func (c *Client) GetConnectionStatus(ctx context.Context, params *GetConnectionStatusInput, optFns ...func(*Options)) (*GetConnectionStatusOutput, error) { - if params == nil { - params = &GetConnectionStatusInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetConnectionStatus", params, optFns, c.addOperationGetConnectionStatusMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetConnectionStatusOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetConnectionStatusInput struct { - - // The managed node ID. - // - // This member is required. - Target *string - - noSmithyDocumentSerde -} - -type GetConnectionStatusOutput struct { - - // The status of the connection to the managed node. For example, 'Connected' or - // 'Not Connected'. - Status types.ConnectionStatus - - // The ID of the managed node to check connection status. - Target *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetConnectionStatusMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetConnectionStatus{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetConnectionStatus{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetConnectionStatus"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetConnectionStatusValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetConnectionStatus(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetConnectionStatus(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetConnectionStatus", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetDefaultPatchBaseline.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetDefaultPatchBaseline.go deleted file mode 100644 index 753e8999..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetDefaultPatchBaseline.go +++ /dev/null @@ -1,138 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the default patch baseline. Amazon Web Services Systems Manager -// supports creating multiple default patch baselines. For example, you can create -// a default patch baseline for each operating system. If you don't specify an -// operating system value, the default patch baseline for Windows is returned. -func (c *Client) GetDefaultPatchBaseline(ctx context.Context, params *GetDefaultPatchBaselineInput, optFns ...func(*Options)) (*GetDefaultPatchBaselineOutput, error) { - if params == nil { - params = &GetDefaultPatchBaselineInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetDefaultPatchBaseline", params, optFns, c.addOperationGetDefaultPatchBaselineMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetDefaultPatchBaselineOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetDefaultPatchBaselineInput struct { - - // Returns the default patch baseline for the specified operating system. - OperatingSystem types.OperatingSystem - - noSmithyDocumentSerde -} - -type GetDefaultPatchBaselineOutput struct { - - // The ID of the default patch baseline. - BaselineId *string - - // The operating system for the returned patch baseline. - OperatingSystem types.OperatingSystem - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetDefaultPatchBaselineMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetDefaultPatchBaseline{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetDefaultPatchBaseline{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetDefaultPatchBaseline"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opGetDefaultPatchBaseline(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetDefaultPatchBaseline(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetDefaultPatchBaseline", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetDeployablePatchSnapshotForInstance.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetDeployablePatchSnapshotForInstance.go deleted file mode 100644 index 862b41dc..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetDeployablePatchSnapshotForInstance.go +++ /dev/null @@ -1,165 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the current snapshot for the patch baseline the managed node uses. -// This API is primarily used by the AWS-RunPatchBaseline Systems Manager document -// (SSM document). If you run the command locally, such as with the Command Line -// Interface (CLI), the system attempts to use your local Amazon Web Services -// credentials and the operation fails. To avoid this, you can run the command in -// the Amazon Web Services Systems Manager console. Use Run Command, a capability -// of Amazon Web Services Systems Manager, with an SSM document that enables you to -// target a managed node with a script or command. For example, run the command -// using the AWS-RunShellScript document or the AWS-RunPowerShellScript document. -func (c *Client) GetDeployablePatchSnapshotForInstance(ctx context.Context, params *GetDeployablePatchSnapshotForInstanceInput, optFns ...func(*Options)) (*GetDeployablePatchSnapshotForInstanceOutput, error) { - if params == nil { - params = &GetDeployablePatchSnapshotForInstanceInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetDeployablePatchSnapshotForInstance", params, optFns, c.addOperationGetDeployablePatchSnapshotForInstanceMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetDeployablePatchSnapshotForInstanceOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetDeployablePatchSnapshotForInstanceInput struct { - - // The ID of the managed node for which the appropriate patch snapshot should be - // retrieved. - // - // This member is required. - InstanceId *string - - // The snapshot ID provided by the user when running AWS-RunPatchBaseline . - // - // This member is required. - SnapshotId *string - - // Defines the basic information about a patch baseline override. - BaselineOverride *types.BaselineOverride - - noSmithyDocumentSerde -} - -type GetDeployablePatchSnapshotForInstanceOutput struct { - - // The managed node ID. - InstanceId *string - - // Returns the specific operating system (for example Windows Server 2012 or - // Amazon Linux 2015.09) on the managed node for the specified patch snapshot. - Product *string - - // A pre-signed Amazon Simple Storage Service (Amazon S3) URL that can be used to - // download the patch snapshot. - SnapshotDownloadUrl *string - - // The user-defined snapshot ID. - SnapshotId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetDeployablePatchSnapshotForInstanceMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetDeployablePatchSnapshotForInstance{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetDeployablePatchSnapshotForInstance{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetDeployablePatchSnapshotForInstance"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetDeployablePatchSnapshotForInstanceValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetDeployablePatchSnapshotForInstance(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetDeployablePatchSnapshotForInstance(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetDeployablePatchSnapshotForInstance", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetDocument.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetDocument.go deleted file mode 100644 index 9aa1641c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetDocument.go +++ /dev/null @@ -1,202 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Gets the contents of the specified Amazon Web Services Systems Manager document -// (SSM document). -func (c *Client) GetDocument(ctx context.Context, params *GetDocumentInput, optFns ...func(*Options)) (*GetDocumentOutput, error) { - if params == nil { - params = &GetDocumentInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetDocument", params, optFns, c.addOperationGetDocumentMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetDocumentOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetDocumentInput struct { - - // The name of the SSM document. - // - // This member is required. - Name *string - - // Returns the document in the specified format. The document format can be either - // JSON or YAML. JSON is the default format. - DocumentFormat types.DocumentFormat - - // The document version for which you want information. - DocumentVersion *string - - // An optional field specifying the version of the artifact associated with the - // document. For example, "Release 12, Update 6". This value is unique across all - // versions of a document and can't be changed. - VersionName *string - - noSmithyDocumentSerde -} - -type GetDocumentOutput struct { - - // A description of the document attachments, including names, locations, sizes, - // and so on. - AttachmentsContent []types.AttachmentContent - - // The contents of the SSM document. - Content *string - - // The date the SSM document was created. - CreatedDate *time.Time - - // The friendly name of the SSM document. This value can differ for each version - // of the document. If you want to update this value, see UpdateDocument . - DisplayName *string - - // The document format, either JSON or YAML. - DocumentFormat types.DocumentFormat - - // The document type. - DocumentType types.DocumentType - - // The document version. - DocumentVersion *string - - // The name of the SSM document. - Name *string - - // A list of SSM documents required by a document. For example, an - // ApplicationConfiguration document requires an ApplicationConfigurationSchema - // document. - Requires []types.DocumentRequires - - // The current review status of a new custom Systems Manager document (SSM - // document) created by a member of your organization, or of the latest version of - // an existing SSM document. Only one version of an SSM document can be in the - // APPROVED state at a time. When a new version is approved, the status of the - // previous version changes to REJECTED. Only one version of an SSM document can be - // in review, or PENDING, at a time. - ReviewStatus types.ReviewStatus - - // The status of the SSM document, such as Creating , Active , Updating , Failed , - // and Deleting . - Status types.DocumentStatus - - // A message returned by Amazon Web Services Systems Manager that explains the - // Status value. For example, a Failed status might be explained by the - // StatusInformation message, "The specified S3 bucket doesn't exist. Verify that - // the URL of the S3 bucket is correct." - StatusInformation *string - - // The version of the artifact associated with the document. For example, "Release - // 12, Update 6". This value is unique across all versions of a document, and can't - // be changed. - VersionName *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetDocumentMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetDocument{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetDocument{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetDocument"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetDocumentValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetDocument(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetDocument(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetDocument", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetInventory.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetInventory.go deleted file mode 100644 index a84b17dc..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetInventory.go +++ /dev/null @@ -1,247 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Query inventory information. This includes managed node status, such as Stopped -// or Terminated . -func (c *Client) GetInventory(ctx context.Context, params *GetInventoryInput, optFns ...func(*Options)) (*GetInventoryOutput, error) { - if params == nil { - params = &GetInventoryInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetInventory", params, optFns, c.addOperationGetInventoryMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetInventoryOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetInventoryInput struct { - - // Returns counts of inventory types based on one or more expressions. For - // example, if you aggregate by using an expression that uses the - // AWS:InstanceInformation.PlatformType type, you can see a count of how many - // Windows and Linux managed nodes exist in your inventoried fleet. - Aggregators []types.InventoryAggregator - - // One or more filters. Use a filter to return a more specific list of results. - Filters []types.InventoryFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - // The list of inventory item types to return. - ResultAttributes []types.ResultAttribute - - noSmithyDocumentSerde -} - -type GetInventoryOutput struct { - - // Collection of inventory entities such as a collection of managed node inventory. - Entities []types.InventoryResultEntity - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetInventoryMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetInventory{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetInventory{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetInventory"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetInventoryValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetInventory(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// GetInventoryAPIClient is a client that implements the GetInventory operation. -type GetInventoryAPIClient interface { - GetInventory(context.Context, *GetInventoryInput, ...func(*Options)) (*GetInventoryOutput, error) -} - -var _ GetInventoryAPIClient = (*Client)(nil) - -// GetInventoryPaginatorOptions is the paginator options for GetInventory -type GetInventoryPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// GetInventoryPaginator is a paginator for GetInventory -type GetInventoryPaginator struct { - options GetInventoryPaginatorOptions - client GetInventoryAPIClient - params *GetInventoryInput - nextToken *string - firstPage bool -} - -// NewGetInventoryPaginator returns a new GetInventoryPaginator -func NewGetInventoryPaginator(client GetInventoryAPIClient, params *GetInventoryInput, optFns ...func(*GetInventoryPaginatorOptions)) *GetInventoryPaginator { - if params == nil { - params = &GetInventoryInput{} - } - - options := GetInventoryPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &GetInventoryPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *GetInventoryPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next GetInventory page. -func (p *GetInventoryPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*GetInventoryOutput, 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 - - result, err := p.client.GetInventory(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 -} - -func newServiceMetadataMiddleware_opGetInventory(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetInventory", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetInventorySchema.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetInventorySchema.go deleted file mode 100644 index 9d422bdc..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetInventorySchema.go +++ /dev/null @@ -1,245 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Return a list of inventory type names for the account, or return a list of -// attribute names for a specific Inventory item type. -func (c *Client) GetInventorySchema(ctx context.Context, params *GetInventorySchemaInput, optFns ...func(*Options)) (*GetInventorySchemaOutput, error) { - if params == nil { - params = &GetInventorySchemaInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetInventorySchema", params, optFns, c.addOperationGetInventorySchemaMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetInventorySchemaOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetInventorySchemaInput struct { - - // Returns inventory schemas that support aggregation. For example, this call - // returns the AWS:InstanceInformation type, because it supports aggregation based - // on the PlatformName , PlatformType , and PlatformVersion attributes. - Aggregator bool - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - // Returns the sub-type schema for a specified inventory type. - SubType *bool - - // The type of inventory item to return. - TypeName *string - - noSmithyDocumentSerde -} - -type GetInventorySchemaOutput struct { - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Inventory schemas returned by the request. - Schemas []types.InventoryItemSchema - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetInventorySchemaMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetInventorySchema{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetInventorySchema{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetInventorySchema"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opGetInventorySchema(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// GetInventorySchemaAPIClient is a client that implements the GetInventorySchema -// operation. -type GetInventorySchemaAPIClient interface { - GetInventorySchema(context.Context, *GetInventorySchemaInput, ...func(*Options)) (*GetInventorySchemaOutput, error) -} - -var _ GetInventorySchemaAPIClient = (*Client)(nil) - -// GetInventorySchemaPaginatorOptions is the paginator options for -// GetInventorySchema -type GetInventorySchemaPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// GetInventorySchemaPaginator is a paginator for GetInventorySchema -type GetInventorySchemaPaginator struct { - options GetInventorySchemaPaginatorOptions - client GetInventorySchemaAPIClient - params *GetInventorySchemaInput - nextToken *string - firstPage bool -} - -// NewGetInventorySchemaPaginator returns a new GetInventorySchemaPaginator -func NewGetInventorySchemaPaginator(client GetInventorySchemaAPIClient, params *GetInventorySchemaInput, optFns ...func(*GetInventorySchemaPaginatorOptions)) *GetInventorySchemaPaginator { - if params == nil { - params = &GetInventorySchemaInput{} - } - - options := GetInventorySchemaPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &GetInventorySchemaPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *GetInventorySchemaPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next GetInventorySchema page. -func (p *GetInventorySchemaPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*GetInventorySchemaOutput, 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 - - result, err := p.client.GetInventorySchema(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 -} - -func newServiceMetadataMiddleware_opGetInventorySchema(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetInventorySchema", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindow.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindow.go deleted file mode 100644 index 24750144..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindow.go +++ /dev/null @@ -1,190 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Retrieves a maintenance window. -func (c *Client) GetMaintenanceWindow(ctx context.Context, params *GetMaintenanceWindowInput, optFns ...func(*Options)) (*GetMaintenanceWindowOutput, error) { - if params == nil { - params = &GetMaintenanceWindowInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetMaintenanceWindow", params, optFns, c.addOperationGetMaintenanceWindowMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetMaintenanceWindowOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetMaintenanceWindowInput struct { - - // The ID of the maintenance window for which you want to retrieve information. - // - // This member is required. - WindowId *string - - noSmithyDocumentSerde -} - -type GetMaintenanceWindowOutput struct { - - // Whether targets must be registered with the maintenance window before tasks can - // be defined for those targets. - AllowUnassociatedTargets bool - - // The date the maintenance window was created. - CreatedDate *time.Time - - // The number of hours before the end of the maintenance window that Amazon Web - // Services Systems Manager stops scheduling new tasks for execution. - Cutoff int32 - - // The description of the maintenance window. - Description *string - - // The duration of the maintenance window in hours. - Duration *int32 - - // Indicates whether the maintenance window is enabled. - Enabled bool - - // The date and time, in ISO-8601 Extended format, for when the maintenance window - // is scheduled to become inactive. The maintenance window won't run after this - // specified time. - EndDate *string - - // The date the maintenance window was last modified. - ModifiedDate *time.Time - - // The name of the maintenance window. - Name *string - - // The next time the maintenance window will actually run, taking into account any - // specified times for the maintenance window to become active or inactive. - NextExecutionTime *string - - // The schedule of the maintenance window in the form of a cron or rate expression. - Schedule *string - - // The number of days to wait to run a maintenance window after the scheduled cron - // expression date and time. - ScheduleOffset *int32 - - // The time zone that the scheduled maintenance window executions are based on, in - // Internet Assigned Numbers Authority (IANA) format. For example: - // "America/Los_Angeles", "UTC", or "Asia/Seoul". For more information, see the - // Time Zone Database (https://www.iana.org/time-zones) on the IANA website. - ScheduleTimezone *string - - // The date and time, in ISO-8601 Extended format, for when the maintenance window - // is scheduled to become active. The maintenance window won't run before this - // specified time. - StartDate *string - - // The ID of the created maintenance window. - WindowId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetMaintenanceWindowMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetMaintenanceWindow"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetMaintenanceWindowValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetMaintenanceWindow(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetMaintenanceWindow(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetMaintenanceWindow", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowExecution.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowExecution.go deleted file mode 100644 index 9c46cf82..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowExecution.go +++ /dev/null @@ -1,153 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Retrieves details about a specific a maintenance window execution. -func (c *Client) GetMaintenanceWindowExecution(ctx context.Context, params *GetMaintenanceWindowExecutionInput, optFns ...func(*Options)) (*GetMaintenanceWindowExecutionOutput, error) { - if params == nil { - params = &GetMaintenanceWindowExecutionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetMaintenanceWindowExecution", params, optFns, c.addOperationGetMaintenanceWindowExecutionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetMaintenanceWindowExecutionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetMaintenanceWindowExecutionInput struct { - - // The ID of the maintenance window execution that includes the task. - // - // This member is required. - WindowExecutionId *string - - noSmithyDocumentSerde -} - -type GetMaintenanceWindowExecutionOutput struct { - - // The time the maintenance window finished running. - EndTime *time.Time - - // The time the maintenance window started running. - StartTime *time.Time - - // The status of the maintenance window execution. - Status types.MaintenanceWindowExecutionStatus - - // The details explaining the status. Not available for all status values. - StatusDetails *string - - // The ID of the task executions from the maintenance window execution. - TaskIds []string - - // The ID of the maintenance window execution. - WindowExecutionId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetMaintenanceWindowExecutionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetMaintenanceWindowExecution{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetMaintenanceWindowExecution{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetMaintenanceWindowExecution"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetMaintenanceWindowExecutionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetMaintenanceWindowExecution(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetMaintenanceWindowExecution(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetMaintenanceWindowExecution", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowExecutionTask.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowExecutionTask.go deleted file mode 100644 index c7ffe975..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowExecutionTask.go +++ /dev/null @@ -1,197 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Retrieves the details about a specific task run as part of a maintenance window -// execution. -func (c *Client) GetMaintenanceWindowExecutionTask(ctx context.Context, params *GetMaintenanceWindowExecutionTaskInput, optFns ...func(*Options)) (*GetMaintenanceWindowExecutionTaskOutput, error) { - if params == nil { - params = &GetMaintenanceWindowExecutionTaskInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetMaintenanceWindowExecutionTask", params, optFns, c.addOperationGetMaintenanceWindowExecutionTaskMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetMaintenanceWindowExecutionTaskOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetMaintenanceWindowExecutionTaskInput struct { - - // The ID of the specific task execution in the maintenance window task that - // should be retrieved. - // - // This member is required. - TaskId *string - - // The ID of the maintenance window execution that includes the task. - // - // This member is required. - WindowExecutionId *string - - noSmithyDocumentSerde -} - -type GetMaintenanceWindowExecutionTaskOutput struct { - - // The details for the CloudWatch alarm you applied to your maintenance window - // task. - AlarmConfiguration *types.AlarmConfiguration - - // The time the task execution completed. - EndTime *time.Time - - // The defined maximum number of task executions that could be run in parallel. - MaxConcurrency *string - - // The defined maximum number of task execution errors allowed before scheduling - // of the task execution would have been stopped. - MaxErrors *string - - // The priority of the task. - Priority int32 - - // The role that was assumed when running the task. - ServiceRole *string - - // The time the task execution started. - StartTime *time.Time - - // The status of the task. - Status types.MaintenanceWindowExecutionStatus - - // The details explaining the status. Not available for all status values. - StatusDetails *string - - // The Amazon Resource Name (ARN) of the task that ran. - TaskArn *string - - // The ID of the specific task execution in the maintenance window task that was - // retrieved. - TaskExecutionId *string - - // The parameters passed to the task when it was run. TaskParameters has been - // deprecated. To specify parameters to pass to a task when it runs, instead use - // the Parameters option in the TaskInvocationParameters structure. For - // information about how Systems Manager handles these options for the supported - // maintenance window task types, see MaintenanceWindowTaskInvocationParameters . - // The map has the following format: - // - Key : string, between 1 and 255 characters - // - Value : an array of strings, each between 1 and 255 characters - TaskParameters []map[string]types.MaintenanceWindowTaskParameterValueExpression - - // The CloudWatch alarms that were invoked by the maintenance window task. - TriggeredAlarms []types.AlarmStateInformation - - // The type of task that was run. - Type types.MaintenanceWindowTaskType - - // The ID of the maintenance window execution that includes the task. - WindowExecutionId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetMaintenanceWindowExecutionTaskMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetMaintenanceWindowExecutionTask{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetMaintenanceWindowExecutionTask{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetMaintenanceWindowExecutionTask"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetMaintenanceWindowExecutionTaskValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetMaintenanceWindowExecutionTask(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetMaintenanceWindowExecutionTask(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetMaintenanceWindowExecutionTask", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowExecutionTaskInvocation.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowExecutionTaskInvocation.go deleted file mode 100644 index a1d96e40..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowExecutionTaskInvocation.go +++ /dev/null @@ -1,185 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Retrieves information about a specific task running on a specific target. -func (c *Client) GetMaintenanceWindowExecutionTaskInvocation(ctx context.Context, params *GetMaintenanceWindowExecutionTaskInvocationInput, optFns ...func(*Options)) (*GetMaintenanceWindowExecutionTaskInvocationOutput, error) { - if params == nil { - params = &GetMaintenanceWindowExecutionTaskInvocationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetMaintenanceWindowExecutionTaskInvocation", params, optFns, c.addOperationGetMaintenanceWindowExecutionTaskInvocationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetMaintenanceWindowExecutionTaskInvocationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetMaintenanceWindowExecutionTaskInvocationInput struct { - - // The invocation ID to retrieve. - // - // This member is required. - InvocationId *string - - // The ID of the specific task in the maintenance window task that should be - // retrieved. - // - // This member is required. - TaskId *string - - // The ID of the maintenance window execution for which the task is a part. - // - // This member is required. - WindowExecutionId *string - - noSmithyDocumentSerde -} - -type GetMaintenanceWindowExecutionTaskInvocationOutput struct { - - // The time that the task finished running on the target. - EndTime *time.Time - - // The execution ID. - ExecutionId *string - - // The invocation ID. - InvocationId *string - - // User-provided value to be included in any Amazon CloudWatch Events or Amazon - // EventBridge events raised while running tasks for these targets in this - // maintenance window. - OwnerInformation *string - - // The parameters used at the time that the task ran. - Parameters *string - - // The time that the task started running on the target. - StartTime *time.Time - - // The task status for an invocation. - Status types.MaintenanceWindowExecutionStatus - - // The details explaining the status. Details are only available for certain - // status values. - StatusDetails *string - - // The task execution ID. - TaskExecutionId *string - - // Retrieves the task type for a maintenance window. - TaskType types.MaintenanceWindowTaskType - - // The maintenance window execution ID. - WindowExecutionId *string - - // The maintenance window target ID. - WindowTargetId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetMaintenanceWindowExecutionTaskInvocationMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetMaintenanceWindowExecutionTaskInvocation{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetMaintenanceWindowExecutionTaskInvocation{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetMaintenanceWindowExecutionTaskInvocation"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetMaintenanceWindowExecutionTaskInvocationValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetMaintenanceWindowExecutionTaskInvocation(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetMaintenanceWindowExecutionTaskInvocation(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetMaintenanceWindowExecutionTaskInvocation", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowTask.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowTask.go deleted file mode 100644 index 12e5c11a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetMaintenanceWindowTask.go +++ /dev/null @@ -1,222 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the details of a maintenance window task. For maintenance window -// tasks without a specified target, you can't supply values for --max-errors and -// --max-concurrency . Instead, the system inserts a placeholder value of 1 , which -// may be reported in the response to this command. These values don't affect the -// running of your task and can be ignored. To retrieve a list of tasks in a -// maintenance window, instead use the DescribeMaintenanceWindowTasks command. -func (c *Client) GetMaintenanceWindowTask(ctx context.Context, params *GetMaintenanceWindowTaskInput, optFns ...func(*Options)) (*GetMaintenanceWindowTaskOutput, error) { - if params == nil { - params = &GetMaintenanceWindowTaskInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetMaintenanceWindowTask", params, optFns, c.addOperationGetMaintenanceWindowTaskMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetMaintenanceWindowTaskOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetMaintenanceWindowTaskInput struct { - - // The maintenance window ID that includes the task to retrieve. - // - // This member is required. - WindowId *string - - // The maintenance window task ID to retrieve. - // - // This member is required. - WindowTaskId *string - - noSmithyDocumentSerde -} - -type GetMaintenanceWindowTaskOutput struct { - - // The details for the CloudWatch alarm you applied to your maintenance window - // task. - AlarmConfiguration *types.AlarmConfiguration - - // The action to take on tasks when the maintenance window cutoff time is reached. - // CONTINUE_TASK means that tasks continue to run. For Automation, Lambda, Step - // Functions tasks, CANCEL_TASK means that currently running task invocations - // continue, but no new task invocations are started. For Run Command tasks, - // CANCEL_TASK means the system attempts to stop the task by sending a - // CancelCommand operation. - CutoffBehavior types.MaintenanceWindowTaskCutoffBehavior - - // The retrieved task description. - Description *string - - // The location in Amazon Simple Storage Service (Amazon S3) where the task - // results are logged. LoggingInfo has been deprecated. To specify an Amazon - // Simple Storage Service (Amazon S3) bucket to contain logs, instead use the - // OutputS3BucketName and OutputS3KeyPrefix options in the TaskInvocationParameters - // structure. For information about how Amazon Web Services Systems Manager handles - // these options for the supported maintenance window task types, see - // MaintenanceWindowTaskInvocationParameters . - LoggingInfo *types.LoggingInfo - - // The maximum number of targets allowed to run this task in parallel. For - // maintenance window tasks without a target specified, you can't supply a value - // for this option. Instead, the system inserts a placeholder value of 1 , which - // may be reported in the response to this command. This value doesn't affect the - // running of your task and can be ignored. - MaxConcurrency *string - - // The maximum number of errors allowed before the task stops being scheduled. For - // maintenance window tasks without a target specified, you can't supply a value - // for this option. Instead, the system inserts a placeholder value of 1 , which - // may be reported in the response to this command. This value doesn't affect the - // running of your task and can be ignored. - MaxErrors *string - - // The retrieved task name. - Name *string - - // The priority of the task when it runs. The lower the number, the higher the - // priority. Tasks that have the same priority are scheduled in parallel. - Priority int32 - - // The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) - // service role to use to publish Amazon Simple Notification Service (Amazon SNS) - // notifications for maintenance window Run Command tasks. - ServiceRoleArn *string - - // The targets where the task should run. - Targets []types.Target - - // The resource that the task used during execution. For RUN_COMMAND and AUTOMATION - // task types, the value of TaskArn is the SSM document name/ARN. For LAMBDA - // tasks, the value is the function name/ARN. For STEP_FUNCTIONS tasks, the value - // is the state machine ARN. - TaskArn *string - - // The parameters to pass to the task when it runs. - TaskInvocationParameters *types.MaintenanceWindowTaskInvocationParameters - - // The parameters to pass to the task when it runs. TaskParameters has been - // deprecated. To specify parameters to pass to a task when it runs, instead use - // the Parameters option in the TaskInvocationParameters structure. For - // information about how Systems Manager handles these options for the supported - // maintenance window task types, see MaintenanceWindowTaskInvocationParameters . - TaskParameters map[string]types.MaintenanceWindowTaskParameterValueExpression - - // The type of task to run. - TaskType types.MaintenanceWindowTaskType - - // The retrieved maintenance window ID. - WindowId *string - - // The retrieved maintenance window task ID. - WindowTaskId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetMaintenanceWindowTaskMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetMaintenanceWindowTask{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetMaintenanceWindowTask{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetMaintenanceWindowTask"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetMaintenanceWindowTaskValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetMaintenanceWindowTask(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetMaintenanceWindowTask(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetMaintenanceWindowTask", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetOpsItem.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetOpsItem.go deleted file mode 100644 index dbb5ed74..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetOpsItem.go +++ /dev/null @@ -1,148 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Get information about an OpsItem by using the ID. You must have permission in -// Identity and Access Management (IAM) to view information about an OpsItem. For -// more information, see Set up OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-setup.html) -// in the Amazon Web Services Systems Manager User Guide. Operations engineers and -// IT professionals use Amazon Web Services Systems Manager OpsCenter to view, -// investigate, and remediate operational issues impacting the performance and -// health of their Amazon Web Services resources. For more information, see -// OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) -// in the Amazon Web Services Systems Manager User Guide. -func (c *Client) GetOpsItem(ctx context.Context, params *GetOpsItemInput, optFns ...func(*Options)) (*GetOpsItemOutput, error) { - if params == nil { - params = &GetOpsItemInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetOpsItem", params, optFns, c.addOperationGetOpsItemMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetOpsItemOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetOpsItemInput struct { - - // The ID of the OpsItem that you want to get. - // - // This member is required. - OpsItemId *string - - // The OpsItem Amazon Resource Name (ARN). - OpsItemArn *string - - noSmithyDocumentSerde -} - -type GetOpsItemOutput struct { - - // The OpsItem. - OpsItem *types.OpsItem - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetOpsItemMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetOpsItem{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetOpsItem{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetOpsItem"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetOpsItemValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetOpsItem(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetOpsItem(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetOpsItem", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetOpsMetadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetOpsMetadata.go deleted file mode 100644 index 5a5f22a4..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetOpsMetadata.go +++ /dev/null @@ -1,151 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// View operational metadata related to an application in Application Manager. -func (c *Client) GetOpsMetadata(ctx context.Context, params *GetOpsMetadataInput, optFns ...func(*Options)) (*GetOpsMetadataOutput, error) { - if params == nil { - params = &GetOpsMetadataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetOpsMetadata", params, optFns, c.addOperationGetOpsMetadataMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetOpsMetadataOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetOpsMetadataInput struct { - - // The Amazon Resource Name (ARN) of an OpsMetadata Object to view. - // - // This member is required. - OpsMetadataArn *string - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - noSmithyDocumentSerde -} - -type GetOpsMetadataOutput struct { - - // OpsMetadata for an Application Manager application. - Metadata map[string]types.MetadataValue - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // The resource ID of the Application Manager application. - ResourceId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetOpsMetadataMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetOpsMetadata{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetOpsMetadata{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetOpsMetadata"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetOpsMetadataValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetOpsMetadata(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetOpsMetadata(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetOpsMetadata", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetOpsSummary.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetOpsSummary.go deleted file mode 100644 index 60559038..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetOpsSummary.go +++ /dev/null @@ -1,250 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// View a summary of operations metadata (OpsData) based on specified filters and -// aggregators. OpsData can include information about Amazon Web Services Systems -// Manager OpsCenter operational workitems (OpsItems) as well as information about -// any Amazon Web Services resource or service configured to report OpsData to -// Amazon Web Services Systems Manager Explorer. -func (c *Client) GetOpsSummary(ctx context.Context, params *GetOpsSummaryInput, optFns ...func(*Options)) (*GetOpsSummaryOutput, error) { - if params == nil { - params = &GetOpsSummaryInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetOpsSummary", params, optFns, c.addOperationGetOpsSummaryMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetOpsSummaryOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetOpsSummaryInput struct { - - // Optional aggregators that return counts of OpsData based on one or more - // expressions. - Aggregators []types.OpsAggregator - - // Optional filters used to scope down the returned OpsData. - Filters []types.OpsFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - // The OpsData data type to return. - ResultAttributes []types.OpsResultAttribute - - // Specify the name of a resource data sync to get. - SyncName *string - - noSmithyDocumentSerde -} - -type GetOpsSummaryOutput struct { - - // The list of aggregated details and filtered OpsData. - Entities []types.OpsEntity - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetOpsSummaryMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetOpsSummary{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetOpsSummary{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetOpsSummary"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetOpsSummaryValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetOpsSummary(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// GetOpsSummaryAPIClient is a client that implements the GetOpsSummary operation. -type GetOpsSummaryAPIClient interface { - GetOpsSummary(context.Context, *GetOpsSummaryInput, ...func(*Options)) (*GetOpsSummaryOutput, error) -} - -var _ GetOpsSummaryAPIClient = (*Client)(nil) - -// GetOpsSummaryPaginatorOptions is the paginator options for GetOpsSummary -type GetOpsSummaryPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// GetOpsSummaryPaginator is a paginator for GetOpsSummary -type GetOpsSummaryPaginator struct { - options GetOpsSummaryPaginatorOptions - client GetOpsSummaryAPIClient - params *GetOpsSummaryInput - nextToken *string - firstPage bool -} - -// NewGetOpsSummaryPaginator returns a new GetOpsSummaryPaginator -func NewGetOpsSummaryPaginator(client GetOpsSummaryAPIClient, params *GetOpsSummaryInput, optFns ...func(*GetOpsSummaryPaginatorOptions)) *GetOpsSummaryPaginator { - if params == nil { - params = &GetOpsSummaryInput{} - } - - options := GetOpsSummaryPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &GetOpsSummaryPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *GetOpsSummaryPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next GetOpsSummary page. -func (p *GetOpsSummaryPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*GetOpsSummaryOutput, 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 - - result, err := p.client.GetOpsSummary(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 -} - -func newServiceMetadataMiddleware_opGetOpsSummary(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetOpsSummary", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParameter.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParameter.go deleted file mode 100644 index 75aaa166..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParameter.go +++ /dev/null @@ -1,145 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Get information about a single parameter by specifying the parameter name. To -// get information about more than one parameter at a time, use the GetParameters -// operation. -func (c *Client) GetParameter(ctx context.Context, params *GetParameterInput, optFns ...func(*Options)) (*GetParameterOutput, error) { - if params == nil { - params = &GetParameterInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetParameter", params, optFns, c.addOperationGetParameterMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetParameterOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetParameterInput struct { - - // The name of the parameter you want to query. To query by parameter label, use - // "Name": "name:label" . To query by parameter version, use "Name": "name:version" - // . - // - // This member is required. - Name *string - - // Return decrypted values for secure string parameters. This flag is ignored for - // String and StringList parameter types. - WithDecryption *bool - - noSmithyDocumentSerde -} - -type GetParameterOutput struct { - - // Information about a parameter. - Parameter *types.Parameter - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetParameterMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetParameter{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetParameter{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetParameter"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetParameterValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetParameter(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetParameter(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetParameter", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParameterHistory.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParameterHistory.go deleted file mode 100644 index cd99f0cd..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParameterHistory.go +++ /dev/null @@ -1,248 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the history of all changes to a parameter. If you change the KMS key -// alias for the KMS key used to encrypt a parameter, then you must also update the -// key alias the parameter uses to reference KMS. Otherwise, GetParameterHistory -// retrieves whatever the original key alias was referencing. -func (c *Client) GetParameterHistory(ctx context.Context, params *GetParameterHistoryInput, optFns ...func(*Options)) (*GetParameterHistoryOutput, error) { - if params == nil { - params = &GetParameterHistoryInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetParameterHistory", params, optFns, c.addOperationGetParameterHistoryMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetParameterHistoryOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetParameterHistoryInput struct { - - // The name of the parameter for which you want to review history. - // - // This member is required. - Name *string - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - // Return decrypted values for secure string parameters. This flag is ignored for - // String and StringList parameter types. - WithDecryption *bool - - noSmithyDocumentSerde -} - -type GetParameterHistoryOutput struct { - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // A list of parameters returned by the request. - Parameters []types.ParameterHistory - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetParameterHistoryMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetParameterHistory{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetParameterHistory{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetParameterHistory"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetParameterHistoryValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetParameterHistory(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// GetParameterHistoryAPIClient is a client that implements the -// GetParameterHistory operation. -type GetParameterHistoryAPIClient interface { - GetParameterHistory(context.Context, *GetParameterHistoryInput, ...func(*Options)) (*GetParameterHistoryOutput, error) -} - -var _ GetParameterHistoryAPIClient = (*Client)(nil) - -// GetParameterHistoryPaginatorOptions is the paginator options for -// GetParameterHistory -type GetParameterHistoryPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// GetParameterHistoryPaginator is a paginator for GetParameterHistory -type GetParameterHistoryPaginator struct { - options GetParameterHistoryPaginatorOptions - client GetParameterHistoryAPIClient - params *GetParameterHistoryInput - nextToken *string - firstPage bool -} - -// NewGetParameterHistoryPaginator returns a new GetParameterHistoryPaginator -func NewGetParameterHistoryPaginator(client GetParameterHistoryAPIClient, params *GetParameterHistoryInput, optFns ...func(*GetParameterHistoryPaginatorOptions)) *GetParameterHistoryPaginator { - if params == nil { - params = &GetParameterHistoryInput{} - } - - options := GetParameterHistoryPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &GetParameterHistoryPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *GetParameterHistoryPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next GetParameterHistory page. -func (p *GetParameterHistoryPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*GetParameterHistoryOutput, 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 - - result, err := p.client.GetParameterHistory(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 -} - -func newServiceMetadataMiddleware_opGetParameterHistory(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetParameterHistory", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParameters.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParameters.go deleted file mode 100644 index 7fabdaf8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParameters.go +++ /dev/null @@ -1,149 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Get information about one or more parameters by specifying multiple parameter -// names. To get information about a single parameter, you can use the GetParameter -// operation instead. -func (c *Client) GetParameters(ctx context.Context, params *GetParametersInput, optFns ...func(*Options)) (*GetParametersOutput, error) { - if params == nil { - params = &GetParametersInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetParameters", params, optFns, c.addOperationGetParametersMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetParametersOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetParametersInput struct { - - // Names of the parameters for which you want to query information. To query by - // parameter label, use "Name": "name:label" . To query by parameter version, use - // "Name": "name:version" . - // - // This member is required. - Names []string - - // Return decrypted secure string value. Return decrypted values for secure string - // parameters. This flag is ignored for String and StringList parameter types. - WithDecryption *bool - - noSmithyDocumentSerde -} - -type GetParametersOutput struct { - - // A list of parameters that aren't formatted correctly or don't run during an - // execution. - InvalidParameters []string - - // A list of details for a parameter. - Parameters []types.Parameter - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetParametersMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetParameters{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetParameters{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetParameters"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetParametersValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetParameters(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetParameters(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetParameters", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParametersByPath.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParametersByPath.go deleted file mode 100644 index 50c44007..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetParametersByPath.go +++ /dev/null @@ -1,268 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieve information about one or more parameters in a specific hierarchy. -// Request results are returned on a best-effort basis. If you specify MaxResults -// in the request, the response includes information up to the limit specified. The -// number of items returned, however, can be between zero and the value of -// MaxResults . If the service reaches an internal limit while processing the -// results, it stops the operation and returns the matching values up to that point -// and a NextToken . You can specify the NextToken in a subsequent call to get the -// next set of results. -func (c *Client) GetParametersByPath(ctx context.Context, params *GetParametersByPathInput, optFns ...func(*Options)) (*GetParametersByPathOutput, error) { - if params == nil { - params = &GetParametersByPathInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetParametersByPath", params, optFns, c.addOperationGetParametersByPathMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetParametersByPathOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetParametersByPathInput struct { - - // The hierarchy for the parameter. Hierarchies start with a forward slash (/). - // The hierarchy is the parameter name except the last part of the parameter. For - // the API call to succeed, the last part of the parameter name can't be in the - // path. A parameter name hierarchy can have a maximum of 15 levels. Here is an - // example of a hierarchy: /Finance/Prod/IAD/WinServ2016/license33 - // - // This member is required. - Path *string - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - // Filters to limit the request results. The following Key values are supported - // for GetParametersByPath : Type , KeyId , and Label . The following Key values - // aren't supported for GetParametersByPath : tag , DataType , Name , Path , and - // Tier . - ParameterFilters []types.ParameterStringFilter - - // Retrieve all parameters within a hierarchy. If a user has access to a path, - // then the user can access all levels of that path. For example, if a user has - // permission to access path /a , then the user can also access /a/b . Even if a - // user has explicitly been denied access in IAM for parameter /a/b , they can - // still call the GetParametersByPath API operation recursively for /a and view - // /a/b . - Recursive *bool - - // Retrieve all parameters in a hierarchy with their value decrypted. - WithDecryption *bool - - noSmithyDocumentSerde -} - -type GetParametersByPathOutput struct { - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // A list of parameters found in the specified hierarchy. - Parameters []types.Parameter - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetParametersByPathMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetParametersByPath{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetParametersByPath{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetParametersByPath"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetParametersByPathValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetParametersByPath(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// GetParametersByPathAPIClient is a client that implements the -// GetParametersByPath operation. -type GetParametersByPathAPIClient interface { - GetParametersByPath(context.Context, *GetParametersByPathInput, ...func(*Options)) (*GetParametersByPathOutput, error) -} - -var _ GetParametersByPathAPIClient = (*Client)(nil) - -// GetParametersByPathPaginatorOptions is the paginator options for -// GetParametersByPath -type GetParametersByPathPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// GetParametersByPathPaginator is a paginator for GetParametersByPath -type GetParametersByPathPaginator struct { - options GetParametersByPathPaginatorOptions - client GetParametersByPathAPIClient - params *GetParametersByPathInput - nextToken *string - firstPage bool -} - -// NewGetParametersByPathPaginator returns a new GetParametersByPathPaginator -func NewGetParametersByPathPaginator(client GetParametersByPathAPIClient, params *GetParametersByPathInput, optFns ...func(*GetParametersByPathPaginatorOptions)) *GetParametersByPathPaginator { - if params == nil { - params = &GetParametersByPathInput{} - } - - options := GetParametersByPathPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &GetParametersByPathPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *GetParametersByPathPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next GetParametersByPath page. -func (p *GetParametersByPathPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*GetParametersByPathOutput, 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 - - result, err := p.client.GetParametersByPath(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 -} - -func newServiceMetadataMiddleware_opGetParametersByPath(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetParametersByPath", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetPatchBaseline.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetPatchBaseline.go deleted file mode 100644 index 667c52cb..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetPatchBaseline.go +++ /dev/null @@ -1,192 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Retrieves information about a patch baseline. -func (c *Client) GetPatchBaseline(ctx context.Context, params *GetPatchBaselineInput, optFns ...func(*Options)) (*GetPatchBaselineOutput, error) { - if params == nil { - params = &GetPatchBaselineInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetPatchBaseline", params, optFns, c.addOperationGetPatchBaselineMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetPatchBaselineOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetPatchBaselineInput struct { - - // The ID of the patch baseline to retrieve. To retrieve information about an - // Amazon Web Services managed patch baseline, specify the full Amazon Resource - // Name (ARN) of the baseline. For example, for the baseline - // AWS-AmazonLinuxDefaultPatchBaseline , specify - // arn:aws:ssm:us-east-2:733109147000:patchbaseline/pb-0e392de35e7c563b7 instead of - // pb-0e392de35e7c563b7 . - // - // This member is required. - BaselineId *string - - noSmithyDocumentSerde -} - -type GetPatchBaselineOutput struct { - - // A set of rules used to include patches in the baseline. - ApprovalRules *types.PatchRuleGroup - - // A list of explicitly approved patches for the baseline. - ApprovedPatches []string - - // Returns the specified compliance severity level for approved patches in the - // patch baseline. - ApprovedPatchesComplianceLevel types.PatchComplianceLevel - - // Indicates whether the list of approved patches includes non-security updates - // that should be applied to the managed nodes. The default value is false . - // Applies to Linux managed nodes only. - ApprovedPatchesEnableNonSecurity *bool - - // The ID of the retrieved patch baseline. - BaselineId *string - - // The date the patch baseline was created. - CreatedDate *time.Time - - // A description of the patch baseline. - Description *string - - // A set of global filters used to exclude patches from the baseline. - GlobalFilters *types.PatchFilterGroup - - // The date the patch baseline was last modified. - ModifiedDate *time.Time - - // The name of the patch baseline. - Name *string - - // Returns the operating system specified for the patch baseline. - OperatingSystem types.OperatingSystem - - // Patch groups included in the patch baseline. - PatchGroups []string - - // A list of explicitly rejected patches for the baseline. - RejectedPatches []string - - // The action specified to take on patches included in the RejectedPatches list. A - // patch can be allowed only if it is a dependency of another package, or blocked - // entirely along with packages that include it as a dependency. - RejectedPatchesAction types.PatchAction - - // Information about the patches to use to update the managed nodes, including - // target operating systems and source repositories. Applies to Linux managed nodes - // only. - Sources []types.PatchSource - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetPatchBaselineMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetPatchBaseline{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetPatchBaseline{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetPatchBaseline"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetPatchBaselineValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetPatchBaseline(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetPatchBaseline(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetPatchBaseline", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetPatchBaselineForPatchGroup.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetPatchBaselineForPatchGroup.go deleted file mode 100644 index e78f1685..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetPatchBaselineForPatchGroup.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves the patch baseline that should be used for the specified patch group. -func (c *Client) GetPatchBaselineForPatchGroup(ctx context.Context, params *GetPatchBaselineForPatchGroupInput, optFns ...func(*Options)) (*GetPatchBaselineForPatchGroupOutput, error) { - if params == nil { - params = &GetPatchBaselineForPatchGroupInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetPatchBaselineForPatchGroup", params, optFns, c.addOperationGetPatchBaselineForPatchGroupMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetPatchBaselineForPatchGroupOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetPatchBaselineForPatchGroupInput struct { - - // The name of the patch group whose patch baseline should be retrieved. - // - // This member is required. - PatchGroup *string - - // Returns the operating system rule specified for patch groups using the patch - // baseline. - OperatingSystem types.OperatingSystem - - noSmithyDocumentSerde -} - -type GetPatchBaselineForPatchGroupOutput struct { - - // The ID of the patch baseline that should be used for the patch group. - BaselineId *string - - // The operating system rule specified for patch groups using the patch baseline. - OperatingSystem types.OperatingSystem - - // The name of the patch group. - PatchGroup *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetPatchBaselineForPatchGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetPatchBaselineForPatchGroup{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetPatchBaselineForPatchGroup{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetPatchBaselineForPatchGroup"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetPatchBaselineForPatchGroupValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetPatchBaselineForPatchGroup(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetPatchBaselineForPatchGroup(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetPatchBaselineForPatchGroup", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetResourcePolicies.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetResourcePolicies.go deleted file mode 100644 index aead9276..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetResourcePolicies.go +++ /dev/null @@ -1,240 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns an array of the Policy object. -func (c *Client) GetResourcePolicies(ctx context.Context, params *GetResourcePoliciesInput, optFns ...func(*Options)) (*GetResourcePoliciesOutput, error) { - if params == nil { - params = &GetResourcePoliciesInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetResourcePolicies", params, optFns, c.addOperationGetResourcePoliciesMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetResourcePoliciesOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetResourcePoliciesInput struct { - - // Amazon Resource Name (ARN) of the resource to which the policies are attached. - // - // This member is required. - ResourceArn *string - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - noSmithyDocumentSerde -} - -type GetResourcePoliciesOutput struct { - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // An array of the Policy object. - Policies []types.GetResourcePoliciesResponseEntry - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetResourcePoliciesMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetResourcePolicies{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetResourcePolicies{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetResourcePolicies"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetResourcePoliciesValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetResourcePolicies(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// GetResourcePoliciesAPIClient is a client that implements the -// GetResourcePolicies operation. -type GetResourcePoliciesAPIClient interface { - GetResourcePolicies(context.Context, *GetResourcePoliciesInput, ...func(*Options)) (*GetResourcePoliciesOutput, error) -} - -var _ GetResourcePoliciesAPIClient = (*Client)(nil) - -// GetResourcePoliciesPaginatorOptions is the paginator options for -// GetResourcePolicies -type GetResourcePoliciesPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// GetResourcePoliciesPaginator is a paginator for GetResourcePolicies -type GetResourcePoliciesPaginator struct { - options GetResourcePoliciesPaginatorOptions - client GetResourcePoliciesAPIClient - params *GetResourcePoliciesInput - nextToken *string - firstPage bool -} - -// NewGetResourcePoliciesPaginator returns a new GetResourcePoliciesPaginator -func NewGetResourcePoliciesPaginator(client GetResourcePoliciesAPIClient, params *GetResourcePoliciesInput, optFns ...func(*GetResourcePoliciesPaginatorOptions)) *GetResourcePoliciesPaginator { - if params == nil { - params = &GetResourcePoliciesInput{} - } - - options := GetResourcePoliciesPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &GetResourcePoliciesPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *GetResourcePoliciesPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next GetResourcePolicies page. -func (p *GetResourcePoliciesPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*GetResourcePoliciesOutput, 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 - - result, err := p.client.GetResourcePolicies(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 -} - -func newServiceMetadataMiddleware_opGetResourcePolicies(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetResourcePolicies", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetServiceSetting.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetServiceSetting.go deleted file mode 100644 index 3f8ec2db..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_GetServiceSetting.go +++ /dev/null @@ -1,161 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// ServiceSetting is an account-level setting for an Amazon Web Services service. -// This setting defines how a user interacts with or uses a service or a feature of -// a service. For example, if an Amazon Web Services service charges money to the -// account based on feature or service usage, then the Amazon Web Services service -// team might create a default setting of false . This means the user can't use -// this feature unless they change the setting to true and intentionally opt in -// for a paid feature. Services map a SettingId object to a setting value. Amazon -// Web Services services teams define the default value for a SettingId . You can't -// create a new SettingId , but you can overwrite the default value if you have the -// ssm:UpdateServiceSetting permission for the setting. Use the -// UpdateServiceSetting API operation to change the default setting. Or use the -// ResetServiceSetting to change the value back to the original value defined by -// the Amazon Web Services service team. Query the current service setting for the -// Amazon Web Services account. -func (c *Client) GetServiceSetting(ctx context.Context, params *GetServiceSettingInput, optFns ...func(*Options)) (*GetServiceSettingOutput, error) { - if params == nil { - params = &GetServiceSettingInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetServiceSetting", params, optFns, c.addOperationGetServiceSettingMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetServiceSettingOutput) - out.ResultMetadata = metadata - return out, nil -} - -// The request body of the GetServiceSetting API operation. -type GetServiceSettingInput struct { - - // The ID of the service setting to get. The setting ID can be one of the - // following. - // - /ssm/managed-instance/default-ec2-instance-management-role - // - /ssm/automation/customer-script-log-destination - // - /ssm/automation/customer-script-log-group-name - // - /ssm/documents/console/public-sharing-permission - // - /ssm/managed-instance/activation-tier - // - /ssm/opsinsights/opscenter - // - /ssm/parameter-store/default-parameter-tier - // - /ssm/parameter-store/high-throughput-enabled - // - // This member is required. - SettingId *string - - noSmithyDocumentSerde -} - -// The query result body of the GetServiceSetting API operation. -type GetServiceSettingOutput struct { - - // The query result of the current service setting. - ServiceSetting *types.ServiceSetting - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetServiceSettingMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpGetServiceSetting{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpGetServiceSetting{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetServiceSetting"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetServiceSettingValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetServiceSetting(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetServiceSetting(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetServiceSetting", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_LabelParameterVersion.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_LabelParameterVersion.go deleted file mode 100644 index 32a9c5a2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_LabelParameterVersion.go +++ /dev/null @@ -1,170 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// A parameter label is a user-defined alias to help you manage different versions -// of a parameter. When you modify a parameter, Amazon Web Services Systems Manager -// automatically saves a new version and increments the version number by one. A -// label can help you remember the purpose of a parameter when there are multiple -// versions. Parameter labels have the following requirements and restrictions. -// - A version of a parameter can have a maximum of 10 labels. -// - You can't attach the same label to different versions of the same -// parameter. For example, if version 1 has the label Production, then you can't -// attach Production to version 2. -// - You can move a label from one version of a parameter to another. -// - You can't create a label when you create a new parameter. You must attach a -// label to a specific version of a parameter. -// - If you no longer want to use a parameter label, then you can either delete -// it or move it to a different version of a parameter. -// - A label can have a maximum of 100 characters. -// - Labels can contain letters (case sensitive), numbers, periods (.), hyphens -// (-), or underscores (_). -// - Labels can't begin with a number, " aws " or " ssm " (not case sensitive). -// If a label fails to meet these requirements, then the label isn't associated -// with a parameter and the system displays it in the list of InvalidLabels. -func (c *Client) LabelParameterVersion(ctx context.Context, params *LabelParameterVersionInput, optFns ...func(*Options)) (*LabelParameterVersionOutput, error) { - if params == nil { - params = &LabelParameterVersionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "LabelParameterVersion", params, optFns, c.addOperationLabelParameterVersionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*LabelParameterVersionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type LabelParameterVersionInput struct { - - // One or more labels to attach to the specified parameter version. - // - // This member is required. - Labels []string - - // The parameter name on which you want to attach one or more labels. - // - // This member is required. - Name *string - - // The specific version of the parameter on which you want to attach one or more - // labels. If no version is specified, the system attaches the label to the latest - // version. - ParameterVersion *int64 - - noSmithyDocumentSerde -} - -type LabelParameterVersionOutput struct { - - // The label doesn't meet the requirements. For information about parameter label - // requirements, see Labeling parameters (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html) - // in the Amazon Web Services Systems Manager User Guide. - InvalidLabels []string - - // The version of the parameter that has been labeled. - ParameterVersion int64 - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationLabelParameterVersionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpLabelParameterVersion{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpLabelParameterVersion{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "LabelParameterVersion"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpLabelParameterVersionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opLabelParameterVersion(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opLabelParameterVersion(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "LabelParameterVersion", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListAssociationVersions.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListAssociationVersions.go deleted file mode 100644 index 4ab028ef..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListAssociationVersions.go +++ /dev/null @@ -1,242 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Retrieves all versions of an association for a specific association ID. -func (c *Client) ListAssociationVersions(ctx context.Context, params *ListAssociationVersionsInput, optFns ...func(*Options)) (*ListAssociationVersionsOutput, error) { - if params == nil { - params = &ListAssociationVersionsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListAssociationVersions", params, optFns, c.addOperationListAssociationVersionsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListAssociationVersionsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListAssociationVersionsInput struct { - - // The association ID for which you want to view all versions. - // - // This member is required. - AssociationId *string - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - noSmithyDocumentSerde -} - -type ListAssociationVersionsOutput struct { - - // Information about all versions of the association for the specified association - // ID. - AssociationVersions []types.AssociationVersionInfo - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListAssociationVersionsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListAssociationVersions{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListAssociationVersions{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListAssociationVersions"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListAssociationVersionsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListAssociationVersions(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListAssociationVersionsAPIClient is a client that implements the -// ListAssociationVersions operation. -type ListAssociationVersionsAPIClient interface { - ListAssociationVersions(context.Context, *ListAssociationVersionsInput, ...func(*Options)) (*ListAssociationVersionsOutput, error) -} - -var _ ListAssociationVersionsAPIClient = (*Client)(nil) - -// ListAssociationVersionsPaginatorOptions is the paginator options for -// ListAssociationVersions -type ListAssociationVersionsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// ListAssociationVersionsPaginator is a paginator for ListAssociationVersions -type ListAssociationVersionsPaginator struct { - options ListAssociationVersionsPaginatorOptions - client ListAssociationVersionsAPIClient - params *ListAssociationVersionsInput - nextToken *string - firstPage bool -} - -// NewListAssociationVersionsPaginator returns a new -// ListAssociationVersionsPaginator -func NewListAssociationVersionsPaginator(client ListAssociationVersionsAPIClient, params *ListAssociationVersionsInput, optFns ...func(*ListAssociationVersionsPaginatorOptions)) *ListAssociationVersionsPaginator { - if params == nil { - params = &ListAssociationVersionsInput{} - } - - options := ListAssociationVersionsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListAssociationVersionsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListAssociationVersionsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListAssociationVersions page. -func (p *ListAssociationVersionsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListAssociationVersionsOutput, 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 - - result, err := p.client.ListAssociationVersions(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 -} - -func newServiceMetadataMiddleware_opListAssociationVersions(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListAssociationVersions", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListAssociations.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListAssociations.go deleted file mode 100644 index e9224d67..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListAssociations.go +++ /dev/null @@ -1,245 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns all State Manager associations in the current Amazon Web Services -// account and Amazon Web Services Region. You can limit the results to a specific -// State Manager association document or managed node by specifying a filter. State -// Manager is a capability of Amazon Web Services Systems Manager. -func (c *Client) ListAssociations(ctx context.Context, params *ListAssociationsInput, optFns ...func(*Options)) (*ListAssociationsOutput, error) { - if params == nil { - params = &ListAssociationsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListAssociations", params, optFns, c.addOperationListAssociationsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListAssociationsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListAssociationsInput struct { - - // One or more filters. Use a filter to return a more specific list of results. - // Filtering associations using the InstanceID attribute only returns legacy - // associations created using the InstanceID attribute. Associations targeting the - // managed node that are part of the Target Attributes ResourceGroup or Tags - // aren't returned. - AssociationFilterList []types.AssociationFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type ListAssociationsOutput struct { - - // The associations. - Associations []types.Association - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListAssociationsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListAssociations{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListAssociations{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListAssociations"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListAssociationsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListAssociations(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListAssociationsAPIClient is a client that implements the ListAssociations -// operation. -type ListAssociationsAPIClient interface { - ListAssociations(context.Context, *ListAssociationsInput, ...func(*Options)) (*ListAssociationsOutput, error) -} - -var _ ListAssociationsAPIClient = (*Client)(nil) - -// ListAssociationsPaginatorOptions is the paginator options for ListAssociations -type ListAssociationsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// ListAssociationsPaginator is a paginator for ListAssociations -type ListAssociationsPaginator struct { - options ListAssociationsPaginatorOptions - client ListAssociationsAPIClient - params *ListAssociationsInput - nextToken *string - firstPage bool -} - -// NewListAssociationsPaginator returns a new ListAssociationsPaginator -func NewListAssociationsPaginator(client ListAssociationsAPIClient, params *ListAssociationsInput, optFns ...func(*ListAssociationsPaginatorOptions)) *ListAssociationsPaginator { - if params == nil { - params = &ListAssociationsInput{} - } - - options := ListAssociationsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListAssociationsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListAssociationsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListAssociations page. -func (p *ListAssociationsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListAssociationsOutput, 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 - - result, err := p.client.ListAssociations(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 -} - -func newServiceMetadataMiddleware_opListAssociations(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListAssociations", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListCommandInvocations.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListCommandInvocations.go deleted file mode 100644 index 26d062db..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListCommandInvocations.go +++ /dev/null @@ -1,256 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// An invocation is copy of a command sent to a specific managed node. A command -// can apply to one or more managed nodes. A command invocation applies to one -// managed node. For example, if a user runs SendCommand against three managed -// nodes, then a command invocation is created for each requested managed node ID. -// ListCommandInvocations provide status about command execution. -func (c *Client) ListCommandInvocations(ctx context.Context, params *ListCommandInvocationsInput, optFns ...func(*Options)) (*ListCommandInvocationsOutput, error) { - if params == nil { - params = &ListCommandInvocationsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListCommandInvocations", params, optFns, c.addOperationListCommandInvocationsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListCommandInvocationsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListCommandInvocationsInput struct { - - // (Optional) The invocations for a specific command ID. - CommandId *string - - // (Optional) If set this returns the response of the command executions and any - // command output. The default value is false . - Details bool - - // (Optional) One or more filters. Use a filter to return a more specific list of - // results. - Filters []types.CommandFilter - - // (Optional) The command execution details for a specific managed node ID. - InstanceId *string - - // (Optional) The maximum number of items to return for this call. The call also - // returns a token that you can specify in a subsequent call to get the next set of - // results. - MaxResults *int32 - - // (Optional) The token for the next set of items to return. (You received this - // token from a previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type ListCommandInvocationsOutput struct { - - // (Optional) A list of all invocations. - CommandInvocations []types.CommandInvocation - - // (Optional) The token for the next set of items to return. (You received this - // token from a previous call.) - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListCommandInvocationsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListCommandInvocations{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListCommandInvocations{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListCommandInvocations"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListCommandInvocationsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListCommandInvocations(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListCommandInvocationsAPIClient is a client that implements the -// ListCommandInvocations operation. -type ListCommandInvocationsAPIClient interface { - ListCommandInvocations(context.Context, *ListCommandInvocationsInput, ...func(*Options)) (*ListCommandInvocationsOutput, error) -} - -var _ ListCommandInvocationsAPIClient = (*Client)(nil) - -// ListCommandInvocationsPaginatorOptions is the paginator options for -// ListCommandInvocations -type ListCommandInvocationsPaginatorOptions struct { - // (Optional) The maximum number of items to return for this call. The call also - // returns a token that you can specify in a subsequent call to get the next set of - // results. - 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 -} - -// ListCommandInvocationsPaginator is a paginator for ListCommandInvocations -type ListCommandInvocationsPaginator struct { - options ListCommandInvocationsPaginatorOptions - client ListCommandInvocationsAPIClient - params *ListCommandInvocationsInput - nextToken *string - firstPage bool -} - -// NewListCommandInvocationsPaginator returns a new ListCommandInvocationsPaginator -func NewListCommandInvocationsPaginator(client ListCommandInvocationsAPIClient, params *ListCommandInvocationsInput, optFns ...func(*ListCommandInvocationsPaginatorOptions)) *ListCommandInvocationsPaginator { - if params == nil { - params = &ListCommandInvocationsInput{} - } - - options := ListCommandInvocationsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListCommandInvocationsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListCommandInvocationsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListCommandInvocations page. -func (p *ListCommandInvocationsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListCommandInvocationsOutput, 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 - - result, err := p.client.ListCommandInvocations(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 -} - -func newServiceMetadataMiddleware_opListCommandInvocations(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListCommandInvocations", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListCommands.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListCommands.go deleted file mode 100644 index 78af4046..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListCommands.go +++ /dev/null @@ -1,248 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists the commands requested by users of the Amazon Web Services account. -func (c *Client) ListCommands(ctx context.Context, params *ListCommandsInput, optFns ...func(*Options)) (*ListCommandsOutput, error) { - if params == nil { - params = &ListCommandsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListCommands", params, optFns, c.addOperationListCommandsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListCommandsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListCommandsInput struct { - - // (Optional) If provided, lists only the specified command. - CommandId *string - - // (Optional) One or more filters. Use a filter to return a more specific list of - // results. - Filters []types.CommandFilter - - // (Optional) Lists commands issued against this managed node ID. You can't - // specify a managed node ID in the same command that you specify Status = Pending - // . This is because the command hasn't reached the managed node yet. - InstanceId *string - - // (Optional) The maximum number of items to return for this call. The call also - // returns a token that you can specify in a subsequent call to get the next set of - // results. - MaxResults *int32 - - // (Optional) The token for the next set of items to return. (You received this - // token from a previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type ListCommandsOutput struct { - - // (Optional) The list of commands requested by the user. - Commands []types.Command - - // (Optional) The token for the next set of items to return. (You received this - // token from a previous call.) - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListCommandsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListCommands{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListCommands{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListCommands"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListCommandsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListCommands(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListCommandsAPIClient is a client that implements the ListCommands operation. -type ListCommandsAPIClient interface { - ListCommands(context.Context, *ListCommandsInput, ...func(*Options)) (*ListCommandsOutput, error) -} - -var _ ListCommandsAPIClient = (*Client)(nil) - -// ListCommandsPaginatorOptions is the paginator options for ListCommands -type ListCommandsPaginatorOptions struct { - // (Optional) The maximum number of items to return for this call. The call also - // returns a token that you can specify in a subsequent call to get the next set of - // results. - 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 -} - -// ListCommandsPaginator is a paginator for ListCommands -type ListCommandsPaginator struct { - options ListCommandsPaginatorOptions - client ListCommandsAPIClient - params *ListCommandsInput - nextToken *string - firstPage bool -} - -// NewListCommandsPaginator returns a new ListCommandsPaginator -func NewListCommandsPaginator(client ListCommandsAPIClient, params *ListCommandsInput, optFns ...func(*ListCommandsPaginatorOptions)) *ListCommandsPaginator { - if params == nil { - params = &ListCommandsInput{} - } - - options := ListCommandsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListCommandsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListCommandsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListCommands page. -func (p *ListCommandsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListCommandsOutput, 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 - - result, err := p.client.ListCommands(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 -} - -func newServiceMetadataMiddleware_opListCommands(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListCommands", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListComplianceItems.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListComplianceItems.go deleted file mode 100644 index c0daf817..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListComplianceItems.go +++ /dev/null @@ -1,247 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// For a specified resource ID, this API operation returns a list of compliance -// statuses for different resource types. Currently, you can only specify one -// resource ID per call. List results depend on the criteria specified in the -// filter. -func (c *Client) ListComplianceItems(ctx context.Context, params *ListComplianceItemsInput, optFns ...func(*Options)) (*ListComplianceItemsOutput, error) { - if params == nil { - params = &ListComplianceItemsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListComplianceItems", params, optFns, c.addOperationListComplianceItemsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListComplianceItemsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListComplianceItemsInput struct { - - // One or more compliance filters. Use a filter to return a more specific list of - // results. - Filters []types.ComplianceStringFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - // The ID for the resources from which to get compliance information. Currently, - // you can only specify one resource ID. - ResourceIds []string - - // The type of resource from which to get compliance information. Currently, the - // only supported resource type is ManagedInstance . - ResourceTypes []string - - noSmithyDocumentSerde -} - -type ListComplianceItemsOutput struct { - - // A list of compliance information for the specified resource ID. - ComplianceItems []types.ComplianceItem - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListComplianceItemsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListComplianceItems{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListComplianceItems{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListComplianceItems"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opListComplianceItems(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListComplianceItemsAPIClient is a client that implements the -// ListComplianceItems operation. -type ListComplianceItemsAPIClient interface { - ListComplianceItems(context.Context, *ListComplianceItemsInput, ...func(*Options)) (*ListComplianceItemsOutput, error) -} - -var _ ListComplianceItemsAPIClient = (*Client)(nil) - -// ListComplianceItemsPaginatorOptions is the paginator options for -// ListComplianceItems -type ListComplianceItemsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// ListComplianceItemsPaginator is a paginator for ListComplianceItems -type ListComplianceItemsPaginator struct { - options ListComplianceItemsPaginatorOptions - client ListComplianceItemsAPIClient - params *ListComplianceItemsInput - nextToken *string - firstPage bool -} - -// NewListComplianceItemsPaginator returns a new ListComplianceItemsPaginator -func NewListComplianceItemsPaginator(client ListComplianceItemsAPIClient, params *ListComplianceItemsInput, optFns ...func(*ListComplianceItemsPaginatorOptions)) *ListComplianceItemsPaginator { - if params == nil { - params = &ListComplianceItemsInput{} - } - - options := ListComplianceItemsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListComplianceItemsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListComplianceItemsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListComplianceItems page. -func (p *ListComplianceItemsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListComplianceItemsOutput, 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 - - result, err := p.client.ListComplianceItems(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 -} - -func newServiceMetadataMiddleware_opListComplianceItems(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListComplianceItems", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListComplianceSummaries.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListComplianceSummaries.go deleted file mode 100644 index c302842e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListComplianceSummaries.go +++ /dev/null @@ -1,244 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a summary count of compliant and non-compliant resources for a -// compliance type. For example, this call can return State Manager associations, -// patches, or custom compliance types according to the filter criteria that you -// specify. -func (c *Client) ListComplianceSummaries(ctx context.Context, params *ListComplianceSummariesInput, optFns ...func(*Options)) (*ListComplianceSummariesOutput, error) { - if params == nil { - params = &ListComplianceSummariesInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListComplianceSummaries", params, optFns, c.addOperationListComplianceSummariesMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListComplianceSummariesOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListComplianceSummariesInput struct { - - // One or more compliance or inventory filters. Use a filter to return a more - // specific list of results. - Filters []types.ComplianceStringFilter - - // The maximum number of items to return for this call. Currently, you can specify - // null or 50. The call also returns a token that you can specify in a subsequent - // call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - noSmithyDocumentSerde -} - -type ListComplianceSummariesOutput struct { - - // A list of compliant and non-compliant summary counts based on compliance types. - // For example, this call returns State Manager associations, patches, or custom - // compliance types according to the filter criteria that you specified. - ComplianceSummaryItems []types.ComplianceSummaryItem - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListComplianceSummariesMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListComplianceSummaries{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListComplianceSummaries{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListComplianceSummaries"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opListComplianceSummaries(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListComplianceSummariesAPIClient is a client that implements the -// ListComplianceSummaries operation. -type ListComplianceSummariesAPIClient interface { - ListComplianceSummaries(context.Context, *ListComplianceSummariesInput, ...func(*Options)) (*ListComplianceSummariesOutput, error) -} - -var _ ListComplianceSummariesAPIClient = (*Client)(nil) - -// ListComplianceSummariesPaginatorOptions is the paginator options for -// ListComplianceSummaries -type ListComplianceSummariesPaginatorOptions struct { - // The maximum number of items to return for this call. Currently, you can specify - // null or 50. The call also returns a token that you can specify in a subsequent - // call to get the next set of results. - 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 -} - -// ListComplianceSummariesPaginator is a paginator for ListComplianceSummaries -type ListComplianceSummariesPaginator struct { - options ListComplianceSummariesPaginatorOptions - client ListComplianceSummariesAPIClient - params *ListComplianceSummariesInput - nextToken *string - firstPage bool -} - -// NewListComplianceSummariesPaginator returns a new -// ListComplianceSummariesPaginator -func NewListComplianceSummariesPaginator(client ListComplianceSummariesAPIClient, params *ListComplianceSummariesInput, optFns ...func(*ListComplianceSummariesPaginatorOptions)) *ListComplianceSummariesPaginator { - if params == nil { - params = &ListComplianceSummariesInput{} - } - - options := ListComplianceSummariesPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListComplianceSummariesPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListComplianceSummariesPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListComplianceSummaries page. -func (p *ListComplianceSummariesPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListComplianceSummariesOutput, 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 - - result, err := p.client.ListComplianceSummaries(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 -} - -func newServiceMetadataMiddleware_opListComplianceSummaries(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListComplianceSummaries", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListDocumentMetadataHistory.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListDocumentMetadataHistory.go deleted file mode 100644 index 75303eb3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListDocumentMetadataHistory.go +++ /dev/null @@ -1,169 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Information about approval reviews for a version of a change template in Change -// Manager. -func (c *Client) ListDocumentMetadataHistory(ctx context.Context, params *ListDocumentMetadataHistoryInput, optFns ...func(*Options)) (*ListDocumentMetadataHistoryOutput, error) { - if params == nil { - params = &ListDocumentMetadataHistoryInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListDocumentMetadataHistory", params, optFns, c.addOperationListDocumentMetadataHistoryMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListDocumentMetadataHistoryOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListDocumentMetadataHistoryInput struct { - - // The type of data for which details are being requested. Currently, the only - // supported value is DocumentReviews . - // - // This member is required. - Metadata types.DocumentMetadataEnum - - // The name of the change template. - // - // This member is required. - Name *string - - // The version of the change template. - DocumentVersion *string - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type ListDocumentMetadataHistoryOutput struct { - - // The user ID of the person in the organization who requested the review of the - // change template. - Author *string - - // The version of the change template. - DocumentVersion *string - - // Information about the response to the change template approval request. - Metadata *types.DocumentMetadataResponseInfo - - // The name of the change template. - Name *string - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListDocumentMetadataHistoryMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListDocumentMetadataHistory{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListDocumentMetadataHistory{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListDocumentMetadataHistory"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListDocumentMetadataHistoryValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListDocumentMetadataHistory(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opListDocumentMetadataHistory(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListDocumentMetadataHistory", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListDocumentVersions.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListDocumentVersions.go deleted file mode 100644 index 72afe4fc..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListDocumentVersions.go +++ /dev/null @@ -1,241 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// List all versions for a document. -func (c *Client) ListDocumentVersions(ctx context.Context, params *ListDocumentVersionsInput, optFns ...func(*Options)) (*ListDocumentVersionsOutput, error) { - if params == nil { - params = &ListDocumentVersionsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListDocumentVersions", params, optFns, c.addOperationListDocumentVersionsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListDocumentVersionsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListDocumentVersionsInput struct { - - // The name of the document. You can specify an Amazon Resource Name (ARN). - // - // This member is required. - Name *string - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type ListDocumentVersionsOutput struct { - - // The document versions. - DocumentVersions []types.DocumentVersionInfo - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListDocumentVersionsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListDocumentVersions{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListDocumentVersions{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListDocumentVersions"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListDocumentVersionsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListDocumentVersions(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListDocumentVersionsAPIClient is a client that implements the -// ListDocumentVersions operation. -type ListDocumentVersionsAPIClient interface { - ListDocumentVersions(context.Context, *ListDocumentVersionsInput, ...func(*Options)) (*ListDocumentVersionsOutput, error) -} - -var _ ListDocumentVersionsAPIClient = (*Client)(nil) - -// ListDocumentVersionsPaginatorOptions is the paginator options for -// ListDocumentVersions -type ListDocumentVersionsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// ListDocumentVersionsPaginator is a paginator for ListDocumentVersions -type ListDocumentVersionsPaginator struct { - options ListDocumentVersionsPaginatorOptions - client ListDocumentVersionsAPIClient - params *ListDocumentVersionsInput - nextToken *string - firstPage bool -} - -// NewListDocumentVersionsPaginator returns a new ListDocumentVersionsPaginator -func NewListDocumentVersionsPaginator(client ListDocumentVersionsAPIClient, params *ListDocumentVersionsInput, optFns ...func(*ListDocumentVersionsPaginatorOptions)) *ListDocumentVersionsPaginator { - if params == nil { - params = &ListDocumentVersionsInput{} - } - - options := ListDocumentVersionsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListDocumentVersionsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListDocumentVersionsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListDocumentVersions page. -func (p *ListDocumentVersionsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListDocumentVersionsOutput, 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 - - result, err := p.client.ListDocumentVersions(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 -} - -func newServiceMetadataMiddleware_opListDocumentVersions(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListDocumentVersions", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListDocuments.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListDocuments.go deleted file mode 100644 index 0d137fe6..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListDocuments.go +++ /dev/null @@ -1,249 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns all Systems Manager (SSM) documents in the current Amazon Web Services -// account and Amazon Web Services Region. You can limit the results of this -// request by using a filter. -func (c *Client) ListDocuments(ctx context.Context, params *ListDocumentsInput, optFns ...func(*Options)) (*ListDocumentsOutput, error) { - if params == nil { - params = &ListDocumentsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListDocuments", params, optFns, c.addOperationListDocumentsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListDocumentsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListDocumentsInput struct { - - // This data type is deprecated. Instead, use Filters . - DocumentFilterList []types.DocumentFilter - - // One or more DocumentKeyValuesFilter objects. Use a filter to return a more - // specific list of results. For keys, you can specify one or more key-value pair - // tags that have been applied to a document. Other valid keys include Owner , Name - // , PlatformTypes , DocumentType , and TargetType . For example, to return - // documents you own use Key=Owner,Values=Self . To specify a custom key-value - // pair, use the format Key=tag:tagName,Values=valueName . This API operation only - // supports filtering documents by using a single tag key and one or more tag - // values. For example: Key=tag:tagName,Values=valueName1,valueName2 - Filters []types.DocumentKeyValuesFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type ListDocumentsOutput struct { - - // The names of the SSM documents. - DocumentIdentifiers []types.DocumentIdentifier - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListDocumentsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListDocuments{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListDocuments{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListDocuments"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListDocumentsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListDocuments(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListDocumentsAPIClient is a client that implements the ListDocuments operation. -type ListDocumentsAPIClient interface { - ListDocuments(context.Context, *ListDocumentsInput, ...func(*Options)) (*ListDocumentsOutput, error) -} - -var _ ListDocumentsAPIClient = (*Client)(nil) - -// ListDocumentsPaginatorOptions is the paginator options for ListDocuments -type ListDocumentsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// ListDocumentsPaginator is a paginator for ListDocuments -type ListDocumentsPaginator struct { - options ListDocumentsPaginatorOptions - client ListDocumentsAPIClient - params *ListDocumentsInput - nextToken *string - firstPage bool -} - -// NewListDocumentsPaginator returns a new ListDocumentsPaginator -func NewListDocumentsPaginator(client ListDocumentsAPIClient, params *ListDocumentsInput, optFns ...func(*ListDocumentsPaginatorOptions)) *ListDocumentsPaginator { - if params == nil { - params = &ListDocumentsInput{} - } - - options := ListDocumentsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListDocumentsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListDocumentsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListDocuments page. -func (p *ListDocumentsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListDocumentsOutput, 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 - - result, err := p.client.ListDocuments(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 -} - -func newServiceMetadataMiddleware_opListDocuments(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListDocuments", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListInventoryEntries.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListInventoryEntries.go deleted file mode 100644 index 8589e481..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListInventoryEntries.go +++ /dev/null @@ -1,169 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// A list of inventory items returned by the request. -func (c *Client) ListInventoryEntries(ctx context.Context, params *ListInventoryEntriesInput, optFns ...func(*Options)) (*ListInventoryEntriesOutput, error) { - if params == nil { - params = &ListInventoryEntriesInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListInventoryEntries", params, optFns, c.addOperationListInventoryEntriesMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListInventoryEntriesOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListInventoryEntriesInput struct { - - // The managed node ID for which you want inventory information. - // - // This member is required. - InstanceId *string - - // The type of inventory item for which you want information. - // - // This member is required. - TypeName *string - - // One or more filters. Use a filter to return a more specific list of results. - Filters []types.InventoryFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - noSmithyDocumentSerde -} - -type ListInventoryEntriesOutput struct { - - // The time that inventory information was collected for the managed node(s). - CaptureTime *string - - // A list of inventory items on the managed node(s). - Entries []map[string]string - - // The managed node ID targeted by the request to query inventory information. - InstanceId *string - - // The token to use when requesting the next set of items. If there are no - // additional items to return, the string is empty. - NextToken *string - - // The inventory schema version used by the managed node(s). - SchemaVersion *string - - // The type of inventory item returned by the request. - TypeName *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListInventoryEntriesMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListInventoryEntries{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListInventoryEntries{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListInventoryEntries"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListInventoryEntriesValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListInventoryEntries(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opListInventoryEntries(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListInventoryEntries", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListOpsItemEvents.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListOpsItemEvents.go deleted file mode 100644 index ee55b62b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListOpsItemEvents.go +++ /dev/null @@ -1,240 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a list of all OpsItem events in the current Amazon Web Services Region -// and Amazon Web Services account. You can limit the results to events associated -// with specific OpsItems by specifying a filter. -func (c *Client) ListOpsItemEvents(ctx context.Context, params *ListOpsItemEventsInput, optFns ...func(*Options)) (*ListOpsItemEventsOutput, error) { - if params == nil { - params = &ListOpsItemEventsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListOpsItemEvents", params, optFns, c.addOperationListOpsItemEventsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListOpsItemEventsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListOpsItemEventsInput struct { - - // One or more OpsItem filters. Use a filter to return a more specific list of - // results. - Filters []types.OpsItemEventFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - noSmithyDocumentSerde -} - -type ListOpsItemEventsOutput struct { - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // A list of event information for the specified OpsItems. - Summaries []types.OpsItemEventSummary - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListOpsItemEventsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListOpsItemEvents{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListOpsItemEvents{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListOpsItemEvents"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListOpsItemEventsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListOpsItemEvents(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListOpsItemEventsAPIClient is a client that implements the ListOpsItemEvents -// operation. -type ListOpsItemEventsAPIClient interface { - ListOpsItemEvents(context.Context, *ListOpsItemEventsInput, ...func(*Options)) (*ListOpsItemEventsOutput, error) -} - -var _ ListOpsItemEventsAPIClient = (*Client)(nil) - -// ListOpsItemEventsPaginatorOptions is the paginator options for ListOpsItemEvents -type ListOpsItemEventsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// ListOpsItemEventsPaginator is a paginator for ListOpsItemEvents -type ListOpsItemEventsPaginator struct { - options ListOpsItemEventsPaginatorOptions - client ListOpsItemEventsAPIClient - params *ListOpsItemEventsInput - nextToken *string - firstPage bool -} - -// NewListOpsItemEventsPaginator returns a new ListOpsItemEventsPaginator -func NewListOpsItemEventsPaginator(client ListOpsItemEventsAPIClient, params *ListOpsItemEventsInput, optFns ...func(*ListOpsItemEventsPaginatorOptions)) *ListOpsItemEventsPaginator { - if params == nil { - params = &ListOpsItemEventsInput{} - } - - options := ListOpsItemEventsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListOpsItemEventsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListOpsItemEventsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListOpsItemEvents page. -func (p *ListOpsItemEventsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListOpsItemEventsOutput, 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 - - result, err := p.client.ListOpsItemEvents(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 -} - -func newServiceMetadataMiddleware_opListOpsItemEvents(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListOpsItemEvents", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListOpsItemRelatedItems.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListOpsItemRelatedItems.go deleted file mode 100644 index 4c3819ee..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListOpsItemRelatedItems.go +++ /dev/null @@ -1,245 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists all related-item resources associated with a Systems Manager OpsCenter -// OpsItem. OpsCenter is a capability of Amazon Web Services Systems Manager. -func (c *Client) ListOpsItemRelatedItems(ctx context.Context, params *ListOpsItemRelatedItemsInput, optFns ...func(*Options)) (*ListOpsItemRelatedItemsOutput, error) { - if params == nil { - params = &ListOpsItemRelatedItemsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListOpsItemRelatedItems", params, optFns, c.addOperationListOpsItemRelatedItemsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListOpsItemRelatedItemsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListOpsItemRelatedItemsInput struct { - - // One or more OpsItem filters. Use a filter to return a more specific list of - // results. - Filters []types.OpsItemRelatedItemsFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // The token for the next set of items to return. (You received this token from a - // previous call.) - NextToken *string - - // The ID of the OpsItem for which you want to list all related-item resources. - OpsItemId *string - - noSmithyDocumentSerde -} - -type ListOpsItemRelatedItemsOutput struct { - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // A list of related-item resources for the specified OpsItem. - Summaries []types.OpsItemRelatedItemSummary - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListOpsItemRelatedItemsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListOpsItemRelatedItems{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListOpsItemRelatedItems{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListOpsItemRelatedItems"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListOpsItemRelatedItemsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListOpsItemRelatedItems(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListOpsItemRelatedItemsAPIClient is a client that implements the -// ListOpsItemRelatedItems operation. -type ListOpsItemRelatedItemsAPIClient interface { - ListOpsItemRelatedItems(context.Context, *ListOpsItemRelatedItemsInput, ...func(*Options)) (*ListOpsItemRelatedItemsOutput, error) -} - -var _ ListOpsItemRelatedItemsAPIClient = (*Client)(nil) - -// ListOpsItemRelatedItemsPaginatorOptions is the paginator options for -// ListOpsItemRelatedItems -type ListOpsItemRelatedItemsPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// ListOpsItemRelatedItemsPaginator is a paginator for ListOpsItemRelatedItems -type ListOpsItemRelatedItemsPaginator struct { - options ListOpsItemRelatedItemsPaginatorOptions - client ListOpsItemRelatedItemsAPIClient - params *ListOpsItemRelatedItemsInput - nextToken *string - firstPage bool -} - -// NewListOpsItemRelatedItemsPaginator returns a new -// ListOpsItemRelatedItemsPaginator -func NewListOpsItemRelatedItemsPaginator(client ListOpsItemRelatedItemsAPIClient, params *ListOpsItemRelatedItemsInput, optFns ...func(*ListOpsItemRelatedItemsPaginatorOptions)) *ListOpsItemRelatedItemsPaginator { - if params == nil { - params = &ListOpsItemRelatedItemsInput{} - } - - options := ListOpsItemRelatedItemsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListOpsItemRelatedItemsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListOpsItemRelatedItemsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListOpsItemRelatedItems page. -func (p *ListOpsItemRelatedItemsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListOpsItemRelatedItemsOutput, 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 - - result, err := p.client.ListOpsItemRelatedItems(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 -} - -func newServiceMetadataMiddleware_opListOpsItemRelatedItems(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListOpsItemRelatedItems", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListOpsMetadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListOpsMetadata.go deleted file mode 100644 index 944fba37..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListOpsMetadata.go +++ /dev/null @@ -1,239 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Amazon Web Services Systems Manager calls this API operation when displaying -// all Application Manager OpsMetadata objects or blobs. -func (c *Client) ListOpsMetadata(ctx context.Context, params *ListOpsMetadataInput, optFns ...func(*Options)) (*ListOpsMetadataOutput, error) { - if params == nil { - params = &ListOpsMetadataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListOpsMetadata", params, optFns, c.addOperationListOpsMetadataMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListOpsMetadataOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListOpsMetadataInput struct { - - // One or more filters to limit the number of OpsMetadata objects returned by the - // call. - Filters []types.OpsMetadataFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - noSmithyDocumentSerde -} - -type ListOpsMetadataOutput struct { - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // Returns a list of OpsMetadata objects. - OpsMetadataList []types.OpsMetadata - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListOpsMetadataMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListOpsMetadata{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListOpsMetadata{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListOpsMetadata"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListOpsMetadataValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListOpsMetadata(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListOpsMetadataAPIClient is a client that implements the ListOpsMetadata -// operation. -type ListOpsMetadataAPIClient interface { - ListOpsMetadata(context.Context, *ListOpsMetadataInput, ...func(*Options)) (*ListOpsMetadataOutput, error) -} - -var _ ListOpsMetadataAPIClient = (*Client)(nil) - -// ListOpsMetadataPaginatorOptions is the paginator options for ListOpsMetadata -type ListOpsMetadataPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// ListOpsMetadataPaginator is a paginator for ListOpsMetadata -type ListOpsMetadataPaginator struct { - options ListOpsMetadataPaginatorOptions - client ListOpsMetadataAPIClient - params *ListOpsMetadataInput - nextToken *string - firstPage bool -} - -// NewListOpsMetadataPaginator returns a new ListOpsMetadataPaginator -func NewListOpsMetadataPaginator(client ListOpsMetadataAPIClient, params *ListOpsMetadataInput, optFns ...func(*ListOpsMetadataPaginatorOptions)) *ListOpsMetadataPaginator { - if params == nil { - params = &ListOpsMetadataInput{} - } - - options := ListOpsMetadataPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListOpsMetadataPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListOpsMetadataPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListOpsMetadata page. -func (p *ListOpsMetadataPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListOpsMetadataOutput, 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 - - result, err := p.client.ListOpsMetadata(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 -} - -func newServiceMetadataMiddleware_opListOpsMetadata(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListOpsMetadata", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListResourceComplianceSummaries.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListResourceComplianceSummaries.go deleted file mode 100644 index 7bae0aa3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListResourceComplianceSummaries.go +++ /dev/null @@ -1,241 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a resource-level summary count. The summary includes information about -// compliant and non-compliant statuses and detailed compliance-item severity -// counts, according to the filter criteria you specify. -func (c *Client) ListResourceComplianceSummaries(ctx context.Context, params *ListResourceComplianceSummariesInput, optFns ...func(*Options)) (*ListResourceComplianceSummariesOutput, error) { - if params == nil { - params = &ListResourceComplianceSummariesInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListResourceComplianceSummaries", params, optFns, c.addOperationListResourceComplianceSummariesMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListResourceComplianceSummariesOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListResourceComplianceSummariesInput struct { - - // One or more filters. Use a filter to return a more specific list of results. - Filters []types.ComplianceStringFilter - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - noSmithyDocumentSerde -} - -type ListResourceComplianceSummariesOutput struct { - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // A summary count for specified or targeted managed nodes. Summary count includes - // information about compliant and non-compliant State Manager associations, patch - // status, or custom items according to the filter criteria that you specify. - ResourceComplianceSummaryItems []types.ResourceComplianceSummaryItem - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListResourceComplianceSummariesMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListResourceComplianceSummaries{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListResourceComplianceSummaries{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListResourceComplianceSummaries"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opListResourceComplianceSummaries(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListResourceComplianceSummariesAPIClient is a client that implements the -// ListResourceComplianceSummaries operation. -type ListResourceComplianceSummariesAPIClient interface { - ListResourceComplianceSummaries(context.Context, *ListResourceComplianceSummariesInput, ...func(*Options)) (*ListResourceComplianceSummariesOutput, error) -} - -var _ ListResourceComplianceSummariesAPIClient = (*Client)(nil) - -// ListResourceComplianceSummariesPaginatorOptions is the paginator options for -// ListResourceComplianceSummaries -type ListResourceComplianceSummariesPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// ListResourceComplianceSummariesPaginator is a paginator for -// ListResourceComplianceSummaries -type ListResourceComplianceSummariesPaginator struct { - options ListResourceComplianceSummariesPaginatorOptions - client ListResourceComplianceSummariesAPIClient - params *ListResourceComplianceSummariesInput - nextToken *string - firstPage bool -} - -// NewListResourceComplianceSummariesPaginator returns a new -// ListResourceComplianceSummariesPaginator -func NewListResourceComplianceSummariesPaginator(client ListResourceComplianceSummariesAPIClient, params *ListResourceComplianceSummariesInput, optFns ...func(*ListResourceComplianceSummariesPaginatorOptions)) *ListResourceComplianceSummariesPaginator { - if params == nil { - params = &ListResourceComplianceSummariesInput{} - } - - options := ListResourceComplianceSummariesPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListResourceComplianceSummariesPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListResourceComplianceSummariesPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListResourceComplianceSummaries page. -func (p *ListResourceComplianceSummariesPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListResourceComplianceSummariesOutput, 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 - - result, err := p.client.ListResourceComplianceSummaries(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 -} - -func newServiceMetadataMiddleware_opListResourceComplianceSummaries(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListResourceComplianceSummaries", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListResourceDataSync.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListResourceDataSync.go deleted file mode 100644 index 20091011..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListResourceDataSync.go +++ /dev/null @@ -1,246 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists your resource data sync configurations. Includes information about the -// last time a sync attempted to start, the last sync status, and the last time a -// sync successfully completed. The number of sync configurations might be too -// large to return using a single call to ListResourceDataSync . You can limit the -// number of sync configurations returned by using the MaxResults parameter. To -// determine whether there are more sync configurations to list, check the value of -// NextToken in the output. If there are more sync configurations to list, you can -// request them by specifying the NextToken returned in the call to the parameter -// of a subsequent call. -func (c *Client) ListResourceDataSync(ctx context.Context, params *ListResourceDataSyncInput, optFns ...func(*Options)) (*ListResourceDataSyncOutput, error) { - if params == nil { - params = &ListResourceDataSyncInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListResourceDataSync", params, optFns, c.addOperationListResourceDataSyncMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListResourceDataSyncOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListResourceDataSyncInput struct { - - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - MaxResults *int32 - - // A token to start the list. Use this token to get the next set of results. - NextToken *string - - // View a list of resource data syncs according to the sync type. Specify - // SyncToDestination to view resource data syncs that synchronize data to an Amazon - // S3 bucket. Specify SyncFromSource to view resource data syncs from - // Organizations or from multiple Amazon Web Services Regions. - SyncType *string - - noSmithyDocumentSerde -} - -type ListResourceDataSyncOutput struct { - - // The token for the next set of items to return. Use this token to get the next - // set of results. - NextToken *string - - // A list of your current resource data sync configurations and their statuses. - ResourceDataSyncItems []types.ResourceDataSyncItem - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListResourceDataSyncMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpListResourceDataSync{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListResourceDataSync{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListResourceDataSync"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opListResourceDataSync(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListResourceDataSyncAPIClient is a client that implements the -// ListResourceDataSync operation. -type ListResourceDataSyncAPIClient interface { - ListResourceDataSync(context.Context, *ListResourceDataSyncInput, ...func(*Options)) (*ListResourceDataSyncOutput, error) -} - -var _ ListResourceDataSyncAPIClient = (*Client)(nil) - -// ListResourceDataSyncPaginatorOptions is the paginator options for -// ListResourceDataSync -type ListResourceDataSyncPaginatorOptions struct { - // The maximum number of items to return for this call. The call also returns a - // token that you can specify in a subsequent call to get the next set of results. - 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 -} - -// ListResourceDataSyncPaginator is a paginator for ListResourceDataSync -type ListResourceDataSyncPaginator struct { - options ListResourceDataSyncPaginatorOptions - client ListResourceDataSyncAPIClient - params *ListResourceDataSyncInput - nextToken *string - firstPage bool -} - -// NewListResourceDataSyncPaginator returns a new ListResourceDataSyncPaginator -func NewListResourceDataSyncPaginator(client ListResourceDataSyncAPIClient, params *ListResourceDataSyncInput, optFns ...func(*ListResourceDataSyncPaginatorOptions)) *ListResourceDataSyncPaginator { - if params == nil { - params = &ListResourceDataSyncInput{} - } - - options := ListResourceDataSyncPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListResourceDataSyncPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListResourceDataSyncPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListResourceDataSync page. -func (p *ListResourceDataSyncPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListResourceDataSyncOutput, 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 - - result, err := p.client.ListResourceDataSync(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 -} - -func newServiceMetadataMiddleware_opListResourceDataSync(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListResourceDataSync", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListTagsForResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListTagsForResource.go deleted file mode 100644 index 06e7a524..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ListTagsForResource.go +++ /dev/null @@ -1,143 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a list of the tags assigned to the specified resource. For information -// about the ID format for each supported resource type, see AddTagsToResource . -func (c *Client) ListTagsForResource(ctx context.Context, params *ListTagsForResourceInput, optFns ...func(*Options)) (*ListTagsForResourceOutput, error) { - if params == nil { - params = &ListTagsForResourceInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListTagsForResource", params, optFns, c.addOperationListTagsForResourceMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListTagsForResourceOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListTagsForResourceInput struct { - - // The resource ID for which you want to see a list of tags. - // - // This member is required. - ResourceId *string - - // Returns a list of tags for a specific resource type. - // - // This member is required. - ResourceType types.ResourceTypeForTagging - - noSmithyDocumentSerde -} - -type ListTagsForResourceOutput struct { - - // A list of tags. - TagList []types.Tag - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -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 - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpListTagsForResource{}, middleware.After) - 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListTagsForResourceValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListTagsForResource(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opListTagsForResource(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListTagsForResource", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ModifyDocumentPermission.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ModifyDocumentPermission.go deleted file mode 100644 index cf28685c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ModifyDocumentPermission.go +++ /dev/null @@ -1,155 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Shares a Amazon Web Services Systems Manager document (SSM document)publicly or -// privately. If you share a document privately, you must specify the Amazon Web -// Services user IDs for those people who can use the document. If you share a -// document publicly, you must specify All as the account ID. -func (c *Client) ModifyDocumentPermission(ctx context.Context, params *ModifyDocumentPermissionInput, optFns ...func(*Options)) (*ModifyDocumentPermissionOutput, error) { - if params == nil { - params = &ModifyDocumentPermissionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ModifyDocumentPermission", params, optFns, c.addOperationModifyDocumentPermissionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ModifyDocumentPermissionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ModifyDocumentPermissionInput struct { - - // The name of the document that you want to share. - // - // This member is required. - Name *string - - // The permission type for the document. The permission type can be Share. - // - // This member is required. - PermissionType types.DocumentPermissionType - - // The Amazon Web Services users that should have access to the document. The - // account IDs can either be a group of account IDs or All. - AccountIdsToAdd []string - - // The Amazon Web Services users that should no longer have access to the - // document. The Amazon Web Services user can either be a group of account IDs or - // All. This action has a higher priority than AccountIdsToAdd. If you specify an - // ID to add and the same ID to remove, the system removes access to the document. - AccountIdsToRemove []string - - // (Optional) The version of the document to share. If it isn't specified, the - // system choose the Default version to share. - SharedDocumentVersion *string - - noSmithyDocumentSerde -} - -type ModifyDocumentPermissionOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationModifyDocumentPermissionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpModifyDocumentPermission{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpModifyDocumentPermission{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ModifyDocumentPermission"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpModifyDocumentPermissionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opModifyDocumentPermission(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opModifyDocumentPermission(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ModifyDocumentPermission", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutComplianceItems.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutComplianceItems.go deleted file mode 100644 index 74324928..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutComplianceItems.go +++ /dev/null @@ -1,197 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Registers a compliance type and other compliance details on a designated -// resource. This operation lets you register custom compliance details with a -// resource. This call overwrites existing compliance information on the resource, -// so you must provide a full list of compliance items each time that you send the -// request. ComplianceType can be one of the following: -// - ExecutionId: The execution ID when the patch, association, or custom -// compliance item was applied. -// - ExecutionType: Specify patch, association, or Custom: string . -// - ExecutionTime. The time the patch, association, or custom compliance item -// was applied to the managed node. -// - Id: The patch, association, or custom compliance ID. -// - Title: A title. -// - Status: The status of the compliance item. For example, approved for -// patches, or Failed for associations. -// - Severity: A patch severity. For example, Critical . -// - DocumentName: An SSM document name. For example, AWS-RunPatchBaseline . -// - DocumentVersion: An SSM document version number. For example, 4. -// - Classification: A patch classification. For example, security updates . -// - PatchBaselineId: A patch baseline ID. -// - PatchSeverity: A patch severity. For example, Critical . -// - PatchState: A patch state. For example, InstancesWithFailedPatches . -// - PatchGroup: The name of a patch group. -// - InstalledTime: The time the association, patch, or custom compliance item -// was applied to the resource. Specify the time by using the following format: -// yyyy-MM-dd'T'HH:mm:ss'Z' -func (c *Client) PutComplianceItems(ctx context.Context, params *PutComplianceItemsInput, optFns ...func(*Options)) (*PutComplianceItemsOutput, error) { - if params == nil { - params = &PutComplianceItemsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "PutComplianceItems", params, optFns, c.addOperationPutComplianceItemsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*PutComplianceItemsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type PutComplianceItemsInput struct { - - // Specify the compliance type. For example, specify Association (for a State - // Manager association), Patch, or Custom: string . - // - // This member is required. - ComplianceType *string - - // A summary of the call execution that includes an execution ID, the type of - // execution (for example, Command ), and the date/time of the execution using a - // datetime object that is saved in the following format: yyyy-MM-dd'T'HH:mm:ss'Z'. - // - // This member is required. - ExecutionSummary *types.ComplianceExecutionSummary - - // Information about the compliance as defined by the resource type. For example, - // for a patch compliance type, Items includes information about the - // PatchSeverity, Classification, and so on. - // - // This member is required. - Items []types.ComplianceItemEntry - - // Specify an ID for this resource. For a managed node, this is the node ID. - // - // This member is required. - ResourceId *string - - // Specify the type of resource. ManagedInstance is currently the only supported - // resource type. - // - // This member is required. - ResourceType *string - - // MD5 or SHA-256 content hash. The content hash is used to determine if existing - // information should be overwritten or ignored. If the content hashes match, the - // request to put compliance information is ignored. - ItemContentHash *string - - // The mode for uploading compliance items. You can specify COMPLETE or PARTIAL . - // In COMPLETE mode, the system overwrites all existing compliance information for - // the resource. You must provide a full list of compliance items each time you - // send the request. In PARTIAL mode, the system overwrites compliance information - // for a specific association. The association must be configured with - // SyncCompliance set to MANUAL . By default, all requests use COMPLETE mode. This - // attribute is only valid for association compliance. - UploadType types.ComplianceUploadType - - noSmithyDocumentSerde -} - -type PutComplianceItemsOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationPutComplianceItemsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutComplianceItems{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpPutComplianceItems{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "PutComplianceItems"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpPutComplianceItemsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutComplianceItems(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opPutComplianceItems(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "PutComplianceItems", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutInventory.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutInventory.go deleted file mode 100644 index b4ef83b7..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutInventory.go +++ /dev/null @@ -1,144 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Bulk update custom inventory items on one or more managed nodes. The request -// adds an inventory item, if it doesn't already exist, or updates an inventory -// item, if it does exist. -func (c *Client) PutInventory(ctx context.Context, params *PutInventoryInput, optFns ...func(*Options)) (*PutInventoryOutput, error) { - if params == nil { - params = &PutInventoryInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "PutInventory", params, optFns, c.addOperationPutInventoryMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*PutInventoryOutput) - out.ResultMetadata = metadata - return out, nil -} - -type PutInventoryInput struct { - - // An managed node ID where you want to add or update inventory items. - // - // This member is required. - InstanceId *string - - // The inventory items that you want to add or update on managed nodes. - // - // This member is required. - Items []types.InventoryItem - - noSmithyDocumentSerde -} - -type PutInventoryOutput struct { - - // Information about the request. - Message *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationPutInventoryMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutInventory{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpPutInventory{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "PutInventory"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpPutInventoryValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutInventory(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opPutInventory(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "PutInventory", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutParameter.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutParameter.go deleted file mode 100644 index e56044b4..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutParameter.go +++ /dev/null @@ -1,308 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Add a parameter to the system. -func (c *Client) PutParameter(ctx context.Context, params *PutParameterInput, optFns ...func(*Options)) (*PutParameterOutput, error) { - if params == nil { - params = &PutParameterInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "PutParameter", params, optFns, c.addOperationPutParameterMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*PutParameterOutput) - out.ResultMetadata = metadata - return out, nil -} - -type PutParameterInput struct { - - // The fully qualified name of the parameter that you want to add to the system. - // The fully qualified name includes the complete hierarchy of the parameter path - // and name. For parameters in a hierarchy, you must include a leading forward - // slash character (/) when you create or reference a parameter. For example: - // /Dev/DBServer/MySQL/db-string13 Naming Constraints: - // - Parameter names are case sensitive. - // - A parameter name must be unique within an Amazon Web Services Region - // - A parameter name can't be prefixed with " aws " or " ssm " - // (case-insensitive). - // - Parameter names can include only the following symbols and letters: - // a-zA-Z0-9_.- In addition, the slash character ( / ) is used to delineate - // hierarchies in parameter names. For example: - // /Dev/Production/East/Project-ABC/MyParameter - // - A parameter name can't include spaces. - // - Parameter hierarchies are limited to a maximum depth of fifteen levels. - // For additional information about valid values for parameter names, see Creating - // Systems Manager parameters (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-su-create.html) - // in the Amazon Web Services Systems Manager User Guide. The maximum length - // constraint of 2048 characters listed below includes 1037 characters reserved for - // internal use by Systems Manager. The maximum length for a parameter name that - // you create is 1011 characters. This includes the characters in the ARN that - // precede the name you specify, such as - // arn:aws:ssm:us-east-2:111122223333:parameter/ . - // - // This member is required. - Name *string - - // The parameter value that you want to add to the system. Standard parameters - // have a value limit of 4 KB. Advanced parameters have a value limit of 8 KB. - // Parameters can't be referenced or nested in the values of other parameters. You - // can't include {{}} or {{ssm:parameter-name}} in a parameter value. - // - // This member is required. - Value *string - - // A regular expression used to validate the parameter value. For example, for - // String types with values restricted to numbers, you can specify the following: - // AllowedPattern=^\d+$ - AllowedPattern *string - - // The data type for a String parameter. Supported data types include plain text - // and Amazon Machine Image (AMI) IDs. The following data type values are - // supported. - // - text - // - aws:ec2:image - // - aws:ssm:integration - // When you create a String parameter and specify aws:ec2:image , Amazon Web - // Services Systems Manager validates the parameter value is in the required - // format, such as ami-12345abcdeEXAMPLE , and that the specified AMI is available - // in your Amazon Web Services account. If the action is successful, the service - // sends back an HTTP 200 response which indicates a successful PutParameter call - // for all cases except for data type aws:ec2:image . If you call PutParameter - // with aws:ec2:image data type, a successful HTTP 200 response does not guarantee - // that your parameter was successfully created or updated. The aws:ec2:image - // value is validated asynchronously, and the PutParameter call returns before the - // validation is complete. If you submit an invalid AMI value, the PutParameter - // operation will return success, but the asynchronous validation will fail and the - // parameter will not be created or updated. To monitor whether your aws:ec2:image - // parameters are created successfully, see Setting up notifications or trigger - // actions based on Parameter Store events (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-cwe.html) - // . For more information about AMI format validation , see Native parameter - // support for Amazon Machine Image (AMI) IDs (https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-ec2-aliases.html) - // . - DataType *string - - // Information about the parameter that you want to add to the system. Optional - // but recommended. Don't enter personally identifiable information in this field. - Description *string - - // The Key Management Service (KMS) ID that you want to use to encrypt a - // parameter. Use a custom key for better security. Required for parameters that - // use the SecureString data type. If you don't specify a key ID, the system uses - // the default key associated with your Amazon Web Services account which is not as - // secure as using a custom key. - // - To use a custom KMS key, choose the SecureString data type with the Key ID - // parameter. - KeyId *string - - // Overwrite an existing parameter. The default value is false . - Overwrite *bool - - // One or more policies to apply to a parameter. This operation takes a JSON - // array. Parameter Store, a capability of Amazon Web Services Systems Manager - // supports the following policy types: Expiration: This policy deletes the - // parameter after it expires. When you create the policy, you specify the - // expiration date. You can update the expiration date and time by updating the - // policy. Updating the parameter doesn't affect the expiration date and time. When - // the expiration time is reached, Parameter Store deletes the parameter. - // ExpirationNotification: This policy initiates an event in Amazon CloudWatch - // Events that notifies you about the expiration. By using this policy, you can - // receive notification before or after the expiration time is reached, in units of - // days or hours. NoChangeNotification: This policy initiates a CloudWatch Events - // event if a parameter hasn't been modified for a specified period of time. This - // policy type is useful when, for example, a secret needs to be changed within a - // period of time, but it hasn't been changed. All existing policies are preserved - // until you send new policies or an empty policy. For more information about - // parameter policies, see Assigning parameter policies (https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html) - // . - Policies *string - - // Optional metadata that you assign to a resource. Tags enable you to categorize - // a resource in different ways, such as by purpose, owner, or environment. For - // example, you might want to tag a Systems Manager parameter to identify the type - // of resource to which it applies, the environment, or the type of configuration - // data referenced by the parameter. In this case, you could specify the following - // key-value pairs: - // - Key=Resource,Value=S3bucket - // - Key=OS,Value=Windows - // - Key=ParameterType,Value=LicenseKey - // To add tags to an existing Systems Manager parameter, use the AddTagsToResource - // operation. - Tags []types.Tag - - // The parameter tier to assign to a parameter. Parameter Store offers a standard - // tier and an advanced tier for parameters. Standard parameters have a content - // size limit of 4 KB and can't be configured to use parameter policies. You can - // create a maximum of 10,000 standard parameters for each Region in an Amazon Web - // Services account. Standard parameters are offered at no additional cost. - // Advanced parameters have a content size limit of 8 KB and can be configured to - // use parameter policies. You can create a maximum of 100,000 advanced parameters - // for each Region in an Amazon Web Services account. Advanced parameters incur a - // charge. For more information, see Standard and advanced parameter tiers (https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) - // in the Amazon Web Services Systems Manager User Guide. You can change a standard - // parameter to an advanced parameter any time. But you can't revert an advanced - // parameter to a standard parameter. Reverting an advanced parameter to a standard - // parameter would result in data loss because the system would truncate the size - // of the parameter from 8 KB to 4 KB. Reverting would also remove any policies - // attached to the parameter. Lastly, advanced parameters use a different form of - // encryption than standard parameters. If you no longer need an advanced - // parameter, or if you no longer want to incur charges for an advanced parameter, - // you must delete it and recreate it as a new standard parameter. Using the - // Default Tier Configuration In PutParameter requests, you can specify the tier - // to create the parameter in. Whenever you specify a tier in the request, - // Parameter Store creates or updates the parameter according to that request. - // However, if you don't specify a tier in a request, Parameter Store assigns the - // tier based on the current Parameter Store default tier configuration. The - // default tier when you begin using Parameter Store is the standard-parameter - // tier. If you use the advanced-parameter tier, you can specify one of the - // following as the default: - // - Advanced: With this option, Parameter Store evaluates all requests as - // advanced parameters. - // - Intelligent-Tiering: With this option, Parameter Store evaluates each - // request to determine if the parameter is standard or advanced. If the request - // doesn't include any options that require an advanced parameter, the parameter is - // created in the standard-parameter tier. If one or more options requiring an - // advanced parameter are included in the request, Parameter Store create a - // parameter in the advanced-parameter tier. This approach helps control your - // parameter-related costs by always creating standard parameters unless an - // advanced parameter is necessary. - // Options that require an advanced parameter include the following: - // - The content size of the parameter is more than 4 KB. - // - The parameter uses a parameter policy. - // - More than 10,000 parameters already exist in your Amazon Web Services - // account in the current Amazon Web Services Region. - // For more information about configuring the default tier option, see Specifying - // a default parameter tier (https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-default-tier.html) - // in the Amazon Web Services Systems Manager User Guide. - Tier types.ParameterTier - - // The type of parameter that you want to add to the system. SecureString isn't - // currently supported for CloudFormation templates. Items in a StringList must be - // separated by a comma (,). You can't use other punctuation or special character - // to escape items in the list. If you have a parameter value that requires a - // comma, then use the String data type. Specifying a parameter type isn't - // required when updating a parameter. You must specify a parameter type when - // creating a parameter. - Type types.ParameterType - - noSmithyDocumentSerde -} - -type PutParameterOutput struct { - - // The tier assigned to the parameter. - Tier types.ParameterTier - - // The new version number of a parameter. If you edit a parameter value, Parameter - // Store automatically creates a new version and assigns this new version a unique - // ID. You can reference a parameter version ID in API operations or in Systems - // Manager documents (SSM documents). By default, if you don't specify a specific - // version, the system returns the latest parameter value when a parameter is - // called. - Version int64 - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationPutParameterMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutParameter{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpPutParameter{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "PutParameter"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpPutParameterValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutParameter(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opPutParameter(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "PutParameter", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutResourcePolicy.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutResourcePolicy.go deleted file mode 100644 index 0ca5a2ad..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_PutResourcePolicy.go +++ /dev/null @@ -1,157 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Creates or updates a Systems Manager resource policy. A resource policy helps -// you to define the IAM entity (for example, an Amazon Web Services account) that -// can manage your Systems Manager resources. Currently, OpsItemGroup is the only -// resource that supports Systems Manager resource policies. The resource policy -// for OpsItemGroup enables Amazon Web Services accounts to view and interact with -// OpsCenter operational work items (OpsItems). -func (c *Client) PutResourcePolicy(ctx context.Context, params *PutResourcePolicyInput, optFns ...func(*Options)) (*PutResourcePolicyOutput, error) { - if params == nil { - params = &PutResourcePolicyInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "PutResourcePolicy", params, optFns, c.addOperationPutResourcePolicyMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*PutResourcePolicyOutput) - out.ResultMetadata = metadata - return out, nil -} - -type PutResourcePolicyInput struct { - - // A policy you want to associate with a resource. - // - // This member is required. - Policy *string - - // Amazon Resource Name (ARN) of the resource to which you want to attach a policy. - // - // This member is required. - ResourceArn *string - - // ID of the current policy version. The hash helps to prevent a situation where - // multiple users attempt to overwrite a policy. You must provide this hash when - // updating or deleting a policy. - PolicyHash *string - - // The policy ID. - PolicyId *string - - noSmithyDocumentSerde -} - -type PutResourcePolicyOutput struct { - - // ID of the current policy version. - PolicyHash *string - - // The policy ID. To update a policy, you must specify PolicyId and PolicyHash . - PolicyId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationPutResourcePolicyMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpPutResourcePolicy{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpPutResourcePolicy{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "PutResourcePolicy"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpPutResourcePolicyValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opPutResourcePolicy(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opPutResourcePolicy(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "PutResourcePolicy", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterDefaultPatchBaseline.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterDefaultPatchBaseline.go deleted file mode 100644 index 6139a66a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterDefaultPatchBaseline.go +++ /dev/null @@ -1,141 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Defines the default patch baseline for the relevant operating system. To reset -// the Amazon Web Services-predefined patch baseline as the default, specify the -// full patch baseline Amazon Resource Name (ARN) as the baseline ID value. For -// example, for CentOS, specify -// arn:aws:ssm:us-east-2:733109147000:patchbaseline/pb-0574b43a65ea646ed instead of -// pb-0574b43a65ea646ed . -func (c *Client) RegisterDefaultPatchBaseline(ctx context.Context, params *RegisterDefaultPatchBaselineInput, optFns ...func(*Options)) (*RegisterDefaultPatchBaselineOutput, error) { - if params == nil { - params = &RegisterDefaultPatchBaselineInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "RegisterDefaultPatchBaseline", params, optFns, c.addOperationRegisterDefaultPatchBaselineMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*RegisterDefaultPatchBaselineOutput) - out.ResultMetadata = metadata - return out, nil -} - -type RegisterDefaultPatchBaselineInput struct { - - // The ID of the patch baseline that should be the default patch baseline. - // - // This member is required. - BaselineId *string - - noSmithyDocumentSerde -} - -type RegisterDefaultPatchBaselineOutput struct { - - // The ID of the default patch baseline. - BaselineId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationRegisterDefaultPatchBaselineMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpRegisterDefaultPatchBaseline{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpRegisterDefaultPatchBaseline{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "RegisterDefaultPatchBaseline"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpRegisterDefaultPatchBaselineValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRegisterDefaultPatchBaseline(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opRegisterDefaultPatchBaseline(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "RegisterDefaultPatchBaseline", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterPatchBaselineForPatchGroup.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterPatchBaselineForPatchGroup.go deleted file mode 100644 index bd808bee..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterPatchBaselineForPatchGroup.go +++ /dev/null @@ -1,144 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Registers a patch baseline for a patch group. -func (c *Client) RegisterPatchBaselineForPatchGroup(ctx context.Context, params *RegisterPatchBaselineForPatchGroupInput, optFns ...func(*Options)) (*RegisterPatchBaselineForPatchGroupOutput, error) { - if params == nil { - params = &RegisterPatchBaselineForPatchGroupInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "RegisterPatchBaselineForPatchGroup", params, optFns, c.addOperationRegisterPatchBaselineForPatchGroupMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*RegisterPatchBaselineForPatchGroupOutput) - out.ResultMetadata = metadata - return out, nil -} - -type RegisterPatchBaselineForPatchGroupInput struct { - - // The ID of the patch baseline to register with the patch group. - // - // This member is required. - BaselineId *string - - // The name of the patch group to be registered with the patch baseline. - // - // This member is required. - PatchGroup *string - - noSmithyDocumentSerde -} - -type RegisterPatchBaselineForPatchGroupOutput struct { - - // The ID of the patch baseline the patch group was registered with. - BaselineId *string - - // The name of the patch group registered with the patch baseline. - PatchGroup *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationRegisterPatchBaselineForPatchGroupMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpRegisterPatchBaselineForPatchGroup{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpRegisterPatchBaselineForPatchGroup{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "RegisterPatchBaselineForPatchGroup"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpRegisterPatchBaselineForPatchGroupValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRegisterPatchBaselineForPatchGroup(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opRegisterPatchBaselineForPatchGroup(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "RegisterPatchBaselineForPatchGroup", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterTargetWithMaintenanceWindow.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterTargetWithMaintenanceWindow.go deleted file mode 100644 index 33b680ba..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterTargetWithMaintenanceWindow.go +++ /dev/null @@ -1,213 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Registers a target with a maintenance window. -func (c *Client) RegisterTargetWithMaintenanceWindow(ctx context.Context, params *RegisterTargetWithMaintenanceWindowInput, optFns ...func(*Options)) (*RegisterTargetWithMaintenanceWindowOutput, error) { - if params == nil { - params = &RegisterTargetWithMaintenanceWindowInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "RegisterTargetWithMaintenanceWindow", params, optFns, c.addOperationRegisterTargetWithMaintenanceWindowMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*RegisterTargetWithMaintenanceWindowOutput) - out.ResultMetadata = metadata - return out, nil -} - -type RegisterTargetWithMaintenanceWindowInput struct { - - // The type of target being registered with the maintenance window. - // - // This member is required. - ResourceType types.MaintenanceWindowResourceType - - // The targets to register with the maintenance window. In other words, the - // managed nodes to run commands on when the maintenance window runs. If a single - // maintenance window task is registered with multiple targets, its task - // invocations occur sequentially and not in parallel. If your task must run on - // multiple targets at the same time, register a task for each target individually - // and assign each task the same priority level. You can specify targets using - // managed node IDs, resource group names, or tags that have been applied to - // managed nodes. Example 1: Specify managed node IDs Key=InstanceIds,Values=,, - // Example 2: Use tag key-pairs applied to managed nodes Key=tag:,Values=, Example - // 3: Use tag-keys applied to managed nodes Key=tag-key,Values=, Example 4: Use - // resource group names Key=resource-groups:Name,Values= Example 5: Use filters - // for resource group types Key=resource-groups:ResourceTypeFilters,Values=, For - // Key=resource-groups:ResourceTypeFilters , specify resource types in the - // following format - // Key=resource-groups:ResourceTypeFilters,Values=AWS::EC2::INSTANCE,AWS::EC2::VPC - // For more information about these examples formats, including the best use case - // for each one, see Examples: Register targets with a maintenance window (https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-targets-examples.html) - // in the Amazon Web Services Systems Manager User Guide. - // - // This member is required. - Targets []types.Target - - // The ID of the maintenance window the target should be registered with. - // - // This member is required. - WindowId *string - - // User-provided idempotency token. - ClientToken *string - - // An optional description for the target. - Description *string - - // An optional name for the target. - Name *string - - // User-provided value that will be included in any Amazon CloudWatch Events - // events raised while running tasks for these targets in this maintenance window. - OwnerInformation *string - - noSmithyDocumentSerde -} - -type RegisterTargetWithMaintenanceWindowOutput struct { - - // The ID of the target definition in this maintenance window. - WindowTargetId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationRegisterTargetWithMaintenanceWindowMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpRegisterTargetWithMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpRegisterTargetWithMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "RegisterTargetWithMaintenanceWindow"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addIdempotencyToken_opRegisterTargetWithMaintenanceWindowMiddleware(stack, options); err != nil { - return err - } - if err = addOpRegisterTargetWithMaintenanceWindowValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRegisterTargetWithMaintenanceWindow(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -type idempotencyToken_initializeOpRegisterTargetWithMaintenanceWindow struct { - tokenProvider IdempotencyTokenProvider -} - -func (*idempotencyToken_initializeOpRegisterTargetWithMaintenanceWindow) ID() string { - return "OperationIdempotencyTokenAutoFill" -} - -func (m *idempotencyToken_initializeOpRegisterTargetWithMaintenanceWindow) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.tokenProvider == nil { - return next.HandleInitialize(ctx, in) - } - - input, ok := in.Parameters.(*RegisterTargetWithMaintenanceWindowInput) - if !ok { - return out, metadata, fmt.Errorf("expected middleware input to be of type *RegisterTargetWithMaintenanceWindowInput ") - } - - if input.ClientToken == nil { - t, err := m.tokenProvider.GetIdempotencyToken() - if err != nil { - return out, metadata, err - } - input.ClientToken = &t - } - return next.HandleInitialize(ctx, in) -} -func addIdempotencyToken_opRegisterTargetWithMaintenanceWindowMiddleware(stack *middleware.Stack, cfg Options) error { - return stack.Initialize.Add(&idempotencyToken_initializeOpRegisterTargetWithMaintenanceWindow{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) -} - -func newServiceMetadataMiddleware_opRegisterTargetWithMaintenanceWindow(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "RegisterTargetWithMaintenanceWindow", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterTaskWithMaintenanceWindow.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterTaskWithMaintenanceWindow.go deleted file mode 100644 index 21a3cb65..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RegisterTaskWithMaintenanceWindow.go +++ /dev/null @@ -1,277 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Adds a new task to a maintenance window. -func (c *Client) RegisterTaskWithMaintenanceWindow(ctx context.Context, params *RegisterTaskWithMaintenanceWindowInput, optFns ...func(*Options)) (*RegisterTaskWithMaintenanceWindowOutput, error) { - if params == nil { - params = &RegisterTaskWithMaintenanceWindowInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "RegisterTaskWithMaintenanceWindow", params, optFns, c.addOperationRegisterTaskWithMaintenanceWindowMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*RegisterTaskWithMaintenanceWindowOutput) - out.ResultMetadata = metadata - return out, nil -} - -type RegisterTaskWithMaintenanceWindowInput struct { - - // The ARN of the task to run. - // - // This member is required. - TaskArn *string - - // The type of task being registered. - // - // This member is required. - TaskType types.MaintenanceWindowTaskType - - // The ID of the maintenance window the task should be added to. - // - // This member is required. - WindowId *string - - // The CloudWatch alarm you want to apply to your maintenance window task. - AlarmConfiguration *types.AlarmConfiguration - - // User-provided idempotency token. - ClientToken *string - - // Indicates whether tasks should continue to run after the cutoff time specified - // in the maintenance windows is reached. - // - CONTINUE_TASK : When the cutoff time is reached, any tasks that are running - // continue. The default value. - // - CANCEL_TASK : - // - For Automation, Lambda, Step Functions tasks: When the cutoff time is - // reached, any task invocations that are already running continue, but no new task - // invocations are started. - // - For Run Command tasks: When the cutoff time is reached, the system sends a - // CancelCommand operation that attempts to cancel the command associated with - // the task. However, there is no guarantee that the command will be terminated and - // the underlying process stopped. The status for tasks that are not completed - // is TIMED_OUT . - CutoffBehavior types.MaintenanceWindowTaskCutoffBehavior - - // An optional description for the task. - Description *string - - // A structure containing information about an Amazon Simple Storage Service - // (Amazon S3) bucket to write managed node-level logs to. LoggingInfo has been - // deprecated. To specify an Amazon Simple Storage Service (Amazon S3) bucket to - // contain logs, instead use the OutputS3BucketName and OutputS3KeyPrefix options - // in the TaskInvocationParameters structure. For information about how Amazon Web - // Services Systems Manager handles these options for the supported maintenance - // window task types, see MaintenanceWindowTaskInvocationParameters . - LoggingInfo *types.LoggingInfo - - // The maximum number of targets this task can be run for, in parallel. Although - // this element is listed as "Required: No", a value can be omitted only when you - // are registering or updating a targetless task (https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-targetless-tasks.html) - // You must provide a value in all other cases. For maintenance window tasks - // without a target specified, you can't supply a value for this option. Instead, - // the system inserts a placeholder value of 1 . This value doesn't affect the - // running of your task. - MaxConcurrency *string - - // The maximum number of errors allowed before this task stops being scheduled. - // Although this element is listed as "Required: No", a value can be omitted only - // when you are registering or updating a targetless task (https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-targetless-tasks.html) - // You must provide a value in all other cases. For maintenance window tasks - // without a target specified, you can't supply a value for this option. Instead, - // the system inserts a placeholder value of 1 . This value doesn't affect the - // running of your task. - MaxErrors *string - - // An optional name for the task. - Name *string - - // The priority of the task in the maintenance window, the lower the number the - // higher the priority. Tasks in a maintenance window are scheduled in priority - // order with tasks that have the same priority scheduled in parallel. - Priority *int32 - - // The Amazon Resource Name (ARN) of the IAM service role for Amazon Web Services - // Systems Manager to assume when running a maintenance window task. If you do not - // specify a service role ARN, Systems Manager uses your account's service-linked - // role. If no service-linked role for Systems Manager exists in your account, it - // is created when you run RegisterTaskWithMaintenanceWindow . For more - // information, see the following topics in the in the Amazon Web Services Systems - // Manager User Guide: - // - Using service-linked roles for Systems Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/using-service-linked-roles.html#slr-permissions) - // - Should I use a service-linked role or a custom service role to run - // maintenance window tasks? (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-maintenance-permissions.html#maintenance-window-tasks-service-role) - ServiceRoleArn *string - - // The targets (either managed nodes or maintenance window targets). One or more - // targets must be specified for maintenance window Run Command-type tasks. - // Depending on the task, targets are optional for other maintenance window task - // types (Automation, Lambda, and Step Functions). For more information about - // running tasks that don't specify targets, see Registering maintenance window - // tasks without targets (https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-targetless-tasks.html) - // in the Amazon Web Services Systems Manager User Guide. Specify managed nodes - // using the following format: Key=InstanceIds,Values=, Specify maintenance window - // targets using the following format: Key=WindowTargetIds,Values=, - Targets []types.Target - - // The parameters that the task should use during execution. Populate only the - // fields that match the task type. All other fields should be empty. - TaskInvocationParameters *types.MaintenanceWindowTaskInvocationParameters - - // The parameters that should be passed to the task when it is run. TaskParameters - // has been deprecated. To specify parameters to pass to a task when it runs, - // instead use the Parameters option in the TaskInvocationParameters structure. - // For information about how Systems Manager handles these options for the - // supported maintenance window task types, see - // MaintenanceWindowTaskInvocationParameters . - TaskParameters map[string]types.MaintenanceWindowTaskParameterValueExpression - - noSmithyDocumentSerde -} - -type RegisterTaskWithMaintenanceWindowOutput struct { - - // The ID of the task in the maintenance window. - WindowTaskId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationRegisterTaskWithMaintenanceWindowMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpRegisterTaskWithMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpRegisterTaskWithMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "RegisterTaskWithMaintenanceWindow"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addIdempotencyToken_opRegisterTaskWithMaintenanceWindowMiddleware(stack, options); err != nil { - return err - } - if err = addOpRegisterTaskWithMaintenanceWindowValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRegisterTaskWithMaintenanceWindow(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -type idempotencyToken_initializeOpRegisterTaskWithMaintenanceWindow struct { - tokenProvider IdempotencyTokenProvider -} - -func (*idempotencyToken_initializeOpRegisterTaskWithMaintenanceWindow) ID() string { - return "OperationIdempotencyTokenAutoFill" -} - -func (m *idempotencyToken_initializeOpRegisterTaskWithMaintenanceWindow) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.tokenProvider == nil { - return next.HandleInitialize(ctx, in) - } - - input, ok := in.Parameters.(*RegisterTaskWithMaintenanceWindowInput) - if !ok { - return out, metadata, fmt.Errorf("expected middleware input to be of type *RegisterTaskWithMaintenanceWindowInput ") - } - - if input.ClientToken == nil { - t, err := m.tokenProvider.GetIdempotencyToken() - if err != nil { - return out, metadata, err - } - input.ClientToken = &t - } - return next.HandleInitialize(ctx, in) -} -func addIdempotencyToken_opRegisterTaskWithMaintenanceWindowMiddleware(stack *middleware.Stack, cfg Options) error { - return stack.Initialize.Add(&idempotencyToken_initializeOpRegisterTaskWithMaintenanceWindow{tokenProvider: cfg.IdempotencyTokenProvider}, middleware.Before) -} - -func newServiceMetadataMiddleware_opRegisterTaskWithMaintenanceWindow(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "RegisterTaskWithMaintenanceWindow", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RemoveTagsFromResource.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RemoveTagsFromResource.go deleted file mode 100644 index f35351ee..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_RemoveTagsFromResource.go +++ /dev/null @@ -1,158 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Removes tag keys from the specified resource. -func (c *Client) RemoveTagsFromResource(ctx context.Context, params *RemoveTagsFromResourceInput, optFns ...func(*Options)) (*RemoveTagsFromResourceOutput, error) { - if params == nil { - params = &RemoveTagsFromResourceInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "RemoveTagsFromResource", params, optFns, c.addOperationRemoveTagsFromResourceMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*RemoveTagsFromResourceOutput) - out.ResultMetadata = metadata - return out, nil -} - -type RemoveTagsFromResourceInput struct { - - // The ID of the resource from which you want to remove tags. For example: - // ManagedInstance: mi-012345abcde MaintenanceWindow: mw-012345abcde Automation : - // example-c160-4567-8519-012345abcde PatchBaseline: pb-012345abcde OpsMetadata - // object: ResourceID for tagging is created from the Amazon Resource Name (ARN) - // for the object. Specifically, ResourceID is created from the strings that come - // after the word opsmetadata in the ARN. For example, an OpsMetadata object with - // an ARN of - // arn:aws:ssm:us-east-2:1234567890:opsmetadata/aws/ssm/MyGroup/appmanager has a - // ResourceID of either aws/ssm/MyGroup/appmanager or /aws/ssm/MyGroup/appmanager . - // For the Document and Parameter values, use the name of the resource. The - // ManagedInstance type for this API operation is only for on-premises managed - // nodes. Specify the name of the managed node in the following format: - // mi-ID_number. For example, mi-1a2b3c4d5e6f. - // - // This member is required. - ResourceId *string - - // The type of resource from which you want to remove a tag. The ManagedInstance - // type for this API operation is only for on-premises managed nodes. Specify the - // name of the managed node in the following format: mi-ID_number . For example, - // mi-1a2b3c4d5e6f . - // - // This member is required. - ResourceType types.ResourceTypeForTagging - - // Tag keys that you want to remove from the specified resource. - // - // This member is required. - TagKeys []string - - noSmithyDocumentSerde -} - -type RemoveTagsFromResourceOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationRemoveTagsFromResourceMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpRemoveTagsFromResource{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpRemoveTagsFromResource{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "RemoveTagsFromResource"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpRemoveTagsFromResourceValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRemoveTagsFromResource(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opRemoveTagsFromResource(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "RemoveTagsFromResource", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ResetServiceSetting.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ResetServiceSetting.go deleted file mode 100644 index fef61e36..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ResetServiceSetting.go +++ /dev/null @@ -1,162 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// ServiceSetting is an account-level setting for an Amazon Web Services service. -// This setting defines how a user interacts with or uses a service or a feature of -// a service. For example, if an Amazon Web Services service charges money to the -// account based on feature or service usage, then the Amazon Web Services service -// team might create a default setting of "false". This means the user can't use -// this feature unless they change the setting to "true" and intentionally opt in -// for a paid feature. Services map a SettingId object to a setting value. Amazon -// Web Services services teams define the default value for a SettingId . You can't -// create a new SettingId , but you can overwrite the default value if you have the -// ssm:UpdateServiceSetting permission for the setting. Use the GetServiceSetting -// API operation to view the current value. Use the UpdateServiceSetting API -// operation to change the default setting. Reset the service setting for the -// account to the default value as provisioned by the Amazon Web Services service -// team. -func (c *Client) ResetServiceSetting(ctx context.Context, params *ResetServiceSettingInput, optFns ...func(*Options)) (*ResetServiceSettingOutput, error) { - if params == nil { - params = &ResetServiceSettingInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ResetServiceSetting", params, optFns, c.addOperationResetServiceSettingMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ResetServiceSettingOutput) - out.ResultMetadata = metadata - return out, nil -} - -// The request body of the ResetServiceSetting API operation. -type ResetServiceSettingInput struct { - - // The Amazon Resource Name (ARN) of the service setting to reset. The setting ID - // can be one of the following. - // - /ssm/managed-instance/default-ec2-instance-management-role - // - /ssm/automation/customer-script-log-destination - // - /ssm/automation/customer-script-log-group-name - // - /ssm/documents/console/public-sharing-permission - // - /ssm/managed-instance/activation-tier - // - /ssm/opsinsights/opscenter - // - /ssm/parameter-store/default-parameter-tier - // - /ssm/parameter-store/high-throughput-enabled - // - // This member is required. - SettingId *string - - noSmithyDocumentSerde -} - -// The result body of the ResetServiceSetting API operation. -type ResetServiceSettingOutput struct { - - // The current, effective service setting after calling the ResetServiceSetting - // API operation. - ServiceSetting *types.ServiceSetting - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationResetServiceSettingMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpResetServiceSetting{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpResetServiceSetting{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ResetServiceSetting"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpResetServiceSettingValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opResetServiceSetting(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opResetServiceSetting(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ResetServiceSetting", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ResumeSession.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ResumeSession.go deleted file mode 100644 index 731f79e0..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_ResumeSession.go +++ /dev/null @@ -1,155 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Reconnects a session to a managed node after it has been disconnected. -// Connections can be resumed for disconnected sessions, but not terminated -// sessions. This command is primarily for use by client machines to automatically -// reconnect during intermittent network issues. It isn't intended for any other -// use. -func (c *Client) ResumeSession(ctx context.Context, params *ResumeSessionInput, optFns ...func(*Options)) (*ResumeSessionOutput, error) { - if params == nil { - params = &ResumeSessionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ResumeSession", params, optFns, c.addOperationResumeSessionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ResumeSessionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ResumeSessionInput struct { - - // The ID of the disconnected session to resume. - // - // This member is required. - SessionId *string - - noSmithyDocumentSerde -} - -type ResumeSessionOutput struct { - - // The ID of the session. - SessionId *string - - // A URL back to SSM Agent on the managed node that the Session Manager client - // uses to send commands and receive output from the managed node. Format: - // wss://ssmmessages.region.amazonaws.com/v1/data-channel/session-id?stream=(input|output) - // . region represents the Region identifier for an Amazon Web Services Region - // supported by Amazon Web Services Systems Manager, such as us-east-2 for the US - // East (Ohio) Region. For a list of supported region values, see the Region column - // in Systems Manager service endpoints (https://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region) - // in the Amazon Web Services General Reference. session-id represents the ID of a - // Session Manager session, such as 1a2b3c4dEXAMPLE . - StreamUrl *string - - // An encrypted token value containing session and caller information. Used to - // authenticate the connection to the managed node. - TokenValue *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationResumeSessionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpResumeSession{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpResumeSession{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ResumeSession"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpResumeSessionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opResumeSession(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opResumeSession(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ResumeSession", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_SendAutomationSignal.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_SendAutomationSignal.go deleted file mode 100644 index 94933a39..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_SendAutomationSignal.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Sends a signal to an Automation execution to change the current behavior or -// status of the execution. -func (c *Client) SendAutomationSignal(ctx context.Context, params *SendAutomationSignalInput, optFns ...func(*Options)) (*SendAutomationSignalOutput, error) { - if params == nil { - params = &SendAutomationSignalInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "SendAutomationSignal", params, optFns, c.addOperationSendAutomationSignalMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*SendAutomationSignalOutput) - out.ResultMetadata = metadata - return out, nil -} - -type SendAutomationSignalInput struct { - - // The unique identifier for an existing Automation execution that you want to - // send the signal to. - // - // This member is required. - AutomationExecutionId *string - - // The type of signal to send to an Automation execution. - // - // This member is required. - SignalType types.SignalType - - // The data sent with the signal. The data schema depends on the type of signal - // used in the request. For Approve and Reject signal types, the payload is an - // optional comment that you can send with the signal type. For example: - // Comment="Looks good" For StartStep and Resume signal types, you must send the - // name of the Automation step to start or resume as the payload. For example: - // StepName="step1" For the StopStep signal type, you must send the step execution - // ID as the payload. For example: - // StepExecutionId="97fff367-fc5a-4299-aed8-0123456789ab" - Payload map[string][]string - - noSmithyDocumentSerde -} - -type SendAutomationSignalOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationSendAutomationSignalMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpSendAutomationSignal{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpSendAutomationSignal{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "SendAutomationSignal"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpSendAutomationSignalValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opSendAutomationSignal(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opSendAutomationSignal(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "SendAutomationSignal", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_SendCommand.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_SendCommand.go deleted file mode 100644 index 76be45f4..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_SendCommand.go +++ /dev/null @@ -1,238 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Runs commands on one or more managed nodes. -func (c *Client) SendCommand(ctx context.Context, params *SendCommandInput, optFns ...func(*Options)) (*SendCommandOutput, error) { - if params == nil { - params = &SendCommandInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "SendCommand", params, optFns, c.addOperationSendCommandMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*SendCommandOutput) - out.ResultMetadata = metadata - return out, nil -} - -type SendCommandInput struct { - - // The name of the Amazon Web Services Systems Manager document (SSM document) to - // run. This can be a public document or a custom document. To run a shared - // document belonging to another account, specify the document Amazon Resource Name - // (ARN). For more information about how to use shared documents, see Using shared - // SSM documents (https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-using-shared.html) - // in the Amazon Web Services Systems Manager User Guide. If you specify a document - // name or ARN that hasn't been shared with your account, you receive an - // InvalidDocument error. - // - // This member is required. - DocumentName *string - - // The CloudWatch alarm you want to apply to your command. - AlarmConfiguration *types.AlarmConfiguration - - // Enables Amazon Web Services Systems Manager to send Run Command output to - // Amazon CloudWatch Logs. Run Command is a capability of Amazon Web Services - // Systems Manager. - CloudWatchOutputConfig *types.CloudWatchOutputConfig - - // User-specified information about the command, such as a brief description of - // what the command should do. - Comment *string - - // The Sha256 or Sha1 hash created by the system when the document was created. - // Sha1 hashes have been deprecated. - DocumentHash *string - - // Sha256 or Sha1. Sha1 hashes have been deprecated. - DocumentHashType types.DocumentHashType - - // The SSM document version to use in the request. You can specify $DEFAULT, - // $LATEST, or a specific version number. If you run commands by using the Command - // Line Interface (Amazon Web Services CLI), then you must escape the first two - // options by using a backslash. If you specify a version number, then you don't - // need to use the backslash. For example: --document-version "\$DEFAULT" - // --document-version "\$LATEST" --document-version "3" - DocumentVersion *string - - // The IDs of the managed nodes where the command should run. Specifying managed - // node IDs is most useful when you are targeting a limited number of managed - // nodes, though you can specify up to 50 IDs. To target a larger number of managed - // nodes, or if you prefer not to list individual node IDs, we recommend using the - // Targets option instead. Using Targets , which accepts tag key-value pairs to - // identify the managed nodes to send commands to, you can a send command to tens, - // hundreds, or thousands of nodes at once. For more information about how to use - // targets, see Using targets and rate controls to send commands to a fleet (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html) - // in the Amazon Web Services Systems Manager User Guide. - InstanceIds []string - - // (Optional) The maximum number of managed nodes that are allowed to run the - // command at the same time. You can specify a number such as 10 or a percentage - // such as 10%. The default value is 50 . For more information about how to use - // MaxConcurrency , see Using concurrency controls (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html#send-commands-velocity) - // in the Amazon Web Services Systems Manager User Guide. - MaxConcurrency *string - - // The maximum number of errors allowed without the command failing. When the - // command fails one more time beyond the value of MaxErrors , the systems stops - // sending the command to additional targets. You can specify a number like 10 or a - // percentage like 10%. The default value is 0 . For more information about how to - // use MaxErrors , see Using error controls (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html#send-commands-maxerrors) - // in the Amazon Web Services Systems Manager User Guide. - MaxErrors *string - - // Configurations for sending notifications. - NotificationConfig *types.NotificationConfig - - // The name of the S3 bucket where command execution responses should be stored. - OutputS3BucketName *string - - // The directory structure within the S3 bucket where the responses should be - // stored. - OutputS3KeyPrefix *string - - // (Deprecated) You can no longer specify this parameter. The system ignores it. - // Instead, Systems Manager automatically determines the Amazon Web Services Region - // of the S3 bucket. - OutputS3Region *string - - // The required and optional parameters specified in the document being run. - Parameters map[string][]string - - // The ARN of the Identity and Access Management (IAM) service role to use to - // publish Amazon Simple Notification Service (Amazon SNS) notifications for Run - // Command commands. This role must provide the sns:Publish permission for your - // notification topic. For information about creating and using this service role, - // see Monitoring Systems Manager status changes using Amazon SNS notifications (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitoring-sns-notifications.html) - // in the Amazon Web Services Systems Manager User Guide. - ServiceRoleArn *string - - // An array of search criteria that targets managed nodes using a Key,Value - // combination that you specify. Specifying targets is most useful when you want to - // send a command to a large number of managed nodes at once. Using Targets , which - // accepts tag key-value pairs to identify managed nodes, you can send a command to - // tens, hundreds, or thousands of nodes at once. To send a command to a smaller - // number of managed nodes, you can use the InstanceIds option instead. For more - // information about how to use targets, see Sending commands to a fleet (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html) - // in the Amazon Web Services Systems Manager User Guide. - Targets []types.Target - - // If this time is reached and the command hasn't already started running, it - // won't run. - TimeoutSeconds *int32 - - noSmithyDocumentSerde -} - -type SendCommandOutput struct { - - // The request as it was received by Systems Manager. Also provides the command ID - // which can be used future references to this request. - Command *types.Command - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationSendCommandMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpSendCommand{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpSendCommand{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "SendCommand"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpSendCommandValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opSendCommand(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opSendCommand(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "SendCommand", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartAssociationsOnce.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartAssociationsOnce.go deleted file mode 100644 index b1346fca..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartAssociationsOnce.go +++ /dev/null @@ -1,133 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Runs an association immediately and only one time. This operation can be -// helpful when troubleshooting associations. -func (c *Client) StartAssociationsOnce(ctx context.Context, params *StartAssociationsOnceInput, optFns ...func(*Options)) (*StartAssociationsOnceOutput, error) { - if params == nil { - params = &StartAssociationsOnceInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "StartAssociationsOnce", params, optFns, c.addOperationStartAssociationsOnceMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*StartAssociationsOnceOutput) - out.ResultMetadata = metadata - return out, nil -} - -type StartAssociationsOnceInput struct { - - // The association IDs that you want to run immediately and only one time. - // - // This member is required. - AssociationIds []string - - noSmithyDocumentSerde -} - -type StartAssociationsOnceOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationStartAssociationsOnceMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartAssociationsOnce{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStartAssociationsOnce{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "StartAssociationsOnce"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpStartAssociationsOnceValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartAssociationsOnce(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opStartAssociationsOnce(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "StartAssociationsOnce", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartAutomationExecution.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartAutomationExecution.go deleted file mode 100644 index fcdb6775..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartAutomationExecution.go +++ /dev/null @@ -1,208 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Initiates execution of an Automation runbook. -func (c *Client) StartAutomationExecution(ctx context.Context, params *StartAutomationExecutionInput, optFns ...func(*Options)) (*StartAutomationExecutionOutput, error) { - if params == nil { - params = &StartAutomationExecutionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "StartAutomationExecution", params, optFns, c.addOperationStartAutomationExecutionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*StartAutomationExecutionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type StartAutomationExecutionInput struct { - - // The name of the SSM document to run. This can be a public document or a custom - // document. To run a shared document belonging to another account, specify the - // document ARN. For more information about how to use shared documents, see Using - // shared SSM documents (https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-using-shared.html) - // in the Amazon Web Services Systems Manager User Guide. - // - // This member is required. - DocumentName *string - - // The CloudWatch alarm you want to apply to your automation. - AlarmConfiguration *types.AlarmConfiguration - - // User-provided idempotency token. The token must be unique, is case insensitive, - // enforces the UUID format, and can't be reused. - ClientToken *string - - // The version of the Automation runbook to use for this execution. - DocumentVersion *string - - // The maximum number of targets allowed to run this task in parallel. You can - // specify a number, such as 10, or a percentage, such as 10%. The default value is - // 10 . - MaxConcurrency *string - - // The number of errors that are allowed before the system stops running the - // automation on additional targets. You can specify either an absolute number of - // errors, for example 10, or a percentage of the target set, for example 10%. If - // you specify 3, for example, the system stops running the automation when the - // fourth error is received. If you specify 0, then the system stops running the - // automation on additional targets after the first error result is returned. If - // you run an automation on 50 resources and set max-errors to 10%, then the system - // stops running the automation on additional targets when the sixth error is - // received. Executions that are already running an automation when max-errors is - // reached are allowed to complete, but some of these executions may fail as well. - // If you need to ensure that there won't be more than max-errors failed - // executions, set max-concurrency to 1 so the executions proceed one at a time. - MaxErrors *string - - // The execution mode of the automation. Valid modes include the following: Auto - // and Interactive. The default mode is Auto. - Mode types.ExecutionMode - - // A key-value map of execution parameters, which match the declared parameters in - // the Automation runbook. - Parameters map[string][]string - - // Optional metadata that you assign to a resource. You can specify a maximum of - // five tags for an automation. Tags enable you to categorize a resource in - // different ways, such as by purpose, owner, or environment. For example, you - // might want to tag an automation to identify an environment or operating system. - // In this case, you could specify the following key-value pairs: - // - Key=environment,Value=test - // - Key=OS,Value=Windows - // To add tags to an existing automation, use the AddTagsToResource operation. - Tags []types.Tag - - // A location is a combination of Amazon Web Services Regions and/or Amazon Web - // Services accounts where you want to run the automation. Use this operation to - // start an automation in multiple Amazon Web Services Regions and multiple Amazon - // Web Services accounts. For more information, see Running Automation workflows - // in multiple Amazon Web Services Regions and Amazon Web Services accounts (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-automation-multiple-accounts-and-regions.html) - // in the Amazon Web Services Systems Manager User Guide. - TargetLocations []types.TargetLocation - - // A key-value mapping of document parameters to target resources. Both Targets - // and TargetMaps can't be specified together. - TargetMaps []map[string][]string - - // The name of the parameter used as the target resource for the rate-controlled - // execution. Required if you specify targets. - TargetParameterName *string - - // A key-value mapping to target resources. Required if you specify - // TargetParameterName. - Targets []types.Target - - noSmithyDocumentSerde -} - -type StartAutomationExecutionOutput struct { - - // The unique ID of a newly scheduled automation execution. - AutomationExecutionId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationStartAutomationExecutionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartAutomationExecution{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStartAutomationExecution{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "StartAutomationExecution"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpStartAutomationExecutionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartAutomationExecution(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opStartAutomationExecution(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "StartAutomationExecution", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartChangeRequestExecution.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartChangeRequestExecution.go deleted file mode 100644 index 556361e2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartChangeRequestExecution.go +++ /dev/null @@ -1,197 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Creates a change request for Change Manager. The Automation runbooks specified -// in the change request run only after all required approvals for the change -// request have been received. -func (c *Client) StartChangeRequestExecution(ctx context.Context, params *StartChangeRequestExecutionInput, optFns ...func(*Options)) (*StartChangeRequestExecutionOutput, error) { - if params == nil { - params = &StartChangeRequestExecutionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "StartChangeRequestExecution", params, optFns, c.addOperationStartChangeRequestExecutionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*StartChangeRequestExecutionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type StartChangeRequestExecutionInput struct { - - // The name of the change template document to run during the runbook workflow. - // - // This member is required. - DocumentName *string - - // Information about the Automation runbooks that are run during the runbook - // workflow. The Automation runbooks specified for the runbook workflow can't run - // until all required approvals for the change request have been received. - // - // This member is required. - Runbooks []types.Runbook - - // Indicates whether the change request can be approved automatically without the - // need for manual approvals. If AutoApprovable is enabled in a change template, - // then setting AutoApprove to true in StartChangeRequestExecution creates a - // change request that bypasses approver review. Change Calendar restrictions are - // not bypassed in this scenario. If the state of an associated calendar is CLOSED - // , change freeze approvers must still grant permission for this change request to - // run. If they don't, the change won't be processed until the calendar state is - // again OPEN . - AutoApprove bool - - // User-provided details about the change. If no details are provided, content - // specified in the Template information section of the associated change template - // is added. - ChangeDetails *string - - // The name of the change request associated with the runbook workflow to be run. - ChangeRequestName *string - - // The user-provided idempotency token. The token must be unique, is case - // insensitive, enforces the UUID format, and can't be reused. - ClientToken *string - - // The version of the change template document to run during the runbook workflow. - DocumentVersion *string - - // A key-value map of parameters that match the declared parameters in the change - // template document. - Parameters map[string][]string - - // The time that the requester expects the runbook workflow related to the change - // request to complete. The time is an estimate only that the requester provides - // for reviewers. - ScheduledEndTime *time.Time - - // The date and time specified in the change request to run the Automation - // runbooks. The Automation runbooks specified for the runbook workflow can't run - // until all required approvals for the change request have been received. - ScheduledTime *time.Time - - // Optional metadata that you assign to a resource. You can specify a maximum of - // five tags for a change request. Tags enable you to categorize a resource in - // different ways, such as by purpose, owner, or environment. For example, you - // might want to tag a change request to identify an environment or target Amazon - // Web Services Region. In this case, you could specify the following key-value - // pairs: - // - Key=Environment,Value=Production - // - Key=Region,Value=us-east-2 - Tags []types.Tag - - noSmithyDocumentSerde -} - -type StartChangeRequestExecutionOutput struct { - - // The unique ID of a runbook workflow operation. (A runbook workflow is a type of - // Automation operation.) - AutomationExecutionId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationStartChangeRequestExecutionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartChangeRequestExecution{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStartChangeRequestExecution{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "StartChangeRequestExecution"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpStartChangeRequestExecutionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartChangeRequestExecution(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opStartChangeRequestExecution(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "StartChangeRequestExecution", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartSession.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartSession.go deleted file mode 100644 index 0fbe804e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StartSession.go +++ /dev/null @@ -1,180 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Initiates a connection to a target (for example, a managed node) for a Session -// Manager session. Returns a URL and token that can be used to open a WebSocket -// connection for sending input and receiving outputs. Amazon Web Services CLI -// usage: start-session is an interactive command that requires the Session -// Manager plugin to be installed on the client machine making the call. For -// information, see Install the Session Manager plugin for the Amazon Web Services -// CLI (https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html) -// in the Amazon Web Services Systems Manager User Guide. Amazon Web Services Tools -// for PowerShell usage: Start-SSMSession isn't currently supported by Amazon Web -// Services Tools for PowerShell on Windows local machines. -func (c *Client) StartSession(ctx context.Context, params *StartSessionInput, optFns ...func(*Options)) (*StartSessionOutput, error) { - if params == nil { - params = &StartSessionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "StartSession", params, optFns, c.addOperationStartSessionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*StartSessionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type StartSessionInput struct { - - // The managed node to connect to for the session. - // - // This member is required. - Target *string - - // The name of the SSM document you want to use to define the type of session, - // input parameters, or preferences for the session. For example, - // SSM-SessionManagerRunShell . You can call the GetDocument API to verify the - // document exists before attempting to start a session. If no document name is - // provided, a shell to the managed node is launched by default. For more - // information, see Start a session (https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html) - // in the Amazon Web Services Systems Manager User Guide. - DocumentName *string - - // The values you want to specify for the parameters defined in the Session - // document. - Parameters map[string][]string - - // The reason for connecting to the instance. This value is included in the - // details for the Amazon CloudWatch Events event created when you start the - // session. - Reason *string - - noSmithyDocumentSerde -} - -type StartSessionOutput struct { - - // The ID of the session. - SessionId *string - - // A URL back to SSM Agent on the managed node that the Session Manager client - // uses to send commands and receive output from the node. Format: - // wss://ssmmessages.region.amazonaws.com/v1/data-channel/session-id?stream=(input|output) - // region represents the Region identifier for an Amazon Web Services Region - // supported by Amazon Web Services Systems Manager, such as us-east-2 for the US - // East (Ohio) Region. For a list of supported region values, see the Region column - // in Systems Manager service endpoints (https://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region) - // in the Amazon Web Services General Reference. session-id represents the ID of a - // Session Manager session, such as 1a2b3c4dEXAMPLE . - StreamUrl *string - - // An encrypted token value containing session and caller information. This token - // is used to authenticate the connection to the managed node, and is valid only - // long enough to ensure the connection is successful. Never share your session's - // token. - TokenValue *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationStartSessionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpStartSession{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStartSession{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "StartSession"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpStartSessionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartSession(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opStartSession(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "StartSession", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StopAutomationExecution.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StopAutomationExecution.go deleted file mode 100644 index cb2928c9..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_StopAutomationExecution.go +++ /dev/null @@ -1,137 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Stop an Automation that is currently running. -func (c *Client) StopAutomationExecution(ctx context.Context, params *StopAutomationExecutionInput, optFns ...func(*Options)) (*StopAutomationExecutionOutput, error) { - if params == nil { - params = &StopAutomationExecutionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "StopAutomationExecution", params, optFns, c.addOperationStopAutomationExecutionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*StopAutomationExecutionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type StopAutomationExecutionInput struct { - - // The execution ID of the Automation to stop. - // - // This member is required. - AutomationExecutionId *string - - // The stop request type. Valid types include the following: Cancel and Complete. - // The default type is Cancel. - Type types.StopType - - noSmithyDocumentSerde -} - -type StopAutomationExecutionOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationStopAutomationExecutionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpStopAutomationExecution{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpStopAutomationExecution{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "StopAutomationExecution"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpStopAutomationExecutionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStopAutomationExecution(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opStopAutomationExecution(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "StopAutomationExecution", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_TerminateSession.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_TerminateSession.go deleted file mode 100644 index f1dbd68c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_TerminateSession.go +++ /dev/null @@ -1,138 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Permanently ends a session and closes the data connection between the Session -// Manager client and SSM Agent on the managed node. A terminated session can't be -// resumed. -func (c *Client) TerminateSession(ctx context.Context, params *TerminateSessionInput, optFns ...func(*Options)) (*TerminateSessionOutput, error) { - if params == nil { - params = &TerminateSessionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "TerminateSession", params, optFns, c.addOperationTerminateSessionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*TerminateSessionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type TerminateSessionInput struct { - - // The ID of the session to terminate. - // - // This member is required. - SessionId *string - - noSmithyDocumentSerde -} - -type TerminateSessionOutput struct { - - // The ID of the session that has been terminated. - SessionId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationTerminateSessionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpTerminateSession{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpTerminateSession{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "TerminateSession"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpTerminateSessionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opTerminateSession(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opTerminateSession(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "TerminateSession", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UnlabelParameterVersion.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UnlabelParameterVersion.go deleted file mode 100644 index f45c3ff3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UnlabelParameterVersion.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Remove a label or labels from a parameter. -func (c *Client) UnlabelParameterVersion(ctx context.Context, params *UnlabelParameterVersionInput, optFns ...func(*Options)) (*UnlabelParameterVersionOutput, error) { - if params == nil { - params = &UnlabelParameterVersionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UnlabelParameterVersion", params, optFns, c.addOperationUnlabelParameterVersionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UnlabelParameterVersionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UnlabelParameterVersionInput struct { - - // One or more labels to delete from the specified parameter version. - // - // This member is required. - Labels []string - - // The name of the parameter from which you want to delete one or more labels. - // - // This member is required. - Name *string - - // The specific version of the parameter which you want to delete one or more - // labels from. If it isn't present, the call will fail. - // - // This member is required. - ParameterVersion *int64 - - noSmithyDocumentSerde -} - -type UnlabelParameterVersionOutput struct { - - // The labels that aren't attached to the given parameter version. - InvalidLabels []string - - // A list of all labels deleted from the parameter. - RemovedLabels []string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUnlabelParameterVersionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUnlabelParameterVersion{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUnlabelParameterVersion{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UnlabelParameterVersion"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUnlabelParameterVersionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUnlabelParameterVersion(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUnlabelParameterVersion(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UnlabelParameterVersion", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateAssociation.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateAssociation.go deleted file mode 100644 index d72a6986..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateAssociation.go +++ /dev/null @@ -1,290 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Updates an association. You can update the association name and version, the -// document version, schedule, parameters, and Amazon Simple Storage Service -// (Amazon S3) output. When you call UpdateAssociation , the system removes all -// optional parameters from the request and overwrites the association with null -// values for those parameters. This is by design. You must specify all optional -// parameters in the call, even if you are not changing the parameters. This -// includes the Name parameter. Before calling this API action, we recommend that -// you call the DescribeAssociation API operation and make a note of all optional -// parameters required for your UpdateAssociation call. In order to call this API -// operation, a user, group, or role must be granted permission to call the -// DescribeAssociation API operation. If you don't have permission to call -// DescribeAssociation , then you receive the following error: An error occurred -// (AccessDeniedException) when calling the UpdateAssociation operation: User: -// isn't authorized to perform: ssm:DescribeAssociation on resource: When you -// update an association, the association immediately runs against the specified -// targets. You can add the ApplyOnlyAtCronInterval parameter to run the -// association during the next schedule run. -func (c *Client) UpdateAssociation(ctx context.Context, params *UpdateAssociationInput, optFns ...func(*Options)) (*UpdateAssociationOutput, error) { - if params == nil { - params = &UpdateAssociationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateAssociation", params, optFns, c.addOperationUpdateAssociationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateAssociationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateAssociationInput struct { - - // The ID of the association you want to update. - // - // This member is required. - AssociationId *string - - // The details for the CloudWatch alarm you want to apply to an automation or - // command. - AlarmConfiguration *types.AlarmConfiguration - - // By default, when you update an association, the system runs it immediately - // after it is updated and then according to the schedule you specified. Specify - // this option if you don't want an association to run immediately after you update - // it. This parameter isn't supported for rate expressions. If you chose this - // option when you created an association and later you edit that association or - // you make changes to the SSM document on which that association is based (by - // using the Documents page in the console), State Manager applies the association - // at the next specified cron interval. For example, if you chose the Latest - // version of an SSM document when you created an association and you edit the - // association by choosing a different document version on the Documents page, - // State Manager applies the association at the next specified cron interval if you - // previously selected this option. If this option wasn't selected, State Manager - // immediately runs the association. You can reset this option. To do so, specify - // the no-apply-only-at-cron-interval parameter when you update the association - // from the command line. This parameter forces the association to run immediately - // after updating it and according to the interval specified. - ApplyOnlyAtCronInterval bool - - // The name of the association that you want to update. - AssociationName *string - - // This parameter is provided for concurrency control purposes. You must specify - // the latest association version in the service. If you want to ensure that this - // request succeeds, either specify $LATEST , or omit this parameter. - AssociationVersion *string - - // Choose the parameter that will define how your automation will branch out. This - // target is required for associations that use an Automation runbook and target - // resources by using rate controls. Automation is a capability of Amazon Web - // Services Systems Manager. - AutomationTargetParameterName *string - - // The names or Amazon Resource Names (ARNs) of the Change Calendar type documents - // you want to gate your associations under. The associations only run when that - // change calendar is open. For more information, see Amazon Web Services Systems - // Manager Change Calendar (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-change-calendar) - // . - CalendarNames []string - - // The severity level to assign to the association. - ComplianceSeverity types.AssociationComplianceSeverity - - // The document version you want update for the association. State Manager doesn't - // support running associations that use a new version of a document if that - // document is shared from another account. State Manager always runs the default - // version of a document if shared from another account, even though the Systems - // Manager console shows that a new version was processed. If you want to run an - // association using a new version of a document shared form another account, you - // must set the document version to default . - DocumentVersion *string - - // The maximum number of targets allowed to run the association at the same time. - // You can specify a number, for example 10, or a percentage of the target set, for - // example 10%. The default value is 100%, which means all targets run the - // association at the same time. If a new managed node starts and attempts to run - // an association while Systems Manager is running MaxConcurrency associations, - // the association is allowed to run. During the next association interval, the new - // managed node will process its association within the limit specified for - // MaxConcurrency . - MaxConcurrency *string - - // The number of errors that are allowed before the system stops sending requests - // to run the association on additional targets. You can specify either an absolute - // number of errors, for example 10, or a percentage of the target set, for example - // 10%. If you specify 3, for example, the system stops sending requests when the - // fourth error is received. If you specify 0, then the system stops sending - // requests after the first error is returned. If you run an association on 50 - // managed nodes and set MaxError to 10%, then the system stops sending the - // request when the sixth error is received. Executions that are already running an - // association when MaxErrors is reached are allowed to complete, but some of - // these executions may fail as well. If you need to ensure that there won't be - // more than max-errors failed executions, set MaxConcurrency to 1 so that - // executions proceed one at a time. - MaxErrors *string - - // The name of the SSM Command document or Automation runbook that contains the - // configuration information for the managed node. You can specify Amazon Web - // Services-predefined documents, documents you created, or a document that is - // shared with you from another account. For Systems Manager document (SSM - // document) that are shared with you from other Amazon Web Services accounts, you - // must specify the complete SSM document ARN, in the following format: - // arn:aws:ssm:region:account-id:document/document-name For example: - // arn:aws:ssm:us-east-2:12345678912:document/My-Shared-Document For Amazon Web - // Services-predefined documents and SSM documents you created in your account, you - // only need to specify the document name. For example, AWS-ApplyPatchBaseline or - // My-Document . - Name *string - - // An S3 bucket where you want to store the results of this request. - OutputLocation *types.InstanceAssociationOutputLocation - - // The parameters you want to update for the association. If you create a - // parameter using Parameter Store, a capability of Amazon Web Services Systems - // Manager, you can reference the parameter using {{ssm:parameter-name}} . - Parameters map[string][]string - - // The cron expression used to schedule the association that you want to update. - ScheduleExpression *string - - // Number of days to wait after the scheduled day to run an association. For - // example, if you specified a cron schedule of cron(0 0 ? * THU#2 *) , you could - // specify an offset of 3 to run the association each Sunday after the second - // Thursday of the month. For more information about cron schedules for - // associations, see Reference: Cron and rate expressions for Systems Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/reference-cron-and-rate-expressions.html) - // in the Amazon Web Services Systems Manager User Guide. To use offsets, you must - // specify the ApplyOnlyAtCronInterval parameter. This option tells the system not - // to run an association immediately after you create it. - ScheduleOffset *int32 - - // The mode for generating association compliance. You can specify AUTO or MANUAL . - // In AUTO mode, the system uses the status of the association execution to - // determine the compliance status. If the association execution runs successfully, - // then the association is COMPLIANT . If the association execution doesn't run - // successfully, the association is NON-COMPLIANT . In MANUAL mode, you must - // specify the AssociationId as a parameter for the PutComplianceItems API - // operation. In this case, compliance data isn't managed by State Manager, a - // capability of Amazon Web Services Systems Manager. It is managed by your direct - // call to the PutComplianceItems API operation. By default, all associations use - // AUTO mode. - SyncCompliance types.AssociationSyncCompliance - - // A location is a combination of Amazon Web Services Regions and Amazon Web - // Services accounts where you want to run the association. Use this action to - // update an association in multiple Regions and multiple accounts. - TargetLocations []types.TargetLocation - - // A key-value mapping of document parameters to target resources. Both Targets - // and TargetMaps can't be specified together. - TargetMaps []map[string][]string - - // The targets of the association. - Targets []types.Target - - noSmithyDocumentSerde -} - -type UpdateAssociationOutput struct { - - // The description of the association that was updated. - AssociationDescription *types.AssociationDescription - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateAssociationMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateAssociation{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateAssociation{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateAssociation"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateAssociationValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateAssociation(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateAssociation(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateAssociation", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateAssociationStatus.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateAssociationStatus.go deleted file mode 100644 index 6030e693..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateAssociationStatus.go +++ /dev/null @@ -1,151 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Updates the status of the Amazon Web Services Systems Manager document (SSM -// document) associated with the specified managed node. UpdateAssociationStatus -// is primarily used by the Amazon Web Services Systems Manager Agent (SSM Agent) -// to report status updates about your associations and is only used for -// associations created with the InstanceId legacy parameter. -func (c *Client) UpdateAssociationStatus(ctx context.Context, params *UpdateAssociationStatusInput, optFns ...func(*Options)) (*UpdateAssociationStatusOutput, error) { - if params == nil { - params = &UpdateAssociationStatusInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateAssociationStatus", params, optFns, c.addOperationUpdateAssociationStatusMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateAssociationStatusOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateAssociationStatusInput struct { - - // The association status. - // - // This member is required. - AssociationStatus *types.AssociationStatus - - // The managed node ID. - // - // This member is required. - InstanceId *string - - // The name of the SSM document. - // - // This member is required. - Name *string - - noSmithyDocumentSerde -} - -type UpdateAssociationStatusOutput struct { - - // Information about the association. - AssociationDescription *types.AssociationDescription - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateAssociationStatusMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateAssociationStatus{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateAssociationStatus{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateAssociationStatus"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateAssociationStatusValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateAssociationStatus(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateAssociationStatus(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateAssociationStatus", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateDocument.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateDocument.go deleted file mode 100644 index e240848e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateDocument.go +++ /dev/null @@ -1,171 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Updates one or more values for an SSM document. -func (c *Client) UpdateDocument(ctx context.Context, params *UpdateDocumentInput, optFns ...func(*Options)) (*UpdateDocumentOutput, error) { - if params == nil { - params = &UpdateDocumentInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateDocument", params, optFns, c.addOperationUpdateDocumentMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateDocumentOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateDocumentInput struct { - - // A valid JSON or YAML string. - // - // This member is required. - Content *string - - // The name of the SSM document that you want to update. - // - // This member is required. - Name *string - - // A list of key-value pairs that describe attachments to a version of a document. - Attachments []types.AttachmentsSource - - // The friendly name of the SSM document that you want to update. This value can - // differ for each version of the document. If you don't specify a value for this - // parameter in your request, the existing value is applied to the new document - // version. - DisplayName *string - - // Specify the document format for the new document version. Systems Manager - // supports JSON and YAML documents. JSON is the default format. - DocumentFormat types.DocumentFormat - - // The version of the document that you want to update. Currently, Systems Manager - // supports updating only the latest version of the document. You can specify the - // version number of the latest version or use the $LATEST variable. If you change - // a document version for a State Manager association, Systems Manager immediately - // runs the association unless you previously specifed the - // apply-only-at-cron-interval parameter. - DocumentVersion *string - - // Specify a new target type for the document. - TargetType *string - - // An optional field specifying the version of the artifact you are updating with - // the document. For example, "Release 12, Update 6". This value is unique across - // all versions of a document, and can't be changed. - VersionName *string - - noSmithyDocumentSerde -} - -type UpdateDocumentOutput struct { - - // A description of the document that was updated. - DocumentDescription *types.DocumentDescription - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateDocumentMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateDocument{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateDocument{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateDocument"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateDocumentValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateDocument(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateDocument(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateDocument", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateDocumentDefaultVersion.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateDocumentDefaultVersion.go deleted file mode 100644 index e395516e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateDocumentDefaultVersion.go +++ /dev/null @@ -1,145 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Set the default version of a document. If you change a document version for a -// State Manager association, Systems Manager immediately runs the association -// unless you previously specifed the apply-only-at-cron-interval parameter. -func (c *Client) UpdateDocumentDefaultVersion(ctx context.Context, params *UpdateDocumentDefaultVersionInput, optFns ...func(*Options)) (*UpdateDocumentDefaultVersionOutput, error) { - if params == nil { - params = &UpdateDocumentDefaultVersionInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateDocumentDefaultVersion", params, optFns, c.addOperationUpdateDocumentDefaultVersionMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateDocumentDefaultVersionOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateDocumentDefaultVersionInput struct { - - // The version of a custom document that you want to set as the default version. - // - // This member is required. - DocumentVersion *string - - // The name of a custom document that you want to set as the default version. - // - // This member is required. - Name *string - - noSmithyDocumentSerde -} - -type UpdateDocumentDefaultVersionOutput struct { - - // The description of a custom document that you want to set as the default - // version. - Description *types.DocumentDefaultVersionDescription - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateDocumentDefaultVersionMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateDocumentDefaultVersion{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateDocumentDefaultVersion{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateDocumentDefaultVersion"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateDocumentDefaultVersionValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateDocumentDefaultVersion(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateDocumentDefaultVersion(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateDocumentDefaultVersion", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateDocumentMetadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateDocumentMetadata.go deleted file mode 100644 index 8d82e9a8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateDocumentMetadata.go +++ /dev/null @@ -1,142 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Updates information related to approval reviews for a specific version of a -// change template in Change Manager. -func (c *Client) UpdateDocumentMetadata(ctx context.Context, params *UpdateDocumentMetadataInput, optFns ...func(*Options)) (*UpdateDocumentMetadataOutput, error) { - if params == nil { - params = &UpdateDocumentMetadataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateDocumentMetadata", params, optFns, c.addOperationUpdateDocumentMetadataMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateDocumentMetadataOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateDocumentMetadataInput struct { - - // The change template review details to update. - // - // This member is required. - DocumentReviews *types.DocumentReviews - - // The name of the change template for which a version's metadata is to be updated. - // - // This member is required. - Name *string - - // The version of a change template in which to update approval metadata. - DocumentVersion *string - - noSmithyDocumentSerde -} - -type UpdateDocumentMetadataOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateDocumentMetadataMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateDocumentMetadata{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateDocumentMetadata{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateDocumentMetadata"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateDocumentMetadataValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateDocumentMetadata(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateDocumentMetadata(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateDocumentMetadata", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateMaintenanceWindow.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateMaintenanceWindow.go deleted file mode 100644 index 4be08b36..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateMaintenanceWindow.go +++ /dev/null @@ -1,236 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Updates an existing maintenance window. Only specified parameters are modified. -// The value you specify for Duration determines the specific end time for the -// maintenance window based on the time it begins. No maintenance window tasks are -// permitted to start after the resulting endtime minus the number of hours you -// specify for Cutoff . For example, if the maintenance window starts at 3 PM, the -// duration is three hours, and the value you specify for Cutoff is one hour, no -// maintenance window tasks can start after 5 PM. -func (c *Client) UpdateMaintenanceWindow(ctx context.Context, params *UpdateMaintenanceWindowInput, optFns ...func(*Options)) (*UpdateMaintenanceWindowOutput, error) { - if params == nil { - params = &UpdateMaintenanceWindowInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateMaintenanceWindow", params, optFns, c.addOperationUpdateMaintenanceWindowMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateMaintenanceWindowOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateMaintenanceWindowInput struct { - - // The ID of the maintenance window to update. - // - // This member is required. - WindowId *string - - // Whether targets must be registered with the maintenance window before tasks can - // be defined for those targets. - AllowUnassociatedTargets *bool - - // The number of hours before the end of the maintenance window that Amazon Web - // Services Systems Manager stops scheduling new tasks for execution. - Cutoff *int32 - - // An optional description for the update request. - Description *string - - // The duration of the maintenance window in hours. - Duration *int32 - - // Whether the maintenance window is enabled. - Enabled *bool - - // The date and time, in ISO-8601 Extended format, for when you want the - // maintenance window to become inactive. EndDate allows you to set a date and - // time in the future when the maintenance window will no longer run. - EndDate *string - - // The name of the maintenance window. - Name *string - - // If True , then all fields that are required by the CreateMaintenanceWindow - // operation are also required for this API request. Optional fields that aren't - // specified are set to null. - Replace *bool - - // The schedule of the maintenance window in the form of a cron or rate expression. - Schedule *string - - // The number of days to wait after the date and time specified by a cron - // expression before running the maintenance window. For example, the following - // cron expression schedules a maintenance window to run the third Tuesday of every - // month at 11:30 PM. cron(30 23 ? * TUE#3 *) If the schedule offset is 2 , the - // maintenance window won't run until two days later. - ScheduleOffset *int32 - - // The time zone that the scheduled maintenance window executions are based on, in - // Internet Assigned Numbers Authority (IANA) format. For example: - // "America/Los_Angeles", "UTC", or "Asia/Seoul". For more information, see the - // Time Zone Database (https://www.iana.org/time-zones) on the IANA website. - ScheduleTimezone *string - - // The date and time, in ISO-8601 Extended format, for when you want the - // maintenance window to become active. StartDate allows you to delay activation - // of the maintenance window until the specified future date. - StartDate *string - - noSmithyDocumentSerde -} - -type UpdateMaintenanceWindowOutput struct { - - // Whether targets must be registered with the maintenance window before tasks can - // be defined for those targets. - AllowUnassociatedTargets bool - - // The number of hours before the end of the maintenance window that Amazon Web - // Services Systems Manager stops scheduling new tasks for execution. - Cutoff int32 - - // An optional description of the update. - Description *string - - // The duration of the maintenance window in hours. - Duration *int32 - - // Whether the maintenance window is enabled. - Enabled bool - - // The date and time, in ISO-8601 Extended format, for when the maintenance window - // is scheduled to become inactive. The maintenance window won't run after this - // specified time. - EndDate *string - - // The name of the maintenance window. - Name *string - - // The schedule of the maintenance window in the form of a cron or rate expression. - Schedule *string - - // The number of days to wait to run a maintenance window after the scheduled cron - // expression date and time. - ScheduleOffset *int32 - - // The time zone that the scheduled maintenance window executions are based on, in - // Internet Assigned Numbers Authority (IANA) format. For example: - // "America/Los_Angeles", "UTC", or "Asia/Seoul". For more information, see the - // Time Zone Database (https://www.iana.org/time-zones) on the IANA website. - ScheduleTimezone *string - - // The date and time, in ISO-8601 Extended format, for when the maintenance window - // is scheduled to become active. The maintenance window won't run before this - // specified time. - StartDate *string - - // The ID of the created maintenance window. - WindowId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateMaintenanceWindowMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateMaintenanceWindow{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateMaintenanceWindow"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateMaintenanceWindowValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateMaintenanceWindow(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateMaintenanceWindow(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateMaintenanceWindow", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateMaintenanceWindowTarget.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateMaintenanceWindowTarget.go deleted file mode 100644 index 48a366a1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateMaintenanceWindowTarget.go +++ /dev/null @@ -1,185 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Modifies the target of an existing maintenance window. You can change the -// following: -// - Name -// - Description -// - Owner -// - IDs for an ID target -// - Tags for a Tag target -// - From any supported tag type to another. The three supported tag types are -// ID target, Tag target, and resource group. For more information, see Target . -// -// If a parameter is null, then the corresponding field isn't modified. -func (c *Client) UpdateMaintenanceWindowTarget(ctx context.Context, params *UpdateMaintenanceWindowTargetInput, optFns ...func(*Options)) (*UpdateMaintenanceWindowTargetOutput, error) { - if params == nil { - params = &UpdateMaintenanceWindowTargetInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateMaintenanceWindowTarget", params, optFns, c.addOperationUpdateMaintenanceWindowTargetMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateMaintenanceWindowTargetOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateMaintenanceWindowTargetInput struct { - - // The maintenance window ID with which to modify the target. - // - // This member is required. - WindowId *string - - // The target ID to modify. - // - // This member is required. - WindowTargetId *string - - // An optional description for the update. - Description *string - - // A name for the update. - Name *string - - // User-provided value that will be included in any Amazon CloudWatch Events - // events raised while running tasks for these targets in this maintenance window. - OwnerInformation *string - - // If True , then all fields that are required by the - // RegisterTargetWithMaintenanceWindow operation are also required for this API - // request. Optional fields that aren't specified are set to null. - Replace *bool - - // The targets to add or replace. - Targets []types.Target - - noSmithyDocumentSerde -} - -type UpdateMaintenanceWindowTargetOutput struct { - - // The updated description. - Description *string - - // The updated name. - Name *string - - // The updated owner. - OwnerInformation *string - - // The updated targets. - Targets []types.Target - - // The maintenance window ID specified in the update request. - WindowId *string - - // The target ID specified in the update request. - WindowTargetId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateMaintenanceWindowTargetMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateMaintenanceWindowTarget{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateMaintenanceWindowTarget{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateMaintenanceWindowTarget"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateMaintenanceWindowTargetValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateMaintenanceWindowTarget(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateMaintenanceWindowTarget(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateMaintenanceWindowTarget", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateMaintenanceWindowTask.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateMaintenanceWindowTask.go deleted file mode 100644 index 07abf522..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateMaintenanceWindowTask.go +++ /dev/null @@ -1,332 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Modifies a task assigned to a maintenance window. You can't change the task -// type, but you can change the following values: -// - TaskARN . For example, you can change a RUN_COMMAND task from -// AWS-RunPowerShellScript to AWS-RunShellScript . -// - ServiceRoleArn -// - TaskInvocationParameters -// - Priority -// - MaxConcurrency -// - MaxErrors -// -// One or more targets must be specified for maintenance window Run Command-type -// tasks. Depending on the task, targets are optional for other maintenance window -// task types (Automation, Lambda, and Step Functions). For more information about -// running tasks that don't specify targets, see Registering maintenance window -// tasks without targets (https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-targetless-tasks.html) -// in the Amazon Web Services Systems Manager User Guide. If the value for a -// parameter in UpdateMaintenanceWindowTask is null, then the corresponding field -// isn't modified. If you set Replace to true, then all fields required by the -// RegisterTaskWithMaintenanceWindow operation are required for this request. -// Optional fields that aren't specified are set to null. When you update a -// maintenance window task that has options specified in TaskInvocationParameters , -// you must provide again all the TaskInvocationParameters values that you want to -// retain. The values you don't specify again are removed. For example, suppose -// that when you registered a Run Command task, you specified -// TaskInvocationParameters values for Comment , NotificationConfig , and -// OutputS3BucketName . If you update the maintenance window task and specify only -// a different OutputS3BucketName value, the values for Comment and -// NotificationConfig are removed. -func (c *Client) UpdateMaintenanceWindowTask(ctx context.Context, params *UpdateMaintenanceWindowTaskInput, optFns ...func(*Options)) (*UpdateMaintenanceWindowTaskOutput, error) { - if params == nil { - params = &UpdateMaintenanceWindowTaskInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateMaintenanceWindowTask", params, optFns, c.addOperationUpdateMaintenanceWindowTaskMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateMaintenanceWindowTaskOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateMaintenanceWindowTaskInput struct { - - // The maintenance window ID that contains the task to modify. - // - // This member is required. - WindowId *string - - // The task ID to modify. - // - // This member is required. - WindowTaskId *string - - // The CloudWatch alarm you want to apply to your maintenance window task. - AlarmConfiguration *types.AlarmConfiguration - - // Indicates whether tasks should continue to run after the cutoff time specified - // in the maintenance windows is reached. - // - CONTINUE_TASK : When the cutoff time is reached, any tasks that are running - // continue. The default value. - // - CANCEL_TASK : - // - For Automation, Lambda, Step Functions tasks: When the cutoff time is - // reached, any task invocations that are already running continue, but no new task - // invocations are started. - // - For Run Command tasks: When the cutoff time is reached, the system sends a - // CancelCommand operation that attempts to cancel the command associated with - // the task. However, there is no guarantee that the command will be terminated and - // the underlying process stopped. The status for tasks that are not completed - // is TIMED_OUT . - CutoffBehavior types.MaintenanceWindowTaskCutoffBehavior - - // The new task description to specify. - Description *string - - // The new logging location in Amazon S3 to specify. LoggingInfo has been - // deprecated. To specify an Amazon Simple Storage Service (Amazon S3) bucket to - // contain logs, instead use the OutputS3BucketName and OutputS3KeyPrefix options - // in the TaskInvocationParameters structure. For information about how Amazon Web - // Services Systems Manager handles these options for the supported maintenance - // window task types, see MaintenanceWindowTaskInvocationParameters . - LoggingInfo *types.LoggingInfo - - // The new MaxConcurrency value you want to specify. MaxConcurrency is the number - // of targets that are allowed to run this task, in parallel. Although this element - // is listed as "Required: No", a value can be omitted only when you are - // registering or updating a targetless task (https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-targetless-tasks.html) - // You must provide a value in all other cases. For maintenance window tasks - // without a target specified, you can't supply a value for this option. Instead, - // the system inserts a placeholder value of 1 . This value doesn't affect the - // running of your task. - MaxConcurrency *string - - // The new MaxErrors value to specify. MaxErrors is the maximum number of errors - // that are allowed before the task stops being scheduled. Although this element is - // listed as "Required: No", a value can be omitted only when you are registering - // or updating a targetless task (https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-targetless-tasks.html) - // You must provide a value in all other cases. For maintenance window tasks - // without a target specified, you can't supply a value for this option. Instead, - // the system inserts a placeholder value of 1 . This value doesn't affect the - // running of your task. - MaxErrors *string - - // The new task name to specify. - Name *string - - // The new task priority to specify. The lower the number, the higher the - // priority. Tasks that have the same priority are scheduled in parallel. - Priority *int32 - - // If True, then all fields that are required by the - // RegisterTaskWithMaintenanceWindow operation are also required for this API - // request. Optional fields that aren't specified are set to null. - Replace *bool - - // The Amazon Resource Name (ARN) of the IAM service role for Amazon Web Services - // Systems Manager to assume when running a maintenance window task. If you do not - // specify a service role ARN, Systems Manager uses your account's service-linked - // role. If no service-linked role for Systems Manager exists in your account, it - // is created when you run RegisterTaskWithMaintenanceWindow . For more - // information, see the following topics in the in the Amazon Web Services Systems - // Manager User Guide: - // - Using service-linked roles for Systems Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/using-service-linked-roles.html#slr-permissions) - // - Should I use a service-linked role or a custom service role to run - // maintenance window tasks? (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-maintenance-permissions.html#maintenance-window-tasks-service-role) - ServiceRoleArn *string - - // The targets (either managed nodes or tags) to modify. Managed nodes are - // specified using the format Key=instanceids,Values=instanceID_1,instanceID_2 . - // Tags are specified using the format Key=tag_name,Values=tag_value . One or more - // targets must be specified for maintenance window Run Command-type tasks. - // Depending on the task, targets are optional for other maintenance window task - // types (Automation, Lambda, and Step Functions). For more information about - // running tasks that don't specify targets, see Registering maintenance window - // tasks without targets (https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-targetless-tasks.html) - // in the Amazon Web Services Systems Manager User Guide. - Targets []types.Target - - // The task ARN to modify. - TaskArn *string - - // The parameters that the task should use during execution. Populate only the - // fields that match the task type. All other fields should be empty. When you - // update a maintenance window task that has options specified in - // TaskInvocationParameters , you must provide again all the - // TaskInvocationParameters values that you want to retain. The values you don't - // specify again are removed. For example, suppose that when you registered a Run - // Command task, you specified TaskInvocationParameters values for Comment , - // NotificationConfig , and OutputS3BucketName . If you update the maintenance - // window task and specify only a different OutputS3BucketName value, the values - // for Comment and NotificationConfig are removed. - TaskInvocationParameters *types.MaintenanceWindowTaskInvocationParameters - - // The parameters to modify. TaskParameters has been deprecated. To specify - // parameters to pass to a task when it runs, instead use the Parameters option in - // the TaskInvocationParameters structure. For information about how Systems - // Manager handles these options for the supported maintenance window task types, - // see MaintenanceWindowTaskInvocationParameters . The map has the following - // format: Key: string, between 1 and 255 characters Value: an array of strings, - // each string is between 1 and 255 characters - TaskParameters map[string]types.MaintenanceWindowTaskParameterValueExpression - - noSmithyDocumentSerde -} - -type UpdateMaintenanceWindowTaskOutput struct { - - // The details for the CloudWatch alarm you applied to your maintenance window - // task. - AlarmConfiguration *types.AlarmConfiguration - - // The specification for whether tasks should continue to run after the cutoff - // time specified in the maintenance windows is reached. - CutoffBehavior types.MaintenanceWindowTaskCutoffBehavior - - // The updated task description. - Description *string - - // The updated logging information in Amazon S3. LoggingInfo has been deprecated. - // To specify an Amazon Simple Storage Service (Amazon S3) bucket to contain logs, - // instead use the OutputS3BucketName and OutputS3KeyPrefix options in the - // TaskInvocationParameters structure. For information about how Amazon Web - // Services Systems Manager handles these options for the supported maintenance - // window task types, see MaintenanceWindowTaskInvocationParameters . - LoggingInfo *types.LoggingInfo - - // The updated MaxConcurrency value. - MaxConcurrency *string - - // The updated MaxErrors value. - MaxErrors *string - - // The updated task name. - Name *string - - // The updated priority value. - Priority int32 - - // The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) - // service role to use to publish Amazon Simple Notification Service (Amazon SNS) - // notifications for maintenance window Run Command tasks. - ServiceRoleArn *string - - // The updated target values. - Targets []types.Target - - // The updated task ARN value. - TaskArn *string - - // The updated parameter values. - TaskInvocationParameters *types.MaintenanceWindowTaskInvocationParameters - - // The updated parameter values. TaskParameters has been deprecated. To specify - // parameters to pass to a task when it runs, instead use the Parameters option in - // the TaskInvocationParameters structure. For information about how Systems - // Manager handles these options for the supported maintenance window task types, - // see MaintenanceWindowTaskInvocationParameters . - TaskParameters map[string]types.MaintenanceWindowTaskParameterValueExpression - - // The ID of the maintenance window that was updated. - WindowId *string - - // The task ID of the maintenance window that was updated. - WindowTaskId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateMaintenanceWindowTaskMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateMaintenanceWindowTask{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateMaintenanceWindowTask{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateMaintenanceWindowTask"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateMaintenanceWindowTaskValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateMaintenanceWindowTask(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateMaintenanceWindowTask(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateMaintenanceWindowTask", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateManagedInstanceRole.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateManagedInstanceRole.go deleted file mode 100644 index 9cd1965b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateManagedInstanceRole.go +++ /dev/null @@ -1,145 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Changes the Identity and Access Management (IAM) role that is assigned to the -// on-premises server, edge device, or virtual machines (VM). IAM roles are first -// assigned to these hybrid nodes during the activation process. For more -// information, see CreateActivation . -func (c *Client) UpdateManagedInstanceRole(ctx context.Context, params *UpdateManagedInstanceRoleInput, optFns ...func(*Options)) (*UpdateManagedInstanceRoleOutput, error) { - if params == nil { - params = &UpdateManagedInstanceRoleInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateManagedInstanceRole", params, optFns, c.addOperationUpdateManagedInstanceRoleMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateManagedInstanceRoleOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateManagedInstanceRoleInput struct { - - // The name of the Identity and Access Management (IAM) role that you want to - // assign to the managed node. This IAM role must provide AssumeRole permissions - // for the Amazon Web Services Systems Manager service principal ssm.amazonaws.com - // . For more information, see Create an IAM service role for a hybrid environment (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-service-role.html) - // in the Amazon Web Services Systems Manager User Guide. You can't specify an IAM - // service-linked role for this parameter. You must create a unique role. - // - // This member is required. - IamRole *string - - // The ID of the managed node where you want to update the role. - // - // This member is required. - InstanceId *string - - noSmithyDocumentSerde -} - -type UpdateManagedInstanceRoleOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateManagedInstanceRoleMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateManagedInstanceRole{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateManagedInstanceRole{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateManagedInstanceRole"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateManagedInstanceRoleValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateManagedInstanceRole(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateManagedInstanceRole(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateManagedInstanceRole", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateOpsItem.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateOpsItem.go deleted file mode 100644 index 6203ad28..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateOpsItem.go +++ /dev/null @@ -1,215 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Edit or change an OpsItem. You must have permission in Identity and Access -// Management (IAM) to update an OpsItem. For more information, see Set up -// OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-setup.html) -// in the Amazon Web Services Systems Manager User Guide. Operations engineers and -// IT professionals use Amazon Web Services Systems Manager OpsCenter to view, -// investigate, and remediate operational issues impacting the performance and -// health of their Amazon Web Services resources. For more information, see -// OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) -// in the Amazon Web Services Systems Manager User Guide. -func (c *Client) UpdateOpsItem(ctx context.Context, params *UpdateOpsItemInput, optFns ...func(*Options)) (*UpdateOpsItemOutput, error) { - if params == nil { - params = &UpdateOpsItemInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateOpsItem", params, optFns, c.addOperationUpdateOpsItemMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateOpsItemOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateOpsItemInput struct { - - // The ID of the OpsItem. - // - // This member is required. - OpsItemId *string - - // The time a runbook workflow ended. Currently reported only for the OpsItem type - // /aws/changerequest . - ActualEndTime *time.Time - - // The time a runbook workflow started. Currently reported only for the OpsItem - // type /aws/changerequest . - ActualStartTime *time.Time - - // Specify a new category for an OpsItem. - Category *string - - // User-defined text that contains information about the OpsItem, in Markdown - // format. - Description *string - - // The Amazon Resource Name (ARN) of an SNS topic where notifications are sent - // when this OpsItem is edited or changed. - Notifications []types.OpsItemNotification - - // Add new keys or edit existing key-value pairs of the OperationalData map in the - // OpsItem object. Operational data is custom data that provides useful reference - // details about the OpsItem. For example, you can specify log files, error - // strings, license keys, troubleshooting tips, or other relevant data. You enter - // operational data as key-value pairs. The key has a maximum length of 128 - // characters. The value has a maximum size of 20 KB. Operational data keys can't - // begin with the following: amazon , aws , amzn , ssm , /amazon , /aws , /amzn , - // /ssm . You can choose to make the data searchable by other users in the account - // or you can restrict search access. Searchable data means that all users with - // access to the OpsItem Overview page (as provided by the DescribeOpsItems API - // operation) can view and search on the specified data. Operational data that - // isn't searchable is only viewable by users who have access to the OpsItem (as - // provided by the GetOpsItem API operation). Use the /aws/resources key in - // OperationalData to specify a related resource in the request. Use the - // /aws/automations key in OperationalData to associate an Automation runbook with - // the OpsItem. To view Amazon Web Services CLI example commands that use these - // keys, see Creating OpsItems manually (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-manually-create-OpsItems.html) - // in the Amazon Web Services Systems Manager User Guide. - OperationalData map[string]types.OpsItemDataValue - - // Keys that you want to remove from the OperationalData map. - OperationalDataToDelete []string - - // The OpsItem Amazon Resource Name (ARN). - OpsItemArn *string - - // The time specified in a change request for a runbook workflow to end. Currently - // supported only for the OpsItem type /aws/changerequest . - PlannedEndTime *time.Time - - // The time specified in a change request for a runbook workflow to start. - // Currently supported only for the OpsItem type /aws/changerequest . - PlannedStartTime *time.Time - - // The importance of this OpsItem in relation to other OpsItems in the system. - Priority *int32 - - // One or more OpsItems that share something in common with the current OpsItems. - // For example, related OpsItems can include OpsItems with similar error messages, - // impacted resources, or statuses for the impacted resource. - RelatedOpsItems []types.RelatedOpsItem - - // Specify a new severity for an OpsItem. - Severity *string - - // The OpsItem status. Status can be Open , In Progress , or Resolved . For more - // information, see Editing OpsItem details (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems-editing-details.html) - // in the Amazon Web Services Systems Manager User Guide. - Status types.OpsItemStatus - - // A short heading that describes the nature of the OpsItem and the impacted - // resource. - Title *string - - noSmithyDocumentSerde -} - -type UpdateOpsItemOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateOpsItemMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateOpsItem{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateOpsItem{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateOpsItem"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateOpsItemValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateOpsItem(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateOpsItem(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateOpsItem", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateOpsMetadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateOpsMetadata.go deleted file mode 100644 index 2ce5ccd8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateOpsMetadata.go +++ /dev/null @@ -1,144 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Amazon Web Services Systems Manager calls this API operation when you edit -// OpsMetadata in Application Manager. -func (c *Client) UpdateOpsMetadata(ctx context.Context, params *UpdateOpsMetadataInput, optFns ...func(*Options)) (*UpdateOpsMetadataOutput, error) { - if params == nil { - params = &UpdateOpsMetadataInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateOpsMetadata", params, optFns, c.addOperationUpdateOpsMetadataMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateOpsMetadataOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateOpsMetadataInput struct { - - // The Amazon Resource Name (ARN) of the OpsMetadata Object to update. - // - // This member is required. - OpsMetadataArn *string - - // The metadata keys to delete from the OpsMetadata object. - KeysToDelete []string - - // Metadata to add to an OpsMetadata object. - MetadataToUpdate map[string]types.MetadataValue - - noSmithyDocumentSerde -} - -type UpdateOpsMetadataOutput struct { - - // The Amazon Resource Name (ARN) of the OpsMetadata Object that was updated. - OpsMetadataArn *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateOpsMetadataMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateOpsMetadata{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateOpsMetadata{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateOpsMetadata"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateOpsMetadataValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateOpsMetadata(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateOpsMetadata(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateOpsMetadata", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdatePatchBaseline.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdatePatchBaseline.go deleted file mode 100644 index 656174ab..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdatePatchBaseline.go +++ /dev/null @@ -1,241 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "time" -) - -// Modifies an existing patch baseline. Fields not specified in the request are -// left unchanged. For information about valid key-value pairs in PatchFilters for -// each supported operating system type, see PatchFilter . -func (c *Client) UpdatePatchBaseline(ctx context.Context, params *UpdatePatchBaselineInput, optFns ...func(*Options)) (*UpdatePatchBaselineOutput, error) { - if params == nil { - params = &UpdatePatchBaselineInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdatePatchBaseline", params, optFns, c.addOperationUpdatePatchBaselineMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdatePatchBaselineOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdatePatchBaselineInput struct { - - // The ID of the patch baseline to update. - // - // This member is required. - BaselineId *string - - // A set of rules used to include patches in the baseline. - ApprovalRules *types.PatchRuleGroup - - // A list of explicitly approved patches for the baseline. For information about - // accepted formats for lists of approved patches and rejected patches, see About - // package name formats for approved and rejected patch lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) - // in the Amazon Web Services Systems Manager User Guide. - ApprovedPatches []string - - // Assigns a new compliance severity level to an existing patch baseline. - ApprovedPatchesComplianceLevel types.PatchComplianceLevel - - // Indicates whether the list of approved patches includes non-security updates - // that should be applied to the managed nodes. The default value is false . - // Applies to Linux managed nodes only. - ApprovedPatchesEnableNonSecurity *bool - - // A description of the patch baseline. - Description *string - - // A set of global filters used to include patches in the baseline. - GlobalFilters *types.PatchFilterGroup - - // The name of the patch baseline. - Name *string - - // A list of explicitly rejected patches for the baseline. For information about - // accepted formats for lists of approved patches and rejected patches, see About - // package name formats for approved and rejected patch lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) - // in the Amazon Web Services Systems Manager User Guide. - RejectedPatches []string - - // The action for Patch Manager to take on patches included in the RejectedPackages - // list. - // - ALLOW_AS_DEPENDENCY : A package in the Rejected patches list is installed - // only if it is a dependency of another package. It is considered compliant with - // the patch baseline, and its status is reported as InstalledOther . This is the - // default action if no option is specified. - // - BLOCK : Packages in the RejectedPatches list, and packages that include them - // as dependencies, aren't installed under any circumstances. If a package was - // installed before it was added to the Rejected patches list, it is considered - // non-compliant with the patch baseline, and its status is reported as - // InstalledRejected . - RejectedPatchesAction types.PatchAction - - // If True, then all fields that are required by the CreatePatchBaseline operation - // are also required for this API request. Optional fields that aren't specified - // are set to null. - Replace *bool - - // Information about the patches to use to update the managed nodes, including - // target operating systems and source repositories. Applies to Linux managed nodes - // only. - Sources []types.PatchSource - - noSmithyDocumentSerde -} - -type UpdatePatchBaselineOutput struct { - - // A set of rules used to include patches in the baseline. - ApprovalRules *types.PatchRuleGroup - - // A list of explicitly approved patches for the baseline. - ApprovedPatches []string - - // The compliance severity level assigned to the patch baseline after the update - // completed. - ApprovedPatchesComplianceLevel types.PatchComplianceLevel - - // Indicates whether the list of approved patches includes non-security updates - // that should be applied to the managed nodes. The default value is false . - // Applies to Linux managed nodes only. - ApprovedPatchesEnableNonSecurity *bool - - // The ID of the deleted patch baseline. - BaselineId *string - - // The date when the patch baseline was created. - CreatedDate *time.Time - - // A description of the patch baseline. - Description *string - - // A set of global filters used to exclude patches from the baseline. - GlobalFilters *types.PatchFilterGroup - - // The date when the patch baseline was last modified. - ModifiedDate *time.Time - - // The name of the patch baseline. - Name *string - - // The operating system rule used by the updated patch baseline. - OperatingSystem types.OperatingSystem - - // A list of explicitly rejected patches for the baseline. - RejectedPatches []string - - // The action specified to take on patches included in the RejectedPatches list. A - // patch can be allowed only if it is a dependency of another package, or blocked - // entirely along with packages that include it as a dependency. - RejectedPatchesAction types.PatchAction - - // Information about the patches to use to update the managed nodes, including - // target operating systems and source repositories. Applies to Linux managed nodes - // only. - Sources []types.PatchSource - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdatePatchBaselineMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdatePatchBaseline{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdatePatchBaseline{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdatePatchBaseline"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdatePatchBaselineValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdatePatchBaseline(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdatePatchBaseline(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdatePatchBaseline", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateResourceDataSync.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateResourceDataSync.go deleted file mode 100644 index a7412206..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateResourceDataSync.go +++ /dev/null @@ -1,150 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Update a resource data sync. After you create a resource data sync for a -// Region, you can't change the account options for that sync. For example, if you -// create a sync in the us-east-2 (Ohio) Region and you choose the Include only -// the current account option, you can't edit that sync later and choose the -// Include all accounts from my Organizations configuration option. Instead, you -// must delete the first resource data sync, and create a new one. This API -// operation only supports a resource data sync that was created with a -// SyncFromSource SyncType . -func (c *Client) UpdateResourceDataSync(ctx context.Context, params *UpdateResourceDataSyncInput, optFns ...func(*Options)) (*UpdateResourceDataSyncOutput, error) { - if params == nil { - params = &UpdateResourceDataSyncInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateResourceDataSync", params, optFns, c.addOperationUpdateResourceDataSyncMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateResourceDataSyncOutput) - out.ResultMetadata = metadata - return out, nil -} - -type UpdateResourceDataSyncInput struct { - - // The name of the resource data sync you want to update. - // - // This member is required. - SyncName *string - - // Specify information about the data sources to synchronize. - // - // This member is required. - SyncSource *types.ResourceDataSyncSource - - // The type of resource data sync. The supported SyncType is SyncFromSource. - // - // This member is required. - SyncType *string - - noSmithyDocumentSerde -} - -type UpdateResourceDataSyncOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateResourceDataSyncMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateResourceDataSync{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateResourceDataSync{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateResourceDataSync"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateResourceDataSyncValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateResourceDataSync(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateResourceDataSync(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateResourceDataSync", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateServiceSetting.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateServiceSetting.go deleted file mode 100644 index 75e4928f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/api_op_UpdateServiceSetting.go +++ /dev/null @@ -1,178 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// ServiceSetting is an account-level setting for an Amazon Web Services service. -// This setting defines how a user interacts with or uses a service or a feature of -// a service. For example, if an Amazon Web Services service charges money to the -// account based on feature or service usage, then the Amazon Web Services service -// team might create a default setting of "false". This means the user can't use -// this feature unless they change the setting to "true" and intentionally opt in -// for a paid feature. Services map a SettingId object to a setting value. Amazon -// Web Services services teams define the default value for a SettingId . You can't -// create a new SettingId , but you can overwrite the default value if you have the -// ssm:UpdateServiceSetting permission for the setting. Use the GetServiceSetting -// API operation to view the current value. Or, use the ResetServiceSetting to -// change the value back to the original value defined by the Amazon Web Services -// service team. Update the service setting for the account. -func (c *Client) UpdateServiceSetting(ctx context.Context, params *UpdateServiceSettingInput, optFns ...func(*Options)) (*UpdateServiceSettingOutput, error) { - if params == nil { - params = &UpdateServiceSettingInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "UpdateServiceSetting", params, optFns, c.addOperationUpdateServiceSettingMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*UpdateServiceSettingOutput) - out.ResultMetadata = metadata - return out, nil -} - -// The request body of the UpdateServiceSetting API operation. -type UpdateServiceSettingInput struct { - - // The Amazon Resource Name (ARN) of the service setting to update. For example, - // arn:aws:ssm:us-east-1:111122223333:servicesetting/ssm/parameter-store/high-throughput-enabled - // . The setting ID can be one of the following. - // - /ssm/managed-instance/default-ec2-instance-management-role - // - /ssm/automation/customer-script-log-destination - // - /ssm/automation/customer-script-log-group-name - // - /ssm/documents/console/public-sharing-permission - // - /ssm/managed-instance/activation-tier - // - /ssm/opsinsights/opscenter - // - /ssm/parameter-store/default-parameter-tier - // - /ssm/parameter-store/high-throughput-enabled - // Permissions to update the - // /ssm/managed-instance/default-ec2-instance-management-role setting should only - // be provided to administrators. Implement least privilege access when allowing - // individuals to configure or modify the Default Host Management Configuration. - // - // This member is required. - SettingId *string - - // The new value to specify for the service setting. The following list specifies - // the available values for each setting. - // - For /ssm/managed-instance/default-ec2-instance-management-role , enter the - // name of an IAM role. - // - For /ssm/automation/customer-script-log-destination , enter CloudWatch . - // - For /ssm/automation/customer-script-log-group-name , enter the name of an - // Amazon CloudWatch Logs log group. - // - For /ssm/documents/console/public-sharing-permission , enter Enable or - // Disable . - // - For /ssm/managed-instance/activation-tier , enter standard or advanced . - // - For /ssm/opsinsights/opscenter , enter Enabled or Disabled . - // - For /ssm/parameter-store/default-parameter-tier , enter Standard , Advanced - // , or Intelligent-Tiering - // - For /ssm/parameter-store/high-throughput-enabled , enter true or false . - // - // This member is required. - SettingValue *string - - noSmithyDocumentSerde -} - -// The result body of the UpdateServiceSetting API operation. -type UpdateServiceSettingOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationUpdateServiceSettingMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsjson11_serializeOpUpdateServiceSetting{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsjson11_deserializeOpUpdateServiceSetting{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "UpdateServiceSetting"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpUpdateServiceSettingValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opUpdateServiceSetting(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opUpdateServiceSetting(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "UpdateServiceSetting", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/auth.go deleted file mode 100644 index bad85d05..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/auth.go +++ /dev/null @@ -1,284 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -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/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -func bindAuthParamsRegion(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(operation string, input interface{}, options Options) *AuthResolverParameters { - params := &AuthResolverParameters{ - Operation: operation, - } - - bindAuthParamsRegion(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, "ssm") - 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, -) { - params := bindAuthResolverParams(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) - 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, -) { - rscheme := getResolvedAuthScheme(ctx) - 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 := resolver.GetIdentity(ctx, rscheme.IdentityProperties) - if err != nil { - return out, metadata, fmt.Errorf("get identity: %w", err) - } - - ctx = setIdentity(ctx, identity) - 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 { -} - -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, -) { - 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") - } - - if err := signer.SignRequest(ctx, req, identity, rscheme.SignerProperties); err != nil { - return out, metadata, fmt.Errorf("sign request: %w", err) - } - - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/deserializers.go deleted file mode 100644 index 048cc313..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/deserializers.go +++ /dev/null @@ -1,48904 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "bytes" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws/protocol/restjson" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - smithy "github.com/aws/smithy-go" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/ptr" - smithytime "github.com/aws/smithy-go/time" - smithyhttp "github.com/aws/smithy-go/transport/http" - "io" - "strings" -) - -type awsAwsjson11_deserializeOpAddTagsToResource struct { -} - -func (*awsAwsjson11_deserializeOpAddTagsToResource) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpAddTagsToResource) 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 - } - - 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_deserializeOpErrorAddTagsToResource(response, &metadata) - } - output := &AddTagsToResourceOutput{} - 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_deserializeOpDocumentAddTagsToResourceOutput(&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_deserializeOpErrorAddTagsToResource(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidResourceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceId(response, errorBody) - - case strings.EqualFold("InvalidResourceType", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceType(response, errorBody) - - case strings.EqualFold("TooManyTagsError", errorCode): - return awsAwsjson11_deserializeErrorTooManyTagsError(response, errorBody) - - case strings.EqualFold("TooManyUpdates", errorCode): - return awsAwsjson11_deserializeErrorTooManyUpdates(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpAssociateOpsItemRelatedItem struct { -} - -func (*awsAwsjson11_deserializeOpAssociateOpsItemRelatedItem) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpAssociateOpsItemRelatedItem) 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 - } - - 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_deserializeOpErrorAssociateOpsItemRelatedItem(response, &metadata) - } - output := &AssociateOpsItemRelatedItemOutput{} - 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_deserializeOpDocumentAssociateOpsItemRelatedItemOutput(&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_deserializeOpErrorAssociateOpsItemRelatedItem(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsItemConflictException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemConflictException(response, errorBody) - - case strings.EqualFold("OpsItemInvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemInvalidParameterException(response, errorBody) - - case strings.EqualFold("OpsItemLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemLimitExceededException(response, errorBody) - - case strings.EqualFold("OpsItemNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemNotFoundException(response, errorBody) - - case strings.EqualFold("OpsItemRelatedItemAlreadyExistsException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemRelatedItemAlreadyExistsException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCancelCommand struct { -} - -func (*awsAwsjson11_deserializeOpCancelCommand) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCancelCommand) 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 - } - - 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_deserializeOpErrorCancelCommand(response, &metadata) - } - output := &CancelCommandOutput{} - 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_deserializeOpDocumentCancelCommandOutput(&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_deserializeOpErrorCancelCommand(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DuplicateInstanceId", errorCode): - return awsAwsjson11_deserializeErrorDuplicateInstanceId(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidCommandId", errorCode): - return awsAwsjson11_deserializeErrorInvalidCommandId(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCancelMaintenanceWindowExecution struct { -} - -func (*awsAwsjson11_deserializeOpCancelMaintenanceWindowExecution) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCancelMaintenanceWindowExecution) 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 - } - - 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_deserializeOpErrorCancelMaintenanceWindowExecution(response, &metadata) - } - output := &CancelMaintenanceWindowExecutionOutput{} - 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_deserializeOpDocumentCancelMaintenanceWindowExecutionOutput(&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_deserializeOpErrorCancelMaintenanceWindowExecution(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCreateActivation struct { -} - -func (*awsAwsjson11_deserializeOpCreateActivation) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCreateActivation) 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 - } - - 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_deserializeOpErrorCreateActivation(response, &metadata) - } - output := &CreateActivationOutput{} - 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_deserializeOpDocumentCreateActivationOutput(&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_deserializeOpErrorCreateActivation(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidParameters", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameters(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCreateAssociation struct { -} - -func (*awsAwsjson11_deserializeOpCreateAssociation) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCreateAssociation) 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 - } - - 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_deserializeOpErrorCreateAssociation(response, &metadata) - } - output := &CreateAssociationOutput{} - 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_deserializeOpDocumentCreateAssociationOutput(&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_deserializeOpErrorCreateAssociation(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AssociationAlreadyExists", errorCode): - return awsAwsjson11_deserializeErrorAssociationAlreadyExists(response, errorBody) - - case strings.EqualFold("AssociationLimitExceeded", errorCode): - return awsAwsjson11_deserializeErrorAssociationLimitExceeded(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentVersion(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidOutputLocation", errorCode): - return awsAwsjson11_deserializeErrorInvalidOutputLocation(response, errorBody) - - case strings.EqualFold("InvalidParameters", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameters(response, errorBody) - - case strings.EqualFold("InvalidSchedule", errorCode): - return awsAwsjson11_deserializeErrorInvalidSchedule(response, errorBody) - - case strings.EqualFold("InvalidTag", errorCode): - return awsAwsjson11_deserializeErrorInvalidTag(response, errorBody) - - case strings.EqualFold("InvalidTarget", errorCode): - return awsAwsjson11_deserializeErrorInvalidTarget(response, errorBody) - - case strings.EqualFold("InvalidTargetMaps", errorCode): - return awsAwsjson11_deserializeErrorInvalidTargetMaps(response, errorBody) - - case strings.EqualFold("UnsupportedPlatformType", errorCode): - return awsAwsjson11_deserializeErrorUnsupportedPlatformType(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCreateAssociationBatch struct { -} - -func (*awsAwsjson11_deserializeOpCreateAssociationBatch) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCreateAssociationBatch) 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 - } - - 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_deserializeOpErrorCreateAssociationBatch(response, &metadata) - } - output := &CreateAssociationBatchOutput{} - 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_deserializeOpDocumentCreateAssociationBatchOutput(&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_deserializeOpErrorCreateAssociationBatch(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AssociationLimitExceeded", errorCode): - return awsAwsjson11_deserializeErrorAssociationLimitExceeded(response, errorBody) - - case strings.EqualFold("DuplicateInstanceId", errorCode): - return awsAwsjson11_deserializeErrorDuplicateInstanceId(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentVersion(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidOutputLocation", errorCode): - return awsAwsjson11_deserializeErrorInvalidOutputLocation(response, errorBody) - - case strings.EqualFold("InvalidParameters", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameters(response, errorBody) - - case strings.EqualFold("InvalidSchedule", errorCode): - return awsAwsjson11_deserializeErrorInvalidSchedule(response, errorBody) - - case strings.EqualFold("InvalidTarget", errorCode): - return awsAwsjson11_deserializeErrorInvalidTarget(response, errorBody) - - case strings.EqualFold("InvalidTargetMaps", errorCode): - return awsAwsjson11_deserializeErrorInvalidTargetMaps(response, errorBody) - - case strings.EqualFold("UnsupportedPlatformType", errorCode): - return awsAwsjson11_deserializeErrorUnsupportedPlatformType(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCreateDocument struct { -} - -func (*awsAwsjson11_deserializeOpCreateDocument) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCreateDocument) 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 - } - - 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_deserializeOpErrorCreateDocument(response, &metadata) - } - output := &CreateDocumentOutput{} - 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_deserializeOpDocumentCreateDocumentOutput(&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_deserializeOpErrorCreateDocument(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DocumentAlreadyExists", errorCode): - return awsAwsjson11_deserializeErrorDocumentAlreadyExists(response, errorBody) - - case strings.EqualFold("DocumentLimitExceeded", errorCode): - return awsAwsjson11_deserializeErrorDocumentLimitExceeded(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocumentContent", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentContent(response, errorBody) - - case strings.EqualFold("InvalidDocumentSchemaVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentSchemaVersion(response, errorBody) - - case strings.EqualFold("MaxDocumentSizeExceeded", errorCode): - return awsAwsjson11_deserializeErrorMaxDocumentSizeExceeded(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCreateMaintenanceWindow struct { -} - -func (*awsAwsjson11_deserializeOpCreateMaintenanceWindow) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCreateMaintenanceWindow) 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 - } - - 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_deserializeOpErrorCreateMaintenanceWindow(response, &metadata) - } - output := &CreateMaintenanceWindowOutput{} - 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_deserializeOpDocumentCreateMaintenanceWindowOutput(&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_deserializeOpErrorCreateMaintenanceWindow(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("IdempotentParameterMismatch", errorCode): - return awsAwsjson11_deserializeErrorIdempotentParameterMismatch(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ResourceLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorResourceLimitExceededException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCreateOpsItem struct { -} - -func (*awsAwsjson11_deserializeOpCreateOpsItem) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCreateOpsItem) 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 - } - - 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_deserializeOpErrorCreateOpsItem(response, &metadata) - } - output := &CreateOpsItemOutput{} - 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_deserializeOpDocumentCreateOpsItemOutput(&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_deserializeOpErrorCreateOpsItem(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsItemAccessDeniedException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemAccessDeniedException(response, errorBody) - - case strings.EqualFold("OpsItemAlreadyExistsException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemAlreadyExistsException(response, errorBody) - - case strings.EqualFold("OpsItemInvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemInvalidParameterException(response, errorBody) - - case strings.EqualFold("OpsItemLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemLimitExceededException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCreateOpsMetadata struct { -} - -func (*awsAwsjson11_deserializeOpCreateOpsMetadata) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCreateOpsMetadata) 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 - } - - 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_deserializeOpErrorCreateOpsMetadata(response, &metadata) - } - output := &CreateOpsMetadataOutput{} - 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_deserializeOpDocumentCreateOpsMetadataOutput(&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_deserializeOpErrorCreateOpsMetadata(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsMetadataAlreadyExistsException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataAlreadyExistsException(response, errorBody) - - case strings.EqualFold("OpsMetadataInvalidArgumentException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataInvalidArgumentException(response, errorBody) - - case strings.EqualFold("OpsMetadataLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataLimitExceededException(response, errorBody) - - case strings.EqualFold("OpsMetadataTooManyUpdatesException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataTooManyUpdatesException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCreatePatchBaseline struct { -} - -func (*awsAwsjson11_deserializeOpCreatePatchBaseline) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCreatePatchBaseline) 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 - } - - 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_deserializeOpErrorCreatePatchBaseline(response, &metadata) - } - output := &CreatePatchBaselineOutput{} - 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_deserializeOpDocumentCreatePatchBaselineOutput(&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_deserializeOpErrorCreatePatchBaseline(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("IdempotentParameterMismatch", errorCode): - return awsAwsjson11_deserializeErrorIdempotentParameterMismatch(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ResourceLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorResourceLimitExceededException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpCreateResourceDataSync struct { -} - -func (*awsAwsjson11_deserializeOpCreateResourceDataSync) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpCreateResourceDataSync) 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 - } - - 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_deserializeOpErrorCreateResourceDataSync(response, &metadata) - } - output := &CreateResourceDataSyncOutput{} - 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_deserializeOpDocumentCreateResourceDataSyncOutput(&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_deserializeOpErrorCreateResourceDataSync(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ResourceDataSyncAlreadyExistsException", errorCode): - return awsAwsjson11_deserializeErrorResourceDataSyncAlreadyExistsException(response, errorBody) - - case strings.EqualFold("ResourceDataSyncCountExceededException", errorCode): - return awsAwsjson11_deserializeErrorResourceDataSyncCountExceededException(response, errorBody) - - case strings.EqualFold("ResourceDataSyncInvalidConfigurationException", errorCode): - return awsAwsjson11_deserializeErrorResourceDataSyncInvalidConfigurationException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteActivation struct { -} - -func (*awsAwsjson11_deserializeOpDeleteActivation) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteActivation) 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 - } - - 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_deserializeOpErrorDeleteActivation(response, &metadata) - } - output := &DeleteActivationOutput{} - 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_deserializeOpDocumentDeleteActivationOutput(&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_deserializeOpErrorDeleteActivation(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidActivation", errorCode): - return awsAwsjson11_deserializeErrorInvalidActivation(response, errorBody) - - case strings.EqualFold("InvalidActivationId", errorCode): - return awsAwsjson11_deserializeErrorInvalidActivationId(response, errorBody) - - case strings.EqualFold("TooManyUpdates", errorCode): - return awsAwsjson11_deserializeErrorTooManyUpdates(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteAssociation struct { -} - -func (*awsAwsjson11_deserializeOpDeleteAssociation) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteAssociation) 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 - } - - 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_deserializeOpErrorDeleteAssociation(response, &metadata) - } - output := &DeleteAssociationOutput{} - 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_deserializeOpDocumentDeleteAssociationOutput(&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_deserializeOpErrorDeleteAssociation(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AssociationDoesNotExist", errorCode): - return awsAwsjson11_deserializeErrorAssociationDoesNotExist(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("TooManyUpdates", errorCode): - return awsAwsjson11_deserializeErrorTooManyUpdates(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteDocument struct { -} - -func (*awsAwsjson11_deserializeOpDeleteDocument) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteDocument) 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 - } - - 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_deserializeOpErrorDeleteDocument(response, &metadata) - } - output := &DeleteDocumentOutput{} - 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_deserializeOpDocumentDeleteDocumentOutput(&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_deserializeOpErrorDeleteDocument(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AssociatedInstances", errorCode): - return awsAwsjson11_deserializeErrorAssociatedInstances(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentOperation", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentOperation(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteInventory struct { -} - -func (*awsAwsjson11_deserializeOpDeleteInventory) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteInventory) 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 - } - - 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_deserializeOpErrorDeleteInventory(response, &metadata) - } - output := &DeleteInventoryOutput{} - 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_deserializeOpDocumentDeleteInventoryOutput(&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_deserializeOpErrorDeleteInventory(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDeleteInventoryParametersException", errorCode): - return awsAwsjson11_deserializeErrorInvalidDeleteInventoryParametersException(response, errorBody) - - case strings.EqualFold("InvalidInventoryRequestException", errorCode): - return awsAwsjson11_deserializeErrorInvalidInventoryRequestException(response, errorBody) - - case strings.EqualFold("InvalidOptionException", errorCode): - return awsAwsjson11_deserializeErrorInvalidOptionException(response, errorBody) - - case strings.EqualFold("InvalidTypeNameException", errorCode): - return awsAwsjson11_deserializeErrorInvalidTypeNameException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteMaintenanceWindow struct { -} - -func (*awsAwsjson11_deserializeOpDeleteMaintenanceWindow) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteMaintenanceWindow) 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 - } - - 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_deserializeOpErrorDeleteMaintenanceWindow(response, &metadata) - } - output := &DeleteMaintenanceWindowOutput{} - 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_deserializeOpDocumentDeleteMaintenanceWindowOutput(&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_deserializeOpErrorDeleteMaintenanceWindow(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteOpsItem struct { -} - -func (*awsAwsjson11_deserializeOpDeleteOpsItem) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteOpsItem) 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 - } - - 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_deserializeOpErrorDeleteOpsItem(response, &metadata) - } - output := &DeleteOpsItemOutput{} - 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_deserializeOpDocumentDeleteOpsItemOutput(&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_deserializeOpErrorDeleteOpsItem(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsItemInvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemInvalidParameterException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteOpsMetadata struct { -} - -func (*awsAwsjson11_deserializeOpDeleteOpsMetadata) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteOpsMetadata) 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 - } - - 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_deserializeOpErrorDeleteOpsMetadata(response, &metadata) - } - output := &DeleteOpsMetadataOutput{} - 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_deserializeOpDocumentDeleteOpsMetadataOutput(&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_deserializeOpErrorDeleteOpsMetadata(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsMetadataInvalidArgumentException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataInvalidArgumentException(response, errorBody) - - case strings.EqualFold("OpsMetadataNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteParameter struct { -} - -func (*awsAwsjson11_deserializeOpDeleteParameter) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteParameter) 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 - } - - 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_deserializeOpErrorDeleteParameter(response, &metadata) - } - output := &DeleteParameterOutput{} - 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_deserializeOpDocumentDeleteParameterOutput(&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_deserializeOpErrorDeleteParameter(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ParameterNotFound", errorCode): - return awsAwsjson11_deserializeErrorParameterNotFound(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteParameters struct { -} - -func (*awsAwsjson11_deserializeOpDeleteParameters) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteParameters) 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 - } - - 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_deserializeOpErrorDeleteParameters(response, &metadata) - } - output := &DeleteParametersOutput{} - 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_deserializeOpDocumentDeleteParametersOutput(&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_deserializeOpErrorDeleteParameters(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeletePatchBaseline struct { -} - -func (*awsAwsjson11_deserializeOpDeletePatchBaseline) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeletePatchBaseline) 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 - } - - 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_deserializeOpErrorDeletePatchBaseline(response, &metadata) - } - output := &DeletePatchBaselineOutput{} - 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_deserializeOpDocumentDeletePatchBaselineOutput(&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_deserializeOpErrorDeletePatchBaseline(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ResourceInUseException", errorCode): - return awsAwsjson11_deserializeErrorResourceInUseException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteResourceDataSync struct { -} - -func (*awsAwsjson11_deserializeOpDeleteResourceDataSync) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteResourceDataSync) 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 - } - - 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_deserializeOpErrorDeleteResourceDataSync(response, &metadata) - } - output := &DeleteResourceDataSyncOutput{} - 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_deserializeOpDocumentDeleteResourceDataSyncOutput(&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_deserializeOpErrorDeleteResourceDataSync(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ResourceDataSyncInvalidConfigurationException", errorCode): - return awsAwsjson11_deserializeErrorResourceDataSyncInvalidConfigurationException(response, errorBody) - - case strings.EqualFold("ResourceDataSyncNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceDataSyncNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeleteResourcePolicy struct { -} - -func (*awsAwsjson11_deserializeOpDeleteResourcePolicy) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeleteResourcePolicy) 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 - } - - 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_deserializeOpErrorDeleteResourcePolicy(response, &metadata) - } - output := &DeleteResourcePolicyOutput{} - 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_deserializeOpDocumentDeleteResourcePolicyOutput(&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_deserializeOpErrorDeleteResourcePolicy(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ResourcePolicyConflictException", errorCode): - return awsAwsjson11_deserializeErrorResourcePolicyConflictException(response, errorBody) - - case strings.EqualFold("ResourcePolicyInvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorResourcePolicyInvalidParameterException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeregisterManagedInstance struct { -} - -func (*awsAwsjson11_deserializeOpDeregisterManagedInstance) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeregisterManagedInstance) 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 - } - - 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_deserializeOpErrorDeregisterManagedInstance(response, &metadata) - } - output := &DeregisterManagedInstanceOutput{} - 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_deserializeOpDocumentDeregisterManagedInstanceOutput(&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_deserializeOpErrorDeregisterManagedInstance(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeregisterPatchBaselineForPatchGroup struct { -} - -func (*awsAwsjson11_deserializeOpDeregisterPatchBaselineForPatchGroup) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeregisterPatchBaselineForPatchGroup) 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 - } - - 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_deserializeOpErrorDeregisterPatchBaselineForPatchGroup(response, &metadata) - } - output := &DeregisterPatchBaselineForPatchGroupOutput{} - 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_deserializeOpDocumentDeregisterPatchBaselineForPatchGroupOutput(&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_deserializeOpErrorDeregisterPatchBaselineForPatchGroup(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidResourceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceId(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeregisterTargetFromMaintenanceWindow struct { -} - -func (*awsAwsjson11_deserializeOpDeregisterTargetFromMaintenanceWindow) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeregisterTargetFromMaintenanceWindow) 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 - } - - 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_deserializeOpErrorDeregisterTargetFromMaintenanceWindow(response, &metadata) - } - output := &DeregisterTargetFromMaintenanceWindowOutput{} - 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_deserializeOpDocumentDeregisterTargetFromMaintenanceWindowOutput(&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_deserializeOpErrorDeregisterTargetFromMaintenanceWindow(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("TargetInUseException", errorCode): - return awsAwsjson11_deserializeErrorTargetInUseException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDeregisterTaskFromMaintenanceWindow struct { -} - -func (*awsAwsjson11_deserializeOpDeregisterTaskFromMaintenanceWindow) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDeregisterTaskFromMaintenanceWindow) 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 - } - - 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_deserializeOpErrorDeregisterTaskFromMaintenanceWindow(response, &metadata) - } - output := &DeregisterTaskFromMaintenanceWindowOutput{} - 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_deserializeOpDocumentDeregisterTaskFromMaintenanceWindowOutput(&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_deserializeOpErrorDeregisterTaskFromMaintenanceWindow(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeActivations struct { -} - -func (*awsAwsjson11_deserializeOpDescribeActivations) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeActivations) 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 - } - - 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_deserializeOpErrorDescribeActivations(response, &metadata) - } - output := &DescribeActivationsOutput{} - 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_deserializeOpDocumentDescribeActivationsOutput(&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_deserializeOpErrorDescribeActivations(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilter", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilter(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeAssociation struct { -} - -func (*awsAwsjson11_deserializeOpDescribeAssociation) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeAssociation) 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 - } - - 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_deserializeOpErrorDescribeAssociation(response, &metadata) - } - output := &DescribeAssociationOutput{} - 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_deserializeOpDocumentDescribeAssociationOutput(&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_deserializeOpErrorDescribeAssociation(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AssociationDoesNotExist", errorCode): - return awsAwsjson11_deserializeErrorAssociationDoesNotExist(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidAssociationVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidAssociationVersion(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeAssociationExecutions struct { -} - -func (*awsAwsjson11_deserializeOpDescribeAssociationExecutions) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeAssociationExecutions) 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 - } - - 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_deserializeOpErrorDescribeAssociationExecutions(response, &metadata) - } - output := &DescribeAssociationExecutionsOutput{} - 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_deserializeOpDocumentDescribeAssociationExecutionsOutput(&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_deserializeOpErrorDescribeAssociationExecutions(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AssociationDoesNotExist", errorCode): - return awsAwsjson11_deserializeErrorAssociationDoesNotExist(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeAssociationExecutionTargets struct { -} - -func (*awsAwsjson11_deserializeOpDescribeAssociationExecutionTargets) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeAssociationExecutionTargets) 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 - } - - 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_deserializeOpErrorDescribeAssociationExecutionTargets(response, &metadata) - } - output := &DescribeAssociationExecutionTargetsOutput{} - 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_deserializeOpDocumentDescribeAssociationExecutionTargetsOutput(&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_deserializeOpErrorDescribeAssociationExecutionTargets(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AssociationDoesNotExist", errorCode): - return awsAwsjson11_deserializeErrorAssociationDoesNotExist(response, errorBody) - - case strings.EqualFold("AssociationExecutionDoesNotExist", errorCode): - return awsAwsjson11_deserializeErrorAssociationExecutionDoesNotExist(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeAutomationExecutions struct { -} - -func (*awsAwsjson11_deserializeOpDescribeAutomationExecutions) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeAutomationExecutions) 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 - } - - 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_deserializeOpErrorDescribeAutomationExecutions(response, &metadata) - } - output := &DescribeAutomationExecutionsOutput{} - 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_deserializeOpDocumentDescribeAutomationExecutionsOutput(&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_deserializeOpErrorDescribeAutomationExecutions(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilterKey", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterKey(response, errorBody) - - case strings.EqualFold("InvalidFilterValue", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterValue(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeAutomationStepExecutions struct { -} - -func (*awsAwsjson11_deserializeOpDescribeAutomationStepExecutions) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeAutomationStepExecutions) 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 - } - - 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_deserializeOpErrorDescribeAutomationStepExecutions(response, &metadata) - } - output := &DescribeAutomationStepExecutionsOutput{} - 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_deserializeOpDocumentDescribeAutomationStepExecutionsOutput(&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_deserializeOpErrorDescribeAutomationStepExecutions(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AutomationExecutionNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorAutomationExecutionNotFoundException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilterKey", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterKey(response, errorBody) - - case strings.EqualFold("InvalidFilterValue", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterValue(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeAvailablePatches struct { -} - -func (*awsAwsjson11_deserializeOpDescribeAvailablePatches) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeAvailablePatches) 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 - } - - 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_deserializeOpErrorDescribeAvailablePatches(response, &metadata) - } - output := &DescribeAvailablePatchesOutput{} - 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_deserializeOpDocumentDescribeAvailablePatchesOutput(&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_deserializeOpErrorDescribeAvailablePatches(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeDocument struct { -} - -func (*awsAwsjson11_deserializeOpDescribeDocument) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeDocument) 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 - } - - 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_deserializeOpErrorDescribeDocument(response, &metadata) - } - output := &DescribeDocumentOutput{} - 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_deserializeOpDocumentDescribeDocumentOutput(&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_deserializeOpErrorDescribeDocument(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentVersion(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeDocumentPermission struct { -} - -func (*awsAwsjson11_deserializeOpDescribeDocumentPermission) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeDocumentPermission) 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 - } - - 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_deserializeOpErrorDescribeDocumentPermission(response, &metadata) - } - output := &DescribeDocumentPermissionOutput{} - 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_deserializeOpDocumentDescribeDocumentPermissionOutput(&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_deserializeOpErrorDescribeDocumentPermission(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentOperation", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentOperation(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - case strings.EqualFold("InvalidPermissionType", errorCode): - return awsAwsjson11_deserializeErrorInvalidPermissionType(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeEffectiveInstanceAssociations struct { -} - -func (*awsAwsjson11_deserializeOpDescribeEffectiveInstanceAssociations) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeEffectiveInstanceAssociations) 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 - } - - 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_deserializeOpErrorDescribeEffectiveInstanceAssociations(response, &metadata) - } - output := &DescribeEffectiveInstanceAssociationsOutput{} - 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_deserializeOpDocumentDescribeEffectiveInstanceAssociationsOutput(&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_deserializeOpErrorDescribeEffectiveInstanceAssociations(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeEffectivePatchesForPatchBaseline struct { -} - -func (*awsAwsjson11_deserializeOpDescribeEffectivePatchesForPatchBaseline) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeEffectivePatchesForPatchBaseline) 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 - } - - 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_deserializeOpErrorDescribeEffectivePatchesForPatchBaseline(response, &metadata) - } - output := &DescribeEffectivePatchesForPatchBaselineOutput{} - 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_deserializeOpDocumentDescribeEffectivePatchesForPatchBaselineOutput(&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_deserializeOpErrorDescribeEffectivePatchesForPatchBaseline(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidResourceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceId(response, errorBody) - - case strings.EqualFold("UnsupportedOperatingSystem", errorCode): - return awsAwsjson11_deserializeErrorUnsupportedOperatingSystem(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeInstanceAssociationsStatus struct { -} - -func (*awsAwsjson11_deserializeOpDescribeInstanceAssociationsStatus) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeInstanceAssociationsStatus) 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 - } - - 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_deserializeOpErrorDescribeInstanceAssociationsStatus(response, &metadata) - } - output := &DescribeInstanceAssociationsStatusOutput{} - 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_deserializeOpDocumentDescribeInstanceAssociationsStatusOutput(&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_deserializeOpErrorDescribeInstanceAssociationsStatus(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeInstanceInformation struct { -} - -func (*awsAwsjson11_deserializeOpDescribeInstanceInformation) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeInstanceInformation) 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 - } - - 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_deserializeOpErrorDescribeInstanceInformation(response, &metadata) - } - output := &DescribeInstanceInformationOutput{} - 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_deserializeOpDocumentDescribeInstanceInformationOutput(&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_deserializeOpErrorDescribeInstanceInformation(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilterKey", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterKey(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidInstanceInformationFilterValue", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceInformationFilterValue(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeInstancePatches struct { -} - -func (*awsAwsjson11_deserializeOpDescribeInstancePatches) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeInstancePatches) 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 - } - - 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_deserializeOpErrorDescribeInstancePatches(response, &metadata) - } - output := &DescribeInstancePatchesOutput{} - 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_deserializeOpDocumentDescribeInstancePatchesOutput(&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_deserializeOpErrorDescribeInstancePatches(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilter", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilter(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeInstancePatchStates struct { -} - -func (*awsAwsjson11_deserializeOpDescribeInstancePatchStates) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeInstancePatchStates) 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 - } - - 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_deserializeOpErrorDescribeInstancePatchStates(response, &metadata) - } - output := &DescribeInstancePatchStatesOutput{} - 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_deserializeOpDocumentDescribeInstancePatchStatesOutput(&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_deserializeOpErrorDescribeInstancePatchStates(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeInstancePatchStatesForPatchGroup struct { -} - -func (*awsAwsjson11_deserializeOpDescribeInstancePatchStatesForPatchGroup) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeInstancePatchStatesForPatchGroup) 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 - } - - 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_deserializeOpErrorDescribeInstancePatchStatesForPatchGroup(response, &metadata) - } - output := &DescribeInstancePatchStatesForPatchGroupOutput{} - 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_deserializeOpDocumentDescribeInstancePatchStatesForPatchGroupOutput(&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_deserializeOpErrorDescribeInstancePatchStatesForPatchGroup(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilter", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilter(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeInventoryDeletions struct { -} - -func (*awsAwsjson11_deserializeOpDescribeInventoryDeletions) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeInventoryDeletions) 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 - } - - 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_deserializeOpErrorDescribeInventoryDeletions(response, &metadata) - } - output := &DescribeInventoryDeletionsOutput{} - 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_deserializeOpDocumentDescribeInventoryDeletionsOutput(&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_deserializeOpErrorDescribeInventoryDeletions(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDeletionIdException", errorCode): - return awsAwsjson11_deserializeErrorInvalidDeletionIdException(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutions struct { -} - -func (*awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutions) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutions) 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 - } - - 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_deserializeOpErrorDescribeMaintenanceWindowExecutions(response, &metadata) - } - output := &DescribeMaintenanceWindowExecutionsOutput{} - 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_deserializeOpDocumentDescribeMaintenanceWindowExecutionsOutput(&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_deserializeOpErrorDescribeMaintenanceWindowExecutions(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutionTaskInvocations struct { -} - -func (*awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutionTaskInvocations) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutionTaskInvocations) 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 - } - - 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_deserializeOpErrorDescribeMaintenanceWindowExecutionTaskInvocations(response, &metadata) - } - output := &DescribeMaintenanceWindowExecutionTaskInvocationsOutput{} - 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_deserializeOpDocumentDescribeMaintenanceWindowExecutionTaskInvocationsOutput(&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_deserializeOpErrorDescribeMaintenanceWindowExecutionTaskInvocations(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutionTasks struct { -} - -func (*awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutionTasks) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeMaintenanceWindowExecutionTasks) 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 - } - - 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_deserializeOpErrorDescribeMaintenanceWindowExecutionTasks(response, &metadata) - } - output := &DescribeMaintenanceWindowExecutionTasksOutput{} - 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_deserializeOpDocumentDescribeMaintenanceWindowExecutionTasksOutput(&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_deserializeOpErrorDescribeMaintenanceWindowExecutionTasks(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeMaintenanceWindows struct { -} - -func (*awsAwsjson11_deserializeOpDescribeMaintenanceWindows) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeMaintenanceWindows) 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 - } - - 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_deserializeOpErrorDescribeMaintenanceWindows(response, &metadata) - } - output := &DescribeMaintenanceWindowsOutput{} - 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_deserializeOpDocumentDescribeMaintenanceWindowsOutput(&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_deserializeOpErrorDescribeMaintenanceWindows(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeMaintenanceWindowSchedule struct { -} - -func (*awsAwsjson11_deserializeOpDescribeMaintenanceWindowSchedule) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeMaintenanceWindowSchedule) 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 - } - - 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_deserializeOpErrorDescribeMaintenanceWindowSchedule(response, &metadata) - } - output := &DescribeMaintenanceWindowScheduleOutput{} - 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_deserializeOpDocumentDescribeMaintenanceWindowScheduleOutput(&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_deserializeOpErrorDescribeMaintenanceWindowSchedule(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeMaintenanceWindowsForTarget struct { -} - -func (*awsAwsjson11_deserializeOpDescribeMaintenanceWindowsForTarget) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeMaintenanceWindowsForTarget) 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 - } - - 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_deserializeOpErrorDescribeMaintenanceWindowsForTarget(response, &metadata) - } - output := &DescribeMaintenanceWindowsForTargetOutput{} - 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_deserializeOpDocumentDescribeMaintenanceWindowsForTargetOutput(&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_deserializeOpErrorDescribeMaintenanceWindowsForTarget(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeMaintenanceWindowTargets struct { -} - -func (*awsAwsjson11_deserializeOpDescribeMaintenanceWindowTargets) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeMaintenanceWindowTargets) 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 - } - - 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_deserializeOpErrorDescribeMaintenanceWindowTargets(response, &metadata) - } - output := &DescribeMaintenanceWindowTargetsOutput{} - 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_deserializeOpDocumentDescribeMaintenanceWindowTargetsOutput(&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_deserializeOpErrorDescribeMaintenanceWindowTargets(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeMaintenanceWindowTasks struct { -} - -func (*awsAwsjson11_deserializeOpDescribeMaintenanceWindowTasks) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeMaintenanceWindowTasks) 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 - } - - 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_deserializeOpErrorDescribeMaintenanceWindowTasks(response, &metadata) - } - output := &DescribeMaintenanceWindowTasksOutput{} - 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_deserializeOpDocumentDescribeMaintenanceWindowTasksOutput(&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_deserializeOpErrorDescribeMaintenanceWindowTasks(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeOpsItems struct { -} - -func (*awsAwsjson11_deserializeOpDescribeOpsItems) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeOpsItems) 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 - } - - 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_deserializeOpErrorDescribeOpsItems(response, &metadata) - } - output := &DescribeOpsItemsOutput{} - 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_deserializeOpDocumentDescribeOpsItemsOutput(&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_deserializeOpErrorDescribeOpsItems(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeParameters struct { -} - -func (*awsAwsjson11_deserializeOpDescribeParameters) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeParameters) 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 - } - - 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_deserializeOpErrorDescribeParameters(response, &metadata) - } - output := &DescribeParametersOutput{} - 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_deserializeOpDocumentDescribeParametersOutput(&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_deserializeOpErrorDescribeParameters(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilterKey", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterKey(response, errorBody) - - case strings.EqualFold("InvalidFilterOption", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterOption(response, errorBody) - - case strings.EqualFold("InvalidFilterValue", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterValue(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribePatchBaselines struct { -} - -func (*awsAwsjson11_deserializeOpDescribePatchBaselines) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribePatchBaselines) 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 - } - - 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_deserializeOpErrorDescribePatchBaselines(response, &metadata) - } - output := &DescribePatchBaselinesOutput{} - 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_deserializeOpDocumentDescribePatchBaselinesOutput(&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_deserializeOpErrorDescribePatchBaselines(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribePatchGroups struct { -} - -func (*awsAwsjson11_deserializeOpDescribePatchGroups) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribePatchGroups) 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 - } - - 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_deserializeOpErrorDescribePatchGroups(response, &metadata) - } - output := &DescribePatchGroupsOutput{} - 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_deserializeOpDocumentDescribePatchGroupsOutput(&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_deserializeOpErrorDescribePatchGroups(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribePatchGroupState struct { -} - -func (*awsAwsjson11_deserializeOpDescribePatchGroupState) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribePatchGroupState) 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 - } - - 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_deserializeOpErrorDescribePatchGroupState(response, &metadata) - } - output := &DescribePatchGroupStateOutput{} - 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_deserializeOpDocumentDescribePatchGroupStateOutput(&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_deserializeOpErrorDescribePatchGroupState(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribePatchProperties struct { -} - -func (*awsAwsjson11_deserializeOpDescribePatchProperties) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribePatchProperties) 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 - } - - 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_deserializeOpErrorDescribePatchProperties(response, &metadata) - } - output := &DescribePatchPropertiesOutput{} - 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_deserializeOpDocumentDescribePatchPropertiesOutput(&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_deserializeOpErrorDescribePatchProperties(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDescribeSessions struct { -} - -func (*awsAwsjson11_deserializeOpDescribeSessions) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDescribeSessions) 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 - } - - 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_deserializeOpErrorDescribeSessions(response, &metadata) - } - output := &DescribeSessionsOutput{} - 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_deserializeOpDocumentDescribeSessionsOutput(&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_deserializeOpErrorDescribeSessions(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilterKey", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterKey(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpDisassociateOpsItemRelatedItem struct { -} - -func (*awsAwsjson11_deserializeOpDisassociateOpsItemRelatedItem) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpDisassociateOpsItemRelatedItem) 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 - } - - 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_deserializeOpErrorDisassociateOpsItemRelatedItem(response, &metadata) - } - output := &DisassociateOpsItemRelatedItemOutput{} - 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_deserializeOpDocumentDisassociateOpsItemRelatedItemOutput(&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_deserializeOpErrorDisassociateOpsItemRelatedItem(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsItemConflictException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemConflictException(response, errorBody) - - case strings.EqualFold("OpsItemInvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemInvalidParameterException(response, errorBody) - - case strings.EqualFold("OpsItemNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemNotFoundException(response, errorBody) - - case strings.EqualFold("OpsItemRelatedItemAssociationNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemRelatedItemAssociationNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetAutomationExecution struct { -} - -func (*awsAwsjson11_deserializeOpGetAutomationExecution) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetAutomationExecution) 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 - } - - 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_deserializeOpErrorGetAutomationExecution(response, &metadata) - } - output := &GetAutomationExecutionOutput{} - 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_deserializeOpDocumentGetAutomationExecutionOutput(&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_deserializeOpErrorGetAutomationExecution(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AutomationExecutionNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorAutomationExecutionNotFoundException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetCalendarState struct { -} - -func (*awsAwsjson11_deserializeOpGetCalendarState) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetCalendarState) 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 - } - - 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_deserializeOpErrorGetCalendarState(response, &metadata) - } - output := &GetCalendarStateOutput{} - 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_deserializeOpDocumentGetCalendarStateOutput(&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_deserializeOpErrorGetCalendarState(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentType", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentType(response, errorBody) - - case strings.EqualFold("UnsupportedCalendarException", errorCode): - return awsAwsjson11_deserializeErrorUnsupportedCalendarException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetCommandInvocation struct { -} - -func (*awsAwsjson11_deserializeOpGetCommandInvocation) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetCommandInvocation) 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 - } - - 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_deserializeOpErrorGetCommandInvocation(response, &metadata) - } - output := &GetCommandInvocationOutput{} - 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_deserializeOpDocumentGetCommandInvocationOutput(&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_deserializeOpErrorGetCommandInvocation(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidCommandId", errorCode): - return awsAwsjson11_deserializeErrorInvalidCommandId(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidPluginName", errorCode): - return awsAwsjson11_deserializeErrorInvalidPluginName(response, errorBody) - - case strings.EqualFold("InvocationDoesNotExist", errorCode): - return awsAwsjson11_deserializeErrorInvocationDoesNotExist(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetConnectionStatus struct { -} - -func (*awsAwsjson11_deserializeOpGetConnectionStatus) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetConnectionStatus) 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 - } - - 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_deserializeOpErrorGetConnectionStatus(response, &metadata) - } - output := &GetConnectionStatusOutput{} - 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_deserializeOpDocumentGetConnectionStatusOutput(&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_deserializeOpErrorGetConnectionStatus(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetDefaultPatchBaseline struct { -} - -func (*awsAwsjson11_deserializeOpGetDefaultPatchBaseline) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetDefaultPatchBaseline) 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 - } - - 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_deserializeOpErrorGetDefaultPatchBaseline(response, &metadata) - } - output := &GetDefaultPatchBaselineOutput{} - 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_deserializeOpDocumentGetDefaultPatchBaselineOutput(&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_deserializeOpErrorGetDefaultPatchBaseline(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetDeployablePatchSnapshotForInstance struct { -} - -func (*awsAwsjson11_deserializeOpGetDeployablePatchSnapshotForInstance) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetDeployablePatchSnapshotForInstance) 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 - } - - 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_deserializeOpErrorGetDeployablePatchSnapshotForInstance(response, &metadata) - } - output := &GetDeployablePatchSnapshotForInstanceOutput{} - 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_deserializeOpDocumentGetDeployablePatchSnapshotForInstanceOutput(&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_deserializeOpErrorGetDeployablePatchSnapshotForInstance(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("UnsupportedFeatureRequiredException", errorCode): - return awsAwsjson11_deserializeErrorUnsupportedFeatureRequiredException(response, errorBody) - - case strings.EqualFold("UnsupportedOperatingSystem", errorCode): - return awsAwsjson11_deserializeErrorUnsupportedOperatingSystem(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetDocument struct { -} - -func (*awsAwsjson11_deserializeOpGetDocument) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetDocument) 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 - } - - 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_deserializeOpErrorGetDocument(response, &metadata) - } - output := &GetDocumentOutput{} - 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_deserializeOpDocumentGetDocumentOutput(&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_deserializeOpErrorGetDocument(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentVersion(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetInventory struct { -} - -func (*awsAwsjson11_deserializeOpGetInventory) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetInventory) 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 - } - - 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_deserializeOpErrorGetInventory(response, &metadata) - } - output := &GetInventoryOutput{} - 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_deserializeOpDocumentGetInventoryOutput(&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_deserializeOpErrorGetInventory(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidAggregatorException", errorCode): - return awsAwsjson11_deserializeErrorInvalidAggregatorException(response, errorBody) - - case strings.EqualFold("InvalidFilter", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilter(response, errorBody) - - case strings.EqualFold("InvalidInventoryGroupException", errorCode): - return awsAwsjson11_deserializeErrorInvalidInventoryGroupException(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - case strings.EqualFold("InvalidResultAttributeException", errorCode): - return awsAwsjson11_deserializeErrorInvalidResultAttributeException(response, errorBody) - - case strings.EqualFold("InvalidTypeNameException", errorCode): - return awsAwsjson11_deserializeErrorInvalidTypeNameException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetInventorySchema struct { -} - -func (*awsAwsjson11_deserializeOpGetInventorySchema) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetInventorySchema) 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 - } - - 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_deserializeOpErrorGetInventorySchema(response, &metadata) - } - output := &GetInventorySchemaOutput{} - 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_deserializeOpDocumentGetInventorySchemaOutput(&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_deserializeOpErrorGetInventorySchema(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - case strings.EqualFold("InvalidTypeNameException", errorCode): - return awsAwsjson11_deserializeErrorInvalidTypeNameException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetMaintenanceWindow struct { -} - -func (*awsAwsjson11_deserializeOpGetMaintenanceWindow) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetMaintenanceWindow) 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 - } - - 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_deserializeOpErrorGetMaintenanceWindow(response, &metadata) - } - output := &GetMaintenanceWindowOutput{} - 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_deserializeOpDocumentGetMaintenanceWindowOutput(&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_deserializeOpErrorGetMaintenanceWindow(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetMaintenanceWindowExecution struct { -} - -func (*awsAwsjson11_deserializeOpGetMaintenanceWindowExecution) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetMaintenanceWindowExecution) 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 - } - - 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_deserializeOpErrorGetMaintenanceWindowExecution(response, &metadata) - } - output := &GetMaintenanceWindowExecutionOutput{} - 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_deserializeOpDocumentGetMaintenanceWindowExecutionOutput(&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_deserializeOpErrorGetMaintenanceWindowExecution(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetMaintenanceWindowExecutionTask struct { -} - -func (*awsAwsjson11_deserializeOpGetMaintenanceWindowExecutionTask) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetMaintenanceWindowExecutionTask) 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 - } - - 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_deserializeOpErrorGetMaintenanceWindowExecutionTask(response, &metadata) - } - output := &GetMaintenanceWindowExecutionTaskOutput{} - 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_deserializeOpDocumentGetMaintenanceWindowExecutionTaskOutput(&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_deserializeOpErrorGetMaintenanceWindowExecutionTask(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetMaintenanceWindowExecutionTaskInvocation struct { -} - -func (*awsAwsjson11_deserializeOpGetMaintenanceWindowExecutionTaskInvocation) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetMaintenanceWindowExecutionTaskInvocation) 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 - } - - 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_deserializeOpErrorGetMaintenanceWindowExecutionTaskInvocation(response, &metadata) - } - output := &GetMaintenanceWindowExecutionTaskInvocationOutput{} - 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_deserializeOpDocumentGetMaintenanceWindowExecutionTaskInvocationOutput(&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_deserializeOpErrorGetMaintenanceWindowExecutionTaskInvocation(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetMaintenanceWindowTask struct { -} - -func (*awsAwsjson11_deserializeOpGetMaintenanceWindowTask) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetMaintenanceWindowTask) 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 - } - - 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_deserializeOpErrorGetMaintenanceWindowTask(response, &metadata) - } - output := &GetMaintenanceWindowTaskOutput{} - 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_deserializeOpDocumentGetMaintenanceWindowTaskOutput(&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_deserializeOpErrorGetMaintenanceWindowTask(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetOpsItem struct { -} - -func (*awsAwsjson11_deserializeOpGetOpsItem) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetOpsItem) 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 - } - - 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_deserializeOpErrorGetOpsItem(response, &metadata) - } - output := &GetOpsItemOutput{} - 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_deserializeOpDocumentGetOpsItemOutput(&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_deserializeOpErrorGetOpsItem(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsItemAccessDeniedException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemAccessDeniedException(response, errorBody) - - case strings.EqualFold("OpsItemNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetOpsMetadata struct { -} - -func (*awsAwsjson11_deserializeOpGetOpsMetadata) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetOpsMetadata) 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 - } - - 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_deserializeOpErrorGetOpsMetadata(response, &metadata) - } - output := &GetOpsMetadataOutput{} - 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_deserializeOpDocumentGetOpsMetadataOutput(&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_deserializeOpErrorGetOpsMetadata(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsMetadataInvalidArgumentException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataInvalidArgumentException(response, errorBody) - - case strings.EqualFold("OpsMetadataNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetOpsSummary struct { -} - -func (*awsAwsjson11_deserializeOpGetOpsSummary) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetOpsSummary) 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 - } - - 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_deserializeOpErrorGetOpsSummary(response, &metadata) - } - output := &GetOpsSummaryOutput{} - 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_deserializeOpDocumentGetOpsSummaryOutput(&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_deserializeOpErrorGetOpsSummary(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidAggregatorException", errorCode): - return awsAwsjson11_deserializeErrorInvalidAggregatorException(response, errorBody) - - case strings.EqualFold("InvalidFilter", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilter(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - case strings.EqualFold("InvalidTypeNameException", errorCode): - return awsAwsjson11_deserializeErrorInvalidTypeNameException(response, errorBody) - - case strings.EqualFold("ResourceDataSyncNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceDataSyncNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetParameter struct { -} - -func (*awsAwsjson11_deserializeOpGetParameter) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetParameter) 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 - } - - 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_deserializeOpErrorGetParameter(response, &metadata) - } - output := &GetParameterOutput{} - 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_deserializeOpDocumentGetParameterOutput(&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_deserializeOpErrorGetParameter(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidKeyId", errorCode): - return awsAwsjson11_deserializeErrorInvalidKeyId(response, errorBody) - - case strings.EqualFold("ParameterNotFound", errorCode): - return awsAwsjson11_deserializeErrorParameterNotFound(response, errorBody) - - case strings.EqualFold("ParameterVersionNotFound", errorCode): - return awsAwsjson11_deserializeErrorParameterVersionNotFound(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetParameterHistory struct { -} - -func (*awsAwsjson11_deserializeOpGetParameterHistory) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetParameterHistory) 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 - } - - 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_deserializeOpErrorGetParameterHistory(response, &metadata) - } - output := &GetParameterHistoryOutput{} - 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_deserializeOpDocumentGetParameterHistoryOutput(&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_deserializeOpErrorGetParameterHistory(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidKeyId", errorCode): - return awsAwsjson11_deserializeErrorInvalidKeyId(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - case strings.EqualFold("ParameterNotFound", errorCode): - return awsAwsjson11_deserializeErrorParameterNotFound(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetParameters struct { -} - -func (*awsAwsjson11_deserializeOpGetParameters) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetParameters) 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 - } - - 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_deserializeOpErrorGetParameters(response, &metadata) - } - output := &GetParametersOutput{} - 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_deserializeOpDocumentGetParametersOutput(&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_deserializeOpErrorGetParameters(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidKeyId", errorCode): - return awsAwsjson11_deserializeErrorInvalidKeyId(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetParametersByPath struct { -} - -func (*awsAwsjson11_deserializeOpGetParametersByPath) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetParametersByPath) 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 - } - - 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_deserializeOpErrorGetParametersByPath(response, &metadata) - } - output := &GetParametersByPathOutput{} - 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_deserializeOpDocumentGetParametersByPathOutput(&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_deserializeOpErrorGetParametersByPath(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilterKey", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterKey(response, errorBody) - - case strings.EqualFold("InvalidFilterOption", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterOption(response, errorBody) - - case strings.EqualFold("InvalidFilterValue", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterValue(response, errorBody) - - case strings.EqualFold("InvalidKeyId", errorCode): - return awsAwsjson11_deserializeErrorInvalidKeyId(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetPatchBaseline struct { -} - -func (*awsAwsjson11_deserializeOpGetPatchBaseline) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetPatchBaseline) 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 - } - - 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_deserializeOpErrorGetPatchBaseline(response, &metadata) - } - output := &GetPatchBaselineOutput{} - 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_deserializeOpDocumentGetPatchBaselineOutput(&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_deserializeOpErrorGetPatchBaseline(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidResourceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceId(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetPatchBaselineForPatchGroup struct { -} - -func (*awsAwsjson11_deserializeOpGetPatchBaselineForPatchGroup) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetPatchBaselineForPatchGroup) 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 - } - - 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_deserializeOpErrorGetPatchBaselineForPatchGroup(response, &metadata) - } - output := &GetPatchBaselineForPatchGroupOutput{} - 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_deserializeOpDocumentGetPatchBaselineForPatchGroupOutput(&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_deserializeOpErrorGetPatchBaselineForPatchGroup(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetResourcePolicies struct { -} - -func (*awsAwsjson11_deserializeOpGetResourcePolicies) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetResourcePolicies) 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 - } - - 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_deserializeOpErrorGetResourcePolicies(response, &metadata) - } - output := &GetResourcePoliciesOutput{} - 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_deserializeOpDocumentGetResourcePoliciesOutput(&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_deserializeOpErrorGetResourcePolicies(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ResourcePolicyInvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorResourcePolicyInvalidParameterException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpGetServiceSetting struct { -} - -func (*awsAwsjson11_deserializeOpGetServiceSetting) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpGetServiceSetting) 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 - } - - 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_deserializeOpErrorGetServiceSetting(response, &metadata) - } - output := &GetServiceSettingOutput{} - 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_deserializeOpDocumentGetServiceSettingOutput(&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_deserializeOpErrorGetServiceSetting(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ServiceSettingNotFound", errorCode): - return awsAwsjson11_deserializeErrorServiceSettingNotFound(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpLabelParameterVersion struct { -} - -func (*awsAwsjson11_deserializeOpLabelParameterVersion) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpLabelParameterVersion) 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 - } - - 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_deserializeOpErrorLabelParameterVersion(response, &metadata) - } - output := &LabelParameterVersionOutput{} - 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_deserializeOpDocumentLabelParameterVersionOutput(&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_deserializeOpErrorLabelParameterVersion(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ParameterNotFound", errorCode): - return awsAwsjson11_deserializeErrorParameterNotFound(response, errorBody) - - case strings.EqualFold("ParameterVersionLabelLimitExceeded", errorCode): - return awsAwsjson11_deserializeErrorParameterVersionLabelLimitExceeded(response, errorBody) - - case strings.EqualFold("ParameterVersionNotFound", errorCode): - return awsAwsjson11_deserializeErrorParameterVersionNotFound(response, errorBody) - - case strings.EqualFold("TooManyUpdates", errorCode): - return awsAwsjson11_deserializeErrorTooManyUpdates(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListAssociations struct { -} - -func (*awsAwsjson11_deserializeOpListAssociations) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListAssociations) 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 - } - - 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_deserializeOpErrorListAssociations(response, &metadata) - } - output := &ListAssociationsOutput{} - 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_deserializeOpDocumentListAssociationsOutput(&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_deserializeOpErrorListAssociations(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListAssociationVersions struct { -} - -func (*awsAwsjson11_deserializeOpListAssociationVersions) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListAssociationVersions) 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 - } - - 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_deserializeOpErrorListAssociationVersions(response, &metadata) - } - output := &ListAssociationVersionsOutput{} - 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_deserializeOpDocumentListAssociationVersionsOutput(&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_deserializeOpErrorListAssociationVersions(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AssociationDoesNotExist", errorCode): - return awsAwsjson11_deserializeErrorAssociationDoesNotExist(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListCommandInvocations struct { -} - -func (*awsAwsjson11_deserializeOpListCommandInvocations) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListCommandInvocations) 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 - } - - 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_deserializeOpErrorListCommandInvocations(response, &metadata) - } - output := &ListCommandInvocationsOutput{} - 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_deserializeOpDocumentListCommandInvocationsOutput(&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_deserializeOpErrorListCommandInvocations(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidCommandId", errorCode): - return awsAwsjson11_deserializeErrorInvalidCommandId(response, errorBody) - - case strings.EqualFold("InvalidFilterKey", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterKey(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListCommands struct { -} - -func (*awsAwsjson11_deserializeOpListCommands) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListCommands) 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 - } - - 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_deserializeOpErrorListCommands(response, &metadata) - } - output := &ListCommandsOutput{} - 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_deserializeOpDocumentListCommandsOutput(&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_deserializeOpErrorListCommands(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidCommandId", errorCode): - return awsAwsjson11_deserializeErrorInvalidCommandId(response, errorBody) - - case strings.EqualFold("InvalidFilterKey", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterKey(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListComplianceItems struct { -} - -func (*awsAwsjson11_deserializeOpListComplianceItems) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListComplianceItems) 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 - } - - 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_deserializeOpErrorListComplianceItems(response, &metadata) - } - output := &ListComplianceItemsOutput{} - 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_deserializeOpDocumentListComplianceItemsOutput(&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_deserializeOpErrorListComplianceItems(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilter", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilter(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - case strings.EqualFold("InvalidResourceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceId(response, errorBody) - - case strings.EqualFold("InvalidResourceType", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceType(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListComplianceSummaries struct { -} - -func (*awsAwsjson11_deserializeOpListComplianceSummaries) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListComplianceSummaries) 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 - } - - 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_deserializeOpErrorListComplianceSummaries(response, &metadata) - } - output := &ListComplianceSummariesOutput{} - 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_deserializeOpDocumentListComplianceSummariesOutput(&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_deserializeOpErrorListComplianceSummaries(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilter", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilter(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListDocumentMetadataHistory struct { -} - -func (*awsAwsjson11_deserializeOpListDocumentMetadataHistory) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListDocumentMetadataHistory) 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 - } - - 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_deserializeOpErrorListDocumentMetadataHistory(response, &metadata) - } - output := &ListDocumentMetadataHistoryOutput{} - 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_deserializeOpDocumentListDocumentMetadataHistoryOutput(&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_deserializeOpErrorListDocumentMetadataHistory(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentVersion(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListDocuments struct { -} - -func (*awsAwsjson11_deserializeOpListDocuments) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListDocuments) 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 - } - - 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_deserializeOpErrorListDocuments(response, &metadata) - } - output := &ListDocumentsOutput{} - 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_deserializeOpDocumentListDocumentsOutput(&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_deserializeOpErrorListDocuments(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilterKey", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilterKey(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListDocumentVersions struct { -} - -func (*awsAwsjson11_deserializeOpListDocumentVersions) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListDocumentVersions) 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 - } - - 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_deserializeOpErrorListDocumentVersions(response, &metadata) - } - output := &ListDocumentVersionsOutput{} - 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_deserializeOpDocumentListDocumentVersionsOutput(&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_deserializeOpErrorListDocumentVersions(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListInventoryEntries struct { -} - -func (*awsAwsjson11_deserializeOpListInventoryEntries) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListInventoryEntries) 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 - } - - 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_deserializeOpErrorListInventoryEntries(response, &metadata) - } - output := &ListInventoryEntriesOutput{} - 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_deserializeOpDocumentListInventoryEntriesOutput(&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_deserializeOpErrorListInventoryEntries(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilter", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilter(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - case strings.EqualFold("InvalidTypeNameException", errorCode): - return awsAwsjson11_deserializeErrorInvalidTypeNameException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListOpsItemEvents struct { -} - -func (*awsAwsjson11_deserializeOpListOpsItemEvents) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListOpsItemEvents) 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 - } - - 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_deserializeOpErrorListOpsItemEvents(response, &metadata) - } - output := &ListOpsItemEventsOutput{} - 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_deserializeOpDocumentListOpsItemEventsOutput(&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_deserializeOpErrorListOpsItemEvents(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsItemInvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemInvalidParameterException(response, errorBody) - - case strings.EqualFold("OpsItemLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemLimitExceededException(response, errorBody) - - case strings.EqualFold("OpsItemNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListOpsItemRelatedItems struct { -} - -func (*awsAwsjson11_deserializeOpListOpsItemRelatedItems) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListOpsItemRelatedItems) 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 - } - - 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_deserializeOpErrorListOpsItemRelatedItems(response, &metadata) - } - output := &ListOpsItemRelatedItemsOutput{} - 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_deserializeOpDocumentListOpsItemRelatedItemsOutput(&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_deserializeOpErrorListOpsItemRelatedItems(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsItemInvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemInvalidParameterException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListOpsMetadata struct { -} - -func (*awsAwsjson11_deserializeOpListOpsMetadata) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListOpsMetadata) 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 - } - - 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_deserializeOpErrorListOpsMetadata(response, &metadata) - } - output := &ListOpsMetadataOutput{} - 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_deserializeOpDocumentListOpsMetadataOutput(&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_deserializeOpErrorListOpsMetadata(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsMetadataInvalidArgumentException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataInvalidArgumentException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListResourceComplianceSummaries struct { -} - -func (*awsAwsjson11_deserializeOpListResourceComplianceSummaries) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListResourceComplianceSummaries) 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 - } - - 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_deserializeOpErrorListResourceComplianceSummaries(response, &metadata) - } - output := &ListResourceComplianceSummariesOutput{} - 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_deserializeOpDocumentListResourceComplianceSummariesOutput(&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_deserializeOpErrorListResourceComplianceSummaries(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidFilter", errorCode): - return awsAwsjson11_deserializeErrorInvalidFilter(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListResourceDataSync struct { -} - -func (*awsAwsjson11_deserializeOpListResourceDataSync) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListResourceDataSync) 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 - } - - 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_deserializeOpErrorListResourceDataSync(response, &metadata) - } - output := &ListResourceDataSyncOutput{} - 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_deserializeOpDocumentListResourceDataSyncOutput(&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_deserializeOpErrorListResourceDataSync(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidNextToken", errorCode): - return awsAwsjson11_deserializeErrorInvalidNextToken(response, errorBody) - - case strings.EqualFold("ResourceDataSyncInvalidConfigurationException", errorCode): - return awsAwsjson11_deserializeErrorResourceDataSyncInvalidConfigurationException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpListTagsForResource struct { -} - -func (*awsAwsjson11_deserializeOpListTagsForResource) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpListTagsForResource) 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 - } - - 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_deserializeOpErrorListTagsForResource(response, &metadata) - } - output := &ListTagsForResourceOutput{} - 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_deserializeOpDocumentListTagsForResourceOutput(&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_deserializeOpErrorListTagsForResource(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidResourceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceId(response, errorBody) - - case strings.EqualFold("InvalidResourceType", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceType(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpModifyDocumentPermission struct { -} - -func (*awsAwsjson11_deserializeOpModifyDocumentPermission) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpModifyDocumentPermission) 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 - } - - 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_deserializeOpErrorModifyDocumentPermission(response, &metadata) - } - output := &ModifyDocumentPermissionOutput{} - 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_deserializeOpDocumentModifyDocumentPermissionOutput(&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_deserializeOpErrorModifyDocumentPermission(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DocumentLimitExceeded", errorCode): - return awsAwsjson11_deserializeErrorDocumentLimitExceeded(response, errorBody) - - case strings.EqualFold("DocumentPermissionLimit", errorCode): - return awsAwsjson11_deserializeErrorDocumentPermissionLimit(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidPermissionType", errorCode): - return awsAwsjson11_deserializeErrorInvalidPermissionType(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpPutComplianceItems struct { -} - -func (*awsAwsjson11_deserializeOpPutComplianceItems) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpPutComplianceItems) 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 - } - - 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_deserializeOpErrorPutComplianceItems(response, &metadata) - } - output := &PutComplianceItemsOutput{} - 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_deserializeOpDocumentPutComplianceItemsOutput(&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_deserializeOpErrorPutComplianceItems(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("ComplianceTypeCountLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorComplianceTypeCountLimitExceededException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidItemContentException", errorCode): - return awsAwsjson11_deserializeErrorInvalidItemContentException(response, errorBody) - - case strings.EqualFold("InvalidResourceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceId(response, errorBody) - - case strings.EqualFold("InvalidResourceType", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceType(response, errorBody) - - case strings.EqualFold("ItemSizeLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorItemSizeLimitExceededException(response, errorBody) - - case strings.EqualFold("TotalSizeLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorTotalSizeLimitExceededException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpPutInventory struct { -} - -func (*awsAwsjson11_deserializeOpPutInventory) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpPutInventory) 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 - } - - 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_deserializeOpErrorPutInventory(response, &metadata) - } - output := &PutInventoryOutput{} - 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_deserializeOpDocumentPutInventoryOutput(&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_deserializeOpErrorPutInventory(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("CustomSchemaCountLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorCustomSchemaCountLimitExceededException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidInventoryItemContextException", errorCode): - return awsAwsjson11_deserializeErrorInvalidInventoryItemContextException(response, errorBody) - - case strings.EqualFold("InvalidItemContentException", errorCode): - return awsAwsjson11_deserializeErrorInvalidItemContentException(response, errorBody) - - case strings.EqualFold("InvalidTypeNameException", errorCode): - return awsAwsjson11_deserializeErrorInvalidTypeNameException(response, errorBody) - - case strings.EqualFold("ItemContentMismatchException", errorCode): - return awsAwsjson11_deserializeErrorItemContentMismatchException(response, errorBody) - - case strings.EqualFold("ItemSizeLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorItemSizeLimitExceededException(response, errorBody) - - case strings.EqualFold("SubTypeCountLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorSubTypeCountLimitExceededException(response, errorBody) - - case strings.EqualFold("TotalSizeLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorTotalSizeLimitExceededException(response, errorBody) - - case strings.EqualFold("UnsupportedInventoryItemContextException", errorCode): - return awsAwsjson11_deserializeErrorUnsupportedInventoryItemContextException(response, errorBody) - - case strings.EqualFold("UnsupportedInventorySchemaVersionException", errorCode): - return awsAwsjson11_deserializeErrorUnsupportedInventorySchemaVersionException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpPutParameter struct { -} - -func (*awsAwsjson11_deserializeOpPutParameter) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpPutParameter) 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 - } - - 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_deserializeOpErrorPutParameter(response, &metadata) - } - output := &PutParameterOutput{} - 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_deserializeOpDocumentPutParameterOutput(&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_deserializeOpErrorPutParameter(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("HierarchyLevelLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorHierarchyLevelLimitExceededException(response, errorBody) - - case strings.EqualFold("HierarchyTypeMismatchException", errorCode): - return awsAwsjson11_deserializeErrorHierarchyTypeMismatchException(response, errorBody) - - case strings.EqualFold("IncompatiblePolicyException", errorCode): - return awsAwsjson11_deserializeErrorIncompatiblePolicyException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidAllowedPatternException", errorCode): - return awsAwsjson11_deserializeErrorInvalidAllowedPatternException(response, errorBody) - - case strings.EqualFold("InvalidKeyId", errorCode): - return awsAwsjson11_deserializeErrorInvalidKeyId(response, errorBody) - - case strings.EqualFold("InvalidPolicyAttributeException", errorCode): - return awsAwsjson11_deserializeErrorInvalidPolicyAttributeException(response, errorBody) - - case strings.EqualFold("InvalidPolicyTypeException", errorCode): - return awsAwsjson11_deserializeErrorInvalidPolicyTypeException(response, errorBody) - - case strings.EqualFold("ParameterAlreadyExists", errorCode): - return awsAwsjson11_deserializeErrorParameterAlreadyExists(response, errorBody) - - case strings.EqualFold("ParameterLimitExceeded", errorCode): - return awsAwsjson11_deserializeErrorParameterLimitExceeded(response, errorBody) - - case strings.EqualFold("ParameterMaxVersionLimitExceeded", errorCode): - return awsAwsjson11_deserializeErrorParameterMaxVersionLimitExceeded(response, errorBody) - - case strings.EqualFold("ParameterPatternMismatchException", errorCode): - return awsAwsjson11_deserializeErrorParameterPatternMismatchException(response, errorBody) - - case strings.EqualFold("PoliciesLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorPoliciesLimitExceededException(response, errorBody) - - case strings.EqualFold("TooManyUpdates", errorCode): - return awsAwsjson11_deserializeErrorTooManyUpdates(response, errorBody) - - case strings.EqualFold("UnsupportedParameterType", errorCode): - return awsAwsjson11_deserializeErrorUnsupportedParameterType(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpPutResourcePolicy struct { -} - -func (*awsAwsjson11_deserializeOpPutResourcePolicy) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpPutResourcePolicy) 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 - } - - 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_deserializeOpErrorPutResourcePolicy(response, &metadata) - } - output := &PutResourcePolicyOutput{} - 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_deserializeOpDocumentPutResourcePolicyOutput(&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_deserializeOpErrorPutResourcePolicy(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ResourcePolicyConflictException", errorCode): - return awsAwsjson11_deserializeErrorResourcePolicyConflictException(response, errorBody) - - case strings.EqualFold("ResourcePolicyInvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorResourcePolicyInvalidParameterException(response, errorBody) - - case strings.EqualFold("ResourcePolicyLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorResourcePolicyLimitExceededException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpRegisterDefaultPatchBaseline struct { -} - -func (*awsAwsjson11_deserializeOpRegisterDefaultPatchBaseline) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpRegisterDefaultPatchBaseline) 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 - } - - 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_deserializeOpErrorRegisterDefaultPatchBaseline(response, &metadata) - } - output := &RegisterDefaultPatchBaselineOutput{} - 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_deserializeOpDocumentRegisterDefaultPatchBaselineOutput(&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_deserializeOpErrorRegisterDefaultPatchBaseline(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidResourceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceId(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpRegisterPatchBaselineForPatchGroup struct { -} - -func (*awsAwsjson11_deserializeOpRegisterPatchBaselineForPatchGroup) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpRegisterPatchBaselineForPatchGroup) 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 - } - - 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_deserializeOpErrorRegisterPatchBaselineForPatchGroup(response, &metadata) - } - output := &RegisterPatchBaselineForPatchGroupOutput{} - 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_deserializeOpDocumentRegisterPatchBaselineForPatchGroupOutput(&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_deserializeOpErrorRegisterPatchBaselineForPatchGroup(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AlreadyExistsException", errorCode): - return awsAwsjson11_deserializeErrorAlreadyExistsException(response, errorBody) - - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidResourceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceId(response, errorBody) - - case strings.EqualFold("ResourceLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorResourceLimitExceededException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpRegisterTargetWithMaintenanceWindow struct { -} - -func (*awsAwsjson11_deserializeOpRegisterTargetWithMaintenanceWindow) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpRegisterTargetWithMaintenanceWindow) 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 - } - - 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_deserializeOpErrorRegisterTargetWithMaintenanceWindow(response, &metadata) - } - output := &RegisterTargetWithMaintenanceWindowOutput{} - 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_deserializeOpDocumentRegisterTargetWithMaintenanceWindowOutput(&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_deserializeOpErrorRegisterTargetWithMaintenanceWindow(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("IdempotentParameterMismatch", errorCode): - return awsAwsjson11_deserializeErrorIdempotentParameterMismatch(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ResourceLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorResourceLimitExceededException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpRegisterTaskWithMaintenanceWindow struct { -} - -func (*awsAwsjson11_deserializeOpRegisterTaskWithMaintenanceWindow) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpRegisterTaskWithMaintenanceWindow) 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 - } - - 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_deserializeOpErrorRegisterTaskWithMaintenanceWindow(response, &metadata) - } - output := &RegisterTaskWithMaintenanceWindowOutput{} - 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_deserializeOpDocumentRegisterTaskWithMaintenanceWindowOutput(&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_deserializeOpErrorRegisterTaskWithMaintenanceWindow(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("FeatureNotAvailableException", errorCode): - return awsAwsjson11_deserializeErrorFeatureNotAvailableException(response, errorBody) - - case strings.EqualFold("IdempotentParameterMismatch", errorCode): - return awsAwsjson11_deserializeErrorIdempotentParameterMismatch(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ResourceLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorResourceLimitExceededException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpRemoveTagsFromResource struct { -} - -func (*awsAwsjson11_deserializeOpRemoveTagsFromResource) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpRemoveTagsFromResource) 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 - } - - 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_deserializeOpErrorRemoveTagsFromResource(response, &metadata) - } - output := &RemoveTagsFromResourceOutput{} - 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_deserializeOpDocumentRemoveTagsFromResourceOutput(&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_deserializeOpErrorRemoveTagsFromResource(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidResourceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceId(response, errorBody) - - case strings.EqualFold("InvalidResourceType", errorCode): - return awsAwsjson11_deserializeErrorInvalidResourceType(response, errorBody) - - case strings.EqualFold("TooManyUpdates", errorCode): - return awsAwsjson11_deserializeErrorTooManyUpdates(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpResetServiceSetting struct { -} - -func (*awsAwsjson11_deserializeOpResetServiceSetting) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpResetServiceSetting) 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 - } - - 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_deserializeOpErrorResetServiceSetting(response, &metadata) - } - output := &ResetServiceSettingOutput{} - 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_deserializeOpDocumentResetServiceSettingOutput(&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_deserializeOpErrorResetServiceSetting(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ServiceSettingNotFound", errorCode): - return awsAwsjson11_deserializeErrorServiceSettingNotFound(response, errorBody) - - case strings.EqualFold("TooManyUpdates", errorCode): - return awsAwsjson11_deserializeErrorTooManyUpdates(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpResumeSession struct { -} - -func (*awsAwsjson11_deserializeOpResumeSession) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpResumeSession) 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 - } - - 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_deserializeOpErrorResumeSession(response, &metadata) - } - output := &ResumeSessionOutput{} - 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_deserializeOpDocumentResumeSessionOutput(&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_deserializeOpErrorResumeSession(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpSendAutomationSignal struct { -} - -func (*awsAwsjson11_deserializeOpSendAutomationSignal) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpSendAutomationSignal) 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 - } - - 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_deserializeOpErrorSendAutomationSignal(response, &metadata) - } - output := &SendAutomationSignalOutput{} - 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_deserializeOpDocumentSendAutomationSignalOutput(&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_deserializeOpErrorSendAutomationSignal(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AutomationExecutionNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorAutomationExecutionNotFoundException(response, errorBody) - - case strings.EqualFold("AutomationStepNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorAutomationStepNotFoundException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidAutomationSignalException", errorCode): - return awsAwsjson11_deserializeErrorInvalidAutomationSignalException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpSendCommand struct { -} - -func (*awsAwsjson11_deserializeOpSendCommand) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpSendCommand) 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 - } - - 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_deserializeOpErrorSendCommand(response, &metadata) - } - output := &SendCommandOutput{} - 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_deserializeOpDocumentSendCommandOutput(&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_deserializeOpErrorSendCommand(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DuplicateInstanceId", errorCode): - return awsAwsjson11_deserializeErrorDuplicateInstanceId(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentVersion(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("InvalidNotificationConfig", errorCode): - return awsAwsjson11_deserializeErrorInvalidNotificationConfig(response, errorBody) - - case strings.EqualFold("InvalidOutputFolder", errorCode): - return awsAwsjson11_deserializeErrorInvalidOutputFolder(response, errorBody) - - case strings.EqualFold("InvalidParameters", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameters(response, errorBody) - - case strings.EqualFold("InvalidRole", errorCode): - return awsAwsjson11_deserializeErrorInvalidRole(response, errorBody) - - case strings.EqualFold("MaxDocumentSizeExceeded", errorCode): - return awsAwsjson11_deserializeErrorMaxDocumentSizeExceeded(response, errorBody) - - case strings.EqualFold("UnsupportedPlatformType", errorCode): - return awsAwsjson11_deserializeErrorUnsupportedPlatformType(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpStartAssociationsOnce struct { -} - -func (*awsAwsjson11_deserializeOpStartAssociationsOnce) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpStartAssociationsOnce) 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 - } - - 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_deserializeOpErrorStartAssociationsOnce(response, &metadata) - } - output := &StartAssociationsOnceOutput{} - 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_deserializeOpDocumentStartAssociationsOnceOutput(&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_deserializeOpErrorStartAssociationsOnce(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AssociationDoesNotExist", errorCode): - return awsAwsjson11_deserializeErrorAssociationDoesNotExist(response, errorBody) - - case strings.EqualFold("InvalidAssociation", errorCode): - return awsAwsjson11_deserializeErrorInvalidAssociation(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpStartAutomationExecution struct { -} - -func (*awsAwsjson11_deserializeOpStartAutomationExecution) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpStartAutomationExecution) 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 - } - - 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_deserializeOpErrorStartAutomationExecution(response, &metadata) - } - output := &StartAutomationExecutionOutput{} - 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_deserializeOpDocumentStartAutomationExecutionOutput(&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_deserializeOpErrorStartAutomationExecution(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AutomationDefinitionNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorAutomationDefinitionNotFoundException(response, errorBody) - - case strings.EqualFold("AutomationDefinitionVersionNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorAutomationDefinitionVersionNotFoundException(response, errorBody) - - case strings.EqualFold("AutomationExecutionLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorAutomationExecutionLimitExceededException(response, errorBody) - - case strings.EqualFold("IdempotentParameterMismatch", errorCode): - return awsAwsjson11_deserializeErrorIdempotentParameterMismatch(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidAutomationExecutionParametersException", errorCode): - return awsAwsjson11_deserializeErrorInvalidAutomationExecutionParametersException(response, errorBody) - - case strings.EqualFold("InvalidTarget", errorCode): - return awsAwsjson11_deserializeErrorInvalidTarget(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpStartChangeRequestExecution struct { -} - -func (*awsAwsjson11_deserializeOpStartChangeRequestExecution) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpStartChangeRequestExecution) 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 - } - - 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_deserializeOpErrorStartChangeRequestExecution(response, &metadata) - } - output := &StartChangeRequestExecutionOutput{} - 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_deserializeOpDocumentStartChangeRequestExecutionOutput(&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_deserializeOpErrorStartChangeRequestExecution(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AutomationDefinitionNotApprovedException", errorCode): - return awsAwsjson11_deserializeErrorAutomationDefinitionNotApprovedException(response, errorBody) - - case strings.EqualFold("AutomationDefinitionNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorAutomationDefinitionNotFoundException(response, errorBody) - - case strings.EqualFold("AutomationDefinitionVersionNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorAutomationDefinitionVersionNotFoundException(response, errorBody) - - case strings.EqualFold("AutomationExecutionLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorAutomationExecutionLimitExceededException(response, errorBody) - - case strings.EqualFold("IdempotentParameterMismatch", errorCode): - return awsAwsjson11_deserializeErrorIdempotentParameterMismatch(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidAutomationExecutionParametersException", errorCode): - return awsAwsjson11_deserializeErrorInvalidAutomationExecutionParametersException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpStartSession struct { -} - -func (*awsAwsjson11_deserializeOpStartSession) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpStartSession) 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 - } - - 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_deserializeOpErrorStartSession(response, &metadata) - } - output := &StartSessionOutput{} - 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_deserializeOpDocumentStartSessionOutput(&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_deserializeOpErrorStartSession(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("TargetNotConnected", errorCode): - return awsAwsjson11_deserializeErrorTargetNotConnected(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpStopAutomationExecution struct { -} - -func (*awsAwsjson11_deserializeOpStopAutomationExecution) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpStopAutomationExecution) 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 - } - - 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_deserializeOpErrorStopAutomationExecution(response, &metadata) - } - output := &StopAutomationExecutionOutput{} - 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_deserializeOpDocumentStopAutomationExecutionOutput(&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_deserializeOpErrorStopAutomationExecution(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AutomationExecutionNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorAutomationExecutionNotFoundException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidAutomationStatusUpdateException", errorCode): - return awsAwsjson11_deserializeErrorInvalidAutomationStatusUpdateException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpTerminateSession struct { -} - -func (*awsAwsjson11_deserializeOpTerminateSession) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpTerminateSession) 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 - } - - 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_deserializeOpErrorTerminateSession(response, &metadata) - } - output := &TerminateSessionOutput{} - 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_deserializeOpDocumentTerminateSessionOutput(&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_deserializeOpErrorTerminateSession(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUnlabelParameterVersion struct { -} - -func (*awsAwsjson11_deserializeOpUnlabelParameterVersion) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUnlabelParameterVersion) 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 - } - - 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_deserializeOpErrorUnlabelParameterVersion(response, &metadata) - } - output := &UnlabelParameterVersionOutput{} - 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_deserializeOpDocumentUnlabelParameterVersionOutput(&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_deserializeOpErrorUnlabelParameterVersion(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ParameterNotFound", errorCode): - return awsAwsjson11_deserializeErrorParameterNotFound(response, errorBody) - - case strings.EqualFold("ParameterVersionNotFound", errorCode): - return awsAwsjson11_deserializeErrorParameterVersionNotFound(response, errorBody) - - case strings.EqualFold("TooManyUpdates", errorCode): - return awsAwsjson11_deserializeErrorTooManyUpdates(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateAssociation struct { -} - -func (*awsAwsjson11_deserializeOpUpdateAssociation) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateAssociation) 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 - } - - 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_deserializeOpErrorUpdateAssociation(response, &metadata) - } - output := &UpdateAssociationOutput{} - 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_deserializeOpDocumentUpdateAssociationOutput(&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_deserializeOpErrorUpdateAssociation(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AssociationDoesNotExist", errorCode): - return awsAwsjson11_deserializeErrorAssociationDoesNotExist(response, errorBody) - - case strings.EqualFold("AssociationVersionLimitExceeded", errorCode): - return awsAwsjson11_deserializeErrorAssociationVersionLimitExceeded(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidAssociationVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidAssociationVersion(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentVersion(response, errorBody) - - case strings.EqualFold("InvalidOutputLocation", errorCode): - return awsAwsjson11_deserializeErrorInvalidOutputLocation(response, errorBody) - - case strings.EqualFold("InvalidParameters", errorCode): - return awsAwsjson11_deserializeErrorInvalidParameters(response, errorBody) - - case strings.EqualFold("InvalidSchedule", errorCode): - return awsAwsjson11_deserializeErrorInvalidSchedule(response, errorBody) - - case strings.EqualFold("InvalidTarget", errorCode): - return awsAwsjson11_deserializeErrorInvalidTarget(response, errorBody) - - case strings.EqualFold("InvalidTargetMaps", errorCode): - return awsAwsjson11_deserializeErrorInvalidTargetMaps(response, errorBody) - - case strings.EqualFold("InvalidUpdate", errorCode): - return awsAwsjson11_deserializeErrorInvalidUpdate(response, errorBody) - - case strings.EqualFold("TooManyUpdates", errorCode): - return awsAwsjson11_deserializeErrorTooManyUpdates(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateAssociationStatus struct { -} - -func (*awsAwsjson11_deserializeOpUpdateAssociationStatus) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateAssociationStatus) 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 - } - - 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_deserializeOpErrorUpdateAssociationStatus(response, &metadata) - } - output := &UpdateAssociationStatusOutput{} - 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_deserializeOpDocumentUpdateAssociationStatusOutput(&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_deserializeOpErrorUpdateAssociationStatus(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AssociationDoesNotExist", errorCode): - return awsAwsjson11_deserializeErrorAssociationDoesNotExist(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - case strings.EqualFold("StatusUnchanged", errorCode): - return awsAwsjson11_deserializeErrorStatusUnchanged(response, errorBody) - - case strings.EqualFold("TooManyUpdates", errorCode): - return awsAwsjson11_deserializeErrorTooManyUpdates(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateDocument struct { -} - -func (*awsAwsjson11_deserializeOpUpdateDocument) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateDocument) 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 - } - - 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_deserializeOpErrorUpdateDocument(response, &metadata) - } - output := &UpdateDocumentOutput{} - 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_deserializeOpDocumentUpdateDocumentOutput(&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_deserializeOpErrorUpdateDocument(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DocumentVersionLimitExceeded", errorCode): - return awsAwsjson11_deserializeErrorDocumentVersionLimitExceeded(response, errorBody) - - case strings.EqualFold("DuplicateDocumentContent", errorCode): - return awsAwsjson11_deserializeErrorDuplicateDocumentContent(response, errorBody) - - case strings.EqualFold("DuplicateDocumentVersionName", errorCode): - return awsAwsjson11_deserializeErrorDuplicateDocumentVersionName(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentContent", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentContent(response, errorBody) - - case strings.EqualFold("InvalidDocumentOperation", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentOperation(response, errorBody) - - case strings.EqualFold("InvalidDocumentSchemaVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentSchemaVersion(response, errorBody) - - case strings.EqualFold("InvalidDocumentVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentVersion(response, errorBody) - - case strings.EqualFold("MaxDocumentSizeExceeded", errorCode): - return awsAwsjson11_deserializeErrorMaxDocumentSizeExceeded(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateDocumentDefaultVersion struct { -} - -func (*awsAwsjson11_deserializeOpUpdateDocumentDefaultVersion) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateDocumentDefaultVersion) 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 - } - - 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_deserializeOpErrorUpdateDocumentDefaultVersion(response, &metadata) - } - output := &UpdateDocumentDefaultVersionOutput{} - 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_deserializeOpDocumentUpdateDocumentDefaultVersionOutput(&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_deserializeOpErrorUpdateDocumentDefaultVersion(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentSchemaVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentSchemaVersion(response, errorBody) - - case strings.EqualFold("InvalidDocumentVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentVersion(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateDocumentMetadata struct { -} - -func (*awsAwsjson11_deserializeOpUpdateDocumentMetadata) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateDocumentMetadata) 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 - } - - 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_deserializeOpErrorUpdateDocumentMetadata(response, &metadata) - } - output := &UpdateDocumentMetadataOutput{} - 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_deserializeOpDocumentUpdateDocumentMetadataOutput(&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_deserializeOpErrorUpdateDocumentMetadata(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidDocument", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocument(response, errorBody) - - case strings.EqualFold("InvalidDocumentOperation", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentOperation(response, errorBody) - - case strings.EqualFold("InvalidDocumentVersion", errorCode): - return awsAwsjson11_deserializeErrorInvalidDocumentVersion(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateMaintenanceWindow struct { -} - -func (*awsAwsjson11_deserializeOpUpdateMaintenanceWindow) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateMaintenanceWindow) 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 - } - - 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_deserializeOpErrorUpdateMaintenanceWindow(response, &metadata) - } - output := &UpdateMaintenanceWindowOutput{} - 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_deserializeOpDocumentUpdateMaintenanceWindowOutput(&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_deserializeOpErrorUpdateMaintenanceWindow(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateMaintenanceWindowTarget struct { -} - -func (*awsAwsjson11_deserializeOpUpdateMaintenanceWindowTarget) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateMaintenanceWindowTarget) 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 - } - - 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_deserializeOpErrorUpdateMaintenanceWindowTarget(response, &metadata) - } - output := &UpdateMaintenanceWindowTargetOutput{} - 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_deserializeOpDocumentUpdateMaintenanceWindowTargetOutput(&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_deserializeOpErrorUpdateMaintenanceWindowTarget(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateMaintenanceWindowTask struct { -} - -func (*awsAwsjson11_deserializeOpUpdateMaintenanceWindowTask) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateMaintenanceWindowTask) 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 - } - - 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_deserializeOpErrorUpdateMaintenanceWindowTask(response, &metadata) - } - output := &UpdateMaintenanceWindowTaskOutput{} - 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_deserializeOpDocumentUpdateMaintenanceWindowTaskOutput(&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_deserializeOpErrorUpdateMaintenanceWindowTask(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateManagedInstanceRole struct { -} - -func (*awsAwsjson11_deserializeOpUpdateManagedInstanceRole) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateManagedInstanceRole) 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 - } - - 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_deserializeOpErrorUpdateManagedInstanceRole(response, &metadata) - } - output := &UpdateManagedInstanceRoleOutput{} - 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_deserializeOpDocumentUpdateManagedInstanceRoleOutput(&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_deserializeOpErrorUpdateManagedInstanceRole(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("InvalidInstanceId", errorCode): - return awsAwsjson11_deserializeErrorInvalidInstanceId(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateOpsItem struct { -} - -func (*awsAwsjson11_deserializeOpUpdateOpsItem) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateOpsItem) 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 - } - - 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_deserializeOpErrorUpdateOpsItem(response, &metadata) - } - output := &UpdateOpsItemOutput{} - 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_deserializeOpDocumentUpdateOpsItemOutput(&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_deserializeOpErrorUpdateOpsItem(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsItemAccessDeniedException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemAccessDeniedException(response, errorBody) - - case strings.EqualFold("OpsItemAlreadyExistsException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemAlreadyExistsException(response, errorBody) - - case strings.EqualFold("OpsItemConflictException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemConflictException(response, errorBody) - - case strings.EqualFold("OpsItemInvalidParameterException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemInvalidParameterException(response, errorBody) - - case strings.EqualFold("OpsItemLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemLimitExceededException(response, errorBody) - - case strings.EqualFold("OpsItemNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorOpsItemNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateOpsMetadata struct { -} - -func (*awsAwsjson11_deserializeOpUpdateOpsMetadata) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateOpsMetadata) 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 - } - - 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_deserializeOpErrorUpdateOpsMetadata(response, &metadata) - } - output := &UpdateOpsMetadataOutput{} - 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_deserializeOpDocumentUpdateOpsMetadataOutput(&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_deserializeOpErrorUpdateOpsMetadata(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("OpsMetadataInvalidArgumentException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataInvalidArgumentException(response, errorBody) - - case strings.EqualFold("OpsMetadataKeyLimitExceededException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataKeyLimitExceededException(response, errorBody) - - case strings.EqualFold("OpsMetadataNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataNotFoundException(response, errorBody) - - case strings.EqualFold("OpsMetadataTooManyUpdatesException", errorCode): - return awsAwsjson11_deserializeErrorOpsMetadataTooManyUpdatesException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdatePatchBaseline struct { -} - -func (*awsAwsjson11_deserializeOpUpdatePatchBaseline) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdatePatchBaseline) 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 - } - - 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_deserializeOpErrorUpdatePatchBaseline(response, &metadata) - } - output := &UpdatePatchBaselineOutput{} - 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_deserializeOpDocumentUpdatePatchBaselineOutput(&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_deserializeOpErrorUpdatePatchBaseline(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("DoesNotExistException", errorCode): - return awsAwsjson11_deserializeErrorDoesNotExistException(response, errorBody) - - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateResourceDataSync struct { -} - -func (*awsAwsjson11_deserializeOpUpdateResourceDataSync) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateResourceDataSync) 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 - } - - 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_deserializeOpErrorUpdateResourceDataSync(response, &metadata) - } - output := &UpdateResourceDataSyncOutput{} - 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_deserializeOpDocumentUpdateResourceDataSyncOutput(&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_deserializeOpErrorUpdateResourceDataSync(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ResourceDataSyncConflictException", errorCode): - return awsAwsjson11_deserializeErrorResourceDataSyncConflictException(response, errorBody) - - case strings.EqualFold("ResourceDataSyncInvalidConfigurationException", errorCode): - return awsAwsjson11_deserializeErrorResourceDataSyncInvalidConfigurationException(response, errorBody) - - case strings.EqualFold("ResourceDataSyncNotFoundException", errorCode): - return awsAwsjson11_deserializeErrorResourceDataSyncNotFoundException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsjson11_deserializeOpUpdateServiceSetting struct { -} - -func (*awsAwsjson11_deserializeOpUpdateServiceSetting) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsjson11_deserializeOpUpdateServiceSetting) 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 - } - - 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_deserializeOpErrorUpdateServiceSetting(response, &metadata) - } - output := &UpdateServiceSettingOutput{} - 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_deserializeOpDocumentUpdateServiceSettingOutput(&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_deserializeOpErrorUpdateServiceSetting(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerError", errorCode): - return awsAwsjson11_deserializeErrorInternalServerError(response, errorBody) - - case strings.EqualFold("ServiceSettingNotFound", errorCode): - return awsAwsjson11_deserializeErrorServiceSettingNotFound(response, errorBody) - - case strings.EqualFold("TooManyUpdates", errorCode): - return awsAwsjson11_deserializeErrorTooManyUpdates(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsAwsjson11_deserializeErrorAlreadyExistsException(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.AlreadyExistsException{} - err := awsAwsjson11_deserializeDocumentAlreadyExistsException(&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_deserializeErrorAssociatedInstances(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.AssociatedInstances{} - err := awsAwsjson11_deserializeDocumentAssociatedInstances(&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_deserializeErrorAssociationAlreadyExists(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.AssociationAlreadyExists{} - err := awsAwsjson11_deserializeDocumentAssociationAlreadyExists(&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_deserializeErrorAssociationDoesNotExist(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.AssociationDoesNotExist{} - err := awsAwsjson11_deserializeDocumentAssociationDoesNotExist(&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_deserializeErrorAssociationExecutionDoesNotExist(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.AssociationExecutionDoesNotExist{} - err := awsAwsjson11_deserializeDocumentAssociationExecutionDoesNotExist(&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_deserializeErrorAssociationLimitExceeded(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.AssociationLimitExceeded{} - err := awsAwsjson11_deserializeDocumentAssociationLimitExceeded(&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_deserializeErrorAssociationVersionLimitExceeded(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.AssociationVersionLimitExceeded{} - err := awsAwsjson11_deserializeDocumentAssociationVersionLimitExceeded(&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_deserializeErrorAutomationDefinitionNotApprovedException(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.AutomationDefinitionNotApprovedException{} - err := awsAwsjson11_deserializeDocumentAutomationDefinitionNotApprovedException(&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_deserializeErrorAutomationDefinitionNotFoundException(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.AutomationDefinitionNotFoundException{} - err := awsAwsjson11_deserializeDocumentAutomationDefinitionNotFoundException(&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_deserializeErrorAutomationDefinitionVersionNotFoundException(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.AutomationDefinitionVersionNotFoundException{} - err := awsAwsjson11_deserializeDocumentAutomationDefinitionVersionNotFoundException(&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_deserializeErrorAutomationExecutionLimitExceededException(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.AutomationExecutionLimitExceededException{} - err := awsAwsjson11_deserializeDocumentAutomationExecutionLimitExceededException(&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_deserializeErrorAutomationExecutionNotFoundException(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.AutomationExecutionNotFoundException{} - err := awsAwsjson11_deserializeDocumentAutomationExecutionNotFoundException(&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_deserializeErrorAutomationStepNotFoundException(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.AutomationStepNotFoundException{} - err := awsAwsjson11_deserializeDocumentAutomationStepNotFoundException(&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_deserializeErrorComplianceTypeCountLimitExceededException(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.ComplianceTypeCountLimitExceededException{} - err := awsAwsjson11_deserializeDocumentComplianceTypeCountLimitExceededException(&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_deserializeErrorCustomSchemaCountLimitExceededException(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.CustomSchemaCountLimitExceededException{} - err := awsAwsjson11_deserializeDocumentCustomSchemaCountLimitExceededException(&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_deserializeErrorDocumentAlreadyExists(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.DocumentAlreadyExists{} - err := awsAwsjson11_deserializeDocumentDocumentAlreadyExists(&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_deserializeErrorDocumentLimitExceeded(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.DocumentLimitExceeded{} - err := awsAwsjson11_deserializeDocumentDocumentLimitExceeded(&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_deserializeErrorDocumentPermissionLimit(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.DocumentPermissionLimit{} - err := awsAwsjson11_deserializeDocumentDocumentPermissionLimit(&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_deserializeErrorDocumentVersionLimitExceeded(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.DocumentVersionLimitExceeded{} - err := awsAwsjson11_deserializeDocumentDocumentVersionLimitExceeded(&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_deserializeErrorDoesNotExistException(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.DoesNotExistException{} - err := awsAwsjson11_deserializeDocumentDoesNotExistException(&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_deserializeErrorDuplicateDocumentContent(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.DuplicateDocumentContent{} - err := awsAwsjson11_deserializeDocumentDuplicateDocumentContent(&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_deserializeErrorDuplicateDocumentVersionName(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.DuplicateDocumentVersionName{} - err := awsAwsjson11_deserializeDocumentDuplicateDocumentVersionName(&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_deserializeErrorDuplicateInstanceId(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.DuplicateInstanceId{} - err := awsAwsjson11_deserializeDocumentDuplicateInstanceId(&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_deserializeErrorFeatureNotAvailableException(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.FeatureNotAvailableException{} - err := awsAwsjson11_deserializeDocumentFeatureNotAvailableException(&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_deserializeErrorHierarchyLevelLimitExceededException(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.HierarchyLevelLimitExceededException{} - err := awsAwsjson11_deserializeDocumentHierarchyLevelLimitExceededException(&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_deserializeErrorHierarchyTypeMismatchException(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.HierarchyTypeMismatchException{} - err := awsAwsjson11_deserializeDocumentHierarchyTypeMismatchException(&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_deserializeErrorIdempotentParameterMismatch(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.IdempotentParameterMismatch{} - err := awsAwsjson11_deserializeDocumentIdempotentParameterMismatch(&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_deserializeErrorIncompatiblePolicyException(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.IncompatiblePolicyException{} - err := awsAwsjson11_deserializeDocumentIncompatiblePolicyException(&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_deserializeErrorInternalServerError(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.InternalServerError{} - err := awsAwsjson11_deserializeDocumentInternalServerError(&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_deserializeErrorInvalidActivation(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.InvalidActivation{} - err := awsAwsjson11_deserializeDocumentInvalidActivation(&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_deserializeErrorInvalidActivationId(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.InvalidActivationId{} - err := awsAwsjson11_deserializeDocumentInvalidActivationId(&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_deserializeErrorInvalidAggregatorException(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.InvalidAggregatorException{} - err := awsAwsjson11_deserializeDocumentInvalidAggregatorException(&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_deserializeErrorInvalidAllowedPatternException(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.InvalidAllowedPatternException{} - err := awsAwsjson11_deserializeDocumentInvalidAllowedPatternException(&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_deserializeErrorInvalidAssociation(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.InvalidAssociation{} - err := awsAwsjson11_deserializeDocumentInvalidAssociation(&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_deserializeErrorInvalidAssociationVersion(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.InvalidAssociationVersion{} - err := awsAwsjson11_deserializeDocumentInvalidAssociationVersion(&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_deserializeErrorInvalidAutomationExecutionParametersException(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.InvalidAutomationExecutionParametersException{} - err := awsAwsjson11_deserializeDocumentInvalidAutomationExecutionParametersException(&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_deserializeErrorInvalidAutomationSignalException(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.InvalidAutomationSignalException{} - err := awsAwsjson11_deserializeDocumentInvalidAutomationSignalException(&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_deserializeErrorInvalidAutomationStatusUpdateException(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.InvalidAutomationStatusUpdateException{} - err := awsAwsjson11_deserializeDocumentInvalidAutomationStatusUpdateException(&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_deserializeErrorInvalidCommandId(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.InvalidCommandId{} - err := awsAwsjson11_deserializeDocumentInvalidCommandId(&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_deserializeErrorInvalidDeleteInventoryParametersException(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.InvalidDeleteInventoryParametersException{} - err := awsAwsjson11_deserializeDocumentInvalidDeleteInventoryParametersException(&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_deserializeErrorInvalidDeletionIdException(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.InvalidDeletionIdException{} - err := awsAwsjson11_deserializeDocumentInvalidDeletionIdException(&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_deserializeErrorInvalidDocument(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.InvalidDocument{} - err := awsAwsjson11_deserializeDocumentInvalidDocument(&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_deserializeErrorInvalidDocumentContent(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.InvalidDocumentContent{} - err := awsAwsjson11_deserializeDocumentInvalidDocumentContent(&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_deserializeErrorInvalidDocumentOperation(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.InvalidDocumentOperation{} - err := awsAwsjson11_deserializeDocumentInvalidDocumentOperation(&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_deserializeErrorInvalidDocumentSchemaVersion(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.InvalidDocumentSchemaVersion{} - err := awsAwsjson11_deserializeDocumentInvalidDocumentSchemaVersion(&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_deserializeErrorInvalidDocumentType(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.InvalidDocumentType{} - err := awsAwsjson11_deserializeDocumentInvalidDocumentType(&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_deserializeErrorInvalidDocumentVersion(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.InvalidDocumentVersion{} - err := awsAwsjson11_deserializeDocumentInvalidDocumentVersion(&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_deserializeErrorInvalidFilter(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.InvalidFilter{} - err := awsAwsjson11_deserializeDocumentInvalidFilter(&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_deserializeErrorInvalidFilterKey(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.InvalidFilterKey{} - err := awsAwsjson11_deserializeDocumentInvalidFilterKey(&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_deserializeErrorInvalidFilterOption(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.InvalidFilterOption{} - err := awsAwsjson11_deserializeDocumentInvalidFilterOption(&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_deserializeErrorInvalidFilterValue(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.InvalidFilterValue{} - err := awsAwsjson11_deserializeDocumentInvalidFilterValue(&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_deserializeErrorInvalidInstanceId(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.InvalidInstanceId{} - err := awsAwsjson11_deserializeDocumentInvalidInstanceId(&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_deserializeErrorInvalidInstanceInformationFilterValue(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.InvalidInstanceInformationFilterValue{} - err := awsAwsjson11_deserializeDocumentInvalidInstanceInformationFilterValue(&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_deserializeErrorInvalidInventoryGroupException(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.InvalidInventoryGroupException{} - err := awsAwsjson11_deserializeDocumentInvalidInventoryGroupException(&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_deserializeErrorInvalidInventoryItemContextException(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.InvalidInventoryItemContextException{} - err := awsAwsjson11_deserializeDocumentInvalidInventoryItemContextException(&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_deserializeErrorInvalidInventoryRequestException(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.InvalidInventoryRequestException{} - err := awsAwsjson11_deserializeDocumentInvalidInventoryRequestException(&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_deserializeErrorInvalidItemContentException(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.InvalidItemContentException{} - err := awsAwsjson11_deserializeDocumentInvalidItemContentException(&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_deserializeErrorInvalidKeyId(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.InvalidKeyId{} - err := awsAwsjson11_deserializeDocumentInvalidKeyId(&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_deserializeErrorInvalidNextToken(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.InvalidNextToken{} - err := awsAwsjson11_deserializeDocumentInvalidNextToken(&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_deserializeErrorInvalidNotificationConfig(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.InvalidNotificationConfig{} - err := awsAwsjson11_deserializeDocumentInvalidNotificationConfig(&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_deserializeErrorInvalidOptionException(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.InvalidOptionException{} - err := awsAwsjson11_deserializeDocumentInvalidOptionException(&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_deserializeErrorInvalidOutputFolder(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.InvalidOutputFolder{} - err := awsAwsjson11_deserializeDocumentInvalidOutputFolder(&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_deserializeErrorInvalidOutputLocation(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.InvalidOutputLocation{} - err := awsAwsjson11_deserializeDocumentInvalidOutputLocation(&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_deserializeErrorInvalidParameters(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.InvalidParameters{} - err := awsAwsjson11_deserializeDocumentInvalidParameters(&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_deserializeErrorInvalidPermissionType(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.InvalidPermissionType{} - err := awsAwsjson11_deserializeDocumentInvalidPermissionType(&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_deserializeErrorInvalidPluginName(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.InvalidPluginName{} - err := awsAwsjson11_deserializeDocumentInvalidPluginName(&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_deserializeErrorInvalidPolicyAttributeException(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.InvalidPolicyAttributeException{} - err := awsAwsjson11_deserializeDocumentInvalidPolicyAttributeException(&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_deserializeErrorInvalidPolicyTypeException(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.InvalidPolicyTypeException{} - err := awsAwsjson11_deserializeDocumentInvalidPolicyTypeException(&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_deserializeErrorInvalidResourceId(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.InvalidResourceId{} - err := awsAwsjson11_deserializeDocumentInvalidResourceId(&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_deserializeErrorInvalidResourceType(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.InvalidResourceType{} - err := awsAwsjson11_deserializeDocumentInvalidResourceType(&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_deserializeErrorInvalidResultAttributeException(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.InvalidResultAttributeException{} - err := awsAwsjson11_deserializeDocumentInvalidResultAttributeException(&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_deserializeErrorInvalidRole(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.InvalidRole{} - err := awsAwsjson11_deserializeDocumentInvalidRole(&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_deserializeErrorInvalidSchedule(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.InvalidSchedule{} - err := awsAwsjson11_deserializeDocumentInvalidSchedule(&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_deserializeErrorInvalidTag(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.InvalidTag{} - err := awsAwsjson11_deserializeDocumentInvalidTag(&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_deserializeErrorInvalidTarget(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.InvalidTarget{} - err := awsAwsjson11_deserializeDocumentInvalidTarget(&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_deserializeErrorInvalidTargetMaps(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.InvalidTargetMaps{} - err := awsAwsjson11_deserializeDocumentInvalidTargetMaps(&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_deserializeErrorInvalidTypeNameException(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.InvalidTypeNameException{} - err := awsAwsjson11_deserializeDocumentInvalidTypeNameException(&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_deserializeErrorInvalidUpdate(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.InvalidUpdate{} - err := awsAwsjson11_deserializeDocumentInvalidUpdate(&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_deserializeErrorInvocationDoesNotExist(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.InvocationDoesNotExist{} - err := awsAwsjson11_deserializeDocumentInvocationDoesNotExist(&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_deserializeErrorItemContentMismatchException(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.ItemContentMismatchException{} - err := awsAwsjson11_deserializeDocumentItemContentMismatchException(&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_deserializeErrorItemSizeLimitExceededException(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.ItemSizeLimitExceededException{} - err := awsAwsjson11_deserializeDocumentItemSizeLimitExceededException(&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_deserializeErrorMaxDocumentSizeExceeded(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.MaxDocumentSizeExceeded{} - err := awsAwsjson11_deserializeDocumentMaxDocumentSizeExceeded(&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_deserializeErrorOpsItemAccessDeniedException(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.OpsItemAccessDeniedException{} - err := awsAwsjson11_deserializeDocumentOpsItemAccessDeniedException(&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_deserializeErrorOpsItemAlreadyExistsException(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.OpsItemAlreadyExistsException{} - err := awsAwsjson11_deserializeDocumentOpsItemAlreadyExistsException(&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_deserializeErrorOpsItemConflictException(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.OpsItemConflictException{} - err := awsAwsjson11_deserializeDocumentOpsItemConflictException(&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_deserializeErrorOpsItemInvalidParameterException(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.OpsItemInvalidParameterException{} - err := awsAwsjson11_deserializeDocumentOpsItemInvalidParameterException(&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_deserializeErrorOpsItemLimitExceededException(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.OpsItemLimitExceededException{} - err := awsAwsjson11_deserializeDocumentOpsItemLimitExceededException(&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_deserializeErrorOpsItemNotFoundException(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.OpsItemNotFoundException{} - err := awsAwsjson11_deserializeDocumentOpsItemNotFoundException(&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_deserializeErrorOpsItemRelatedItemAlreadyExistsException(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.OpsItemRelatedItemAlreadyExistsException{} - err := awsAwsjson11_deserializeDocumentOpsItemRelatedItemAlreadyExistsException(&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_deserializeErrorOpsItemRelatedItemAssociationNotFoundException(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.OpsItemRelatedItemAssociationNotFoundException{} - err := awsAwsjson11_deserializeDocumentOpsItemRelatedItemAssociationNotFoundException(&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_deserializeErrorOpsMetadataAlreadyExistsException(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.OpsMetadataAlreadyExistsException{} - err := awsAwsjson11_deserializeDocumentOpsMetadataAlreadyExistsException(&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_deserializeErrorOpsMetadataInvalidArgumentException(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.OpsMetadataInvalidArgumentException{} - err := awsAwsjson11_deserializeDocumentOpsMetadataInvalidArgumentException(&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_deserializeErrorOpsMetadataKeyLimitExceededException(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.OpsMetadataKeyLimitExceededException{} - err := awsAwsjson11_deserializeDocumentOpsMetadataKeyLimitExceededException(&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_deserializeErrorOpsMetadataLimitExceededException(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.OpsMetadataLimitExceededException{} - err := awsAwsjson11_deserializeDocumentOpsMetadataLimitExceededException(&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_deserializeErrorOpsMetadataNotFoundException(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.OpsMetadataNotFoundException{} - err := awsAwsjson11_deserializeDocumentOpsMetadataNotFoundException(&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_deserializeErrorOpsMetadataTooManyUpdatesException(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.OpsMetadataTooManyUpdatesException{} - err := awsAwsjson11_deserializeDocumentOpsMetadataTooManyUpdatesException(&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_deserializeErrorParameterAlreadyExists(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.ParameterAlreadyExists{} - err := awsAwsjson11_deserializeDocumentParameterAlreadyExists(&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_deserializeErrorParameterLimitExceeded(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.ParameterLimitExceeded{} - err := awsAwsjson11_deserializeDocumentParameterLimitExceeded(&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_deserializeErrorParameterMaxVersionLimitExceeded(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.ParameterMaxVersionLimitExceeded{} - err := awsAwsjson11_deserializeDocumentParameterMaxVersionLimitExceeded(&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_deserializeErrorParameterNotFound(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.ParameterNotFound{} - err := awsAwsjson11_deserializeDocumentParameterNotFound(&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_deserializeErrorParameterPatternMismatchException(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.ParameterPatternMismatchException{} - err := awsAwsjson11_deserializeDocumentParameterPatternMismatchException(&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_deserializeErrorParameterVersionLabelLimitExceeded(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.ParameterVersionLabelLimitExceeded{} - err := awsAwsjson11_deserializeDocumentParameterVersionLabelLimitExceeded(&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_deserializeErrorParameterVersionNotFound(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.ParameterVersionNotFound{} - err := awsAwsjson11_deserializeDocumentParameterVersionNotFound(&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_deserializeErrorPoliciesLimitExceededException(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.PoliciesLimitExceededException{} - err := awsAwsjson11_deserializeDocumentPoliciesLimitExceededException(&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_deserializeErrorResourceDataSyncAlreadyExistsException(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.ResourceDataSyncAlreadyExistsException{} - err := awsAwsjson11_deserializeDocumentResourceDataSyncAlreadyExistsException(&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_deserializeErrorResourceDataSyncConflictException(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.ResourceDataSyncConflictException{} - err := awsAwsjson11_deserializeDocumentResourceDataSyncConflictException(&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_deserializeErrorResourceDataSyncCountExceededException(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.ResourceDataSyncCountExceededException{} - err := awsAwsjson11_deserializeDocumentResourceDataSyncCountExceededException(&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_deserializeErrorResourceDataSyncInvalidConfigurationException(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.ResourceDataSyncInvalidConfigurationException{} - err := awsAwsjson11_deserializeDocumentResourceDataSyncInvalidConfigurationException(&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_deserializeErrorResourceDataSyncNotFoundException(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.ResourceDataSyncNotFoundException{} - err := awsAwsjson11_deserializeDocumentResourceDataSyncNotFoundException(&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_deserializeErrorResourceInUseException(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.ResourceInUseException{} - err := awsAwsjson11_deserializeDocumentResourceInUseException(&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_deserializeErrorResourceLimitExceededException(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.ResourceLimitExceededException{} - err := awsAwsjson11_deserializeDocumentResourceLimitExceededException(&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_deserializeErrorResourcePolicyConflictException(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.ResourcePolicyConflictException{} - err := awsAwsjson11_deserializeDocumentResourcePolicyConflictException(&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_deserializeErrorResourcePolicyInvalidParameterException(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.ResourcePolicyInvalidParameterException{} - err := awsAwsjson11_deserializeDocumentResourcePolicyInvalidParameterException(&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_deserializeErrorResourcePolicyLimitExceededException(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.ResourcePolicyLimitExceededException{} - err := awsAwsjson11_deserializeDocumentResourcePolicyLimitExceededException(&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_deserializeErrorServiceSettingNotFound(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.ServiceSettingNotFound{} - err := awsAwsjson11_deserializeDocumentServiceSettingNotFound(&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_deserializeErrorStatusUnchanged(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.StatusUnchanged{} - err := awsAwsjson11_deserializeDocumentStatusUnchanged(&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_deserializeErrorSubTypeCountLimitExceededException(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.SubTypeCountLimitExceededException{} - err := awsAwsjson11_deserializeDocumentSubTypeCountLimitExceededException(&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_deserializeErrorTargetInUseException(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.TargetInUseException{} - err := awsAwsjson11_deserializeDocumentTargetInUseException(&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_deserializeErrorTargetNotConnected(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.TargetNotConnected{} - err := awsAwsjson11_deserializeDocumentTargetNotConnected(&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_deserializeErrorTooManyTagsError(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.TooManyTagsError{} - err := awsAwsjson11_deserializeDocumentTooManyTagsError(&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_deserializeErrorTooManyUpdates(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.TooManyUpdates{} - err := awsAwsjson11_deserializeDocumentTooManyUpdates(&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_deserializeErrorTotalSizeLimitExceededException(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.TotalSizeLimitExceededException{} - err := awsAwsjson11_deserializeDocumentTotalSizeLimitExceededException(&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_deserializeErrorUnsupportedCalendarException(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.UnsupportedCalendarException{} - err := awsAwsjson11_deserializeDocumentUnsupportedCalendarException(&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_deserializeErrorUnsupportedFeatureRequiredException(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.UnsupportedFeatureRequiredException{} - err := awsAwsjson11_deserializeDocumentUnsupportedFeatureRequiredException(&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_deserializeErrorUnsupportedInventoryItemContextException(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.UnsupportedInventoryItemContextException{} - err := awsAwsjson11_deserializeDocumentUnsupportedInventoryItemContextException(&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_deserializeErrorUnsupportedInventorySchemaVersionException(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.UnsupportedInventorySchemaVersionException{} - err := awsAwsjson11_deserializeDocumentUnsupportedInventorySchemaVersionException(&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_deserializeErrorUnsupportedOperatingSystem(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.UnsupportedOperatingSystem{} - err := awsAwsjson11_deserializeDocumentUnsupportedOperatingSystem(&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_deserializeErrorUnsupportedParameterType(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.UnsupportedParameterType{} - err := awsAwsjson11_deserializeDocumentUnsupportedParameterType(&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_deserializeErrorUnsupportedPlatformType(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.UnsupportedPlatformType{} - err := awsAwsjson11_deserializeDocumentUnsupportedPlatformType(&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_deserializeDocumentAccountIdList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccountId to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAccounts(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Account to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAccountSharingInfo(v **types.AccountSharingInfo, 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.AccountSharingInfo - if *v == nil { - sv = &types.AccountSharingInfo{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AccountId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccountId to be of type string, got %T instead", value) - } - sv.AccountId = ptr.String(jtv) - } - - case "SharedDocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SharedDocumentVersion to be of type string, got %T instead", value) - } - sv.SharedDocumentVersion = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAccountSharingInfoList(v *[]types.AccountSharingInfo, 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.AccountSharingInfo - if *v == nil { - cv = []types.AccountSharingInfo{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.AccountSharingInfo - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAccountSharingInfo(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentActivation(v **types.Activation, 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.Activation - if *v == nil { - sv = &types.Activation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ActivationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ActivationId to be of type string, got %T instead", value) - } - sv.ActivationId = ptr.String(jtv) - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected CreatedDate to be a JSON Number, got %T instead", value) - - } - } - - case "DefaultInstanceName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DefaultInstanceName to be of type string, got %T instead", value) - } - sv.DefaultInstanceName = ptr.String(jtv) - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ActivationDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "ExpirationDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ExpirationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected ExpirationDate to be a JSON Number, got %T instead", value) - - } - } - - case "Expired": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected Boolean to be of type *bool, got %T instead", value) - } - sv.Expired = jtv - } - - case "IamRole": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected IamRole to be of type string, got %T instead", value) - } - sv.IamRole = ptr.String(jtv) - } - - case "RegistrationLimit": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected RegistrationLimit to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.RegistrationLimit = ptr.Int32(int32(i64)) - } - - case "RegistrationsCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected RegistrationsCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.RegistrationsCount = ptr.Int32(int32(i64)) - } - - case "Tags": - if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentActivationList(v *[]types.Activation, 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.Activation - if *v == nil { - cv = []types.Activation{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.Activation - destAddr := &col - if err := awsAwsjson11_deserializeDocumentActivation(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAlarm(v **types.Alarm, 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.Alarm - if *v == nil { - sv = &types.Alarm{} - } 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 AlarmName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAlarmConfiguration(v **types.AlarmConfiguration, 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.AlarmConfiguration - if *v == nil { - sv = &types.AlarmConfiguration{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Alarms": - if err := awsAwsjson11_deserializeDocumentAlarmList(&sv.Alarms, value); err != nil { - return err - } - - case "IgnorePollAlarmFailure": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected Boolean to be of type *bool, got %T instead", value) - } - sv.IgnorePollAlarmFailure = jtv - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAlarmList(v *[]types.Alarm, 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.Alarm - if *v == nil { - cv = []types.Alarm{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.Alarm - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAlarm(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAlarmStateInformation(v **types.AlarmStateInformation, 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.AlarmStateInformation - if *v == nil { - sv = &types.AlarmStateInformation{} - } 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 AlarmName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "State": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ExternalAlarmState to be of type string, got %T instead", value) - } - sv.State = types.ExternalAlarmState(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAlarmStateInformationList(v *[]types.AlarmStateInformation, 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.AlarmStateInformation - if *v == nil { - cv = []types.AlarmStateInformation{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.AlarmStateInformation - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAlarmStateInformation(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAlreadyExistsException(v **types.AlreadyExistsException, 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.AlreadyExistsException - if *v == nil { - sv = &types.AlreadyExistsException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociatedInstances(v **types.AssociatedInstances, 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.AssociatedInstances - if *v == nil { - sv = &types.AssociatedInstances{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociation(v **types.Association, 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.Association - if *v == nil { - sv = &types.Association{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationId to be of type string, got %T instead", value) - } - sv.AssociationId = ptr.String(jtv) - } - - case "AssociationName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationName to be of type string, got %T instead", value) - } - sv.AssociationName = ptr.String(jtv) - } - - case "AssociationVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationVersion to be of type string, got %T instead", value) - } - sv.AssociationVersion = ptr.String(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "InstanceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - sv.InstanceId = ptr.String(jtv) - } - - case "LastExecutionDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastExecutionDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentARN to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Overview": - if err := awsAwsjson11_deserializeDocumentAssociationOverview(&sv.Overview, value); err != nil { - return err - } - - case "ScheduleExpression": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ScheduleExpression to be of type string, got %T instead", value) - } - sv.ScheduleExpression = ptr.String(jtv) - } - - case "ScheduleOffset": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ScheduleOffset to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ScheduleOffset = ptr.Int32(int32(i64)) - } - - case "TargetMaps": - if err := awsAwsjson11_deserializeDocumentTargetMaps(&sv.TargetMaps, value); err != nil { - return err - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationAlreadyExists(v **types.AssociationAlreadyExists, 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.AssociationAlreadyExists - if *v == nil { - sv = &types.AssociationAlreadyExists{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationDescription(v **types.AssociationDescription, 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.AssociationDescription - if *v == nil { - sv = &types.AssociationDescription{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.AlarmConfiguration, value); err != nil { - return err - } - - case "ApplyOnlyAtCronInterval": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected ApplyOnlyAtCronInterval to be of type *bool, got %T instead", value) - } - sv.ApplyOnlyAtCronInterval = jtv - } - - case "AssociationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationId to be of type string, got %T instead", value) - } - sv.AssociationId = ptr.String(jtv) - } - - case "AssociationName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationName to be of type string, got %T instead", value) - } - sv.AssociationName = ptr.String(jtv) - } - - case "AssociationVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationVersion to be of type string, got %T instead", value) - } - sv.AssociationVersion = ptr.String(jtv) - } - - case "AutomationTargetParameterName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationTargetParameterName to be of type string, got %T instead", value) - } - sv.AutomationTargetParameterName = ptr.String(jtv) - } - - case "CalendarNames": - if err := awsAwsjson11_deserializeDocumentCalendarNameOrARNList(&sv.CalendarNames, value); err != nil { - return err - } - - case "ComplianceSeverity": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationComplianceSeverity to be of type string, got %T instead", value) - } - sv.ComplianceSeverity = types.AssociationComplianceSeverity(jtv) - } - - case "Date": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.Date = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "InstanceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - sv.InstanceId = ptr.String(jtv) - } - - case "LastExecutionDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastExecutionDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastSuccessfulExecutionDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastSuccessfulExecutionDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastUpdateAssociationDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastUpdateAssociationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "MaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.MaxConcurrency = ptr.String(jtv) - } - - case "MaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.MaxErrors = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentARN to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "OutputLocation": - if err := awsAwsjson11_deserializeDocumentInstanceAssociationOutputLocation(&sv.OutputLocation, value); err != nil { - return err - } - - case "Overview": - if err := awsAwsjson11_deserializeDocumentAssociationOverview(&sv.Overview, value); err != nil { - return err - } - - case "Parameters": - if err := awsAwsjson11_deserializeDocumentParameters(&sv.Parameters, value); err != nil { - return err - } - - case "ScheduleExpression": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ScheduleExpression to be of type string, got %T instead", value) - } - sv.ScheduleExpression = ptr.String(jtv) - } - - case "ScheduleOffset": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ScheduleOffset to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ScheduleOffset = ptr.Int32(int32(i64)) - } - - case "Status": - if err := awsAwsjson11_deserializeDocumentAssociationStatus(&sv.Status, value); err != nil { - return err - } - - case "SyncCompliance": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationSyncCompliance to be of type string, got %T instead", value) - } - sv.SyncCompliance = types.AssociationSyncCompliance(jtv) - } - - case "TargetLocations": - if err := awsAwsjson11_deserializeDocumentTargetLocations(&sv.TargetLocations, value); err != nil { - return err - } - - case "TargetMaps": - if err := awsAwsjson11_deserializeDocumentTargetMaps(&sv.TargetMaps, value); err != nil { - return err - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - case "TriggeredAlarms": - if err := awsAwsjson11_deserializeDocumentAlarmStateInformationList(&sv.TriggeredAlarms, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationDescriptionList(v *[]types.AssociationDescription, 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.AssociationDescription - if *v == nil { - cv = []types.AssociationDescription{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.AssociationDescription - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAssociationDescription(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationDoesNotExist(v **types.AssociationDoesNotExist, 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.AssociationDoesNotExist - if *v == nil { - sv = &types.AssociationDoesNotExist{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationExecution(v **types.AssociationExecution, 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.AssociationExecution - if *v == nil { - sv = &types.AssociationExecution{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.AlarmConfiguration, value); err != nil { - return err - } - - case "AssociationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationId to be of type string, got %T instead", value) - } - sv.AssociationId = ptr.String(jtv) - } - - case "AssociationVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationVersion to be of type string, got %T instead", value) - } - sv.AssociationVersion = ptr.String(jtv) - } - - case "CreatedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "DetailedStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusName to be of type string, got %T instead", value) - } - sv.DetailedStatus = ptr.String(jtv) - } - - case "ExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationExecutionId to be of type string, got %T instead", value) - } - sv.ExecutionId = ptr.String(jtv) - } - - case "LastExecutionDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastExecutionDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ResourceCountByStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceCountByStatus to be of type string, got %T instead", value) - } - sv.ResourceCountByStatus = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusName to be of type string, got %T instead", value) - } - sv.Status = ptr.String(jtv) - } - - case "TriggeredAlarms": - if err := awsAwsjson11_deserializeDocumentAlarmStateInformationList(&sv.TriggeredAlarms, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationExecutionDoesNotExist(v **types.AssociationExecutionDoesNotExist, 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.AssociationExecutionDoesNotExist - if *v == nil { - sv = &types.AssociationExecutionDoesNotExist{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationExecutionsList(v *[]types.AssociationExecution, 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.AssociationExecution - if *v == nil { - cv = []types.AssociationExecution{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.AssociationExecution - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAssociationExecution(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationExecutionTarget(v **types.AssociationExecutionTarget, 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.AssociationExecutionTarget - if *v == nil { - sv = &types.AssociationExecutionTarget{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationId to be of type string, got %T instead", value) - } - sv.AssociationId = ptr.String(jtv) - } - - case "AssociationVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationVersion to be of type string, got %T instead", value) - } - sv.AssociationVersion = ptr.String(jtv) - } - - case "DetailedStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusName to be of type string, got %T instead", value) - } - sv.DetailedStatus = ptr.String(jtv) - } - - case "ExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationExecutionId to be of type string, got %T instead", value) - } - sv.ExecutionId = ptr.String(jtv) - } - - case "LastExecutionDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastExecutionDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "OutputSource": - if err := awsAwsjson11_deserializeDocumentOutputSource(&sv.OutputSource, value); err != nil { - return err - } - - case "ResourceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationResourceId to be of type string, got %T instead", value) - } - sv.ResourceId = ptr.String(jtv) - } - - case "ResourceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationResourceType to be of type string, got %T instead", value) - } - sv.ResourceType = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusName to be of type string, got %T instead", value) - } - sv.Status = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationExecutionTargetsList(v *[]types.AssociationExecutionTarget, 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.AssociationExecutionTarget - if *v == nil { - cv = []types.AssociationExecutionTarget{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.AssociationExecutionTarget - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAssociationExecutionTarget(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationLimitExceeded(v **types.AssociationLimitExceeded, 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.AssociationLimitExceeded - if *v == nil { - sv = &types.AssociationLimitExceeded{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationList(v *[]types.Association, 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.Association - if *v == nil { - cv = []types.Association{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.Association - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAssociation(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationOverview(v **types.AssociationOverview, 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.AssociationOverview - if *v == nil { - sv = &types.AssociationOverview{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationStatusAggregatedCount": - if err := awsAwsjson11_deserializeDocumentAssociationStatusAggregatedCount(&sv.AssociationStatusAggregatedCount, value); err != nil { - return err - } - - case "DetailedStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusName to be of type string, got %T instead", value) - } - sv.DetailedStatus = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusName to be of type string, got %T instead", value) - } - sv.Status = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationStatus(v **types.AssociationStatus, 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.AssociationStatus - if *v == nil { - sv = &types.AssociationStatus{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AdditionalInfo": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusAdditionalInfo to be of type string, got %T instead", value) - } - sv.AdditionalInfo = ptr.String(jtv) - } - - case "Date": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.Date = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationStatusName to be of type string, got %T instead", value) - } - sv.Name = types.AssociationStatusName(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationStatusAggregatedCount(v *map[string]int32, 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]int32 - if *v == nil { - mv = map[string]int32{} - } else { - mv = *v - } - - for key, value := range shape { - var parsedVal int32 - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected InstanceCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - parsedVal = int32(i64) - } - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationVersionInfo(v **types.AssociationVersionInfo, 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.AssociationVersionInfo - if *v == nil { - sv = &types.AssociationVersionInfo{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ApplyOnlyAtCronInterval": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected ApplyOnlyAtCronInterval to be of type *bool, got %T instead", value) - } - sv.ApplyOnlyAtCronInterval = jtv - } - - case "AssociationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationId to be of type string, got %T instead", value) - } - sv.AssociationId = ptr.String(jtv) - } - - case "AssociationName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationName to be of type string, got %T instead", value) - } - sv.AssociationName = ptr.String(jtv) - } - - case "AssociationVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationVersion to be of type string, got %T instead", value) - } - sv.AssociationVersion = ptr.String(jtv) - } - - case "CalendarNames": - if err := awsAwsjson11_deserializeDocumentCalendarNameOrARNList(&sv.CalendarNames, value); err != nil { - return err - } - - case "ComplianceSeverity": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationComplianceSeverity to be of type string, got %T instead", value) - } - sv.ComplianceSeverity = types.AssociationComplianceSeverity(jtv) - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "MaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.MaxConcurrency = ptr.String(jtv) - } - - case "MaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.MaxErrors = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentARN to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "OutputLocation": - if err := awsAwsjson11_deserializeDocumentInstanceAssociationOutputLocation(&sv.OutputLocation, value); err != nil { - return err - } - - case "Parameters": - if err := awsAwsjson11_deserializeDocumentParameters(&sv.Parameters, value); err != nil { - return err - } - - case "ScheduleExpression": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ScheduleExpression to be of type string, got %T instead", value) - } - sv.ScheduleExpression = ptr.String(jtv) - } - - case "ScheduleOffset": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ScheduleOffset to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ScheduleOffset = ptr.Int32(int32(i64)) - } - - case "SyncCompliance": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationSyncCompliance to be of type string, got %T instead", value) - } - sv.SyncCompliance = types.AssociationSyncCompliance(jtv) - } - - case "TargetLocations": - if err := awsAwsjson11_deserializeDocumentTargetLocations(&sv.TargetLocations, value); err != nil { - return err - } - - case "TargetMaps": - if err := awsAwsjson11_deserializeDocumentTargetMaps(&sv.TargetMaps, value); err != nil { - return err - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationVersionLimitExceeded(v **types.AssociationVersionLimitExceeded, 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.AssociationVersionLimitExceeded - if *v == nil { - sv = &types.AssociationVersionLimitExceeded{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAssociationVersionList(v *[]types.AssociationVersionInfo, 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.AssociationVersionInfo - if *v == nil { - cv = []types.AssociationVersionInfo{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.AssociationVersionInfo - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAssociationVersionInfo(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAttachmentContent(v **types.AttachmentContent, 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.AttachmentContent - if *v == nil { - sv = &types.AttachmentContent{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Hash": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AttachmentHash to be of type string, got %T instead", value) - } - sv.Hash = ptr.String(jtv) - } - - case "HashType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AttachmentHashType to be of type string, got %T instead", value) - } - sv.HashType = types.AttachmentHashType(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AttachmentName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Size": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ContentLength to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Size = i64 - } - - case "Url": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AttachmentUrl to be of type string, got %T instead", value) - } - sv.Url = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAttachmentContentList(v *[]types.AttachmentContent, 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.AttachmentContent - if *v == nil { - cv = []types.AttachmentContent{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.AttachmentContent - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAttachmentContent(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAttachmentInformation(v **types.AttachmentInformation, 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.AttachmentInformation - if *v == nil { - sv = &types.AttachmentInformation{} - } 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 AttachmentName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAttachmentInformationList(v *[]types.AttachmentInformation, 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.AttachmentInformation - if *v == nil { - cv = []types.AttachmentInformation{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.AttachmentInformation - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAttachmentInformation(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAutomationDefinitionNotApprovedException(v **types.AutomationDefinitionNotApprovedException, 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.AutomationDefinitionNotApprovedException - if *v == nil { - sv = &types.AutomationDefinitionNotApprovedException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAutomationDefinitionNotFoundException(v **types.AutomationDefinitionNotFoundException, 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.AutomationDefinitionNotFoundException - if *v == nil { - sv = &types.AutomationDefinitionNotFoundException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAutomationDefinitionVersionNotFoundException(v **types.AutomationDefinitionVersionNotFoundException, 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.AutomationDefinitionVersionNotFoundException - if *v == nil { - sv = &types.AutomationDefinitionVersionNotFoundException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAutomationExecution(v **types.AutomationExecution, 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.AutomationExecution - if *v == nil { - sv = &types.AutomationExecution{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.AlarmConfiguration, value); err != nil { - return err - } - - case "AssociationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.AssociationId = ptr.String(jtv) - } - - case "AutomationExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationExecutionId to be of type string, got %T instead", value) - } - sv.AutomationExecutionId = ptr.String(jtv) - } - - case "AutomationExecutionStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationExecutionStatus to be of type string, got %T instead", value) - } - sv.AutomationExecutionStatus = types.AutomationExecutionStatus(jtv) - } - - case "AutomationSubtype": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationSubtype to be of type string, got %T instead", value) - } - sv.AutomationSubtype = types.AutomationSubtype(jtv) - } - - case "ChangeRequestName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ChangeRequestName to be of type string, got %T instead", value) - } - sv.ChangeRequestName = ptr.String(jtv) - } - - case "CurrentAction": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.CurrentAction = ptr.String(jtv) - } - - case "CurrentStepName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.CurrentStepName = ptr.String(jtv) - } - - case "DocumentName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentName to be of type string, got %T instead", value) - } - sv.DocumentName = ptr.String(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "ExecutedBy": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.ExecutedBy = ptr.String(jtv) - } - - case "ExecutionEndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ExecutionEndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ExecutionStartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ExecutionStartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "FailureMessage": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.FailureMessage = ptr.String(jtv) - } - - case "MaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.MaxConcurrency = ptr.String(jtv) - } - - case "MaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.MaxErrors = ptr.String(jtv) - } - - case "Mode": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ExecutionMode to be of type string, got %T instead", value) - } - sv.Mode = types.ExecutionMode(jtv) - } - - case "OpsItemId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.OpsItemId = ptr.String(jtv) - } - - case "Outputs": - if err := awsAwsjson11_deserializeDocumentAutomationParameterMap(&sv.Outputs, value); err != nil { - return err - } - - case "Parameters": - if err := awsAwsjson11_deserializeDocumentAutomationParameterMap(&sv.Parameters, value); err != nil { - return err - } - - case "ParentAutomationExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationExecutionId to be of type string, got %T instead", value) - } - sv.ParentAutomationExecutionId = ptr.String(jtv) - } - - case "ProgressCounters": - if err := awsAwsjson11_deserializeDocumentProgressCounters(&sv.ProgressCounters, value); err != nil { - return err - } - - case "ResolvedTargets": - if err := awsAwsjson11_deserializeDocumentResolvedTargets(&sv.ResolvedTargets, value); err != nil { - return err - } - - case "Runbooks": - if err := awsAwsjson11_deserializeDocumentRunbooks(&sv.Runbooks, value); err != nil { - return err - } - - case "ScheduledTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ScheduledTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "StepExecutions": - if err := awsAwsjson11_deserializeDocumentStepExecutionList(&sv.StepExecutions, value); err != nil { - return err - } - - case "StepExecutionsTruncated": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected Boolean to be of type *bool, got %T instead", value) - } - sv.StepExecutionsTruncated = jtv - } - - case "Target": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Target = ptr.String(jtv) - } - - case "TargetLocations": - if err := awsAwsjson11_deserializeDocumentTargetLocations(&sv.TargetLocations, value); err != nil { - return err - } - - case "TargetMaps": - if err := awsAwsjson11_deserializeDocumentTargetMaps(&sv.TargetMaps, value); err != nil { - return err - } - - case "TargetParameterName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationParameterKey to be of type string, got %T instead", value) - } - sv.TargetParameterName = ptr.String(jtv) - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - case "TriggeredAlarms": - if err := awsAwsjson11_deserializeDocumentAlarmStateInformationList(&sv.TriggeredAlarms, value); err != nil { - return err - } - - case "Variables": - if err := awsAwsjson11_deserializeDocumentAutomationParameterMap(&sv.Variables, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAutomationExecutionLimitExceededException(v **types.AutomationExecutionLimitExceededException, 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.AutomationExecutionLimitExceededException - if *v == nil { - sv = &types.AutomationExecutionLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAutomationExecutionMetadata(v **types.AutomationExecutionMetadata, 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.AutomationExecutionMetadata - if *v == nil { - sv = &types.AutomationExecutionMetadata{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.AlarmConfiguration, value); err != nil { - return err - } - - case "AssociationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.AssociationId = ptr.String(jtv) - } - - case "AutomationExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationExecutionId to be of type string, got %T instead", value) - } - sv.AutomationExecutionId = ptr.String(jtv) - } - - case "AutomationExecutionStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationExecutionStatus to be of type string, got %T instead", value) - } - sv.AutomationExecutionStatus = types.AutomationExecutionStatus(jtv) - } - - case "AutomationSubtype": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationSubtype to be of type string, got %T instead", value) - } - sv.AutomationSubtype = types.AutomationSubtype(jtv) - } - - case "AutomationType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationType to be of type string, got %T instead", value) - } - sv.AutomationType = types.AutomationType(jtv) - } - - case "ChangeRequestName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ChangeRequestName to be of type string, got %T instead", value) - } - sv.ChangeRequestName = ptr.String(jtv) - } - - case "CurrentAction": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.CurrentAction = ptr.String(jtv) - } - - case "CurrentStepName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.CurrentStepName = ptr.String(jtv) - } - - case "DocumentName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentName to be of type string, got %T instead", value) - } - sv.DocumentName = ptr.String(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "ExecutedBy": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.ExecutedBy = ptr.String(jtv) - } - - case "ExecutionEndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ExecutionEndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ExecutionStartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ExecutionStartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "FailureMessage": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.FailureMessage = ptr.String(jtv) - } - - case "LogFile": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.LogFile = ptr.String(jtv) - } - - case "MaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.MaxConcurrency = ptr.String(jtv) - } - - case "MaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.MaxErrors = ptr.String(jtv) - } - - case "Mode": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ExecutionMode to be of type string, got %T instead", value) - } - sv.Mode = types.ExecutionMode(jtv) - } - - case "OpsItemId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.OpsItemId = ptr.String(jtv) - } - - case "Outputs": - if err := awsAwsjson11_deserializeDocumentAutomationParameterMap(&sv.Outputs, value); err != nil { - return err - } - - case "ParentAutomationExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationExecutionId to be of type string, got %T instead", value) - } - sv.ParentAutomationExecutionId = ptr.String(jtv) - } - - case "ResolvedTargets": - if err := awsAwsjson11_deserializeDocumentResolvedTargets(&sv.ResolvedTargets, value); err != nil { - return err - } - - case "Runbooks": - if err := awsAwsjson11_deserializeDocumentRunbooks(&sv.Runbooks, value); err != nil { - return err - } - - case "ScheduledTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ScheduledTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Target": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Target = ptr.String(jtv) - } - - case "TargetMaps": - if err := awsAwsjson11_deserializeDocumentTargetMaps(&sv.TargetMaps, value); err != nil { - return err - } - - case "TargetParameterName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationParameterKey to be of type string, got %T instead", value) - } - sv.TargetParameterName = ptr.String(jtv) - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - case "TriggeredAlarms": - if err := awsAwsjson11_deserializeDocumentAlarmStateInformationList(&sv.TriggeredAlarms, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAutomationExecutionMetadataList(v *[]types.AutomationExecutionMetadata, 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.AutomationExecutionMetadata - if *v == nil { - cv = []types.AutomationExecutionMetadata{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.AutomationExecutionMetadata - destAddr := &col - if err := awsAwsjson11_deserializeDocumentAutomationExecutionMetadata(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAutomationExecutionNotFoundException(v **types.AutomationExecutionNotFoundException, 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.AutomationExecutionNotFoundException - if *v == nil { - sv = &types.AutomationExecutionNotFoundException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentAutomationParameterMap(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 - mapVar := parsedVal - if err := awsAwsjson11_deserializeDocumentAutomationParameterValueList(&mapVar, value); err != nil { - return err - } - parsedVal = mapVar - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentAutomationParameterValueList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationParameterValue to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentAutomationStepNotFoundException(v **types.AutomationStepNotFoundException, 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.AutomationStepNotFoundException - if *v == nil { - sv = &types.AutomationStepNotFoundException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentCalendarNameOrARNList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CalendarNameOrARN to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentCategoryEnumList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Category to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentCategoryList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Category to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentCloudWatchOutputConfig(v **types.CloudWatchOutputConfig, 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.CloudWatchOutputConfig - if *v == nil { - sv = &types.CloudWatchOutputConfig{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CloudWatchLogGroupName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CloudWatchLogGroupName to be of type string, got %T instead", value) - } - sv.CloudWatchLogGroupName = ptr.String(jtv) - } - - case "CloudWatchOutputEnabled": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected CloudWatchOutputEnabled to be of type *bool, got %T instead", value) - } - sv.CloudWatchOutputEnabled = jtv - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentCommand(v **types.Command, 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.Command - if *v == nil { - sv = &types.Command{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.AlarmConfiguration, value); err != nil { - return err - } - - case "CloudWatchOutputConfig": - if err := awsAwsjson11_deserializeDocumentCloudWatchOutputConfig(&sv.CloudWatchOutputConfig, value); err != nil { - return err - } - - case "CommandId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CommandId to be of type string, got %T instead", value) - } - sv.CommandId = ptr.String(jtv) - } - - case "Comment": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Comment to be of type string, got %T instead", value) - } - sv.Comment = ptr.String(jtv) - } - - case "CompletedCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected CompletedCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.CompletedCount = int32(i64) - } - - case "DeliveryTimedOutCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected DeliveryTimedOutCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.DeliveryTimedOutCount = int32(i64) - } - - case "DocumentName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentName to be of type string, got %T instead", value) - } - sv.DocumentName = ptr.String(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "ErrorCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ErrorCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ErrorCount = int32(i64) - } - - case "ExpiresAfter": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ExpiresAfter = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "InstanceIds": - if err := awsAwsjson11_deserializeDocumentInstanceIdList(&sv.InstanceIds, value); err != nil { - return err - } - - case "MaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.MaxConcurrency = ptr.String(jtv) - } - - case "MaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.MaxErrors = ptr.String(jtv) - } - - case "NotificationConfig": - if err := awsAwsjson11_deserializeDocumentNotificationConfig(&sv.NotificationConfig, value); err != nil { - return err - } - - case "OutputS3BucketName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3BucketName to be of type string, got %T instead", value) - } - sv.OutputS3BucketName = ptr.String(jtv) - } - - case "OutputS3KeyPrefix": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3KeyPrefix to be of type string, got %T instead", value) - } - sv.OutputS3KeyPrefix = ptr.String(jtv) - } - - case "OutputS3Region": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3Region to be of type string, got %T instead", value) - } - sv.OutputS3Region = ptr.String(jtv) - } - - case "Parameters": - if err := awsAwsjson11_deserializeDocumentParameters(&sv.Parameters, value); err != nil { - return err - } - - case "RequestedDateTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.RequestedDateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ServiceRole": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ServiceRole to be of type string, got %T instead", value) - } - sv.ServiceRole = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CommandStatus to be of type string, got %T instead", value) - } - sv.Status = types.CommandStatus(jtv) - } - - case "StatusDetails": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusDetails to be of type string, got %T instead", value) - } - sv.StatusDetails = ptr.String(jtv) - } - - case "TargetCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected TargetCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.TargetCount = int32(i64) - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - case "TimeoutSeconds": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected TimeoutSeconds to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.TimeoutSeconds = ptr.Int32(int32(i64)) - } - - case "TriggeredAlarms": - if err := awsAwsjson11_deserializeDocumentAlarmStateInformationList(&sv.TriggeredAlarms, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentCommandInvocation(v **types.CommandInvocation, 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.CommandInvocation - if *v == nil { - sv = &types.CommandInvocation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CloudWatchOutputConfig": - if err := awsAwsjson11_deserializeDocumentCloudWatchOutputConfig(&sv.CloudWatchOutputConfig, value); err != nil { - return err - } - - case "CommandId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CommandId to be of type string, got %T instead", value) - } - sv.CommandId = ptr.String(jtv) - } - - case "CommandPlugins": - if err := awsAwsjson11_deserializeDocumentCommandPluginList(&sv.CommandPlugins, value); err != nil { - return err - } - - case "Comment": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Comment to be of type string, got %T instead", value) - } - sv.Comment = ptr.String(jtv) - } - - case "DocumentName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentName to be of type string, got %T instead", value) - } - sv.DocumentName = ptr.String(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "InstanceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - sv.InstanceId = ptr.String(jtv) - } - - case "InstanceName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceTagName to be of type string, got %T instead", value) - } - sv.InstanceName = ptr.String(jtv) - } - - case "NotificationConfig": - if err := awsAwsjson11_deserializeDocumentNotificationConfig(&sv.NotificationConfig, value); err != nil { - return err - } - - case "RequestedDateTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.RequestedDateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ServiceRole": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ServiceRole to be of type string, got %T instead", value) - } - sv.ServiceRole = ptr.String(jtv) - } - - case "StandardErrorUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Url to be of type string, got %T instead", value) - } - sv.StandardErrorUrl = ptr.String(jtv) - } - - case "StandardOutputUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Url to be of type string, got %T instead", value) - } - sv.StandardOutputUrl = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CommandInvocationStatus to be of type string, got %T instead", value) - } - sv.Status = types.CommandInvocationStatus(jtv) - } - - case "StatusDetails": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusDetails to be of type string, got %T instead", value) - } - sv.StatusDetails = ptr.String(jtv) - } - - case "TraceOutput": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InvocationTraceOutput to be of type string, got %T instead", value) - } - sv.TraceOutput = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentCommandInvocationList(v *[]types.CommandInvocation, 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.CommandInvocation - if *v == nil { - cv = []types.CommandInvocation{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.CommandInvocation - destAddr := &col - if err := awsAwsjson11_deserializeDocumentCommandInvocation(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentCommandList(v *[]types.Command, 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.Command - if *v == nil { - cv = []types.Command{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.Command - destAddr := &col - if err := awsAwsjson11_deserializeDocumentCommand(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentCommandPlugin(v **types.CommandPlugin, 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.CommandPlugin - if *v == nil { - sv = &types.CommandPlugin{} - } 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 CommandPluginName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Output": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CommandPluginOutput to be of type string, got %T instead", value) - } - sv.Output = ptr.String(jtv) - } - - case "OutputS3BucketName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3BucketName to be of type string, got %T instead", value) - } - sv.OutputS3BucketName = ptr.String(jtv) - } - - case "OutputS3KeyPrefix": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3KeyPrefix to be of type string, got %T instead", value) - } - sv.OutputS3KeyPrefix = ptr.String(jtv) - } - - case "OutputS3Region": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3Region to be of type string, got %T instead", value) - } - sv.OutputS3Region = ptr.String(jtv) - } - - case "ResponseCode": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ResponseCode to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ResponseCode = int32(i64) - } - - case "ResponseFinishDateTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ResponseFinishDateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ResponseStartDateTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ResponseStartDateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "StandardErrorUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Url to be of type string, got %T instead", value) - } - sv.StandardErrorUrl = ptr.String(jtv) - } - - case "StandardOutputUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Url to be of type string, got %T instead", value) - } - sv.StandardOutputUrl = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CommandPluginStatus to be of type string, got %T instead", value) - } - sv.Status = types.CommandPluginStatus(jtv) - } - - case "StatusDetails": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusDetails to be of type string, got %T instead", value) - } - sv.StatusDetails = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentCommandPluginList(v *[]types.CommandPlugin, 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.CommandPlugin - if *v == nil { - cv = []types.CommandPlugin{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.CommandPlugin - destAddr := &col - if err := awsAwsjson11_deserializeDocumentCommandPlugin(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentComplianceExecutionSummary(v **types.ComplianceExecutionSummary, 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.ComplianceExecutionSummary - if *v == nil { - sv = &types.ComplianceExecutionSummary{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceExecutionId to be of type string, got %T instead", value) - } - sv.ExecutionId = ptr.String(jtv) - } - - case "ExecutionTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ExecutionTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ExecutionType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceExecutionType to be of type string, got %T instead", value) - } - sv.ExecutionType = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentComplianceItem(v **types.ComplianceItem, 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.ComplianceItem - if *v == nil { - sv = &types.ComplianceItem{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ComplianceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceTypeName to be of type string, got %T instead", value) - } - sv.ComplianceType = ptr.String(jtv) - } - - case "Details": - if err := awsAwsjson11_deserializeDocumentComplianceItemDetails(&sv.Details, value); err != nil { - return err - } - - case "ExecutionSummary": - if err := awsAwsjson11_deserializeDocumentComplianceExecutionSummary(&sv.ExecutionSummary, value); err != nil { - return err - } - - case "Id": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceItemId to be of type string, got %T instead", value) - } - sv.Id = ptr.String(jtv) - } - - case "ResourceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceResourceId to be of type string, got %T instead", value) - } - sv.ResourceId = ptr.String(jtv) - } - - case "ResourceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceResourceType to be of type string, got %T instead", value) - } - sv.ResourceType = ptr.String(jtv) - } - - case "Severity": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceSeverity to be of type string, got %T instead", value) - } - sv.Severity = types.ComplianceSeverity(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceStatus to be of type string, got %T instead", value) - } - sv.Status = types.ComplianceStatus(jtv) - } - - case "Title": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceItemTitle to be of type string, got %T instead", value) - } - sv.Title = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentComplianceItemDetails(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 AttributeValue to be of type string, got %T instead", value) - } - parsedVal = jtv - } - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentComplianceItemList(v *[]types.ComplianceItem, 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.ComplianceItem - if *v == nil { - cv = []types.ComplianceItem{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ComplianceItem - destAddr := &col - if err := awsAwsjson11_deserializeDocumentComplianceItem(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentComplianceSummaryItem(v **types.ComplianceSummaryItem, 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.ComplianceSummaryItem - if *v == nil { - sv = &types.ComplianceSummaryItem{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ComplianceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceTypeName to be of type string, got %T instead", value) - } - sv.ComplianceType = ptr.String(jtv) - } - - case "CompliantSummary": - if err := awsAwsjson11_deserializeDocumentCompliantSummary(&sv.CompliantSummary, value); err != nil { - return err - } - - case "NonCompliantSummary": - if err := awsAwsjson11_deserializeDocumentNonCompliantSummary(&sv.NonCompliantSummary, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentComplianceSummaryItemList(v *[]types.ComplianceSummaryItem, 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.ComplianceSummaryItem - if *v == nil { - cv = []types.ComplianceSummaryItem{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ComplianceSummaryItem - destAddr := &col - if err := awsAwsjson11_deserializeDocumentComplianceSummaryItem(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentComplianceTypeCountLimitExceededException(v **types.ComplianceTypeCountLimitExceededException, 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.ComplianceTypeCountLimitExceededException - if *v == nil { - sv = &types.ComplianceTypeCountLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentCompliantSummary(v **types.CompliantSummary, 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.CompliantSummary - if *v == nil { - sv = &types.CompliantSummary{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CompliantCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ComplianceSummaryCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.CompliantCount = int32(i64) - } - - case "SeveritySummary": - if err := awsAwsjson11_deserializeDocumentSeveritySummary(&sv.SeveritySummary, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentCreateAssociationBatchRequestEntry(v **types.CreateAssociationBatchRequestEntry, 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.CreateAssociationBatchRequestEntry - if *v == nil { - sv = &types.CreateAssociationBatchRequestEntry{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.AlarmConfiguration, value); err != nil { - return err - } - - case "ApplyOnlyAtCronInterval": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected ApplyOnlyAtCronInterval to be of type *bool, got %T instead", value) - } - sv.ApplyOnlyAtCronInterval = jtv - } - - case "AssociationName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationName to be of type string, got %T instead", value) - } - sv.AssociationName = ptr.String(jtv) - } - - case "AutomationTargetParameterName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationTargetParameterName to be of type string, got %T instead", value) - } - sv.AutomationTargetParameterName = ptr.String(jtv) - } - - case "CalendarNames": - if err := awsAwsjson11_deserializeDocumentCalendarNameOrARNList(&sv.CalendarNames, value); err != nil { - return err - } - - case "ComplianceSeverity": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationComplianceSeverity to be of type string, got %T instead", value) - } - sv.ComplianceSeverity = types.AssociationComplianceSeverity(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "InstanceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - sv.InstanceId = ptr.String(jtv) - } - - case "MaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.MaxConcurrency = ptr.String(jtv) - } - - case "MaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.MaxErrors = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentARN to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "OutputLocation": - if err := awsAwsjson11_deserializeDocumentInstanceAssociationOutputLocation(&sv.OutputLocation, value); err != nil { - return err - } - - case "Parameters": - if err := awsAwsjson11_deserializeDocumentParameters(&sv.Parameters, value); err != nil { - return err - } - - case "ScheduleExpression": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ScheduleExpression to be of type string, got %T instead", value) - } - sv.ScheduleExpression = ptr.String(jtv) - } - - case "ScheduleOffset": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ScheduleOffset to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ScheduleOffset = ptr.Int32(int32(i64)) - } - - case "SyncCompliance": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationSyncCompliance to be of type string, got %T instead", value) - } - sv.SyncCompliance = types.AssociationSyncCompliance(jtv) - } - - case "TargetLocations": - if err := awsAwsjson11_deserializeDocumentTargetLocations(&sv.TargetLocations, value); err != nil { - return err - } - - case "TargetMaps": - if err := awsAwsjson11_deserializeDocumentTargetMaps(&sv.TargetMaps, value); err != nil { - return err - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentCustomSchemaCountLimitExceededException(v **types.CustomSchemaCountLimitExceededException, 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.CustomSchemaCountLimitExceededException - if *v == nil { - sv = &types.CustomSchemaCountLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentAlreadyExists(v **types.DocumentAlreadyExists, 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.DocumentAlreadyExists - if *v == nil { - sv = &types.DocumentAlreadyExists{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentDefaultVersionDescription(v **types.DocumentDefaultVersionDescription, 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.DocumentDefaultVersionDescription - if *v == nil { - sv = &types.DocumentDefaultVersionDescription{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DefaultVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DefaultVersion = ptr.String(jtv) - } - - case "DefaultVersionName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersionName to be of type string, got %T instead", value) - } - sv.DefaultVersionName = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentDescription(v **types.DocumentDescription, 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.DocumentDescription - if *v == nil { - sv = &types.DocumentDescription{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ApprovedVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.ApprovedVersion = ptr.String(jtv) - } - - case "AttachmentsInformation": - if err := awsAwsjson11_deserializeDocumentAttachmentInformationList(&sv.AttachmentsInformation, value); err != nil { - return err - } - - case "Author": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentAuthor to be of type string, got %T instead", value) - } - sv.Author = ptr.String(jtv) - } - - case "Category": - if err := awsAwsjson11_deserializeDocumentCategoryList(&sv.Category, value); err != nil { - return err - } - - case "CategoryEnum": - if err := awsAwsjson11_deserializeDocumentCategoryEnumList(&sv.CategoryEnum, value); err != nil { - return err - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "DefaultVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DefaultVersion = ptr.String(jtv) - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DescriptionInDocument to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "DisplayName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentDisplayName to be of type string, got %T instead", value) - } - sv.DisplayName = ptr.String(jtv) - } - - case "DocumentFormat": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentFormat to be of type string, got %T instead", value) - } - sv.DocumentFormat = types.DocumentFormat(jtv) - } - - case "DocumentType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentType to be of type string, got %T instead", value) - } - sv.DocumentType = types.DocumentType(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "Hash": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentHash to be of type string, got %T instead", value) - } - sv.Hash = ptr.String(jtv) - } - - case "HashType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentHashType to be of type string, got %T instead", value) - } - sv.HashType = types.DocumentHashType(jtv) - } - - case "LatestVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.LatestVersion = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentARN to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Owner": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentOwner to be of type string, got %T instead", value) - } - sv.Owner = ptr.String(jtv) - } - - case "Parameters": - if err := awsAwsjson11_deserializeDocumentDocumentParameterList(&sv.Parameters, value); err != nil { - return err - } - - case "PendingReviewVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.PendingReviewVersion = ptr.String(jtv) - } - - case "PlatformTypes": - if err := awsAwsjson11_deserializeDocumentPlatformTypeList(&sv.PlatformTypes, value); err != nil { - return err - } - - case "Requires": - if err := awsAwsjson11_deserializeDocumentDocumentRequiresList(&sv.Requires, value); err != nil { - return err - } - - case "ReviewInformation": - if err := awsAwsjson11_deserializeDocumentReviewInformationList(&sv.ReviewInformation, value); err != nil { - return err - } - - case "ReviewStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ReviewStatus to be of type string, got %T instead", value) - } - sv.ReviewStatus = types.ReviewStatus(jtv) - } - - case "SchemaVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentSchemaVersion to be of type string, got %T instead", value) - } - sv.SchemaVersion = ptr.String(jtv) - } - - case "Sha1": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentSha1 to be of type string, got %T instead", value) - } - sv.Sha1 = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentStatus to be of type string, got %T instead", value) - } - sv.Status = types.DocumentStatus(jtv) - } - - case "StatusInformation": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentStatusInformation to be of type string, got %T instead", value) - } - sv.StatusInformation = ptr.String(jtv) - } - - case "Tags": - if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil { - return err - } - - case "TargetType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TargetType to be of type string, got %T instead", value) - } - sv.TargetType = ptr.String(jtv) - } - - case "VersionName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersionName to be of type string, got %T instead", value) - } - sv.VersionName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentIdentifier(v **types.DocumentIdentifier, 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.DocumentIdentifier - if *v == nil { - sv = &types.DocumentIdentifier{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Author": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentAuthor to be of type string, got %T instead", value) - } - sv.Author = ptr.String(jtv) - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "DisplayName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentDisplayName to be of type string, got %T instead", value) - } - sv.DisplayName = ptr.String(jtv) - } - - case "DocumentFormat": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentFormat to be of type string, got %T instead", value) - } - sv.DocumentFormat = types.DocumentFormat(jtv) - } - - case "DocumentType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentType to be of type string, got %T instead", value) - } - sv.DocumentType = types.DocumentType(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentARN to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Owner": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentOwner to be of type string, got %T instead", value) - } - sv.Owner = ptr.String(jtv) - } - - case "PlatformTypes": - if err := awsAwsjson11_deserializeDocumentPlatformTypeList(&sv.PlatformTypes, value); err != nil { - return err - } - - case "Requires": - if err := awsAwsjson11_deserializeDocumentDocumentRequiresList(&sv.Requires, value); err != nil { - return err - } - - case "ReviewStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ReviewStatus to be of type string, got %T instead", value) - } - sv.ReviewStatus = types.ReviewStatus(jtv) - } - - case "SchemaVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentSchemaVersion to be of type string, got %T instead", value) - } - sv.SchemaVersion = ptr.String(jtv) - } - - case "Tags": - if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil { - return err - } - - case "TargetType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TargetType to be of type string, got %T instead", value) - } - sv.TargetType = ptr.String(jtv) - } - - case "VersionName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersionName to be of type string, got %T instead", value) - } - sv.VersionName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentIdentifierList(v *[]types.DocumentIdentifier, 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.DocumentIdentifier - if *v == nil { - cv = []types.DocumentIdentifier{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.DocumentIdentifier - destAddr := &col - if err := awsAwsjson11_deserializeDocumentDocumentIdentifier(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentLimitExceeded(v **types.DocumentLimitExceeded, 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.DocumentLimitExceeded - if *v == nil { - sv = &types.DocumentLimitExceeded{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentMetadataResponseInfo(v **types.DocumentMetadataResponseInfo, 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.DocumentMetadataResponseInfo - if *v == nil { - sv = &types.DocumentMetadataResponseInfo{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ReviewerResponse": - if err := awsAwsjson11_deserializeDocumentDocumentReviewerResponseList(&sv.ReviewerResponse, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentParameter(v **types.DocumentParameter, 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.DocumentParameter - if *v == nil { - sv = &types.DocumentParameter{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DefaultValue": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentParameterDefaultValue to be of type string, got %T instead", value) - } - sv.DefaultValue = ptr.String(jtv) - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentParameterDescrption to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentParameterName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Type": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentParameterType to be of type string, got %T instead", value) - } - sv.Type = types.DocumentParameterType(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentParameterList(v *[]types.DocumentParameter, 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.DocumentParameter - if *v == nil { - cv = []types.DocumentParameter{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.DocumentParameter - destAddr := &col - if err := awsAwsjson11_deserializeDocumentDocumentParameter(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentPermissionLimit(v **types.DocumentPermissionLimit, 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.DocumentPermissionLimit - if *v == nil { - sv = &types.DocumentPermissionLimit{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentRequires(v **types.DocumentRequires, 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.DocumentRequires - if *v == nil { - sv = &types.DocumentRequires{} - } 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 DocumentARN to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "RequireType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RequireType to be of type string, got %T instead", value) - } - sv.RequireType = ptr.String(jtv) - } - - case "Version": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.Version = ptr.String(jtv) - } - - case "VersionName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersionName to be of type string, got %T instead", value) - } - sv.VersionName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentRequiresList(v *[]types.DocumentRequires, 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.DocumentRequires - if *v == nil { - cv = []types.DocumentRequires{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.DocumentRequires - destAddr := &col - if err := awsAwsjson11_deserializeDocumentDocumentRequires(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentReviewCommentList(v *[]types.DocumentReviewCommentSource, 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.DocumentReviewCommentSource - if *v == nil { - cv = []types.DocumentReviewCommentSource{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.DocumentReviewCommentSource - destAddr := &col - if err := awsAwsjson11_deserializeDocumentDocumentReviewCommentSource(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentReviewCommentSource(v **types.DocumentReviewCommentSource, 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.DocumentReviewCommentSource - if *v == nil { - sv = &types.DocumentReviewCommentSource{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Content": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentReviewComment to be of type string, got %T instead", value) - } - sv.Content = ptr.String(jtv) - } - - case "Type": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentReviewCommentType to be of type string, got %T instead", value) - } - sv.Type = types.DocumentReviewCommentType(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentReviewerResponseList(v *[]types.DocumentReviewerResponseSource, 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.DocumentReviewerResponseSource - if *v == nil { - cv = []types.DocumentReviewerResponseSource{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.DocumentReviewerResponseSource - destAddr := &col - if err := awsAwsjson11_deserializeDocumentDocumentReviewerResponseSource(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentReviewerResponseSource(v **types.DocumentReviewerResponseSource, 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.DocumentReviewerResponseSource - if *v == nil { - sv = &types.DocumentReviewerResponseSource{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Comment": - if err := awsAwsjson11_deserializeDocumentDocumentReviewCommentList(&sv.Comment, value); err != nil { - return err - } - - case "CreateTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Reviewer": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Reviewer to be of type string, got %T instead", value) - } - sv.Reviewer = ptr.String(jtv) - } - - case "ReviewStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ReviewStatus to be of type string, got %T instead", value) - } - sv.ReviewStatus = types.ReviewStatus(jtv) - } - - case "UpdatedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.UpdatedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentVersionInfo(v **types.DocumentVersionInfo, 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.DocumentVersionInfo - if *v == nil { - sv = &types.DocumentVersionInfo{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "DisplayName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentDisplayName to be of type string, got %T instead", value) - } - sv.DisplayName = ptr.String(jtv) - } - - case "DocumentFormat": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentFormat to be of type string, got %T instead", value) - } - sv.DocumentFormat = types.DocumentFormat(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "IsDefaultVersion": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected Boolean to be of type *bool, got %T instead", value) - } - sv.IsDefaultVersion = jtv - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "ReviewStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ReviewStatus to be of type string, got %T instead", value) - } - sv.ReviewStatus = types.ReviewStatus(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentStatus to be of type string, got %T instead", value) - } - sv.Status = types.DocumentStatus(jtv) - } - - case "StatusInformation": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentStatusInformation to be of type string, got %T instead", value) - } - sv.StatusInformation = ptr.String(jtv) - } - - case "VersionName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersionName to be of type string, got %T instead", value) - } - sv.VersionName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentVersionLimitExceeded(v **types.DocumentVersionLimitExceeded, 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.DocumentVersionLimitExceeded - if *v == nil { - sv = &types.DocumentVersionLimitExceeded{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDocumentVersionList(v *[]types.DocumentVersionInfo, 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.DocumentVersionInfo - if *v == nil { - cv = []types.DocumentVersionInfo{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.DocumentVersionInfo - destAddr := &col - if err := awsAwsjson11_deserializeDocumentDocumentVersionInfo(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentDoesNotExistException(v **types.DoesNotExistException, 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.DoesNotExistException - if *v == nil { - sv = &types.DoesNotExistException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDuplicateDocumentContent(v **types.DuplicateDocumentContent, 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.DuplicateDocumentContent - if *v == nil { - sv = &types.DuplicateDocumentContent{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDuplicateDocumentVersionName(v **types.DuplicateDocumentVersionName, 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.DuplicateDocumentVersionName - if *v == nil { - sv = &types.DuplicateDocumentVersionName{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentDuplicateInstanceId(v **types.DuplicateInstanceId, 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.DuplicateInstanceId - if *v == nil { - sv = &types.DuplicateInstanceId{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentEffectivePatch(v **types.EffectivePatch, 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.EffectivePatch - if *v == nil { - sv = &types.EffectivePatch{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Patch": - if err := awsAwsjson11_deserializeDocumentPatch(&sv.Patch, value); err != nil { - return err - } - - case "PatchStatus": - if err := awsAwsjson11_deserializeDocumentPatchStatus(&sv.PatchStatus, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentEffectivePatchList(v *[]types.EffectivePatch, 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.EffectivePatch - if *v == nil { - cv = []types.EffectivePatch{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.EffectivePatch - destAddr := &col - if err := awsAwsjson11_deserializeDocumentEffectivePatch(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentFailedCreateAssociation(v **types.FailedCreateAssociation, 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.FailedCreateAssociation - if *v == nil { - sv = &types.FailedCreateAssociation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Entry": - if err := awsAwsjson11_deserializeDocumentCreateAssociationBatchRequestEntry(&sv.Entry, value); err != nil { - return err - } - - case "Fault": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Fault to be of type string, got %T instead", value) - } - sv.Fault = types.Fault(jtv) - } - - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BatchErrorMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentFailedCreateAssociationList(v *[]types.FailedCreateAssociation, 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.FailedCreateAssociation - if *v == nil { - cv = []types.FailedCreateAssociation{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.FailedCreateAssociation - destAddr := &col - if err := awsAwsjson11_deserializeDocumentFailedCreateAssociation(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentFailureDetails(v **types.FailureDetails, 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.FailureDetails - if *v == nil { - sv = &types.FailureDetails{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Details": - if err := awsAwsjson11_deserializeDocumentAutomationParameterMap(&sv.Details, value); err != nil { - return err - } - - case "FailureStage": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.FailureStage = ptr.String(jtv) - } - - case "FailureType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.FailureType = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentFeatureNotAvailableException(v **types.FeatureNotAvailableException, 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.FeatureNotAvailableException - if *v == nil { - sv = &types.FeatureNotAvailableException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentGetResourcePoliciesResponseEntries(v *[]types.GetResourcePoliciesResponseEntry, 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.GetResourcePoliciesResponseEntry - if *v == nil { - cv = []types.GetResourcePoliciesResponseEntry{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.GetResourcePoliciesResponseEntry - destAddr := &col - if err := awsAwsjson11_deserializeDocumentGetResourcePoliciesResponseEntry(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentGetResourcePoliciesResponseEntry(v **types.GetResourcePoliciesResponseEntry, 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.GetResourcePoliciesResponseEntry - if *v == nil { - sv = &types.GetResourcePoliciesResponseEntry{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Policy": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Policy to be of type string, got %T instead", value) - } - sv.Policy = ptr.String(jtv) - } - - case "PolicyHash": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PolicyHash to be of type string, got %T instead", value) - } - sv.PolicyHash = ptr.String(jtv) - } - - case "PolicyId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PolicyId to be of type string, got %T instead", value) - } - sv.PolicyId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentHierarchyLevelLimitExceededException(v **types.HierarchyLevelLimitExceededException, 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.HierarchyLevelLimitExceededException - if *v == nil { - sv = &types.HierarchyLevelLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentHierarchyTypeMismatchException(v **types.HierarchyTypeMismatchException, 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.HierarchyTypeMismatchException - if *v == nil { - sv = &types.HierarchyTypeMismatchException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentIdempotentParameterMismatch(v **types.IdempotentParameterMismatch, 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.IdempotentParameterMismatch - if *v == nil { - sv = &types.IdempotentParameterMismatch{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentIncompatiblePolicyException(v **types.IncompatiblePolicyException, 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.IncompatiblePolicyException - if *v == nil { - sv = &types.IncompatiblePolicyException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInstanceAggregatedAssociationOverview(v **types.InstanceAggregatedAssociationOverview, 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.InstanceAggregatedAssociationOverview - if *v == nil { - sv = &types.InstanceAggregatedAssociationOverview{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DetailedStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusName to be of type string, got %T instead", value) - } - sv.DetailedStatus = ptr.String(jtv) - } - - case "InstanceAssociationStatusAggregatedCount": - if err := awsAwsjson11_deserializeDocumentInstanceAssociationStatusAggregatedCount(&sv.InstanceAssociationStatusAggregatedCount, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInstanceAssociation(v **types.InstanceAssociation, 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.InstanceAssociation - if *v == nil { - sv = &types.InstanceAssociation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationId to be of type string, got %T instead", value) - } - sv.AssociationId = ptr.String(jtv) - } - - case "AssociationVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationVersion to be of type string, got %T instead", value) - } - sv.AssociationVersion = ptr.String(jtv) - } - - case "Content": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentContent to be of type string, got %T instead", value) - } - sv.Content = ptr.String(jtv) - } - - case "InstanceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - sv.InstanceId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInstanceAssociationList(v *[]types.InstanceAssociation, 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.InstanceAssociation - if *v == nil { - cv = []types.InstanceAssociation{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.InstanceAssociation - destAddr := &col - if err := awsAwsjson11_deserializeDocumentInstanceAssociation(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInstanceAssociationOutputLocation(v **types.InstanceAssociationOutputLocation, 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.InstanceAssociationOutputLocation - if *v == nil { - sv = &types.InstanceAssociationOutputLocation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "S3Location": - if err := awsAwsjson11_deserializeDocumentS3OutputLocation(&sv.S3Location, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInstanceAssociationOutputUrl(v **types.InstanceAssociationOutputUrl, 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.InstanceAssociationOutputUrl - if *v == nil { - sv = &types.InstanceAssociationOutputUrl{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "S3OutputUrl": - if err := awsAwsjson11_deserializeDocumentS3OutputUrl(&sv.S3OutputUrl, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInstanceAssociationStatusAggregatedCount(v *map[string]int32, 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]int32 - if *v == nil { - mv = map[string]int32{} - } else { - mv = *v - } - - for key, value := range shape { - var parsedVal int32 - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected InstanceCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - parsedVal = int32(i64) - } - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentInstanceAssociationStatusInfo(v **types.InstanceAssociationStatusInfo, 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.InstanceAssociationStatusInfo - if *v == nil { - sv = &types.InstanceAssociationStatusInfo{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationId to be of type string, got %T instead", value) - } - sv.AssociationId = ptr.String(jtv) - } - - case "AssociationName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationName to be of type string, got %T instead", value) - } - sv.AssociationName = ptr.String(jtv) - } - - case "AssociationVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AssociationVersion to be of type string, got %T instead", value) - } - sv.AssociationVersion = ptr.String(jtv) - } - - case "DetailedStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusName to be of type string, got %T instead", value) - } - sv.DetailedStatus = ptr.String(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "ErrorCode": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AgentErrorCode to be of type string, got %T instead", value) - } - sv.ErrorCode = ptr.String(jtv) - } - - case "ExecutionDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ExecutionDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ExecutionSummary": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceAssociationExecutionSummary to be of type string, got %T instead", value) - } - sv.ExecutionSummary = ptr.String(jtv) - } - - case "InstanceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - sv.InstanceId = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentARN to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "OutputUrl": - if err := awsAwsjson11_deserializeDocumentInstanceAssociationOutputUrl(&sv.OutputUrl, value); err != nil { - return err - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusName to be of type string, got %T instead", value) - } - sv.Status = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInstanceAssociationStatusInfos(v *[]types.InstanceAssociationStatusInfo, 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.InstanceAssociationStatusInfo - if *v == nil { - cv = []types.InstanceAssociationStatusInfo{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.InstanceAssociationStatusInfo - destAddr := &col - if err := awsAwsjson11_deserializeDocumentInstanceAssociationStatusInfo(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInstanceIdList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInstanceInformation(v **types.InstanceInformation, 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.InstanceInformation - if *v == nil { - sv = &types.InstanceInformation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ActivationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ActivationId to be of type string, got %T instead", value) - } - sv.ActivationId = ptr.String(jtv) - } - - case "AgentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Version to be of type string, got %T instead", value) - } - sv.AgentVersion = ptr.String(jtv) - } - - case "AssociationOverview": - if err := awsAwsjson11_deserializeDocumentInstanceAggregatedAssociationOverview(&sv.AssociationOverview, value); err != nil { - return err - } - - case "AssociationStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusName to be of type string, got %T instead", value) - } - sv.AssociationStatus = ptr.String(jtv) - } - - case "ComputerName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComputerName to be of type string, got %T instead", value) - } - sv.ComputerName = ptr.String(jtv) - } - - case "IamRole": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected IamRole to be of type string, got %T instead", value) - } - sv.IamRole = ptr.String(jtv) - } - - case "InstanceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - sv.InstanceId = ptr.String(jtv) - } - - case "IPAddress": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected IPAddress to be of type string, got %T instead", value) - } - sv.IPAddress = ptr.String(jtv) - } - - case "IsLatestVersion": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected Boolean to be of type *bool, got %T instead", value) - } - sv.IsLatestVersion = ptr.Bool(jtv) - } - - case "LastAssociationExecutionDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastAssociationExecutionDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastPingDateTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastPingDateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastSuccessfulAssociationExecutionDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastSuccessfulAssociationExecutionDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "PingStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PingStatus to be of type string, got %T instead", value) - } - sv.PingStatus = types.PingStatus(jtv) - } - - case "PlatformName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.PlatformName = ptr.String(jtv) - } - - case "PlatformType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PlatformType to be of type string, got %T instead", value) - } - sv.PlatformType = types.PlatformType(jtv) - } - - case "PlatformVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.PlatformVersion = ptr.String(jtv) - } - - case "RegistrationDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.RegistrationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ResourceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceType to be of type string, got %T instead", value) - } - sv.ResourceType = types.ResourceType(jtv) - } - - case "SourceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SourceId to be of type string, got %T instead", value) - } - sv.SourceId = ptr.String(jtv) - } - - case "SourceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SourceType to be of type string, got %T instead", value) - } - sv.SourceType = types.SourceType(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInstanceInformationList(v *[]types.InstanceInformation, 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.InstanceInformation - if *v == nil { - cv = []types.InstanceInformation{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.InstanceInformation - destAddr := &col - if err := awsAwsjson11_deserializeDocumentInstanceInformation(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInstancePatchState(v **types.InstancePatchState, 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.InstancePatchState - if *v == nil { - sv = &types.InstancePatchState{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "BaselineId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineId to be of type string, got %T instead", value) - } - sv.BaselineId = ptr.String(jtv) - } - - case "CriticalNonCompliantCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchCriticalNonCompliantCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.CriticalNonCompliantCount = ptr.Int32(int32(i64)) - } - - case "FailedCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchFailedCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.FailedCount = int32(i64) - } - - case "InstalledCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchInstalledCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstalledCount = int32(i64) - } - - case "InstalledOtherCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchInstalledOtherCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstalledOtherCount = int32(i64) - } - - case "InstalledPendingRebootCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchInstalledPendingRebootCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstalledPendingRebootCount = ptr.Int32(int32(i64)) - } - - case "InstalledRejectedCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchInstalledRejectedCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstalledRejectedCount = ptr.Int32(int32(i64)) - } - - case "InstallOverrideList": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstallOverrideList to be of type string, got %T instead", value) - } - sv.InstallOverrideList = ptr.String(jtv) - } - - case "InstanceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - sv.InstanceId = ptr.String(jtv) - } - - case "LastNoRebootInstallOperationTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastNoRebootInstallOperationTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "MissingCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchMissingCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.MissingCount = int32(i64) - } - - case "NotApplicableCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchNotApplicableCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.NotApplicableCount = int32(i64) - } - - case "Operation": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchOperationType to be of type string, got %T instead", value) - } - sv.Operation = types.PatchOperationType(jtv) - } - - case "OperationEndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.OperationEndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "OperationStartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.OperationStartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "OtherNonCompliantCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchOtherNonCompliantCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.OtherNonCompliantCount = ptr.Int32(int32(i64)) - } - - case "OwnerInformation": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OwnerInformation to be of type string, got %T instead", value) - } - sv.OwnerInformation = ptr.String(jtv) - } - - case "PatchGroup": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchGroup to be of type string, got %T instead", value) - } - sv.PatchGroup = ptr.String(jtv) - } - - case "RebootOption": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RebootOption to be of type string, got %T instead", value) - } - sv.RebootOption = types.RebootOption(jtv) - } - - case "SecurityNonCompliantCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchSecurityNonCompliantCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.SecurityNonCompliantCount = ptr.Int32(int32(i64)) - } - - case "SnapshotId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SnapshotId to be of type string, got %T instead", value) - } - sv.SnapshotId = ptr.String(jtv) - } - - case "UnreportedNotApplicableCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchUnreportedNotApplicableCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.UnreportedNotApplicableCount = ptr.Int32(int32(i64)) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInstancePatchStateList(v *[]types.InstancePatchState, 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.InstancePatchState - if *v == nil { - cv = []types.InstancePatchState{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.InstancePatchState - destAddr := &col - if err := awsAwsjson11_deserializeDocumentInstancePatchState(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInstancePatchStatesList(v *[]types.InstancePatchState, 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.InstancePatchState - if *v == nil { - cv = []types.InstancePatchState{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.InstancePatchState - destAddr := &col - if err := awsAwsjson11_deserializeDocumentInstancePatchState(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInternalServerError(v **types.InternalServerError, 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.InternalServerError - if *v == nil { - sv = &types.InternalServerError{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidActivation(v **types.InvalidActivation, 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.InvalidActivation - if *v == nil { - sv = &types.InvalidActivation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidActivationId(v **types.InvalidActivationId, 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.InvalidActivationId - if *v == nil { - sv = &types.InvalidActivationId{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidAggregatorException(v **types.InvalidAggregatorException, 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.InvalidAggregatorException - if *v == nil { - sv = &types.InvalidAggregatorException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidAllowedPatternException(v **types.InvalidAllowedPatternException, 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.InvalidAllowedPatternException - if *v == nil { - sv = &types.InvalidAllowedPatternException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidAssociation(v **types.InvalidAssociation, 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.InvalidAssociation - if *v == nil { - sv = &types.InvalidAssociation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidAssociationVersion(v **types.InvalidAssociationVersion, 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.InvalidAssociationVersion - if *v == nil { - sv = &types.InvalidAssociationVersion{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidAutomationExecutionParametersException(v **types.InvalidAutomationExecutionParametersException, 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.InvalidAutomationExecutionParametersException - if *v == nil { - sv = &types.InvalidAutomationExecutionParametersException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidAutomationSignalException(v **types.InvalidAutomationSignalException, 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.InvalidAutomationSignalException - if *v == nil { - sv = &types.InvalidAutomationSignalException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidAutomationStatusUpdateException(v **types.InvalidAutomationStatusUpdateException, 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.InvalidAutomationStatusUpdateException - if *v == nil { - sv = &types.InvalidAutomationStatusUpdateException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidCommandId(v **types.InvalidCommandId, 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.InvalidCommandId - if *v == nil { - sv = &types.InvalidCommandId{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidDeleteInventoryParametersException(v **types.InvalidDeleteInventoryParametersException, 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.InvalidDeleteInventoryParametersException - if *v == nil { - sv = &types.InvalidDeleteInventoryParametersException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidDeletionIdException(v **types.InvalidDeletionIdException, 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.InvalidDeletionIdException - if *v == nil { - sv = &types.InvalidDeletionIdException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidDocument(v **types.InvalidDocument, 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.InvalidDocument - if *v == nil { - sv = &types.InvalidDocument{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidDocumentContent(v **types.InvalidDocumentContent, 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.InvalidDocumentContent - if *v == nil { - sv = &types.InvalidDocumentContent{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidDocumentOperation(v **types.InvalidDocumentOperation, 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.InvalidDocumentOperation - if *v == nil { - sv = &types.InvalidDocumentOperation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidDocumentSchemaVersion(v **types.InvalidDocumentSchemaVersion, 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.InvalidDocumentSchemaVersion - if *v == nil { - sv = &types.InvalidDocumentSchemaVersion{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidDocumentType(v **types.InvalidDocumentType, 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.InvalidDocumentType - if *v == nil { - sv = &types.InvalidDocumentType{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidDocumentVersion(v **types.InvalidDocumentVersion, 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.InvalidDocumentVersion - if *v == nil { - sv = &types.InvalidDocumentVersion{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidFilter(v **types.InvalidFilter, 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.InvalidFilter - if *v == nil { - sv = &types.InvalidFilter{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidFilterKey(v **types.InvalidFilterKey, 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.InvalidFilterKey - if *v == nil { - sv = &types.InvalidFilterKey{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidFilterOption(v **types.InvalidFilterOption, 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.InvalidFilterOption - if *v == nil { - sv = &types.InvalidFilterOption{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidFilterValue(v **types.InvalidFilterValue, 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.InvalidFilterValue - if *v == nil { - sv = &types.InvalidFilterValue{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidInstanceId(v **types.InvalidInstanceId, 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.InvalidInstanceId - if *v == nil { - sv = &types.InvalidInstanceId{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidInstanceInformationFilterValue(v **types.InvalidInstanceInformationFilterValue, 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.InvalidInstanceInformationFilterValue - if *v == nil { - sv = &types.InvalidInstanceInformationFilterValue{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidInventoryGroupException(v **types.InvalidInventoryGroupException, 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.InvalidInventoryGroupException - if *v == nil { - sv = &types.InvalidInventoryGroupException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidInventoryItemContextException(v **types.InvalidInventoryItemContextException, 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.InvalidInventoryItemContextException - if *v == nil { - sv = &types.InvalidInventoryItemContextException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidInventoryRequestException(v **types.InvalidInventoryRequestException, 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.InvalidInventoryRequestException - if *v == nil { - sv = &types.InvalidInventoryRequestException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidItemContentException(v **types.InvalidItemContentException, 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.InvalidItemContentException - if *v == nil { - sv = &types.InvalidItemContentException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "TypeName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemTypeName to be of type string, got %T instead", value) - } - sv.TypeName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidKeyId(v **types.InvalidKeyId, 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.InvalidKeyId - if *v == nil { - sv = &types.InvalidKeyId{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidNextToken(v **types.InvalidNextToken, 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.InvalidNextToken - if *v == nil { - sv = &types.InvalidNextToken{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidNotificationConfig(v **types.InvalidNotificationConfig, 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.InvalidNotificationConfig - if *v == nil { - sv = &types.InvalidNotificationConfig{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidOptionException(v **types.InvalidOptionException, 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.InvalidOptionException - if *v == nil { - sv = &types.InvalidOptionException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidOutputFolder(v **types.InvalidOutputFolder, 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.InvalidOutputFolder - if *v == nil { - sv = &types.InvalidOutputFolder{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidOutputLocation(v **types.InvalidOutputLocation, 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.InvalidOutputLocation - if *v == nil { - sv = &types.InvalidOutputLocation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidParameters(v **types.InvalidParameters, 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.InvalidParameters - if *v == nil { - sv = &types.InvalidParameters{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidPermissionType(v **types.InvalidPermissionType, 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.InvalidPermissionType - if *v == nil { - sv = &types.InvalidPermissionType{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidPluginName(v **types.InvalidPluginName, 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.InvalidPluginName - if *v == nil { - sv = &types.InvalidPluginName{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidPolicyAttributeException(v **types.InvalidPolicyAttributeException, 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.InvalidPolicyAttributeException - if *v == nil { - sv = &types.InvalidPolicyAttributeException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidPolicyTypeException(v **types.InvalidPolicyTypeException, 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.InvalidPolicyTypeException - if *v == nil { - sv = &types.InvalidPolicyTypeException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidResourceId(v **types.InvalidResourceId, 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.InvalidResourceId - if *v == nil { - sv = &types.InvalidResourceId{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidResourceType(v **types.InvalidResourceType, 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.InvalidResourceType - if *v == nil { - sv = &types.InvalidResourceType{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidResultAttributeException(v **types.InvalidResultAttributeException, 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.InvalidResultAttributeException - if *v == nil { - sv = &types.InvalidResultAttributeException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidRole(v **types.InvalidRole, 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.InvalidRole - if *v == nil { - sv = &types.InvalidRole{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidSchedule(v **types.InvalidSchedule, 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.InvalidSchedule - if *v == nil { - sv = &types.InvalidSchedule{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidTag(v **types.InvalidTag, 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.InvalidTag - if *v == nil { - sv = &types.InvalidTag{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidTarget(v **types.InvalidTarget, 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.InvalidTarget - if *v == nil { - sv = &types.InvalidTarget{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidTargetMaps(v **types.InvalidTargetMaps, 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.InvalidTargetMaps - if *v == nil { - sv = &types.InvalidTargetMaps{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidTypeNameException(v **types.InvalidTypeNameException, 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.InvalidTypeNameException - if *v == nil { - sv = &types.InvalidTypeNameException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInvalidUpdate(v **types.InvalidUpdate, 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.InvalidUpdate - if *v == nil { - sv = &types.InvalidUpdate{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryDeletionsList(v *[]types.InventoryDeletionStatusItem, 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.InventoryDeletionStatusItem - if *v == nil { - cv = []types.InventoryDeletionStatusItem{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.InventoryDeletionStatusItem - destAddr := &col - if err := awsAwsjson11_deserializeDocumentInventoryDeletionStatusItem(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryDeletionStatusItem(v **types.InventoryDeletionStatusItem, 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.InventoryDeletionStatusItem - if *v == nil { - sv = &types.InventoryDeletionStatusItem{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DeletionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected UUID to be of type string, got %T instead", value) - } - sv.DeletionId = ptr.String(jtv) - } - - case "DeletionStartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.DeletionStartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected InventoryDeletionStartTime to be a JSON Number, got %T instead", value) - - } - } - - case "DeletionSummary": - if err := awsAwsjson11_deserializeDocumentInventoryDeletionSummary(&sv.DeletionSummary, value); err != nil { - return err - } - - case "LastStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryDeletionStatus to be of type string, got %T instead", value) - } - sv.LastStatus = types.InventoryDeletionStatus(jtv) - } - - case "LastStatusMessage": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryDeletionLastStatusMessage to be of type string, got %T instead", value) - } - sv.LastStatusMessage = ptr.String(jtv) - } - - case "LastStatusUpdateTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastStatusUpdateTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected InventoryDeletionLastStatusUpdateTime to be a JSON Number, got %T instead", value) - - } - } - - case "TypeName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemTypeName to be of type string, got %T instead", value) - } - sv.TypeName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryDeletionSummary(v **types.InventoryDeletionSummary, 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.InventoryDeletionSummary - if *v == nil { - sv = &types.InventoryDeletionSummary{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "RemainingCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected RemainingCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.RemainingCount = int32(i64) - } - - case "SummaryItems": - if err := awsAwsjson11_deserializeDocumentInventoryDeletionSummaryItems(&sv.SummaryItems, value); err != nil { - return err - } - - case "TotalCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected TotalCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.TotalCount = int32(i64) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryDeletionSummaryItem(v **types.InventoryDeletionSummaryItem, 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.InventoryDeletionSummaryItem - if *v == nil { - sv = &types.InventoryDeletionSummaryItem{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Count": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ResourceCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Count = int32(i64) - } - - case "RemainingCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected RemainingCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.RemainingCount = int32(i64) - } - - case "Version": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemSchemaVersion to be of type string, got %T instead", value) - } - sv.Version = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryDeletionSummaryItems(v *[]types.InventoryDeletionSummaryItem, 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.InventoryDeletionSummaryItem - if *v == nil { - cv = []types.InventoryDeletionSummaryItem{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.InventoryDeletionSummaryItem - destAddr := &col - if err := awsAwsjson11_deserializeDocumentInventoryDeletionSummaryItem(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryItemAttribute(v **types.InventoryItemAttribute, 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.InventoryItemAttribute - if *v == nil { - sv = &types.InventoryItemAttribute{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DataType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryAttributeDataType to be of type string, got %T instead", value) - } - sv.DataType = types.InventoryAttributeDataType(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemAttributeName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryItemAttributeList(v *[]types.InventoryItemAttribute, 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.InventoryItemAttribute - if *v == nil { - cv = []types.InventoryItemAttribute{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.InventoryItemAttribute - destAddr := &col - if err := awsAwsjson11_deserializeDocumentInventoryItemAttribute(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryItemEntry(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 AttributeValue to be of type string, got %T instead", value) - } - parsedVal = jtv - } - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryItemEntryList(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.([]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var cv []map[string]string - if *v == nil { - cv = []map[string]string{} - } else { - cv = *v - } - - for _, value := range shape { - var col map[string]string - if err := awsAwsjson11_deserializeDocumentInventoryItemEntry(&col, value); err != nil { - return err - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryItemSchema(v **types.InventoryItemSchema, 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.InventoryItemSchema - if *v == nil { - sv = &types.InventoryItemSchema{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Attributes": - if err := awsAwsjson11_deserializeDocumentInventoryItemAttributeList(&sv.Attributes, value); err != nil { - return err - } - - case "DisplayName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryTypeDisplayName to be of type string, got %T instead", value) - } - sv.DisplayName = ptr.String(jtv) - } - - case "TypeName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemTypeName to be of type string, got %T instead", value) - } - sv.TypeName = ptr.String(jtv) - } - - case "Version": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemSchemaVersion to be of type string, got %T instead", value) - } - sv.Version = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryItemSchemaResultList(v *[]types.InventoryItemSchema, 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.InventoryItemSchema - if *v == nil { - cv = []types.InventoryItemSchema{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.InventoryItemSchema - destAddr := &col - if err := awsAwsjson11_deserializeDocumentInventoryItemSchema(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryResultEntity(v **types.InventoryResultEntity, 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.InventoryResultEntity - if *v == nil { - sv = &types.InventoryResultEntity{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Data": - if err := awsAwsjson11_deserializeDocumentInventoryResultItemMap(&sv.Data, value); err != nil { - return err - } - - case "Id": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryResultEntityId to be of type string, got %T instead", value) - } - sv.Id = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryResultEntityList(v *[]types.InventoryResultEntity, 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.InventoryResultEntity - if *v == nil { - cv = []types.InventoryResultEntity{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.InventoryResultEntity - destAddr := &col - if err := awsAwsjson11_deserializeDocumentInventoryResultEntity(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryResultItem(v **types.InventoryResultItem, 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.InventoryResultItem - if *v == nil { - sv = &types.InventoryResultItem{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CaptureTime": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemCaptureTime to be of type string, got %T instead", value) - } - sv.CaptureTime = ptr.String(jtv) - } - - case "Content": - if err := awsAwsjson11_deserializeDocumentInventoryItemEntryList(&sv.Content, value); err != nil { - return err - } - - case "ContentHash": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemContentHash to be of type string, got %T instead", value) - } - sv.ContentHash = ptr.String(jtv) - } - - case "SchemaVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemSchemaVersion to be of type string, got %T instead", value) - } - sv.SchemaVersion = ptr.String(jtv) - } - - case "TypeName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemTypeName to be of type string, got %T instead", value) - } - sv.TypeName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentInventoryResultItemMap(v *map[string]types.InventoryResultItem, 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]types.InventoryResultItem - if *v == nil { - mv = map[string]types.InventoryResultItem{} - } else { - mv = *v - } - - for key, value := range shape { - var parsedVal types.InventoryResultItem - mapVar := parsedVal - destAddr := &mapVar - if err := awsAwsjson11_deserializeDocumentInventoryResultItem(&destAddr, value); err != nil { - return err - } - parsedVal = *destAddr - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentInvocationDoesNotExist(v **types.InvocationDoesNotExist, 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.InvocationDoesNotExist - if *v == nil { - sv = &types.InvocationDoesNotExist{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentItemContentMismatchException(v **types.ItemContentMismatchException, 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.ItemContentMismatchException - if *v == nil { - sv = &types.ItemContentMismatchException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "TypeName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemTypeName to be of type string, got %T instead", value) - } - sv.TypeName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentItemSizeLimitExceededException(v **types.ItemSizeLimitExceededException, 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.ItemSizeLimitExceededException - if *v == nil { - sv = &types.ItemSizeLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "TypeName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemTypeName to be of type string, got %T instead", value) - } - sv.TypeName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentLoggingInfo(v **types.LoggingInfo, 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.LoggingInfo - if *v == nil { - sv = &types.LoggingInfo{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "S3BucketName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3BucketName to be of type string, got %T instead", value) - } - sv.S3BucketName = ptr.String(jtv) - } - - case "S3KeyPrefix": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3KeyPrefix to be of type string, got %T instead", value) - } - sv.S3KeyPrefix = ptr.String(jtv) - } - - case "S3Region": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3Region to be of type string, got %T instead", value) - } - sv.S3Region = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowAutomationParameters(v **types.MaintenanceWindowAutomationParameters, 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.MaintenanceWindowAutomationParameters - if *v == nil { - sv = &types.MaintenanceWindowAutomationParameters{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "Parameters": - if err := awsAwsjson11_deserializeDocumentAutomationParameterMap(&sv.Parameters, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowExecution(v **types.MaintenanceWindowExecution, 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.MaintenanceWindowExecution - if *v == nil { - sv = &types.MaintenanceWindowExecution{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "EndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.EndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "StartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.StartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatus to be of type string, got %T instead", value) - } - sv.Status = types.MaintenanceWindowExecutionStatus(jtv) - } - - case "StatusDetails": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatusDetails to be of type string, got %T instead", value) - } - sv.StatusDetails = ptr.String(jtv) - } - - case "WindowExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionId to be of type string, got %T instead", value) - } - sv.WindowExecutionId = ptr.String(jtv) - } - - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionList(v *[]types.MaintenanceWindowExecution, 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.MaintenanceWindowExecution - if *v == nil { - cv = []types.MaintenanceWindowExecution{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.MaintenanceWindowExecution - destAddr := &col - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowExecution(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionTaskIdentity(v **types.MaintenanceWindowExecutionTaskIdentity, 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.MaintenanceWindowExecutionTaskIdentity - if *v == nil { - sv = &types.MaintenanceWindowExecutionTaskIdentity{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.AlarmConfiguration, value); err != nil { - return err - } - - case "EndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.EndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "StartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.StartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatus to be of type string, got %T instead", value) - } - sv.Status = types.MaintenanceWindowExecutionStatus(jtv) - } - - case "StatusDetails": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatusDetails to be of type string, got %T instead", value) - } - sv.StatusDetails = ptr.String(jtv) - } - - case "TaskArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskArn to be of type string, got %T instead", value) - } - sv.TaskArn = ptr.String(jtv) - } - - case "TaskExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionTaskId to be of type string, got %T instead", value) - } - sv.TaskExecutionId = ptr.String(jtv) - } - - case "TaskType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskType to be of type string, got %T instead", value) - } - sv.TaskType = types.MaintenanceWindowTaskType(jtv) - } - - case "TriggeredAlarms": - if err := awsAwsjson11_deserializeDocumentAlarmStateInformationList(&sv.TriggeredAlarms, value); err != nil { - return err - } - - case "WindowExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionId to be of type string, got %T instead", value) - } - sv.WindowExecutionId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionTaskIdentityList(v *[]types.MaintenanceWindowExecutionTaskIdentity, 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.MaintenanceWindowExecutionTaskIdentity - if *v == nil { - cv = []types.MaintenanceWindowExecutionTaskIdentity{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.MaintenanceWindowExecutionTaskIdentity - destAddr := &col - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionTaskIdentity(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionTaskIdList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionTaskId to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionTaskInvocationIdentity(v **types.MaintenanceWindowExecutionTaskInvocationIdentity, 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.MaintenanceWindowExecutionTaskInvocationIdentity - if *v == nil { - sv = &types.MaintenanceWindowExecutionTaskInvocationIdentity{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "EndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.EndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionTaskExecutionId to be of type string, got %T instead", value) - } - sv.ExecutionId = ptr.String(jtv) - } - - case "InvocationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionTaskInvocationId to be of type string, got %T instead", value) - } - sv.InvocationId = ptr.String(jtv) - } - - case "OwnerInformation": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OwnerInformation to be of type string, got %T instead", value) - } - sv.OwnerInformation = ptr.String(jtv) - } - - case "Parameters": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionTaskInvocationParameters to be of type string, got %T instead", value) - } - sv.Parameters = ptr.String(jtv) - } - - case "StartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.StartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatus to be of type string, got %T instead", value) - } - sv.Status = types.MaintenanceWindowExecutionStatus(jtv) - } - - case "StatusDetails": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatusDetails to be of type string, got %T instead", value) - } - sv.StatusDetails = ptr.String(jtv) - } - - case "TaskExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionTaskId to be of type string, got %T instead", value) - } - sv.TaskExecutionId = ptr.String(jtv) - } - - case "TaskType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskType to be of type string, got %T instead", value) - } - sv.TaskType = types.MaintenanceWindowTaskType(jtv) - } - - case "WindowExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionId to be of type string, got %T instead", value) - } - sv.WindowExecutionId = ptr.String(jtv) - } - - case "WindowTargetId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskTargetId to be of type string, got %T instead", value) - } - sv.WindowTargetId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionTaskInvocationIdentityList(v *[]types.MaintenanceWindowExecutionTaskInvocationIdentity, 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.MaintenanceWindowExecutionTaskInvocationIdentity - if *v == nil { - cv = []types.MaintenanceWindowExecutionTaskInvocationIdentity{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.MaintenanceWindowExecutionTaskInvocationIdentity - destAddr := &col - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionTaskInvocationIdentity(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowIdentity(v **types.MaintenanceWindowIdentity, 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.MaintenanceWindowIdentity - if *v == nil { - sv = &types.MaintenanceWindowIdentity{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Cutoff": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowCutoff to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Cutoff = int32(i64) - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "Duration": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowDurationHours to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Duration = ptr.Int32(int32(i64)) - } - - case "Enabled": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected MaintenanceWindowEnabled to be of type *bool, got %T instead", value) - } - sv.Enabled = jtv - } - - case "EndDate": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowStringDateTime to be of type string, got %T instead", value) - } - sv.EndDate = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "NextExecutionTime": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowStringDateTime to be of type string, got %T instead", value) - } - sv.NextExecutionTime = ptr.String(jtv) - } - - case "Schedule": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowSchedule to be of type string, got %T instead", value) - } - sv.Schedule = ptr.String(jtv) - } - - case "ScheduleOffset": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowOffset to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ScheduleOffset = ptr.Int32(int32(i64)) - } - - case "ScheduleTimezone": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTimezone to be of type string, got %T instead", value) - } - sv.ScheduleTimezone = ptr.String(jtv) - } - - case "StartDate": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowStringDateTime to be of type string, got %T instead", value) - } - sv.StartDate = ptr.String(jtv) - } - - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowIdentityForTarget(v **types.MaintenanceWindowIdentityForTarget, 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.MaintenanceWindowIdentityForTarget - if *v == nil { - sv = &types.MaintenanceWindowIdentityForTarget{} - } 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 MaintenanceWindowName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowIdentityList(v *[]types.MaintenanceWindowIdentity, 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.MaintenanceWindowIdentity - if *v == nil { - cv = []types.MaintenanceWindowIdentity{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.MaintenanceWindowIdentity - destAddr := &col - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowIdentity(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowLambdaParameters(v **types.MaintenanceWindowLambdaParameters, 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.MaintenanceWindowLambdaParameters - if *v == nil { - sv = &types.MaintenanceWindowLambdaParameters{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ClientContext": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowLambdaClientContext to be of type string, got %T instead", value) - } - sv.ClientContext = ptr.String(jtv) - } - - case "Payload": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowLambdaPayload to be []byte, got %T instead", value) - } - dv, err := base64.StdEncoding.DecodeString(jtv) - if err != nil { - return fmt.Errorf("failed to base64 decode MaintenanceWindowLambdaPayload, %w", err) - } - sv.Payload = dv - } - - case "Qualifier": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowLambdaQualifier to be of type string, got %T instead", value) - } - sv.Qualifier = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowRunCommandParameters(v **types.MaintenanceWindowRunCommandParameters, 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.MaintenanceWindowRunCommandParameters - if *v == nil { - sv = &types.MaintenanceWindowRunCommandParameters{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CloudWatchOutputConfig": - if err := awsAwsjson11_deserializeDocumentCloudWatchOutputConfig(&sv.CloudWatchOutputConfig, value); err != nil { - return err - } - - case "Comment": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Comment to be of type string, got %T instead", value) - } - sv.Comment = ptr.String(jtv) - } - - case "DocumentHash": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentHash to be of type string, got %T instead", value) - } - sv.DocumentHash = ptr.String(jtv) - } - - case "DocumentHashType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentHashType to be of type string, got %T instead", value) - } - sv.DocumentHashType = types.DocumentHashType(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "NotificationConfig": - if err := awsAwsjson11_deserializeDocumentNotificationConfig(&sv.NotificationConfig, value); err != nil { - return err - } - - case "OutputS3BucketName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3BucketName to be of type string, got %T instead", value) - } - sv.OutputS3BucketName = ptr.String(jtv) - } - - case "OutputS3KeyPrefix": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3KeyPrefix to be of type string, got %T instead", value) - } - sv.OutputS3KeyPrefix = ptr.String(jtv) - } - - case "Parameters": - if err := awsAwsjson11_deserializeDocumentParameters(&sv.Parameters, value); err != nil { - return err - } - - case "ServiceRoleArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ServiceRole to be of type string, got %T instead", value) - } - sv.ServiceRoleArn = ptr.String(jtv) - } - - case "TimeoutSeconds": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected TimeoutSeconds to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.TimeoutSeconds = ptr.Int32(int32(i64)) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowsForTargetList(v *[]types.MaintenanceWindowIdentityForTarget, 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.MaintenanceWindowIdentityForTarget - if *v == nil { - cv = []types.MaintenanceWindowIdentityForTarget{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.MaintenanceWindowIdentityForTarget - destAddr := &col - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowIdentityForTarget(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowStepFunctionsParameters(v **types.MaintenanceWindowStepFunctionsParameters, 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.MaintenanceWindowStepFunctionsParameters - if *v == nil { - sv = &types.MaintenanceWindowStepFunctionsParameters{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Input": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowStepFunctionsInput to be of type string, got %T instead", value) - } - sv.Input = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowStepFunctionsName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowTarget(v **types.MaintenanceWindowTarget, 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.MaintenanceWindowTarget - if *v == nil { - sv = &types.MaintenanceWindowTarget{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "OwnerInformation": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OwnerInformation to be of type string, got %T instead", value) - } - sv.OwnerInformation = ptr.String(jtv) - } - - case "ResourceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowResourceType to be of type string, got %T instead", value) - } - sv.ResourceType = types.MaintenanceWindowResourceType(jtv) - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - case "WindowTargetId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTargetId to be of type string, got %T instead", value) - } - sv.WindowTargetId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowTargetList(v *[]types.MaintenanceWindowTarget, 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.MaintenanceWindowTarget - if *v == nil { - cv = []types.MaintenanceWindowTarget{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.MaintenanceWindowTarget - destAddr := &col - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTarget(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowTask(v **types.MaintenanceWindowTask, 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.MaintenanceWindowTask - if *v == nil { - sv = &types.MaintenanceWindowTask{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.AlarmConfiguration, value); err != nil { - return err - } - - case "CutoffBehavior": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskCutoffBehavior to be of type string, got %T instead", value) - } - sv.CutoffBehavior = types.MaintenanceWindowTaskCutoffBehavior(jtv) - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "LoggingInfo": - if err := awsAwsjson11_deserializeDocumentLoggingInfo(&sv.LoggingInfo, value); err != nil { - return err - } - - case "MaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.MaxConcurrency = ptr.String(jtv) - } - - case "MaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.MaxErrors = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Priority": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskPriority to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Priority = int32(i64) - } - - case "ServiceRoleArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ServiceRole to be of type string, got %T instead", value) - } - sv.ServiceRoleArn = ptr.String(jtv) - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - case "TaskArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskArn to be of type string, got %T instead", value) - } - sv.TaskArn = ptr.String(jtv) - } - - case "TaskParameters": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTaskParameters(&sv.TaskParameters, value); err != nil { - return err - } - - case "Type": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskType to be of type string, got %T instead", value) - } - sv.Type = types.MaintenanceWindowTaskType(jtv) - } - - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - case "WindowTaskId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskId to be of type string, got %T instead", value) - } - sv.WindowTaskId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowTaskInvocationParameters(v **types.MaintenanceWindowTaskInvocationParameters, 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.MaintenanceWindowTaskInvocationParameters - if *v == nil { - sv = &types.MaintenanceWindowTaskInvocationParameters{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Automation": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowAutomationParameters(&sv.Automation, value); err != nil { - return err - } - - case "Lambda": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowLambdaParameters(&sv.Lambda, value); err != nil { - return err - } - - case "RunCommand": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowRunCommandParameters(&sv.RunCommand, value); err != nil { - return err - } - - case "StepFunctions": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowStepFunctionsParameters(&sv.StepFunctions, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowTaskList(v *[]types.MaintenanceWindowTask, 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.MaintenanceWindowTask - if *v == nil { - cv = []types.MaintenanceWindowTask{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.MaintenanceWindowTask - destAddr := &col - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTask(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowTaskParameters(v *map[string]types.MaintenanceWindowTaskParameterValueExpression, 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]types.MaintenanceWindowTaskParameterValueExpression - if *v == nil { - mv = map[string]types.MaintenanceWindowTaskParameterValueExpression{} - } else { - mv = *v - } - - for key, value := range shape { - var parsedVal types.MaintenanceWindowTaskParameterValueExpression - mapVar := parsedVal - destAddr := &mapVar - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTaskParameterValueExpression(&destAddr, value); err != nil { - return err - } - parsedVal = *destAddr - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowTaskParametersList(v *[]map[string]types.MaintenanceWindowTaskParameterValueExpression, 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 []map[string]types.MaintenanceWindowTaskParameterValueExpression - if *v == nil { - cv = []map[string]types.MaintenanceWindowTaskParameterValueExpression{} - } else { - cv = *v - } - - for _, value := range shape { - var col map[string]types.MaintenanceWindowTaskParameterValueExpression - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTaskParameters(&col, value); err != nil { - return err - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowTaskParameterValueExpression(v **types.MaintenanceWindowTaskParameterValueExpression, 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.MaintenanceWindowTaskParameterValueExpression - if *v == nil { - sv = &types.MaintenanceWindowTaskParameterValueExpression{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Values": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTaskParameterValueList(&sv.Values, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMaintenanceWindowTaskParameterValueList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskParameterValue to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentMaxDocumentSizeExceeded(v **types.MaxDocumentSizeExceeded, 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.MaxDocumentSizeExceeded - if *v == nil { - sv = &types.MaxDocumentSizeExceeded{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentMetadataMap(v *map[string]types.MetadataValue, 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]types.MetadataValue - if *v == nil { - mv = map[string]types.MetadataValue{} - } else { - mv = *v - } - - for key, value := range shape { - var parsedVal types.MetadataValue - mapVar := parsedVal - destAddr := &mapVar - if err := awsAwsjson11_deserializeDocumentMetadataValue(&destAddr, value); err != nil { - return err - } - parsedVal = *destAddr - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentMetadataValue(v **types.MetadataValue, 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.MetadataValue - if *v == nil { - sv = &types.MetadataValue{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Value": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MetadataValueString to be of type string, got %T instead", value) - } - sv.Value = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentNonCompliantSummary(v **types.NonCompliantSummary, 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.NonCompliantSummary - if *v == nil { - sv = &types.NonCompliantSummary{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "NonCompliantCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ComplianceSummaryCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.NonCompliantCount = int32(i64) - } - - case "SeveritySummary": - if err := awsAwsjson11_deserializeDocumentSeveritySummary(&sv.SeveritySummary, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentNormalStringMap(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 String to be of type string, got %T instead", value) - } - parsedVal = jtv - } - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentNotificationConfig(v **types.NotificationConfig, 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.NotificationConfig - if *v == nil { - sv = &types.NotificationConfig{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "NotificationArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NotificationArn to be of type string, got %T instead", value) - } - sv.NotificationArn = ptr.String(jtv) - } - - case "NotificationEvents": - if err := awsAwsjson11_deserializeDocumentNotificationEventList(&sv.NotificationEvents, value); err != nil { - return err - } - - case "NotificationType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NotificationType to be of type string, got %T instead", value) - } - sv.NotificationType = types.NotificationType(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentNotificationEventList(v *[]types.NotificationEvent, 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.NotificationEvent - if *v == nil { - cv = []types.NotificationEvent{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.NotificationEvent - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NotificationEvent to be of type string, got %T instead", value) - } - col = types.NotificationEvent(jtv) - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsEntity(v **types.OpsEntity, 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.OpsEntity - if *v == nil { - sv = &types.OpsEntity{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Data": - if err := awsAwsjson11_deserializeDocumentOpsEntityItemMap(&sv.Data, value); err != nil { - return err - } - - case "Id": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsEntityId to be of type string, got %T instead", value) - } - sv.Id = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsEntityItem(v **types.OpsEntityItem, 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.OpsEntityItem - if *v == nil { - sv = &types.OpsEntityItem{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CaptureTime": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsEntityItemCaptureTime to be of type string, got %T instead", value) - } - sv.CaptureTime = ptr.String(jtv) - } - - case "Content": - if err := awsAwsjson11_deserializeDocumentOpsEntityItemEntryList(&sv.Content, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsEntityItemEntry(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 AttributeValue to be of type string, got %T instead", value) - } - parsedVal = jtv - } - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsEntityItemEntryList(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.([]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var cv []map[string]string - if *v == nil { - cv = []map[string]string{} - } else { - cv = *v - } - - for _, value := range shape { - var col map[string]string - if err := awsAwsjson11_deserializeDocumentOpsEntityItemEntry(&col, value); err != nil { - return err - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsEntityItemMap(v *map[string]types.OpsEntityItem, 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]types.OpsEntityItem - if *v == nil { - mv = map[string]types.OpsEntityItem{} - } else { - mv = *v - } - - for key, value := range shape { - var parsedVal types.OpsEntityItem - mapVar := parsedVal - destAddr := &mapVar - if err := awsAwsjson11_deserializeDocumentOpsEntityItem(&destAddr, value); err != nil { - return err - } - parsedVal = *destAddr - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsEntityList(v *[]types.OpsEntity, 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.OpsEntity - if *v == nil { - cv = []types.OpsEntity{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.OpsEntity - destAddr := &col - if err := awsAwsjson11_deserializeDocumentOpsEntity(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItem(v **types.OpsItem, 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.OpsItem - if *v == nil { - sv = &types.OpsItem{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ActualEndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ActualEndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ActualStartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ActualStartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Category": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemCategory to be of type string, got %T instead", value) - } - sv.Category = ptr.String(jtv) - } - - case "CreatedBy": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.CreatedBy = ptr.String(jtv) - } - - case "CreatedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "LastModifiedBy": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.LastModifiedBy = ptr.String(jtv) - } - - case "LastModifiedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastModifiedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Notifications": - if err := awsAwsjson11_deserializeDocumentOpsItemNotifications(&sv.Notifications, value); err != nil { - return err - } - - case "OperationalData": - if err := awsAwsjson11_deserializeDocumentOpsItemOperationalData(&sv.OperationalData, value); err != nil { - return err - } - - case "OpsItemArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemArn to be of type string, got %T instead", value) - } - sv.OpsItemArn = ptr.String(jtv) - } - - case "OpsItemId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemId to be of type string, got %T instead", value) - } - sv.OpsItemId = ptr.String(jtv) - } - - case "OpsItemType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemType to be of type string, got %T instead", value) - } - sv.OpsItemType = ptr.String(jtv) - } - - case "PlannedEndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.PlannedEndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "PlannedStartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.PlannedStartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Priority": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected OpsItemPriority to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Priority = ptr.Int32(int32(i64)) - } - - case "RelatedOpsItems": - if err := awsAwsjson11_deserializeDocumentRelatedOpsItems(&sv.RelatedOpsItems, value); err != nil { - return err - } - - case "Severity": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemSeverity to be of type string, got %T instead", value) - } - sv.Severity = ptr.String(jtv) - } - - case "Source": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemSource to be of type string, got %T instead", value) - } - sv.Source = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemStatus to be of type string, got %T instead", value) - } - sv.Status = types.OpsItemStatus(jtv) - } - - case "Title": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemTitle to be of type string, got %T instead", value) - } - sv.Title = ptr.String(jtv) - } - - case "Version": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Version = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemAccessDeniedException(v **types.OpsItemAccessDeniedException, 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.OpsItemAccessDeniedException - if *v == nil { - sv = &types.OpsItemAccessDeniedException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemAlreadyExistsException(v **types.OpsItemAlreadyExistsException, 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.OpsItemAlreadyExistsException - if *v == nil { - sv = &types.OpsItemAlreadyExistsException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "OpsItemId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.OpsItemId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemConflictException(v **types.OpsItemConflictException, 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.OpsItemConflictException - if *v == nil { - sv = &types.OpsItemConflictException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemDataValue(v **types.OpsItemDataValue, 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.OpsItemDataValue - if *v == nil { - sv = &types.OpsItemDataValue{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Type": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemDataType to be of type string, got %T instead", value) - } - sv.Type = types.OpsItemDataType(jtv) - } - - case "Value": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemDataValueString to be of type string, got %T instead", value) - } - sv.Value = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemEventSummaries(v *[]types.OpsItemEventSummary, 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.OpsItemEventSummary - if *v == nil { - cv = []types.OpsItemEventSummary{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.OpsItemEventSummary - destAddr := &col - if err := awsAwsjson11_deserializeDocumentOpsItemEventSummary(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemEventSummary(v **types.OpsItemEventSummary, 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.OpsItemEventSummary - if *v == nil { - sv = &types.OpsItemEventSummary{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CreatedBy": - if err := awsAwsjson11_deserializeDocumentOpsItemIdentity(&sv.CreatedBy, value); err != nil { - return err - } - - case "CreatedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Detail": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Detail = ptr.String(jtv) - } - - case "DetailType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.DetailType = ptr.String(jtv) - } - - case "EventId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.EventId = ptr.String(jtv) - } - - case "OpsItemId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.OpsItemId = ptr.String(jtv) - } - - case "Source": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Source = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemIdentity(v **types.OpsItemIdentity, 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.OpsItemIdentity - if *v == nil { - sv = &types.OpsItemIdentity{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Arn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Arn = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemInvalidParameterException(v **types.OpsItemInvalidParameterException, 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.OpsItemInvalidParameterException - if *v == nil { - sv = &types.OpsItemInvalidParameterException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "ParameterNames": - if err := awsAwsjson11_deserializeDocumentOpsItemParameterNamesList(&sv.ParameterNames, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemLimitExceededException(v **types.OpsItemLimitExceededException, 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.OpsItemLimitExceededException - if *v == nil { - sv = &types.OpsItemLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Limit": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Limit = int32(i64) - } - - case "LimitType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.LimitType = ptr.String(jtv) - } - - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "ResourceTypes": - if err := awsAwsjson11_deserializeDocumentOpsItemParameterNamesList(&sv.ResourceTypes, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemNotFoundException(v **types.OpsItemNotFoundException, 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.OpsItemNotFoundException - if *v == nil { - sv = &types.OpsItemNotFoundException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemNotification(v **types.OpsItemNotification, 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.OpsItemNotification - if *v == nil { - sv = &types.OpsItemNotification{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Arn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Arn = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemNotifications(v *[]types.OpsItemNotification, 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.OpsItemNotification - if *v == nil { - cv = []types.OpsItemNotification{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.OpsItemNotification - destAddr := &col - if err := awsAwsjson11_deserializeDocumentOpsItemNotification(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemOperationalData(v *map[string]types.OpsItemDataValue, 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]types.OpsItemDataValue - if *v == nil { - mv = map[string]types.OpsItemDataValue{} - } else { - mv = *v - } - - for key, value := range shape { - var parsedVal types.OpsItemDataValue - mapVar := parsedVal - destAddr := &mapVar - if err := awsAwsjson11_deserializeDocumentOpsItemDataValue(&destAddr, value); err != nil { - return err - } - parsedVal = *destAddr - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemParameterNamesList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemRelatedItemAlreadyExistsException(v **types.OpsItemRelatedItemAlreadyExistsException, 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.OpsItemRelatedItemAlreadyExistsException - if *v == nil { - sv = &types.OpsItemRelatedItemAlreadyExistsException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "OpsItemId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemId to be of type string, got %T instead", value) - } - sv.OpsItemId = ptr.String(jtv) - } - - case "ResourceUri": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemRelatedItemAssociationResourceUri to be of type string, got %T instead", value) - } - sv.ResourceUri = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemRelatedItemAssociationNotFoundException(v **types.OpsItemRelatedItemAssociationNotFoundException, 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.OpsItemRelatedItemAssociationNotFoundException - if *v == nil { - sv = &types.OpsItemRelatedItemAssociationNotFoundException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemRelatedItemSummaries(v *[]types.OpsItemRelatedItemSummary, 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.OpsItemRelatedItemSummary - if *v == nil { - cv = []types.OpsItemRelatedItemSummary{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.OpsItemRelatedItemSummary - destAddr := &col - if err := awsAwsjson11_deserializeDocumentOpsItemRelatedItemSummary(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemRelatedItemSummary(v **types.OpsItemRelatedItemSummary, 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.OpsItemRelatedItemSummary - if *v == nil { - sv = &types.OpsItemRelatedItemSummary{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemRelatedItemAssociationId to be of type string, got %T instead", value) - } - sv.AssociationId = ptr.String(jtv) - } - - case "AssociationType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemRelatedItemAssociationType to be of type string, got %T instead", value) - } - sv.AssociationType = ptr.String(jtv) - } - - case "CreatedBy": - if err := awsAwsjson11_deserializeDocumentOpsItemIdentity(&sv.CreatedBy, value); err != nil { - return err - } - - case "CreatedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastModifiedBy": - if err := awsAwsjson11_deserializeDocumentOpsItemIdentity(&sv.LastModifiedBy, value); err != nil { - return err - } - - case "LastModifiedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastModifiedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "OpsItemId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemId to be of type string, got %T instead", value) - } - sv.OpsItemId = ptr.String(jtv) - } - - case "ResourceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemRelatedItemAssociationResourceType to be of type string, got %T instead", value) - } - sv.ResourceType = ptr.String(jtv) - } - - case "ResourceUri": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemRelatedItemAssociationResourceUri to be of type string, got %T instead", value) - } - sv.ResourceUri = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemSummaries(v *[]types.OpsItemSummary, 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.OpsItemSummary - if *v == nil { - cv = []types.OpsItemSummary{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.OpsItemSummary - destAddr := &col - if err := awsAwsjson11_deserializeDocumentOpsItemSummary(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsItemSummary(v **types.OpsItemSummary, 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.OpsItemSummary - if *v == nil { - sv = &types.OpsItemSummary{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ActualEndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ActualEndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ActualStartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ActualStartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Category": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemCategory to be of type string, got %T instead", value) - } - sv.Category = ptr.String(jtv) - } - - case "CreatedBy": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.CreatedBy = ptr.String(jtv) - } - - case "CreatedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastModifiedBy": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.LastModifiedBy = ptr.String(jtv) - } - - case "LastModifiedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastModifiedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "OperationalData": - if err := awsAwsjson11_deserializeDocumentOpsItemOperationalData(&sv.OperationalData, value); err != nil { - return err - } - - case "OpsItemId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemId to be of type string, got %T instead", value) - } - sv.OpsItemId = ptr.String(jtv) - } - - case "OpsItemType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemType to be of type string, got %T instead", value) - } - sv.OpsItemType = ptr.String(jtv) - } - - case "PlannedEndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.PlannedEndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "PlannedStartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.PlannedStartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Priority": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected OpsItemPriority to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Priority = ptr.Int32(int32(i64)) - } - - case "Severity": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemSeverity to be of type string, got %T instead", value) - } - sv.Severity = ptr.String(jtv) - } - - case "Source": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemSource to be of type string, got %T instead", value) - } - sv.Source = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemStatus to be of type string, got %T instead", value) - } - sv.Status = types.OpsItemStatus(jtv) - } - - case "Title": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemTitle to be of type string, got %T instead", value) - } - sv.Title = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsMetadata(v **types.OpsMetadata, 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.OpsMetadata - if *v == nil { - sv = &types.OpsMetadata{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CreationDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreationDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastModifiedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastModifiedUser": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.LastModifiedUser = ptr.String(jtv) - } - - case "OpsMetadataArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsMetadataArn to be of type string, got %T instead", value) - } - sv.OpsMetadataArn = ptr.String(jtv) - } - - case "ResourceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsMetadataResourceId to be of type string, got %T instead", value) - } - sv.ResourceId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsMetadataAlreadyExistsException(v **types.OpsMetadataAlreadyExistsException, 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.OpsMetadataAlreadyExistsException - if *v == nil { - sv = &types.OpsMetadataAlreadyExistsException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsMetadataInvalidArgumentException(v **types.OpsMetadataInvalidArgumentException, 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.OpsMetadataInvalidArgumentException - if *v == nil { - sv = &types.OpsMetadataInvalidArgumentException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsMetadataKeyLimitExceededException(v **types.OpsMetadataKeyLimitExceededException, 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.OpsMetadataKeyLimitExceededException - if *v == nil { - sv = &types.OpsMetadataKeyLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsMetadataLimitExceededException(v **types.OpsMetadataLimitExceededException, 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.OpsMetadataLimitExceededException - if *v == nil { - sv = &types.OpsMetadataLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsMetadataList(v *[]types.OpsMetadata, 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.OpsMetadata - if *v == nil { - cv = []types.OpsMetadata{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.OpsMetadata - destAddr := &col - if err := awsAwsjson11_deserializeDocumentOpsMetadata(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsMetadataNotFoundException(v **types.OpsMetadataNotFoundException, 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.OpsMetadataNotFoundException - if *v == nil { - sv = &types.OpsMetadataNotFoundException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOpsMetadataTooManyUpdatesException(v **types.OpsMetadataTooManyUpdatesException, 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.OpsMetadataTooManyUpdatesException - if *v == nil { - sv = &types.OpsMetadataTooManyUpdatesException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentOutputSource(v **types.OutputSource, 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.OutputSource - if *v == nil { - sv = &types.OutputSource{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "OutputSourceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OutputSourceId to be of type string, got %T instead", value) - } - sv.OutputSourceId = ptr.String(jtv) - } - - case "OutputSourceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OutputSourceType to be of type string, got %T instead", value) - } - sv.OutputSourceType = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParameter(v **types.Parameter, 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.Parameter - if *v == nil { - sv = &types.Parameter{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "DataType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterDataType to be of type string, got %T instead", value) - } - sv.DataType = ptr.String(jtv) - } - - case "LastModifiedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PSParameterName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Selector": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PSParameterSelector to be of type string, got %T instead", value) - } - sv.Selector = ptr.String(jtv) - } - - case "SourceResult": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.SourceResult = ptr.String(jtv) - } - - case "Type": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterType to be of type string, got %T instead", value) - } - sv.Type = types.ParameterType(jtv) - } - - case "Value": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PSParameterValue to be of type string, got %T instead", value) - } - sv.Value = ptr.String(jtv) - } - - case "Version": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PSParameterVersion to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Version = i64 - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterAlreadyExists(v **types.ParameterAlreadyExists, 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.ParameterAlreadyExists - if *v == nil { - sv = &types.ParameterAlreadyExists{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterHistory(v **types.ParameterHistory, 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.ParameterHistory - if *v == nil { - sv = &types.ParameterHistory{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AllowedPattern": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AllowedPattern to be of type string, got %T instead", value) - } - sv.AllowedPattern = ptr.String(jtv) - } - - case "DataType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterDataType to be of type string, got %T instead", value) - } - sv.DataType = ptr.String(jtv) - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "KeyId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterKeyId to be of type string, got %T instead", value) - } - sv.KeyId = ptr.String(jtv) - } - - case "Labels": - if err := awsAwsjson11_deserializeDocumentParameterLabelList(&sv.Labels, value); err != nil { - return err - } - - case "LastModifiedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastModifiedUser": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.LastModifiedUser = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PSParameterName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Policies": - if err := awsAwsjson11_deserializeDocumentParameterPolicyList(&sv.Policies, value); err != nil { - return err - } - - case "Tier": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterTier to be of type string, got %T instead", value) - } - sv.Tier = types.ParameterTier(jtv) - } - - case "Type": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterType to be of type string, got %T instead", value) - } - sv.Type = types.ParameterType(jtv) - } - - case "Value": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PSParameterValue to be of type string, got %T instead", value) - } - sv.Value = ptr.String(jtv) - } - - case "Version": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PSParameterVersion to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Version = i64 - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterHistoryList(v *[]types.ParameterHistory, 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.ParameterHistory - if *v == nil { - cv = []types.ParameterHistory{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ParameterHistory - destAddr := &col - if err := awsAwsjson11_deserializeDocumentParameterHistory(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterInlinePolicy(v **types.ParameterInlinePolicy, 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.ParameterInlinePolicy - if *v == nil { - sv = &types.ParameterInlinePolicy{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "PolicyStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.PolicyStatus = ptr.String(jtv) - } - - case "PolicyText": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.PolicyText = ptr.String(jtv) - } - - case "PolicyType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.PolicyType = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterLabelList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterLabel to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterLimitExceeded(v **types.ParameterLimitExceeded, 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.ParameterLimitExceeded - if *v == nil { - sv = &types.ParameterLimitExceeded{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterList(v *[]types.Parameter, 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.Parameter - if *v == nil { - cv = []types.Parameter{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.Parameter - destAddr := &col - if err := awsAwsjson11_deserializeDocumentParameter(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterMaxVersionLimitExceeded(v **types.ParameterMaxVersionLimitExceeded, 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.ParameterMaxVersionLimitExceeded - if *v == nil { - sv = &types.ParameterMaxVersionLimitExceeded{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterMetadata(v **types.ParameterMetadata, 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.ParameterMetadata - if *v == nil { - sv = &types.ParameterMetadata{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AllowedPattern": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AllowedPattern to be of type string, got %T instead", value) - } - sv.AllowedPattern = ptr.String(jtv) - } - - case "DataType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterDataType to be of type string, got %T instead", value) - } - sv.DataType = ptr.String(jtv) - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "KeyId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterKeyId to be of type string, got %T instead", value) - } - sv.KeyId = ptr.String(jtv) - } - - case "LastModifiedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastModifiedUser": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.LastModifiedUser = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PSParameterName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Policies": - if err := awsAwsjson11_deserializeDocumentParameterPolicyList(&sv.Policies, value); err != nil { - return err - } - - case "Tier": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterTier to be of type string, got %T instead", value) - } - sv.Tier = types.ParameterTier(jtv) - } - - case "Type": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterType to be of type string, got %T instead", value) - } - sv.Type = types.ParameterType(jtv) - } - - case "Version": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PSParameterVersion to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Version = i64 - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterMetadataList(v *[]types.ParameterMetadata, 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.ParameterMetadata - if *v == nil { - cv = []types.ParameterMetadata{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ParameterMetadata - destAddr := &col - if err := awsAwsjson11_deserializeDocumentParameterMetadata(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterNameList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PSParameterName to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterNotFound(v **types.ParameterNotFound, 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.ParameterNotFound - if *v == nil { - sv = &types.ParameterNotFound{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterPatternMismatchException(v **types.ParameterPatternMismatchException, 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.ParameterPatternMismatchException - if *v == nil { - sv = &types.ParameterPatternMismatchException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterPolicyList(v *[]types.ParameterInlinePolicy, 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.ParameterInlinePolicy - if *v == nil { - cv = []types.ParameterInlinePolicy{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ParameterInlinePolicy - destAddr := &col - if err := awsAwsjson11_deserializeDocumentParameterInlinePolicy(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentParameters(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 - mapVar := parsedVal - if err := awsAwsjson11_deserializeDocumentParameterValueList(&mapVar, value); err != nil { - return err - } - parsedVal = mapVar - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterValueList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterValue to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterVersionLabelLimitExceeded(v **types.ParameterVersionLabelLimitExceeded, 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.ParameterVersionLabelLimitExceeded - if *v == nil { - sv = &types.ParameterVersionLabelLimitExceeded{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParameterVersionNotFound(v **types.ParameterVersionNotFound, 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.ParameterVersionNotFound - if *v == nil { - sv = &types.ParameterVersionNotFound{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentParentStepDetails(v **types.ParentStepDetails, 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.ParentStepDetails - if *v == nil { - sv = &types.ParentStepDetails{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Action": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationActionName to be of type string, got %T instead", value) - } - sv.Action = ptr.String(jtv) - } - - case "Iteration": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Iteration = ptr.Int32(int32(i64)) - } - - case "IteratorValue": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.IteratorValue = ptr.String(jtv) - } - - case "StepExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.StepExecutionId = ptr.String(jtv) - } - - case "StepName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.StepName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPatch(v **types.Patch, 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.Patch - if *v == nil { - sv = &types.Patch{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AdvisoryIds": - if err := awsAwsjson11_deserializeDocumentPatchAdvisoryIdList(&sv.AdvisoryIds, value); err != nil { - return err - } - - case "Arch": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchArch to be of type string, got %T instead", value) - } - sv.Arch = ptr.String(jtv) - } - - case "BugzillaIds": - if err := awsAwsjson11_deserializeDocumentPatchBugzillaIdList(&sv.BugzillaIds, value); err != nil { - return err - } - - case "Classification": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchClassification to be of type string, got %T instead", value) - } - sv.Classification = ptr.String(jtv) - } - - case "ContentUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchContentUrl to be of type string, got %T instead", value) - } - sv.ContentUrl = ptr.String(jtv) - } - - case "CVEIds": - if err := awsAwsjson11_deserializeDocumentPatchCVEIdList(&sv.CVEIds, value); err != nil { - return err - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "Epoch": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PatchEpoch to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Epoch = int32(i64) - } - - case "Id": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchId to be of type string, got %T instead", value) - } - sv.Id = ptr.String(jtv) - } - - case "KbNumber": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchKbNumber to be of type string, got %T instead", value) - } - sv.KbNumber = ptr.String(jtv) - } - - case "Language": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchLanguage to be of type string, got %T instead", value) - } - sv.Language = ptr.String(jtv) - } - - case "MsrcNumber": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchMsrcNumber to be of type string, got %T instead", value) - } - sv.MsrcNumber = ptr.String(jtv) - } - - case "MsrcSeverity": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchMsrcSeverity to be of type string, got %T instead", value) - } - sv.MsrcSeverity = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Product": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchProduct to be of type string, got %T instead", value) - } - sv.Product = ptr.String(jtv) - } - - case "ProductFamily": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchProductFamily to be of type string, got %T instead", value) - } - sv.ProductFamily = ptr.String(jtv) - } - - case "Release": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchRelease to be of type string, got %T instead", value) - } - sv.Release = ptr.String(jtv) - } - - case "ReleaseDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ReleaseDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Repository": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchRepository to be of type string, got %T instead", value) - } - sv.Repository = ptr.String(jtv) - } - - case "Severity": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchSeverity to be of type string, got %T instead", value) - } - sv.Severity = ptr.String(jtv) - } - - case "Title": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchTitle to be of type string, got %T instead", value) - } - sv.Title = ptr.String(jtv) - } - - case "Vendor": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchVendor to be of type string, got %T instead", value) - } - sv.Vendor = ptr.String(jtv) - } - - case "Version": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchVersion to be of type string, got %T instead", value) - } - sv.Version = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchAdvisoryIdList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchAdvisoryId to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchBaselineIdentity(v **types.PatchBaselineIdentity, 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.PatchBaselineIdentity - if *v == nil { - sv = &types.PatchBaselineIdentity{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "BaselineDescription": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineDescription to be of type string, got %T instead", value) - } - sv.BaselineDescription = ptr.String(jtv) - } - - case "BaselineId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineId to be of type string, got %T instead", value) - } - sv.BaselineId = ptr.String(jtv) - } - - case "BaselineName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineName to be of type string, got %T instead", value) - } - sv.BaselineName = ptr.String(jtv) - } - - case "DefaultBaseline": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected DefaultBaseline to be of type *bool, got %T instead", value) - } - sv.DefaultBaseline = jtv - } - - case "OperatingSystem": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OperatingSystem to be of type string, got %T instead", value) - } - sv.OperatingSystem = types.OperatingSystem(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchBaselineIdentityList(v *[]types.PatchBaselineIdentity, 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.PatchBaselineIdentity - if *v == nil { - cv = []types.PatchBaselineIdentity{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.PatchBaselineIdentity - destAddr := &col - if err := awsAwsjson11_deserializeDocumentPatchBaselineIdentity(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchBugzillaIdList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchBugzillaId to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchComplianceData(v **types.PatchComplianceData, 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.PatchComplianceData - if *v == nil { - sv = &types.PatchComplianceData{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Classification": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchClassification to be of type string, got %T instead", value) - } - sv.Classification = ptr.String(jtv) - } - - case "CVEIds": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchCVEIds to be of type string, got %T instead", value) - } - sv.CVEIds = ptr.String(jtv) - } - - case "InstalledTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.InstalledTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "KBId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchKbNumber to be of type string, got %T instead", value) - } - sv.KBId = ptr.String(jtv) - } - - case "Severity": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchSeverity to be of type string, got %T instead", value) - } - sv.Severity = ptr.String(jtv) - } - - case "State": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchComplianceDataState to be of type string, got %T instead", value) - } - sv.State = types.PatchComplianceDataState(jtv) - } - - case "Title": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchTitle to be of type string, got %T instead", value) - } - sv.Title = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchComplianceDataList(v *[]types.PatchComplianceData, 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.PatchComplianceData - if *v == nil { - cv = []types.PatchComplianceData{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.PatchComplianceData - destAddr := &col - if err := awsAwsjson11_deserializeDocumentPatchComplianceData(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchCVEIdList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchCVEId to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchFilter(v **types.PatchFilter, 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.PatchFilter - if *v == nil { - sv = &types.PatchFilter{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Key": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchFilterKey to be of type string, got %T instead", value) - } - sv.Key = types.PatchFilterKey(jtv) - } - - case "Values": - if err := awsAwsjson11_deserializeDocumentPatchFilterValueList(&sv.Values, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchFilterGroup(v **types.PatchFilterGroup, 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.PatchFilterGroup - if *v == nil { - sv = &types.PatchFilterGroup{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "PatchFilters": - if err := awsAwsjson11_deserializeDocumentPatchFilterList(&sv.PatchFilters, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchFilterList(v *[]types.PatchFilter, 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.PatchFilter - if *v == nil { - cv = []types.PatchFilter{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.PatchFilter - destAddr := &col - if err := awsAwsjson11_deserializeDocumentPatchFilter(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchFilterValueList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchFilterValue to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchGroupList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchGroup to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchGroupPatchBaselineMapping(v **types.PatchGroupPatchBaselineMapping, 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.PatchGroupPatchBaselineMapping - if *v == nil { - sv = &types.PatchGroupPatchBaselineMapping{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "BaselineIdentity": - if err := awsAwsjson11_deserializeDocumentPatchBaselineIdentity(&sv.BaselineIdentity, value); err != nil { - return err - } - - case "PatchGroup": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchGroup to be of type string, got %T instead", value) - } - sv.PatchGroup = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchGroupPatchBaselineMappingList(v *[]types.PatchGroupPatchBaselineMapping, 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.PatchGroupPatchBaselineMapping - if *v == nil { - cv = []types.PatchGroupPatchBaselineMapping{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.PatchGroupPatchBaselineMapping - destAddr := &col - if err := awsAwsjson11_deserializeDocumentPatchGroupPatchBaselineMapping(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchIdList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchId to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchList(v *[]types.Patch, 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.Patch - if *v == nil { - cv = []types.Patch{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.Patch - destAddr := &col - if err := awsAwsjson11_deserializeDocumentPatch(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchPropertiesList(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.([]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var cv []map[string]string - if *v == nil { - cv = []map[string]string{} - } else { - cv = *v - } - - for _, value := range shape { - var col map[string]string - if err := awsAwsjson11_deserializeDocumentPatchPropertyEntry(&col, value); err != nil { - return err - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchPropertyEntry(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 AttributeValue to be of type string, got %T instead", value) - } - parsedVal = jtv - } - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchRule(v **types.PatchRule, 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.PatchRule - if *v == nil { - sv = &types.PatchRule{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ApproveAfterDays": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ApproveAfterDays to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ApproveAfterDays = ptr.Int32(int32(i64)) - } - - case "ApproveUntilDate": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchStringDateTime to be of type string, got %T instead", value) - } - sv.ApproveUntilDate = ptr.String(jtv) - } - - case "ComplianceLevel": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchComplianceLevel to be of type string, got %T instead", value) - } - sv.ComplianceLevel = types.PatchComplianceLevel(jtv) - } - - case "EnableNonSecurity": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected Boolean to be of type *bool, got %T instead", value) - } - sv.EnableNonSecurity = ptr.Bool(jtv) - } - - case "PatchFilterGroup": - if err := awsAwsjson11_deserializeDocumentPatchFilterGroup(&sv.PatchFilterGroup, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchRuleGroup(v **types.PatchRuleGroup, 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.PatchRuleGroup - if *v == nil { - sv = &types.PatchRuleGroup{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "PatchRules": - if err := awsAwsjson11_deserializeDocumentPatchRuleList(&sv.PatchRules, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchRuleList(v *[]types.PatchRule, 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.PatchRule - if *v == nil { - cv = []types.PatchRule{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.PatchRule - destAddr := &col - if err := awsAwsjson11_deserializeDocumentPatchRule(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchSource(v **types.PatchSource, 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.PatchSource - if *v == nil { - sv = &types.PatchSource{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Configuration": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchSourceConfiguration to be of type string, got %T instead", value) - } - sv.Configuration = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchSourceName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Products": - if err := awsAwsjson11_deserializeDocumentPatchSourceProductList(&sv.Products, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchSourceList(v *[]types.PatchSource, 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.PatchSource - if *v == nil { - cv = []types.PatchSource{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.PatchSource - destAddr := &col - if err := awsAwsjson11_deserializeDocumentPatchSource(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchSourceProductList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchSourceProduct to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPatchStatus(v **types.PatchStatus, 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.PatchStatus - if *v == nil { - sv = &types.PatchStatus{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ApprovalDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ApprovalDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ComplianceLevel": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchComplianceLevel to be of type string, got %T instead", value) - } - sv.ComplianceLevel = types.PatchComplianceLevel(jtv) - } - - case "DeploymentStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchDeploymentStatus to be of type string, got %T instead", value) - } - sv.DeploymentStatus = types.PatchDeploymentStatus(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentPlatformTypeList(v *[]types.PlatformType, 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.PlatformType - if *v == nil { - cv = []types.PlatformType{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.PlatformType - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PlatformType to be of type string, got %T instead", value) - } - col = types.PlatformType(jtv) - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentPoliciesLimitExceededException(v **types.PoliciesLimitExceededException, 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.PoliciesLimitExceededException - if *v == nil { - sv = &types.PoliciesLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentProgressCounters(v **types.ProgressCounters, 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.ProgressCounters - if *v == nil { - sv = &types.ProgressCounters{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CancelledSteps": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.CancelledSteps = int32(i64) - } - - case "FailedSteps": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.FailedSteps = int32(i64) - } - - case "SuccessSteps": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.SuccessSteps = int32(i64) - } - - case "TimedOutSteps": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.TimedOutSteps = int32(i64) - } - - case "TotalSteps": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.TotalSteps = int32(i64) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentRegions(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Region to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentRelatedOpsItem(v **types.RelatedOpsItem, 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.RelatedOpsItem - if *v == nil { - sv = &types.RelatedOpsItem{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "OpsItemId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.OpsItemId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentRelatedOpsItems(v *[]types.RelatedOpsItem, 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.RelatedOpsItem - if *v == nil { - cv = []types.RelatedOpsItem{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.RelatedOpsItem - destAddr := &col - if err := awsAwsjson11_deserializeDocumentRelatedOpsItem(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentResolvedTargets(v **types.ResolvedTargets, 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.ResolvedTargets - if *v == nil { - sv = &types.ResolvedTargets{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ParameterValues": - if err := awsAwsjson11_deserializeDocumentTargetParameterList(&sv.ParameterValues, value); err != nil { - return err - } - - case "Truncated": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected Boolean to be of type *bool, got %T instead", value) - } - sv.Truncated = jtv - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceComplianceSummaryItem(v **types.ResourceComplianceSummaryItem, 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.ResourceComplianceSummaryItem - if *v == nil { - sv = &types.ResourceComplianceSummaryItem{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ComplianceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceTypeName to be of type string, got %T instead", value) - } - sv.ComplianceType = ptr.String(jtv) - } - - case "CompliantSummary": - if err := awsAwsjson11_deserializeDocumentCompliantSummary(&sv.CompliantSummary, value); err != nil { - return err - } - - case "ExecutionSummary": - if err := awsAwsjson11_deserializeDocumentComplianceExecutionSummary(&sv.ExecutionSummary, value); err != nil { - return err - } - - case "NonCompliantSummary": - if err := awsAwsjson11_deserializeDocumentNonCompliantSummary(&sv.NonCompliantSummary, value); err != nil { - return err - } - - case "OverallSeverity": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceSeverity to be of type string, got %T instead", value) - } - sv.OverallSeverity = types.ComplianceSeverity(jtv) - } - - case "ResourceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceResourceId to be of type string, got %T instead", value) - } - sv.ResourceId = ptr.String(jtv) - } - - case "ResourceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceResourceType to be of type string, got %T instead", value) - } - sv.ResourceType = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ComplianceStatus to be of type string, got %T instead", value) - } - sv.Status = types.ComplianceStatus(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceComplianceSummaryItemList(v *[]types.ResourceComplianceSummaryItem, 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.ResourceComplianceSummaryItem - if *v == nil { - cv = []types.ResourceComplianceSummaryItem{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ResourceComplianceSummaryItem - destAddr := &col - if err := awsAwsjson11_deserializeDocumentResourceComplianceSummaryItem(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncAlreadyExistsException(v **types.ResourceDataSyncAlreadyExistsException, 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.ResourceDataSyncAlreadyExistsException - if *v == nil { - sv = &types.ResourceDataSyncAlreadyExistsException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "SyncName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncName to be of type string, got %T instead", value) - } - sv.SyncName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncAwsOrganizationsSource(v **types.ResourceDataSyncAwsOrganizationsSource, 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.ResourceDataSyncAwsOrganizationsSource - if *v == nil { - sv = &types.ResourceDataSyncAwsOrganizationsSource{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "OrganizationalUnits": - if err := awsAwsjson11_deserializeDocumentResourceDataSyncOrganizationalUnitList(&sv.OrganizationalUnits, value); err != nil { - return err - } - - case "OrganizationSourceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncOrganizationSourceType to be of type string, got %T instead", value) - } - sv.OrganizationSourceType = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncConflictException(v **types.ResourceDataSyncConflictException, 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.ResourceDataSyncConflictException - if *v == nil { - sv = &types.ResourceDataSyncConflictException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncCountExceededException(v **types.ResourceDataSyncCountExceededException, 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.ResourceDataSyncCountExceededException - if *v == nil { - sv = &types.ResourceDataSyncCountExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncDestinationDataSharing(v **types.ResourceDataSyncDestinationDataSharing, 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.ResourceDataSyncDestinationDataSharing - if *v == nil { - sv = &types.ResourceDataSyncDestinationDataSharing{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DestinationDataSharingType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncDestinationDataSharingType to be of type string, got %T instead", value) - } - sv.DestinationDataSharingType = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncInvalidConfigurationException(v **types.ResourceDataSyncInvalidConfigurationException, 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.ResourceDataSyncInvalidConfigurationException - if *v == nil { - sv = &types.ResourceDataSyncInvalidConfigurationException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncItem(v **types.ResourceDataSyncItem, 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.ResourceDataSyncItem - if *v == nil { - sv = &types.ResourceDataSyncItem{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "LastStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected LastResourceDataSyncStatus to be of type string, got %T instead", value) - } - sv.LastStatus = types.LastResourceDataSyncStatus(jtv) - } - - case "LastSuccessfulSyncTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastSuccessfulSyncTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected LastSuccessfulResourceDataSyncTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastSyncStatusMessage": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected LastResourceDataSyncMessage to be of type string, got %T instead", value) - } - sv.LastSyncStatusMessage = ptr.String(jtv) - } - - case "LastSyncTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastSyncTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected LastResourceDataSyncTime to be a JSON Number, got %T instead", value) - - } - } - - case "S3Destination": - if err := awsAwsjson11_deserializeDocumentResourceDataSyncS3Destination(&sv.S3Destination, value); err != nil { - return err - } - - case "SyncCreatedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.SyncCreatedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected ResourceDataSyncCreatedTime to be a JSON Number, got %T instead", value) - - } - } - - case "SyncLastModifiedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.SyncLastModifiedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected ResourceDataSyncLastModifiedTime to be a JSON Number, got %T instead", value) - - } - } - - case "SyncName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncName to be of type string, got %T instead", value) - } - sv.SyncName = ptr.String(jtv) - } - - case "SyncSource": - if err := awsAwsjson11_deserializeDocumentResourceDataSyncSourceWithState(&sv.SyncSource, value); err != nil { - return err - } - - case "SyncType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncType to be of type string, got %T instead", value) - } - sv.SyncType = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncItemList(v *[]types.ResourceDataSyncItem, 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.ResourceDataSyncItem - if *v == nil { - cv = []types.ResourceDataSyncItem{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ResourceDataSyncItem - destAddr := &col - if err := awsAwsjson11_deserializeDocumentResourceDataSyncItem(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncNotFoundException(v **types.ResourceDataSyncNotFoundException, 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.ResourceDataSyncNotFoundException - if *v == nil { - sv = &types.ResourceDataSyncNotFoundException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "SyncName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncName to be of type string, got %T instead", value) - } - sv.SyncName = ptr.String(jtv) - } - - case "SyncType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncType to be of type string, got %T instead", value) - } - sv.SyncType = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncOrganizationalUnit(v **types.ResourceDataSyncOrganizationalUnit, 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.ResourceDataSyncOrganizationalUnit - if *v == nil { - sv = &types.ResourceDataSyncOrganizationalUnit{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "OrganizationalUnitId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncOrganizationalUnitId to be of type string, got %T instead", value) - } - sv.OrganizationalUnitId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncOrganizationalUnitList(v *[]types.ResourceDataSyncOrganizationalUnit, 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.ResourceDataSyncOrganizationalUnit - if *v == nil { - cv = []types.ResourceDataSyncOrganizationalUnit{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ResourceDataSyncOrganizationalUnit - destAddr := &col - if err := awsAwsjson11_deserializeDocumentResourceDataSyncOrganizationalUnit(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncS3Destination(v **types.ResourceDataSyncS3Destination, 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.ResourceDataSyncS3Destination - if *v == nil { - sv = &types.ResourceDataSyncS3Destination{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AWSKMSKeyARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncAWSKMSKeyARN to be of type string, got %T instead", value) - } - sv.AWSKMSKeyARN = ptr.String(jtv) - } - - case "BucketName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncS3BucketName to be of type string, got %T instead", value) - } - sv.BucketName = ptr.String(jtv) - } - - case "DestinationDataSharing": - if err := awsAwsjson11_deserializeDocumentResourceDataSyncDestinationDataSharing(&sv.DestinationDataSharing, value); err != nil { - return err - } - - case "Prefix": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncS3Prefix to be of type string, got %T instead", value) - } - sv.Prefix = ptr.String(jtv) - } - - case "Region": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncS3Region to be of type string, got %T instead", value) - } - sv.Region = ptr.String(jtv) - } - - case "SyncFormat": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncS3Format to be of type string, got %T instead", value) - } - sv.SyncFormat = types.ResourceDataSyncS3Format(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncSourceRegionList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncSourceRegion to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceDataSyncSourceWithState(v **types.ResourceDataSyncSourceWithState, 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.ResourceDataSyncSourceWithState - if *v == nil { - sv = &types.ResourceDataSyncSourceWithState{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AwsOrganizationsSource": - if err := awsAwsjson11_deserializeDocumentResourceDataSyncAwsOrganizationsSource(&sv.AwsOrganizationsSource, value); err != nil { - return err - } - - case "EnableAllOpsDataSources": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected ResourceDataSyncEnableAllOpsDataSources to be of type *bool, got %T instead", value) - } - sv.EnableAllOpsDataSources = jtv - } - - case "IncludeFutureRegions": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected ResourceDataSyncIncludeFutureRegions to be of type *bool, got %T instead", value) - } - sv.IncludeFutureRegions = jtv - } - - case "SourceRegions": - if err := awsAwsjson11_deserializeDocumentResourceDataSyncSourceRegionList(&sv.SourceRegions, value); err != nil { - return err - } - - case "SourceType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncSourceType to be of type string, got %T instead", value) - } - sv.SourceType = ptr.String(jtv) - } - - case "State": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ResourceDataSyncState to be of type string, got %T instead", value) - } - sv.State = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceInUseException(v **types.ResourceInUseException, 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.ResourceInUseException - if *v == nil { - sv = &types.ResourceInUseException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourceLimitExceededException(v **types.ResourceLimitExceededException, 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.ResourceLimitExceededException - if *v == nil { - sv = &types.ResourceLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourcePolicyConflictException(v **types.ResourcePolicyConflictException, 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.ResourcePolicyConflictException - if *v == nil { - sv = &types.ResourcePolicyConflictException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourcePolicyInvalidParameterException(v **types.ResourcePolicyInvalidParameterException, 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.ResourcePolicyInvalidParameterException - if *v == nil { - sv = &types.ResourcePolicyInvalidParameterException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "ParameterNames": - if err := awsAwsjson11_deserializeDocumentResourcePolicyParameterNamesList(&sv.ParameterNames, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourcePolicyLimitExceededException(v **types.ResourcePolicyLimitExceededException, 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.ResourcePolicyLimitExceededException - if *v == nil { - sv = &types.ResourcePolicyLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Limit": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Limit = int32(i64) - } - - case "LimitType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.LimitType = ptr.String(jtv) - } - - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentResourcePolicyParameterNamesList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentReviewInformation(v **types.ReviewInformation, 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.ReviewInformation - if *v == nil { - sv = &types.ReviewInformation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ReviewedTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ReviewedTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Reviewer": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Reviewer to be of type string, got %T instead", value) - } - sv.Reviewer = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ReviewStatus to be of type string, got %T instead", value) - } - sv.Status = types.ReviewStatus(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentReviewInformationList(v *[]types.ReviewInformation, 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.ReviewInformation - if *v == nil { - cv = []types.ReviewInformation{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ReviewInformation - destAddr := &col - if err := awsAwsjson11_deserializeDocumentReviewInformation(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentRunbook(v **types.Runbook, 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.Runbook - if *v == nil { - sv = &types.Runbook{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DocumentName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentARN to be of type string, got %T instead", value) - } - sv.DocumentName = ptr.String(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "MaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.MaxConcurrency = ptr.String(jtv) - } - - case "MaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.MaxErrors = ptr.String(jtv) - } - - case "Parameters": - if err := awsAwsjson11_deserializeDocumentAutomationParameterMap(&sv.Parameters, value); err != nil { - return err - } - - case "TargetLocations": - if err := awsAwsjson11_deserializeDocumentTargetLocations(&sv.TargetLocations, value); err != nil { - return err - } - - case "TargetMaps": - if err := awsAwsjson11_deserializeDocumentTargetMaps(&sv.TargetMaps, value); err != nil { - return err - } - - case "TargetParameterName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationParameterKey to be of type string, got %T instead", value) - } - sv.TargetParameterName = ptr.String(jtv) - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentRunbooks(v *[]types.Runbook, 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.Runbook - if *v == nil { - cv = []types.Runbook{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.Runbook - destAddr := &col - if err := awsAwsjson11_deserializeDocumentRunbook(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentS3OutputLocation(v **types.S3OutputLocation, 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.S3OutputLocation - if *v == nil { - sv = &types.S3OutputLocation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "OutputS3BucketName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3BucketName to be of type string, got %T instead", value) - } - sv.OutputS3BucketName = ptr.String(jtv) - } - - case "OutputS3KeyPrefix": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3KeyPrefix to be of type string, got %T instead", value) - } - sv.OutputS3KeyPrefix = ptr.String(jtv) - } - - case "OutputS3Region": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected S3Region to be of type string, got %T instead", value) - } - sv.OutputS3Region = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentS3OutputUrl(v **types.S3OutputUrl, 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.S3OutputUrl - if *v == nil { - sv = &types.S3OutputUrl{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "OutputUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Url to be of type string, got %T instead", value) - } - sv.OutputUrl = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentScheduledWindowExecution(v **types.ScheduledWindowExecution, 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.ScheduledWindowExecution - if *v == nil { - sv = &types.ScheduledWindowExecution{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ExecutionTime": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowStringDateTime to be of type string, got %T instead", value) - } - sv.ExecutionTime = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentScheduledWindowExecutionList(v *[]types.ScheduledWindowExecution, 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.ScheduledWindowExecution - if *v == nil { - cv = []types.ScheduledWindowExecution{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.ScheduledWindowExecution - destAddr := &col - if err := awsAwsjson11_deserializeDocumentScheduledWindowExecution(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentServiceSetting(v **types.ServiceSetting, 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.ServiceSetting - if *v == nil { - sv = &types.ServiceSetting{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ARN": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.ARN = ptr.String(jtv) - } - - case "LastModifiedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.LastModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "LastModifiedUser": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.LastModifiedUser = ptr.String(jtv) - } - - case "SettingId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ServiceSettingId to be of type string, got %T instead", value) - } - sv.SettingId = ptr.String(jtv) - } - - case "SettingValue": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ServiceSettingValue to be of type string, got %T instead", value) - } - sv.SettingValue = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Status = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentServiceSettingNotFound(v **types.ServiceSettingNotFound, 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.ServiceSettingNotFound - if *v == nil { - sv = &types.ServiceSettingNotFound{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentSession(v **types.Session, 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.Session - if *v == nil { - sv = &types.Session{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Details": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionDetails to be of type string, got %T instead", value) - } - sv.Details = ptr.String(jtv) - } - - case "DocumentName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentName to be of type string, got %T instead", value) - } - sv.DocumentName = ptr.String(jtv) - } - - case "EndDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.EndDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "MaxSessionDuration": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxSessionDuration to be of type string, got %T instead", value) - } - sv.MaxSessionDuration = ptr.String(jtv) - } - - case "OutputUrl": - if err := awsAwsjson11_deserializeDocumentSessionManagerOutputUrl(&sv.OutputUrl, value); err != nil { - return err - } - - case "Owner": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionOwner to be of type string, got %T instead", value) - } - sv.Owner = ptr.String(jtv) - } - - case "Reason": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionReason to be of type string, got %T instead", value) - } - sv.Reason = ptr.String(jtv) - } - - case "SessionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionId to be of type string, got %T instead", value) - } - sv.SessionId = ptr.String(jtv) - } - - case "StartDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.StartDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionStatus to be of type string, got %T instead", value) - } - sv.Status = types.SessionStatus(jtv) - } - - case "Target": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionTarget to be of type string, got %T instead", value) - } - sv.Target = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentSessionList(v *[]types.Session, 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.Session - if *v == nil { - cv = []types.Session{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.Session - destAddr := &col - if err := awsAwsjson11_deserializeDocumentSession(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentSessionManagerOutputUrl(v **types.SessionManagerOutputUrl, 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.SessionManagerOutputUrl - if *v == nil { - sv = &types.SessionManagerOutputUrl{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CloudWatchOutputUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionManagerCloudWatchOutputUrl to be of type string, got %T instead", value) - } - sv.CloudWatchOutputUrl = ptr.String(jtv) - } - - case "S3OutputUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionManagerS3OutputUrl to be of type string, got %T instead", value) - } - sv.S3OutputUrl = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentSeveritySummary(v **types.SeveritySummary, 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.SeveritySummary - if *v == nil { - sv = &types.SeveritySummary{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CriticalCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ComplianceSummaryCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.CriticalCount = int32(i64) - } - - case "HighCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ComplianceSummaryCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.HighCount = int32(i64) - } - - case "InformationalCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ComplianceSummaryCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InformationalCount = int32(i64) - } - - case "LowCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ComplianceSummaryCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.LowCount = int32(i64) - } - - case "MediumCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ComplianceSummaryCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.MediumCount = int32(i64) - } - - case "UnspecifiedCount": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ComplianceSummaryCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.UnspecifiedCount = int32(i64) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentStatusUnchanged(v **types.StatusUnchanged, 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.StatusUnchanged - if *v == nil { - sv = &types.StatusUnchanged{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentStepExecution(v **types.StepExecution, 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.StepExecution - if *v == nil { - sv = &types.StepExecution{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Action": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationActionName to be of type string, got %T instead", value) - } - sv.Action = ptr.String(jtv) - } - - case "ExecutionEndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ExecutionEndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ExecutionStartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ExecutionStartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "FailureDetails": - if err := awsAwsjson11_deserializeDocumentFailureDetails(&sv.FailureDetails, value); err != nil { - return err - } - - case "FailureMessage": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.FailureMessage = ptr.String(jtv) - } - - case "Inputs": - if err := awsAwsjson11_deserializeDocumentNormalStringMap(&sv.Inputs, value); err != nil { - return err - } - - case "IsCritical": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected Boolean to be of type *bool, got %T instead", value) - } - sv.IsCritical = ptr.Bool(jtv) - } - - case "IsEnd": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected Boolean to be of type *bool, got %T instead", value) - } - sv.IsEnd = ptr.Bool(jtv) - } - - case "MaxAttempts": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.MaxAttempts = ptr.Int32(int32(i64)) - } - - case "NextStep": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.NextStep = ptr.String(jtv) - } - - case "OnFailure": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.OnFailure = ptr.String(jtv) - } - - case "Outputs": - if err := awsAwsjson11_deserializeDocumentAutomationParameterMap(&sv.Outputs, value); err != nil { - return err - } - - case "OverriddenParameters": - if err := awsAwsjson11_deserializeDocumentAutomationParameterMap(&sv.OverriddenParameters, value); err != nil { - return err - } - - case "ParentStepDetails": - if err := awsAwsjson11_deserializeDocumentParentStepDetails(&sv.ParentStepDetails, value); err != nil { - return err - } - - case "Response": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Response = ptr.String(jtv) - } - - case "ResponseCode": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.ResponseCode = ptr.String(jtv) - } - - case "StepExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.StepExecutionId = ptr.String(jtv) - } - - case "StepName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.StepName = ptr.String(jtv) - } - - case "StepStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationExecutionStatus to be of type string, got %T instead", value) - } - sv.StepStatus = types.AutomationExecutionStatus(jtv) - } - - case "TargetLocation": - if err := awsAwsjson11_deserializeDocumentTargetLocation(&sv.TargetLocation, value); err != nil { - return err - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - case "TimeoutSeconds": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Long to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.TimeoutSeconds = ptr.Int64(i64) - } - - case "TriggeredAlarms": - if err := awsAwsjson11_deserializeDocumentAlarmStateInformationList(&sv.TriggeredAlarms, value); err != nil { - return err - } - - case "ValidNextSteps": - if err := awsAwsjson11_deserializeDocumentValidNextStepList(&sv.ValidNextSteps, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentStepExecutionList(v *[]types.StepExecution, 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.StepExecution - if *v == nil { - cv = []types.StepExecution{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.StepExecution - destAddr := &col - if err := awsAwsjson11_deserializeDocumentStepExecution(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentSubTypeCountLimitExceededException(v **types.SubTypeCountLimitExceededException, 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.SubTypeCountLimitExceededException - if *v == nil { - sv = &types.SubTypeCountLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentTag(v **types.Tag, 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.Tag - if *v == nil { - sv = &types.Tag{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Key": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TagKey to be of type string, got %T instead", value) - } - sv.Key = ptr.String(jtv) - } - - case "Value": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TagValue to be of type string, got %T instead", value) - } - sv.Value = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentTagList(v *[]types.Tag, 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.Tag - if *v == nil { - 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_deserializeDocumentTarget(v **types.Target, 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.Target - if *v == nil { - sv = &types.Target{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Key": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TargetKey to be of type string, got %T instead", value) - } - sv.Key = ptr.String(jtv) - } - - case "Values": - if err := awsAwsjson11_deserializeDocumentTargetValues(&sv.Values, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentTargetInUseException(v **types.TargetInUseException, 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.TargetInUseException - if *v == nil { - sv = &types.TargetInUseException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentTargetLocation(v **types.TargetLocation, 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.TargetLocation - if *v == nil { - sv = &types.TargetLocation{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Accounts": - if err := awsAwsjson11_deserializeDocumentAccounts(&sv.Accounts, value); err != nil { - return err - } - - case "ExecutionRoleName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ExecutionRoleName to be of type string, got %T instead", value) - } - sv.ExecutionRoleName = ptr.String(jtv) - } - - case "Regions": - if err := awsAwsjson11_deserializeDocumentRegions(&sv.Regions, value); err != nil { - return err - } - - case "TargetLocationAlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.TargetLocationAlarmConfiguration, value); err != nil { - return err - } - - case "TargetLocationMaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.TargetLocationMaxConcurrency = ptr.String(jtv) - } - - case "TargetLocationMaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.TargetLocationMaxErrors = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentTargetLocations(v *[]types.TargetLocation, 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.TargetLocation - if *v == nil { - cv = []types.TargetLocation{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.TargetLocation - destAddr := &col - if err := awsAwsjson11_deserializeDocumentTargetLocation(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentTargetMap(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 - mapVar := parsedVal - if err := awsAwsjson11_deserializeDocumentTargetMapValueList(&mapVar, value); err != nil { - return err - } - parsedVal = mapVar - mv[key] = parsedVal - - } - *v = mv - return nil -} - -func awsAwsjson11_deserializeDocumentTargetMaps(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.([]interface{}) - if !ok { - return fmt.Errorf("unexpected JSON type %v", value) - } - - var cv []map[string][]string - if *v == nil { - cv = []map[string][]string{} - } else { - cv = *v - } - - for _, value := range shape { - var col map[string][]string - if err := awsAwsjson11_deserializeDocumentTargetMap(&col, value); err != nil { - return err - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentTargetMapValueList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TargetMapValue to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentTargetNotConnected(v **types.TargetNotConnected, 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.TargetNotConnected - if *v == nil { - sv = &types.TargetNotConnected{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentTargetParameterList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterValue to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentTargets(v *[]types.Target, 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.Target - if *v == nil { - cv = []types.Target{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.Target - destAddr := &col - if err := awsAwsjson11_deserializeDocumentTarget(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentTargetValues(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TargetValue to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeDocumentTooManyTagsError(v **types.TooManyTagsError, 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.TooManyTagsError - if *v == nil { - sv = &types.TooManyTagsError{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentTooManyUpdates(v **types.TooManyUpdates, 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.TooManyUpdates - if *v == nil { - sv = &types.TooManyUpdates{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentTotalSizeLimitExceededException(v **types.TotalSizeLimitExceededException, 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.TotalSizeLimitExceededException - if *v == nil { - sv = &types.TotalSizeLimitExceededException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentUnsupportedCalendarException(v **types.UnsupportedCalendarException, 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.UnsupportedCalendarException - if *v == nil { - sv = &types.UnsupportedCalendarException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentUnsupportedFeatureRequiredException(v **types.UnsupportedFeatureRequiredException, 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.UnsupportedFeatureRequiredException - if *v == nil { - sv = &types.UnsupportedFeatureRequiredException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentUnsupportedInventoryItemContextException(v **types.UnsupportedInventoryItemContextException, 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.UnsupportedInventoryItemContextException - if *v == nil { - sv = &types.UnsupportedInventoryItemContextException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - case "TypeName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemTypeName to be of type string, got %T instead", value) - } - sv.TypeName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentUnsupportedInventorySchemaVersionException(v **types.UnsupportedInventorySchemaVersionException, 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.UnsupportedInventorySchemaVersionException - if *v == nil { - sv = &types.UnsupportedInventorySchemaVersionException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentUnsupportedOperatingSystem(v **types.UnsupportedOperatingSystem, 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.UnsupportedOperatingSystem - if *v == nil { - sv = &types.UnsupportedOperatingSystem{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentUnsupportedParameterType(v **types.UnsupportedParameterType, 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.UnsupportedParameterType - if *v == nil { - sv = &types.UnsupportedParameterType{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentUnsupportedPlatformType(v **types.UnsupportedPlatformType, 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.UnsupportedPlatformType - if *v == nil { - sv = &types.UnsupportedPlatformType{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeDocumentValidNextStepList(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ValidNextStep to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsAwsjson11_deserializeOpDocumentAddTagsToResourceOutput(v **AddTagsToResourceOutput, 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 *AddTagsToResourceOutput - if *v == nil { - sv = &AddTagsToResourceOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentAssociateOpsItemRelatedItemOutput(v **AssociateOpsItemRelatedItemOutput, 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 *AssociateOpsItemRelatedItemOutput - if *v == nil { - sv = &AssociateOpsItemRelatedItemOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemRelatedItemAssociationId to be of type string, got %T instead", value) - } - sv.AssociationId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCancelCommandOutput(v **CancelCommandOutput, 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 *CancelCommandOutput - if *v == nil { - sv = &CancelCommandOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCancelMaintenanceWindowExecutionOutput(v **CancelMaintenanceWindowExecutionOutput, 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 *CancelMaintenanceWindowExecutionOutput - if *v == nil { - sv = &CancelMaintenanceWindowExecutionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "WindowExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionId to be of type string, got %T instead", value) - } - sv.WindowExecutionId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCreateActivationOutput(v **CreateActivationOutput, 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 *CreateActivationOutput - if *v == nil { - sv = &CreateActivationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ActivationCode": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ActivationCode to be of type string, got %T instead", value) - } - sv.ActivationCode = ptr.String(jtv) - } - - case "ActivationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ActivationId to be of type string, got %T instead", value) - } - sv.ActivationId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCreateAssociationBatchOutput(v **CreateAssociationBatchOutput, 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 *CreateAssociationBatchOutput - if *v == nil { - sv = &CreateAssociationBatchOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Failed": - if err := awsAwsjson11_deserializeDocumentFailedCreateAssociationList(&sv.Failed, value); err != nil { - return err - } - - case "Successful": - if err := awsAwsjson11_deserializeDocumentAssociationDescriptionList(&sv.Successful, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCreateAssociationOutput(v **CreateAssociationOutput, 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 *CreateAssociationOutput - if *v == nil { - sv = &CreateAssociationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationDescription": - if err := awsAwsjson11_deserializeDocumentAssociationDescription(&sv.AssociationDescription, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCreateDocumentOutput(v **CreateDocumentOutput, 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 *CreateDocumentOutput - if *v == nil { - sv = &CreateDocumentOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DocumentDescription": - if err := awsAwsjson11_deserializeDocumentDocumentDescription(&sv.DocumentDescription, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCreateMaintenanceWindowOutput(v **CreateMaintenanceWindowOutput, 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 *CreateMaintenanceWindowOutput - if *v == nil { - sv = &CreateMaintenanceWindowOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCreateOpsItemOutput(v **CreateOpsItemOutput, 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 *CreateOpsItemOutput - if *v == nil { - sv = &CreateOpsItemOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "OpsItemArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsItemArn to be of type string, got %T instead", value) - } - sv.OpsItemArn = ptr.String(jtv) - } - - case "OpsItemId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected String to be of type string, got %T instead", value) - } - sv.OpsItemId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCreateOpsMetadataOutput(v **CreateOpsMetadataOutput, 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 *CreateOpsMetadataOutput - if *v == nil { - sv = &CreateOpsMetadataOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "OpsMetadataArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsMetadataArn to be of type string, got %T instead", value) - } - sv.OpsMetadataArn = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCreatePatchBaselineOutput(v **CreatePatchBaselineOutput, 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 *CreatePatchBaselineOutput - if *v == nil { - sv = &CreatePatchBaselineOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "BaselineId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineId to be of type string, got %T instead", value) - } - sv.BaselineId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentCreateResourceDataSyncOutput(v **CreateResourceDataSyncOutput, 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 *CreateResourceDataSyncOutput - if *v == nil { - sv = &CreateResourceDataSyncOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteActivationOutput(v **DeleteActivationOutput, 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 *DeleteActivationOutput - if *v == nil { - sv = &DeleteActivationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteAssociationOutput(v **DeleteAssociationOutput, 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 *DeleteAssociationOutput - if *v == nil { - sv = &DeleteAssociationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteDocumentOutput(v **DeleteDocumentOutput, 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 *DeleteDocumentOutput - if *v == nil { - sv = &DeleteDocumentOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteInventoryOutput(v **DeleteInventoryOutput, 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 *DeleteInventoryOutput - if *v == nil { - sv = &DeleteInventoryOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DeletionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected UUID to be of type string, got %T instead", value) - } - sv.DeletionId = ptr.String(jtv) - } - - case "DeletionSummary": - if err := awsAwsjson11_deserializeDocumentInventoryDeletionSummary(&sv.DeletionSummary, value); err != nil { - return err - } - - case "TypeName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemTypeName to be of type string, got %T instead", value) - } - sv.TypeName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteMaintenanceWindowOutput(v **DeleteMaintenanceWindowOutput, 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 *DeleteMaintenanceWindowOutput - if *v == nil { - sv = &DeleteMaintenanceWindowOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteOpsItemOutput(v **DeleteOpsItemOutput, 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 *DeleteOpsItemOutput - if *v == nil { - sv = &DeleteOpsItemOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteOpsMetadataOutput(v **DeleteOpsMetadataOutput, 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 *DeleteOpsMetadataOutput - if *v == nil { - sv = &DeleteOpsMetadataOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteParameterOutput(v **DeleteParameterOutput, 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 *DeleteParameterOutput - if *v == nil { - sv = &DeleteParameterOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteParametersOutput(v **DeleteParametersOutput, 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 *DeleteParametersOutput - if *v == nil { - sv = &DeleteParametersOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DeletedParameters": - if err := awsAwsjson11_deserializeDocumentParameterNameList(&sv.DeletedParameters, value); err != nil { - return err - } - - case "InvalidParameters": - if err := awsAwsjson11_deserializeDocumentParameterNameList(&sv.InvalidParameters, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeletePatchBaselineOutput(v **DeletePatchBaselineOutput, 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 *DeletePatchBaselineOutput - if *v == nil { - sv = &DeletePatchBaselineOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "BaselineId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineId to be of type string, got %T instead", value) - } - sv.BaselineId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteResourceDataSyncOutput(v **DeleteResourceDataSyncOutput, 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 *DeleteResourceDataSyncOutput - if *v == nil { - sv = &DeleteResourceDataSyncOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeleteResourcePolicyOutput(v **DeleteResourcePolicyOutput, 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 *DeleteResourcePolicyOutput - if *v == nil { - sv = &DeleteResourcePolicyOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeregisterManagedInstanceOutput(v **DeregisterManagedInstanceOutput, 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 *DeregisterManagedInstanceOutput - if *v == nil { - sv = &DeregisterManagedInstanceOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeregisterPatchBaselineForPatchGroupOutput(v **DeregisterPatchBaselineForPatchGroupOutput, 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 *DeregisterPatchBaselineForPatchGroupOutput - if *v == nil { - sv = &DeregisterPatchBaselineForPatchGroupOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "BaselineId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineId to be of type string, got %T instead", value) - } - sv.BaselineId = ptr.String(jtv) - } - - case "PatchGroup": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchGroup to be of type string, got %T instead", value) - } - sv.PatchGroup = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeregisterTargetFromMaintenanceWindowOutput(v **DeregisterTargetFromMaintenanceWindowOutput, 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 *DeregisterTargetFromMaintenanceWindowOutput - if *v == nil { - sv = &DeregisterTargetFromMaintenanceWindowOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - case "WindowTargetId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTargetId to be of type string, got %T instead", value) - } - sv.WindowTargetId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDeregisterTaskFromMaintenanceWindowOutput(v **DeregisterTaskFromMaintenanceWindowOutput, 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 *DeregisterTaskFromMaintenanceWindowOutput - if *v == nil { - sv = &DeregisterTaskFromMaintenanceWindowOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - case "WindowTaskId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskId to be of type string, got %T instead", value) - } - sv.WindowTaskId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeActivationsOutput(v **DescribeActivationsOutput, 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 *DescribeActivationsOutput - if *v == nil { - sv = &DescribeActivationsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ActivationList": - if err := awsAwsjson11_deserializeDocumentActivationList(&sv.ActivationList, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeAssociationExecutionsOutput(v **DescribeAssociationExecutionsOutput, 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 *DescribeAssociationExecutionsOutput - if *v == nil { - sv = &DescribeAssociationExecutionsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationExecutions": - if err := awsAwsjson11_deserializeDocumentAssociationExecutionsList(&sv.AssociationExecutions, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeAssociationExecutionTargetsOutput(v **DescribeAssociationExecutionTargetsOutput, 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 *DescribeAssociationExecutionTargetsOutput - if *v == nil { - sv = &DescribeAssociationExecutionTargetsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationExecutionTargets": - if err := awsAwsjson11_deserializeDocumentAssociationExecutionTargetsList(&sv.AssociationExecutionTargets, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeAssociationOutput(v **DescribeAssociationOutput, 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 *DescribeAssociationOutput - if *v == nil { - sv = &DescribeAssociationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationDescription": - if err := awsAwsjson11_deserializeDocumentAssociationDescription(&sv.AssociationDescription, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeAutomationExecutionsOutput(v **DescribeAutomationExecutionsOutput, 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 *DescribeAutomationExecutionsOutput - if *v == nil { - sv = &DescribeAutomationExecutionsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AutomationExecutionMetadataList": - if err := awsAwsjson11_deserializeDocumentAutomationExecutionMetadataList(&sv.AutomationExecutionMetadataList, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeAutomationStepExecutionsOutput(v **DescribeAutomationStepExecutionsOutput, 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 *DescribeAutomationStepExecutionsOutput - if *v == nil { - sv = &DescribeAutomationStepExecutionsOutput{} - } 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 "StepExecutions": - if err := awsAwsjson11_deserializeDocumentStepExecutionList(&sv.StepExecutions, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeAvailablePatchesOutput(v **DescribeAvailablePatchesOutput, 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 *DescribeAvailablePatchesOutput - if *v == nil { - sv = &DescribeAvailablePatchesOutput{} - } 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 "Patches": - if err := awsAwsjson11_deserializeDocumentPatchList(&sv.Patches, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeDocumentOutput(v **DescribeDocumentOutput, 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 *DescribeDocumentOutput - if *v == nil { - sv = &DescribeDocumentOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Document": - if err := awsAwsjson11_deserializeDocumentDocumentDescription(&sv.Document, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeDocumentPermissionOutput(v **DescribeDocumentPermissionOutput, 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 *DescribeDocumentPermissionOutput - if *v == nil { - sv = &DescribeDocumentPermissionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AccountIds": - if err := awsAwsjson11_deserializeDocumentAccountIdList(&sv.AccountIds, value); err != nil { - return err - } - - case "AccountSharingInfoList": - if err := awsAwsjson11_deserializeDocumentAccountSharingInfoList(&sv.AccountSharingInfoList, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeEffectiveInstanceAssociationsOutput(v **DescribeEffectiveInstanceAssociationsOutput, 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 *DescribeEffectiveInstanceAssociationsOutput - if *v == nil { - sv = &DescribeEffectiveInstanceAssociationsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Associations": - if err := awsAwsjson11_deserializeDocumentInstanceAssociationList(&sv.Associations, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeEffectivePatchesForPatchBaselineOutput(v **DescribeEffectivePatchesForPatchBaselineOutput, 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 *DescribeEffectivePatchesForPatchBaselineOutput - if *v == nil { - sv = &DescribeEffectivePatchesForPatchBaselineOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "EffectivePatches": - if err := awsAwsjson11_deserializeDocumentEffectivePatchList(&sv.EffectivePatches, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeInstanceAssociationsStatusOutput(v **DescribeInstanceAssociationsStatusOutput, 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 *DescribeInstanceAssociationsStatusOutput - if *v == nil { - sv = &DescribeInstanceAssociationsStatusOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "InstanceAssociationStatusInfos": - if err := awsAwsjson11_deserializeDocumentInstanceAssociationStatusInfos(&sv.InstanceAssociationStatusInfos, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeInstanceInformationOutput(v **DescribeInstanceInformationOutput, 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 *DescribeInstanceInformationOutput - if *v == nil { - sv = &DescribeInstanceInformationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "InstanceInformationList": - if err := awsAwsjson11_deserializeDocumentInstanceInformationList(&sv.InstanceInformationList, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeInstancePatchesOutput(v **DescribeInstancePatchesOutput, 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 *DescribeInstancePatchesOutput - if *v == nil { - sv = &DescribeInstancePatchesOutput{} - } 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 "Patches": - if err := awsAwsjson11_deserializeDocumentPatchComplianceDataList(&sv.Patches, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeInstancePatchStatesForPatchGroupOutput(v **DescribeInstancePatchStatesForPatchGroupOutput, 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 *DescribeInstancePatchStatesForPatchGroupOutput - if *v == nil { - sv = &DescribeInstancePatchStatesForPatchGroupOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "InstancePatchStates": - if err := awsAwsjson11_deserializeDocumentInstancePatchStatesList(&sv.InstancePatchStates, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeInstancePatchStatesOutput(v **DescribeInstancePatchStatesOutput, 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 *DescribeInstancePatchStatesOutput - if *v == nil { - sv = &DescribeInstancePatchStatesOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "InstancePatchStates": - if err := awsAwsjson11_deserializeDocumentInstancePatchStateList(&sv.InstancePatchStates, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeInventoryDeletionsOutput(v **DescribeInventoryDeletionsOutput, 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 *DescribeInventoryDeletionsOutput - if *v == nil { - sv = &DescribeInventoryDeletionsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "InventoryDeletions": - if err := awsAwsjson11_deserializeDocumentInventoryDeletionsList(&sv.InventoryDeletions, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeMaintenanceWindowExecutionsOutput(v **DescribeMaintenanceWindowExecutionsOutput, 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 *DescribeMaintenanceWindowExecutionsOutput - if *v == nil { - sv = &DescribeMaintenanceWindowExecutionsOutput{} - } 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 "WindowExecutions": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionList(&sv.WindowExecutions, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeMaintenanceWindowExecutionTaskInvocationsOutput(v **DescribeMaintenanceWindowExecutionTaskInvocationsOutput, 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 *DescribeMaintenanceWindowExecutionTaskInvocationsOutput - if *v == nil { - sv = &DescribeMaintenanceWindowExecutionTaskInvocationsOutput{} - } 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 "WindowExecutionTaskInvocationIdentities": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionTaskInvocationIdentityList(&sv.WindowExecutionTaskInvocationIdentities, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeMaintenanceWindowExecutionTasksOutput(v **DescribeMaintenanceWindowExecutionTasksOutput, 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 *DescribeMaintenanceWindowExecutionTasksOutput - if *v == nil { - sv = &DescribeMaintenanceWindowExecutionTasksOutput{} - } 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 "WindowExecutionTaskIdentities": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionTaskIdentityList(&sv.WindowExecutionTaskIdentities, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeMaintenanceWindowScheduleOutput(v **DescribeMaintenanceWindowScheduleOutput, 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 *DescribeMaintenanceWindowScheduleOutput - if *v == nil { - sv = &DescribeMaintenanceWindowScheduleOutput{} - } 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 "ScheduledWindowExecutions": - if err := awsAwsjson11_deserializeDocumentScheduledWindowExecutionList(&sv.ScheduledWindowExecutions, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeMaintenanceWindowsForTargetOutput(v **DescribeMaintenanceWindowsForTargetOutput, 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 *DescribeMaintenanceWindowsForTargetOutput - if *v == nil { - sv = &DescribeMaintenanceWindowsForTargetOutput{} - } 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 "WindowIdentities": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowsForTargetList(&sv.WindowIdentities, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeMaintenanceWindowsOutput(v **DescribeMaintenanceWindowsOutput, 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 *DescribeMaintenanceWindowsOutput - if *v == nil { - sv = &DescribeMaintenanceWindowsOutput{} - } 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 "WindowIdentities": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowIdentityList(&sv.WindowIdentities, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeMaintenanceWindowTargetsOutput(v **DescribeMaintenanceWindowTargetsOutput, 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 *DescribeMaintenanceWindowTargetsOutput - if *v == nil { - sv = &DescribeMaintenanceWindowTargetsOutput{} - } 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 "Targets": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTargetList(&sv.Targets, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeMaintenanceWindowTasksOutput(v **DescribeMaintenanceWindowTasksOutput, 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 *DescribeMaintenanceWindowTasksOutput - if *v == nil { - sv = &DescribeMaintenanceWindowTasksOutput{} - } 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 "Tasks": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTaskList(&sv.Tasks, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeOpsItemsOutput(v **DescribeOpsItemsOutput, 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 *DescribeOpsItemsOutput - if *v == nil { - sv = &DescribeOpsItemsOutput{} - } 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 String to be of type string, got %T instead", value) - } - sv.NextToken = ptr.String(jtv) - } - - case "OpsItemSummaries": - if err := awsAwsjson11_deserializeDocumentOpsItemSummaries(&sv.OpsItemSummaries, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeParametersOutput(v **DescribeParametersOutput, 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 *DescribeParametersOutput - if *v == nil { - sv = &DescribeParametersOutput{} - } 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 "Parameters": - if err := awsAwsjson11_deserializeDocumentParameterMetadataList(&sv.Parameters, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribePatchBaselinesOutput(v **DescribePatchBaselinesOutput, 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 *DescribePatchBaselinesOutput - if *v == nil { - sv = &DescribePatchBaselinesOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "BaselineIdentities": - if err := awsAwsjson11_deserializeDocumentPatchBaselineIdentityList(&sv.BaselineIdentities, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribePatchGroupsOutput(v **DescribePatchGroupsOutput, 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 *DescribePatchGroupsOutput - if *v == nil { - sv = &DescribePatchGroupsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Mappings": - if err := awsAwsjson11_deserializeDocumentPatchGroupPatchBaselineMappingList(&sv.Mappings, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribePatchGroupStateOutput(v **DescribePatchGroupStateOutput, 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 *DescribePatchGroupStateOutput - if *v == nil { - sv = &DescribePatchGroupStateOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Instances": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Instances = int32(i64) - } - - case "InstancesWithCriticalNonCompliantPatches": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected InstancesCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstancesWithCriticalNonCompliantPatches = ptr.Int32(int32(i64)) - } - - case "InstancesWithFailedPatches": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstancesWithFailedPatches = int32(i64) - } - - case "InstancesWithInstalledOtherPatches": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstancesWithInstalledOtherPatches = int32(i64) - } - - case "InstancesWithInstalledPatches": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstancesWithInstalledPatches = int32(i64) - } - - case "InstancesWithInstalledPendingRebootPatches": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected InstancesCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstancesWithInstalledPendingRebootPatches = ptr.Int32(int32(i64)) - } - - case "InstancesWithInstalledRejectedPatches": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected InstancesCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstancesWithInstalledRejectedPatches = ptr.Int32(int32(i64)) - } - - case "InstancesWithMissingPatches": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstancesWithMissingPatches = int32(i64) - } - - case "InstancesWithNotApplicablePatches": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstancesWithNotApplicablePatches = int32(i64) - } - - case "InstancesWithOtherNonCompliantPatches": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected InstancesCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstancesWithOtherNonCompliantPatches = ptr.Int32(int32(i64)) - } - - case "InstancesWithSecurityNonCompliantPatches": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected InstancesCount to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstancesWithSecurityNonCompliantPatches = ptr.Int32(int32(i64)) - } - - case "InstancesWithUnreportedNotApplicablePatches": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected Integer to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.InstancesWithUnreportedNotApplicablePatches = ptr.Int32(int32(i64)) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribePatchPropertiesOutput(v **DescribePatchPropertiesOutput, 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 *DescribePatchPropertiesOutput - if *v == nil { - sv = &DescribePatchPropertiesOutput{} - } 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 "Properties": - if err := awsAwsjson11_deserializeDocumentPatchPropertiesList(&sv.Properties, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDescribeSessionsOutput(v **DescribeSessionsOutput, 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 *DescribeSessionsOutput - if *v == nil { - sv = &DescribeSessionsOutput{} - } 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 "Sessions": - if err := awsAwsjson11_deserializeDocumentSessionList(&sv.Sessions, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentDisassociateOpsItemRelatedItemOutput(v **DisassociateOpsItemRelatedItemOutput, 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 *DisassociateOpsItemRelatedItemOutput - if *v == nil { - sv = &DisassociateOpsItemRelatedItemOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetAutomationExecutionOutput(v **GetAutomationExecutionOutput, 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 *GetAutomationExecutionOutput - if *v == nil { - sv = &GetAutomationExecutionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AutomationExecution": - if err := awsAwsjson11_deserializeDocumentAutomationExecution(&sv.AutomationExecution, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetCalendarStateOutput(v **GetCalendarStateOutput, 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 *GetCalendarStateOutput - if *v == nil { - sv = &GetCalendarStateOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AtTime": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ISO8601String to be of type string, got %T instead", value) - } - sv.AtTime = ptr.String(jtv) - } - - case "NextTransitionTime": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ISO8601String to be of type string, got %T instead", value) - } - sv.NextTransitionTime = ptr.String(jtv) - } - - case "State": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CalendarState to be of type string, got %T instead", value) - } - sv.State = types.CalendarState(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetCommandInvocationOutput(v **GetCommandInvocationOutput, 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 *GetCommandInvocationOutput - if *v == nil { - sv = &GetCommandInvocationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CloudWatchOutputConfig": - if err := awsAwsjson11_deserializeDocumentCloudWatchOutputConfig(&sv.CloudWatchOutputConfig, value); err != nil { - return err - } - - case "CommandId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CommandId to be of type string, got %T instead", value) - } - sv.CommandId = ptr.String(jtv) - } - - case "Comment": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Comment to be of type string, got %T instead", value) - } - sv.Comment = ptr.String(jtv) - } - - case "DocumentName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentName to be of type string, got %T instead", value) - } - sv.DocumentName = ptr.String(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "ExecutionElapsedTime": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StringDateTime to be of type string, got %T instead", value) - } - sv.ExecutionElapsedTime = ptr.String(jtv) - } - - case "ExecutionEndDateTime": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StringDateTime to be of type string, got %T instead", value) - } - sv.ExecutionEndDateTime = ptr.String(jtv) - } - - case "ExecutionStartDateTime": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StringDateTime to be of type string, got %T instead", value) - } - sv.ExecutionStartDateTime = ptr.String(jtv) - } - - case "InstanceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - sv.InstanceId = ptr.String(jtv) - } - - case "PluginName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CommandPluginName to be of type string, got %T instead", value) - } - sv.PluginName = ptr.String(jtv) - } - - case "ResponseCode": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ResponseCode to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ResponseCode = int32(i64) - } - - case "StandardErrorContent": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StandardErrorContent to be of type string, got %T instead", value) - } - sv.StandardErrorContent = ptr.String(jtv) - } - - case "StandardErrorUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Url to be of type string, got %T instead", value) - } - sv.StandardErrorUrl = ptr.String(jtv) - } - - case "StandardOutputContent": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StandardOutputContent to be of type string, got %T instead", value) - } - sv.StandardOutputContent = ptr.String(jtv) - } - - case "StandardOutputUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Url to be of type string, got %T instead", value) - } - sv.StandardOutputUrl = ptr.String(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected CommandInvocationStatus to be of type string, got %T instead", value) - } - sv.Status = types.CommandInvocationStatus(jtv) - } - - case "StatusDetails": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StatusDetails to be of type string, got %T instead", value) - } - sv.StatusDetails = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetConnectionStatusOutput(v **GetConnectionStatusOutput, 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 *GetConnectionStatusOutput - if *v == nil { - sv = &GetConnectionStatusOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ConnectionStatus to be of type string, got %T instead", value) - } - sv.Status = types.ConnectionStatus(jtv) - } - - case "Target": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionTarget to be of type string, got %T instead", value) - } - sv.Target = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetDefaultPatchBaselineOutput(v **GetDefaultPatchBaselineOutput, 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 *GetDefaultPatchBaselineOutput - if *v == nil { - sv = &GetDefaultPatchBaselineOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "BaselineId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineId to be of type string, got %T instead", value) - } - sv.BaselineId = ptr.String(jtv) - } - - case "OperatingSystem": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OperatingSystem to be of type string, got %T instead", value) - } - sv.OperatingSystem = types.OperatingSystem(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetDeployablePatchSnapshotForInstanceOutput(v **GetDeployablePatchSnapshotForInstanceOutput, 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 *GetDeployablePatchSnapshotForInstanceOutput - if *v == nil { - sv = &GetDeployablePatchSnapshotForInstanceOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "InstanceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - sv.InstanceId = ptr.String(jtv) - } - - case "Product": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Product to be of type string, got %T instead", value) - } - sv.Product = ptr.String(jtv) - } - - case "SnapshotDownloadUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SnapshotDownloadUrl to be of type string, got %T instead", value) - } - sv.SnapshotDownloadUrl = ptr.String(jtv) - } - - case "SnapshotId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SnapshotId to be of type string, got %T instead", value) - } - sv.SnapshotId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetDocumentOutput(v **GetDocumentOutput, 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 *GetDocumentOutput - if *v == nil { - sv = &GetDocumentOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AttachmentsContent": - if err := awsAwsjson11_deserializeDocumentAttachmentContentList(&sv.AttachmentsContent, value); err != nil { - return err - } - - case "Content": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentContent to be of type string, got %T instead", value) - } - sv.Content = ptr.String(jtv) - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "DisplayName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentDisplayName to be of type string, got %T instead", value) - } - sv.DisplayName = ptr.String(jtv) - } - - case "DocumentFormat": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentFormat to be of type string, got %T instead", value) - } - sv.DocumentFormat = types.DocumentFormat(jtv) - } - - case "DocumentType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentType to be of type string, got %T instead", value) - } - sv.DocumentType = types.DocumentType(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentARN to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Requires": - if err := awsAwsjson11_deserializeDocumentDocumentRequiresList(&sv.Requires, value); err != nil { - return err - } - - case "ReviewStatus": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ReviewStatus to be of type string, got %T instead", value) - } - sv.ReviewStatus = types.ReviewStatus(jtv) - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentStatus to be of type string, got %T instead", value) - } - sv.Status = types.DocumentStatus(jtv) - } - - case "StatusInformation": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentStatusInformation to be of type string, got %T instead", value) - } - sv.StatusInformation = ptr.String(jtv) - } - - case "VersionName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersionName to be of type string, got %T instead", value) - } - sv.VersionName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetInventoryOutput(v **GetInventoryOutput, 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 *GetInventoryOutput - if *v == nil { - sv = &GetInventoryOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Entities": - if err := awsAwsjson11_deserializeDocumentInventoryResultEntityList(&sv.Entities, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetInventorySchemaOutput(v **GetInventorySchemaOutput, 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 *GetInventorySchemaOutput - if *v == nil { - sv = &GetInventorySchemaOutput{} - } 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 "Schemas": - if err := awsAwsjson11_deserializeDocumentInventoryItemSchemaResultList(&sv.Schemas, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetMaintenanceWindowExecutionOutput(v **GetMaintenanceWindowExecutionOutput, 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 *GetMaintenanceWindowExecutionOutput - if *v == nil { - sv = &GetMaintenanceWindowExecutionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "EndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.EndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "StartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.StartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatus to be of type string, got %T instead", value) - } - sv.Status = types.MaintenanceWindowExecutionStatus(jtv) - } - - case "StatusDetails": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatusDetails to be of type string, got %T instead", value) - } - sv.StatusDetails = ptr.String(jtv) - } - - case "TaskIds": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowExecutionTaskIdList(&sv.TaskIds, value); err != nil { - return err - } - - case "WindowExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionId to be of type string, got %T instead", value) - } - sv.WindowExecutionId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetMaintenanceWindowExecutionTaskInvocationOutput(v **GetMaintenanceWindowExecutionTaskInvocationOutput, 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 *GetMaintenanceWindowExecutionTaskInvocationOutput - if *v == nil { - sv = &GetMaintenanceWindowExecutionTaskInvocationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "EndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.EndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "ExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionTaskExecutionId to be of type string, got %T instead", value) - } - sv.ExecutionId = ptr.String(jtv) - } - - case "InvocationId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionTaskInvocationId to be of type string, got %T instead", value) - } - sv.InvocationId = ptr.String(jtv) - } - - case "OwnerInformation": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OwnerInformation to be of type string, got %T instead", value) - } - sv.OwnerInformation = ptr.String(jtv) - } - - case "Parameters": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionTaskInvocationParameters to be of type string, got %T instead", value) - } - sv.Parameters = ptr.String(jtv) - } - - case "StartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.StartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatus to be of type string, got %T instead", value) - } - sv.Status = types.MaintenanceWindowExecutionStatus(jtv) - } - - case "StatusDetails": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatusDetails to be of type string, got %T instead", value) - } - sv.StatusDetails = ptr.String(jtv) - } - - case "TaskExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionTaskId to be of type string, got %T instead", value) - } - sv.TaskExecutionId = ptr.String(jtv) - } - - case "TaskType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskType to be of type string, got %T instead", value) - } - sv.TaskType = types.MaintenanceWindowTaskType(jtv) - } - - case "WindowExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionId to be of type string, got %T instead", value) - } - sv.WindowExecutionId = ptr.String(jtv) - } - - case "WindowTargetId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskTargetId to be of type string, got %T instead", value) - } - sv.WindowTargetId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetMaintenanceWindowExecutionTaskOutput(v **GetMaintenanceWindowExecutionTaskOutput, 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 *GetMaintenanceWindowExecutionTaskOutput - if *v == nil { - sv = &GetMaintenanceWindowExecutionTaskOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.AlarmConfiguration, value); err != nil { - return err - } - - case "EndTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.EndTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "MaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.MaxConcurrency = ptr.String(jtv) - } - - case "MaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.MaxErrors = ptr.String(jtv) - } - - case "Priority": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskPriority to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Priority = int32(i64) - } - - case "ServiceRole": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ServiceRole to be of type string, got %T instead", value) - } - sv.ServiceRole = ptr.String(jtv) - } - - case "StartTime": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.StartTime = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Status": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatus to be of type string, got %T instead", value) - } - sv.Status = types.MaintenanceWindowExecutionStatus(jtv) - } - - case "StatusDetails": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionStatusDetails to be of type string, got %T instead", value) - } - sv.StatusDetails = ptr.String(jtv) - } - - case "TaskArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskArn to be of type string, got %T instead", value) - } - sv.TaskArn = ptr.String(jtv) - } - - case "TaskExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionTaskId to be of type string, got %T instead", value) - } - sv.TaskExecutionId = ptr.String(jtv) - } - - case "TaskParameters": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTaskParametersList(&sv.TaskParameters, value); err != nil { - return err - } - - case "TriggeredAlarms": - if err := awsAwsjson11_deserializeDocumentAlarmStateInformationList(&sv.TriggeredAlarms, value); err != nil { - return err - } - - case "Type": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskType to be of type string, got %T instead", value) - } - sv.Type = types.MaintenanceWindowTaskType(jtv) - } - - case "WindowExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowExecutionId to be of type string, got %T instead", value) - } - sv.WindowExecutionId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetMaintenanceWindowOutput(v **GetMaintenanceWindowOutput, 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 *GetMaintenanceWindowOutput - if *v == nil { - sv = &GetMaintenanceWindowOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AllowUnassociatedTargets": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected MaintenanceWindowAllowUnassociatedTargets to be of type *bool, got %T instead", value) - } - sv.AllowUnassociatedTargets = jtv - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Cutoff": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowCutoff to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Cutoff = int32(i64) - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "Duration": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowDurationHours to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Duration = ptr.Int32(int32(i64)) - } - - case "Enabled": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected MaintenanceWindowEnabled to be of type *bool, got %T instead", value) - } - sv.Enabled = jtv - } - - case "EndDate": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowStringDateTime to be of type string, got %T instead", value) - } - sv.EndDate = ptr.String(jtv) - } - - case "ModifiedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "NextExecutionTime": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowStringDateTime to be of type string, got %T instead", value) - } - sv.NextExecutionTime = ptr.String(jtv) - } - - case "Schedule": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowSchedule to be of type string, got %T instead", value) - } - sv.Schedule = ptr.String(jtv) - } - - case "ScheduleOffset": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowOffset to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ScheduleOffset = ptr.Int32(int32(i64)) - } - - case "ScheduleTimezone": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTimezone to be of type string, got %T instead", value) - } - sv.ScheduleTimezone = ptr.String(jtv) - } - - case "StartDate": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowStringDateTime to be of type string, got %T instead", value) - } - sv.StartDate = ptr.String(jtv) - } - - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetMaintenanceWindowTaskOutput(v **GetMaintenanceWindowTaskOutput, 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 *GetMaintenanceWindowTaskOutput - if *v == nil { - sv = &GetMaintenanceWindowTaskOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.AlarmConfiguration, value); err != nil { - return err - } - - case "CutoffBehavior": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskCutoffBehavior to be of type string, got %T instead", value) - } - sv.CutoffBehavior = types.MaintenanceWindowTaskCutoffBehavior(jtv) - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "LoggingInfo": - if err := awsAwsjson11_deserializeDocumentLoggingInfo(&sv.LoggingInfo, value); err != nil { - return err - } - - case "MaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.MaxConcurrency = ptr.String(jtv) - } - - case "MaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.MaxErrors = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Priority": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskPriority to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Priority = int32(i64) - } - - case "ServiceRoleArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ServiceRole to be of type string, got %T instead", value) - } - sv.ServiceRoleArn = ptr.String(jtv) - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - case "TaskArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskArn to be of type string, got %T instead", value) - } - sv.TaskArn = ptr.String(jtv) - } - - case "TaskInvocationParameters": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTaskInvocationParameters(&sv.TaskInvocationParameters, value); err != nil { - return err - } - - case "TaskParameters": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTaskParameters(&sv.TaskParameters, value); err != nil { - return err - } - - case "TaskType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskType to be of type string, got %T instead", value) - } - sv.TaskType = types.MaintenanceWindowTaskType(jtv) - } - - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - case "WindowTaskId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskId to be of type string, got %T instead", value) - } - sv.WindowTaskId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetOpsItemOutput(v **GetOpsItemOutput, 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 *GetOpsItemOutput - if *v == nil { - sv = &GetOpsItemOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "OpsItem": - if err := awsAwsjson11_deserializeDocumentOpsItem(&sv.OpsItem, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetOpsMetadataOutput(v **GetOpsMetadataOutput, 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 *GetOpsMetadataOutput - if *v == nil { - sv = &GetOpsMetadataOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Metadata": - if err := awsAwsjson11_deserializeDocumentMetadataMap(&sv.Metadata, value); err != nil { - return err - } - - 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 "ResourceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsMetadataResourceId to be of type string, got %T instead", value) - } - sv.ResourceId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetOpsSummaryOutput(v **GetOpsSummaryOutput, 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 *GetOpsSummaryOutput - if *v == nil { - sv = &GetOpsSummaryOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Entities": - if err := awsAwsjson11_deserializeDocumentOpsEntityList(&sv.Entities, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetParameterHistoryOutput(v **GetParameterHistoryOutput, 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 *GetParameterHistoryOutput - if *v == nil { - sv = &GetParameterHistoryOutput{} - } 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 "Parameters": - if err := awsAwsjson11_deserializeDocumentParameterHistoryList(&sv.Parameters, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetParameterOutput(v **GetParameterOutput, 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 *GetParameterOutput - if *v == nil { - sv = &GetParameterOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Parameter": - if err := awsAwsjson11_deserializeDocumentParameter(&sv.Parameter, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetParametersByPathOutput(v **GetParametersByPathOutput, 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 *GetParametersByPathOutput - if *v == nil { - sv = &GetParametersByPathOutput{} - } 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 "Parameters": - if err := awsAwsjson11_deserializeDocumentParameterList(&sv.Parameters, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetParametersOutput(v **GetParametersOutput, 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 *GetParametersOutput - if *v == nil { - sv = &GetParametersOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "InvalidParameters": - if err := awsAwsjson11_deserializeDocumentParameterNameList(&sv.InvalidParameters, value); err != nil { - return err - } - - case "Parameters": - if err := awsAwsjson11_deserializeDocumentParameterList(&sv.Parameters, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetPatchBaselineForPatchGroupOutput(v **GetPatchBaselineForPatchGroupOutput, 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 *GetPatchBaselineForPatchGroupOutput - if *v == nil { - sv = &GetPatchBaselineForPatchGroupOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "BaselineId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineId to be of type string, got %T instead", value) - } - sv.BaselineId = ptr.String(jtv) - } - - case "OperatingSystem": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OperatingSystem to be of type string, got %T instead", value) - } - sv.OperatingSystem = types.OperatingSystem(jtv) - } - - case "PatchGroup": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchGroup to be of type string, got %T instead", value) - } - sv.PatchGroup = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetPatchBaselineOutput(v **GetPatchBaselineOutput, 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 *GetPatchBaselineOutput - if *v == nil { - sv = &GetPatchBaselineOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ApprovalRules": - if err := awsAwsjson11_deserializeDocumentPatchRuleGroup(&sv.ApprovalRules, value); err != nil { - return err - } - - case "ApprovedPatches": - if err := awsAwsjson11_deserializeDocumentPatchIdList(&sv.ApprovedPatches, value); err != nil { - return err - } - - case "ApprovedPatchesComplianceLevel": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchComplianceLevel to be of type string, got %T instead", value) - } - sv.ApprovedPatchesComplianceLevel = types.PatchComplianceLevel(jtv) - } - - case "ApprovedPatchesEnableNonSecurity": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected Boolean to be of type *bool, got %T instead", value) - } - sv.ApprovedPatchesEnableNonSecurity = ptr.Bool(jtv) - } - - case "BaselineId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineId to be of type string, got %T instead", value) - } - sv.BaselineId = ptr.String(jtv) - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "GlobalFilters": - if err := awsAwsjson11_deserializeDocumentPatchFilterGroup(&sv.GlobalFilters, value); err != nil { - return err - } - - case "ModifiedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "OperatingSystem": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OperatingSystem to be of type string, got %T instead", value) - } - sv.OperatingSystem = types.OperatingSystem(jtv) - } - - case "PatchGroups": - if err := awsAwsjson11_deserializeDocumentPatchGroupList(&sv.PatchGroups, value); err != nil { - return err - } - - case "RejectedPatches": - if err := awsAwsjson11_deserializeDocumentPatchIdList(&sv.RejectedPatches, value); err != nil { - return err - } - - case "RejectedPatchesAction": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchAction to be of type string, got %T instead", value) - } - sv.RejectedPatchesAction = types.PatchAction(jtv) - } - - case "Sources": - if err := awsAwsjson11_deserializeDocumentPatchSourceList(&sv.Sources, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetResourcePoliciesOutput(v **GetResourcePoliciesOutput, 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 *GetResourcePoliciesOutput - if *v == nil { - sv = &GetResourcePoliciesOutput{} - } 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 String to be of type string, got %T instead", value) - } - sv.NextToken = ptr.String(jtv) - } - - case "Policies": - if err := awsAwsjson11_deserializeDocumentGetResourcePoliciesResponseEntries(&sv.Policies, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentGetServiceSettingOutput(v **GetServiceSettingOutput, 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 *GetServiceSettingOutput - if *v == nil { - sv = &GetServiceSettingOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ServiceSetting": - if err := awsAwsjson11_deserializeDocumentServiceSetting(&sv.ServiceSetting, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentLabelParameterVersionOutput(v **LabelParameterVersionOutput, 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 *LabelParameterVersionOutput - if *v == nil { - sv = &LabelParameterVersionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "InvalidLabels": - if err := awsAwsjson11_deserializeDocumentParameterLabelList(&sv.InvalidLabels, value); err != nil { - return err - } - - case "ParameterVersion": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PSParameterVersion to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ParameterVersion = i64 - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListAssociationsOutput(v **ListAssociationsOutput, 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 *ListAssociationsOutput - if *v == nil { - sv = &ListAssociationsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Associations": - if err := awsAwsjson11_deserializeDocumentAssociationList(&sv.Associations, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListAssociationVersionsOutput(v **ListAssociationVersionsOutput, 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 *ListAssociationVersionsOutput - if *v == nil { - sv = &ListAssociationVersionsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationVersions": - if err := awsAwsjson11_deserializeDocumentAssociationVersionList(&sv.AssociationVersions, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListCommandInvocationsOutput(v **ListCommandInvocationsOutput, 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 *ListCommandInvocationsOutput - if *v == nil { - sv = &ListCommandInvocationsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CommandInvocations": - if err := awsAwsjson11_deserializeDocumentCommandInvocationList(&sv.CommandInvocations, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListCommandsOutput(v **ListCommandsOutput, 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 *ListCommandsOutput - if *v == nil { - sv = &ListCommandsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Commands": - if err := awsAwsjson11_deserializeDocumentCommandList(&sv.Commands, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListComplianceItemsOutput(v **ListComplianceItemsOutput, 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 *ListComplianceItemsOutput - if *v == nil { - sv = &ListComplianceItemsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ComplianceItems": - if err := awsAwsjson11_deserializeDocumentComplianceItemList(&sv.ComplianceItems, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListComplianceSummariesOutput(v **ListComplianceSummariesOutput, 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 *ListComplianceSummariesOutput - if *v == nil { - sv = &ListComplianceSummariesOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ComplianceSummaryItems": - if err := awsAwsjson11_deserializeDocumentComplianceSummaryItemList(&sv.ComplianceSummaryItems, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListDocumentMetadataHistoryOutput(v **ListDocumentMetadataHistoryOutput, 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 *ListDocumentMetadataHistoryOutput - if *v == nil { - sv = &ListDocumentMetadataHistoryOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Author": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentAuthor to be of type string, got %T instead", value) - } - sv.Author = ptr.String(jtv) - } - - case "DocumentVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentVersion to be of type string, got %T instead", value) - } - sv.DocumentVersion = ptr.String(jtv) - } - - case "Metadata": - if err := awsAwsjson11_deserializeDocumentDocumentMetadataResponseInfo(&sv.Metadata, value); err != nil { - return err - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DocumentName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListDocumentsOutput(v **ListDocumentsOutput, 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 *ListDocumentsOutput - if *v == nil { - sv = &ListDocumentsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DocumentIdentifiers": - if err := awsAwsjson11_deserializeDocumentDocumentIdentifierList(&sv.DocumentIdentifiers, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListDocumentVersionsOutput(v **ListDocumentVersionsOutput, 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 *ListDocumentVersionsOutput - if *v == nil { - sv = &ListDocumentVersionsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DocumentVersions": - if err := awsAwsjson11_deserializeDocumentDocumentVersionList(&sv.DocumentVersions, value); err != nil { - return err - } - - 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) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListInventoryEntriesOutput(v **ListInventoryEntriesOutput, 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 *ListInventoryEntriesOutput - if *v == nil { - sv = &ListInventoryEntriesOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "CaptureTime": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemCaptureTime to be of type string, got %T instead", value) - } - sv.CaptureTime = ptr.String(jtv) - } - - case "Entries": - if err := awsAwsjson11_deserializeDocumentInventoryItemEntryList(&sv.Entries, value); err != nil { - return err - } - - case "InstanceId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InstanceId to be of type string, got %T instead", value) - } - sv.InstanceId = ptr.String(jtv) - } - - 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 "SchemaVersion": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemSchemaVersion to be of type string, got %T instead", value) - } - sv.SchemaVersion = ptr.String(jtv) - } - - case "TypeName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected InventoryItemTypeName to be of type string, got %T instead", value) - } - sv.TypeName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListOpsItemEventsOutput(v **ListOpsItemEventsOutput, 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 *ListOpsItemEventsOutput - if *v == nil { - sv = &ListOpsItemEventsOutput{} - } 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 String to be of type string, got %T instead", value) - } - sv.NextToken = ptr.String(jtv) - } - - case "Summaries": - if err := awsAwsjson11_deserializeDocumentOpsItemEventSummaries(&sv.Summaries, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListOpsItemRelatedItemsOutput(v **ListOpsItemRelatedItemsOutput, 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 *ListOpsItemRelatedItemsOutput - if *v == nil { - sv = &ListOpsItemRelatedItemsOutput{} - } 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 String to be of type string, got %T instead", value) - } - sv.NextToken = ptr.String(jtv) - } - - case "Summaries": - if err := awsAwsjson11_deserializeDocumentOpsItemRelatedItemSummaries(&sv.Summaries, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListOpsMetadataOutput(v **ListOpsMetadataOutput, 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 *ListOpsMetadataOutput - if *v == nil { - sv = &ListOpsMetadataOutput{} - } 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 "OpsMetadataList": - if err := awsAwsjson11_deserializeDocumentOpsMetadataList(&sv.OpsMetadataList, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListResourceComplianceSummariesOutput(v **ListResourceComplianceSummariesOutput, 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 *ListResourceComplianceSummariesOutput - if *v == nil { - sv = &ListResourceComplianceSummariesOutput{} - } 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 "ResourceComplianceSummaryItems": - if err := awsAwsjson11_deserializeDocumentResourceComplianceSummaryItemList(&sv.ResourceComplianceSummaryItems, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListResourceDataSyncOutput(v **ListResourceDataSyncOutput, 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 *ListResourceDataSyncOutput - if *v == nil { - sv = &ListResourceDataSyncOutput{} - } 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 "ResourceDataSyncItems": - if err := awsAwsjson11_deserializeDocumentResourceDataSyncItemList(&sv.ResourceDataSyncItems, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentListTagsForResourceOutput(v **ListTagsForResourceOutput, 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 *ListTagsForResourceOutput - if *v == nil { - sv = &ListTagsForResourceOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "TagList": - if err := awsAwsjson11_deserializeDocumentTagList(&sv.TagList, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentModifyDocumentPermissionOutput(v **ModifyDocumentPermissionOutput, 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 *ModifyDocumentPermissionOutput - if *v == nil { - sv = &ModifyDocumentPermissionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentPutComplianceItemsOutput(v **PutComplianceItemsOutput, 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 *PutComplianceItemsOutput - if *v == nil { - sv = &PutComplianceItemsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentPutInventoryOutput(v **PutInventoryOutput, 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 *PutInventoryOutput - if *v == nil { - sv = &PutInventoryOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PutInventoryMessage to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentPutParameterOutput(v **PutParameterOutput, 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 *PutParameterOutput - if *v == nil { - sv = &PutParameterOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Tier": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ParameterTier to be of type string, got %T instead", value) - } - sv.Tier = types.ParameterTier(jtv) - } - - case "Version": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected PSParameterVersion to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Version = i64 - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentPutResourcePolicyOutput(v **PutResourcePolicyOutput, 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 *PutResourcePolicyOutput - if *v == nil { - sv = &PutResourcePolicyOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "PolicyHash": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PolicyHash to be of type string, got %T instead", value) - } - sv.PolicyHash = ptr.String(jtv) - } - - case "PolicyId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PolicyId to be of type string, got %T instead", value) - } - sv.PolicyId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentRegisterDefaultPatchBaselineOutput(v **RegisterDefaultPatchBaselineOutput, 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 *RegisterDefaultPatchBaselineOutput - if *v == nil { - sv = &RegisterDefaultPatchBaselineOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "BaselineId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineId to be of type string, got %T instead", value) - } - sv.BaselineId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentRegisterPatchBaselineForPatchGroupOutput(v **RegisterPatchBaselineForPatchGroupOutput, 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 *RegisterPatchBaselineForPatchGroupOutput - if *v == nil { - sv = &RegisterPatchBaselineForPatchGroupOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "BaselineId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineId to be of type string, got %T instead", value) - } - sv.BaselineId = ptr.String(jtv) - } - - case "PatchGroup": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchGroup to be of type string, got %T instead", value) - } - sv.PatchGroup = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentRegisterTargetWithMaintenanceWindowOutput(v **RegisterTargetWithMaintenanceWindowOutput, 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 *RegisterTargetWithMaintenanceWindowOutput - if *v == nil { - sv = &RegisterTargetWithMaintenanceWindowOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "WindowTargetId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTargetId to be of type string, got %T instead", value) - } - sv.WindowTargetId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentRegisterTaskWithMaintenanceWindowOutput(v **RegisterTaskWithMaintenanceWindowOutput, 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 *RegisterTaskWithMaintenanceWindowOutput - if *v == nil { - sv = &RegisterTaskWithMaintenanceWindowOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "WindowTaskId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskId to be of type string, got %T instead", value) - } - sv.WindowTaskId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentRemoveTagsFromResourceOutput(v **RemoveTagsFromResourceOutput, 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 *RemoveTagsFromResourceOutput - if *v == nil { - sv = &RemoveTagsFromResourceOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentResetServiceSettingOutput(v **ResetServiceSettingOutput, 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 *ResetServiceSettingOutput - if *v == nil { - sv = &ResetServiceSettingOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ServiceSetting": - if err := awsAwsjson11_deserializeDocumentServiceSetting(&sv.ServiceSetting, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentResumeSessionOutput(v **ResumeSessionOutput, 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 *ResumeSessionOutput - if *v == nil { - sv = &ResumeSessionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "SessionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionId to be of type string, got %T instead", value) - } - sv.SessionId = ptr.String(jtv) - } - - case "StreamUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StreamUrl to be of type string, got %T instead", value) - } - sv.StreamUrl = ptr.String(jtv) - } - - case "TokenValue": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TokenValue to be of type string, got %T instead", value) - } - sv.TokenValue = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentSendAutomationSignalOutput(v **SendAutomationSignalOutput, 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 *SendAutomationSignalOutput - if *v == nil { - sv = &SendAutomationSignalOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentSendCommandOutput(v **SendCommandOutput, 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 *SendCommandOutput - if *v == nil { - sv = &SendCommandOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Command": - if err := awsAwsjson11_deserializeDocumentCommand(&sv.Command, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentStartAssociationsOnceOutput(v **StartAssociationsOnceOutput, 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 *StartAssociationsOnceOutput - if *v == nil { - sv = &StartAssociationsOnceOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentStartAutomationExecutionOutput(v **StartAutomationExecutionOutput, 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 *StartAutomationExecutionOutput - if *v == nil { - sv = &StartAutomationExecutionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AutomationExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationExecutionId to be of type string, got %T instead", value) - } - sv.AutomationExecutionId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentStartChangeRequestExecutionOutput(v **StartChangeRequestExecutionOutput, 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 *StartChangeRequestExecutionOutput - if *v == nil { - sv = &StartChangeRequestExecutionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AutomationExecutionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AutomationExecutionId to be of type string, got %T instead", value) - } - sv.AutomationExecutionId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentStartSessionOutput(v **StartSessionOutput, 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 *StartSessionOutput - if *v == nil { - sv = &StartSessionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "SessionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionId to be of type string, got %T instead", value) - } - sv.SessionId = ptr.String(jtv) - } - - case "StreamUrl": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected StreamUrl to be of type string, got %T instead", value) - } - sv.StreamUrl = ptr.String(jtv) - } - - case "TokenValue": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TokenValue to be of type string, got %T instead", value) - } - sv.TokenValue = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentStopAutomationExecutionOutput(v **StopAutomationExecutionOutput, 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 *StopAutomationExecutionOutput - if *v == nil { - sv = &StopAutomationExecutionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentTerminateSessionOutput(v **TerminateSessionOutput, 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 *TerminateSessionOutput - if *v == nil { - sv = &TerminateSessionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "SessionId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionId to be of type string, got %T instead", value) - } - sv.SessionId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUnlabelParameterVersionOutput(v **UnlabelParameterVersionOutput, 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 *UnlabelParameterVersionOutput - if *v == nil { - sv = &UnlabelParameterVersionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "InvalidLabels": - if err := awsAwsjson11_deserializeDocumentParameterLabelList(&sv.InvalidLabels, value); err != nil { - return err - } - - case "RemovedLabels": - if err := awsAwsjson11_deserializeDocumentParameterLabelList(&sv.RemovedLabels, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateAssociationOutput(v **UpdateAssociationOutput, 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 *UpdateAssociationOutput - if *v == nil { - sv = &UpdateAssociationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationDescription": - if err := awsAwsjson11_deserializeDocumentAssociationDescription(&sv.AssociationDescription, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateAssociationStatusOutput(v **UpdateAssociationStatusOutput, 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 *UpdateAssociationStatusOutput - if *v == nil { - sv = &UpdateAssociationStatusOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AssociationDescription": - if err := awsAwsjson11_deserializeDocumentAssociationDescription(&sv.AssociationDescription, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateDocumentDefaultVersionOutput(v **UpdateDocumentDefaultVersionOutput, 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 *UpdateDocumentDefaultVersionOutput - if *v == nil { - sv = &UpdateDocumentDefaultVersionOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Description": - if err := awsAwsjson11_deserializeDocumentDocumentDefaultVersionDescription(&sv.Description, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateDocumentMetadataOutput(v **UpdateDocumentMetadataOutput, 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 *UpdateDocumentMetadataOutput - if *v == nil { - sv = &UpdateDocumentMetadataOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateDocumentOutput(v **UpdateDocumentOutput, 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 *UpdateDocumentOutput - if *v == nil { - sv = &UpdateDocumentOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "DocumentDescription": - if err := awsAwsjson11_deserializeDocumentDocumentDescription(&sv.DocumentDescription, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateMaintenanceWindowOutput(v **UpdateMaintenanceWindowOutput, 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 *UpdateMaintenanceWindowOutput - if *v == nil { - sv = &UpdateMaintenanceWindowOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AllowUnassociatedTargets": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected MaintenanceWindowAllowUnassociatedTargets to be of type *bool, got %T instead", value) - } - sv.AllowUnassociatedTargets = jtv - } - - case "Cutoff": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowCutoff to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Cutoff = int32(i64) - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "Duration": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowDurationHours to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Duration = ptr.Int32(int32(i64)) - } - - case "Enabled": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected MaintenanceWindowEnabled to be of type *bool, got %T instead", value) - } - sv.Enabled = jtv - } - - case "EndDate": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowStringDateTime to be of type string, got %T instead", value) - } - sv.EndDate = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Schedule": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowSchedule to be of type string, got %T instead", value) - } - sv.Schedule = ptr.String(jtv) - } - - case "ScheduleOffset": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowOffset to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ScheduleOffset = ptr.Int32(int32(i64)) - } - - case "ScheduleTimezone": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTimezone to be of type string, got %T instead", value) - } - sv.ScheduleTimezone = ptr.String(jtv) - } - - case "StartDate": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowStringDateTime to be of type string, got %T instead", value) - } - sv.StartDate = ptr.String(jtv) - } - - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateMaintenanceWindowTargetOutput(v **UpdateMaintenanceWindowTargetOutput, 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 *UpdateMaintenanceWindowTargetOutput - if *v == nil { - sv = &UpdateMaintenanceWindowTargetOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "OwnerInformation": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OwnerInformation to be of type string, got %T instead", value) - } - sv.OwnerInformation = ptr.String(jtv) - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - case "WindowTargetId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTargetId to be of type string, got %T instead", value) - } - sv.WindowTargetId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateMaintenanceWindowTaskOutput(v **UpdateMaintenanceWindowTaskOutput, 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 *UpdateMaintenanceWindowTaskOutput - if *v == nil { - sv = &UpdateMaintenanceWindowTaskOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "AlarmConfiguration": - if err := awsAwsjson11_deserializeDocumentAlarmConfiguration(&sv.AlarmConfiguration, value); err != nil { - return err - } - - case "CutoffBehavior": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskCutoffBehavior to be of type string, got %T instead", value) - } - sv.CutoffBehavior = types.MaintenanceWindowTaskCutoffBehavior(jtv) - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "LoggingInfo": - if err := awsAwsjson11_deserializeDocumentLoggingInfo(&sv.LoggingInfo, value); err != nil { - return err - } - - case "MaxConcurrency": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxConcurrency to be of type string, got %T instead", value) - } - sv.MaxConcurrency = ptr.String(jtv) - } - - case "MaxErrors": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaxErrors to be of type string, got %T instead", value) - } - sv.MaxErrors = ptr.String(jtv) - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "Priority": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskPriority to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Priority = int32(i64) - } - - case "ServiceRoleArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ServiceRole to be of type string, got %T instead", value) - } - sv.ServiceRoleArn = ptr.String(jtv) - } - - case "Targets": - if err := awsAwsjson11_deserializeDocumentTargets(&sv.Targets, value); err != nil { - return err - } - - case "TaskArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskArn to be of type string, got %T instead", value) - } - sv.TaskArn = ptr.String(jtv) - } - - case "TaskInvocationParameters": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTaskInvocationParameters(&sv.TaskInvocationParameters, value); err != nil { - return err - } - - case "TaskParameters": - if err := awsAwsjson11_deserializeDocumentMaintenanceWindowTaskParameters(&sv.TaskParameters, value); err != nil { - return err - } - - case "WindowId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowId to be of type string, got %T instead", value) - } - sv.WindowId = ptr.String(jtv) - } - - case "WindowTaskId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected MaintenanceWindowTaskId to be of type string, got %T instead", value) - } - sv.WindowTaskId = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateManagedInstanceRoleOutput(v **UpdateManagedInstanceRoleOutput, 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 *UpdateManagedInstanceRoleOutput - if *v == nil { - sv = &UpdateManagedInstanceRoleOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateOpsItemOutput(v **UpdateOpsItemOutput, 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 *UpdateOpsItemOutput - if *v == nil { - sv = &UpdateOpsItemOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateOpsMetadataOutput(v **UpdateOpsMetadataOutput, 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 *UpdateOpsMetadataOutput - if *v == nil { - sv = &UpdateOpsMetadataOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "OpsMetadataArn": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OpsMetadataArn to be of type string, got %T instead", value) - } - sv.OpsMetadataArn = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdatePatchBaselineOutput(v **UpdatePatchBaselineOutput, 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 *UpdatePatchBaselineOutput - if *v == nil { - sv = &UpdatePatchBaselineOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "ApprovalRules": - if err := awsAwsjson11_deserializeDocumentPatchRuleGroup(&sv.ApprovalRules, value); err != nil { - return err - } - - case "ApprovedPatches": - if err := awsAwsjson11_deserializeDocumentPatchIdList(&sv.ApprovedPatches, value); err != nil { - return err - } - - case "ApprovedPatchesComplianceLevel": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchComplianceLevel to be of type string, got %T instead", value) - } - sv.ApprovedPatchesComplianceLevel = types.PatchComplianceLevel(jtv) - } - - case "ApprovedPatchesEnableNonSecurity": - if value != nil { - jtv, ok := value.(bool) - if !ok { - return fmt.Errorf("expected Boolean to be of type *bool, got %T instead", value) - } - sv.ApprovedPatchesEnableNonSecurity = ptr.Bool(jtv) - } - - case "BaselineId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineId to be of type string, got %T instead", value) - } - sv.BaselineId = ptr.String(jtv) - } - - case "CreatedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.CreatedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineDescription to be of type string, got %T instead", value) - } - sv.Description = ptr.String(jtv) - } - - case "GlobalFilters": - if err := awsAwsjson11_deserializeDocumentPatchFilterGroup(&sv.GlobalFilters, value); err != nil { - return err - } - - case "ModifiedDate": - if value != nil { - switch jtv := value.(type) { - case json.Number: - f64, err := jtv.Float64() - if err != nil { - return err - } - sv.ModifiedDate = ptr.Time(smithytime.ParseEpochSeconds(f64)) - - default: - return fmt.Errorf("expected DateTime to be a JSON Number, got %T instead", value) - - } - } - - case "Name": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected BaselineName to be of type string, got %T instead", value) - } - sv.Name = ptr.String(jtv) - } - - case "OperatingSystem": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected OperatingSystem to be of type string, got %T instead", value) - } - sv.OperatingSystem = types.OperatingSystem(jtv) - } - - case "RejectedPatches": - if err := awsAwsjson11_deserializeDocumentPatchIdList(&sv.RejectedPatches, value); err != nil { - return err - } - - case "RejectedPatchesAction": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected PatchAction to be of type string, got %T instead", value) - } - sv.RejectedPatchesAction = types.PatchAction(jtv) - } - - case "Sources": - if err := awsAwsjson11_deserializeDocumentPatchSourceList(&sv.Sources, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateResourceDataSyncOutput(v **UpdateResourceDataSyncOutput, 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 *UpdateResourceDataSyncOutput - if *v == nil { - sv = &UpdateResourceDataSyncOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsAwsjson11_deserializeOpDocumentUpdateServiceSettingOutput(v **UpdateServiceSettingOutput, 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 *UpdateServiceSettingOutput - if *v == nil { - sv = &UpdateServiceSettingOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - default: - _, _ = key, value - - } - } - *v = sv - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/doc.go deleted file mode 100644 index e546b708..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/doc.go +++ /dev/null @@ -1,28 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -// Package ssm provides the API client, operations, and parameter types for Amazon -// Simple Systems Manager (SSM). -// -// Amazon Web Services Systems Manager is the operations hub for your Amazon Web -// Services applications and resources and a secure end-to-end management solution -// for hybrid cloud environments that enables safe and secure operations at scale. -// This reference is intended to be used with the Amazon Web Services Systems -// Manager User Guide (https://docs.aws.amazon.com/systems-manager/latest/userguide/) -// . To get started, see Setting up Amazon Web Services Systems Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up.html) -// . Related resources -// - For information about each of the capabilities that comprise Systems -// Manager, see Systems Manager capabilities (https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html#systems-manager-capabilities) -// in the Amazon Web Services Systems Manager User Guide. -// - For details about predefined runbooks for Automation, a capability of -// Amazon Web Services Systems Manager, see the Systems Manager Automation -// runbook reference (https://docs.aws.amazon.com/systems-manager-automation-runbooks/latest/userguide/automation-runbook-reference.html) -// . -// - For information about AppConfig, a capability of Systems Manager, see the -// AppConfig User Guide (https://docs.aws.amazon.com/appconfig/latest/userguide/) -// and the AppConfig API Reference (https://docs.aws.amazon.com/appconfig/2019-10-09/APIReference/) -// . -// - For information about Incident Manager, a capability of Systems Manager, -// see the Systems Manager Incident Manager User Guide (https://docs.aws.amazon.com/incident-manager/latest/userguide/) -// and the Systems Manager Incident Manager API Reference (https://docs.aws.amazon.com/incident-manager/latest/APIReference/) -// . -package ssm diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/endpoints.go deleted file mode 100644 index 4cd4e2f7..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/endpoints.go +++ /dev/null @@ -1,528 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "errors" - "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/ssm/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" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net/http" - "net/url" - "os" - "strings" -) - -// EndpointResolverOptions is the service endpoint resolver options -type EndpointResolverOptions = internalendpoints.Options - -// EndpointResolver interface for resolving service endpoints. -type EndpointResolver interface { - ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) -} - -var _ EndpointResolver = &internalendpoints.Resolver{} - -// NewDefaultEndpointResolver constructs a new service endpoint resolver -func NewDefaultEndpointResolver() *internalendpoints.Resolver { - return internalendpoints.New() -} - -// EndpointResolverFunc is a helper utility that wraps a function so it satisfies -// the EndpointResolver interface. This is useful when you want to add additional -// endpoint resolving logic, or stub out specific endpoints with custom values. -type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) - -func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return fn(region, options) -} - -// EndpointResolverFromURL returns an EndpointResolver configured using the -// provided endpoint url. By default, the resolved endpoint resolver uses the -// client region as signing region, and the endpoint source is set to -// EndpointSourceCustom.You can provide functional options to configure endpoint -// values for the resolved endpoint. -func EndpointResolverFromURL(url string, optFns ...func(*aws.Endpoint)) EndpointResolver { - e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom} - for _, fn := range optFns { - fn(&e) - } - - return EndpointResolverFunc( - func(region string, options EndpointResolverOptions) (aws.Endpoint, error) { - if len(e.SigningRegion) == 0 { - e.SigningRegion = region - } - return e, nil - }, - ) -} - -type ResolveEndpoint struct { - Resolver EndpointResolver - Options EndpointResolverOptions -} - -func (*ResolveEndpoint) ID() string { - return "ResolveEndpoint" -} - -func (m *ResolveEndpoint) 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.Resolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - eo := m.Options - eo.Logger = middleware.GetLogger(ctx) - - var endpoint aws.Endpoint - endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), eo) - if err != nil { - nf := (&aws.EndpointNotFoundError{}) - if errors.As(err, &nf) { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, false) - return next.HandleSerialize(ctx, in) - } - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL, err = url.Parse(endpoint.URL) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) - } - - if len(awsmiddleware.GetSigningName(ctx)) == 0 { - signingName := endpoint.SigningName - if len(signingName) == 0 { - signingName = "ssm" - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - } - ctx = awsmiddleware.SetEndpointSource(ctx, endpoint.Source) - ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) - ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) - ctx = awsmiddleware.SetPartitionID(ctx, endpoint.PartitionID) - return next.HandleSerialize(ctx, in) -} -func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&ResolveEndpoint{ - Resolver: o.EndpointResolver, - Options: o.EndpointOptions, - }, "OperationSerializer", middleware.Before) -} - -func removeResolveEndpointMiddleware(stack *middleware.Stack) error { - _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) - return err -} - -type wrappedEndpointResolver struct { - awsResolver aws.EndpointResolverWithOptions -} - -func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return w.awsResolver.ResolveEndpoint(ServiceID, region, options) -} - -type awsEndpointResolverAdaptor func(service, region string) (aws.Endpoint, error) - -func (a awsEndpointResolverAdaptor) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { - return a(service, region) -} - -var _ aws.EndpointResolverWithOptions = awsEndpointResolverAdaptor(nil) - -// withEndpointResolver returns an aws.EndpointResolverWithOptions that first delegates endpoint resolution to the awsResolver. -// If awsResolver returns aws.EndpointNotFoundError error, the v1 resolver middleware will swallow the error, -// and set an appropriate context flag such that fallback will occur when EndpointResolverV2 is invoked -// via its middleware. -// -// If another error (besides aws.EndpointNotFoundError) is returned, then that error will be propagated. -func withEndpointResolver(awsResolver aws.EndpointResolver, awsResolverWithOptions aws.EndpointResolverWithOptions) EndpointResolver { - var resolver aws.EndpointResolverWithOptions - - if awsResolverWithOptions != nil { - resolver = awsResolverWithOptions - } else if awsResolver != nil { - resolver = awsEndpointResolverAdaptor(awsResolver.ResolveEndpoint) - } - - return &wrappedEndpointResolver{ - awsResolver: resolver, - } -} - -func finalizeClientEndpointResolverOptions(options *Options) { - options.EndpointOptions.LogDeprecated = options.ClientLogMode.IsDeprecatedUsage() - - if len(options.EndpointOptions.ResolvedRegion) == 0 { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(options.Region, fipsInfix) || - strings.Contains(options.Region, fipsPrefix) || - strings.Contains(options.Region, fipsSuffix) { - options.EndpointOptions.ResolvedRegion = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - options.Region, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - options.EndpointOptions.UseFIPSEndpoint = aws.FIPSEndpointStateEnabled - } - } - -} - -func resolveEndpointResolverV2(options *Options) { - if options.EndpointResolverV2 == nil { - options.EndpointResolverV2 = NewDefaultEndpointResolverV2() - } -} - -func resolveBaseEndpoint(cfg aws.Config, o *Options) { - if cfg.BaseEndpoint != nil { - o.BaseEndpoint = cfg.BaseEndpoint - } - - _, g := os.LookupEnv("AWS_ENDPOINT_URL") - _, s := os.LookupEnv("AWS_ENDPOINT_URL_SSM") - - if g && !s { - return - } - - value, found, err := internalConfig.ResolveServiceBaseEndpoint(context.Background(), "SSM", cfg.ConfigSources) - if found && err == nil { - o.BaseEndpoint = &value - } -} - -// EndpointParameters provides the parameters that influence how endpoints are -// resolved. -type EndpointParameters struct { - // The AWS region used to dispatch the request. - // - // Parameter is - // required. - // - // AWS::Region - Region *string - - // When true, use the dual-stack endpoint. If the configured endpoint does not - // support dual-stack, dispatching the request MAY return an error. - // - // Defaults to - // false if no value is provided. - // - // AWS::UseDualStack - UseDualStack *bool - - // When true, send this request to the FIPS-compliant regional endpoint. If the - // configured endpoint does not have a FIPS compliant endpoint, dispatching the - // request will return an error. - // - // Defaults to false if no value is - // provided. - // - // AWS::UseFIPS - UseFIPS *bool - - // Override the endpoint used to send this request - // - // Parameter is - // required. - // - // SDK::Endpoint - Endpoint *string -} - -// ValidateRequired validates required parameters are set. -func (p EndpointParameters) ValidateRequired() error { - if p.UseDualStack == nil { - return fmt.Errorf("parameter UseDualStack is required") - } - - if p.UseFIPS == nil { - return fmt.Errorf("parameter UseFIPS is required") - } - - return nil -} - -// WithDefaults returns a shallow copy of EndpointParameterswith default values -// applied to members where applicable. -func (p EndpointParameters) WithDefaults() EndpointParameters { - if p.UseDualStack == nil { - p.UseDualStack = ptr.Bool(false) - } - - if p.UseFIPS == nil { - p.UseFIPS = ptr.Bool(false) - } - return p -} - -// EndpointResolverV2 provides the interface for resolving service endpoints. -type EndpointResolverV2 interface { - // ResolveEndpoint attempts to resolve the endpoint with the provided options, - // returning the endpoint if found. Otherwise an error is returned. - ResolveEndpoint(ctx context.Context, params EndpointParameters) ( - smithyendpoints.Endpoint, error, - ) -} - -// resolver provides the implementation for resolving endpoints. -type resolver struct{} - -func NewDefaultEndpointResolverV2() EndpointResolverV2 { - return &resolver{} -} - -// ResolveEndpoint attempts to resolve the endpoint with the provided options, -// returning the endpoint if found. Otherwise an error is returned. -func (r *resolver) ResolveEndpoint( - ctx context.Context, params EndpointParameters, -) ( - endpoint smithyendpoints.Endpoint, err error, -) { - params = params.WithDefaults() - if err = params.ValidateRequired(); err != nil { - return endpoint, fmt.Errorf("endpoint parameters are not valid, %w", err) - } - _UseDualStack := *params.UseDualStack - _UseFIPS := *params.UseFIPS - - if exprVal := params.Endpoint; exprVal != nil { - _Endpoint := *exprVal - _ = _Endpoint - if _UseFIPS == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: FIPS and custom endpoint are not supported") - } - if _UseDualStack == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Dualstack and custom endpoint are not supported") - } - uriString := _Endpoint - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if exprVal := params.Region; exprVal != nil { - _Region := *exprVal - _ = _Region - if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { - _PartitionResult := *exprVal - _ = _PartitionResult - if _UseFIPS == true { - if _UseDualStack == true { - if true == _PartitionResult.SupportsFIPS { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://ssm-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS and DualStack are enabled, but this partition does not support one or both") - } - } - if _UseFIPS == true { - if _PartitionResult.SupportsFIPS == true { - if _PartitionResult.Name == "aws-us-gov" { - uriString := func() string { - var out strings.Builder - out.WriteString("https://ssm.") - out.WriteString(_Region) - out.WriteString(".amazonaws.com") - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://ssm-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS is enabled but this partition does not support FIPS") - } - if _UseDualStack == true { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://ssm.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "DualStack is enabled but this partition does not support DualStack") - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://ssm.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("Endpoint resolution failed. Invalid operation or environment input.") - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") -} - -type endpointParamsBinder interface { - bindEndpointParams(*EndpointParameters) -} - -func bindEndpointParams(input interface{}, options Options) *EndpointParameters { - params := &EndpointParameters{} - - params.Region = aws.String(endpoints.MapFIPSRegion(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, -) { - 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(getOperationInput(ctx), m.options) - endpt, err := m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - 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) - } - - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/generated.json deleted file mode 100644 index b9f761a5..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/generated.json +++ /dev/null @@ -1,172 +0,0 @@ -{ - "dependencies": { - "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" - }, - "files": [ - "api_client.go", - "api_client_test.go", - "api_op_AddTagsToResource.go", - "api_op_AssociateOpsItemRelatedItem.go", - "api_op_CancelCommand.go", - "api_op_CancelMaintenanceWindowExecution.go", - "api_op_CreateActivation.go", - "api_op_CreateAssociation.go", - "api_op_CreateAssociationBatch.go", - "api_op_CreateDocument.go", - "api_op_CreateMaintenanceWindow.go", - "api_op_CreateOpsItem.go", - "api_op_CreateOpsMetadata.go", - "api_op_CreatePatchBaseline.go", - "api_op_CreateResourceDataSync.go", - "api_op_DeleteActivation.go", - "api_op_DeleteAssociation.go", - "api_op_DeleteDocument.go", - "api_op_DeleteInventory.go", - "api_op_DeleteMaintenanceWindow.go", - "api_op_DeleteOpsItem.go", - "api_op_DeleteOpsMetadata.go", - "api_op_DeleteParameter.go", - "api_op_DeleteParameters.go", - "api_op_DeletePatchBaseline.go", - "api_op_DeleteResourceDataSync.go", - "api_op_DeleteResourcePolicy.go", - "api_op_DeregisterManagedInstance.go", - "api_op_DeregisterPatchBaselineForPatchGroup.go", - "api_op_DeregisterTargetFromMaintenanceWindow.go", - "api_op_DeregisterTaskFromMaintenanceWindow.go", - "api_op_DescribeActivations.go", - "api_op_DescribeAssociation.go", - "api_op_DescribeAssociationExecutionTargets.go", - "api_op_DescribeAssociationExecutions.go", - "api_op_DescribeAutomationExecutions.go", - "api_op_DescribeAutomationStepExecutions.go", - "api_op_DescribeAvailablePatches.go", - "api_op_DescribeDocument.go", - "api_op_DescribeDocumentPermission.go", - "api_op_DescribeEffectiveInstanceAssociations.go", - "api_op_DescribeEffectivePatchesForPatchBaseline.go", - "api_op_DescribeInstanceAssociationsStatus.go", - "api_op_DescribeInstanceInformation.go", - "api_op_DescribeInstancePatchStates.go", - "api_op_DescribeInstancePatchStatesForPatchGroup.go", - "api_op_DescribeInstancePatches.go", - "api_op_DescribeInventoryDeletions.go", - "api_op_DescribeMaintenanceWindowExecutionTaskInvocations.go", - "api_op_DescribeMaintenanceWindowExecutionTasks.go", - "api_op_DescribeMaintenanceWindowExecutions.go", - "api_op_DescribeMaintenanceWindowSchedule.go", - "api_op_DescribeMaintenanceWindowTargets.go", - "api_op_DescribeMaintenanceWindowTasks.go", - "api_op_DescribeMaintenanceWindows.go", - "api_op_DescribeMaintenanceWindowsForTarget.go", - "api_op_DescribeOpsItems.go", - "api_op_DescribeParameters.go", - "api_op_DescribePatchBaselines.go", - "api_op_DescribePatchGroupState.go", - "api_op_DescribePatchGroups.go", - "api_op_DescribePatchProperties.go", - "api_op_DescribeSessions.go", - "api_op_DisassociateOpsItemRelatedItem.go", - "api_op_GetAutomationExecution.go", - "api_op_GetCalendarState.go", - "api_op_GetCommandInvocation.go", - "api_op_GetConnectionStatus.go", - "api_op_GetDefaultPatchBaseline.go", - "api_op_GetDeployablePatchSnapshotForInstance.go", - "api_op_GetDocument.go", - "api_op_GetInventory.go", - "api_op_GetInventorySchema.go", - "api_op_GetMaintenanceWindow.go", - "api_op_GetMaintenanceWindowExecution.go", - "api_op_GetMaintenanceWindowExecutionTask.go", - "api_op_GetMaintenanceWindowExecutionTaskInvocation.go", - "api_op_GetMaintenanceWindowTask.go", - "api_op_GetOpsItem.go", - "api_op_GetOpsMetadata.go", - "api_op_GetOpsSummary.go", - "api_op_GetParameter.go", - "api_op_GetParameterHistory.go", - "api_op_GetParameters.go", - "api_op_GetParametersByPath.go", - "api_op_GetPatchBaseline.go", - "api_op_GetPatchBaselineForPatchGroup.go", - "api_op_GetResourcePolicies.go", - "api_op_GetServiceSetting.go", - "api_op_LabelParameterVersion.go", - "api_op_ListAssociationVersions.go", - "api_op_ListAssociations.go", - "api_op_ListCommandInvocations.go", - "api_op_ListCommands.go", - "api_op_ListComplianceItems.go", - "api_op_ListComplianceSummaries.go", - "api_op_ListDocumentMetadataHistory.go", - "api_op_ListDocumentVersions.go", - "api_op_ListDocuments.go", - "api_op_ListInventoryEntries.go", - "api_op_ListOpsItemEvents.go", - "api_op_ListOpsItemRelatedItems.go", - "api_op_ListOpsMetadata.go", - "api_op_ListResourceComplianceSummaries.go", - "api_op_ListResourceDataSync.go", - "api_op_ListTagsForResource.go", - "api_op_ModifyDocumentPermission.go", - "api_op_PutComplianceItems.go", - "api_op_PutInventory.go", - "api_op_PutParameter.go", - "api_op_PutResourcePolicy.go", - "api_op_RegisterDefaultPatchBaseline.go", - "api_op_RegisterPatchBaselineForPatchGroup.go", - "api_op_RegisterTargetWithMaintenanceWindow.go", - "api_op_RegisterTaskWithMaintenanceWindow.go", - "api_op_RemoveTagsFromResource.go", - "api_op_ResetServiceSetting.go", - "api_op_ResumeSession.go", - "api_op_SendAutomationSignal.go", - "api_op_SendCommand.go", - "api_op_StartAssociationsOnce.go", - "api_op_StartAutomationExecution.go", - "api_op_StartChangeRequestExecution.go", - "api_op_StartSession.go", - "api_op_StopAutomationExecution.go", - "api_op_TerminateSession.go", - "api_op_UnlabelParameterVersion.go", - "api_op_UpdateAssociation.go", - "api_op_UpdateAssociationStatus.go", - "api_op_UpdateDocument.go", - "api_op_UpdateDocumentDefaultVersion.go", - "api_op_UpdateDocumentMetadata.go", - "api_op_UpdateMaintenanceWindow.go", - "api_op_UpdateMaintenanceWindowTarget.go", - "api_op_UpdateMaintenanceWindowTask.go", - "api_op_UpdateManagedInstanceRole.go", - "api_op_UpdateOpsItem.go", - "api_op_UpdateOpsMetadata.go", - "api_op_UpdatePatchBaseline.go", - "api_op_UpdateResourceDataSync.go", - "api_op_UpdateServiceSetting.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", - "types/enums.go", - "types/errors.go", - "types/types.go", - "validators.go" - ], - "go": "1.15", - "module": "github.com/aws/aws-sdk-go-v2/service/ssm", - "unstable": false -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/go_module_metadata.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/go_module_metadata.go deleted file mode 100644 index 9b35f7aa..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package ssm - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.44.7" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/internal/endpoints/endpoints.go deleted file mode 100644 index 88f63256..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/internal/endpoints/endpoints.go +++ /dev/null @@ -1,534 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package endpoints - -import ( - "github.com/aws/aws-sdk-go-v2/aws" - endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" - "github.com/aws/smithy-go/logging" - "regexp" -) - -// Options is the endpoint resolver configuration options -type Options struct { - // Logger is a logging implementation that log events should be sent to. - Logger logging.Logger - - // LogDeprecated indicates that deprecated endpoints should be logged to the - // provided logger. - LogDeprecated bool - - // ResolvedRegion is used to override the region to be resolved, rather then the - // using the value passed to the ResolveEndpoint method. This value is used by the - // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative - // name. You must not set this value directly in your application. - ResolvedRegion string - - // DisableHTTPS informs the resolver to return an endpoint that does not use the - // HTTPS scheme. - DisableHTTPS bool - - // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. - UseDualStackEndpoint aws.DualStackEndpointState - - // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. - UseFIPSEndpoint aws.FIPSEndpointState -} - -func (o Options) GetResolvedRegion() string { - return o.ResolvedRegion -} - -func (o Options) GetDisableHTTPS() bool { - return o.DisableHTTPS -} - -func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { - return o.UseDualStackEndpoint -} - -func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { - return o.UseFIPSEndpoint -} - -func transformToSharedOptions(options Options) endpoints.Options { - return endpoints.Options{ - Logger: options.Logger, - LogDeprecated: options.LogDeprecated, - ResolvedRegion: options.ResolvedRegion, - DisableHTTPS: options.DisableHTTPS, - UseDualStackEndpoint: options.UseDualStackEndpoint, - UseFIPSEndpoint: options.UseFIPSEndpoint, - } -} - -// Resolver SSM endpoint resolver -type Resolver struct { - partitions endpoints.Partitions -} - -// ResolveEndpoint resolves the service endpoint for the given region and options -func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { - if len(region) == 0 { - return endpoint, &aws.MissingRegionError{} - } - - opt := transformToSharedOptions(options) - return r.partitions.ResolveEndpoint(region, opt) -} - -// New returns a new Resolver -func New() *Resolver { - return &Resolver{ - partitions: defaultPartitions, - } -} - -var partitionRegexp = struct { - Aws *regexp.Regexp - AwsCn *regexp.Regexp - AwsIso *regexp.Regexp - AwsIsoB *regexp.Regexp - AwsIsoE *regexp.Regexp - AwsIsoF *regexp.Regexp - AwsUsGov *regexp.Regexp -}{ - - Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$"), - AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), - AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), - AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), - AwsIsoE: regexp.MustCompile("^eu\\-isoe\\-\\w+\\-\\d+$"), - AwsIsoF: regexp.MustCompile("^us\\-isof\\-\\w+\\-\\d+$"), - AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), -} - -var defaultPartitions = endpoints.Partitions{ - { - ID: "aws", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "ssm.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "ssm-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "ssm.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.Aws, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "af-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-south-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-4", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ca-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ca-central-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.ca-central-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "ca-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ca-west-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.ca-west-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "eu-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-central-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-north-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-south-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "fips-ca-central-1", - }: endpoints.Endpoint{ - Hostname: "ssm-fips.ca-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ca-central-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "fips-ca-west-1", - }: endpoints.Endpoint{ - Hostname: "ssm-fips.ca-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ca-west-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "fips-us-east-1", - }: endpoints.Endpoint{ - Hostname: "ssm-fips.us-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "fips-us-east-2", - }: endpoints.Endpoint{ - Hostname: "ssm-fips.us-east-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-2", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "fips-us-west-1", - }: endpoints.Endpoint{ - Hostname: "ssm-fips.us-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "fips-us-west-2", - }: endpoints.Endpoint{ - Hostname: "ssm-fips.us-west-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-2", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "il-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "me-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "me-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "sa-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-east-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.us-east-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-east-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-east-2", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.us-east-2.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-west-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.us-west-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-west-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-west-2", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.us-west-2.amazonaws.com", - }, - }, - }, - { - ID: "aws-cn", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "ssm.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "ssm-fips.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "ssm.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsCn, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "cn-north-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "cn-northwest-1", - }: endpoints.Endpoint{}, - }, - }, - { - ID: "aws-iso", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "ssm.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIso, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-iso-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-iso-west-1", - }: endpoints.Endpoint{}, - }, - }, - { - ID: "aws-iso-b", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "ssm.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoB, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-isob-east-1", - }: endpoints.Endpoint{}, - }, - }, - { - ID: "aws-iso-e", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "ssm.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoE, - IsRegionalized: true, - }, - { - ID: "aws-iso-f", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm-fips.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "ssm.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoF, - IsRegionalized: true, - }, - { - ID: "aws-us-gov", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "ssm.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "ssm-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "ssm.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsUsGov, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "fips-us-gov-east-1", - }: endpoints.Endpoint{ - Hostname: "ssm.us-gov-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "fips-us-gov-west-1", - }: endpoints.Endpoint{ - Hostname: "ssm.us-gov-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-gov-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-gov-east-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm.us-gov-east-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "ssm.us-gov-west-1.amazonaws.com", - }, - }, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/options.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/options.go deleted file mode 100644 index 197dfd32..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/options.go +++ /dev/null @@ -1,221 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -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/middleware" - 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 - - // Provides idempotency tokens values that will be automatically populated into - // idempotent API operations. - IdempotencyTokenProvider IdempotencyTokenProvider - - // The logger writer interface to write logging messages to. - Logger logging.Logger - - // 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 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/ssm/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/serializers.go deleted file mode 100644 index 9e3ab946..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/serializers.go +++ /dev/null @@ -1,14912 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "bytes" - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/encoding/httpbinding" - smithyjson "github.com/aws/smithy-go/encoding/json" - "github.com/aws/smithy-go/middleware" - smithytime "github.com/aws/smithy-go/time" - smithyhttp "github.com/aws/smithy-go/transport/http" - "path" -) - -type awsAwsjson11_serializeOpAddTagsToResource struct { -} - -func (*awsAwsjson11_serializeOpAddTagsToResource) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpAddTagsToResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*AddTagsToResourceInput) - _ = 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("AmazonSSM.AddTagsToResource") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentAddTagsToResourceInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpAssociateOpsItemRelatedItem struct { -} - -func (*awsAwsjson11_serializeOpAssociateOpsItemRelatedItem) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpAssociateOpsItemRelatedItem) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*AssociateOpsItemRelatedItemInput) - _ = 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("AmazonSSM.AssociateOpsItemRelatedItem") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentAssociateOpsItemRelatedItemInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCancelCommand struct { -} - -func (*awsAwsjson11_serializeOpCancelCommand) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCancelCommand) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CancelCommandInput) - _ = 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("AmazonSSM.CancelCommand") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCancelCommandInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCancelMaintenanceWindowExecution struct { -} - -func (*awsAwsjson11_serializeOpCancelMaintenanceWindowExecution) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCancelMaintenanceWindowExecution) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CancelMaintenanceWindowExecutionInput) - _ = 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("AmazonSSM.CancelMaintenanceWindowExecution") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCancelMaintenanceWindowExecutionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCreateActivation struct { -} - -func (*awsAwsjson11_serializeOpCreateActivation) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCreateActivation) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreateActivationInput) - _ = 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("AmazonSSM.CreateActivation") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCreateActivationInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCreateAssociation struct { -} - -func (*awsAwsjson11_serializeOpCreateAssociation) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCreateAssociation) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreateAssociationInput) - _ = 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("AmazonSSM.CreateAssociation") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCreateAssociationInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCreateAssociationBatch struct { -} - -func (*awsAwsjson11_serializeOpCreateAssociationBatch) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCreateAssociationBatch) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreateAssociationBatchInput) - _ = 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("AmazonSSM.CreateAssociationBatch") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCreateAssociationBatchInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCreateDocument struct { -} - -func (*awsAwsjson11_serializeOpCreateDocument) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCreateDocument) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreateDocumentInput) - _ = 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("AmazonSSM.CreateDocument") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCreateDocumentInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCreateMaintenanceWindow struct { -} - -func (*awsAwsjson11_serializeOpCreateMaintenanceWindow) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCreateMaintenanceWindow) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreateMaintenanceWindowInput) - _ = 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("AmazonSSM.CreateMaintenanceWindow") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCreateMaintenanceWindowInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCreateOpsItem struct { -} - -func (*awsAwsjson11_serializeOpCreateOpsItem) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCreateOpsItem) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreateOpsItemInput) - _ = 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("AmazonSSM.CreateOpsItem") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCreateOpsItemInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCreateOpsMetadata struct { -} - -func (*awsAwsjson11_serializeOpCreateOpsMetadata) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCreateOpsMetadata) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreateOpsMetadataInput) - _ = 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("AmazonSSM.CreateOpsMetadata") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCreateOpsMetadataInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCreatePatchBaseline struct { -} - -func (*awsAwsjson11_serializeOpCreatePatchBaseline) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCreatePatchBaseline) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreatePatchBaselineInput) - _ = 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("AmazonSSM.CreatePatchBaseline") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCreatePatchBaselineInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpCreateResourceDataSync struct { -} - -func (*awsAwsjson11_serializeOpCreateResourceDataSync) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpCreateResourceDataSync) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreateResourceDataSyncInput) - _ = 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("AmazonSSM.CreateResourceDataSync") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentCreateResourceDataSyncInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteActivation struct { -} - -func (*awsAwsjson11_serializeOpDeleteActivation) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteActivation) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteActivationInput) - _ = 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("AmazonSSM.DeleteActivation") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteActivationInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteAssociation struct { -} - -func (*awsAwsjson11_serializeOpDeleteAssociation) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteAssociation) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteAssociationInput) - _ = 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("AmazonSSM.DeleteAssociation") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteAssociationInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteDocument struct { -} - -func (*awsAwsjson11_serializeOpDeleteDocument) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteDocument) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteDocumentInput) - _ = 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("AmazonSSM.DeleteDocument") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteDocumentInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteInventory struct { -} - -func (*awsAwsjson11_serializeOpDeleteInventory) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteInventory) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteInventoryInput) - _ = 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("AmazonSSM.DeleteInventory") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteInventoryInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteMaintenanceWindow struct { -} - -func (*awsAwsjson11_serializeOpDeleteMaintenanceWindow) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteMaintenanceWindow) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteMaintenanceWindowInput) - _ = 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("AmazonSSM.DeleteMaintenanceWindow") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteMaintenanceWindowInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteOpsItem struct { -} - -func (*awsAwsjson11_serializeOpDeleteOpsItem) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteOpsItem) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteOpsItemInput) - _ = 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("AmazonSSM.DeleteOpsItem") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteOpsItemInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteOpsMetadata struct { -} - -func (*awsAwsjson11_serializeOpDeleteOpsMetadata) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteOpsMetadata) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteOpsMetadataInput) - _ = 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("AmazonSSM.DeleteOpsMetadata") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteOpsMetadataInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteParameter struct { -} - -func (*awsAwsjson11_serializeOpDeleteParameter) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteParameter) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteParameterInput) - _ = 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("AmazonSSM.DeleteParameter") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteParameterInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteParameters struct { -} - -func (*awsAwsjson11_serializeOpDeleteParameters) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteParameters) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteParametersInput) - _ = 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("AmazonSSM.DeleteParameters") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteParametersInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeletePatchBaseline struct { -} - -func (*awsAwsjson11_serializeOpDeletePatchBaseline) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeletePatchBaseline) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeletePatchBaselineInput) - _ = 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("AmazonSSM.DeletePatchBaseline") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeletePatchBaselineInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteResourceDataSync struct { -} - -func (*awsAwsjson11_serializeOpDeleteResourceDataSync) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteResourceDataSync) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteResourceDataSyncInput) - _ = 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("AmazonSSM.DeleteResourceDataSync") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteResourceDataSyncInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeleteResourcePolicy struct { -} - -func (*awsAwsjson11_serializeOpDeleteResourcePolicy) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeleteResourcePolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeleteResourcePolicyInput) - _ = 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("AmazonSSM.DeleteResourcePolicy") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeleteResourcePolicyInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeregisterManagedInstance struct { -} - -func (*awsAwsjson11_serializeOpDeregisterManagedInstance) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeregisterManagedInstance) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeregisterManagedInstanceInput) - _ = 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("AmazonSSM.DeregisterManagedInstance") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeregisterManagedInstanceInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeregisterPatchBaselineForPatchGroup struct { -} - -func (*awsAwsjson11_serializeOpDeregisterPatchBaselineForPatchGroup) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeregisterPatchBaselineForPatchGroup) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeregisterPatchBaselineForPatchGroupInput) - _ = 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("AmazonSSM.DeregisterPatchBaselineForPatchGroup") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeregisterPatchBaselineForPatchGroupInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeregisterTargetFromMaintenanceWindow struct { -} - -func (*awsAwsjson11_serializeOpDeregisterTargetFromMaintenanceWindow) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeregisterTargetFromMaintenanceWindow) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeregisterTargetFromMaintenanceWindowInput) - _ = 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("AmazonSSM.DeregisterTargetFromMaintenanceWindow") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeregisterTargetFromMaintenanceWindowInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDeregisterTaskFromMaintenanceWindow struct { -} - -func (*awsAwsjson11_serializeOpDeregisterTaskFromMaintenanceWindow) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDeregisterTaskFromMaintenanceWindow) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DeregisterTaskFromMaintenanceWindowInput) - _ = 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("AmazonSSM.DeregisterTaskFromMaintenanceWindow") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDeregisterTaskFromMaintenanceWindowInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeActivations struct { -} - -func (*awsAwsjson11_serializeOpDescribeActivations) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeActivations) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeActivationsInput) - _ = 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("AmazonSSM.DescribeActivations") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeActivationsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeAssociation struct { -} - -func (*awsAwsjson11_serializeOpDescribeAssociation) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeAssociation) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeAssociationInput) - _ = 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("AmazonSSM.DescribeAssociation") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeAssociationInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeAssociationExecutions struct { -} - -func (*awsAwsjson11_serializeOpDescribeAssociationExecutions) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeAssociationExecutions) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeAssociationExecutionsInput) - _ = 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("AmazonSSM.DescribeAssociationExecutions") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeAssociationExecutionsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeAssociationExecutionTargets struct { -} - -func (*awsAwsjson11_serializeOpDescribeAssociationExecutionTargets) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeAssociationExecutionTargets) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeAssociationExecutionTargetsInput) - _ = 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("AmazonSSM.DescribeAssociationExecutionTargets") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeAssociationExecutionTargetsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeAutomationExecutions struct { -} - -func (*awsAwsjson11_serializeOpDescribeAutomationExecutions) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeAutomationExecutions) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeAutomationExecutionsInput) - _ = 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("AmazonSSM.DescribeAutomationExecutions") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeAutomationExecutionsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeAutomationStepExecutions struct { -} - -func (*awsAwsjson11_serializeOpDescribeAutomationStepExecutions) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeAutomationStepExecutions) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeAutomationStepExecutionsInput) - _ = 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("AmazonSSM.DescribeAutomationStepExecutions") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeAutomationStepExecutionsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeAvailablePatches struct { -} - -func (*awsAwsjson11_serializeOpDescribeAvailablePatches) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeAvailablePatches) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeAvailablePatchesInput) - _ = 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("AmazonSSM.DescribeAvailablePatches") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeAvailablePatchesInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeDocument struct { -} - -func (*awsAwsjson11_serializeOpDescribeDocument) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeDocument) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeDocumentInput) - _ = 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("AmazonSSM.DescribeDocument") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeDocumentInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeDocumentPermission struct { -} - -func (*awsAwsjson11_serializeOpDescribeDocumentPermission) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeDocumentPermission) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeDocumentPermissionInput) - _ = 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("AmazonSSM.DescribeDocumentPermission") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeDocumentPermissionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeEffectiveInstanceAssociations struct { -} - -func (*awsAwsjson11_serializeOpDescribeEffectiveInstanceAssociations) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeEffectiveInstanceAssociations) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeEffectiveInstanceAssociationsInput) - _ = 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("AmazonSSM.DescribeEffectiveInstanceAssociations") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeEffectiveInstanceAssociationsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeEffectivePatchesForPatchBaseline struct { -} - -func (*awsAwsjson11_serializeOpDescribeEffectivePatchesForPatchBaseline) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeEffectivePatchesForPatchBaseline) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeEffectivePatchesForPatchBaselineInput) - _ = 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("AmazonSSM.DescribeEffectivePatchesForPatchBaseline") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeEffectivePatchesForPatchBaselineInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeInstanceAssociationsStatus struct { -} - -func (*awsAwsjson11_serializeOpDescribeInstanceAssociationsStatus) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeInstanceAssociationsStatus) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeInstanceAssociationsStatusInput) - _ = 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("AmazonSSM.DescribeInstanceAssociationsStatus") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeInstanceAssociationsStatusInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeInstanceInformation struct { -} - -func (*awsAwsjson11_serializeOpDescribeInstanceInformation) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeInstanceInformation) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeInstanceInformationInput) - _ = 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("AmazonSSM.DescribeInstanceInformation") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeInstanceInformationInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeInstancePatches struct { -} - -func (*awsAwsjson11_serializeOpDescribeInstancePatches) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeInstancePatches) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeInstancePatchesInput) - _ = 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("AmazonSSM.DescribeInstancePatches") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeInstancePatchesInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeInstancePatchStates struct { -} - -func (*awsAwsjson11_serializeOpDescribeInstancePatchStates) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeInstancePatchStates) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeInstancePatchStatesInput) - _ = 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("AmazonSSM.DescribeInstancePatchStates") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeInstancePatchStatesInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeInstancePatchStatesForPatchGroup struct { -} - -func (*awsAwsjson11_serializeOpDescribeInstancePatchStatesForPatchGroup) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeInstancePatchStatesForPatchGroup) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeInstancePatchStatesForPatchGroupInput) - _ = 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("AmazonSSM.DescribeInstancePatchStatesForPatchGroup") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeInstancePatchStatesForPatchGroupInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeInventoryDeletions struct { -} - -func (*awsAwsjson11_serializeOpDescribeInventoryDeletions) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeInventoryDeletions) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeInventoryDeletionsInput) - _ = 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("AmazonSSM.DescribeInventoryDeletions") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeInventoryDeletionsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutions struct { -} - -func (*awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutions) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutions) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeMaintenanceWindowExecutionsInput) - _ = 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("AmazonSSM.DescribeMaintenanceWindowExecutions") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowExecutionsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutionTaskInvocations struct { -} - -func (*awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutionTaskInvocations) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutionTaskInvocations) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeMaintenanceWindowExecutionTaskInvocationsInput) - _ = 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("AmazonSSM.DescribeMaintenanceWindowExecutionTaskInvocations") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowExecutionTaskInvocationsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutionTasks struct { -} - -func (*awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutionTasks) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeMaintenanceWindowExecutionTasks) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeMaintenanceWindowExecutionTasksInput) - _ = 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("AmazonSSM.DescribeMaintenanceWindowExecutionTasks") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowExecutionTasksInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeMaintenanceWindows struct { -} - -func (*awsAwsjson11_serializeOpDescribeMaintenanceWindows) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeMaintenanceWindows) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeMaintenanceWindowsInput) - _ = 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("AmazonSSM.DescribeMaintenanceWindows") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeMaintenanceWindowSchedule struct { -} - -func (*awsAwsjson11_serializeOpDescribeMaintenanceWindowSchedule) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeMaintenanceWindowSchedule) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeMaintenanceWindowScheduleInput) - _ = 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("AmazonSSM.DescribeMaintenanceWindowSchedule") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowScheduleInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeMaintenanceWindowsForTarget struct { -} - -func (*awsAwsjson11_serializeOpDescribeMaintenanceWindowsForTarget) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeMaintenanceWindowsForTarget) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeMaintenanceWindowsForTargetInput) - _ = 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("AmazonSSM.DescribeMaintenanceWindowsForTarget") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowsForTargetInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeMaintenanceWindowTargets struct { -} - -func (*awsAwsjson11_serializeOpDescribeMaintenanceWindowTargets) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeMaintenanceWindowTargets) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeMaintenanceWindowTargetsInput) - _ = 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("AmazonSSM.DescribeMaintenanceWindowTargets") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowTargetsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeMaintenanceWindowTasks struct { -} - -func (*awsAwsjson11_serializeOpDescribeMaintenanceWindowTasks) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeMaintenanceWindowTasks) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeMaintenanceWindowTasksInput) - _ = 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("AmazonSSM.DescribeMaintenanceWindowTasks") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowTasksInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeOpsItems struct { -} - -func (*awsAwsjson11_serializeOpDescribeOpsItems) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeOpsItems) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeOpsItemsInput) - _ = 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("AmazonSSM.DescribeOpsItems") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeOpsItemsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeParameters struct { -} - -func (*awsAwsjson11_serializeOpDescribeParameters) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeParameters) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeParametersInput) - _ = 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("AmazonSSM.DescribeParameters") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeParametersInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribePatchBaselines struct { -} - -func (*awsAwsjson11_serializeOpDescribePatchBaselines) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribePatchBaselines) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribePatchBaselinesInput) - _ = 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("AmazonSSM.DescribePatchBaselines") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribePatchBaselinesInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribePatchGroups struct { -} - -func (*awsAwsjson11_serializeOpDescribePatchGroups) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribePatchGroups) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribePatchGroupsInput) - _ = 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("AmazonSSM.DescribePatchGroups") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribePatchGroupsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribePatchGroupState struct { -} - -func (*awsAwsjson11_serializeOpDescribePatchGroupState) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribePatchGroupState) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribePatchGroupStateInput) - _ = 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("AmazonSSM.DescribePatchGroupState") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribePatchGroupStateInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribePatchProperties struct { -} - -func (*awsAwsjson11_serializeOpDescribePatchProperties) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribePatchProperties) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribePatchPropertiesInput) - _ = 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("AmazonSSM.DescribePatchProperties") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribePatchPropertiesInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDescribeSessions struct { -} - -func (*awsAwsjson11_serializeOpDescribeSessions) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDescribeSessions) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DescribeSessionsInput) - _ = 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("AmazonSSM.DescribeSessions") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDescribeSessionsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpDisassociateOpsItemRelatedItem struct { -} - -func (*awsAwsjson11_serializeOpDisassociateOpsItemRelatedItem) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpDisassociateOpsItemRelatedItem) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DisassociateOpsItemRelatedItemInput) - _ = 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("AmazonSSM.DisassociateOpsItemRelatedItem") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentDisassociateOpsItemRelatedItemInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetAutomationExecution struct { -} - -func (*awsAwsjson11_serializeOpGetAutomationExecution) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetAutomationExecution) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetAutomationExecutionInput) - _ = 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("AmazonSSM.GetAutomationExecution") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetAutomationExecutionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetCalendarState struct { -} - -func (*awsAwsjson11_serializeOpGetCalendarState) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetCalendarState) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetCalendarStateInput) - _ = 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("AmazonSSM.GetCalendarState") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetCalendarStateInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetCommandInvocation struct { -} - -func (*awsAwsjson11_serializeOpGetCommandInvocation) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetCommandInvocation) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetCommandInvocationInput) - _ = 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("AmazonSSM.GetCommandInvocation") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetCommandInvocationInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetConnectionStatus struct { -} - -func (*awsAwsjson11_serializeOpGetConnectionStatus) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetConnectionStatus) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetConnectionStatusInput) - _ = 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("AmazonSSM.GetConnectionStatus") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetConnectionStatusInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetDefaultPatchBaseline struct { -} - -func (*awsAwsjson11_serializeOpGetDefaultPatchBaseline) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetDefaultPatchBaseline) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetDefaultPatchBaselineInput) - _ = 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("AmazonSSM.GetDefaultPatchBaseline") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetDefaultPatchBaselineInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetDeployablePatchSnapshotForInstance struct { -} - -func (*awsAwsjson11_serializeOpGetDeployablePatchSnapshotForInstance) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetDeployablePatchSnapshotForInstance) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetDeployablePatchSnapshotForInstanceInput) - _ = 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("AmazonSSM.GetDeployablePatchSnapshotForInstance") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetDeployablePatchSnapshotForInstanceInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetDocument struct { -} - -func (*awsAwsjson11_serializeOpGetDocument) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetDocument) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetDocumentInput) - _ = 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("AmazonSSM.GetDocument") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetDocumentInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetInventory struct { -} - -func (*awsAwsjson11_serializeOpGetInventory) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetInventory) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetInventoryInput) - _ = 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("AmazonSSM.GetInventory") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetInventoryInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetInventorySchema struct { -} - -func (*awsAwsjson11_serializeOpGetInventorySchema) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetInventorySchema) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetInventorySchemaInput) - _ = 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("AmazonSSM.GetInventorySchema") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetInventorySchemaInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetMaintenanceWindow struct { -} - -func (*awsAwsjson11_serializeOpGetMaintenanceWindow) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetMaintenanceWindow) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetMaintenanceWindowInput) - _ = 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("AmazonSSM.GetMaintenanceWindow") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetMaintenanceWindowInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetMaintenanceWindowExecution struct { -} - -func (*awsAwsjson11_serializeOpGetMaintenanceWindowExecution) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetMaintenanceWindowExecution) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetMaintenanceWindowExecutionInput) - _ = 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("AmazonSSM.GetMaintenanceWindowExecution") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetMaintenanceWindowExecutionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetMaintenanceWindowExecutionTask struct { -} - -func (*awsAwsjson11_serializeOpGetMaintenanceWindowExecutionTask) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetMaintenanceWindowExecutionTask) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetMaintenanceWindowExecutionTaskInput) - _ = 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("AmazonSSM.GetMaintenanceWindowExecutionTask") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetMaintenanceWindowExecutionTaskInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetMaintenanceWindowExecutionTaskInvocation struct { -} - -func (*awsAwsjson11_serializeOpGetMaintenanceWindowExecutionTaskInvocation) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetMaintenanceWindowExecutionTaskInvocation) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetMaintenanceWindowExecutionTaskInvocationInput) - _ = 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("AmazonSSM.GetMaintenanceWindowExecutionTaskInvocation") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetMaintenanceWindowExecutionTaskInvocationInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetMaintenanceWindowTask struct { -} - -func (*awsAwsjson11_serializeOpGetMaintenanceWindowTask) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetMaintenanceWindowTask) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetMaintenanceWindowTaskInput) - _ = 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("AmazonSSM.GetMaintenanceWindowTask") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetMaintenanceWindowTaskInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetOpsItem struct { -} - -func (*awsAwsjson11_serializeOpGetOpsItem) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetOpsItem) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetOpsItemInput) - _ = 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("AmazonSSM.GetOpsItem") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetOpsItemInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetOpsMetadata struct { -} - -func (*awsAwsjson11_serializeOpGetOpsMetadata) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetOpsMetadata) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetOpsMetadataInput) - _ = 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("AmazonSSM.GetOpsMetadata") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetOpsMetadataInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetOpsSummary struct { -} - -func (*awsAwsjson11_serializeOpGetOpsSummary) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetOpsSummary) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetOpsSummaryInput) - _ = 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("AmazonSSM.GetOpsSummary") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetOpsSummaryInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetParameter struct { -} - -func (*awsAwsjson11_serializeOpGetParameter) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetParameter) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetParameterInput) - _ = 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("AmazonSSM.GetParameter") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetParameterInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetParameterHistory struct { -} - -func (*awsAwsjson11_serializeOpGetParameterHistory) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetParameterHistory) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetParameterHistoryInput) - _ = 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("AmazonSSM.GetParameterHistory") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetParameterHistoryInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetParameters struct { -} - -func (*awsAwsjson11_serializeOpGetParameters) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetParameters) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetParametersInput) - _ = 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("AmazonSSM.GetParameters") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetParametersInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetParametersByPath struct { -} - -func (*awsAwsjson11_serializeOpGetParametersByPath) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetParametersByPath) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetParametersByPathInput) - _ = 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("AmazonSSM.GetParametersByPath") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetParametersByPathInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetPatchBaseline struct { -} - -func (*awsAwsjson11_serializeOpGetPatchBaseline) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetPatchBaseline) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetPatchBaselineInput) - _ = 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("AmazonSSM.GetPatchBaseline") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetPatchBaselineInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetPatchBaselineForPatchGroup struct { -} - -func (*awsAwsjson11_serializeOpGetPatchBaselineForPatchGroup) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetPatchBaselineForPatchGroup) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetPatchBaselineForPatchGroupInput) - _ = 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("AmazonSSM.GetPatchBaselineForPatchGroup") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetPatchBaselineForPatchGroupInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetResourcePolicies struct { -} - -func (*awsAwsjson11_serializeOpGetResourcePolicies) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetResourcePolicies) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetResourcePoliciesInput) - _ = 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("AmazonSSM.GetResourcePolicies") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetResourcePoliciesInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpGetServiceSetting struct { -} - -func (*awsAwsjson11_serializeOpGetServiceSetting) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpGetServiceSetting) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetServiceSettingInput) - _ = 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("AmazonSSM.GetServiceSetting") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentGetServiceSettingInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpLabelParameterVersion struct { -} - -func (*awsAwsjson11_serializeOpLabelParameterVersion) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpLabelParameterVersion) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*LabelParameterVersionInput) - _ = 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("AmazonSSM.LabelParameterVersion") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentLabelParameterVersionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListAssociations struct { -} - -func (*awsAwsjson11_serializeOpListAssociations) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListAssociations) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListAssociationsInput) - _ = 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("AmazonSSM.ListAssociations") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListAssociationsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListAssociationVersions struct { -} - -func (*awsAwsjson11_serializeOpListAssociationVersions) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListAssociationVersions) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListAssociationVersionsInput) - _ = 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("AmazonSSM.ListAssociationVersions") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListAssociationVersionsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListCommandInvocations struct { -} - -func (*awsAwsjson11_serializeOpListCommandInvocations) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListCommandInvocations) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListCommandInvocationsInput) - _ = 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("AmazonSSM.ListCommandInvocations") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListCommandInvocationsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListCommands struct { -} - -func (*awsAwsjson11_serializeOpListCommands) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListCommands) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListCommandsInput) - _ = 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("AmazonSSM.ListCommands") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListCommandsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListComplianceItems struct { -} - -func (*awsAwsjson11_serializeOpListComplianceItems) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListComplianceItems) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListComplianceItemsInput) - _ = 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("AmazonSSM.ListComplianceItems") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListComplianceItemsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListComplianceSummaries struct { -} - -func (*awsAwsjson11_serializeOpListComplianceSummaries) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListComplianceSummaries) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListComplianceSummariesInput) - _ = 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("AmazonSSM.ListComplianceSummaries") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListComplianceSummariesInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListDocumentMetadataHistory struct { -} - -func (*awsAwsjson11_serializeOpListDocumentMetadataHistory) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListDocumentMetadataHistory) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListDocumentMetadataHistoryInput) - _ = 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("AmazonSSM.ListDocumentMetadataHistory") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListDocumentMetadataHistoryInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListDocuments struct { -} - -func (*awsAwsjson11_serializeOpListDocuments) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListDocuments) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListDocumentsInput) - _ = 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("AmazonSSM.ListDocuments") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListDocumentsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListDocumentVersions struct { -} - -func (*awsAwsjson11_serializeOpListDocumentVersions) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListDocumentVersions) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListDocumentVersionsInput) - _ = 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("AmazonSSM.ListDocumentVersions") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListDocumentVersionsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListInventoryEntries struct { -} - -func (*awsAwsjson11_serializeOpListInventoryEntries) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListInventoryEntries) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListInventoryEntriesInput) - _ = 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("AmazonSSM.ListInventoryEntries") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListInventoryEntriesInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListOpsItemEvents struct { -} - -func (*awsAwsjson11_serializeOpListOpsItemEvents) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListOpsItemEvents) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListOpsItemEventsInput) - _ = 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("AmazonSSM.ListOpsItemEvents") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListOpsItemEventsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListOpsItemRelatedItems struct { -} - -func (*awsAwsjson11_serializeOpListOpsItemRelatedItems) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListOpsItemRelatedItems) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListOpsItemRelatedItemsInput) - _ = 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("AmazonSSM.ListOpsItemRelatedItems") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListOpsItemRelatedItemsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListOpsMetadata struct { -} - -func (*awsAwsjson11_serializeOpListOpsMetadata) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListOpsMetadata) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListOpsMetadataInput) - _ = 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("AmazonSSM.ListOpsMetadata") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListOpsMetadataInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListResourceComplianceSummaries struct { -} - -func (*awsAwsjson11_serializeOpListResourceComplianceSummaries) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListResourceComplianceSummaries) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListResourceComplianceSummariesInput) - _ = 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("AmazonSSM.ListResourceComplianceSummaries") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListResourceComplianceSummariesInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListResourceDataSync struct { -} - -func (*awsAwsjson11_serializeOpListResourceDataSync) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListResourceDataSync) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListResourceDataSyncInput) - _ = 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("AmazonSSM.ListResourceDataSync") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListResourceDataSyncInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpListTagsForResource struct { -} - -func (*awsAwsjson11_serializeOpListTagsForResource) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpListTagsForResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListTagsForResourceInput) - _ = 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("AmazonSSM.ListTagsForResource") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentListTagsForResourceInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpModifyDocumentPermission struct { -} - -func (*awsAwsjson11_serializeOpModifyDocumentPermission) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpModifyDocumentPermission) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ModifyDocumentPermissionInput) - _ = 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("AmazonSSM.ModifyDocumentPermission") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentModifyDocumentPermissionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpPutComplianceItems struct { -} - -func (*awsAwsjson11_serializeOpPutComplianceItems) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpPutComplianceItems) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*PutComplianceItemsInput) - _ = 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("AmazonSSM.PutComplianceItems") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentPutComplianceItemsInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpPutInventory struct { -} - -func (*awsAwsjson11_serializeOpPutInventory) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpPutInventory) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*PutInventoryInput) - _ = 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("AmazonSSM.PutInventory") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentPutInventoryInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpPutParameter struct { -} - -func (*awsAwsjson11_serializeOpPutParameter) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpPutParameter) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*PutParameterInput) - _ = 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("AmazonSSM.PutParameter") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentPutParameterInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpPutResourcePolicy struct { -} - -func (*awsAwsjson11_serializeOpPutResourcePolicy) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpPutResourcePolicy) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*PutResourcePolicyInput) - _ = 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("AmazonSSM.PutResourcePolicy") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentPutResourcePolicyInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpRegisterDefaultPatchBaseline struct { -} - -func (*awsAwsjson11_serializeOpRegisterDefaultPatchBaseline) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpRegisterDefaultPatchBaseline) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*RegisterDefaultPatchBaselineInput) - _ = 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("AmazonSSM.RegisterDefaultPatchBaseline") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentRegisterDefaultPatchBaselineInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpRegisterPatchBaselineForPatchGroup struct { -} - -func (*awsAwsjson11_serializeOpRegisterPatchBaselineForPatchGroup) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpRegisterPatchBaselineForPatchGroup) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*RegisterPatchBaselineForPatchGroupInput) - _ = 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("AmazonSSM.RegisterPatchBaselineForPatchGroup") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentRegisterPatchBaselineForPatchGroupInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpRegisterTargetWithMaintenanceWindow struct { -} - -func (*awsAwsjson11_serializeOpRegisterTargetWithMaintenanceWindow) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpRegisterTargetWithMaintenanceWindow) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*RegisterTargetWithMaintenanceWindowInput) - _ = 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("AmazonSSM.RegisterTargetWithMaintenanceWindow") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentRegisterTargetWithMaintenanceWindowInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpRegisterTaskWithMaintenanceWindow struct { -} - -func (*awsAwsjson11_serializeOpRegisterTaskWithMaintenanceWindow) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpRegisterTaskWithMaintenanceWindow) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*RegisterTaskWithMaintenanceWindowInput) - _ = 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("AmazonSSM.RegisterTaskWithMaintenanceWindow") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentRegisterTaskWithMaintenanceWindowInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpRemoveTagsFromResource struct { -} - -func (*awsAwsjson11_serializeOpRemoveTagsFromResource) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpRemoveTagsFromResource) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*RemoveTagsFromResourceInput) - _ = 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("AmazonSSM.RemoveTagsFromResource") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentRemoveTagsFromResourceInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpResetServiceSetting struct { -} - -func (*awsAwsjson11_serializeOpResetServiceSetting) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpResetServiceSetting) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ResetServiceSettingInput) - _ = 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("AmazonSSM.ResetServiceSetting") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentResetServiceSettingInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpResumeSession struct { -} - -func (*awsAwsjson11_serializeOpResumeSession) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpResumeSession) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ResumeSessionInput) - _ = 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("AmazonSSM.ResumeSession") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentResumeSessionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpSendAutomationSignal struct { -} - -func (*awsAwsjson11_serializeOpSendAutomationSignal) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpSendAutomationSignal) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*SendAutomationSignalInput) - _ = 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("AmazonSSM.SendAutomationSignal") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentSendAutomationSignalInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpSendCommand struct { -} - -func (*awsAwsjson11_serializeOpSendCommand) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpSendCommand) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*SendCommandInput) - _ = 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("AmazonSSM.SendCommand") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentSendCommandInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpStartAssociationsOnce struct { -} - -func (*awsAwsjson11_serializeOpStartAssociationsOnce) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpStartAssociationsOnce) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*StartAssociationsOnceInput) - _ = 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("AmazonSSM.StartAssociationsOnce") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentStartAssociationsOnceInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpStartAutomationExecution struct { -} - -func (*awsAwsjson11_serializeOpStartAutomationExecution) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpStartAutomationExecution) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*StartAutomationExecutionInput) - _ = 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("AmazonSSM.StartAutomationExecution") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentStartAutomationExecutionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpStartChangeRequestExecution struct { -} - -func (*awsAwsjson11_serializeOpStartChangeRequestExecution) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpStartChangeRequestExecution) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*StartChangeRequestExecutionInput) - _ = 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("AmazonSSM.StartChangeRequestExecution") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentStartChangeRequestExecutionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpStartSession struct { -} - -func (*awsAwsjson11_serializeOpStartSession) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpStartSession) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*StartSessionInput) - _ = 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("AmazonSSM.StartSession") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentStartSessionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpStopAutomationExecution struct { -} - -func (*awsAwsjson11_serializeOpStopAutomationExecution) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpStopAutomationExecution) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*StopAutomationExecutionInput) - _ = 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("AmazonSSM.StopAutomationExecution") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentStopAutomationExecutionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpTerminateSession struct { -} - -func (*awsAwsjson11_serializeOpTerminateSession) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpTerminateSession) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*TerminateSessionInput) - _ = 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("AmazonSSM.TerminateSession") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentTerminateSessionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUnlabelParameterVersion struct { -} - -func (*awsAwsjson11_serializeOpUnlabelParameterVersion) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUnlabelParameterVersion) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UnlabelParameterVersionInput) - _ = 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("AmazonSSM.UnlabelParameterVersion") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUnlabelParameterVersionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateAssociation struct { -} - -func (*awsAwsjson11_serializeOpUpdateAssociation) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateAssociation) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateAssociationInput) - _ = 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("AmazonSSM.UpdateAssociation") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateAssociationInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateAssociationStatus struct { -} - -func (*awsAwsjson11_serializeOpUpdateAssociationStatus) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateAssociationStatus) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateAssociationStatusInput) - _ = 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("AmazonSSM.UpdateAssociationStatus") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateAssociationStatusInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateDocument struct { -} - -func (*awsAwsjson11_serializeOpUpdateDocument) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateDocument) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateDocumentInput) - _ = 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("AmazonSSM.UpdateDocument") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateDocumentInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateDocumentDefaultVersion struct { -} - -func (*awsAwsjson11_serializeOpUpdateDocumentDefaultVersion) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateDocumentDefaultVersion) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateDocumentDefaultVersionInput) - _ = 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("AmazonSSM.UpdateDocumentDefaultVersion") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateDocumentDefaultVersionInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateDocumentMetadata struct { -} - -func (*awsAwsjson11_serializeOpUpdateDocumentMetadata) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateDocumentMetadata) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateDocumentMetadataInput) - _ = 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("AmazonSSM.UpdateDocumentMetadata") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateDocumentMetadataInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateMaintenanceWindow struct { -} - -func (*awsAwsjson11_serializeOpUpdateMaintenanceWindow) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateMaintenanceWindow) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateMaintenanceWindowInput) - _ = 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("AmazonSSM.UpdateMaintenanceWindow") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateMaintenanceWindowInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateMaintenanceWindowTarget struct { -} - -func (*awsAwsjson11_serializeOpUpdateMaintenanceWindowTarget) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateMaintenanceWindowTarget) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateMaintenanceWindowTargetInput) - _ = 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("AmazonSSM.UpdateMaintenanceWindowTarget") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateMaintenanceWindowTargetInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateMaintenanceWindowTask struct { -} - -func (*awsAwsjson11_serializeOpUpdateMaintenanceWindowTask) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateMaintenanceWindowTask) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateMaintenanceWindowTaskInput) - _ = 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("AmazonSSM.UpdateMaintenanceWindowTask") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateMaintenanceWindowTaskInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateManagedInstanceRole struct { -} - -func (*awsAwsjson11_serializeOpUpdateManagedInstanceRole) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateManagedInstanceRole) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateManagedInstanceRoleInput) - _ = 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("AmazonSSM.UpdateManagedInstanceRole") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateManagedInstanceRoleInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateOpsItem struct { -} - -func (*awsAwsjson11_serializeOpUpdateOpsItem) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateOpsItem) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateOpsItemInput) - _ = 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("AmazonSSM.UpdateOpsItem") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateOpsItemInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateOpsMetadata struct { -} - -func (*awsAwsjson11_serializeOpUpdateOpsMetadata) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateOpsMetadata) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateOpsMetadataInput) - _ = 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("AmazonSSM.UpdateOpsMetadata") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateOpsMetadataInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdatePatchBaseline struct { -} - -func (*awsAwsjson11_serializeOpUpdatePatchBaseline) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdatePatchBaseline) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdatePatchBaselineInput) - _ = 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("AmazonSSM.UpdatePatchBaseline") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdatePatchBaselineInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateResourceDataSync struct { -} - -func (*awsAwsjson11_serializeOpUpdateResourceDataSync) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateResourceDataSync) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateResourceDataSyncInput) - _ = 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("AmazonSSM.UpdateResourceDataSync") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateResourceDataSyncInput(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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsjson11_serializeOpUpdateServiceSetting struct { -} - -func (*awsAwsjson11_serializeOpUpdateServiceSetting) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsjson11_serializeOpUpdateServiceSetting) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*UpdateServiceSettingInput) - _ = 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("AmazonSSM.UpdateServiceSetting") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsAwsjson11_serializeOpDocumentUpdateServiceSettingInput(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 - - return next.HandleSerialize(ctx, in) -} -func awsAwsjson11_serializeDocumentAccountIdList(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_serializeDocumentAccounts(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_serializeDocumentAlarm(v *types.Alarm, 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_serializeDocumentAlarmConfiguration(v *types.AlarmConfiguration, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Alarms != nil { - ok := object.Key("Alarms") - if err := awsAwsjson11_serializeDocumentAlarmList(v.Alarms, ok); err != nil { - return err - } - } - - if v.IgnorePollAlarmFailure { - ok := object.Key("IgnorePollAlarmFailure") - ok.Boolean(v.IgnorePollAlarmFailure) - } - - return nil -} - -func awsAwsjson11_serializeDocumentAlarmList(v []types.Alarm, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentAlarm(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentAssociationExecutionFilter(v *types.AssociationExecutionFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("Key") - ok.String(string(v.Key)) - } - - if len(v.Type) > 0 { - ok := object.Key("Type") - ok.String(string(v.Type)) - } - - if v.Value != nil { - ok := object.Key("Value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeDocumentAssociationExecutionFilterList(v []types.AssociationExecutionFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentAssociationExecutionFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentAssociationExecutionTargetsFilter(v *types.AssociationExecutionTargetsFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("Key") - ok.String(string(v.Key)) - } - - if v.Value != nil { - ok := object.Key("Value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeDocumentAssociationExecutionTargetsFilterList(v []types.AssociationExecutionTargetsFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentAssociationExecutionTargetsFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentAssociationFilter(v *types.AssociationFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("key") - ok.String(string(v.Key)) - } - - if v.Value != nil { - ok := object.Key("value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeDocumentAssociationFilterList(v []types.AssociationFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentAssociationFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentAssociationIdList(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_serializeDocumentAssociationStatus(v *types.AssociationStatus, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AdditionalInfo != nil { - ok := object.Key("AdditionalInfo") - ok.String(*v.AdditionalInfo) - } - - if v.Date != nil { - ok := object.Key("Date") - ok.Double(smithytime.FormatEpochSeconds(*v.Date)) - } - - if v.Message != nil { - ok := object.Key("Message") - ok.String(*v.Message) - } - - if len(v.Name) > 0 { - ok := object.Key("Name") - ok.String(string(v.Name)) - } - - return nil -} - -func awsAwsjson11_serializeDocumentAttachmentsSource(v *types.AttachmentsSource, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("Key") - ok.String(string(v.Key)) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentAttachmentsSourceValues(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentAttachmentsSourceList(v []types.AttachmentsSource, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentAttachmentsSource(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentAttachmentsSourceValues(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_serializeDocumentAutomationExecutionFilter(v *types.AutomationExecutionFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("Key") - ok.String(string(v.Key)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentAutomationExecutionFilterValueList(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentAutomationExecutionFilterList(v []types.AutomationExecutionFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentAutomationExecutionFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentAutomationExecutionFilterValueList(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_serializeDocumentAutomationParameterMap(v map[string][]string, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - for key := range v { - om := object.Key(key) - if vv := v[key]; vv == nil { - continue - } - if err := awsAwsjson11_serializeDocumentAutomationParameterValueList(v[key], om); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentAutomationParameterValueList(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_serializeDocumentBaselineOverride(v *types.BaselineOverride, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ApprovalRules != nil { - ok := object.Key("ApprovalRules") - if err := awsAwsjson11_serializeDocumentPatchRuleGroup(v.ApprovalRules, ok); err != nil { - return err - } - } - - if v.ApprovedPatches != nil { - ok := object.Key("ApprovedPatches") - if err := awsAwsjson11_serializeDocumentPatchIdList(v.ApprovedPatches, ok); err != nil { - return err - } - } - - if len(v.ApprovedPatchesComplianceLevel) > 0 { - ok := object.Key("ApprovedPatchesComplianceLevel") - ok.String(string(v.ApprovedPatchesComplianceLevel)) - } - - if v.ApprovedPatchesEnableNonSecurity { - ok := object.Key("ApprovedPatchesEnableNonSecurity") - ok.Boolean(v.ApprovedPatchesEnableNonSecurity) - } - - if v.GlobalFilters != nil { - ok := object.Key("GlobalFilters") - if err := awsAwsjson11_serializeDocumentPatchFilterGroup(v.GlobalFilters, ok); err != nil { - return err - } - } - - if len(v.OperatingSystem) > 0 { - ok := object.Key("OperatingSystem") - ok.String(string(v.OperatingSystem)) - } - - if v.RejectedPatches != nil { - ok := object.Key("RejectedPatches") - if err := awsAwsjson11_serializeDocumentPatchIdList(v.RejectedPatches, ok); err != nil { - return err - } - } - - if len(v.RejectedPatchesAction) > 0 { - ok := object.Key("RejectedPatchesAction") - ok.String(string(v.RejectedPatchesAction)) - } - - if v.Sources != nil { - ok := object.Key("Sources") - if err := awsAwsjson11_serializeDocumentPatchSourceList(v.Sources, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentCalendarNameOrARNList(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_serializeDocumentCloudWatchOutputConfig(v *types.CloudWatchOutputConfig, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.CloudWatchLogGroupName != nil { - ok := object.Key("CloudWatchLogGroupName") - ok.String(*v.CloudWatchLogGroupName) - } - - if v.CloudWatchOutputEnabled { - ok := object.Key("CloudWatchOutputEnabled") - ok.Boolean(v.CloudWatchOutputEnabled) - } - - return nil -} - -func awsAwsjson11_serializeDocumentCommandFilter(v *types.CommandFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("key") - ok.String(string(v.Key)) - } - - if v.Value != nil { - ok := object.Key("value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeDocumentCommandFilterList(v []types.CommandFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentCommandFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentComplianceExecutionSummary(v *types.ComplianceExecutionSummary, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ExecutionId != nil { - ok := object.Key("ExecutionId") - ok.String(*v.ExecutionId) - } - - if v.ExecutionTime != nil { - ok := object.Key("ExecutionTime") - ok.Double(smithytime.FormatEpochSeconds(*v.ExecutionTime)) - } - - if v.ExecutionType != nil { - ok := object.Key("ExecutionType") - ok.String(*v.ExecutionType) - } - - return nil -} - -func awsAwsjson11_serializeDocumentComplianceItemDetails(v map[string]string, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - for key := range v { - om := object.Key(key) - om.String(v[key]) - } - return nil -} - -func awsAwsjson11_serializeDocumentComplianceItemEntry(v *types.ComplianceItemEntry, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Details != nil { - ok := object.Key("Details") - if err := awsAwsjson11_serializeDocumentComplianceItemDetails(v.Details, ok); err != nil { - return err - } - } - - if v.Id != nil { - ok := object.Key("Id") - ok.String(*v.Id) - } - - if len(v.Severity) > 0 { - ok := object.Key("Severity") - ok.String(string(v.Severity)) - } - - if len(v.Status) > 0 { - ok := object.Key("Status") - ok.String(string(v.Status)) - } - - if v.Title != nil { - ok := object.Key("Title") - ok.String(*v.Title) - } - - return nil -} - -func awsAwsjson11_serializeDocumentComplianceItemEntryList(v []types.ComplianceItemEntry, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentComplianceItemEntry(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentComplianceResourceIdList(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_serializeDocumentComplianceResourceTypeList(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_serializeDocumentComplianceStringFilter(v *types.ComplianceStringFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if len(v.Type) > 0 { - ok := object.Key("Type") - ok.String(string(v.Type)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentComplianceStringFilterValueList(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentComplianceStringFilterList(v []types.ComplianceStringFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentComplianceStringFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentComplianceStringFilterValueList(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_serializeDocumentCreateAssociationBatchRequestEntries(v []types.CreateAssociationBatchRequestEntry, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentCreateAssociationBatchRequestEntry(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentCreateAssociationBatchRequestEntry(v *types.CreateAssociationBatchRequestEntry, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AlarmConfiguration != nil { - ok := object.Key("AlarmConfiguration") - if err := awsAwsjson11_serializeDocumentAlarmConfiguration(v.AlarmConfiguration, ok); err != nil { - return err - } - } - - if v.ApplyOnlyAtCronInterval { - ok := object.Key("ApplyOnlyAtCronInterval") - ok.Boolean(v.ApplyOnlyAtCronInterval) - } - - if v.AssociationName != nil { - ok := object.Key("AssociationName") - ok.String(*v.AssociationName) - } - - if v.AutomationTargetParameterName != nil { - ok := object.Key("AutomationTargetParameterName") - ok.String(*v.AutomationTargetParameterName) - } - - if v.CalendarNames != nil { - ok := object.Key("CalendarNames") - if err := awsAwsjson11_serializeDocumentCalendarNameOrARNList(v.CalendarNames, ok); err != nil { - return err - } - } - - if len(v.ComplianceSeverity) > 0 { - ok := object.Key("ComplianceSeverity") - ok.String(string(v.ComplianceSeverity)) - } - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.MaxConcurrency != nil { - ok := object.Key("MaxConcurrency") - ok.String(*v.MaxConcurrency) - } - - if v.MaxErrors != nil { - ok := object.Key("MaxErrors") - ok.String(*v.MaxErrors) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.OutputLocation != nil { - ok := object.Key("OutputLocation") - if err := awsAwsjson11_serializeDocumentInstanceAssociationOutputLocation(v.OutputLocation, ok); err != nil { - return err - } - } - - if v.Parameters != nil { - ok := object.Key("Parameters") - if err := awsAwsjson11_serializeDocumentParameters(v.Parameters, ok); err != nil { - return err - } - } - - if v.ScheduleExpression != nil { - ok := object.Key("ScheduleExpression") - ok.String(*v.ScheduleExpression) - } - - if v.ScheduleOffset != nil { - ok := object.Key("ScheduleOffset") - ok.Integer(*v.ScheduleOffset) - } - - if len(v.SyncCompliance) > 0 { - ok := object.Key("SyncCompliance") - ok.String(string(v.SyncCompliance)) - } - - if v.TargetLocations != nil { - ok := object.Key("TargetLocations") - if err := awsAwsjson11_serializeDocumentTargetLocations(v.TargetLocations, ok); err != nil { - return err - } - } - - if v.TargetMaps != nil { - ok := object.Key("TargetMaps") - if err := awsAwsjson11_serializeDocumentTargetMaps(v.TargetMaps, ok); err != nil { - return err - } - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentDescribeActivationsFilter(v *types.DescribeActivationsFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.FilterKey) > 0 { - ok := object.Key("FilterKey") - ok.String(string(v.FilterKey)) - } - - if v.FilterValues != nil { - ok := object.Key("FilterValues") - if err := awsAwsjson11_serializeDocumentStringList(v.FilterValues, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentDescribeActivationsFilterList(v []types.DescribeActivationsFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentDescribeActivationsFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentDocumentFilter(v *types.DocumentFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("key") - ok.String(string(v.Key)) - } - - if v.Value != nil { - ok := object.Key("value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeDocumentDocumentFilterList(v []types.DocumentFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentDocumentFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentDocumentKeyValuesFilter(v *types.DocumentKeyValuesFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentDocumentKeyValuesFilterValues(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentDocumentKeyValuesFilterList(v []types.DocumentKeyValuesFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentDocumentKeyValuesFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentDocumentKeyValuesFilterValues(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_serializeDocumentDocumentRequires(v *types.DocumentRequires, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.RequireType != nil { - ok := object.Key("RequireType") - ok.String(*v.RequireType) - } - - if v.Version != nil { - ok := object.Key("Version") - ok.String(*v.Version) - } - - if v.VersionName != nil { - ok := object.Key("VersionName") - ok.String(*v.VersionName) - } - - return nil -} - -func awsAwsjson11_serializeDocumentDocumentRequiresList(v []types.DocumentRequires, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentDocumentRequires(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentDocumentReviewCommentList(v []types.DocumentReviewCommentSource, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentDocumentReviewCommentSource(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentDocumentReviewCommentSource(v *types.DocumentReviewCommentSource, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Content != nil { - ok := object.Key("Content") - ok.String(*v.Content) - } - - if len(v.Type) > 0 { - ok := object.Key("Type") - ok.String(string(v.Type)) - } - - return nil -} - -func awsAwsjson11_serializeDocumentDocumentReviews(v *types.DocumentReviews, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Action) > 0 { - ok := object.Key("Action") - ok.String(string(v.Action)) - } - - if v.Comment != nil { - ok := object.Key("Comment") - if err := awsAwsjson11_serializeDocumentDocumentReviewCommentList(v.Comment, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentInstanceAssociationOutputLocation(v *types.InstanceAssociationOutputLocation, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.S3Location != nil { - ok := object.Key("S3Location") - if err := awsAwsjson11_serializeDocumentS3OutputLocation(v.S3Location, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentInstanceIdList(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_serializeDocumentInstanceInformationFilter(v *types.InstanceInformationFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("key") - ok.String(string(v.Key)) - } - - if v.ValueSet != nil { - ok := object.Key("valueSet") - if err := awsAwsjson11_serializeDocumentInstanceInformationFilterValueSet(v.ValueSet, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentInstanceInformationFilterList(v []types.InstanceInformationFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentInstanceInformationFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentInstanceInformationFilterValueSet(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_serializeDocumentInstanceInformationStringFilter(v *types.InstanceInformationStringFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentInstanceInformationFilterValueSet(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentInstanceInformationStringFilterList(v []types.InstanceInformationStringFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentInstanceInformationStringFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentInstancePatchStateFilter(v *types.InstancePatchStateFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if len(v.Type) > 0 { - ok := object.Key("Type") - ok.String(string(v.Type)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentInstancePatchStateFilterValues(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentInstancePatchStateFilterList(v []types.InstancePatchStateFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentInstancePatchStateFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentInstancePatchStateFilterValues(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_serializeDocumentInventoryAggregator(v *types.InventoryAggregator, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Aggregators != nil { - ok := object.Key("Aggregators") - if err := awsAwsjson11_serializeDocumentInventoryAggregatorList(v.Aggregators, ok); err != nil { - return err - } - } - - if v.Expression != nil { - ok := object.Key("Expression") - ok.String(*v.Expression) - } - - if v.Groups != nil { - ok := object.Key("Groups") - if err := awsAwsjson11_serializeDocumentInventoryGroupList(v.Groups, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentInventoryAggregatorList(v []types.InventoryAggregator, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentInventoryAggregator(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentInventoryFilter(v *types.InventoryFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if len(v.Type) > 0 { - ok := object.Key("Type") - ok.String(string(v.Type)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentInventoryFilterValueList(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentInventoryFilterList(v []types.InventoryFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentInventoryFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentInventoryFilterValueList(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_serializeDocumentInventoryGroup(v *types.InventoryGroup, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentInventoryFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - return nil -} - -func awsAwsjson11_serializeDocumentInventoryGroupList(v []types.InventoryGroup, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentInventoryGroup(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentInventoryItem(v *types.InventoryItem, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.CaptureTime != nil { - ok := object.Key("CaptureTime") - ok.String(*v.CaptureTime) - } - - if v.Content != nil { - ok := object.Key("Content") - if err := awsAwsjson11_serializeDocumentInventoryItemEntryList(v.Content, ok); err != nil { - return err - } - } - - if v.ContentHash != nil { - ok := object.Key("ContentHash") - ok.String(*v.ContentHash) - } - - if v.Context != nil { - ok := object.Key("Context") - if err := awsAwsjson11_serializeDocumentInventoryItemContentContext(v.Context, ok); err != nil { - return err - } - } - - if v.SchemaVersion != nil { - ok := object.Key("SchemaVersion") - ok.String(*v.SchemaVersion) - } - - if v.TypeName != nil { - ok := object.Key("TypeName") - ok.String(*v.TypeName) - } - - return nil -} - -func awsAwsjson11_serializeDocumentInventoryItemContentContext(v map[string]string, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - for key := range v { - om := object.Key(key) - om.String(v[key]) - } - return nil -} - -func awsAwsjson11_serializeDocumentInventoryItemEntry(v map[string]string, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - for key := range v { - om := object.Key(key) - om.String(v[key]) - } - return nil -} - -func awsAwsjson11_serializeDocumentInventoryItemEntryList(v []map[string]string, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if vv := v[i]; vv == nil { - continue - } - if err := awsAwsjson11_serializeDocumentInventoryItemEntry(v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentInventoryItemList(v []types.InventoryItem, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentInventoryItem(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentKeyList(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_serializeDocumentLoggingInfo(v *types.LoggingInfo, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.S3BucketName != nil { - ok := object.Key("S3BucketName") - ok.String(*v.S3BucketName) - } - - if v.S3KeyPrefix != nil { - ok := object.Key("S3KeyPrefix") - ok.String(*v.S3KeyPrefix) - } - - if v.S3Region != nil { - ok := object.Key("S3Region") - ok.String(*v.S3Region) - } - - return nil -} - -func awsAwsjson11_serializeDocumentMaintenanceWindowAutomationParameters(v *types.MaintenanceWindowAutomationParameters, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.Parameters != nil { - ok := object.Key("Parameters") - if err := awsAwsjson11_serializeDocumentAutomationParameterMap(v.Parameters, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentMaintenanceWindowFilter(v *types.MaintenanceWindowFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowFilterValues(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentMaintenanceWindowFilterList(v []types.MaintenanceWindowFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentMaintenanceWindowFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentMaintenanceWindowFilterValues(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_serializeDocumentMaintenanceWindowLambdaParameters(v *types.MaintenanceWindowLambdaParameters, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientContext != nil { - ok := object.Key("ClientContext") - ok.String(*v.ClientContext) - } - - if v.Payload != nil { - ok := object.Key("Payload") - ok.Base64EncodeBytes(v.Payload) - } - - if v.Qualifier != nil { - ok := object.Key("Qualifier") - ok.String(*v.Qualifier) - } - - return nil -} - -func awsAwsjson11_serializeDocumentMaintenanceWindowRunCommandParameters(v *types.MaintenanceWindowRunCommandParameters, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.CloudWatchOutputConfig != nil { - ok := object.Key("CloudWatchOutputConfig") - if err := awsAwsjson11_serializeDocumentCloudWatchOutputConfig(v.CloudWatchOutputConfig, ok); err != nil { - return err - } - } - - if v.Comment != nil { - ok := object.Key("Comment") - ok.String(*v.Comment) - } - - if v.DocumentHash != nil { - ok := object.Key("DocumentHash") - ok.String(*v.DocumentHash) - } - - if len(v.DocumentHashType) > 0 { - ok := object.Key("DocumentHashType") - ok.String(string(v.DocumentHashType)) - } - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.NotificationConfig != nil { - ok := object.Key("NotificationConfig") - if err := awsAwsjson11_serializeDocumentNotificationConfig(v.NotificationConfig, ok); err != nil { - return err - } - } - - if v.OutputS3BucketName != nil { - ok := object.Key("OutputS3BucketName") - ok.String(*v.OutputS3BucketName) - } - - if v.OutputS3KeyPrefix != nil { - ok := object.Key("OutputS3KeyPrefix") - ok.String(*v.OutputS3KeyPrefix) - } - - if v.Parameters != nil { - ok := object.Key("Parameters") - if err := awsAwsjson11_serializeDocumentParameters(v.Parameters, ok); err != nil { - return err - } - } - - if v.ServiceRoleArn != nil { - ok := object.Key("ServiceRoleArn") - ok.String(*v.ServiceRoleArn) - } - - if v.TimeoutSeconds != nil { - ok := object.Key("TimeoutSeconds") - ok.Integer(*v.TimeoutSeconds) - } - - return nil -} - -func awsAwsjson11_serializeDocumentMaintenanceWindowStepFunctionsParameters(v *types.MaintenanceWindowStepFunctionsParameters, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Input != nil { - ok := object.Key("Input") - ok.String(*v.Input) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - return nil -} - -func awsAwsjson11_serializeDocumentMaintenanceWindowTaskInvocationParameters(v *types.MaintenanceWindowTaskInvocationParameters, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Automation != nil { - ok := object.Key("Automation") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowAutomationParameters(v.Automation, ok); err != nil { - return err - } - } - - if v.Lambda != nil { - ok := object.Key("Lambda") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowLambdaParameters(v.Lambda, ok); err != nil { - return err - } - } - - if v.RunCommand != nil { - ok := object.Key("RunCommand") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowRunCommandParameters(v.RunCommand, ok); err != nil { - return err - } - } - - if v.StepFunctions != nil { - ok := object.Key("StepFunctions") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowStepFunctionsParameters(v.StepFunctions, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentMaintenanceWindowTaskParameters(v map[string]types.MaintenanceWindowTaskParameterValueExpression, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - for key := range v { - om := object.Key(key) - mapVar := v[key] - if err := awsAwsjson11_serializeDocumentMaintenanceWindowTaskParameterValueExpression(&mapVar, om); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentMaintenanceWindowTaskParameterValueExpression(v *types.MaintenanceWindowTaskParameterValueExpression, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowTaskParameterValueList(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentMaintenanceWindowTaskParameterValueList(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_serializeDocumentMetadataKeysToDeleteList(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_serializeDocumentMetadataMap(v map[string]types.MetadataValue, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - for key := range v { - om := object.Key(key) - mapVar := v[key] - if err := awsAwsjson11_serializeDocumentMetadataValue(&mapVar, om); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentMetadataValue(v *types.MetadataValue, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Value != nil { - ok := object.Key("Value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeDocumentNotificationConfig(v *types.NotificationConfig, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.NotificationArn != nil { - ok := object.Key("NotificationArn") - ok.String(*v.NotificationArn) - } - - if v.NotificationEvents != nil { - ok := object.Key("NotificationEvents") - if err := awsAwsjson11_serializeDocumentNotificationEventList(v.NotificationEvents, ok); err != nil { - return err - } - } - - if len(v.NotificationType) > 0 { - ok := object.Key("NotificationType") - ok.String(string(v.NotificationType)) - } - - return nil -} - -func awsAwsjson11_serializeDocumentNotificationEventList(v []types.NotificationEvent, 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_serializeDocumentOpsAggregator(v *types.OpsAggregator, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Aggregators != nil { - ok := object.Key("Aggregators") - if err := awsAwsjson11_serializeDocumentOpsAggregatorList(v.Aggregators, ok); err != nil { - return err - } - } - - if v.AggregatorType != nil { - ok := object.Key("AggregatorType") - ok.String(*v.AggregatorType) - } - - if v.AttributeName != nil { - ok := object.Key("AttributeName") - ok.String(*v.AttributeName) - } - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentOpsFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.TypeName != nil { - ok := object.Key("TypeName") - ok.String(*v.TypeName) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentOpsAggregatorValueMap(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentOpsAggregatorList(v []types.OpsAggregator, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentOpsAggregator(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentOpsAggregatorValueMap(v map[string]string, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - for key := range v { - om := object.Key(key) - om.String(v[key]) - } - return nil -} - -func awsAwsjson11_serializeDocumentOpsFilter(v *types.OpsFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if len(v.Type) > 0 { - ok := object.Key("Type") - ok.String(string(v.Type)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentOpsFilterValueList(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentOpsFilterList(v []types.OpsFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentOpsFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentOpsFilterValueList(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_serializeDocumentOpsItemDataValue(v *types.OpsItemDataValue, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Type) > 0 { - ok := object.Key("Type") - ok.String(string(v.Type)) - } - - if v.Value != nil { - ok := object.Key("Value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeDocumentOpsItemEventFilter(v *types.OpsItemEventFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("Key") - ok.String(string(v.Key)) - } - - if len(v.Operator) > 0 { - ok := object.Key("Operator") - ok.String(string(v.Operator)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentOpsItemEventFilterValues(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentOpsItemEventFilters(v []types.OpsItemEventFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentOpsItemEventFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentOpsItemEventFilterValues(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_serializeDocumentOpsItemFilter(v *types.OpsItemFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("Key") - ok.String(string(v.Key)) - } - - if len(v.Operator) > 0 { - ok := object.Key("Operator") - ok.String(string(v.Operator)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentOpsItemFilterValues(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentOpsItemFilters(v []types.OpsItemFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentOpsItemFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentOpsItemFilterValues(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_serializeDocumentOpsItemNotification(v *types.OpsItemNotification, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Arn != nil { - ok := object.Key("Arn") - ok.String(*v.Arn) - } - - return nil -} - -func awsAwsjson11_serializeDocumentOpsItemNotifications(v []types.OpsItemNotification, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentOpsItemNotification(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentOpsItemOperationalData(v map[string]types.OpsItemDataValue, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - for key := range v { - om := object.Key(key) - mapVar := v[key] - if err := awsAwsjson11_serializeDocumentOpsItemDataValue(&mapVar, om); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentOpsItemOpsDataKeysList(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_serializeDocumentOpsItemRelatedItemsFilter(v *types.OpsItemRelatedItemsFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("Key") - ok.String(string(v.Key)) - } - - if len(v.Operator) > 0 { - ok := object.Key("Operator") - ok.String(string(v.Operator)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentOpsItemRelatedItemsFilterValues(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentOpsItemRelatedItemsFilters(v []types.OpsItemRelatedItemsFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentOpsItemRelatedItemsFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentOpsItemRelatedItemsFilterValues(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_serializeDocumentOpsMetadataFilter(v *types.OpsMetadataFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentOpsMetadataFilterValueList(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentOpsMetadataFilterList(v []types.OpsMetadataFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentOpsMetadataFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentOpsMetadataFilterValueList(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_serializeDocumentOpsResultAttribute(v *types.OpsResultAttribute, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.TypeName != nil { - ok := object.Key("TypeName") - ok.String(*v.TypeName) - } - - return nil -} - -func awsAwsjson11_serializeDocumentOpsResultAttributeList(v []types.OpsResultAttribute, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentOpsResultAttribute(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentParameterLabelList(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_serializeDocumentParameterNameList(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_serializeDocumentParameters(v map[string][]string, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - for key := range v { - om := object.Key(key) - if vv := v[key]; vv == nil { - continue - } - if err := awsAwsjson11_serializeDocumentParameterValueList(v[key], om); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentParametersFilter(v *types.ParametersFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("Key") - ok.String(string(v.Key)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentParametersFilterValueList(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentParametersFilterList(v []types.ParametersFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentParametersFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentParametersFilterValueList(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_serializeDocumentParameterStringFilter(v *types.ParameterStringFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if v.Option != nil { - ok := object.Key("Option") - ok.String(*v.Option) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentParameterStringFilterValueList(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentParameterStringFilterList(v []types.ParameterStringFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentParameterStringFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentParameterStringFilterValueList(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_serializeDocumentParameterValueList(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_serializeDocumentPatchFilter(v *types.PatchFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("Key") - ok.String(string(v.Key)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentPatchFilterValueList(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentPatchFilterGroup(v *types.PatchFilterGroup, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.PatchFilters != nil { - ok := object.Key("PatchFilters") - if err := awsAwsjson11_serializeDocumentPatchFilterList(v.PatchFilters, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentPatchFilterList(v []types.PatchFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentPatchFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentPatchFilterValueList(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_serializeDocumentPatchIdList(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_serializeDocumentPatchOrchestratorFilter(v *types.PatchOrchestratorFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentPatchOrchestratorFilterValues(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentPatchOrchestratorFilterList(v []types.PatchOrchestratorFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentPatchOrchestratorFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentPatchOrchestratorFilterValues(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_serializeDocumentPatchRule(v *types.PatchRule, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ApproveAfterDays != nil { - ok := object.Key("ApproveAfterDays") - ok.Integer(*v.ApproveAfterDays) - } - - if v.ApproveUntilDate != nil { - ok := object.Key("ApproveUntilDate") - ok.String(*v.ApproveUntilDate) - } - - if len(v.ComplianceLevel) > 0 { - ok := object.Key("ComplianceLevel") - ok.String(string(v.ComplianceLevel)) - } - - if v.EnableNonSecurity != nil { - ok := object.Key("EnableNonSecurity") - ok.Boolean(*v.EnableNonSecurity) - } - - if v.PatchFilterGroup != nil { - ok := object.Key("PatchFilterGroup") - if err := awsAwsjson11_serializeDocumentPatchFilterGroup(v.PatchFilterGroup, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentPatchRuleGroup(v *types.PatchRuleGroup, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.PatchRules != nil { - ok := object.Key("PatchRules") - if err := awsAwsjson11_serializeDocumentPatchRuleList(v.PatchRules, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentPatchRuleList(v []types.PatchRule, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentPatchRule(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentPatchSource(v *types.PatchSource, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Configuration != nil { - ok := object.Key("Configuration") - ok.String(*v.Configuration) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.Products != nil { - ok := object.Key("Products") - if err := awsAwsjson11_serializeDocumentPatchSourceProductList(v.Products, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentPatchSourceList(v []types.PatchSource, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentPatchSource(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentPatchSourceProductList(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_serializeDocumentRegions(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_serializeDocumentRegistrationMetadataItem(v *types.RegistrationMetadataItem, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if v.Value != nil { - ok := object.Key("Value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeDocumentRegistrationMetadataList(v []types.RegistrationMetadataItem, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentRegistrationMetadataItem(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentRelatedOpsItem(v *types.RelatedOpsItem, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.OpsItemId != nil { - ok := object.Key("OpsItemId") - ok.String(*v.OpsItemId) - } - - return nil -} - -func awsAwsjson11_serializeDocumentRelatedOpsItems(v []types.RelatedOpsItem, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentRelatedOpsItem(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentResourceDataSyncAwsOrganizationsSource(v *types.ResourceDataSyncAwsOrganizationsSource, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.OrganizationalUnits != nil { - ok := object.Key("OrganizationalUnits") - if err := awsAwsjson11_serializeDocumentResourceDataSyncOrganizationalUnitList(v.OrganizationalUnits, ok); err != nil { - return err - } - } - - if v.OrganizationSourceType != nil { - ok := object.Key("OrganizationSourceType") - ok.String(*v.OrganizationSourceType) - } - - return nil -} - -func awsAwsjson11_serializeDocumentResourceDataSyncDestinationDataSharing(v *types.ResourceDataSyncDestinationDataSharing, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DestinationDataSharingType != nil { - ok := object.Key("DestinationDataSharingType") - ok.String(*v.DestinationDataSharingType) - } - - return nil -} - -func awsAwsjson11_serializeDocumentResourceDataSyncOrganizationalUnit(v *types.ResourceDataSyncOrganizationalUnit, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.OrganizationalUnitId != nil { - ok := object.Key("OrganizationalUnitId") - ok.String(*v.OrganizationalUnitId) - } - - return nil -} - -func awsAwsjson11_serializeDocumentResourceDataSyncOrganizationalUnitList(v []types.ResourceDataSyncOrganizationalUnit, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentResourceDataSyncOrganizationalUnit(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentResourceDataSyncS3Destination(v *types.ResourceDataSyncS3Destination, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AWSKMSKeyARN != nil { - ok := object.Key("AWSKMSKeyARN") - ok.String(*v.AWSKMSKeyARN) - } - - if v.BucketName != nil { - ok := object.Key("BucketName") - ok.String(*v.BucketName) - } - - if v.DestinationDataSharing != nil { - ok := object.Key("DestinationDataSharing") - if err := awsAwsjson11_serializeDocumentResourceDataSyncDestinationDataSharing(v.DestinationDataSharing, ok); err != nil { - return err - } - } - - if v.Prefix != nil { - ok := object.Key("Prefix") - ok.String(*v.Prefix) - } - - if v.Region != nil { - ok := object.Key("Region") - ok.String(*v.Region) - } - - if len(v.SyncFormat) > 0 { - ok := object.Key("SyncFormat") - ok.String(string(v.SyncFormat)) - } - - return nil -} - -func awsAwsjson11_serializeDocumentResourceDataSyncSource(v *types.ResourceDataSyncSource, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AwsOrganizationsSource != nil { - ok := object.Key("AwsOrganizationsSource") - if err := awsAwsjson11_serializeDocumentResourceDataSyncAwsOrganizationsSource(v.AwsOrganizationsSource, ok); err != nil { - return err - } - } - - if v.EnableAllOpsDataSources { - ok := object.Key("EnableAllOpsDataSources") - ok.Boolean(v.EnableAllOpsDataSources) - } - - if v.IncludeFutureRegions { - ok := object.Key("IncludeFutureRegions") - ok.Boolean(v.IncludeFutureRegions) - } - - if v.SourceRegions != nil { - ok := object.Key("SourceRegions") - if err := awsAwsjson11_serializeDocumentResourceDataSyncSourceRegionList(v.SourceRegions, ok); err != nil { - return err - } - } - - if v.SourceType != nil { - ok := object.Key("SourceType") - ok.String(*v.SourceType) - } - - return nil -} - -func awsAwsjson11_serializeDocumentResourceDataSyncSourceRegionList(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_serializeDocumentResultAttribute(v *types.ResultAttribute, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.TypeName != nil { - ok := object.Key("TypeName") - ok.String(*v.TypeName) - } - - return nil -} - -func awsAwsjson11_serializeDocumentResultAttributeList(v []types.ResultAttribute, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentResultAttribute(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentRunbook(v *types.Runbook, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DocumentName != nil { - ok := object.Key("DocumentName") - ok.String(*v.DocumentName) - } - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.MaxConcurrency != nil { - ok := object.Key("MaxConcurrency") - ok.String(*v.MaxConcurrency) - } - - if v.MaxErrors != nil { - ok := object.Key("MaxErrors") - ok.String(*v.MaxErrors) - } - - if v.Parameters != nil { - ok := object.Key("Parameters") - if err := awsAwsjson11_serializeDocumentAutomationParameterMap(v.Parameters, ok); err != nil { - return err - } - } - - if v.TargetLocations != nil { - ok := object.Key("TargetLocations") - if err := awsAwsjson11_serializeDocumentTargetLocations(v.TargetLocations, ok); err != nil { - return err - } - } - - if v.TargetMaps != nil { - ok := object.Key("TargetMaps") - if err := awsAwsjson11_serializeDocumentTargetMaps(v.TargetMaps, ok); err != nil { - return err - } - } - - if v.TargetParameterName != nil { - ok := object.Key("TargetParameterName") - ok.String(*v.TargetParameterName) - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentRunbooks(v []types.Runbook, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentRunbook(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentS3OutputLocation(v *types.S3OutputLocation, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.OutputS3BucketName != nil { - ok := object.Key("OutputS3BucketName") - ok.String(*v.OutputS3BucketName) - } - - if v.OutputS3KeyPrefix != nil { - ok := object.Key("OutputS3KeyPrefix") - ok.String(*v.OutputS3KeyPrefix) - } - - if v.OutputS3Region != nil { - ok := object.Key("OutputS3Region") - ok.String(*v.OutputS3Region) - } - - return nil -} - -func awsAwsjson11_serializeDocumentSessionFilter(v *types.SessionFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("key") - ok.String(string(v.Key)) - } - - if v.Value != nil { - ok := object.Key("value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeDocumentSessionFilterList(v []types.SessionFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentSessionFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentSessionManagerParameters(v map[string][]string, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - for key := range v { - om := object.Key(key) - if vv := v[key]; vv == nil { - continue - } - if err := awsAwsjson11_serializeDocumentSessionManagerParameterValueList(v[key], om); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentSessionManagerParameterValueList(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_serializeDocumentStepExecutionFilter(v *types.StepExecutionFilter, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.Key) > 0 { - ok := object.Key("Key") - ok.String(string(v.Key)) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentStepExecutionFilterValueList(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentStepExecutionFilterList(v []types.StepExecutionFilter, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentStepExecutionFilter(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentStepExecutionFilterValueList(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_serializeDocumentStringList(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_serializeDocumentTag(v *types.Tag, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if v.Value != nil { - ok := object.Key("Value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeDocumentTagList(v []types.Tag, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentTag(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentTarget(v *types.Target, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Key != nil { - ok := object.Key("Key") - ok.String(*v.Key) - } - - if v.Values != nil { - ok := object.Key("Values") - if err := awsAwsjson11_serializeDocumentTargetValues(v.Values, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeDocumentTargetLocation(v *types.TargetLocation, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Accounts != nil { - ok := object.Key("Accounts") - if err := awsAwsjson11_serializeDocumentAccounts(v.Accounts, ok); err != nil { - return err - } - } - - if v.ExecutionRoleName != nil { - ok := object.Key("ExecutionRoleName") - ok.String(*v.ExecutionRoleName) - } - - if v.Regions != nil { - ok := object.Key("Regions") - if err := awsAwsjson11_serializeDocumentRegions(v.Regions, ok); err != nil { - return err - } - } - - if v.TargetLocationAlarmConfiguration != nil { - ok := object.Key("TargetLocationAlarmConfiguration") - if err := awsAwsjson11_serializeDocumentAlarmConfiguration(v.TargetLocationAlarmConfiguration, ok); err != nil { - return err - } - } - - if v.TargetLocationMaxConcurrency != nil { - ok := object.Key("TargetLocationMaxConcurrency") - ok.String(*v.TargetLocationMaxConcurrency) - } - - if v.TargetLocationMaxErrors != nil { - ok := object.Key("TargetLocationMaxErrors") - ok.String(*v.TargetLocationMaxErrors) - } - - return nil -} - -func awsAwsjson11_serializeDocumentTargetLocations(v []types.TargetLocation, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentTargetLocation(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentTargetMap(v map[string][]string, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - for key := range v { - om := object.Key(key) - if vv := v[key]; vv == nil { - continue - } - if err := awsAwsjson11_serializeDocumentTargetMapValueList(v[key], om); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentTargetMaps(v []map[string][]string, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if vv := v[i]; vv == nil { - continue - } - if err := awsAwsjson11_serializeDocumentTargetMap(v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentTargetMapValueList(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_serializeDocumentTargets(v []types.Target, value smithyjson.Value) error { - array := value.Array() - defer array.Close() - - for i := range v { - av := array.Value() - if err := awsAwsjson11_serializeDocumentTarget(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsjson11_serializeDocumentTargetValues(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_serializeOpDocumentAddTagsToResourceInput(v *AddTagsToResourceInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ResourceId != nil { - ok := object.Key("ResourceId") - ok.String(*v.ResourceId) - } - - if len(v.ResourceType) > 0 { - ok := object.Key("ResourceType") - ok.String(string(v.ResourceType)) - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagList(v.Tags, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentAssociateOpsItemRelatedItemInput(v *AssociateOpsItemRelatedItemInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AssociationType != nil { - ok := object.Key("AssociationType") - ok.String(*v.AssociationType) - } - - if v.OpsItemId != nil { - ok := object.Key("OpsItemId") - ok.String(*v.OpsItemId) - } - - if v.ResourceType != nil { - ok := object.Key("ResourceType") - ok.String(*v.ResourceType) - } - - if v.ResourceUri != nil { - ok := object.Key("ResourceUri") - ok.String(*v.ResourceUri) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCancelCommandInput(v *CancelCommandInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.CommandId != nil { - ok := object.Key("CommandId") - ok.String(*v.CommandId) - } - - if v.InstanceIds != nil { - ok := object.Key("InstanceIds") - if err := awsAwsjson11_serializeDocumentInstanceIdList(v.InstanceIds, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCancelMaintenanceWindowExecutionInput(v *CancelMaintenanceWindowExecutionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.WindowExecutionId != nil { - ok := object.Key("WindowExecutionId") - ok.String(*v.WindowExecutionId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCreateActivationInput(v *CreateActivationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DefaultInstanceName != nil { - ok := object.Key("DefaultInstanceName") - ok.String(*v.DefaultInstanceName) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.ExpirationDate != nil { - ok := object.Key("ExpirationDate") - ok.Double(smithytime.FormatEpochSeconds(*v.ExpirationDate)) - } - - if v.IamRole != nil { - ok := object.Key("IamRole") - ok.String(*v.IamRole) - } - - if v.RegistrationLimit != nil { - ok := object.Key("RegistrationLimit") - ok.Integer(*v.RegistrationLimit) - } - - if v.RegistrationMetadata != nil { - ok := object.Key("RegistrationMetadata") - if err := awsAwsjson11_serializeDocumentRegistrationMetadataList(v.RegistrationMetadata, ok); err != nil { - return err - } - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagList(v.Tags, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCreateAssociationBatchInput(v *CreateAssociationBatchInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Entries != nil { - ok := object.Key("Entries") - if err := awsAwsjson11_serializeDocumentCreateAssociationBatchRequestEntries(v.Entries, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCreateAssociationInput(v *CreateAssociationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AlarmConfiguration != nil { - ok := object.Key("AlarmConfiguration") - if err := awsAwsjson11_serializeDocumentAlarmConfiguration(v.AlarmConfiguration, ok); err != nil { - return err - } - } - - if v.ApplyOnlyAtCronInterval { - ok := object.Key("ApplyOnlyAtCronInterval") - ok.Boolean(v.ApplyOnlyAtCronInterval) - } - - if v.AssociationName != nil { - ok := object.Key("AssociationName") - ok.String(*v.AssociationName) - } - - if v.AutomationTargetParameterName != nil { - ok := object.Key("AutomationTargetParameterName") - ok.String(*v.AutomationTargetParameterName) - } - - if v.CalendarNames != nil { - ok := object.Key("CalendarNames") - if err := awsAwsjson11_serializeDocumentCalendarNameOrARNList(v.CalendarNames, ok); err != nil { - return err - } - } - - if len(v.ComplianceSeverity) > 0 { - ok := object.Key("ComplianceSeverity") - ok.String(string(v.ComplianceSeverity)) - } - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.MaxConcurrency != nil { - ok := object.Key("MaxConcurrency") - ok.String(*v.MaxConcurrency) - } - - if v.MaxErrors != nil { - ok := object.Key("MaxErrors") - ok.String(*v.MaxErrors) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.OutputLocation != nil { - ok := object.Key("OutputLocation") - if err := awsAwsjson11_serializeDocumentInstanceAssociationOutputLocation(v.OutputLocation, ok); err != nil { - return err - } - } - - if v.Parameters != nil { - ok := object.Key("Parameters") - if err := awsAwsjson11_serializeDocumentParameters(v.Parameters, ok); err != nil { - return err - } - } - - if v.ScheduleExpression != nil { - ok := object.Key("ScheduleExpression") - ok.String(*v.ScheduleExpression) - } - - if v.ScheduleOffset != nil { - ok := object.Key("ScheduleOffset") - ok.Integer(*v.ScheduleOffset) - } - - if len(v.SyncCompliance) > 0 { - ok := object.Key("SyncCompliance") - ok.String(string(v.SyncCompliance)) - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagList(v.Tags, ok); err != nil { - return err - } - } - - if v.TargetLocations != nil { - ok := object.Key("TargetLocations") - if err := awsAwsjson11_serializeDocumentTargetLocations(v.TargetLocations, ok); err != nil { - return err - } - } - - if v.TargetMaps != nil { - ok := object.Key("TargetMaps") - if err := awsAwsjson11_serializeDocumentTargetMaps(v.TargetMaps, ok); err != nil { - return err - } - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCreateDocumentInput(v *CreateDocumentInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Attachments != nil { - ok := object.Key("Attachments") - if err := awsAwsjson11_serializeDocumentAttachmentsSourceList(v.Attachments, ok); err != nil { - return err - } - } - - if v.Content != nil { - ok := object.Key("Content") - ok.String(*v.Content) - } - - if v.DisplayName != nil { - ok := object.Key("DisplayName") - ok.String(*v.DisplayName) - } - - if len(v.DocumentFormat) > 0 { - ok := object.Key("DocumentFormat") - ok.String(string(v.DocumentFormat)) - } - - if len(v.DocumentType) > 0 { - ok := object.Key("DocumentType") - ok.String(string(v.DocumentType)) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.Requires != nil { - ok := object.Key("Requires") - if err := awsAwsjson11_serializeDocumentDocumentRequiresList(v.Requires, ok); err != nil { - return err - } - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagList(v.Tags, ok); err != nil { - return err - } - } - - if v.TargetType != nil { - ok := object.Key("TargetType") - ok.String(*v.TargetType) - } - - if v.VersionName != nil { - ok := object.Key("VersionName") - ok.String(*v.VersionName) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCreateMaintenanceWindowInput(v *CreateMaintenanceWindowInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - { - ok := object.Key("AllowUnassociatedTargets") - ok.Boolean(v.AllowUnassociatedTargets) - } - - if v.ClientToken != nil { - ok := object.Key("ClientToken") - ok.String(*v.ClientToken) - } - - { - ok := object.Key("Cutoff") - ok.Integer(v.Cutoff) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.Duration != nil { - ok := object.Key("Duration") - ok.Integer(*v.Duration) - } - - if v.EndDate != nil { - ok := object.Key("EndDate") - ok.String(*v.EndDate) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.Schedule != nil { - ok := object.Key("Schedule") - ok.String(*v.Schedule) - } - - if v.ScheduleOffset != nil { - ok := object.Key("ScheduleOffset") - ok.Integer(*v.ScheduleOffset) - } - - if v.ScheduleTimezone != nil { - ok := object.Key("ScheduleTimezone") - ok.String(*v.ScheduleTimezone) - } - - if v.StartDate != nil { - ok := object.Key("StartDate") - ok.String(*v.StartDate) - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagList(v.Tags, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCreateOpsItemInput(v *CreateOpsItemInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AccountId != nil { - ok := object.Key("AccountId") - ok.String(*v.AccountId) - } - - if v.ActualEndTime != nil { - ok := object.Key("ActualEndTime") - ok.Double(smithytime.FormatEpochSeconds(*v.ActualEndTime)) - } - - if v.ActualStartTime != nil { - ok := object.Key("ActualStartTime") - ok.Double(smithytime.FormatEpochSeconds(*v.ActualStartTime)) - } - - if v.Category != nil { - ok := object.Key("Category") - ok.String(*v.Category) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.Notifications != nil { - ok := object.Key("Notifications") - if err := awsAwsjson11_serializeDocumentOpsItemNotifications(v.Notifications, ok); err != nil { - return err - } - } - - if v.OperationalData != nil { - ok := object.Key("OperationalData") - if err := awsAwsjson11_serializeDocumentOpsItemOperationalData(v.OperationalData, ok); err != nil { - return err - } - } - - if v.OpsItemType != nil { - ok := object.Key("OpsItemType") - ok.String(*v.OpsItemType) - } - - if v.PlannedEndTime != nil { - ok := object.Key("PlannedEndTime") - ok.Double(smithytime.FormatEpochSeconds(*v.PlannedEndTime)) - } - - if v.PlannedStartTime != nil { - ok := object.Key("PlannedStartTime") - ok.Double(smithytime.FormatEpochSeconds(*v.PlannedStartTime)) - } - - if v.Priority != nil { - ok := object.Key("Priority") - ok.Integer(*v.Priority) - } - - if v.RelatedOpsItems != nil { - ok := object.Key("RelatedOpsItems") - if err := awsAwsjson11_serializeDocumentRelatedOpsItems(v.RelatedOpsItems, ok); err != nil { - return err - } - } - - if v.Severity != nil { - ok := object.Key("Severity") - ok.String(*v.Severity) - } - - if v.Source != nil { - ok := object.Key("Source") - ok.String(*v.Source) - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagList(v.Tags, ok); err != nil { - return err - } - } - - if v.Title != nil { - ok := object.Key("Title") - ok.String(*v.Title) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCreateOpsMetadataInput(v *CreateOpsMetadataInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Metadata != nil { - ok := object.Key("Metadata") - if err := awsAwsjson11_serializeDocumentMetadataMap(v.Metadata, ok); err != nil { - return err - } - } - - if v.ResourceId != nil { - ok := object.Key("ResourceId") - ok.String(*v.ResourceId) - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagList(v.Tags, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCreatePatchBaselineInput(v *CreatePatchBaselineInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ApprovalRules != nil { - ok := object.Key("ApprovalRules") - if err := awsAwsjson11_serializeDocumentPatchRuleGroup(v.ApprovalRules, ok); err != nil { - return err - } - } - - if v.ApprovedPatches != nil { - ok := object.Key("ApprovedPatches") - if err := awsAwsjson11_serializeDocumentPatchIdList(v.ApprovedPatches, ok); err != nil { - return err - } - } - - if len(v.ApprovedPatchesComplianceLevel) > 0 { - ok := object.Key("ApprovedPatchesComplianceLevel") - ok.String(string(v.ApprovedPatchesComplianceLevel)) - } - - if v.ApprovedPatchesEnableNonSecurity != nil { - ok := object.Key("ApprovedPatchesEnableNonSecurity") - ok.Boolean(*v.ApprovedPatchesEnableNonSecurity) - } - - if v.ClientToken != nil { - ok := object.Key("ClientToken") - ok.String(*v.ClientToken) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.GlobalFilters != nil { - ok := object.Key("GlobalFilters") - if err := awsAwsjson11_serializeDocumentPatchFilterGroup(v.GlobalFilters, ok); err != nil { - return err - } - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if len(v.OperatingSystem) > 0 { - ok := object.Key("OperatingSystem") - ok.String(string(v.OperatingSystem)) - } - - if v.RejectedPatches != nil { - ok := object.Key("RejectedPatches") - if err := awsAwsjson11_serializeDocumentPatchIdList(v.RejectedPatches, ok); err != nil { - return err - } - } - - if len(v.RejectedPatchesAction) > 0 { - ok := object.Key("RejectedPatchesAction") - ok.String(string(v.RejectedPatchesAction)) - } - - if v.Sources != nil { - ok := object.Key("Sources") - if err := awsAwsjson11_serializeDocumentPatchSourceList(v.Sources, ok); err != nil { - return err - } - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagList(v.Tags, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentCreateResourceDataSyncInput(v *CreateResourceDataSyncInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.S3Destination != nil { - ok := object.Key("S3Destination") - if err := awsAwsjson11_serializeDocumentResourceDataSyncS3Destination(v.S3Destination, ok); err != nil { - return err - } - } - - if v.SyncName != nil { - ok := object.Key("SyncName") - ok.String(*v.SyncName) - } - - if v.SyncSource != nil { - ok := object.Key("SyncSource") - if err := awsAwsjson11_serializeDocumentResourceDataSyncSource(v.SyncSource, ok); err != nil { - return err - } - } - - if v.SyncType != nil { - ok := object.Key("SyncType") - ok.String(*v.SyncType) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteActivationInput(v *DeleteActivationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ActivationId != nil { - ok := object.Key("ActivationId") - ok.String(*v.ActivationId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteAssociationInput(v *DeleteAssociationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AssociationId != nil { - ok := object.Key("AssociationId") - ok.String(*v.AssociationId) - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteDocumentInput(v *DeleteDocumentInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.Force { - ok := object.Key("Force") - ok.Boolean(v.Force) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.VersionName != nil { - ok := object.Key("VersionName") - ok.String(*v.VersionName) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteInventoryInput(v *DeleteInventoryInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientToken != nil { - ok := object.Key("ClientToken") - ok.String(*v.ClientToken) - } - - if v.DryRun { - ok := object.Key("DryRun") - ok.Boolean(v.DryRun) - } - - if len(v.SchemaDeleteOption) > 0 { - ok := object.Key("SchemaDeleteOption") - ok.String(string(v.SchemaDeleteOption)) - } - - if v.TypeName != nil { - ok := object.Key("TypeName") - ok.String(*v.TypeName) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteMaintenanceWindowInput(v *DeleteMaintenanceWindowInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteOpsItemInput(v *DeleteOpsItemInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.OpsItemId != nil { - ok := object.Key("OpsItemId") - ok.String(*v.OpsItemId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteOpsMetadataInput(v *DeleteOpsMetadataInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.OpsMetadataArn != nil { - ok := object.Key("OpsMetadataArn") - ok.String(*v.OpsMetadataArn) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteParameterInput(v *DeleteParameterInput, 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_serializeOpDocumentDeleteParametersInput(v *DeleteParametersInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Names != nil { - ok := object.Key("Names") - if err := awsAwsjson11_serializeDocumentParameterNameList(v.Names, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeletePatchBaselineInput(v *DeletePatchBaselineInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.BaselineId != nil { - ok := object.Key("BaselineId") - ok.String(*v.BaselineId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteResourceDataSyncInput(v *DeleteResourceDataSyncInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SyncName != nil { - ok := object.Key("SyncName") - ok.String(*v.SyncName) - } - - if v.SyncType != nil { - ok := object.Key("SyncType") - ok.String(*v.SyncType) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeleteResourcePolicyInput(v *DeleteResourcePolicyInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.PolicyHash != nil { - ok := object.Key("PolicyHash") - ok.String(*v.PolicyHash) - } - - if v.PolicyId != nil { - ok := object.Key("PolicyId") - ok.String(*v.PolicyId) - } - - if v.ResourceArn != nil { - ok := object.Key("ResourceArn") - ok.String(*v.ResourceArn) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeregisterManagedInstanceInput(v *DeregisterManagedInstanceInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeregisterPatchBaselineForPatchGroupInput(v *DeregisterPatchBaselineForPatchGroupInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.BaselineId != nil { - ok := object.Key("BaselineId") - ok.String(*v.BaselineId) - } - - if v.PatchGroup != nil { - ok := object.Key("PatchGroup") - ok.String(*v.PatchGroup) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeregisterTargetFromMaintenanceWindowInput(v *DeregisterTargetFromMaintenanceWindowInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Safe != nil { - ok := object.Key("Safe") - ok.Boolean(*v.Safe) - } - - if v.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - if v.WindowTargetId != nil { - ok := object.Key("WindowTargetId") - ok.String(*v.WindowTargetId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDeregisterTaskFromMaintenanceWindowInput(v *DeregisterTaskFromMaintenanceWindowInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - if v.WindowTaskId != nil { - ok := object.Key("WindowTaskId") - ok.String(*v.WindowTaskId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeActivationsInput(v *DescribeActivationsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentDescribeActivationsFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeAssociationExecutionsInput(v *DescribeAssociationExecutionsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AssociationId != nil { - ok := object.Key("AssociationId") - ok.String(*v.AssociationId) - } - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentAssociationExecutionFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeAssociationExecutionTargetsInput(v *DescribeAssociationExecutionTargetsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AssociationId != nil { - ok := object.Key("AssociationId") - ok.String(*v.AssociationId) - } - - if v.ExecutionId != nil { - ok := object.Key("ExecutionId") - ok.String(*v.ExecutionId) - } - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentAssociationExecutionTargetsFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeAssociationInput(v *DescribeAssociationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AssociationId != nil { - ok := object.Key("AssociationId") - ok.String(*v.AssociationId) - } - - if v.AssociationVersion != nil { - ok := object.Key("AssociationVersion") - ok.String(*v.AssociationVersion) - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeAutomationExecutionsInput(v *DescribeAutomationExecutionsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentAutomationExecutionFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeAutomationStepExecutionsInput(v *DescribeAutomationStepExecutionsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AutomationExecutionId != nil { - ok := object.Key("AutomationExecutionId") - ok.String(*v.AutomationExecutionId) - } - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentStepExecutionFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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.ReverseOrder != nil { - ok := object.Key("ReverseOrder") - ok.Boolean(*v.ReverseOrder) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeAvailablePatchesInput(v *DescribeAvailablePatchesInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentPatchOrchestratorFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeDocumentInput(v *DescribeDocumentInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.VersionName != nil { - ok := object.Key("VersionName") - ok.String(*v.VersionName) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeDocumentPermissionInput(v *DescribeDocumentPermissionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - if len(v.PermissionType) > 0 { - ok := object.Key("PermissionType") - ok.String(string(v.PermissionType)) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeEffectiveInstanceAssociationsInput(v *DescribeEffectiveInstanceAssociationsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeEffectivePatchesForPatchBaselineInput(v *DescribeEffectivePatchesForPatchBaselineInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.BaselineId != nil { - ok := object.Key("BaselineId") - ok.String(*v.BaselineId) - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeInstanceAssociationsStatusInput(v *DescribeInstanceAssociationsStatusInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeInstanceInformationInput(v *DescribeInstanceInformationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentInstanceInformationStringFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.InstanceInformationFilterList != nil { - ok := object.Key("InstanceInformationFilterList") - if err := awsAwsjson11_serializeDocumentInstanceInformationFilterList(v.InstanceInformationFilterList, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeInstancePatchesInput(v *DescribeInstancePatchesInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentPatchOrchestratorFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeInstancePatchStatesForPatchGroupInput(v *DescribeInstancePatchStatesForPatchGroupInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentInstancePatchStateFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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.PatchGroup != nil { - ok := object.Key("PatchGroup") - ok.String(*v.PatchGroup) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeInstancePatchStatesInput(v *DescribeInstancePatchStatesInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.InstanceIds != nil { - ok := object.Key("InstanceIds") - if err := awsAwsjson11_serializeDocumentInstanceIdList(v.InstanceIds, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeInventoryDeletionsInput(v *DescribeInventoryDeletionsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DeletionId != nil { - ok := object.Key("DeletionId") - ok.String(*v.DeletionId) - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowExecutionsInput(v *DescribeMaintenanceWindowExecutionsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowExecutionTaskInvocationsInput(v *DescribeMaintenanceWindowExecutionTaskInvocationsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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.TaskId != nil { - ok := object.Key("TaskId") - ok.String(*v.TaskId) - } - - if v.WindowExecutionId != nil { - ok := object.Key("WindowExecutionId") - ok.String(*v.WindowExecutionId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowExecutionTasksInput(v *DescribeMaintenanceWindowExecutionTasksInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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.WindowExecutionId != nil { - ok := object.Key("WindowExecutionId") - ok.String(*v.WindowExecutionId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowScheduleInput(v *DescribeMaintenanceWindowScheduleInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentPatchOrchestratorFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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 len(v.ResourceType) > 0 { - ok := object.Key("ResourceType") - ok.String(string(v.ResourceType)) - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - if v.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowsForTargetInput(v *DescribeMaintenanceWindowsForTargetInput, 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 len(v.ResourceType) > 0 { - ok := object.Key("ResourceType") - ok.String(string(v.ResourceType)) - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowsInput(v *DescribeMaintenanceWindowsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowTargetsInput(v *DescribeMaintenanceWindowTargetsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeMaintenanceWindowTasksInput(v *DescribeMaintenanceWindowTasksInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeOpsItemsInput(v *DescribeOpsItemsInput, 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.OpsItemFilters != nil { - ok := object.Key("OpsItemFilters") - if err := awsAwsjson11_serializeDocumentOpsItemFilters(v.OpsItemFilters, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeParametersInput(v *DescribeParametersInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentParametersFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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.ParameterFilters != nil { - ok := object.Key("ParameterFilters") - if err := awsAwsjson11_serializeDocumentParameterStringFilterList(v.ParameterFilters, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribePatchBaselinesInput(v *DescribePatchBaselinesInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentPatchOrchestratorFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribePatchGroupsInput(v *DescribePatchGroupsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentPatchOrchestratorFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribePatchGroupStateInput(v *DescribePatchGroupStateInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.PatchGroup != nil { - ok := object.Key("PatchGroup") - ok.String(*v.PatchGroup) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribePatchPropertiesInput(v *DescribePatchPropertiesInput, 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 len(v.OperatingSystem) > 0 { - ok := object.Key("OperatingSystem") - ok.String(string(v.OperatingSystem)) - } - - if len(v.PatchSet) > 0 { - ok := object.Key("PatchSet") - ok.String(string(v.PatchSet)) - } - - if len(v.Property) > 0 { - ok := object.Key("Property") - ok.String(string(v.Property)) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDescribeSessionsInput(v *DescribeSessionsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentSessionFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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 len(v.State) > 0 { - ok := object.Key("State") - ok.String(string(v.State)) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentDisassociateOpsItemRelatedItemInput(v *DisassociateOpsItemRelatedItemInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AssociationId != nil { - ok := object.Key("AssociationId") - ok.String(*v.AssociationId) - } - - if v.OpsItemId != nil { - ok := object.Key("OpsItemId") - ok.String(*v.OpsItemId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetAutomationExecutionInput(v *GetAutomationExecutionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AutomationExecutionId != nil { - ok := object.Key("AutomationExecutionId") - ok.String(*v.AutomationExecutionId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetCalendarStateInput(v *GetCalendarStateInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AtTime != nil { - ok := object.Key("AtTime") - ok.String(*v.AtTime) - } - - if v.CalendarNames != nil { - ok := object.Key("CalendarNames") - if err := awsAwsjson11_serializeDocumentCalendarNameOrARNList(v.CalendarNames, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetCommandInvocationInput(v *GetCommandInvocationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.CommandId != nil { - ok := object.Key("CommandId") - ok.String(*v.CommandId) - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.PluginName != nil { - ok := object.Key("PluginName") - ok.String(*v.PluginName) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetConnectionStatusInput(v *GetConnectionStatusInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Target != nil { - ok := object.Key("Target") - ok.String(*v.Target) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetDefaultPatchBaselineInput(v *GetDefaultPatchBaselineInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.OperatingSystem) > 0 { - ok := object.Key("OperatingSystem") - ok.String(string(v.OperatingSystem)) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetDeployablePatchSnapshotForInstanceInput(v *GetDeployablePatchSnapshotForInstanceInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.BaselineOverride != nil { - ok := object.Key("BaselineOverride") - if err := awsAwsjson11_serializeDocumentBaselineOverride(v.BaselineOverride, ok); err != nil { - return err - } - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.SnapshotId != nil { - ok := object.Key("SnapshotId") - ok.String(*v.SnapshotId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetDocumentInput(v *GetDocumentInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.DocumentFormat) > 0 { - ok := object.Key("DocumentFormat") - ok.String(string(v.DocumentFormat)) - } - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.VersionName != nil { - ok := object.Key("VersionName") - ok.String(*v.VersionName) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetInventoryInput(v *GetInventoryInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Aggregators != nil { - ok := object.Key("Aggregators") - if err := awsAwsjson11_serializeDocumentInventoryAggregatorList(v.Aggregators, ok); err != nil { - return err - } - } - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentInventoryFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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.ResultAttributes != nil { - ok := object.Key("ResultAttributes") - if err := awsAwsjson11_serializeDocumentResultAttributeList(v.ResultAttributes, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetInventorySchemaInput(v *GetInventorySchemaInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Aggregator { - ok := object.Key("Aggregator") - ok.Boolean(v.Aggregator) - } - - 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.SubType != nil { - ok := object.Key("SubType") - ok.Boolean(*v.SubType) - } - - if v.TypeName != nil { - ok := object.Key("TypeName") - ok.String(*v.TypeName) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetMaintenanceWindowExecutionInput(v *GetMaintenanceWindowExecutionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.WindowExecutionId != nil { - ok := object.Key("WindowExecutionId") - ok.String(*v.WindowExecutionId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetMaintenanceWindowExecutionTaskInput(v *GetMaintenanceWindowExecutionTaskInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.TaskId != nil { - ok := object.Key("TaskId") - ok.String(*v.TaskId) - } - - if v.WindowExecutionId != nil { - ok := object.Key("WindowExecutionId") - ok.String(*v.WindowExecutionId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetMaintenanceWindowExecutionTaskInvocationInput(v *GetMaintenanceWindowExecutionTaskInvocationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.InvocationId != nil { - ok := object.Key("InvocationId") - ok.String(*v.InvocationId) - } - - if v.TaskId != nil { - ok := object.Key("TaskId") - ok.String(*v.TaskId) - } - - if v.WindowExecutionId != nil { - ok := object.Key("WindowExecutionId") - ok.String(*v.WindowExecutionId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetMaintenanceWindowInput(v *GetMaintenanceWindowInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetMaintenanceWindowTaskInput(v *GetMaintenanceWindowTaskInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - if v.WindowTaskId != nil { - ok := object.Key("WindowTaskId") - ok.String(*v.WindowTaskId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetOpsItemInput(v *GetOpsItemInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.OpsItemArn != nil { - ok := object.Key("OpsItemArn") - ok.String(*v.OpsItemArn) - } - - if v.OpsItemId != nil { - ok := object.Key("OpsItemId") - ok.String(*v.OpsItemId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetOpsMetadataInput(v *GetOpsMetadataInput, 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.OpsMetadataArn != nil { - ok := object.Key("OpsMetadataArn") - ok.String(*v.OpsMetadataArn) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetOpsSummaryInput(v *GetOpsSummaryInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Aggregators != nil { - ok := object.Key("Aggregators") - if err := awsAwsjson11_serializeDocumentOpsAggregatorList(v.Aggregators, ok); err != nil { - return err - } - } - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentOpsFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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.ResultAttributes != nil { - ok := object.Key("ResultAttributes") - if err := awsAwsjson11_serializeDocumentOpsResultAttributeList(v.ResultAttributes, ok); err != nil { - return err - } - } - - if v.SyncName != nil { - ok := object.Key("SyncName") - ok.String(*v.SyncName) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetParameterHistoryInput(v *GetParameterHistoryInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - if v.WithDecryption != nil { - ok := object.Key("WithDecryption") - ok.Boolean(*v.WithDecryption) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetParameterInput(v *GetParameterInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.WithDecryption != nil { - ok := object.Key("WithDecryption") - ok.Boolean(*v.WithDecryption) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetParametersByPathInput(v *GetParametersByPathInput, 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.ParameterFilters != nil { - ok := object.Key("ParameterFilters") - if err := awsAwsjson11_serializeDocumentParameterStringFilterList(v.ParameterFilters, ok); err != nil { - return err - } - } - - if v.Path != nil { - ok := object.Key("Path") - ok.String(*v.Path) - } - - if v.Recursive != nil { - ok := object.Key("Recursive") - ok.Boolean(*v.Recursive) - } - - if v.WithDecryption != nil { - ok := object.Key("WithDecryption") - ok.Boolean(*v.WithDecryption) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetParametersInput(v *GetParametersInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Names != nil { - ok := object.Key("Names") - if err := awsAwsjson11_serializeDocumentParameterNameList(v.Names, ok); err != nil { - return err - } - } - - if v.WithDecryption != nil { - ok := object.Key("WithDecryption") - ok.Boolean(*v.WithDecryption) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetPatchBaselineForPatchGroupInput(v *GetPatchBaselineForPatchGroupInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if len(v.OperatingSystem) > 0 { - ok := object.Key("OperatingSystem") - ok.String(string(v.OperatingSystem)) - } - - if v.PatchGroup != nil { - ok := object.Key("PatchGroup") - ok.String(*v.PatchGroup) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetPatchBaselineInput(v *GetPatchBaselineInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.BaselineId != nil { - ok := object.Key("BaselineId") - ok.String(*v.BaselineId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetResourcePoliciesInput(v *GetResourcePoliciesInput, 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.ResourceArn != nil { - ok := object.Key("ResourceArn") - ok.String(*v.ResourceArn) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentGetServiceSettingInput(v *GetServiceSettingInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SettingId != nil { - ok := object.Key("SettingId") - ok.String(*v.SettingId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentLabelParameterVersionInput(v *LabelParameterVersionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Labels != nil { - ok := object.Key("Labels") - if err := awsAwsjson11_serializeDocumentParameterLabelList(v.Labels, ok); err != nil { - return err - } - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.ParameterVersion != nil { - ok := object.Key("ParameterVersion") - ok.Long(*v.ParameterVersion) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListAssociationsInput(v *ListAssociationsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AssociationFilterList != nil { - ok := object.Key("AssociationFilterList") - if err := awsAwsjson11_serializeDocumentAssociationFilterList(v.AssociationFilterList, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListAssociationVersionsInput(v *ListAssociationVersionsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AssociationId != nil { - ok := object.Key("AssociationId") - ok.String(*v.AssociationId) - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListCommandInvocationsInput(v *ListCommandInvocationsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.CommandId != nil { - ok := object.Key("CommandId") - ok.String(*v.CommandId) - } - - if v.Details { - ok := object.Key("Details") - ok.Boolean(v.Details) - } - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentCommandFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListCommandsInput(v *ListCommandsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.CommandId != nil { - ok := object.Key("CommandId") - ok.String(*v.CommandId) - } - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentCommandFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListComplianceItemsInput(v *ListComplianceItemsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentComplianceStringFilterList(v.Filters, ok); err != nil { - return err - } - } - - 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.ResourceIds != nil { - ok := object.Key("ResourceIds") - if err := awsAwsjson11_serializeDocumentComplianceResourceIdList(v.ResourceIds, ok); err != nil { - return err - } - } - - if v.ResourceTypes != nil { - ok := object.Key("ResourceTypes") - if err := awsAwsjson11_serializeDocumentComplianceResourceTypeList(v.ResourceTypes, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListComplianceSummariesInput(v *ListComplianceSummariesInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentComplianceStringFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListDocumentMetadataHistoryInput(v *ListDocumentMetadataHistoryInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if len(v.Metadata) > 0 { - ok := object.Key("Metadata") - ok.String(string(v.Metadata)) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListDocumentsInput(v *ListDocumentsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DocumentFilterList != nil { - ok := object.Key("DocumentFilterList") - if err := awsAwsjson11_serializeDocumentDocumentFilterList(v.DocumentFilterList, ok); err != nil { - return err - } - } - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentDocumentKeyValuesFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListDocumentVersionsInput(v *ListDocumentVersionsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListInventoryEntriesInput(v *ListInventoryEntriesInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentInventoryFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - 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.TypeName != nil { - ok := object.Key("TypeName") - ok.String(*v.TypeName) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListOpsItemEventsInput(v *ListOpsItemEventsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentOpsItemEventFilters(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListOpsItemRelatedItemsInput(v *ListOpsItemRelatedItemsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentOpsItemRelatedItemsFilters(v.Filters, ok); err != nil { - return err - } - } - - 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.OpsItemId != nil { - ok := object.Key("OpsItemId") - ok.String(*v.OpsItemId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListOpsMetadataInput(v *ListOpsMetadataInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentOpsMetadataFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListResourceComplianceSummariesInput(v *ListResourceComplianceSummariesInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Filters != nil { - ok := object.Key("Filters") - if err := awsAwsjson11_serializeDocumentComplianceStringFilterList(v.Filters, ok); err != nil { - return err - } - } - - if v.MaxResults != nil { - ok := object.Key("MaxResults") - ok.Integer(*v.MaxResults) - } - - if v.NextToken != nil { - ok := object.Key("NextToken") - ok.String(*v.NextToken) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListResourceDataSyncInput(v *ListResourceDataSyncInput, 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.SyncType != nil { - ok := object.Key("SyncType") - ok.String(*v.SyncType) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentListTagsForResourceInput(v *ListTagsForResourceInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ResourceId != nil { - ok := object.Key("ResourceId") - ok.String(*v.ResourceId) - } - - if len(v.ResourceType) > 0 { - ok := object.Key("ResourceType") - ok.String(string(v.ResourceType)) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentModifyDocumentPermissionInput(v *ModifyDocumentPermissionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AccountIdsToAdd != nil { - ok := object.Key("AccountIdsToAdd") - if err := awsAwsjson11_serializeDocumentAccountIdList(v.AccountIdsToAdd, ok); err != nil { - return err - } - } - - if v.AccountIdsToRemove != nil { - ok := object.Key("AccountIdsToRemove") - if err := awsAwsjson11_serializeDocumentAccountIdList(v.AccountIdsToRemove, ok); err != nil { - return err - } - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if len(v.PermissionType) > 0 { - ok := object.Key("PermissionType") - ok.String(string(v.PermissionType)) - } - - if v.SharedDocumentVersion != nil { - ok := object.Key("SharedDocumentVersion") - ok.String(*v.SharedDocumentVersion) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentPutComplianceItemsInput(v *PutComplianceItemsInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ComplianceType != nil { - ok := object.Key("ComplianceType") - ok.String(*v.ComplianceType) - } - - if v.ExecutionSummary != nil { - ok := object.Key("ExecutionSummary") - if err := awsAwsjson11_serializeDocumentComplianceExecutionSummary(v.ExecutionSummary, ok); err != nil { - return err - } - } - - if v.ItemContentHash != nil { - ok := object.Key("ItemContentHash") - ok.String(*v.ItemContentHash) - } - - if v.Items != nil { - ok := object.Key("Items") - if err := awsAwsjson11_serializeDocumentComplianceItemEntryList(v.Items, ok); err != nil { - return err - } - } - - if v.ResourceId != nil { - ok := object.Key("ResourceId") - ok.String(*v.ResourceId) - } - - if v.ResourceType != nil { - ok := object.Key("ResourceType") - ok.String(*v.ResourceType) - } - - if len(v.UploadType) > 0 { - ok := object.Key("UploadType") - ok.String(string(v.UploadType)) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentPutInventoryInput(v *PutInventoryInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.Items != nil { - ok := object.Key("Items") - if err := awsAwsjson11_serializeDocumentInventoryItemList(v.Items, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentPutParameterInput(v *PutParameterInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AllowedPattern != nil { - ok := object.Key("AllowedPattern") - ok.String(*v.AllowedPattern) - } - - if v.DataType != nil { - ok := object.Key("DataType") - ok.String(*v.DataType) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.KeyId != nil { - ok := object.Key("KeyId") - ok.String(*v.KeyId) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.Overwrite != nil { - ok := object.Key("Overwrite") - ok.Boolean(*v.Overwrite) - } - - if v.Policies != nil { - ok := object.Key("Policies") - ok.String(*v.Policies) - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagList(v.Tags, ok); err != nil { - return err - } - } - - if len(v.Tier) > 0 { - ok := object.Key("Tier") - ok.String(string(v.Tier)) - } - - if len(v.Type) > 0 { - ok := object.Key("Type") - ok.String(string(v.Type)) - } - - if v.Value != nil { - ok := object.Key("Value") - ok.String(*v.Value) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentPutResourcePolicyInput(v *PutResourcePolicyInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Policy != nil { - ok := object.Key("Policy") - ok.String(*v.Policy) - } - - if v.PolicyHash != nil { - ok := object.Key("PolicyHash") - ok.String(*v.PolicyHash) - } - - if v.PolicyId != nil { - ok := object.Key("PolicyId") - ok.String(*v.PolicyId) - } - - if v.ResourceArn != nil { - ok := object.Key("ResourceArn") - ok.String(*v.ResourceArn) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentRegisterDefaultPatchBaselineInput(v *RegisterDefaultPatchBaselineInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.BaselineId != nil { - ok := object.Key("BaselineId") - ok.String(*v.BaselineId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentRegisterPatchBaselineForPatchGroupInput(v *RegisterPatchBaselineForPatchGroupInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.BaselineId != nil { - ok := object.Key("BaselineId") - ok.String(*v.BaselineId) - } - - if v.PatchGroup != nil { - ok := object.Key("PatchGroup") - ok.String(*v.PatchGroup) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentRegisterTargetWithMaintenanceWindowInput(v *RegisterTargetWithMaintenanceWindowInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientToken != nil { - ok := object.Key("ClientToken") - ok.String(*v.ClientToken) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.OwnerInformation != nil { - ok := object.Key("OwnerInformation") - ok.String(*v.OwnerInformation) - } - - if len(v.ResourceType) > 0 { - ok := object.Key("ResourceType") - ok.String(string(v.ResourceType)) - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - if v.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentRegisterTaskWithMaintenanceWindowInput(v *RegisterTaskWithMaintenanceWindowInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AlarmConfiguration != nil { - ok := object.Key("AlarmConfiguration") - if err := awsAwsjson11_serializeDocumentAlarmConfiguration(v.AlarmConfiguration, ok); err != nil { - return err - } - } - - if v.ClientToken != nil { - ok := object.Key("ClientToken") - ok.String(*v.ClientToken) - } - - if len(v.CutoffBehavior) > 0 { - ok := object.Key("CutoffBehavior") - ok.String(string(v.CutoffBehavior)) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.LoggingInfo != nil { - ok := object.Key("LoggingInfo") - if err := awsAwsjson11_serializeDocumentLoggingInfo(v.LoggingInfo, ok); err != nil { - return err - } - } - - if v.MaxConcurrency != nil { - ok := object.Key("MaxConcurrency") - ok.String(*v.MaxConcurrency) - } - - if v.MaxErrors != nil { - ok := object.Key("MaxErrors") - ok.String(*v.MaxErrors) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.Priority != nil { - ok := object.Key("Priority") - ok.Integer(*v.Priority) - } - - if v.ServiceRoleArn != nil { - ok := object.Key("ServiceRoleArn") - ok.String(*v.ServiceRoleArn) - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - if v.TaskArn != nil { - ok := object.Key("TaskArn") - ok.String(*v.TaskArn) - } - - if v.TaskInvocationParameters != nil { - ok := object.Key("TaskInvocationParameters") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowTaskInvocationParameters(v.TaskInvocationParameters, ok); err != nil { - return err - } - } - - if v.TaskParameters != nil { - ok := object.Key("TaskParameters") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowTaskParameters(v.TaskParameters, ok); err != nil { - return err - } - } - - if len(v.TaskType) > 0 { - ok := object.Key("TaskType") - ok.String(string(v.TaskType)) - } - - if v.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentRemoveTagsFromResourceInput(v *RemoveTagsFromResourceInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ResourceId != nil { - ok := object.Key("ResourceId") - ok.String(*v.ResourceId) - } - - if len(v.ResourceType) > 0 { - ok := object.Key("ResourceType") - ok.String(string(v.ResourceType)) - } - - if v.TagKeys != nil { - ok := object.Key("TagKeys") - if err := awsAwsjson11_serializeDocumentKeyList(v.TagKeys, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentResetServiceSettingInput(v *ResetServiceSettingInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SettingId != nil { - ok := object.Key("SettingId") - ok.String(*v.SettingId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentResumeSessionInput(v *ResumeSessionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SessionId != nil { - ok := object.Key("SessionId") - ok.String(*v.SessionId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentSendAutomationSignalInput(v *SendAutomationSignalInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AutomationExecutionId != nil { - ok := object.Key("AutomationExecutionId") - ok.String(*v.AutomationExecutionId) - } - - if v.Payload != nil { - ok := object.Key("Payload") - if err := awsAwsjson11_serializeDocumentAutomationParameterMap(v.Payload, ok); err != nil { - return err - } - } - - if len(v.SignalType) > 0 { - ok := object.Key("SignalType") - ok.String(string(v.SignalType)) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentSendCommandInput(v *SendCommandInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AlarmConfiguration != nil { - ok := object.Key("AlarmConfiguration") - if err := awsAwsjson11_serializeDocumentAlarmConfiguration(v.AlarmConfiguration, ok); err != nil { - return err - } - } - - if v.CloudWatchOutputConfig != nil { - ok := object.Key("CloudWatchOutputConfig") - if err := awsAwsjson11_serializeDocumentCloudWatchOutputConfig(v.CloudWatchOutputConfig, ok); err != nil { - return err - } - } - - if v.Comment != nil { - ok := object.Key("Comment") - ok.String(*v.Comment) - } - - if v.DocumentHash != nil { - ok := object.Key("DocumentHash") - ok.String(*v.DocumentHash) - } - - if len(v.DocumentHashType) > 0 { - ok := object.Key("DocumentHashType") - ok.String(string(v.DocumentHashType)) - } - - if v.DocumentName != nil { - ok := object.Key("DocumentName") - ok.String(*v.DocumentName) - } - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.InstanceIds != nil { - ok := object.Key("InstanceIds") - if err := awsAwsjson11_serializeDocumentInstanceIdList(v.InstanceIds, ok); err != nil { - return err - } - } - - if v.MaxConcurrency != nil { - ok := object.Key("MaxConcurrency") - ok.String(*v.MaxConcurrency) - } - - if v.MaxErrors != nil { - ok := object.Key("MaxErrors") - ok.String(*v.MaxErrors) - } - - if v.NotificationConfig != nil { - ok := object.Key("NotificationConfig") - if err := awsAwsjson11_serializeDocumentNotificationConfig(v.NotificationConfig, ok); err != nil { - return err - } - } - - if v.OutputS3BucketName != nil { - ok := object.Key("OutputS3BucketName") - ok.String(*v.OutputS3BucketName) - } - - if v.OutputS3KeyPrefix != nil { - ok := object.Key("OutputS3KeyPrefix") - ok.String(*v.OutputS3KeyPrefix) - } - - if v.OutputS3Region != nil { - ok := object.Key("OutputS3Region") - ok.String(*v.OutputS3Region) - } - - if v.Parameters != nil { - ok := object.Key("Parameters") - if err := awsAwsjson11_serializeDocumentParameters(v.Parameters, ok); err != nil { - return err - } - } - - if v.ServiceRoleArn != nil { - ok := object.Key("ServiceRoleArn") - ok.String(*v.ServiceRoleArn) - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - if v.TimeoutSeconds != nil { - ok := object.Key("TimeoutSeconds") - ok.Integer(*v.TimeoutSeconds) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentStartAssociationsOnceInput(v *StartAssociationsOnceInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AssociationIds != nil { - ok := object.Key("AssociationIds") - if err := awsAwsjson11_serializeDocumentAssociationIdList(v.AssociationIds, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentStartAutomationExecutionInput(v *StartAutomationExecutionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AlarmConfiguration != nil { - ok := object.Key("AlarmConfiguration") - if err := awsAwsjson11_serializeDocumentAlarmConfiguration(v.AlarmConfiguration, ok); err != nil { - return err - } - } - - if v.ClientToken != nil { - ok := object.Key("ClientToken") - ok.String(*v.ClientToken) - } - - if v.DocumentName != nil { - ok := object.Key("DocumentName") - ok.String(*v.DocumentName) - } - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.MaxConcurrency != nil { - ok := object.Key("MaxConcurrency") - ok.String(*v.MaxConcurrency) - } - - if v.MaxErrors != nil { - ok := object.Key("MaxErrors") - ok.String(*v.MaxErrors) - } - - if len(v.Mode) > 0 { - ok := object.Key("Mode") - ok.String(string(v.Mode)) - } - - if v.Parameters != nil { - ok := object.Key("Parameters") - if err := awsAwsjson11_serializeDocumentAutomationParameterMap(v.Parameters, ok); err != nil { - return err - } - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagList(v.Tags, ok); err != nil { - return err - } - } - - if v.TargetLocations != nil { - ok := object.Key("TargetLocations") - if err := awsAwsjson11_serializeDocumentTargetLocations(v.TargetLocations, ok); err != nil { - return err - } - } - - if v.TargetMaps != nil { - ok := object.Key("TargetMaps") - if err := awsAwsjson11_serializeDocumentTargetMaps(v.TargetMaps, ok); err != nil { - return err - } - } - - if v.TargetParameterName != nil { - ok := object.Key("TargetParameterName") - ok.String(*v.TargetParameterName) - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentStartChangeRequestExecutionInput(v *StartChangeRequestExecutionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AutoApprove { - ok := object.Key("AutoApprove") - ok.Boolean(v.AutoApprove) - } - - if v.ChangeDetails != nil { - ok := object.Key("ChangeDetails") - ok.String(*v.ChangeDetails) - } - - if v.ChangeRequestName != nil { - ok := object.Key("ChangeRequestName") - ok.String(*v.ChangeRequestName) - } - - if v.ClientToken != nil { - ok := object.Key("ClientToken") - ok.String(*v.ClientToken) - } - - if v.DocumentName != nil { - ok := object.Key("DocumentName") - ok.String(*v.DocumentName) - } - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.Parameters != nil { - ok := object.Key("Parameters") - if err := awsAwsjson11_serializeDocumentAutomationParameterMap(v.Parameters, ok); err != nil { - return err - } - } - - if v.Runbooks != nil { - ok := object.Key("Runbooks") - if err := awsAwsjson11_serializeDocumentRunbooks(v.Runbooks, ok); err != nil { - return err - } - } - - if v.ScheduledEndTime != nil { - ok := object.Key("ScheduledEndTime") - ok.Double(smithytime.FormatEpochSeconds(*v.ScheduledEndTime)) - } - - if v.ScheduledTime != nil { - ok := object.Key("ScheduledTime") - ok.Double(smithytime.FormatEpochSeconds(*v.ScheduledTime)) - } - - if v.Tags != nil { - ok := object.Key("Tags") - if err := awsAwsjson11_serializeDocumentTagList(v.Tags, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentStartSessionInput(v *StartSessionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DocumentName != nil { - ok := object.Key("DocumentName") - ok.String(*v.DocumentName) - } - - if v.Parameters != nil { - ok := object.Key("Parameters") - if err := awsAwsjson11_serializeDocumentSessionManagerParameters(v.Parameters, ok); err != nil { - return err - } - } - - if v.Reason != nil { - ok := object.Key("Reason") - ok.String(*v.Reason) - } - - if v.Target != nil { - ok := object.Key("Target") - ok.String(*v.Target) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentStopAutomationExecutionInput(v *StopAutomationExecutionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AutomationExecutionId != nil { - ok := object.Key("AutomationExecutionId") - ok.String(*v.AutomationExecutionId) - } - - if len(v.Type) > 0 { - ok := object.Key("Type") - ok.String(string(v.Type)) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentTerminateSessionInput(v *TerminateSessionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SessionId != nil { - ok := object.Key("SessionId") - ok.String(*v.SessionId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUnlabelParameterVersionInput(v *UnlabelParameterVersionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Labels != nil { - ok := object.Key("Labels") - if err := awsAwsjson11_serializeDocumentParameterLabelList(v.Labels, ok); err != nil { - return err - } - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.ParameterVersion != nil { - ok := object.Key("ParameterVersion") - ok.Long(*v.ParameterVersion) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateAssociationInput(v *UpdateAssociationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AlarmConfiguration != nil { - ok := object.Key("AlarmConfiguration") - if err := awsAwsjson11_serializeDocumentAlarmConfiguration(v.AlarmConfiguration, ok); err != nil { - return err - } - } - - if v.ApplyOnlyAtCronInterval { - ok := object.Key("ApplyOnlyAtCronInterval") - ok.Boolean(v.ApplyOnlyAtCronInterval) - } - - if v.AssociationId != nil { - ok := object.Key("AssociationId") - ok.String(*v.AssociationId) - } - - if v.AssociationName != nil { - ok := object.Key("AssociationName") - ok.String(*v.AssociationName) - } - - if v.AssociationVersion != nil { - ok := object.Key("AssociationVersion") - ok.String(*v.AssociationVersion) - } - - if v.AutomationTargetParameterName != nil { - ok := object.Key("AutomationTargetParameterName") - ok.String(*v.AutomationTargetParameterName) - } - - if v.CalendarNames != nil { - ok := object.Key("CalendarNames") - if err := awsAwsjson11_serializeDocumentCalendarNameOrARNList(v.CalendarNames, ok); err != nil { - return err - } - } - - if len(v.ComplianceSeverity) > 0 { - ok := object.Key("ComplianceSeverity") - ok.String(string(v.ComplianceSeverity)) - } - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.MaxConcurrency != nil { - ok := object.Key("MaxConcurrency") - ok.String(*v.MaxConcurrency) - } - - if v.MaxErrors != nil { - ok := object.Key("MaxErrors") - ok.String(*v.MaxErrors) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.OutputLocation != nil { - ok := object.Key("OutputLocation") - if err := awsAwsjson11_serializeDocumentInstanceAssociationOutputLocation(v.OutputLocation, ok); err != nil { - return err - } - } - - if v.Parameters != nil { - ok := object.Key("Parameters") - if err := awsAwsjson11_serializeDocumentParameters(v.Parameters, ok); err != nil { - return err - } - } - - if v.ScheduleExpression != nil { - ok := object.Key("ScheduleExpression") - ok.String(*v.ScheduleExpression) - } - - if v.ScheduleOffset != nil { - ok := object.Key("ScheduleOffset") - ok.Integer(*v.ScheduleOffset) - } - - if len(v.SyncCompliance) > 0 { - ok := object.Key("SyncCompliance") - ok.String(string(v.SyncCompliance)) - } - - if v.TargetLocations != nil { - ok := object.Key("TargetLocations") - if err := awsAwsjson11_serializeDocumentTargetLocations(v.TargetLocations, ok); err != nil { - return err - } - } - - if v.TargetMaps != nil { - ok := object.Key("TargetMaps") - if err := awsAwsjson11_serializeDocumentTargetMaps(v.TargetMaps, ok); err != nil { - return err - } - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateAssociationStatusInput(v *UpdateAssociationStatusInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AssociationStatus != nil { - ok := object.Key("AssociationStatus") - if err := awsAwsjson11_serializeDocumentAssociationStatus(v.AssociationStatus, ok); err != nil { - return err - } - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateDocumentDefaultVersionInput(v *UpdateDocumentDefaultVersionInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateDocumentInput(v *UpdateDocumentInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Attachments != nil { - ok := object.Key("Attachments") - if err := awsAwsjson11_serializeDocumentAttachmentsSourceList(v.Attachments, ok); err != nil { - return err - } - } - - if v.Content != nil { - ok := object.Key("Content") - ok.String(*v.Content) - } - - if v.DisplayName != nil { - ok := object.Key("DisplayName") - ok.String(*v.DisplayName) - } - - if len(v.DocumentFormat) > 0 { - ok := object.Key("DocumentFormat") - ok.String(string(v.DocumentFormat)) - } - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.TargetType != nil { - ok := object.Key("TargetType") - ok.String(*v.TargetType) - } - - if v.VersionName != nil { - ok := object.Key("VersionName") - ok.String(*v.VersionName) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateDocumentMetadataInput(v *UpdateDocumentMetadataInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.DocumentReviews != nil { - ok := object.Key("DocumentReviews") - if err := awsAwsjson11_serializeDocumentDocumentReviews(v.DocumentReviews, ok); err != nil { - return err - } - } - - if v.DocumentVersion != nil { - ok := object.Key("DocumentVersion") - ok.String(*v.DocumentVersion) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateMaintenanceWindowInput(v *UpdateMaintenanceWindowInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AllowUnassociatedTargets != nil { - ok := object.Key("AllowUnassociatedTargets") - ok.Boolean(*v.AllowUnassociatedTargets) - } - - if v.Cutoff != nil { - ok := object.Key("Cutoff") - ok.Integer(*v.Cutoff) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.Duration != nil { - ok := object.Key("Duration") - ok.Integer(*v.Duration) - } - - if v.Enabled != nil { - ok := object.Key("Enabled") - ok.Boolean(*v.Enabled) - } - - if v.EndDate != nil { - ok := object.Key("EndDate") - ok.String(*v.EndDate) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.Replace != nil { - ok := object.Key("Replace") - ok.Boolean(*v.Replace) - } - - if v.Schedule != nil { - ok := object.Key("Schedule") - ok.String(*v.Schedule) - } - - if v.ScheduleOffset != nil { - ok := object.Key("ScheduleOffset") - ok.Integer(*v.ScheduleOffset) - } - - if v.ScheduleTimezone != nil { - ok := object.Key("ScheduleTimezone") - ok.String(*v.ScheduleTimezone) - } - - if v.StartDate != nil { - ok := object.Key("StartDate") - ok.String(*v.StartDate) - } - - if v.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateMaintenanceWindowTargetInput(v *UpdateMaintenanceWindowTargetInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.OwnerInformation != nil { - ok := object.Key("OwnerInformation") - ok.String(*v.OwnerInformation) - } - - if v.Replace != nil { - ok := object.Key("Replace") - ok.Boolean(*v.Replace) - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - if v.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - if v.WindowTargetId != nil { - ok := object.Key("WindowTargetId") - ok.String(*v.WindowTargetId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateMaintenanceWindowTaskInput(v *UpdateMaintenanceWindowTaskInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.AlarmConfiguration != nil { - ok := object.Key("AlarmConfiguration") - if err := awsAwsjson11_serializeDocumentAlarmConfiguration(v.AlarmConfiguration, ok); err != nil { - return err - } - } - - if len(v.CutoffBehavior) > 0 { - ok := object.Key("CutoffBehavior") - ok.String(string(v.CutoffBehavior)) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.LoggingInfo != nil { - ok := object.Key("LoggingInfo") - if err := awsAwsjson11_serializeDocumentLoggingInfo(v.LoggingInfo, ok); err != nil { - return err - } - } - - if v.MaxConcurrency != nil { - ok := object.Key("MaxConcurrency") - ok.String(*v.MaxConcurrency) - } - - if v.MaxErrors != nil { - ok := object.Key("MaxErrors") - ok.String(*v.MaxErrors) - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.Priority != nil { - ok := object.Key("Priority") - ok.Integer(*v.Priority) - } - - if v.Replace != nil { - ok := object.Key("Replace") - ok.Boolean(*v.Replace) - } - - if v.ServiceRoleArn != nil { - ok := object.Key("ServiceRoleArn") - ok.String(*v.ServiceRoleArn) - } - - if v.Targets != nil { - ok := object.Key("Targets") - if err := awsAwsjson11_serializeDocumentTargets(v.Targets, ok); err != nil { - return err - } - } - - if v.TaskArn != nil { - ok := object.Key("TaskArn") - ok.String(*v.TaskArn) - } - - if v.TaskInvocationParameters != nil { - ok := object.Key("TaskInvocationParameters") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowTaskInvocationParameters(v.TaskInvocationParameters, ok); err != nil { - return err - } - } - - if v.TaskParameters != nil { - ok := object.Key("TaskParameters") - if err := awsAwsjson11_serializeDocumentMaintenanceWindowTaskParameters(v.TaskParameters, ok); err != nil { - return err - } - } - - if v.WindowId != nil { - ok := object.Key("WindowId") - ok.String(*v.WindowId) - } - - if v.WindowTaskId != nil { - ok := object.Key("WindowTaskId") - ok.String(*v.WindowTaskId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateManagedInstanceRoleInput(v *UpdateManagedInstanceRoleInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.IamRole != nil { - ok := object.Key("IamRole") - ok.String(*v.IamRole) - } - - if v.InstanceId != nil { - ok := object.Key("InstanceId") - ok.String(*v.InstanceId) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateOpsItemInput(v *UpdateOpsItemInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ActualEndTime != nil { - ok := object.Key("ActualEndTime") - ok.Double(smithytime.FormatEpochSeconds(*v.ActualEndTime)) - } - - if v.ActualStartTime != nil { - ok := object.Key("ActualStartTime") - ok.Double(smithytime.FormatEpochSeconds(*v.ActualStartTime)) - } - - if v.Category != nil { - ok := object.Key("Category") - ok.String(*v.Category) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.Notifications != nil { - ok := object.Key("Notifications") - if err := awsAwsjson11_serializeDocumentOpsItemNotifications(v.Notifications, ok); err != nil { - return err - } - } - - if v.OperationalData != nil { - ok := object.Key("OperationalData") - if err := awsAwsjson11_serializeDocumentOpsItemOperationalData(v.OperationalData, ok); err != nil { - return err - } - } - - if v.OperationalDataToDelete != nil { - ok := object.Key("OperationalDataToDelete") - if err := awsAwsjson11_serializeDocumentOpsItemOpsDataKeysList(v.OperationalDataToDelete, ok); err != nil { - return err - } - } - - if v.OpsItemArn != nil { - ok := object.Key("OpsItemArn") - ok.String(*v.OpsItemArn) - } - - if v.OpsItemId != nil { - ok := object.Key("OpsItemId") - ok.String(*v.OpsItemId) - } - - if v.PlannedEndTime != nil { - ok := object.Key("PlannedEndTime") - ok.Double(smithytime.FormatEpochSeconds(*v.PlannedEndTime)) - } - - if v.PlannedStartTime != nil { - ok := object.Key("PlannedStartTime") - ok.Double(smithytime.FormatEpochSeconds(*v.PlannedStartTime)) - } - - if v.Priority != nil { - ok := object.Key("Priority") - ok.Integer(*v.Priority) - } - - if v.RelatedOpsItems != nil { - ok := object.Key("RelatedOpsItems") - if err := awsAwsjson11_serializeDocumentRelatedOpsItems(v.RelatedOpsItems, ok); err != nil { - return err - } - } - - if v.Severity != nil { - ok := object.Key("Severity") - ok.String(*v.Severity) - } - - if len(v.Status) > 0 { - ok := object.Key("Status") - ok.String(string(v.Status)) - } - - if v.Title != nil { - ok := object.Key("Title") - ok.String(*v.Title) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateOpsMetadataInput(v *UpdateOpsMetadataInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.KeysToDelete != nil { - ok := object.Key("KeysToDelete") - if err := awsAwsjson11_serializeDocumentMetadataKeysToDeleteList(v.KeysToDelete, ok); err != nil { - return err - } - } - - if v.MetadataToUpdate != nil { - ok := object.Key("MetadataToUpdate") - if err := awsAwsjson11_serializeDocumentMetadataMap(v.MetadataToUpdate, ok); err != nil { - return err - } - } - - if v.OpsMetadataArn != nil { - ok := object.Key("OpsMetadataArn") - ok.String(*v.OpsMetadataArn) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdatePatchBaselineInput(v *UpdatePatchBaselineInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ApprovalRules != nil { - ok := object.Key("ApprovalRules") - if err := awsAwsjson11_serializeDocumentPatchRuleGroup(v.ApprovalRules, ok); err != nil { - return err - } - } - - if v.ApprovedPatches != nil { - ok := object.Key("ApprovedPatches") - if err := awsAwsjson11_serializeDocumentPatchIdList(v.ApprovedPatches, ok); err != nil { - return err - } - } - - if len(v.ApprovedPatchesComplianceLevel) > 0 { - ok := object.Key("ApprovedPatchesComplianceLevel") - ok.String(string(v.ApprovedPatchesComplianceLevel)) - } - - if v.ApprovedPatchesEnableNonSecurity != nil { - ok := object.Key("ApprovedPatchesEnableNonSecurity") - ok.Boolean(*v.ApprovedPatchesEnableNonSecurity) - } - - if v.BaselineId != nil { - ok := object.Key("BaselineId") - ok.String(*v.BaselineId) - } - - if v.Description != nil { - ok := object.Key("Description") - ok.String(*v.Description) - } - - if v.GlobalFilters != nil { - ok := object.Key("GlobalFilters") - if err := awsAwsjson11_serializeDocumentPatchFilterGroup(v.GlobalFilters, ok); err != nil { - return err - } - } - - if v.Name != nil { - ok := object.Key("Name") - ok.String(*v.Name) - } - - if v.RejectedPatches != nil { - ok := object.Key("RejectedPatches") - if err := awsAwsjson11_serializeDocumentPatchIdList(v.RejectedPatches, ok); err != nil { - return err - } - } - - if len(v.RejectedPatchesAction) > 0 { - ok := object.Key("RejectedPatchesAction") - ok.String(string(v.RejectedPatchesAction)) - } - - if v.Replace != nil { - ok := object.Key("Replace") - ok.Boolean(*v.Replace) - } - - if v.Sources != nil { - ok := object.Key("Sources") - if err := awsAwsjson11_serializeDocumentPatchSourceList(v.Sources, ok); err != nil { - return err - } - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateResourceDataSyncInput(v *UpdateResourceDataSyncInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SyncName != nil { - ok := object.Key("SyncName") - ok.String(*v.SyncName) - } - - if v.SyncSource != nil { - ok := object.Key("SyncSource") - if err := awsAwsjson11_serializeDocumentResourceDataSyncSource(v.SyncSource, ok); err != nil { - return err - } - } - - if v.SyncType != nil { - ok := object.Key("SyncType") - ok.String(*v.SyncType) - } - - return nil -} - -func awsAwsjson11_serializeOpDocumentUpdateServiceSettingInput(v *UpdateServiceSettingInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.SettingId != nil { - ok := object.Key("SettingId") - ok.String(*v.SettingId) - } - - if v.SettingValue != nil { - ok := object.Key("SettingValue") - ok.String(*v.SettingValue) - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/types/enums.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/types/enums.go deleted file mode 100644 index bb6c67ae..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/types/enums.go +++ /dev/null @@ -1,2012 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -type AssociationComplianceSeverity string - -// Enum values for AssociationComplianceSeverity -const ( - AssociationComplianceSeverityCritical AssociationComplianceSeverity = "CRITICAL" - AssociationComplianceSeverityHigh AssociationComplianceSeverity = "HIGH" - AssociationComplianceSeverityMedium AssociationComplianceSeverity = "MEDIUM" - AssociationComplianceSeverityLow AssociationComplianceSeverity = "LOW" - AssociationComplianceSeverityUnspecified AssociationComplianceSeverity = "UNSPECIFIED" -) - -// Values returns all known values for AssociationComplianceSeverity. 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 (AssociationComplianceSeverity) Values() []AssociationComplianceSeverity { - return []AssociationComplianceSeverity{ - "CRITICAL", - "HIGH", - "MEDIUM", - "LOW", - "UNSPECIFIED", - } -} - -type AssociationExecutionFilterKey string - -// Enum values for AssociationExecutionFilterKey -const ( - AssociationExecutionFilterKeyExecutionId AssociationExecutionFilterKey = "ExecutionId" - AssociationExecutionFilterKeyStatus AssociationExecutionFilterKey = "Status" - AssociationExecutionFilterKeyCreatedTime AssociationExecutionFilterKey = "CreatedTime" -) - -// Values returns all known values for AssociationExecutionFilterKey. 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 (AssociationExecutionFilterKey) Values() []AssociationExecutionFilterKey { - return []AssociationExecutionFilterKey{ - "ExecutionId", - "Status", - "CreatedTime", - } -} - -type AssociationExecutionTargetsFilterKey string - -// Enum values for AssociationExecutionTargetsFilterKey -const ( - AssociationExecutionTargetsFilterKeyStatus AssociationExecutionTargetsFilterKey = "Status" - AssociationExecutionTargetsFilterKeyResourceId AssociationExecutionTargetsFilterKey = "ResourceId" - AssociationExecutionTargetsFilterKeyResourceType AssociationExecutionTargetsFilterKey = "ResourceType" -) - -// Values returns all known values for AssociationExecutionTargetsFilterKey. 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 (AssociationExecutionTargetsFilterKey) Values() []AssociationExecutionTargetsFilterKey { - return []AssociationExecutionTargetsFilterKey{ - "Status", - "ResourceId", - "ResourceType", - } -} - -type AssociationFilterKey string - -// Enum values for AssociationFilterKey -const ( - AssociationFilterKeyInstanceId AssociationFilterKey = "InstanceId" - AssociationFilterKeyName AssociationFilterKey = "Name" - AssociationFilterKeyAssociationId AssociationFilterKey = "AssociationId" - AssociationFilterKeyStatus AssociationFilterKey = "AssociationStatusName" - AssociationFilterKeyLastExecutedBefore AssociationFilterKey = "LastExecutedBefore" - AssociationFilterKeyLastExecutedAfter AssociationFilterKey = "LastExecutedAfter" - AssociationFilterKeyAssociationName AssociationFilterKey = "AssociationName" - AssociationFilterKeyResourceGroupName AssociationFilterKey = "ResourceGroupName" -) - -// Values returns all known values for AssociationFilterKey. 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 (AssociationFilterKey) Values() []AssociationFilterKey { - return []AssociationFilterKey{ - "InstanceId", - "Name", - "AssociationId", - "AssociationStatusName", - "LastExecutedBefore", - "LastExecutedAfter", - "AssociationName", - "ResourceGroupName", - } -} - -type AssociationFilterOperatorType string - -// Enum values for AssociationFilterOperatorType -const ( - AssociationFilterOperatorTypeEqual AssociationFilterOperatorType = "EQUAL" - AssociationFilterOperatorTypeLessThan AssociationFilterOperatorType = "LESS_THAN" - AssociationFilterOperatorTypeGreaterThan AssociationFilterOperatorType = "GREATER_THAN" -) - -// Values returns all known values for AssociationFilterOperatorType. 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 (AssociationFilterOperatorType) Values() []AssociationFilterOperatorType { - return []AssociationFilterOperatorType{ - "EQUAL", - "LESS_THAN", - "GREATER_THAN", - } -} - -type AssociationStatusName string - -// Enum values for AssociationStatusName -const ( - AssociationStatusNamePending AssociationStatusName = "Pending" - AssociationStatusNameSuccess AssociationStatusName = "Success" - AssociationStatusNameFailed AssociationStatusName = "Failed" -) - -// Values returns all known values for AssociationStatusName. 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 (AssociationStatusName) Values() []AssociationStatusName { - return []AssociationStatusName{ - "Pending", - "Success", - "Failed", - } -} - -type AssociationSyncCompliance string - -// Enum values for AssociationSyncCompliance -const ( - AssociationSyncComplianceAuto AssociationSyncCompliance = "AUTO" - AssociationSyncComplianceManual AssociationSyncCompliance = "MANUAL" -) - -// Values returns all known values for AssociationSyncCompliance. 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 (AssociationSyncCompliance) Values() []AssociationSyncCompliance { - return []AssociationSyncCompliance{ - "AUTO", - "MANUAL", - } -} - -type AttachmentHashType string - -// Enum values for AttachmentHashType -const ( - AttachmentHashTypeSha256 AttachmentHashType = "Sha256" -) - -// Values returns all known values for AttachmentHashType. 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 (AttachmentHashType) Values() []AttachmentHashType { - return []AttachmentHashType{ - "Sha256", - } -} - -type AttachmentsSourceKey string - -// Enum values for AttachmentsSourceKey -const ( - AttachmentsSourceKeySourceUrl AttachmentsSourceKey = "SourceUrl" - AttachmentsSourceKeyS3FileUrl AttachmentsSourceKey = "S3FileUrl" - AttachmentsSourceKeyAttachmentReference AttachmentsSourceKey = "AttachmentReference" -) - -// Values returns all known values for AttachmentsSourceKey. 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 (AttachmentsSourceKey) Values() []AttachmentsSourceKey { - return []AttachmentsSourceKey{ - "SourceUrl", - "S3FileUrl", - "AttachmentReference", - } -} - -type AutomationExecutionFilterKey string - -// Enum values for AutomationExecutionFilterKey -const ( - AutomationExecutionFilterKeyDocumentNamePrefix AutomationExecutionFilterKey = "DocumentNamePrefix" - AutomationExecutionFilterKeyExecutionStatus AutomationExecutionFilterKey = "ExecutionStatus" - AutomationExecutionFilterKeyExecutionId AutomationExecutionFilterKey = "ExecutionId" - AutomationExecutionFilterKeyParentExecutionId AutomationExecutionFilterKey = "ParentExecutionId" - AutomationExecutionFilterKeyCurrentAction AutomationExecutionFilterKey = "CurrentAction" - AutomationExecutionFilterKeyStartTimeBefore AutomationExecutionFilterKey = "StartTimeBefore" - AutomationExecutionFilterKeyStartTimeAfter AutomationExecutionFilterKey = "StartTimeAfter" - AutomationExecutionFilterKeyAutomationType AutomationExecutionFilterKey = "AutomationType" - AutomationExecutionFilterKeyTagKey AutomationExecutionFilterKey = "TagKey" - AutomationExecutionFilterKeyTargetResourceGroup AutomationExecutionFilterKey = "TargetResourceGroup" - AutomationExecutionFilterKeyAutomationSubtype AutomationExecutionFilterKey = "AutomationSubtype" - AutomationExecutionFilterKeyOpsItemId AutomationExecutionFilterKey = "OpsItemId" -) - -// Values returns all known values for AutomationExecutionFilterKey. 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 (AutomationExecutionFilterKey) Values() []AutomationExecutionFilterKey { - return []AutomationExecutionFilterKey{ - "DocumentNamePrefix", - "ExecutionStatus", - "ExecutionId", - "ParentExecutionId", - "CurrentAction", - "StartTimeBefore", - "StartTimeAfter", - "AutomationType", - "TagKey", - "TargetResourceGroup", - "AutomationSubtype", - "OpsItemId", - } -} - -type AutomationExecutionStatus string - -// Enum values for AutomationExecutionStatus -const ( - AutomationExecutionStatusPending AutomationExecutionStatus = "Pending" - AutomationExecutionStatusInprogress AutomationExecutionStatus = "InProgress" - AutomationExecutionStatusWaiting AutomationExecutionStatus = "Waiting" - AutomationExecutionStatusSuccess AutomationExecutionStatus = "Success" - AutomationExecutionStatusTimedout AutomationExecutionStatus = "TimedOut" - AutomationExecutionStatusCancelling AutomationExecutionStatus = "Cancelling" - AutomationExecutionStatusCancelled AutomationExecutionStatus = "Cancelled" - AutomationExecutionStatusFailed AutomationExecutionStatus = "Failed" - AutomationExecutionStatusPendingApproval AutomationExecutionStatus = "PendingApproval" - AutomationExecutionStatusApproved AutomationExecutionStatus = "Approved" - AutomationExecutionStatusRejected AutomationExecutionStatus = "Rejected" - AutomationExecutionStatusScheduled AutomationExecutionStatus = "Scheduled" - AutomationExecutionStatusRunbookInprogress AutomationExecutionStatus = "RunbookInProgress" - AutomationExecutionStatusPendingChangeCalendarOverride AutomationExecutionStatus = "PendingChangeCalendarOverride" - AutomationExecutionStatusChangeCalendarOverrideApproved AutomationExecutionStatus = "ChangeCalendarOverrideApproved" - AutomationExecutionStatusChangeCalendarOverrideRejected AutomationExecutionStatus = "ChangeCalendarOverrideRejected" - AutomationExecutionStatusCompletedWithSuccess AutomationExecutionStatus = "CompletedWithSuccess" - AutomationExecutionStatusCompletedWithFailure AutomationExecutionStatus = "CompletedWithFailure" - AutomationExecutionStatusExited AutomationExecutionStatus = "Exited" -) - -// Values returns all known values for AutomationExecutionStatus. 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 (AutomationExecutionStatus) Values() []AutomationExecutionStatus { - return []AutomationExecutionStatus{ - "Pending", - "InProgress", - "Waiting", - "Success", - "TimedOut", - "Cancelling", - "Cancelled", - "Failed", - "PendingApproval", - "Approved", - "Rejected", - "Scheduled", - "RunbookInProgress", - "PendingChangeCalendarOverride", - "ChangeCalendarOverrideApproved", - "ChangeCalendarOverrideRejected", - "CompletedWithSuccess", - "CompletedWithFailure", - "Exited", - } -} - -type AutomationSubtype string - -// Enum values for AutomationSubtype -const ( - AutomationSubtypeChangeRequest AutomationSubtype = "ChangeRequest" -) - -// Values returns all known values for AutomationSubtype. 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 (AutomationSubtype) Values() []AutomationSubtype { - return []AutomationSubtype{ - "ChangeRequest", - } -} - -type AutomationType string - -// Enum values for AutomationType -const ( - AutomationTypeCrossAccount AutomationType = "CrossAccount" - AutomationTypeLocal AutomationType = "Local" -) - -// Values returns all known values for AutomationType. 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 (AutomationType) Values() []AutomationType { - return []AutomationType{ - "CrossAccount", - "Local", - } -} - -type CalendarState string - -// Enum values for CalendarState -const ( - CalendarStateOpen CalendarState = "OPEN" - CalendarStateClosed CalendarState = "CLOSED" -) - -// Values returns all known values for CalendarState. 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 (CalendarState) Values() []CalendarState { - return []CalendarState{ - "OPEN", - "CLOSED", - } -} - -type CommandFilterKey string - -// Enum values for CommandFilterKey -const ( - CommandFilterKeyInvokedAfter CommandFilterKey = "InvokedAfter" - CommandFilterKeyInvokedBefore CommandFilterKey = "InvokedBefore" - CommandFilterKeyStatus CommandFilterKey = "Status" - CommandFilterKeyExecutionStage CommandFilterKey = "ExecutionStage" - CommandFilterKeyDocumentName CommandFilterKey = "DocumentName" -) - -// Values returns all known values for CommandFilterKey. 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 (CommandFilterKey) Values() []CommandFilterKey { - return []CommandFilterKey{ - "InvokedAfter", - "InvokedBefore", - "Status", - "ExecutionStage", - "DocumentName", - } -} - -type CommandInvocationStatus string - -// Enum values for CommandInvocationStatus -const ( - CommandInvocationStatusPending CommandInvocationStatus = "Pending" - CommandInvocationStatusInProgress CommandInvocationStatus = "InProgress" - CommandInvocationStatusDelayed CommandInvocationStatus = "Delayed" - CommandInvocationStatusSuccess CommandInvocationStatus = "Success" - CommandInvocationStatusCancelled CommandInvocationStatus = "Cancelled" - CommandInvocationStatusTimedOut CommandInvocationStatus = "TimedOut" - CommandInvocationStatusFailed CommandInvocationStatus = "Failed" - CommandInvocationStatusCancelling CommandInvocationStatus = "Cancelling" -) - -// Values returns all known values for CommandInvocationStatus. 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 (CommandInvocationStatus) Values() []CommandInvocationStatus { - return []CommandInvocationStatus{ - "Pending", - "InProgress", - "Delayed", - "Success", - "Cancelled", - "TimedOut", - "Failed", - "Cancelling", - } -} - -type CommandPluginStatus string - -// Enum values for CommandPluginStatus -const ( - CommandPluginStatusPending CommandPluginStatus = "Pending" - CommandPluginStatusInProgress CommandPluginStatus = "InProgress" - CommandPluginStatusSuccess CommandPluginStatus = "Success" - CommandPluginStatusTimedOut CommandPluginStatus = "TimedOut" - CommandPluginStatusCancelled CommandPluginStatus = "Cancelled" - CommandPluginStatusFailed CommandPluginStatus = "Failed" -) - -// Values returns all known values for CommandPluginStatus. 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 (CommandPluginStatus) Values() []CommandPluginStatus { - return []CommandPluginStatus{ - "Pending", - "InProgress", - "Success", - "TimedOut", - "Cancelled", - "Failed", - } -} - -type CommandStatus string - -// Enum values for CommandStatus -const ( - CommandStatusPending CommandStatus = "Pending" - CommandStatusInProgress CommandStatus = "InProgress" - CommandStatusSuccess CommandStatus = "Success" - CommandStatusCancelled CommandStatus = "Cancelled" - CommandStatusFailed CommandStatus = "Failed" - CommandStatusTimedOut CommandStatus = "TimedOut" - CommandStatusCancelling CommandStatus = "Cancelling" -) - -// Values returns all known values for CommandStatus. 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 (CommandStatus) Values() []CommandStatus { - return []CommandStatus{ - "Pending", - "InProgress", - "Success", - "Cancelled", - "Failed", - "TimedOut", - "Cancelling", - } -} - -type ComplianceQueryOperatorType string - -// Enum values for ComplianceQueryOperatorType -const ( - ComplianceQueryOperatorTypeEqual ComplianceQueryOperatorType = "EQUAL" - ComplianceQueryOperatorTypeNotEqual ComplianceQueryOperatorType = "NOT_EQUAL" - ComplianceQueryOperatorTypeBeginWith ComplianceQueryOperatorType = "BEGIN_WITH" - ComplianceQueryOperatorTypeLessThan ComplianceQueryOperatorType = "LESS_THAN" - ComplianceQueryOperatorTypeGreaterThan ComplianceQueryOperatorType = "GREATER_THAN" -) - -// Values returns all known values for ComplianceQueryOperatorType. 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 (ComplianceQueryOperatorType) Values() []ComplianceQueryOperatorType { - return []ComplianceQueryOperatorType{ - "EQUAL", - "NOT_EQUAL", - "BEGIN_WITH", - "LESS_THAN", - "GREATER_THAN", - } -} - -type ComplianceSeverity string - -// Enum values for ComplianceSeverity -const ( - ComplianceSeverityCritical ComplianceSeverity = "CRITICAL" - ComplianceSeverityHigh ComplianceSeverity = "HIGH" - ComplianceSeverityMedium ComplianceSeverity = "MEDIUM" - ComplianceSeverityLow ComplianceSeverity = "LOW" - ComplianceSeverityInformational ComplianceSeverity = "INFORMATIONAL" - ComplianceSeverityUnspecified ComplianceSeverity = "UNSPECIFIED" -) - -// Values returns all known values for ComplianceSeverity. 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 (ComplianceSeverity) Values() []ComplianceSeverity { - return []ComplianceSeverity{ - "CRITICAL", - "HIGH", - "MEDIUM", - "LOW", - "INFORMATIONAL", - "UNSPECIFIED", - } -} - -type ComplianceStatus string - -// Enum values for ComplianceStatus -const ( - ComplianceStatusCompliant ComplianceStatus = "COMPLIANT" - ComplianceStatusNonCompliant ComplianceStatus = "NON_COMPLIANT" -) - -// Values returns all known values for ComplianceStatus. 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 (ComplianceStatus) Values() []ComplianceStatus { - return []ComplianceStatus{ - "COMPLIANT", - "NON_COMPLIANT", - } -} - -type ComplianceUploadType string - -// Enum values for ComplianceUploadType -const ( - ComplianceUploadTypeComplete ComplianceUploadType = "COMPLETE" - ComplianceUploadTypePartial ComplianceUploadType = "PARTIAL" -) - -// Values returns all known values for ComplianceUploadType. 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 (ComplianceUploadType) Values() []ComplianceUploadType { - return []ComplianceUploadType{ - "COMPLETE", - "PARTIAL", - } -} - -type ConnectionStatus string - -// Enum values for ConnectionStatus -const ( - ConnectionStatusConnected ConnectionStatus = "connected" - ConnectionStatusNotConnected ConnectionStatus = "notconnected" -) - -// Values returns all known values for ConnectionStatus. 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 (ConnectionStatus) Values() []ConnectionStatus { - return []ConnectionStatus{ - "connected", - "notconnected", - } -} - -type DescribeActivationsFilterKeys string - -// Enum values for DescribeActivationsFilterKeys -const ( - DescribeActivationsFilterKeysActivationIds DescribeActivationsFilterKeys = "ActivationIds" - DescribeActivationsFilterKeysDefaultInstanceName DescribeActivationsFilterKeys = "DefaultInstanceName" - DescribeActivationsFilterKeysIamRole DescribeActivationsFilterKeys = "IamRole" -) - -// Values returns all known values for DescribeActivationsFilterKeys. 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 (DescribeActivationsFilterKeys) Values() []DescribeActivationsFilterKeys { - return []DescribeActivationsFilterKeys{ - "ActivationIds", - "DefaultInstanceName", - "IamRole", - } -} - -type DocumentFilterKey string - -// Enum values for DocumentFilterKey -const ( - DocumentFilterKeyName DocumentFilterKey = "Name" - DocumentFilterKeyOwner DocumentFilterKey = "Owner" - DocumentFilterKeyPlatformTypes DocumentFilterKey = "PlatformTypes" - DocumentFilterKeyDocumentType DocumentFilterKey = "DocumentType" -) - -// Values returns all known values for DocumentFilterKey. 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 (DocumentFilterKey) Values() []DocumentFilterKey { - return []DocumentFilterKey{ - "Name", - "Owner", - "PlatformTypes", - "DocumentType", - } -} - -type DocumentFormat string - -// Enum values for DocumentFormat -const ( - DocumentFormatYaml DocumentFormat = "YAML" - DocumentFormatJson DocumentFormat = "JSON" - DocumentFormatText DocumentFormat = "TEXT" -) - -// Values returns all known values for DocumentFormat. 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 (DocumentFormat) Values() []DocumentFormat { - return []DocumentFormat{ - "YAML", - "JSON", - "TEXT", - } -} - -type DocumentHashType string - -// Enum values for DocumentHashType -const ( - DocumentHashTypeSha256 DocumentHashType = "Sha256" - DocumentHashTypeSha1 DocumentHashType = "Sha1" -) - -// Values returns all known values for DocumentHashType. 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 (DocumentHashType) Values() []DocumentHashType { - return []DocumentHashType{ - "Sha256", - "Sha1", - } -} - -type DocumentMetadataEnum string - -// Enum values for DocumentMetadataEnum -const ( - DocumentMetadataEnumDocumentReviews DocumentMetadataEnum = "DocumentReviews" -) - -// Values returns all known values for DocumentMetadataEnum. 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 (DocumentMetadataEnum) Values() []DocumentMetadataEnum { - return []DocumentMetadataEnum{ - "DocumentReviews", - } -} - -type DocumentParameterType string - -// Enum values for DocumentParameterType -const ( - DocumentParameterTypeString DocumentParameterType = "String" - DocumentParameterTypeStringList DocumentParameterType = "StringList" -) - -// Values returns all known values for DocumentParameterType. 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 (DocumentParameterType) Values() []DocumentParameterType { - return []DocumentParameterType{ - "String", - "StringList", - } -} - -type DocumentPermissionType string - -// Enum values for DocumentPermissionType -const ( - DocumentPermissionTypeShare DocumentPermissionType = "Share" -) - -// Values returns all known values for DocumentPermissionType. 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 (DocumentPermissionType) Values() []DocumentPermissionType { - return []DocumentPermissionType{ - "Share", - } -} - -type DocumentReviewAction string - -// Enum values for DocumentReviewAction -const ( - DocumentReviewActionSendForReview DocumentReviewAction = "SendForReview" - DocumentReviewActionUpdateReview DocumentReviewAction = "UpdateReview" - DocumentReviewActionApprove DocumentReviewAction = "Approve" - DocumentReviewActionReject DocumentReviewAction = "Reject" -) - -// Values returns all known values for DocumentReviewAction. 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 (DocumentReviewAction) Values() []DocumentReviewAction { - return []DocumentReviewAction{ - "SendForReview", - "UpdateReview", - "Approve", - "Reject", - } -} - -type DocumentReviewCommentType string - -// Enum values for DocumentReviewCommentType -const ( - DocumentReviewCommentTypeComment DocumentReviewCommentType = "Comment" -) - -// Values returns all known values for DocumentReviewCommentType. 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 (DocumentReviewCommentType) Values() []DocumentReviewCommentType { - return []DocumentReviewCommentType{ - "Comment", - } -} - -type DocumentStatus string - -// Enum values for DocumentStatus -const ( - DocumentStatusCreating DocumentStatus = "Creating" - DocumentStatusActive DocumentStatus = "Active" - DocumentStatusUpdating DocumentStatus = "Updating" - DocumentStatusDeleting DocumentStatus = "Deleting" - DocumentStatusFailed DocumentStatus = "Failed" -) - -// Values returns all known values for DocumentStatus. 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 (DocumentStatus) Values() []DocumentStatus { - return []DocumentStatus{ - "Creating", - "Active", - "Updating", - "Deleting", - "Failed", - } -} - -type DocumentType string - -// Enum values for DocumentType -const ( - DocumentTypeCommand DocumentType = "Command" - DocumentTypePolicy DocumentType = "Policy" - DocumentTypeAutomation DocumentType = "Automation" - DocumentTypeSession DocumentType = "Session" - DocumentTypePackage DocumentType = "Package" - DocumentTypeApplicationConfiguration DocumentType = "ApplicationConfiguration" - DocumentTypeApplicationConfigurationSchema DocumentType = "ApplicationConfigurationSchema" - DocumentTypeDeploymentStrategy DocumentType = "DeploymentStrategy" - DocumentTypeChangeCalendar DocumentType = "ChangeCalendar" - DocumentTypeChangeTemplate DocumentType = "Automation.ChangeTemplate" - DocumentTypeProblemAnalysis DocumentType = "ProblemAnalysis" - DocumentTypeProblemAnalysisTemplate DocumentType = "ProblemAnalysisTemplate" - DocumentTypeCloudFormation DocumentType = "CloudFormation" - DocumentTypeConformancePackTemplate DocumentType = "ConformancePackTemplate" - DocumentTypeQuickSetup DocumentType = "QuickSetup" -) - -// Values returns all known values for DocumentType. 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 (DocumentType) Values() []DocumentType { - return []DocumentType{ - "Command", - "Policy", - "Automation", - "Session", - "Package", - "ApplicationConfiguration", - "ApplicationConfigurationSchema", - "DeploymentStrategy", - "ChangeCalendar", - "Automation.ChangeTemplate", - "ProblemAnalysis", - "ProblemAnalysisTemplate", - "CloudFormation", - "ConformancePackTemplate", - "QuickSetup", - } -} - -type ExecutionMode string - -// Enum values for ExecutionMode -const ( - ExecutionModeAuto ExecutionMode = "Auto" - ExecutionModeInteractive ExecutionMode = "Interactive" -) - -// Values returns all known values for ExecutionMode. 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 (ExecutionMode) Values() []ExecutionMode { - return []ExecutionMode{ - "Auto", - "Interactive", - } -} - -type ExternalAlarmState string - -// Enum values for ExternalAlarmState -const ( - ExternalAlarmStateUnknown ExternalAlarmState = "UNKNOWN" - ExternalAlarmStateAlarm ExternalAlarmState = "ALARM" -) - -// Values returns all known values for ExternalAlarmState. 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 (ExternalAlarmState) Values() []ExternalAlarmState { - return []ExternalAlarmState{ - "UNKNOWN", - "ALARM", - } -} - -type Fault string - -// Enum values for Fault -const ( - FaultClient Fault = "Client" - FaultServer Fault = "Server" - FaultUnknown Fault = "Unknown" -) - -// Values returns all known values for Fault. 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 (Fault) Values() []Fault { - return []Fault{ - "Client", - "Server", - "Unknown", - } -} - -type InstanceInformationFilterKey string - -// Enum values for InstanceInformationFilterKey -const ( - InstanceInformationFilterKeyInstanceIds InstanceInformationFilterKey = "InstanceIds" - InstanceInformationFilterKeyAgentVersion InstanceInformationFilterKey = "AgentVersion" - InstanceInformationFilterKeyPingStatus InstanceInformationFilterKey = "PingStatus" - InstanceInformationFilterKeyPlatformTypes InstanceInformationFilterKey = "PlatformTypes" - InstanceInformationFilterKeyActivationIds InstanceInformationFilterKey = "ActivationIds" - InstanceInformationFilterKeyIamRole InstanceInformationFilterKey = "IamRole" - InstanceInformationFilterKeyResourceType InstanceInformationFilterKey = "ResourceType" - InstanceInformationFilterKeyAssociationStatus InstanceInformationFilterKey = "AssociationStatus" -) - -// Values returns all known values for InstanceInformationFilterKey. 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 (InstanceInformationFilterKey) Values() []InstanceInformationFilterKey { - return []InstanceInformationFilterKey{ - "InstanceIds", - "AgentVersion", - "PingStatus", - "PlatformTypes", - "ActivationIds", - "IamRole", - "ResourceType", - "AssociationStatus", - } -} - -type InstancePatchStateOperatorType string - -// Enum values for InstancePatchStateOperatorType -const ( - InstancePatchStateOperatorTypeEqual InstancePatchStateOperatorType = "Equal" - InstancePatchStateOperatorTypeNotEqual InstancePatchStateOperatorType = "NotEqual" - InstancePatchStateOperatorTypeLessThan InstancePatchStateOperatorType = "LessThan" - InstancePatchStateOperatorTypeGreaterThan InstancePatchStateOperatorType = "GreaterThan" -) - -// Values returns all known values for InstancePatchStateOperatorType. 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 (InstancePatchStateOperatorType) Values() []InstancePatchStateOperatorType { - return []InstancePatchStateOperatorType{ - "Equal", - "NotEqual", - "LessThan", - "GreaterThan", - } -} - -type InventoryAttributeDataType string - -// Enum values for InventoryAttributeDataType -const ( - InventoryAttributeDataTypeString InventoryAttributeDataType = "string" - InventoryAttributeDataTypeNumber InventoryAttributeDataType = "number" -) - -// Values returns all known values for InventoryAttributeDataType. 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 (InventoryAttributeDataType) Values() []InventoryAttributeDataType { - return []InventoryAttributeDataType{ - "string", - "number", - } -} - -type InventoryDeletionStatus string - -// Enum values for InventoryDeletionStatus -const ( - InventoryDeletionStatusInProgress InventoryDeletionStatus = "InProgress" - InventoryDeletionStatusComplete InventoryDeletionStatus = "Complete" -) - -// Values returns all known values for InventoryDeletionStatus. 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 (InventoryDeletionStatus) Values() []InventoryDeletionStatus { - return []InventoryDeletionStatus{ - "InProgress", - "Complete", - } -} - -type InventoryQueryOperatorType string - -// Enum values for InventoryQueryOperatorType -const ( - InventoryQueryOperatorTypeEqual InventoryQueryOperatorType = "Equal" - InventoryQueryOperatorTypeNotEqual InventoryQueryOperatorType = "NotEqual" - InventoryQueryOperatorTypeBeginWith InventoryQueryOperatorType = "BeginWith" - InventoryQueryOperatorTypeLessThan InventoryQueryOperatorType = "LessThan" - InventoryQueryOperatorTypeGreaterThan InventoryQueryOperatorType = "GreaterThan" - InventoryQueryOperatorTypeExists InventoryQueryOperatorType = "Exists" -) - -// Values returns all known values for InventoryQueryOperatorType. 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 (InventoryQueryOperatorType) Values() []InventoryQueryOperatorType { - return []InventoryQueryOperatorType{ - "Equal", - "NotEqual", - "BeginWith", - "LessThan", - "GreaterThan", - "Exists", - } -} - -type InventorySchemaDeleteOption string - -// Enum values for InventorySchemaDeleteOption -const ( - InventorySchemaDeleteOptionDisableSchema InventorySchemaDeleteOption = "DisableSchema" - InventorySchemaDeleteOptionDeleteSchema InventorySchemaDeleteOption = "DeleteSchema" -) - -// Values returns all known values for InventorySchemaDeleteOption. 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 (InventorySchemaDeleteOption) Values() []InventorySchemaDeleteOption { - return []InventorySchemaDeleteOption{ - "DisableSchema", - "DeleteSchema", - } -} - -type LastResourceDataSyncStatus string - -// Enum values for LastResourceDataSyncStatus -const ( - LastResourceDataSyncStatusSuccessful LastResourceDataSyncStatus = "Successful" - LastResourceDataSyncStatusFailed LastResourceDataSyncStatus = "Failed" - LastResourceDataSyncStatusInprogress LastResourceDataSyncStatus = "InProgress" -) - -// Values returns all known values for LastResourceDataSyncStatus. 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 (LastResourceDataSyncStatus) Values() []LastResourceDataSyncStatus { - return []LastResourceDataSyncStatus{ - "Successful", - "Failed", - "InProgress", - } -} - -type MaintenanceWindowExecutionStatus string - -// Enum values for MaintenanceWindowExecutionStatus -const ( - MaintenanceWindowExecutionStatusPending MaintenanceWindowExecutionStatus = "PENDING" - MaintenanceWindowExecutionStatusInProgress MaintenanceWindowExecutionStatus = "IN_PROGRESS" - MaintenanceWindowExecutionStatusSuccess MaintenanceWindowExecutionStatus = "SUCCESS" - MaintenanceWindowExecutionStatusFailed MaintenanceWindowExecutionStatus = "FAILED" - MaintenanceWindowExecutionStatusTimedOut MaintenanceWindowExecutionStatus = "TIMED_OUT" - MaintenanceWindowExecutionStatusCancelling MaintenanceWindowExecutionStatus = "CANCELLING" - MaintenanceWindowExecutionStatusCancelled MaintenanceWindowExecutionStatus = "CANCELLED" - MaintenanceWindowExecutionStatusSkippedOverlapping MaintenanceWindowExecutionStatus = "SKIPPED_OVERLAPPING" -) - -// Values returns all known values for MaintenanceWindowExecutionStatus. 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 (MaintenanceWindowExecutionStatus) Values() []MaintenanceWindowExecutionStatus { - return []MaintenanceWindowExecutionStatus{ - "PENDING", - "IN_PROGRESS", - "SUCCESS", - "FAILED", - "TIMED_OUT", - "CANCELLING", - "CANCELLED", - "SKIPPED_OVERLAPPING", - } -} - -type MaintenanceWindowResourceType string - -// Enum values for MaintenanceWindowResourceType -const ( - MaintenanceWindowResourceTypeInstance MaintenanceWindowResourceType = "INSTANCE" - MaintenanceWindowResourceTypeResourceGroup MaintenanceWindowResourceType = "RESOURCE_GROUP" -) - -// Values returns all known values for MaintenanceWindowResourceType. 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 (MaintenanceWindowResourceType) Values() []MaintenanceWindowResourceType { - return []MaintenanceWindowResourceType{ - "INSTANCE", - "RESOURCE_GROUP", - } -} - -type MaintenanceWindowTaskCutoffBehavior string - -// Enum values for MaintenanceWindowTaskCutoffBehavior -const ( - MaintenanceWindowTaskCutoffBehaviorContinueTask MaintenanceWindowTaskCutoffBehavior = "CONTINUE_TASK" - MaintenanceWindowTaskCutoffBehaviorCancelTask MaintenanceWindowTaskCutoffBehavior = "CANCEL_TASK" -) - -// Values returns all known values for MaintenanceWindowTaskCutoffBehavior. 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 (MaintenanceWindowTaskCutoffBehavior) Values() []MaintenanceWindowTaskCutoffBehavior { - return []MaintenanceWindowTaskCutoffBehavior{ - "CONTINUE_TASK", - "CANCEL_TASK", - } -} - -type MaintenanceWindowTaskType string - -// Enum values for MaintenanceWindowTaskType -const ( - MaintenanceWindowTaskTypeRunCommand MaintenanceWindowTaskType = "RUN_COMMAND" - MaintenanceWindowTaskTypeAutomation MaintenanceWindowTaskType = "AUTOMATION" - MaintenanceWindowTaskTypeStepFunctions MaintenanceWindowTaskType = "STEP_FUNCTIONS" - MaintenanceWindowTaskTypeLambda MaintenanceWindowTaskType = "LAMBDA" -) - -// Values returns all known values for MaintenanceWindowTaskType. 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 (MaintenanceWindowTaskType) Values() []MaintenanceWindowTaskType { - return []MaintenanceWindowTaskType{ - "RUN_COMMAND", - "AUTOMATION", - "STEP_FUNCTIONS", - "LAMBDA", - } -} - -type NotificationEvent string - -// Enum values for NotificationEvent -const ( - NotificationEventAll NotificationEvent = "All" - NotificationEventInProgress NotificationEvent = "InProgress" - NotificationEventSuccess NotificationEvent = "Success" - NotificationEventTimedOut NotificationEvent = "TimedOut" - NotificationEventCancelled NotificationEvent = "Cancelled" - NotificationEventFailed NotificationEvent = "Failed" -) - -// Values returns all known values for NotificationEvent. 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 (NotificationEvent) Values() []NotificationEvent { - return []NotificationEvent{ - "All", - "InProgress", - "Success", - "TimedOut", - "Cancelled", - "Failed", - } -} - -type NotificationType string - -// Enum values for NotificationType -const ( - NotificationTypeCommand NotificationType = "Command" - NotificationTypeInvocation NotificationType = "Invocation" -) - -// Values returns all known values for NotificationType. 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 (NotificationType) Values() []NotificationType { - return []NotificationType{ - "Command", - "Invocation", - } -} - -type OperatingSystem string - -// Enum values for OperatingSystem -const ( - OperatingSystemWindows OperatingSystem = "WINDOWS" - OperatingSystemAmazonLinux OperatingSystem = "AMAZON_LINUX" - OperatingSystemAmazonLinux2 OperatingSystem = "AMAZON_LINUX_2" - OperatingSystemAmazonLinux2022 OperatingSystem = "AMAZON_LINUX_2022" - OperatingSystemUbuntu OperatingSystem = "UBUNTU" - OperatingSystemRedhatEnterpriseLinux OperatingSystem = "REDHAT_ENTERPRISE_LINUX" - OperatingSystemSuse OperatingSystem = "SUSE" - OperatingSystemCentOS OperatingSystem = "CENTOS" - OperatingSystemOracleLinux OperatingSystem = "ORACLE_LINUX" - OperatingSystemDebian OperatingSystem = "DEBIAN" - OperatingSystemMacOS OperatingSystem = "MACOS" - OperatingSystemRaspbian OperatingSystem = "RASPBIAN" - OperatingSystemRockyLinux OperatingSystem = "ROCKY_LINUX" - OperatingSystemAlmaLinux OperatingSystem = "ALMA_LINUX" - OperatingSystemAmazonLinux2023 OperatingSystem = "AMAZON_LINUX_2023" -) - -// Values returns all known values for OperatingSystem. 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 (OperatingSystem) Values() []OperatingSystem { - return []OperatingSystem{ - "WINDOWS", - "AMAZON_LINUX", - "AMAZON_LINUX_2", - "AMAZON_LINUX_2022", - "UBUNTU", - "REDHAT_ENTERPRISE_LINUX", - "SUSE", - "CENTOS", - "ORACLE_LINUX", - "DEBIAN", - "MACOS", - "RASPBIAN", - "ROCKY_LINUX", - "ALMA_LINUX", - "AMAZON_LINUX_2023", - } -} - -type OpsFilterOperatorType string - -// Enum values for OpsFilterOperatorType -const ( - OpsFilterOperatorTypeEqual OpsFilterOperatorType = "Equal" - OpsFilterOperatorTypeNotEqual OpsFilterOperatorType = "NotEqual" - OpsFilterOperatorTypeBeginWith OpsFilterOperatorType = "BeginWith" - OpsFilterOperatorTypeLessThan OpsFilterOperatorType = "LessThan" - OpsFilterOperatorTypeGreaterThan OpsFilterOperatorType = "GreaterThan" - OpsFilterOperatorTypeExists OpsFilterOperatorType = "Exists" -) - -// Values returns all known values for OpsFilterOperatorType. 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 (OpsFilterOperatorType) Values() []OpsFilterOperatorType { - return []OpsFilterOperatorType{ - "Equal", - "NotEqual", - "BeginWith", - "LessThan", - "GreaterThan", - "Exists", - } -} - -type OpsItemDataType string - -// Enum values for OpsItemDataType -const ( - OpsItemDataTypeSearchableString OpsItemDataType = "SearchableString" - OpsItemDataTypeString OpsItemDataType = "String" -) - -// Values returns all known values for OpsItemDataType. 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 (OpsItemDataType) Values() []OpsItemDataType { - return []OpsItemDataType{ - "SearchableString", - "String", - } -} - -type OpsItemEventFilterKey string - -// Enum values for OpsItemEventFilterKey -const ( - OpsItemEventFilterKeyOpsitemId OpsItemEventFilterKey = "OpsItemId" -) - -// Values returns all known values for OpsItemEventFilterKey. 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 (OpsItemEventFilterKey) Values() []OpsItemEventFilterKey { - return []OpsItemEventFilterKey{ - "OpsItemId", - } -} - -type OpsItemEventFilterOperator string - -// Enum values for OpsItemEventFilterOperator -const ( - OpsItemEventFilterOperatorEqual OpsItemEventFilterOperator = "Equal" -) - -// Values returns all known values for OpsItemEventFilterOperator. 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 (OpsItemEventFilterOperator) Values() []OpsItemEventFilterOperator { - return []OpsItemEventFilterOperator{ - "Equal", - } -} - -type OpsItemFilterKey string - -// Enum values for OpsItemFilterKey -const ( - OpsItemFilterKeyStatus OpsItemFilterKey = "Status" - OpsItemFilterKeyCreatedBy OpsItemFilterKey = "CreatedBy" - OpsItemFilterKeySource OpsItemFilterKey = "Source" - OpsItemFilterKeyPriority OpsItemFilterKey = "Priority" - OpsItemFilterKeyTitle OpsItemFilterKey = "Title" - OpsItemFilterKeyOpsitemId OpsItemFilterKey = "OpsItemId" - OpsItemFilterKeyCreatedTime OpsItemFilterKey = "CreatedTime" - OpsItemFilterKeyLastModifiedTime OpsItemFilterKey = "LastModifiedTime" - OpsItemFilterKeyActualStartTime OpsItemFilterKey = "ActualStartTime" - OpsItemFilterKeyActualEndTime OpsItemFilterKey = "ActualEndTime" - OpsItemFilterKeyPlannedStartTime OpsItemFilterKey = "PlannedStartTime" - OpsItemFilterKeyPlannedEndTime OpsItemFilterKey = "PlannedEndTime" - OpsItemFilterKeyOperationalData OpsItemFilterKey = "OperationalData" - OpsItemFilterKeyOperationalDataKey OpsItemFilterKey = "OperationalDataKey" - OpsItemFilterKeyOperationalDataValue OpsItemFilterKey = "OperationalDataValue" - OpsItemFilterKeyResourceId OpsItemFilterKey = "ResourceId" - OpsItemFilterKeyAutomationId OpsItemFilterKey = "AutomationId" - OpsItemFilterKeyCategory OpsItemFilterKey = "Category" - OpsItemFilterKeySeverity OpsItemFilterKey = "Severity" - OpsItemFilterKeyOpsitemType OpsItemFilterKey = "OpsItemType" - OpsItemFilterKeyChangeRequestRequesterArn OpsItemFilterKey = "ChangeRequestByRequesterArn" - OpsItemFilterKeyChangeRequestRequesterName OpsItemFilterKey = "ChangeRequestByRequesterName" - OpsItemFilterKeyChangeRequestApproverArn OpsItemFilterKey = "ChangeRequestByApproverArn" - OpsItemFilterKeyChangeRequestApproverName OpsItemFilterKey = "ChangeRequestByApproverName" - OpsItemFilterKeyChangeRequestTemplate OpsItemFilterKey = "ChangeRequestByTemplate" - OpsItemFilterKeyChangeRequestTargetsResourceGroup OpsItemFilterKey = "ChangeRequestByTargetsResourceGroup" - OpsItemFilterKeyInsightType OpsItemFilterKey = "InsightByType" - OpsItemFilterKeyAccountId OpsItemFilterKey = "AccountId" -) - -// Values returns all known values for OpsItemFilterKey. 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 (OpsItemFilterKey) Values() []OpsItemFilterKey { - return []OpsItemFilterKey{ - "Status", - "CreatedBy", - "Source", - "Priority", - "Title", - "OpsItemId", - "CreatedTime", - "LastModifiedTime", - "ActualStartTime", - "ActualEndTime", - "PlannedStartTime", - "PlannedEndTime", - "OperationalData", - "OperationalDataKey", - "OperationalDataValue", - "ResourceId", - "AutomationId", - "Category", - "Severity", - "OpsItemType", - "ChangeRequestByRequesterArn", - "ChangeRequestByRequesterName", - "ChangeRequestByApproverArn", - "ChangeRequestByApproverName", - "ChangeRequestByTemplate", - "ChangeRequestByTargetsResourceGroup", - "InsightByType", - "AccountId", - } -} - -type OpsItemFilterOperator string - -// Enum values for OpsItemFilterOperator -const ( - OpsItemFilterOperatorEqual OpsItemFilterOperator = "Equal" - OpsItemFilterOperatorContains OpsItemFilterOperator = "Contains" - OpsItemFilterOperatorGreaterThan OpsItemFilterOperator = "GreaterThan" - OpsItemFilterOperatorLessThan OpsItemFilterOperator = "LessThan" -) - -// Values returns all known values for OpsItemFilterOperator. 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 (OpsItemFilterOperator) Values() []OpsItemFilterOperator { - return []OpsItemFilterOperator{ - "Equal", - "Contains", - "GreaterThan", - "LessThan", - } -} - -type OpsItemRelatedItemsFilterKey string - -// Enum values for OpsItemRelatedItemsFilterKey -const ( - OpsItemRelatedItemsFilterKeyResourceType OpsItemRelatedItemsFilterKey = "ResourceType" - OpsItemRelatedItemsFilterKeyAssociationId OpsItemRelatedItemsFilterKey = "AssociationId" - OpsItemRelatedItemsFilterKeyResourceUri OpsItemRelatedItemsFilterKey = "ResourceUri" -) - -// Values returns all known values for OpsItemRelatedItemsFilterKey. 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 (OpsItemRelatedItemsFilterKey) Values() []OpsItemRelatedItemsFilterKey { - return []OpsItemRelatedItemsFilterKey{ - "ResourceType", - "AssociationId", - "ResourceUri", - } -} - -type OpsItemRelatedItemsFilterOperator string - -// Enum values for OpsItemRelatedItemsFilterOperator -const ( - OpsItemRelatedItemsFilterOperatorEqual OpsItemRelatedItemsFilterOperator = "Equal" -) - -// Values returns all known values for OpsItemRelatedItemsFilterOperator. 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 (OpsItemRelatedItemsFilterOperator) Values() []OpsItemRelatedItemsFilterOperator { - return []OpsItemRelatedItemsFilterOperator{ - "Equal", - } -} - -type OpsItemStatus string - -// Enum values for OpsItemStatus -const ( - OpsItemStatusOpen OpsItemStatus = "Open" - OpsItemStatusInProgress OpsItemStatus = "InProgress" - OpsItemStatusResolved OpsItemStatus = "Resolved" - OpsItemStatusPending OpsItemStatus = "Pending" - OpsItemStatusTimedOut OpsItemStatus = "TimedOut" - OpsItemStatusCancelling OpsItemStatus = "Cancelling" - OpsItemStatusCancelled OpsItemStatus = "Cancelled" - OpsItemStatusFailed OpsItemStatus = "Failed" - OpsItemStatusCompletedWithSuccess OpsItemStatus = "CompletedWithSuccess" - OpsItemStatusCompletedWithFailure OpsItemStatus = "CompletedWithFailure" - OpsItemStatusScheduled OpsItemStatus = "Scheduled" - OpsItemStatusRunbookInProgress OpsItemStatus = "RunbookInProgress" - OpsItemStatusPendingChangeCalendarOverride OpsItemStatus = "PendingChangeCalendarOverride" - OpsItemStatusChangeCalendarOverrideApproved OpsItemStatus = "ChangeCalendarOverrideApproved" - OpsItemStatusChangeCalendarOverrideRejected OpsItemStatus = "ChangeCalendarOverrideRejected" - OpsItemStatusPendingApproval OpsItemStatus = "PendingApproval" - OpsItemStatusApproved OpsItemStatus = "Approved" - OpsItemStatusRejected OpsItemStatus = "Rejected" - OpsItemStatusClosed OpsItemStatus = "Closed" -) - -// Values returns all known values for OpsItemStatus. 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 (OpsItemStatus) Values() []OpsItemStatus { - return []OpsItemStatus{ - "Open", - "InProgress", - "Resolved", - "Pending", - "TimedOut", - "Cancelling", - "Cancelled", - "Failed", - "CompletedWithSuccess", - "CompletedWithFailure", - "Scheduled", - "RunbookInProgress", - "PendingChangeCalendarOverride", - "ChangeCalendarOverrideApproved", - "ChangeCalendarOverrideRejected", - "PendingApproval", - "Approved", - "Rejected", - "Closed", - } -} - -type ParametersFilterKey string - -// Enum values for ParametersFilterKey -const ( - ParametersFilterKeyName ParametersFilterKey = "Name" - ParametersFilterKeyType ParametersFilterKey = "Type" - ParametersFilterKeyKeyId ParametersFilterKey = "KeyId" -) - -// Values returns all known values for ParametersFilterKey. 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 (ParametersFilterKey) Values() []ParametersFilterKey { - return []ParametersFilterKey{ - "Name", - "Type", - "KeyId", - } -} - -type ParameterTier string - -// Enum values for ParameterTier -const ( - ParameterTierStandard ParameterTier = "Standard" - ParameterTierAdvanced ParameterTier = "Advanced" - ParameterTierIntelligentTiering ParameterTier = "Intelligent-Tiering" -) - -// Values returns all known values for ParameterTier. 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 (ParameterTier) Values() []ParameterTier { - return []ParameterTier{ - "Standard", - "Advanced", - "Intelligent-Tiering", - } -} - -type ParameterType string - -// Enum values for ParameterType -const ( - ParameterTypeString ParameterType = "String" - ParameterTypeStringList ParameterType = "StringList" - ParameterTypeSecureString ParameterType = "SecureString" -) - -// Values returns all known values for ParameterType. 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 (ParameterType) Values() []ParameterType { - return []ParameterType{ - "String", - "StringList", - "SecureString", - } -} - -type PatchAction string - -// Enum values for PatchAction -const ( - PatchActionAllowAsDependency PatchAction = "ALLOW_AS_DEPENDENCY" - PatchActionBlock PatchAction = "BLOCK" -) - -// Values returns all known values for PatchAction. 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 (PatchAction) Values() []PatchAction { - return []PatchAction{ - "ALLOW_AS_DEPENDENCY", - "BLOCK", - } -} - -type PatchComplianceDataState string - -// Enum values for PatchComplianceDataState -const ( - PatchComplianceDataStateInstalled PatchComplianceDataState = "INSTALLED" - PatchComplianceDataStateInstalledOther PatchComplianceDataState = "INSTALLED_OTHER" - PatchComplianceDataStateInstalledPendingReboot PatchComplianceDataState = "INSTALLED_PENDING_REBOOT" - PatchComplianceDataStateInstalledRejected PatchComplianceDataState = "INSTALLED_REJECTED" - PatchComplianceDataStateMissing PatchComplianceDataState = "MISSING" - PatchComplianceDataStateNotApplicable PatchComplianceDataState = "NOT_APPLICABLE" - PatchComplianceDataStateFailed PatchComplianceDataState = "FAILED" -) - -// Values returns all known values for PatchComplianceDataState. 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 (PatchComplianceDataState) Values() []PatchComplianceDataState { - return []PatchComplianceDataState{ - "INSTALLED", - "INSTALLED_OTHER", - "INSTALLED_PENDING_REBOOT", - "INSTALLED_REJECTED", - "MISSING", - "NOT_APPLICABLE", - "FAILED", - } -} - -type PatchComplianceLevel string - -// Enum values for PatchComplianceLevel -const ( - PatchComplianceLevelCritical PatchComplianceLevel = "CRITICAL" - PatchComplianceLevelHigh PatchComplianceLevel = "HIGH" - PatchComplianceLevelMedium PatchComplianceLevel = "MEDIUM" - PatchComplianceLevelLow PatchComplianceLevel = "LOW" - PatchComplianceLevelInformational PatchComplianceLevel = "INFORMATIONAL" - PatchComplianceLevelUnspecified PatchComplianceLevel = "UNSPECIFIED" -) - -// Values returns all known values for PatchComplianceLevel. 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 (PatchComplianceLevel) Values() []PatchComplianceLevel { - return []PatchComplianceLevel{ - "CRITICAL", - "HIGH", - "MEDIUM", - "LOW", - "INFORMATIONAL", - "UNSPECIFIED", - } -} - -type PatchDeploymentStatus string - -// Enum values for PatchDeploymentStatus -const ( - PatchDeploymentStatusApproved PatchDeploymentStatus = "APPROVED" - PatchDeploymentStatusPendingApproval PatchDeploymentStatus = "PENDING_APPROVAL" - PatchDeploymentStatusExplicitApproved PatchDeploymentStatus = "EXPLICIT_APPROVED" - PatchDeploymentStatusExplicitRejected PatchDeploymentStatus = "EXPLICIT_REJECTED" -) - -// Values returns all known values for PatchDeploymentStatus. 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 (PatchDeploymentStatus) Values() []PatchDeploymentStatus { - return []PatchDeploymentStatus{ - "APPROVED", - "PENDING_APPROVAL", - "EXPLICIT_APPROVED", - "EXPLICIT_REJECTED", - } -} - -type PatchFilterKey string - -// Enum values for PatchFilterKey -const ( - PatchFilterKeyArch PatchFilterKey = "ARCH" - PatchFilterKeyAdvisoryId PatchFilterKey = "ADVISORY_ID" - PatchFilterKeyBugzillaId PatchFilterKey = "BUGZILLA_ID" - PatchFilterKeyPatchSet PatchFilterKey = "PATCH_SET" - PatchFilterKeyProduct PatchFilterKey = "PRODUCT" - PatchFilterKeyProductFamily PatchFilterKey = "PRODUCT_FAMILY" - PatchFilterKeyClassification PatchFilterKey = "CLASSIFICATION" - PatchFilterKeyCVEId PatchFilterKey = "CVE_ID" - PatchFilterKeyEpoch PatchFilterKey = "EPOCH" - PatchFilterKeyMsrcSeverity PatchFilterKey = "MSRC_SEVERITY" - PatchFilterKeyName PatchFilterKey = "NAME" - PatchFilterKeyPatchId PatchFilterKey = "PATCH_ID" - PatchFilterKeySection PatchFilterKey = "SECTION" - PatchFilterKeyPriority PatchFilterKey = "PRIORITY" - PatchFilterKeyRepository PatchFilterKey = "REPOSITORY" - PatchFilterKeyRelease PatchFilterKey = "RELEASE" - PatchFilterKeySeverity PatchFilterKey = "SEVERITY" - PatchFilterKeySecurity PatchFilterKey = "SECURITY" - PatchFilterKeyVersion PatchFilterKey = "VERSION" -) - -// Values returns all known values for PatchFilterKey. 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 (PatchFilterKey) Values() []PatchFilterKey { - return []PatchFilterKey{ - "ARCH", - "ADVISORY_ID", - "BUGZILLA_ID", - "PATCH_SET", - "PRODUCT", - "PRODUCT_FAMILY", - "CLASSIFICATION", - "CVE_ID", - "EPOCH", - "MSRC_SEVERITY", - "NAME", - "PATCH_ID", - "SECTION", - "PRIORITY", - "REPOSITORY", - "RELEASE", - "SEVERITY", - "SECURITY", - "VERSION", - } -} - -type PatchOperationType string - -// Enum values for PatchOperationType -const ( - PatchOperationTypeScan PatchOperationType = "Scan" - PatchOperationTypeInstall PatchOperationType = "Install" -) - -// Values returns all known values for PatchOperationType. 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 (PatchOperationType) Values() []PatchOperationType { - return []PatchOperationType{ - "Scan", - "Install", - } -} - -type PatchProperty string - -// Enum values for PatchProperty -const ( - PatchPropertyProduct PatchProperty = "PRODUCT" - PatchPropertyPatchProductFamily PatchProperty = "PRODUCT_FAMILY" - PatchPropertyPatchClassification PatchProperty = "CLASSIFICATION" - PatchPropertyPatchMsrcSeverity PatchProperty = "MSRC_SEVERITY" - PatchPropertyPatchPriority PatchProperty = "PRIORITY" - PatchPropertyPatchSeverity PatchProperty = "SEVERITY" -) - -// Values returns all known values for PatchProperty. 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 (PatchProperty) Values() []PatchProperty { - return []PatchProperty{ - "PRODUCT", - "PRODUCT_FAMILY", - "CLASSIFICATION", - "MSRC_SEVERITY", - "PRIORITY", - "SEVERITY", - } -} - -type PatchSet string - -// Enum values for PatchSet -const ( - PatchSetOs PatchSet = "OS" - PatchSetApplication PatchSet = "APPLICATION" -) - -// Values returns all known values for PatchSet. 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 (PatchSet) Values() []PatchSet { - return []PatchSet{ - "OS", - "APPLICATION", - } -} - -type PingStatus string - -// Enum values for PingStatus -const ( - PingStatusOnline PingStatus = "Online" - PingStatusConnectionLost PingStatus = "ConnectionLost" - PingStatusInactive PingStatus = "Inactive" -) - -// Values returns all known values for PingStatus. 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 (PingStatus) Values() []PingStatus { - return []PingStatus{ - "Online", - "ConnectionLost", - "Inactive", - } -} - -type PlatformType string - -// Enum values for PlatformType -const ( - PlatformTypeWindows PlatformType = "Windows" - PlatformTypeLinux PlatformType = "Linux" - PlatformTypeMacos PlatformType = "MacOS" -) - -// Values returns all known values for PlatformType. 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 (PlatformType) Values() []PlatformType { - return []PlatformType{ - "Windows", - "Linux", - "MacOS", - } -} - -type RebootOption string - -// Enum values for RebootOption -const ( - RebootOptionRebootIfNeeded RebootOption = "RebootIfNeeded" - RebootOptionNoReboot RebootOption = "NoReboot" -) - -// Values returns all known values for RebootOption. 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 (RebootOption) Values() []RebootOption { - return []RebootOption{ - "RebootIfNeeded", - "NoReboot", - } -} - -type ResourceDataSyncS3Format string - -// Enum values for ResourceDataSyncS3Format -const ( - ResourceDataSyncS3FormatJsonSerde ResourceDataSyncS3Format = "JsonSerDe" -) - -// Values returns all known values for ResourceDataSyncS3Format. 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 (ResourceDataSyncS3Format) Values() []ResourceDataSyncS3Format { - return []ResourceDataSyncS3Format{ - "JsonSerDe", - } -} - -type ResourceType string - -// Enum values for ResourceType -const ( - ResourceTypeManagedInstance ResourceType = "ManagedInstance" - ResourceTypeEc2Instance ResourceType = "EC2Instance" -) - -// Values returns all known values for ResourceType. 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 (ResourceType) Values() []ResourceType { - return []ResourceType{ - "ManagedInstance", - "EC2Instance", - } -} - -type ResourceTypeForTagging string - -// Enum values for ResourceTypeForTagging -const ( - ResourceTypeForTaggingDocument ResourceTypeForTagging = "Document" - ResourceTypeForTaggingManagedInstance ResourceTypeForTagging = "ManagedInstance" - ResourceTypeForTaggingMaintenanceWindow ResourceTypeForTagging = "MaintenanceWindow" - ResourceTypeForTaggingParameter ResourceTypeForTagging = "Parameter" - ResourceTypeForTaggingPatchBaseline ResourceTypeForTagging = "PatchBaseline" - ResourceTypeForTaggingOpsItem ResourceTypeForTagging = "OpsItem" - ResourceTypeForTaggingOpsmetadata ResourceTypeForTagging = "OpsMetadata" - ResourceTypeForTaggingAutomation ResourceTypeForTagging = "Automation" - ResourceTypeForTaggingAssociation ResourceTypeForTagging = "Association" -) - -// Values returns all known values for ResourceTypeForTagging. 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 (ResourceTypeForTagging) Values() []ResourceTypeForTagging { - return []ResourceTypeForTagging{ - "Document", - "ManagedInstance", - "MaintenanceWindow", - "Parameter", - "PatchBaseline", - "OpsItem", - "OpsMetadata", - "Automation", - "Association", - } -} - -type ReviewStatus string - -// Enum values for ReviewStatus -const ( - ReviewStatusApproved ReviewStatus = "APPROVED" - ReviewStatusNotReviewed ReviewStatus = "NOT_REVIEWED" - ReviewStatusPending ReviewStatus = "PENDING" - ReviewStatusRejected ReviewStatus = "REJECTED" -) - -// Values returns all known values for ReviewStatus. 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 (ReviewStatus) Values() []ReviewStatus { - return []ReviewStatus{ - "APPROVED", - "NOT_REVIEWED", - "PENDING", - "REJECTED", - } -} - -type SessionFilterKey string - -// Enum values for SessionFilterKey -const ( - SessionFilterKeyInvokedAfter SessionFilterKey = "InvokedAfter" - SessionFilterKeyInvokedBefore SessionFilterKey = "InvokedBefore" - SessionFilterKeyTargetId SessionFilterKey = "Target" - SessionFilterKeyOwner SessionFilterKey = "Owner" - SessionFilterKeyStatus SessionFilterKey = "Status" - SessionFilterKeySessionId SessionFilterKey = "SessionId" -) - -// Values returns all known values for SessionFilterKey. 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 (SessionFilterKey) Values() []SessionFilterKey { - return []SessionFilterKey{ - "InvokedAfter", - "InvokedBefore", - "Target", - "Owner", - "Status", - "SessionId", - } -} - -type SessionState string - -// Enum values for SessionState -const ( - SessionStateActive SessionState = "Active" - SessionStateHistory SessionState = "History" -) - -// Values returns all known values for SessionState. 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 (SessionState) Values() []SessionState { - return []SessionState{ - "Active", - "History", - } -} - -type SessionStatus string - -// Enum values for SessionStatus -const ( - SessionStatusConnected SessionStatus = "Connected" - SessionStatusConnecting SessionStatus = "Connecting" - SessionStatusDisconnected SessionStatus = "Disconnected" - SessionStatusTerminated SessionStatus = "Terminated" - SessionStatusTerminating SessionStatus = "Terminating" - SessionStatusFailed SessionStatus = "Failed" -) - -// Values returns all known values for SessionStatus. 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 (SessionStatus) Values() []SessionStatus { - return []SessionStatus{ - "Connected", - "Connecting", - "Disconnected", - "Terminated", - "Terminating", - "Failed", - } -} - -type SignalType string - -// Enum values for SignalType -const ( - SignalTypeApprove SignalType = "Approve" - SignalTypeReject SignalType = "Reject" - SignalTypeStartStep SignalType = "StartStep" - SignalTypeStopStep SignalType = "StopStep" - SignalTypeResume SignalType = "Resume" -) - -// Values returns all known values for SignalType. 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 (SignalType) Values() []SignalType { - return []SignalType{ - "Approve", - "Reject", - "StartStep", - "StopStep", - "Resume", - } -} - -type SourceType string - -// Enum values for SourceType -const ( - SourceTypeAwsEc2Instance SourceType = "AWS::EC2::Instance" - SourceTypeAwsIotThing SourceType = "AWS::IoT::Thing" - SourceTypeAwsSsmManagedinstance SourceType = "AWS::SSM::ManagedInstance" -) - -// Values returns all known values for SourceType. 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 (SourceType) Values() []SourceType { - return []SourceType{ - "AWS::EC2::Instance", - "AWS::IoT::Thing", - "AWS::SSM::ManagedInstance", - } -} - -type StepExecutionFilterKey string - -// Enum values for StepExecutionFilterKey -const ( - StepExecutionFilterKeyStartTimeBefore StepExecutionFilterKey = "StartTimeBefore" - StepExecutionFilterKeyStartTimeAfter StepExecutionFilterKey = "StartTimeAfter" - StepExecutionFilterKeyStepExecutionStatus StepExecutionFilterKey = "StepExecutionStatus" - StepExecutionFilterKeyStepExecutionId StepExecutionFilterKey = "StepExecutionId" - StepExecutionFilterKeyStepName StepExecutionFilterKey = "StepName" - StepExecutionFilterKeyAction StepExecutionFilterKey = "Action" - StepExecutionFilterKeyParentStepExecutionId StepExecutionFilterKey = "ParentStepExecutionId" - StepExecutionFilterKeyParentStepIteration StepExecutionFilterKey = "ParentStepIteration" - StepExecutionFilterKeyParentStepIteratorValue StepExecutionFilterKey = "ParentStepIteratorValue" -) - -// Values returns all known values for StepExecutionFilterKey. 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 (StepExecutionFilterKey) Values() []StepExecutionFilterKey { - return []StepExecutionFilterKey{ - "StartTimeBefore", - "StartTimeAfter", - "StepExecutionStatus", - "StepExecutionId", - "StepName", - "Action", - "ParentStepExecutionId", - "ParentStepIteration", - "ParentStepIteratorValue", - } -} - -type StopType string - -// Enum values for StopType -const ( - StopTypeComplete StopType = "Complete" - StopTypeCancel StopType = "Cancel" -) - -// Values returns all known values for StopType. 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 (StopType) Values() []StopType { - return []StopType{ - "Complete", - "Cancel", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/types/errors.go deleted file mode 100644 index 61ec235e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/types/errors.go +++ /dev/null @@ -1,3567 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - "fmt" - smithy "github.com/aws/smithy-go" -) - -// Error returned if an attempt is made to register a patch group with a patch -// baseline that is already registered with a different patch baseline. -type AlreadyExistsException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AlreadyExistsException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AlreadyExistsException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AlreadyExistsException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AlreadyExistsException" - } - return *e.ErrorCodeOverride -} -func (e *AlreadyExistsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You must disassociate a document from all managed nodes before you can delete -// it. -type AssociatedInstances struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AssociatedInstances) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AssociatedInstances) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AssociatedInstances) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AssociatedInstances" - } - return *e.ErrorCodeOverride -} -func (e *AssociatedInstances) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified association already exists. -type AssociationAlreadyExists struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AssociationAlreadyExists) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AssociationAlreadyExists) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AssociationAlreadyExists) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AssociationAlreadyExists" - } - return *e.ErrorCodeOverride -} -func (e *AssociationAlreadyExists) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified association doesn't exist. -type AssociationDoesNotExist struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AssociationDoesNotExist) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AssociationDoesNotExist) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AssociationDoesNotExist) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AssociationDoesNotExist" - } - return *e.ErrorCodeOverride -} -func (e *AssociationDoesNotExist) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified execution ID doesn't exist. Verify the ID number and try again. -type AssociationExecutionDoesNotExist struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AssociationExecutionDoesNotExist) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AssociationExecutionDoesNotExist) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AssociationExecutionDoesNotExist) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AssociationExecutionDoesNotExist" - } - return *e.ErrorCodeOverride -} -func (e *AssociationExecutionDoesNotExist) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You can have at most 2,000 active associations. -type AssociationLimitExceeded struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AssociationLimitExceeded) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AssociationLimitExceeded) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AssociationLimitExceeded) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AssociationLimitExceeded" - } - return *e.ErrorCodeOverride -} -func (e *AssociationLimitExceeded) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You have reached the maximum number versions allowed for an association. Each -// association has a limit of 1,000 versions. -type AssociationVersionLimitExceeded struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AssociationVersionLimitExceeded) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AssociationVersionLimitExceeded) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AssociationVersionLimitExceeded) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AssociationVersionLimitExceeded" - } - return *e.ErrorCodeOverride -} -func (e *AssociationVersionLimitExceeded) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the Change Manager change template used in the change request -// was rejected or is still in a pending state. -type AutomationDefinitionNotApprovedException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AutomationDefinitionNotApprovedException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AutomationDefinitionNotApprovedException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AutomationDefinitionNotApprovedException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AutomationDefinitionNotApprovedException" - } - return *e.ErrorCodeOverride -} -func (e *AutomationDefinitionNotApprovedException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// An Automation runbook with the specified name couldn't be found. -type AutomationDefinitionNotFoundException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AutomationDefinitionNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AutomationDefinitionNotFoundException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AutomationDefinitionNotFoundException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AutomationDefinitionNotFoundException" - } - return *e.ErrorCodeOverride -} -func (e *AutomationDefinitionNotFoundException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// An Automation runbook with the specified name and version couldn't be found. -type AutomationDefinitionVersionNotFoundException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AutomationDefinitionVersionNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AutomationDefinitionVersionNotFoundException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AutomationDefinitionVersionNotFoundException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AutomationDefinitionVersionNotFoundException" - } - return *e.ErrorCodeOverride -} -func (e *AutomationDefinitionVersionNotFoundException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The number of simultaneously running Automation executions exceeded the -// allowable limit. -type AutomationExecutionLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AutomationExecutionLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AutomationExecutionLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AutomationExecutionLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AutomationExecutionLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *AutomationExecutionLimitExceededException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// There is no automation execution information for the requested automation -// execution ID. -type AutomationExecutionNotFoundException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AutomationExecutionNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AutomationExecutionNotFoundException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AutomationExecutionNotFoundException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AutomationExecutionNotFoundException" - } - return *e.ErrorCodeOverride -} -func (e *AutomationExecutionNotFoundException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The specified step name and execution ID don't exist. Verify the information -// and try again. -type AutomationStepNotFoundException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *AutomationStepNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AutomationStepNotFoundException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AutomationStepNotFoundException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AutomationStepNotFoundException" - } - return *e.ErrorCodeOverride -} -func (e *AutomationStepNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You specified too many custom compliance types. You can specify a maximum of 10 -// different types. -type ComplianceTypeCountLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ComplianceTypeCountLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ComplianceTypeCountLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ComplianceTypeCountLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ComplianceTypeCountLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *ComplianceTypeCountLimitExceededException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// You have exceeded the limit for custom schemas. Delete one or more custom -// schemas and try again. -type CustomSchemaCountLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *CustomSchemaCountLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *CustomSchemaCountLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *CustomSchemaCountLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "CustomSchemaCountLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *CustomSchemaCountLimitExceededException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The specified document already exists. -type DocumentAlreadyExists struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *DocumentAlreadyExists) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *DocumentAlreadyExists) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *DocumentAlreadyExists) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "DocumentAlreadyExists" - } - return *e.ErrorCodeOverride -} -func (e *DocumentAlreadyExists) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You can have at most 500 active SSM documents. -type DocumentLimitExceeded struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *DocumentLimitExceeded) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *DocumentLimitExceeded) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *DocumentLimitExceeded) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "DocumentLimitExceeded" - } - return *e.ErrorCodeOverride -} -func (e *DocumentLimitExceeded) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The document can't be shared with more Amazon Web Services accounts. You can -// specify a maximum of 20 accounts per API operation to share a private document. -// By default, you can share a private document with a maximum of 1,000 accounts -// and publicly share up to five documents. If you need to increase the quota for -// privately or publicly shared Systems Manager documents, contact Amazon Web -// Services Support. -type DocumentPermissionLimit struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *DocumentPermissionLimit) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *DocumentPermissionLimit) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *DocumentPermissionLimit) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "DocumentPermissionLimit" - } - return *e.ErrorCodeOverride -} -func (e *DocumentPermissionLimit) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The document has too many versions. Delete one or more document versions and -// try again. -type DocumentVersionLimitExceeded struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *DocumentVersionLimitExceeded) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *DocumentVersionLimitExceeded) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *DocumentVersionLimitExceeded) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "DocumentVersionLimitExceeded" - } - return *e.ErrorCodeOverride -} -func (e *DocumentVersionLimitExceeded) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Error returned when the ID specified for a resource, such as a maintenance -// window or patch baseline, doesn't exist. For information about resource quotas -// in Amazon Web Services Systems Manager, see Systems Manager service quotas (https://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) -// in the Amazon Web Services General Reference. -type DoesNotExistException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *DoesNotExistException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *DoesNotExistException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *DoesNotExistException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "DoesNotExistException" - } - return *e.ErrorCodeOverride -} -func (e *DoesNotExistException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The content of the association document matches another document. Change the -// content of the document and try again. -type DuplicateDocumentContent struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *DuplicateDocumentContent) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *DuplicateDocumentContent) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *DuplicateDocumentContent) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "DuplicateDocumentContent" - } - return *e.ErrorCodeOverride -} -func (e *DuplicateDocumentContent) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The version name has already been used in this document. Specify a different -// version name, and then try again. -type DuplicateDocumentVersionName struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *DuplicateDocumentVersionName) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *DuplicateDocumentVersionName) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *DuplicateDocumentVersionName) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "DuplicateDocumentVersionName" - } - return *e.ErrorCodeOverride -} -func (e *DuplicateDocumentVersionName) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You can't specify a managed node ID in more than one association. -type DuplicateInstanceId struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *DuplicateInstanceId) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *DuplicateInstanceId) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *DuplicateInstanceId) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "DuplicateInstanceId" - } - return *e.ErrorCodeOverride -} -func (e *DuplicateInstanceId) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You attempted to register a LAMBDA or STEP_FUNCTIONS task in a region where the -// corresponding service isn't available. -type FeatureNotAvailableException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *FeatureNotAvailableException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *FeatureNotAvailableException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *FeatureNotAvailableException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "FeatureNotAvailableException" - } - return *e.ErrorCodeOverride -} -func (e *FeatureNotAvailableException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// A hierarchy can have a maximum of 15 levels. For more information, see -// Requirements and constraints for parameter names (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-parameter-name-constraints.html) -// in the Amazon Web Services Systems Manager User Guide. -type HierarchyLevelLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *HierarchyLevelLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *HierarchyLevelLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *HierarchyLevelLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "HierarchyLevelLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *HierarchyLevelLimitExceededException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// Parameter Store doesn't support changing a parameter type in a hierarchy. For -// example, you can't change a parameter from a String type to a SecureString -// type. You must create a new, unique parameter. -type HierarchyTypeMismatchException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *HierarchyTypeMismatchException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *HierarchyTypeMismatchException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *HierarchyTypeMismatchException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "HierarchyTypeMismatchException" - } - return *e.ErrorCodeOverride -} -func (e *HierarchyTypeMismatchException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Error returned when an idempotent operation is retried and the parameters don't -// match the original call to the API with the same idempotency token. -type IdempotentParameterMismatch struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *IdempotentParameterMismatch) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *IdempotentParameterMismatch) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *IdempotentParameterMismatch) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "IdempotentParameterMismatch" - } - return *e.ErrorCodeOverride -} -func (e *IdempotentParameterMismatch) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// There is a conflict in the policies specified for this parameter. You can't, -// for example, specify two Expiration policies for a parameter. Review your -// policies, and try again. -type IncompatiblePolicyException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *IncompatiblePolicyException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *IncompatiblePolicyException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *IncompatiblePolicyException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "IncompatiblePolicyException" - } - return *e.ErrorCodeOverride -} -func (e *IncompatiblePolicyException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// An error occurred on the server side. -type InternalServerError struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InternalServerError) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InternalServerError) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InternalServerError) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InternalServerError" - } - return *e.ErrorCodeOverride -} -func (e *InternalServerError) ErrorFault() smithy.ErrorFault { return smithy.FaultServer } - -// The activation isn't valid. The activation might have been deleted, or the -// ActivationId and the ActivationCode don't match. -type InvalidActivation struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidActivation) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidActivation) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidActivation) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidActivation" - } - return *e.ErrorCodeOverride -} -func (e *InvalidActivation) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The activation ID isn't valid. Verify the you entered the correct ActivationId -// or ActivationCode and try again. -type InvalidActivationId struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidActivationId) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidActivationId) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidActivationId) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidActivationId" - } - return *e.ErrorCodeOverride -} -func (e *InvalidActivationId) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified aggregator isn't valid for inventory groups. Verify that the -// aggregator uses a valid inventory type such as AWS:Application or -// AWS:InstanceInformation . -type InvalidAggregatorException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidAggregatorException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidAggregatorException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidAggregatorException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidAggregatorException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidAggregatorException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The request doesn't meet the regular expression requirement. -type InvalidAllowedPatternException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidAllowedPatternException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidAllowedPatternException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidAllowedPatternException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidAllowedPatternException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidAllowedPatternException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The association isn't valid or doesn't exist. -type InvalidAssociation struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidAssociation) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidAssociation) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidAssociation) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidAssociation" - } - return *e.ErrorCodeOverride -} -func (e *InvalidAssociation) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The version you specified isn't valid. Use ListAssociationVersions to view all -// versions of an association according to the association ID. Or, use the $LATEST -// parameter to view the latest version of the association. -type InvalidAssociationVersion struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidAssociationVersion) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidAssociationVersion) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidAssociationVersion) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidAssociationVersion" - } - return *e.ErrorCodeOverride -} -func (e *InvalidAssociationVersion) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The supplied parameters for invoking the specified Automation runbook are -// incorrect. For example, they may not match the set of parameters permitted for -// the specified Automation document. -type InvalidAutomationExecutionParametersException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidAutomationExecutionParametersException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidAutomationExecutionParametersException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidAutomationExecutionParametersException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidAutomationExecutionParametersException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidAutomationExecutionParametersException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The signal isn't valid for the current Automation execution. -type InvalidAutomationSignalException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidAutomationSignalException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidAutomationSignalException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidAutomationSignalException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidAutomationSignalException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidAutomationSignalException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified update status operation isn't valid. -type InvalidAutomationStatusUpdateException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidAutomationStatusUpdateException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidAutomationStatusUpdateException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidAutomationStatusUpdateException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidAutomationStatusUpdateException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidAutomationStatusUpdateException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The specified command ID isn't valid. Verify the ID and try again. -type InvalidCommandId struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidCommandId) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidCommandId) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidCommandId) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidCommandId" - } - return *e.ErrorCodeOverride -} -func (e *InvalidCommandId) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// One or more of the parameters specified for the delete operation isn't valid. -// Verify all parameters and try again. -type InvalidDeleteInventoryParametersException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidDeleteInventoryParametersException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidDeleteInventoryParametersException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidDeleteInventoryParametersException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidDeleteInventoryParametersException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidDeleteInventoryParametersException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The ID specified for the delete operation doesn't exist or isn't valid. Verify -// the ID and try again. -type InvalidDeletionIdException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidDeletionIdException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidDeletionIdException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidDeletionIdException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidDeletionIdException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidDeletionIdException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified SSM document doesn't exist. -type InvalidDocument struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidDocument) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidDocument) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidDocument) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidDocument" - } - return *e.ErrorCodeOverride -} -func (e *InvalidDocument) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The content for the document isn't valid. -type InvalidDocumentContent struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidDocumentContent) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidDocumentContent) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidDocumentContent) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidDocumentContent" - } - return *e.ErrorCodeOverride -} -func (e *InvalidDocumentContent) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You attempted to delete a document while it is still shared. You must stop -// sharing the document before you can delete it. -type InvalidDocumentOperation struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidDocumentOperation) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidDocumentOperation) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidDocumentOperation) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidDocumentOperation" - } - return *e.ErrorCodeOverride -} -func (e *InvalidDocumentOperation) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The version of the document schema isn't supported. -type InvalidDocumentSchemaVersion struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidDocumentSchemaVersion) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidDocumentSchemaVersion) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidDocumentSchemaVersion) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidDocumentSchemaVersion" - } - return *e.ErrorCodeOverride -} -func (e *InvalidDocumentSchemaVersion) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The SSM document type isn't valid. Valid document types are described in the -// DocumentType property. -type InvalidDocumentType struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidDocumentType) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidDocumentType) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidDocumentType) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidDocumentType" - } - return *e.ErrorCodeOverride -} -func (e *InvalidDocumentType) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The document version isn't valid or doesn't exist. -type InvalidDocumentVersion struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidDocumentVersion) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidDocumentVersion) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidDocumentVersion) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidDocumentVersion" - } - return *e.ErrorCodeOverride -} -func (e *InvalidDocumentVersion) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The filter name isn't valid. Verify the you entered the correct name and try -// again. -type InvalidFilter struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidFilter) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidFilter) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidFilter) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidFilter" - } - return *e.ErrorCodeOverride -} -func (e *InvalidFilter) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified key isn't valid. -type InvalidFilterKey struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidFilterKey) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidFilterKey) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidFilterKey) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidFilterKey" - } - return *e.ErrorCodeOverride -} -func (e *InvalidFilterKey) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified filter option isn't valid. Valid options are Equals and -// BeginsWith. For Path filter, valid options are Recursive and OneLevel. -type InvalidFilterOption struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidFilterOption) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidFilterOption) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidFilterOption) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidFilterOption" - } - return *e.ErrorCodeOverride -} -func (e *InvalidFilterOption) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The filter value isn't valid. Verify the value and try again. -type InvalidFilterValue struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidFilterValue) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidFilterValue) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidFilterValue) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidFilterValue" - } - return *e.ErrorCodeOverride -} -func (e *InvalidFilterValue) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The following problems can cause this exception: -// - You don't have permission to access the managed node. -// - Amazon Web Services Systems Manager Agent(SSM Agent) isn't running. Verify -// that SSM Agent is running. -// - SSM Agent isn't registered with the SSM endpoint. Try reinstalling SSM -// Agent. -// - The managed node isn't in valid state. Valid states are: Running , Pending , -// Stopped , and Stopping . Invalid states are: Shutting-down and Terminated . -type InvalidInstanceId struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidInstanceId) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidInstanceId) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidInstanceId) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidInstanceId" - } - return *e.ErrorCodeOverride -} -func (e *InvalidInstanceId) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified filter value isn't valid. -type InvalidInstanceInformationFilterValue struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidInstanceInformationFilterValue) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidInstanceInformationFilterValue) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidInstanceInformationFilterValue) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidInstanceInformationFilterValue" - } - return *e.ErrorCodeOverride -} -func (e *InvalidInstanceInformationFilterValue) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The specified inventory group isn't valid. -type InvalidInventoryGroupException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidInventoryGroupException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidInventoryGroupException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidInventoryGroupException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidInventoryGroupException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidInventoryGroupException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You specified invalid keys or values in the Context attribute for InventoryItem -// . Verify the keys and values, and try again. -type InvalidInventoryItemContextException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidInventoryItemContextException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidInventoryItemContextException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidInventoryItemContextException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidInventoryItemContextException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidInventoryItemContextException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The request isn't valid. -type InvalidInventoryRequestException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidInventoryRequestException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidInventoryRequestException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidInventoryRequestException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidInventoryRequestException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidInventoryRequestException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// One or more content items isn't valid. -type InvalidItemContentException struct { - Message *string - - ErrorCodeOverride *string - - TypeName *string - - noSmithyDocumentSerde -} - -func (e *InvalidItemContentException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidItemContentException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidItemContentException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidItemContentException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidItemContentException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The query key ID isn't valid. -type InvalidKeyId struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidKeyId) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidKeyId) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidKeyId) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidKeyId" - } - return *e.ErrorCodeOverride -} -func (e *InvalidKeyId) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified token isn't valid. -type InvalidNextToken struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidNextToken) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidNextToken) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidNextToken) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidNextToken" - } - return *e.ErrorCodeOverride -} -func (e *InvalidNextToken) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// One or more configuration items isn't valid. Verify that a valid Amazon -// Resource Name (ARN) was provided for an Amazon Simple Notification Service -// topic. -type InvalidNotificationConfig struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidNotificationConfig) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidNotificationConfig) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidNotificationConfig) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidNotificationConfig" - } - return *e.ErrorCodeOverride -} -func (e *InvalidNotificationConfig) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The delete inventory option specified isn't valid. Verify the option and try -// again. -type InvalidOptionException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidOptionException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidOptionException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidOptionException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidOptionException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidOptionException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The S3 bucket doesn't exist. -type InvalidOutputFolder struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidOutputFolder) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidOutputFolder) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidOutputFolder) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidOutputFolder" - } - return *e.ErrorCodeOverride -} -func (e *InvalidOutputFolder) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The output location isn't valid or doesn't exist. -type InvalidOutputLocation struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidOutputLocation) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidOutputLocation) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidOutputLocation) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidOutputLocation" - } - return *e.ErrorCodeOverride -} -func (e *InvalidOutputLocation) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You must specify values for all required parameters in the Amazon Web Services -// Systems Manager document (SSM document). You can only supply values to -// parameters defined in the SSM document. -type InvalidParameters struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidParameters) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidParameters) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidParameters) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidParameters" - } - return *e.ErrorCodeOverride -} -func (e *InvalidParameters) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The permission type isn't supported. Share is the only supported permission -// type. -type InvalidPermissionType struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidPermissionType) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidPermissionType) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidPermissionType) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidPermissionType" - } - return *e.ErrorCodeOverride -} -func (e *InvalidPermissionType) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The plugin name isn't valid. -type InvalidPluginName struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidPluginName) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidPluginName) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidPluginName) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidPluginName" - } - return *e.ErrorCodeOverride -} -func (e *InvalidPluginName) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// A policy attribute or its value is invalid. -type InvalidPolicyAttributeException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidPolicyAttributeException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidPolicyAttributeException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidPolicyAttributeException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidPolicyAttributeException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidPolicyAttributeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The policy type isn't supported. Parameter Store supports the following policy -// types: Expiration, ExpirationNotification, and NoChangeNotification. -type InvalidPolicyTypeException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidPolicyTypeException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidPolicyTypeException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidPolicyTypeException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidPolicyTypeException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidPolicyTypeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The resource ID isn't valid. Verify that you entered the correct ID and try -// again. -type InvalidResourceId struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidResourceId) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidResourceId) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidResourceId) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidResourceId" - } - return *e.ErrorCodeOverride -} -func (e *InvalidResourceId) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The resource type isn't valid. For example, if you are attempting to tag an EC2 -// instance, the instance must be a registered managed node. -type InvalidResourceType struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidResourceType) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidResourceType) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidResourceType) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidResourceType" - } - return *e.ErrorCodeOverride -} -func (e *InvalidResourceType) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified inventory item result attribute isn't valid. -type InvalidResultAttributeException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidResultAttributeException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidResultAttributeException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidResultAttributeException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidResultAttributeException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidResultAttributeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The role name can't contain invalid characters. Also verify that you specified -// an IAM role for notifications that includes the required trust policy. For -// information about configuring the IAM role for Run Command notifications, see -// Configuring Amazon SNS Notifications for Run Command (https://docs.aws.amazon.com/systems-manager/latest/userguide/rc-sns-notifications.html) -// in the Amazon Web Services Systems Manager User Guide. -type InvalidRole struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidRole) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidRole) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidRole) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidRole" - } - return *e.ErrorCodeOverride -} -func (e *InvalidRole) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The schedule is invalid. Verify your cron or rate expression and try again. -type InvalidSchedule struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidSchedule) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidSchedule) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidSchedule) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidSchedule" - } - return *e.ErrorCodeOverride -} -func (e *InvalidSchedule) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified tag key or value isn't valid. -type InvalidTag struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidTag) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidTag) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidTag) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidTag" - } - return *e.ErrorCodeOverride -} -func (e *InvalidTag) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The target isn't valid or doesn't exist. It might not be configured for Systems -// Manager or you might not have permission to perform the operation. -type InvalidTarget struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidTarget) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidTarget) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidTarget) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidTarget" - } - return *e.ErrorCodeOverride -} -func (e *InvalidTarget) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// TargetMap parameter isn't valid. -type InvalidTargetMaps struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidTargetMaps) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidTargetMaps) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidTargetMaps) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidTargetMaps" - } - return *e.ErrorCodeOverride -} -func (e *InvalidTargetMaps) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The parameter type name isn't valid. -type InvalidTypeNameException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidTypeNameException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidTypeNameException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidTypeNameException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidTypeNameException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidTypeNameException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The update isn't valid. -type InvalidUpdate struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidUpdate) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidUpdate) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidUpdate) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidUpdate" - } - return *e.ErrorCodeOverride -} -func (e *InvalidUpdate) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The command ID and managed node ID you specified didn't match any invocations. -// Verify the command ID and the managed node ID and try again. -type InvocationDoesNotExist struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvocationDoesNotExist) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvocationDoesNotExist) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvocationDoesNotExist) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvocationDoesNotExist" - } - return *e.ErrorCodeOverride -} -func (e *InvocationDoesNotExist) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The inventory item has invalid content. -type ItemContentMismatchException struct { - Message *string - - ErrorCodeOverride *string - - TypeName *string - - noSmithyDocumentSerde -} - -func (e *ItemContentMismatchException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ItemContentMismatchException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ItemContentMismatchException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ItemContentMismatchException" - } - return *e.ErrorCodeOverride -} -func (e *ItemContentMismatchException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The inventory item size has exceeded the size limit. -type ItemSizeLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - TypeName *string - - noSmithyDocumentSerde -} - -func (e *ItemSizeLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ItemSizeLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ItemSizeLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ItemSizeLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *ItemSizeLimitExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The size limit of a document is 64 KB. -type MaxDocumentSizeExceeded struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *MaxDocumentSizeExceeded) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *MaxDocumentSizeExceeded) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *MaxDocumentSizeExceeded) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "MaxDocumentSizeExceeded" - } - return *e.ErrorCodeOverride -} -func (e *MaxDocumentSizeExceeded) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You don't have permission to view OpsItems in the specified account. Verify -// that your account is configured either as a Systems Manager delegated -// administrator or that you are logged into the Organizations management account. -type OpsItemAccessDeniedException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *OpsItemAccessDeniedException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsItemAccessDeniedException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsItemAccessDeniedException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsItemAccessDeniedException" - } - return *e.ErrorCodeOverride -} -func (e *OpsItemAccessDeniedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The OpsItem already exists. -type OpsItemAlreadyExistsException struct { - Message *string - - ErrorCodeOverride *string - - OpsItemId *string - - noSmithyDocumentSerde -} - -func (e *OpsItemAlreadyExistsException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsItemAlreadyExistsException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsItemAlreadyExistsException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsItemAlreadyExistsException" - } - return *e.ErrorCodeOverride -} -func (e *OpsItemAlreadyExistsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified OpsItem is in the process of being deleted. -type OpsItemConflictException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *OpsItemConflictException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsItemConflictException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsItemConflictException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsItemConflictException" - } - return *e.ErrorCodeOverride -} -func (e *OpsItemConflictException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// A specified parameter argument isn't valid. Verify the available arguments and -// try again. -type OpsItemInvalidParameterException struct { - Message *string - - ErrorCodeOverride *string - - ParameterNames []string - - noSmithyDocumentSerde -} - -func (e *OpsItemInvalidParameterException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsItemInvalidParameterException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsItemInvalidParameterException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsItemInvalidParameterException" - } - return *e.ErrorCodeOverride -} -func (e *OpsItemInvalidParameterException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The request caused OpsItems to exceed one or more quotas. -type OpsItemLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - ResourceTypes []string - Limit int32 - LimitType *string - - noSmithyDocumentSerde -} - -func (e *OpsItemLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsItemLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsItemLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsItemLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *OpsItemLimitExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified OpsItem ID doesn't exist. Verify the ID and try again. -type OpsItemNotFoundException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *OpsItemNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsItemNotFoundException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsItemNotFoundException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsItemNotFoundException" - } - return *e.ErrorCodeOverride -} -func (e *OpsItemNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The Amazon Resource Name (ARN) is already associated with the OpsItem. -type OpsItemRelatedItemAlreadyExistsException struct { - Message *string - - ErrorCodeOverride *string - - ResourceUri *string - OpsItemId *string - - noSmithyDocumentSerde -} - -func (e *OpsItemRelatedItemAlreadyExistsException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsItemRelatedItemAlreadyExistsException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsItemRelatedItemAlreadyExistsException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsItemRelatedItemAlreadyExistsException" - } - return *e.ErrorCodeOverride -} -func (e *OpsItemRelatedItemAlreadyExistsException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The association wasn't found using the parameters you specified in the call. -// Verify the information and try again. -type OpsItemRelatedItemAssociationNotFoundException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *OpsItemRelatedItemAssociationNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsItemRelatedItemAssociationNotFoundException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsItemRelatedItemAssociationNotFoundException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsItemRelatedItemAssociationNotFoundException" - } - return *e.ErrorCodeOverride -} -func (e *OpsItemRelatedItemAssociationNotFoundException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// An OpsMetadata object already exists for the selected resource. -type OpsMetadataAlreadyExistsException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *OpsMetadataAlreadyExistsException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsMetadataAlreadyExistsException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsMetadataAlreadyExistsException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsMetadataAlreadyExistsException" - } - return *e.ErrorCodeOverride -} -func (e *OpsMetadataAlreadyExistsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// One of the arguments passed is invalid. -type OpsMetadataInvalidArgumentException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *OpsMetadataInvalidArgumentException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsMetadataInvalidArgumentException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsMetadataInvalidArgumentException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsMetadataInvalidArgumentException" - } - return *e.ErrorCodeOverride -} -func (e *OpsMetadataInvalidArgumentException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The OpsMetadata object exceeds the maximum number of OpsMetadata keys that you -// can assign to an application in Application Manager. -type OpsMetadataKeyLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *OpsMetadataKeyLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsMetadataKeyLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsMetadataKeyLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsMetadataKeyLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *OpsMetadataKeyLimitExceededException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// Your account reached the maximum number of OpsMetadata objects allowed by -// Application Manager. The maximum is 200 OpsMetadata objects. Delete one or more -// OpsMetadata object and try again. -type OpsMetadataLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *OpsMetadataLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsMetadataLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsMetadataLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsMetadataLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *OpsMetadataLimitExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The OpsMetadata object doesn't exist. -type OpsMetadataNotFoundException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *OpsMetadataNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsMetadataNotFoundException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsMetadataNotFoundException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsMetadataNotFoundException" - } - return *e.ErrorCodeOverride -} -func (e *OpsMetadataNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The system is processing too many concurrent updates. Wait a few moments and -// try again. -type OpsMetadataTooManyUpdatesException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *OpsMetadataTooManyUpdatesException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *OpsMetadataTooManyUpdatesException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *OpsMetadataTooManyUpdatesException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "OpsMetadataTooManyUpdatesException" - } - return *e.ErrorCodeOverride -} -func (e *OpsMetadataTooManyUpdatesException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The parameter already exists. You can't create duplicate parameters. -type ParameterAlreadyExists struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ParameterAlreadyExists) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ParameterAlreadyExists) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ParameterAlreadyExists) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ParameterAlreadyExists" - } - return *e.ErrorCodeOverride -} -func (e *ParameterAlreadyExists) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You have exceeded the number of parameters for this Amazon Web Services -// account. Delete one or more parameters and try again. -type ParameterLimitExceeded struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ParameterLimitExceeded) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ParameterLimitExceeded) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ParameterLimitExceeded) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ParameterLimitExceeded" - } - return *e.ErrorCodeOverride -} -func (e *ParameterLimitExceeded) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Parameter Store retains the 100 most recently created versions of a parameter. -// After this number of versions has been created, Parameter Store deletes the -// oldest version when a new one is created. However, if the oldest version has a -// label attached to it, Parameter Store won't delete the version and instead -// presents this error message: An error occurred -// (ParameterMaxVersionLimitExceeded) when calling the PutParameter operation: You -// attempted to create a new version of parameter-name by calling the PutParameter -// API with the overwrite flag. Version version-number, the oldest version, can't -// be deleted because it has a label associated with it. Move the label to another -// version of the parameter, and try again. This safeguard is to prevent parameter -// versions with mission critical labels assigned to them from being deleted. To -// continue creating new parameters, first move the label from the oldest version -// of the parameter to a newer one for use in your operations. For information -// about moving parameter labels, see Move a parameter label (console) (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html#sysman-paramstore-labels-console-move) -// or Move a parameter label (CLI) (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html#sysman-paramstore-labels-cli-move) -// in the Amazon Web Services Systems Manager User Guide. -type ParameterMaxVersionLimitExceeded struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ParameterMaxVersionLimitExceeded) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ParameterMaxVersionLimitExceeded) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ParameterMaxVersionLimitExceeded) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ParameterMaxVersionLimitExceeded" - } - return *e.ErrorCodeOverride -} -func (e *ParameterMaxVersionLimitExceeded) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The parameter couldn't be found. Verify the name and try again. -type ParameterNotFound struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ParameterNotFound) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ParameterNotFound) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ParameterNotFound) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ParameterNotFound" - } - return *e.ErrorCodeOverride -} -func (e *ParameterNotFound) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The parameter name isn't valid. -type ParameterPatternMismatchException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ParameterPatternMismatchException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ParameterPatternMismatchException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ParameterPatternMismatchException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ParameterPatternMismatchException" - } - return *e.ErrorCodeOverride -} -func (e *ParameterPatternMismatchException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// A parameter version can have a maximum of ten labels. -type ParameterVersionLabelLimitExceeded struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ParameterVersionLabelLimitExceeded) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ParameterVersionLabelLimitExceeded) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ParameterVersionLabelLimitExceeded) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ParameterVersionLabelLimitExceeded" - } - return *e.ErrorCodeOverride -} -func (e *ParameterVersionLabelLimitExceeded) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The specified parameter version wasn't found. Verify the parameter name and -// version, and try again. -type ParameterVersionNotFound struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ParameterVersionNotFound) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ParameterVersionNotFound) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ParameterVersionNotFound) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ParameterVersionNotFound" - } - return *e.ErrorCodeOverride -} -func (e *ParameterVersionNotFound) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You specified more than the maximum number of allowed policies for the -// parameter. The maximum is 10. -type PoliciesLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *PoliciesLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *PoliciesLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *PoliciesLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "PoliciesLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *PoliciesLimitExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// A sync configuration with the same name already exists. -type ResourceDataSyncAlreadyExistsException struct { - Message *string - - ErrorCodeOverride *string - - SyncName *string - - noSmithyDocumentSerde -} - -func (e *ResourceDataSyncAlreadyExistsException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourceDataSyncAlreadyExistsException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourceDataSyncAlreadyExistsException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourceDataSyncAlreadyExistsException" - } - return *e.ErrorCodeOverride -} -func (e *ResourceDataSyncAlreadyExistsException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// Another UpdateResourceDataSync request is being processed. Wait a few minutes -// and try again. -type ResourceDataSyncConflictException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ResourceDataSyncConflictException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourceDataSyncConflictException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourceDataSyncConflictException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourceDataSyncConflictException" - } - return *e.ErrorCodeOverride -} -func (e *ResourceDataSyncConflictException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// You have exceeded the allowed maximum sync configurations. -type ResourceDataSyncCountExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ResourceDataSyncCountExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourceDataSyncCountExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourceDataSyncCountExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourceDataSyncCountExceededException" - } - return *e.ErrorCodeOverride -} -func (e *ResourceDataSyncCountExceededException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The specified sync configuration is invalid. -type ResourceDataSyncInvalidConfigurationException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ResourceDataSyncInvalidConfigurationException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourceDataSyncInvalidConfigurationException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourceDataSyncInvalidConfigurationException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourceDataSyncInvalidConfigurationException" - } - return *e.ErrorCodeOverride -} -func (e *ResourceDataSyncInvalidConfigurationException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The specified sync name wasn't found. -type ResourceDataSyncNotFoundException struct { - Message *string - - ErrorCodeOverride *string - - SyncName *string - SyncType *string - - noSmithyDocumentSerde -} - -func (e *ResourceDataSyncNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourceDataSyncNotFoundException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourceDataSyncNotFoundException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourceDataSyncNotFoundException" - } - return *e.ErrorCodeOverride -} -func (e *ResourceDataSyncNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Error returned if an attempt is made to delete a patch baseline that is -// registered for a patch group. -type ResourceInUseException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ResourceInUseException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourceInUseException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourceInUseException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourceInUseException" - } - return *e.ErrorCodeOverride -} -func (e *ResourceInUseException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Error returned when the caller has exceeded the default resource quotas. For -// example, too many maintenance windows or patch baselines have been created. For -// information about resource quotas in Systems Manager, see Systems Manager -// service quotas (https://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) -// in the Amazon Web Services General Reference. -type ResourceLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ResourceLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourceLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourceLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourceLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *ResourceLimitExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The hash provided in the call doesn't match the stored hash. This exception is -// thrown when trying to update an obsolete policy version or when multiple -// requests to update a policy are sent. -type ResourcePolicyConflictException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ResourcePolicyConflictException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourcePolicyConflictException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourcePolicyConflictException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourcePolicyConflictException" - } - return *e.ErrorCodeOverride -} -func (e *ResourcePolicyConflictException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// One or more parameters specified for the call aren't valid. Verify the -// parameters and their values and try again. -type ResourcePolicyInvalidParameterException struct { - Message *string - - ErrorCodeOverride *string - - ParameterNames []string - - noSmithyDocumentSerde -} - -func (e *ResourcePolicyInvalidParameterException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourcePolicyInvalidParameterException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourcePolicyInvalidParameterException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourcePolicyInvalidParameterException" - } - return *e.ErrorCodeOverride -} -func (e *ResourcePolicyInvalidParameterException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The PutResourcePolicy API action enforces two limits. A policy can't be greater -// than 1024 bytes in size. And only one policy can be attached to OpsItemGroup . -// Verify these limits and try again. -type ResourcePolicyLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - Limit int32 - LimitType *string - - noSmithyDocumentSerde -} - -func (e *ResourcePolicyLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourcePolicyLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourcePolicyLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourcePolicyLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *ResourcePolicyLimitExceededException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The specified service setting wasn't found. Either the service name or the -// setting hasn't been provisioned by the Amazon Web Services service team. -type ServiceSettingNotFound struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ServiceSettingNotFound) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ServiceSettingNotFound) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ServiceSettingNotFound) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ServiceSettingNotFound" - } - return *e.ErrorCodeOverride -} -func (e *ServiceSettingNotFound) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The updated status is the same as the current status. -type StatusUnchanged struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *StatusUnchanged) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *StatusUnchanged) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *StatusUnchanged) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "StatusUnchanged" - } - return *e.ErrorCodeOverride -} -func (e *StatusUnchanged) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The sub-type count exceeded the limit for the inventory type. -type SubTypeCountLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *SubTypeCountLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *SubTypeCountLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *SubTypeCountLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "SubTypeCountLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *SubTypeCountLimitExceededException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// You specified the Safe option for the DeregisterTargetFromMaintenanceWindow -// operation, but the target is still referenced in a task. -type TargetInUseException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *TargetInUseException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *TargetInUseException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *TargetInUseException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "TargetInUseException" - } - return *e.ErrorCodeOverride -} -func (e *TargetInUseException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified target managed node for the session isn't fully configured for -// use with Session Manager. For more information, see Getting started with -// Session Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started.html) -// in the Amazon Web Services Systems Manager User Guide. This error is also -// returned if you attempt to start a session on a managed node that is located in -// a different account or Region -type TargetNotConnected struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *TargetNotConnected) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *TargetNotConnected) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *TargetNotConnected) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "TargetNotConnected" - } - return *e.ErrorCodeOverride -} -func (e *TargetNotConnected) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The Targets parameter includes too many tags. Remove one or more tags and try -// the command again. -type TooManyTagsError struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *TooManyTagsError) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *TooManyTagsError) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *TooManyTagsError) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "TooManyTagsError" - } - return *e.ErrorCodeOverride -} -func (e *TooManyTagsError) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// There are concurrent updates for a resource that supports one update at a time. -type TooManyUpdates struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *TooManyUpdates) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *TooManyUpdates) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *TooManyUpdates) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "TooManyUpdates" - } - return *e.ErrorCodeOverride -} -func (e *TooManyUpdates) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The size of inventory data has exceeded the total size limit for the resource. -type TotalSizeLimitExceededException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *TotalSizeLimitExceededException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *TotalSizeLimitExceededException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *TotalSizeLimitExceededException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "TotalSizeLimitExceededException" - } - return *e.ErrorCodeOverride -} -func (e *TotalSizeLimitExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The calendar entry contained in the specified SSM document isn't supported. -type UnsupportedCalendarException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *UnsupportedCalendarException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnsupportedCalendarException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnsupportedCalendarException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnsupportedCalendarException" - } - return *e.ErrorCodeOverride -} -func (e *UnsupportedCalendarException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Patching for applications released by Microsoft is only available on EC2 -// instances and advanced instances. To patch applications released by Microsoft on -// on-premises servers and VMs, you must enable advanced instances. For more -// information, see Enabling the advanced-instances tier (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances-advanced.html) -// in the Amazon Web Services Systems Manager User Guide. -type UnsupportedFeatureRequiredException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *UnsupportedFeatureRequiredException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnsupportedFeatureRequiredException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnsupportedFeatureRequiredException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnsupportedFeatureRequiredException" - } - return *e.ErrorCodeOverride -} -func (e *UnsupportedFeatureRequiredException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The Context attribute that you specified for the InventoryItem isn't allowed -// for this inventory type. You can only use the Context attribute with inventory -// types like AWS:ComplianceItem . -type UnsupportedInventoryItemContextException struct { - Message *string - - ErrorCodeOverride *string - - TypeName *string - - noSmithyDocumentSerde -} - -func (e *UnsupportedInventoryItemContextException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnsupportedInventoryItemContextException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnsupportedInventoryItemContextException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnsupportedInventoryItemContextException" - } - return *e.ErrorCodeOverride -} -func (e *UnsupportedInventoryItemContextException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// Inventory item type schema version has to match supported versions in the -// service. Check output of GetInventorySchema to see the available schema version -// for each type. -type UnsupportedInventorySchemaVersionException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *UnsupportedInventorySchemaVersionException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnsupportedInventorySchemaVersionException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnsupportedInventorySchemaVersionException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnsupportedInventorySchemaVersionException" - } - return *e.ErrorCodeOverride -} -func (e *UnsupportedInventorySchemaVersionException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The operating systems you specified isn't supported, or the operation isn't -// supported for the operating system. -type UnsupportedOperatingSystem struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *UnsupportedOperatingSystem) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnsupportedOperatingSystem) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnsupportedOperatingSystem) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnsupportedOperatingSystem" - } - return *e.ErrorCodeOverride -} -func (e *UnsupportedOperatingSystem) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The parameter type isn't supported. -type UnsupportedParameterType struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *UnsupportedParameterType) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnsupportedParameterType) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnsupportedParameterType) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnsupportedParameterType" - } - return *e.ErrorCodeOverride -} -func (e *UnsupportedParameterType) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The document doesn't support the platform type of the given managed node ID(s). -// For example, you sent an document for a Windows managed node to a Linux node. -type UnsupportedPlatformType struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *UnsupportedPlatformType) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnsupportedPlatformType) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnsupportedPlatformType) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnsupportedPlatformType" - } - return *e.ErrorCodeOverride -} -func (e *UnsupportedPlatformType) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/types/types.go deleted file mode 100644 index 6ea901a2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/types/types.go +++ /dev/null @@ -1,5096 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - smithydocument "github.com/aws/smithy-go/document" - "time" -) - -// Information includes the Amazon Web Services account ID where the current -// document is shared and the version shared with that account. -type AccountSharingInfo struct { - - // The Amazon Web Services account ID where the current document is shared. - AccountId *string - - // The version of the current document shared with the account. - SharedDocumentVersion *string - - noSmithyDocumentSerde -} - -// An activation registers one or more on-premises servers or virtual machines -// (VMs) with Amazon Web Services so that you can configure those servers or VMs -// using Run Command. A server or VM that has been registered with Amazon Web -// Services Systems Manager is called a managed node. -type Activation struct { - - // The ID created by Systems Manager when you submitted the activation. - ActivationId *string - - // The date the activation was created. - CreatedDate *time.Time - - // A name for the managed node when it is created. - DefaultInstanceName *string - - // A user defined description of the activation. - Description *string - - // The date when this activation can no longer be used to register managed nodes. - ExpirationDate *time.Time - - // Whether or not the activation is expired. - Expired bool - - // The Identity and Access Management (IAM) role to assign to the managed node. - IamRole *string - - // The maximum number of managed nodes that can be registered using this - // activation. - RegistrationLimit *int32 - - // The number of managed nodes already registered with this activation. - RegistrationsCount *int32 - - // Tags assigned to the activation. - Tags []Tag - - noSmithyDocumentSerde -} - -// A CloudWatch alarm you apply to an automation or command. -type Alarm struct { - - // The name of your CloudWatch alarm. - // - // This member is required. - Name *string - - noSmithyDocumentSerde -} - -// The details for the CloudWatch alarm you want to apply to an automation or -// command. -type AlarmConfiguration struct { - - // The name of the CloudWatch alarm specified in the configuration. - // - // This member is required. - Alarms []Alarm - - // When this value is true, your automation or command continues to run in cases - // where we can’t retrieve alarm status information from CloudWatch. In cases where - // we successfully retrieve an alarm status of OK or INSUFFICIENT_DATA, the - // automation or command continues to run, regardless of this value. Default is - // false. - IgnorePollAlarmFailure bool - - noSmithyDocumentSerde -} - -// The details about the state of your CloudWatch alarm. -type AlarmStateInformation struct { - - // The name of your CloudWatch alarm. - // - // This member is required. - Name *string - - // The state of your CloudWatch alarm. - // - // This member is required. - State ExternalAlarmState - - noSmithyDocumentSerde -} - -// Describes an association of a Amazon Web Services Systems Manager document (SSM -// document) and a managed node. -type Association struct { - - // The ID created by the system when you create an association. An association is - // a binding between a document and a set of targets with a schedule. - AssociationId *string - - // The association name. - AssociationName *string - - // The association version. - AssociationVersion *string - - // The version of the document used in the association. If you change a document - // version for a State Manager association, Systems Manager immediately runs the - // association unless you previously specifed the apply-only-at-cron-interval - // parameter. State Manager doesn't support running associations that use a new - // version of a document if that document is shared from another account. State - // Manager always runs the default version of a document if shared from another - // account, even though the Systems Manager console shows that a new version was - // processed. If you want to run an association using a new version of a document - // shared form another account, you must set the document version to default . - DocumentVersion *string - - // The managed node ID. - InstanceId *string - - // The date on which the association was last run. - LastExecutionDate *time.Time - - // The name of the SSM document. - Name *string - - // Information about the association. - Overview *AssociationOverview - - // A cron expression that specifies a schedule when the association runs. The - // schedule runs in Coordinated Universal Time (UTC). - ScheduleExpression *string - - // Number of days to wait after the scheduled day to run an association. - ScheduleOffset *int32 - - // A key-value mapping of document parameters to target resources. Both Targets - // and TargetMaps can't be specified together. - TargetMaps []map[string][]string - - // The managed nodes targeted by the request to create an association. You can - // target all managed nodes in an Amazon Web Services account by specifying the - // InstanceIds key with a value of * . - Targets []Target - - noSmithyDocumentSerde -} - -// Describes the parameters for a document. -type AssociationDescription struct { - - // The details for the CloudWatch alarm you want to apply to an automation or - // command. - AlarmConfiguration *AlarmConfiguration - - // By default, when you create a new associations, the system runs it immediately - // after it is created and then according to the schedule you specified. Specify - // this option if you don't want an association to run immediately after you create - // it. This parameter isn't supported for rate expressions. - ApplyOnlyAtCronInterval bool - - // The association ID. - AssociationId *string - - // The association name. - AssociationName *string - - // The association version. - AssociationVersion *string - - // Choose the parameter that will define how your automation will branch out. This - // target is required for associations that use an Automation runbook and target - // resources by using rate controls. Automation is a capability of Amazon Web - // Services Systems Manager. - AutomationTargetParameterName *string - - // The names or Amazon Resource Names (ARNs) of the Change Calendar type documents - // your associations are gated under. The associations only run when that change - // calendar is open. For more information, see Amazon Web Services Systems Manager - // Change Calendar (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-change-calendar) - // . - CalendarNames []string - - // The severity level that is assigned to the association. - ComplianceSeverity AssociationComplianceSeverity - - // The date when the association was made. - Date *time.Time - - // The document version. - DocumentVersion *string - - // The managed node ID. - InstanceId *string - - // The date on which the association was last run. - LastExecutionDate *time.Time - - // The last date on which the association was successfully run. - LastSuccessfulExecutionDate *time.Time - - // The date when the association was last updated. - LastUpdateAssociationDate *time.Time - - // The maximum number of targets allowed to run the association at the same time. - // You can specify a number, for example 10, or a percentage of the target set, for - // example 10%. The default value is 100%, which means all targets run the - // association at the same time. If a new managed node starts and attempts to run - // an association while Systems Manager is running MaxConcurrency associations, - // the association is allowed to run. During the next association interval, the new - // managed node will process its association within the limit specified for - // MaxConcurrency . - MaxConcurrency *string - - // The number of errors that are allowed before the system stops sending requests - // to run the association on additional targets. You can specify either an absolute - // number of errors, for example 10, or a percentage of the target set, for example - // 10%. If you specify 3, for example, the system stops sending requests when the - // fourth error is received. If you specify 0, then the system stops sending - // requests after the first error is returned. If you run an association on 50 - // managed nodes and set MaxError to 10%, then the system stops sending the - // request when the sixth error is received. Executions that are already running an - // association when MaxErrors is reached are allowed to complete, but some of - // these executions may fail as well. If you need to ensure that there won't be - // more than max-errors failed executions, set MaxConcurrency to 1 so that - // executions proceed one at a time. - MaxErrors *string - - // The name of the SSM document. - Name *string - - // An S3 bucket where you want to store the output details of the request. - OutputLocation *InstanceAssociationOutputLocation - - // Information about the association. - Overview *AssociationOverview - - // A description of the parameters for a document. - Parameters map[string][]string - - // A cron expression that specifies a schedule when the association runs. - ScheduleExpression *string - - // Number of days to wait after the scheduled day to run an association. - ScheduleOffset *int32 - - // The association status. - Status *AssociationStatus - - // The mode for generating association compliance. You can specify AUTO or MANUAL . - // In AUTO mode, the system uses the status of the association execution to - // determine the compliance status. If the association execution runs successfully, - // then the association is COMPLIANT . If the association execution doesn't run - // successfully, the association is NON-COMPLIANT . In MANUAL mode, you must - // specify the AssociationId as a parameter for the PutComplianceItems API - // operation. In this case, compliance data isn't managed by State Manager, a - // capability of Amazon Web Services Systems Manager. It is managed by your direct - // call to the PutComplianceItems API operation. By default, all associations use - // AUTO mode. - SyncCompliance AssociationSyncCompliance - - // The combination of Amazon Web Services Regions and Amazon Web Services accounts - // where you want to run the association. - TargetLocations []TargetLocation - - // A key-value mapping of document parameters to target resources. Both Targets - // and TargetMaps can't be specified together. - TargetMaps []map[string][]string - - // The managed nodes targeted by the request. - Targets []Target - - // The CloudWatch alarm that was invoked during the association. - TriggeredAlarms []AlarmStateInformation - - noSmithyDocumentSerde -} - -// Includes information about the specified association. -type AssociationExecution struct { - - // The details for the CloudWatch alarm you want to apply to an automation or - // command. - AlarmConfiguration *AlarmConfiguration - - // The association ID. - AssociationId *string - - // The association version. - AssociationVersion *string - - // The time the execution started. - CreatedTime *time.Time - - // Detailed status information about the execution. - DetailedStatus *string - - // The execution ID for the association. - ExecutionId *string - - // The date of the last execution. - LastExecutionDate *time.Time - - // An aggregate status of the resources in the execution based on the status type. - ResourceCountByStatus *string - - // The status of the association execution. - Status *string - - // The CloudWatch alarms that were invoked by the association. - TriggeredAlarms []AlarmStateInformation - - noSmithyDocumentSerde -} - -// Filters used in the request. -type AssociationExecutionFilter struct { - - // The key value used in the request. - // - // This member is required. - Key AssociationExecutionFilterKey - - // The filter type specified in the request. - // - // This member is required. - Type AssociationFilterOperatorType - - // The value specified for the key. - // - // This member is required. - Value *string - - noSmithyDocumentSerde -} - -// Includes information about the specified association execution. -type AssociationExecutionTarget struct { - - // The association ID. - AssociationId *string - - // The association version. - AssociationVersion *string - - // Detailed information about the execution status. - DetailedStatus *string - - // The execution ID. - ExecutionId *string - - // The date of the last execution. - LastExecutionDate *time.Time - - // The location where the association details are saved. - OutputSource *OutputSource - - // The resource ID, for example, the managed node ID where the association ran. - ResourceId *string - - // The resource type, for example, EC2. - ResourceType *string - - // The association execution status. - Status *string - - noSmithyDocumentSerde -} - -// Filters for the association execution. -type AssociationExecutionTargetsFilter struct { - - // The key value used in the request. - // - // This member is required. - Key AssociationExecutionTargetsFilterKey - - // The value specified for the key. - // - // This member is required. - Value *string - - noSmithyDocumentSerde -} - -// Describes a filter. -type AssociationFilter struct { - - // The name of the filter. InstanceId has been deprecated. - // - // This member is required. - Key AssociationFilterKey - - // The filter value. - // - // This member is required. - Value *string - - noSmithyDocumentSerde -} - -// Information about the association. -type AssociationOverview struct { - - // Returns the number of targets for the association status. For example, if you - // created an association with two managed nodes, and one of them was successful, - // this would return the count of managed nodes by status. - AssociationStatusAggregatedCount map[string]int32 - - // A detailed status of the association. - DetailedStatus *string - - // The status of the association. Status can be: Pending, Success, or Failed. - Status *string - - noSmithyDocumentSerde -} - -// Describes an association status. -type AssociationStatus struct { - - // The date when the status changed. - // - // This member is required. - Date *time.Time - - // The reason for the status. - // - // This member is required. - Message *string - - // The status. - // - // This member is required. - Name AssociationStatusName - - // A user-defined string. - AdditionalInfo *string - - noSmithyDocumentSerde -} - -// Information about the association version. -type AssociationVersionInfo struct { - - // By default, when you create a new associations, the system runs it immediately - // after it is created and then according to the schedule you specified. Specify - // this option if you don't want an association to run immediately after you create - // it. This parameter isn't supported for rate expressions. - ApplyOnlyAtCronInterval bool - - // The ID created by the system when the association was created. - AssociationId *string - - // The name specified for the association version when the association version was - // created. - AssociationName *string - - // The association version. - AssociationVersion *string - - // The names or Amazon Resource Names (ARNs) of the Change Calendar type documents - // your associations are gated under. The associations for this version only run - // when that Change Calendar is open. For more information, see Amazon Web - // Services Systems Manager Change Calendar (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-change-calendar) - // . - CalendarNames []string - - // The severity level that is assigned to the association. - ComplianceSeverity AssociationComplianceSeverity - - // The date the association version was created. - CreatedDate *time.Time - - // The version of an Amazon Web Services Systems Manager document (SSM document) - // used when the association version was created. - DocumentVersion *string - - // The maximum number of targets allowed to run the association at the same time. - // You can specify a number, for example 10, or a percentage of the target set, for - // example 10%. The default value is 100%, which means all targets run the - // association at the same time. If a new managed node starts and attempts to run - // an association while Systems Manager is running MaxConcurrency associations, - // the association is allowed to run. During the next association interval, the new - // managed node will process its association within the limit specified for - // MaxConcurrency . - MaxConcurrency *string - - // The number of errors that are allowed before the system stops sending requests - // to run the association on additional targets. You can specify either an absolute - // number of errors, for example 10, or a percentage of the target set, for example - // 10%. If you specify 3, for example, the system stops sending requests when the - // fourth error is received. If you specify 0, then the system stops sending - // requests after the first error is returned. If you run an association on 50 - // managed nodes and set MaxError to 10%, then the system stops sending the - // request when the sixth error is received. Executions that are already running an - // association when MaxErrors is reached are allowed to complete, but some of - // these executions may fail as well. If you need to ensure that there won't be - // more than max-errors failed executions, set MaxConcurrency to 1 so that - // executions proceed one at a time. - MaxErrors *string - - // The name specified when the association was created. - Name *string - - // The location in Amazon S3 specified for the association when the association - // version was created. - OutputLocation *InstanceAssociationOutputLocation - - // Parameters specified when the association version was created. - Parameters map[string][]string - - // The cron or rate schedule specified for the association when the association - // version was created. - ScheduleExpression *string - - // Number of days to wait after the scheduled day to run an association. - ScheduleOffset *int32 - - // The mode for generating association compliance. You can specify AUTO or MANUAL . - // In AUTO mode, the system uses the status of the association execution to - // determine the compliance status. If the association execution runs successfully, - // then the association is COMPLIANT . If the association execution doesn't run - // successfully, the association is NON-COMPLIANT . In MANUAL mode, you must - // specify the AssociationId as a parameter for the PutComplianceItems API - // operation. In this case, compliance data isn't managed by State Manager, a - // capability of Amazon Web Services Systems Manager. It is managed by your direct - // call to the PutComplianceItems API operation. By default, all associations use - // AUTO mode. - SyncCompliance AssociationSyncCompliance - - // The combination of Amazon Web Services Regions and Amazon Web Services accounts - // where you wanted to run the association when this association version was - // created. - TargetLocations []TargetLocation - - // A key-value mapping of document parameters to target resources. Both Targets - // and TargetMaps can't be specified together. - TargetMaps []map[string][]string - - // The targets specified for the association when the association version was - // created. - Targets []Target - - noSmithyDocumentSerde -} - -// A structure that includes attributes that describe a document attachment. -type AttachmentContent struct { - - // The cryptographic hash value of the document content. - Hash *string - - // The hash algorithm used to calculate the hash value. - HashType AttachmentHashType - - // The name of an attachment. - Name *string - - // The size of an attachment in bytes. - Size int64 - - // The URL location of the attachment content. - Url *string - - noSmithyDocumentSerde -} - -// An attribute of an attachment, such as the attachment name. -type AttachmentInformation struct { - - // The name of the attachment. - Name *string - - noSmithyDocumentSerde -} - -// Identifying information about a document attachment, including the file name -// and a key-value pair that identifies the location of an attachment to a -// document. -type AttachmentsSource struct { - - // The key of a key-value pair that identifies the location of an attachment to a - // document. - Key AttachmentsSourceKey - - // The name of the document attachment file. - Name *string - - // The value of a key-value pair that identifies the location of an attachment to - // a document. The format for Value depends on the type of key you specify. - // - For the key SourceUrl, the value is an S3 bucket location. For example: - // "Values": [ "s3://doc-example-bucket/my-folder" ] - // - For the key S3FileUrl, the value is a file in an S3 bucket. For example: - // "Values": [ "s3://doc-example-bucket/my-folder/my-file.py" ] - // - For the key AttachmentReference, the value is constructed from the name of - // another SSM document in your account, a version number of that document, and a - // file attached to that document version that you want to reuse. For example: - // "Values": [ "MyOtherDocument/3/my-other-file.py" ] However, if the SSM - // document is shared with you from another account, the full SSM document ARN must - // be specified instead of the document name only. For example: "Values": [ - // "arn:aws:ssm:us-east-2:111122223333:document/OtherAccountDocument/3/their-file.py" - // ] - Values []string - - noSmithyDocumentSerde -} - -// Detailed information about the current state of an individual Automation -// execution. -type AutomationExecution struct { - - // The details for the CloudWatch alarm applied to your automation. - AlarmConfiguration *AlarmConfiguration - - // The ID of a State Manager association used in the Automation operation. - AssociationId *string - - // The execution ID. - AutomationExecutionId *string - - // The execution status of the Automation. - AutomationExecutionStatus AutomationExecutionStatus - - // The subtype of the Automation operation. Currently, the only supported value is - // ChangeRequest . - AutomationSubtype AutomationSubtype - - // The name of the Change Manager change request. - ChangeRequestName *string - - // The action of the step that is currently running. - CurrentAction *string - - // The name of the step that is currently running. - CurrentStepName *string - - // The name of the Automation runbook used during the execution. - DocumentName *string - - // The version of the document to use during execution. - DocumentVersion *string - - // The Amazon Resource Name (ARN) of the user who ran the automation. - ExecutedBy *string - - // The time the execution finished. - ExecutionEndTime *time.Time - - // The time the execution started. - ExecutionStartTime *time.Time - - // A message describing why an execution has failed, if the status is set to - // Failed. - FailureMessage *string - - // The MaxConcurrency value specified by the user when the execution started. - MaxConcurrency *string - - // The MaxErrors value specified by the user when the execution started. - MaxErrors *string - - // The automation execution mode. - Mode ExecutionMode - - // The ID of an OpsItem that is created to represent a Change Manager change - // request. - OpsItemId *string - - // The list of execution outputs as defined in the Automation runbook. - Outputs map[string][]string - - // The key-value map of execution parameters, which were supplied when calling - // StartAutomationExecution . - Parameters map[string][]string - - // The AutomationExecutionId of the parent automation. - ParentAutomationExecutionId *string - - // An aggregate of step execution statuses displayed in the Amazon Web Services - // Systems Manager console for a multi-Region and multi-account Automation - // execution. - ProgressCounters *ProgressCounters - - // A list of resolved targets in the rate control execution. - ResolvedTargets *ResolvedTargets - - // Information about the Automation runbooks that are run as part of a runbook - // workflow. The Automation runbooks specified for the runbook workflow can't run - // until all required approvals for the change request have been received. - Runbooks []Runbook - - // The date and time the Automation operation is scheduled to start. - ScheduledTime *time.Time - - // A list of details about the current state of all steps that comprise an - // execution. An Automation runbook contains a list of steps that are run in order. - StepExecutions []StepExecution - - // A boolean value that indicates if the response contains the full list of the - // Automation step executions. If true, use the DescribeAutomationStepExecutions - // API operation to get the full list of step executions. - StepExecutionsTruncated bool - - // The target of the execution. - Target *string - - // The combination of Amazon Web Services Regions and/or Amazon Web Services - // accounts where you want to run the Automation. - TargetLocations []TargetLocation - - // The specified key-value mapping of document parameters to target resources. - TargetMaps []map[string][]string - - // The parameter name. - TargetParameterName *string - - // The specified targets. - Targets []Target - - // The CloudWatch alarm that was invoked by the automation. - TriggeredAlarms []AlarmStateInformation - - // Variables defined for the automation. - Variables map[string][]string - - noSmithyDocumentSerde -} - -// A filter used to match specific automation executions. This is used to limit -// the scope of Automation execution information returned. -type AutomationExecutionFilter struct { - - // One or more keys to limit the results. - // - // This member is required. - Key AutomationExecutionFilterKey - - // The values used to limit the execution information associated with the filter's - // key. - // - // This member is required. - Values []string - - noSmithyDocumentSerde -} - -// Details about a specific Automation execution. -type AutomationExecutionMetadata struct { - - // The details for the CloudWatch alarm applied to your automation. - AlarmConfiguration *AlarmConfiguration - - // The ID of a State Manager association used in the Automation operation. - AssociationId *string - - // The execution ID. - AutomationExecutionId *string - - // The status of the execution. - AutomationExecutionStatus AutomationExecutionStatus - - // The subtype of the Automation operation. Currently, the only supported value is - // ChangeRequest . - AutomationSubtype AutomationSubtype - - // Use this filter with DescribeAutomationExecutions . Specify either Local or - // CrossAccount. CrossAccount is an Automation that runs in multiple Amazon Web - // Services Regions and Amazon Web Services accounts. For more information, see - // Running Automation workflows in multiple Amazon Web Services Regions and - // accounts (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-automation-multiple-accounts-and-regions.html) - // in the Amazon Web Services Systems Manager User Guide. - AutomationType AutomationType - - // The name of the Change Manager change request. - ChangeRequestName *string - - // The action of the step that is currently running. - CurrentAction *string - - // The name of the step that is currently running. - CurrentStepName *string - - // The name of the Automation runbook used during execution. - DocumentName *string - - // The document version used during the execution. - DocumentVersion *string - - // The IAM role ARN of the user who ran the automation. - ExecutedBy *string - - // The time the execution finished. This isn't populated if the execution is still - // in progress. - ExecutionEndTime *time.Time - - // The time the execution started. - ExecutionStartTime *time.Time - - // The list of execution outputs as defined in the Automation runbook. - FailureMessage *string - - // An S3 bucket where execution information is stored. - LogFile *string - - // The MaxConcurrency value specified by the user when starting the automation. - MaxConcurrency *string - - // The MaxErrors value specified by the user when starting the automation. - MaxErrors *string - - // The Automation execution mode. - Mode ExecutionMode - - // The ID of an OpsItem that is created to represent a Change Manager change - // request. - OpsItemId *string - - // The list of execution outputs as defined in the Automation runbook. - Outputs map[string][]string - - // The execution ID of the parent automation. - ParentAutomationExecutionId *string - - // A list of targets that resolved during the execution. - ResolvedTargets *ResolvedTargets - - // Information about the Automation runbooks that are run during a runbook - // workflow in Change Manager. The Automation runbooks specified for the runbook - // workflow can't run until all required approvals for the change request have been - // received. - Runbooks []Runbook - - // The date and time the Automation operation is scheduled to start. - ScheduledTime *time.Time - - // The list of execution outputs as defined in the Automation runbook. - Target *string - - // The specified key-value mapping of document parameters to target resources. - TargetMaps []map[string][]string - - // The list of execution outputs as defined in the Automation runbook. - TargetParameterName *string - - // The targets defined by the user when starting the automation. - Targets []Target - - // The CloudWatch alarm that was invoked by the automation. - TriggeredAlarms []AlarmStateInformation - - noSmithyDocumentSerde -} - -// Defines the basic information about a patch baseline override. -type BaselineOverride struct { - - // A set of rules defining the approval rules for a patch baseline. - ApprovalRules *PatchRuleGroup - - // A list of explicitly approved patches for the baseline. For information about - // accepted formats for lists of approved patches and rejected patches, see About - // package name formats for approved and rejected patch lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) - // in the Amazon Web Services Systems Manager User Guide. - ApprovedPatches []string - - // Defines the compliance level for approved patches. When an approved patch is - // reported as missing, this value describes the severity of the compliance - // violation. - ApprovedPatchesComplianceLevel PatchComplianceLevel - - // Indicates whether the list of approved patches includes non-security updates - // that should be applied to the managed nodes. The default value is false . - // Applies to Linux managed nodes only. - ApprovedPatchesEnableNonSecurity bool - - // A set of patch filters, typically used for approval rules. - GlobalFilters *PatchFilterGroup - - // The operating system rule used by the patch baseline override. - OperatingSystem OperatingSystem - - // A list of explicitly rejected patches for the baseline. For information about - // accepted formats for lists of approved patches and rejected patches, see About - // package name formats for approved and rejected patch lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) - // in the Amazon Web Services Systems Manager User Guide. - RejectedPatches []string - - // The action for Patch Manager to take on patches included in the RejectedPackages - // list. A patch can be allowed only if it is a dependency of another package, or - // blocked entirely along with packages that include it as a dependency. - RejectedPatchesAction PatchAction - - // Information about the patches to use to update the managed nodes, including - // target operating systems and source repositories. Applies to Linux managed nodes - // only. - Sources []PatchSource - - noSmithyDocumentSerde -} - -// Configuration options for sending command output to Amazon CloudWatch Logs. -type CloudWatchOutputConfig struct { - - // The name of the CloudWatch Logs log group where you want to send command - // output. If you don't specify a group name, Amazon Web Services Systems Manager - // automatically creates a log group for you. The log group uses the following - // naming format: aws/ssm/SystemsManagerDocumentName - CloudWatchLogGroupName *string - - // Enables Systems Manager to send command output to CloudWatch Logs. - CloudWatchOutputEnabled bool - - noSmithyDocumentSerde -} - -// Describes a command request. -type Command struct { - - // The details for the CloudWatch alarm applied to your command. - AlarmConfiguration *AlarmConfiguration - - // Amazon CloudWatch Logs information where you want Amazon Web Services Systems - // Manager to send the command output. - CloudWatchOutputConfig *CloudWatchOutputConfig - - // A unique identifier for this command. - CommandId *string - - // User-specified information about the command, such as a brief description of - // what the command should do. - Comment *string - - // The number of targets for which the command invocation reached a terminal - // state. Terminal states include the following: Success, Failed, Execution Timed - // Out, Delivery Timed Out, Cancelled, Terminated, or Undeliverable. - CompletedCount int32 - - // The number of targets for which the status is Delivery Timed Out. - DeliveryTimedOutCount int32 - - // The name of the document requested for execution. - DocumentName *string - - // The Systems Manager document (SSM document) version. - DocumentVersion *string - - // The number of targets for which the status is Failed or Execution Timed Out. - ErrorCount int32 - - // If a command expires, it changes status to DeliveryTimedOut for all invocations - // that have the status InProgress , Pending , or Delayed . ExpiresAfter is - // calculated based on the total timeout for the overall command. For more - // information, see Understanding command timeout values (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html?icmpid=docs_ec2_console#monitor-about-status-timeouts) - // in the Amazon Web Services Systems Manager User Guide. - ExpiresAfter *time.Time - - // The managed node IDs against which this command was requested. - InstanceIds []string - - // The maximum number of managed nodes that are allowed to run the command at the - // same time. You can specify a number of managed nodes, such as 10, or a - // percentage of nodes, such as 10%. The default value is 50. For more information - // about how to use MaxConcurrency , see Running commands using Systems Manager - // Run Command (https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) - // in the Amazon Web Services Systems Manager User Guide. - MaxConcurrency *string - - // The maximum number of errors allowed before the system stops sending the - // command to additional targets. You can specify a number of errors, such as 10, - // or a percentage or errors, such as 10%. The default value is 0 . For more - // information about how to use MaxErrors , see Running commands using Systems - // Manager Run Command (https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) - // in the Amazon Web Services Systems Manager User Guide. - MaxErrors *string - - // Configurations for sending notifications about command status changes. - NotificationConfig *NotificationConfig - - // The S3 bucket where the responses to the command executions should be stored. - // This was requested when issuing the command. - OutputS3BucketName *string - - // The S3 directory path inside the bucket where the responses to the command - // executions should be stored. This was requested when issuing the command. - OutputS3KeyPrefix *string - - // (Deprecated) You can no longer specify this parameter. The system ignores it. - // Instead, Systems Manager automatically determines the Amazon Web Services Region - // of the S3 bucket. - OutputS3Region *string - - // The parameter values to be inserted in the document when running the command. - Parameters map[string][]string - - // The date and time the command was requested. - RequestedDateTime *time.Time - - // The Identity and Access Management (IAM) service role that Run Command, a - // capability of Amazon Web Services Systems Manager, uses to act on your behalf - // when sending notifications about command status changes. - ServiceRole *string - - // The status of the command. - Status CommandStatus - - // A detailed status of the command execution. StatusDetails includes more - // information than Status because it includes states resulting from error and - // concurrency control parameters. StatusDetails can show different results than - // Status. For more information about these statuses, see Understanding command - // statuses (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) - // in the Amazon Web Services Systems Manager User Guide. StatusDetails can be one - // of the following values: - // - Pending: The command hasn't been sent to any managed nodes. - // - In Progress: The command has been sent to at least one managed node but - // hasn't reached a final state on all managed nodes. - // - Success: The command successfully ran on all invocations. This is a - // terminal state. - // - Delivery Timed Out: The value of MaxErrors or more command invocations - // shows a status of Delivery Timed Out. This is a terminal state. - // - Execution Timed Out: The value of MaxErrors or more command invocations - // shows a status of Execution Timed Out. This is a terminal state. - // - Failed: The value of MaxErrors or more command invocations shows a status - // of Failed. This is a terminal state. - // - Incomplete: The command was attempted on all managed nodes and one or more - // invocations doesn't have a value of Success but not enough invocations failed - // for the status to be Failed. This is a terminal state. - // - Cancelled: The command was terminated before it was completed. This is a - // terminal state. - // - Rate Exceeded: The number of managed nodes targeted by the command exceeded - // the account limit for pending invocations. The system has canceled the command - // before running it on any managed node. This is a terminal state. - // - Delayed: The system attempted to send the command to the managed node but - // wasn't successful. The system retries again. - StatusDetails *string - - // The number of targets for the command. - TargetCount int32 - - // An array of search criteria that targets managed nodes using a Key,Value - // combination that you specify. Targets is required if you don't provide one or - // more managed node IDs in the call. - Targets []Target - - // The TimeoutSeconds value specified for a command. - TimeoutSeconds *int32 - - // The CloudWatch alarm that was invoked by the command. - TriggeredAlarms []AlarmStateInformation - - noSmithyDocumentSerde -} - -// Describes a command filter. A managed node ID can't be specified when a command -// status is Pending because the command hasn't run on the node yet. -type CommandFilter struct { - - // The name of the filter. The ExecutionStage filter can't be used with the - // ListCommandInvocations operation, only with ListCommands . - // - // This member is required. - Key CommandFilterKey - - // The filter value. Valid values for each filter key are as follows: - // - InvokedAfter: Specify a timestamp to limit your results. For example, - // specify 2021-07-07T00:00:00Z to see a list of command executions occurring - // July 7, 2021, and later. - // - InvokedBefore: Specify a timestamp to limit your results. For example, - // specify 2021-07-07T00:00:00Z to see a list of command executions from before - // July 7, 2021. - // - Status: Specify a valid command status to see a list of all command - // executions with that status. The status choices depend on the API you call. The - // status values you can specify for ListCommands are: - // - Pending - // - InProgress - // - Success - // - Cancelled - // - Failed - // - TimedOut (this includes both Delivery and Execution time outs) - // - AccessDenied - // - DeliveryTimedOut - // - ExecutionTimedOut - // - Incomplete - // - NoInstancesInTag - // - LimitExceeded The status values you can specify for ListCommandInvocations - // are: - // - Pending - // - InProgress - // - Delayed - // - Success - // - Cancelled - // - Failed - // - TimedOut (this includes both Delivery and Execution time outs) - // - AccessDenied - // - DeliveryTimedOut - // - ExecutionTimedOut - // - Undeliverable - // - InvalidPlatform - // - Terminated - // - DocumentName: Specify name of the Amazon Web Services Systems Manager - // document (SSM document) for which you want to see command execution results. For - // example, specify AWS-RunPatchBaseline to see command executions that used this - // SSM document to perform security patching operations on managed nodes. - // - ExecutionStage: Specify one of the following values ( ListCommands - // operations only): - // - Executing : Returns a list of command executions that are currently still - // running. - // - Complete : Returns a list of command executions that have already completed. - // - // This member is required. - Value *string - - noSmithyDocumentSerde -} - -// An invocation is a copy of a command sent to a specific managed node. A command -// can apply to one or more managed nodes. A command invocation applies to one -// managed node. For example, if a user runs SendCommand against three managed -// nodes, then a command invocation is created for each requested managed node ID. -// A command invocation returns status and detail information about a command you -// ran. -type CommandInvocation struct { - - // Amazon CloudWatch Logs information where you want Amazon Web Services Systems - // Manager to send the command output. - CloudWatchOutputConfig *CloudWatchOutputConfig - - // The command against which this invocation was requested. - CommandId *string - - // Plugins processed by the command. - CommandPlugins []CommandPlugin - - // User-specified information about the command, such as a brief description of - // what the command should do. - Comment *string - - // The document name that was requested for execution. - DocumentName *string - - // The Systems Manager document (SSM document) version. - DocumentVersion *string - - // The managed node ID in which this invocation was requested. - InstanceId *string - - // The fully qualified host name of the managed node. - InstanceName *string - - // Configurations for sending notifications about command status changes on a per - // managed node basis. - NotificationConfig *NotificationConfig - - // The time and date the request was sent to this managed node. - RequestedDateTime *time.Time - - // The Identity and Access Management (IAM) service role that Run Command, a - // capability of Amazon Web Services Systems Manager, uses to act on your behalf - // when sending notifications about command status changes on a per managed node - // basis. - ServiceRole *string - - // The URL to the plugin's StdErr file in Amazon Simple Storage Service (Amazon - // S3), if the S3 bucket was defined for the parent command. For an invocation, - // StandardErrorUrl is populated if there is just one plugin defined for the - // command, and the S3 bucket was defined for the command. - StandardErrorUrl *string - - // The URL to the plugin's StdOut file in Amazon Simple Storage Service (Amazon - // S3), if the S3 bucket was defined for the parent command. For an invocation, - // StandardOutputUrl is populated if there is just one plugin defined for the - // command, and the S3 bucket was defined for the command. - StandardOutputUrl *string - - // Whether or not the invocation succeeded, failed, or is pending. - Status CommandInvocationStatus - - // A detailed status of the command execution for each invocation (each managed - // node targeted by the command). StatusDetails includes more information than - // Status because it includes states resulting from error and concurrency control - // parameters. StatusDetails can show different results than Status. For more - // information about these statuses, see Understanding command statuses (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) - // in the Amazon Web Services Systems Manager User Guide. StatusDetails can be one - // of the following values: - // - Pending: The command hasn't been sent to the managed node. - // - In Progress: The command has been sent to the managed node but hasn't - // reached a terminal state. - // - Success: The execution of the command or plugin was successfully completed. - // This is a terminal state. - // - Delivery Timed Out: The command wasn't delivered to the managed node before - // the delivery timeout expired. Delivery timeouts don't count against the parent - // command's MaxErrors limit, but they do contribute to whether the parent - // command status is Success or Incomplete. This is a terminal state. - // - Execution Timed Out: Command execution started on the managed node, but the - // execution wasn't complete before the execution timeout expired. Execution - // timeouts count against the MaxErrors limit of the parent command. This is a - // terminal state. - // - Failed: The command wasn't successful on the managed node. For a plugin, - // this indicates that the result code wasn't zero. For a command invocation, this - // indicates that the result code for one or more plugins wasn't zero. Invocation - // failures count against the MaxErrors limit of the parent command. This is a - // terminal state. - // - Cancelled: The command was terminated before it was completed. This is a - // terminal state. - // - Undeliverable: The command can't be delivered to the managed node. The - // managed node might not exist or might not be responding. Undeliverable - // invocations don't count against the parent command's MaxErrors limit and don't - // contribute to whether the parent command status is Success or Incomplete. This - // is a terminal state. - // - Terminated: The parent command exceeded its MaxErrors limit and subsequent - // command invocations were canceled by the system. This is a terminal state. - // - Delayed: The system attempted to send the command to the managed node but - // wasn't successful. The system retries again. - StatusDetails *string - - // Gets the trace output sent by the agent. - TraceOutput *string - - noSmithyDocumentSerde -} - -// Describes plugin details. -type CommandPlugin struct { - - // The name of the plugin. Must be one of the following: aws:updateAgent , - // aws:domainjoin , aws:applications , aws:runPowerShellScript , aws:psmodule , - // aws:cloudWatch , aws:runShellScript , or aws:updateSSMAgent . - Name *string - - // Output of the plugin execution. - Output *string - - // The S3 bucket where the responses to the command executions should be stored. - // This was requested when issuing the command. For example, in the following - // response: - // doc-example-bucket/ab19cb99-a030-46dd-9dfc-8eSAMPLEPre-Fix/i-02573cafcfEXAMPLE/awsrunShellScript - // doc-example-bucket is the name of the S3 bucket; - // ab19cb99-a030-46dd-9dfc-8eSAMPLEPre-Fix is the name of the S3 prefix; - // i-02573cafcfEXAMPLE is the managed node ID; awsrunShellScript is the name of - // the plugin. - OutputS3BucketName *string - - // The S3 directory path inside the bucket where the responses to the command - // executions should be stored. This was requested when issuing the command. For - // example, in the following response: - // doc-example-bucket/ab19cb99-a030-46dd-9dfc-8eSAMPLEPre-Fix/i-02573cafcfEXAMPLE/awsrunShellScript - // doc-example-bucket is the name of the S3 bucket; - // ab19cb99-a030-46dd-9dfc-8eSAMPLEPre-Fix is the name of the S3 prefix; - // i-02573cafcfEXAMPLE is the managed node ID; awsrunShellScript is the name of - // the plugin. - OutputS3KeyPrefix *string - - // (Deprecated) You can no longer specify this parameter. The system ignores it. - // Instead, Amazon Web Services Systems Manager automatically determines the S3 - // bucket region. - OutputS3Region *string - - // A numeric response code generated after running the plugin. - ResponseCode int32 - - // The time the plugin stopped running. Could stop prematurely if, for example, a - // cancel command was sent. - ResponseFinishDateTime *time.Time - - // The time the plugin started running. - ResponseStartDateTime *time.Time - - // The URL for the complete text written by the plugin to stderr. If execution - // isn't yet complete, then this string is empty. - StandardErrorUrl *string - - // The URL for the complete text written by the plugin to stdout in Amazon S3. If - // the S3 bucket for the command wasn't specified, then this string is empty. - StandardOutputUrl *string - - // The status of this plugin. You can run a document with multiple plugins. - Status CommandPluginStatus - - // A detailed status of the plugin execution. StatusDetails includes more - // information than Status because it includes states resulting from error and - // concurrency control parameters. StatusDetails can show different results than - // Status. For more information about these statuses, see Understanding command - // statuses (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) - // in the Amazon Web Services Systems Manager User Guide. StatusDetails can be one - // of the following values: - // - Pending: The command hasn't been sent to the managed node. - // - In Progress: The command has been sent to the managed node but hasn't - // reached a terminal state. - // - Success: The execution of the command or plugin was successfully completed. - // This is a terminal state. - // - Delivery Timed Out: The command wasn't delivered to the managed node before - // the delivery timeout expired. Delivery timeouts don't count against the parent - // command's MaxErrors limit, but they do contribute to whether the parent - // command status is Success or Incomplete. This is a terminal state. - // - Execution Timed Out: Command execution started on the managed node, but the - // execution wasn't complete before the execution timeout expired. Execution - // timeouts count against the MaxErrors limit of the parent command. This is a - // terminal state. - // - Failed: The command wasn't successful on the managed node. For a plugin, - // this indicates that the result code wasn't zero. For a command invocation, this - // indicates that the result code for one or more plugins wasn't zero. Invocation - // failures count against the MaxErrors limit of the parent command. This is a - // terminal state. - // - Cancelled: The command was terminated before it was completed. This is a - // terminal state. - // - Undeliverable: The command can't be delivered to the managed node. The - // managed node might not exist, or it might not be responding. Undeliverable - // invocations don't count against the parent command's MaxErrors limit, and they - // don't contribute to whether the parent command status is Success or Incomplete. - // This is a terminal state. - // - Terminated: The parent command exceeded its MaxErrors limit and subsequent - // command invocations were canceled by the system. This is a terminal state. - StatusDetails *string - - noSmithyDocumentSerde -} - -// A summary of the call execution that includes an execution ID, the type of -// execution (for example, Command ), and the date/time of the execution using a -// datetime object that is saved in the following format: yyyy-MM-dd'T'HH:mm:ss'Z'. -type ComplianceExecutionSummary struct { - - // The time the execution ran as a datetime object that is saved in the following - // format: yyyy-MM-dd'T'HH:mm:ss'Z'. - // - // This member is required. - ExecutionTime *time.Time - - // An ID created by the system when PutComplianceItems was called. For example, - // CommandID is a valid execution ID. You can use this ID in subsequent calls. - ExecutionId *string - - // The type of execution. For example, Command is a valid execution type. - ExecutionType *string - - noSmithyDocumentSerde -} - -// Information about the compliance as defined by the resource type. For example, -// for a patch resource type, Items includes information about the PatchSeverity, -// Classification, and so on. -type ComplianceItem struct { - - // The compliance type. For example, Association (for a State Manager - // association), Patch, or Custom: string are all valid compliance types. - ComplianceType *string - - // A "Key": "Value" tag combination for the compliance item. - Details map[string]string - - // A summary for the compliance item. The summary includes an execution ID, the - // execution type (for example, command), and the execution time. - ExecutionSummary *ComplianceExecutionSummary - - // An ID for the compliance item. For example, if the compliance item is a Windows - // patch, the ID could be the number of the KB article; for example: KB4010320. - Id *string - - // An ID for the resource. For a managed node, this is the node ID. - ResourceId *string - - // The type of resource. ManagedInstance is currently the only supported resource - // type. - ResourceType *string - - // The severity of the compliance status. Severity can be one of the following: - // Critical, High, Medium, Low, Informational, Unspecified. - Severity ComplianceSeverity - - // The status of the compliance item. An item is either COMPLIANT, NON_COMPLIANT, - // or an empty string (for Windows patches that aren't applicable). - Status ComplianceStatus - - // A title for the compliance item. For example, if the compliance item is a - // Windows patch, the title could be the title of the KB article for the patch; for - // example: Security Update for Active Directory Federation Services. - Title *string - - noSmithyDocumentSerde -} - -// Information about a compliance item. -type ComplianceItemEntry struct { - - // The severity of the compliance status. Severity can be one of the following: - // Critical, High, Medium, Low, Informational, Unspecified. - // - // This member is required. - Severity ComplianceSeverity - - // The status of the compliance item. An item is either COMPLIANT or NON_COMPLIANT. - // - // This member is required. - Status ComplianceStatus - - // A "Key": "Value" tag combination for the compliance item. - Details map[string]string - - // The compliance item ID. For example, if the compliance item is a Windows patch, - // the ID could be the number of the KB article. - Id *string - - // The title of the compliance item. For example, if the compliance item is a - // Windows patch, the title could be the title of the KB article for the patch; for - // example: Security Update for Active Directory Federation Services. - Title *string - - noSmithyDocumentSerde -} - -// One or more filters. Use a filter to return a more specific list of results. -type ComplianceStringFilter struct { - - // The name of the filter. - Key *string - - // The type of comparison that should be performed for the value: Equal, NotEqual, - // BeginWith, LessThan, or GreaterThan. - Type ComplianceQueryOperatorType - - // The value for which to search. - Values []string - - noSmithyDocumentSerde -} - -// A summary of compliance information by compliance type. -type ComplianceSummaryItem struct { - - // The type of compliance item. For example, the compliance type can be - // Association, Patch, or Custom:string. - ComplianceType *string - - // A list of COMPLIANT items for the specified compliance type. - CompliantSummary *CompliantSummary - - // A list of NON_COMPLIANT items for the specified compliance type. - NonCompliantSummary *NonCompliantSummary - - noSmithyDocumentSerde -} - -// A summary of resources that are compliant. The summary is organized according -// to the resource count for each compliance type. -type CompliantSummary struct { - - // The total number of resources that are compliant. - CompliantCount int32 - - // A summary of the compliance severity by compliance type. - SeveritySummary *SeveritySummary - - noSmithyDocumentSerde -} - -// Describes the association of a Amazon Web Services Systems Manager document -// (SSM document) and a managed node. -type CreateAssociationBatchRequestEntry struct { - - // The name of the SSM document that contains the configuration information for - // the managed node. You can specify Command or Automation runbooks. You can - // specify Amazon Web Services-predefined documents, documents you created, or a - // document that is shared with you from another account. For SSM documents that - // are shared with you from other Amazon Web Services accounts, you must specify - // the complete SSM document ARN, in the following format: - // arn:aws:ssm:region:account-id:document/document-name For example: - // arn:aws:ssm:us-east-2:12345678912:document/My-Shared-Document For Amazon Web - // Services-predefined documents and SSM documents you created in your account, you - // only need to specify the document name. For example, AWS-ApplyPatchBaseline or - // My-Document . - // - // This member is required. - Name *string - - // The details for the CloudWatch alarm you want to apply to an automation or - // command. - AlarmConfiguration *AlarmConfiguration - - // By default, when you create a new associations, the system runs it immediately - // after it is created and then according to the schedule you specified. Specify - // this option if you don't want an association to run immediately after you create - // it. This parameter isn't supported for rate expressions. - ApplyOnlyAtCronInterval bool - - // Specify a descriptive name for the association. - AssociationName *string - - // Specify the target for the association. This target is required for - // associations that use an Automation runbook and target resources by using rate - // controls. Automation is a capability of Amazon Web Services Systems Manager. - AutomationTargetParameterName *string - - // The names or Amazon Resource Names (ARNs) of the Change Calendar type documents - // your associations are gated under. The associations only run when that Change - // Calendar is open. For more information, see Amazon Web Services Systems Manager - // Change Calendar (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-change-calendar) - // . - CalendarNames []string - - // The severity level to assign to the association. - ComplianceSeverity AssociationComplianceSeverity - - // The document version. - DocumentVersion *string - - // The managed node ID. InstanceId has been deprecated. To specify a managed node - // ID for an association, use the Targets parameter. Requests that include the - // parameter InstanceID with Systems Manager documents (SSM documents) that use - // schema version 2.0 or later will fail. In addition, if you use the parameter - // InstanceId , you can't use the parameters AssociationName , DocumentVersion , - // MaxErrors , MaxConcurrency , OutputLocation , or ScheduleExpression . To use - // these parameters, you must use the Targets parameter. - InstanceId *string - - // The maximum number of targets allowed to run the association at the same time. - // You can specify a number, for example 10, or a percentage of the target set, for - // example 10%. The default value is 100%, which means all targets run the - // association at the same time. If a new managed node starts and attempts to run - // an association while Systems Manager is running MaxConcurrency associations, - // the association is allowed to run. During the next association interval, the new - // managed node will process its association within the limit specified for - // MaxConcurrency . - MaxConcurrency *string - - // The number of errors that are allowed before the system stops sending requests - // to run the association on additional targets. You can specify either an absolute - // number of errors, for example 10, or a percentage of the target set, for example - // 10%. If you specify 3, for example, the system stops sending requests when the - // fourth error is received. If you specify 0, then the system stops sending - // requests after the first error is returned. If you run an association on 50 - // managed nodes and set MaxError to 10%, then the system stops sending the - // request when the sixth error is received. Executions that are already running an - // association when MaxErrors is reached are allowed to complete, but some of - // these executions may fail as well. If you need to ensure that there won't be - // more than max-errors failed executions, set MaxConcurrency to 1 so that - // executions proceed one at a time. - MaxErrors *string - - // An S3 bucket where you want to store the results of this request. - OutputLocation *InstanceAssociationOutputLocation - - // A description of the parameters for a document. - Parameters map[string][]string - - // A cron expression that specifies a schedule when the association runs. - ScheduleExpression *string - - // Number of days to wait after the scheduled day to run an association. - ScheduleOffset *int32 - - // The mode for generating association compliance. You can specify AUTO or MANUAL . - // In AUTO mode, the system uses the status of the association execution to - // determine the compliance status. If the association execution runs successfully, - // then the association is COMPLIANT . If the association execution doesn't run - // successfully, the association is NON-COMPLIANT . In MANUAL mode, you must - // specify the AssociationId as a parameter for the PutComplianceItems API - // operation. In this case, compliance data isn't managed by State Manager, a - // capability of Amazon Web Services Systems Manager. It is managed by your direct - // call to the PutComplianceItems API operation. By default, all associations use - // AUTO mode. - SyncCompliance AssociationSyncCompliance - - // Use this action to create an association in multiple Regions and multiple - // accounts. - TargetLocations []TargetLocation - - // A key-value mapping of document parameters to target resources. Both Targets - // and TargetMaps can't be specified together. - TargetMaps []map[string][]string - - // The managed nodes targeted by the request. - Targets []Target - - noSmithyDocumentSerde -} - -// Filter for the DescribeActivation API. -type DescribeActivationsFilter struct { - - // The name of the filter. - FilterKey DescribeActivationsFilterKeys - - // The filter values. - FilterValues []string - - noSmithyDocumentSerde -} - -// A default version of a document. -type DocumentDefaultVersionDescription struct { - - // The default version of the document. - DefaultVersion *string - - // The default version of the artifact associated with the document. - DefaultVersionName *string - - // The name of the document. - Name *string - - noSmithyDocumentSerde -} - -// Describes an Amazon Web Services Systems Manager document (SSM document). -type DocumentDescription struct { - - // The version of the document currently approved for use in the organization. - ApprovedVersion *string - - // Details about the document attachments, including names, locations, sizes, and - // so on. - AttachmentsInformation []AttachmentInformation - - // The user in your organization who created the document. - Author *string - - // The classification of a document to help you identify and categorize its use. - Category []string - - // The value that identifies a document's category. - CategoryEnum []string - - // The date when the document was created. - CreatedDate *time.Time - - // The default version. - DefaultVersion *string - - // A description of the document. - Description *string - - // The friendly name of the SSM document. This value can differ for each version - // of the document. If you want to update this value, see UpdateDocument . - DisplayName *string - - // The document format, either JSON or YAML. - DocumentFormat DocumentFormat - - // The type of document. - DocumentType DocumentType - - // The document version. - DocumentVersion *string - - // The Sha256 or Sha1 hash created by the system when the document was created. - // Sha1 hashes have been deprecated. - Hash *string - - // The hash type of the document. Valid values include Sha256 or Sha1 . Sha1 hashes - // have been deprecated. - HashType DocumentHashType - - // The latest version of the document. - LatestVersion *string - - // The name of the SSM document. - Name *string - - // The Amazon Web Services user that created the document. - Owner *string - - // A description of the parameters for a document. - Parameters []DocumentParameter - - // The version of the document that is currently under review. - PendingReviewVersion *string - - // The list of operating system (OS) platforms compatible with this SSM document. - PlatformTypes []PlatformType - - // A list of SSM documents required by a document. For example, an - // ApplicationConfiguration document requires an ApplicationConfigurationSchema - // document. - Requires []DocumentRequires - - // Details about the review of a document. - ReviewInformation []ReviewInformation - - // The current status of the review. - ReviewStatus ReviewStatus - - // The schema version. - SchemaVersion *string - - // The SHA1 hash of the document, which you can use for verification. - Sha1 *string - - // The status of the SSM document. - Status DocumentStatus - - // A message returned by Amazon Web Services Systems Manager that explains the - // Status value. For example, a Failed status might be explained by the - // StatusInformation message, "The specified S3 bucket doesn't exist. Verify that - // the URL of the S3 bucket is correct." - StatusInformation *string - - // The tags, or metadata, that have been applied to the document. - Tags []Tag - - // The target type which defines the kinds of resources the document can run on. - // For example, /AWS::EC2::Instance . For a list of valid resource types, see - // Amazon Web Services resource and property types reference (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) - // in the CloudFormation User Guide. - TargetType *string - - // The version of the artifact associated with the document. - VersionName *string - - noSmithyDocumentSerde -} - -// This data type is deprecated. Instead, use DocumentKeyValuesFilter . -type DocumentFilter struct { - - // The name of the filter. - // - // This member is required. - Key DocumentFilterKey - - // The value of the filter. - // - // This member is required. - Value *string - - noSmithyDocumentSerde -} - -// Describes the name of a SSM document. -type DocumentIdentifier struct { - - // The user in your organization who created the document. - Author *string - - // The date the SSM document was created. - CreatedDate *time.Time - - // An optional field where you can specify a friendly name for the SSM document. - // This value can differ for each version of the document. If you want to update - // this value, see UpdateDocument . - DisplayName *string - - // The document format, either JSON or YAML. - DocumentFormat DocumentFormat - - // The document type. - DocumentType DocumentType - - // The document version. - DocumentVersion *string - - // The name of the SSM document. - Name *string - - // The Amazon Web Services user that created the document. - Owner *string - - // The operating system platform. - PlatformTypes []PlatformType - - // A list of SSM documents required by a document. For example, an - // ApplicationConfiguration document requires an ApplicationConfigurationSchema - // document. - Requires []DocumentRequires - - // The current status of a document review. - ReviewStatus ReviewStatus - - // The schema version. - SchemaVersion *string - - // The tags, or metadata, that have been applied to the document. - Tags []Tag - - // The target type which defines the kinds of resources the document can run on. - // For example, /AWS::EC2::Instance . For a list of valid resource types, see - // Amazon Web Services resource and property types reference (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) - // in the CloudFormation User Guide. - TargetType *string - - // An optional field specifying the version of the artifact associated with the - // document. For example, "Release 12, Update 6". This value is unique across all - // versions of a document, and can't be changed. - VersionName *string - - noSmithyDocumentSerde -} - -// One or more filters. Use a filter to return a more specific list of documents. -// For keys, you can specify one or more tags that have been applied to a document. -// You can also use Amazon Web Services-provided keys, some of which have specific -// allowed values. These keys and their associated values are as follows: -// DocumentType -// - ApplicationConfiguration -// - ApplicationConfigurationSchema -// - Automation -// - ChangeCalendar -// - Command -// - Package -// - Policy -// - Session -// -// Owner Note that only one Owner can be specified in a request. For example: -// Key=Owner,Values=Self . -// - Amazon -// - Private -// - Public -// - Self -// - ThirdParty -// -// PlatformTypes -// - Linux -// - Windows -// -// Name is another Amazon Web Services-provided key. If you use Name as a key, you -// can use a name prefix to return a list of documents. For example, in the Amazon -// Web Services CLI, to return a list of all documents that begin with Te , run the -// following command: aws ssm list-documents --filters Key=Name,Values=Te You can -// also use the TargetType Amazon Web Services-provided key. For a list of valid -// resource type values that can be used with this key, see Amazon Web Services -// resource and property types reference (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) -// in the CloudFormation User Guide. If you specify more than two keys, only -// documents that are identified by all the tags are returned in the results. If -// you specify more than two values for a key, documents that are identified by any -// of the values are returned in the results. To specify a custom key-value pair, -// use the format Key=tag:tagName,Values=valueName . For example, if you created a -// key called region and are using the Amazon Web Services CLI to call the -// list-documents command: aws ssm list-documents --filters -// Key=tag:region,Values=east,west Key=Owner,Values=Self -type DocumentKeyValuesFilter struct { - - // The name of the filter key. - Key *string - - // The value for the filter key. - Values []string - - noSmithyDocumentSerde -} - -// Details about the response to a document review request. -type DocumentMetadataResponseInfo struct { - - // Details about a reviewer's response to a document review request. - ReviewerResponse []DocumentReviewerResponseSource - - noSmithyDocumentSerde -} - -// Parameters specified in a Systems Manager document that run on the server when -// the command is run. -type DocumentParameter struct { - - // If specified, the default values for the parameters. Parameters without a - // default value are required. Parameters with a default value are optional. - DefaultValue *string - - // A description of what the parameter does, how to use it, the default value, and - // whether or not the parameter is optional. - Description *string - - // The name of the parameter. - Name *string - - // The type of parameter. The type can be either String or StringList. - Type DocumentParameterType - - noSmithyDocumentSerde -} - -// An SSM document required by the current document. -type DocumentRequires struct { - - // The name of the required SSM document. The name can be an Amazon Resource Name - // (ARN). - // - // This member is required. - Name *string - - // The document type of the required SSM document. - RequireType *string - - // The document version required by the current document. - Version *string - - // An optional field specifying the version of the artifact associated with the - // document. For example, "Release 12, Update 6". This value is unique across all - // versions of a document, and can't be changed. - VersionName *string - - noSmithyDocumentSerde -} - -// Information about comments added to a document review request. -type DocumentReviewCommentSource struct { - - // The content of a comment entered by a user who requests a review of a new - // document version, or who reviews the new version. - Content *string - - // The type of information added to a review request. Currently, only the value - // Comment is supported. - Type DocumentReviewCommentType - - noSmithyDocumentSerde -} - -// Information about a reviewer's response to a document review request. -type DocumentReviewerResponseSource struct { - - // The comment entered by a reviewer as part of their document review response. - Comment []DocumentReviewCommentSource - - // The date and time that a reviewer entered a response to a document review - // request. - CreateTime *time.Time - - // The current review status of a new custom SSM document created by a member of - // your organization, or of the latest version of an existing SSM document. Only - // one version of a document can be in the APPROVED state at a time. When a new - // version is approved, the status of the previous version changes to REJECTED. - // Only one version of a document can be in review, or PENDING, at a time. - ReviewStatus ReviewStatus - - // The user in your organization assigned to review a document request. - Reviewer *string - - // The date and time that a reviewer last updated a response to a document review - // request. - UpdatedTime *time.Time - - noSmithyDocumentSerde -} - -// Information about a document approval review. -type DocumentReviews struct { - - // The action to take on a document approval review request. - // - // This member is required. - Action DocumentReviewAction - - // A comment entered by a user in your organization about the document review - // request. - Comment []DocumentReviewCommentSource - - noSmithyDocumentSerde -} - -// Version information about the document. -type DocumentVersionInfo struct { - - // The date the document was created. - CreatedDate *time.Time - - // The friendly name of the SSM document. This value can differ for each version - // of the document. If you want to update this value, see UpdateDocument . - DisplayName *string - - // The document format, either JSON or YAML. - DocumentFormat DocumentFormat - - // The document version. - DocumentVersion *string - - // An identifier for the default version of the document. - IsDefaultVersion bool - - // The document name. - Name *string - - // The current status of the approval review for the latest version of the - // document. - ReviewStatus ReviewStatus - - // The status of the SSM document, such as Creating , Active , Failed , and - // Deleting . - Status DocumentStatus - - // A message returned by Amazon Web Services Systems Manager that explains the - // Status value. For example, a Failed status might be explained by the - // StatusInformation message, "The specified S3 bucket doesn't exist. Verify that - // the URL of the S3 bucket is correct." - StatusInformation *string - - // The version of the artifact associated with the document. For example, "Release - // 12, Update 6". This value is unique across all versions of a document, and can't - // be changed. - VersionName *string - - noSmithyDocumentSerde -} - -// The EffectivePatch structure defines metadata about a patch along with the -// approval state of the patch in a particular patch baseline. The approval state -// includes information about whether the patch is currently approved, due to be -// approved by a rule, explicitly approved, or explicitly rejected and the date the -// patch was or will be approved. -type EffectivePatch struct { - - // Provides metadata for a patch, including information such as the KB ID, - // severity, classification and a URL for where more information can be obtained - // about the patch. - Patch *Patch - - // The status of the patch in a patch baseline. This includes information about - // whether the patch is currently approved, due to be approved by a rule, - // explicitly approved, or explicitly rejected and the date the patch was or will - // be approved. - PatchStatus *PatchStatus - - noSmithyDocumentSerde -} - -// Describes a failed association. -type FailedCreateAssociation struct { - - // The association. - Entry *CreateAssociationBatchRequestEntry - - // The source of the failure. - Fault Fault - - // A description of the failure. - Message *string - - noSmithyDocumentSerde -} - -// Information about an Automation failure. -type FailureDetails struct { - - // Detailed information about the Automation step failure. - Details map[string][]string - - // The stage of the Automation execution when the failure occurred. The stages - // include the following: InputValidation, PreVerification, Invocation, - // PostVerification. - FailureStage *string - - // The type of Automation failure. Failure types include the following: Action, - // Permission, Throttling, Verification, Internal. - FailureType *string - - noSmithyDocumentSerde -} - -// A resource policy helps you to define the IAM entity (for example, an Amazon -// Web Services account) that can manage your Systems Manager resources. Currently, -// OpsItemGroup is the only resource that supports Systems Manager resource -// policies. The resource policy for OpsItemGroup enables Amazon Web Services -// accounts to view and interact with OpsCenter operational work items (OpsItems). -type GetResourcePoliciesResponseEntry struct { - - // A resource policy helps you to define the IAM entity (for example, an Amazon - // Web Services account) that can manage your Systems Manager resources. Currently, - // OpsItemGroup is the only resource that supports Systems Manager resource - // policies. The resource policy for OpsItemGroup enables Amazon Web Services - // accounts to view and interact with OpsCenter operational work items (OpsItems). - Policy *string - - // ID of the current policy version. The hash helps to prevent a situation where - // multiple users attempt to overwrite a policy. You must provide this hash when - // updating or deleting a policy. - PolicyHash *string - - // A policy ID. - PolicyId *string - - noSmithyDocumentSerde -} - -// Status information about the aggregated associations. -type InstanceAggregatedAssociationOverview struct { - - // Detailed status information about the aggregated associations. - DetailedStatus *string - - // The number of associations for the managed node(s). - InstanceAssociationStatusAggregatedCount map[string]int32 - - noSmithyDocumentSerde -} - -// One or more association documents on the managed node. -type InstanceAssociation struct { - - // The association ID. - AssociationId *string - - // Version information for the association on the managed node. - AssociationVersion *string - - // The content of the association document for the managed node(s). - Content *string - - // The managed node ID. - InstanceId *string - - noSmithyDocumentSerde -} - -// An S3 bucket where you want to store the results of this request. For the -// minimal permissions required to enable Amazon S3 output for an association, see -// Creating associations (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc.html) -// in the Systems Manager User Guide. -type InstanceAssociationOutputLocation struct { - - // An S3 bucket where you want to store the results of this request. - S3Location *S3OutputLocation - - noSmithyDocumentSerde -} - -// The URL of S3 bucket where you want to store the results of this request. -type InstanceAssociationOutputUrl struct { - - // The URL of S3 bucket where you want to store the results of this request. - S3OutputUrl *S3OutputUrl - - noSmithyDocumentSerde -} - -// Status information about the association. -type InstanceAssociationStatusInfo struct { - - // The association ID. - AssociationId *string - - // The name of the association applied to the managed node. - AssociationName *string - - // The version of the association applied to the managed node. - AssociationVersion *string - - // Detailed status information about the association. - DetailedStatus *string - - // The association document versions. - DocumentVersion *string - - // An error code returned by the request to create the association. - ErrorCode *string - - // The date the association ran. - ExecutionDate *time.Time - - // Summary information about association execution. - ExecutionSummary *string - - // The managed node ID where the association was created. - InstanceId *string - - // The name of the association. - Name *string - - // A URL for an S3 bucket where you want to store the results of this request. - OutputUrl *InstanceAssociationOutputUrl - - // Status information about the association. - Status *string - - noSmithyDocumentSerde -} - -// Describes a filter for a specific list of managed nodes. -type InstanceInformation struct { - - // The activation ID created by Amazon Web Services Systems Manager when the - // server or virtual machine (VM) was registered. - ActivationId *string - - // The version of SSM Agent running on your Linux managed node. - AgentVersion *string - - // Information about the association. - AssociationOverview *InstanceAggregatedAssociationOverview - - // The status of the association. - AssociationStatus *string - - // The fully qualified host name of the managed node. - ComputerName *string - - // The IP address of the managed node. - IPAddress *string - - // The Identity and Access Management (IAM) role assigned to the on-premises - // Systems Manager managed node. This call doesn't return the IAM role for Amazon - // Elastic Compute Cloud (Amazon EC2) instances. To retrieve the IAM role for an - // EC2 instance, use the Amazon EC2 DescribeInstances operation. For information, - // see DescribeInstances (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) - // in the Amazon EC2 API Reference or describe-instances (https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) - // in the Amazon Web Services CLI Command Reference. - IamRole *string - - // The managed node ID. - InstanceId *string - - // Indicates whether the latest version of SSM Agent is running on your Linux - // managed node. This field doesn't indicate whether or not the latest version is - // installed on Windows managed nodes, because some older versions of Windows - // Server use the EC2Config service to process Systems Manager requests. - IsLatestVersion *bool - - // The date the association was last run. - LastAssociationExecutionDate *time.Time - - // The date and time when the agent last pinged the Systems Manager service. - LastPingDateTime *time.Time - - // The last date the association was successfully run. - LastSuccessfulAssociationExecutionDate *time.Time - - // The name assigned to an on-premises server, edge device, or virtual machine - // (VM) when it is activated as a Systems Manager managed node. The name is - // specified as the DefaultInstanceName property using the CreateActivation - // command. It is applied to the managed node by specifying the Activation Code and - // Activation ID when you install SSM Agent on the node, as explained in Install - // SSM Agent for a hybrid environment (Linux) (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-managed-linux.html) - // and Install SSM Agent for a hybrid environment (Windows) (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-managed-win.html) - // . To retrieve the Name tag of an EC2 instance, use the Amazon EC2 - // DescribeInstances operation. For information, see DescribeInstances (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) - // in the Amazon EC2 API Reference or describe-instances (https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) - // in the Amazon Web Services CLI Command Reference. - Name *string - - // Connection status of SSM Agent. The status Inactive has been deprecated and is - // no longer in use. - PingStatus PingStatus - - // The name of the operating system platform running on your managed node. - PlatformName *string - - // The operating system platform type. - PlatformType PlatformType - - // The version of the OS platform running on your managed node. - PlatformVersion *string - - // The date the server or VM was registered with Amazon Web Services as a managed - // node. - RegistrationDate *time.Time - - // The type of instance. Instances are either EC2 instances or managed instances. - ResourceType ResourceType - - // The ID of the source resource. For IoT Greengrass devices, SourceId is the - // Thing name. - SourceId *string - - // The type of the source resource. For IoT Greengrass devices, SourceType is - // AWS::IoT::Thing . - SourceType SourceType - - noSmithyDocumentSerde -} - -// Describes a filter for a specific list of managed nodes. You can filter node -// information by using tags. You specify tags by using a key-value mapping. Use -// this operation instead of the -// DescribeInstanceInformationRequest$InstanceInformationFilterList method. The -// InstanceInformationFilterList method is a legacy method and doesn't support tags. -type InstanceInformationFilter struct { - - // The name of the filter. - // - // This member is required. - Key InstanceInformationFilterKey - - // The filter values. - // - // This member is required. - ValueSet []string - - noSmithyDocumentSerde -} - -// The filters to describe or get information about your managed nodes. -type InstanceInformationStringFilter struct { - - // The filter key name to describe your managed nodes. Valid filter key values: - // ActivationIds | AgentVersion | AssociationStatus | IamRole | InstanceIds | - // PingStatus | PlatformTypes | ResourceType | SourceIds | SourceTypes | "tag-key" - // | "tag: {keyname} - // - Valid values for the AssociationStatus filter key: Success | Pending | - // Failed - // - Valid values for the PingStatus filter key: Online | ConnectionLost | - // Inactive (deprecated) - // - Valid values for the PlatformType filter key: Windows | Linux | MacOS - // - Valid values for the ResourceType filter key: EC2Instance | ManagedInstance - // - Valid values for the SourceType filter key: AWS::EC2::Instance | - // AWS::SSM::ManagedInstance | AWS::IoT::Thing - // - Valid tag examples: Key=tag-key,Values=Purpose | Key=tag:Purpose,Values=Test - // . - // - // This member is required. - Key *string - - // The filter values. - // - // This member is required. - Values []string - - noSmithyDocumentSerde -} - -// Defines the high-level patch compliance state for a managed node, providing -// information about the number of installed, missing, not applicable, and failed -// patches along with metadata about the operation when this information was -// gathered for the managed node. -type InstancePatchState struct { - - // The ID of the patch baseline used to patch the managed node. - // - // This member is required. - BaselineId *string - - // The ID of the managed node the high-level patch compliance information was - // collected for. - // - // This member is required. - InstanceId *string - - // The type of patching operation that was performed: or - // - SCAN assesses the patch compliance state. - // - INSTALL installs missing patches. - // - // This member is required. - Operation PatchOperationType - - // The time the most recent patching operation completed on the managed node. - // - // This member is required. - OperationEndTime *time.Time - - // The time the most recent patching operation was started on the managed node. - // - // This member is required. - OperationStartTime *time.Time - - // The name of the patch group the managed node belongs to. - // - // This member is required. - PatchGroup *string - - // The number of patches per node that are specified as Critical for compliance - // reporting in the patch baseline aren't installed. These patches might be - // missing, have failed installation, were rejected, or were installed but awaiting - // a required managed node reboot. The status of these managed nodes is - // NON_COMPLIANT . - CriticalNonCompliantCount *int32 - - // The number of patches from the patch baseline that were attempted to be - // installed during the last patching operation, but failed to install. - FailedCount int32 - - // An https URL or an Amazon Simple Storage Service (Amazon S3) path-style URL to - // a list of patches to be installed. This patch installation list, which you - // maintain in an S3 bucket in YAML format and specify in the SSM document - // AWS-RunPatchBaseline , overrides the patches specified by the default patch - // baseline. For more information about the InstallOverrideList parameter, see - // About the AWS-RunPatchBaseline (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-about-aws-runpatchbaseline.html) - // SSM document in the Amazon Web Services Systems Manager User Guide. - InstallOverrideList *string - - // The number of patches from the patch baseline that are installed on the managed - // node. - InstalledCount int32 - - // The number of patches not specified in the patch baseline that are installed on - // the managed node. - InstalledOtherCount int32 - - // The number of patches installed by Patch Manager since the last time the - // managed node was rebooted. - InstalledPendingRebootCount *int32 - - // The number of patches installed on a managed node that are specified in a - // RejectedPatches list. Patches with a status of InstalledRejected were typically - // installed before they were added to a RejectedPatches list. If - // ALLOW_AS_DEPENDENCY is the specified option for RejectedPatchesAction , the - // value of InstalledRejectedCount will always be 0 (zero). - InstalledRejectedCount *int32 - - // The time of the last attempt to patch the managed node with NoReboot specified - // as the reboot option. - LastNoRebootInstallOperationTime *time.Time - - // The number of patches from the patch baseline that are applicable for the - // managed node but aren't currently installed. - MissingCount int32 - - // The number of patches from the patch baseline that aren't applicable for the - // managed node and therefore aren't installed on the node. This number may be - // truncated if the list of patch names is very large. The number of patches beyond - // this limit are reported in UnreportedNotApplicableCount . - NotApplicableCount int32 - - // The number of patches per node that are specified as other than Critical or - // Security but aren't compliant with the patch baseline. The status of these - // managed nodes is NON_COMPLIANT . - OtherNonCompliantCount *int32 - - // Placeholder information. This field will always be empty in the current release - // of the service. - OwnerInformation *string - - // Indicates the reboot option specified in the patch baseline. Reboot options - // apply to Install operations only. Reboots aren't attempted for Patch Manager - // Scan operations. - // - RebootIfNeeded : Patch Manager tries to reboot the managed node if it - // installed any patches, or if any patches are detected with a status of - // InstalledPendingReboot . - // - NoReboot : Patch Manager attempts to install missing packages without trying - // to reboot the system. Patches installed with this option are assigned a status - // of InstalledPendingReboot . These patches might not be in effect until a - // reboot is performed. - RebootOption RebootOption - - // The number of patches per node that are specified as Security in a patch - // advisory aren't installed. These patches might be missing, have failed - // installation, were rejected, or were installed but awaiting a required managed - // node reboot. The status of these managed nodes is NON_COMPLIANT . - SecurityNonCompliantCount *int32 - - // The ID of the patch baseline snapshot used during the patching operation when - // this compliance data was collected. - SnapshotId *string - - // The number of patches beyond the supported limit of NotApplicableCount that - // aren't reported by name to Inventory. Inventory is a capability of Amazon Web - // Services Systems Manager. - UnreportedNotApplicableCount *int32 - - noSmithyDocumentSerde -} - -// Defines a filter used in DescribeInstancePatchStatesForPatchGroup to scope down -// the information returned by the API. Example: To filter for all managed nodes in -// a patch group having more than three patches with a FailedCount status, use the -// following for the filter: -// - Value for Key : FailedCount -// - Value for Type : GreaterThan -// - Value for Values : 3 -type InstancePatchStateFilter struct { - - // The key for the filter. Supported values include the following: - // - InstalledCount - // - InstalledOtherCount - // - InstalledPendingRebootCount - // - InstalledRejectedCount - // - MissingCount - // - FailedCount - // - UnreportedNotApplicableCount - // - NotApplicableCount - // - // This member is required. - Key *string - - // The type of comparison that should be performed for the value. - // - // This member is required. - Type InstancePatchStateOperatorType - - // The value for the filter. Must be an integer greater than or equal to 0. - // - // This member is required. - Values []string - - noSmithyDocumentSerde -} - -// Specifies the inventory type and attribute for the aggregation execution. -type InventoryAggregator struct { - - // Nested aggregators to further refine aggregation for an inventory type. - Aggregators []InventoryAggregator - - // The inventory type and attribute name for aggregation. - Expression *string - - // A user-defined set of one or more filters on which to aggregate inventory data. - // Groups return a count of resources that match and don't match the specified - // criteria. - Groups []InventoryGroup - - noSmithyDocumentSerde -} - -// Status information returned by the DeleteInventory operation. -type InventoryDeletionStatusItem struct { - - // The deletion ID returned by the DeleteInventory operation. - DeletionId *string - - // The UTC timestamp when the delete operation started. - DeletionStartTime *time.Time - - // Information about the delete operation. For more information about this - // summary, see Understanding the delete inventory summary (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-custom.html#sysman-inventory-delete) - // in the Amazon Web Services Systems Manager User Guide. - DeletionSummary *InventoryDeletionSummary - - // The status of the operation. Possible values are InProgress and Complete. - LastStatus InventoryDeletionStatus - - // Information about the status. - LastStatusMessage *string - - // The UTC timestamp of when the last status report. - LastStatusUpdateTime *time.Time - - // The name of the inventory data type. - TypeName *string - - noSmithyDocumentSerde -} - -// Information about the delete operation. -type InventoryDeletionSummary struct { - - // Remaining number of items to delete. - RemainingCount int32 - - // A list of counts and versions for deleted items. - SummaryItems []InventoryDeletionSummaryItem - - // The total number of items to delete. This count doesn't change during the - // delete operation. - TotalCount int32 - - noSmithyDocumentSerde -} - -// Either a count, remaining count, or a version number in a delete inventory -// summary. -type InventoryDeletionSummaryItem struct { - - // A count of the number of deleted items. - Count int32 - - // The remaining number of items to delete. - RemainingCount int32 - - // The inventory type version. - Version *string - - noSmithyDocumentSerde -} - -// One or more filters. Use a filter to return a more specific list of results. -type InventoryFilter struct { - - // The name of the filter key. - // - // This member is required. - Key *string - - // Inventory filter values. Example: inventory filter where managed node IDs are - // specified as values Key=AWS:InstanceInformation.InstanceId,Values= - // i-a12b3c4d5e6g, i-1a2b3c4d5e6,Type=Equal . - // - // This member is required. - Values []string - - // The type of filter. The Exists filter must be used with aggregators. For more - // information, see Aggregating inventory data (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-aggregate.html) - // in the Amazon Web Services Systems Manager User Guide. - Type InventoryQueryOperatorType - - noSmithyDocumentSerde -} - -// A user-defined set of one or more filters on which to aggregate inventory data. -// Groups return a count of resources that match and don't match the specified -// criteria. -type InventoryGroup struct { - - // Filters define the criteria for the group. The matchingCount field displays the - // number of resources that match the criteria. The notMatchingCount field - // displays the number of resources that don't match the criteria. - // - // This member is required. - Filters []InventoryFilter - - // The name of the group. - // - // This member is required. - Name *string - - noSmithyDocumentSerde -} - -// Information collected from managed nodes based on your inventory policy document -type InventoryItem struct { - - // The time the inventory information was collected. - // - // This member is required. - CaptureTime *string - - // The schema version for the inventory item. - // - // This member is required. - SchemaVersion *string - - // The name of the inventory type. Default inventory item type names start with AWS - // . Custom inventory type names will start with Custom. Default inventory item - // types include the following: AWS:AWSComponent , AWS:Application , - // AWS:InstanceInformation , AWS:Network , and AWS:WindowsUpdate . - // - // This member is required. - TypeName *string - - // The inventory data of the inventory type. - Content []map[string]string - - // MD5 hash of the inventory item type contents. The content hash is used to - // determine whether to update inventory information. The PutInventory API doesn't - // update the inventory item type contents if the MD5 hash hasn't changed since - // last update. - ContentHash *string - - // A map of associated properties for a specified inventory type. For example, - // with this attribute, you can specify the ExecutionId , ExecutionType , - // ComplianceType properties of the AWS:ComplianceItem type. - Context map[string]string - - noSmithyDocumentSerde -} - -// Attributes are the entries within the inventory item content. It contains name -// and value. -type InventoryItemAttribute struct { - - // The data type of the inventory item attribute. - // - // This member is required. - DataType InventoryAttributeDataType - - // Name of the inventory item attribute. - // - // This member is required. - Name *string - - noSmithyDocumentSerde -} - -// The inventory item schema definition. Users can use this to compose inventory -// query filters. -type InventoryItemSchema struct { - - // The schema attributes for inventory. This contains data type and attribute name. - // - // This member is required. - Attributes []InventoryItemAttribute - - // The name of the inventory type. Default inventory item type names start with - // Amazon Web Services. Custom inventory type names will start with Custom. Default - // inventory item types include the following: AWS:AWSComponent , AWS:Application , - // AWS:InstanceInformation , AWS:Network , and AWS:WindowsUpdate . - // - // This member is required. - TypeName *string - - // The alias name of the inventory type. The alias name is used for display - // purposes. - DisplayName *string - - // The schema version for the inventory item. - Version *string - - noSmithyDocumentSerde -} - -// Inventory query results. -type InventoryResultEntity struct { - - // The data section in the inventory result entity JSON. - Data map[string]InventoryResultItem - - // ID of the inventory result entity. For example, for managed node inventory the - // result will be the managed node ID. For EC2 instance inventory, the result will - // be the instance ID. - Id *string - - noSmithyDocumentSerde -} - -// The inventory result item. -type InventoryResultItem struct { - - // Contains all the inventory data of the item type. Results include attribute - // names and values. - // - // This member is required. - Content []map[string]string - - // The schema version for the inventory result item/ - // - // This member is required. - SchemaVersion *string - - // The name of the inventory result item type. - // - // This member is required. - TypeName *string - - // The time inventory item data was captured. - CaptureTime *string - - // MD5 hash of the inventory item type contents. The content hash is used to - // determine whether to update inventory information. The PutInventory API doesn't - // update the inventory item type contents if the MD5 hash hasn't changed since - // last update. - ContentHash *string - - noSmithyDocumentSerde -} - -// Information about an Amazon Simple Storage Service (Amazon S3) bucket to write -// managed node-level logs to. LoggingInfo has been deprecated. To specify an -// Amazon Simple Storage Service (Amazon S3) bucket to contain logs, instead use -// the OutputS3BucketName and OutputS3KeyPrefix options in the -// TaskInvocationParameters structure. For information about how Amazon Web -// Services Systems Manager handles these options for the supported maintenance -// window task types, see MaintenanceWindowTaskInvocationParameters . -type LoggingInfo struct { - - // The name of an S3 bucket where execution logs are stored. - // - // This member is required. - S3BucketName *string - - // The Amazon Web Services Region where the S3 bucket is located. - // - // This member is required. - S3Region *string - - // (Optional) The S3 bucket subfolder. - S3KeyPrefix *string - - noSmithyDocumentSerde -} - -// The parameters for an AUTOMATION task type. -type MaintenanceWindowAutomationParameters struct { - - // The version of an Automation runbook to use during task execution. - DocumentVersion *string - - // The parameters for the AUTOMATION task. For information about specifying and - // updating task parameters, see RegisterTaskWithMaintenanceWindow and - // UpdateMaintenanceWindowTask . LoggingInfo has been deprecated. To specify an - // Amazon Simple Storage Service (Amazon S3) bucket to contain logs, instead use - // the OutputS3BucketName and OutputS3KeyPrefix options in the - // TaskInvocationParameters structure. For information about how Amazon Web - // Services Systems Manager handles these options for the supported maintenance - // window task types, see MaintenanceWindowTaskInvocationParameters . - // TaskParameters has been deprecated. To specify parameters to pass to a task when - // it runs, instead use the Parameters option in the TaskInvocationParameters - // structure. For information about how Systems Manager handles these options for - // the supported maintenance window task types, see - // MaintenanceWindowTaskInvocationParameters . For AUTOMATION task types, Amazon - // Web Services Systems Manager ignores any values specified for these parameters. - Parameters map[string][]string - - noSmithyDocumentSerde -} - -// Describes the information about an execution of a maintenance window. -type MaintenanceWindowExecution struct { - - // The time the execution finished. - EndTime *time.Time - - // The time the execution started. - StartTime *time.Time - - // The status of the execution. - Status MaintenanceWindowExecutionStatus - - // The details explaining the status. Not available for all status values. - StatusDetails *string - - // The ID of the maintenance window execution. - WindowExecutionId *string - - // The ID of the maintenance window. - WindowId *string - - noSmithyDocumentSerde -} - -// Information about a task execution performed as part of a maintenance window -// execution. -type MaintenanceWindowExecutionTaskIdentity struct { - - // The details for the CloudWatch alarm applied to your maintenance window task. - AlarmConfiguration *AlarmConfiguration - - // The time the task execution finished. - EndTime *time.Time - - // The time the task execution started. - StartTime *time.Time - - // The status of the task execution. - Status MaintenanceWindowExecutionStatus - - // The details explaining the status of the task execution. Not available for all - // status values. - StatusDetails *string - - // The Amazon Resource Name (ARN) of the task that ran. - TaskArn *string - - // The ID of the specific task execution in the maintenance window execution. - TaskExecutionId *string - - // The type of task that ran. - TaskType MaintenanceWindowTaskType - - // The CloudWatch alarm that was invoked by the maintenance window task. - TriggeredAlarms []AlarmStateInformation - - // The ID of the maintenance window execution that ran the task. - WindowExecutionId *string - - noSmithyDocumentSerde -} - -// Describes the information about a task invocation for a particular target as -// part of a task execution performed as part of a maintenance window execution. -type MaintenanceWindowExecutionTaskInvocationIdentity struct { - - // The time the invocation finished. - EndTime *time.Time - - // The ID of the action performed in the service that actually handled the task - // invocation. If the task type is RUN_COMMAND , this value is the command ID. - ExecutionId *string - - // The ID of the task invocation. - InvocationId *string - - // User-provided value that was specified when the target was registered with the - // maintenance window. This was also included in any Amazon CloudWatch Events - // events raised during the task invocation. - OwnerInformation *string - - // The parameters that were provided for the invocation when it was run. - Parameters *string - - // The time the invocation started. - StartTime *time.Time - - // The status of the task invocation. - Status MaintenanceWindowExecutionStatus - - // The details explaining the status of the task invocation. Not available for all - // status values. - StatusDetails *string - - // The ID of the specific task execution in the maintenance window execution. - TaskExecutionId *string - - // The task type. - TaskType MaintenanceWindowTaskType - - // The ID of the maintenance window execution that ran the task. - WindowExecutionId *string - - // The ID of the target definition in this maintenance window the invocation was - // performed for. - WindowTargetId *string - - noSmithyDocumentSerde -} - -// Filter used in the request. Supported filter keys depend on the API operation -// that includes the filter. API operations that use MaintenanceWindowFilter> -// include the following: -// - DescribeMaintenanceWindowExecutions -// - DescribeMaintenanceWindowExecutionTaskInvocations -// - DescribeMaintenanceWindowExecutionTasks -// - DescribeMaintenanceWindows -// - DescribeMaintenanceWindowTargets -// - DescribeMaintenanceWindowTasks -type MaintenanceWindowFilter struct { - - // The name of the filter. - Key *string - - // The filter values. - Values []string - - noSmithyDocumentSerde -} - -// Information about the maintenance window. -type MaintenanceWindowIdentity struct { - - // The number of hours before the end of the maintenance window that Amazon Web - // Services Systems Manager stops scheduling new tasks for execution. - Cutoff int32 - - // A description of the maintenance window. - Description *string - - // The duration of the maintenance window in hours. - Duration *int32 - - // Indicates whether the maintenance window is enabled. - Enabled bool - - // The date and time, in ISO-8601 Extended format, for when the maintenance window - // is scheduled to become inactive. - EndDate *string - - // The name of the maintenance window. - Name *string - - // The next time the maintenance window will actually run, taking into account any - // specified times for the maintenance window to become active or inactive. - NextExecutionTime *string - - // The schedule of the maintenance window in the form of a cron or rate expression. - Schedule *string - - // The number of days to wait to run a maintenance window after the scheduled cron - // expression date and time. - ScheduleOffset *int32 - - // The time zone that the scheduled maintenance window executions are based on, in - // Internet Assigned Numbers Authority (IANA) format. - ScheduleTimezone *string - - // The date and time, in ISO-8601 Extended format, for when the maintenance window - // is scheduled to become active. - StartDate *string - - // The ID of the maintenance window. - WindowId *string - - noSmithyDocumentSerde -} - -// The maintenance window to which the specified target belongs. -type MaintenanceWindowIdentityForTarget struct { - - // The name of the maintenance window. - Name *string - - // The ID of the maintenance window. - WindowId *string - - noSmithyDocumentSerde -} - -// The parameters for a LAMBDA task type. For information about specifying and -// updating task parameters, see RegisterTaskWithMaintenanceWindow and -// UpdateMaintenanceWindowTask . LoggingInfo has been deprecated. To specify an -// Amazon Simple Storage Service (Amazon S3) bucket to contain logs, instead use -// the OutputS3BucketName and OutputS3KeyPrefix options in the -// TaskInvocationParameters structure. For information about how Amazon Web -// Services Systems Manager handles these options for the supported maintenance -// window task types, see MaintenanceWindowTaskInvocationParameters . -// TaskParameters has been deprecated. To specify parameters to pass to a task when -// it runs, instead use the Parameters option in the TaskInvocationParameters -// structure. For information about how Systems Manager handles these options for -// the supported maintenance window task types, see -// MaintenanceWindowTaskInvocationParameters . For Lambda tasks, Systems Manager -// ignores any values specified for TaskParameters and LoggingInfo. -type MaintenanceWindowLambdaParameters struct { - - // Pass client-specific information to the Lambda function that you are invoking. - // You can then process the client information in your Lambda function as you - // choose through the context variable. - ClientContext *string - - // JSON to provide to your Lambda function as input. - Payload []byte - - // (Optional) Specify an Lambda function version or alias name. If you specify a - // function version, the operation uses the qualified function Amazon Resource Name - // (ARN) to invoke a specific Lambda function. If you specify an alias name, the - // operation uses the alias ARN to invoke the Lambda function version to which the - // alias points. - Qualifier *string - - noSmithyDocumentSerde -} - -// The parameters for a RUN_COMMAND task type. For information about specifying -// and updating task parameters, see RegisterTaskWithMaintenanceWindow and -// UpdateMaintenanceWindowTask . LoggingInfo has been deprecated. To specify an -// Amazon Simple Storage Service (Amazon S3) bucket to contain logs, instead use -// the OutputS3BucketName and OutputS3KeyPrefix options in the -// TaskInvocationParameters structure. For information about how Amazon Web -// Services Systems Manager handles these options for the supported maintenance -// window task types, see MaintenanceWindowTaskInvocationParameters . -// TaskParameters has been deprecated. To specify parameters to pass to a task when -// it runs, instead use the Parameters option in the TaskInvocationParameters -// structure. For information about how Systems Manager handles these options for -// the supported maintenance window task types, see -// MaintenanceWindowTaskInvocationParameters . For RUN_COMMAND tasks, Systems -// Manager uses specified values for TaskParameters and LoggingInfo only if no -// values are specified for TaskInvocationParameters . -type MaintenanceWindowRunCommandParameters struct { - - // Configuration options for sending command output to Amazon CloudWatch Logs. - CloudWatchOutputConfig *CloudWatchOutputConfig - - // Information about the commands to run. - Comment *string - - // The SHA-256 or SHA-1 hash created by the system when the document was created. - // SHA-1 hashes have been deprecated. - DocumentHash *string - - // SHA-256 or SHA-1. SHA-1 hashes have been deprecated. - DocumentHashType DocumentHashType - - // The Amazon Web Services Systems Manager document (SSM document) version to use - // in the request. You can specify $DEFAULT , $LATEST , or a specific version - // number. If you run commands by using the Amazon Web Services CLI, then you must - // escape the first two options by using a backslash. If you specify a version - // number, then you don't need to use the backslash. For example: - // --document-version "\$DEFAULT" - // --document-version "\$LATEST" - // - // --document-version "3" - DocumentVersion *string - - // Configurations for sending notifications about command status changes on a - // per-managed node basis. - NotificationConfig *NotificationConfig - - // The name of the Amazon Simple Storage Service (Amazon S3) bucket. - OutputS3BucketName *string - - // The S3 bucket subfolder. - OutputS3KeyPrefix *string - - // The parameters for the RUN_COMMAND task execution. - Parameters map[string][]string - - // The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) - // service role to use to publish Amazon Simple Notification Service (Amazon SNS) - // notifications for maintenance window Run Command tasks. - ServiceRoleArn *string - - // If this time is reached and the command hasn't already started running, it - // doesn't run. - TimeoutSeconds *int32 - - noSmithyDocumentSerde -} - -// The parameters for a STEP_FUNCTIONS task. For information about specifying and -// updating task parameters, see RegisterTaskWithMaintenanceWindow and -// UpdateMaintenanceWindowTask . LoggingInfo has been deprecated. To specify an -// Amazon Simple Storage Service (Amazon S3) bucket to contain logs, instead use -// the OutputS3BucketName and OutputS3KeyPrefix options in the -// TaskInvocationParameters structure. For information about how Amazon Web -// Services Systems Manager handles these options for the supported maintenance -// window task types, see MaintenanceWindowTaskInvocationParameters . -// TaskParameters has been deprecated. To specify parameters to pass to a task when -// it runs, instead use the Parameters option in the TaskInvocationParameters -// structure. For information about how Systems Manager handles these options for -// the supported maintenance window task types, see -// MaintenanceWindowTaskInvocationParameters . For Step Functions tasks, Systems -// Manager ignores any values specified for TaskParameters and LoggingInfo . -type MaintenanceWindowStepFunctionsParameters struct { - - // The inputs for the STEP_FUNCTIONS task. - Input *string - - // The name of the STEP_FUNCTIONS task. - Name *string - - noSmithyDocumentSerde -} - -// The target registered with the maintenance window. -type MaintenanceWindowTarget struct { - - // A description for the target. - Description *string - - // The name for the maintenance window target. - Name *string - - // A user-provided value that will be included in any Amazon CloudWatch Events - // events that are raised while running tasks for these targets in this maintenance - // window. - OwnerInformation *string - - // The type of target that is being registered with the maintenance window. - ResourceType MaintenanceWindowResourceType - - // The targets, either managed nodes or tags. Specify managed nodes using the - // following format: Key=instanceids,Values=, Tags are specified using the - // following format: Key=,Values= . - Targets []Target - - // The ID of the maintenance window to register the target with. - WindowId *string - - // The ID of the target. - WindowTargetId *string - - noSmithyDocumentSerde -} - -// Information about a task defined for a maintenance window. -type MaintenanceWindowTask struct { - - // The details for the CloudWatch alarm applied to your maintenance window task. - AlarmConfiguration *AlarmConfiguration - - // The specification for whether tasks should continue to run after the cutoff - // time specified in the maintenance windows is reached. - CutoffBehavior MaintenanceWindowTaskCutoffBehavior - - // A description of the task. - Description *string - - // Information about an S3 bucket to write task-level logs to. LoggingInfo has - // been deprecated. To specify an Amazon Simple Storage Service (Amazon S3) bucket - // to contain logs, instead use the OutputS3BucketName and OutputS3KeyPrefix - // options in the TaskInvocationParameters structure. For information about how - // Amazon Web Services Systems Manager handles these options for the supported - // maintenance window task types, see MaintenanceWindowTaskInvocationParameters . - LoggingInfo *LoggingInfo - - // The maximum number of targets this task can be run for, in parallel. Although - // this element is listed as "Required: No", a value can be omitted only when you - // are registering or updating a targetless task (https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-targetless-tasks.html) - // You must provide a value in all other cases. For maintenance window tasks - // without a target specified, you can't supply a value for this option. Instead, - // the system inserts a placeholder value of 1 . This value doesn't affect the - // running of your task. - MaxConcurrency *string - - // The maximum number of errors allowed before this task stops being scheduled. - // Although this element is listed as "Required: No", a value can be omitted only - // when you are registering or updating a targetless task (https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-targetless-tasks.html) - // You must provide a value in all other cases. For maintenance window tasks - // without a target specified, you can't supply a value for this option. Instead, - // the system inserts a placeholder value of 1 . This value doesn't affect the - // running of your task. - MaxErrors *string - - // The task name. - Name *string - - // The priority of the task in the maintenance window. The lower the number, the - // higher the priority. Tasks that have the same priority are scheduled in - // parallel. - Priority int32 - - // The Amazon Resource Name (ARN) of the Identity and Access Management (IAM) - // service role to use to publish Amazon Simple Notification Service (Amazon SNS) - // notifications for maintenance window Run Command tasks. - ServiceRoleArn *string - - // The targets (either managed nodes or tags). Managed nodes are specified using - // Key=instanceids,Values=, . Tags are specified using Key=,Values= . - Targets []Target - - // The resource that the task uses during execution. For RUN_COMMAND and AUTOMATION - // task types, TaskArn is the Amazon Web Services Systems Manager (SSM document) - // name or ARN. For LAMBDA tasks, it's the function name or ARN. For STEP_FUNCTIONS - // tasks, it's the state machine ARN. - TaskArn *string - - // The parameters that should be passed to the task when it is run. TaskParameters - // has been deprecated. To specify parameters to pass to a task when it runs, - // instead use the Parameters option in the TaskInvocationParameters structure. - // For information about how Systems Manager handles these options for the - // supported maintenance window task types, see - // MaintenanceWindowTaskInvocationParameters . - TaskParameters map[string]MaintenanceWindowTaskParameterValueExpression - - // The type of task. - Type MaintenanceWindowTaskType - - // The ID of the maintenance window where the task is registered. - WindowId *string - - // The task ID. - WindowTaskId *string - - noSmithyDocumentSerde -} - -// The parameters for task execution. -type MaintenanceWindowTaskInvocationParameters struct { - - // The parameters for an AUTOMATION task type. - Automation *MaintenanceWindowAutomationParameters - - // The parameters for a LAMBDA task type. - Lambda *MaintenanceWindowLambdaParameters - - // The parameters for a RUN_COMMAND task type. - RunCommand *MaintenanceWindowRunCommandParameters - - // The parameters for a STEP_FUNCTIONS task type. - StepFunctions *MaintenanceWindowStepFunctionsParameters - - noSmithyDocumentSerde -} - -// Defines the values for a task parameter. -type MaintenanceWindowTaskParameterValueExpression struct { - - // This field contains an array of 0 or more strings, each 1 to 255 characters in - // length. - Values []string - - noSmithyDocumentSerde -} - -// Metadata to assign to an Application Manager application. -type MetadataValue struct { - - // Metadata value to assign to an Application Manager application. - Value *string - - noSmithyDocumentSerde -} - -// A summary of resources that aren't compliant. The summary is organized -// according to resource type. -type NonCompliantSummary struct { - - // The total number of compliance items that aren't compliant. - NonCompliantCount int32 - - // A summary of the non-compliance severity by compliance type - SeveritySummary *SeveritySummary - - noSmithyDocumentSerde -} - -// Configurations for sending notifications. -type NotificationConfig struct { - - // An Amazon Resource Name (ARN) for an Amazon Simple Notification Service (Amazon - // SNS) topic. Run Command pushes notifications about command status changes to - // this topic. - NotificationArn *string - - // The different events for which you can receive notifications. To learn more - // about these events, see Monitoring Systems Manager status changes using Amazon - // SNS notifications (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitoring-sns-notifications.html) - // in the Amazon Web Services Systems Manager User Guide. - NotificationEvents []NotificationEvent - - // The type of notification. - // - Command : Receive notification when the status of a command changes. - // - Invocation : For commands sent to multiple managed nodes, receive - // notification on a per-node basis when the status of a command changes. - NotificationType NotificationType - - noSmithyDocumentSerde -} - -// One or more aggregators for viewing counts of OpsData using different -// dimensions such as Source , CreatedTime , or Source and CreatedTime , to name a -// few. -type OpsAggregator struct { - - // Either a Range or Count aggregator for limiting an OpsData summary. - AggregatorType *string - - // A nested aggregator for viewing counts of OpsData. - Aggregators []OpsAggregator - - // The name of an OpsData attribute on which to limit the count of OpsData. - AttributeName *string - - // The aggregator filters. - Filters []OpsFilter - - // The data type name to use for viewing counts of OpsData. - TypeName *string - - // The aggregator value. - Values map[string]string - - noSmithyDocumentSerde -} - -// The result of the query. -type OpsEntity struct { - - // The data returned by the query. - Data map[string]OpsEntityItem - - // The query ID. - Id *string - - noSmithyDocumentSerde -} - -// The OpsData summary. -type OpsEntityItem struct { - - // The time the OpsData was captured. - CaptureTime *string - - // The details of an OpsData summary. - Content []map[string]string - - noSmithyDocumentSerde -} - -// A filter for viewing OpsData summaries. -type OpsFilter struct { - - // The name of the filter. - // - // This member is required. - Key *string - - // The filter value. - // - // This member is required. - Values []string - - // The type of filter. - Type OpsFilterOperatorType - - noSmithyDocumentSerde -} - -// Operations engineers and IT professionals use Amazon Web Services Systems -// Manager OpsCenter to view, investigate, and remediate operational work items -// (OpsItems) impacting the performance and health of their Amazon Web Services -// resources. OpsCenter is integrated with Amazon EventBridge and Amazon -// CloudWatch. This means you can configure these services to automatically create -// an OpsItem in OpsCenter when a CloudWatch alarm enters the ALARM state or when -// EventBridge processes an event from any Amazon Web Services service that -// publishes events. Configuring Amazon CloudWatch alarms and EventBridge events to -// automatically create OpsItems allows you to quickly diagnose and remediate -// issues with Amazon Web Services resources from a single console. To help you -// diagnose issues, each OpsItem includes contextually relevant information such as -// the name and ID of the Amazon Web Services resource that generated the OpsItem, -// alarm or event details, alarm history, and an alarm timeline graph. For the -// Amazon Web Services resource, OpsCenter aggregates information from Config, -// CloudTrail logs, and EventBridge, so you don't have to navigate across multiple -// console pages during your investigation. For more information, see OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) -// in the Amazon Web Services Systems Manager User Guide. -type OpsItem struct { - - // The time a runbook workflow ended. Currently reported only for the OpsItem type - // /aws/changerequest . - ActualEndTime *time.Time - - // The time a runbook workflow started. Currently reported only for the OpsItem - // type /aws/changerequest . - ActualStartTime *time.Time - - // An OpsItem category. Category options include: Availability, Cost, Performance, - // Recovery, Security. - Category *string - - // The ARN of the Amazon Web Services account that created the OpsItem. - CreatedBy *string - - // The date and time the OpsItem was created. - CreatedTime *time.Time - - // The OpsItem description. - Description *string - - // The ARN of the Amazon Web Services account that last updated the OpsItem. - LastModifiedBy *string - - // The date and time the OpsItem was last updated. - LastModifiedTime *time.Time - - // The Amazon Resource Name (ARN) of an Amazon Simple Notification Service (Amazon - // SNS) topic where notifications are sent when this OpsItem is edited or changed. - Notifications []OpsItemNotification - - // Operational data is custom data that provides useful reference details about - // the OpsItem. For example, you can specify log files, error strings, license - // keys, troubleshooting tips, or other relevant data. You enter operational data - // as key-value pairs. The key has a maximum length of 128 characters. The value - // has a maximum size of 20 KB. Operational data keys can't begin with the - // following: amazon , aws , amzn , ssm , /amazon , /aws , /amzn , /ssm . You can - // choose to make the data searchable by other users in the account or you can - // restrict search access. Searchable data means that all users with access to the - // OpsItem Overview page (as provided by the DescribeOpsItems API operation) can - // view and search on the specified data. Operational data that isn't searchable is - // only viewable by users who have access to the OpsItem (as provided by the - // GetOpsItem API operation). Use the /aws/resources key in OperationalData to - // specify a related resource in the request. Use the /aws/automations key in - // OperationalData to associate an Automation runbook with the OpsItem. To view - // Amazon Web Services CLI example commands that use these keys, see Creating - // OpsItems manually (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-manually-create-OpsItems.html) - // in the Amazon Web Services Systems Manager User Guide. - OperationalData map[string]OpsItemDataValue - - // The OpsItem Amazon Resource Name (ARN). - OpsItemArn *string - - // The ID of the OpsItem. - OpsItemId *string - - // The type of OpsItem. Systems Manager supports the following types of OpsItems: - // - /aws/issue This type of OpsItem is used for default OpsItems created by - // OpsCenter. - // - /aws/changerequest This type of OpsItem is used by Change Manager for - // reviewing and approving or rejecting change requests. - // - /aws/insight This type of OpsItem is used by OpsCenter for aggregating and - // reporting on duplicate OpsItems. - OpsItemType *string - - // The time specified in a change request for a runbook workflow to end. Currently - // supported only for the OpsItem type /aws/changerequest . - PlannedEndTime *time.Time - - // The time specified in a change request for a runbook workflow to start. - // Currently supported only for the OpsItem type /aws/changerequest . - PlannedStartTime *time.Time - - // The importance of this OpsItem in relation to other OpsItems in the system. - Priority *int32 - - // One or more OpsItems that share something in common with the current OpsItem. - // For example, related OpsItems can include OpsItems with similar error messages, - // impacted resources, or statuses for the impacted resource. - RelatedOpsItems []RelatedOpsItem - - // The severity of the OpsItem. Severity options range from 1 to 4. - Severity *string - - // The origin of the OpsItem, such as Amazon EC2 or Systems Manager. The impacted - // resource is a subset of source. - Source *string - - // The OpsItem status. Status can be Open , In Progress , or Resolved . For more - // information, see Editing OpsItem details (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems-editing-details.html) - // in the Amazon Web Services Systems Manager User Guide. - Status OpsItemStatus - - // A short heading that describes the nature of the OpsItem and the impacted - // resource. - Title *string - - // The version of this OpsItem. Each time the OpsItem is edited the version number - // increments by one. - Version *string - - noSmithyDocumentSerde -} - -// An object that defines the value of the key and its type in the OperationalData -// map. -type OpsItemDataValue struct { - - // The type of key-value pair. Valid types include SearchableString and String . - Type OpsItemDataType - - // The value of the OperationalData key. - Value *string - - noSmithyDocumentSerde -} - -// Describes a filter for a specific list of OpsItem events. You can filter event -// information by using tags. You specify tags by using a key-value pair mapping. -type OpsItemEventFilter struct { - - // The name of the filter key. Currently, the only supported value is OpsItemId . - // - // This member is required. - Key OpsItemEventFilterKey - - // The operator used by the filter call. Currently, the only supported value is - // Equal . - // - // This member is required. - Operator OpsItemEventFilterOperator - - // The values for the filter, consisting of one or more OpsItem IDs. - // - // This member is required. - Values []string - - noSmithyDocumentSerde -} - -// Summary information about an OpsItem event or that associated an OpsItem with a -// related item. -type OpsItemEventSummary struct { - - // Information about the user or resource that created the OpsItem event. - CreatedBy *OpsItemIdentity - - // The date and time the OpsItem event was created. - CreatedTime *time.Time - - // Specific information about the OpsItem event. - Detail *string - - // The type of information provided as a detail. - DetailType *string - - // The ID of the OpsItem event. - EventId *string - - // The ID of the OpsItem. - OpsItemId *string - - // The source of the OpsItem event. - Source *string - - noSmithyDocumentSerde -} - -// Describes an OpsItem filter. -type OpsItemFilter struct { - - // The name of the filter. - // - // This member is required. - Key OpsItemFilterKey - - // The operator used by the filter call. - // - // This member is required. - Operator OpsItemFilterOperator - - // The filter value. - // - // This member is required. - Values []string - - noSmithyDocumentSerde -} - -// Information about the user or resource that created an OpsItem event. -type OpsItemIdentity struct { - - // The Amazon Resource Name (ARN) of the IAM entity that created the OpsItem event. - Arn *string - - noSmithyDocumentSerde -} - -// A notification about the OpsItem. -type OpsItemNotification struct { - - // The Amazon Resource Name (ARN) of an Amazon Simple Notification Service (Amazon - // SNS) topic where notifications are sent when this OpsItem is edited or changed. - Arn *string - - noSmithyDocumentSerde -} - -// Describes a filter for a specific list of related-item resources. -type OpsItemRelatedItemsFilter struct { - - // The name of the filter key. Supported values include ResourceUri , ResourceType - // , or AssociationId . - // - // This member is required. - Key OpsItemRelatedItemsFilterKey - - // The operator used by the filter call. The only supported operator is EQUAL . - // - // This member is required. - Operator OpsItemRelatedItemsFilterOperator - - // The values for the filter. - // - // This member is required. - Values []string - - noSmithyDocumentSerde -} - -// Summary information about related-item resources for an OpsItem. -type OpsItemRelatedItemSummary struct { - - // The association ID. - AssociationId *string - - // The association type. - AssociationType *string - - // Information about the user or resource that created an OpsItem event. - CreatedBy *OpsItemIdentity - - // The time the related-item association was created. - CreatedTime *time.Time - - // Information about the user or resource that created an OpsItem event. - LastModifiedBy *OpsItemIdentity - - // The time the related-item association was last updated. - LastModifiedTime *time.Time - - // The OpsItem ID. - OpsItemId *string - - // The resource type. - ResourceType *string - - // The Amazon Resource Name (ARN) of the related-item resource. - ResourceUri *string - - noSmithyDocumentSerde -} - -// A count of OpsItems. -type OpsItemSummary struct { - - // The time a runbook workflow ended. Currently reported only for the OpsItem type - // /aws/changerequest . - ActualEndTime *time.Time - - // The time a runbook workflow started. Currently reported only for the OpsItem - // type /aws/changerequest . - ActualStartTime *time.Time - - // A list of OpsItems by category. - Category *string - - // The Amazon Resource Name (ARN) of the IAM entity that created the OpsItem. - CreatedBy *string - - // The date and time the OpsItem was created. - CreatedTime *time.Time - - // The Amazon Resource Name (ARN) of the IAM entity that created the OpsItem. - LastModifiedBy *string - - // The date and time the OpsItem was last updated. - LastModifiedTime *time.Time - - // Operational data is custom data that provides useful reference details about - // the OpsItem. - OperationalData map[string]OpsItemDataValue - - // The ID of the OpsItem. - OpsItemId *string - - // The type of OpsItem. Systems Manager supports the following types of OpsItems: - // - /aws/issue This type of OpsItem is used for default OpsItems created by - // OpsCenter. - // - /aws/changerequest This type of OpsItem is used by Change Manager for - // reviewing and approving or rejecting change requests. - // - /aws/insight This type of OpsItem is used by OpsCenter for aggregating and - // reporting on duplicate OpsItems. - OpsItemType *string - - // The time specified in a change request for a runbook workflow to end. Currently - // supported only for the OpsItem type /aws/changerequest . - PlannedEndTime *time.Time - - // The time specified in a change request for a runbook workflow to start. - // Currently supported only for the OpsItem type /aws/changerequest . - PlannedStartTime *time.Time - - // The importance of this OpsItem in relation to other OpsItems in the system. - Priority *int32 - - // A list of OpsItems by severity. - Severity *string - - // The impacted Amazon Web Services resource. - Source *string - - // The OpsItem status. Status can be Open , In Progress , or Resolved . - Status OpsItemStatus - - // A short heading that describes the nature of the OpsItem and the impacted - // resource. - Title *string - - noSmithyDocumentSerde -} - -// Operational metadata for an application in Application Manager. -type OpsMetadata struct { - - // The date the OpsMetadata objects was created. - CreationDate *time.Time - - // The date the OpsMetadata object was last updated. - LastModifiedDate *time.Time - - // The user name who last updated the OpsMetadata object. - LastModifiedUser *string - - // The Amazon Resource Name (ARN) of the OpsMetadata Object or blob. - OpsMetadataArn *string - - // The ID of the Application Manager application. - ResourceId *string - - noSmithyDocumentSerde -} - -// A filter to limit the number of OpsMetadata objects displayed. -type OpsMetadataFilter struct { - - // A filter key. - // - // This member is required. - Key *string - - // A filter value. - // - // This member is required. - Values []string - - noSmithyDocumentSerde -} - -// The OpsItem data type to return. -type OpsResultAttribute struct { - - // Name of the data type. Valid value: AWS:OpsItem , AWS:EC2InstanceInformation , - // AWS:OpsItemTrendline , or AWS:ComplianceSummary . - // - // This member is required. - TypeName *string - - noSmithyDocumentSerde -} - -// Information about the source where the association execution details are stored. -type OutputSource struct { - - // The ID of the output source, for example the URL of an S3 bucket. - OutputSourceId *string - - // The type of source where the association execution details are stored, for - // example, Amazon S3. - OutputSourceType *string - - noSmithyDocumentSerde -} - -// An Amazon Web Services Systems Manager parameter in Parameter Store. -type Parameter struct { - - // The Amazon Resource Name (ARN) of the parameter. - ARN *string - - // The data type of the parameter, such as text or aws:ec2:image . The default is - // text . - DataType *string - - // Date the parameter was last changed or updated and the parameter version was - // created. - LastModifiedDate *time.Time - - // The name of the parameter. - Name *string - - // Either the version number or the label used to retrieve the parameter value. - // Specify selectors by using one of the following formats: parameter_name:version - // parameter_name:label - Selector *string - - // Applies to parameters that reference information in other Amazon Web Services - // services. SourceResult is the raw result or response from the source. - SourceResult *string - - // The type of parameter. Valid values include the following: String , StringList , - // and SecureString . If type is StringList , the system returns a comma-separated - // string with no spaces between commas in the Value field. - Type ParameterType - - // The parameter value. If type is StringList , the system returns a - // comma-separated string with no spaces between commas in the Value field. - Value *string - - // The parameter version. - Version int64 - - noSmithyDocumentSerde -} - -// Information about parameter usage. -type ParameterHistory struct { - - // Parameter names can include the following letters and symbols. a-zA-Z0-9_.- - AllowedPattern *string - - // The data type of the parameter, such as text or aws:ec2:image . The default is - // text . - DataType *string - - // Information about the parameter. - Description *string - - // The ID of the query key used for this parameter. - KeyId *string - - // Labels assigned to the parameter version. - Labels []string - - // Date the parameter was last changed or updated. - LastModifiedDate *time.Time - - // Amazon Resource Name (ARN) of the Amazon Web Services user who last changed the - // parameter. - LastModifiedUser *string - - // The name of the parameter. - Name *string - - // Information about the policies assigned to a parameter. Assigning parameter - // policies (https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html) - // in the Amazon Web Services Systems Manager User Guide. - Policies []ParameterInlinePolicy - - // The parameter tier. - Tier ParameterTier - - // The type of parameter used. - Type ParameterType - - // The parameter value. - Value *string - - // The parameter version. - Version int64 - - noSmithyDocumentSerde -} - -// One or more policies assigned to a parameter. -type ParameterInlinePolicy struct { - - // The status of the policy. Policies report the following statuses: Pending (the - // policy hasn't been enforced or applied yet), Finished (the policy was applied), - // Failed (the policy wasn't applied), or InProgress (the policy is being applied - // now). - PolicyStatus *string - - // The JSON text of the policy. - PolicyText *string - - // The type of policy. Parameter Store, a capability of Amazon Web Services - // Systems Manager, supports the following policy types: Expiration, - // ExpirationNotification, and NoChangeNotification. - PolicyType *string - - noSmithyDocumentSerde -} - -// Metadata includes information like the ARN of the last user and the date/time -// the parameter was last used. -type ParameterMetadata struct { - - // A parameter name can include only the following letters and symbols. - // a-zA-Z0-9_.- - AllowedPattern *string - - // The data type of the parameter, such as text or aws:ec2:image . The default is - // text . - DataType *string - - // Description of the parameter actions. - Description *string - - // The ID of the query key used for this parameter. - KeyId *string - - // Date the parameter was last changed or updated. - LastModifiedDate *time.Time - - // Amazon Resource Name (ARN) of the Amazon Web Services user who last changed the - // parameter. - LastModifiedUser *string - - // The parameter name. - Name *string - - // A list of policies associated with a parameter. - Policies []ParameterInlinePolicy - - // The parameter tier. - Tier ParameterTier - - // The type of parameter. Valid parameter types include the following: String , - // StringList , and SecureString . - Type ParameterType - - // The parameter version. - Version int64 - - noSmithyDocumentSerde -} - -// This data type is deprecated. Instead, use ParameterStringFilter . -type ParametersFilter struct { - - // The name of the filter. - // - // This member is required. - Key ParametersFilterKey - - // The filter values. - // - // This member is required. - Values []string - - noSmithyDocumentSerde -} - -// One or more filters. Use a filter to return a more specific list of results. -type ParameterStringFilter struct { - - // The name of the filter. The ParameterStringFilter object is used by the - // DescribeParameters and GetParametersByPath API operations. However, not all of - // the pattern values listed for Key can be used with both operations. For - // DescribeParameters , all of the listed patterns are valid except Label . For - // GetParametersByPath , the following patterns listed for Key aren't valid: tag , - // DataType , Name , Path , and Tier . For examples of Amazon Web Services CLI - // commands demonstrating valid parameter filter constructions, see Searching for - // Systems Manager parameters (https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-search.html) - // in the Amazon Web Services Systems Manager User Guide. - // - // This member is required. - Key *string - - // For all filters used with DescribeParameters , valid options include Equals and - // BeginsWith . The Name filter additionally supports the Contains option. - // (Exception: For filters using the key Path , valid options include Recursive - // and OneLevel .) For filters used with GetParametersByPath , valid options - // include Equals and BeginsWith . (Exception: For filters using Label as the Key - // name, the only valid option is Equals .) - Option *string - - // The value you want to search for. - Values []string - - noSmithyDocumentSerde -} - -// A detailed status of the parent step. -type ParentStepDetails struct { - - // The name of the automation action. - Action *string - - // The current repetition of the loop represented by an integer. - Iteration *int32 - - // The current value of the specified iterator in the loop. - IteratorValue *string - - // The unique ID of a step execution. - StepExecutionId *string - - // The name of the step. - StepName *string - - noSmithyDocumentSerde -} - -// Represents metadata about a patch. -type Patch struct { - - // The Advisory ID of the patch. For example, RHSA-2020:3779 . Applies to - // Linux-based managed nodes only. - AdvisoryIds []string - - // The architecture of the patch. For example, in - // example-pkg-0.710.10-2.7.abcd.x86_64 , the architecture is indicated by x86_64 . - // Applies to Linux-based managed nodes only. - Arch *string - - // The Bugzilla ID of the patch. For example, 1600646 . Applies to Linux-based - // managed nodes only. - BugzillaIds []string - - // The Common Vulnerabilities and Exposures (CVE) ID of the patch. For example, - // CVE-2011-3192 . Applies to Linux-based managed nodes only. - CVEIds []string - - // The classification of the patch. For example, SecurityUpdates , Updates , or - // CriticalUpdates . - Classification *string - - // The URL where more information can be obtained about the patch. - ContentUrl *string - - // The description of the patch. - Description *string - - // The epoch of the patch. For example in pkg-example-EE-20180914-2.2.amzn1.noarch - // , the epoch value is 20180914-2 . Applies to Linux-based managed nodes only. - Epoch int32 - - // The ID of the patch. Applies to Windows patches only. This ID isn't the same as - // the Microsoft Knowledge Base ID. - Id *string - - // The Microsoft Knowledge Base ID of the patch. Applies to Windows patches only. - KbNumber *string - - // The language of the patch if it's language-specific. - Language *string - - // The ID of the Microsoft Security Response Center (MSRC) bulletin the patch is - // related to. For example, MS14-045 . Applies to Windows patches only. - MsrcNumber *string - - // The severity of the patch, such as Critical , Important , or Moderate . Applies - // to Windows patches only. - MsrcSeverity *string - - // The name of the patch. Applies to Linux-based managed nodes only. - Name *string - - // The specific product the patch is applicable for. For example, WindowsServer2016 - // or AmazonLinux2018.03 . - Product *string - - // The product family the patch is applicable for. For example, Windows or Amazon - // Linux 2 . - ProductFamily *string - - // The particular release of a patch. For example, in - // pkg-example-EE-20180914-2.2.amzn1.noarch , the release is 2.amaz1 . Applies to - // Linux-based managed nodes only. - Release *string - - // The date the patch was released. - ReleaseDate *time.Time - - // The source patch repository for the operating system and version, such as - // trusty-security for Ubuntu Server 14.04 LTE and focal-security for Ubuntu - // Server 20.04 LTE. Applies to Linux-based managed nodes only. - Repository *string - - // The severity level of the patch. For example, CRITICAL or MODERATE . - Severity *string - - // The title of the patch. - Title *string - - // The name of the vendor providing the patch. - Vendor *string - - // The version number of the patch. For example, in - // example-pkg-1.710.10-2.7.abcd.x86_64 , the version number is indicated by -1 . - // Applies to Linux-based managed nodes only. - Version *string - - noSmithyDocumentSerde -} - -// Defines the basic information about a patch baseline. -type PatchBaselineIdentity struct { - - // The description of the patch baseline. - BaselineDescription *string - - // The ID of the patch baseline. - BaselineId *string - - // The name of the patch baseline. - BaselineName *string - - // Whether this is the default baseline. Amazon Web Services Systems Manager - // supports creating multiple default patch baselines. For example, you can create - // a default patch baseline for each operating system. - DefaultBaseline bool - - // Defines the operating system the patch baseline applies to. The default value - // is WINDOWS . - OperatingSystem OperatingSystem - - noSmithyDocumentSerde -} - -// Information about the state of a patch on a particular managed node as it -// relates to the patch baseline used to patch the node. -type PatchComplianceData struct { - - // The classification of the patch, such as SecurityUpdates , Updates , and - // CriticalUpdates . - // - // This member is required. - Classification *string - - // The date/time the patch was installed on the managed node. Not all operating - // systems provide this level of information. - // - // This member is required. - InstalledTime *time.Time - - // The operating system-specific ID of the patch. - // - // This member is required. - KBId *string - - // The severity of the patch such as Critical , Important , and Moderate . - // - // This member is required. - Severity *string - - // The state of the patch on the managed node, such as INSTALLED or FAILED. For - // descriptions of each patch state, see About patch compliance (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-compliance-about.html#sysman-compliance-monitor-patch) - // in the Amazon Web Services Systems Manager User Guide. - // - // This member is required. - State PatchComplianceDataState - - // The title of the patch. - // - // This member is required. - Title *string - - // The IDs of one or more Common Vulnerabilities and Exposure (CVE) issues that - // are resolved by the patch. - CVEIds *string - - noSmithyDocumentSerde -} - -// Defines which patches should be included in a patch baseline. A patch filter -// consists of a key and a set of values. The filter key is a patch property. For -// example, the available filter keys for WINDOWS are PATCH_SET , PRODUCT , -// PRODUCT_FAMILY , CLASSIFICATION , and MSRC_SEVERITY . The filter values define a -// matching criterion for the patch property indicated by the key. For example, if -// the filter key is PRODUCT and the filter values are ["Office 2013", "Office -// 2016"] , then the filter accepts all patches where product name is either -// "Office 2013" or "Office 2016". The filter values can be exact values for the -// patch property given as a key, or a wildcard (*), which matches all values. You -// can view lists of valid values for the patch properties by running the -// DescribePatchProperties command. For information about which patch properties -// can be used with each major operating system, see DescribePatchProperties . -type PatchFilter struct { - - // The key for the filter. Run the DescribePatchProperties command to view lists - // of valid keys for each operating system type. - // - // This member is required. - Key PatchFilterKey - - // The value for the filter key. Run the DescribePatchProperties command to view - // lists of valid values for each key based on operating system type. - // - // This member is required. - Values []string - - noSmithyDocumentSerde -} - -// A set of patch filters, typically used for approval rules. -type PatchFilterGroup struct { - - // The set of patch filters that make up the group. - // - // This member is required. - PatchFilters []PatchFilter - - noSmithyDocumentSerde -} - -// The mapping between a patch group and the patch baseline the patch group is -// registered with. -type PatchGroupPatchBaselineMapping struct { - - // The patch baseline the patch group is registered with. - BaselineIdentity *PatchBaselineIdentity - - // The name of the patch group registered with the patch baseline. - PatchGroup *string - - noSmithyDocumentSerde -} - -// Defines a filter used in Patch Manager APIs. Supported filter keys depend on -// the API operation that includes the filter. Patch Manager API operations that -// use PatchOrchestratorFilter include the following: -// - DescribeAvailablePatches -// - DescribeInstancePatches -// - DescribePatchBaselines -// - DescribePatchGroups -type PatchOrchestratorFilter struct { - - // The key for the filter. - Key *string - - // The value for the filter. - Values []string - - noSmithyDocumentSerde -} - -// Defines an approval rule for a patch baseline. -type PatchRule struct { - - // The patch filter group that defines the criteria for the rule. - // - // This member is required. - PatchFilterGroup *PatchFilterGroup - - // The number of days after the release date of each patch matched by the rule - // that the patch is marked as approved in the patch baseline. For example, a value - // of 7 means that patches are approved seven days after they are released. Not - // supported on Debian Server or Ubuntu Server. - ApproveAfterDays *int32 - - // The cutoff date for auto approval of released patches. Any patches released on - // or before this date are installed automatically. Not supported on Debian Server - // or Ubuntu Server. Enter dates in the format YYYY-MM-DD . For example, 2021-12-31 - // . - ApproveUntilDate *string - - // A compliance severity level for all approved patches in a patch baseline. - ComplianceLevel PatchComplianceLevel - - // For managed nodes identified by the approval rule filters, enables a patch - // baseline to apply non-security updates available in the specified repository. - // The default value is false . Applies to Linux managed nodes only. - EnableNonSecurity *bool - - noSmithyDocumentSerde -} - -// A set of rules defining the approval rules for a patch baseline. -type PatchRuleGroup struct { - - // The rules that make up the rule group. - // - // This member is required. - PatchRules []PatchRule - - noSmithyDocumentSerde -} - -// Information about the patches to use to update the managed nodes, including -// target operating systems and source repository. Applies to Linux managed nodes -// only. -type PatchSource struct { - - // The value of the yum repo configuration. For example: [main] - // name=MyCustomRepository - // - // baseurl=https://my-custom-repository - // enabled=1 For information about other options available for your yum repository - // configuration, see dnf.conf(5) (https://man7.org/linux/man-pages/man5/dnf.conf.5.html) - // . - // - // This member is required. - Configuration *string - - // The name specified to identify the patch source. - // - // This member is required. - Name *string - - // The specific operating system versions a patch repository applies to, such as - // "Ubuntu16.04", "AmazonLinux2016.09", "RedhatEnterpriseLinux7.2" or "Suse12.7". - // For lists of supported product values, see PatchFilter . - // - // This member is required. - Products []string - - noSmithyDocumentSerde -} - -// Information about the approval status of a patch. -type PatchStatus struct { - - // The date the patch was approved (or will be approved if the status is - // PENDING_APPROVAL ). - ApprovalDate *time.Time - - // The compliance severity level for a patch. - ComplianceLevel PatchComplianceLevel - - // The approval status of a patch. - DeploymentStatus PatchDeploymentStatus - - noSmithyDocumentSerde -} - -// An aggregate of step execution statuses displayed in the Amazon Web Services -// Systems Manager console for a multi-Region and multi-account Automation -// execution. -type ProgressCounters struct { - - // The total number of steps that the system cancelled in all specified Amazon Web - // Services Regions and Amazon Web Services accounts for the current Automation - // execution. - CancelledSteps int32 - - // The total number of steps that failed to run in all specified Amazon Web - // Services Regions and Amazon Web Services accounts for the current Automation - // execution. - FailedSteps int32 - - // The total number of steps that successfully completed in all specified Amazon - // Web Services Regions and Amazon Web Services accounts for the current Automation - // execution. - SuccessSteps int32 - - // The total number of steps that timed out in all specified Amazon Web Services - // Regions and Amazon Web Services accounts for the current Automation execution. - TimedOutSteps int32 - - // The total number of steps run in all specified Amazon Web Services Regions and - // Amazon Web Services accounts for the current Automation execution. - TotalSteps int32 - - noSmithyDocumentSerde -} - -// Reserved for internal use. -type RegistrationMetadataItem struct { - - // Reserved for internal use. - // - // This member is required. - Key *string - - // Reserved for internal use. - // - // This member is required. - Value *string - - noSmithyDocumentSerde -} - -// An OpsItems that shares something in common with the current OpsItem. For -// example, related OpsItems can include OpsItems with similar error messages, -// impacted resources, or statuses for the impacted resource. -type RelatedOpsItem struct { - - // The ID of an OpsItem related to the current OpsItem. - // - // This member is required. - OpsItemId *string - - noSmithyDocumentSerde -} - -// Information about targets that resolved during the Automation execution. -type ResolvedTargets struct { - - // A list of parameter values sent to targets that resolved during the Automation - // execution. - ParameterValues []string - - // A boolean value indicating whether the resolved target list is truncated. - Truncated bool - - noSmithyDocumentSerde -} - -// Compliance summary information for a specific resource. -type ResourceComplianceSummaryItem struct { - - // The compliance type. - ComplianceType *string - - // A list of items that are compliant for the resource. - CompliantSummary *CompliantSummary - - // Information about the execution. - ExecutionSummary *ComplianceExecutionSummary - - // A list of items that aren't compliant for the resource. - NonCompliantSummary *NonCompliantSummary - - // The highest severity item found for the resource. The resource is compliant for - // this item. - OverallSeverity ComplianceSeverity - - // The resource ID. - ResourceId *string - - // The resource type. - ResourceType *string - - // The compliance status for the resource. - Status ComplianceStatus - - noSmithyDocumentSerde -} - -// Information about the AwsOrganizationsSource resource data sync source. A sync -// source of this type can synchronize data from Organizations or, if an Amazon Web -// Services organization isn't present, from multiple Amazon Web Services Regions. -type ResourceDataSyncAwsOrganizationsSource struct { - - // If an Amazon Web Services organization is present, this is either - // OrganizationalUnits or EntireOrganization . For OrganizationalUnits , the data - // is aggregated from a set of organization units. For EntireOrganization , the - // data is aggregated from the entire Amazon Web Services organization. - // - // This member is required. - OrganizationSourceType *string - - // The Organizations organization units included in the sync. - OrganizationalUnits []ResourceDataSyncOrganizationalUnit - - noSmithyDocumentSerde -} - -// Synchronize Amazon Web Services Systems Manager Inventory data from multiple -// Amazon Web Services accounts defined in Organizations to a centralized Amazon S3 -// bucket. Data is synchronized to individual key prefixes in the central bucket. -// Each key prefix represents a different Amazon Web Services account ID. -type ResourceDataSyncDestinationDataSharing struct { - - // The sharing data type. Only Organization is supported. - DestinationDataSharingType *string - - noSmithyDocumentSerde -} - -// Information about a resource data sync configuration, including its current -// status and last successful sync. -type ResourceDataSyncItem struct { - - // The status reported by the last sync. - LastStatus LastResourceDataSyncStatus - - // The last time the sync operations returned a status of SUCCESSFUL (UTC). - LastSuccessfulSyncTime *time.Time - - // The status message details reported by the last sync. - LastSyncStatusMessage *string - - // The last time the configuration attempted to sync (UTC). - LastSyncTime *time.Time - - // Configuration information for the target S3 bucket. - S3Destination *ResourceDataSyncS3Destination - - // The date and time the configuration was created (UTC). - SyncCreatedTime *time.Time - - // The date and time the resource data sync was changed. - SyncLastModifiedTime *time.Time - - // The name of the resource data sync. - SyncName *string - - // Information about the source where the data was synchronized. - SyncSource *ResourceDataSyncSourceWithState - - // The type of resource data sync. If SyncType is SyncToDestination , then the - // resource data sync synchronizes data to an S3 bucket. If the SyncType is - // SyncFromSource then the resource data sync synchronizes data from Organizations - // or from multiple Amazon Web Services Regions. - SyncType *string - - noSmithyDocumentSerde -} - -// The Organizations organizational unit data source for the sync. -type ResourceDataSyncOrganizationalUnit struct { - - // The Organizations unit ID data source for the sync. - OrganizationalUnitId *string - - noSmithyDocumentSerde -} - -// Information about the target S3 bucket for the resource data sync. -type ResourceDataSyncS3Destination struct { - - // The name of the S3 bucket where the aggregated data is stored. - // - // This member is required. - BucketName *string - - // The Amazon Web Services Region with the S3 bucket targeted by the resource data - // sync. - // - // This member is required. - Region *string - - // A supported sync format. The following format is currently supported: JsonSerDe - // - // This member is required. - SyncFormat ResourceDataSyncS3Format - - // The ARN of an encryption key for a destination in Amazon S3. Must belong to the - // same Region as the destination S3 bucket. - AWSKMSKeyARN *string - - // Enables destination data sharing. By default, this field is null . - DestinationDataSharing *ResourceDataSyncDestinationDataSharing - - // An Amazon S3 prefix for the bucket. - Prefix *string - - noSmithyDocumentSerde -} - -// Information about the source of the data included in the resource data sync. -type ResourceDataSyncSource struct { - - // The SyncSource Amazon Web Services Regions included in the resource data sync. - // - // This member is required. - SourceRegions []string - - // The type of data source for the resource data sync. SourceType is either - // AwsOrganizations (if an organization is present in Organizations) or - // SingleAccountMultiRegions . - // - // This member is required. - SourceType *string - - // Information about the AwsOrganizationsSource resource data sync source. A sync - // source of this type can synchronize data from Organizations. - AwsOrganizationsSource *ResourceDataSyncAwsOrganizationsSource - - // When you create a resource data sync, if you choose one of the Organizations - // options, then Systems Manager automatically enables all OpsData sources in the - // selected Amazon Web Services Regions for all Amazon Web Services accounts in - // your organization (or in the selected organization units). For more information, - // see About multiple account and Region resource data syncs (https://docs.aws.amazon.com/systems-manager/latest/userguide/Explorer-resouce-data-sync-multiple-accounts-and-regions.html) - // in the Amazon Web Services Systems Manager User Guide. - EnableAllOpsDataSources bool - - // Whether to automatically synchronize and aggregate data from new Amazon Web - // Services Regions when those Regions come online. - IncludeFutureRegions bool - - noSmithyDocumentSerde -} - -// The data type name for including resource data sync state. There are four sync -// states: OrganizationNotExists (Your organization doesn't exist) NoPermissions -// (The system can't locate the service-linked role. This role is automatically -// created when a user creates a resource data sync in Amazon Web Services Systems -// Manager Explorer.) InvalidOrganizationalUnit (You specified or selected an -// invalid unit in the resource data sync configuration.) TrustedAccessDisabled -// (You disabled Systems Manager access in the organization in Organizations.) -type ResourceDataSyncSourceWithState struct { - - // The field name in SyncSource for the ResourceDataSyncAwsOrganizationsSource - // type. - AwsOrganizationsSource *ResourceDataSyncAwsOrganizationsSource - - // When you create a resource data sync, if you choose one of the Organizations - // options, then Systems Manager automatically enables all OpsData sources in the - // selected Amazon Web Services Regions for all Amazon Web Services accounts in - // your organization (or in the selected organization units). For more information, - // see About multiple account and Region resource data syncs (https://docs.aws.amazon.com/systems-manager/latest/userguide/Explorer-resouce-data-sync-multiple-accounts-and-regions.html) - // in the Amazon Web Services Systems Manager User Guide. - EnableAllOpsDataSources bool - - // Whether to automatically synchronize and aggregate data from new Amazon Web - // Services Regions when those Regions come online. - IncludeFutureRegions bool - - // The SyncSource Amazon Web Services Regions included in the resource data sync. - SourceRegions []string - - // The type of data source for the resource data sync. SourceType is either - // AwsOrganizations (if an organization is present in Organizations) or - // singleAccountMultiRegions . - SourceType *string - - // The data type name for including resource data sync state. There are four sync - // states: OrganizationNotExists : Your organization doesn't exist. NoPermissions : - // The system can't locate the service-linked role. This role is automatically - // created when a user creates a resource data sync in Explorer. - // InvalidOrganizationalUnit : You specified or selected an invalid unit in the - // resource data sync configuration. TrustedAccessDisabled : You disabled Systems - // Manager access in the organization in Organizations. - State *string - - noSmithyDocumentSerde -} - -// The inventory item result attribute. -type ResultAttribute struct { - - // Name of the inventory item type. Valid value: AWS:InstanceInformation . Default - // Value: AWS:InstanceInformation . - // - // This member is required. - TypeName *string - - noSmithyDocumentSerde -} - -// Information about the result of a document review request. -type ReviewInformation struct { - - // The time that the reviewer took action on the document review request. - ReviewedTime *time.Time - - // The reviewer assigned to take action on the document review request. - Reviewer *string - - // The current status of the document review request. - Status ReviewStatus - - noSmithyDocumentSerde -} - -// Information about an Automation runbook used in a runbook workflow in Change -// Manager. The Automation runbooks specified for the runbook workflow can't run -// until all required approvals for the change request have been received. -type Runbook struct { - - // The name of the Automation runbook used in a runbook workflow. - // - // This member is required. - DocumentName *string - - // The version of the Automation runbook used in a runbook workflow. - DocumentVersion *string - - // The MaxConcurrency value specified by the user when the operation started, - // indicating the maximum number of resources that the runbook operation can run on - // at the same time. - MaxConcurrency *string - - // The MaxErrors value specified by the user when the execution started, - // indicating the maximum number of errors that can occur during the operation - // before the updates are stopped or rolled back. - MaxErrors *string - - // The key-value map of execution parameters, which were supplied when calling - // StartChangeRequestExecution . - Parameters map[string][]string - - // Information about the Amazon Web Services Regions and Amazon Web Services - // accounts targeted by the current Runbook operation. - TargetLocations []TargetLocation - - // A key-value mapping of runbook parameters to target resources. Both Targets and - // TargetMaps can't be specified together. - TargetMaps []map[string][]string - - // The name of the parameter used as the target resource for the rate-controlled - // runbook workflow. Required if you specify Targets . - TargetParameterName *string - - // A key-value mapping to target resources that the runbook operation performs - // tasks on. Required if you specify TargetParameterName . - Targets []Target - - noSmithyDocumentSerde -} - -// An S3 bucket where you want to store the results of this request. -type S3OutputLocation struct { - - // The name of the S3 bucket. - OutputS3BucketName *string - - // The S3 bucket subfolder. - OutputS3KeyPrefix *string - - // The Amazon Web Services Region of the S3 bucket. - OutputS3Region *string - - noSmithyDocumentSerde -} - -// A URL for the Amazon Web Services Systems Manager (Systems Manager) bucket -// where you want to store the results of this request. -type S3OutputUrl struct { - - // A URL for an S3 bucket where you want to store the results of this request. - OutputUrl *string - - noSmithyDocumentSerde -} - -// Information about a scheduled execution for a maintenance window. -type ScheduledWindowExecution struct { - - // The time, in ISO-8601 Extended format, that the maintenance window is scheduled - // to be run. - ExecutionTime *string - - // The name of the maintenance window to be run. - Name *string - - // The ID of the maintenance window to be run. - WindowId *string - - noSmithyDocumentSerde -} - -// The service setting data structure. ServiceSetting is an account-level setting -// for an Amazon Web Services service. This setting defines how a user interacts -// with or uses a service or a feature of a service. For example, if an Amazon Web -// Services service charges money to the account based on feature or service usage, -// then the Amazon Web Services service team might create a default setting of -// "false". This means the user can't use this feature unless they change the -// setting to "true" and intentionally opt in for a paid feature. Services map a -// SettingId object to a setting value. Amazon Web Services services teams define -// the default value for a SettingId . You can't create a new SettingId , but you -// can overwrite the default value if you have the ssm:UpdateServiceSetting -// permission for the setting. Use the UpdateServiceSetting API operation to -// change the default setting. Or, use the ResetServiceSetting to change the value -// back to the original value defined by the Amazon Web Services service team. -type ServiceSetting struct { - - // The ARN of the service setting. - ARN *string - - // The last time the service setting was modified. - LastModifiedDate *time.Time - - // The ARN of the last modified user. This field is populated only if the setting - // value was overwritten. - LastModifiedUser *string - - // The ID of the service setting. - SettingId *string - - // The value of the service setting. - SettingValue *string - - // The status of the service setting. The value can be Default, Customized or - // PendingUpdate. - // - Default: The current setting uses a default value provisioned by the Amazon - // Web Services service team. - // - Customized: The current setting use a custom value specified by the - // customer. - // - PendingUpdate: The current setting uses a default or custom value, but a - // setting change request is pending approval. - Status *string - - noSmithyDocumentSerde -} - -// Information about a Session Manager connection to a managed node. -type Session struct { - - // Reserved for future use. - Details *string - - // The name of the Session Manager SSM document used to define the parameters and - // plugin settings for the session. For example, SSM-SessionManagerRunShell . - DocumentName *string - - // The date and time, in ISO-8601 Extended format, when the session was terminated. - EndDate *time.Time - - // The maximum duration of a session before it terminates. - MaxSessionDuration *string - - // Reserved for future use. - OutputUrl *SessionManagerOutputUrl - - // The ID of the Amazon Web Services user that started the session. - Owner *string - - // The reason for connecting to the instance. - Reason *string - - // The ID of the session. - SessionId *string - - // The date and time, in ISO-8601 Extended format, when the session began. - StartDate *time.Time - - // The status of the session. For example, "Connected" or "Terminated". - Status SessionStatus - - // The managed node that the Session Manager session connected to. - Target *string - - noSmithyDocumentSerde -} - -// Describes a filter for Session Manager information. -type SessionFilter struct { - - // The name of the filter. - // - // This member is required. - Key SessionFilterKey - - // The filter value. Valid values for each filter key are as follows: - // - InvokedAfter: Specify a timestamp to limit your results. For example, - // specify 2018-08-29T00:00:00Z to see sessions that started August 29, 2018, and - // later. - // - InvokedBefore: Specify a timestamp to limit your results. For example, - // specify 2018-08-29T00:00:00Z to see sessions that started before August 29, - // 2018. - // - Target: Specify a managed node to which session connections have been made. - // - Owner: Specify an Amazon Web Services user to see a list of sessions - // started by that user. - // - Status: Specify a valid session status to see a list of all sessions with - // that status. Status values you can specify include: - // - Connected - // - Connecting - // - Disconnected - // - Terminated - // - Terminating - // - Failed - // - SessionId: Specify a session ID to return details about the session. - // - // This member is required. - Value *string - - noSmithyDocumentSerde -} - -// Reserved for future use. -type SessionManagerOutputUrl struct { - - // Reserved for future use. - CloudWatchOutputUrl *string - - // Reserved for future use. - S3OutputUrl *string - - noSmithyDocumentSerde -} - -// The number of managed nodes found for each patch severity level defined in the -// request filter. -type SeveritySummary struct { - - // The total number of resources or compliance items that have a severity level of - // Critical . Critical severity is determined by the organization that published - // the compliance items. - CriticalCount int32 - - // The total number of resources or compliance items that have a severity level of - // high. High severity is determined by the organization that published the - // compliance items. - HighCount int32 - - // The total number of resources or compliance items that have a severity level of - // informational. Informational severity is determined by the organization that - // published the compliance items. - InformationalCount int32 - - // The total number of resources or compliance items that have a severity level of - // low. Low severity is determined by the organization that published the - // compliance items. - LowCount int32 - - // The total number of resources or compliance items that have a severity level of - // medium. Medium severity is determined by the organization that published the - // compliance items. - MediumCount int32 - - // The total number of resources or compliance items that have a severity level of - // unspecified. Unspecified severity is determined by the organization that - // published the compliance items. - UnspecifiedCount int32 - - noSmithyDocumentSerde -} - -// Detailed information about an the execution state of an Automation step. -type StepExecution struct { - - // The action this step performs. The action determines the behavior of the step. - Action *string - - // If a step has finished execution, this contains the time the execution ended. - // If the step hasn't yet concluded, this field isn't populated. - ExecutionEndTime *time.Time - - // If a step has begun execution, this contains the time the step started. If the - // step is in Pending status, this field isn't populated. - ExecutionStartTime *time.Time - - // Information about the Automation failure. - FailureDetails *FailureDetails - - // If a step failed, this message explains why the execution failed. - FailureMessage *string - - // Fully-resolved values passed into the step before execution. - Inputs map[string]string - - // The flag which can be used to help decide whether the failure of current step - // leads to the Automation failure. - IsCritical *bool - - // The flag which can be used to end automation no matter whether the step - // succeeds or fails. - IsEnd *bool - - // The maximum number of tries to run the action of the step. The default value is - // 1 . - MaxAttempts *int32 - - // The next step after the step succeeds. - NextStep *string - - // The action to take if the step fails. The default value is Abort . - OnFailure *string - - // Returned values from the execution of the step. - Outputs map[string][]string - - // A user-specified list of parameters to override when running a step. - OverriddenParameters map[string][]string - - // Information about the parent step. - ParentStepDetails *ParentStepDetails - - // A message associated with the response code for an execution. - Response *string - - // The response code returned by the execution of the step. - ResponseCode *string - - // The unique ID of a step execution. - StepExecutionId *string - - // The name of this execution step. - StepName *string - - // The execution status for this step. - StepStatus AutomationExecutionStatus - - // The combination of Amazon Web Services Regions and Amazon Web Services accounts - // targeted by the current Automation execution. - TargetLocation *TargetLocation - - // The targets for the step execution. - Targets []Target - - // The timeout seconds of the step. - TimeoutSeconds *int64 - - // The CloudWatch alarms that were invoked by the automation. - TriggeredAlarms []AlarmStateInformation - - // Strategies used when step fails, we support Continue and Abort. Abort will fail - // the automation when the step fails. Continue will ignore the failure of current - // step and allow automation to run the next step. With conditional branching, we - // add step:stepName to support the automation to go to another specific step. - ValidNextSteps []string - - noSmithyDocumentSerde -} - -// A filter to limit the amount of step execution information returned by the call. -type StepExecutionFilter struct { - - // One or more keys to limit the results. - // - // This member is required. - Key StepExecutionFilterKey - - // The values of the filter key. - // - // This member is required. - Values []string - - noSmithyDocumentSerde -} - -// Metadata that you assign to your Amazon Web Services resources. Tags enable you -// to categorize your resources in different ways, for example, by purpose, owner, -// or environment. In Amazon Web Services Systems Manager, you can apply tags to -// Systems Manager documents (SSM documents), managed nodes, maintenance windows, -// parameters, patch baselines, OpsItems, and OpsMetadata. -type Tag struct { - - // The name of the tag. - // - // This member is required. - Key *string - - // The value of the tag. - // - // This member is required. - Value *string - - noSmithyDocumentSerde -} - -// An array of search criteria that targets managed nodes using a key-value pair -// that you specify. One or more targets must be specified for maintenance window -// Run Command-type tasks. Depending on the task, targets are optional for other -// maintenance window task types (Automation, Lambda, and Step Functions). For more -// information about running tasks that don't specify targets, see Registering -// maintenance window tasks without targets (https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-targetless-tasks.html) -// in the Amazon Web Services Systems Manager User Guide. Supported formats include -// the following. -// - Key=InstanceIds,Values=,, -// - Key=tag:,Values=, -// - Key=tag-key,Values=, -// - Run Command and Maintenance window targets only: -// Key=resource-groups:Name,Values= -// - Maintenance window targets only: -// Key=resource-groups:ResourceTypeFilters,Values=, -// - Automation targets only: Key=ResourceGroup;Values= -// -// For example: -// -// - -// Key=InstanceIds,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE,i-07782c72faEXAMPLE -// - Key=tag:CostCenter,Values=CostCenter1,CostCenter2,CostCenter3 -// - Key=tag-key,Values=Name,Instance-Type,CostCenter -// - Run Command and Maintenance window targets only: -// Key=resource-groups:Name,Values=ProductionResourceGroup This example -// demonstrates how to target all resources in the resource group -// ProductionResourceGroup in your maintenance window. -// - Maintenance window targets only: -// Key=resource-groups:ResourceTypeFilters,Values=AWS::EC2::INSTANCE,AWS::EC2::VPC -// This example demonstrates how to target only Amazon Elastic Compute Cloud -// (Amazon EC2) instances and VPCs in your maintenance window. -// - Automation targets only: Key=ResourceGroup,Values=MyResourceGroup -// - State Manager association targets only: Key=InstanceIds,Values=* This -// example demonstrates how to target all managed instances in the Amazon Web -// Services Region where the association was created. -// -// For more information about how to send commands that target managed nodes using -// Key,Value parameters, see Targeting multiple instances (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html#send-commands-targeting) -// in the Amazon Web Services Systems Manager User Guide. -type Target struct { - - // User-defined criteria for sending commands that target managed nodes that meet - // the criteria. - Key *string - - // User-defined criteria that maps to Key . For example, if you specified - // tag:ServerRole , you could specify value:WebServer to run a command on - // instances that include EC2 tags of ServerRole,WebServer . Depending on the type - // of target, the maximum number of values for a key might be lower than the global - // maximum of 50. - Values []string - - noSmithyDocumentSerde -} - -// The combination of Amazon Web Services Regions and Amazon Web Services accounts -// targeted by the current Automation execution. -type TargetLocation struct { - - // The Amazon Web Services accounts targeted by the current Automation execution. - Accounts []string - - // The Automation execution role used by the currently running Automation. If not - // specified, the default value is AWS-SystemsManager-AutomationExecutionRole . - ExecutionRoleName *string - - // The Amazon Web Services Regions targeted by the current Automation execution. - Regions []string - - // The details for the CloudWatch alarm you want to apply to an automation or - // command. - TargetLocationAlarmConfiguration *AlarmConfiguration - - // The maximum number of Amazon Web Services Regions and Amazon Web Services - // accounts allowed to run the Automation concurrently. - TargetLocationMaxConcurrency *string - - // The maximum number of errors allowed before the system stops queueing - // additional Automation executions for the currently running Automation. - TargetLocationMaxErrors *string - - noSmithyDocumentSerde -} - -type noSmithyDocumentSerde = smithydocument.NoSerde diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/validators.go deleted file mode 100644 index 37cb33aa..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssm/validators.go +++ /dev/null @@ -1,6858 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssm - -import ( - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/service/ssm/types" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -type validateOpAddTagsToResource struct { -} - -func (*validateOpAddTagsToResource) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpAddTagsToResource) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*AddTagsToResourceInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpAddTagsToResourceInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpAssociateOpsItemRelatedItem struct { -} - -func (*validateOpAssociateOpsItemRelatedItem) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpAssociateOpsItemRelatedItem) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*AssociateOpsItemRelatedItemInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpAssociateOpsItemRelatedItemInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCancelCommand struct { -} - -func (*validateOpCancelCommand) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCancelCommand) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CancelCommandInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCancelCommandInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCancelMaintenanceWindowExecution struct { -} - -func (*validateOpCancelMaintenanceWindowExecution) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCancelMaintenanceWindowExecution) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CancelMaintenanceWindowExecutionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCancelMaintenanceWindowExecutionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCreateActivation struct { -} - -func (*validateOpCreateActivation) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateActivation) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateActivationInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateActivationInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCreateAssociationBatch struct { -} - -func (*validateOpCreateAssociationBatch) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateAssociationBatch) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateAssociationBatchInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateAssociationBatchInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCreateAssociation struct { -} - -func (*validateOpCreateAssociation) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateAssociation) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateAssociationInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateAssociationInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCreateDocument struct { -} - -func (*validateOpCreateDocument) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateDocument) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateDocumentInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateDocumentInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCreateMaintenanceWindow struct { -} - -func (*validateOpCreateMaintenanceWindow) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateMaintenanceWindow) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateMaintenanceWindowInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateMaintenanceWindowInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCreateOpsItem struct { -} - -func (*validateOpCreateOpsItem) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateOpsItem) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateOpsItemInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateOpsItemInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCreateOpsMetadata struct { -} - -func (*validateOpCreateOpsMetadata) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateOpsMetadata) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateOpsMetadataInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateOpsMetadataInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCreatePatchBaseline struct { -} - -func (*validateOpCreatePatchBaseline) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreatePatchBaseline) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreatePatchBaselineInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreatePatchBaselineInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCreateResourceDataSync struct { -} - -func (*validateOpCreateResourceDataSync) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateResourceDataSync) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateResourceDataSyncInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateResourceDataSyncInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteActivation struct { -} - -func (*validateOpDeleteActivation) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteActivation) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteActivationInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteActivationInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteDocument struct { -} - -func (*validateOpDeleteDocument) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteDocument) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteDocumentInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteDocumentInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteInventory struct { -} - -func (*validateOpDeleteInventory) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteInventory) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteInventoryInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteInventoryInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteMaintenanceWindow struct { -} - -func (*validateOpDeleteMaintenanceWindow) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteMaintenanceWindow) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteMaintenanceWindowInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteMaintenanceWindowInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteOpsItem struct { -} - -func (*validateOpDeleteOpsItem) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteOpsItem) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteOpsItemInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteOpsItemInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteOpsMetadata struct { -} - -func (*validateOpDeleteOpsMetadata) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteOpsMetadata) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteOpsMetadataInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteOpsMetadataInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteParameter struct { -} - -func (*validateOpDeleteParameter) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteParameter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteParameterInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteParameterInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteParameters struct { -} - -func (*validateOpDeleteParameters) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteParameters) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteParametersInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteParametersInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeletePatchBaseline struct { -} - -func (*validateOpDeletePatchBaseline) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeletePatchBaseline) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeletePatchBaselineInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeletePatchBaselineInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteResourceDataSync struct { -} - -func (*validateOpDeleteResourceDataSync) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteResourceDataSync) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteResourceDataSyncInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteResourceDataSyncInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeleteResourcePolicy struct { -} - -func (*validateOpDeleteResourcePolicy) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeleteResourcePolicy) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeleteResourcePolicyInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeleteResourcePolicyInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeregisterManagedInstance struct { -} - -func (*validateOpDeregisterManagedInstance) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeregisterManagedInstance) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeregisterManagedInstanceInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeregisterManagedInstanceInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeregisterPatchBaselineForPatchGroup struct { -} - -func (*validateOpDeregisterPatchBaselineForPatchGroup) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeregisterPatchBaselineForPatchGroup) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeregisterPatchBaselineForPatchGroupInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeregisterPatchBaselineForPatchGroupInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeregisterTargetFromMaintenanceWindow struct { -} - -func (*validateOpDeregisterTargetFromMaintenanceWindow) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeregisterTargetFromMaintenanceWindow) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeregisterTargetFromMaintenanceWindowInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeregisterTargetFromMaintenanceWindowInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDeregisterTaskFromMaintenanceWindow struct { -} - -func (*validateOpDeregisterTaskFromMaintenanceWindow) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDeregisterTaskFromMaintenanceWindow) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DeregisterTaskFromMaintenanceWindowInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDeregisterTaskFromMaintenanceWindowInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeAssociationExecutions struct { -} - -func (*validateOpDescribeAssociationExecutions) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeAssociationExecutions) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeAssociationExecutionsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeAssociationExecutionsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeAssociationExecutionTargets struct { -} - -func (*validateOpDescribeAssociationExecutionTargets) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeAssociationExecutionTargets) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeAssociationExecutionTargetsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeAssociationExecutionTargetsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeAutomationExecutions struct { -} - -func (*validateOpDescribeAutomationExecutions) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeAutomationExecutions) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeAutomationExecutionsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeAutomationExecutionsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeAutomationStepExecutions struct { -} - -func (*validateOpDescribeAutomationStepExecutions) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeAutomationStepExecutions) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeAutomationStepExecutionsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeAutomationStepExecutionsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeDocument struct { -} - -func (*validateOpDescribeDocument) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeDocument) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeDocumentInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeDocumentInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeDocumentPermission struct { -} - -func (*validateOpDescribeDocumentPermission) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeDocumentPermission) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeDocumentPermissionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeDocumentPermissionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeEffectiveInstanceAssociations struct { -} - -func (*validateOpDescribeEffectiveInstanceAssociations) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeEffectiveInstanceAssociations) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeEffectiveInstanceAssociationsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeEffectiveInstanceAssociationsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeEffectivePatchesForPatchBaseline struct { -} - -func (*validateOpDescribeEffectivePatchesForPatchBaseline) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeEffectivePatchesForPatchBaseline) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeEffectivePatchesForPatchBaselineInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeEffectivePatchesForPatchBaselineInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeInstanceAssociationsStatus struct { -} - -func (*validateOpDescribeInstanceAssociationsStatus) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeInstanceAssociationsStatus) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeInstanceAssociationsStatusInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeInstanceAssociationsStatusInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeInstanceInformation struct { -} - -func (*validateOpDescribeInstanceInformation) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeInstanceInformation) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeInstanceInformationInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeInstanceInformationInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeInstancePatches struct { -} - -func (*validateOpDescribeInstancePatches) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeInstancePatches) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeInstancePatchesInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeInstancePatchesInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeInstancePatchStatesForPatchGroup struct { -} - -func (*validateOpDescribeInstancePatchStatesForPatchGroup) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeInstancePatchStatesForPatchGroup) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeInstancePatchStatesForPatchGroupInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeInstancePatchStatesForPatchGroupInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeInstancePatchStates struct { -} - -func (*validateOpDescribeInstancePatchStates) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeInstancePatchStates) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeInstancePatchStatesInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeInstancePatchStatesInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeMaintenanceWindowExecutions struct { -} - -func (*validateOpDescribeMaintenanceWindowExecutions) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeMaintenanceWindowExecutions) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeMaintenanceWindowExecutionsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeMaintenanceWindowExecutionsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeMaintenanceWindowExecutionTaskInvocations struct { -} - -func (*validateOpDescribeMaintenanceWindowExecutionTaskInvocations) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeMaintenanceWindowExecutionTaskInvocations) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeMaintenanceWindowExecutionTaskInvocationsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeMaintenanceWindowExecutionTaskInvocationsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeMaintenanceWindowExecutionTasks struct { -} - -func (*validateOpDescribeMaintenanceWindowExecutionTasks) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeMaintenanceWindowExecutionTasks) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeMaintenanceWindowExecutionTasksInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeMaintenanceWindowExecutionTasksInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeMaintenanceWindowsForTarget struct { -} - -func (*validateOpDescribeMaintenanceWindowsForTarget) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeMaintenanceWindowsForTarget) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeMaintenanceWindowsForTargetInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeMaintenanceWindowsForTargetInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeMaintenanceWindowTargets struct { -} - -func (*validateOpDescribeMaintenanceWindowTargets) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeMaintenanceWindowTargets) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeMaintenanceWindowTargetsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeMaintenanceWindowTargetsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeMaintenanceWindowTasks struct { -} - -func (*validateOpDescribeMaintenanceWindowTasks) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeMaintenanceWindowTasks) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeMaintenanceWindowTasksInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeMaintenanceWindowTasksInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeOpsItems struct { -} - -func (*validateOpDescribeOpsItems) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeOpsItems) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeOpsItemsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeOpsItemsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeParameters struct { -} - -func (*validateOpDescribeParameters) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeParameters) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeParametersInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeParametersInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribePatchGroupState struct { -} - -func (*validateOpDescribePatchGroupState) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribePatchGroupState) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribePatchGroupStateInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribePatchGroupStateInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribePatchProperties struct { -} - -func (*validateOpDescribePatchProperties) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribePatchProperties) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribePatchPropertiesInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribePatchPropertiesInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDescribeSessions struct { -} - -func (*validateOpDescribeSessions) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDescribeSessions) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DescribeSessionsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDescribeSessionsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDisassociateOpsItemRelatedItem struct { -} - -func (*validateOpDisassociateOpsItemRelatedItem) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDisassociateOpsItemRelatedItem) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DisassociateOpsItemRelatedItemInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDisassociateOpsItemRelatedItemInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetAutomationExecution struct { -} - -func (*validateOpGetAutomationExecution) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetAutomationExecution) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetAutomationExecutionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetAutomationExecutionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetCalendarState struct { -} - -func (*validateOpGetCalendarState) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetCalendarState) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetCalendarStateInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetCalendarStateInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetCommandInvocation struct { -} - -func (*validateOpGetCommandInvocation) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetCommandInvocation) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetCommandInvocationInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetCommandInvocationInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetConnectionStatus struct { -} - -func (*validateOpGetConnectionStatus) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetConnectionStatus) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetConnectionStatusInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetConnectionStatusInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetDeployablePatchSnapshotForInstance struct { -} - -func (*validateOpGetDeployablePatchSnapshotForInstance) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetDeployablePatchSnapshotForInstance) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetDeployablePatchSnapshotForInstanceInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetDeployablePatchSnapshotForInstanceInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetDocument struct { -} - -func (*validateOpGetDocument) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetDocument) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetDocumentInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetDocumentInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetInventory struct { -} - -func (*validateOpGetInventory) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetInventory) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetInventoryInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetInventoryInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetMaintenanceWindowExecution struct { -} - -func (*validateOpGetMaintenanceWindowExecution) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetMaintenanceWindowExecution) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetMaintenanceWindowExecutionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetMaintenanceWindowExecutionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetMaintenanceWindowExecutionTask struct { -} - -func (*validateOpGetMaintenanceWindowExecutionTask) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetMaintenanceWindowExecutionTask) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetMaintenanceWindowExecutionTaskInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetMaintenanceWindowExecutionTaskInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetMaintenanceWindowExecutionTaskInvocation struct { -} - -func (*validateOpGetMaintenanceWindowExecutionTaskInvocation) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetMaintenanceWindowExecutionTaskInvocation) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetMaintenanceWindowExecutionTaskInvocationInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetMaintenanceWindowExecutionTaskInvocationInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetMaintenanceWindow struct { -} - -func (*validateOpGetMaintenanceWindow) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetMaintenanceWindow) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetMaintenanceWindowInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetMaintenanceWindowInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetMaintenanceWindowTask struct { -} - -func (*validateOpGetMaintenanceWindowTask) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetMaintenanceWindowTask) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetMaintenanceWindowTaskInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetMaintenanceWindowTaskInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetOpsItem struct { -} - -func (*validateOpGetOpsItem) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetOpsItem) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetOpsItemInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetOpsItemInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetOpsMetadata struct { -} - -func (*validateOpGetOpsMetadata) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetOpsMetadata) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetOpsMetadataInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetOpsMetadataInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetOpsSummary struct { -} - -func (*validateOpGetOpsSummary) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetOpsSummary) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetOpsSummaryInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetOpsSummaryInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetParameterHistory struct { -} - -func (*validateOpGetParameterHistory) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetParameterHistory) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetParameterHistoryInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetParameterHistoryInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetParameter struct { -} - -func (*validateOpGetParameter) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetParameter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetParameterInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetParameterInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetParametersByPath struct { -} - -func (*validateOpGetParametersByPath) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetParametersByPath) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetParametersByPathInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetParametersByPathInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetParameters struct { -} - -func (*validateOpGetParameters) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetParameters) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetParametersInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetParametersInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetPatchBaselineForPatchGroup struct { -} - -func (*validateOpGetPatchBaselineForPatchGroup) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetPatchBaselineForPatchGroup) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetPatchBaselineForPatchGroupInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetPatchBaselineForPatchGroupInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetPatchBaseline struct { -} - -func (*validateOpGetPatchBaseline) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetPatchBaseline) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetPatchBaselineInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetPatchBaselineInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetResourcePolicies struct { -} - -func (*validateOpGetResourcePolicies) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetResourcePolicies) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetResourcePoliciesInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetResourcePoliciesInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetServiceSetting struct { -} - -func (*validateOpGetServiceSetting) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetServiceSetting) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetServiceSettingInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetServiceSettingInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpLabelParameterVersion struct { -} - -func (*validateOpLabelParameterVersion) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpLabelParameterVersion) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*LabelParameterVersionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpLabelParameterVersionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListAssociations struct { -} - -func (*validateOpListAssociations) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListAssociations) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListAssociationsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListAssociationsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListAssociationVersions struct { -} - -func (*validateOpListAssociationVersions) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListAssociationVersions) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListAssociationVersionsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListAssociationVersionsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListCommandInvocations struct { -} - -func (*validateOpListCommandInvocations) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListCommandInvocations) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListCommandInvocationsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListCommandInvocationsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListCommands struct { -} - -func (*validateOpListCommands) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListCommands) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListCommandsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListCommandsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListDocumentMetadataHistory struct { -} - -func (*validateOpListDocumentMetadataHistory) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListDocumentMetadataHistory) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListDocumentMetadataHistoryInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListDocumentMetadataHistoryInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListDocuments struct { -} - -func (*validateOpListDocuments) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListDocuments) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListDocumentsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListDocumentsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListDocumentVersions struct { -} - -func (*validateOpListDocumentVersions) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListDocumentVersions) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListDocumentVersionsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListDocumentVersionsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListInventoryEntries struct { -} - -func (*validateOpListInventoryEntries) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListInventoryEntries) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListInventoryEntriesInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListInventoryEntriesInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListOpsItemEvents struct { -} - -func (*validateOpListOpsItemEvents) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListOpsItemEvents) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListOpsItemEventsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListOpsItemEventsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListOpsItemRelatedItems struct { -} - -func (*validateOpListOpsItemRelatedItems) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListOpsItemRelatedItems) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListOpsItemRelatedItemsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListOpsItemRelatedItemsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListOpsMetadata struct { -} - -func (*validateOpListOpsMetadata) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListOpsMetadata) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListOpsMetadataInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListOpsMetadataInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListTagsForResource struct { -} - -func (*validateOpListTagsForResource) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListTagsForResource) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListTagsForResourceInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListTagsForResourceInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpModifyDocumentPermission struct { -} - -func (*validateOpModifyDocumentPermission) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpModifyDocumentPermission) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ModifyDocumentPermissionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpModifyDocumentPermissionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpPutComplianceItems struct { -} - -func (*validateOpPutComplianceItems) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpPutComplianceItems) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*PutComplianceItemsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpPutComplianceItemsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpPutInventory struct { -} - -func (*validateOpPutInventory) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpPutInventory) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*PutInventoryInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpPutInventoryInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpPutParameter struct { -} - -func (*validateOpPutParameter) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpPutParameter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*PutParameterInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpPutParameterInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpPutResourcePolicy struct { -} - -func (*validateOpPutResourcePolicy) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpPutResourcePolicy) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*PutResourcePolicyInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpPutResourcePolicyInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpRegisterDefaultPatchBaseline struct { -} - -func (*validateOpRegisterDefaultPatchBaseline) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpRegisterDefaultPatchBaseline) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*RegisterDefaultPatchBaselineInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpRegisterDefaultPatchBaselineInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpRegisterPatchBaselineForPatchGroup struct { -} - -func (*validateOpRegisterPatchBaselineForPatchGroup) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpRegisterPatchBaselineForPatchGroup) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*RegisterPatchBaselineForPatchGroupInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpRegisterPatchBaselineForPatchGroupInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpRegisterTargetWithMaintenanceWindow struct { -} - -func (*validateOpRegisterTargetWithMaintenanceWindow) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpRegisterTargetWithMaintenanceWindow) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*RegisterTargetWithMaintenanceWindowInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpRegisterTargetWithMaintenanceWindowInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpRegisterTaskWithMaintenanceWindow struct { -} - -func (*validateOpRegisterTaskWithMaintenanceWindow) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpRegisterTaskWithMaintenanceWindow) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*RegisterTaskWithMaintenanceWindowInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpRegisterTaskWithMaintenanceWindowInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpRemoveTagsFromResource struct { -} - -func (*validateOpRemoveTagsFromResource) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpRemoveTagsFromResource) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*RemoveTagsFromResourceInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpRemoveTagsFromResourceInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpResetServiceSetting struct { -} - -func (*validateOpResetServiceSetting) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpResetServiceSetting) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ResetServiceSettingInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpResetServiceSettingInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpResumeSession struct { -} - -func (*validateOpResumeSession) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpResumeSession) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ResumeSessionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpResumeSessionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpSendAutomationSignal struct { -} - -func (*validateOpSendAutomationSignal) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpSendAutomationSignal) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*SendAutomationSignalInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpSendAutomationSignalInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpSendCommand struct { -} - -func (*validateOpSendCommand) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpSendCommand) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*SendCommandInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpSendCommandInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpStartAssociationsOnce struct { -} - -func (*validateOpStartAssociationsOnce) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpStartAssociationsOnce) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*StartAssociationsOnceInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpStartAssociationsOnceInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpStartAutomationExecution struct { -} - -func (*validateOpStartAutomationExecution) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpStartAutomationExecution) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*StartAutomationExecutionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpStartAutomationExecutionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpStartChangeRequestExecution struct { -} - -func (*validateOpStartChangeRequestExecution) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpStartChangeRequestExecution) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*StartChangeRequestExecutionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpStartChangeRequestExecutionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpStartSession struct { -} - -func (*validateOpStartSession) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpStartSession) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*StartSessionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpStartSessionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpStopAutomationExecution struct { -} - -func (*validateOpStopAutomationExecution) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpStopAutomationExecution) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*StopAutomationExecutionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpStopAutomationExecutionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpTerminateSession struct { -} - -func (*validateOpTerminateSession) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpTerminateSession) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*TerminateSessionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpTerminateSessionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUnlabelParameterVersion struct { -} - -func (*validateOpUnlabelParameterVersion) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUnlabelParameterVersion) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UnlabelParameterVersionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUnlabelParameterVersionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateAssociation struct { -} - -func (*validateOpUpdateAssociation) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateAssociation) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateAssociationInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateAssociationInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateAssociationStatus struct { -} - -func (*validateOpUpdateAssociationStatus) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateAssociationStatus) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateAssociationStatusInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateAssociationStatusInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateDocumentDefaultVersion struct { -} - -func (*validateOpUpdateDocumentDefaultVersion) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateDocumentDefaultVersion) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateDocumentDefaultVersionInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateDocumentDefaultVersionInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateDocument struct { -} - -func (*validateOpUpdateDocument) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateDocument) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateDocumentInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateDocumentInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateDocumentMetadata struct { -} - -func (*validateOpUpdateDocumentMetadata) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateDocumentMetadata) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateDocumentMetadataInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateDocumentMetadataInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateMaintenanceWindow struct { -} - -func (*validateOpUpdateMaintenanceWindow) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateMaintenanceWindow) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateMaintenanceWindowInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateMaintenanceWindowInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateMaintenanceWindowTarget struct { -} - -func (*validateOpUpdateMaintenanceWindowTarget) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateMaintenanceWindowTarget) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateMaintenanceWindowTargetInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateMaintenanceWindowTargetInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateMaintenanceWindowTask struct { -} - -func (*validateOpUpdateMaintenanceWindowTask) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateMaintenanceWindowTask) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateMaintenanceWindowTaskInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateMaintenanceWindowTaskInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateManagedInstanceRole struct { -} - -func (*validateOpUpdateManagedInstanceRole) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateManagedInstanceRole) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateManagedInstanceRoleInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateManagedInstanceRoleInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateOpsItem struct { -} - -func (*validateOpUpdateOpsItem) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateOpsItem) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateOpsItemInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateOpsItemInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateOpsMetadata struct { -} - -func (*validateOpUpdateOpsMetadata) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateOpsMetadata) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateOpsMetadataInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateOpsMetadataInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdatePatchBaseline struct { -} - -func (*validateOpUpdatePatchBaseline) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdatePatchBaseline) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdatePatchBaselineInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdatePatchBaselineInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateResourceDataSync struct { -} - -func (*validateOpUpdateResourceDataSync) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateResourceDataSync) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateResourceDataSyncInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateResourceDataSyncInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpUpdateServiceSetting struct { -} - -func (*validateOpUpdateServiceSetting) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpUpdateServiceSetting) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*UpdateServiceSettingInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpUpdateServiceSettingInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -func addOpAddTagsToResourceValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpAddTagsToResource{}, middleware.After) -} - -func addOpAssociateOpsItemRelatedItemValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpAssociateOpsItemRelatedItem{}, middleware.After) -} - -func addOpCancelCommandValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCancelCommand{}, middleware.After) -} - -func addOpCancelMaintenanceWindowExecutionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCancelMaintenanceWindowExecution{}, middleware.After) -} - -func addOpCreateActivationValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateActivation{}, middleware.After) -} - -func addOpCreateAssociationBatchValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateAssociationBatch{}, middleware.After) -} - -func addOpCreateAssociationValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateAssociation{}, middleware.After) -} - -func addOpCreateDocumentValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateDocument{}, middleware.After) -} - -func addOpCreateMaintenanceWindowValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateMaintenanceWindow{}, middleware.After) -} - -func addOpCreateOpsItemValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateOpsItem{}, middleware.After) -} - -func addOpCreateOpsMetadataValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateOpsMetadata{}, middleware.After) -} - -func addOpCreatePatchBaselineValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreatePatchBaseline{}, middleware.After) -} - -func addOpCreateResourceDataSyncValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateResourceDataSync{}, middleware.After) -} - -func addOpDeleteActivationValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteActivation{}, middleware.After) -} - -func addOpDeleteDocumentValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteDocument{}, middleware.After) -} - -func addOpDeleteInventoryValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteInventory{}, middleware.After) -} - -func addOpDeleteMaintenanceWindowValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteMaintenanceWindow{}, middleware.After) -} - -func addOpDeleteOpsItemValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteOpsItem{}, middleware.After) -} - -func addOpDeleteOpsMetadataValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteOpsMetadata{}, middleware.After) -} - -func addOpDeleteParameterValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteParameter{}, middleware.After) -} - -func addOpDeleteParametersValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteParameters{}, middleware.After) -} - -func addOpDeletePatchBaselineValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeletePatchBaseline{}, middleware.After) -} - -func addOpDeleteResourceDataSyncValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteResourceDataSync{}, middleware.After) -} - -func addOpDeleteResourcePolicyValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeleteResourcePolicy{}, middleware.After) -} - -func addOpDeregisterManagedInstanceValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeregisterManagedInstance{}, middleware.After) -} - -func addOpDeregisterPatchBaselineForPatchGroupValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeregisterPatchBaselineForPatchGroup{}, middleware.After) -} - -func addOpDeregisterTargetFromMaintenanceWindowValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeregisterTargetFromMaintenanceWindow{}, middleware.After) -} - -func addOpDeregisterTaskFromMaintenanceWindowValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDeregisterTaskFromMaintenanceWindow{}, middleware.After) -} - -func addOpDescribeAssociationExecutionsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeAssociationExecutions{}, middleware.After) -} - -func addOpDescribeAssociationExecutionTargetsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeAssociationExecutionTargets{}, middleware.After) -} - -func addOpDescribeAutomationExecutionsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeAutomationExecutions{}, middleware.After) -} - -func addOpDescribeAutomationStepExecutionsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeAutomationStepExecutions{}, middleware.After) -} - -func addOpDescribeDocumentValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeDocument{}, middleware.After) -} - -func addOpDescribeDocumentPermissionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeDocumentPermission{}, middleware.After) -} - -func addOpDescribeEffectiveInstanceAssociationsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeEffectiveInstanceAssociations{}, middleware.After) -} - -func addOpDescribeEffectivePatchesForPatchBaselineValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeEffectivePatchesForPatchBaseline{}, middleware.After) -} - -func addOpDescribeInstanceAssociationsStatusValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeInstanceAssociationsStatus{}, middleware.After) -} - -func addOpDescribeInstanceInformationValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeInstanceInformation{}, middleware.After) -} - -func addOpDescribeInstancePatchesValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeInstancePatches{}, middleware.After) -} - -func addOpDescribeInstancePatchStatesForPatchGroupValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeInstancePatchStatesForPatchGroup{}, middleware.After) -} - -func addOpDescribeInstancePatchStatesValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeInstancePatchStates{}, middleware.After) -} - -func addOpDescribeMaintenanceWindowExecutionsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeMaintenanceWindowExecutions{}, middleware.After) -} - -func addOpDescribeMaintenanceWindowExecutionTaskInvocationsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeMaintenanceWindowExecutionTaskInvocations{}, middleware.After) -} - -func addOpDescribeMaintenanceWindowExecutionTasksValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeMaintenanceWindowExecutionTasks{}, middleware.After) -} - -func addOpDescribeMaintenanceWindowsForTargetValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeMaintenanceWindowsForTarget{}, middleware.After) -} - -func addOpDescribeMaintenanceWindowTargetsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeMaintenanceWindowTargets{}, middleware.After) -} - -func addOpDescribeMaintenanceWindowTasksValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeMaintenanceWindowTasks{}, middleware.After) -} - -func addOpDescribeOpsItemsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeOpsItems{}, middleware.After) -} - -func addOpDescribeParametersValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeParameters{}, middleware.After) -} - -func addOpDescribePatchGroupStateValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribePatchGroupState{}, middleware.After) -} - -func addOpDescribePatchPropertiesValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribePatchProperties{}, middleware.After) -} - -func addOpDescribeSessionsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDescribeSessions{}, middleware.After) -} - -func addOpDisassociateOpsItemRelatedItemValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDisassociateOpsItemRelatedItem{}, middleware.After) -} - -func addOpGetAutomationExecutionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetAutomationExecution{}, middleware.After) -} - -func addOpGetCalendarStateValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetCalendarState{}, middleware.After) -} - -func addOpGetCommandInvocationValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetCommandInvocation{}, middleware.After) -} - -func addOpGetConnectionStatusValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetConnectionStatus{}, middleware.After) -} - -func addOpGetDeployablePatchSnapshotForInstanceValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetDeployablePatchSnapshotForInstance{}, middleware.After) -} - -func addOpGetDocumentValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetDocument{}, middleware.After) -} - -func addOpGetInventoryValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetInventory{}, middleware.After) -} - -func addOpGetMaintenanceWindowExecutionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetMaintenanceWindowExecution{}, middleware.After) -} - -func addOpGetMaintenanceWindowExecutionTaskValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetMaintenanceWindowExecutionTask{}, middleware.After) -} - -func addOpGetMaintenanceWindowExecutionTaskInvocationValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetMaintenanceWindowExecutionTaskInvocation{}, middleware.After) -} - -func addOpGetMaintenanceWindowValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetMaintenanceWindow{}, middleware.After) -} - -func addOpGetMaintenanceWindowTaskValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetMaintenanceWindowTask{}, middleware.After) -} - -func addOpGetOpsItemValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetOpsItem{}, middleware.After) -} - -func addOpGetOpsMetadataValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetOpsMetadata{}, middleware.After) -} - -func addOpGetOpsSummaryValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetOpsSummary{}, middleware.After) -} - -func addOpGetParameterHistoryValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetParameterHistory{}, middleware.After) -} - -func addOpGetParameterValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetParameter{}, middleware.After) -} - -func addOpGetParametersByPathValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetParametersByPath{}, middleware.After) -} - -func addOpGetParametersValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetParameters{}, middleware.After) -} - -func addOpGetPatchBaselineForPatchGroupValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetPatchBaselineForPatchGroup{}, middleware.After) -} - -func addOpGetPatchBaselineValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetPatchBaseline{}, middleware.After) -} - -func addOpGetResourcePoliciesValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetResourcePolicies{}, middleware.After) -} - -func addOpGetServiceSettingValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetServiceSetting{}, middleware.After) -} - -func addOpLabelParameterVersionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpLabelParameterVersion{}, middleware.After) -} - -func addOpListAssociationsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListAssociations{}, middleware.After) -} - -func addOpListAssociationVersionsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListAssociationVersions{}, middleware.After) -} - -func addOpListCommandInvocationsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListCommandInvocations{}, middleware.After) -} - -func addOpListCommandsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListCommands{}, middleware.After) -} - -func addOpListDocumentMetadataHistoryValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListDocumentMetadataHistory{}, middleware.After) -} - -func addOpListDocumentsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListDocuments{}, middleware.After) -} - -func addOpListDocumentVersionsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListDocumentVersions{}, middleware.After) -} - -func addOpListInventoryEntriesValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListInventoryEntries{}, middleware.After) -} - -func addOpListOpsItemEventsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListOpsItemEvents{}, middleware.After) -} - -func addOpListOpsItemRelatedItemsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListOpsItemRelatedItems{}, middleware.After) -} - -func addOpListOpsMetadataValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListOpsMetadata{}, middleware.After) -} - -func addOpListTagsForResourceValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListTagsForResource{}, middleware.After) -} - -func addOpModifyDocumentPermissionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpModifyDocumentPermission{}, middleware.After) -} - -func addOpPutComplianceItemsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpPutComplianceItems{}, middleware.After) -} - -func addOpPutInventoryValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpPutInventory{}, middleware.After) -} - -func addOpPutParameterValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpPutParameter{}, middleware.After) -} - -func addOpPutResourcePolicyValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpPutResourcePolicy{}, middleware.After) -} - -func addOpRegisterDefaultPatchBaselineValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpRegisterDefaultPatchBaseline{}, middleware.After) -} - -func addOpRegisterPatchBaselineForPatchGroupValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpRegisterPatchBaselineForPatchGroup{}, middleware.After) -} - -func addOpRegisterTargetWithMaintenanceWindowValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpRegisterTargetWithMaintenanceWindow{}, middleware.After) -} - -func addOpRegisterTaskWithMaintenanceWindowValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpRegisterTaskWithMaintenanceWindow{}, middleware.After) -} - -func addOpRemoveTagsFromResourceValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpRemoveTagsFromResource{}, middleware.After) -} - -func addOpResetServiceSettingValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpResetServiceSetting{}, middleware.After) -} - -func addOpResumeSessionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpResumeSession{}, middleware.After) -} - -func addOpSendAutomationSignalValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpSendAutomationSignal{}, middleware.After) -} - -func addOpSendCommandValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpSendCommand{}, middleware.After) -} - -func addOpStartAssociationsOnceValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpStartAssociationsOnce{}, middleware.After) -} - -func addOpStartAutomationExecutionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpStartAutomationExecution{}, middleware.After) -} - -func addOpStartChangeRequestExecutionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpStartChangeRequestExecution{}, middleware.After) -} - -func addOpStartSessionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpStartSession{}, middleware.After) -} - -func addOpStopAutomationExecutionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpStopAutomationExecution{}, middleware.After) -} - -func addOpTerminateSessionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpTerminateSession{}, middleware.After) -} - -func addOpUnlabelParameterVersionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUnlabelParameterVersion{}, middleware.After) -} - -func addOpUpdateAssociationValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateAssociation{}, middleware.After) -} - -func addOpUpdateAssociationStatusValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateAssociationStatus{}, middleware.After) -} - -func addOpUpdateDocumentDefaultVersionValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateDocumentDefaultVersion{}, middleware.After) -} - -func addOpUpdateDocumentValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateDocument{}, middleware.After) -} - -func addOpUpdateDocumentMetadataValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateDocumentMetadata{}, middleware.After) -} - -func addOpUpdateMaintenanceWindowValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateMaintenanceWindow{}, middleware.After) -} - -func addOpUpdateMaintenanceWindowTargetValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateMaintenanceWindowTarget{}, middleware.After) -} - -func addOpUpdateMaintenanceWindowTaskValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateMaintenanceWindowTask{}, middleware.After) -} - -func addOpUpdateManagedInstanceRoleValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateManagedInstanceRole{}, middleware.After) -} - -func addOpUpdateOpsItemValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateOpsItem{}, middleware.After) -} - -func addOpUpdateOpsMetadataValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateOpsMetadata{}, middleware.After) -} - -func addOpUpdatePatchBaselineValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdatePatchBaseline{}, middleware.After) -} - -func addOpUpdateResourceDataSyncValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateResourceDataSync{}, middleware.After) -} - -func addOpUpdateServiceSettingValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpUpdateServiceSetting{}, middleware.After) -} - -func validateAlarm(v *types.Alarm) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "Alarm"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateAlarmConfiguration(v *types.AlarmConfiguration) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AlarmConfiguration"} - if v.Alarms == nil { - invalidParams.Add(smithy.NewErrParamRequired("Alarms")) - } else if v.Alarms != nil { - if err := validateAlarmList(v.Alarms); err != nil { - invalidParams.AddNested("Alarms", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateAlarmList(v []types.Alarm) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AlarmList"} - for i := range v { - if err := validateAlarm(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateAssociationExecutionFilter(v *types.AssociationExecutionFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssociationExecutionFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Value == nil { - invalidParams.Add(smithy.NewErrParamRequired("Value")) - } - if len(v.Type) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Type")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateAssociationExecutionFilterList(v []types.AssociationExecutionFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssociationExecutionFilterList"} - for i := range v { - if err := validateAssociationExecutionFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateAssociationExecutionTargetsFilter(v *types.AssociationExecutionTargetsFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssociationExecutionTargetsFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Value == nil { - invalidParams.Add(smithy.NewErrParamRequired("Value")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateAssociationExecutionTargetsFilterList(v []types.AssociationExecutionTargetsFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssociationExecutionTargetsFilterList"} - for i := range v { - if err := validateAssociationExecutionTargetsFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateAssociationFilter(v *types.AssociationFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssociationFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Value == nil { - invalidParams.Add(smithy.NewErrParamRequired("Value")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateAssociationFilterList(v []types.AssociationFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssociationFilterList"} - for i := range v { - if err := validateAssociationFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateAssociationStatus(v *types.AssociationStatus) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssociationStatus"} - if v.Date == nil { - invalidParams.Add(smithy.NewErrParamRequired("Date")) - } - if len(v.Name) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.Message == nil { - invalidParams.Add(smithy.NewErrParamRequired("Message")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateAutomationExecutionFilter(v *types.AutomationExecutionFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AutomationExecutionFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateAutomationExecutionFilterList(v []types.AutomationExecutionFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AutomationExecutionFilterList"} - for i := range v { - if err := validateAutomationExecutionFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateBaselineOverride(v *types.BaselineOverride) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "BaselineOverride"} - if v.GlobalFilters != nil { - if err := validatePatchFilterGroup(v.GlobalFilters); err != nil { - invalidParams.AddNested("GlobalFilters", err.(smithy.InvalidParamsError)) - } - } - if v.ApprovalRules != nil { - if err := validatePatchRuleGroup(v.ApprovalRules); err != nil { - invalidParams.AddNested("ApprovalRules", err.(smithy.InvalidParamsError)) - } - } - if v.Sources != nil { - if err := validatePatchSourceList(v.Sources); err != nil { - invalidParams.AddNested("Sources", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateCommandFilter(v *types.CommandFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CommandFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Value == nil { - invalidParams.Add(smithy.NewErrParamRequired("Value")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateCommandFilterList(v []types.CommandFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CommandFilterList"} - for i := range v { - if err := validateCommandFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateComplianceExecutionSummary(v *types.ComplianceExecutionSummary) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ComplianceExecutionSummary"} - if v.ExecutionTime == nil { - invalidParams.Add(smithy.NewErrParamRequired("ExecutionTime")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateComplianceItemEntry(v *types.ComplianceItemEntry) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ComplianceItemEntry"} - if len(v.Severity) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Severity")) - } - if len(v.Status) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Status")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateComplianceItemEntryList(v []types.ComplianceItemEntry) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ComplianceItemEntryList"} - for i := range v { - if err := validateComplianceItemEntry(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateCreateAssociationBatchRequestEntries(v []types.CreateAssociationBatchRequestEntry) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateAssociationBatchRequestEntries"} - for i := range v { - if err := validateCreateAssociationBatchRequestEntry(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateCreateAssociationBatchRequestEntry(v *types.CreateAssociationBatchRequestEntry) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateAssociationBatchRequestEntry"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.TargetLocations != nil { - if err := validateTargetLocations(v.TargetLocations); err != nil { - invalidParams.AddNested("TargetLocations", err.(smithy.InvalidParamsError)) - } - } - if v.AlarmConfiguration != nil { - if err := validateAlarmConfiguration(v.AlarmConfiguration); err != nil { - invalidParams.AddNested("AlarmConfiguration", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateDocumentFilter(v *types.DocumentFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DocumentFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Value == nil { - invalidParams.Add(smithy.NewErrParamRequired("Value")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateDocumentFilterList(v []types.DocumentFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DocumentFilterList"} - for i := range v { - if err := validateDocumentFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateDocumentRequires(v *types.DocumentRequires) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DocumentRequires"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateDocumentRequiresList(v []types.DocumentRequires) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DocumentRequiresList"} - for i := range v { - if err := validateDocumentRequires(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateDocumentReviews(v *types.DocumentReviews) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DocumentReviews"} - if len(v.Action) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Action")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInstanceInformationFilter(v *types.InstanceInformationFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InstanceInformationFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.ValueSet == nil { - invalidParams.Add(smithy.NewErrParamRequired("ValueSet")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInstanceInformationFilterList(v []types.InstanceInformationFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InstanceInformationFilterList"} - for i := range v { - if err := validateInstanceInformationFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInstanceInformationStringFilter(v *types.InstanceInformationStringFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InstanceInformationStringFilter"} - if v.Key == nil { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInstanceInformationStringFilterList(v []types.InstanceInformationStringFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InstanceInformationStringFilterList"} - for i := range v { - if err := validateInstanceInformationStringFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInstancePatchStateFilter(v *types.InstancePatchStateFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InstancePatchStateFilter"} - if v.Key == nil { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if len(v.Type) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Type")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInstancePatchStateFilterList(v []types.InstancePatchStateFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InstancePatchStateFilterList"} - for i := range v { - if err := validateInstancePatchStateFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInventoryAggregator(v *types.InventoryAggregator) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InventoryAggregator"} - if v.Aggregators != nil { - if err := validateInventoryAggregatorList(v.Aggregators); err != nil { - invalidParams.AddNested("Aggregators", err.(smithy.InvalidParamsError)) - } - } - if v.Groups != nil { - if err := validateInventoryGroupList(v.Groups); err != nil { - invalidParams.AddNested("Groups", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInventoryAggregatorList(v []types.InventoryAggregator) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InventoryAggregatorList"} - for i := range v { - if err := validateInventoryAggregator(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInventoryFilter(v *types.InventoryFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InventoryFilter"} - if v.Key == nil { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInventoryFilterList(v []types.InventoryFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InventoryFilterList"} - for i := range v { - if err := validateInventoryFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInventoryGroup(v *types.InventoryGroup) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InventoryGroup"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.Filters == nil { - invalidParams.Add(smithy.NewErrParamRequired("Filters")) - } else if v.Filters != nil { - if err := validateInventoryFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInventoryGroupList(v []types.InventoryGroup) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InventoryGroupList"} - for i := range v { - if err := validateInventoryGroup(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInventoryItem(v *types.InventoryItem) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InventoryItem"} - if v.TypeName == nil { - invalidParams.Add(smithy.NewErrParamRequired("TypeName")) - } - if v.SchemaVersion == nil { - invalidParams.Add(smithy.NewErrParamRequired("SchemaVersion")) - } - if v.CaptureTime == nil { - invalidParams.Add(smithy.NewErrParamRequired("CaptureTime")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateInventoryItemList(v []types.InventoryItem) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "InventoryItemList"} - for i := range v { - if err := validateInventoryItem(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateLoggingInfo(v *types.LoggingInfo) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "LoggingInfo"} - if v.S3BucketName == nil { - invalidParams.Add(smithy.NewErrParamRequired("S3BucketName")) - } - if v.S3Region == nil { - invalidParams.Add(smithy.NewErrParamRequired("S3Region")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsAggregator(v *types.OpsAggregator) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsAggregator"} - if v.Filters != nil { - if err := validateOpsFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if v.Aggregators != nil { - if err := validateOpsAggregatorList(v.Aggregators); err != nil { - invalidParams.AddNested("Aggregators", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsAggregatorList(v []types.OpsAggregator) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsAggregatorList"} - for i := range v { - if err := validateOpsAggregator(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsFilter(v *types.OpsFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsFilter"} - if v.Key == nil { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsFilterList(v []types.OpsFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsFilterList"} - for i := range v { - if err := validateOpsFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsItemEventFilter(v *types.OpsItemEventFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsItemEventFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if len(v.Operator) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Operator")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsItemEventFilters(v []types.OpsItemEventFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsItemEventFilters"} - for i := range v { - if err := validateOpsItemEventFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsItemFilter(v *types.OpsItemFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsItemFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if len(v.Operator) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Operator")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsItemFilters(v []types.OpsItemFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsItemFilters"} - for i := range v { - if err := validateOpsItemFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsItemRelatedItemsFilter(v *types.OpsItemRelatedItemsFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsItemRelatedItemsFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if len(v.Operator) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Operator")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsItemRelatedItemsFilters(v []types.OpsItemRelatedItemsFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsItemRelatedItemsFilters"} - for i := range v { - if err := validateOpsItemRelatedItemsFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsMetadataFilter(v *types.OpsMetadataFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsMetadataFilter"} - if v.Key == nil { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsMetadataFilterList(v []types.OpsMetadataFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsMetadataFilterList"} - for i := range v { - if err := validateOpsMetadataFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsResultAttribute(v *types.OpsResultAttribute) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsResultAttribute"} - if v.TypeName == nil { - invalidParams.Add(smithy.NewErrParamRequired("TypeName")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpsResultAttributeList(v []types.OpsResultAttribute) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "OpsResultAttributeList"} - for i := range v { - if err := validateOpsResultAttribute(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateParametersFilter(v *types.ParametersFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ParametersFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateParametersFilterList(v []types.ParametersFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ParametersFilterList"} - for i := range v { - if err := validateParametersFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateParameterStringFilter(v *types.ParameterStringFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ParameterStringFilter"} - if v.Key == nil { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateParameterStringFilterList(v []types.ParameterStringFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ParameterStringFilterList"} - for i := range v { - if err := validateParameterStringFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validatePatchFilter(v *types.PatchFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PatchFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validatePatchFilterGroup(v *types.PatchFilterGroup) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PatchFilterGroup"} - if v.PatchFilters == nil { - invalidParams.Add(smithy.NewErrParamRequired("PatchFilters")) - } else if v.PatchFilters != nil { - if err := validatePatchFilterList(v.PatchFilters); err != nil { - invalidParams.AddNested("PatchFilters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validatePatchFilterList(v []types.PatchFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PatchFilterList"} - for i := range v { - if err := validatePatchFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validatePatchRule(v *types.PatchRule) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PatchRule"} - if v.PatchFilterGroup == nil { - invalidParams.Add(smithy.NewErrParamRequired("PatchFilterGroup")) - } else if v.PatchFilterGroup != nil { - if err := validatePatchFilterGroup(v.PatchFilterGroup); err != nil { - invalidParams.AddNested("PatchFilterGroup", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validatePatchRuleGroup(v *types.PatchRuleGroup) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PatchRuleGroup"} - if v.PatchRules == nil { - invalidParams.Add(smithy.NewErrParamRequired("PatchRules")) - } else if v.PatchRules != nil { - if err := validatePatchRuleList(v.PatchRules); err != nil { - invalidParams.AddNested("PatchRules", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validatePatchRuleList(v []types.PatchRule) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PatchRuleList"} - for i := range v { - if err := validatePatchRule(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validatePatchSource(v *types.PatchSource) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PatchSource"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.Products == nil { - invalidParams.Add(smithy.NewErrParamRequired("Products")) - } - if v.Configuration == nil { - invalidParams.Add(smithy.NewErrParamRequired("Configuration")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validatePatchSourceList(v []types.PatchSource) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PatchSourceList"} - for i := range v { - if err := validatePatchSource(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateRegistrationMetadataItem(v *types.RegistrationMetadataItem) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RegistrationMetadataItem"} - if v.Key == nil { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Value == nil { - invalidParams.Add(smithy.NewErrParamRequired("Value")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateRegistrationMetadataList(v []types.RegistrationMetadataItem) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RegistrationMetadataList"} - for i := range v { - if err := validateRegistrationMetadataItem(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateRelatedOpsItem(v *types.RelatedOpsItem) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RelatedOpsItem"} - if v.OpsItemId == nil { - invalidParams.Add(smithy.NewErrParamRequired("OpsItemId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateRelatedOpsItems(v []types.RelatedOpsItem) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RelatedOpsItems"} - for i := range v { - if err := validateRelatedOpsItem(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateResourceDataSyncAwsOrganizationsSource(v *types.ResourceDataSyncAwsOrganizationsSource) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ResourceDataSyncAwsOrganizationsSource"} - if v.OrganizationSourceType == nil { - invalidParams.Add(smithy.NewErrParamRequired("OrganizationSourceType")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateResourceDataSyncS3Destination(v *types.ResourceDataSyncS3Destination) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ResourceDataSyncS3Destination"} - if v.BucketName == nil { - invalidParams.Add(smithy.NewErrParamRequired("BucketName")) - } - if len(v.SyncFormat) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("SyncFormat")) - } - if v.Region == nil { - invalidParams.Add(smithy.NewErrParamRequired("Region")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateResourceDataSyncSource(v *types.ResourceDataSyncSource) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ResourceDataSyncSource"} - if v.SourceType == nil { - invalidParams.Add(smithy.NewErrParamRequired("SourceType")) - } - if v.AwsOrganizationsSource != nil { - if err := validateResourceDataSyncAwsOrganizationsSource(v.AwsOrganizationsSource); err != nil { - invalidParams.AddNested("AwsOrganizationsSource", err.(smithy.InvalidParamsError)) - } - } - if v.SourceRegions == nil { - invalidParams.Add(smithy.NewErrParamRequired("SourceRegions")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateResultAttribute(v *types.ResultAttribute) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ResultAttribute"} - if v.TypeName == nil { - invalidParams.Add(smithy.NewErrParamRequired("TypeName")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateResultAttributeList(v []types.ResultAttribute) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ResultAttributeList"} - for i := range v { - if err := validateResultAttribute(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateRunbook(v *types.Runbook) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "Runbook"} - if v.DocumentName == nil { - invalidParams.Add(smithy.NewErrParamRequired("DocumentName")) - } - if v.TargetLocations != nil { - if err := validateTargetLocations(v.TargetLocations); err != nil { - invalidParams.AddNested("TargetLocations", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateRunbooks(v []types.Runbook) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "Runbooks"} - for i := range v { - if err := validateRunbook(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateSessionFilter(v *types.SessionFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "SessionFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Value == nil { - invalidParams.Add(smithy.NewErrParamRequired("Value")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateSessionFilterList(v []types.SessionFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "SessionFilterList"} - for i := range v { - if err := validateSessionFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateStepExecutionFilter(v *types.StepExecutionFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "StepExecutionFilter"} - if len(v.Key) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Values == nil { - invalidParams.Add(smithy.NewErrParamRequired("Values")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateStepExecutionFilterList(v []types.StepExecutionFilter) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "StepExecutionFilterList"} - for i := range v { - if err := validateStepExecutionFilter(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateTag(v *types.Tag) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "Tag"} - if v.Key == nil { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Value == nil { - invalidParams.Add(smithy.NewErrParamRequired("Value")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateTagList(v []types.Tag) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "TagList"} - for i := range v { - if err := validateTag(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateTargetLocation(v *types.TargetLocation) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "TargetLocation"} - if v.TargetLocationAlarmConfiguration != nil { - if err := validateAlarmConfiguration(v.TargetLocationAlarmConfiguration); err != nil { - invalidParams.AddNested("TargetLocationAlarmConfiguration", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateTargetLocations(v []types.TargetLocation) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "TargetLocations"} - for i := range v { - if err := validateTargetLocation(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpAddTagsToResourceInput(v *AddTagsToResourceInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AddTagsToResourceInput"} - if len(v.ResourceType) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("ResourceType")) - } - if v.ResourceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourceId")) - } - if v.Tags == nil { - invalidParams.Add(smithy.NewErrParamRequired("Tags")) - } else if v.Tags != nil { - if err := validateTagList(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpAssociateOpsItemRelatedItemInput(v *AssociateOpsItemRelatedItemInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssociateOpsItemRelatedItemInput"} - if v.OpsItemId == nil { - invalidParams.Add(smithy.NewErrParamRequired("OpsItemId")) - } - if v.AssociationType == nil { - invalidParams.Add(smithy.NewErrParamRequired("AssociationType")) - } - if v.ResourceType == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourceType")) - } - if v.ResourceUri == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourceUri")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCancelCommandInput(v *CancelCommandInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CancelCommandInput"} - if v.CommandId == nil { - invalidParams.Add(smithy.NewErrParamRequired("CommandId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCancelMaintenanceWindowExecutionInput(v *CancelMaintenanceWindowExecutionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CancelMaintenanceWindowExecutionInput"} - if v.WindowExecutionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowExecutionId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCreateActivationInput(v *CreateActivationInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateActivationInput"} - if v.IamRole == nil { - invalidParams.Add(smithy.NewErrParamRequired("IamRole")) - } - if v.Tags != nil { - if err := validateTagList(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if v.RegistrationMetadata != nil { - if err := validateRegistrationMetadataList(v.RegistrationMetadata); err != nil { - invalidParams.AddNested("RegistrationMetadata", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCreateAssociationBatchInput(v *CreateAssociationBatchInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateAssociationBatchInput"} - if v.Entries == nil { - invalidParams.Add(smithy.NewErrParamRequired("Entries")) - } else if v.Entries != nil { - if err := validateCreateAssociationBatchRequestEntries(v.Entries); err != nil { - invalidParams.AddNested("Entries", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCreateAssociationInput(v *CreateAssociationInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateAssociationInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.TargetLocations != nil { - if err := validateTargetLocations(v.TargetLocations); err != nil { - invalidParams.AddNested("TargetLocations", err.(smithy.InvalidParamsError)) - } - } - if v.Tags != nil { - if err := validateTagList(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if v.AlarmConfiguration != nil { - if err := validateAlarmConfiguration(v.AlarmConfiguration); err != nil { - invalidParams.AddNested("AlarmConfiguration", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCreateDocumentInput(v *CreateDocumentInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateDocumentInput"} - if v.Content == nil { - invalidParams.Add(smithy.NewErrParamRequired("Content")) - } - if v.Requires != nil { - if err := validateDocumentRequiresList(v.Requires); err != nil { - invalidParams.AddNested("Requires", err.(smithy.InvalidParamsError)) - } - } - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.Tags != nil { - if err := validateTagList(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCreateMaintenanceWindowInput(v *CreateMaintenanceWindowInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateMaintenanceWindowInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.Schedule == nil { - invalidParams.Add(smithy.NewErrParamRequired("Schedule")) - } - if v.Duration == nil { - invalidParams.Add(smithy.NewErrParamRequired("Duration")) - } - if v.Tags != nil { - if err := validateTagList(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCreateOpsItemInput(v *CreateOpsItemInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateOpsItemInput"} - if v.Description == nil { - invalidParams.Add(smithy.NewErrParamRequired("Description")) - } - if v.RelatedOpsItems != nil { - if err := validateRelatedOpsItems(v.RelatedOpsItems); err != nil { - invalidParams.AddNested("RelatedOpsItems", err.(smithy.InvalidParamsError)) - } - } - if v.Source == nil { - invalidParams.Add(smithy.NewErrParamRequired("Source")) - } - if v.Title == nil { - invalidParams.Add(smithy.NewErrParamRequired("Title")) - } - if v.Tags != nil { - if err := validateTagList(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCreateOpsMetadataInput(v *CreateOpsMetadataInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateOpsMetadataInput"} - if v.ResourceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourceId")) - } - if v.Tags != nil { - if err := validateTagList(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCreatePatchBaselineInput(v *CreatePatchBaselineInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreatePatchBaselineInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.GlobalFilters != nil { - if err := validatePatchFilterGroup(v.GlobalFilters); err != nil { - invalidParams.AddNested("GlobalFilters", err.(smithy.InvalidParamsError)) - } - } - if v.ApprovalRules != nil { - if err := validatePatchRuleGroup(v.ApprovalRules); err != nil { - invalidParams.AddNested("ApprovalRules", err.(smithy.InvalidParamsError)) - } - } - if v.Sources != nil { - if err := validatePatchSourceList(v.Sources); err != nil { - invalidParams.AddNested("Sources", err.(smithy.InvalidParamsError)) - } - } - if v.Tags != nil { - if err := validateTagList(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCreateResourceDataSyncInput(v *CreateResourceDataSyncInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateResourceDataSyncInput"} - if v.SyncName == nil { - invalidParams.Add(smithy.NewErrParamRequired("SyncName")) - } - if v.S3Destination != nil { - if err := validateResourceDataSyncS3Destination(v.S3Destination); err != nil { - invalidParams.AddNested("S3Destination", err.(smithy.InvalidParamsError)) - } - } - if v.SyncSource != nil { - if err := validateResourceDataSyncSource(v.SyncSource); err != nil { - invalidParams.AddNested("SyncSource", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteActivationInput(v *DeleteActivationInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteActivationInput"} - if v.ActivationId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ActivationId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteDocumentInput(v *DeleteDocumentInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteDocumentInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteInventoryInput(v *DeleteInventoryInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteInventoryInput"} - if v.TypeName == nil { - invalidParams.Add(smithy.NewErrParamRequired("TypeName")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteMaintenanceWindowInput(v *DeleteMaintenanceWindowInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteMaintenanceWindowInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteOpsItemInput(v *DeleteOpsItemInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteOpsItemInput"} - if v.OpsItemId == nil { - invalidParams.Add(smithy.NewErrParamRequired("OpsItemId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteOpsMetadataInput(v *DeleteOpsMetadataInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteOpsMetadataInput"} - if v.OpsMetadataArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("OpsMetadataArn")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteParameterInput(v *DeleteParameterInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteParameterInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteParametersInput(v *DeleteParametersInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteParametersInput"} - if v.Names == nil { - invalidParams.Add(smithy.NewErrParamRequired("Names")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeletePatchBaselineInput(v *DeletePatchBaselineInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeletePatchBaselineInput"} - if v.BaselineId == nil { - invalidParams.Add(smithy.NewErrParamRequired("BaselineId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteResourceDataSyncInput(v *DeleteResourceDataSyncInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteResourceDataSyncInput"} - if v.SyncName == nil { - invalidParams.Add(smithy.NewErrParamRequired("SyncName")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeleteResourcePolicyInput(v *DeleteResourcePolicyInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeleteResourcePolicyInput"} - if v.ResourceArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourceArn")) - } - if v.PolicyId == nil { - invalidParams.Add(smithy.NewErrParamRequired("PolicyId")) - } - if v.PolicyHash == nil { - invalidParams.Add(smithy.NewErrParamRequired("PolicyHash")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeregisterManagedInstanceInput(v *DeregisterManagedInstanceInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeregisterManagedInstanceInput"} - if v.InstanceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("InstanceId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeregisterPatchBaselineForPatchGroupInput(v *DeregisterPatchBaselineForPatchGroupInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeregisterPatchBaselineForPatchGroupInput"} - if v.BaselineId == nil { - invalidParams.Add(smithy.NewErrParamRequired("BaselineId")) - } - if v.PatchGroup == nil { - invalidParams.Add(smithy.NewErrParamRequired("PatchGroup")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeregisterTargetFromMaintenanceWindowInput(v *DeregisterTargetFromMaintenanceWindowInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeregisterTargetFromMaintenanceWindowInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if v.WindowTargetId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowTargetId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDeregisterTaskFromMaintenanceWindowInput(v *DeregisterTaskFromMaintenanceWindowInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DeregisterTaskFromMaintenanceWindowInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if v.WindowTaskId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowTaskId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeAssociationExecutionsInput(v *DescribeAssociationExecutionsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeAssociationExecutionsInput"} - if v.AssociationId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AssociationId")) - } - if v.Filters != nil { - if err := validateAssociationExecutionFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeAssociationExecutionTargetsInput(v *DescribeAssociationExecutionTargetsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeAssociationExecutionTargetsInput"} - if v.AssociationId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AssociationId")) - } - if v.ExecutionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ExecutionId")) - } - if v.Filters != nil { - if err := validateAssociationExecutionTargetsFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeAutomationExecutionsInput(v *DescribeAutomationExecutionsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeAutomationExecutionsInput"} - if v.Filters != nil { - if err := validateAutomationExecutionFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeAutomationStepExecutionsInput(v *DescribeAutomationStepExecutionsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeAutomationStepExecutionsInput"} - if v.AutomationExecutionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AutomationExecutionId")) - } - if v.Filters != nil { - if err := validateStepExecutionFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeDocumentInput(v *DescribeDocumentInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeDocumentInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeDocumentPermissionInput(v *DescribeDocumentPermissionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeDocumentPermissionInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if len(v.PermissionType) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("PermissionType")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeEffectiveInstanceAssociationsInput(v *DescribeEffectiveInstanceAssociationsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeEffectiveInstanceAssociationsInput"} - if v.InstanceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("InstanceId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeEffectivePatchesForPatchBaselineInput(v *DescribeEffectivePatchesForPatchBaselineInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeEffectivePatchesForPatchBaselineInput"} - if v.BaselineId == nil { - invalidParams.Add(smithy.NewErrParamRequired("BaselineId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeInstanceAssociationsStatusInput(v *DescribeInstanceAssociationsStatusInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeInstanceAssociationsStatusInput"} - if v.InstanceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("InstanceId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeInstanceInformationInput(v *DescribeInstanceInformationInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeInstanceInformationInput"} - if v.InstanceInformationFilterList != nil { - if err := validateInstanceInformationFilterList(v.InstanceInformationFilterList); err != nil { - invalidParams.AddNested("InstanceInformationFilterList", err.(smithy.InvalidParamsError)) - } - } - if v.Filters != nil { - if err := validateInstanceInformationStringFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeInstancePatchesInput(v *DescribeInstancePatchesInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeInstancePatchesInput"} - if v.InstanceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("InstanceId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeInstancePatchStatesForPatchGroupInput(v *DescribeInstancePatchStatesForPatchGroupInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeInstancePatchStatesForPatchGroupInput"} - if v.PatchGroup == nil { - invalidParams.Add(smithy.NewErrParamRequired("PatchGroup")) - } - if v.Filters != nil { - if err := validateInstancePatchStateFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeInstancePatchStatesInput(v *DescribeInstancePatchStatesInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeInstancePatchStatesInput"} - if v.InstanceIds == nil { - invalidParams.Add(smithy.NewErrParamRequired("InstanceIds")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeMaintenanceWindowExecutionsInput(v *DescribeMaintenanceWindowExecutionsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeMaintenanceWindowExecutionsInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeMaintenanceWindowExecutionTaskInvocationsInput(v *DescribeMaintenanceWindowExecutionTaskInvocationsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeMaintenanceWindowExecutionTaskInvocationsInput"} - if v.WindowExecutionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowExecutionId")) - } - if v.TaskId == nil { - invalidParams.Add(smithy.NewErrParamRequired("TaskId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeMaintenanceWindowExecutionTasksInput(v *DescribeMaintenanceWindowExecutionTasksInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeMaintenanceWindowExecutionTasksInput"} - if v.WindowExecutionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowExecutionId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeMaintenanceWindowsForTargetInput(v *DescribeMaintenanceWindowsForTargetInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeMaintenanceWindowsForTargetInput"} - if v.Targets == nil { - invalidParams.Add(smithy.NewErrParamRequired("Targets")) - } - if len(v.ResourceType) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("ResourceType")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeMaintenanceWindowTargetsInput(v *DescribeMaintenanceWindowTargetsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeMaintenanceWindowTargetsInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeMaintenanceWindowTasksInput(v *DescribeMaintenanceWindowTasksInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeMaintenanceWindowTasksInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeOpsItemsInput(v *DescribeOpsItemsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeOpsItemsInput"} - if v.OpsItemFilters != nil { - if err := validateOpsItemFilters(v.OpsItemFilters); err != nil { - invalidParams.AddNested("OpsItemFilters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeParametersInput(v *DescribeParametersInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeParametersInput"} - if v.Filters != nil { - if err := validateParametersFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if v.ParameterFilters != nil { - if err := validateParameterStringFilterList(v.ParameterFilters); err != nil { - invalidParams.AddNested("ParameterFilters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribePatchGroupStateInput(v *DescribePatchGroupStateInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribePatchGroupStateInput"} - if v.PatchGroup == nil { - invalidParams.Add(smithy.NewErrParamRequired("PatchGroup")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribePatchPropertiesInput(v *DescribePatchPropertiesInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribePatchPropertiesInput"} - if len(v.OperatingSystem) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("OperatingSystem")) - } - if len(v.Property) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Property")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDescribeSessionsInput(v *DescribeSessionsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DescribeSessionsInput"} - if len(v.State) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("State")) - } - if v.Filters != nil { - if err := validateSessionFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDisassociateOpsItemRelatedItemInput(v *DisassociateOpsItemRelatedItemInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DisassociateOpsItemRelatedItemInput"} - if v.OpsItemId == nil { - invalidParams.Add(smithy.NewErrParamRequired("OpsItemId")) - } - if v.AssociationId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AssociationId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetAutomationExecutionInput(v *GetAutomationExecutionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetAutomationExecutionInput"} - if v.AutomationExecutionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AutomationExecutionId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetCalendarStateInput(v *GetCalendarStateInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetCalendarStateInput"} - if v.CalendarNames == nil { - invalidParams.Add(smithy.NewErrParamRequired("CalendarNames")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetCommandInvocationInput(v *GetCommandInvocationInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetCommandInvocationInput"} - if v.CommandId == nil { - invalidParams.Add(smithy.NewErrParamRequired("CommandId")) - } - if v.InstanceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("InstanceId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetConnectionStatusInput(v *GetConnectionStatusInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetConnectionStatusInput"} - if v.Target == nil { - invalidParams.Add(smithy.NewErrParamRequired("Target")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetDeployablePatchSnapshotForInstanceInput(v *GetDeployablePatchSnapshotForInstanceInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetDeployablePatchSnapshotForInstanceInput"} - if v.InstanceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("InstanceId")) - } - if v.SnapshotId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SnapshotId")) - } - if v.BaselineOverride != nil { - if err := validateBaselineOverride(v.BaselineOverride); err != nil { - invalidParams.AddNested("BaselineOverride", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetDocumentInput(v *GetDocumentInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetDocumentInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetInventoryInput(v *GetInventoryInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetInventoryInput"} - if v.Filters != nil { - if err := validateInventoryFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if v.Aggregators != nil { - if err := validateInventoryAggregatorList(v.Aggregators); err != nil { - invalidParams.AddNested("Aggregators", err.(smithy.InvalidParamsError)) - } - } - if v.ResultAttributes != nil { - if err := validateResultAttributeList(v.ResultAttributes); err != nil { - invalidParams.AddNested("ResultAttributes", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetMaintenanceWindowExecutionInput(v *GetMaintenanceWindowExecutionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetMaintenanceWindowExecutionInput"} - if v.WindowExecutionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowExecutionId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetMaintenanceWindowExecutionTaskInput(v *GetMaintenanceWindowExecutionTaskInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetMaintenanceWindowExecutionTaskInput"} - if v.WindowExecutionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowExecutionId")) - } - if v.TaskId == nil { - invalidParams.Add(smithy.NewErrParamRequired("TaskId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetMaintenanceWindowExecutionTaskInvocationInput(v *GetMaintenanceWindowExecutionTaskInvocationInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetMaintenanceWindowExecutionTaskInvocationInput"} - if v.WindowExecutionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowExecutionId")) - } - if v.TaskId == nil { - invalidParams.Add(smithy.NewErrParamRequired("TaskId")) - } - if v.InvocationId == nil { - invalidParams.Add(smithy.NewErrParamRequired("InvocationId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetMaintenanceWindowInput(v *GetMaintenanceWindowInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetMaintenanceWindowInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetMaintenanceWindowTaskInput(v *GetMaintenanceWindowTaskInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetMaintenanceWindowTaskInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if v.WindowTaskId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowTaskId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetOpsItemInput(v *GetOpsItemInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetOpsItemInput"} - if v.OpsItemId == nil { - invalidParams.Add(smithy.NewErrParamRequired("OpsItemId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetOpsMetadataInput(v *GetOpsMetadataInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetOpsMetadataInput"} - if v.OpsMetadataArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("OpsMetadataArn")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetOpsSummaryInput(v *GetOpsSummaryInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetOpsSummaryInput"} - if v.Filters != nil { - if err := validateOpsFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if v.Aggregators != nil { - if err := validateOpsAggregatorList(v.Aggregators); err != nil { - invalidParams.AddNested("Aggregators", err.(smithy.InvalidParamsError)) - } - } - if v.ResultAttributes != nil { - if err := validateOpsResultAttributeList(v.ResultAttributes); err != nil { - invalidParams.AddNested("ResultAttributes", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetParameterHistoryInput(v *GetParameterHistoryInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetParameterHistoryInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetParameterInput(v *GetParameterInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetParameterInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetParametersByPathInput(v *GetParametersByPathInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetParametersByPathInput"} - if v.Path == nil { - invalidParams.Add(smithy.NewErrParamRequired("Path")) - } - if v.ParameterFilters != nil { - if err := validateParameterStringFilterList(v.ParameterFilters); err != nil { - invalidParams.AddNested("ParameterFilters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetParametersInput(v *GetParametersInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetParametersInput"} - if v.Names == nil { - invalidParams.Add(smithy.NewErrParamRequired("Names")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetPatchBaselineForPatchGroupInput(v *GetPatchBaselineForPatchGroupInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetPatchBaselineForPatchGroupInput"} - if v.PatchGroup == nil { - invalidParams.Add(smithy.NewErrParamRequired("PatchGroup")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetPatchBaselineInput(v *GetPatchBaselineInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetPatchBaselineInput"} - if v.BaselineId == nil { - invalidParams.Add(smithy.NewErrParamRequired("BaselineId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetResourcePoliciesInput(v *GetResourcePoliciesInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetResourcePoliciesInput"} - if v.ResourceArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourceArn")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetServiceSettingInput(v *GetServiceSettingInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetServiceSettingInput"} - if v.SettingId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SettingId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpLabelParameterVersionInput(v *LabelParameterVersionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "LabelParameterVersionInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.Labels == nil { - invalidParams.Add(smithy.NewErrParamRequired("Labels")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListAssociationsInput(v *ListAssociationsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListAssociationsInput"} - if v.AssociationFilterList != nil { - if err := validateAssociationFilterList(v.AssociationFilterList); err != nil { - invalidParams.AddNested("AssociationFilterList", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListAssociationVersionsInput(v *ListAssociationVersionsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListAssociationVersionsInput"} - if v.AssociationId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AssociationId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListCommandInvocationsInput(v *ListCommandInvocationsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListCommandInvocationsInput"} - if v.Filters != nil { - if err := validateCommandFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListCommandsInput(v *ListCommandsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListCommandsInput"} - if v.Filters != nil { - if err := validateCommandFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListDocumentMetadataHistoryInput(v *ListDocumentMetadataHistoryInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListDocumentMetadataHistoryInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if len(v.Metadata) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("Metadata")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListDocumentsInput(v *ListDocumentsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListDocumentsInput"} - if v.DocumentFilterList != nil { - if err := validateDocumentFilterList(v.DocumentFilterList); err != nil { - invalidParams.AddNested("DocumentFilterList", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListDocumentVersionsInput(v *ListDocumentVersionsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListDocumentVersionsInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListInventoryEntriesInput(v *ListInventoryEntriesInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListInventoryEntriesInput"} - if v.InstanceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("InstanceId")) - } - if v.TypeName == nil { - invalidParams.Add(smithy.NewErrParamRequired("TypeName")) - } - if v.Filters != nil { - if err := validateInventoryFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListOpsItemEventsInput(v *ListOpsItemEventsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListOpsItemEventsInput"} - if v.Filters != nil { - if err := validateOpsItemEventFilters(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListOpsItemRelatedItemsInput(v *ListOpsItemRelatedItemsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListOpsItemRelatedItemsInput"} - if v.Filters != nil { - if err := validateOpsItemRelatedItemsFilters(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListOpsMetadataInput(v *ListOpsMetadataInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListOpsMetadataInput"} - if v.Filters != nil { - if err := validateOpsMetadataFilterList(v.Filters); err != nil { - invalidParams.AddNested("Filters", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListTagsForResourceInput(v *ListTagsForResourceInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListTagsForResourceInput"} - if len(v.ResourceType) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("ResourceType")) - } - if v.ResourceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourceId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpModifyDocumentPermissionInput(v *ModifyDocumentPermissionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ModifyDocumentPermissionInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if len(v.PermissionType) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("PermissionType")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpPutComplianceItemsInput(v *PutComplianceItemsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PutComplianceItemsInput"} - if v.ResourceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourceId")) - } - if v.ResourceType == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourceType")) - } - if v.ComplianceType == nil { - invalidParams.Add(smithy.NewErrParamRequired("ComplianceType")) - } - if v.ExecutionSummary == nil { - invalidParams.Add(smithy.NewErrParamRequired("ExecutionSummary")) - } else if v.ExecutionSummary != nil { - if err := validateComplianceExecutionSummary(v.ExecutionSummary); err != nil { - invalidParams.AddNested("ExecutionSummary", err.(smithy.InvalidParamsError)) - } - } - if v.Items == nil { - invalidParams.Add(smithy.NewErrParamRequired("Items")) - } else if v.Items != nil { - if err := validateComplianceItemEntryList(v.Items); err != nil { - invalidParams.AddNested("Items", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpPutInventoryInput(v *PutInventoryInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PutInventoryInput"} - if v.InstanceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("InstanceId")) - } - if v.Items == nil { - invalidParams.Add(smithy.NewErrParamRequired("Items")) - } else if v.Items != nil { - if err := validateInventoryItemList(v.Items); err != nil { - invalidParams.AddNested("Items", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpPutParameterInput(v *PutParameterInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PutParameterInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.Value == nil { - invalidParams.Add(smithy.NewErrParamRequired("Value")) - } - if v.Tags != nil { - if err := validateTagList(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpPutResourcePolicyInput(v *PutResourcePolicyInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "PutResourcePolicyInput"} - if v.ResourceArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourceArn")) - } - if v.Policy == nil { - invalidParams.Add(smithy.NewErrParamRequired("Policy")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpRegisterDefaultPatchBaselineInput(v *RegisterDefaultPatchBaselineInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RegisterDefaultPatchBaselineInput"} - if v.BaselineId == nil { - invalidParams.Add(smithy.NewErrParamRequired("BaselineId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpRegisterPatchBaselineForPatchGroupInput(v *RegisterPatchBaselineForPatchGroupInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RegisterPatchBaselineForPatchGroupInput"} - if v.BaselineId == nil { - invalidParams.Add(smithy.NewErrParamRequired("BaselineId")) - } - if v.PatchGroup == nil { - invalidParams.Add(smithy.NewErrParamRequired("PatchGroup")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpRegisterTargetWithMaintenanceWindowInput(v *RegisterTargetWithMaintenanceWindowInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RegisterTargetWithMaintenanceWindowInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if len(v.ResourceType) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("ResourceType")) - } - if v.Targets == nil { - invalidParams.Add(smithy.NewErrParamRequired("Targets")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpRegisterTaskWithMaintenanceWindowInput(v *RegisterTaskWithMaintenanceWindowInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RegisterTaskWithMaintenanceWindowInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if v.TaskArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("TaskArn")) - } - if len(v.TaskType) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("TaskType")) - } - if v.LoggingInfo != nil { - if err := validateLoggingInfo(v.LoggingInfo); err != nil { - invalidParams.AddNested("LoggingInfo", err.(smithy.InvalidParamsError)) - } - } - if v.AlarmConfiguration != nil { - if err := validateAlarmConfiguration(v.AlarmConfiguration); err != nil { - invalidParams.AddNested("AlarmConfiguration", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpRemoveTagsFromResourceInput(v *RemoveTagsFromResourceInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RemoveTagsFromResourceInput"} - if len(v.ResourceType) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("ResourceType")) - } - if v.ResourceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ResourceId")) - } - if v.TagKeys == nil { - invalidParams.Add(smithy.NewErrParamRequired("TagKeys")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpResetServiceSettingInput(v *ResetServiceSettingInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ResetServiceSettingInput"} - if v.SettingId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SettingId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpResumeSessionInput(v *ResumeSessionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ResumeSessionInput"} - if v.SessionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SessionId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpSendAutomationSignalInput(v *SendAutomationSignalInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "SendAutomationSignalInput"} - if v.AutomationExecutionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AutomationExecutionId")) - } - if len(v.SignalType) == 0 { - invalidParams.Add(smithy.NewErrParamRequired("SignalType")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpSendCommandInput(v *SendCommandInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "SendCommandInput"} - if v.DocumentName == nil { - invalidParams.Add(smithy.NewErrParamRequired("DocumentName")) - } - if v.AlarmConfiguration != nil { - if err := validateAlarmConfiguration(v.AlarmConfiguration); err != nil { - invalidParams.AddNested("AlarmConfiguration", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpStartAssociationsOnceInput(v *StartAssociationsOnceInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "StartAssociationsOnceInput"} - if v.AssociationIds == nil { - invalidParams.Add(smithy.NewErrParamRequired("AssociationIds")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpStartAutomationExecutionInput(v *StartAutomationExecutionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "StartAutomationExecutionInput"} - if v.DocumentName == nil { - invalidParams.Add(smithy.NewErrParamRequired("DocumentName")) - } - if v.TargetLocations != nil { - if err := validateTargetLocations(v.TargetLocations); err != nil { - invalidParams.AddNested("TargetLocations", err.(smithy.InvalidParamsError)) - } - } - if v.Tags != nil { - if err := validateTagList(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if v.AlarmConfiguration != nil { - if err := validateAlarmConfiguration(v.AlarmConfiguration); err != nil { - invalidParams.AddNested("AlarmConfiguration", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpStartChangeRequestExecutionInput(v *StartChangeRequestExecutionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "StartChangeRequestExecutionInput"} - if v.DocumentName == nil { - invalidParams.Add(smithy.NewErrParamRequired("DocumentName")) - } - if v.Runbooks == nil { - invalidParams.Add(smithy.NewErrParamRequired("Runbooks")) - } else if v.Runbooks != nil { - if err := validateRunbooks(v.Runbooks); err != nil { - invalidParams.AddNested("Runbooks", err.(smithy.InvalidParamsError)) - } - } - if v.Tags != nil { - if err := validateTagList(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpStartSessionInput(v *StartSessionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "StartSessionInput"} - if v.Target == nil { - invalidParams.Add(smithy.NewErrParamRequired("Target")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpStopAutomationExecutionInput(v *StopAutomationExecutionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "StopAutomationExecutionInput"} - if v.AutomationExecutionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AutomationExecutionId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpTerminateSessionInput(v *TerminateSessionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "TerminateSessionInput"} - if v.SessionId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SessionId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUnlabelParameterVersionInput(v *UnlabelParameterVersionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UnlabelParameterVersionInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.ParameterVersion == nil { - invalidParams.Add(smithy.NewErrParamRequired("ParameterVersion")) - } - if v.Labels == nil { - invalidParams.Add(smithy.NewErrParamRequired("Labels")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateAssociationInput(v *UpdateAssociationInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateAssociationInput"} - if v.AssociationId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AssociationId")) - } - if v.TargetLocations != nil { - if err := validateTargetLocations(v.TargetLocations); err != nil { - invalidParams.AddNested("TargetLocations", err.(smithy.InvalidParamsError)) - } - } - if v.AlarmConfiguration != nil { - if err := validateAlarmConfiguration(v.AlarmConfiguration); err != nil { - invalidParams.AddNested("AlarmConfiguration", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateAssociationStatusInput(v *UpdateAssociationStatusInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateAssociationStatusInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.InstanceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("InstanceId")) - } - if v.AssociationStatus == nil { - invalidParams.Add(smithy.NewErrParamRequired("AssociationStatus")) - } else if v.AssociationStatus != nil { - if err := validateAssociationStatus(v.AssociationStatus); err != nil { - invalidParams.AddNested("AssociationStatus", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateDocumentDefaultVersionInput(v *UpdateDocumentDefaultVersionInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateDocumentDefaultVersionInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.DocumentVersion == nil { - invalidParams.Add(smithy.NewErrParamRequired("DocumentVersion")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateDocumentInput(v *UpdateDocumentInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateDocumentInput"} - if v.Content == nil { - invalidParams.Add(smithy.NewErrParamRequired("Content")) - } - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateDocumentMetadataInput(v *UpdateDocumentMetadataInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateDocumentMetadataInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.DocumentReviews == nil { - invalidParams.Add(smithy.NewErrParamRequired("DocumentReviews")) - } else if v.DocumentReviews != nil { - if err := validateDocumentReviews(v.DocumentReviews); err != nil { - invalidParams.AddNested("DocumentReviews", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateMaintenanceWindowInput(v *UpdateMaintenanceWindowInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateMaintenanceWindowInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateMaintenanceWindowTargetInput(v *UpdateMaintenanceWindowTargetInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateMaintenanceWindowTargetInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if v.WindowTargetId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowTargetId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateMaintenanceWindowTaskInput(v *UpdateMaintenanceWindowTaskInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateMaintenanceWindowTaskInput"} - if v.WindowId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowId")) - } - if v.WindowTaskId == nil { - invalidParams.Add(smithy.NewErrParamRequired("WindowTaskId")) - } - if v.LoggingInfo != nil { - if err := validateLoggingInfo(v.LoggingInfo); err != nil { - invalidParams.AddNested("LoggingInfo", err.(smithy.InvalidParamsError)) - } - } - if v.AlarmConfiguration != nil { - if err := validateAlarmConfiguration(v.AlarmConfiguration); err != nil { - invalidParams.AddNested("AlarmConfiguration", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateManagedInstanceRoleInput(v *UpdateManagedInstanceRoleInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateManagedInstanceRoleInput"} - if v.InstanceId == nil { - invalidParams.Add(smithy.NewErrParamRequired("InstanceId")) - } - if v.IamRole == nil { - invalidParams.Add(smithy.NewErrParamRequired("IamRole")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateOpsItemInput(v *UpdateOpsItemInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateOpsItemInput"} - if v.RelatedOpsItems != nil { - if err := validateRelatedOpsItems(v.RelatedOpsItems); err != nil { - invalidParams.AddNested("RelatedOpsItems", err.(smithy.InvalidParamsError)) - } - } - if v.OpsItemId == nil { - invalidParams.Add(smithy.NewErrParamRequired("OpsItemId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateOpsMetadataInput(v *UpdateOpsMetadataInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateOpsMetadataInput"} - if v.OpsMetadataArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("OpsMetadataArn")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdatePatchBaselineInput(v *UpdatePatchBaselineInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdatePatchBaselineInput"} - if v.BaselineId == nil { - invalidParams.Add(smithy.NewErrParamRequired("BaselineId")) - } - if v.GlobalFilters != nil { - if err := validatePatchFilterGroup(v.GlobalFilters); err != nil { - invalidParams.AddNested("GlobalFilters", err.(smithy.InvalidParamsError)) - } - } - if v.ApprovalRules != nil { - if err := validatePatchRuleGroup(v.ApprovalRules); err != nil { - invalidParams.AddNested("ApprovalRules", err.(smithy.InvalidParamsError)) - } - } - if v.Sources != nil { - if err := validatePatchSourceList(v.Sources); err != nil { - invalidParams.AddNested("Sources", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateResourceDataSyncInput(v *UpdateResourceDataSyncInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateResourceDataSyncInput"} - if v.SyncName == nil { - invalidParams.Add(smithy.NewErrParamRequired("SyncName")) - } - if v.SyncType == nil { - invalidParams.Add(smithy.NewErrParamRequired("SyncType")) - } - if v.SyncSource == nil { - invalidParams.Add(smithy.NewErrParamRequired("SyncSource")) - } else if v.SyncSource != nil { - if err := validateResourceDataSyncSource(v.SyncSource); err != nil { - invalidParams.AddNested("SyncSource", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpUpdateServiceSettingInput(v *UpdateServiceSettingInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "UpdateServiceSettingInput"} - if v.SettingId == nil { - invalidParams.Add(smithy.NewErrParamRequired("SettingId")) - } - if v.SettingValue == nil { - invalidParams.Add(smithy.NewErrParamRequired("SettingValue")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} 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 deleted file mode 100644 index 46dea1b5..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/CHANGELOG.md +++ /dev/null @@ -1,378 +0,0 @@ -# v1.18.7 (2024-01-18) - -* No change notes available for this release. - -# v1.18.6 (2024-01-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.5 (2023-12-08) - -* **Bug Fix**: Reinstate presence of default Retryer in functional options, but still respect max attempts set therein. - -# v1.18.4 (2023-12-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.3 (2023-12-06) - -* **Bug Fix**: Restore pre-refactor auth behavior where all operations could technically be performed anonymously. - -# v1.18.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.18.1 (2023-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.0 (2023-11-29) - -* **Feature**: Expose Options() accessor on service clients. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.5 (2023-11-28.2) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.4 (2023-11-28) - -* **Bug Fix**: Respect setting RetryMaxAttempts in functional options at client construction. - -# v1.17.3 (2023-11-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.2 (2023-11-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.1 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.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.16.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.15.2 (2023-10-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.1 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.0 (2023-10-02) - -* **Feature**: Fix FIPS Endpoints in aws-us-gov. - -# v1.14.1 (2023-09-22) - -* No change notes available for this release. - -# v1.14.0 (2023-09-18) - -* **Announcement**: [BREAKFIX] Change in MaxResults datatype from value to pointer type in cognito-sync service. -* **Feature**: Adds several endpoint ruleset changes across all models: smaller rulesets, removed non-unique regional endpoints, fixes FIPS and DualStack endpoints, and make region not required in SDK::Endpoint. Additional breakfix to cognito-sync field. - -# v1.13.6 (2023-08-31) - -* No change notes available for this release. - -# v1.13.5 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.4 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.3 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.2 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.1 (2023-08-01) - -* No change notes available for this release. - -# v1.13.0 (2023-07-31) - -* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.14 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.13 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.12 (2023-06-15) - -* No change notes available for this release. - -# v1.12.11 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.10 (2023-05-04) - -* No change notes available for this release. - -# v1.12.9 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.8 (2023-04-10) - -* No change notes available for this release. - -# v1.12.7 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.6 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.5 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.4 (2023-02-22) - -* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes. - -# v1.12.3 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.2 (2023-02-15) - -* **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. -* **Bug Fix**: Correct error type parsing for restJson services. - -# v1.12.1 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2023-01-05) - -* **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - -# v1.11.28 (2022-12-20) - -* No change notes available for this release. - -# v1.11.27 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.26 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.25 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.24 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.23 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.22 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.21 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.20 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.19 (2022-08-30) - -* **Documentation**: Documentation updates for the AWS IAM Identity Center Portal CLI Reference. - -# v1.11.18 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.17 (2022-08-15) - -* **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) - -# v1.11.16 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.15 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.14 (2022-08-08) - -* **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.13 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.12 (2022-07-11) - -* No change notes available for this release. - -# v1.11.11 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.10 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.9 (2022-06-16) - -* No change notes available for this release. - -# v1.11.8 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.7 (2022-05-26) - -* No change notes available for this release. - -# v1.11.6 (2022-05-25) - -* No change notes available for this release. - -# v1.11.5 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2022-02-24) - -* **Feature**: API client updated -* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Documentation**: Updated API models -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2021-12-21) - -* **Feature**: API Paginators now support specifying the initial starting token, and support stopping on empty string tokens. - -# v1.6.2 (2021-12-02) - -* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514)) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Feature**: Updated service to latest API model. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.2 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.1 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.3 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.2 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.1 (2021-07-15) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/service/sso/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go deleted file mode 100644 index e4396992..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_client.go +++ /dev/null @@ -1,475 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/defaults" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "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" - smithy "github.com/aws/smithy-go" - smithydocument "github.com/aws/smithy-go/document" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net" - "net/http" - "time" -) - -const ServiceID = "SSO" -const ServiceAPIVersion = "2019-06-10" - -// Client provides the API client to make operations call for AWS Single Sign-On. -type Client struct { - options Options -} - -// 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() - - resolveDefaultLogger(&options) - - setResolvedDefaultsMode(&options) - - resolveRetryer(&options) - - resolveHTTPClient(&options) - - resolveHTTPSignerV4(&options) - - resolveEndpointResolverV2(&options) - - resolveAuthSchemeResolver(&options) - - for _, fn := range optFns { - fn(&options) - } - - finalizeRetryMaxAttempts(&options) - - ignoreAnonymousAuth(&options) - - wrapWithAnonymousAuth(&options) - - resolveAuthSchemes(&options) - - client := &Client{ - options: options, - } - - return client -} - -// 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) { - ctx = middleware.ClearStackValues(ctx) - stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) - options := c.options.Copy() - - for _, fn := range optFns { - fn(&options) - } - - finalizeOperationRetryMaxAttempts(&options, *c) - - finalizeClientEndpointResolverOptions(&options) - - for _, fn := range stackFns { - if err := fn(stack, options); err != nil { - return nil, metadata, err - } - } - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, metadata, err - } - } - - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) - if err != nil { - err = &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: err, - } - } - 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{}, "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 { - LegacyResolver EndpointResolver -} - -func (*legacyEndpointContextSetter) ID() string { - return "legacyEndpointContextSetter" -} - -func (m *legacyEndpointContextSetter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.LegacyResolver != nil { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true) - } - - return next.HandleInitialize(ctx, in) - -} -func addlegacyEndpointContextSetter(stack *middleware.Stack, o Options) error { - return stack.Initialize.Add(&legacyEndpointContextSetter{ - LegacyResolver: o.EndpointResolver, - }, middleware.Before) -} - -func resolveDefaultLogger(o *Options) { - if o.Logger != nil { - return - } - o.Logger = logging.Nop{} -} - -func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { - return middleware.AddSetLoggerMiddleware(stack, o.Logger) -} - -func setResolvedDefaultsMode(o *Options) { - if len(o.resolvedDefaultsMode) > 0 { - return - } - - var mode aws.DefaultsMode - mode.SetFromString(string(o.DefaultsMode)) - - if mode == aws.DefaultsModeAuto { - mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment) - } - - o.resolvedDefaultsMode = mode -} - -// NewFromConfig returns a new client from the provided config. -func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { - opts := Options{ - Region: cfg.Region, - DefaultsMode: cfg.DefaultsMode, - RuntimeEnvironment: cfg.RuntimeEnvironment, - HTTPClient: cfg.HTTPClient, - Credentials: cfg.Credentials, - APIOptions: cfg.APIOptions, - Logger: cfg.Logger, - ClientLogMode: cfg.ClientLogMode, - AppID: cfg.AppID, - } - resolveAWSRetryerProvider(cfg, &opts) - resolveAWSRetryMaxAttempts(cfg, &opts) - resolveAWSRetryMode(cfg, &opts) - resolveAWSEndpointResolver(cfg, &opts) - resolveUseDualStackEndpoint(cfg, &opts) - resolveUseFIPSEndpoint(cfg, &opts) - resolveBaseEndpoint(cfg, &opts) - return New(opts, optFns...) -} - -func resolveHTTPClient(o *Options) { - var buildable *awshttp.BuildableClient - - if o.HTTPClient != nil { - var ok bool - buildable, ok = o.HTTPClient.(*awshttp.BuildableClient) - if !ok { - return - } - } else { - buildable = awshttp.NewBuildableClient() - } - - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) { - if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok { - dialer.Timeout = dialerTimeout - } - }) - - buildable = buildable.WithTransportOptions(func(transport *http.Transport) { - if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok { - transport.TLSHandshakeTimeout = tlsHandshakeTimeout - } - }) - } - - o.HTTPClient = buildable -} - -func resolveRetryer(o *Options) { - if o.Retryer != nil { - return - } - - if len(o.RetryMode) == 0 { - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - o.RetryMode = modeConfig.RetryMode - } - } - if len(o.RetryMode) == 0 { - o.RetryMode = aws.RetryModeStandard - } - - var standardOptions []func(*retry.StandardOptions) - if v := o.RetryMaxAttempts; v != 0 { - standardOptions = append(standardOptions, func(so *retry.StandardOptions) { - so.MaxAttempts = v - }) - } - - switch o.RetryMode { - case aws.RetryModeAdaptive: - var adaptiveOptions []func(*retry.AdaptiveModeOptions) - if len(standardOptions) != 0 { - adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) { - ao.StandardOptions = append(ao.StandardOptions, standardOptions...) - }) - } - o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...) - - default: - o.Retryer = retry.NewStandard(standardOptions...) - } -} - -func resolveAWSRetryerProvider(cfg aws.Config, o *Options) { - if cfg.Retryer == nil { - return - } - o.Retryer = cfg.Retryer() -} - -func resolveAWSRetryMode(cfg aws.Config, o *Options) { - if len(cfg.RetryMode) == 0 { - return - } - o.RetryMode = cfg.RetryMode -} -func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { - if cfg.RetryMaxAttempts == 0 { - return - } - o.RetryMaxAttempts = cfg.RetryMaxAttempts -} - -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 - } - - o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) -} - -func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { - if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil { - return - } - o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions) -} - -func addClientUserAgent(stack *middleware.Stack, options Options) error { - if err := awsmiddleware.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "sso", goModuleVersion)(stack); err != nil { - return err - } - - if len(options.AppID) > 0 { - return awsmiddleware.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID)(stack) - } - - return nil -} - -type HTTPSignerV4 interface { - SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error -} - -func resolveHTTPSignerV4(o *Options) { - if o.HTTPSignerV4 != nil { - return - } - o.HTTPSignerV4 = newDefaultV4Signer(*o) -} - -func newDefaultV4Signer(o Options) *v4.Signer { - return v4.NewSigner(func(so *v4.SignerOptions) { - so.Logger = o.Logger - so.LogSigning = o.ClientLogMode.IsSigning() - }) -} - -func addRetryMiddlewares(stack *middleware.Stack, o Options) error { - mo := retry.AddRetryMiddlewaresOptions{ - Retryer: o.Retryer, - LogRetryAttempts: o.ClientLogMode.IsRetries(), - } - return retry.AddRetryMiddlewares(stack, mo) -} - -// resolves dual-stack endpoint configuration -func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseDualStackEndpoint = value - } - return nil -} - -// resolves FIPS endpoint configuration -func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseFIPSEndpoint = value - } - return nil -} - -func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - return awsmiddleware.AddRequestIDRetrieverMiddleware(stack) -} - -func addResponseErrorMiddleware(stack *middleware.Stack) error { - return awshttp.AddResponseErrorMiddleware(stack) -} - -func addRequestResponseLogging(stack *middleware.Stack, o Options) error { - return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ - LogRequest: o.ClientLogMode.IsRequest(), - LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(), - LogResponse: o.ClientLogMode.IsResponse(), - LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(), - }, middleware.After) -} - -type disableHTTPSMiddleware struct { - DisableHTTPS bool -} - -func (*disableHTTPSMiddleware) ID() string { - return "disableHTTPS" -} - -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.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) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_GetRoleCredentials.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_GetRoleCredentials.go deleted file mode 100644 index 436eadc8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_GetRoleCredentials.go +++ /dev/null @@ -1,146 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/service/sso/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns the STS short-term credentials for a given role name that is assigned -// to the user. -func (c *Client) GetRoleCredentials(ctx context.Context, params *GetRoleCredentialsInput, optFns ...func(*Options)) (*GetRoleCredentialsOutput, error) { - if params == nil { - params = &GetRoleCredentialsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetRoleCredentials", params, optFns, c.addOperationGetRoleCredentialsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetRoleCredentialsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetRoleCredentialsInput struct { - - // The token issued by the CreateToken API call. For more information, see - // CreateToken (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // This member is required. - AccessToken *string - - // The identifier for the AWS account that is assigned to the user. - // - // This member is required. - AccountId *string - - // The friendly name of the role that is assigned to the user. - // - // This member is required. - RoleName *string - - noSmithyDocumentSerde -} - -type GetRoleCredentialsOutput struct { - - // The credentials for the role that is assigned to the user. - RoleCredentials *types.RoleCredentials - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetRoleCredentialsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsRestjson1_serializeOpGetRoleCredentials{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpGetRoleCredentials{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetRoleCredentials"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetRoleCredentialsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetRoleCredentials(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetRoleCredentials(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetRoleCredentials", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccountRoles.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccountRoles.go deleted file mode 100644 index d81b0677..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccountRoles.go +++ /dev/null @@ -1,241 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/service/sso/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists all roles that are assigned to the user for a given AWS account. -func (c *Client) ListAccountRoles(ctx context.Context, params *ListAccountRolesInput, optFns ...func(*Options)) (*ListAccountRolesOutput, error) { - if params == nil { - params = &ListAccountRolesInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListAccountRoles", params, optFns, c.addOperationListAccountRolesMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListAccountRolesOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListAccountRolesInput struct { - - // The token issued by the CreateToken API call. For more information, see - // CreateToken (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // This member is required. - AccessToken *string - - // The identifier for the AWS account that is assigned to the user. - // - // This member is required. - AccountId *string - - // The number of items that clients can request per page. - MaxResults *int32 - - // The page token from the previous response output when you request subsequent - // pages. - NextToken *string - - noSmithyDocumentSerde -} - -type ListAccountRolesOutput struct { - - // The page token client that is used to retrieve the list of accounts. - NextToken *string - - // A paginated response with the list of roles and the next token if more results - // are available. - RoleList []types.RoleInfo - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListAccountRolesMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsRestjson1_serializeOpListAccountRoles{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpListAccountRoles{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListAccountRoles"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListAccountRolesValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListAccountRoles(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListAccountRolesAPIClient is a client that implements the ListAccountRoles -// operation. -type ListAccountRolesAPIClient interface { - ListAccountRoles(context.Context, *ListAccountRolesInput, ...func(*Options)) (*ListAccountRolesOutput, error) -} - -var _ ListAccountRolesAPIClient = (*Client)(nil) - -// ListAccountRolesPaginatorOptions is the paginator options for ListAccountRoles -type ListAccountRolesPaginatorOptions struct { - // The number of items that clients can request per page. - 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 -} - -// ListAccountRolesPaginator is a paginator for ListAccountRoles -type ListAccountRolesPaginator struct { - options ListAccountRolesPaginatorOptions - client ListAccountRolesAPIClient - params *ListAccountRolesInput - nextToken *string - firstPage bool -} - -// NewListAccountRolesPaginator returns a new ListAccountRolesPaginator -func NewListAccountRolesPaginator(client ListAccountRolesAPIClient, params *ListAccountRolesInput, optFns ...func(*ListAccountRolesPaginatorOptions)) *ListAccountRolesPaginator { - if params == nil { - params = &ListAccountRolesInput{} - } - - options := ListAccountRolesPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListAccountRolesPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListAccountRolesPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListAccountRoles page. -func (p *ListAccountRolesPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListAccountRolesOutput, 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 - - result, err := p.client.ListAccountRoles(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 -} - -func newServiceMetadataMiddleware_opListAccountRoles(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListAccountRoles", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccounts.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccounts.go deleted file mode 100644 index 38f8472a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_ListAccounts.go +++ /dev/null @@ -1,238 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/service/sso/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Lists all AWS accounts assigned to the user. These AWS accounts are assigned by -// the administrator of the account. For more information, see Assign User Access (https://docs.aws.amazon.com/singlesignon/latest/userguide/useraccess.html#assignusers) -// in the IAM Identity Center User Guide. This operation returns a paginated -// response. -func (c *Client) ListAccounts(ctx context.Context, params *ListAccountsInput, optFns ...func(*Options)) (*ListAccountsOutput, error) { - if params == nil { - params = &ListAccountsInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "ListAccounts", params, optFns, c.addOperationListAccountsMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*ListAccountsOutput) - out.ResultMetadata = metadata - return out, nil -} - -type ListAccountsInput struct { - - // The token issued by the CreateToken API call. For more information, see - // CreateToken (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // This member is required. - AccessToken *string - - // This is the number of items clients can request per page. - MaxResults *int32 - - // (Optional) When requesting subsequent pages, this is the page token from the - // previous response output. - NextToken *string - - noSmithyDocumentSerde -} - -type ListAccountsOutput struct { - - // A paginated response with the list of account information and the next token if - // more results are available. - AccountList []types.AccountInfo - - // The page token client that is used to retrieve the list of accounts. - NextToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationListAccountsMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsRestjson1_serializeOpListAccounts{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpListAccounts{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "ListAccounts"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpListAccountsValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opListAccounts(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -// ListAccountsAPIClient is a client that implements the ListAccounts operation. -type ListAccountsAPIClient interface { - ListAccounts(context.Context, *ListAccountsInput, ...func(*Options)) (*ListAccountsOutput, error) -} - -var _ ListAccountsAPIClient = (*Client)(nil) - -// ListAccountsPaginatorOptions is the paginator options for ListAccounts -type ListAccountsPaginatorOptions struct { - // This is the number of items clients can request per page. - 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 -} - -// ListAccountsPaginator is a paginator for ListAccounts -type ListAccountsPaginator struct { - options ListAccountsPaginatorOptions - client ListAccountsAPIClient - params *ListAccountsInput - nextToken *string - firstPage bool -} - -// NewListAccountsPaginator returns a new ListAccountsPaginator -func NewListAccountsPaginator(client ListAccountsAPIClient, params *ListAccountsInput, optFns ...func(*ListAccountsPaginatorOptions)) *ListAccountsPaginator { - if params == nil { - params = &ListAccountsInput{} - } - - options := ListAccountsPaginatorOptions{} - if params.MaxResults != nil { - options.Limit = *params.MaxResults - } - - for _, fn := range optFns { - fn(&options) - } - - return &ListAccountsPaginator{ - options: options, - client: client, - params: params, - firstPage: true, - nextToken: params.NextToken, - } -} - -// HasMorePages returns a boolean indicating whether more pages are available -func (p *ListAccountsPaginator) HasMorePages() bool { - return p.firstPage || (p.nextToken != nil && len(*p.nextToken) != 0) -} - -// NextPage retrieves the next ListAccounts page. -func (p *ListAccountsPaginator) NextPage(ctx context.Context, optFns ...func(*Options)) (*ListAccountsOutput, 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 - - result, err := p.client.ListAccounts(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 -} - -func newServiceMetadataMiddleware_opListAccounts(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "ListAccounts", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_Logout.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_Logout.go deleted file mode 100644 index 82e98a89..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/api_op_Logout.go +++ /dev/null @@ -1,141 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -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" -) - -// Removes the locally stored SSO tokens from the client-side cache and sends an -// API call to the IAM Identity Center service to invalidate the corresponding -// server-side IAM Identity Center sign in session. If a user uses IAM Identity -// Center to access the AWS CLI, the user’s IAM Identity Center sign in session is -// used to obtain an IAM session, as specified in the corresponding IAM Identity -// Center permission set. More specifically, IAM Identity Center assumes an IAM -// role in the target account on behalf of the user, and the corresponding -// temporary AWS credentials are returned to the client. After user logout, any -// existing IAM role sessions that were created by using IAM Identity Center -// permission sets continue based on the duration configured in the permission set. -// For more information, see User authentications (https://docs.aws.amazon.com/singlesignon/latest/userguide/authconcept.html) -// in the IAM Identity Center User Guide. -func (c *Client) Logout(ctx context.Context, params *LogoutInput, optFns ...func(*Options)) (*LogoutOutput, error) { - if params == nil { - params = &LogoutInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "Logout", params, optFns, c.addOperationLogoutMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*LogoutOutput) - out.ResultMetadata = metadata - return out, nil -} - -type LogoutInput struct { - - // The token issued by the CreateToken API call. For more information, see - // CreateToken (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/API_CreateToken.html) - // in the IAM Identity Center OIDC API Reference Guide. - // - // This member is required. - AccessToken *string - - noSmithyDocumentSerde -} - -type LogoutOutput struct { - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationLogoutMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsRestjson1_serializeOpLogout{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpLogout{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "Logout"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpLogoutValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opLogout(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opLogout(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "Logout", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/auth.go deleted file mode 100644 index 3b28e825..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/auth.go +++ /dev/null @@ -1,308 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -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/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -func bindAuthParamsRegion(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(operation string, input interface{}, options Options) *AuthResolverParameters { - params := &AuthResolverParameters{ - Operation: operation, - } - - bindAuthParamsRegion(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{ - "GetRoleCredentials": func(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - {SchemeID: smithyauth.SchemeIDAnonymous}, - } - }, - - "ListAccountRoles": func(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - {SchemeID: smithyauth.SchemeIDAnonymous}, - } - }, - - "ListAccounts": func(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - {SchemeID: smithyauth.SchemeIDAnonymous}, - } - }, - - "Logout": func(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - {SchemeID: smithyauth.SchemeIDAnonymous}, - } - }, -} - -func serviceAuthOptions(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - { - SchemeID: smithyauth.SchemeIDSigV4, - SignerProperties: func() smithy.Properties { - var props smithy.Properties - smithyhttp.SetSigV4SigningName(&props, "awsssoportal") - 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, -) { - params := bindAuthResolverParams(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) - 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, -) { - rscheme := getResolvedAuthScheme(ctx) - 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 := resolver.GetIdentity(ctx, rscheme.IdentityProperties) - if err != nil { - return out, metadata, fmt.Errorf("get identity: %w", err) - } - - ctx = setIdentity(ctx, identity) - 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 { -} - -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, -) { - 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") - } - - if err := signer.SignRequest(ctx, req, identity, rscheme.SignerProperties); err != nil { - return out, metadata, fmt.Errorf("sign request: %w", err) - } - - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/deserializers.go deleted file mode 100644 index 8bba205f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/deserializers.go +++ /dev/null @@ -1,1151 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws/protocol/restjson" - "github.com/aws/aws-sdk-go-v2/service/sso/types" - smithy "github.com/aws/smithy-go" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/ptr" - smithyhttp "github.com/aws/smithy-go/transport/http" - "io" - "io/ioutil" - "strings" -) - -type awsRestjson1_deserializeOpGetRoleCredentials struct { -} - -func (*awsRestjson1_deserializeOpGetRoleCredentials) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpGetRoleCredentials) 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 - } - - 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, awsRestjson1_deserializeOpErrorGetRoleCredentials(response, &metadata) - } - output := &GetRoleCredentialsOutput{} - 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 = awsRestjson1_deserializeOpDocumentGetRoleCredentialsOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorGetRoleCredentials(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsRestjson1_deserializeErrorResourceNotFoundException(response, errorBody) - - case strings.EqualFold("TooManyRequestsException", errorCode): - return awsRestjson1_deserializeErrorTooManyRequestsException(response, errorBody) - - case strings.EqualFold("UnauthorizedException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentGetRoleCredentialsOutput(v **GetRoleCredentialsOutput, 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 *GetRoleCredentialsOutput - if *v == nil { - sv = &GetRoleCredentialsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "roleCredentials": - if err := awsRestjson1_deserializeDocumentRoleCredentials(&sv.RoleCredentials, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -type awsRestjson1_deserializeOpListAccountRoles struct { -} - -func (*awsRestjson1_deserializeOpListAccountRoles) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpListAccountRoles) 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 - } - - 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, awsRestjson1_deserializeOpErrorListAccountRoles(response, &metadata) - } - output := &ListAccountRolesOutput{} - 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 = awsRestjson1_deserializeOpDocumentListAccountRolesOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorListAccountRoles(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsRestjson1_deserializeErrorResourceNotFoundException(response, errorBody) - - case strings.EqualFold("TooManyRequestsException", errorCode): - return awsRestjson1_deserializeErrorTooManyRequestsException(response, errorBody) - - case strings.EqualFold("UnauthorizedException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentListAccountRolesOutput(v **ListAccountRolesOutput, 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 *ListAccountRolesOutput - if *v == nil { - sv = &ListAccountRolesOutput{} - } 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 NextTokenType to be of type string, got %T instead", value) - } - sv.NextToken = ptr.String(jtv) - } - - case "roleList": - if err := awsRestjson1_deserializeDocumentRoleListType(&sv.RoleList, value); err != nil { - return err - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -type awsRestjson1_deserializeOpListAccounts struct { -} - -func (*awsRestjson1_deserializeOpListAccounts) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpListAccounts) 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 - } - - 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, awsRestjson1_deserializeOpErrorListAccounts(response, &metadata) - } - output := &ListAccountsOutput{} - 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 = awsRestjson1_deserializeOpDocumentListAccountsOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorListAccounts(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("ResourceNotFoundException", errorCode): - return awsRestjson1_deserializeErrorResourceNotFoundException(response, errorBody) - - case strings.EqualFold("TooManyRequestsException", errorCode): - return awsRestjson1_deserializeErrorTooManyRequestsException(response, errorBody) - - case strings.EqualFold("UnauthorizedException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentListAccountsOutput(v **ListAccountsOutput, 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 *ListAccountsOutput - if *v == nil { - sv = &ListAccountsOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "accountList": - if err := awsRestjson1_deserializeDocumentAccountListType(&sv.AccountList, value); err != nil { - return err - } - - case "nextToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected NextTokenType to be of type string, got %T instead", value) - } - sv.NextToken = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -type awsRestjson1_deserializeOpLogout struct { -} - -func (*awsRestjson1_deserializeOpLogout) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpLogout) 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 - } - - 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, awsRestjson1_deserializeOpErrorLogout(response, &metadata) - } - output := &LogoutOutput{} - out.Result = output - - if _, err = io.Copy(ioutil.Discard, response.Body); err != nil { - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to discard response body, %w", err), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorLogout(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("TooManyRequestsException", errorCode): - return awsRestjson1_deserializeErrorTooManyRequestsException(response, errorBody) - - case strings.EqualFold("UnauthorizedException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeErrorInvalidRequestException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidRequestException{} - 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 - } - - err := awsRestjson1_deserializeDocumentInvalidRequestException(&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 awsRestjson1_deserializeErrorResourceNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.ResourceNotFoundException{} - 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 - } - - err := awsRestjson1_deserializeDocumentResourceNotFoundException(&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 awsRestjson1_deserializeErrorTooManyRequestsException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.TooManyRequestsException{} - 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 - } - - err := awsRestjson1_deserializeDocumentTooManyRequestsException(&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 awsRestjson1_deserializeErrorUnauthorizedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.UnauthorizedException{} - 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 - } - - err := awsRestjson1_deserializeDocumentUnauthorizedException(&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 awsRestjson1_deserializeDocumentAccountInfo(v **types.AccountInfo, 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.AccountInfo - if *v == nil { - sv = &types.AccountInfo{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "accountId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccountIdType to be of type string, got %T instead", value) - } - sv.AccountId = ptr.String(jtv) - } - - case "accountName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccountNameType to be of type string, got %T instead", value) - } - sv.AccountName = ptr.String(jtv) - } - - case "emailAddress": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected EmailAddressType to be of type string, got %T instead", value) - } - sv.EmailAddress = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentAccountListType(v *[]types.AccountInfo, 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.AccountInfo - if *v == nil { - cv = []types.AccountInfo{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.AccountInfo - destAddr := &col - if err := awsRestjson1_deserializeDocumentAccountInfo(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidRequestException(v **types.InvalidRequestException, 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.InvalidRequestException - if *v == nil { - sv = &types.InvalidRequestException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentResourceNotFoundException(v **types.ResourceNotFoundException, 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.ResourceNotFoundException - if *v == nil { - sv = &types.ResourceNotFoundException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentRoleCredentials(v **types.RoleCredentials, 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.RoleCredentials - if *v == nil { - sv = &types.RoleCredentials{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "accessKeyId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccessKeyType to be of type string, got %T instead", value) - } - sv.AccessKeyId = ptr.String(jtv) - } - - case "expiration": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ExpirationTimestampType to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Expiration = i64 - } - - case "secretAccessKey": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SecretAccessKeyType to be of type string, got %T instead", value) - } - sv.SecretAccessKey = ptr.String(jtv) - } - - case "sessionToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected SessionTokenType to be of type string, got %T instead", value) - } - sv.SessionToken = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentRoleInfo(v **types.RoleInfo, 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.RoleInfo - if *v == nil { - sv = &types.RoleInfo{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "accountId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccountIdType to be of type string, got %T instead", value) - } - sv.AccountId = ptr.String(jtv) - } - - case "roleName": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RoleNameType to be of type string, got %T instead", value) - } - sv.RoleName = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentRoleListType(v *[]types.RoleInfo, 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.RoleInfo - if *v == nil { - cv = []types.RoleInfo{} - } else { - cv = *v - } - - for _, value := range shape { - var col types.RoleInfo - destAddr := &col - if err := awsRestjson1_deserializeDocumentRoleInfo(&destAddr, value); err != nil { - return err - } - col = *destAddr - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsRestjson1_deserializeDocumentTooManyRequestsException(v **types.TooManyRequestsException, 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.TooManyRequestsException - if *v == nil { - sv = &types.TooManyRequestsException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentUnauthorizedException(v **types.UnauthorizedException, 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.UnauthorizedException - if *v == nil { - sv = &types.UnauthorizedException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "message": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Message = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/doc.go deleted file mode 100644 index 59456d5d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/doc.go +++ /dev/null @@ -1,21 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -// Package sso provides the API client, operations, and parameter types for AWS -// Single Sign-On. -// -// AWS IAM Identity Center (successor to AWS Single Sign-On) Portal is a web -// service that makes it easy for you to assign user access to IAM Identity Center -// resources such as the AWS access portal. Users can get AWS account applications -// and roles assigned to them and get federated into the application. Although AWS -// Single Sign-On was renamed, the sso and identitystore API namespaces will -// continue to retain their original name for backward compatibility purposes. For -// more information, see IAM Identity Center rename (https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html#renamed) -// . This reference guide describes the IAM Identity Center Portal operations that -// you can call programatically and includes detailed information on data types and -// errors. AWS provides SDKs that consist of libraries and sample code for various -// programming languages and platforms, such as Java, Ruby, .Net, iOS, or Android. -// The SDKs provide a convenient way to create programmatic access to IAM Identity -// Center and other AWS services. For more information about the AWS SDKs, -// including how to download and install them, see Tools for Amazon Web Services (http://aws.amazon.com/tools/) -// . -package sso diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/endpoints.go deleted file mode 100644 index d31380cf..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/endpoints.go +++ /dev/null @@ -1,528 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "errors" - "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/sso/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" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net/http" - "net/url" - "os" - "strings" -) - -// EndpointResolverOptions is the service endpoint resolver options -type EndpointResolverOptions = internalendpoints.Options - -// EndpointResolver interface for resolving service endpoints. -type EndpointResolver interface { - ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) -} - -var _ EndpointResolver = &internalendpoints.Resolver{} - -// NewDefaultEndpointResolver constructs a new service endpoint resolver -func NewDefaultEndpointResolver() *internalendpoints.Resolver { - return internalendpoints.New() -} - -// EndpointResolverFunc is a helper utility that wraps a function so it satisfies -// the EndpointResolver interface. This is useful when you want to add additional -// endpoint resolving logic, or stub out specific endpoints with custom values. -type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) - -func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return fn(region, options) -} - -// EndpointResolverFromURL returns an EndpointResolver configured using the -// provided endpoint url. By default, the resolved endpoint resolver uses the -// client region as signing region, and the endpoint source is set to -// EndpointSourceCustom.You can provide functional options to configure endpoint -// values for the resolved endpoint. -func EndpointResolverFromURL(url string, optFns ...func(*aws.Endpoint)) EndpointResolver { - e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom} - for _, fn := range optFns { - fn(&e) - } - - return EndpointResolverFunc( - func(region string, options EndpointResolverOptions) (aws.Endpoint, error) { - if len(e.SigningRegion) == 0 { - e.SigningRegion = region - } - return e, nil - }, - ) -} - -type ResolveEndpoint struct { - Resolver EndpointResolver - Options EndpointResolverOptions -} - -func (*ResolveEndpoint) ID() string { - return "ResolveEndpoint" -} - -func (m *ResolveEndpoint) 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.Resolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - eo := m.Options - eo.Logger = middleware.GetLogger(ctx) - - var endpoint aws.Endpoint - endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), eo) - if err != nil { - nf := (&aws.EndpointNotFoundError{}) - if errors.As(err, &nf) { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, false) - return next.HandleSerialize(ctx, in) - } - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL, err = url.Parse(endpoint.URL) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) - } - - if len(awsmiddleware.GetSigningName(ctx)) == 0 { - signingName := endpoint.SigningName - if len(signingName) == 0 { - signingName = "awsssoportal" - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - } - ctx = awsmiddleware.SetEndpointSource(ctx, endpoint.Source) - ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) - ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) - ctx = awsmiddleware.SetPartitionID(ctx, endpoint.PartitionID) - return next.HandleSerialize(ctx, in) -} -func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&ResolveEndpoint{ - Resolver: o.EndpointResolver, - Options: o.EndpointOptions, - }, "OperationSerializer", middleware.Before) -} - -func removeResolveEndpointMiddleware(stack *middleware.Stack) error { - _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) - return err -} - -type wrappedEndpointResolver struct { - awsResolver aws.EndpointResolverWithOptions -} - -func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return w.awsResolver.ResolveEndpoint(ServiceID, region, options) -} - -type awsEndpointResolverAdaptor func(service, region string) (aws.Endpoint, error) - -func (a awsEndpointResolverAdaptor) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { - return a(service, region) -} - -var _ aws.EndpointResolverWithOptions = awsEndpointResolverAdaptor(nil) - -// withEndpointResolver returns an aws.EndpointResolverWithOptions that first delegates endpoint resolution to the awsResolver. -// If awsResolver returns aws.EndpointNotFoundError error, the v1 resolver middleware will swallow the error, -// and set an appropriate context flag such that fallback will occur when EndpointResolverV2 is invoked -// via its middleware. -// -// If another error (besides aws.EndpointNotFoundError) is returned, then that error will be propagated. -func withEndpointResolver(awsResolver aws.EndpointResolver, awsResolverWithOptions aws.EndpointResolverWithOptions) EndpointResolver { - var resolver aws.EndpointResolverWithOptions - - if awsResolverWithOptions != nil { - resolver = awsResolverWithOptions - } else if awsResolver != nil { - resolver = awsEndpointResolverAdaptor(awsResolver.ResolveEndpoint) - } - - return &wrappedEndpointResolver{ - awsResolver: resolver, - } -} - -func finalizeClientEndpointResolverOptions(options *Options) { - options.EndpointOptions.LogDeprecated = options.ClientLogMode.IsDeprecatedUsage() - - if len(options.EndpointOptions.ResolvedRegion) == 0 { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(options.Region, fipsInfix) || - strings.Contains(options.Region, fipsPrefix) || - strings.Contains(options.Region, fipsSuffix) { - options.EndpointOptions.ResolvedRegion = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - options.Region, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - options.EndpointOptions.UseFIPSEndpoint = aws.FIPSEndpointStateEnabled - } - } - -} - -func resolveEndpointResolverV2(options *Options) { - if options.EndpointResolverV2 == nil { - options.EndpointResolverV2 = NewDefaultEndpointResolverV2() - } -} - -func resolveBaseEndpoint(cfg aws.Config, o *Options) { - if cfg.BaseEndpoint != nil { - o.BaseEndpoint = cfg.BaseEndpoint - } - - _, g := os.LookupEnv("AWS_ENDPOINT_URL") - _, s := os.LookupEnv("AWS_ENDPOINT_URL_SSO") - - if g && !s { - return - } - - value, found, err := internalConfig.ResolveServiceBaseEndpoint(context.Background(), "SSO", cfg.ConfigSources) - if found && err == nil { - o.BaseEndpoint = &value - } -} - -// EndpointParameters provides the parameters that influence how endpoints are -// resolved. -type EndpointParameters struct { - // The AWS region used to dispatch the request. - // - // Parameter is - // required. - // - // AWS::Region - Region *string - - // When true, use the dual-stack endpoint. If the configured endpoint does not - // support dual-stack, dispatching the request MAY return an error. - // - // Defaults to - // false if no value is provided. - // - // AWS::UseDualStack - UseDualStack *bool - - // When true, send this request to the FIPS-compliant regional endpoint. If the - // configured endpoint does not have a FIPS compliant endpoint, dispatching the - // request will return an error. - // - // Defaults to false if no value is - // provided. - // - // AWS::UseFIPS - UseFIPS *bool - - // Override the endpoint used to send this request - // - // Parameter is - // required. - // - // SDK::Endpoint - Endpoint *string -} - -// ValidateRequired validates required parameters are set. -func (p EndpointParameters) ValidateRequired() error { - if p.UseDualStack == nil { - return fmt.Errorf("parameter UseDualStack is required") - } - - if p.UseFIPS == nil { - return fmt.Errorf("parameter UseFIPS is required") - } - - return nil -} - -// WithDefaults returns a shallow copy of EndpointParameterswith default values -// applied to members where applicable. -func (p EndpointParameters) WithDefaults() EndpointParameters { - if p.UseDualStack == nil { - p.UseDualStack = ptr.Bool(false) - } - - if p.UseFIPS == nil { - p.UseFIPS = ptr.Bool(false) - } - return p -} - -// EndpointResolverV2 provides the interface for resolving service endpoints. -type EndpointResolverV2 interface { - // ResolveEndpoint attempts to resolve the endpoint with the provided options, - // returning the endpoint if found. Otherwise an error is returned. - ResolveEndpoint(ctx context.Context, params EndpointParameters) ( - smithyendpoints.Endpoint, error, - ) -} - -// resolver provides the implementation for resolving endpoints. -type resolver struct{} - -func NewDefaultEndpointResolverV2() EndpointResolverV2 { - return &resolver{} -} - -// ResolveEndpoint attempts to resolve the endpoint with the provided options, -// returning the endpoint if found. Otherwise an error is returned. -func (r *resolver) ResolveEndpoint( - ctx context.Context, params EndpointParameters, -) ( - endpoint smithyendpoints.Endpoint, err error, -) { - params = params.WithDefaults() - if err = params.ValidateRequired(); err != nil { - return endpoint, fmt.Errorf("endpoint parameters are not valid, %w", err) - } - _UseDualStack := *params.UseDualStack - _UseFIPS := *params.UseFIPS - - if exprVal := params.Endpoint; exprVal != nil { - _Endpoint := *exprVal - _ = _Endpoint - if _UseFIPS == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: FIPS and custom endpoint are not supported") - } - if _UseDualStack == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Dualstack and custom endpoint are not supported") - } - uriString := _Endpoint - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if exprVal := params.Region; exprVal != nil { - _Region := *exprVal - _ = _Region - if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { - _PartitionResult := *exprVal - _ = _PartitionResult - if _UseFIPS == true { - if _UseDualStack == true { - if true == _PartitionResult.SupportsFIPS { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://portal.sso-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS and DualStack are enabled, but this partition does not support one or both") - } - } - if _UseFIPS == true { - if true == _PartitionResult.SupportsFIPS { - if "aws-us-gov" == _PartitionResult.Name { - uriString := func() string { - var out strings.Builder - out.WriteString("https://portal.sso.") - out.WriteString(_Region) - out.WriteString(".amazonaws.com") - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://portal.sso-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS is enabled but this partition does not support FIPS") - } - if _UseDualStack == true { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://portal.sso.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "DualStack is enabled but this partition does not support DualStack") - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://portal.sso.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("Endpoint resolution failed. Invalid operation or environment input.") - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") -} - -type endpointParamsBinder interface { - bindEndpointParams(*EndpointParameters) -} - -func bindEndpointParams(input interface{}, options Options) *EndpointParameters { - params := &EndpointParameters{} - - params.Region = aws.String(endpoints.MapFIPSRegion(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, -) { - 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(getOperationInput(ctx), m.options) - endpt, err := m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - 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) - } - - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/generated.json deleted file mode 100644 index 53060bcc..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/generated.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "dependencies": { - "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" - }, - "files": [ - "api_client.go", - "api_client_test.go", - "api_op_GetRoleCredentials.go", - "api_op_ListAccountRoles.go", - "api_op_ListAccounts.go", - "api_op_Logout.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", - "types/errors.go", - "types/types.go", - "validators.go" - ], - "go": "1.15", - "module": "github.com/aws/aws-sdk-go-v2/service/sso", - "unstable": false -} 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 deleted file mode 100644 index 857a6af7..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package sso - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.18.7" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints/endpoints.go deleted file mode 100644 index c8f7c09e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/internal/endpoints/endpoints.go +++ /dev/null @@ -1,534 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package endpoints - -import ( - "github.com/aws/aws-sdk-go-v2/aws" - endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" - "github.com/aws/smithy-go/logging" - "regexp" -) - -// Options is the endpoint resolver configuration options -type Options struct { - // Logger is a logging implementation that log events should be sent to. - Logger logging.Logger - - // LogDeprecated indicates that deprecated endpoints should be logged to the - // provided logger. - LogDeprecated bool - - // ResolvedRegion is used to override the region to be resolved, rather then the - // using the value passed to the ResolveEndpoint method. This value is used by the - // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative - // name. You must not set this value directly in your application. - ResolvedRegion string - - // DisableHTTPS informs the resolver to return an endpoint that does not use the - // HTTPS scheme. - DisableHTTPS bool - - // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. - UseDualStackEndpoint aws.DualStackEndpointState - - // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. - UseFIPSEndpoint aws.FIPSEndpointState -} - -func (o Options) GetResolvedRegion() string { - return o.ResolvedRegion -} - -func (o Options) GetDisableHTTPS() bool { - return o.DisableHTTPS -} - -func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { - return o.UseDualStackEndpoint -} - -func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { - return o.UseFIPSEndpoint -} - -func transformToSharedOptions(options Options) endpoints.Options { - return endpoints.Options{ - Logger: options.Logger, - LogDeprecated: options.LogDeprecated, - ResolvedRegion: options.ResolvedRegion, - DisableHTTPS: options.DisableHTTPS, - UseDualStackEndpoint: options.UseDualStackEndpoint, - UseFIPSEndpoint: options.UseFIPSEndpoint, - } -} - -// Resolver SSO endpoint resolver -type Resolver struct { - partitions endpoints.Partitions -} - -// ResolveEndpoint resolves the service endpoint for the given region and options -func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { - if len(region) == 0 { - return endpoint, &aws.MissingRegionError{} - } - - opt := transformToSharedOptions(options) - return r.partitions.ResolveEndpoint(region, opt) -} - -// New returns a new Resolver -func New() *Resolver { - return &Resolver{ - partitions: defaultPartitions, - } -} - -var partitionRegexp = struct { - Aws *regexp.Regexp - AwsCn *regexp.Regexp - AwsIso *regexp.Regexp - AwsIsoB *regexp.Regexp - AwsIsoE *regexp.Regexp - AwsIsoF *regexp.Regexp - AwsUsGov *regexp.Regexp -}{ - - Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$"), - AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), - AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), - AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), - AwsIsoE: regexp.MustCompile("^eu\\-isoe\\-\\w+\\-\\d+$"), - AwsIsoF: regexp.MustCompile("^us\\-isof\\-\\w+\\-\\d+$"), - AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), -} - -var defaultPartitions = endpoints.Partitions{ - { - ID: "aws", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "portal.sso.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "portal.sso-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.Aws, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "af-south-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.af-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "af-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-east-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-northeast-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-2", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-northeast-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-2", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-3", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-northeast-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-3", - }, - }, - endpoints.EndpointKey{ - Region: "ap-south-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-southeast-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-2", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-southeast-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-2", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-3", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ap-southeast-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-3", - }, - }, - endpoints.EndpointKey{ - Region: "ca-central-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.ca-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ca-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-central-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-central-2", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-central-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-central-2", - }, - }, - endpoints.EndpointKey{ - Region: "eu-north-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-north-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-north-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-south-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-2", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-west-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-2", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-3", - }: endpoints.Endpoint{ - Hostname: "portal.sso.eu-west-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-3", - }, - }, - endpoints.EndpointKey{ - Region: "il-central-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.il-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "il-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "me-central-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.me-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "me-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "me-south-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.me-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "me-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "sa-east-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.sa-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "sa-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-east-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-east-2", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-east-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-2", - }, - }, - endpoints.EndpointKey{ - Region: "us-west-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-west-2", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-west-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - { - ID: "aws-cn", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "portal.sso.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "portal.sso-fips.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsCn, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "cn-north-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.cn-north-1.amazonaws.com.cn", - CredentialScope: endpoints.CredentialScope{ - Region: "cn-north-1", - }, - }, - endpoints.EndpointKey{ - Region: "cn-northwest-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.cn-northwest-1.amazonaws.com.cn", - CredentialScope: endpoints.CredentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - { - ID: "aws-iso", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIso, - IsRegionalized: true, - }, - { - ID: "aws-iso-b", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoB, - IsRegionalized: true, - }, - { - ID: "aws-iso-e", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoE, - IsRegionalized: true, - }, - { - ID: "aws-iso-f", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoF, - IsRegionalized: true, - }, - { - ID: "aws-us-gov", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "portal.sso.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "portal.sso-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "portal.sso-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "portal.sso.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsUsGov, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-gov-east-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-gov-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - }: endpoints.Endpoint{ - Hostname: "portal.sso.us-gov-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/options.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/options.go deleted file mode 100644 index 5dee7e53..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/options.go +++ /dev/null @@ -1,217 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -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/middleware" - 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 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 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/sso/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/serializers.go deleted file mode 100644 index 02e31411..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/serializers.go +++ /dev/null @@ -1,284 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "fmt" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/encoding/httpbinding" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -type awsRestjson1_serializeOpGetRoleCredentials struct { -} - -func (*awsRestjson1_serializeOpGetRoleCredentials) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpGetRoleCredentials) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetRoleCredentialsInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/federation/credentials") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "GET" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if err := awsRestjson1_serializeOpHttpBindingsGetRoleCredentialsInput(input, restEncoder); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsGetRoleCredentialsInput(v *GetRoleCredentialsInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - if v.AccessToken != nil && len(*v.AccessToken) > 0 { - locationName := "X-Amz-Sso_bearer_token" - encoder.SetHeader(locationName).String(*v.AccessToken) - } - - if v.AccountId != nil { - encoder.SetQuery("account_id").String(*v.AccountId) - } - - if v.RoleName != nil { - encoder.SetQuery("role_name").String(*v.RoleName) - } - - return nil -} - -type awsRestjson1_serializeOpListAccountRoles struct { -} - -func (*awsRestjson1_serializeOpListAccountRoles) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpListAccountRoles) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListAccountRolesInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/assignment/roles") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "GET" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if err := awsRestjson1_serializeOpHttpBindingsListAccountRolesInput(input, restEncoder); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsListAccountRolesInput(v *ListAccountRolesInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - if v.AccessToken != nil && len(*v.AccessToken) > 0 { - locationName := "X-Amz-Sso_bearer_token" - encoder.SetHeader(locationName).String(*v.AccessToken) - } - - if v.AccountId != nil { - encoder.SetQuery("account_id").String(*v.AccountId) - } - - if v.MaxResults != nil { - encoder.SetQuery("max_result").Integer(*v.MaxResults) - } - - if v.NextToken != nil { - encoder.SetQuery("next_token").String(*v.NextToken) - } - - return nil -} - -type awsRestjson1_serializeOpListAccounts struct { -} - -func (*awsRestjson1_serializeOpListAccounts) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpListAccounts) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*ListAccountsInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/assignment/accounts") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "GET" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if err := awsRestjson1_serializeOpHttpBindingsListAccountsInput(input, restEncoder); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsListAccountsInput(v *ListAccountsInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - if v.AccessToken != nil && len(*v.AccessToken) > 0 { - locationName := "X-Amz-Sso_bearer_token" - encoder.SetHeader(locationName).String(*v.AccessToken) - } - - if v.MaxResults != nil { - encoder.SetQuery("max_result").Integer(*v.MaxResults) - } - - if v.NextToken != nil { - encoder.SetQuery("next_token").String(*v.NextToken) - } - - return nil -} - -type awsRestjson1_serializeOpLogout struct { -} - -func (*awsRestjson1_serializeOpLogout) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpLogout) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*LogoutInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/logout") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "POST" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if err := awsRestjson1_serializeOpHttpBindingsLogoutInput(input, restEncoder); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request.Request, err = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsLogoutInput(v *LogoutInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - if v.AccessToken != nil && len(*v.AccessToken) > 0 { - locationName := "X-Amz-Sso_bearer_token" - encoder.SetHeader(locationName).String(*v.AccessToken) - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/errors.go deleted file mode 100644 index e97a126e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/errors.go +++ /dev/null @@ -1,115 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - "fmt" - smithy "github.com/aws/smithy-go" -) - -// Indicates that a problem occurred with the input to the request. For example, a -// required parameter might be missing or out of range. -type InvalidRequestException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidRequestException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidRequestException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidRequestException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidRequestException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidRequestException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The specified resource doesn't exist. -type ResourceNotFoundException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ResourceNotFoundException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ResourceNotFoundException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ResourceNotFoundException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ResourceNotFoundException" - } - return *e.ErrorCodeOverride -} -func (e *ResourceNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the request is being made too frequently and is more than what -// the server can handle. -type TooManyRequestsException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *TooManyRequestsException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *TooManyRequestsException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *TooManyRequestsException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "TooManyRequestsException" - } - return *e.ErrorCodeOverride -} -func (e *TooManyRequestsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the request is not authorized. This can happen due to an invalid -// access token in the request. -type UnauthorizedException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *UnauthorizedException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnauthorizedException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnauthorizedException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnauthorizedException" - } - return *e.ErrorCodeOverride -} -func (e *UnauthorizedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/types.go deleted file mode 100644 index 8dc02296..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/types/types.go +++ /dev/null @@ -1,61 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - smithydocument "github.com/aws/smithy-go/document" -) - -// Provides information about your AWS account. -type AccountInfo struct { - - // The identifier of the AWS account that is assigned to the user. - AccountId *string - - // The display name of the AWS account that is assigned to the user. - AccountName *string - - // The email address of the AWS account that is assigned to the user. - EmailAddress *string - - noSmithyDocumentSerde -} - -// Provides information about the role credentials that are assigned to the user. -type RoleCredentials struct { - - // The identifier used for the temporary security credentials. For more - // information, see Using Temporary Security Credentials to Request Access to AWS - // Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) - // in the AWS IAM User Guide. - AccessKeyId *string - - // The date on which temporary security credentials expire. - Expiration int64 - - // The key that is used to sign the request. For more information, see Using - // Temporary Security Credentials to Request Access to AWS Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) - // in the AWS IAM User Guide. - SecretAccessKey *string - - // The token used for temporary credentials. For more information, see Using - // Temporary Security Credentials to Request Access to AWS Resources (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) - // in the AWS IAM User Guide. - SessionToken *string - - noSmithyDocumentSerde -} - -// Provides information about the role that is assigned to the user. -type RoleInfo struct { - - // The identifier of the AWS account assigned to the user. - AccountId *string - - // The friendly name of the role that is assigned to the user. - RoleName *string - - noSmithyDocumentSerde -} - -type noSmithyDocumentSerde = smithydocument.NoSerde diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sso/validators.go deleted file mode 100644 index f6bf461f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sso/validators.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sso - -import ( - "context" - "fmt" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -type validateOpGetRoleCredentials struct { -} - -func (*validateOpGetRoleCredentials) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetRoleCredentials) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetRoleCredentialsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetRoleCredentialsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListAccountRoles struct { -} - -func (*validateOpListAccountRoles) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListAccountRoles) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListAccountRolesInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListAccountRolesInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpListAccounts struct { -} - -func (*validateOpListAccounts) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpListAccounts) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*ListAccountsInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpListAccountsInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpLogout struct { -} - -func (*validateOpLogout) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpLogout) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*LogoutInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpLogoutInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -func addOpGetRoleCredentialsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetRoleCredentials{}, middleware.After) -} - -func addOpListAccountRolesValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListAccountRoles{}, middleware.After) -} - -func addOpListAccountsValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpListAccounts{}, middleware.After) -} - -func addOpLogoutValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpLogout{}, middleware.After) -} - -func validateOpGetRoleCredentialsInput(v *GetRoleCredentialsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetRoleCredentialsInput"} - if v.RoleName == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleName")) - } - if v.AccountId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccountId")) - } - if v.AccessToken == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListAccountRolesInput(v *ListAccountRolesInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListAccountRolesInput"} - if v.AccessToken == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) - } - if v.AccountId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccountId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpListAccountsInput(v *ListAccountsInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "ListAccountsInput"} - if v.AccessToken == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpLogoutInput(v *LogoutInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "LogoutInput"} - if v.AccessToken == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccessToken")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} 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 deleted file mode 100644 index f77c4785..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/CHANGELOG.md +++ /dev/null @@ -1,372 +0,0 @@ -# v1.21.7 (2024-01-16) - -* No change notes available for this release. - -# 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.3 (2023-11-28.2) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.20.2 (2023-11-28) - -* **Bug Fix**: Respect setting RetryMaxAttempts in functional options at client construction. - -# v1.20.1 (2023-11-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.20.0 (2023-11-17) - -* **Feature**: Adding support for `sso-oauth:CreateTokenWithIAM`. - -# v1.19.2 (2023-11-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.1 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.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.18.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.17.3 (2023-10-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.2 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.1 (2023-09-22) - -* No change notes available for this release. - -# v1.17.0 (2023-09-20) - -* **Feature**: Update FIPS endpoints in aws-us-gov. - -# v1.16.0 (2023-09-18) - -* **Announcement**: [BREAKFIX] Change in MaxResults datatype from value to pointer type in cognito-sync service. -* **Feature**: Adds several endpoint ruleset changes across all models: smaller rulesets, removed non-unique regional endpoints, fixes FIPS and DualStack endpoints, and make region not required in SDK::Endpoint. Additional breakfix to cognito-sync field. - -# v1.15.6 (2023-09-05) - -* No change notes available for this release. - -# v1.15.5 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.4 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.3 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.2 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.1 (2023-08-01) - -* No change notes available for this release. - -# v1.15.0 (2023-07-31) - -* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.14 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.13 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.12 (2023-06-15) - -* No change notes available for this release. - -# v1.14.11 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.10 (2023-05-04) - -* No change notes available for this release. - -# v1.14.9 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.8 (2023-04-10) - -* No change notes available for this release. - -# v1.14.7 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.6 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.5 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.4 (2023-02-22) - -* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes. - -# v1.14.3 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.2 (2023-02-15) - -* **Announcement**: When receiving an error response in restJson-based services, an incorrect error type may have been returned based on the content of the response. This has been fixed via PR #2012 tracked in issue #1910. -* **Bug Fix**: Correct error type parsing for restJson services. - -# v1.14.1 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.0 (2023-01-05) - -* **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - -# v1.13.11 (2022-12-19) - -* No change notes available for this release. - -# v1.13.10 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.9 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.8 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.7 (2022-10-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.6 (2022-09-30) - -* **Documentation**: Documentation updates for the IAM Identity Center OIDC CLI Reference. - -# v1.13.5 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.4 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.3 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.2 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.1 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2022-08-25) - -* **Feature**: Updated required request parameters on IAM Identity Center's OIDC CreateToken action. - -# v1.12.14 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.13 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.12 (2022-08-08) - -* **Documentation**: Documentation updates to reflect service rename - AWS IAM Identity Center (successor to AWS Single Sign-On) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.11 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.10 (2022-07-11) - -* No change notes available for this release. - -# v1.12.9 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.8 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.7 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.6 (2022-05-27) - -* No change notes available for this release. - -# v1.12.5 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2022-02-24) - -* **Feature**: API client updated -* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.9.0 (2022-01-07) - -* **Feature**: API client updated -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.2 (2021-12-02) - -* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514)) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2021-10-21) - -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-10-11) - -* **Feature**: API client updated -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-09-17) - -* **Feature**: Updated API client and endpoints to latest revision. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-08-27) - -* **Feature**: Updated API model to latest revision. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.3 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.2 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.1 (2021-07-15) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.3.0 (2021-06-25) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.2.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/service/ssooidc/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go deleted file mode 100644 index fed08973..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_client.go +++ /dev/null @@ -1,475 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/defaults" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "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" - smithy "github.com/aws/smithy-go" - smithydocument "github.com/aws/smithy-go/document" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net" - "net/http" - "time" -) - -const ServiceID = "SSO OIDC" -const ServiceAPIVersion = "2019-06-10" - -// Client provides the API client to make operations call for AWS SSO OIDC. -type Client struct { - options Options -} - -// 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() - - resolveDefaultLogger(&options) - - setResolvedDefaultsMode(&options) - - resolveRetryer(&options) - - resolveHTTPClient(&options) - - resolveHTTPSignerV4(&options) - - resolveEndpointResolverV2(&options) - - resolveAuthSchemeResolver(&options) - - for _, fn := range optFns { - fn(&options) - } - - finalizeRetryMaxAttempts(&options) - - ignoreAnonymousAuth(&options) - - wrapWithAnonymousAuth(&options) - - resolveAuthSchemes(&options) - - client := &Client{ - options: options, - } - - return client -} - -// 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) { - ctx = middleware.ClearStackValues(ctx) - stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) - options := c.options.Copy() - - for _, fn := range optFns { - fn(&options) - } - - finalizeOperationRetryMaxAttempts(&options, *c) - - finalizeClientEndpointResolverOptions(&options) - - for _, fn := range stackFns { - if err := fn(stack, options); err != nil { - return nil, metadata, err - } - } - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, metadata, err - } - } - - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) - if err != nil { - err = &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: err, - } - } - 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{}, "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 { - LegacyResolver EndpointResolver -} - -func (*legacyEndpointContextSetter) ID() string { - return "legacyEndpointContextSetter" -} - -func (m *legacyEndpointContextSetter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.LegacyResolver != nil { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true) - } - - return next.HandleInitialize(ctx, in) - -} -func addlegacyEndpointContextSetter(stack *middleware.Stack, o Options) error { - return stack.Initialize.Add(&legacyEndpointContextSetter{ - LegacyResolver: o.EndpointResolver, - }, middleware.Before) -} - -func resolveDefaultLogger(o *Options) { - if o.Logger != nil { - return - } - o.Logger = logging.Nop{} -} - -func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { - return middleware.AddSetLoggerMiddleware(stack, o.Logger) -} - -func setResolvedDefaultsMode(o *Options) { - if len(o.resolvedDefaultsMode) > 0 { - return - } - - var mode aws.DefaultsMode - mode.SetFromString(string(o.DefaultsMode)) - - if mode == aws.DefaultsModeAuto { - mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment) - } - - o.resolvedDefaultsMode = mode -} - -// NewFromConfig returns a new client from the provided config. -func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { - opts := Options{ - Region: cfg.Region, - DefaultsMode: cfg.DefaultsMode, - RuntimeEnvironment: cfg.RuntimeEnvironment, - HTTPClient: cfg.HTTPClient, - Credentials: cfg.Credentials, - APIOptions: cfg.APIOptions, - Logger: cfg.Logger, - ClientLogMode: cfg.ClientLogMode, - AppID: cfg.AppID, - } - resolveAWSRetryerProvider(cfg, &opts) - resolveAWSRetryMaxAttempts(cfg, &opts) - resolveAWSRetryMode(cfg, &opts) - resolveAWSEndpointResolver(cfg, &opts) - resolveUseDualStackEndpoint(cfg, &opts) - resolveUseFIPSEndpoint(cfg, &opts) - resolveBaseEndpoint(cfg, &opts) - return New(opts, optFns...) -} - -func resolveHTTPClient(o *Options) { - var buildable *awshttp.BuildableClient - - if o.HTTPClient != nil { - var ok bool - buildable, ok = o.HTTPClient.(*awshttp.BuildableClient) - if !ok { - return - } - } else { - buildable = awshttp.NewBuildableClient() - } - - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) { - if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok { - dialer.Timeout = dialerTimeout - } - }) - - buildable = buildable.WithTransportOptions(func(transport *http.Transport) { - if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok { - transport.TLSHandshakeTimeout = tlsHandshakeTimeout - } - }) - } - - o.HTTPClient = buildable -} - -func resolveRetryer(o *Options) { - if o.Retryer != nil { - return - } - - if len(o.RetryMode) == 0 { - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - o.RetryMode = modeConfig.RetryMode - } - } - if len(o.RetryMode) == 0 { - o.RetryMode = aws.RetryModeStandard - } - - var standardOptions []func(*retry.StandardOptions) - if v := o.RetryMaxAttempts; v != 0 { - standardOptions = append(standardOptions, func(so *retry.StandardOptions) { - so.MaxAttempts = v - }) - } - - switch o.RetryMode { - case aws.RetryModeAdaptive: - var adaptiveOptions []func(*retry.AdaptiveModeOptions) - if len(standardOptions) != 0 { - adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) { - ao.StandardOptions = append(ao.StandardOptions, standardOptions...) - }) - } - o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...) - - default: - o.Retryer = retry.NewStandard(standardOptions...) - } -} - -func resolveAWSRetryerProvider(cfg aws.Config, o *Options) { - if cfg.Retryer == nil { - return - } - o.Retryer = cfg.Retryer() -} - -func resolveAWSRetryMode(cfg aws.Config, o *Options) { - if len(cfg.RetryMode) == 0 { - return - } - o.RetryMode = cfg.RetryMode -} -func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { - if cfg.RetryMaxAttempts == 0 { - return - } - o.RetryMaxAttempts = cfg.RetryMaxAttempts -} - -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 - } - - o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) -} - -func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { - if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil { - return - } - o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions) -} - -func addClientUserAgent(stack *middleware.Stack, options Options) error { - if err := awsmiddleware.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "ssooidc", goModuleVersion)(stack); err != nil { - return err - } - - if len(options.AppID) > 0 { - return awsmiddleware.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID)(stack) - } - - return nil -} - -type HTTPSignerV4 interface { - SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error -} - -func resolveHTTPSignerV4(o *Options) { - if o.HTTPSignerV4 != nil { - return - } - o.HTTPSignerV4 = newDefaultV4Signer(*o) -} - -func newDefaultV4Signer(o Options) *v4.Signer { - return v4.NewSigner(func(so *v4.SignerOptions) { - so.Logger = o.Logger - so.LogSigning = o.ClientLogMode.IsSigning() - }) -} - -func addRetryMiddlewares(stack *middleware.Stack, o Options) error { - mo := retry.AddRetryMiddlewaresOptions{ - Retryer: o.Retryer, - LogRetryAttempts: o.ClientLogMode.IsRetries(), - } - return retry.AddRetryMiddlewares(stack, mo) -} - -// resolves dual-stack endpoint configuration -func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseDualStackEndpoint = value - } - return nil -} - -// resolves FIPS endpoint configuration -func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseFIPSEndpoint = value - } - return nil -} - -func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - return awsmiddleware.AddRequestIDRetrieverMiddleware(stack) -} - -func addResponseErrorMiddleware(stack *middleware.Stack) error { - return awshttp.AddResponseErrorMiddleware(stack) -} - -func addRequestResponseLogging(stack *middleware.Stack, o Options) error { - return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ - LogRequest: o.ClientLogMode.IsRequest(), - LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(), - LogResponse: o.ClientLogMode.IsResponse(), - LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(), - }, middleware.After) -} - -type disableHTTPSMiddleware struct { - DisableHTTPS bool -} - -func (*disableHTTPSMiddleware) ID() string { - return "disableHTTPS" -} - -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.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) -} 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 deleted file mode 100644 index 42464294..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateToken.go +++ /dev/null @@ -1,203 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -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" -) - -// 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 -// APIs using bearer authentication. -func (c *Client) CreateToken(ctx context.Context, params *CreateTokenInput, optFns ...func(*Options)) (*CreateTokenOutput, error) { - if params == nil { - params = &CreateTokenInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateToken", params, optFns, c.addOperationCreateTokenMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateTokenOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateTokenInput struct { - - // The unique identifier string for the client or application. This value comes - // from the result of the RegisterClient API. - // - // This member is required. - ClientId *string - - // A secret string generated for the client. This value should come from the - // persisted result of the RegisterClient API. - // - // 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: * 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 CreateToken API. - Code *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 StartDeviceAuthorization API. - DeviceCode *string - - // Used only when calling this API for the Authorization Code grant type. This - // value specifies the location of the client or application that has registered to - // receive the authorization code. - 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. - // For more information about the features and limitations of the current IAM - // Identity Center OIDC implementation, see Considerations for Using this Guide in - // the IAM Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html) - // . - RefreshToken *string - - // The list of scopes for which authorization is requested. The access token that - // is issued is limited to the scopes that are granted. If this value is not - // specified, IAM Identity Center authorizes all scopes that are configured for the - // client during the call to RegisterClient . - Scope []string - - noSmithyDocumentSerde -} - -type CreateTokenOutput struct { - - // A bearer token to access AWS accounts and applications assigned to a user. - AccessToken *string - - // Indicates the time in seconds when an access token will expire. - ExpiresIn int32 - - // The idToken is not implemented or supported. For more information about the - // features and limitations of the current IAM Identity Center OIDC implementation, - // see Considerations for Using this Guide in the IAM Identity Center OIDC API - // Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html) - // . A JSON Web Token (JWT) that identifies who is associated with the issued - // access token. - IdToken *string - - // A token that, if present, can be used to refresh a previously issued access - // token that might have expired. For more information about the features and - // limitations of the current IAM Identity Center OIDC implementation, see - // Considerations for Using this Guide in the IAM Identity Center OIDC API - // Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html) - // . - RefreshToken *string - - // Used to notify the client that the returned token is an access token. The - // supported token type is Bearer . - TokenType *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateToken{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateToken{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreateToken"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCreateTokenValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateToken(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCreateToken(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateToken", - } -} 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 deleted file mode 100644 index ed4b98f7..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_CreateTokenWithIAM.go +++ /dev/null @@ -1,230 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// 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 AWS 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 { - params = &CreateTokenWithIAMInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "CreateTokenWithIAM", params, optFns, c.addOperationCreateTokenWithIAMMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*CreateTokenWithIAMOutput) - out.ResultMetadata = metadata - return out, nil -} - -type CreateTokenWithIAMInput struct { - - // The unique identifier string for the client or application. This value is an - // application ARN that has OAuth grants configured. - // - // This member is required. - ClientId *string - - // Supports the following OAuth grant types: Authorization Code, Refresh Token, - // JWT Bearer, and Token Exchange. Specify one of the following values, depending - // on the grant type that you want: * Authorization Code - authorization_code * - // Refresh Token - refresh_token * JWT Bearer - - // urn:ietf:params:oauth:grant-type:jwt-bearer * Token Exchange - - // urn:ietf:params:oauth:grant-type:token-exchange - // - // This member is required. - GrantType *string - - // Used only when calling this API for the JWT Bearer grant type. This value - // specifies the JSON Web Token (JWT) issued by a trusted token issuer. To - // authorize a trusted token issuer, configure the JWT Bearer GrantOptions for the - // application. - 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 - // obtained through a redirect from IAM Identity Center to a redirect URI persisted - // in the Authorization Code GrantOptions for the application. - Code *string - - // Used only when calling this API for the Authorization Code grant type. This - // value specifies the location of the client or application that has registered to - // receive the authorization code. - 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. - // For more information about the features and limitations of the current IAM - // Identity Center OIDC implementation, see Considerations for Using this Guide in - // the IAM Identity Center OIDC API Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html) - // . - RefreshToken *string - - // Used only when calling this API for the Token Exchange grant type. This value - // specifies the type of token that the requester can receive. The following values - // are supported: * Access Token - urn:ietf:params:oauth:token-type:access_token * - // Refresh Token - urn:ietf:params:oauth:token-type:refresh_token - RequestedTokenType *string - - // The list of scopes for which authorization is requested. The access token that - // is issued is limited to the scopes that are granted. If the value is not - // specified, IAM Identity Center authorizes all scopes configured for the - // application, including the following default scopes: openid , aws , - // sts:identity_context . - Scope []string - - // Used only when calling this API for the Token Exchange grant type. This value - // specifies the subject of the exchange. The value of the subject token must be an - // access token issued by IAM Identity Center to a different client or application. - // The access token must have authorized scopes that indicate the requested - // application as a target audience. - SubjectToken *string - - // Used only when calling this API for the Token Exchange grant type. This value - // specifies the type of token that is passed as the subject of the exchange. The - // following value is supported: * Access Token - - // urn:ietf:params:oauth:token-type:access_token - SubjectTokenType *string - - noSmithyDocumentSerde -} - -type CreateTokenWithIAMOutput struct { - - // A bearer token to access AWS accounts and applications assigned to a user. - AccessToken *string - - // Indicates the time in seconds when an access token will expire. - ExpiresIn int32 - - // A JSON Web Token (JWT) that identifies the user associated with the issued - // access token. - IdToken *string - - // Indicates the type of tokens that are issued by IAM Identity Center. The - // following values are supported: * Access Token - - // urn:ietf:params:oauth:token-type:access_token * Refresh Token - - // urn:ietf:params:oauth:token-type:refresh_token - IssuedTokenType *string - - // A token that, if present, can be used to refresh a previously issued access - // token that might have expired. For more information about the features and - // limitations of the current IAM Identity Center OIDC implementation, see - // Considerations for Using this Guide in the IAM Identity Center OIDC API - // Reference (https://docs.aws.amazon.com/singlesignon/latest/OIDCAPIReference/Welcome.html) - // . - RefreshToken *string - - // The list of scopes for which authorization is granted. The access token that is - // issued is limited to the scopes that are granted. - Scope []string - - // Used to notify the requester that the returned token is an access token. The - // supported token type is Bearer . - TokenType *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationCreateTokenWithIAMMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateTokenWithIAM{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateTokenWithIAM{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "CreateTokenWithIAM"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpCreateTokenWithIAMValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateTokenWithIAM(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opCreateTokenWithIAM(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "CreateTokenWithIAM", - } -} 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 deleted file mode 100644 index 7aee9049..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_RegisterClient.go +++ /dev/null @@ -1,161 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -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" -) - -// 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. -func (c *Client) RegisterClient(ctx context.Context, params *RegisterClientInput, optFns ...func(*Options)) (*RegisterClientOutput, error) { - if params == nil { - params = &RegisterClientInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "RegisterClient", params, optFns, c.addOperationRegisterClientMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*RegisterClientOutput) - out.ResultMetadata = metadata - return out, nil -} - -type RegisterClientInput struct { - - // The friendly name of the client. - // - // This member is required. - ClientName *string - - // The type of client. The service supports only public as a client type. Anything - // other than public will be rejected by the service. - // - // This member is required. - ClientType *string - - // The list of scopes that are defined by the client. Upon authorization, this - // list is used to restrict permissions when granting an access token. - Scopes []string - - noSmithyDocumentSerde -} - -type RegisterClientOutput struct { - - // An endpoint that the client can use to request authorization. - AuthorizationEndpoint *string - - // The unique identifier string for each client. This client uses this identifier - // to get authenticated by the service in subsequent calls. - ClientId *string - - // Indicates the time at which the clientId and clientSecret were issued. - ClientIdIssuedAt int64 - - // A secret string generated for the client. The client will use this string to - // get authenticated by the service in subsequent calls. - ClientSecret *string - - // Indicates the time at which the clientId and clientSecret will become invalid. - ClientSecretExpiresAt int64 - - // An endpoint that the client can use to create tokens. - TokenEndpoint *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationRegisterClientMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsRestjson1_serializeOpRegisterClient{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpRegisterClient{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "RegisterClient"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpRegisterClientValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opRegisterClient(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opRegisterClient(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "RegisterClient", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_StartDeviceAuthorization.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_StartDeviceAuthorization.go deleted file mode 100644 index d30349e6..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/api_op_StartDeviceAuthorization.go +++ /dev/null @@ -1,169 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -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" -) - -// Initiates device authorization by requesting a pair of verification codes from -// the authorization service. -func (c *Client) StartDeviceAuthorization(ctx context.Context, params *StartDeviceAuthorizationInput, optFns ...func(*Options)) (*StartDeviceAuthorizationOutput, error) { - if params == nil { - params = &StartDeviceAuthorizationInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "StartDeviceAuthorization", params, optFns, c.addOperationStartDeviceAuthorizationMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*StartDeviceAuthorizationOutput) - out.ResultMetadata = metadata - return out, nil -} - -type StartDeviceAuthorizationInput struct { - - // The unique identifier string for the client that is registered with IAM - // Identity Center. This value should come from the persisted result of the - // RegisterClient API operation. - // - // This member is required. - ClientId *string - - // A secret string that is generated for the client. This value should come from - // the persisted result of the RegisterClient API operation. - // - // This member is required. - ClientSecret *string - - // The URL for the Amazon Web Services access portal. For more information, see - // Using the Amazon Web Services access portal (https://docs.aws.amazon.com/singlesignon/latest/userguide/using-the-portal.html) - // in the IAM Identity Center User Guide. - // - // This member is required. - StartUrl *string - - noSmithyDocumentSerde -} - -type StartDeviceAuthorizationOutput struct { - - // The short-lived code that is used by the device when polling for a session - // token. - DeviceCode *string - - // Indicates the number of seconds in which the verification code will become - // invalid. - ExpiresIn int32 - - // Indicates the number of seconds the client must wait between attempts when - // polling for a session. - Interval int32 - - // A one-time user verification code. This is needed to authorize an in-use device. - UserCode *string - - // The URI of the verification page that takes the userCode to authorize the - // device. - VerificationUri *string - - // An alternate URL that the client can use to automatically launch a browser. - // This process skips the manual step in which the user visits the verification - // page and enters their code. - VerificationUriComplete *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationStartDeviceAuthorizationMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsRestjson1_serializeOpStartDeviceAuthorization{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsRestjson1_deserializeOpStartDeviceAuthorization{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "StartDeviceAuthorization"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpStartDeviceAuthorizationValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opStartDeviceAuthorization(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opStartDeviceAuthorization(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "StartDeviceAuthorization", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/auth.go deleted file mode 100644 index 40b3becb..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/auth.go +++ /dev/null @@ -1,302 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -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/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -func bindAuthParamsRegion(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(operation string, input interface{}, options Options) *AuthResolverParameters { - params := &AuthResolverParameters{ - Operation: operation, - } - - bindAuthParamsRegion(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{ - "CreateToken": func(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - {SchemeID: smithyauth.SchemeIDAnonymous}, - } - }, - - "RegisterClient": func(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - {SchemeID: smithyauth.SchemeIDAnonymous}, - } - }, - - "StartDeviceAuthorization": func(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - {SchemeID: smithyauth.SchemeIDAnonymous}, - } - }, -} - -func serviceAuthOptions(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - { - SchemeID: smithyauth.SchemeIDSigV4, - SignerProperties: func() smithy.Properties { - var props smithy.Properties - smithyhttp.SetSigV4SigningName(&props, "sso-oauth") - 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, -) { - params := bindAuthResolverParams(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) - 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, -) { - rscheme := getResolvedAuthScheme(ctx) - 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 := resolver.GetIdentity(ctx, rscheme.IdentityProperties) - if err != nil { - return out, metadata, fmt.Errorf("get identity: %w", err) - } - - ctx = setIdentity(ctx, identity) - 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 { -} - -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, -) { - 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") - } - - if err := signer.SignRequest(ctx, req, identity, rscheme.SignerProperties); err != nil { - return out, metadata, fmt.Errorf("sign request: %w", err) - } - - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/deserializers.go deleted file mode 100644 index 76a1160e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/deserializers.go +++ /dev/null @@ -1,2066 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws/protocol/restjson" - "github.com/aws/aws-sdk-go-v2/service/ssooidc/types" - smithy "github.com/aws/smithy-go" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/ptr" - smithyhttp "github.com/aws/smithy-go/transport/http" - "io" - "strings" -) - -type awsRestjson1_deserializeOpCreateToken struct { -} - -func (*awsRestjson1_deserializeOpCreateToken) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpCreateToken) 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 - } - - 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, awsRestjson1_deserializeOpErrorCreateToken(response, &metadata) - } - output := &CreateTokenOutput{} - 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 = awsRestjson1_deserializeOpDocumentCreateTokenOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorCreateToken(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AccessDeniedException", errorCode): - return awsRestjson1_deserializeErrorAccessDeniedException(response, errorBody) - - case strings.EqualFold("AuthorizationPendingException", errorCode): - return awsRestjson1_deserializeErrorAuthorizationPendingException(response, errorBody) - - case strings.EqualFold("ExpiredTokenException", errorCode): - return awsRestjson1_deserializeErrorExpiredTokenException(response, errorBody) - - case strings.EqualFold("InternalServerException", errorCode): - return awsRestjson1_deserializeErrorInternalServerException(response, errorBody) - - case strings.EqualFold("InvalidClientException", errorCode): - return awsRestjson1_deserializeErrorInvalidClientException(response, errorBody) - - case strings.EqualFold("InvalidGrantException", errorCode): - return awsRestjson1_deserializeErrorInvalidGrantException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("InvalidScopeException", errorCode): - return awsRestjson1_deserializeErrorInvalidScopeException(response, errorBody) - - case strings.EqualFold("SlowDownException", errorCode): - return awsRestjson1_deserializeErrorSlowDownException(response, errorBody) - - case strings.EqualFold("UnauthorizedClientException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedClientException(response, errorBody) - - case strings.EqualFold("UnsupportedGrantTypeException", errorCode): - return awsRestjson1_deserializeErrorUnsupportedGrantTypeException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentCreateTokenOutput(v **CreateTokenOutput, 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 *CreateTokenOutput - if *v == nil { - sv = &CreateTokenOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "accessToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccessToken to be of type string, got %T instead", value) - } - sv.AccessToken = ptr.String(jtv) - } - - case "expiresIn": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ExpirationInSeconds to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ExpiresIn = int32(i64) - } - - case "idToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected IdToken to be of type string, got %T instead", value) - } - sv.IdToken = ptr.String(jtv) - } - - case "refreshToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RefreshToken to be of type string, got %T instead", value) - } - sv.RefreshToken = ptr.String(jtv) - } - - case "tokenType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TokenType to be of type string, got %T instead", value) - } - sv.TokenType = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -type awsRestjson1_deserializeOpCreateTokenWithIAM struct { -} - -func (*awsRestjson1_deserializeOpCreateTokenWithIAM) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpCreateTokenWithIAM) 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 - } - - 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, awsRestjson1_deserializeOpErrorCreateTokenWithIAM(response, &metadata) - } - output := &CreateTokenWithIAMOutput{} - 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 = awsRestjson1_deserializeOpDocumentCreateTokenWithIAMOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorCreateTokenWithIAM(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("AccessDeniedException", errorCode): - return awsRestjson1_deserializeErrorAccessDeniedException(response, errorBody) - - case strings.EqualFold("AuthorizationPendingException", errorCode): - return awsRestjson1_deserializeErrorAuthorizationPendingException(response, errorBody) - - case strings.EqualFold("ExpiredTokenException", errorCode): - return awsRestjson1_deserializeErrorExpiredTokenException(response, errorBody) - - case strings.EqualFold("InternalServerException", errorCode): - return awsRestjson1_deserializeErrorInternalServerException(response, errorBody) - - case strings.EqualFold("InvalidClientException", errorCode): - return awsRestjson1_deserializeErrorInvalidClientException(response, errorBody) - - case strings.EqualFold("InvalidGrantException", errorCode): - return awsRestjson1_deserializeErrorInvalidGrantException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("InvalidRequestRegionException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestRegionException(response, errorBody) - - case strings.EqualFold("InvalidScopeException", errorCode): - return awsRestjson1_deserializeErrorInvalidScopeException(response, errorBody) - - case strings.EqualFold("SlowDownException", errorCode): - return awsRestjson1_deserializeErrorSlowDownException(response, errorBody) - - case strings.EqualFold("UnauthorizedClientException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedClientException(response, errorBody) - - case strings.EqualFold("UnsupportedGrantTypeException", errorCode): - return awsRestjson1_deserializeErrorUnsupportedGrantTypeException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentCreateTokenWithIAMOutput(v **CreateTokenWithIAMOutput, 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 *CreateTokenWithIAMOutput - if *v == nil { - sv = &CreateTokenWithIAMOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "accessToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected AccessToken to be of type string, got %T instead", value) - } - sv.AccessToken = ptr.String(jtv) - } - - case "expiresIn": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ExpirationInSeconds to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ExpiresIn = int32(i64) - } - - case "idToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected IdToken to be of type string, got %T instead", value) - } - sv.IdToken = ptr.String(jtv) - } - - case "issuedTokenType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TokenTypeURI to be of type string, got %T instead", value) - } - sv.IssuedTokenType = ptr.String(jtv) - } - - case "refreshToken": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected RefreshToken to be of type string, got %T instead", value) - } - sv.RefreshToken = ptr.String(jtv) - } - - case "scope": - if err := awsRestjson1_deserializeDocumentScopes(&sv.Scope, value); err != nil { - return err - } - - case "tokenType": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected TokenType to be of type string, got %T instead", value) - } - sv.TokenType = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -type awsRestjson1_deserializeOpRegisterClient struct { -} - -func (*awsRestjson1_deserializeOpRegisterClient) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpRegisterClient) 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 - } - - 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, awsRestjson1_deserializeOpErrorRegisterClient(response, &metadata) - } - output := &RegisterClientOutput{} - 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 = awsRestjson1_deserializeOpDocumentRegisterClientOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorRegisterClient(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerException", errorCode): - return awsRestjson1_deserializeErrorInternalServerException(response, errorBody) - - case strings.EqualFold("InvalidClientMetadataException", errorCode): - return awsRestjson1_deserializeErrorInvalidClientMetadataException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("InvalidScopeException", errorCode): - return awsRestjson1_deserializeErrorInvalidScopeException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentRegisterClientOutput(v **RegisterClientOutput, 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 *RegisterClientOutput - if *v == nil { - sv = &RegisterClientOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "authorizationEndpoint": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected URI to be of type string, got %T instead", value) - } - sv.AuthorizationEndpoint = ptr.String(jtv) - } - - case "clientId": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ClientId to be of type string, got %T instead", value) - } - sv.ClientId = ptr.String(jtv) - } - - case "clientIdIssuedAt": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected LongTimeStampType to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ClientIdIssuedAt = i64 - } - - case "clientSecret": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ClientSecret to be of type string, got %T instead", value) - } - sv.ClientSecret = ptr.String(jtv) - } - - case "clientSecretExpiresAt": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected LongTimeStampType to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ClientSecretExpiresAt = i64 - } - - case "tokenEndpoint": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected URI to be of type string, got %T instead", value) - } - sv.TokenEndpoint = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -type awsRestjson1_deserializeOpStartDeviceAuthorization struct { -} - -func (*awsRestjson1_deserializeOpStartDeviceAuthorization) ID() string { - return "OperationDeserializer" -} - -func (m *awsRestjson1_deserializeOpStartDeviceAuthorization) 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 - } - - 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, awsRestjson1_deserializeOpErrorStartDeviceAuthorization(response, &metadata) - } - output := &StartDeviceAuthorizationOutput{} - 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 = awsRestjson1_deserializeOpDocumentStartDeviceAuthorizationOutput(&output, shape) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body with invalid JSON, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return out, metadata, err -} - -func awsRestjson1_deserializeOpErrorStartDeviceAuthorization(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") - if len(headerCode) != 0 { - errorCode = restjson.SanitizeErrorCode(headerCode) - } - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - - body := io.TeeReader(errorBody, ringBuffer) - decoder := json.NewDecoder(body) - decoder.UseNumber() - jsonCode, message, err := restjson.GetErrorInfo(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 len(headerCode) == 0 && len(jsonCode) != 0 { - errorCode = restjson.SanitizeErrorCode(jsonCode) - } - if len(message) != 0 { - errorMessage = message - } - - switch { - case strings.EqualFold("InternalServerException", errorCode): - return awsRestjson1_deserializeErrorInternalServerException(response, errorBody) - - case strings.EqualFold("InvalidClientException", errorCode): - return awsRestjson1_deserializeErrorInvalidClientException(response, errorBody) - - case strings.EqualFold("InvalidRequestException", errorCode): - return awsRestjson1_deserializeErrorInvalidRequestException(response, errorBody) - - case strings.EqualFold("SlowDownException", errorCode): - return awsRestjson1_deserializeErrorSlowDownException(response, errorBody) - - case strings.EqualFold("UnauthorizedClientException", errorCode): - return awsRestjson1_deserializeErrorUnauthorizedClientException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsRestjson1_deserializeOpDocumentStartDeviceAuthorizationOutput(v **StartDeviceAuthorizationOutput, 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 *StartDeviceAuthorizationOutput - if *v == nil { - sv = &StartDeviceAuthorizationOutput{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "deviceCode": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected DeviceCode to be of type string, got %T instead", value) - } - sv.DeviceCode = ptr.String(jtv) - } - - case "expiresIn": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected ExpirationInSeconds to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.ExpiresIn = int32(i64) - } - - case "interval": - if value != nil { - jtv, ok := value.(json.Number) - if !ok { - return fmt.Errorf("expected IntervalInSeconds to be json.Number, got %T instead", value) - } - i64, err := jtv.Int64() - if err != nil { - return err - } - sv.Interval = int32(i64) - } - - case "userCode": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected UserCode to be of type string, got %T instead", value) - } - sv.UserCode = ptr.String(jtv) - } - - case "verificationUri": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected URI to be of type string, got %T instead", value) - } - sv.VerificationUri = ptr.String(jtv) - } - - case "verificationUriComplete": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected URI to be of type string, got %T instead", value) - } - sv.VerificationUriComplete = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeErrorAccessDeniedException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.AccessDeniedException{} - 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 - } - - err := awsRestjson1_deserializeDocumentAccessDeniedException(&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 awsRestjson1_deserializeErrorAuthorizationPendingException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.AuthorizationPendingException{} - 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 - } - - err := awsRestjson1_deserializeDocumentAuthorizationPendingException(&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 awsRestjson1_deserializeErrorExpiredTokenException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.ExpiredTokenException{} - 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 - } - - err := awsRestjson1_deserializeDocumentExpiredTokenException(&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 awsRestjson1_deserializeErrorInternalServerException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InternalServerException{} - 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 - } - - err := awsRestjson1_deserializeDocumentInternalServerException(&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 awsRestjson1_deserializeErrorInvalidClientException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidClientException{} - 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 - } - - err := awsRestjson1_deserializeDocumentInvalidClientException(&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 awsRestjson1_deserializeErrorInvalidClientMetadataException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidClientMetadataException{} - 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 - } - - err := awsRestjson1_deserializeDocumentInvalidClientMetadataException(&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 awsRestjson1_deserializeErrorInvalidGrantException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidGrantException{} - 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 - } - - err := awsRestjson1_deserializeDocumentInvalidGrantException(&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 awsRestjson1_deserializeErrorInvalidRequestException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidRequestException{} - 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 - } - - err := awsRestjson1_deserializeDocumentInvalidRequestException(&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 awsRestjson1_deserializeErrorInvalidRequestRegionException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidRequestRegionException{} - 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 - } - - err := awsRestjson1_deserializeDocumentInvalidRequestRegionException(&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 awsRestjson1_deserializeErrorInvalidScopeException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidScopeException{} - 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 - } - - err := awsRestjson1_deserializeDocumentInvalidScopeException(&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 awsRestjson1_deserializeErrorSlowDownException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.SlowDownException{} - 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 - } - - err := awsRestjson1_deserializeDocumentSlowDownException(&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 awsRestjson1_deserializeErrorUnauthorizedClientException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.UnauthorizedClientException{} - 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 - } - - err := awsRestjson1_deserializeDocumentUnauthorizedClientException(&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 awsRestjson1_deserializeErrorUnsupportedGrantTypeException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.UnsupportedGrantTypeException{} - 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 - } - - err := awsRestjson1_deserializeDocumentUnsupportedGrantTypeException(&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 awsRestjson1_deserializeDocumentAccessDeniedException(v **types.AccessDeniedException, 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.AccessDeniedException - if *v == nil { - sv = &types.AccessDeniedException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentAuthorizationPendingException(v **types.AuthorizationPendingException, 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.AuthorizationPendingException - if *v == nil { - sv = &types.AuthorizationPendingException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentExpiredTokenException(v **types.ExpiredTokenException, 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.ExpiredTokenException - if *v == nil { - sv = &types.ExpiredTokenException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInternalServerException(v **types.InternalServerException, 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.InternalServerException - if *v == nil { - sv = &types.InternalServerException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidClientException(v **types.InvalidClientException, 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.InvalidClientException - if *v == nil { - sv = &types.InvalidClientException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidClientMetadataException(v **types.InvalidClientMetadataException, 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.InvalidClientMetadataException - if *v == nil { - sv = &types.InvalidClientMetadataException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidGrantException(v **types.InvalidGrantException, 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.InvalidGrantException - if *v == nil { - sv = &types.InvalidGrantException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidRequestException(v **types.InvalidRequestException, 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.InvalidRequestException - if *v == nil { - sv = &types.InvalidRequestException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidRequestRegionException(v **types.InvalidRequestRegionException, 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.InvalidRequestRegionException - if *v == nil { - sv = &types.InvalidRequestRegionException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "endpoint": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Location to be of type string, got %T instead", value) - } - sv.Endpoint = ptr.String(jtv) - } - - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - case "region": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Region to be of type string, got %T instead", value) - } - sv.Region = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentInvalidScopeException(v **types.InvalidScopeException, 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.InvalidScopeException - if *v == nil { - sv = &types.InvalidScopeException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentScopes(v *[]string, 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 []string - if *v == nil { - cv = []string{} - } else { - cv = *v - } - - for _, value := range shape { - var col string - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Scope to be of type string, got %T instead", value) - } - col = jtv - } - cv = append(cv, col) - - } - *v = cv - return nil -} - -func awsRestjson1_deserializeDocumentSlowDownException(v **types.SlowDownException, 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.SlowDownException - if *v == nil { - sv = &types.SlowDownException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentUnauthorizedClientException(v **types.UnauthorizedClientException, 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.UnauthorizedClientException - if *v == nil { - sv = &types.UnauthorizedClientException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} - -func awsRestjson1_deserializeDocumentUnsupportedGrantTypeException(v **types.UnsupportedGrantTypeException, 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.UnsupportedGrantTypeException - if *v == nil { - sv = &types.UnsupportedGrantTypeException{} - } else { - sv = *v - } - - for key, value := range shape { - switch key { - case "error": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected Error to be of type string, got %T instead", value) - } - sv.Error_ = ptr.String(jtv) - } - - case "error_description": - if value != nil { - jtv, ok := value.(string) - if !ok { - return fmt.Errorf("expected ErrorDescription to be of type string, got %T instead", value) - } - sv.Error_description = ptr.String(jtv) - } - - default: - _, _ = key, value - - } - } - *v = sv - return nil -} 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 deleted file mode 100644 index 53cd4f55..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/doc.go +++ /dev/null @@ -1,38 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -// Package ssooidc provides the API client, operations, and parameter types for -// AWS SSO OIDC. -// -// IAM Identity Center OpenID Connect (OIDC) is a web service that enables a -// client (such as CLI or a native application) to register with IAM Identity -// 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. 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 works. -// - The IAM Identity Center OIDC service currently implements only the portions -// of the OAuth 2.0 Device Authorization Grant standard ( -// https://tools.ietf.org/html/rfc8628 (https://tools.ietf.org/html/rfc8628) ) -// that are necessary to enable single sign-on authentication with the CLI. -// - With older versions of the CLI, the service only emits OIDC access tokens, -// so to obtain a new token, users must explicitly re-authenticate. To access the -// OIDC flow that supports token refresh and doesn’t require re-authentication, -// update to the latest CLI version (1.27.10 for CLI V1 and 2.9.0 for CLI V2) with -// support for OIDC token refresh and configurable IAM Identity Center session -// durations. For more information, see Configure Amazon Web Services access -// portal session duration (https://docs.aws.amazon.com/singlesignon/latest/userguide/configure-user-session.html) -// . -// - The access tokens provided by this service grant access to all Amazon Web -// Services account entitlements assigned to an IAM Identity Center user, not just -// a particular application. -// - The documentation in this guide does not describe the mechanism to convert -// the access token into Amazon Web Services Auth (“sigv4”) credentials for use -// with IAM-protected Amazon Web Services service endpoints. For more information, -// see GetRoleCredentials (https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html) -// in the IAM Identity Center Portal API Reference Guide. -// -// For general information about IAM Identity Center, see What is IAM Identity -// Center? (https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) -// in the IAM Identity Center User Guide. -package ssooidc diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/endpoints.go deleted file mode 100644 index 85b87089..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/endpoints.go +++ /dev/null @@ -1,528 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "context" - "errors" - "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/ssooidc/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" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net/http" - "net/url" - "os" - "strings" -) - -// EndpointResolverOptions is the service endpoint resolver options -type EndpointResolverOptions = internalendpoints.Options - -// EndpointResolver interface for resolving service endpoints. -type EndpointResolver interface { - ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) -} - -var _ EndpointResolver = &internalendpoints.Resolver{} - -// NewDefaultEndpointResolver constructs a new service endpoint resolver -func NewDefaultEndpointResolver() *internalendpoints.Resolver { - return internalendpoints.New() -} - -// EndpointResolverFunc is a helper utility that wraps a function so it satisfies -// the EndpointResolver interface. This is useful when you want to add additional -// endpoint resolving logic, or stub out specific endpoints with custom values. -type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) - -func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return fn(region, options) -} - -// EndpointResolverFromURL returns an EndpointResolver configured using the -// provided endpoint url. By default, the resolved endpoint resolver uses the -// client region as signing region, and the endpoint source is set to -// EndpointSourceCustom.You can provide functional options to configure endpoint -// values for the resolved endpoint. -func EndpointResolverFromURL(url string, optFns ...func(*aws.Endpoint)) EndpointResolver { - e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom} - for _, fn := range optFns { - fn(&e) - } - - return EndpointResolverFunc( - func(region string, options EndpointResolverOptions) (aws.Endpoint, error) { - if len(e.SigningRegion) == 0 { - e.SigningRegion = region - } - return e, nil - }, - ) -} - -type ResolveEndpoint struct { - Resolver EndpointResolver - Options EndpointResolverOptions -} - -func (*ResolveEndpoint) ID() string { - return "ResolveEndpoint" -} - -func (m *ResolveEndpoint) 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.Resolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - eo := m.Options - eo.Logger = middleware.GetLogger(ctx) - - var endpoint aws.Endpoint - endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), eo) - if err != nil { - nf := (&aws.EndpointNotFoundError{}) - if errors.As(err, &nf) { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, false) - return next.HandleSerialize(ctx, in) - } - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL, err = url.Parse(endpoint.URL) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) - } - - if len(awsmiddleware.GetSigningName(ctx)) == 0 { - signingName := endpoint.SigningName - if len(signingName) == 0 { - signingName = "sso-oauth" - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - } - ctx = awsmiddleware.SetEndpointSource(ctx, endpoint.Source) - ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) - ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) - ctx = awsmiddleware.SetPartitionID(ctx, endpoint.PartitionID) - return next.HandleSerialize(ctx, in) -} -func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&ResolveEndpoint{ - Resolver: o.EndpointResolver, - Options: o.EndpointOptions, - }, "OperationSerializer", middleware.Before) -} - -func removeResolveEndpointMiddleware(stack *middleware.Stack) error { - _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) - return err -} - -type wrappedEndpointResolver struct { - awsResolver aws.EndpointResolverWithOptions -} - -func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return w.awsResolver.ResolveEndpoint(ServiceID, region, options) -} - -type awsEndpointResolverAdaptor func(service, region string) (aws.Endpoint, error) - -func (a awsEndpointResolverAdaptor) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { - return a(service, region) -} - -var _ aws.EndpointResolverWithOptions = awsEndpointResolverAdaptor(nil) - -// withEndpointResolver returns an aws.EndpointResolverWithOptions that first delegates endpoint resolution to the awsResolver. -// If awsResolver returns aws.EndpointNotFoundError error, the v1 resolver middleware will swallow the error, -// and set an appropriate context flag such that fallback will occur when EndpointResolverV2 is invoked -// via its middleware. -// -// If another error (besides aws.EndpointNotFoundError) is returned, then that error will be propagated. -func withEndpointResolver(awsResolver aws.EndpointResolver, awsResolverWithOptions aws.EndpointResolverWithOptions) EndpointResolver { - var resolver aws.EndpointResolverWithOptions - - if awsResolverWithOptions != nil { - resolver = awsResolverWithOptions - } else if awsResolver != nil { - resolver = awsEndpointResolverAdaptor(awsResolver.ResolveEndpoint) - } - - return &wrappedEndpointResolver{ - awsResolver: resolver, - } -} - -func finalizeClientEndpointResolverOptions(options *Options) { - options.EndpointOptions.LogDeprecated = options.ClientLogMode.IsDeprecatedUsage() - - if len(options.EndpointOptions.ResolvedRegion) == 0 { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(options.Region, fipsInfix) || - strings.Contains(options.Region, fipsPrefix) || - strings.Contains(options.Region, fipsSuffix) { - options.EndpointOptions.ResolvedRegion = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - options.Region, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - options.EndpointOptions.UseFIPSEndpoint = aws.FIPSEndpointStateEnabled - } - } - -} - -func resolveEndpointResolverV2(options *Options) { - if options.EndpointResolverV2 == nil { - options.EndpointResolverV2 = NewDefaultEndpointResolverV2() - } -} - -func resolveBaseEndpoint(cfg aws.Config, o *Options) { - if cfg.BaseEndpoint != nil { - o.BaseEndpoint = cfg.BaseEndpoint - } - - _, g := os.LookupEnv("AWS_ENDPOINT_URL") - _, s := os.LookupEnv("AWS_ENDPOINT_URL_SSO_OIDC") - - if g && !s { - return - } - - value, found, err := internalConfig.ResolveServiceBaseEndpoint(context.Background(), "SSO OIDC", cfg.ConfigSources) - if found && err == nil { - o.BaseEndpoint = &value - } -} - -// EndpointParameters provides the parameters that influence how endpoints are -// resolved. -type EndpointParameters struct { - // The AWS region used to dispatch the request. - // - // Parameter is - // required. - // - // AWS::Region - Region *string - - // When true, use the dual-stack endpoint. If the configured endpoint does not - // support dual-stack, dispatching the request MAY return an error. - // - // Defaults to - // false if no value is provided. - // - // AWS::UseDualStack - UseDualStack *bool - - // When true, send this request to the FIPS-compliant regional endpoint. If the - // configured endpoint does not have a FIPS compliant endpoint, dispatching the - // request will return an error. - // - // Defaults to false if no value is - // provided. - // - // AWS::UseFIPS - UseFIPS *bool - - // Override the endpoint used to send this request - // - // Parameter is - // required. - // - // SDK::Endpoint - Endpoint *string -} - -// ValidateRequired validates required parameters are set. -func (p EndpointParameters) ValidateRequired() error { - if p.UseDualStack == nil { - return fmt.Errorf("parameter UseDualStack is required") - } - - if p.UseFIPS == nil { - return fmt.Errorf("parameter UseFIPS is required") - } - - return nil -} - -// WithDefaults returns a shallow copy of EndpointParameterswith default values -// applied to members where applicable. -func (p EndpointParameters) WithDefaults() EndpointParameters { - if p.UseDualStack == nil { - p.UseDualStack = ptr.Bool(false) - } - - if p.UseFIPS == nil { - p.UseFIPS = ptr.Bool(false) - } - return p -} - -// EndpointResolverV2 provides the interface for resolving service endpoints. -type EndpointResolverV2 interface { - // ResolveEndpoint attempts to resolve the endpoint with the provided options, - // returning the endpoint if found. Otherwise an error is returned. - ResolveEndpoint(ctx context.Context, params EndpointParameters) ( - smithyendpoints.Endpoint, error, - ) -} - -// resolver provides the implementation for resolving endpoints. -type resolver struct{} - -func NewDefaultEndpointResolverV2() EndpointResolverV2 { - return &resolver{} -} - -// ResolveEndpoint attempts to resolve the endpoint with the provided options, -// returning the endpoint if found. Otherwise an error is returned. -func (r *resolver) ResolveEndpoint( - ctx context.Context, params EndpointParameters, -) ( - endpoint smithyendpoints.Endpoint, err error, -) { - params = params.WithDefaults() - if err = params.ValidateRequired(); err != nil { - return endpoint, fmt.Errorf("endpoint parameters are not valid, %w", err) - } - _UseDualStack := *params.UseDualStack - _UseFIPS := *params.UseFIPS - - if exprVal := params.Endpoint; exprVal != nil { - _Endpoint := *exprVal - _ = _Endpoint - if _UseFIPS == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: FIPS and custom endpoint are not supported") - } - if _UseDualStack == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Dualstack and custom endpoint are not supported") - } - uriString := _Endpoint - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if exprVal := params.Region; exprVal != nil { - _Region := *exprVal - _ = _Region - if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { - _PartitionResult := *exprVal - _ = _PartitionResult - if _UseFIPS == true { - if _UseDualStack == true { - if true == _PartitionResult.SupportsFIPS { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://oidc-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS and DualStack are enabled, but this partition does not support one or both") - } - } - if _UseFIPS == true { - if _PartitionResult.SupportsFIPS == true { - if _PartitionResult.Name == "aws-us-gov" { - uriString := func() string { - var out strings.Builder - out.WriteString("https://oidc.") - out.WriteString(_Region) - out.WriteString(".amazonaws.com") - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://oidc-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS is enabled but this partition does not support FIPS") - } - if _UseDualStack == true { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://oidc.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "DualStack is enabled but this partition does not support DualStack") - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://oidc.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("Endpoint resolution failed. Invalid operation or environment input.") - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") -} - -type endpointParamsBinder interface { - bindEndpointParams(*EndpointParameters) -} - -func bindEndpointParams(input interface{}, options Options) *EndpointParameters { - params := &EndpointParameters{} - - params.Region = aws.String(endpoints.MapFIPSRegion(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, -) { - 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(getOperationInput(ctx), m.options) - endpt, err := m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - 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) - } - - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/generated.json deleted file mode 100644 index 0a6b3493..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/generated.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "dependencies": { - "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" - }, - "files": [ - "api_client.go", - "api_client_test.go", - "api_op_CreateToken.go", - "api_op_CreateTokenWithIAM.go", - "api_op_RegisterClient.go", - "api_op_StartDeviceAuthorization.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", - "types/errors.go", - "types/types.go", - "validators.go" - ], - "go": "1.15", - "module": "github.com/aws/aws-sdk-go-v2/service/ssooidc", - "unstable": false -} 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 deleted file mode 100644 index 474a574e..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package ssooidc - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.21.7" diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints/endpoints.go deleted file mode 100644 index cbd77fd2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/internal/endpoints/endpoints.go +++ /dev/null @@ -1,534 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package endpoints - -import ( - "github.com/aws/aws-sdk-go-v2/aws" - endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" - "github.com/aws/smithy-go/logging" - "regexp" -) - -// Options is the endpoint resolver configuration options -type Options struct { - // Logger is a logging implementation that log events should be sent to. - Logger logging.Logger - - // LogDeprecated indicates that deprecated endpoints should be logged to the - // provided logger. - LogDeprecated bool - - // ResolvedRegion is used to override the region to be resolved, rather then the - // using the value passed to the ResolveEndpoint method. This value is used by the - // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative - // name. You must not set this value directly in your application. - ResolvedRegion string - - // DisableHTTPS informs the resolver to return an endpoint that does not use the - // HTTPS scheme. - DisableHTTPS bool - - // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. - UseDualStackEndpoint aws.DualStackEndpointState - - // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. - UseFIPSEndpoint aws.FIPSEndpointState -} - -func (o Options) GetResolvedRegion() string { - return o.ResolvedRegion -} - -func (o Options) GetDisableHTTPS() bool { - return o.DisableHTTPS -} - -func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { - return o.UseDualStackEndpoint -} - -func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { - return o.UseFIPSEndpoint -} - -func transformToSharedOptions(options Options) endpoints.Options { - return endpoints.Options{ - Logger: options.Logger, - LogDeprecated: options.LogDeprecated, - ResolvedRegion: options.ResolvedRegion, - DisableHTTPS: options.DisableHTTPS, - UseDualStackEndpoint: options.UseDualStackEndpoint, - UseFIPSEndpoint: options.UseFIPSEndpoint, - } -} - -// Resolver SSO OIDC endpoint resolver -type Resolver struct { - partitions endpoints.Partitions -} - -// ResolveEndpoint resolves the service endpoint for the given region and options -func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { - if len(region) == 0 { - return endpoint, &aws.MissingRegionError{} - } - - opt := transformToSharedOptions(options) - return r.partitions.ResolveEndpoint(region, opt) -} - -// New returns a new Resolver -func New() *Resolver { - return &Resolver{ - partitions: defaultPartitions, - } -} - -var partitionRegexp = struct { - Aws *regexp.Regexp - AwsCn *regexp.Regexp - AwsIso *regexp.Regexp - AwsIsoB *regexp.Regexp - AwsIsoE *regexp.Regexp - AwsIsoF *regexp.Regexp - AwsUsGov *regexp.Regexp -}{ - - Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$"), - AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), - AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), - AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), - AwsIsoE: regexp.MustCompile("^eu\\-isoe\\-\\w+\\-\\d+$"), - AwsIsoF: regexp.MustCompile("^us\\-isof\\-\\w+\\-\\d+$"), - AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), -} - -var defaultPartitions = endpoints.Partitions{ - { - ID: "aws", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "oidc.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "oidc-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.Aws, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "af-south-1", - }: endpoints.Endpoint{ - Hostname: "oidc.af-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "af-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-east-1", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-1", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-northeast-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-2", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-northeast-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-2", - }, - }, - endpoints.EndpointKey{ - Region: "ap-northeast-3", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-northeast-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-northeast-3", - }, - }, - endpoints.EndpointKey{ - Region: "ap-south-1", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-1", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-southeast-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-1", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-2", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-southeast-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-2", - }, - }, - endpoints.EndpointKey{ - Region: "ap-southeast-3", - }: endpoints.Endpoint{ - Hostname: "oidc.ap-southeast-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ap-southeast-3", - }, - }, - endpoints.EndpointKey{ - Region: "ca-central-1", - }: endpoints.Endpoint{ - Hostname: "oidc.ca-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "ca-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-central-1", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-central-2", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-central-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-central-2", - }, - }, - endpoints.EndpointKey{ - Region: "eu-north-1", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-north-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-north-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-south-1", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-1", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-1", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-2", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-west-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-2", - }, - }, - endpoints.EndpointKey{ - Region: "eu-west-3", - }: endpoints.Endpoint{ - Hostname: "oidc.eu-west-3.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "eu-west-3", - }, - }, - endpoints.EndpointKey{ - Region: "il-central-1", - }: endpoints.Endpoint{ - Hostname: "oidc.il-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "il-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "me-central-1", - }: endpoints.Endpoint{ - Hostname: "oidc.me-central-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "me-central-1", - }, - }, - endpoints.EndpointKey{ - Region: "me-south-1", - }: endpoints.Endpoint{ - Hostname: "oidc.me-south-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "me-south-1", - }, - }, - endpoints.EndpointKey{ - Region: "sa-east-1", - }: endpoints.Endpoint{ - Hostname: "oidc.sa-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "sa-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-east-1", - }: endpoints.Endpoint{ - Hostname: "oidc.us-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-east-2", - }: endpoints.Endpoint{ - Hostname: "oidc.us-east-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-2", - }, - }, - endpoints.EndpointKey{ - Region: "us-west-1", - }: endpoints.Endpoint{ - Hostname: "oidc.us-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-west-2", - }: endpoints.Endpoint{ - Hostname: "oidc.us-west-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - { - ID: "aws-cn", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "oidc.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "oidc-fips.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsCn, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "cn-north-1", - }: endpoints.Endpoint{ - Hostname: "oidc.cn-north-1.amazonaws.com.cn", - CredentialScope: endpoints.CredentialScope{ - Region: "cn-north-1", - }, - }, - endpoints.EndpointKey{ - Region: "cn-northwest-1", - }: endpoints.Endpoint{ - Hostname: "oidc.cn-northwest-1.amazonaws.com.cn", - CredentialScope: endpoints.CredentialScope{ - Region: "cn-northwest-1", - }, - }, - }, - }, - { - ID: "aws-iso", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIso, - IsRegionalized: true, - }, - { - ID: "aws-iso-b", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoB, - IsRegionalized: true, - }, - { - ID: "aws-iso-e", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoE, - IsRegionalized: true, - }, - { - ID: "aws-iso-f", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoF, - IsRegionalized: true, - }, - { - ID: "aws-us-gov", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "oidc.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "oidc-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "oidc-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "oidc.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsUsGov, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-gov-east-1", - }: endpoints.Endpoint{ - Hostname: "oidc.us-gov-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - }: endpoints.Endpoint{ - Hostname: "oidc.us-gov-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/options.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/options.go deleted file mode 100644 index b964e7e1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/options.go +++ /dev/null @@ -1,217 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -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/middleware" - 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 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 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/ssooidc/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/serializers.go deleted file mode 100644 index 754218b7..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/serializers.go +++ /dev/null @@ -1,431 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "bytes" - "context" - "fmt" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/encoding/httpbinding" - smithyjson "github.com/aws/smithy-go/encoding/json" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -type awsRestjson1_serializeOpCreateToken struct { -} - -func (*awsRestjson1_serializeOpCreateToken) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpCreateToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreateTokenInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/token") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "POST" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - restEncoder.SetHeader("Content-Type").String("application/json") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsRestjson1_serializeOpDocumentCreateTokenInput(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 = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsCreateTokenInput(v *CreateTokenInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - return nil -} - -func awsRestjson1_serializeOpDocumentCreateTokenInput(v *CreateTokenInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientId != nil { - ok := object.Key("clientId") - ok.String(*v.ClientId) - } - - if v.ClientSecret != nil { - ok := object.Key("clientSecret") - ok.String(*v.ClientSecret) - } - - if v.Code != nil { - ok := object.Key("code") - ok.String(*v.Code) - } - - if v.DeviceCode != nil { - ok := object.Key("deviceCode") - ok.String(*v.DeviceCode) - } - - if v.GrantType != nil { - ok := object.Key("grantType") - ok.String(*v.GrantType) - } - - if v.RedirectUri != nil { - ok := object.Key("redirectUri") - ok.String(*v.RedirectUri) - } - - if v.RefreshToken != nil { - ok := object.Key("refreshToken") - ok.String(*v.RefreshToken) - } - - if v.Scope != nil { - ok := object.Key("scope") - if err := awsRestjson1_serializeDocumentScopes(v.Scope, ok); err != nil { - return err - } - } - - return nil -} - -type awsRestjson1_serializeOpCreateTokenWithIAM struct { -} - -func (*awsRestjson1_serializeOpCreateTokenWithIAM) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpCreateTokenWithIAM) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*CreateTokenWithIAMInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/token?aws_iam=t") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "POST" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - restEncoder.SetHeader("Content-Type").String("application/json") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsRestjson1_serializeOpDocumentCreateTokenWithIAMInput(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 = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsCreateTokenWithIAMInput(v *CreateTokenWithIAMInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - return nil -} - -func awsRestjson1_serializeOpDocumentCreateTokenWithIAMInput(v *CreateTokenWithIAMInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.Assertion != nil { - ok := object.Key("assertion") - ok.String(*v.Assertion) - } - - if v.ClientId != nil { - ok := object.Key("clientId") - ok.String(*v.ClientId) - } - - if v.Code != nil { - ok := object.Key("code") - ok.String(*v.Code) - } - - if v.GrantType != nil { - ok := object.Key("grantType") - ok.String(*v.GrantType) - } - - if v.RedirectUri != nil { - ok := object.Key("redirectUri") - ok.String(*v.RedirectUri) - } - - if v.RefreshToken != nil { - ok := object.Key("refreshToken") - ok.String(*v.RefreshToken) - } - - if v.RequestedTokenType != nil { - ok := object.Key("requestedTokenType") - ok.String(*v.RequestedTokenType) - } - - if v.Scope != nil { - ok := object.Key("scope") - if err := awsRestjson1_serializeDocumentScopes(v.Scope, ok); err != nil { - return err - } - } - - if v.SubjectToken != nil { - ok := object.Key("subjectToken") - ok.String(*v.SubjectToken) - } - - if v.SubjectTokenType != nil { - ok := object.Key("subjectTokenType") - ok.String(*v.SubjectTokenType) - } - - return nil -} - -type awsRestjson1_serializeOpRegisterClient struct { -} - -func (*awsRestjson1_serializeOpRegisterClient) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpRegisterClient) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*RegisterClientInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/client/register") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "POST" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - restEncoder.SetHeader("Content-Type").String("application/json") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsRestjson1_serializeOpDocumentRegisterClientInput(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 = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsRegisterClientInput(v *RegisterClientInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - return nil -} - -func awsRestjson1_serializeOpDocumentRegisterClientInput(v *RegisterClientInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientName != nil { - ok := object.Key("clientName") - ok.String(*v.ClientName) - } - - if v.ClientType != nil { - ok := object.Key("clientType") - ok.String(*v.ClientType) - } - - if v.Scopes != nil { - ok := object.Key("scopes") - if err := awsRestjson1_serializeDocumentScopes(v.Scopes, ok); err != nil { - return err - } - } - - return nil -} - -type awsRestjson1_serializeOpStartDeviceAuthorization struct { -} - -func (*awsRestjson1_serializeOpStartDeviceAuthorization) ID() string { - return "OperationSerializer" -} - -func (m *awsRestjson1_serializeOpStartDeviceAuthorization) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*StartDeviceAuthorizationInput) - _ = input - if !ok { - return out, metadata, &smithy.SerializationError{Err: fmt.Errorf("unknown input parameters type %T", in.Parameters)} - } - - opPath, opQuery := httpbinding.SplitURI("/device_authorization") - request.URL.Path = smithyhttp.JoinPath(request.URL.Path, opPath) - request.URL.RawQuery = smithyhttp.JoinRawQuery(request.URL.RawQuery, opQuery) - request.Method = "POST" - var restEncoder *httpbinding.Encoder - if request.URL.RawPath == "" { - restEncoder, err = httpbinding.NewEncoder(request.URL.Path, request.URL.RawQuery, request.Header) - } else { - request.URL.RawPath = smithyhttp.JoinPath(request.URL.RawPath, opPath) - restEncoder, err = httpbinding.NewEncoderWithRawPath(request.URL.Path, request.URL.RawPath, request.URL.RawQuery, request.Header) - } - - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - restEncoder.SetHeader("Content-Type").String("application/json") - - jsonEncoder := smithyjson.NewEncoder() - if err := awsRestjson1_serializeOpDocumentStartDeviceAuthorizationInput(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 = restEncoder.Encode(request.Request); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - in.Request = request - - return next.HandleSerialize(ctx, in) -} -func awsRestjson1_serializeOpHttpBindingsStartDeviceAuthorizationInput(v *StartDeviceAuthorizationInput, encoder *httpbinding.Encoder) error { - if v == nil { - return fmt.Errorf("unsupported serialization of nil %T", v) - } - - return nil -} - -func awsRestjson1_serializeOpDocumentStartDeviceAuthorizationInput(v *StartDeviceAuthorizationInput, value smithyjson.Value) error { - object := value.Object() - defer object.Close() - - if v.ClientId != nil { - ok := object.Key("clientId") - ok.String(*v.ClientId) - } - - if v.ClientSecret != nil { - ok := object.Key("clientSecret") - ok.String(*v.ClientSecret) - } - - if v.StartUrl != nil { - ok := object.Key("startUrl") - ok.String(*v.StartUrl) - } - - return nil -} - -func awsRestjson1_serializeDocumentScopes(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 -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/errors.go deleted file mode 100644 index 86b62049..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/errors.go +++ /dev/null @@ -1,398 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - "fmt" - smithy "github.com/aws/smithy-go" -) - -// You do not have sufficient access to perform this action. -type AccessDeniedException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *AccessDeniedException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AccessDeniedException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AccessDeniedException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AccessDeniedException" - } - return *e.ErrorCodeOverride -} -func (e *AccessDeniedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that a request to authorize a client with an access user session -// token is pending. -type AuthorizationPendingException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *AuthorizationPendingException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *AuthorizationPendingException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *AuthorizationPendingException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "AuthorizationPendingException" - } - return *e.ErrorCodeOverride -} -func (e *AuthorizationPendingException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the token issued by the service is expired and is no longer -// valid. -type ExpiredTokenException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *ExpiredTokenException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ExpiredTokenException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ExpiredTokenException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ExpiredTokenException" - } - return *e.ErrorCodeOverride -} -func (e *ExpiredTokenException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that an error from the service occurred while trying to process a -// request. -type InternalServerException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InternalServerException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InternalServerException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InternalServerException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InternalServerException" - } - return *e.ErrorCodeOverride -} -func (e *InternalServerException) ErrorFault() smithy.ErrorFault { return smithy.FaultServer } - -// Indicates that the clientId or clientSecret in the request is invalid. For -// example, this can occur when a client sends an incorrect clientId or an expired -// clientSecret . -type InvalidClientException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InvalidClientException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidClientException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidClientException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidClientException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidClientException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the client information sent in the request during registration -// is invalid. -type InvalidClientMetadataException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InvalidClientMetadataException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidClientMetadataException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidClientMetadataException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidClientMetadataException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidClientMetadataException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that a request contains an invalid grant. This can occur if a client -// makes a CreateToken request with an invalid grant type. -type InvalidGrantException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InvalidGrantException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidGrantException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidGrantException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidGrantException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidGrantException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that something is wrong with the input to the request. For example, a -// required parameter might be missing or out of range. -type InvalidRequestException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InvalidRequestException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidRequestException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidRequestException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidRequestException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidRequestException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that a token provided as input to the request was issued by and is -// only usable by calling IAM Identity Center endpoints in another region. -type InvalidRequestRegionException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - Endpoint *string - Region *string - - noSmithyDocumentSerde -} - -func (e *InvalidRequestRegionException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidRequestRegionException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidRequestRegionException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidRequestRegionException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidRequestRegionException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the scope provided in the request is invalid. -type InvalidScopeException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *InvalidScopeException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidScopeException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidScopeException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidScopeException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidScopeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the client is making the request too frequently and is more than -// the service can handle. -type SlowDownException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *SlowDownException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *SlowDownException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *SlowDownException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "SlowDownException" - } - return *e.ErrorCodeOverride -} -func (e *SlowDownException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the client is not currently authorized to make the request. This -// can happen when a clientId is not issued for a public client. -type UnauthorizedClientException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *UnauthorizedClientException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnauthorizedClientException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnauthorizedClientException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnauthorizedClientException" - } - return *e.ErrorCodeOverride -} -func (e *UnauthorizedClientException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// Indicates that the grant type in the request is not supported by the service. -type UnsupportedGrantTypeException struct { - Message *string - - ErrorCodeOverride *string - - Error_ *string - Error_description *string - - noSmithyDocumentSerde -} - -func (e *UnsupportedGrantTypeException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *UnsupportedGrantTypeException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *UnsupportedGrantTypeException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "UnsupportedGrantTypeException" - } - return *e.ErrorCodeOverride -} -func (e *UnsupportedGrantTypeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/types.go deleted file mode 100644 index 0ec0789f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/types/types.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - smithydocument "github.com/aws/smithy-go/document" -) - -type noSmithyDocumentSerde = smithydocument.NoSerde diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/validators.go deleted file mode 100644 index 9c17e4c8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/ssooidc/validators.go +++ /dev/null @@ -1,184 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package ssooidc - -import ( - "context" - "fmt" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -type validateOpCreateToken struct { -} - -func (*validateOpCreateToken) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateToken) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateTokenInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateTokenInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpCreateTokenWithIAM struct { -} - -func (*validateOpCreateTokenWithIAM) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpCreateTokenWithIAM) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*CreateTokenWithIAMInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpCreateTokenWithIAMInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpRegisterClient struct { -} - -func (*validateOpRegisterClient) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpRegisterClient) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*RegisterClientInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpRegisterClientInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpStartDeviceAuthorization struct { -} - -func (*validateOpStartDeviceAuthorization) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpStartDeviceAuthorization) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*StartDeviceAuthorizationInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpStartDeviceAuthorizationInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -func addOpCreateTokenValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateToken{}, middleware.After) -} - -func addOpCreateTokenWithIAMValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpCreateTokenWithIAM{}, middleware.After) -} - -func addOpRegisterClientValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpRegisterClient{}, middleware.After) -} - -func addOpStartDeviceAuthorizationValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpStartDeviceAuthorization{}, middleware.After) -} - -func validateOpCreateTokenInput(v *CreateTokenInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateTokenInput"} - if v.ClientId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientId")) - } - if v.ClientSecret == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientSecret")) - } - if v.GrantType == nil { - invalidParams.Add(smithy.NewErrParamRequired("GrantType")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpCreateTokenWithIAMInput(v *CreateTokenWithIAMInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "CreateTokenWithIAMInput"} - if v.ClientId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientId")) - } - if v.GrantType == nil { - invalidParams.Add(smithy.NewErrParamRequired("GrantType")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpRegisterClientInput(v *RegisterClientInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "RegisterClientInput"} - if v.ClientName == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientName")) - } - if v.ClientType == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientType")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpStartDeviceAuthorizationInput(v *StartDeviceAuthorizationInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "StartDeviceAuthorizationInput"} - if v.ClientId == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientId")) - } - if v.ClientSecret == nil { - invalidParams.Add(smithy.NewErrParamRequired("ClientSecret")) - } - if v.StartUrl == nil { - invalidParams.Add(smithy.NewErrParamRequired("StartUrl")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} 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 deleted file mode 100644 index f9b6404d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/CHANGELOG.md +++ /dev/null @@ -1,395 +0,0 @@ -# v1.26.7 (2024-01-04) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.26.6 (2023-12-20) - -* No change notes available for this release. - -# v1.26.5 (2023-12-08) - -* **Bug Fix**: Reinstate presence of default Retryer in functional options, but still respect max attempts set therein. - -# v1.26.4 (2023-12-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.26.3 (2023-12-06) - -* **Bug Fix**: Restore pre-refactor auth behavior where all operations could technically be performed anonymously. -* **Bug Fix**: STS `AssumeRoleWithSAML` and `AssumeRoleWithWebIdentity` would incorrectly attempt to use SigV4 authentication. - -# v1.26.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.26.1 (2023-11-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.26.0 (2023-11-29) - -* **Feature**: Expose Options() accessor on service clients. -* **Documentation**: Documentation updates for AWS Security Token Service. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.6 (2023-11-28.2) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.5 (2023-11-28) - -* **Bug Fix**: Respect setting RetryMaxAttempts in functional options at client construction. - -# v1.25.4 (2023-11-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.3 (2023-11-17) - -* **Documentation**: API updates for the AWS Security Token Service - -# v1.25.2 (2023-11-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.1 (2023-11-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.25.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.24.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.23.2 (2023-10-12) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.23.1 (2023-10-06) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.23.0 (2023-10-02) - -* **Feature**: STS API updates for assumeRole - -# v1.22.0 (2023-09-18) - -* **Announcement**: [BREAKFIX] Change in MaxResults datatype from value to pointer type in cognito-sync service. -* **Feature**: Adds several endpoint ruleset changes across all models: smaller rulesets, removed non-unique regional endpoints, fixes FIPS and DualStack endpoints, and make region not required in SDK::Endpoint. Additional breakfix to cognito-sync field. - -# v1.21.5 (2023-08-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.4 (2023-08-18) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.3 (2023-08-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.2 (2023-08-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.21.1 (2023-08-01) - -* No change notes available for this release. - -# v1.21.0 (2023-07-31) - -* **Feature**: Adds support for smithy-modeled endpoint resolution. A new rules-based endpoint resolution will be added to the SDK which will supercede and deprecate existing endpoint resolution. Specifically, EndpointResolver will be deprecated while BaseEndpoint and EndpointResolverV2 will take its place. For more information, please see the Endpoints section in our Developer Guide. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.20.1 (2023-07-28) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.20.0 (2023-07-25) - -* **Feature**: API updates for the AWS Security Token Service - -# v1.19.3 (2023-07-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.2 (2023-06-15) - -* No change notes available for this release. - -# v1.19.1 (2023-06-13) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.19.0 (2023-05-08) - -* **Feature**: Documentation updates for AWS Security Token Service. - -# v1.18.11 (2023-05-04) - -* No change notes available for this release. - -# v1.18.10 (2023-04-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.9 (2023-04-10) - -* No change notes available for this release. - -# v1.18.8 (2023-04-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.7 (2023-03-21) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.6 (2023-03-10) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.5 (2023-02-22) - -* **Bug Fix**: Prevent nil pointer dereference when retrieving error codes. - -# v1.18.4 (2023-02-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.18.3 (2023-02-03) - -* **Dependency Update**: Updated to the latest SDK module versions -* **Dependency Update**: Upgrade smithy to 1.27.2 and correct empty query list serialization. - -# v1.18.2 (2023-01-25) - -* **Documentation**: Doc only change to update wording in a key topic - -# v1.18.1 (2023-01-23) - -* No change notes available for this release. - -# v1.18.0 (2023-01-05) - -* **Feature**: Add `ErrorCodeOverride` field to all error structs (aws/smithy-go#401). - -# v1.17.7 (2022-12-15) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.6 (2022-12-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.5 (2022-11-22) - -* No change notes available for this release. - -# v1.17.4 (2022-11-17) - -* **Documentation**: Documentation updates for AWS Security Token Service. - -# v1.17.3 (2022-11-16) - -* No change notes available for this release. - -# v1.17.2 (2022-11-10) - -* No change notes available for this release. - -# v1.17.1 (2022-10-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.17.0 (2022-10-21) - -* **Feature**: Add presign functionality for sts:AssumeRole operation -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.19 (2022-09-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.18 (2022-09-14) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.17 (2022-09-02) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.16 (2022-08-31) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.15 (2022-08-30) - -* No change notes available for this release. - -# v1.16.14 (2022-08-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.13 (2022-08-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.12 (2022-08-09) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.11 (2022-08-08) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.10 (2022-08-01) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.9 (2022-07-05) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.8 (2022-06-29) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.7 (2022-06-07) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.6 (2022-05-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.5 (2022-05-16) - -* **Documentation**: Documentation updates for AWS Security Token Service. - -# v1.16.4 (2022-04-25) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.3 (2022-03-30) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.2 (2022-03-24) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.1 (2022-03-23) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.16.0 (2022-03-08) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Documentation**: Updated service client model to latest release. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.15.0 (2022-02-24) - -* **Feature**: API client updated -* **Feature**: Adds RetryMaxAttempts and RetryMod to API client Options. This allows the API clients' default Retryer to be configured from the shared configuration files or environment variables. Adding a new Retry mode of `Adaptive`. `Adaptive` retry mode is an experimental mode, adding client rate limiting when throttles reponses are received from an API. See [retry.AdaptiveMode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws/retry#AdaptiveMode) for more details, and configuration options. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.14.0 (2022-01-14) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.13.0 (2022-01-07) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.12.0 (2021-12-21) - -* **Feature**: Updated to latest service endpoints - -# v1.11.1 (2021-12-02) - -* **Bug Fix**: Fixes a bug that prevented aws.EndpointResolverWithOptions from being used by the service client. ([#1514](https://github.com/aws/aws-sdk-go-v2/pull/1514)) -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.11.0 (2021-11-30) - -* **Feature**: API client updated - -# v1.10.1 (2021-11-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.10.0 (2021-11-12) - -* **Feature**: Service clients now support custom endpoints that have an initial URI path defined. - -# v1.9.0 (2021-11-06) - -* **Feature**: The SDK now supports configuration of FIPS and DualStack endpoints using environment variables, shared configuration, or programmatically. -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.8.0 (2021-10-21) - -* **Feature**: API client updated -* **Feature**: Updated to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.2 (2021-10-11) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.1 (2021-09-17) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.7.0 (2021-08-27) - -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.2 (2021-08-19) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.1 (2021-08-04) - -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version. -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.6.0 (2021-07-15) - -* **Feature**: The ErrorCode method on generated service error types has been corrected to match the API model. -* **Documentation**: Updated service model to latest revision. -* **Dependency Update**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.5.0 (2021-06-25) - -* **Feature**: API client updated -* **Feature**: Updated `github.com/aws/smithy-go` to latest version -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.1 (2021-05-20) - -* **Dependency Update**: Updated to the latest SDK module versions - -# v1.4.0 (2021-05-14) - -* **Feature**: Constant has been added to modules to enable runtime version inspection for reporting. -* **Dependency Update**: Updated to the latest SDK module versions - diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/LICENSE.txt deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/LICENSE.txt +++ /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/aws/aws-sdk-go-v2/service/sts/api_client.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go deleted file mode 100644 index 369de83b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_client.go +++ /dev/null @@ -1,627 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws" - "github.com/aws/aws-sdk-go-v2/aws/defaults" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/protocol/query" - "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" - acceptencodingcust "github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding" - presignedurlcust "github.com/aws/aws-sdk-go-v2/service/internal/presigned-url" - smithy "github.com/aws/smithy-go" - smithydocument "github.com/aws/smithy-go/document" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net" - "net/http" - "time" -) - -const ServiceID = "STS" -const ServiceAPIVersion = "2011-06-15" - -// Client provides the API client to make operations call for AWS Security Token -// Service. -type Client struct { - options Options -} - -// 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() - - resolveDefaultLogger(&options) - - setResolvedDefaultsMode(&options) - - resolveRetryer(&options) - - resolveHTTPClient(&options) - - resolveHTTPSignerV4(&options) - - resolveEndpointResolverV2(&options) - - resolveAuthSchemeResolver(&options) - - for _, fn := range optFns { - fn(&options) - } - - finalizeRetryMaxAttempts(&options) - - ignoreAnonymousAuth(&options) - - wrapWithAnonymousAuth(&options) - - resolveAuthSchemes(&options) - - client := &Client{ - options: options, - } - - return client -} - -// 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) { - ctx = middleware.ClearStackValues(ctx) - stack := middleware.NewStack(opID, smithyhttp.NewStackRequest) - options := c.options.Copy() - - for _, fn := range optFns { - fn(&options) - } - - finalizeOperationRetryMaxAttempts(&options, *c) - - finalizeClientEndpointResolverOptions(&options) - - for _, fn := range stackFns { - if err := fn(stack, options); err != nil { - return nil, metadata, err - } - } - - for _, fn := range options.APIOptions { - if err := fn(stack); err != nil { - return nil, metadata, err - } - } - - handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack) - result, metadata, err = handler.Handle(ctx, params) - if err != nil { - err = &smithy.OperationError{ - ServiceID: ServiceID, - OperationName: opID, - Err: err, - } - } - 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{}, "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 { - LegacyResolver EndpointResolver -} - -func (*legacyEndpointContextSetter) ID() string { - return "legacyEndpointContextSetter" -} - -func (m *legacyEndpointContextSetter) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - if m.LegacyResolver != nil { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true) - } - - return next.HandleInitialize(ctx, in) - -} -func addlegacyEndpointContextSetter(stack *middleware.Stack, o Options) error { - return stack.Initialize.Add(&legacyEndpointContextSetter{ - LegacyResolver: o.EndpointResolver, - }, middleware.Before) -} - -func resolveDefaultLogger(o *Options) { - if o.Logger != nil { - return - } - o.Logger = logging.Nop{} -} - -func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error { - return middleware.AddSetLoggerMiddleware(stack, o.Logger) -} - -func setResolvedDefaultsMode(o *Options) { - if len(o.resolvedDefaultsMode) > 0 { - return - } - - var mode aws.DefaultsMode - mode.SetFromString(string(o.DefaultsMode)) - - if mode == aws.DefaultsModeAuto { - mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment) - } - - o.resolvedDefaultsMode = mode -} - -// NewFromConfig returns a new client from the provided config. -func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client { - opts := Options{ - Region: cfg.Region, - DefaultsMode: cfg.DefaultsMode, - RuntimeEnvironment: cfg.RuntimeEnvironment, - HTTPClient: cfg.HTTPClient, - Credentials: cfg.Credentials, - APIOptions: cfg.APIOptions, - Logger: cfg.Logger, - ClientLogMode: cfg.ClientLogMode, - AppID: cfg.AppID, - } - resolveAWSRetryerProvider(cfg, &opts) - resolveAWSRetryMaxAttempts(cfg, &opts) - resolveAWSRetryMode(cfg, &opts) - resolveAWSEndpointResolver(cfg, &opts) - resolveUseDualStackEndpoint(cfg, &opts) - resolveUseFIPSEndpoint(cfg, &opts) - resolveBaseEndpoint(cfg, &opts) - return New(opts, optFns...) -} - -func resolveHTTPClient(o *Options) { - var buildable *awshttp.BuildableClient - - if o.HTTPClient != nil { - var ok bool - buildable, ok = o.HTTPClient.(*awshttp.BuildableClient) - if !ok { - return - } - } else { - buildable = awshttp.NewBuildableClient() - } - - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) { - if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok { - dialer.Timeout = dialerTimeout - } - }) - - buildable = buildable.WithTransportOptions(func(transport *http.Transport) { - if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok { - transport.TLSHandshakeTimeout = tlsHandshakeTimeout - } - }) - } - - o.HTTPClient = buildable -} - -func resolveRetryer(o *Options) { - if o.Retryer != nil { - return - } - - if len(o.RetryMode) == 0 { - modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode) - if err == nil { - o.RetryMode = modeConfig.RetryMode - } - } - if len(o.RetryMode) == 0 { - o.RetryMode = aws.RetryModeStandard - } - - var standardOptions []func(*retry.StandardOptions) - if v := o.RetryMaxAttempts; v != 0 { - standardOptions = append(standardOptions, func(so *retry.StandardOptions) { - so.MaxAttempts = v - }) - } - - switch o.RetryMode { - case aws.RetryModeAdaptive: - var adaptiveOptions []func(*retry.AdaptiveModeOptions) - if len(standardOptions) != 0 { - adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) { - ao.StandardOptions = append(ao.StandardOptions, standardOptions...) - }) - } - o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...) - - default: - o.Retryer = retry.NewStandard(standardOptions...) - } -} - -func resolveAWSRetryerProvider(cfg aws.Config, o *Options) { - if cfg.Retryer == nil { - return - } - o.Retryer = cfg.Retryer() -} - -func resolveAWSRetryMode(cfg aws.Config, o *Options) { - if len(cfg.RetryMode) == 0 { - return - } - o.RetryMode = cfg.RetryMode -} -func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) { - if cfg.RetryMaxAttempts == 0 { - return - } - o.RetryMaxAttempts = cfg.RetryMaxAttempts -} - -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 - } - - o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts) -} - -func resolveAWSEndpointResolver(cfg aws.Config, o *Options) { - if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil { - return - } - o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions) -} - -func addClientUserAgent(stack *middleware.Stack, options Options) error { - if err := awsmiddleware.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "sts", goModuleVersion)(stack); err != nil { - return err - } - - if len(options.AppID) > 0 { - return awsmiddleware.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID)(stack) - } - - return nil -} - -type HTTPSignerV4 interface { - SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error -} - -func resolveHTTPSignerV4(o *Options) { - if o.HTTPSignerV4 != nil { - return - } - o.HTTPSignerV4 = newDefaultV4Signer(*o) -} - -func newDefaultV4Signer(o Options) *v4.Signer { - return v4.NewSigner(func(so *v4.SignerOptions) { - so.Logger = o.Logger - so.LogSigning = o.ClientLogMode.IsSigning() - }) -} - -func addRetryMiddlewares(stack *middleware.Stack, o Options) error { - mo := retry.AddRetryMiddlewaresOptions{ - Retryer: o.Retryer, - LogRetryAttempts: o.ClientLogMode.IsRetries(), - } - return retry.AddRetryMiddlewares(stack, mo) -} - -// resolves dual-stack endpoint configuration -func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseDualStackEndpoint = value - } - return nil -} - -// resolves FIPS endpoint configuration -func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error { - if len(cfg.ConfigSources) == 0 { - return nil - } - value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources) - if err != nil { - return err - } - if found { - o.EndpointOptions.UseFIPSEndpoint = value - } - return nil -} - -func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error { - return awsmiddleware.AddRequestIDRetrieverMiddleware(stack) -} - -func addResponseErrorMiddleware(stack *middleware.Stack) error { - return awshttp.AddResponseErrorMiddleware(stack) -} - -// HTTPPresignerV4 represents presigner interface used by presign url client -type HTTPPresignerV4 interface { - PresignHTTP( - ctx context.Context, credentials aws.Credentials, r *http.Request, - payloadHash string, service string, region string, signingTime time.Time, - optFns ...func(*v4.SignerOptions), - ) (url string, signedHeader http.Header, err error) -} - -// PresignOptions represents the presign client options -type PresignOptions struct { - - // ClientOptions are list of functional options to mutate client options used by - // the presign client. - ClientOptions []func(*Options) - - // Presigner is the presigner used by the presign url client - Presigner HTTPPresignerV4 -} - -func (o PresignOptions) copy() PresignOptions { - clientOptions := make([]func(*Options), len(o.ClientOptions)) - copy(clientOptions, o.ClientOptions) - o.ClientOptions = clientOptions - return o -} - -// WithPresignClientFromClientOptions is a helper utility to retrieve a function -// that takes PresignOption as input -func WithPresignClientFromClientOptions(optFns ...func(*Options)) func(*PresignOptions) { - return withPresignClientFromClientOptions(optFns).options -} - -type withPresignClientFromClientOptions []func(*Options) - -func (w withPresignClientFromClientOptions) options(o *PresignOptions) { - o.ClientOptions = append(o.ClientOptions, w...) -} - -// PresignClient represents the presign url client -type PresignClient struct { - client *Client - options PresignOptions -} - -// NewPresignClient generates a presign client using provided API Client and -// presign options -func NewPresignClient(c *Client, optFns ...func(*PresignOptions)) *PresignClient { - var options PresignOptions - for _, fn := range optFns { - fn(&options) - } - if len(options.ClientOptions) != 0 { - c = New(c.options, options.ClientOptions...) - } - - if options.Presigner == nil { - options.Presigner = newDefaultV4Signer(c.options) - } - - return &PresignClient{ - client: c, - options: options, - } -} - -func withNopHTTPClientAPIOption(o *Options) { - o.HTTPClient = smithyhttp.NopClient{} -} - -type presignContextPolyfillMiddleware struct { -} - -func (*presignContextPolyfillMiddleware) ID() string { - return "presignContextPolyfill" -} - -func (m *presignContextPolyfillMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) ( - out middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - rscheme := getResolvedAuthScheme(ctx) - if rscheme == nil { - return out, metadata, fmt.Errorf("no resolved auth scheme") - } - - schemeID := rscheme.Scheme.SchemeID() - - if schemeID == "aws.auth#sigv4" || schemeID == "com.amazonaws.s3#sigv4express" { - if sn, ok := smithyhttp.GetSigV4SigningName(&rscheme.SignerProperties); ok { - ctx = awsmiddleware.SetSigningName(ctx, sn) - } - if sr, ok := smithyhttp.GetSigV4SigningRegion(&rscheme.SignerProperties); ok { - ctx = awsmiddleware.SetSigningRegion(ctx, sr) - } - } else if schemeID == "aws.auth#sigv4a" { - if sn, ok := smithyhttp.GetSigV4ASigningName(&rscheme.SignerProperties); ok { - ctx = awsmiddleware.SetSigningName(ctx, sn) - } - if sr, ok := smithyhttp.GetSigV4ASigningRegions(&rscheme.SignerProperties); ok { - ctx = awsmiddleware.SetSigningRegion(ctx, sr[0]) - } - } - - return next.HandleFinalize(ctx, in) -} - -type presignConverter PresignOptions - -func (c presignConverter) convertToPresignMiddleware(stack *middleware.Stack, options Options) (err error) { - if _, ok := stack.Finalize.Get((*acceptencodingcust.DisableGzip)(nil).ID()); ok { - stack.Finalize.Remove((*acceptencodingcust.DisableGzip)(nil).ID()) - } - if _, ok := stack.Finalize.Get((*retry.Attempt)(nil).ID()); ok { - stack.Finalize.Remove((*retry.Attempt)(nil).ID()) - } - if _, ok := stack.Finalize.Get((*retry.MetricsHeader)(nil).ID()); ok { - stack.Finalize.Remove((*retry.MetricsHeader)(nil).ID()) - } - stack.Deserialize.Clear() - stack.Build.Remove((*awsmiddleware.ClientRequestID)(nil).ID()) - stack.Build.Remove("UserAgent") - if err := stack.Finalize.Insert(&presignContextPolyfillMiddleware{}, "Signing", middleware.Before); err != nil { - return err - } - - pmw := v4.NewPresignHTTPRequestMiddleware(v4.PresignHTTPRequestMiddlewareOptions{ - CredentialsProvider: options.Credentials, - Presigner: c.Presigner, - LogSigning: options.ClientLogMode.IsSigning(), - }) - if _, err := stack.Finalize.Swap("Signing", pmw); err != nil { - return err - } - if err = smithyhttp.AddNoPayloadDefaultContentTypeRemover(stack); err != nil { - return err - } - // convert request to a GET request - err = query.AddAsGetRequestMiddleware(stack) - if err != nil { - return err - } - err = presignedurlcust.AddAsIsPresigingMiddleware(stack) - if err != nil { - return err - } - return nil -} - -func addRequestResponseLogging(stack *middleware.Stack, o Options) error { - return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{ - LogRequest: o.ClientLogMode.IsRequest(), - LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(), - LogResponse: o.ClientLogMode.IsResponse(), - LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(), - }, middleware.After) -} - -type disableHTTPSMiddleware struct { - DisableHTTPS bool -} - -func (*disableHTTPSMiddleware) ID() string { - return "disableHTTPS" -} - -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.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) -} 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 deleted file mode 100644 index 2938dac8..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRole.go +++ /dev/null @@ -1,439 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a set of temporary security credentials that you can use to access -// Amazon Web Services resources. These temporary credentials consist of an access -// key ID, a secret access key, and a security token. Typically, you use AssumeRole -// within your account or for cross-account access. For a comparison of AssumeRole -// with other API operations that produce temporary credentials, see Requesting -// Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. Permissions The temporary security credentials created by -// AssumeRole can be used to make API calls to any Amazon Web Services service -// with the following exception: You cannot call the Amazon Web Services STS -// GetFederationToken or GetSessionToken API operations. (Optional) You can pass -// inline or managed session policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that you -// use for both inline and managed session policies can't exceed 2,048 characters. -// Passing policies to this operation returns new temporary credentials. The -// resulting session's permissions are the intersection of the role's -// identity-based policy and the session policies. You can use the role's temporary -// credentials in subsequent Amazon Web Services API calls to access resources in -// the account that owns the role. You cannot use session policies to grant more -// permissions than those allowed by the identity-based policy of the role that is -// being assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. When you create a role, you create two policies: a role -// trust policy that specifies who can assume the role, and a permissions policy -// that specifies what can be done with the role. You specify the trusted principal -// that is allowed to assume the role in the role trust policy. To assume a role -// from a different account, your Amazon Web Services account must be trusted by -// the role. The trust relationship is defined in the role's trust policy when the -// role is created. That trust policy states which accounts are allowed to delegate -// that access to users in the account. A user who wants to access a role in a -// different account must also have permissions that are delegated from the account -// administrator. The administrator must attach a policy that allows the user to -// call AssumeRole for the ARN of the role in the other account. To allow a user -// to assume a role in the same account, you can do either of the following: -// - Attach a policy to the user that allows the user to call AssumeRole (as long -// as the role's trust policy trusts the account). -// - Add the user as a principal directly in the role's trust policy. -// -// You can do either because the role’s trust policy acts as an IAM resource-based -// policy. When a resource-based policy grants access to a principal in the same -// account, no additional identity-based policy is required. For more information -// about trust policies and resource-based policies, see IAM Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) -// in the IAM User Guide. Tags (Optional) You can pass tag key-value pairs to your -// session. These tags are called session tags. For more information about session -// tags, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. An administrator must grant you the permissions necessary -// to pass session tags. The administrator can also create granular permissions to -// allow you to pass only specific session tags. For more information, see -// Tutorial: Using Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. You can set the session tags as transitive. Transitive -// tags persist during role chaining. For more information, see Chaining Roles -// with Session Tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) -// in the IAM User Guide. Using MFA with AssumeRole (Optional) You can include -// multi-factor authentication (MFA) information when you call AssumeRole . This is -// useful for cross-account scenarios to ensure that the user that assumes the role -// has been authenticated with an Amazon Web Services MFA device. In that scenario, -// the trust policy of the role being assumed includes a condition that tests for -// MFA authentication. If the caller does not include valid MFA information, the -// request to assume the role is denied. The condition in a trust policy that tests -// for MFA authentication might look like the following example. "Condition": -// {"Bool": {"aws:MultiFactorAuthPresent": true}} For more information, see -// Configuring MFA-Protected API Access (https://docs.aws.amazon.com/IAM/latest/UserGuide/MFAProtectedAPI.html) -// in the IAM User Guide guide. To use MFA with AssumeRole , you pass values for -// the SerialNumber and TokenCode parameters. The SerialNumber value identifies -// the user's hardware or virtual MFA device. The TokenCode is the time-based -// one-time password (TOTP) that the MFA device produces. -func (c *Client) AssumeRole(ctx context.Context, params *AssumeRoleInput, optFns ...func(*Options)) (*AssumeRoleOutput, error) { - if params == nil { - params = &AssumeRoleInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "AssumeRole", params, optFns, c.addOperationAssumeRoleMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*AssumeRoleOutput) - out.ResultMetadata = metadata - return out, nil -} - -type AssumeRoleInput struct { - - // The Amazon Resource Name (ARN) of the role to assume. - // - // This member is required. - RoleArn *string - - // An identifier for the assumed role session. Use the role session name to - // uniquely identify a session when the same role is assumed by different - // principals or for different reasons. In cross-account scenarios, the role - // session name is visible to, and can be logged by the account that owns the role. - // The role session name is also used in the ARN of the assumed role principal. - // This means that subsequent cross-account API requests that use the temporary - // security credentials will expose the role session name to the external account - // in their CloudTrail logs. 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: - // =,.@- - // - // This member is required. - RoleSessionName *string - - // The duration, in seconds, of the role session. The value specified can range - // from 900 seconds (15 minutes) up to the maximum session duration set for the - // role. The maximum session duration setting can have a value from 1 hour to 12 - // hours. If you specify a value higher than this setting or the administrator - // setting (whichever is lower), the operation fails. For example, if you specify a - // session duration of 12 hours, but your administrator set the maximum session - // duration to 6 hours, your operation fails. Role chaining limits your Amazon Web - // Services CLI or Amazon Web Services API role session to a maximum of one hour. - // When you use the AssumeRole API operation to assume a role, you can specify the - // duration of your role session with the DurationSeconds parameter. You can - // specify a parameter value of up to 43200 seconds (12 hours), depending on the - // maximum session duration setting for your role. However, if you assume a role - // using role chaining and provide a DurationSeconds parameter value greater than - // one hour, the operation fails. To learn how to view the maximum value for your - // role, see View the Maximum Session Duration Setting for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. By default, the value is set to 3600 seconds. The - // DurationSeconds parameter is separate from the duration of a console session - // that you might request using the returned credentials. The request to the - // federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // Amazon Web Services Management Console (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int32 - - // A unique identifier that might be required when you assume a role in another - // account. If the administrator of the account to which the role belongs provided - // you with an external ID, then provide that value in the ExternalId parameter. - // This value can be any string, such as a passphrase or account number. A - // cross-account role is usually set up to trust everyone in an account. Therefore, - // the administrator of the trusting account might send an external ID to the - // administrator of the trusted account. That way, only someone with the ID can - // assume the role, rather than everyone in the account. For more information about - // the external ID, see How to Use an External ID When Granting Access to Your - // Amazon Web Services Resources to a Third Party (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html) - // in the IAM User Guide. 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: - // =,.@:/- - ExternalId *string - - // An IAM policy in JSON format that you want to use as an inline session policy. - // This parameter is optional. Passing policies to this operation returns new - // temporary credentials. The resulting session's permissions are the intersection - // of the role's identity-based policy and the session policies. You can use the - // role's temporary credentials in subsequent Amazon Web Services API calls to - // access resources in the account that owns the role. You cannot use session - // policies to grant more permissions than those allowed by the identity-based - // policy of the role that is being assumed. For more information, see Session - // Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. The plaintext that you use for both inline and managed - // session policies can't exceed 2,048 characters. The JSON policy characters can - // be any ASCII character from the space character to the end of the valid - // character list (\u0020 through \u00FF). It can also include the tab (\u0009), - // linefeed (\u000A), and carriage return (\u000D) characters. An Amazon Web - // Services conversion compresses the passed inline session policy, managed policy - // ARNs, and session tags into a packed binary format that has a separate limit. - // Your request can fail for this limit even if your plaintext meets the other - // requirements. The PackedPolicySize response element indicates by percentage how - // close the policies and tags for your request are to the upper size limit. - Policy *string - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want to - // use as managed session policies. The policies must exist in the same account as - // the role. This parameter is optional. You can provide up to 10 managed policy - // ARNs. However, the plaintext that you use for both inline and managed session - // policies can't exceed 2,048 characters. For more information about ARNs, see - // Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. An Amazon Web Services conversion - // compresses the passed inline session policy, managed policy ARNs, and session - // tags into a packed binary format that has a separate limit. Your request can - // fail for this limit even if your plaintext meets the other requirements. The - // PackedPolicySize response element indicates by percentage how close the policies - // and tags for your request are to the upper size limit. Passing policies to this - // operation returns new temporary credentials. The resulting session's permissions - // are the intersection of the role's identity-based policy and the session - // policies. You can use the role's temporary credentials in subsequent Amazon Web - // Services API calls to access resources in the account that owns the role. You - // cannot use session policies to grant more permissions than those allowed by the - // identity-based policy of the role that is being assumed. For more information, - // see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyArns []types.PolicyDescriptorType - - // A list of previously acquired trusted context assertions in the format of a - // JSON array. The trusted context assertion is signed and encrypted by Amazon Web - // Services STS. The following is an example of a ProvidedContext value that - // includes a single trusted context assertion and the ARN of the context provider - // from which the trusted context assertion was generated. - // [{"ProviderArn":"arn:aws:iam::aws:contextProvider/IdentityCenter","ContextAssertion":"trusted-context-assertion"}] - ProvidedContexts []types.ProvidedContext - - // The identification number of the MFA device that is associated with the user - // who is making the AssumeRole call. Specify this value if the trust policy of - // the role being assumed includes a condition that requires MFA authentication. - // The value is either the serial number for a hardware device (such as - // GAHT12345678 ) or an Amazon Resource Name (ARN) for a virtual device (such as - // arn:aws:iam::123456789012:mfa/user ). 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: =,.@- - SerialNumber *string - - // The source identity specified by the principal that is calling the AssumeRole - // operation. You can require users to specify a source identity when they assume a - // role. You do this by using the sts:SourceIdentity condition key in a role trust - // policy. You can use source identity information in CloudTrail logs to determine - // who took actions with a role. You can use the aws:SourceIdentity condition key - // to further control access to Amazon Web Services resources based on the value of - // source identity. For more information about using source identity, see Monitor - // and control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. 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 value that begins with the text aws: . This prefix is - // reserved for Amazon Web Services internal use. - SourceIdentity *string - - // A list of session tags that you want to pass. Each session tag consists of a - // key name and an associated value. For more information about session tags, see - // Tagging Amazon Web Services STS Sessions (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) - // in the IAM User Guide. This parameter is optional. You can pass up to 50 session - // tags. The plaintext session tag keys can’t exceed 128 characters, and the values - // can’t exceed 256 characters. For these and additional limits, see IAM and STS - // Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. An Amazon Web Services conversion compresses the passed - // inline session policy, managed policy ARNs, and session tags into a packed - // binary format that has a separate limit. Your request can fail for this limit - // even if your plaintext meets the other requirements. The PackedPolicySize - // response element indicates by percentage how close the policies and tags for - // your request are to the upper size limit. You can pass a session tag with the - // same key as a tag that is already attached to the role. When you do, session - // tags override a role tag with the same key. Tag key–value pairs are not case - // sensitive, but case is preserved. This means that you cannot have separate - // Department and department tag keys. Assume that the role has the Department = - // Marketing tag and you pass the department = engineering session tag. Department - // and department are not saved as separate tags, and the session tag passed in - // the request takes precedence over the role tag. Additionally, if you used - // temporary credentials to perform this operation, the new session inherits any - // transitive session tags from the calling session. If you pass a session tag with - // the same key as an inherited tag, the operation fails. To view the inherited - // tags for a session, see the CloudTrail logs. For more information, see Viewing - // Session Tags in CloudTrail (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_ctlogs) - // in the IAM User Guide. - Tags []types.Tag - - // The value provided by the MFA device, if the trust policy of the role being - // assumed requires MFA. (In other words, if the policy includes a condition that - // tests for MFA). If the role being assumed requires MFA and if the TokenCode - // value is missing or expired, the AssumeRole call returns an "access denied" - // error. The format for this parameter, as described by its regex pattern, is a - // sequence of six numeric digits. - TokenCode *string - - // A list of keys for session tags that you want to set as transitive. If you set - // a tag key as transitive, the corresponding key and value passes to subsequent - // sessions in a role chain. For more information, see Chaining Roles with Session - // Tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) - // in the IAM User Guide. This parameter is optional. When you set session tags as - // transitive, the session policy and session tags packed binary limit is not - // affected. If you choose not to specify a transitive tag key, then no tags are - // passed from this session to any subsequent sessions. - TransitiveTagKeys []string - - noSmithyDocumentSerde -} - -// Contains the response to a successful AssumeRole request, including temporary -// Amazon Web Services credentials that can be used to make Amazon Web Services -// requests. -type AssumeRoleOutput struct { - - // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers - // that you can use to refer to the resulting temporary security credentials. For - // example, you can reference these credentials as a principal in a resource-based - // policy by using the ARN or assumed role ID. The ARN and ID include the - // RoleSessionName that you specified when you called AssumeRole . - AssumedRoleUser *types.AssumedRoleUser - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. The size of the security token - // that STS API operations return is not fixed. We strongly recommend that you make - // no assumptions about the maximum size. - Credentials *types.Credentials - - // A percentage value that indicates the packed size of the session policies and - // session tags combined passed in the request. The request fails if the packed - // size is greater than 100 percent, which means the policies and tags exceeded the - // allowed space. - PackedPolicySize *int32 - - // The source identity specified by the principal that is calling the AssumeRole - // operation. You can require users to specify a source identity when they assume a - // role. You do this by using the sts:SourceIdentity condition key in a role trust - // policy. You can use source identity information in CloudTrail logs to determine - // who took actions with a role. You can use the aws:SourceIdentity condition key - // to further control access to Amazon Web Services resources based on the value of - // source identity. For more information about using source identity, see Monitor - // and control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. 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: - // =,.@- - SourceIdentity *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationAssumeRoleMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsquery_serializeOpAssumeRole{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpAssumeRole{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "AssumeRole"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpAssumeRoleValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAssumeRole(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opAssumeRole(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "AssumeRole", - } -} - -// PresignAssumeRole is used to generate a presigned HTTP Request which contains -// presigned URL, signed headers and HTTP method used. -func (c *PresignClient) PresignAssumeRole(ctx context.Context, params *AssumeRoleInput, optFns ...func(*PresignOptions)) (*v4.PresignedHTTPRequest, error) { - if params == nil { - params = &AssumeRoleInput{} - } - options := c.options.copy() - for _, fn := range optFns { - fn(&options) - } - clientOptFns := append(options.ClientOptions, withNopHTTPClientAPIOption) - - result, _, err := c.client.invokeOperation(ctx, "AssumeRole", params, clientOptFns, - c.client.addOperationAssumeRoleMiddlewares, - presignConverter(options).convertToPresignMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*v4.PresignedHTTPRequest) - return out, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithSAML.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithSAML.go deleted file mode 100644 index ef576b64..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithSAML.go +++ /dev/null @@ -1,361 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a set of temporary security credentials for users who have been -// authenticated via a SAML authentication response. This operation provides a -// mechanism for tying an enterprise identity store or directory to role-based -// Amazon Web Services access without user-specific credentials or configuration. -// For a comparison of AssumeRoleWithSAML with the other API operations that -// produce temporary credentials, see Requesting Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. The temporary security credentials returned by this -// operation consist of an access key ID, a secret access key, and a security -// token. Applications can use these temporary security credentials to sign calls -// to Amazon Web Services services. Session Duration By default, the temporary -// security credentials created by AssumeRoleWithSAML last for one hour. However, -// you can use the optional DurationSeconds parameter to specify the duration of -// your session. Your role session lasts for the duration that you specify, or -// until the time specified in the SAML authentication response's -// SessionNotOnOrAfter value, whichever is shorter. You can provide a -// DurationSeconds value from 900 seconds (15 minutes) up to the maximum session -// duration setting for the role. This setting can have a value from 1 hour to 12 -// hours. To learn how to view the maximum value for your role, see View the -// Maximum Session Duration Setting for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) -// in the IAM User Guide. The maximum session duration limit applies when you use -// the AssumeRole* API operations or the assume-role* CLI commands. However the -// limit does not apply when you use those operations to create a console URL. For -// more information, see Using IAM Roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. Role chaining (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-role-chaining) -// limits your CLI or Amazon Web Services API role session to a maximum of one -// hour. When you use the AssumeRole API operation to assume a role, you can -// specify the duration of your role session with the DurationSeconds parameter. -// You can specify a parameter value of up to 43200 seconds (12 hours), depending -// on the maximum session duration setting for your role. However, if you assume a -// role using role chaining and provide a DurationSeconds parameter value greater -// than one hour, the operation fails. Permissions The temporary security -// credentials created by AssumeRoleWithSAML can be used to make API calls to any -// Amazon Web Services service with the following exception: you cannot call the -// STS GetFederationToken or GetSessionToken API operations. (Optional) You can -// pass inline or managed session policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that you -// use for both inline and managed session policies can't exceed 2,048 characters. -// Passing policies to this operation returns new temporary credentials. The -// resulting session's permissions are the intersection of the role's -// identity-based policy and the session policies. You can use the role's temporary -// credentials in subsequent Amazon Web Services API calls to access resources in -// the account that owns the role. You cannot use session policies to grant more -// permissions than those allowed by the identity-based policy of the role that is -// being assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. Calling AssumeRoleWithSAML does not require the use of -// Amazon Web Services security credentials. The identity of the caller is -// validated by using keys in the metadata document that is uploaded for the SAML -// provider entity for your identity provider. Calling AssumeRoleWithSAML can -// result in an entry in your CloudTrail logs. The entry includes the value in the -// NameID element of the SAML assertion. We recommend that you use a NameIDType -// that is not associated with any personally identifiable information (PII). For -// example, you could instead use the persistent identifier ( -// urn:oasis:names:tc:SAML:2.0:nameid-format:persistent ). Tags (Optional) You can -// configure your IdP to pass attributes into your SAML assertion as session tags. -// Each session tag consists of a key name and an associated value. For more -// information about session tags, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. You can pass up to 50 session tags. The plaintext session -// tag keys can’t exceed 128 characters and the values can’t exceed 256 characters. -// For these and additional limits, see IAM and STS Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) -// in the IAM User Guide. An Amazon Web Services conversion compresses the passed -// inline session policy, managed policy ARNs, and session tags into a packed -// binary format that has a separate limit. Your request can fail for this limit -// even if your plaintext meets the other requirements. The PackedPolicySize -// response element indicates by percentage how close the policies and tags for -// your request are to the upper size limit. You can pass a session tag with the -// same key as a tag that is attached to the role. When you do, session tags -// override the role's tags with the same key. An administrator must grant you the -// permissions necessary to pass session tags. The administrator can also create -// granular permissions to allow you to pass only specific session tags. For more -// information, see Tutorial: Using Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. You can set the session tags as transitive. Transitive -// tags persist during role chaining. For more information, see Chaining Roles -// with Session Tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) -// in the IAM User Guide. SAML Configuration Before your application can call -// AssumeRoleWithSAML , you must configure your SAML identity provider (IdP) to -// issue the claims required by Amazon Web Services. Additionally, you must use -// Identity and Access Management (IAM) to create a SAML provider entity in your -// Amazon Web Services account that represents your identity provider. You must -// also create an IAM role that specifies this SAML provider in its trust policy. -// For more information, see the following resources: -// - About SAML 2.0-based Federation (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html) -// in the IAM User Guide. -// - Creating SAML Identity Providers (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) -// in the IAM User Guide. -// - Configuring a Relying Party and Claims (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_relying-party.html) -// in the IAM User Guide. -// - Creating a Role for SAML 2.0 Federation (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_saml.html) -// in the IAM User Guide. -func (c *Client) AssumeRoleWithSAML(ctx context.Context, params *AssumeRoleWithSAMLInput, optFns ...func(*Options)) (*AssumeRoleWithSAMLOutput, error) { - if params == nil { - params = &AssumeRoleWithSAMLInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "AssumeRoleWithSAML", params, optFns, c.addOperationAssumeRoleWithSAMLMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*AssumeRoleWithSAMLOutput) - out.ResultMetadata = metadata - return out, nil -} - -type AssumeRoleWithSAMLInput struct { - - // The Amazon Resource Name (ARN) of the SAML provider in IAM that describes the - // IdP. - // - // This member is required. - PrincipalArn *string - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // This member is required. - RoleArn *string - - // The base64 encoded SAML authentication response provided by the IdP. For more - // information, see Configuring a Relying Party and Adding Claims (https://docs.aws.amazon.com/IAM/latest/UserGuide/create-role-saml-IdP-tasks.html) - // in the IAM User Guide. - // - // This member is required. - SAMLAssertion *string - - // The duration, in seconds, of the role session. Your role session lasts for the - // duration that you specify for the DurationSeconds parameter, or until the time - // specified in the SAML authentication response's SessionNotOnOrAfter value, - // whichever is shorter. You can provide a DurationSeconds value from 900 seconds - // (15 minutes) up to the maximum session duration setting for the role. This - // setting can have a value from 1 hour to 12 hours. If you specify a value higher - // than this setting, the operation fails. For example, if you specify a session - // duration of 12 hours, but your administrator set the maximum session duration to - // 6 hours, your operation fails. To learn how to view the maximum value for your - // role, see View the Maximum Session Duration Setting for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. By default, the value is set to 3600 seconds. The - // DurationSeconds parameter is separate from the duration of a console session - // that you might request using the returned credentials. The request to the - // federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // Amazon Web Services Management Console (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int32 - - // An IAM policy in JSON format that you want to use as an inline session policy. - // This parameter is optional. Passing policies to this operation returns new - // temporary credentials. The resulting session's permissions are the intersection - // of the role's identity-based policy and the session policies. You can use the - // role's temporary credentials in subsequent Amazon Web Services API calls to - // access resources in the account that owns the role. You cannot use session - // policies to grant more permissions than those allowed by the identity-based - // policy of the role that is being assumed. For more information, see Session - // Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. The plaintext that you use for both inline and managed - // session policies can't exceed 2,048 characters. The JSON policy characters can - // be any ASCII character from the space character to the end of the valid - // character list (\u0020 through \u00FF). It can also include the tab (\u0009), - // linefeed (\u000A), and carriage return (\u000D) characters. An Amazon Web - // Services conversion compresses the passed inline session policy, managed policy - // ARNs, and session tags into a packed binary format that has a separate limit. - // Your request can fail for this limit even if your plaintext meets the other - // requirements. The PackedPolicySize response element indicates by percentage how - // close the policies and tags for your request are to the upper size limit. - Policy *string - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want to - // use as managed session policies. The policies must exist in the same account as - // the role. This parameter is optional. You can provide up to 10 managed policy - // ARNs. However, the plaintext that you use for both inline and managed session - // policies can't exceed 2,048 characters. For more information about ARNs, see - // Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. An Amazon Web Services conversion - // compresses the passed inline session policy, managed policy ARNs, and session - // tags into a packed binary format that has a separate limit. Your request can - // fail for this limit even if your plaintext meets the other requirements. The - // PackedPolicySize response element indicates by percentage how close the policies - // and tags for your request are to the upper size limit. Passing policies to this - // operation returns new temporary credentials. The resulting session's permissions - // are the intersection of the role's identity-based policy and the session - // policies. You can use the role's temporary credentials in subsequent Amazon Web - // Services API calls to access resources in the account that owns the role. You - // cannot use session policies to grant more permissions than those allowed by the - // identity-based policy of the role that is being assumed. For more information, - // see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyArns []types.PolicyDescriptorType - - noSmithyDocumentSerde -} - -// Contains the response to a successful AssumeRoleWithSAML request, including -// temporary Amazon Web Services credentials that can be used to make Amazon Web -// Services requests. -type AssumeRoleWithSAMLOutput struct { - - // The identifiers for the temporary security credentials that the operation - // returns. - AssumedRoleUser *types.AssumedRoleUser - - // The value of the Recipient attribute of the SubjectConfirmationData element of - // the SAML assertion. - Audience *string - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. The size of the security token - // that STS API operations return is not fixed. We strongly recommend that you make - // no assumptions about the maximum size. - Credentials *types.Credentials - - // The value of the Issuer element of the SAML assertion. - Issuer *string - - // A hash value based on the concatenation of the following: - // - The Issuer response value. - // - The Amazon Web Services account ID. - // - The friendly name (the last part of the ARN) of the SAML provider in IAM. - // The combination of NameQualifier and Subject can be used to uniquely identify a - // user. The following pseudocode shows how the hash value is calculated: BASE64 ( - // SHA1 ( "https://example.com/saml" + "123456789012" + "/MySAMLIdP" ) ) - NameQualifier *string - - // A percentage value that indicates the packed size of the session policies and - // session tags combined passed in the request. The request fails if the packed - // size is greater than 100 percent, which means the policies and tags exceeded the - // allowed space. - PackedPolicySize *int32 - - // The value in the SourceIdentity attribute in the SAML assertion. You can - // require users to set a source identity value when they assume a role. You do - // this by using the sts:SourceIdentity condition key in a role trust policy. That - // way, actions that are taken with the role are associated with that user. After - // the source identity is set, the value cannot be changed. It is present in the - // request for all actions that are taken by the role and persists across chained - // role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts#iam-term-role-chaining) - // sessions. You can configure your SAML identity provider to use an attribute - // associated with your users, like user name or email, as the source identity when - // calling AssumeRoleWithSAML . You do this by adding an attribute to the SAML - // assertion. For more information about using source identity, see Monitor and - // control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. 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: - // =,.@- - SourceIdentity *string - - // The value of the NameID element in the Subject element of the SAML assertion. - Subject *string - - // The format of the name ID, as defined by the Format attribute in the NameID - // element of the SAML assertion. Typical examples of the format are transient or - // persistent . If the format includes the prefix - // urn:oasis:names:tc:SAML:2.0:nameid-format , that prefix is removed. For example, - // urn:oasis:names:tc:SAML:2.0:nameid-format:transient is returned as transient . - // If the format includes any other prefix, the format is returned with no - // modifications. - SubjectType *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationAssumeRoleWithSAMLMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsquery_serializeOpAssumeRoleWithSAML{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpAssumeRoleWithSAML{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "AssumeRoleWithSAML"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpAssumeRoleWithSAMLValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAssumeRoleWithSAML(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opAssumeRoleWithSAML(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "AssumeRoleWithSAML", - } -} 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 deleted file mode 100644 index b2f126b1..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_AssumeRoleWithWebIdentity.go +++ /dev/null @@ -1,380 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a set of temporary security credentials for users who have been -// authenticated in a mobile or web application with a web identity provider. -// Example providers include the OAuth 2.0 providers Login with Amazon and -// Facebook, or any OpenID Connect-compatible identity provider such as Google or -// Amazon Cognito federated identities (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) -// . For mobile applications, we recommend that you use Amazon Cognito. You can use -// Amazon Cognito with the Amazon Web Services SDK for iOS Developer Guide (http://aws.amazon.com/sdkforios/) -// and the Amazon Web Services SDK for Android Developer Guide (http://aws.amazon.com/sdkforandroid/) -// to uniquely identify a user. You can also supply the user with a consistent -// identity throughout the lifetime of an application. To learn more about Amazon -// Cognito, see Amazon Cognito identity pools (https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-identity.html) -// in Amazon Cognito Developer Guide. Calling AssumeRoleWithWebIdentity does not -// require the use of Amazon Web Services security credentials. Therefore, you can -// distribute an application (for example, on mobile devices) that requests -// temporary security credentials without including long-term Amazon Web Services -// credentials in the application. You also don't need to deploy server-based proxy -// services that use long-term Amazon Web Services credentials. Instead, the -// identity of the caller is validated by using a token from the web identity -// provider. For a comparison of AssumeRoleWithWebIdentity with the other API -// operations that produce temporary credentials, see Requesting Temporary -// Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. The temporary security credentials returned by this API -// consist of an access key ID, a secret access key, and a security token. -// Applications can use these temporary security credentials to sign calls to -// Amazon Web Services service API operations. Session Duration By default, the -// temporary security credentials created by AssumeRoleWithWebIdentity last for -// one hour. However, you can use the optional DurationSeconds parameter to -// specify the duration of your session. You can provide a value from 900 seconds -// (15 minutes) up to the maximum session duration setting for the role. This -// setting can have a value from 1 hour to 12 hours. To learn how to view the -// maximum value for your role, see View the Maximum Session Duration Setting for -// a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) -// in the IAM User Guide. The maximum session duration limit applies when you use -// the AssumeRole* API operations or the assume-role* CLI commands. However the -// limit does not apply when you use those operations to create a console URL. For -// more information, see Using IAM Roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. Permissions The temporary security credentials created by -// AssumeRoleWithWebIdentity can be used to make API calls to any Amazon Web -// Services service with the following exception: you cannot call the STS -// GetFederationToken or GetSessionToken API operations. (Optional) You can pass -// inline or managed session policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that you -// use for both inline and managed session policies can't exceed 2,048 characters. -// Passing policies to this operation returns new temporary credentials. The -// resulting session's permissions are the intersection of the role's -// identity-based policy and the session policies. You can use the role's temporary -// credentials in subsequent Amazon Web Services API calls to access resources in -// the account that owns the role. You cannot use session policies to grant more -// permissions than those allowed by the identity-based policy of the role that is -// being assumed. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. Tags (Optional) You can configure your IdP to pass -// attributes into your web identity token as session tags. Each session tag -// consists of a key name and an associated value. For more information about -// session tags, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. You can pass up to 50 session tags. The plaintext session -// tag keys can’t exceed 128 characters and the values can’t exceed 256 characters. -// For these and additional limits, see IAM and STS Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) -// in the IAM User Guide. An Amazon Web Services conversion compresses the passed -// inline session policy, managed policy ARNs, and session tags into a packed -// binary format that has a separate limit. Your request can fail for this limit -// even if your plaintext meets the other requirements. The PackedPolicySize -// response element indicates by percentage how close the policies and tags for -// your request are to the upper size limit. You can pass a session tag with the -// same key as a tag that is attached to the role. When you do, the session tag -// overrides the role tag with the same key. An administrator must grant you the -// permissions necessary to pass session tags. The administrator can also create -// granular permissions to allow you to pass only specific session tags. For more -// information, see Tutorial: Using Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. You can set the session tags as transitive. Transitive -// tags persist during role chaining. For more information, see Chaining Roles -// with Session Tags (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining) -// in the IAM User Guide. Identities Before your application can call -// AssumeRoleWithWebIdentity , you must have an identity token from a supported -// identity provider and create a role that the application can assume. The role -// that your application assumes must trust the identity provider that is -// associated with the identity token. In other words, the identity provider must -// be specified in the role's trust policy. Calling AssumeRoleWithWebIdentity can -// result in an entry in your CloudTrail logs. The entry includes the Subject (http://openid.net/specs/openid-connect-core-1_0.html#Claims) -// of the provided web identity token. We recommend that you avoid using any -// personally identifiable information (PII) in this field. For example, you could -// instead use a GUID or a pairwise identifier, as suggested in the OIDC -// specification (http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes) -// . For more information about how to use web identity federation and the -// AssumeRoleWithWebIdentity API, see the following resources: -// - Using Web Identity Federation API Operations for Mobile Apps (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_manual.html) -// and Federation Through a Web-based Identity Provider (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity) -// . -// - Web Identity Federation Playground (https://aws.amazon.com/blogs/aws/the-aws-web-identity-federation-playground/) -// . Walk through the process of authenticating through Login with Amazon, -// Facebook, or Google, getting temporary security credentials, and then using -// those credentials to make a request to Amazon Web Services. -// - Amazon Web Services SDK for iOS Developer Guide (http://aws.amazon.com/sdkforios/) -// and Amazon Web Services SDK for Android Developer Guide (http://aws.amazon.com/sdkforandroid/) -// . These toolkits contain sample apps that show how to invoke the identity -// providers. The toolkits then show how to use the information from these -// providers to get and use temporary security credentials. -// - Web Identity Federation with Mobile Applications (http://aws.amazon.com/articles/web-identity-federation-with-mobile-applications) -// . This article discusses web identity federation and shows an example of how to -// use web identity federation to get access to content in Amazon S3. -func (c *Client) AssumeRoleWithWebIdentity(ctx context.Context, params *AssumeRoleWithWebIdentityInput, optFns ...func(*Options)) (*AssumeRoleWithWebIdentityOutput, error) { - if params == nil { - params = &AssumeRoleWithWebIdentityInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "AssumeRoleWithWebIdentity", params, optFns, c.addOperationAssumeRoleWithWebIdentityMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*AssumeRoleWithWebIdentityOutput) - out.ResultMetadata = metadata - return out, nil -} - -type AssumeRoleWithWebIdentityInput struct { - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // This member is required. - RoleArn *string - - // An identifier for the assumed role session. Typically, you pass the name or - // identifier that is associated with the user who is using your application. That - // way, the temporary security credentials that your application will use are - // associated with that user. This session name is included as part of the ARN and - // assumed role ID in the AssumedRoleUser response element. 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: =,.@- - // - // This member is required. - RoleSessionName *string - - // The OAuth 2.0 access token or OpenID Connect ID token that is provided by the - // 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. Only tokens with RSA - // algorithms (RS256) are supported. - // - // This member is required. - WebIdentityToken *string - - // The duration, in seconds, of the role session. The value can range from 900 - // seconds (15 minutes) up to the maximum session duration setting for the role. - // This setting can have a value from 1 hour to 12 hours. If you specify a value - // higher than this setting, the operation fails. For example, if you specify a - // session duration of 12 hours, but your administrator set the maximum session - // duration to 6 hours, your operation fails. To learn how to view the maximum - // value for your role, see View the Maximum Session Duration Setting for a Role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session) - // in the IAM User Guide. By default, the value is set to 3600 seconds. The - // DurationSeconds parameter is separate from the duration of a console session - // that you might request using the returned credentials. The request to the - // federation endpoint for a console sign-in token takes a SessionDuration - // parameter that specifies the maximum length of the console session. For more - // information, see Creating a URL that Enables Federated Users to Access the - // Amazon Web Services Management Console (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int32 - - // An IAM policy in JSON format that you want to use as an inline session policy. - // This parameter is optional. Passing policies to this operation returns new - // temporary credentials. The resulting session's permissions are the intersection - // of the role's identity-based policy and the session policies. You can use the - // role's temporary credentials in subsequent Amazon Web Services API calls to - // access resources in the account that owns the role. You cannot use session - // policies to grant more permissions than those allowed by the identity-based - // policy of the role that is being assumed. For more information, see Session - // Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. The plaintext that you use for both inline and managed - // session policies can't exceed 2,048 characters. The JSON policy characters can - // be any ASCII character from the space character to the end of the valid - // character list (\u0020 through \u00FF). It can also include the tab (\u0009), - // linefeed (\u000A), and carriage return (\u000D) characters. An Amazon Web - // Services conversion compresses the passed inline session policy, managed policy - // ARNs, and session tags into a packed binary format that has a separate limit. - // Your request can fail for this limit even if your plaintext meets the other - // requirements. The PackedPolicySize response element indicates by percentage how - // close the policies and tags for your request are to the upper size limit. - Policy *string - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want to - // use as managed session policies. The policies must exist in the same account as - // the role. This parameter is optional. You can provide up to 10 managed policy - // ARNs. However, the plaintext that you use for both inline and managed session - // policies can't exceed 2,048 characters. For more information about ARNs, see - // Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. An Amazon Web Services conversion - // compresses the passed inline session policy, managed policy ARNs, and session - // tags into a packed binary format that has a separate limit. Your request can - // fail for this limit even if your plaintext meets the other requirements. The - // PackedPolicySize response element indicates by percentage how close the policies - // and tags for your request are to the upper size limit. Passing policies to this - // operation returns new temporary credentials. The resulting session's permissions - // are the intersection of the role's identity-based policy and the session - // policies. You can use the role's temporary credentials in subsequent Amazon Web - // Services API calls to access resources in the account that owns the role. You - // cannot use session policies to grant more permissions than those allowed by the - // identity-based policy of the role that is being assumed. For more information, - // see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. - PolicyArns []types.PolicyDescriptorType - - // The fully qualified host component of the domain name of the OAuth 2.0 identity - // provider. Do not specify this value for an OpenID Connect identity provider. - // Currently www.amazon.com and graph.facebook.com are the only supported identity - // providers for OAuth 2.0 access tokens. Do not include URL schemes and port - // numbers. Do not specify this value for OpenID Connect ID tokens. - ProviderId *string - - noSmithyDocumentSerde -} - -// Contains the response to a successful AssumeRoleWithWebIdentity request, -// including temporary Amazon Web Services credentials that can be used to make -// Amazon Web Services requests. -type AssumeRoleWithWebIdentityOutput struct { - - // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers - // that you can use to refer to the resulting temporary security credentials. For - // example, you can reference these credentials as a principal in a resource-based - // policy by using the ARN or assumed role ID. The ARN and ID include the - // RoleSessionName that you specified when you called AssumeRole . - AssumedRoleUser *types.AssumedRoleUser - - // The intended audience (also known as client ID) of the web identity token. This - // is traditionally the client identifier issued to the application that requested - // the web identity token. - Audience *string - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security token. The size of the security token that STS API - // operations return is not fixed. We strongly recommend that you make no - // assumptions about the maximum size. - Credentials *types.Credentials - - // A percentage value that indicates the packed size of the session policies and - // session tags combined passed in the request. The request fails if the packed - // size is greater than 100 percent, which means the policies and tags exceeded the - // allowed space. - PackedPolicySize *int32 - - // The issuing authority of the web identity token presented. For OpenID Connect - // ID tokens, this contains the value of the iss field. For OAuth 2.0 access - // tokens, this contains the value of the ProviderId parameter that was passed in - // the AssumeRoleWithWebIdentity request. - Provider *string - - // The value of the source identity that is returned in the JSON web token (JWT) - // from the identity provider. You can require users to set a source identity value - // when they assume a role. You do this by using the sts:SourceIdentity condition - // key in a role trust policy. That way, actions that are taken with the role are - // associated with that user. After the source identity is set, the value cannot be - // changed. It is present in the request for all actions that are taken by the role - // and persists across chained role (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts#iam-term-role-chaining) - // sessions. You can configure your identity provider to use an attribute - // associated with your users, like user name or email, as the source identity when - // calling AssumeRoleWithWebIdentity . You do this by adding a claim to the JSON - // web token. To learn more about OIDC tokens and claims, see Using Tokens with - // User Pools (https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html) - // in the Amazon Cognito Developer Guide. For more information about using source - // identity, see Monitor and control actions taken with assumed roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html) - // in the IAM User Guide. 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: - // =,.@- - SourceIdentity *string - - // The unique user identifier that is returned by the identity provider. This - // identifier is associated with the WebIdentityToken that was submitted with the - // AssumeRoleWithWebIdentity call. The identifier is typically unique to the user - // and the application that acquired the WebIdentityToken (pairwise identifier). - // For OpenID Connect ID tokens, this field contains the value returned by the - // identity provider as the token's sub (Subject) claim. - SubjectFromWebIdentityToken *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationAssumeRoleWithWebIdentityMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsquery_serializeOpAssumeRoleWithWebIdentity{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpAssumeRoleWithWebIdentity{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "AssumeRoleWithWebIdentity"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpAssumeRoleWithWebIdentityValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opAssumeRoleWithWebIdentity(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opAssumeRoleWithWebIdentity(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "AssumeRoleWithWebIdentity", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_DecodeAuthorizationMessage.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_DecodeAuthorizationMessage.go deleted file mode 100644 index 97a00b97..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_DecodeAuthorizationMessage.go +++ /dev/null @@ -1,161 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Decodes additional information about the authorization status of a request from -// an encoded message returned in response to an Amazon Web Services request. For -// example, if a user is not authorized to perform an operation that he or she has -// requested, the request returns a Client.UnauthorizedOperation response (an HTTP -// 403 response). Some Amazon Web Services operations additionally return an -// encoded message that can provide details about this authorization failure. Only -// certain Amazon Web Services operations return an encoded authorization message. -// The documentation for an individual operation indicates whether that operation -// returns an encoded message in addition to returning an HTTP code. The message is -// encoded because the details of the authorization status can contain privileged -// information that the user who requested the operation should not see. To decode -// an authorization status message, a user must be granted permissions through an -// IAM policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) -// to request the DecodeAuthorizationMessage ( sts:DecodeAuthorizationMessage ) -// action. The decoded message includes the following type of information: -// - Whether the request was denied due to an explicit deny or due to the -// absence of an explicit allow. For more information, see Determining Whether a -// Request is Allowed or Denied (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow) -// in the IAM User Guide. -// - The principal who made the request. -// - The requested action. -// - The requested resource. -// - The values of condition keys in the context of the user's request. -func (c *Client) DecodeAuthorizationMessage(ctx context.Context, params *DecodeAuthorizationMessageInput, optFns ...func(*Options)) (*DecodeAuthorizationMessageOutput, error) { - if params == nil { - params = &DecodeAuthorizationMessageInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "DecodeAuthorizationMessage", params, optFns, c.addOperationDecodeAuthorizationMessageMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*DecodeAuthorizationMessageOutput) - out.ResultMetadata = metadata - return out, nil -} - -type DecodeAuthorizationMessageInput struct { - - // The encoded message that was returned with the response. - // - // This member is required. - EncodedMessage *string - - noSmithyDocumentSerde -} - -// A document that contains additional information about the authorization status -// of a request from an encoded message that is returned in response to an Amazon -// Web Services request. -type DecodeAuthorizationMessageOutput struct { - - // The API returns a response with the decoded message. - DecodedMessage *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationDecodeAuthorizationMessageMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsquery_serializeOpDecodeAuthorizationMessage{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpDecodeAuthorizationMessage{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "DecodeAuthorizationMessage"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpDecodeAuthorizationMessageValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opDecodeAuthorizationMessage(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opDecodeAuthorizationMessage(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "DecodeAuthorizationMessage", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetAccessKeyInfo.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetAccessKeyInfo.go deleted file mode 100644 index e01fcebf..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetAccessKeyInfo.go +++ /dev/null @@ -1,154 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns the account identifier for the specified access key ID. Access keys -// consist of two parts: an access key ID (for example, AKIAIOSFODNN7EXAMPLE ) and -// a secret access key (for example, wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY ). -// For more information about access keys, see Managing Access Keys for IAM Users (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html) -// in the IAM User Guide. When you pass an access key ID to this operation, it -// returns the ID of the Amazon Web Services account to which the keys belong. -// Access key IDs beginning with AKIA are long-term credentials for an IAM user or -// the Amazon Web Services account root user. Access key IDs beginning with ASIA -// are temporary credentials that are created using STS operations. If the account -// in the response belongs to you, you can sign in as the root user and review your -// root user access keys. Then, you can pull a credentials report (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html) -// to learn which IAM user owns the keys. To learn who requested the temporary -// credentials for an ASIA access key, view the STS events in your CloudTrail logs (https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html) -// in the IAM User Guide. This operation does not indicate the state of the access -// key. The key might be active, inactive, or deleted. Active keys might not have -// permissions to perform an operation. Providing a deleted access key might return -// an error that the key doesn't exist. -func (c *Client) GetAccessKeyInfo(ctx context.Context, params *GetAccessKeyInfoInput, optFns ...func(*Options)) (*GetAccessKeyInfoOutput, error) { - if params == nil { - params = &GetAccessKeyInfoInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetAccessKeyInfo", params, optFns, c.addOperationGetAccessKeyInfoMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetAccessKeyInfoOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetAccessKeyInfoInput struct { - - // The identifier of an access key. This parameter allows (through its regex - // pattern) a string of characters that can consist of any upper- or lowercase - // letter or digit. - // - // This member is required. - AccessKeyId *string - - noSmithyDocumentSerde -} - -type GetAccessKeyInfoOutput struct { - - // The number used to identify the Amazon Web Services account. - Account *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetAccessKeyInfoMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsquery_serializeOpGetAccessKeyInfo{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpGetAccessKeyInfo{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetAccessKeyInfo"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetAccessKeyInfoValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetAccessKeyInfo(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetAccessKeyInfo(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetAccessKeyInfo", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetCallerIdentity.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetCallerIdentity.go deleted file mode 100644 index 80296940..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetCallerIdentity.go +++ /dev/null @@ -1,170 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns details about the IAM user or role whose credentials are used to call -// the operation. No permissions are required to perform this operation. If an -// administrator attaches a policy to your identity that explicitly denies access -// to the sts:GetCallerIdentity action, you can still perform this operation. -// Permissions are not required because the same information is returned when -// access is denied. To view an example response, see I Am Not Authorized to -// Perform: iam:DeleteVirtualMFADevice (https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_access-denied-delete-mfa) -// in the IAM User Guide. -func (c *Client) GetCallerIdentity(ctx context.Context, params *GetCallerIdentityInput, optFns ...func(*Options)) (*GetCallerIdentityOutput, error) { - if params == nil { - params = &GetCallerIdentityInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetCallerIdentity", params, optFns, c.addOperationGetCallerIdentityMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetCallerIdentityOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetCallerIdentityInput struct { - noSmithyDocumentSerde -} - -// Contains the response to a successful GetCallerIdentity request, including -// information about the entity making the request. -type GetCallerIdentityOutput struct { - - // The Amazon Web Services account ID number of the account that owns or contains - // the calling entity. - Account *string - - // The Amazon Web Services ARN associated with the calling entity. - Arn *string - - // The unique identifier of the calling entity. The exact value depends on the - // type of entity that is making the call. The values returned are those listed in - // the aws:userid column in the Principal table (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html#principaltable) - // found on the Policy Variables reference page in the IAM User Guide. - UserId *string - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetCallerIdentityMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsquery_serializeOpGetCallerIdentity{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpGetCallerIdentity{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetCallerIdentity"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opGetCallerIdentity(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetCallerIdentity(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetCallerIdentity", - } -} - -// PresignGetCallerIdentity is used to generate a presigned HTTP Request which -// contains presigned URL, signed headers and HTTP method used. -func (c *PresignClient) PresignGetCallerIdentity(ctx context.Context, params *GetCallerIdentityInput, optFns ...func(*PresignOptions)) (*v4.PresignedHTTPRequest, error) { - if params == nil { - params = &GetCallerIdentityInput{} - } - options := c.options.copy() - for _, fn := range optFns { - fn(&options) - } - clientOptFns := append(options.ClientOptions, withNopHTTPClientAPIOption) - - result, _, err := c.client.invokeOperation(ctx, "GetCallerIdentity", params, clientOptFns, - c.client.addOperationGetCallerIdentityMiddlewares, - presignConverter(options).convertToPresignMiddleware, - ) - if err != nil { - return nil, err - } - - out := result.(*v4.PresignedHTTPRequest) - return out, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetFederationToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetFederationToken.go deleted file mode 100644 index efaba119..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetFederationToken.go +++ /dev/null @@ -1,321 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a set of temporary security credentials (consisting of an access key -// ID, a secret access key, and a security token) for a user. A typical use is in a -// proxy application that gets temporary security credentials on behalf of -// distributed applications inside a corporate network. You must call the -// GetFederationToken operation using the long-term security credentials of an IAM -// user. As a result, this call is appropriate in contexts where those credentials -// can be safeguarded, usually in a server-based application. For a comparison of -// GetFederationToken with the other API operations that produce temporary -// credentials, see Requesting Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. Although it is possible to call GetFederationToken using -// the security credentials of an Amazon Web Services account root user rather than -// an IAM user that you create for the purpose of a proxy application, we do not -// recommend it. For more information, see Safeguard your root user credentials -// and don't use them for everyday tasks (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials) -// in the IAM User Guide. You can create a mobile-based or browser-based app that -// can authenticate users using a web identity provider like Login with Amazon, -// Facebook, Google, or an OpenID Connect-compatible identity provider. In this -// case, we recommend that you use Amazon Cognito (http://aws.amazon.com/cognito/) -// or AssumeRoleWithWebIdentity . For more information, see Federation Through a -// Web-based Identity Provider (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity) -// in the IAM User Guide. Session duration The temporary credentials are valid for -// the specified duration, from 900 seconds (15 minutes) up to a maximum of 129,600 -// seconds (36 hours). The default session duration is 43,200 seconds (12 hours). -// Temporary credentials obtained by using the root user credentials have a maximum -// duration of 3,600 seconds (1 hour). Permissions You can use the temporary -// credentials created by GetFederationToken in any Amazon Web Services service -// with the following exceptions: -// - You cannot call any IAM operations using the CLI or the Amazon Web Services -// API. This limitation does not apply to console sessions. -// - You cannot call any STS operations except GetCallerIdentity . -// -// You can use temporary credentials for single sign-on (SSO) to the console. You -// must pass an inline or managed session policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// to this operation. You can pass a single JSON policy document to use as an -// inline session policy. You can also specify up to 10 managed policy Amazon -// Resource Names (ARNs) to use as managed session policies. The plaintext that you -// use for both inline and managed session policies can't exceed 2,048 characters. -// Though the session policy parameters are optional, if you do not pass a policy, -// then the resulting federated user session has no permissions. When you pass -// session policies, the session permissions are the intersection of the IAM user -// policies and the session policies that you pass. This gives you a way to further -// restrict the permissions for a federated user. You cannot use session policies -// to grant more permissions than those that are defined in the permissions policy -// of the IAM user. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) -// in the IAM User Guide. For information about using GetFederationToken to create -// temporary security credentials, see GetFederationToken—Federation Through a -// Custom Identity Broker (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getfederationtoken) -// . You can use the credentials to access a resource that has a resource-based -// policy. If that policy specifically references the federated user session in the -// Principal element of the policy, the session has the permissions allowed by the -// policy. These permissions are granted in addition to the permissions granted by -// the session policies. Tags (Optional) You can pass tag key-value pairs to your -// session. These are called session tags. For more information about session tags, -// see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. You can create a mobile-based or browser-based app that -// can authenticate users using a web identity provider like Login with Amazon, -// Facebook, Google, or an OpenID Connect-compatible identity provider. In this -// case, we recommend that you use Amazon Cognito (http://aws.amazon.com/cognito/) -// or AssumeRoleWithWebIdentity . For more information, see Federation Through a -// Web-based Identity Provider (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity) -// in the IAM User Guide. An administrator must grant you the permissions necessary -// to pass session tags. The administrator can also create granular permissions to -// allow you to pass only specific session tags. For more information, see -// Tutorial: Using Tags for Attribute-Based Access Control (https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html) -// in the IAM User Guide. Tag key–value pairs are not case sensitive, but case is -// preserved. This means that you cannot have separate Department and department -// tag keys. Assume that the user that you are federating has the Department = -// Marketing tag and you pass the department = engineering session tag. Department -// and department are not saved as separate tags, and the session tag passed in -// the request takes precedence over the user tag. -func (c *Client) GetFederationToken(ctx context.Context, params *GetFederationTokenInput, optFns ...func(*Options)) (*GetFederationTokenOutput, error) { - if params == nil { - params = &GetFederationTokenInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetFederationToken", params, optFns, c.addOperationGetFederationTokenMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetFederationTokenOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetFederationTokenInput struct { - - // The name of the federated user. The name is used as an identifier for the - // temporary security credentials (such as Bob ). For example, you can reference - // the federated user name in a resource-based policy, such as in an Amazon S3 - // bucket policy. 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: - // =,.@- - // - // This member is required. - Name *string - - // The duration, in seconds, that the session should last. Acceptable durations - // for federation sessions range from 900 seconds (15 minutes) to 129,600 seconds - // (36 hours), with 43,200 seconds (12 hours) as the default. Sessions obtained - // using root user credentials are restricted to a maximum of 3,600 seconds (one - // hour). If the specified duration is longer than one hour, the session obtained - // by using root user credentials defaults to one hour. - DurationSeconds *int32 - - // An IAM policy in JSON format that you want to use as an inline session policy. - // You must pass an inline or managed session policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // to this operation. You can pass a single JSON policy document to use as an - // inline session policy. You can also specify up to 10 managed policy Amazon - // Resource Names (ARNs) to use as managed session policies. This parameter is - // optional. However, if you do not pass any session policies, then the resulting - // federated user session has no permissions. When you pass session policies, the - // session permissions are the intersection of the IAM user policies and the - // session policies that you pass. This gives you a way to further restrict the - // permissions for a federated user. You cannot use session policies to grant more - // permissions than those that are defined in the permissions policy of the IAM - // user. For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. The resulting credentials can be used to access a - // resource that has a resource-based policy. If that policy specifically - // references the federated user session in the Principal element of the policy, - // the session has the permissions allowed by the policy. These permissions are - // granted in addition to the permissions that are granted by the session policies. - // The plaintext that you use for both inline and managed session policies can't - // exceed 2,048 characters. The JSON policy characters can be any ASCII character - // from the space character to the end of the valid character list (\u0020 through - // \u00FF). It can also include the tab (\u0009), linefeed (\u000A), and carriage - // return (\u000D) characters. An Amazon Web Services conversion compresses the - // passed inline session policy, managed policy ARNs, and session tags into a - // packed binary format that has a separate limit. Your request can fail for this - // limit even if your plaintext meets the other requirements. The PackedPolicySize - // response element indicates by percentage how close the policies and tags for - // your request are to the upper size limit. - Policy *string - - // The Amazon Resource Names (ARNs) of the IAM managed policies that you want to - // use as a managed session policy. The policies must exist in the same account as - // the IAM user that is requesting federated access. You must pass an inline or - // managed session policy (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // to this operation. You can pass a single JSON policy document to use as an - // inline session policy. You can also specify up to 10 managed policy Amazon - // Resource Names (ARNs) to use as managed session policies. The plaintext that you - // use for both inline and managed session policies can't exceed 2,048 characters. - // You can provide up to 10 managed policy ARNs. For more information about ARNs, - // see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. This parameter is optional. - // However, if you do not pass any session policies, then the resulting federated - // user session has no permissions. When you pass session policies, the session - // permissions are the intersection of the IAM user policies and the session - // policies that you pass. This gives you a way to further restrict the permissions - // for a federated user. You cannot use session policies to grant more permissions - // than those that are defined in the permissions policy of the IAM user. For more - // information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) - // in the IAM User Guide. The resulting credentials can be used to access a - // resource that has a resource-based policy. If that policy specifically - // references the federated user session in the Principal element of the policy, - // the session has the permissions allowed by the policy. These permissions are - // granted in addition to the permissions that are granted by the session policies. - // An Amazon Web Services conversion compresses the passed inline session policy, - // managed policy ARNs, and session tags into a packed binary format that has a - // separate limit. Your request can fail for this limit even if your plaintext - // meets the other requirements. The PackedPolicySize response element indicates - // by percentage how close the policies and tags for your request are to the upper - // size limit. - PolicyArns []types.PolicyDescriptorType - - // A list of session tags. Each session tag consists of a key name and an - // associated value. For more information about session tags, see Passing Session - // Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) - // in the IAM User Guide. This parameter is optional. You can pass up to 50 session - // tags. The plaintext session tag keys can’t exceed 128 characters and the values - // can’t exceed 256 characters. For these and additional limits, see IAM and STS - // Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. An Amazon Web Services conversion compresses the passed - // inline session policy, managed policy ARNs, and session tags into a packed - // binary format that has a separate limit. Your request can fail for this limit - // even if your plaintext meets the other requirements. The PackedPolicySize - // response element indicates by percentage how close the policies and tags for - // your request are to the upper size limit. You can pass a session tag with the - // same key as a tag that is already attached to the user you are federating. When - // you do, session tags override a user tag with the same key. Tag key–value pairs - // are not case sensitive, but case is preserved. This means that you cannot have - // separate Department and department tag keys. Assume that the role has the - // Department = Marketing tag and you pass the department = engineering session - // tag. Department and department are not saved as separate tags, and the session - // tag passed in the request takes precedence over the role tag. - Tags []types.Tag - - noSmithyDocumentSerde -} - -// Contains the response to a successful GetFederationToken request, including -// temporary Amazon Web Services credentials that can be used to make Amazon Web -// Services requests. -type GetFederationTokenOutput struct { - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. The size of the security token - // that STS API operations return is not fixed. We strongly recommend that you make - // no assumptions about the maximum size. - Credentials *types.Credentials - - // Identifiers for the federated user associated with the credentials (such as - // arn:aws:sts::123456789012:federated-user/Bob or 123456789012:Bob ). You can use - // the federated user's ARN in your resource-based policies, such as an Amazon S3 - // bucket policy. - FederatedUser *types.FederatedUser - - // A percentage value that indicates the packed size of the session policies and - // session tags combined passed in the request. The request fails if the packed - // size is greater than 100 percent, which means the policies and tags exceeded the - // allowed space. - PackedPolicySize *int32 - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetFederationTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsquery_serializeOpGetFederationToken{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpGetFederationToken{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetFederationToken"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = addOpGetFederationTokenValidationMiddleware(stack); err != nil { - return err - } - if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetFederationToken(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetFederationToken(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetFederationToken", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetSessionToken.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetSessionToken.go deleted file mode 100644 index 7b07435f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/api_op_GetSessionToken.go +++ /dev/null @@ -1,204 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - "github.com/aws/aws-sdk-go-v2/aws/signer/v4" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Returns a set of temporary credentials for an Amazon Web Services account or -// IAM user. The credentials consist of an access key ID, a secret access key, and -// a security token. Typically, you use GetSessionToken if you want to use MFA to -// protect programmatic calls to specific Amazon Web Services API operations like -// Amazon EC2 StopInstances . MFA-enabled IAM users must call GetSessionToken and -// submit an MFA code that is associated with their MFA device. Using the temporary -// security credentials that the call returns, IAM users can then make programmatic -// calls to API operations that require MFA authentication. An incorrect MFA code -// causes the API to return an access denied error. For a comparison of -// GetSessionToken with the other API operations that produce temporary -// credentials, see Requesting Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the Amazon Web Services STS API operations (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. No permissions are required for users to perform this -// operation. The purpose of the sts:GetSessionToken operation is to authenticate -// the user using MFA. You cannot use policies to control authentication -// operations. For more information, see Permissions for GetSessionToken (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_getsessiontoken.html) -// in the IAM User Guide. Session Duration The GetSessionToken operation must be -// called by using the long-term Amazon Web Services security credentials of an IAM -// user. Credentials that are created by IAM users are valid for the duration that -// you specify. This duration can range from 900 seconds (15 minutes) up to a -// maximum of 129,600 seconds (36 hours), with a default of 43,200 seconds (12 -// hours). Credentials based on account credentials can range from 900 seconds (15 -// minutes) up to 3,600 seconds (1 hour), with a default of 1 hour. Permissions The -// temporary security credentials created by GetSessionToken can be used to make -// API calls to any Amazon Web Services service with the following exceptions: -// - You cannot call any IAM API operations unless MFA authentication -// information is included in the request. -// - You cannot call any STS API except AssumeRole or GetCallerIdentity . -// -// The credentials that GetSessionToken returns are based on permissions -// associated with the IAM user whose credentials were used to call the operation. -// The temporary credentials have the same permissions as the IAM user. Although it -// is possible to call GetSessionToken using the security credentials of an Amazon -// Web Services account root user rather than an IAM user, we do not recommend it. -// If GetSessionToken is called using root user credentials, the temporary -// credentials have root user permissions. For more information, see Safeguard -// your root user credentials and don't use them for everyday tasks (https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials) -// in the IAM User Guide For more information about using GetSessionToken to -// create temporary credentials, see Temporary Credentials for Users in Untrusted -// Environments (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken) -// in the IAM User Guide. -func (c *Client) GetSessionToken(ctx context.Context, params *GetSessionTokenInput, optFns ...func(*Options)) (*GetSessionTokenOutput, error) { - if params == nil { - params = &GetSessionTokenInput{} - } - - result, metadata, err := c.invokeOperation(ctx, "GetSessionToken", params, optFns, c.addOperationGetSessionTokenMiddlewares) - if err != nil { - return nil, err - } - - out := result.(*GetSessionTokenOutput) - out.ResultMetadata = metadata - return out, nil -} - -type GetSessionTokenInput struct { - - // The duration, in seconds, that the credentials should remain valid. Acceptable - // durations for IAM user sessions range from 900 seconds (15 minutes) to 129,600 - // seconds (36 hours), with 43,200 seconds (12 hours) as the default. Sessions for - // Amazon Web Services account owners are restricted to a maximum of 3,600 seconds - // (one hour). If the duration is longer than one hour, the session for Amazon Web - // Services account owners defaults to one hour. - DurationSeconds *int32 - - // The identification number of the MFA device that is associated with the IAM - // user who is making the GetSessionToken call. Specify this value if the IAM user - // has a policy that requires MFA authentication. The value is either the serial - // number for a hardware device (such as GAHT12345678 ) or an Amazon Resource Name - // (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user ). You - // can find the device for an IAM user by going to the Amazon Web Services - // Management Console and viewing the user's security credentials. 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: =,.@:/- - SerialNumber *string - - // The value provided by the MFA device, if MFA is required. If any policy - // requires the IAM user to submit an MFA code, specify this value. If MFA - // authentication is required, the user must provide a code when requesting a set - // of temporary security credentials. A user who fails to provide the code receives - // an "access denied" response when requesting resources that require MFA - // authentication. The format for this parameter, as described by its regex - // pattern, is a sequence of six numeric digits. - TokenCode *string - - noSmithyDocumentSerde -} - -// Contains the response to a successful GetSessionToken request, including -// temporary Amazon Web Services credentials that can be used to make Amazon Web -// Services requests. -type GetSessionTokenOutput struct { - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. The size of the security token - // that STS API operations return is not fixed. We strongly recommend that you make - // no assumptions about the maximum size. - Credentials *types.Credentials - - // Metadata pertaining to the operation's result. - ResultMetadata middleware.Metadata - - noSmithyDocumentSerde -} - -func (c *Client) addOperationGetSessionTokenMiddlewares(stack *middleware.Stack, options Options) (err error) { - if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil { - return err - } - err = stack.Serialize.Add(&awsAwsquery_serializeOpGetSessionToken{}, middleware.After) - if err != nil { - return err - } - err = stack.Deserialize.Add(&awsAwsquery_deserializeOpGetSessionToken{}, middleware.After) - if err != nil { - return err - } - if err := addProtocolFinalizerMiddlewares(stack, options, "GetSessionToken"); 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 { - return err - } - if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil { - return err - } - if err = addResolveEndpointMiddleware(stack, options); err != nil { - return err - } - if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil { - return err - } - if err = addRetryMiddlewares(stack, options); err != nil { - return err - } - if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { - return err - } - if err = awsmiddleware.AddRecordResponseTiming(stack); 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 = stack.Initialize.Add(newServiceMetadataMiddleware_opGetSessionToken(options.Region), middleware.Before); err != nil { - return err - } - if err = awsmiddleware.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 - } - return nil -} - -func newServiceMetadataMiddleware_opGetSessionToken(region string) *awsmiddleware.RegisterServiceMetadata { - return &awsmiddleware.RegisterServiceMetadata{ - Region: region, - ServiceID: ServiceID, - OperationName: "GetSessionToken", - } -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/auth.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/auth.go deleted file mode 100644 index 9db5bfd4..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/auth.go +++ /dev/null @@ -1,296 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -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/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -func bindAuthParamsRegion(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(operation string, input interface{}, options Options) *AuthResolverParameters { - params := &AuthResolverParameters{ - Operation: operation, - } - - bindAuthParamsRegion(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{ - "AssumeRoleWithSAML": func(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - {SchemeID: smithyauth.SchemeIDAnonymous}, - } - }, - - "AssumeRoleWithWebIdentity": func(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - {SchemeID: smithyauth.SchemeIDAnonymous}, - } - }, -} - -func serviceAuthOptions(params *AuthResolverParameters) []*smithyauth.Option { - return []*smithyauth.Option{ - { - SchemeID: smithyauth.SchemeIDSigV4, - SignerProperties: func() smithy.Properties { - var props smithy.Properties - smithyhttp.SetSigV4SigningName(&props, "sts") - 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, -) { - params := bindAuthResolverParams(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) - 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, -) { - rscheme := getResolvedAuthScheme(ctx) - 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 := resolver.GetIdentity(ctx, rscheme.IdentityProperties) - if err != nil { - return out, metadata, fmt.Errorf("get identity: %w", err) - } - - ctx = setIdentity(ctx, identity) - 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 { -} - -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, -) { - 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") - } - - if err := signer.SignRequest(ctx, req, identity, rscheme.SignerProperties); err != nil { - return out, metadata, fmt.Errorf("sign request: %w", err) - } - - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/deserializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/deserializers.go deleted file mode 100644 index 5d634ce3..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/deserializers.go +++ /dev/null @@ -1,2507 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "bytes" - "context" - "encoding/xml" - "fmt" - awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" - awsxml "github.com/aws/aws-sdk-go-v2/aws/protocol/xml" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - smithy "github.com/aws/smithy-go" - smithyxml "github.com/aws/smithy-go/encoding/xml" - smithyio "github.com/aws/smithy-go/io" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/ptr" - smithytime "github.com/aws/smithy-go/time" - smithyhttp "github.com/aws/smithy-go/transport/http" - "io" - "strconv" - "strings" -) - -type awsAwsquery_deserializeOpAssumeRole struct { -} - -func (*awsAwsquery_deserializeOpAssumeRole) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpAssumeRole) 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 - } - - 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, awsAwsquery_deserializeOpErrorAssumeRole(response, &metadata) - } - output := &AssumeRoleOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("AssumeRoleResult") - 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 - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentAssumeRoleOutput(&output, 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 out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorAssumeRole(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 - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("ExpiredTokenException", errorCode): - return awsAwsquery_deserializeErrorExpiredTokenException(response, errorBody) - - case strings.EqualFold("MalformedPolicyDocument", errorCode): - return awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("PackedPolicyTooLarge", errorCode): - return awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response, errorBody) - - case strings.EqualFold("RegionDisabledException", errorCode): - return awsAwsquery_deserializeErrorRegionDisabledException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpAssumeRoleWithSAML struct { -} - -func (*awsAwsquery_deserializeOpAssumeRoleWithSAML) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpAssumeRoleWithSAML) 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 - } - - 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, awsAwsquery_deserializeOpErrorAssumeRoleWithSAML(response, &metadata) - } - output := &AssumeRoleWithSAMLOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("AssumeRoleWithSAMLResult") - 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 - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentAssumeRoleWithSAMLOutput(&output, 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 out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorAssumeRoleWithSAML(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 - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("ExpiredTokenException", errorCode): - return awsAwsquery_deserializeErrorExpiredTokenException(response, errorBody) - - case strings.EqualFold("IDPRejectedClaim", errorCode): - return awsAwsquery_deserializeErrorIDPRejectedClaimException(response, errorBody) - - case strings.EqualFold("InvalidIdentityToken", errorCode): - return awsAwsquery_deserializeErrorInvalidIdentityTokenException(response, errorBody) - - case strings.EqualFold("MalformedPolicyDocument", errorCode): - return awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("PackedPolicyTooLarge", errorCode): - return awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response, errorBody) - - case strings.EqualFold("RegionDisabledException", errorCode): - return awsAwsquery_deserializeErrorRegionDisabledException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpAssumeRoleWithWebIdentity struct { -} - -func (*awsAwsquery_deserializeOpAssumeRoleWithWebIdentity) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpAssumeRoleWithWebIdentity) 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 - } - - 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, awsAwsquery_deserializeOpErrorAssumeRoleWithWebIdentity(response, &metadata) - } - output := &AssumeRoleWithWebIdentityOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("AssumeRoleWithWebIdentityResult") - 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 - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentAssumeRoleWithWebIdentityOutput(&output, 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 out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorAssumeRoleWithWebIdentity(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 - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("ExpiredTokenException", errorCode): - return awsAwsquery_deserializeErrorExpiredTokenException(response, errorBody) - - case strings.EqualFold("IDPCommunicationError", errorCode): - return awsAwsquery_deserializeErrorIDPCommunicationErrorException(response, errorBody) - - case strings.EqualFold("IDPRejectedClaim", errorCode): - return awsAwsquery_deserializeErrorIDPRejectedClaimException(response, errorBody) - - case strings.EqualFold("InvalidIdentityToken", errorCode): - return awsAwsquery_deserializeErrorInvalidIdentityTokenException(response, errorBody) - - case strings.EqualFold("MalformedPolicyDocument", errorCode): - return awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("PackedPolicyTooLarge", errorCode): - return awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response, errorBody) - - case strings.EqualFold("RegionDisabledException", errorCode): - return awsAwsquery_deserializeErrorRegionDisabledException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpDecodeAuthorizationMessage struct { -} - -func (*awsAwsquery_deserializeOpDecodeAuthorizationMessage) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpDecodeAuthorizationMessage) 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 - } - - 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, awsAwsquery_deserializeOpErrorDecodeAuthorizationMessage(response, &metadata) - } - output := &DecodeAuthorizationMessageOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("DecodeAuthorizationMessageResult") - 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 - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentDecodeAuthorizationMessageOutput(&output, 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 out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorDecodeAuthorizationMessage(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 - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("InvalidAuthorizationMessageException", errorCode): - return awsAwsquery_deserializeErrorInvalidAuthorizationMessageException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpGetAccessKeyInfo struct { -} - -func (*awsAwsquery_deserializeOpGetAccessKeyInfo) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpGetAccessKeyInfo) 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 - } - - 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, awsAwsquery_deserializeOpErrorGetAccessKeyInfo(response, &metadata) - } - output := &GetAccessKeyInfoOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("GetAccessKeyInfoResult") - 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 - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentGetAccessKeyInfoOutput(&output, 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 out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorGetAccessKeyInfo(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 - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpGetCallerIdentity struct { -} - -func (*awsAwsquery_deserializeOpGetCallerIdentity) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpGetCallerIdentity) 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 - } - - 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, awsAwsquery_deserializeOpErrorGetCallerIdentity(response, &metadata) - } - output := &GetCallerIdentityOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("GetCallerIdentityResult") - 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 - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentGetCallerIdentityOutput(&output, 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 out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorGetCallerIdentity(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 - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpGetFederationToken struct { -} - -func (*awsAwsquery_deserializeOpGetFederationToken) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpGetFederationToken) 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 - } - - 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, awsAwsquery_deserializeOpErrorGetFederationToken(response, &metadata) - } - output := &GetFederationTokenOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("GetFederationTokenResult") - 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 - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentGetFederationTokenOutput(&output, 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 out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorGetFederationToken(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 - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("MalformedPolicyDocument", errorCode): - return awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response, errorBody) - - case strings.EqualFold("PackedPolicyTooLarge", errorCode): - return awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response, errorBody) - - case strings.EqualFold("RegionDisabledException", errorCode): - return awsAwsquery_deserializeErrorRegionDisabledException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -type awsAwsquery_deserializeOpGetSessionToken struct { -} - -func (*awsAwsquery_deserializeOpGetSessionToken) ID() string { - return "OperationDeserializer" -} - -func (m *awsAwsquery_deserializeOpGetSessionToken) 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 - } - - 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, awsAwsquery_deserializeOpErrorGetSessionToken(response, &metadata) - } - output := &GetSessionTokenOutput{} - out.Result = output - - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(response.Body, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return out, metadata, nil - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return out, metadata, &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("GetSessionTokenResult") - 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 - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeOpDocumentGetSessionTokenOutput(&output, 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 out, metadata, err - } - - return out, metadata, err -} - -func awsAwsquery_deserializeOpErrorGetSessionToken(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 - - errorComponents, err := awsxml.GetErrorResponseComponents(errorBody, false) - if err != nil { - return err - } - if reqID := errorComponents.RequestID; len(reqID) != 0 { - awsmiddleware.SetRequestIDMetadata(metadata, reqID) - } - if len(errorComponents.Code) != 0 { - errorCode = errorComponents.Code - } - if len(errorComponents.Message) != 0 { - errorMessage = errorComponents.Message - } - errorBody.Seek(0, io.SeekStart) - switch { - case strings.EqualFold("RegionDisabledException", errorCode): - return awsAwsquery_deserializeErrorRegionDisabledException(response, errorBody) - - default: - genericError := &smithy.GenericAPIError{ - Code: errorCode, - Message: errorMessage, - } - return genericError - - } -} - -func awsAwsquery_deserializeErrorExpiredTokenException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.ExpiredTokenException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentExpiredTokenException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorIDPCommunicationErrorException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.IDPCommunicationErrorException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentIDPCommunicationErrorException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorIDPRejectedClaimException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.IDPRejectedClaimException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentIDPRejectedClaimException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorInvalidAuthorizationMessageException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidAuthorizationMessageException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentInvalidAuthorizationMessageException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorInvalidIdentityTokenException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.InvalidIdentityTokenException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentInvalidIdentityTokenException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorMalformedPolicyDocumentException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.MalformedPolicyDocumentException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentMalformedPolicyDocumentException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorPackedPolicyTooLargeException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.PackedPolicyTooLargeException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentPackedPolicyTooLargeException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeErrorRegionDisabledException(response *smithyhttp.Response, errorBody *bytes.Reader) error { - output := &types.RegionDisabledException{} - var buff [1024]byte - ringBuffer := smithyio.NewRingBuffer(buff[:]) - body := io.TeeReader(errorBody, ringBuffer) - rootDecoder := xml.NewDecoder(body) - t, err := smithyxml.FetchRootElement(rootDecoder) - if err == io.EOF { - return output - } - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder := smithyxml.WrapNodeDecoder(rootDecoder, t) - t, err = decoder.GetElement("Error") - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - decoder = smithyxml.WrapNodeDecoder(decoder.Decoder, t) - err = awsAwsquery_deserializeDocumentRegionDisabledException(&output, decoder) - if err != nil { - var snapshot bytes.Buffer - io.Copy(&snapshot, ringBuffer) - return &smithy.DeserializationError{ - Err: fmt.Errorf("failed to decode response body, %w", err), - Snapshot: snapshot.Bytes(), - } - } - - return output -} - -func awsAwsquery_deserializeDocumentAssumedRoleUser(v **types.AssumedRoleUser, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.AssumedRoleUser - if *v == nil { - sv = &types.AssumedRoleUser{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Arn", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Arn = ptr.String(xtv) - } - - case strings.EqualFold("AssumedRoleId", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.AssumedRoleId = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentCredentials(v **types.Credentials, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.Credentials - if *v == nil { - sv = &types.Credentials{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("AccessKeyId", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.AccessKeyId = ptr.String(xtv) - } - - case strings.EqualFold("Expiration", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - t, err := smithytime.ParseDateTime(xtv) - if err != nil { - return err - } - sv.Expiration = ptr.Time(t) - } - - case strings.EqualFold("SecretAccessKey", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SecretAccessKey = ptr.String(xtv) - } - - case strings.EqualFold("SessionToken", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SessionToken = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentExpiredTokenException(v **types.ExpiredTokenException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.ExpiredTokenException - if *v == nil { - sv = &types.ExpiredTokenException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentFederatedUser(v **types.FederatedUser, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.FederatedUser - if *v == nil { - sv = &types.FederatedUser{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Arn", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Arn = ptr.String(xtv) - } - - case strings.EqualFold("FederatedUserId", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.FederatedUserId = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentIDPCommunicationErrorException(v **types.IDPCommunicationErrorException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.IDPCommunicationErrorException - if *v == nil { - sv = &types.IDPCommunicationErrorException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentIDPRejectedClaimException(v **types.IDPRejectedClaimException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.IDPRejectedClaimException - if *v == nil { - sv = &types.IDPRejectedClaimException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentInvalidAuthorizationMessageException(v **types.InvalidAuthorizationMessageException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.InvalidAuthorizationMessageException - if *v == nil { - sv = &types.InvalidAuthorizationMessageException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentInvalidIdentityTokenException(v **types.InvalidIdentityTokenException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.InvalidIdentityTokenException - if *v == nil { - sv = &types.InvalidIdentityTokenException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentMalformedPolicyDocumentException(v **types.MalformedPolicyDocumentException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.MalformedPolicyDocumentException - if *v == nil { - sv = &types.MalformedPolicyDocumentException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentPackedPolicyTooLargeException(v **types.PackedPolicyTooLargeException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.PackedPolicyTooLargeException - if *v == nil { - sv = &types.PackedPolicyTooLargeException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeDocumentRegionDisabledException(v **types.RegionDisabledException, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *types.RegionDisabledException - if *v == nil { - sv = &types.RegionDisabledException{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("message", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Message = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentAssumeRoleOutput(v **AssumeRoleOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *AssumeRoleOutput - if *v == nil { - sv = &AssumeRoleOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("AssumedRoleUser", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentAssumedRoleUser(&sv.AssumedRoleUser, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("Credentials", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentCredentials(&sv.Credentials, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("PackedPolicySize", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - i64, err := strconv.ParseInt(xtv, 10, 64) - if err != nil { - return err - } - sv.PackedPolicySize = ptr.Int32(int32(i64)) - } - - case strings.EqualFold("SourceIdentity", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SourceIdentity = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentAssumeRoleWithSAMLOutput(v **AssumeRoleWithSAMLOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *AssumeRoleWithSAMLOutput - if *v == nil { - sv = &AssumeRoleWithSAMLOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("AssumedRoleUser", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentAssumedRoleUser(&sv.AssumedRoleUser, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("Audience", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Audience = ptr.String(xtv) - } - - case strings.EqualFold("Credentials", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentCredentials(&sv.Credentials, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("Issuer", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Issuer = ptr.String(xtv) - } - - case strings.EqualFold("NameQualifier", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.NameQualifier = ptr.String(xtv) - } - - case strings.EqualFold("PackedPolicySize", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - i64, err := strconv.ParseInt(xtv, 10, 64) - if err != nil { - return err - } - sv.PackedPolicySize = ptr.Int32(int32(i64)) - } - - case strings.EqualFold("SourceIdentity", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SourceIdentity = ptr.String(xtv) - } - - case strings.EqualFold("Subject", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Subject = ptr.String(xtv) - } - - case strings.EqualFold("SubjectType", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SubjectType = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentAssumeRoleWithWebIdentityOutput(v **AssumeRoleWithWebIdentityOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *AssumeRoleWithWebIdentityOutput - if *v == nil { - sv = &AssumeRoleWithWebIdentityOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("AssumedRoleUser", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentAssumedRoleUser(&sv.AssumedRoleUser, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("Audience", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Audience = ptr.String(xtv) - } - - case strings.EqualFold("Credentials", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentCredentials(&sv.Credentials, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("PackedPolicySize", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - i64, err := strconv.ParseInt(xtv, 10, 64) - if err != nil { - return err - } - sv.PackedPolicySize = ptr.Int32(int32(i64)) - } - - case strings.EqualFold("Provider", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Provider = ptr.String(xtv) - } - - case strings.EqualFold("SourceIdentity", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SourceIdentity = ptr.String(xtv) - } - - case strings.EqualFold("SubjectFromWebIdentityToken", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.SubjectFromWebIdentityToken = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentDecodeAuthorizationMessageOutput(v **DecodeAuthorizationMessageOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *DecodeAuthorizationMessageOutput - if *v == nil { - sv = &DecodeAuthorizationMessageOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("DecodedMessage", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.DecodedMessage = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentGetAccessKeyInfoOutput(v **GetAccessKeyInfoOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *GetAccessKeyInfoOutput - if *v == nil { - sv = &GetAccessKeyInfoOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Account", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Account = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentGetCallerIdentityOutput(v **GetCallerIdentityOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *GetCallerIdentityOutput - if *v == nil { - sv = &GetCallerIdentityOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Account", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Account = ptr.String(xtv) - } - - case strings.EqualFold("Arn", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.Arn = ptr.String(xtv) - } - - case strings.EqualFold("UserId", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - sv.UserId = ptr.String(xtv) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentGetFederationTokenOutput(v **GetFederationTokenOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *GetFederationTokenOutput - if *v == nil { - sv = &GetFederationTokenOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Credentials", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentCredentials(&sv.Credentials, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("FederatedUser", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentFederatedUser(&sv.FederatedUser, nodeDecoder); err != nil { - return err - } - - case strings.EqualFold("PackedPolicySize", t.Name.Local): - val, err := decoder.Value() - if err != nil { - return err - } - if val == nil { - break - } - { - xtv := string(val) - i64, err := strconv.ParseInt(xtv, 10, 64) - if err != nil { - return err - } - sv.PackedPolicySize = ptr.Int32(int32(i64)) - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} - -func awsAwsquery_deserializeOpDocumentGetSessionTokenOutput(v **GetSessionTokenOutput, decoder smithyxml.NodeDecoder) error { - if v == nil { - return fmt.Errorf("unexpected nil of type %T", v) - } - var sv *GetSessionTokenOutput - if *v == nil { - sv = &GetSessionTokenOutput{} - } else { - sv = *v - } - - for { - t, done, err := decoder.Token() - if err != nil { - return err - } - if done { - break - } - originalDecoder := decoder - decoder = smithyxml.WrapNodeDecoder(originalDecoder.Decoder, t) - switch { - case strings.EqualFold("Credentials", t.Name.Local): - nodeDecoder := smithyxml.WrapNodeDecoder(decoder.Decoder, t) - if err := awsAwsquery_deserializeDocumentCredentials(&sv.Credentials, nodeDecoder); err != nil { - return err - } - - default: - // Do nothing and ignore the unexpected tag element - err = decoder.Decoder.Skip() - if err != nil { - return err - } - - } - decoder = originalDecoder - } - *v = sv - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/doc.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/doc.go deleted file mode 100644 index d963fd8d..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/doc.go +++ /dev/null @@ -1,11 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -// Package sts provides the API client, operations, and parameter types for AWS -// Security Token Service. -// -// Security Token Service Security Token Service (STS) enables you to request -// temporary, limited-privilege credentials for users. This guide provides -// descriptions of the STS API. For more information about using this service, see -// Temporary Security Credentials (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html) -// . -package sts diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/endpoints.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/endpoints.go deleted file mode 100644 index 9f7932f9..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/endpoints.go +++ /dev/null @@ -1,1108 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "errors" - "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/sts/internal/endpoints" - smithy "github.com/aws/smithy-go" - 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" - smithyhttp "github.com/aws/smithy-go/transport/http" - "net/http" - "net/url" - "os" - "strings" -) - -// EndpointResolverOptions is the service endpoint resolver options -type EndpointResolverOptions = internalendpoints.Options - -// EndpointResolver interface for resolving service endpoints. -type EndpointResolver interface { - ResolveEndpoint(region string, options EndpointResolverOptions) (aws.Endpoint, error) -} - -var _ EndpointResolver = &internalendpoints.Resolver{} - -// NewDefaultEndpointResolver constructs a new service endpoint resolver -func NewDefaultEndpointResolver() *internalendpoints.Resolver { - return internalendpoints.New() -} - -// EndpointResolverFunc is a helper utility that wraps a function so it satisfies -// the EndpointResolver interface. This is useful when you want to add additional -// endpoint resolving logic, or stub out specific endpoints with custom values. -type EndpointResolverFunc func(region string, options EndpointResolverOptions) (aws.Endpoint, error) - -func (fn EndpointResolverFunc) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return fn(region, options) -} - -// EndpointResolverFromURL returns an EndpointResolver configured using the -// provided endpoint url. By default, the resolved endpoint resolver uses the -// client region as signing region, and the endpoint source is set to -// EndpointSourceCustom.You can provide functional options to configure endpoint -// values for the resolved endpoint. -func EndpointResolverFromURL(url string, optFns ...func(*aws.Endpoint)) EndpointResolver { - e := aws.Endpoint{URL: url, Source: aws.EndpointSourceCustom} - for _, fn := range optFns { - fn(&e) - } - - return EndpointResolverFunc( - func(region string, options EndpointResolverOptions) (aws.Endpoint, error) { - if len(e.SigningRegion) == 0 { - e.SigningRegion = region - } - return e, nil - }, - ) -} - -type ResolveEndpoint struct { - Resolver EndpointResolver - Options EndpointResolverOptions -} - -func (*ResolveEndpoint) ID() string { - return "ResolveEndpoint" -} - -func (m *ResolveEndpoint) 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.Resolver == nil { - return out, metadata, fmt.Errorf("expected endpoint resolver to not be nil") - } - - eo := m.Options - eo.Logger = middleware.GetLogger(ctx) - - var endpoint aws.Endpoint - endpoint, err = m.Resolver.ResolveEndpoint(awsmiddleware.GetRegion(ctx), eo) - if err != nil { - nf := (&aws.EndpointNotFoundError{}) - if errors.As(err, &nf) { - ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, false) - return next.HandleSerialize(ctx, in) - } - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - req.URL, err = url.Parse(endpoint.URL) - if err != nil { - return out, metadata, fmt.Errorf("failed to parse endpoint URL: %w", err) - } - - if len(awsmiddleware.GetSigningName(ctx)) == 0 { - signingName := endpoint.SigningName - if len(signingName) == 0 { - signingName = "sts" - } - ctx = awsmiddleware.SetSigningName(ctx, signingName) - } - ctx = awsmiddleware.SetEndpointSource(ctx, endpoint.Source) - ctx = smithyhttp.SetHostnameImmutable(ctx, endpoint.HostnameImmutable) - ctx = awsmiddleware.SetSigningRegion(ctx, endpoint.SigningRegion) - ctx = awsmiddleware.SetPartitionID(ctx, endpoint.PartitionID) - return next.HandleSerialize(ctx, in) -} -func addResolveEndpointMiddleware(stack *middleware.Stack, o Options) error { - return stack.Serialize.Insert(&ResolveEndpoint{ - Resolver: o.EndpointResolver, - Options: o.EndpointOptions, - }, "OperationSerializer", middleware.Before) -} - -func removeResolveEndpointMiddleware(stack *middleware.Stack) error { - _, err := stack.Serialize.Remove((&ResolveEndpoint{}).ID()) - return err -} - -type wrappedEndpointResolver struct { - awsResolver aws.EndpointResolverWithOptions -} - -func (w *wrappedEndpointResolver) ResolveEndpoint(region string, options EndpointResolverOptions) (endpoint aws.Endpoint, err error) { - return w.awsResolver.ResolveEndpoint(ServiceID, region, options) -} - -type awsEndpointResolverAdaptor func(service, region string) (aws.Endpoint, error) - -func (a awsEndpointResolverAdaptor) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { - return a(service, region) -} - -var _ aws.EndpointResolverWithOptions = awsEndpointResolverAdaptor(nil) - -// withEndpointResolver returns an aws.EndpointResolverWithOptions that first delegates endpoint resolution to the awsResolver. -// If awsResolver returns aws.EndpointNotFoundError error, the v1 resolver middleware will swallow the error, -// and set an appropriate context flag such that fallback will occur when EndpointResolverV2 is invoked -// via its middleware. -// -// If another error (besides aws.EndpointNotFoundError) is returned, then that error will be propagated. -func withEndpointResolver(awsResolver aws.EndpointResolver, awsResolverWithOptions aws.EndpointResolverWithOptions) EndpointResolver { - var resolver aws.EndpointResolverWithOptions - - if awsResolverWithOptions != nil { - resolver = awsResolverWithOptions - } else if awsResolver != nil { - resolver = awsEndpointResolverAdaptor(awsResolver.ResolveEndpoint) - } - - return &wrappedEndpointResolver{ - awsResolver: resolver, - } -} - -func finalizeClientEndpointResolverOptions(options *Options) { - options.EndpointOptions.LogDeprecated = options.ClientLogMode.IsDeprecatedUsage() - - if len(options.EndpointOptions.ResolvedRegion) == 0 { - const fipsInfix = "-fips-" - const fipsPrefix = "fips-" - const fipsSuffix = "-fips" - - if strings.Contains(options.Region, fipsInfix) || - strings.Contains(options.Region, fipsPrefix) || - strings.Contains(options.Region, fipsSuffix) { - options.EndpointOptions.ResolvedRegion = strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll( - options.Region, fipsInfix, "-"), fipsPrefix, ""), fipsSuffix, "") - options.EndpointOptions.UseFIPSEndpoint = aws.FIPSEndpointStateEnabled - } - } - -} - -func resolveEndpointResolverV2(options *Options) { - if options.EndpointResolverV2 == nil { - options.EndpointResolverV2 = NewDefaultEndpointResolverV2() - } -} - -func resolveBaseEndpoint(cfg aws.Config, o *Options) { - if cfg.BaseEndpoint != nil { - o.BaseEndpoint = cfg.BaseEndpoint - } - - _, g := os.LookupEnv("AWS_ENDPOINT_URL") - _, s := os.LookupEnv("AWS_ENDPOINT_URL_STS") - - if g && !s { - return - } - - value, found, err := internalConfig.ResolveServiceBaseEndpoint(context.Background(), "STS", cfg.ConfigSources) - if found && err == nil { - o.BaseEndpoint = &value - } -} - -// EndpointParameters provides the parameters that influence how endpoints are -// resolved. -type EndpointParameters struct { - // The AWS region used to dispatch the request. - // - // Parameter is - // required. - // - // AWS::Region - Region *string - - // When true, use the dual-stack endpoint. If the configured endpoint does not - // support dual-stack, dispatching the request MAY return an error. - // - // Defaults to - // false if no value is provided. - // - // AWS::UseDualStack - UseDualStack *bool - - // When true, send this request to the FIPS-compliant regional endpoint. If the - // configured endpoint does not have a FIPS compliant endpoint, dispatching the - // request will return an error. - // - // Defaults to false if no value is - // provided. - // - // AWS::UseFIPS - UseFIPS *bool - - // Override the endpoint used to send this request - // - // Parameter is - // required. - // - // SDK::Endpoint - Endpoint *string - - // Whether the global endpoint should be used, rather then the regional endpoint - // for us-east-1. - // - // Defaults to false if no value is - // provided. - // - // AWS::STS::UseGlobalEndpoint - UseGlobalEndpoint *bool -} - -// ValidateRequired validates required parameters are set. -func (p EndpointParameters) ValidateRequired() error { - if p.UseDualStack == nil { - return fmt.Errorf("parameter UseDualStack is required") - } - - if p.UseFIPS == nil { - return fmt.Errorf("parameter UseFIPS is required") - } - - if p.UseGlobalEndpoint == nil { - return fmt.Errorf("parameter UseGlobalEndpoint is required") - } - - return nil -} - -// WithDefaults returns a shallow copy of EndpointParameterswith default values -// applied to members where applicable. -func (p EndpointParameters) WithDefaults() EndpointParameters { - if p.UseDualStack == nil { - p.UseDualStack = ptr.Bool(false) - } - - if p.UseFIPS == nil { - p.UseFIPS = ptr.Bool(false) - } - - if p.UseGlobalEndpoint == nil { - p.UseGlobalEndpoint = ptr.Bool(false) - } - return p -} - -// EndpointResolverV2 provides the interface for resolving service endpoints. -type EndpointResolverV2 interface { - // ResolveEndpoint attempts to resolve the endpoint with the provided options, - // returning the endpoint if found. Otherwise an error is returned. - ResolveEndpoint(ctx context.Context, params EndpointParameters) ( - smithyendpoints.Endpoint, error, - ) -} - -// resolver provides the implementation for resolving endpoints. -type resolver struct{} - -func NewDefaultEndpointResolverV2() EndpointResolverV2 { - return &resolver{} -} - -// ResolveEndpoint attempts to resolve the endpoint with the provided options, -// returning the endpoint if found. Otherwise an error is returned. -func (r *resolver) ResolveEndpoint( - ctx context.Context, params EndpointParameters, -) ( - endpoint smithyendpoints.Endpoint, err error, -) { - params = params.WithDefaults() - if err = params.ValidateRequired(); err != nil { - return endpoint, fmt.Errorf("endpoint parameters are not valid, %w", err) - } - _UseDualStack := *params.UseDualStack - _UseFIPS := *params.UseFIPS - _UseGlobalEndpoint := *params.UseGlobalEndpoint - - if _UseGlobalEndpoint == true { - if !(params.Endpoint != nil) { - if exprVal := params.Region; exprVal != nil { - _Region := *exprVal - _ = _Region - if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { - _PartitionResult := *exprVal - _ = _PartitionResult - if _UseFIPS == false { - if _UseDualStack == false { - if _Region == "ap-northeast-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "ap-south-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "ap-southeast-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "ap-southeast-2" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "aws-global" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "ca-central-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "eu-central-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "eu-north-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "eu-west-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "eu-west-2" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "eu-west-3" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "sa-east-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "us-east-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "us-east-2" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "us-west-1" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - if _Region == "us-west-2" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, _Region) - return sp - }(), - }, - }) - return out - }(), - }, nil - } - } - } - } - } - } - if exprVal := params.Endpoint; exprVal != nil { - _Endpoint := *exprVal - _ = _Endpoint - if _UseFIPS == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: FIPS and custom endpoint are not supported") - } - if _UseDualStack == true { - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Dualstack and custom endpoint are not supported") - } - uriString := _Endpoint - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - if exprVal := params.Region; exprVal != nil { - _Region := *exprVal - _ = _Region - if exprVal := awsrulesfn.GetPartition(_Region); exprVal != nil { - _PartitionResult := *exprVal - _ = _PartitionResult - if _UseFIPS == true { - if _UseDualStack == true { - if true == _PartitionResult.SupportsFIPS { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS and DualStack are enabled, but this partition does not support one or both") - } - } - if _UseFIPS == true { - if _PartitionResult.SupportsFIPS == true { - if _PartitionResult.Name == "aws-us-gov" { - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts.") - out.WriteString(_Region) - out.WriteString(".amazonaws.com") - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts-fips.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "FIPS is enabled but this partition does not support FIPS") - } - if _UseDualStack == true { - if true == _PartitionResult.SupportsDualStack { - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DualStackDnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "DualStack is enabled but this partition does not support DualStack") - } - if _Region == "aws-global" { - uriString := "https://sts.amazonaws.com" - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - Properties: func() smithy.Properties { - var out smithy.Properties - smithyauth.SetAuthOptions(&out, []*smithyauth.Option{ - { - SchemeID: "aws.auth#sigv4", - SignerProperties: func() smithy.Properties { - var sp smithy.Properties - smithyhttp.SetSigV4SigningName(&sp, "sts") - smithyhttp.SetSigV4ASigningName(&sp, "sts") - - smithyhttp.SetSigV4SigningRegion(&sp, "us-east-1") - return sp - }(), - }, - }) - return out - }(), - }, nil - } - uriString := func() string { - var out strings.Builder - out.WriteString("https://sts.") - out.WriteString(_Region) - out.WriteString(".") - out.WriteString(_PartitionResult.DnsSuffix) - return out.String() - }() - - uri, err := url.Parse(uriString) - if err != nil { - return endpoint, fmt.Errorf("Failed to parse uri: %s", uriString) - } - - return smithyendpoints.Endpoint{ - URI: *uri, - Headers: http.Header{}, - }, nil - } - return endpoint, fmt.Errorf("Endpoint resolution failed. Invalid operation or environment input.") - } - return endpoint, fmt.Errorf("endpoint rule error, %s", "Invalid Configuration: Missing Region") -} - -type endpointParamsBinder interface { - bindEndpointParams(*EndpointParameters) -} - -func bindEndpointParams(input interface{}, options Options) *EndpointParameters { - params := &EndpointParameters{} - - params.Region = aws.String(endpoints.MapFIPSRegion(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, -) { - 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(getOperationInput(ctx), m.options) - endpt, err := m.options.EndpointResolverV2.ResolveEndpoint(ctx, *params) - if err != nil { - return out, metadata, fmt.Errorf("failed to resolve service endpoint, %w", err) - } - - 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) - } - - return next.HandleFinalize(ctx, in) -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/generated.json b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/generated.json deleted file mode 100644 index d90b8bce..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/generated.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "dependencies": { - "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/aws-sdk-go-v2/service/internal/accept-encoding": "v1.0.5", - "github.com/aws/aws-sdk-go-v2/service/internal/presigned-url": "v1.0.7", - "github.com/aws/smithy-go": "v1.4.0", - "github.com/google/go-cmp": "v0.5.4" - }, - "files": [ - "api_client.go", - "api_client_test.go", - "api_op_AssumeRole.go", - "api_op_AssumeRoleWithSAML.go", - "api_op_AssumeRoleWithWebIdentity.go", - "api_op_DecodeAuthorizationMessage.go", - "api_op_GetAccessKeyInfo.go", - "api_op_GetCallerIdentity.go", - "api_op_GetFederationToken.go", - "api_op_GetSessionToken.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", - "types/errors.go", - "types/types.go", - "validators.go" - ], - "go": "1.15", - "module": "github.com/aws/aws-sdk-go-v2/service/sts", - "unstable": false -} 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 deleted file mode 100644 index 962c336c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package sts - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.26.7" 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 deleted file mode 100644 index 3dbd993b..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/internal/endpoints/endpoints.go +++ /dev/null @@ -1,512 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package endpoints - -import ( - "github.com/aws/aws-sdk-go-v2/aws" - endpoints "github.com/aws/aws-sdk-go-v2/internal/endpoints/v2" - "github.com/aws/smithy-go/logging" - "regexp" -) - -// Options is the endpoint resolver configuration options -type Options struct { - // Logger is a logging implementation that log events should be sent to. - Logger logging.Logger - - // LogDeprecated indicates that deprecated endpoints should be logged to the - // provided logger. - LogDeprecated bool - - // ResolvedRegion is used to override the region to be resolved, rather then the - // using the value passed to the ResolveEndpoint method. This value is used by the - // SDK to translate regions like fips-us-east-1 or us-east-1-fips to an alternative - // name. You must not set this value directly in your application. - ResolvedRegion string - - // DisableHTTPS informs the resolver to return an endpoint that does not use the - // HTTPS scheme. - DisableHTTPS bool - - // UseDualStackEndpoint specifies the resolver must resolve a dual-stack endpoint. - UseDualStackEndpoint aws.DualStackEndpointState - - // UseFIPSEndpoint specifies the resolver must resolve a FIPS endpoint. - UseFIPSEndpoint aws.FIPSEndpointState -} - -func (o Options) GetResolvedRegion() string { - return o.ResolvedRegion -} - -func (o Options) GetDisableHTTPS() bool { - return o.DisableHTTPS -} - -func (o Options) GetUseDualStackEndpoint() aws.DualStackEndpointState { - return o.UseDualStackEndpoint -} - -func (o Options) GetUseFIPSEndpoint() aws.FIPSEndpointState { - return o.UseFIPSEndpoint -} - -func transformToSharedOptions(options Options) endpoints.Options { - return endpoints.Options{ - Logger: options.Logger, - LogDeprecated: options.LogDeprecated, - ResolvedRegion: options.ResolvedRegion, - DisableHTTPS: options.DisableHTTPS, - UseDualStackEndpoint: options.UseDualStackEndpoint, - UseFIPSEndpoint: options.UseFIPSEndpoint, - } -} - -// Resolver STS endpoint resolver -type Resolver struct { - partitions endpoints.Partitions -} - -// ResolveEndpoint resolves the service endpoint for the given region and options -func (r *Resolver) ResolveEndpoint(region string, options Options) (endpoint aws.Endpoint, err error) { - if len(region) == 0 { - return endpoint, &aws.MissingRegionError{} - } - - opt := transformToSharedOptions(options) - return r.partitions.ResolveEndpoint(region, opt) -} - -// New returns a new Resolver -func New() *Resolver { - return &Resolver{ - partitions: defaultPartitions, - } -} - -var partitionRegexp = struct { - Aws *regexp.Regexp - AwsCn *regexp.Regexp - AwsIso *regexp.Regexp - AwsIsoB *regexp.Regexp - AwsIsoE *regexp.Regexp - AwsIsoF *regexp.Regexp - AwsUsGov *regexp.Regexp -}{ - - Aws: regexp.MustCompile("^(us|eu|ap|sa|ca|me|af|il)\\-\\w+\\-\\d+$"), - AwsCn: regexp.MustCompile("^cn\\-\\w+\\-\\d+$"), - AwsIso: regexp.MustCompile("^us\\-iso\\-\\w+\\-\\d+$"), - AwsIsoB: regexp.MustCompile("^us\\-isob\\-\\w+\\-\\d+$"), - AwsIsoE: regexp.MustCompile("^eu\\-isoe\\-\\w+\\-\\d+$"), - AwsIsoF: regexp.MustCompile("^us\\-isof\\-\\w+\\-\\d+$"), - AwsUsGov: regexp.MustCompile("^us\\-gov\\-\\w+\\-\\d+$"), -} - -var defaultPartitions = endpoints.Partitions{ - { - ID: "aws", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "sts.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "sts-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.Aws, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "af-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-northeast-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-south-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ap-southeast-4", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "aws-global", - }: endpoints.Endpoint{ - Hostname: "sts.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-1", - }, - }, - endpoints.EndpointKey{ - Region: "ca-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "ca-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-central-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-north-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-south-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "eu-west-3", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "il-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "me-central-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "me-south-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "sa-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-east-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.us-east-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-east-1-fips", - }: endpoints.Endpoint{ - Hostname: "sts-fips.us-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-east-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-east-2", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.us-east-2.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-east-2-fips", - }: endpoints.Endpoint{ - Hostname: "sts-fips.us-east-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-east-2", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-west-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.us-west-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-west-1-fips", - }: endpoints.Endpoint{ - Hostname: "sts-fips.us-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-west-2", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-west-2", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.us-west-2.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-west-2-fips", - }: endpoints.Endpoint{ - Hostname: "sts-fips.us-west-2.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-west-2", - }, - Deprecated: aws.TrueTernary, - }, - }, - }, - { - ID: "aws-cn", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "sts.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "sts-fips.{region}.api.amazonwebservices.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.amazonaws.com.cn", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsCn, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "cn-north-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "cn-northwest-1", - }: endpoints.Endpoint{}, - }, - }, - { - ID: "aws-iso", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.c2s.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIso, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-iso-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-iso-west-1", - }: endpoints.Endpoint{}, - }, - }, - { - ID: "aws-iso-b", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.sc2s.sgov.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoB, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-isob-east-1", - }: endpoints.Endpoint{}, - }, - }, - { - ID: "aws-iso-e", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.cloud.adc-e.uk", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoE, - IsRegionalized: true, - }, - { - ID: "aws-iso-f", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts-fips.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.csp.hci.ic.gov", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsIsoF, - IsRegionalized: true, - }, - { - ID: "aws-us-gov", - Defaults: map[endpoints.DefaultKey]endpoints.Endpoint{ - { - Variant: endpoints.DualStackVariant, - }: { - Hostname: "sts.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: endpoints.FIPSVariant | endpoints.DualStackVariant, - }: { - Hostname: "sts-fips.{region}.api.aws", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - { - Variant: 0, - }: { - Hostname: "sts.{region}.amazonaws.com", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - }, - RegionRegex: partitionRegexp.AwsUsGov, - IsRegionalized: true, - Endpoints: endpoints.Endpoints{ - endpoints.EndpointKey{ - Region: "us-gov-east-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-gov-east-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts.us-gov-east-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-gov-east-1-fips", - }: endpoints.Endpoint{ - Hostname: "sts.us-gov-east-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-east-1", - }, - Deprecated: aws.TrueTernary, - }, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - }: endpoints.Endpoint{}, - endpoints.EndpointKey{ - Region: "us-gov-west-1", - Variant: endpoints.FIPSVariant, - }: { - Hostname: "sts.us-gov-west-1.amazonaws.com", - }, - endpoints.EndpointKey{ - Region: "us-gov-west-1-fips", - }: endpoints.Endpoint{ - Hostname: "sts.us-gov-west-1.amazonaws.com", - CredentialScope: endpoints.CredentialScope{ - Region: "us-gov-west-1", - }, - Deprecated: aws.TrueTernary, - }, - }, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/options.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/options.go deleted file mode 100644 index 5c1be79f..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/options.go +++ /dev/null @@ -1,217 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -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/middleware" - 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 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 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/sts/serializers.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/serializers.go deleted file mode 100644 index 4c08061c..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/serializers.go +++ /dev/null @@ -1,862 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "bytes" - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/aws/protocol/query" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/encoding/httpbinding" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "path" -) - -type awsAwsquery_serializeOpAssumeRole struct { -} - -func (*awsAwsquery_serializeOpAssumeRole) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpAssumeRole) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*AssumeRoleInput) - _ = 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-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("AssumeRole") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentAssumeRoleInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpAssumeRoleWithSAML struct { -} - -func (*awsAwsquery_serializeOpAssumeRoleWithSAML) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpAssumeRoleWithSAML) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*AssumeRoleWithSAMLInput) - _ = 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-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("AssumeRoleWithSAML") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentAssumeRoleWithSAMLInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpAssumeRoleWithWebIdentity struct { -} - -func (*awsAwsquery_serializeOpAssumeRoleWithWebIdentity) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpAssumeRoleWithWebIdentity) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*AssumeRoleWithWebIdentityInput) - _ = 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-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("AssumeRoleWithWebIdentity") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentAssumeRoleWithWebIdentityInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpDecodeAuthorizationMessage struct { -} - -func (*awsAwsquery_serializeOpDecodeAuthorizationMessage) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpDecodeAuthorizationMessage) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*DecodeAuthorizationMessageInput) - _ = 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-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("DecodeAuthorizationMessage") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentDecodeAuthorizationMessageInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpGetAccessKeyInfo struct { -} - -func (*awsAwsquery_serializeOpGetAccessKeyInfo) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpGetAccessKeyInfo) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetAccessKeyInfoInput) - _ = 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-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("GetAccessKeyInfo") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentGetAccessKeyInfoInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpGetCallerIdentity struct { -} - -func (*awsAwsquery_serializeOpGetCallerIdentity) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpGetCallerIdentity) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetCallerIdentityInput) - _ = 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-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("GetCallerIdentity") - body.Key("Version").String("2011-06-15") - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpGetFederationToken struct { -} - -func (*awsAwsquery_serializeOpGetFederationToken) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpGetFederationToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetFederationTokenInput) - _ = 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-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("GetFederationToken") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentGetFederationTokenInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.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 - - return next.HandleSerialize(ctx, in) -} - -type awsAwsquery_serializeOpGetSessionToken struct { -} - -func (*awsAwsquery_serializeOpGetSessionToken) ID() string { - return "OperationSerializer" -} - -func (m *awsAwsquery_serializeOpGetSessionToken) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - 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.(*GetSessionTokenInput) - _ = 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-www-form-urlencoded") - - bodyWriter := bytes.NewBuffer(nil) - bodyEncoder := query.NewEncoder(bodyWriter) - body := bodyEncoder.Object() - body.Key("Action").String("GetSessionToken") - body.Key("Version").String("2011-06-15") - - if err := awsAwsquery_serializeOpDocumentGetSessionTokenInput(input, bodyEncoder.Value); err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - err = bodyEncoder.Encode() - if err != nil { - return out, metadata, &smithy.SerializationError{Err: err} - } - - if request, err = request.SetStream(bytes.NewReader(bodyWriter.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 - - return next.HandleSerialize(ctx, in) -} -func awsAwsquery_serializeDocumentPolicyDescriptorListType(v []types.PolicyDescriptorType, value query.Value) error { - array := value.Array("member") - - for i := range v { - av := array.Value() - if err := awsAwsquery_serializeDocumentPolicyDescriptorType(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsquery_serializeDocumentPolicyDescriptorType(v *types.PolicyDescriptorType, value query.Value) error { - object := value.Object() - _ = object - - if v.Arn != nil { - objectKey := object.Key("arn") - objectKey.String(*v.Arn) - } - - return nil -} - -func awsAwsquery_serializeDocumentProvidedContext(v *types.ProvidedContext, value query.Value) error { - object := value.Object() - _ = object - - if v.ContextAssertion != nil { - objectKey := object.Key("ContextAssertion") - objectKey.String(*v.ContextAssertion) - } - - if v.ProviderArn != nil { - objectKey := object.Key("ProviderArn") - objectKey.String(*v.ProviderArn) - } - - return nil -} - -func awsAwsquery_serializeDocumentProvidedContextsListType(v []types.ProvidedContext, value query.Value) error { - array := value.Array("member") - - for i := range v { - av := array.Value() - if err := awsAwsquery_serializeDocumentProvidedContext(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsquery_serializeDocumentTag(v *types.Tag, value query.Value) error { - object := value.Object() - _ = object - - if v.Key != nil { - objectKey := object.Key("Key") - objectKey.String(*v.Key) - } - - if v.Value != nil { - objectKey := object.Key("Value") - objectKey.String(*v.Value) - } - - return nil -} - -func awsAwsquery_serializeDocumentTagKeyListType(v []string, value query.Value) error { - array := value.Array("member") - - for i := range v { - av := array.Value() - av.String(v[i]) - } - return nil -} - -func awsAwsquery_serializeDocumentTagListType(v []types.Tag, value query.Value) error { - array := value.Array("member") - - for i := range v { - av := array.Value() - if err := awsAwsquery_serializeDocumentTag(&v[i], av); err != nil { - return err - } - } - return nil -} - -func awsAwsquery_serializeOpDocumentAssumeRoleInput(v *AssumeRoleInput, value query.Value) error { - object := value.Object() - _ = object - - if v.DurationSeconds != nil { - objectKey := object.Key("DurationSeconds") - objectKey.Integer(*v.DurationSeconds) - } - - if v.ExternalId != nil { - objectKey := object.Key("ExternalId") - objectKey.String(*v.ExternalId) - } - - if v.Policy != nil { - objectKey := object.Key("Policy") - objectKey.String(*v.Policy) - } - - if v.PolicyArns != nil { - objectKey := object.Key("PolicyArns") - if err := awsAwsquery_serializeDocumentPolicyDescriptorListType(v.PolicyArns, objectKey); err != nil { - return err - } - } - - if v.ProvidedContexts != nil { - objectKey := object.Key("ProvidedContexts") - if err := awsAwsquery_serializeDocumentProvidedContextsListType(v.ProvidedContexts, objectKey); err != nil { - return err - } - } - - if v.RoleArn != nil { - objectKey := object.Key("RoleArn") - objectKey.String(*v.RoleArn) - } - - if v.RoleSessionName != nil { - objectKey := object.Key("RoleSessionName") - objectKey.String(*v.RoleSessionName) - } - - if v.SerialNumber != nil { - objectKey := object.Key("SerialNumber") - objectKey.String(*v.SerialNumber) - } - - if v.SourceIdentity != nil { - objectKey := object.Key("SourceIdentity") - objectKey.String(*v.SourceIdentity) - } - - if v.Tags != nil { - objectKey := object.Key("Tags") - if err := awsAwsquery_serializeDocumentTagListType(v.Tags, objectKey); err != nil { - return err - } - } - - if v.TokenCode != nil { - objectKey := object.Key("TokenCode") - objectKey.String(*v.TokenCode) - } - - if v.TransitiveTagKeys != nil { - objectKey := object.Key("TransitiveTagKeys") - if err := awsAwsquery_serializeDocumentTagKeyListType(v.TransitiveTagKeys, objectKey); err != nil { - return err - } - } - - return nil -} - -func awsAwsquery_serializeOpDocumentAssumeRoleWithSAMLInput(v *AssumeRoleWithSAMLInput, value query.Value) error { - object := value.Object() - _ = object - - if v.DurationSeconds != nil { - objectKey := object.Key("DurationSeconds") - objectKey.Integer(*v.DurationSeconds) - } - - if v.Policy != nil { - objectKey := object.Key("Policy") - objectKey.String(*v.Policy) - } - - if v.PolicyArns != nil { - objectKey := object.Key("PolicyArns") - if err := awsAwsquery_serializeDocumentPolicyDescriptorListType(v.PolicyArns, objectKey); err != nil { - return err - } - } - - if v.PrincipalArn != nil { - objectKey := object.Key("PrincipalArn") - objectKey.String(*v.PrincipalArn) - } - - if v.RoleArn != nil { - objectKey := object.Key("RoleArn") - objectKey.String(*v.RoleArn) - } - - if v.SAMLAssertion != nil { - objectKey := object.Key("SAMLAssertion") - objectKey.String(*v.SAMLAssertion) - } - - return nil -} - -func awsAwsquery_serializeOpDocumentAssumeRoleWithWebIdentityInput(v *AssumeRoleWithWebIdentityInput, value query.Value) error { - object := value.Object() - _ = object - - if v.DurationSeconds != nil { - objectKey := object.Key("DurationSeconds") - objectKey.Integer(*v.DurationSeconds) - } - - if v.Policy != nil { - objectKey := object.Key("Policy") - objectKey.String(*v.Policy) - } - - if v.PolicyArns != nil { - objectKey := object.Key("PolicyArns") - if err := awsAwsquery_serializeDocumentPolicyDescriptorListType(v.PolicyArns, objectKey); err != nil { - return err - } - } - - if v.ProviderId != nil { - objectKey := object.Key("ProviderId") - objectKey.String(*v.ProviderId) - } - - if v.RoleArn != nil { - objectKey := object.Key("RoleArn") - objectKey.String(*v.RoleArn) - } - - if v.RoleSessionName != nil { - objectKey := object.Key("RoleSessionName") - objectKey.String(*v.RoleSessionName) - } - - if v.WebIdentityToken != nil { - objectKey := object.Key("WebIdentityToken") - objectKey.String(*v.WebIdentityToken) - } - - return nil -} - -func awsAwsquery_serializeOpDocumentDecodeAuthorizationMessageInput(v *DecodeAuthorizationMessageInput, value query.Value) error { - object := value.Object() - _ = object - - if v.EncodedMessage != nil { - objectKey := object.Key("EncodedMessage") - objectKey.String(*v.EncodedMessage) - } - - return nil -} - -func awsAwsquery_serializeOpDocumentGetAccessKeyInfoInput(v *GetAccessKeyInfoInput, value query.Value) error { - object := value.Object() - _ = object - - if v.AccessKeyId != nil { - objectKey := object.Key("AccessKeyId") - objectKey.String(*v.AccessKeyId) - } - - return nil -} - -func awsAwsquery_serializeOpDocumentGetCallerIdentityInput(v *GetCallerIdentityInput, value query.Value) error { - object := value.Object() - _ = object - - return nil -} - -func awsAwsquery_serializeOpDocumentGetFederationTokenInput(v *GetFederationTokenInput, value query.Value) error { - object := value.Object() - _ = object - - if v.DurationSeconds != nil { - objectKey := object.Key("DurationSeconds") - objectKey.Integer(*v.DurationSeconds) - } - - if v.Name != nil { - objectKey := object.Key("Name") - objectKey.String(*v.Name) - } - - if v.Policy != nil { - objectKey := object.Key("Policy") - objectKey.String(*v.Policy) - } - - if v.PolicyArns != nil { - objectKey := object.Key("PolicyArns") - if err := awsAwsquery_serializeDocumentPolicyDescriptorListType(v.PolicyArns, objectKey); err != nil { - return err - } - } - - if v.Tags != nil { - objectKey := object.Key("Tags") - if err := awsAwsquery_serializeDocumentTagListType(v.Tags, objectKey); err != nil { - return err - } - } - - return nil -} - -func awsAwsquery_serializeOpDocumentGetSessionTokenInput(v *GetSessionTokenInput, value query.Value) error { - object := value.Object() - _ = object - - if v.DurationSeconds != nil { - objectKey := object.Key("DurationSeconds") - objectKey.Integer(*v.DurationSeconds) - } - - if v.SerialNumber != nil { - objectKey := object.Key("SerialNumber") - objectKey.String(*v.SerialNumber) - } - - if v.TokenCode != nil { - objectKey := object.Key("TokenCode") - objectKey.String(*v.TokenCode) - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/errors.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/errors.go deleted file mode 100644 index 097875b2..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/errors.go +++ /dev/null @@ -1,244 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - "fmt" - smithy "github.com/aws/smithy-go" -) - -// The web identity token that was passed is expired or is not valid. Get a new -// identity token from the identity provider and then retry the request. -type ExpiredTokenException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *ExpiredTokenException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *ExpiredTokenException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *ExpiredTokenException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "ExpiredTokenException" - } - return *e.ErrorCodeOverride -} -func (e *ExpiredTokenException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The request could not be fulfilled because the identity provider (IDP) that was -// asked to verify the incoming identity token could not be reached. This is often -// a transient error caused by network conditions. Retry the request a limited -// number of times so that you don't exceed the request rate. If the error -// persists, the identity provider might be down or not responding. -type IDPCommunicationErrorException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *IDPCommunicationErrorException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *IDPCommunicationErrorException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *IDPCommunicationErrorException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "IDPCommunicationError" - } - return *e.ErrorCodeOverride -} -func (e *IDPCommunicationErrorException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The identity provider (IdP) reported that authentication failed. This might be -// because the claim is invalid. If this error is returned for the -// AssumeRoleWithWebIdentity operation, it can also mean that the claim has expired -// or has been explicitly revoked. -type IDPRejectedClaimException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *IDPRejectedClaimException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *IDPRejectedClaimException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *IDPRejectedClaimException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "IDPRejectedClaim" - } - return *e.ErrorCodeOverride -} -func (e *IDPRejectedClaimException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The error returned if the message passed to DecodeAuthorizationMessage was -// invalid. This can happen if the token contains invalid characters, such as -// linebreaks. -type InvalidAuthorizationMessageException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidAuthorizationMessageException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidAuthorizationMessageException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidAuthorizationMessageException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidAuthorizationMessageException" - } - return *e.ErrorCodeOverride -} -func (e *InvalidAuthorizationMessageException) ErrorFault() smithy.ErrorFault { - return smithy.FaultClient -} - -// The web identity token that was passed could not be validated by Amazon Web -// Services. Get a new identity token from the identity provider and then retry the -// request. -type InvalidIdentityTokenException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *InvalidIdentityTokenException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *InvalidIdentityTokenException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *InvalidIdentityTokenException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "InvalidIdentityToken" - } - return *e.ErrorCodeOverride -} -func (e *InvalidIdentityTokenException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -type MalformedPolicyDocumentException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *MalformedPolicyDocumentException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *MalformedPolicyDocumentException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *MalformedPolicyDocumentException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "MalformedPolicyDocument" - } - return *e.ErrorCodeOverride -} -func (e *MalformedPolicyDocumentException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// The request was rejected because the total packed size of the session policies -// and session tags combined was too large. An Amazon Web Services conversion -// compresses the session policy document, session policy ARNs, and session tags -// into a packed binary format that has a separate limit. The error message -// indicates by percentage how close the policies and tags are to the upper size -// limit. For more information, see Passing Session Tags in STS (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. You could receive this error even though you meet other -// defined session policy and session tag limits. For more information, see IAM -// and STS Entity Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html#reference_iam-limits-entity-length) -// in the IAM User Guide. -type PackedPolicyTooLargeException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *PackedPolicyTooLargeException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *PackedPolicyTooLargeException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *PackedPolicyTooLargeException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "PackedPolicyTooLarge" - } - return *e.ErrorCodeOverride -} -func (e *PackedPolicyTooLargeException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } - -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating Amazon Web Services STS in an Amazon Web Services Region (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -type RegionDisabledException struct { - Message *string - - ErrorCodeOverride *string - - noSmithyDocumentSerde -} - -func (e *RegionDisabledException) Error() string { - return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage()) -} -func (e *RegionDisabledException) ErrorMessage() string { - if e.Message == nil { - return "" - } - return *e.Message -} -func (e *RegionDisabledException) ErrorCode() string { - if e == nil || e.ErrorCodeOverride == nil { - return "RegionDisabledException" - } - return *e.ErrorCodeOverride -} -func (e *RegionDisabledException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient } diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/types.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/types.go deleted file mode 100644 index e3701d11..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/types/types.go +++ /dev/null @@ -1,134 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package types - -import ( - smithydocument "github.com/aws/smithy-go/document" - "time" -) - -// The identifiers for the temporary security credentials that the operation -// returns. -type AssumedRoleUser struct { - - // The ARN of the temporary security credentials that are returned from the - // AssumeRole action. For more information about ARNs and how to use them in - // policies, see IAM Identifiers (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in the IAM User Guide. - // - // This member is required. - Arn *string - - // A unique identifier that contains the role ID and the role session name of the - // role that is being assumed. The role ID is generated by Amazon Web Services when - // the role is created. - // - // This member is required. - AssumedRoleId *string - - noSmithyDocumentSerde -} - -// Amazon Web Services credentials for API authentication. -type Credentials struct { - - // The access key ID that identifies the temporary security credentials. - // - // This member is required. - AccessKeyId *string - - // The date on which the current credentials expire. - // - // This member is required. - Expiration *time.Time - - // The secret access key that can be used to sign requests. - // - // This member is required. - SecretAccessKey *string - - // The token that users must pass to the service API to use the temporary - // credentials. - // - // This member is required. - SessionToken *string - - noSmithyDocumentSerde -} - -// Identifiers for the federated user that is associated with the credentials. -type FederatedUser struct { - - // The ARN that specifies the federated user that is associated with the - // credentials. For more information about ARNs and how to use them in policies, - // see IAM Identifiers (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in the IAM User Guide. - // - // This member is required. - Arn *string - - // The string that identifies the federated user associated with the credentials, - // similar to the unique ID of an IAM user. - // - // This member is required. - FederatedUserId *string - - noSmithyDocumentSerde -} - -// A reference to the IAM managed policy that is passed as a session policy for a -// role session or a federated user session. -type PolicyDescriptorType struct { - - // The Amazon Resource Name (ARN) of the IAM managed policy to use as a session - // policy for the role. For more information about ARNs, see Amazon Resource Names - // (ARNs) and Amazon Web Services Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) - // in the Amazon Web Services General Reference. - Arn *string - - noSmithyDocumentSerde -} - -// Contains information about the provided context. This includes the signed and -// encrypted trusted context assertion and the context provider ARN from which the -// trusted context assertion was generated. -type ProvidedContext struct { - - // The signed and encrypted trusted context assertion generated by the context - // provider. The trusted context assertion is signed and encrypted by Amazon Web - // Services STS. - ContextAssertion *string - - // The context provider ARN from which the trusted context assertion was generated. - ProviderArn *string - - noSmithyDocumentSerde -} - -// You can pass custom key-value pair attributes when you assume a role or -// federate a user. These are called session tags. You can then use the session -// tags to control access to resources. For more information, see Tagging Amazon -// Web Services STS Sessions (https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html) -// in the IAM User Guide. -type Tag struct { - - // The key for a session tag. You can pass up to 50 session tags. The plain text - // session tag keys can’t exceed 128 characters. For these and additional limits, - // see IAM and STS Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. - // - // This member is required. - Key *string - - // The value for a session tag. You can pass up to 50 session tags. The plain text - // session tag values can’t exceed 256 characters. For these and additional limits, - // see IAM and STS Character Limits (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length) - // in the IAM User Guide. - // - // This member is required. - Value *string - - noSmithyDocumentSerde -} - -type noSmithyDocumentSerde = smithydocument.NoSerde diff --git a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/validators.go b/vendor/github.com/aws/aws-sdk-go-v2/service/sts/validators.go deleted file mode 100644 index 3e4bad2a..00000000 --- a/vendor/github.com/aws/aws-sdk-go-v2/service/sts/validators.go +++ /dev/null @@ -1,305 +0,0 @@ -// Code generated by smithy-go-codegen DO NOT EDIT. - -package sts - -import ( - "context" - "fmt" - "github.com/aws/aws-sdk-go-v2/service/sts/types" - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -type validateOpAssumeRole struct { -} - -func (*validateOpAssumeRole) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpAssumeRole) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*AssumeRoleInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpAssumeRoleInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpAssumeRoleWithSAML struct { -} - -func (*validateOpAssumeRoleWithSAML) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpAssumeRoleWithSAML) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*AssumeRoleWithSAMLInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpAssumeRoleWithSAMLInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpAssumeRoleWithWebIdentity struct { -} - -func (*validateOpAssumeRoleWithWebIdentity) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpAssumeRoleWithWebIdentity) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*AssumeRoleWithWebIdentityInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpAssumeRoleWithWebIdentityInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpDecodeAuthorizationMessage struct { -} - -func (*validateOpDecodeAuthorizationMessage) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpDecodeAuthorizationMessage) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*DecodeAuthorizationMessageInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpDecodeAuthorizationMessageInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetAccessKeyInfo struct { -} - -func (*validateOpGetAccessKeyInfo) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetAccessKeyInfo) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetAccessKeyInfoInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetAccessKeyInfoInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -type validateOpGetFederationToken struct { -} - -func (*validateOpGetFederationToken) ID() string { - return "OperationInputValidation" -} - -func (m *validateOpGetFederationToken) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - input, ok := in.Parameters.(*GetFederationTokenInput) - if !ok { - return out, metadata, fmt.Errorf("unknown input parameters type %T", in.Parameters) - } - if err := validateOpGetFederationTokenInput(input); err != nil { - return out, metadata, err - } - return next.HandleInitialize(ctx, in) -} - -func addOpAssumeRoleValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpAssumeRole{}, middleware.After) -} - -func addOpAssumeRoleWithSAMLValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpAssumeRoleWithSAML{}, middleware.After) -} - -func addOpAssumeRoleWithWebIdentityValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpAssumeRoleWithWebIdentity{}, middleware.After) -} - -func addOpDecodeAuthorizationMessageValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpDecodeAuthorizationMessage{}, middleware.After) -} - -func addOpGetAccessKeyInfoValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetAccessKeyInfo{}, middleware.After) -} - -func addOpGetFederationTokenValidationMiddleware(stack *middleware.Stack) error { - return stack.Initialize.Add(&validateOpGetFederationToken{}, middleware.After) -} - -func validateTag(v *types.Tag) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "Tag"} - if v.Key == nil { - invalidParams.Add(smithy.NewErrParamRequired("Key")) - } - if v.Value == nil { - invalidParams.Add(smithy.NewErrParamRequired("Value")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateTagListType(v []types.Tag) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "TagListType"} - for i := range v { - if err := validateTag(&v[i]); err != nil { - invalidParams.AddNested(fmt.Sprintf("[%d]", i), err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpAssumeRoleInput(v *AssumeRoleInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssumeRoleInput"} - if v.RoleArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleArn")) - } - if v.RoleSessionName == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleSessionName")) - } - if v.Tags != nil { - if err := validateTagListType(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpAssumeRoleWithSAMLInput(v *AssumeRoleWithSAMLInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssumeRoleWithSAMLInput"} - if v.RoleArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleArn")) - } - if v.PrincipalArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("PrincipalArn")) - } - if v.SAMLAssertion == nil { - invalidParams.Add(smithy.NewErrParamRequired("SAMLAssertion")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpAssumeRoleWithWebIdentityInput(v *AssumeRoleWithWebIdentityInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "AssumeRoleWithWebIdentityInput"} - if v.RoleArn == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleArn")) - } - if v.RoleSessionName == nil { - invalidParams.Add(smithy.NewErrParamRequired("RoleSessionName")) - } - if v.WebIdentityToken == nil { - invalidParams.Add(smithy.NewErrParamRequired("WebIdentityToken")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpDecodeAuthorizationMessageInput(v *DecodeAuthorizationMessageInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "DecodeAuthorizationMessageInput"} - if v.EncodedMessage == nil { - invalidParams.Add(smithy.NewErrParamRequired("EncodedMessage")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetAccessKeyInfoInput(v *GetAccessKeyInfoInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetAccessKeyInfoInput"} - if v.AccessKeyId == nil { - invalidParams.Add(smithy.NewErrParamRequired("AccessKeyId")) - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} - -func validateOpGetFederationTokenInput(v *GetFederationTokenInput) error { - if v == nil { - return nil - } - invalidParams := smithy.InvalidParamsError{Context: "GetFederationTokenInput"} - if v.Name == nil { - invalidParams.Add(smithy.NewErrParamRequired("Name")) - } - if v.Tags != nil { - if err := validateTagListType(v.Tags); err != nil { - invalidParams.AddNested("Tags", err.(smithy.InvalidParamsError)) - } - } - if invalidParams.Len() > 0 { - return invalidParams - } else { - return nil - } -} diff --git a/vendor/github.com/aws/smithy-go/.gitignore b/vendor/github.com/aws/smithy-go/.gitignore deleted file mode 100644 index c92d6105..00000000 --- a/vendor/github.com/aws/smithy-go/.gitignore +++ /dev/null @@ -1,26 +0,0 @@ -# Eclipse -.classpath -.project -.settings/ - -# Intellij -.idea/ -*.iml -*.iws - -# Mac -.DS_Store - -# Maven -target/ -**/dependency-reduced-pom.xml - -# Gradle -/.gradle -build/ -*/out/ -*/*/out/ - -# VS Code -bin/ -.vscode/ diff --git a/vendor/github.com/aws/smithy-go/.travis.yml b/vendor/github.com/aws/smithy-go/.travis.yml deleted file mode 100644 index f8d1035c..00000000 --- a/vendor/github.com/aws/smithy-go/.travis.yml +++ /dev/null @@ -1,28 +0,0 @@ -language: go -sudo: true -dist: bionic - -branches: - only: - - main - -os: - - linux - - osx - # Travis doesn't work with windows and Go tip - #- windows - -go: - - tip - -matrix: - allow_failures: - - go: tip - -before_install: - - if [ "$TRAVIS_OS_NAME" = "windows" ]; then choco install make; fi - - (cd /tmp/; go get golang.org/x/lint/golint) - -script: - - make go test -v ./...; - diff --git a/vendor/github.com/aws/smithy-go/CHANGELOG.md b/vendor/github.com/aws/smithy-go/CHANGELOG.md deleted file mode 100644 index 46b11508..00000000 --- a/vendor/github.com/aws/smithy-go/CHANGELOG.md +++ /dev/null @@ -1,216 +0,0 @@ -# Release (2023-12-07) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.19.0 - * **Feature**: Support modeled request compression. - -# Release (2023-11-30) - -* No change notes available for this release. - -# Release (2023-11-29) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.18.0 - * **Feature**: Expose Options() method on generated service clients. - -# Release (2023-11-15) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.17.0 - * **Feature**: Support identity/auth components of client reference architecture. - -# Release (2023-10-31) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.16.0 - * **Feature**: **LANG**: Bump minimum go version to 1.19. - -# Release (2023-10-06) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.15.0 - * **Feature**: Add `http.WithHeaderComment` middleware. - -# Release (2023-08-18) - -* No change notes available for this release. - -# Release (2023-08-07) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.14.1 - * **Bug Fix**: Prevent duplicated error returns in EndpointResolverV2 default implementation. - -# Release (2023-07-31) - -## General Highlights -* **Feature**: Adds support for smithy-modeled endpoint resolution. - -# Release (2022-12-02) - -* No change notes available for this release. - -# Release (2022-10-24) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.13.4 - * **Bug Fix**: fixed document type checking for encoding nested types - -# Release (2022-09-14) - -* No change notes available for this release. - -# Release (v1.13.2) - -* No change notes available for this release. - -# Release (v1.13.1) - -* No change notes available for this release. - -# Release (v1.13.0) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.13.0 - * **Feature**: Adds support for the Smithy httpBearerAuth authentication trait to smithy-go. This allows the SDK to support the bearer authentication flow for API operations decorated with httpBearerAuth. An API client will need to be provided with its own bearer.TokenProvider implementation or use the bearer.StaticTokenProvider implementation. - -# Release (v1.12.1) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.12.1 - * **Bug Fix**: Fixes a bug where JSON object keys were not escaped. - -# Release (v1.12.0) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.12.0 - * **Feature**: `transport/http`: Add utility for setting context metadata when operation serializer automatically assigns content-type default value. - -# Release (v1.11.3) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.11.3 - * **Dependency Update**: Updates smithy-go unit test dependency go-cmp to 0.5.8. - -# Release (v1.11.2) - -* No change notes available for this release. - -# Release (v1.11.1) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.11.1 - * **Bug Fix**: Updates the smithy-go HTTP Request to correctly handle building the request to an http.Request. Related to [aws/aws-sdk-go-v2#1583](https://github.com/aws/aws-sdk-go-v2/issues/1583) - -# Release (v1.11.0) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.11.0 - * **Feature**: Updates deserialization of header list to supported quoted strings - -# Release (v1.10.0) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.10.0 - * **Feature**: Add `ptr.Duration`, `ptr.ToDuration`, `ptr.DurationSlice`, `ptr.ToDurationSlice`, `ptr.DurationMap`, and `ptr.ToDurationMap` functions for the `time.Duration` type. - -# Release (v1.9.1) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.9.1 - * **Documentation**: Fixes various typos in Go package documentation. - -# Release (v1.9.0) - -## Module Highlights -* `github.com/aws/smithy-go`: v1.9.0 - * **Feature**: sync: OnceErr, can be used to concurrently record a signal when an error has occurred. - * **Bug Fix**: `transport/http`: CloseResponseBody and ErrorCloseResponseBody middleware have been updated to ensure that the body is fully drained before closing. - -# Release v1.8.1 - -### Smithy Go Module -* **Bug Fix**: Fixed an issue that would cause the HTTP Content-Length to be set to 0 if the stream body was not set. - * Fixes [aws/aws-sdk-go-v2#1418](https://github.com/aws/aws-sdk-go-v2/issues/1418) - -# Release v1.8.0 - -### Smithy Go Module - -* `time`: Add support for parsing additional DateTime timestamp format ([#324](https://github.com/aws/smithy-go/pull/324)) - * Adds support for parsing DateTime timestamp formatted time similar to RFC 3339, but without the `Z` character, nor UTC offset. - * Fixes [#1387](https://github.com/aws/aws-sdk-go-v2/issues/1387) - -# Release v1.7.0 - -### Smithy Go Module -* `ptr`: Handle error for deferred file close call ([#314](https://github.com/aws/smithy-go/pull/314)) - * Handle error for defer close call -* `middleware`: Add Clone to Metadata ([#318](https://github.com/aws/smithy-go/pull/318)) - * Adds a new Clone method to the middleware Metadata type. This provides a shallow clone of the entries in the Metadata. -* `document`: Add new package for document shape serialization support ([#310](https://github.com/aws/smithy-go/pull/310)) - -### Codegen -* Add Smithy Document Shape Support ([#310](https://github.com/aws/smithy-go/pull/310)) - * Adds support for Smithy Document shapes and supporting types for protocols to implement support - -# Release v1.6.0 (2021-07-15) - -### Smithy Go Module -* `encoding/httpbinding`: Support has been added for encoding `float32` and `float64` values that are `NaN`, `Infinity`, or `-Infinity`. ([#316](https://github.com/aws/smithy-go/pull/316)) - -### Codegen -* Adds support for handling `float32` and `float64` `NaN` values in HTTP Protocol Unit Tests. ([#316](https://github.com/aws/smithy-go/pull/316)) -* Adds support protocol generator implementations to override the error code string returned by `ErrorCode` methods on generated error types. ([#315](https://github.com/aws/smithy-go/pull/315)) - -# Release v1.5.0 (2021-06-25) - -### Smithy Go module -* `time`: Update time parsing to not be as strict for HTTPDate and DateTime ([#307](https://github.com/aws/smithy-go/pull/307)) - * Fixes [#302](https://github.com/aws/smithy-go/issues/302) by changing time to UTC before formatting so no local offset time is lost. - -### Codegen -* Adds support for integrating client members via plugins ([#301](https://github.com/aws/smithy-go/pull/301)) -* Fix serialization of enum types marked with payload trait ([#296](https://github.com/aws/smithy-go/pull/296)) -* Update generation of API client modules to include a manifest of files generated ([#283](https://github.com/aws/smithy-go/pull/283)) -* Update Group Java group ID for smithy-go generator ([#298](https://github.com/aws/smithy-go/pull/298)) -* Support the delegation of determining the errors that can occur for an operation ([#304](https://github.com/aws/smithy-go/pull/304)) -* Support for marking and documenting deprecated client config fields. ([#303](https://github.com/aws/smithy-go/pull/303)) - -# Release v1.4.0 (2021-05-06) - -### Smithy Go module -* `encoding/xml`: Fix escaping of Next Line and Line Start in XML Encoder ([#267](https://github.com/aws/smithy-go/pull/267)) - -### Codegen -* Add support for Smithy 1.7 ([#289](https://github.com/aws/smithy-go/pull/289)) -* Add support for httpQueryParams location -* Add support for model renaming conflict resolution with service closure - -# Release v1.3.1 (2021-04-08) - -### Smithy Go module -* `transport/http`: Loosen endpoint hostname validation to allow specifying port numbers. ([#279](https://github.com/aws/smithy-go/pull/279)) -* `io`: Fix RingBuffer panics due to out of bounds index. ([#282](https://github.com/aws/smithy-go/pull/282)) - -# Release v1.3.0 (2021-04-01) - -### Smithy Go module -* `transport/http`: Add utility to safely join string to url path, and url raw query. - -### Codegen -* Update HttpBindingProtocolGenerator to use http/transport JoinPath and JoinQuery utility. - -# Release v1.2.0 (2021-03-12) - -### Smithy Go module -* Fix support for parsing shortened year format in HTTP Date header. -* Fix GitHub APIDiff action workflow to get gorelease tool correctly. -* Fix codegen artifact unit test for Go 1.16 - -### Codegen -* Fix generating paginator nil parameter handling before usage. -* Fix Serialize unboxed members decorated as required. -* Add ability to define resolvers at both client construction and operation invocation. -* Support for extending paginators with custom runtime trait diff --git a/vendor/github.com/aws/smithy-go/CODE_OF_CONDUCT.md b/vendor/github.com/aws/smithy-go/CODE_OF_CONDUCT.md deleted file mode 100644 index 5b627cfa..00000000 --- a/vendor/github.com/aws/smithy-go/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,4 +0,0 @@ -## Code of Conduct -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). -For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. diff --git a/vendor/github.com/aws/smithy-go/CONTRIBUTING.md b/vendor/github.com/aws/smithy-go/CONTRIBUTING.md deleted file mode 100644 index c4b6a1c5..00000000 --- a/vendor/github.com/aws/smithy-go/CONTRIBUTING.md +++ /dev/null @@ -1,59 +0,0 @@ -# Contributing Guidelines - -Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional -documentation, we greatly value feedback and contributions from our community. - -Please read through this document before submitting any issues or pull requests to ensure we have all the necessary -information to effectively respond to your bug report or contribution. - - -## Reporting Bugs/Feature Requests - -We welcome you to use the GitHub issue tracker to report bugs or suggest features. - -When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already -reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: - -* A reproducible test case or series of steps -* The version of our code being used -* Any modifications you've made relevant to the bug -* Anything unusual about your environment or deployment - - -## Contributing via Pull Requests -Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: - -1. You are working against the latest source on the *main* branch. -2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. -3. You open an issue to discuss any significant work - we would hate for your time to be wasted. - -To send us a pull request, please: - -1. Fork the repository. -2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. -3. Ensure local tests pass. -4. Commit to your fork using clear commit messages. -5. Send us a pull request, answering any default questions in the pull request interface. -6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. - -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/). - - -## 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. - - -## Code of Conduct -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). -For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. - - -## Security issue notifications -If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. - - -## Licensing - -See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. diff --git a/vendor/github.com/aws/smithy-go/LICENSE b/vendor/github.com/aws/smithy-go/LICENSE deleted file mode 100644 index 67db8588..00000000 --- a/vendor/github.com/aws/smithy-go/LICENSE +++ /dev/null @@ -1,175 +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. diff --git a/vendor/github.com/aws/smithy-go/Makefile b/vendor/github.com/aws/smithy-go/Makefile deleted file mode 100644 index 4b3c2093..00000000 --- a/vendor/github.com/aws/smithy-go/Makefile +++ /dev/null @@ -1,97 +0,0 @@ -PRE_RELEASE_VERSION ?= - -RELEASE_MANIFEST_FILE ?= -RELEASE_CHGLOG_DESC_FILE ?= - -REPOTOOLS_VERSION ?= latest -REPOTOOLS_MODULE = github.com/awslabs/aws-go-multi-module-repository-tools -REPOTOOLS_CMD_CALCULATE_RELEASE = ${REPOTOOLS_MODULE}/cmd/calculaterelease@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS ?= -REPOTOOLS_CMD_UPDATE_REQUIRES = ${REPOTOOLS_MODULE}/cmd/updaterequires@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_UPDATE_MODULE_METADATA = ${REPOTOOLS_MODULE}/cmd/updatemodulemeta@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_GENERATE_CHANGELOG = ${REPOTOOLS_MODULE}/cmd/generatechangelog@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_CHANGELOG = ${REPOTOOLS_MODULE}/cmd/changelog@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_TAG_RELEASE = ${REPOTOOLS_MODULE}/cmd/tagrelease@${REPOTOOLS_VERSION} -REPOTOOLS_CMD_MODULE_VERSION = ${REPOTOOLS_MODULE}/cmd/moduleversion@${REPOTOOLS_VERSION} - -UNIT_TEST_TAGS= -BUILD_TAGS= - -ifneq ($(PRE_RELEASE_VERSION),) - REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS += -preview=${PRE_RELEASE_VERSION} -endif - -smithy-publish-local: - cd codegen && ./gradlew publishToMavenLocal - -smithy-build: - cd codegen && ./gradlew build - -smithy-clean: - cd codegen && ./gradlew clean - -################## -# Linting/Verify # -################## -.PHONY: verify vet - -verify: vet - -vet: - go vet ${BUILD_TAGS} --all ./... - -################ -# Unit Testing # -################ -.PHONY: unit unit-race unit-test unit-race-test - -unit: verify - go vet ${BUILD_TAGS} --all ./... && \ - go test ${BUILD_TAGS} ${RUN_NONE} ./... && \ - go test -timeout=1m ${UNIT_TEST_TAGS} ./... - -unit-race: verify - go vet ${BUILD_TAGS} --all ./... && \ - go test ${BUILD_TAGS} ${RUN_NONE} ./... && \ - go test -timeout=1m ${UNIT_TEST_TAGS} -race -cpu=4 ./... - -unit-test: verify - go test -timeout=1m ${UNIT_TEST_TAGS} ./... - -unit-race-test: verify - go test -timeout=1m ${UNIT_TEST_TAGS} -race -cpu=4 ./... - -##################### -# Release Process # -##################### -.PHONY: preview-release pre-release-validation release - -preview-release: - go run ${REPOTOOLS_CMD_CALCULATE_RELEASE} ${REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS} - -pre-release-validation: - @if [[ -z "${RELEASE_MANIFEST_FILE}" ]]; then \ - echo "RELEASE_MANIFEST_FILE is required to specify the file to write the release manifest" && false; \ - fi - @if [[ -z "${RELEASE_CHGLOG_DESC_FILE}" ]]; then \ - echo "RELEASE_CHGLOG_DESC_FILE is required to specify the file to write the release notes" && false; \ - fi - -release: pre-release-validation - go run ${REPOTOOLS_CMD_CALCULATE_RELEASE} -o ${RELEASE_MANIFEST_FILE} ${REPOTOOLS_CMD_CALCULATE_RELEASE_ADDITIONAL_ARGS} - go run ${REPOTOOLS_CMD_UPDATE_REQUIRES} -release ${RELEASE_MANIFEST_FILE} - go run ${REPOTOOLS_CMD_UPDATE_MODULE_METADATA} -release ${RELEASE_MANIFEST_FILE} - go run ${REPOTOOLS_CMD_GENERATE_CHANGELOG} -release ${RELEASE_MANIFEST_FILE} -o ${RELEASE_CHGLOG_DESC_FILE} - go run ${REPOTOOLS_CMD_CHANGELOG} rm -all - go run ${REPOTOOLS_CMD_TAG_RELEASE} -release ${RELEASE_MANIFEST_FILE} - -module-version: - @go run ${REPOTOOLS_CMD_MODULE_VERSION} . - -############## -# Repo Tools # -############## -.PHONY: install-changelog - -install-changelog: - go install ${REPOTOOLS_MODULE}/cmd/changelog@${REPOTOOLS_VERSION} diff --git a/vendor/github.com/aws/smithy-go/NOTICE b/vendor/github.com/aws/smithy-go/NOTICE deleted file mode 100644 index 616fc588..00000000 --- a/vendor/github.com/aws/smithy-go/NOTICE +++ /dev/null @@ -1 +0,0 @@ -Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/vendor/github.com/aws/smithy-go/README.md b/vendor/github.com/aws/smithy-go/README.md deleted file mode 100644 index c374f692..00000000 --- a/vendor/github.com/aws/smithy-go/README.md +++ /dev/null @@ -1,27 +0,0 @@ -## Smithy Go - -[![Go Build Status](https://github.com/aws/smithy-go/actions/workflows/go.yml/badge.svg?branch=main)](https://github.com/aws/smithy-go/actions/workflows/go.yml)[![Codegen Build Status](https://github.com/aws/smithy-go/actions/workflows/codegen.yml/badge.svg?branch=main)](https://github.com/aws/smithy-go/actions/workflows/codegen.yml) - -[Smithy](https://smithy.io/) code generators for Go. - -**WARNING: All interfaces are subject to change.** - -## Can I use this? - -In order to generate a usable smithy client you must provide a [protocol definition](https://github.com/aws/smithy-go/blob/main/codegen/smithy-go-codegen/src/main/java/software/amazon/smithy/go/codegen/integration/ProtocolGenerator.java), -such as [AWS restJson1](https://smithy.io/2.0/aws/protocols/aws-restjson1-protocol.html), -in order to generate transport mechanisms and serialization/deserialization -code ("serde") accordingly. - -The code generator does not currently support any protocols out of the box, -therefore the useability of this project on its own is currently limited. -Support for all [AWS protocols](https://smithy.io/2.0/aws/protocols/index.html) -exists in [aws-sdk-go-v2](https://github.com/aws/aws-sdk-go-v2). We are -tracking the movement of those out of the SDK into smithy-go in -[#458](https://github.com/aws/smithy-go/issues/458), but there's currently no -timeline for doing so. - -## License - -This project is licensed under the Apache-2.0 License. - diff --git a/vendor/github.com/aws/smithy-go/auth/auth.go b/vendor/github.com/aws/smithy-go/auth/auth.go deleted file mode 100644 index 5bdb70c9..00000000 --- a/vendor/github.com/aws/smithy-go/auth/auth.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package auth defines protocol-agnostic authentication types for smithy -// clients. -package auth diff --git a/vendor/github.com/aws/smithy-go/auth/bearer/docs.go b/vendor/github.com/aws/smithy-go/auth/bearer/docs.go deleted file mode 100644 index 1c9b9715..00000000 --- a/vendor/github.com/aws/smithy-go/auth/bearer/docs.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package bearer provides middleware and utilities for authenticating API -// operation calls with a Bearer Token. -package bearer diff --git a/vendor/github.com/aws/smithy-go/auth/bearer/middleware.go b/vendor/github.com/aws/smithy-go/auth/bearer/middleware.go deleted file mode 100644 index 8c7d7209..00000000 --- a/vendor/github.com/aws/smithy-go/auth/bearer/middleware.go +++ /dev/null @@ -1,104 +0,0 @@ -package bearer - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" -) - -// Message is the middleware stack's request transport message value. -type Message interface{} - -// Signer provides an interface for implementations to decorate a request -// message with a bearer token. The signer is responsible for validating the -// message type is compatible with the signer. -type Signer interface { - SignWithBearerToken(context.Context, Token, Message) (Message, error) -} - -// AuthenticationMiddleware provides the Finalize middleware step for signing -// an request message with a bearer token. -type AuthenticationMiddleware struct { - signer Signer - tokenProvider TokenProvider -} - -// AddAuthenticationMiddleware helper adds the AuthenticationMiddleware to the -// middleware Stack in the Finalize step with the options provided. -func AddAuthenticationMiddleware(s *middleware.Stack, signer Signer, tokenProvider TokenProvider) error { - return s.Finalize.Add( - NewAuthenticationMiddleware(signer, tokenProvider), - middleware.After, - ) -} - -// NewAuthenticationMiddleware returns an initialized AuthenticationMiddleware. -func NewAuthenticationMiddleware(signer Signer, tokenProvider TokenProvider) *AuthenticationMiddleware { - return &AuthenticationMiddleware{ - signer: signer, - tokenProvider: tokenProvider, - } -} - -const authenticationMiddlewareID = "BearerTokenAuthentication" - -// ID returns the resolver identifier -func (m *AuthenticationMiddleware) ID() string { - return authenticationMiddlewareID -} - -// HandleFinalize implements the FinalizeMiddleware interface in order to -// update the request with bearer token authentication. -func (m *AuthenticationMiddleware) HandleFinalize( - ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler, -) ( - out middleware.FinalizeOutput, metadata middleware.Metadata, err error, -) { - token, err := m.tokenProvider.RetrieveBearerToken(ctx) - if err != nil { - return out, metadata, fmt.Errorf("failed AuthenticationMiddleware wrap message, %w", err) - } - - signedMessage, err := m.signer.SignWithBearerToken(ctx, token, in.Request) - if err != nil { - return out, metadata, fmt.Errorf("failed AuthenticationMiddleware sign message, %w", err) - } - - in.Request = signedMessage - return next.HandleFinalize(ctx, in) -} - -// SignHTTPSMessage provides a bearer token authentication implementation that -// will sign the message with the provided bearer token. -// -// Will fail if the message is not a smithy-go HTTP request or the request is -// not HTTPS. -type SignHTTPSMessage struct{} - -// NewSignHTTPSMessage returns an initialized signer for HTTP messages. -func NewSignHTTPSMessage() *SignHTTPSMessage { - return &SignHTTPSMessage{} -} - -// SignWithBearerToken returns a copy of the HTTP request with the bearer token -// added via the "Authorization" header, per RFC 6750, https://datatracker.ietf.org/doc/html/rfc6750. -// -// Returns an error if the request's URL scheme is not HTTPS, or the request -// message is not an smithy-go HTTP Request pointer type. -func (SignHTTPSMessage) SignWithBearerToken(ctx context.Context, token Token, message Message) (Message, error) { - req, ok := message.(*smithyhttp.Request) - if !ok { - return nil, fmt.Errorf("expect smithy-go HTTP Request, got %T", message) - } - - if !req.IsHTTPS() { - return nil, fmt.Errorf("bearer token with HTTP request requires HTTPS") - } - - reqClone := req.Clone() - reqClone.Header.Set("Authorization", "Bearer "+token.Value) - - return reqClone, nil -} diff --git a/vendor/github.com/aws/smithy-go/auth/bearer/token.go b/vendor/github.com/aws/smithy-go/auth/bearer/token.go deleted file mode 100644 index be260d4c..00000000 --- a/vendor/github.com/aws/smithy-go/auth/bearer/token.go +++ /dev/null @@ -1,50 +0,0 @@ -package bearer - -import ( - "context" - "time" -) - -// Token provides a type wrapping a bearer token and expiration metadata. -type Token struct { - Value string - - CanExpire bool - Expires time.Time -} - -// Expired returns if the token's Expires time is before or equal to the time -// provided. If CanExpires is false, Expired will always return false. -func (t Token) Expired(now time.Time) bool { - if !t.CanExpire { - return false - } - now = now.Round(0) - return now.Equal(t.Expires) || now.After(t.Expires) -} - -// TokenProvider provides interface for retrieving bearer tokens. -type TokenProvider interface { - RetrieveBearerToken(context.Context) (Token, error) -} - -// TokenProviderFunc provides a helper utility to wrap a function as a type -// that implements the TokenProvider interface. -type TokenProviderFunc func(context.Context) (Token, error) - -// RetrieveBearerToken calls the wrapped function, returning the Token or -// error. -func (fn TokenProviderFunc) RetrieveBearerToken(ctx context.Context) (Token, error) { - return fn(ctx) -} - -// StaticTokenProvider provides a utility for wrapping a static bearer token -// value within an implementation of a token provider. -type StaticTokenProvider struct { - Token Token -} - -// RetrieveBearerToken returns the static token specified. -func (s StaticTokenProvider) RetrieveBearerToken(context.Context) (Token, error) { - return s.Token, nil -} diff --git a/vendor/github.com/aws/smithy-go/auth/bearer/token_cache.go b/vendor/github.com/aws/smithy-go/auth/bearer/token_cache.go deleted file mode 100644 index 223ddf52..00000000 --- a/vendor/github.com/aws/smithy-go/auth/bearer/token_cache.go +++ /dev/null @@ -1,208 +0,0 @@ -package bearer - -import ( - "context" - "fmt" - "sync/atomic" - "time" - - smithycontext "github.com/aws/smithy-go/context" - "github.com/aws/smithy-go/internal/sync/singleflight" -) - -// package variable that can be override in unit tests. -var timeNow = time.Now - -// TokenCacheOptions provides a set of optional configuration options for the -// TokenCache TokenProvider. -type TokenCacheOptions struct { - // The duration before the token will expire when the credentials will be - // refreshed. If DisableAsyncRefresh is true, the RetrieveBearerToken calls - // will be blocking. - // - // Asynchronous refreshes are deduplicated, and only one will be in-flight - // at a time. If the token expires while an asynchronous refresh is in - // flight, the next call to RetrieveBearerToken will block on that refresh - // to return. - RefreshBeforeExpires time.Duration - - // The timeout the underlying TokenProvider's RetrieveBearerToken call must - // return within, or will be canceled. Defaults to 0, no timeout. - // - // If 0 timeout, its possible for the underlying tokenProvider's - // RetrieveBearerToken call to block forever. Preventing subsequent - // TokenCache attempts to refresh the token. - // - // If this timeout is reached all pending deduplicated calls to - // TokenCache RetrieveBearerToken will fail with an error. - RetrieveBearerTokenTimeout time.Duration - - // The minimum duration between asynchronous refresh attempts. If the next - // asynchronous recent refresh attempt was within the minimum delay - // duration, the call to retrieve will return the current cached token, if - // not expired. - // - // The asynchronous retrieve is deduplicated across multiple calls when - // RetrieveBearerToken is called. The asynchronous retrieve is not a - // periodic task. It is only performed when the token has not yet expired, - // and the current item is within the RefreshBeforeExpires window, and the - // TokenCache's RetrieveBearerToken method is called. - // - // If 0, (default) there will be no minimum delay between asynchronous - // refresh attempts. - // - // If DisableAsyncRefresh is true, this option is ignored. - AsyncRefreshMinimumDelay time.Duration - - // Sets if the TokenCache will attempt to refresh the token in the - // background asynchronously instead of blocking for credentials to be - // refreshed. If disabled token refresh will be blocking. - // - // The first call to RetrieveBearerToken will always be blocking, because - // there is no cached token. - DisableAsyncRefresh bool -} - -// TokenCache provides an utility to cache Bearer Authentication tokens from a -// wrapped TokenProvider. The TokenCache can be has options to configure the -// cache's early and asynchronous refresh of the token. -type TokenCache struct { - options TokenCacheOptions - provider TokenProvider - - cachedToken atomic.Value - lastRefreshAttemptTime atomic.Value - sfGroup singleflight.Group -} - -// NewTokenCache returns a initialized TokenCache that implements the -// TokenProvider interface. Wrapping the provider passed in. Also taking a set -// of optional functional option parameters to configure the token cache. -func NewTokenCache(provider TokenProvider, optFns ...func(*TokenCacheOptions)) *TokenCache { - var options TokenCacheOptions - for _, fn := range optFns { - fn(&options) - } - - return &TokenCache{ - options: options, - provider: provider, - } -} - -// RetrieveBearerToken returns the token if it could be obtained, or error if a -// valid token could not be retrieved. -// -// The passed in Context's cancel/deadline/timeout will impacting only this -// individual retrieve call and not any other already queued up calls. This -// means underlying provider's RetrieveBearerToken calls could block for ever, -// and not be canceled with the Context. Set RetrieveBearerTokenTimeout to -// provide a timeout, preventing the underlying TokenProvider blocking forever. -// -// By default, if the passed in Context is canceled, all of its values will be -// considered expired. The wrapped TokenProvider will not be able to lookup the -// values from the Context once it is expired. This is done to protect against -// expired values no longer being valid. To disable this behavior, use -// smithy-go's context.WithPreserveExpiredValues to add a value to the Context -// before calling RetrieveBearerToken to enable support for expired values. -// -// Without RetrieveBearerTokenTimeout there is the potential for a underlying -// Provider's RetrieveBearerToken call to sit forever. Blocking in subsequent -// attempts at refreshing the token. -func (p *TokenCache) RetrieveBearerToken(ctx context.Context) (Token, error) { - cachedToken, ok := p.getCachedToken() - if !ok || cachedToken.Expired(timeNow()) { - return p.refreshBearerToken(ctx) - } - - // Check if the token should be refreshed before it expires. - refreshToken := cachedToken.Expired(timeNow().Add(p.options.RefreshBeforeExpires)) - if !refreshToken { - return cachedToken, nil - } - - if p.options.DisableAsyncRefresh { - return p.refreshBearerToken(ctx) - } - - p.tryAsyncRefresh(ctx) - - return cachedToken, nil -} - -// tryAsyncRefresh attempts to asynchronously refresh the token returning the -// already cached token. If it AsyncRefreshMinimumDelay option is not zero, and -// the duration since the last refresh is less than that value, nothing will be -// done. -func (p *TokenCache) tryAsyncRefresh(ctx context.Context) { - if p.options.AsyncRefreshMinimumDelay != 0 { - var lastRefreshAttempt time.Time - if v := p.lastRefreshAttemptTime.Load(); v != nil { - lastRefreshAttempt = v.(time.Time) - } - - if timeNow().Before(lastRefreshAttempt.Add(p.options.AsyncRefreshMinimumDelay)) { - return - } - } - - // Ignore the returned channel so this won't be blocking, and limit the - // number of additional goroutines created. - p.sfGroup.DoChan("async-refresh", func() (interface{}, error) { - res, err := p.refreshBearerToken(ctx) - if p.options.AsyncRefreshMinimumDelay != 0 { - var refreshAttempt time.Time - if err != nil { - refreshAttempt = timeNow() - } - p.lastRefreshAttemptTime.Store(refreshAttempt) - } - - return res, err - }) -} - -func (p *TokenCache) refreshBearerToken(ctx context.Context) (Token, error) { - resCh := p.sfGroup.DoChan("refresh-token", func() (interface{}, error) { - ctx := smithycontext.WithSuppressCancel(ctx) - if v := p.options.RetrieveBearerTokenTimeout; v != 0 { - var cancel func() - ctx, cancel = context.WithTimeout(ctx, v) - defer cancel() - } - return p.singleRetrieve(ctx) - }) - - select { - case res := <-resCh: - return res.Val.(Token), res.Err - case <-ctx.Done(): - return Token{}, fmt.Errorf("retrieve bearer token canceled, %w", ctx.Err()) - } -} - -func (p *TokenCache) singleRetrieve(ctx context.Context) (interface{}, error) { - token, err := p.provider.RetrieveBearerToken(ctx) - if err != nil { - return Token{}, fmt.Errorf("failed to retrieve bearer token, %w", err) - } - - p.cachedToken.Store(&token) - return token, nil -} - -// getCachedToken returns the currently cached token and true if found. Returns -// false if no token is cached. -func (p *TokenCache) getCachedToken() (Token, bool) { - v := p.cachedToken.Load() - if v == nil { - return Token{}, false - } - - t := v.(*Token) - if t == nil || t.Value == "" { - return Token{}, false - } - - return *t, true -} diff --git a/vendor/github.com/aws/smithy-go/auth/identity.go b/vendor/github.com/aws/smithy-go/auth/identity.go deleted file mode 100644 index ba8cf70d..00000000 --- a/vendor/github.com/aws/smithy-go/auth/identity.go +++ /dev/null @@ -1,47 +0,0 @@ -package auth - -import ( - "context" - "time" - - "github.com/aws/smithy-go" -) - -// Identity contains information that identifies who the user making the -// request is. -type Identity interface { - Expiration() time.Time -} - -// IdentityResolver defines the interface through which an Identity is -// retrieved. -type IdentityResolver interface { - GetIdentity(context.Context, smithy.Properties) (Identity, error) -} - -// IdentityResolverOptions defines the interface through which an entity can be -// queried to retrieve an IdentityResolver for a given auth scheme. -type IdentityResolverOptions interface { - GetIdentityResolver(schemeID string) IdentityResolver -} - -// AnonymousIdentity is a sentinel to indicate no identity. -type AnonymousIdentity struct{} - -var _ Identity = (*AnonymousIdentity)(nil) - -// Expiration returns the zero value for time, as anonymous identity never -// expires. -func (*AnonymousIdentity) Expiration() time.Time { - return time.Time{} -} - -// AnonymousIdentityResolver returns AnonymousIdentity. -type AnonymousIdentityResolver struct{} - -var _ IdentityResolver = (*AnonymousIdentityResolver)(nil) - -// GetIdentity returns AnonymousIdentity. -func (*AnonymousIdentityResolver) GetIdentity(_ context.Context, _ smithy.Properties) (Identity, error) { - return &AnonymousIdentity{}, nil -} diff --git a/vendor/github.com/aws/smithy-go/auth/option.go b/vendor/github.com/aws/smithy-go/auth/option.go deleted file mode 100644 index d5dabff0..00000000 --- a/vendor/github.com/aws/smithy-go/auth/option.go +++ /dev/null @@ -1,25 +0,0 @@ -package auth - -import "github.com/aws/smithy-go" - -type ( - authOptionsKey struct{} -) - -// Option represents a possible authentication method for an operation. -type Option struct { - SchemeID string - IdentityProperties smithy.Properties - SignerProperties smithy.Properties -} - -// GetAuthOptions gets auth Options from Properties. -func GetAuthOptions(p *smithy.Properties) ([]*Option, bool) { - v, ok := p.Get(authOptionsKey{}).([]*Option) - return v, ok -} - -// SetAuthOptions sets auth Options on Properties. -func SetAuthOptions(p *smithy.Properties, options []*Option) { - p.Set(authOptionsKey{}, options) -} diff --git a/vendor/github.com/aws/smithy-go/auth/scheme_id.go b/vendor/github.com/aws/smithy-go/auth/scheme_id.go deleted file mode 100644 index fb6a57c6..00000000 --- a/vendor/github.com/aws/smithy-go/auth/scheme_id.go +++ /dev/null @@ -1,20 +0,0 @@ -package auth - -// Anonymous -const ( - SchemeIDAnonymous = "smithy.api#noAuth" -) - -// HTTP auth schemes -const ( - SchemeIDHTTPBasic = "smithy.api#httpBasicAuth" - SchemeIDHTTPDigest = "smithy.api#httpDigestAuth" - SchemeIDHTTPBearer = "smithy.api#httpBearerAuth" - SchemeIDHTTPAPIKey = "smithy.api#httpApiKeyAuth" -) - -// AWS auth schemes -const ( - SchemeIDSigV4 = "aws.auth#sigv4" - SchemeIDSigV4A = "aws.auth#sigv4a" -) diff --git a/vendor/github.com/aws/smithy-go/context/suppress_expired.go b/vendor/github.com/aws/smithy-go/context/suppress_expired.go deleted file mode 100644 index a39b84a2..00000000 --- a/vendor/github.com/aws/smithy-go/context/suppress_expired.go +++ /dev/null @@ -1,81 +0,0 @@ -package context - -import "context" - -// valueOnlyContext provides a utility to preserve only the values of a -// Context. Suppressing any cancellation or deadline on that context being -// propagated downstream of this value. -// -// If preserveExpiredValues is false (default), and the valueCtx is canceled, -// calls to lookup values with the Values method, will always return nil. Setting -// preserveExpiredValues to true, will allow the valueOnlyContext to lookup -// values in valueCtx even if valueCtx is canceled. -// -// Based on the Go standard libraries net/lookup.go onlyValuesCtx utility. -// https://github.com/golang/go/blob/da2773fe3e2f6106634673a38dc3a6eb875fe7d8/src/net/lookup.go -type valueOnlyContext struct { - context.Context - - preserveExpiredValues bool - valuesCtx context.Context -} - -var _ context.Context = (*valueOnlyContext)(nil) - -// Value looks up the key, returning its value. If configured to not preserve -// values of expired context, and the wrapping context is canceled, nil will be -// returned. -func (v *valueOnlyContext) Value(key interface{}) interface{} { - if !v.preserveExpiredValues { - select { - case <-v.valuesCtx.Done(): - return nil - default: - } - } - - return v.valuesCtx.Value(key) -} - -// WithSuppressCancel wraps the Context value, suppressing its deadline and -// cancellation events being propagated downstream to consumer of the returned -// context. -// -// By default the wrapped Context's Values are available downstream until the -// wrapped Context is canceled. Once the wrapped Context is canceled, Values -// method called on the context return will no longer lookup any key. As they -// are now considered expired. -// -// To override this behavior, use WithPreserveExpiredValues on the Context -// before it is wrapped by WithSuppressCancel. This will make the Context -// returned by WithSuppressCancel allow lookup of expired values. -func WithSuppressCancel(ctx context.Context) context.Context { - return &valueOnlyContext{ - Context: context.Background(), - valuesCtx: ctx, - - preserveExpiredValues: GetPreserveExpiredValues(ctx), - } -} - -type preserveExpiredValuesKey struct{} - -// WithPreserveExpiredValues adds a Value to the Context if expired values -// should be preserved, and looked up by a Context wrapped by -// WithSuppressCancel. -// -// WithPreserveExpiredValues must be added as a value to a Context, before that -// Context is wrapped by WithSuppressCancel -func WithPreserveExpiredValues(ctx context.Context, enable bool) context.Context { - return context.WithValue(ctx, preserveExpiredValuesKey{}, enable) -} - -// GetPreserveExpiredValues looks up, and returns the PreserveExpressValues -// value in the context. Returning true if enabled, false otherwise. -func GetPreserveExpiredValues(ctx context.Context) bool { - v := ctx.Value(preserveExpiredValuesKey{}) - if v != nil { - return v.(bool) - } - return false -} diff --git a/vendor/github.com/aws/smithy-go/doc.go b/vendor/github.com/aws/smithy-go/doc.go deleted file mode 100644 index 87b0c74b..00000000 --- a/vendor/github.com/aws/smithy-go/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package smithy provides the core components for a Smithy SDK. -package smithy diff --git a/vendor/github.com/aws/smithy-go/document.go b/vendor/github.com/aws/smithy-go/document.go deleted file mode 100644 index dec498c5..00000000 --- a/vendor/github.com/aws/smithy-go/document.go +++ /dev/null @@ -1,10 +0,0 @@ -package smithy - -// Document provides access to loosely structured data in a document-like -// format. -// -// Deprecated: See the github.com/aws/smithy-go/document package. -type Document interface { - UnmarshalDocument(interface{}) error - GetValue() (interface{}, error) -} diff --git a/vendor/github.com/aws/smithy-go/document/doc.go b/vendor/github.com/aws/smithy-go/document/doc.go deleted file mode 100644 index 03055b7a..00000000 --- a/vendor/github.com/aws/smithy-go/document/doc.go +++ /dev/null @@ -1,12 +0,0 @@ -// Package document provides interface definitions and error types for document types. -// -// A document is a protocol-agnostic type which supports a JSON-like data-model. You can use this type to send -// UTF-8 strings, arbitrary precision numbers, booleans, nulls, a list of these values, and a map of UTF-8 -// strings to these values. -// -// API Clients expose document constructors in their respective client document packages which must be used to -// Marshal and Unmarshal Go types to and from their respective protocol representations. -// -// See the Marshaler and Unmarshaler type documentation for more details on how to Go types can be converted to and from -// document types. -package document diff --git a/vendor/github.com/aws/smithy-go/document/document.go b/vendor/github.com/aws/smithy-go/document/document.go deleted file mode 100644 index 8f852d95..00000000 --- a/vendor/github.com/aws/smithy-go/document/document.go +++ /dev/null @@ -1,153 +0,0 @@ -package document - -import ( - "fmt" - "math/big" - "strconv" -) - -// Marshaler is an interface for a type that marshals a document to its protocol-specific byte representation and -// returns the resulting bytes. A non-nil error will be returned if an error is encountered during marshaling. -// -// Marshal supports basic scalars (int,uint,float,bool,string), big.Int, and big.Float, maps, slices, and structs. -// Anonymous nested types are flattened based on Go anonymous type visibility. -// -// When defining struct types. the `document` struct tag can be used to control how the value will be -// marshaled into the resulting protocol document. -// -// // Field is ignored -// Field int `document:"-"` -// -// // Field object of key "myName" -// Field int `document:"myName"` -// -// // Field object key of key "myName", and -// // Field is omitted if the field is a zero value for the type. -// Field int `document:"myName,omitempty"` -// -// // Field object key of "Field", and -// // Field is omitted if the field is a zero value for the type. -// Field int `document:",omitempty"` -// -// All struct fields, including anonymous fields, are marshaled unless the -// any of the following conditions are meet. -// -// - the field is not exported -// - document field tag is "-" -// - document field tag specifies "omitempty", and is a zero value. -// -// Pointer and interface values are encoded as the value pointed to or -// contained in the interface. A nil value encodes as a null -// value unless `omitempty` struct tag is provided. -// -// Channel, complex, and function values are not encoded and will be skipped -// when walking the value to be marshaled. -// -// time.Time is not supported and will cause the Marshaler to return an error. These values should be represented -// by your application as a string or numerical representation. -// -// Errors that occur when marshaling will stop the marshaler, and return the error. -// -// Marshal cannot represent cyclic data structures and will not handle them. -// Passing cyclic structures to Marshal will result in an infinite recursion. -type Marshaler interface { - MarshalSmithyDocument() ([]byte, error) -} - -// Unmarshaler is an interface for a type that unmarshals a document from its protocol-specific representation, and -// stores the result into the value pointed by v. If v is nil or not a pointer then InvalidUnmarshalError will be -// returned. -// -// Unmarshaler supports the same encodings produced by a document Marshaler. This includes support for the `document` -// struct field tag for controlling how struct fields are unmarshaled. -// -// Both generic interface{} and concrete types are valid unmarshal destination types. When unmarshaling a document -// into an empty interface the Unmarshaler will store one of these values: -// bool, for boolean values -// document.Number, for arbitrary-precision numbers (int64, float64, big.Int, big.Float) -// string, for string values -// []interface{}, for array values -// map[string]interface{}, for objects -// nil, for null values -// -// When unmarshaling, any error that occurs will halt the unmarshal and return the error. -type Unmarshaler interface { - UnmarshalSmithyDocument(v interface{}) error -} - -type noSerde interface { - noSmithyDocumentSerde() -} - -// NoSerde is a sentinel value to indicate that a given type should not be marshaled or unmarshaled -// into a protocol document. -type NoSerde struct{} - -func (n NoSerde) noSmithyDocumentSerde() {} - -var _ noSerde = (*NoSerde)(nil) - -// IsNoSerde returns whether the given type implements the no smithy document serde interface. -func IsNoSerde(x interface{}) bool { - _, ok := x.(noSerde) - return ok -} - -// Number is an arbitrary precision numerical value -type Number string - -// Int64 returns the number as a string. -func (n Number) String() string { - return string(n) -} - -// Int64 returns the number as an int64. -func (n Number) Int64() (int64, error) { - return n.intOfBitSize(64) -} - -func (n Number) intOfBitSize(bitSize int) (int64, error) { - return strconv.ParseInt(string(n), 10, bitSize) -} - -// Uint64 returns the number as a uint64. -func (n Number) Uint64() (uint64, error) { - return n.uintOfBitSize(64) -} - -func (n Number) uintOfBitSize(bitSize int) (uint64, error) { - return strconv.ParseUint(string(n), 10, bitSize) -} - -// Float32 returns the number parsed as a 32-bit float, returns a float64. -func (n Number) Float32() (float64, error) { - return n.floatOfBitSize(32) -} - -// Float64 returns the number as a float64. -func (n Number) Float64() (float64, error) { - return n.floatOfBitSize(64) -} - -// Float64 returns the number as a float64. -func (n Number) floatOfBitSize(bitSize int) (float64, error) { - return strconv.ParseFloat(string(n), bitSize) -} - -// BigFloat attempts to convert the number to a big.Float, returns an error if the operation fails. -func (n Number) BigFloat() (*big.Float, error) { - f, ok := (&big.Float{}).SetString(string(n)) - if !ok { - return nil, fmt.Errorf("failed to convert to big.Float") - } - return f, nil -} - -// BigInt attempts to convert the number to a big.Int, returns an error if the operation fails. -func (n Number) BigInt() (*big.Int, error) { - f, ok := (&big.Int{}).SetString(string(n), 10) - if !ok { - return nil, fmt.Errorf("failed to convert to big.Float") - } - return f, nil -} diff --git a/vendor/github.com/aws/smithy-go/document/errors.go b/vendor/github.com/aws/smithy-go/document/errors.go deleted file mode 100644 index 046a7a76..00000000 --- a/vendor/github.com/aws/smithy-go/document/errors.go +++ /dev/null @@ -1,75 +0,0 @@ -package document - -import ( - "fmt" - "reflect" -) - -// UnmarshalTypeError is an error type representing an error -// unmarshaling a Smithy document to a Go value type. This is different -// from UnmarshalError in that it does not wrap an underlying error type. -type UnmarshalTypeError struct { - Value string - Type reflect.Type -} - -// Error returns the string representation of the error. -// Satisfying the error interface. -func (e *UnmarshalTypeError) Error() string { - return fmt.Sprintf("unmarshal failed, cannot unmarshal %s into Go value type %s", - e.Value, e.Type.String()) -} - -// An InvalidUnmarshalError is an error type representing an invalid type -// encountered while unmarshaling a Smithy document to a Go value type. -type InvalidUnmarshalError struct { - Type reflect.Type -} - -// Error returns the string representation of the error. -// Satisfying the error interface. -func (e *InvalidUnmarshalError) Error() string { - var msg string - if e.Type == nil { - msg = "cannot unmarshal to nil value" - } else if e.Type.Kind() != reflect.Ptr { - msg = fmt.Sprintf("cannot unmarshal to non-pointer value, got %s", e.Type.String()) - } else { - msg = fmt.Sprintf("cannot unmarshal to nil value, %s", e.Type.String()) - } - - return fmt.Sprintf("unmarshal failed, %s", msg) -} - -// An UnmarshalError wraps an error that occurred while unmarshaling a -// Smithy document into a Go type. This is different from -// UnmarshalTypeError in that it wraps the underlying error that occurred. -type UnmarshalError struct { - Err error - Value string - Type reflect.Type -} - -// Unwrap returns the underlying unmarshaling error -func (e *UnmarshalError) Unwrap() error { - return e.Err -} - -// Error returns the string representation of the error. -// Satisfying the error interface. -func (e *UnmarshalError) Error() string { - return fmt.Sprintf("unmarshal failed, cannot unmarshal %q into %s, %v", - e.Value, e.Type.String(), e.Err) -} - -// An InvalidMarshalError is an error type representing an error -// occurring when marshaling a Go value type. -type InvalidMarshalError struct { - Message string -} - -// Error returns the string representation of the error. -// Satisfying the error interface. -func (e *InvalidMarshalError) Error() string { - return fmt.Sprintf("marshal failed, %s", e.Message) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/doc.go b/vendor/github.com/aws/smithy-go/encoding/doc.go deleted file mode 100644 index 792fdfa0..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package encoding provides utilities for encoding values for specific -// document encodings. - -package encoding diff --git a/vendor/github.com/aws/smithy-go/encoding/encoding.go b/vendor/github.com/aws/smithy-go/encoding/encoding.go deleted file mode 100644 index 2fdfb522..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/encoding.go +++ /dev/null @@ -1,40 +0,0 @@ -package encoding - -import ( - "fmt" - "math" - "strconv" -) - -// EncodeFloat encodes a float value as per the stdlib encoder for json and xml protocol -// This encodes a float value into dst while attempting to conform to ES6 ToString for Numbers -// -// Based on encoding/json floatEncoder from the Go Standard Library -// https://golang.org/src/encoding/json/encode.go -func EncodeFloat(dst []byte, v float64, bits int) []byte { - if math.IsInf(v, 0) || math.IsNaN(v) { - panic(fmt.Sprintf("invalid float value: %s", strconv.FormatFloat(v, 'g', -1, bits))) - } - - abs := math.Abs(v) - fmt := byte('f') - - if abs != 0 { - if bits == 64 && (abs < 1e-6 || abs >= 1e21) || bits == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) { - fmt = 'e' - } - } - - dst = strconv.AppendFloat(dst, v, fmt, -1, bits) - - if fmt == 'e' { - // clean up e-09 to e-9 - n := len(dst) - if n >= 4 && dst[n-4] == 'e' && dst[n-3] == '-' && dst[n-2] == '0' { - dst[n-2] = dst[n-1] - dst = dst[:n-1] - } - } - - return dst -} diff --git a/vendor/github.com/aws/smithy-go/encoding/httpbinding/encode.go b/vendor/github.com/aws/smithy-go/encoding/httpbinding/encode.go deleted file mode 100644 index 543e7cf0..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/httpbinding/encode.go +++ /dev/null @@ -1,123 +0,0 @@ -package httpbinding - -import ( - "fmt" - "net/http" - "net/url" - "strconv" - "strings" -) - -const ( - contentLengthHeader = "Content-Length" - floatNaN = "NaN" - floatInfinity = "Infinity" - floatNegInfinity = "-Infinity" -) - -// An Encoder provides encoding of REST URI path, query, and header components -// of an HTTP request. Can also encode a stream as the payload. -// -// Does not support SetFields. -type Encoder struct { - path, rawPath, pathBuffer []byte - - query url.Values - header http.Header -} - -// NewEncoder creates a new encoder from the passed in request. It assumes that -// raw path contains no valuable information at this point, so it passes in path -// as path and raw path for subsequent trans -func NewEncoder(path, query string, headers http.Header) (*Encoder, error) { - return NewEncoderWithRawPath(path, path, query, headers) -} - -// NewHTTPBindingEncoder creates a new encoder from the passed in request. All query and -// header values will be added on top of the request's existing values. Overwriting -// duplicate values. -func NewEncoderWithRawPath(path, rawPath, query string, headers http.Header) (*Encoder, error) { - parseQuery, err := url.ParseQuery(query) - if err != nil { - return nil, fmt.Errorf("failed to parse query string: %w", err) - } - - e := &Encoder{ - path: []byte(path), - rawPath: []byte(rawPath), - query: parseQuery, - header: headers.Clone(), - } - - return e, nil -} - -// Encode returns a REST protocol encoder for encoding HTTP bindings. -// -// Due net/http requiring `Content-Length` to be specified on the http.Request#ContentLength directly. Encode -// will look for whether the header is present, and if so will remove it and set the respective value on http.Request. -// -// Returns any error occurring during encoding. -func (e *Encoder) Encode(req *http.Request) (*http.Request, error) { - req.URL.Path, req.URL.RawPath = string(e.path), string(e.rawPath) - req.URL.RawQuery = e.query.Encode() - - // net/http ignores Content-Length header and requires it to be set on http.Request - if v := e.header.Get(contentLengthHeader); len(v) > 0 { - iv, err := strconv.ParseInt(v, 10, 64) - if err != nil { - return nil, err - } - req.ContentLength = iv - e.header.Del(contentLengthHeader) - } - - req.Header = e.header - - return req, nil -} - -// AddHeader returns a HeaderValue for appending to the given header name -func (e *Encoder) AddHeader(key string) HeaderValue { - return newHeaderValue(e.header, key, true) -} - -// SetHeader returns a HeaderValue for setting the given header name -func (e *Encoder) SetHeader(key string) HeaderValue { - return newHeaderValue(e.header, key, false) -} - -// Headers returns a Header used for encoding headers with the given prefix -func (e *Encoder) Headers(prefix string) Headers { - return Headers{ - header: e.header, - prefix: strings.TrimSpace(prefix), - } -} - -// HasHeader returns if a header with the key specified exists with one or -// more value. -func (e Encoder) HasHeader(key string) bool { - return len(e.header[key]) != 0 -} - -// SetURI returns a URIValue used for setting the given path key -func (e *Encoder) SetURI(key string) URIValue { - return newURIValue(&e.path, &e.rawPath, &e.pathBuffer, key) -} - -// SetQuery returns a QueryValue used for setting the given query key -func (e *Encoder) SetQuery(key string) QueryValue { - return NewQueryValue(e.query, key, false) -} - -// AddQuery returns a QueryValue used for appending the given query key -func (e *Encoder) AddQuery(key string) QueryValue { - return NewQueryValue(e.query, key, true) -} - -// HasQuery returns if a query with the key specified exists with one or -// more values. -func (e *Encoder) HasQuery(key string) bool { - return len(e.query.Get(key)) != 0 -} diff --git a/vendor/github.com/aws/smithy-go/encoding/httpbinding/header.go b/vendor/github.com/aws/smithy-go/encoding/httpbinding/header.go deleted file mode 100644 index f9256e17..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/httpbinding/header.go +++ /dev/null @@ -1,122 +0,0 @@ -package httpbinding - -import ( - "encoding/base64" - "math" - "math/big" - "net/http" - "strconv" - "strings" -) - -// Headers is used to encode header keys using a provided prefix -type Headers struct { - header http.Header - prefix string -} - -// AddHeader returns a HeaderValue used to append values to prefix+key -func (h Headers) AddHeader(key string) HeaderValue { - return h.newHeaderValue(key, true) -} - -// SetHeader returns a HeaderValue used to set the value of prefix+key -func (h Headers) SetHeader(key string) HeaderValue { - return h.newHeaderValue(key, false) -} - -func (h Headers) newHeaderValue(key string, append bool) HeaderValue { - return newHeaderValue(h.header, h.prefix+strings.TrimSpace(key), append) -} - -// HeaderValue is used to encode values to an HTTP header -type HeaderValue struct { - header http.Header - key string - append bool -} - -func newHeaderValue(header http.Header, key string, append bool) HeaderValue { - return HeaderValue{header: header, key: strings.TrimSpace(key), append: append} -} - -func (h HeaderValue) modifyHeader(value string) { - if h.append { - h.header[h.key] = append(h.header[h.key], value) - } else { - h.header[h.key] = append(h.header[h.key][:0], value) - } -} - -// String encodes the value v as the header string value -func (h HeaderValue) String(v string) { - h.modifyHeader(v) -} - -// Byte encodes the value v as a query string value -func (h HeaderValue) Byte(v int8) { - h.Long(int64(v)) -} - -// Short encodes the value v as a query string value -func (h HeaderValue) Short(v int16) { - h.Long(int64(v)) -} - -// Integer encodes the value v as the header string value -func (h HeaderValue) Integer(v int32) { - h.Long(int64(v)) -} - -// Long encodes the value v as the header string value -func (h HeaderValue) Long(v int64) { - h.modifyHeader(strconv.FormatInt(v, 10)) -} - -// Boolean encodes the value v as a query string value -func (h HeaderValue) Boolean(v bool) { - h.modifyHeader(strconv.FormatBool(v)) -} - -// Float encodes the value v as a query string value -func (h HeaderValue) Float(v float32) { - h.float(float64(v), 32) -} - -// Double encodes the value v as a query string value -func (h HeaderValue) Double(v float64) { - h.float(v, 64) -} - -func (h HeaderValue) float(v float64, bitSize int) { - switch { - case math.IsNaN(v): - h.String(floatNaN) - case math.IsInf(v, 1): - h.String(floatInfinity) - case math.IsInf(v, -1): - h.String(floatNegInfinity) - default: - h.modifyHeader(strconv.FormatFloat(v, 'f', -1, bitSize)) - } -} - -// BigInteger encodes the value v as a query string value -func (h HeaderValue) BigInteger(v *big.Int) { - h.modifyHeader(v.String()) -} - -// BigDecimal encodes the value v as a query string value -func (h HeaderValue) BigDecimal(v *big.Float) { - if i, accuracy := v.Int64(); accuracy == big.Exact { - h.Long(i) - return - } - h.modifyHeader(v.Text('e', -1)) -} - -// Blob encodes the value v as a base64 header string value -func (h HeaderValue) Blob(v []byte) { - encodeToString := base64.StdEncoding.EncodeToString(v) - h.modifyHeader(encodeToString) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/httpbinding/path_replace.go b/vendor/github.com/aws/smithy-go/encoding/httpbinding/path_replace.go deleted file mode 100644 index e78926c9..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/httpbinding/path_replace.go +++ /dev/null @@ -1,108 +0,0 @@ -package httpbinding - -import ( - "bytes" - "fmt" -) - -const ( - uriTokenStart = '{' - uriTokenStop = '}' - uriTokenSkip = '+' -) - -func bufCap(b []byte, n int) []byte { - if cap(b) < n { - return make([]byte, 0, n) - } - - return b[0:0] -} - -// replacePathElement replaces a single element in the path []byte. -// Escape is used to control whether the value will be escaped using Amazon path escape style. -func replacePathElement(path, fieldBuf []byte, key, val string, escape bool) ([]byte, []byte, error) { - fieldBuf = bufCap(fieldBuf, len(key)+3) // { [+] } - fieldBuf = append(fieldBuf, uriTokenStart) - fieldBuf = append(fieldBuf, key...) - - start := bytes.Index(path, fieldBuf) - end := start + len(fieldBuf) - if start < 0 || len(path[end:]) == 0 { - // TODO what to do about error? - return path, fieldBuf, fmt.Errorf("invalid path index, start=%d,end=%d. %s", start, end, path) - } - - encodeSep := true - if path[end] == uriTokenSkip { - // '+' token means do not escape slashes - encodeSep = false - end++ - } - - if escape { - val = EscapePath(val, encodeSep) - } - - if path[end] != uriTokenStop { - return path, fieldBuf, fmt.Errorf("invalid path element, does not contain token stop, %s", path) - } - end++ - - fieldBuf = bufCap(fieldBuf, len(val)) - fieldBuf = append(fieldBuf, val...) - - keyLen := end - start - valLen := len(fieldBuf) - - if keyLen == valLen { - copy(path[start:], fieldBuf) - return path, fieldBuf, nil - } - - newLen := len(path) + (valLen - keyLen) - if len(path) < newLen { - path = path[:cap(path)] - } - if cap(path) < newLen { - newURI := make([]byte, newLen) - copy(newURI, path) - path = newURI - } - - // shift - copy(path[start+valLen:], path[end:]) - path = path[:newLen] - copy(path[start:], fieldBuf) - - return path, fieldBuf, nil -} - -// EscapePath escapes part of a URL path in Amazon style. -func EscapePath(path string, encodeSep bool) string { - var buf bytes.Buffer - for i := 0; i < len(path); i++ { - c := path[i] - if noEscape[c] || (c == '/' && !encodeSep) { - buf.WriteByte(c) - } else { - fmt.Fprintf(&buf, "%%%02X", c) - } - } - return buf.String() -} - -var noEscape [256]bool - -func init() { - for i := 0; i < len(noEscape); i++ { - // AWS expects every character except these to be escaped - noEscape[i] = (i >= 'A' && i <= 'Z') || - (i >= 'a' && i <= 'z') || - (i >= '0' && i <= '9') || - i == '-' || - i == '.' || - i == '_' || - i == '~' - } -} diff --git a/vendor/github.com/aws/smithy-go/encoding/httpbinding/query.go b/vendor/github.com/aws/smithy-go/encoding/httpbinding/query.go deleted file mode 100644 index c2e7d0a2..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/httpbinding/query.go +++ /dev/null @@ -1,107 +0,0 @@ -package httpbinding - -import ( - "encoding/base64" - "math" - "math/big" - "net/url" - "strconv" -) - -// QueryValue is used to encode query key values -type QueryValue struct { - query url.Values - key string - append bool -} - -// NewQueryValue creates a new QueryValue which enables encoding -// a query value into the given url.Values. -func NewQueryValue(query url.Values, key string, append bool) QueryValue { - return QueryValue{ - query: query, - key: key, - append: append, - } -} - -func (qv QueryValue) updateKey(value string) { - if qv.append { - qv.query.Add(qv.key, value) - } else { - qv.query.Set(qv.key, value) - } -} - -// Blob encodes v as a base64 query string value -func (qv QueryValue) Blob(v []byte) { - encodeToString := base64.StdEncoding.EncodeToString(v) - qv.updateKey(encodeToString) -} - -// Boolean encodes v as a query string value -func (qv QueryValue) Boolean(v bool) { - qv.updateKey(strconv.FormatBool(v)) -} - -// String encodes v as a query string value -func (qv QueryValue) String(v string) { - qv.updateKey(v) -} - -// Byte encodes v as a query string value -func (qv QueryValue) Byte(v int8) { - qv.Long(int64(v)) -} - -// Short encodes v as a query string value -func (qv QueryValue) Short(v int16) { - qv.Long(int64(v)) -} - -// Integer encodes v as a query string value -func (qv QueryValue) Integer(v int32) { - qv.Long(int64(v)) -} - -// Long encodes v as a query string value -func (qv QueryValue) Long(v int64) { - qv.updateKey(strconv.FormatInt(v, 10)) -} - -// Float encodes v as a query string value -func (qv QueryValue) Float(v float32) { - qv.float(float64(v), 32) -} - -// Double encodes v as a query string value -func (qv QueryValue) Double(v float64) { - qv.float(v, 64) -} - -func (qv QueryValue) float(v float64, bitSize int) { - switch { - case math.IsNaN(v): - qv.String(floatNaN) - case math.IsInf(v, 1): - qv.String(floatInfinity) - case math.IsInf(v, -1): - qv.String(floatNegInfinity) - default: - qv.updateKey(strconv.FormatFloat(v, 'f', -1, bitSize)) - } -} - -// BigInteger encodes v as a query string value -func (qv QueryValue) BigInteger(v *big.Int) { - qv.updateKey(v.String()) -} - -// BigDecimal encodes v as a query string value -func (qv QueryValue) BigDecimal(v *big.Float) { - if i, accuracy := v.Int64(); accuracy == big.Exact { - qv.Long(i) - return - } - qv.updateKey(v.Text('e', -1)) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/httpbinding/uri.go b/vendor/github.com/aws/smithy-go/encoding/httpbinding/uri.go deleted file mode 100644 index f04e1198..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/httpbinding/uri.go +++ /dev/null @@ -1,111 +0,0 @@ -package httpbinding - -import ( - "math" - "math/big" - "strconv" - "strings" -) - -// URIValue is used to encode named URI parameters -type URIValue struct { - path, rawPath, buffer *[]byte - - key string -} - -func newURIValue(path *[]byte, rawPath *[]byte, buffer *[]byte, key string) URIValue { - return URIValue{path: path, rawPath: rawPath, buffer: buffer, key: key} -} - -func (u URIValue) modifyURI(value string) (err error) { - *u.path, *u.buffer, err = replacePathElement(*u.path, *u.buffer, u.key, value, false) - if err != nil { - return err - } - *u.rawPath, *u.buffer, err = replacePathElement(*u.rawPath, *u.buffer, u.key, value, true) - return err -} - -// Boolean encodes v as a URI string value -func (u URIValue) Boolean(v bool) error { - return u.modifyURI(strconv.FormatBool(v)) -} - -// String encodes v as a URI string value -func (u URIValue) String(v string) error { - return u.modifyURI(v) -} - -// Byte encodes v as a URI string value -func (u URIValue) Byte(v int8) error { - return u.Long(int64(v)) -} - -// Short encodes v as a URI string value -func (u URIValue) Short(v int16) error { - return u.Long(int64(v)) -} - -// Integer encodes v as a URI string value -func (u URIValue) Integer(v int32) error { - return u.Long(int64(v)) -} - -// Long encodes v as a URI string value -func (u URIValue) Long(v int64) error { - return u.modifyURI(strconv.FormatInt(v, 10)) -} - -// Float encodes v as a query string value -func (u URIValue) Float(v float32) error { - return u.float(float64(v), 32) -} - -// Double encodes v as a query string value -func (u URIValue) Double(v float64) error { - return u.float(v, 64) -} - -func (u URIValue) float(v float64, bitSize int) error { - switch { - case math.IsNaN(v): - return u.String(floatNaN) - case math.IsInf(v, 1): - return u.String(floatInfinity) - case math.IsInf(v, -1): - return u.String(floatNegInfinity) - default: - return u.modifyURI(strconv.FormatFloat(v, 'f', -1, bitSize)) - } -} - -// BigInteger encodes v as a query string value -func (u URIValue) BigInteger(v *big.Int) error { - return u.modifyURI(v.String()) -} - -// BigDecimal encodes v as a query string value -func (u URIValue) BigDecimal(v *big.Float) error { - if i, accuracy := v.Int64(); accuracy == big.Exact { - return u.Long(i) - } - return u.modifyURI(v.Text('e', -1)) -} - -// SplitURI parses a Smithy HTTP binding trait URI -func SplitURI(uri string) (path, query string) { - queryStart := strings.IndexRune(uri, '?') - if queryStart == -1 { - path = uri - return path, query - } - - path = uri[:queryStart] - if queryStart+1 >= len(uri) { - return path, query - } - query = uri[queryStart+1:] - - return path, query -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/array.go b/vendor/github.com/aws/smithy-go/encoding/json/array.go deleted file mode 100644 index 7a232f66..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/array.go +++ /dev/null @@ -1,35 +0,0 @@ -package json - -import ( - "bytes" -) - -// Array represents the encoding of a JSON Array -type Array struct { - w *bytes.Buffer - writeComma bool - scratch *[]byte -} - -func newArray(w *bytes.Buffer, scratch *[]byte) *Array { - w.WriteRune(leftBracket) - return &Array{w: w, scratch: scratch} -} - -// Value adds a new element to the JSON Array. -// Returns a Value type that is used to encode -// the array element. -func (a *Array) Value() Value { - if a.writeComma { - a.w.WriteRune(comma) - } else { - a.writeComma = true - } - - return newValue(a.w, a.scratch) -} - -// Close encodes the end of the JSON Array -func (a *Array) Close() { - a.w.WriteRune(rightBracket) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/constants.go b/vendor/github.com/aws/smithy-go/encoding/json/constants.go deleted file mode 100644 index 91044092..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/constants.go +++ /dev/null @@ -1,15 +0,0 @@ -package json - -const ( - leftBrace = '{' - rightBrace = '}' - - leftBracket = '[' - rightBracket = ']' - - comma = ',' - quote = '"' - colon = ':' - - null = "null" -) diff --git a/vendor/github.com/aws/smithy-go/encoding/json/decoder_util.go b/vendor/github.com/aws/smithy-go/encoding/json/decoder_util.go deleted file mode 100644 index 7050c85b..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/decoder_util.go +++ /dev/null @@ -1,139 +0,0 @@ -package json - -import ( - "bytes" - "encoding/json" - "fmt" - "io" -) - -// DiscardUnknownField discards unknown fields from a decoder body. -// This function is useful while deserializing a JSON body with additional -// unknown information that should be discarded. -func DiscardUnknownField(decoder *json.Decoder) error { - // This deliberately does not share logic with CollectUnknownField, even - // though it could, because if we were to delegate to that then we'd incur - // extra allocations and general memory usage. - v, err := decoder.Token() - if err == io.EOF { - return nil - } - if err != nil { - return err - } - - if _, ok := v.(json.Delim); ok { - for decoder.More() { - err = DiscardUnknownField(decoder) - } - endToken, err := decoder.Token() - if err != nil { - return err - } - if _, ok := endToken.(json.Delim); !ok { - return fmt.Errorf("invalid JSON : expected json delimiter, found %T %v", - endToken, endToken) - } - } - - return nil -} - -// CollectUnknownField grabs the contents of unknown fields from the decoder body -// and returns them as a byte slice. This is useful for skipping unknown fields without -// completely discarding them. -func CollectUnknownField(decoder *json.Decoder) ([]byte, error) { - result, err := collectUnknownField(decoder) - if err != nil { - return nil, err - } - - buff := bytes.NewBuffer(nil) - encoder := json.NewEncoder(buff) - - if err := encoder.Encode(result); err != nil { - return nil, err - } - - return buff.Bytes(), nil -} - -func collectUnknownField(decoder *json.Decoder) (interface{}, error) { - // Grab the initial value. This could either be a concrete value like a string or a a - // delimiter. - token, err := decoder.Token() - if err == io.EOF { - return nil, nil - } - if err != nil { - return nil, err - } - - // If it's an array or object, we'll need to recurse. - delim, ok := token.(json.Delim) - if ok { - var result interface{} - if delim == '{' { - result, err = collectUnknownObject(decoder) - if err != nil { - return nil, err - } - } else { - result, err = collectUnknownArray(decoder) - if err != nil { - return nil, err - } - } - - // Discard the closing token. decoder.Token handles checking for matching delimiters - if _, err := decoder.Token(); err != nil { - return nil, err - } - return result, nil - } - - return token, nil -} - -func collectUnknownArray(decoder *json.Decoder) ([]interface{}, error) { - // We need to create an empty array here instead of a nil array, since by getting - // into this function at all we necessarily have seen a non-nil list. - array := []interface{}{} - - for decoder.More() { - value, err := collectUnknownField(decoder) - if err != nil { - return nil, err - } - array = append(array, value) - } - - return array, nil -} - -func collectUnknownObject(decoder *json.Decoder) (map[string]interface{}, error) { - object := make(map[string]interface{}) - - for decoder.More() { - key, err := collectUnknownField(decoder) - if err != nil { - return nil, err - } - - // Keys have to be strings, which is particularly important as the encoder - // won't except a map with interface{} keys - stringKey, ok := key.(string) - if !ok { - return nil, fmt.Errorf("expected string key, found %T", key) - } - - value, err := collectUnknownField(decoder) - if err != nil { - return nil, err - } - - object[stringKey] = value - } - - return object, nil -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/encoder.go b/vendor/github.com/aws/smithy-go/encoding/json/encoder.go deleted file mode 100644 index 8772953f..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/encoder.go +++ /dev/null @@ -1,30 +0,0 @@ -package json - -import ( - "bytes" -) - -// Encoder is JSON encoder that supports construction of JSON values -// using methods. -type Encoder struct { - w *bytes.Buffer - Value -} - -// NewEncoder returns a new JSON encoder -func NewEncoder() *Encoder { - writer := bytes.NewBuffer(nil) - scratch := make([]byte, 64) - - return &Encoder{w: writer, Value: newValue(writer, &scratch)} -} - -// String returns the String output of the JSON encoder -func (e Encoder) String() string { - return e.w.String() -} - -// Bytes returns the []byte slice of the JSON encoder -func (e Encoder) Bytes() []byte { - return e.w.Bytes() -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/escape.go b/vendor/github.com/aws/smithy-go/encoding/json/escape.go deleted file mode 100644 index d984d0cd..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/escape.go +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright 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. - -// Copied and modified from Go 1.8 stdlib's encoding/json/#safeSet - -package json - -import ( - "bytes" - "unicode/utf8" -) - -// safeSet holds the value true if the ASCII character with the given array -// position can be represented inside a JSON string without any further -// escaping. -// -// All values are true except for the ASCII control characters (0-31), the -// double quote ("), and the backslash character ("\"). -var safeSet = [utf8.RuneSelf]bool{ - ' ': true, - '!': true, - '"': false, - '#': true, - '$': true, - '%': true, - '&': true, - '\'': true, - '(': true, - ')': true, - '*': true, - '+': true, - ',': true, - '-': true, - '.': true, - '/': true, - '0': true, - '1': true, - '2': true, - '3': true, - '4': true, - '5': true, - '6': true, - '7': true, - '8': true, - '9': true, - ':': true, - ';': true, - '<': true, - '=': true, - '>': true, - '?': true, - '@': true, - 'A': true, - 'B': true, - 'C': true, - 'D': true, - 'E': true, - 'F': true, - 'G': true, - 'H': true, - 'I': true, - 'J': true, - 'K': true, - 'L': true, - 'M': true, - 'N': true, - 'O': true, - 'P': true, - 'Q': true, - 'R': true, - 'S': true, - 'T': true, - 'U': true, - 'V': true, - 'W': true, - 'X': true, - 'Y': true, - 'Z': true, - '[': true, - '\\': false, - ']': true, - '^': true, - '_': true, - '`': true, - 'a': true, - 'b': true, - 'c': true, - 'd': true, - 'e': true, - 'f': true, - 'g': true, - 'h': true, - 'i': true, - 'j': true, - 'k': true, - 'l': true, - 'm': true, - 'n': true, - 'o': true, - 'p': true, - 'q': true, - 'r': true, - 's': true, - 't': true, - 'u': true, - 'v': true, - 'w': true, - 'x': true, - 'y': true, - 'z': true, - '{': true, - '|': true, - '}': true, - '~': true, - '\u007f': true, -} - -// copied from Go 1.8 stdlib's encoding/json/#hex -var hex = "0123456789abcdef" - -// escapeStringBytes escapes and writes the passed in string bytes to the dst -// buffer -// -// Copied and modifed from Go 1.8 stdlib's encodeing/json/#encodeState.stringBytes -func escapeStringBytes(e *bytes.Buffer, s []byte) { - e.WriteByte('"') - start := 0 - for i := 0; i < len(s); { - if b := s[i]; b < utf8.RuneSelf { - if safeSet[b] { - i++ - continue - } - if start < i { - e.Write(s[start:i]) - } - switch b { - case '\\', '"': - e.WriteByte('\\') - e.WriteByte(b) - case '\n': - e.WriteByte('\\') - e.WriteByte('n') - case '\r': - e.WriteByte('\\') - e.WriteByte('r') - case '\t': - e.WriteByte('\\') - e.WriteByte('t') - default: - // This encodes bytes < 0x20 except for \t, \n and \r. - // If escapeHTML is set, it also escapes <, >, and & - // because they can lead to security holes when - // user-controlled strings are rendered into JSON - // and served to some browsers. - e.WriteString(`\u00`) - e.WriteByte(hex[b>>4]) - e.WriteByte(hex[b&0xF]) - } - i++ - start = i - continue - } - c, size := utf8.DecodeRune(s[i:]) - if c == utf8.RuneError && size == 1 { - if start < i { - e.Write(s[start:i]) - } - e.WriteString(`\ufffd`) - i += size - start = i - continue - } - // U+2028 is LINE SEPARATOR. - // U+2029 is PARAGRAPH SEPARATOR. - // They are both technically valid characters in JSON strings, - // but don't work in JSONP, which has to be evaluated as JavaScript, - // and can lead to security holes there. It is valid JSON to - // escape them, so we do so unconditionally. - // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion. - if c == '\u2028' || c == '\u2029' { - if start < i { - e.Write(s[start:i]) - } - e.WriteString(`\u202`) - e.WriteByte(hex[c&0xF]) - i += size - start = i - continue - } - i += size - } - if start < len(s) { - e.Write(s[start:]) - } - e.WriteByte('"') -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/object.go b/vendor/github.com/aws/smithy-go/encoding/json/object.go deleted file mode 100644 index 722346d0..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/object.go +++ /dev/null @@ -1,40 +0,0 @@ -package json - -import ( - "bytes" -) - -// Object represents the encoding of a JSON Object type -type Object struct { - w *bytes.Buffer - writeComma bool - scratch *[]byte -} - -func newObject(w *bytes.Buffer, scratch *[]byte) *Object { - w.WriteRune(leftBrace) - return &Object{w: w, scratch: scratch} -} - -func (o *Object) writeKey(key string) { - escapeStringBytes(o.w, []byte(key)) - o.w.WriteRune(colon) -} - -// Key adds the given named key to the JSON object. -// Returns a Value encoder that should be used to encode -// a JSON value type. -func (o *Object) Key(name string) Value { - if o.writeComma { - o.w.WriteRune(comma) - } else { - o.writeComma = true - } - o.writeKey(name) - return newValue(o.w, o.scratch) -} - -// Close encodes the end of the JSON Object -func (o *Object) Close() { - o.w.WriteRune(rightBrace) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/json/value.go b/vendor/github.com/aws/smithy-go/encoding/json/value.go deleted file mode 100644 index b41ff1e1..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/json/value.go +++ /dev/null @@ -1,149 +0,0 @@ -package json - -import ( - "bytes" - "encoding/base64" - "math/big" - "strconv" - - "github.com/aws/smithy-go/encoding" -) - -// Value represents a JSON Value type -// JSON Value types: Object, Array, String, Number, Boolean, and Null -type Value struct { - w *bytes.Buffer - scratch *[]byte -} - -// newValue returns a new Value encoder -func newValue(w *bytes.Buffer, scratch *[]byte) Value { - return Value{w: w, scratch: scratch} -} - -// String encodes v as a JSON string -func (jv Value) String(v string) { - escapeStringBytes(jv.w, []byte(v)) -} - -// Byte encodes v as a JSON number -func (jv Value) Byte(v int8) { - jv.Long(int64(v)) -} - -// Short encodes v as a JSON number -func (jv Value) Short(v int16) { - jv.Long(int64(v)) -} - -// Integer encodes v as a JSON number -func (jv Value) Integer(v int32) { - jv.Long(int64(v)) -} - -// Long encodes v as a JSON number -func (jv Value) Long(v int64) { - *jv.scratch = strconv.AppendInt((*jv.scratch)[:0], v, 10) - jv.w.Write(*jv.scratch) -} - -// ULong encodes v as a JSON number -func (jv Value) ULong(v uint64) { - *jv.scratch = strconv.AppendUint((*jv.scratch)[:0], v, 10) - jv.w.Write(*jv.scratch) -} - -// Float encodes v as a JSON number -func (jv Value) Float(v float32) { - jv.float(float64(v), 32) -} - -// Double encodes v as a JSON number -func (jv Value) Double(v float64) { - jv.float(v, 64) -} - -func (jv Value) float(v float64, bits int) { - *jv.scratch = encoding.EncodeFloat((*jv.scratch)[:0], v, bits) - jv.w.Write(*jv.scratch) -} - -// Boolean encodes v as a JSON boolean -func (jv Value) Boolean(v bool) { - *jv.scratch = strconv.AppendBool((*jv.scratch)[:0], v) - jv.w.Write(*jv.scratch) -} - -// Base64EncodeBytes writes v as a base64 value in JSON string -func (jv Value) Base64EncodeBytes(v []byte) { - encodeByteSlice(jv.w, (*jv.scratch)[:0], v) -} - -// Write writes v directly to the JSON document -func (jv Value) Write(v []byte) { - jv.w.Write(v) -} - -// Array returns a new Array encoder -func (jv Value) Array() *Array { - return newArray(jv.w, jv.scratch) -} - -// Object returns a new Object encoder -func (jv Value) Object() *Object { - return newObject(jv.w, jv.scratch) -} - -// Null encodes a null JSON value -func (jv Value) Null() { - jv.w.WriteString(null) -} - -// BigInteger encodes v as JSON value -func (jv Value) BigInteger(v *big.Int) { - jv.w.Write([]byte(v.Text(10))) -} - -// BigDecimal encodes v as JSON value -func (jv Value) BigDecimal(v *big.Float) { - if i, accuracy := v.Int64(); accuracy == big.Exact { - jv.Long(i) - return - } - // TODO: Should this try to match ES6 ToString similar to stdlib JSON? - jv.w.Write([]byte(v.Text('e', -1))) -} - -// Based on encoding/json encodeByteSlice from the Go Standard Library -// https://golang.org/src/encoding/json/encode.go -func encodeByteSlice(w *bytes.Buffer, scratch []byte, v []byte) { - if v == nil { - w.WriteString(null) - return - } - - w.WriteRune(quote) - - encodedLen := base64.StdEncoding.EncodedLen(len(v)) - if encodedLen <= len(scratch) { - // If the encoded bytes fit in e.scratch, avoid an extra - // allocation and use the cheaper Encoding.Encode. - dst := scratch[:encodedLen] - base64.StdEncoding.Encode(dst, v) - w.Write(dst) - } else if encodedLen <= 1024 { - // The encoded bytes are short enough to allocate for, and - // Encoding.Encode is still cheaper. - dst := make([]byte, encodedLen) - base64.StdEncoding.Encode(dst, v) - w.Write(dst) - } else { - // The encoded bytes are too long to cheaply allocate, and - // Encoding.Encode is no longer noticeably cheaper. - enc := base64.NewEncoder(base64.StdEncoding, w) - enc.Write(v) - enc.Close() - } - - w.WriteRune(quote) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/array.go b/vendor/github.com/aws/smithy-go/encoding/xml/array.go deleted file mode 100644 index 508f3c99..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/array.go +++ /dev/null @@ -1,49 +0,0 @@ -package xml - -// arrayMemberWrapper is the default member wrapper tag name for XML Array type -var arrayMemberWrapper = StartElement{ - Name: Name{Local: "member"}, -} - -// Array represents the encoding of a XML array type -type Array struct { - w writer - scratch *[]byte - - // member start element is the array member wrapper start element - memberStartElement StartElement - - // isFlattened indicates if the array is a flattened array. - isFlattened bool -} - -// newArray returns an array encoder. -// It also takes in the member start element, array start element. -// It takes in a isFlattened bool, indicating that an array is flattened array. -// -// A wrapped array ["value1", "value2"] is represented as -// `value1value2`. - -// A flattened array `someList: ["value1", "value2"]` is represented as -// `value1value2`. -func newArray(w writer, scratch *[]byte, memberStartElement StartElement, arrayStartElement StartElement, isFlattened bool) *Array { - var memberWrapper = memberStartElement - if isFlattened { - memberWrapper = arrayStartElement - } - - return &Array{ - w: w, - scratch: scratch, - memberStartElement: memberWrapper, - isFlattened: isFlattened, - } -} - -// Member adds a new member to the XML array. -// It returns a Value encoder. -func (a *Array) Member() Value { - v := newValue(a.w, a.scratch, a.memberStartElement) - v.isFlattened = a.isFlattened - return v -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/constants.go b/vendor/github.com/aws/smithy-go/encoding/xml/constants.go deleted file mode 100644 index ccee90a6..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/constants.go +++ /dev/null @@ -1,10 +0,0 @@ -package xml - -const ( - leftAngleBracket = '<' - rightAngleBracket = '>' - forwardSlash = '/' - colon = ':' - equals = '=' - quote = '"' -) diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/doc.go b/vendor/github.com/aws/smithy-go/encoding/xml/doc.go deleted file mode 100644 index f9200093..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/doc.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Package xml holds the XMl encoder utility. This utility is written in accordance to our design to delegate to -shape serializer function in which a xml.Value will be passed around. - -Resources followed: https://smithy.io/2.0/spec/protocol-traits.html#xml-bindings - -Member Element - -Member element should be used to encode xml shapes into xml elements except for flattened xml shapes. Member element -write their own element start tag. These elements should always be closed. - -Flattened Element - -Flattened element should be used to encode shapes marked with flattened trait into xml elements. Flattened element -do not write a start tag, and thus should not be closed. - -Simple types encoding - -All simple type methods on value such as String(), Long() etc; auto close the associated member element. - -Array - -Array returns the collection encoder. It has two modes, wrapped and flattened encoding. - -Wrapped arrays have two methods Array() and ArrayWithCustomName() which facilitate array member wrapping. -By default, a wrapped array members are wrapped with `member` named start element. - - appletree - -Flattened arrays rely on Value being marked as flattened. -If a shape is marked as flattened, Array() will use the shape element name as wrapper for array elements. - - appletree - -Map - -Map is the map encoder. It has two modes, wrapped and flattened encoding. - -Wrapped map has Array() method, which facilitate map member wrapping. -By default, a wrapped map members are wrapped with `entry` named start element. - - appletreesnowice - -Flattened map rely on Value being marked as flattened. -If a shape is marked as flattened, Map() will use the shape element name as wrapper for map entry elements. - - appletreesnowice -*/ -package xml diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/element.go b/vendor/github.com/aws/smithy-go/encoding/xml/element.go deleted file mode 100644 index ae84e799..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/element.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2009 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. - -// Copied and modified from Go 1.14 stdlib's encoding/xml - -package xml - -// A Name represents an XML name (Local) annotated -// with a name space identifier (Space). -// In tokens returned by Decoder.Token, the Space identifier -// is given as a canonical URL, not the short prefix used -// in the document being parsed. -type Name struct { - Space, Local string -} - -// An Attr represents an attribute in an XML element (Name=Value). -type Attr struct { - Name Name - Value string -} - -/* -NewAttribute returns a pointer to an attribute. -It takes in a local name aka attribute name, and value -representing the attribute value. -*/ -func NewAttribute(local, value string) Attr { - return Attr{ - Name: Name{ - Local: local, - }, - Value: value, - } -} - -/* -NewNamespaceAttribute returns a pointer to an attribute. -It takes in a local name aka attribute name, and value -representing the attribute value. - -NewNamespaceAttribute appends `xmlns:` in front of namespace -prefix. - -For creating a name space attribute representing -`xmlns:prefix="http://example.com`, the breakdown would be: -local = "prefix" -value = "http://example.com" -*/ -func NewNamespaceAttribute(local, value string) Attr { - attr := NewAttribute(local, value) - - // default name space identifier - attr.Name.Space = "xmlns" - return attr -} - -// A StartElement represents an XML start element. -type StartElement struct { - Name Name - Attr []Attr -} - -// Copy creates a new copy of StartElement. -func (e StartElement) Copy() StartElement { - attrs := make([]Attr, len(e.Attr)) - copy(attrs, e.Attr) - e.Attr = attrs - return e -} - -// End returns the corresponding XML end element. -func (e StartElement) End() EndElement { - return EndElement{e.Name} -} - -// returns true if start element local name is empty -func (e StartElement) isZero() bool { - return len(e.Name.Local) == 0 -} - -// An EndElement represents an XML end element. -type EndElement struct { - Name Name -} - -// returns true if end element local name is empty -func (e EndElement) isZero() bool { - return len(e.Name.Local) == 0 -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/encoder.go b/vendor/github.com/aws/smithy-go/encoding/xml/encoder.go deleted file mode 100644 index 16fb3ddd..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/encoder.go +++ /dev/null @@ -1,51 +0,0 @@ -package xml - -// writer interface used by the xml encoder to write an encoded xml -// document in a writer. -type writer interface { - - // Write takes in a byte slice and returns number of bytes written and error - Write(p []byte) (n int, err error) - - // WriteRune takes in a rune and returns number of bytes written and error - WriteRune(r rune) (n int, err error) - - // WriteString takes in a string and returns number of bytes written and error - WriteString(s string) (n int, err error) - - // String method returns a string - String() string - - // Bytes return a byte slice. - Bytes() []byte -} - -// Encoder is an XML encoder that supports construction of XML values -// using methods. The encoder takes in a writer and maintains a scratch buffer. -type Encoder struct { - w writer - scratch *[]byte -} - -// NewEncoder returns an XML encoder -func NewEncoder(w writer) *Encoder { - scratch := make([]byte, 64) - - return &Encoder{w: w, scratch: &scratch} -} - -// String returns the string output of the XML encoder -func (e Encoder) String() string { - return e.w.String() -} - -// Bytes returns the []byte slice of the XML encoder -func (e Encoder) Bytes() []byte { - return e.w.Bytes() -} - -// RootElement builds a root element encoding -// It writes it's start element tag. The value should be closed. -func (e Encoder) RootElement(element StartElement) Value { - return newValue(e.w, e.scratch, element) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/error_utils.go b/vendor/github.com/aws/smithy-go/encoding/xml/error_utils.go deleted file mode 100644 index f3db6ccc..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/error_utils.go +++ /dev/null @@ -1,51 +0,0 @@ -package xml - -import ( - "encoding/xml" - "fmt" - "io" -) - -// ErrorComponents represents the error response fields -// that will be deserialized from an xml error response body -type ErrorComponents struct { - Code string - Message string -} - -// GetErrorResponseComponents returns the error fields from an xml error response body -func GetErrorResponseComponents(r io.Reader, noErrorWrapping bool) (ErrorComponents, error) { - if noErrorWrapping { - var errResponse noWrappedErrorResponse - if err := xml.NewDecoder(r).Decode(&errResponse); err != nil && err != io.EOF { - return ErrorComponents{}, fmt.Errorf("error while deserializing xml error response: %w", err) - } - return ErrorComponents{ - Code: errResponse.Code, - Message: errResponse.Message, - }, nil - } - - var errResponse wrappedErrorResponse - if err := xml.NewDecoder(r).Decode(&errResponse); err != nil && err != io.EOF { - return ErrorComponents{}, fmt.Errorf("error while deserializing xml error response: %w", err) - } - return ErrorComponents{ - Code: errResponse.Code, - Message: errResponse.Message, - }, nil -} - -// noWrappedErrorResponse represents the error response body with -// no internal ... -type wrappedErrorResponse struct { - Code string `xml:"Error>Code"` - Message string `xml:"Error>Message"` -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/escape.go b/vendor/github.com/aws/smithy-go/encoding/xml/escape.go deleted file mode 100644 index 1c5479af..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/escape.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2009 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. - -// Copied and modified from Go 1.14 stdlib's encoding/xml - -package xml - -import ( - "unicode/utf8" -) - -// Copied from Go 1.14 stdlib's encoding/xml -var ( - escQuot = []byte(""") // shorter than """ - escApos = []byte("'") // shorter than "'" - escAmp = []byte("&") - escLT = []byte("<") - escGT = []byte(">") - escTab = []byte(" ") - escNL = []byte(" ") - escCR = []byte(" ") - escFFFD = []byte("\uFFFD") // Unicode replacement character - - // Additional Escapes - escNextLine = []byte("…") - escLS = []byte("
") -) - -// Decide whether the given rune is in the XML Character Range, per -// the Char production of https://www.xml.com/axml/testaxml.htm, -// Section 2.2 Characters. -func isInCharacterRange(r rune) (inrange bool) { - return r == 0x09 || - r == 0x0A || - r == 0x0D || - r >= 0x20 && r <= 0xD7FF || - r >= 0xE000 && r <= 0xFFFD || - r >= 0x10000 && r <= 0x10FFFF -} - -// TODO: When do we need to escape the string? -// Based on encoding/xml escapeString from the Go Standard Library. -// https://golang.org/src/encoding/xml/xml.go -func escapeString(e writer, s string) { - var esc []byte - last := 0 - for i := 0; i < len(s); { - r, width := utf8.DecodeRuneInString(s[i:]) - i += width - switch r { - case '"': - esc = escQuot - case '\'': - esc = escApos - case '&': - esc = escAmp - case '<': - esc = escLT - case '>': - esc = escGT - case '\t': - esc = escTab - case '\n': - esc = escNL - case '\r': - esc = escCR - case '\u0085': - // Not escaped by stdlib - esc = escNextLine - case '\u2028': - // Not escaped by stdlib - esc = escLS - default: - if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) { - esc = escFFFD - break - } - continue - } - e.WriteString(s[last : i-width]) - e.Write(esc) - last = i - } - e.WriteString(s[last:]) -} - -// escapeText writes to w the properly escaped XML equivalent -// of the plain text data s. If escapeNewline is true, newline -// characters will be escaped. -// -// Based on encoding/xml escapeText from the Go Standard Library. -// https://golang.org/src/encoding/xml/xml.go -func escapeText(e writer, s []byte) { - var esc []byte - last := 0 - for i := 0; i < len(s); { - r, width := utf8.DecodeRune(s[i:]) - i += width - switch r { - case '"': - esc = escQuot - case '\'': - esc = escApos - case '&': - esc = escAmp - case '<': - esc = escLT - case '>': - esc = escGT - case '\t': - esc = escTab - case '\n': - // This always escapes newline, which is different than stdlib's optional - // escape of new line. - esc = escNL - case '\r': - esc = escCR - case '\u0085': - // Not escaped by stdlib - esc = escNextLine - case '\u2028': - // Not escaped by stdlib - esc = escLS - default: - if !isInCharacterRange(r) || (r == 0xFFFD && width == 1) { - esc = escFFFD - break - } - continue - } - e.Write(s[last : i-width]) - e.Write(esc) - last = i - } - e.Write(s[last:]) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/map.go b/vendor/github.com/aws/smithy-go/encoding/xml/map.go deleted file mode 100644 index e4285896..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/map.go +++ /dev/null @@ -1,53 +0,0 @@ -package xml - -// mapEntryWrapper is the default member wrapper start element for XML Map entry -var mapEntryWrapper = StartElement{ - Name: Name{Local: "entry"}, -} - -// Map represents the encoding of a XML map type -type Map struct { - w writer - scratch *[]byte - - // member start element is the map entry wrapper start element - memberStartElement StartElement - - // isFlattened returns true if the map is a flattened map - isFlattened bool -} - -// newMap returns a map encoder which sets the default map -// entry wrapper to `entry`. -// -// A map `someMap : {{key:"abc", value:"123"}}` is represented as -// `abc123`. -func newMap(w writer, scratch *[]byte) *Map { - return &Map{ - w: w, - scratch: scratch, - memberStartElement: mapEntryWrapper, - } -} - -// newFlattenedMap returns a map encoder which sets the map -// entry wrapper to the passed in memberWrapper`. -// -// A flattened map `someMap : {{key:"abc", value:"123"}}` is represented as -// `abc123`. -func newFlattenedMap(w writer, scratch *[]byte, memberWrapper StartElement) *Map { - return &Map{ - w: w, - scratch: scratch, - memberStartElement: memberWrapper, - isFlattened: true, - } -} - -// Entry returns a Value encoder with map's element. -// It writes the member wrapper start tag for each entry. -func (m *Map) Entry() Value { - v := newValue(m.w, m.scratch, m.memberStartElement) - v.isFlattened = m.isFlattened - return v -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/value.go b/vendor/github.com/aws/smithy-go/encoding/xml/value.go deleted file mode 100644 index 09434b2c..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/value.go +++ /dev/null @@ -1,302 +0,0 @@ -package xml - -import ( - "encoding/base64" - "fmt" - "math/big" - "strconv" - - "github.com/aws/smithy-go/encoding" -) - -// Value represents an XML Value type -// XML Value types: Object, Array, Map, String, Number, Boolean. -type Value struct { - w writer - scratch *[]byte - - // xml start element is the associated start element for the Value - startElement StartElement - - // indicates if the Value represents a flattened shape - isFlattened bool -} - -// newFlattenedValue returns a Value encoder. newFlattenedValue does NOT write the start element tag -func newFlattenedValue(w writer, scratch *[]byte, startElement StartElement) Value { - return Value{ - w: w, - scratch: scratch, - startElement: startElement, - } -} - -// newValue writes the start element xml tag and returns a Value -func newValue(w writer, scratch *[]byte, startElement StartElement) Value { - writeStartElement(w, startElement) - return Value{w: w, scratch: scratch, startElement: startElement} -} - -// writeStartElement takes in a start element and writes it. -// It handles namespace, attributes in start element. -func writeStartElement(w writer, el StartElement) error { - if el.isZero() { - return fmt.Errorf("xml start element cannot be nil") - } - - w.WriteRune(leftAngleBracket) - - if len(el.Name.Space) != 0 { - escapeString(w, el.Name.Space) - w.WriteRune(colon) - } - escapeString(w, el.Name.Local) - for _, attr := range el.Attr { - w.WriteRune(' ') - writeAttribute(w, &attr) - } - - w.WriteRune(rightAngleBracket) - return nil -} - -// writeAttribute writes an attribute from a provided Attribute -// For a namespace attribute, the attr.Name.Space must be defined as "xmlns". -// https://www.w3.org/TR/REC-xml-names/#NT-DefaultAttName -func writeAttribute(w writer, attr *Attr) { - // if local, space both are not empty - if len(attr.Name.Space) != 0 && len(attr.Name.Local) != 0 { - escapeString(w, attr.Name.Space) - w.WriteRune(colon) - } - - // if prefix is empty, the default `xmlns` space should be used as prefix. - if len(attr.Name.Local) == 0 { - attr.Name.Local = attr.Name.Space - } - - escapeString(w, attr.Name.Local) - w.WriteRune(equals) - w.WriteRune(quote) - escapeString(w, attr.Value) - w.WriteRune(quote) -} - -// writeEndElement takes in a end element and writes it. -func writeEndElement(w writer, el EndElement) error { - if el.isZero() { - return fmt.Errorf("xml end element cannot be nil") - } - - w.WriteRune(leftAngleBracket) - w.WriteRune(forwardSlash) - - if len(el.Name.Space) != 0 { - escapeString(w, el.Name.Space) - w.WriteRune(colon) - } - escapeString(w, el.Name.Local) - w.WriteRune(rightAngleBracket) - - return nil -} - -// String encodes v as a XML string. -// It will auto close the parent xml element tag. -func (xv Value) String(v string) { - escapeString(xv.w, v) - xv.Close() -} - -// Byte encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Byte(v int8) { - xv.Long(int64(v)) -} - -// Short encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Short(v int16) { - xv.Long(int64(v)) -} - -// Integer encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Integer(v int32) { - xv.Long(int64(v)) -} - -// Long encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Long(v int64) { - *xv.scratch = strconv.AppendInt((*xv.scratch)[:0], v, 10) - xv.w.Write(*xv.scratch) - - xv.Close() -} - -// Float encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Float(v float32) { - xv.float(float64(v), 32) - xv.Close() -} - -// Double encodes v as a XML number. -// It will auto close the parent xml element tag. -func (xv Value) Double(v float64) { - xv.float(v, 64) - xv.Close() -} - -func (xv Value) float(v float64, bits int) { - *xv.scratch = encoding.EncodeFloat((*xv.scratch)[:0], v, bits) - xv.w.Write(*xv.scratch) -} - -// Boolean encodes v as a XML boolean. -// It will auto close the parent xml element tag. -func (xv Value) Boolean(v bool) { - *xv.scratch = strconv.AppendBool((*xv.scratch)[:0], v) - xv.w.Write(*xv.scratch) - - xv.Close() -} - -// Base64EncodeBytes writes v as a base64 value in XML string. -// It will auto close the parent xml element tag. -func (xv Value) Base64EncodeBytes(v []byte) { - encodeByteSlice(xv.w, (*xv.scratch)[:0], v) - xv.Close() -} - -// BigInteger encodes v big.Int as XML value. -// It will auto close the parent xml element tag. -func (xv Value) BigInteger(v *big.Int) { - xv.w.Write([]byte(v.Text(10))) - xv.Close() -} - -// BigDecimal encodes v big.Float as XML value. -// It will auto close the parent xml element tag. -func (xv Value) BigDecimal(v *big.Float) { - if i, accuracy := v.Int64(); accuracy == big.Exact { - xv.Long(i) - return - } - - xv.w.Write([]byte(v.Text('e', -1))) - xv.Close() -} - -// Write writes v directly to the xml document -// if escapeXMLText is set to true, write will escape text. -// It will auto close the parent xml element tag. -func (xv Value) Write(v []byte, escapeXMLText bool) { - // escape and write xml text - if escapeXMLText { - escapeText(xv.w, v) - } else { - // write xml directly - xv.w.Write(v) - } - - xv.Close() -} - -// MemberElement does member element encoding. It returns a Value. -// Member Element method should be used for all shapes except flattened shapes. -// -// A call to MemberElement will write nested element tags directly using the -// provided start element. The value returned by MemberElement should be closed. -func (xv Value) MemberElement(element StartElement) Value { - return newValue(xv.w, xv.scratch, element) -} - -// FlattenedElement returns flattened element encoding. It returns a Value. -// This method should be used for flattened shapes. -// -// Unlike MemberElement, flattened element will NOT write element tags -// directly for the associated start element. -// -// The value returned by the FlattenedElement does not need to be closed. -func (xv Value) FlattenedElement(element StartElement) Value { - v := newFlattenedValue(xv.w, xv.scratch, element) - v.isFlattened = true - return v -} - -// Array returns an array encoder. By default, the members of array are -// wrapped with `` element tag. -// If value is marked as flattened, the start element is used to wrap the members instead of -// the `` element. -func (xv Value) Array() *Array { - return newArray(xv.w, xv.scratch, arrayMemberWrapper, xv.startElement, xv.isFlattened) -} - -/* -ArrayWithCustomName returns an array encoder. - -It takes named start element as an argument, the named start element will used to wrap xml array entries. -for eg, `entry1` -Here `customName` named start element will be wrapped on each array member. -*/ -func (xv Value) ArrayWithCustomName(element StartElement) *Array { - return newArray(xv.w, xv.scratch, element, xv.startElement, xv.isFlattened) -} - -/* -Map returns a map encoder. By default, the map entries are -wrapped with `` element tag. - -If value is marked as flattened, the start element is used to wrap the entry instead of -the `` element. -*/ -func (xv Value) Map() *Map { - // flattened map - if xv.isFlattened { - return newFlattenedMap(xv.w, xv.scratch, xv.startElement) - } - - // un-flattened map - return newMap(xv.w, xv.scratch) -} - -// encodeByteSlice is modified copy of json encoder's encodeByteSlice. -// It is used to base64 encode a byte slice. -func encodeByteSlice(w writer, scratch []byte, v []byte) { - if v == nil { - return - } - - encodedLen := base64.StdEncoding.EncodedLen(len(v)) - if encodedLen <= len(scratch) { - // If the encoded bytes fit in e.scratch, avoid an extra - // allocation and use the cheaper Encoding.Encode. - dst := scratch[:encodedLen] - base64.StdEncoding.Encode(dst, v) - w.Write(dst) - } else if encodedLen <= 1024 { - // The encoded bytes are short enough to allocate for, and - // Encoding.Encode is still cheaper. - dst := make([]byte, encodedLen) - base64.StdEncoding.Encode(dst, v) - w.Write(dst) - } else { - // The encoded bytes are too long to cheaply allocate, and - // Encoding.Encode is no longer noticeably cheaper. - enc := base64.NewEncoder(base64.StdEncoding, w) - enc.Write(v) - enc.Close() - } -} - -// IsFlattened returns true if value is for flattened shape. -func (xv Value) IsFlattened() bool { - return xv.isFlattened -} - -// Close closes the value. -func (xv Value) Close() { - writeEndElement(xv.w, xv.startElement.End()) -} diff --git a/vendor/github.com/aws/smithy-go/encoding/xml/xml_decoder.go b/vendor/github.com/aws/smithy-go/encoding/xml/xml_decoder.go deleted file mode 100644 index dc4eebdf..00000000 --- a/vendor/github.com/aws/smithy-go/encoding/xml/xml_decoder.go +++ /dev/null @@ -1,154 +0,0 @@ -package xml - -import ( - "encoding/xml" - "fmt" - "strings" -) - -// NodeDecoder is a XML decoder wrapper that is responsible to decoding -// a single XML Node element and it's nested member elements. This wrapper decoder -// takes in the start element of the top level node being decoded. -type NodeDecoder struct { - Decoder *xml.Decoder - StartEl xml.StartElement -} - -// WrapNodeDecoder returns an initialized XMLNodeDecoder -func WrapNodeDecoder(decoder *xml.Decoder, startEl xml.StartElement) NodeDecoder { - return NodeDecoder{ - Decoder: decoder, - StartEl: startEl, - } -} - -// Token on a Node Decoder returns a xml StartElement. It returns a boolean that indicates the -// a token is the node decoder's end node token; and an error which indicates any error -// that occurred while retrieving the start element -func (d NodeDecoder) Token() (t xml.StartElement, done bool, err error) { - for { - token, e := d.Decoder.Token() - if e != nil { - return t, done, e - } - - // check if we reach end of the node being decoded - if el, ok := token.(xml.EndElement); ok { - return t, el == d.StartEl.End(), err - } - - if t, ok := token.(xml.StartElement); ok { - return restoreAttrNamespaces(t), false, err - } - - // skip token if it is a comment or preamble or empty space value due to indentation - // or if it's a value and is not expected - } -} - -// restoreAttrNamespaces update XML attributes to restore the short namespaces found within -// the raw XML document. -func restoreAttrNamespaces(node xml.StartElement) xml.StartElement { - if len(node.Attr) == 0 { - return node - } - - // Generate a mapping of XML namespace values to their short names. - ns := map[string]string{} - for _, a := range node.Attr { - if a.Name.Space == "xmlns" { - ns[a.Value] = a.Name.Local - break - } - } - - for i, a := range node.Attr { - if a.Name.Space == "xmlns" { - continue - } - // By default, xml.Decoder will fully resolve these namespaces. So if you had - // then by default the second attribute would have the `Name.Space` resolved to `baz`. But we need it to - // continue to resolve as `bar` so we can easily identify it later on. - if v, ok := ns[node.Attr[i].Name.Space]; ok { - node.Attr[i].Name.Space = v - } - } - return node -} - -// GetElement looks for the given tag name at the current level, and returns the element if found, and -// skipping over non-matching elements. Returns an error if the node is not found, or if an error occurs while walking -// the document. -func (d NodeDecoder) GetElement(name string) (t xml.StartElement, err error) { - for { - token, done, err := d.Token() - if err != nil { - return t, err - } - if done { - return t, fmt.Errorf("%s node not found", name) - } - switch { - case strings.EqualFold(name, token.Name.Local): - return token, nil - default: - err = d.Decoder.Skip() - if err != nil { - return t, err - } - } - } -} - -// Value provides an abstraction to retrieve char data value within an xml element. -// The method will return an error if it encounters a nested xml element instead of char data. -// This method should only be used to retrieve simple type or blob shape values as []byte. -func (d NodeDecoder) Value() (c []byte, err error) { - t, e := d.Decoder.Token() - if e != nil { - return c, e - } - - endElement := d.StartEl.End() - - switch ev := t.(type) { - case xml.CharData: - c = ev.Copy() - case xml.EndElement: // end tag or self-closing - if ev == endElement { - return []byte{}, err - } - return c, fmt.Errorf("expected value for %v element, got %T type %v instead", d.StartEl.Name.Local, t, t) - default: - return c, fmt.Errorf("expected value for %v element, got %T type %v instead", d.StartEl.Name.Local, t, t) - } - - t, e = d.Decoder.Token() - if e != nil { - return c, e - } - - if ev, ok := t.(xml.EndElement); ok { - if ev == endElement { - return c, err - } - } - - return c, fmt.Errorf("expected end element %v, got %T type %v instead", endElement, t, t) -} - -// FetchRootElement takes in a decoder and returns the first start element within the xml body. -// This function is useful in fetching the start element of an XML response and ignore the -// comments and preamble -func FetchRootElement(decoder *xml.Decoder) (startElement xml.StartElement, err error) { - for { - t, e := decoder.Token() - if e != nil { - return startElement, e - } - - if startElement, ok := t.(xml.StartElement); ok { - return startElement, err - } - } -} diff --git a/vendor/github.com/aws/smithy-go/endpoints/endpoint.go b/vendor/github.com/aws/smithy-go/endpoints/endpoint.go deleted file mode 100644 index a9352839..00000000 --- a/vendor/github.com/aws/smithy-go/endpoints/endpoint.go +++ /dev/null @@ -1,23 +0,0 @@ -package transport - -import ( - "net/http" - "net/url" - - "github.com/aws/smithy-go" -) - -// Endpoint is the endpoint object returned by Endpoint resolution V2 -type Endpoint struct { - // The complete URL minimally specfiying the scheme and host. - // May optionally specify the port and base path component. - URI url.URL - - // An optional set of headers to be sent using transport layer headers. - Headers http.Header - - // A grab-bag property map of endpoint attributes. The - // values present here are subject to change, or being add/removed at any - // time. - Properties smithy.Properties -} diff --git a/vendor/github.com/aws/smithy-go/errors.go b/vendor/github.com/aws/smithy-go/errors.go deleted file mode 100644 index d6948d02..00000000 --- a/vendor/github.com/aws/smithy-go/errors.go +++ /dev/null @@ -1,137 +0,0 @@ -package smithy - -import "fmt" - -// APIError provides the generic API and protocol agnostic error type all SDK -// generated exception types will implement. -type APIError interface { - error - - // ErrorCode returns the error code for the API exception. - ErrorCode() string - // ErrorMessage returns the error message for the API exception. - ErrorMessage() string - // ErrorFault returns the fault for the API exception. - ErrorFault() ErrorFault -} - -// GenericAPIError provides a generic concrete API error type that SDKs can use -// to deserialize error responses into. Should be used for unmodeled or untyped -// errors. -type GenericAPIError struct { - Code string - Message string - Fault ErrorFault -} - -// ErrorCode returns the error code for the API exception. -func (e *GenericAPIError) ErrorCode() string { return e.Code } - -// ErrorMessage returns the error message for the API exception. -func (e *GenericAPIError) ErrorMessage() string { return e.Message } - -// ErrorFault returns the fault for the API exception. -func (e *GenericAPIError) ErrorFault() ErrorFault { return e.Fault } - -func (e *GenericAPIError) Error() string { - return fmt.Sprintf("api error %s: %s", e.Code, e.Message) -} - -var _ APIError = (*GenericAPIError)(nil) - -// OperationError decorates an underlying error which occurred while invoking -// an operation with names of the operation and API. -type OperationError struct { - ServiceID string - OperationName string - Err error -} - -// Service returns the name of the API service the error occurred with. -func (e *OperationError) Service() string { return e.ServiceID } - -// Operation returns the name of the API operation the error occurred with. -func (e *OperationError) Operation() string { return e.OperationName } - -// Unwrap returns the nested error if any, or nil. -func (e *OperationError) Unwrap() error { return e.Err } - -func (e *OperationError) Error() string { - return fmt.Sprintf("operation error %s: %s, %v", e.ServiceID, e.OperationName, e.Err) -} - -// DeserializationError provides a wrapper for an error that occurs during -// deserialization. -type DeserializationError struct { - Err error // original error - Snapshot []byte -} - -// Error returns a formatted error for DeserializationError -func (e *DeserializationError) Error() string { - const msg = "deserialization failed" - if e.Err == nil { - return msg - } - return fmt.Sprintf("%s, %v", msg, e.Err) -} - -// Unwrap returns the underlying Error in DeserializationError -func (e *DeserializationError) Unwrap() error { return e.Err } - -// ErrorFault provides the type for a Smithy API error fault. -type ErrorFault int - -// ErrorFault enumeration values -const ( - FaultUnknown ErrorFault = iota - FaultServer - FaultClient -) - -func (f ErrorFault) String() string { - switch f { - case FaultServer: - return "server" - case FaultClient: - return "client" - default: - return "unknown" - } -} - -// SerializationError represents an error that occurred while attempting to serialize a request -type SerializationError struct { - Err error // original error -} - -// Error returns a formatted error for SerializationError -func (e *SerializationError) Error() string { - const msg = "serialization failed" - if e.Err == nil { - return msg - } - return fmt.Sprintf("%s: %v", msg, e.Err) -} - -// Unwrap returns the underlying Error in SerializationError -func (e *SerializationError) Unwrap() error { return e.Err } - -// CanceledError is the error that will be returned by an API request that was -// canceled. API operations given a Context may return this error when -// canceled. -type CanceledError struct { - Err error -} - -// CanceledError returns true to satisfy interfaces checking for canceled errors. -func (*CanceledError) CanceledError() bool { return true } - -// Unwrap returns the underlying error, if there was one. -func (e *CanceledError) Unwrap() error { - return e.Err -} - -func (e *CanceledError) Error() string { - return fmt.Sprintf("canceled, %v", e.Err) -} diff --git a/vendor/github.com/aws/smithy-go/go_module_metadata.go b/vendor/github.com/aws/smithy-go/go_module_metadata.go deleted file mode 100644 index cd6f7fa4..00000000 --- a/vendor/github.com/aws/smithy-go/go_module_metadata.go +++ /dev/null @@ -1,6 +0,0 @@ -// Code generated by internal/repotools/cmd/updatemodulemeta DO NOT EDIT. - -package smithy - -// goModuleVersion is the tagged release for this module -const goModuleVersion = "1.19.0" diff --git a/vendor/github.com/aws/smithy-go/internal/sync/singleflight/LICENSE b/vendor/github.com/aws/smithy-go/internal/sync/singleflight/LICENSE deleted file mode 100644 index fe6a6200..00000000 --- a/vendor/github.com/aws/smithy-go/internal/sync/singleflight/LICENSE +++ /dev/null @@ -1,28 +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 COPYIGHT 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/aws/smithy-go/internal/sync/singleflight/docs.go b/vendor/github.com/aws/smithy-go/internal/sync/singleflight/docs.go deleted file mode 100644 index 9c9d02b9..00000000 --- a/vendor/github.com/aws/smithy-go/internal/sync/singleflight/docs.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package singleflight provides a duplicate function call suppression -// mechanism. This package is a fork of the Go golang.org/x/sync/singleflight -// package. The package is forked, because the package a part of the unstable -// and unversioned golang.org/x/sync module. -// -// https://github.com/golang/sync/tree/67f06af15bc961c363a7260195bcd53487529a21/singleflight - -package singleflight diff --git a/vendor/github.com/aws/smithy-go/internal/sync/singleflight/singleflight.go b/vendor/github.com/aws/smithy-go/internal/sync/singleflight/singleflight.go deleted file mode 100644 index e8a1b17d..00000000 --- a/vendor/github.com/aws/smithy-go/internal/sync/singleflight/singleflight.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2013 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 singleflight - -import ( - "bytes" - "errors" - "fmt" - "runtime" - "runtime/debug" - "sync" -) - -// errGoexit indicates the runtime.Goexit was called in -// the user given function. -var errGoexit = errors.New("runtime.Goexit was called") - -// A panicError is an arbitrary value recovered from a panic -// with the stack trace during the execution of given function. -type panicError struct { - value interface{} - stack []byte -} - -// Error implements error interface. -func (p *panicError) Error() string { - return fmt.Sprintf("%v\n\n%s", p.value, p.stack) -} - -func newPanicError(v interface{}) error { - stack := debug.Stack() - - // The first line of the stack trace is of the form "goroutine N [status]:" - // but by the time the panic reaches Do the goroutine may no longer exist - // and its status will have changed. Trim out the misleading line. - if line := bytes.IndexByte(stack[:], '\n'); line >= 0 { - stack = stack[line+1:] - } - return &panicError{value: v, stack: stack} -} - -// call is an in-flight or completed singleflight.Do call -type call struct { - wg sync.WaitGroup - - // These fields are written once before the WaitGroup is done - // and are only read after the WaitGroup is done. - val interface{} - err error - - // forgotten indicates whether Forget was called with this call's key - // while the call was still in flight. - forgotten bool - - // These fields are read and written with the singleflight - // mutex held before the WaitGroup is done, and are read but - // not written after the WaitGroup is done. - dups int - chans []chan<- Result -} - -// Group represents a class of work and forms a namespace in -// which units of work can be executed with duplicate suppression. -type Group struct { - mu sync.Mutex // protects m - m map[string]*call // lazily initialized -} - -// Result holds the results of Do, so they can be passed -// on a channel. -type Result struct { - Val interface{} - Err error - Shared bool -} - -// Do executes and returns the results of the given function, making -// sure that only one execution is in-flight for a given key at a -// time. If a duplicate comes in, the duplicate caller waits for the -// original to complete and receives the same results. -// The return value shared indicates whether v was given to multiple callers. -func (g *Group) Do(key string, fn func() (interface{}, error)) (v interface{}, err error, shared bool) { - g.mu.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - g.mu.Unlock() - c.wg.Wait() - - if e, ok := c.err.(*panicError); ok { - panic(e) - } else if c.err == errGoexit { - runtime.Goexit() - } - return c.val, c.err, true - } - c := new(call) - c.wg.Add(1) - g.m[key] = c - g.mu.Unlock() - - g.doCall(c, key, fn) - return c.val, c.err, c.dups > 0 -} - -// DoChan is like Do but returns a channel that will receive the -// results when they are ready. -// -// The returned channel will not be closed. -func (g *Group) DoChan(key string, fn func() (interface{}, error)) <-chan Result { - ch := make(chan Result, 1) - g.mu.Lock() - if g.m == nil { - g.m = make(map[string]*call) - } - if c, ok := g.m[key]; ok { - c.dups++ - c.chans = append(c.chans, ch) - g.mu.Unlock() - return ch - } - c := &call{chans: []chan<- Result{ch}} - c.wg.Add(1) - g.m[key] = c - g.mu.Unlock() - - go g.doCall(c, key, fn) - - return ch -} - -// doCall handles the single call for a key. -func (g *Group) doCall(c *call, key string, fn func() (interface{}, error)) { - normalReturn := false - recovered := false - - // use double-defer to distinguish panic from runtime.Goexit, - // more details see https://golang.org/cl/134395 - defer func() { - // the given function invoked runtime.Goexit - if !normalReturn && !recovered { - c.err = errGoexit - } - - c.wg.Done() - g.mu.Lock() - defer g.mu.Unlock() - if !c.forgotten { - delete(g.m, key) - } - - if e, ok := c.err.(*panicError); ok { - // In order to prevent the waiting channels from being blocked forever, - // needs to ensure that this panic cannot be recovered. - if len(c.chans) > 0 { - go panic(e) - select {} // Keep this goroutine around so that it will appear in the crash dump. - } else { - panic(e) - } - } else if c.err == errGoexit { - // Already in the process of goexit, no need to call again - } else { - // Normal return - for _, ch := range c.chans { - ch <- Result{c.val, c.err, c.dups > 0} - } - } - }() - - func() { - defer func() { - if !normalReturn { - // Ideally, we would wait to take a stack trace until we've determined - // whether this is a panic or a runtime.Goexit. - // - // Unfortunately, the only way we can distinguish the two is to see - // whether the recover stopped the goroutine from terminating, and by - // the time we know that, the part of the stack trace relevant to the - // panic has been discarded. - if r := recover(); r != nil { - c.err = newPanicError(r) - } - } - }() - - c.val, c.err = fn() - normalReturn = true - }() - - if !normalReturn { - recovered = true - } -} - -// Forget tells the singleflight to forget about a key. Future calls -// to Do for this key will call the function rather than waiting for -// an earlier call to complete. -func (g *Group) Forget(key string) { - g.mu.Lock() - if c, ok := g.m[key]; ok { - c.forgotten = true - } - delete(g.m, key) - g.mu.Unlock() -} diff --git a/vendor/github.com/aws/smithy-go/io/byte.go b/vendor/github.com/aws/smithy-go/io/byte.go deleted file mode 100644 index f8417c15..00000000 --- a/vendor/github.com/aws/smithy-go/io/byte.go +++ /dev/null @@ -1,12 +0,0 @@ -package io - -const ( - // Byte is 8 bits - Byte int64 = 1 - // KibiByte (KiB) is 1024 Bytes - KibiByte = Byte * 1024 - // MebiByte (MiB) is 1024 KiB - MebiByte = KibiByte * 1024 - // GibiByte (GiB) is 1024 MiB - GibiByte = MebiByte * 1024 -) diff --git a/vendor/github.com/aws/smithy-go/io/doc.go b/vendor/github.com/aws/smithy-go/io/doc.go deleted file mode 100644 index a6a33eaf..00000000 --- a/vendor/github.com/aws/smithy-go/io/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package io provides utilities for Smithy generated API clients. -package io diff --git a/vendor/github.com/aws/smithy-go/io/reader.go b/vendor/github.com/aws/smithy-go/io/reader.go deleted file mode 100644 index 07063f29..00000000 --- a/vendor/github.com/aws/smithy-go/io/reader.go +++ /dev/null @@ -1,16 +0,0 @@ -package io - -import ( - "io" -) - -// ReadSeekNopCloser wraps an io.ReadSeeker with an additional Close method -// that does nothing. -type ReadSeekNopCloser struct { - io.ReadSeeker -} - -// Close does nothing. -func (ReadSeekNopCloser) Close() error { - return nil -} diff --git a/vendor/github.com/aws/smithy-go/io/ringbuffer.go b/vendor/github.com/aws/smithy-go/io/ringbuffer.go deleted file mode 100644 index 06b476ad..00000000 --- a/vendor/github.com/aws/smithy-go/io/ringbuffer.go +++ /dev/null @@ -1,94 +0,0 @@ -package io - -import ( - "bytes" - "io" -) - -// RingBuffer struct satisfies io.ReadWrite interface. -// -// ReadBuffer is a revolving buffer data structure, which can be used to store snapshots of data in a -// revolving window. -type RingBuffer struct { - slice []byte - start int - end int - size int -} - -// NewRingBuffer method takes in a byte slice as an input and returns a RingBuffer. -func NewRingBuffer(slice []byte) *RingBuffer { - ringBuf := RingBuffer{ - slice: slice, - } - return &ringBuf -} - -// Write method inserts the elements in a byte slice, and returns the number of bytes written along with any error. -func (r *RingBuffer) Write(p []byte) (int, error) { - for _, b := range p { - // check if end points to invalid index, we need to circle back - if r.end == len(r.slice) { - r.end = 0 - } - // check if start points to invalid index, we need to circle back - if r.start == len(r.slice) { - r.start = 0 - } - // if ring buffer is filled, increment the start index - if r.size == len(r.slice) { - r.size-- - r.start++ - } - - r.slice[r.end] = b - r.end++ - r.size++ - } - return len(p), nil -} - -// Read copies the data on the ring buffer into the byte slice provided to the method. -// Returns the read count along with any error encountered while reading. -func (r *RingBuffer) Read(p []byte) (int, error) { - // readCount keeps track of the number of bytes read - var readCount int - for j := 0; j < len(p); j++ { - // if ring buffer is empty or completely read - // return EOF error. - if r.size == 0 { - return readCount, io.EOF - } - - if r.start == len(r.slice) { - r.start = 0 - } - - p[j] = r.slice[r.start] - readCount++ - // increment the start pointer for ring buffer - r.start++ - // decrement the size of ring buffer - r.size-- - } - return readCount, nil -} - -// Len returns the number of unread bytes in the buffer. -func (r *RingBuffer) Len() int { - return r.size -} - -// Bytes returns a copy of the RingBuffer's bytes. -func (r RingBuffer) Bytes() []byte { - var b bytes.Buffer - io.Copy(&b, &r) - return b.Bytes() -} - -// Reset resets the ring buffer. -func (r *RingBuffer) Reset() { - *r = RingBuffer{ - slice: r.slice, - } -} diff --git a/vendor/github.com/aws/smithy-go/local-mod-replace.sh b/vendor/github.com/aws/smithy-go/local-mod-replace.sh deleted file mode 100644 index 800bf376..00000000 --- a/vendor/github.com/aws/smithy-go/local-mod-replace.sh +++ /dev/null @@ -1,39 +0,0 @@ -#1/usr/bin/env bash - -PROJECT_DIR="" -SMITHY_SOURCE_DIR=$(cd `dirname $0` && pwd) - -usage() { - echo "Usage: $0 [-s SMITHY_SOURCE_DIR] [-d PROJECT_DIR]" 1>&2 - exit 1 -} - -while getopts "hs:d:" options; do - case "${options}" in - s) - SMITHY_SOURCE_DIR=${OPTARG} - if [ "$SMITHY_SOURCE_DIR" == "" ]; then - echo "path to smithy-go source directory is required" || exit - usage - fi - ;; - d) - PROJECT_DIR=${OPTARG} - ;; - h) - usage - ;; - *) - usage - ;; - esac -done - -if [ "$PROJECT_DIR" != "" ]; then - cd $PROJECT_DIR || exit -fi - -go mod graph | awk '{print $1}' | cut -d '@' -f 1 | sort | uniq | grep "github.com/aws/smithy-go" | while read x; do - repPath=${x/github.com\/aws\/smithy-go/${SMITHY_SOURCE_DIR}} - echo -replace $x=$repPath -done | xargs go mod edit diff --git a/vendor/github.com/aws/smithy-go/logging/logger.go b/vendor/github.com/aws/smithy-go/logging/logger.go deleted file mode 100644 index 2071924b..00000000 --- a/vendor/github.com/aws/smithy-go/logging/logger.go +++ /dev/null @@ -1,82 +0,0 @@ -package logging - -import ( - "context" - "io" - "log" -) - -// Classification is the type of the log entry's classification name. -type Classification string - -// Set of standard classifications that can be used by clients and middleware -const ( - Warn Classification = "WARN" - Debug Classification = "DEBUG" -) - -// Logger is an interface for logging entries at certain classifications. -type Logger interface { - // Logf is expected to support the standard fmt package "verbs". - Logf(classification Classification, format string, v ...interface{}) -} - -// LoggerFunc is a wrapper around a function to satisfy the Logger interface. -type LoggerFunc func(classification Classification, format string, v ...interface{}) - -// Logf delegates the logging request to the wrapped function. -func (f LoggerFunc) Logf(classification Classification, format string, v ...interface{}) { - f(classification, format, v...) -} - -// ContextLogger is an optional interface a Logger implementation may expose that provides -// the ability to create context aware log entries. -type ContextLogger interface { - WithContext(context.Context) Logger -} - -// WithContext will pass the provided context to logger if it implements the ContextLogger interface and return the resulting -// logger. Otherwise the logger will be returned as is. As a special case if a nil logger is provided, a Nop logger will -// be returned to the caller. -func WithContext(ctx context.Context, logger Logger) Logger { - if logger == nil { - return Nop{} - } - - cl, ok := logger.(ContextLogger) - if !ok { - return logger - } - - return cl.WithContext(ctx) -} - -// Nop is a Logger implementation that simply does not perform any logging. -type Nop struct{} - -// Logf simply returns without performing any action -func (n Nop) Logf(Classification, string, ...interface{}) { - return -} - -// StandardLogger is a Logger implementation that wraps the standard library logger, and delegates logging to it's -// Printf method. -type StandardLogger struct { - Logger *log.Logger -} - -// Logf logs the given classification and message to the underlying logger. -func (s StandardLogger) Logf(classification Classification, format string, v ...interface{}) { - if len(classification) != 0 { - format = string(classification) + " " + format - } - - s.Logger.Printf(format, v...) -} - -// NewStandardLogger returns a new StandardLogger -func NewStandardLogger(writer io.Writer) *StandardLogger { - return &StandardLogger{ - Logger: log.New(writer, "SDK ", log.LstdFlags), - } -} diff --git a/vendor/github.com/aws/smithy-go/middleware/doc.go b/vendor/github.com/aws/smithy-go/middleware/doc.go deleted file mode 100644 index 9858928a..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/doc.go +++ /dev/null @@ -1,67 +0,0 @@ -// Package middleware provides transport agnostic middleware for decorating SDK -// handlers. -// -// The Smithy middleware stack provides ordered behavior to be invoked on an -// underlying handler. The stack is separated into steps that are invoked in a -// static order. A step is a collection of middleware that are injected into a -// ordered list defined by the user. The user may add, insert, swap, and remove a -// step's middleware. When the stack is invoked the step middleware become static, -// and their order cannot be modified. -// -// A stack and its step middleware are **not** safe to modify concurrently. -// -// A stack will use the ordered list of middleware to decorate a underlying -// handler. A handler could be something like an HTTP Client that round trips an -// API operation over HTTP. -// -// Smithy Middleware Stack -// -// A Stack is a collection of middleware that wrap a handler. The stack can be -// broken down into discreet steps. Each step may contain zero or more middleware -// specific to that stack's step. -// -// A Stack Step is a predefined set of middleware that are invoked in a static -// order by the Stack. These steps represent fixed points in the middleware stack -// for organizing specific behavior, such as serialize and build. A Stack Step is -// composed of zero or more middleware that are specific to that step. A step may -// define its own set of input/output parameters the generic input/output -// parameters are cast from. A step calls its middleware recursively, before -// calling the next step in the stack returning the result or error of the step -// middleware decorating the underlying handler. -// -// * Initialize: Prepares the input, and sets any default parameters as needed, -// (e.g. idempotency token, and presigned URLs). -// -// * Serialize: Serializes the prepared input into a data structure that can be -// consumed by the target transport's message, (e.g. REST-JSON serialization). -// -// * Build: Adds additional metadata to the serialized transport message, (e.g. -// HTTP's Content-Length header, or body checksum). Decorations and -// modifications to the message should be copied to all message attempts. -// -// * Finalize: Performs final preparations needed before sending the message. The -// message should already be complete by this stage, and is only alternated to -// meet the expectations of the recipient, (e.g. Retry and AWS SigV4 request -// signing). -// -// * Deserialize: Reacts to the handler's response returned by the recipient of -// the request message. Deserializes the response into a structured type or -// error above stacks can react to. -// -// Adding Middleware to a Stack Step -// -// Middleware can be added to a step front or back, or relative, by name, to an -// existing middleware in that stack. If a middleware does not have a name, a -// unique name will be generated at the middleware and be added to the step. -// -// // Create middleware stack -// stack := middleware.NewStack() -// -// // Add middleware to stack steps -// stack.Initialize.Add(paramValidationMiddleware, middleware.After) -// stack.Serialize.Add(marshalOperationFoo, middleware.After) -// stack.Deserialize.Add(unmarshalOperationFoo, middleware.After) -// -// // Invoke middleware on handler. -// resp, err := stack.HandleMiddleware(ctx, req.Input, clientHandler) -package middleware diff --git a/vendor/github.com/aws/smithy-go/middleware/logging.go b/vendor/github.com/aws/smithy-go/middleware/logging.go deleted file mode 100644 index c2f0dbb6..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/logging.go +++ /dev/null @@ -1,46 +0,0 @@ -package middleware - -import ( - "context" - - "github.com/aws/smithy-go/logging" -) - -// loggerKey is the context value key for which the logger is associated with. -type loggerKey struct{} - -// GetLogger takes a context to retrieve a Logger from. If no logger is present on the context a logging.Nop logger -// is returned. If the logger retrieved from context supports the ContextLogger interface, the context will be passed -// to the WithContext method and the resulting logger will be returned. Otherwise the stored logger is returned as is. -func GetLogger(ctx context.Context) logging.Logger { - logger, ok := ctx.Value(loggerKey{}).(logging.Logger) - if !ok || logger == nil { - return logging.Nop{} - } - - return logging.WithContext(ctx, logger) -} - -// SetLogger sets the provided logger value on the provided ctx. -func SetLogger(ctx context.Context, logger logging.Logger) context.Context { - return context.WithValue(ctx, loggerKey{}, logger) -} - -type setLogger struct { - Logger logging.Logger -} - -// AddSetLoggerMiddleware adds a middleware that will add the provided logger to the middleware context. -func AddSetLoggerMiddleware(stack *Stack, logger logging.Logger) error { - return stack.Initialize.Add(&setLogger{Logger: logger}, After) -} - -func (a *setLogger) ID() string { - return "SetLogger" -} - -func (a *setLogger) HandleInitialize(ctx context.Context, in InitializeInput, next InitializeHandler) ( - out InitializeOutput, metadata Metadata, err error, -) { - return next.HandleInitialize(SetLogger(ctx, a.Logger), in) -} diff --git a/vendor/github.com/aws/smithy-go/middleware/metadata.go b/vendor/github.com/aws/smithy-go/middleware/metadata.go deleted file mode 100644 index 7bb7dbcf..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/metadata.go +++ /dev/null @@ -1,65 +0,0 @@ -package middleware - -// MetadataReader provides an interface for reading metadata from the -// underlying metadata container. -type MetadataReader interface { - Get(key interface{}) interface{} -} - -// Metadata provides storing and reading metadata values. Keys may be any -// comparable value type. Get and set will panic if key is not a comparable -// value type. -// -// Metadata uses lazy initialization, and Set method must be called as an -// addressable value, or pointer. Not doing so may cause key/value pair to not -// be set. -type Metadata struct { - values map[interface{}]interface{} -} - -// Get attempts to retrieve the value the key points to. Returns nil if the -// key was not found. -// -// Panics if key type is not comparable. -func (m Metadata) Get(key interface{}) interface{} { - return m.values[key] -} - -// Clone creates a shallow copy of Metadata entries, returning a new Metadata -// value with the original entries copied into it. -func (m Metadata) Clone() Metadata { - vs := make(map[interface{}]interface{}, len(m.values)) - for k, v := range m.values { - vs[k] = v - } - - return Metadata{ - values: vs, - } -} - -// Set stores the value pointed to by the key. If a value already exists at -// that key it will be replaced with the new value. -// -// Set method must be called as an addressable value, or pointer. If Set is not -// called as an addressable value or pointer, the key value pair being set may -// be lost. -// -// Panics if the key type is not comparable. -func (m *Metadata) Set(key, value interface{}) { - if m.values == nil { - m.values = map[interface{}]interface{}{} - } - m.values[key] = value -} - -// Has returns whether the key exists in the metadata. -// -// Panics if the key type is not comparable. -func (m Metadata) Has(key interface{}) bool { - if m.values == nil { - return false - } - _, ok := m.values[key] - return ok -} diff --git a/vendor/github.com/aws/smithy-go/middleware/middleware.go b/vendor/github.com/aws/smithy-go/middleware/middleware.go deleted file mode 100644 index 803b7c75..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/middleware.go +++ /dev/null @@ -1,71 +0,0 @@ -package middleware - -import ( - "context" -) - -// Handler provides the interface for performing the logic to obtain an output, -// or error for the given input. -type Handler interface { - // Handle performs logic to obtain an output for the given input. Handler - // should be decorated with middleware to perform input specific behavior. - Handle(ctx context.Context, input interface{}) ( - output interface{}, metadata Metadata, err error, - ) -} - -// HandlerFunc provides a wrapper around a function pointer to be used as a -// middleware handler. -type HandlerFunc func(ctx context.Context, input interface{}) ( - output interface{}, metadata Metadata, err error, -) - -// Handle invokes the underlying function, returning the result. -func (fn HandlerFunc) Handle(ctx context.Context, input interface{}) ( - output interface{}, metadata Metadata, err error, -) { - return fn(ctx, input) -} - -// Middleware provides the interface to call handlers in a chain. -type Middleware interface { - // ID provides a unique identifier for the middleware. - ID() string - - // Performs the middleware's handling of the input, returning the output, - // or error. The middleware can invoke the next Handler if handling should - // continue. - HandleMiddleware(ctx context.Context, input interface{}, next Handler) ( - output interface{}, metadata Metadata, err error, - ) -} - -// decoratedHandler wraps a middleware in order to to call the next handler in -// the chain. -type decoratedHandler struct { - // The next handler to be called. - Next Handler - - // The current middleware decorating the handler. - With Middleware -} - -// Handle implements the Handler interface to handle a operation invocation. -func (m decoratedHandler) Handle(ctx context.Context, input interface{}) ( - output interface{}, metadata Metadata, err error, -) { - return m.With.HandleMiddleware(ctx, input, m.Next) -} - -// DecorateHandler decorates a handler with a middleware. Wrapping the handler -// with the middleware. -func DecorateHandler(h Handler, with ...Middleware) Handler { - for i := len(with) - 1; i >= 0; i-- { - h = decoratedHandler{ - Next: h, - With: with[i], - } - } - - return h -} diff --git a/vendor/github.com/aws/smithy-go/middleware/ordered_group.go b/vendor/github.com/aws/smithy-go/middleware/ordered_group.go deleted file mode 100644 index 4b195308..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/ordered_group.go +++ /dev/null @@ -1,268 +0,0 @@ -package middleware - -import "fmt" - -// RelativePosition provides specifying the relative position of a middleware -// in an ordered group. -type RelativePosition int - -// Relative position for middleware in steps. -const ( - After RelativePosition = iota - Before -) - -type ider interface { - ID() string -} - -// orderedIDs provides an ordered collection of items with relative ordering -// by name. -type orderedIDs struct { - order *relativeOrder - items map[string]ider -} - -const baseOrderedItems = 5 - -func newOrderedIDs() *orderedIDs { - return &orderedIDs{ - order: newRelativeOrder(), - items: make(map[string]ider, baseOrderedItems), - } -} - -// Add injects the item to the relative position of the item group. Returns an -// error if the item already exists. -func (g *orderedIDs) Add(m ider, pos RelativePosition) error { - id := m.ID() - if len(id) == 0 { - return fmt.Errorf("empty ID, ID must not be empty") - } - - if err := g.order.Add(pos, id); err != nil { - return err - } - - g.items[id] = m - return nil -} - -// Insert injects the item relative to an existing item id. Returns an error if -// the original item does not exist, or the item being added already exists. -func (g *orderedIDs) Insert(m ider, relativeTo string, pos RelativePosition) error { - if len(m.ID()) == 0 { - return fmt.Errorf("insert ID must not be empty") - } - if len(relativeTo) == 0 { - return fmt.Errorf("relative to ID must not be empty") - } - - if err := g.order.Insert(relativeTo, pos, m.ID()); err != nil { - return err - } - - g.items[m.ID()] = m - return nil -} - -// Get returns the ider identified by id. If ider is not present, returns false. -func (g *orderedIDs) Get(id string) (ider, bool) { - v, ok := g.items[id] - return v, ok -} - -// Swap removes the item by id, replacing it with the new item. Returns an error -// if the original item doesn't exist. -func (g *orderedIDs) Swap(id string, m ider) (ider, error) { - if len(id) == 0 { - return nil, fmt.Errorf("swap from ID must not be empty") - } - - iderID := m.ID() - if len(iderID) == 0 { - return nil, fmt.Errorf("swap to ID must not be empty") - } - - if err := g.order.Swap(id, iderID); err != nil { - return nil, err - } - - removed := g.items[id] - - delete(g.items, id) - g.items[iderID] = m - - return removed, nil -} - -// Remove removes the item by id. Returns an error if the item -// doesn't exist. -func (g *orderedIDs) Remove(id string) (ider, error) { - if len(id) == 0 { - return nil, fmt.Errorf("remove ID must not be empty") - } - - if err := g.order.Remove(id); err != nil { - return nil, err - } - - removed := g.items[id] - delete(g.items, id) - return removed, nil -} - -func (g *orderedIDs) List() []string { - items := g.order.List() - order := make([]string, len(items)) - copy(order, items) - return order -} - -// Clear removes all entries and slots. -func (g *orderedIDs) Clear() { - g.order.Clear() - g.items = map[string]ider{} -} - -// GetOrder returns the item in the order it should be invoked in. -func (g *orderedIDs) GetOrder() []interface{} { - order := g.order.List() - ordered := make([]interface{}, len(order)) - for i := 0; i < len(order); i++ { - ordered[i] = g.items[order[i]] - } - - return ordered -} - -// relativeOrder provides ordering of item -type relativeOrder struct { - order []string -} - -func newRelativeOrder() *relativeOrder { - return &relativeOrder{ - order: make([]string, 0, baseOrderedItems), - } -} - -// Add inserts an item into the order relative to the position provided. -func (s *relativeOrder) Add(pos RelativePosition, ids ...string) error { - if len(ids) == 0 { - return nil - } - - for _, id := range ids { - if _, ok := s.has(id); ok { - return fmt.Errorf("already exists, %v", id) - } - } - - switch pos { - case Before: - return s.insert(0, Before, ids...) - - case After: - s.order = append(s.order, ids...) - - default: - return fmt.Errorf("invalid position, %v", int(pos)) - } - - return nil -} - -// Insert injects an item before or after the relative item. Returns -// an error if the relative item does not exist. -func (s *relativeOrder) Insert(relativeTo string, pos RelativePosition, ids ...string) error { - if len(ids) == 0 { - return nil - } - - for _, id := range ids { - if _, ok := s.has(id); ok { - return fmt.Errorf("already exists, %v", id) - } - } - - i, ok := s.has(relativeTo) - if !ok { - return fmt.Errorf("not found, %v", relativeTo) - } - - return s.insert(i, pos, ids...) -} - -// Swap will replace the item id with the to item. Returns an -// error if the original item id does not exist. Allows swapping out an -// item for another item with the same id. -func (s *relativeOrder) Swap(id, to string) error { - i, ok := s.has(id) - if !ok { - return fmt.Errorf("not found, %v", id) - } - - if _, ok = s.has(to); ok && id != to { - return fmt.Errorf("already exists, %v", to) - } - - s.order[i] = to - return nil -} - -func (s *relativeOrder) Remove(id string) error { - i, ok := s.has(id) - if !ok { - return fmt.Errorf("not found, %v", id) - } - - s.order = append(s.order[:i], s.order[i+1:]...) - return nil -} - -func (s *relativeOrder) List() []string { - return s.order -} - -func (s *relativeOrder) Clear() { - s.order = s.order[0:0] -} - -func (s *relativeOrder) insert(i int, pos RelativePosition, ids ...string) error { - switch pos { - case Before: - n := len(ids) - var src []string - if n <= cap(s.order)-len(s.order) { - s.order = s.order[:len(s.order)+n] - src = s.order - } else { - src = s.order - s.order = make([]string, len(s.order)+n) - copy(s.order[:i], src[:i]) // only when allocating a new slice do we need to copy the front half - } - copy(s.order[i+n:], src[i:]) - copy(s.order[i:], ids) - case After: - if i == len(s.order)-1 || len(s.order) == 0 { - s.order = append(s.order, ids...) - } else { - s.order = append(s.order[:i+1], append(ids, s.order[i+1:]...)...) - } - - default: - return fmt.Errorf("invalid position, %v", int(pos)) - } - - return nil -} - -func (s *relativeOrder) has(id string) (i int, found bool) { - for i := 0; i < len(s.order); i++ { - if s.order[i] == id { - return i, true - } - } - return 0, false -} diff --git a/vendor/github.com/aws/smithy-go/middleware/stack.go b/vendor/github.com/aws/smithy-go/middleware/stack.go deleted file mode 100644 index 45ccb5b9..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/stack.go +++ /dev/null @@ -1,209 +0,0 @@ -package middleware - -import ( - "context" - "io" - "strings" -) - -// Stack provides protocol and transport agnostic set of middleware split into -// distinct steps. Steps have specific transitions between them, that are -// managed by the individual step. -// -// Steps are composed as middleware around the underlying handler in the -// following order: -// -// Initialize -> Serialize -> Build -> Finalize -> Deserialize -> Handler -// -// Any middleware within the chain may choose to stop and return an error or -// response. Since the middleware decorate the handler like a call stack, each -// middleware will receive the result of the next middleware in the chain. -// Middleware that does not need to react to an input, or result must forward -// along the input down the chain, or return the result back up the chain. -// -// Initialize <- Serialize -> Build -> Finalize <- Deserialize <- Handler -type Stack struct { - // Initialize prepares the input, and sets any default parameters as - // needed, (e.g. idempotency token, and presigned URLs). - // - // Takes Input Parameters, and returns result or error. - // - // Receives result or error from Serialize step. - Initialize *InitializeStep - - // Serialize serializes the prepared input into a data structure that can be consumed - // by the target transport's message, (e.g. REST-JSON serialization) - // - // Converts Input Parameters into a Request, and returns the result or error. - // - // Receives result or error from Build step. - Serialize *SerializeStep - - // Build adds additional metadata to the serialized transport message - // (e.g. HTTP's Content-Length header, or body checksum). Decorations and - // modifications to the message should be copied to all message attempts. - // - // Takes Request, and returns result or error. - // - // Receives result or error from Finalize step. - Build *BuildStep - - // Finalize performs final preparations needed before sending the message. The - // message should already be complete by this stage, and is only alternated - // to meet the expectations of the recipient (e.g. Retry and AWS SigV4 - // request signing) - // - // Takes Request, and returns result or error. - // - // Receives result or error from Deserialize step. - Finalize *FinalizeStep - - // Deserialize reacts to the handler's response returned by the recipient of the request - // message. Deserializes the response into a structured type or error above - // stacks can react to. - // - // Should only forward Request to underlying handler. - // - // Takes Request, and returns result or error. - // - // Receives raw response, or error from underlying handler. - Deserialize *DeserializeStep - - id string -} - -// NewStack returns an initialize empty stack. -func NewStack(id string, newRequestFn func() interface{}) *Stack { - return &Stack{ - id: id, - Initialize: NewInitializeStep(), - Serialize: NewSerializeStep(newRequestFn), - Build: NewBuildStep(), - Finalize: NewFinalizeStep(), - Deserialize: NewDeserializeStep(), - } -} - -// ID returns the unique ID for the stack as a middleware. -func (s *Stack) ID() string { return s.id } - -// HandleMiddleware invokes the middleware stack decorating the next handler. -// Each step of stack will be invoked in order before calling the next step. -// With the next handler call last. -// -// The input value must be the input parameters of the operation being -// performed. -// -// Will return the result of the operation, or error. -func (s *Stack) HandleMiddleware(ctx context.Context, input interface{}, next Handler) ( - output interface{}, metadata Metadata, err error, -) { - h := DecorateHandler(next, - s.Initialize, - s.Serialize, - s.Build, - s.Finalize, - s.Deserialize, - ) - - return h.Handle(ctx, input) -} - -// List returns a list of all middleware in the stack by step. -func (s *Stack) List() []string { - var l []string - l = append(l, s.id) - - l = append(l, s.Initialize.ID()) - l = append(l, s.Initialize.List()...) - - l = append(l, s.Serialize.ID()) - l = append(l, s.Serialize.List()...) - - l = append(l, s.Build.ID()) - l = append(l, s.Build.List()...) - - l = append(l, s.Finalize.ID()) - l = append(l, s.Finalize.List()...) - - l = append(l, s.Deserialize.ID()) - l = append(l, s.Deserialize.List()...) - - return l -} - -func (s *Stack) String() string { - var b strings.Builder - - w := &indentWriter{w: &b} - - w.WriteLine(s.id) - w.Push() - - writeStepItems(w, s.Initialize) - writeStepItems(w, s.Serialize) - writeStepItems(w, s.Build) - writeStepItems(w, s.Finalize) - writeStepItems(w, s.Deserialize) - - return b.String() -} - -type stackStepper interface { - ID() string - List() []string -} - -func writeStepItems(w *indentWriter, s stackStepper) { - type lister interface { - List() []string - } - - w.WriteLine(s.ID()) - w.Push() - - defer w.Pop() - - // ignore stack to prevent circular iterations - if _, ok := s.(*Stack); ok { - return - } - - for _, id := range s.List() { - w.WriteLine(id) - } -} - -type stringWriter interface { - io.Writer - WriteString(string) (int, error) - WriteRune(rune) (int, error) -} - -type indentWriter struct { - w stringWriter - depth int -} - -const indentDepth = "\t\t\t\t\t\t\t\t\t\t" - -func (w *indentWriter) Push() { - w.depth++ -} - -func (w *indentWriter) Pop() { - w.depth-- - if w.depth < 0 { - w.depth = 0 - } -} - -func (w *indentWriter) WriteLine(v string) { - w.w.WriteString(indentDepth[:w.depth]) - - v = strings.ReplaceAll(v, "\n", "\\n") - v = strings.ReplaceAll(v, "\r", "\\r") - - w.w.WriteString(v) - w.w.WriteRune('\n') -} diff --git a/vendor/github.com/aws/smithy-go/middleware/stack_values.go b/vendor/github.com/aws/smithy-go/middleware/stack_values.go deleted file mode 100644 index ef96009b..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/stack_values.go +++ /dev/null @@ -1,100 +0,0 @@ -package middleware - -import ( - "context" - "reflect" - "strings" -) - -// WithStackValue adds a key value pair to the context that is intended to be -// scoped to a stack. Use ClearStackValues to get a new context with all stack -// values cleared. -func WithStackValue(ctx context.Context, key, value interface{}) context.Context { - md, _ := ctx.Value(stackValuesKey{}).(*stackValues) - - md = withStackValue(md, key, value) - return context.WithValue(ctx, stackValuesKey{}, md) -} - -// ClearStackValues returns a context without any stack values. -func ClearStackValues(ctx context.Context) context.Context { - return context.WithValue(ctx, stackValuesKey{}, nil) -} - -// GetStackValues returns the value pointed to by the key within the stack -// values, if it is present. -func GetStackValue(ctx context.Context, key interface{}) interface{} { - md, _ := ctx.Value(stackValuesKey{}).(*stackValues) - if md == nil { - return nil - } - - return md.Value(key) -} - -type stackValuesKey struct{} - -type stackValues struct { - key interface{} - value interface{} - parent *stackValues -} - -func withStackValue(parent *stackValues, key, value interface{}) *stackValues { - if key == nil { - panic("nil key") - } - if !reflect.TypeOf(key).Comparable() { - panic("key is not comparable") - } - return &stackValues{key: key, value: value, parent: parent} -} - -func (m *stackValues) Value(key interface{}) interface{} { - if key == m.key { - return m.value - } - - if m.parent == nil { - return nil - } - - return m.parent.Value(key) -} - -func (c *stackValues) String() string { - var str strings.Builder - - cc := c - for cc == nil { - str.WriteString("(" + - reflect.TypeOf(c.key).String() + - ": " + - stringify(cc.value) + - ")") - if cc.parent != nil { - str.WriteString(" -> ") - } - cc = cc.parent - } - str.WriteRune('}') - - return str.String() -} - -type stringer interface { - String() string -} - -// stringify tries a bit to stringify v, without using fmt, since we don't -// want context depending on the unicode tables. This is only used by -// *valueCtx.String(). -func stringify(v interface{}) string { - switch s := v.(type) { - case stringer: - return s.String() - case string: - return s - } - return "" -} diff --git a/vendor/github.com/aws/smithy-go/middleware/step_build.go b/vendor/github.com/aws/smithy-go/middleware/step_build.go deleted file mode 100644 index 7e1d94ca..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/step_build.go +++ /dev/null @@ -1,211 +0,0 @@ -package middleware - -import ( - "context" -) - -// BuildInput provides the input parameters for the BuildMiddleware to consume. -// BuildMiddleware may modify the Request value before forwarding the input -// along to the next BuildHandler. -type BuildInput struct { - Request interface{} -} - -// BuildOutput provides the result returned by the next BuildHandler. -type BuildOutput struct { - Result interface{} -} - -// BuildHandler provides the interface for the next handler the -// BuildMiddleware will call in the middleware chain. -type BuildHandler interface { - HandleBuild(ctx context.Context, in BuildInput) ( - out BuildOutput, metadata Metadata, err error, - ) -} - -// BuildMiddleware provides the interface for middleware specific to the -// serialize step. Delegates to the next BuildHandler for further -// processing. -type BuildMiddleware interface { - // Unique ID for the middleware in theBuildStep. The step does not allow - // duplicate IDs. - ID() string - - // Invokes the middleware behavior which must delegate to the next handler - // for the middleware chain to continue. The method must return a result or - // error to its caller. - HandleBuild(ctx context.Context, in BuildInput, next BuildHandler) ( - out BuildOutput, metadata Metadata, err error, - ) -} - -// BuildMiddlewareFunc returns a BuildMiddleware with the unique ID provided, -// and the func to be invoked. -func BuildMiddlewareFunc(id string, fn func(context.Context, BuildInput, BuildHandler) (BuildOutput, Metadata, error)) BuildMiddleware { - return buildMiddlewareFunc{ - id: id, - fn: fn, - } -} - -type buildMiddlewareFunc struct { - // Unique ID for the middleware. - id string - - // Middleware function to be called. - fn func(context.Context, BuildInput, BuildHandler) (BuildOutput, Metadata, error) -} - -// ID returns the unique ID for the middleware. -func (s buildMiddlewareFunc) ID() string { return s.id } - -// HandleBuild invokes the middleware Fn. -func (s buildMiddlewareFunc) HandleBuild(ctx context.Context, in BuildInput, next BuildHandler) ( - out BuildOutput, metadata Metadata, err error, -) { - return s.fn(ctx, in, next) -} - -var _ BuildMiddleware = (buildMiddlewareFunc{}) - -// BuildStep provides the ordered grouping of BuildMiddleware to be invoked on -// a handler. -type BuildStep struct { - ids *orderedIDs -} - -// NewBuildStep returns a BuildStep ready to have middleware for -// initialization added to it. -func NewBuildStep() *BuildStep { - return &BuildStep{ - ids: newOrderedIDs(), - } -} - -var _ Middleware = (*BuildStep)(nil) - -// ID returns the unique name of the step as a middleware. -func (s *BuildStep) ID() string { - return "Build stack step" -} - -// HandleMiddleware invokes the middleware by decorating the next handler -// provided. Returns the result of the middleware and handler being invoked. -// -// Implements Middleware interface. -func (s *BuildStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( - out interface{}, metadata Metadata, err error, -) { - order := s.ids.GetOrder() - - var h BuildHandler = buildWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedBuildHandler{ - Next: h, - With: order[i].(BuildMiddleware), - } - } - - sIn := BuildInput{ - Request: in, - } - - res, metadata, err := h.HandleBuild(ctx, sIn) - return res.Result, metadata, err -} - -// Get retrieves the middleware identified by id. If the middleware is not present, returns false. -func (s *BuildStep) Get(id string) (BuildMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { - return nil, false - } - return get.(BuildMiddleware), ok -} - -// Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. -func (s *BuildStep) Add(m BuildMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) -} - -// Insert injects the middleware relative to an existing middleware id. -// Returns an error if the original middleware does not exist, or the middleware -// being added already exists. -func (s *BuildStep) Insert(m BuildMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) -} - -// Swap removes the middleware by id, replacing it with the new middleware. -// Returns the middleware removed, or an error if the middleware to be removed -// doesn't exist. -func (s *BuildStep) Swap(id string, m BuildMiddleware) (BuildMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err - } - - return removed.(BuildMiddleware), nil -} - -// Remove removes the middleware by id. Returns error if the middleware -// doesn't exist. -func (s *BuildStep) Remove(id string) (BuildMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err - } - - return removed.(BuildMiddleware), nil -} - -// List returns a list of the middleware in the step. -func (s *BuildStep) List() []string { - return s.ids.List() -} - -// Clear removes all middleware in the step. -func (s *BuildStep) Clear() { - s.ids.Clear() -} - -type buildWrapHandler struct { - Next Handler -} - -var _ BuildHandler = (*buildWrapHandler)(nil) - -// Implements BuildHandler, converts types and delegates to underlying -// generic handler. -func (w buildWrapHandler) HandleBuild(ctx context.Context, in BuildInput) ( - out BuildOutput, metadata Metadata, err error, -) { - res, metadata, err := w.Next.Handle(ctx, in.Request) - return BuildOutput{ - Result: res, - }, metadata, err -} - -type decoratedBuildHandler struct { - Next BuildHandler - With BuildMiddleware -} - -var _ BuildHandler = (*decoratedBuildHandler)(nil) - -func (h decoratedBuildHandler) HandleBuild(ctx context.Context, in BuildInput) ( - out BuildOutput, metadata Metadata, err error, -) { - return h.With.HandleBuild(ctx, in, h.Next) -} - -// BuildHandlerFunc provides a wrapper around a function to be used as a build middleware handler. -type BuildHandlerFunc func(context.Context, BuildInput) (BuildOutput, Metadata, error) - -// HandleBuild invokes the wrapped function with the provided arguments. -func (b BuildHandlerFunc) HandleBuild(ctx context.Context, in BuildInput) (BuildOutput, Metadata, error) { - return b(ctx, in) -} - -var _ BuildHandler = BuildHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/middleware/step_deserialize.go b/vendor/github.com/aws/smithy-go/middleware/step_deserialize.go deleted file mode 100644 index 44860721..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/step_deserialize.go +++ /dev/null @@ -1,217 +0,0 @@ -package middleware - -import ( - "context" -) - -// DeserializeInput provides the input parameters for the DeserializeInput to -// consume. DeserializeMiddleware should not modify the Request, and instead -// forward it along to the next DeserializeHandler. -type DeserializeInput struct { - Request interface{} -} - -// DeserializeOutput provides the result returned by the next -// DeserializeHandler. The DeserializeMiddleware should deserialize the -// RawResponse into a Result that can be consumed by middleware higher up in -// the stack. -type DeserializeOutput struct { - RawResponse interface{} - Result interface{} -} - -// DeserializeHandler provides the interface for the next handler the -// DeserializeMiddleware will call in the middleware chain. -type DeserializeHandler interface { - HandleDeserialize(ctx context.Context, in DeserializeInput) ( - out DeserializeOutput, metadata Metadata, err error, - ) -} - -// DeserializeMiddleware provides the interface for middleware specific to the -// serialize step. Delegates to the next DeserializeHandler for further -// processing. -type DeserializeMiddleware interface { - // ID returns a unique ID for the middleware in the DeserializeStep. The step does not - // allow duplicate IDs. - ID() string - - // HandleDeserialize invokes the middleware behavior which must delegate to the next handler - // for the middleware chain to continue. The method must return a result or - // error to its caller. - HandleDeserialize(ctx context.Context, in DeserializeInput, next DeserializeHandler) ( - out DeserializeOutput, metadata Metadata, err error, - ) -} - -// DeserializeMiddlewareFunc returns a DeserializeMiddleware with the unique ID -// provided, and the func to be invoked. -func DeserializeMiddlewareFunc(id string, fn func(context.Context, DeserializeInput, DeserializeHandler) (DeserializeOutput, Metadata, error)) DeserializeMiddleware { - return deserializeMiddlewareFunc{ - id: id, - fn: fn, - } -} - -type deserializeMiddlewareFunc struct { - // Unique ID for the middleware. - id string - - // Middleware function to be called. - fn func(context.Context, DeserializeInput, DeserializeHandler) ( - DeserializeOutput, Metadata, error, - ) -} - -// ID returns the unique ID for the middleware. -func (s deserializeMiddlewareFunc) ID() string { return s.id } - -// HandleDeserialize invokes the middleware Fn. -func (s deserializeMiddlewareFunc) HandleDeserialize(ctx context.Context, in DeserializeInput, next DeserializeHandler) ( - out DeserializeOutput, metadata Metadata, err error, -) { - return s.fn(ctx, in, next) -} - -var _ DeserializeMiddleware = (deserializeMiddlewareFunc{}) - -// DeserializeStep provides the ordered grouping of DeserializeMiddleware to be -// invoked on a handler. -type DeserializeStep struct { - ids *orderedIDs -} - -// NewDeserializeStep returns a DeserializeStep ready to have middleware for -// initialization added to it. -func NewDeserializeStep() *DeserializeStep { - return &DeserializeStep{ - ids: newOrderedIDs(), - } -} - -var _ Middleware = (*DeserializeStep)(nil) - -// ID returns the unique ID of the step as a middleware. -func (s *DeserializeStep) ID() string { - return "Deserialize stack step" -} - -// HandleMiddleware invokes the middleware by decorating the next handler -// provided. Returns the result of the middleware and handler being invoked. -// -// Implements Middleware interface. -func (s *DeserializeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( - out interface{}, metadata Metadata, err error, -) { - order := s.ids.GetOrder() - - var h DeserializeHandler = deserializeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedDeserializeHandler{ - Next: h, - With: order[i].(DeserializeMiddleware), - } - } - - sIn := DeserializeInput{ - Request: in, - } - - res, metadata, err := h.HandleDeserialize(ctx, sIn) - return res.Result, metadata, err -} - -// Get retrieves the middleware identified by id. If the middleware is not present, returns false. -func (s *DeserializeStep) Get(id string) (DeserializeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { - return nil, false - } - return get.(DeserializeMiddleware), ok -} - -// Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. -func (s *DeserializeStep) Add(m DeserializeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) -} - -// Insert injects the middleware relative to an existing middleware ID. -// Returns error if the original middleware does not exist, or the middleware -// being added already exists. -func (s *DeserializeStep) Insert(m DeserializeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) -} - -// Swap removes the middleware by id, replacing it with the new middleware. -// Returns the middleware removed, or error if the middleware to be removed -// doesn't exist. -func (s *DeserializeStep) Swap(id string, m DeserializeMiddleware) (DeserializeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err - } - - return removed.(DeserializeMiddleware), nil -} - -// Remove removes the middleware by id. Returns error if the middleware -// doesn't exist. -func (s *DeserializeStep) Remove(id string) (DeserializeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err - } - - return removed.(DeserializeMiddleware), nil -} - -// List returns a list of the middleware in the step. -func (s *DeserializeStep) List() []string { - return s.ids.List() -} - -// Clear removes all middleware in the step. -func (s *DeserializeStep) Clear() { - s.ids.Clear() -} - -type deserializeWrapHandler struct { - Next Handler -} - -var _ DeserializeHandler = (*deserializeWrapHandler)(nil) - -// HandleDeserialize implements DeserializeHandler, converts types and delegates to underlying -// generic handler. -func (w deserializeWrapHandler) HandleDeserialize(ctx context.Context, in DeserializeInput) ( - out DeserializeOutput, metadata Metadata, err error, -) { - resp, metadata, err := w.Next.Handle(ctx, in.Request) - return DeserializeOutput{ - RawResponse: resp, - }, metadata, err -} - -type decoratedDeserializeHandler struct { - Next DeserializeHandler - With DeserializeMiddleware -} - -var _ DeserializeHandler = (*decoratedDeserializeHandler)(nil) - -func (h decoratedDeserializeHandler) HandleDeserialize(ctx context.Context, in DeserializeInput) ( - out DeserializeOutput, metadata Metadata, err error, -) { - return h.With.HandleDeserialize(ctx, in, h.Next) -} - -// DeserializeHandlerFunc provides a wrapper around a function to be used as a deserialize middleware handler. -type DeserializeHandlerFunc func(context.Context, DeserializeInput) (DeserializeOutput, Metadata, error) - -// HandleDeserialize invokes the wrapped function with the given arguments. -func (d DeserializeHandlerFunc) HandleDeserialize(ctx context.Context, in DeserializeInput) (DeserializeOutput, Metadata, error) { - return d(ctx, in) -} - -var _ DeserializeHandler = DeserializeHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/middleware/step_finalize.go b/vendor/github.com/aws/smithy-go/middleware/step_finalize.go deleted file mode 100644 index 065e3885..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/step_finalize.go +++ /dev/null @@ -1,211 +0,0 @@ -package middleware - -import "context" - -// FinalizeInput provides the input parameters for the FinalizeMiddleware to -// consume. FinalizeMiddleware may modify the Request value before forwarding -// the FinalizeInput along to the next next FinalizeHandler. -type FinalizeInput struct { - Request interface{} -} - -// FinalizeOutput provides the result returned by the next FinalizeHandler. -type FinalizeOutput struct { - Result interface{} -} - -// FinalizeHandler provides the interface for the next handler the -// FinalizeMiddleware will call in the middleware chain. -type FinalizeHandler interface { - HandleFinalize(ctx context.Context, in FinalizeInput) ( - out FinalizeOutput, metadata Metadata, err error, - ) -} - -// FinalizeMiddleware provides the interface for middleware specific to the -// serialize step. Delegates to the next FinalizeHandler for further -// processing. -type FinalizeMiddleware interface { - // ID returns a unique ID for the middleware in the FinalizeStep. The step does not - // allow duplicate IDs. - ID() string - - // HandleFinalize invokes the middleware behavior which must delegate to the next handler - // for the middleware chain to continue. The method must return a result or - // error to its caller. - HandleFinalize(ctx context.Context, in FinalizeInput, next FinalizeHandler) ( - out FinalizeOutput, metadata Metadata, err error, - ) -} - -// FinalizeMiddlewareFunc returns a FinalizeMiddleware with the unique ID -// provided, and the func to be invoked. -func FinalizeMiddlewareFunc(id string, fn func(context.Context, FinalizeInput, FinalizeHandler) (FinalizeOutput, Metadata, error)) FinalizeMiddleware { - return finalizeMiddlewareFunc{ - id: id, - fn: fn, - } -} - -type finalizeMiddlewareFunc struct { - // Unique ID for the middleware. - id string - - // Middleware function to be called. - fn func(context.Context, FinalizeInput, FinalizeHandler) ( - FinalizeOutput, Metadata, error, - ) -} - -// ID returns the unique ID for the middleware. -func (s finalizeMiddlewareFunc) ID() string { return s.id } - -// HandleFinalize invokes the middleware Fn. -func (s finalizeMiddlewareFunc) HandleFinalize(ctx context.Context, in FinalizeInput, next FinalizeHandler) ( - out FinalizeOutput, metadata Metadata, err error, -) { - return s.fn(ctx, in, next) -} - -var _ FinalizeMiddleware = (finalizeMiddlewareFunc{}) - -// FinalizeStep provides the ordered grouping of FinalizeMiddleware to be -// invoked on a handler. -type FinalizeStep struct { - ids *orderedIDs -} - -// NewFinalizeStep returns a FinalizeStep ready to have middleware for -// initialization added to it. -func NewFinalizeStep() *FinalizeStep { - return &FinalizeStep{ - ids: newOrderedIDs(), - } -} - -var _ Middleware = (*FinalizeStep)(nil) - -// ID returns the unique id of the step as a middleware. -func (s *FinalizeStep) ID() string { - return "Finalize stack step" -} - -// HandleMiddleware invokes the middleware by decorating the next handler -// provided. Returns the result of the middleware and handler being invoked. -// -// Implements Middleware interface. -func (s *FinalizeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( - out interface{}, metadata Metadata, err error, -) { - order := s.ids.GetOrder() - - var h FinalizeHandler = finalizeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedFinalizeHandler{ - Next: h, - With: order[i].(FinalizeMiddleware), - } - } - - sIn := FinalizeInput{ - Request: in, - } - - res, metadata, err := h.HandleFinalize(ctx, sIn) - return res.Result, metadata, err -} - -// Get retrieves the middleware identified by id. If the middleware is not present, returns false. -func (s *FinalizeStep) Get(id string) (FinalizeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { - return nil, false - } - return get.(FinalizeMiddleware), ok -} - -// Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. -func (s *FinalizeStep) Add(m FinalizeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) -} - -// Insert injects the middleware relative to an existing middleware ID. -// Returns error if the original middleware does not exist, or the middleware -// being added already exists. -func (s *FinalizeStep) Insert(m FinalizeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) -} - -// Swap removes the middleware by id, replacing it with the new middleware. -// Returns the middleware removed, or error if the middleware to be removed -// doesn't exist. -func (s *FinalizeStep) Swap(id string, m FinalizeMiddleware) (FinalizeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err - } - - return removed.(FinalizeMiddleware), nil -} - -// Remove removes the middleware by id. Returns error if the middleware -// doesn't exist. -func (s *FinalizeStep) Remove(id string) (FinalizeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err - } - - return removed.(FinalizeMiddleware), nil -} - -// List returns a list of the middleware in the step. -func (s *FinalizeStep) List() []string { - return s.ids.List() -} - -// Clear removes all middleware in the step. -func (s *FinalizeStep) Clear() { - s.ids.Clear() -} - -type finalizeWrapHandler struct { - Next Handler -} - -var _ FinalizeHandler = (*finalizeWrapHandler)(nil) - -// HandleFinalize implements FinalizeHandler, converts types and delegates to underlying -// generic handler. -func (w finalizeWrapHandler) HandleFinalize(ctx context.Context, in FinalizeInput) ( - out FinalizeOutput, metadata Metadata, err error, -) { - res, metadata, err := w.Next.Handle(ctx, in.Request) - return FinalizeOutput{ - Result: res, - }, metadata, err -} - -type decoratedFinalizeHandler struct { - Next FinalizeHandler - With FinalizeMiddleware -} - -var _ FinalizeHandler = (*decoratedFinalizeHandler)(nil) - -func (h decoratedFinalizeHandler) HandleFinalize(ctx context.Context, in FinalizeInput) ( - out FinalizeOutput, metadata Metadata, err error, -) { - return h.With.HandleFinalize(ctx, in, h.Next) -} - -// FinalizeHandlerFunc provides a wrapper around a function to be used as a finalize middleware handler. -type FinalizeHandlerFunc func(context.Context, FinalizeInput) (FinalizeOutput, Metadata, error) - -// HandleFinalize invokes the wrapped function with the given arguments. -func (f FinalizeHandlerFunc) HandleFinalize(ctx context.Context, in FinalizeInput) (FinalizeOutput, Metadata, error) { - return f(ctx, in) -} - -var _ FinalizeHandler = FinalizeHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/middleware/step_initialize.go b/vendor/github.com/aws/smithy-go/middleware/step_initialize.go deleted file mode 100644 index fe359144..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/step_initialize.go +++ /dev/null @@ -1,211 +0,0 @@ -package middleware - -import "context" - -// InitializeInput wraps the input parameters for the InitializeMiddlewares to -// consume. InitializeMiddleware may modify the parameter value before -// forwarding it along to the next InitializeHandler. -type InitializeInput struct { - Parameters interface{} -} - -// InitializeOutput provides the result returned by the next InitializeHandler. -type InitializeOutput struct { - Result interface{} -} - -// InitializeHandler provides the interface for the next handler the -// InitializeMiddleware will call in the middleware chain. -type InitializeHandler interface { - HandleInitialize(ctx context.Context, in InitializeInput) ( - out InitializeOutput, metadata Metadata, err error, - ) -} - -// InitializeMiddleware provides the interface for middleware specific to the -// initialize step. Delegates to the next InitializeHandler for further -// processing. -type InitializeMiddleware interface { - // ID returns a unique ID for the middleware in the InitializeStep. The step does not - // allow duplicate IDs. - ID() string - - // HandleInitialize invokes the middleware behavior which must delegate to the next handler - // for the middleware chain to continue. The method must return a result or - // error to its caller. - HandleInitialize(ctx context.Context, in InitializeInput, next InitializeHandler) ( - out InitializeOutput, metadata Metadata, err error, - ) -} - -// InitializeMiddlewareFunc returns a InitializeMiddleware with the unique ID provided, -// and the func to be invoked. -func InitializeMiddlewareFunc(id string, fn func(context.Context, InitializeInput, InitializeHandler) (InitializeOutput, Metadata, error)) InitializeMiddleware { - return initializeMiddlewareFunc{ - id: id, - fn: fn, - } -} - -type initializeMiddlewareFunc struct { - // Unique ID for the middleware. - id string - - // Middleware function to be called. - fn func(context.Context, InitializeInput, InitializeHandler) ( - InitializeOutput, Metadata, error, - ) -} - -// ID returns the unique ID for the middleware. -func (s initializeMiddlewareFunc) ID() string { return s.id } - -// HandleInitialize invokes the middleware Fn. -func (s initializeMiddlewareFunc) HandleInitialize(ctx context.Context, in InitializeInput, next InitializeHandler) ( - out InitializeOutput, metadata Metadata, err error, -) { - return s.fn(ctx, in, next) -} - -var _ InitializeMiddleware = (initializeMiddlewareFunc{}) - -// InitializeStep provides the ordered grouping of InitializeMiddleware to be -// invoked on a handler. -type InitializeStep struct { - ids *orderedIDs -} - -// NewInitializeStep returns an InitializeStep ready to have middleware for -// initialization added to it. -func NewInitializeStep() *InitializeStep { - return &InitializeStep{ - ids: newOrderedIDs(), - } -} - -var _ Middleware = (*InitializeStep)(nil) - -// ID returns the unique ID of the step as a middleware. -func (s *InitializeStep) ID() string { - return "Initialize stack step" -} - -// HandleMiddleware invokes the middleware by decorating the next handler -// provided. Returns the result of the middleware and handler being invoked. -// -// Implements Middleware interface. -func (s *InitializeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( - out interface{}, metadata Metadata, err error, -) { - order := s.ids.GetOrder() - - var h InitializeHandler = initializeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedInitializeHandler{ - Next: h, - With: order[i].(InitializeMiddleware), - } - } - - sIn := InitializeInput{ - Parameters: in, - } - - res, metadata, err := h.HandleInitialize(ctx, sIn) - return res.Result, metadata, err -} - -// Get retrieves the middleware identified by id. If the middleware is not present, returns false. -func (s *InitializeStep) Get(id string) (InitializeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { - return nil, false - } - return get.(InitializeMiddleware), ok -} - -// Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. -func (s *InitializeStep) Add(m InitializeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) -} - -// Insert injects the middleware relative to an existing middleware ID. -// Returns error if the original middleware does not exist, or the middleware -// being added already exists. -func (s *InitializeStep) Insert(m InitializeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) -} - -// Swap removes the middleware by id, replacing it with the new middleware. -// Returns the middleware removed, or error if the middleware to be removed -// doesn't exist. -func (s *InitializeStep) Swap(id string, m InitializeMiddleware) (InitializeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err - } - - return removed.(InitializeMiddleware), nil -} - -// Remove removes the middleware by id. Returns error if the middleware -// doesn't exist. -func (s *InitializeStep) Remove(id string) (InitializeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err - } - - return removed.(InitializeMiddleware), nil -} - -// List returns a list of the middleware in the step. -func (s *InitializeStep) List() []string { - return s.ids.List() -} - -// Clear removes all middleware in the step. -func (s *InitializeStep) Clear() { - s.ids.Clear() -} - -type initializeWrapHandler struct { - Next Handler -} - -var _ InitializeHandler = (*initializeWrapHandler)(nil) - -// HandleInitialize implements InitializeHandler, converts types and delegates to underlying -// generic handler. -func (w initializeWrapHandler) HandleInitialize(ctx context.Context, in InitializeInput) ( - out InitializeOutput, metadata Metadata, err error, -) { - res, metadata, err := w.Next.Handle(ctx, in.Parameters) - return InitializeOutput{ - Result: res, - }, metadata, err -} - -type decoratedInitializeHandler struct { - Next InitializeHandler - With InitializeMiddleware -} - -var _ InitializeHandler = (*decoratedInitializeHandler)(nil) - -func (h decoratedInitializeHandler) HandleInitialize(ctx context.Context, in InitializeInput) ( - out InitializeOutput, metadata Metadata, err error, -) { - return h.With.HandleInitialize(ctx, in, h.Next) -} - -// InitializeHandlerFunc provides a wrapper around a function to be used as an initialize middleware handler. -type InitializeHandlerFunc func(context.Context, InitializeInput) (InitializeOutput, Metadata, error) - -// HandleInitialize calls the wrapped function with the provided arguments. -func (i InitializeHandlerFunc) HandleInitialize(ctx context.Context, in InitializeInput) (InitializeOutput, Metadata, error) { - return i(ctx, in) -} - -var _ InitializeHandler = InitializeHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/middleware/step_serialize.go b/vendor/github.com/aws/smithy-go/middleware/step_serialize.go deleted file mode 100644 index 114bafce..00000000 --- a/vendor/github.com/aws/smithy-go/middleware/step_serialize.go +++ /dev/null @@ -1,219 +0,0 @@ -package middleware - -import "context" - -// SerializeInput provides the input parameters for the SerializeMiddleware to -// consume. SerializeMiddleware may modify the Request value before forwarding -// SerializeInput along to the next SerializeHandler. The Parameters member -// should not be modified by SerializeMiddleware, InitializeMiddleware should -// be responsible for modifying the provided Parameter value. -type SerializeInput struct { - Parameters interface{} - Request interface{} -} - -// SerializeOutput provides the result returned by the next SerializeHandler. -type SerializeOutput struct { - Result interface{} -} - -// SerializeHandler provides the interface for the next handler the -// SerializeMiddleware will call in the middleware chain. -type SerializeHandler interface { - HandleSerialize(ctx context.Context, in SerializeInput) ( - out SerializeOutput, metadata Metadata, err error, - ) -} - -// SerializeMiddleware provides the interface for middleware specific to the -// serialize step. Delegates to the next SerializeHandler for further -// processing. -type SerializeMiddleware interface { - // ID returns a unique ID for the middleware in the SerializeStep. The step does not - // allow duplicate IDs. - ID() string - - // HandleSerialize invokes the middleware behavior which must delegate to the next handler - // for the middleware chain to continue. The method must return a result or - // error to its caller. - HandleSerialize(ctx context.Context, in SerializeInput, next SerializeHandler) ( - out SerializeOutput, metadata Metadata, err error, - ) -} - -// SerializeMiddlewareFunc returns a SerializeMiddleware with the unique ID -// provided, and the func to be invoked. -func SerializeMiddlewareFunc(id string, fn func(context.Context, SerializeInput, SerializeHandler) (SerializeOutput, Metadata, error)) SerializeMiddleware { - return serializeMiddlewareFunc{ - id: id, - fn: fn, - } -} - -type serializeMiddlewareFunc struct { - // Unique ID for the middleware. - id string - - // Middleware function to be called. - fn func(context.Context, SerializeInput, SerializeHandler) ( - SerializeOutput, Metadata, error, - ) -} - -// ID returns the unique ID for the middleware. -func (s serializeMiddlewareFunc) ID() string { return s.id } - -// HandleSerialize invokes the middleware Fn. -func (s serializeMiddlewareFunc) HandleSerialize(ctx context.Context, in SerializeInput, next SerializeHandler) ( - out SerializeOutput, metadata Metadata, err error, -) { - return s.fn(ctx, in, next) -} - -var _ SerializeMiddleware = (serializeMiddlewareFunc{}) - -// SerializeStep provides the ordered grouping of SerializeMiddleware to be -// invoked on a handler. -type SerializeStep struct { - newRequest func() interface{} - ids *orderedIDs -} - -// NewSerializeStep returns a SerializeStep ready to have middleware for -// initialization added to it. The newRequest func parameter is used to -// initialize the transport specific request for the stack SerializeStep to -// serialize the input parameters into. -func NewSerializeStep(newRequest func() interface{}) *SerializeStep { - return &SerializeStep{ - ids: newOrderedIDs(), - newRequest: newRequest, - } -} - -var _ Middleware = (*SerializeStep)(nil) - -// ID returns the unique ID of the step as a middleware. -func (s *SerializeStep) ID() string { - return "Serialize stack step" -} - -// HandleMiddleware invokes the middleware by decorating the next handler -// provided. Returns the result of the middleware and handler being invoked. -// -// Implements Middleware interface. -func (s *SerializeStep) HandleMiddleware(ctx context.Context, in interface{}, next Handler) ( - out interface{}, metadata Metadata, err error, -) { - order := s.ids.GetOrder() - - var h SerializeHandler = serializeWrapHandler{Next: next} - for i := len(order) - 1; i >= 0; i-- { - h = decoratedSerializeHandler{ - Next: h, - With: order[i].(SerializeMiddleware), - } - } - - sIn := SerializeInput{ - Parameters: in, - Request: s.newRequest(), - } - - res, metadata, err := h.HandleSerialize(ctx, sIn) - return res.Result, metadata, err -} - -// Get retrieves the middleware identified by id. If the middleware is not present, returns false. -func (s *SerializeStep) Get(id string) (SerializeMiddleware, bool) { - get, ok := s.ids.Get(id) - if !ok { - return nil, false - } - return get.(SerializeMiddleware), ok -} - -// Add injects the middleware to the relative position of the middleware group. -// Returns an error if the middleware already exists. -func (s *SerializeStep) Add(m SerializeMiddleware, pos RelativePosition) error { - return s.ids.Add(m, pos) -} - -// Insert injects the middleware relative to an existing middleware ID. -// Returns error if the original middleware does not exist, or the middleware -// being added already exists. -func (s *SerializeStep) Insert(m SerializeMiddleware, relativeTo string, pos RelativePosition) error { - return s.ids.Insert(m, relativeTo, pos) -} - -// Swap removes the middleware by id, replacing it with the new middleware. -// Returns the middleware removed, or error if the middleware to be removed -// doesn't exist. -func (s *SerializeStep) Swap(id string, m SerializeMiddleware) (SerializeMiddleware, error) { - removed, err := s.ids.Swap(id, m) - if err != nil { - return nil, err - } - - return removed.(SerializeMiddleware), nil -} - -// Remove removes the middleware by id. Returns error if the middleware -// doesn't exist. -func (s *SerializeStep) Remove(id string) (SerializeMiddleware, error) { - removed, err := s.ids.Remove(id) - if err != nil { - return nil, err - } - - return removed.(SerializeMiddleware), nil -} - -// List returns a list of the middleware in the step. -func (s *SerializeStep) List() []string { - return s.ids.List() -} - -// Clear removes all middleware in the step. -func (s *SerializeStep) Clear() { - s.ids.Clear() -} - -type serializeWrapHandler struct { - Next Handler -} - -var _ SerializeHandler = (*serializeWrapHandler)(nil) - -// Implements SerializeHandler, converts types and delegates to underlying -// generic handler. -func (w serializeWrapHandler) HandleSerialize(ctx context.Context, in SerializeInput) ( - out SerializeOutput, metadata Metadata, err error, -) { - res, metadata, err := w.Next.Handle(ctx, in.Request) - return SerializeOutput{ - Result: res, - }, metadata, err -} - -type decoratedSerializeHandler struct { - Next SerializeHandler - With SerializeMiddleware -} - -var _ SerializeHandler = (*decoratedSerializeHandler)(nil) - -func (h decoratedSerializeHandler) HandleSerialize(ctx context.Context, in SerializeInput) ( - out SerializeOutput, metadata Metadata, err error, -) { - return h.With.HandleSerialize(ctx, in, h.Next) -} - -// SerializeHandlerFunc provides a wrapper around a function to be used as a serialize middleware handler. -type SerializeHandlerFunc func(context.Context, SerializeInput) (SerializeOutput, Metadata, error) - -// HandleSerialize calls the wrapped function with the provided arguments. -func (s SerializeHandlerFunc) HandleSerialize(ctx context.Context, in SerializeInput) (SerializeOutput, Metadata, error) { - return s(ctx, in) -} - -var _ SerializeHandler = SerializeHandlerFunc(nil) diff --git a/vendor/github.com/aws/smithy-go/modman.toml b/vendor/github.com/aws/smithy-go/modman.toml deleted file mode 100644 index 20295cdd..00000000 --- a/vendor/github.com/aws/smithy-go/modman.toml +++ /dev/null @@ -1,11 +0,0 @@ -[dependencies] - "github.com/google/go-cmp" = "v0.5.8" - "github.com/jmespath/go-jmespath" = "v0.4.0" - -[modules] - - [modules.codegen] - no_tag = true - - [modules."codegen/smithy-go-codegen/build/test-generated/go/internal/testmodule"] - no_tag = true diff --git a/vendor/github.com/aws/smithy-go/private/requestcompression/gzip.go b/vendor/github.com/aws/smithy-go/private/requestcompression/gzip.go deleted file mode 100644 index 004d78f2..00000000 --- a/vendor/github.com/aws/smithy-go/private/requestcompression/gzip.go +++ /dev/null @@ -1,30 +0,0 @@ -package requestcompression - -import ( - "bytes" - "compress/gzip" - "fmt" - "io" -) - -func gzipCompress(input io.Reader) ([]byte, error) { - var b bytes.Buffer - w, err := gzip.NewWriterLevel(&b, gzip.DefaultCompression) - if err != nil { - return nil, fmt.Errorf("failed to create gzip writer, %v", err) - } - - inBytes, err := io.ReadAll(input) - if err != nil { - return nil, fmt.Errorf("failed read payload to compress, %v", err) - } - - if _, err = w.Write(inBytes); err != nil { - return nil, fmt.Errorf("failed to write payload to be compressed, %v", err) - } - if err = w.Close(); err != nil { - return nil, fmt.Errorf("failed to flush payload being compressed, %v", err) - } - - return b.Bytes(), nil -} diff --git a/vendor/github.com/aws/smithy-go/private/requestcompression/middleware_capture_request_compression.go b/vendor/github.com/aws/smithy-go/private/requestcompression/middleware_capture_request_compression.go deleted file mode 100644 index 06c16afc..00000000 --- a/vendor/github.com/aws/smithy-go/private/requestcompression/middleware_capture_request_compression.go +++ /dev/null @@ -1,52 +0,0 @@ -package requestcompression - -import ( - "bytes" - "context" - "fmt" - "github.com/aws/smithy-go/middleware" - smithyhttp "github.com/aws/smithy-go/transport/http" - "io" - "net/http" -) - -const captureUncompressedRequestID = "CaptureUncompressedRequest" - -// AddCaptureUncompressedRequestMiddleware captures http request before compress encoding for check -func AddCaptureUncompressedRequestMiddleware(stack *middleware.Stack, buf *bytes.Buffer) error { - return stack.Serialize.Insert(&captureUncompressedRequestMiddleware{ - buf: buf, - }, "RequestCompression", middleware.Before) -} - -type captureUncompressedRequestMiddleware struct { - req *http.Request - buf *bytes.Buffer - bytes []byte -} - -// ID returns id of the captureUncompressedRequestMiddleware -func (*captureUncompressedRequestMiddleware) ID() string { - return captureUncompressedRequestID -} - -// HandleSerialize captures request payload before it is compressed by request compression middleware -func (m *captureUncompressedRequestMiddleware) HandleSerialize(ctx context.Context, input middleware.SerializeInput, next middleware.SerializeHandler, -) ( - output middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - request, ok := input.Request.(*smithyhttp.Request) - if !ok { - return output, metadata, fmt.Errorf("error when retrieving http request") - } - - _, err = io.Copy(m.buf, request.GetStream()) - if err != nil { - return output, metadata, fmt.Errorf("error when copying http request stream: %q", err) - } - if err = request.RewindStream(); err != nil { - return output, metadata, fmt.Errorf("error when rewinding request stream: %q", err) - } - - return next.HandleSerialize(ctx, input) -} diff --git a/vendor/github.com/aws/smithy-go/private/requestcompression/request_compression.go b/vendor/github.com/aws/smithy-go/private/requestcompression/request_compression.go deleted file mode 100644 index 7c414760..00000000 --- a/vendor/github.com/aws/smithy-go/private/requestcompression/request_compression.go +++ /dev/null @@ -1,103 +0,0 @@ -// Package requestcompression implements runtime support for smithy-modeled -// request compression. -// -// This package is designated as private and is intended for use only by the -// smithy client runtime. The exported API therein is not considered stable and -// is subject to breaking changes without notice. -package requestcompression - -import ( - "bytes" - "context" - "fmt" - "github.com/aws/smithy-go/middleware" - "github.com/aws/smithy-go/transport/http" - "io" -) - -const MaxRequestMinCompressSizeBytes = 10485760 - -// Enumeration values for supported compress Algorithms. -const ( - GZIP = "gzip" -) - -type compressFunc func(io.Reader) ([]byte, error) - -var allowedAlgorithms = map[string]compressFunc{ - GZIP: gzipCompress, -} - -// AddRequestCompression add requestCompression middleware to op stack -func AddRequestCompression(stack *middleware.Stack, disabled bool, minBytes int64, algorithms []string) error { - return stack.Serialize.Add(&requestCompression{ - disableRequestCompression: disabled, - requestMinCompressSizeBytes: minBytes, - compressAlgorithms: algorithms, - }, middleware.After) -} - -type requestCompression struct { - disableRequestCompression bool - requestMinCompressSizeBytes int64 - compressAlgorithms []string -} - -// ID returns the ID of the middleware -func (m requestCompression) ID() string { - return "RequestCompression" -} - -// HandleSerialize gzip compress the request's stream/body if enabled by config fields -func (m requestCompression) HandleSerialize( - ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler, -) ( - out middleware.SerializeOutput, metadata middleware.Metadata, err error, -) { - if m.disableRequestCompression { - return next.HandleSerialize(ctx, in) - } - // still need to check requestMinCompressSizeBytes in case it is out of range after service client config - if m.requestMinCompressSizeBytes < 0 || m.requestMinCompressSizeBytes > MaxRequestMinCompressSizeBytes { - return out, metadata, fmt.Errorf("invalid range for min request compression size bytes %d, must be within 0 and 10485760 inclusively", m.requestMinCompressSizeBytes) - } - - req, ok := in.Request.(*http.Request) - if !ok { - return out, metadata, fmt.Errorf("unknown request type %T", req) - } - - for _, algorithm := range m.compressAlgorithms { - compressFunc := allowedAlgorithms[algorithm] - if compressFunc != nil { - if stream := req.GetStream(); stream != nil { - size, found, err := req.StreamLength() - if err != nil { - return out, metadata, fmt.Errorf("error while finding request stream length, %v", err) - } else if !found || size < m.requestMinCompressSizeBytes { - return next.HandleSerialize(ctx, in) - } - - compressedBytes, err := compressFunc(stream) - if err != nil { - return out, metadata, fmt.Errorf("failed to compress request stream, %v", err) - } - - var newReq *http.Request - if newReq, err = req.SetStream(bytes.NewReader(compressedBytes)); err != nil { - return out, metadata, fmt.Errorf("failed to set request stream, %v", err) - } - *req = *newReq - - if val := req.Header.Get("Content-Encoding"); val != "" { - req.Header.Set("Content-Encoding", fmt.Sprintf("%s, %s", val, algorithm)) - } else { - req.Header.Set("Content-Encoding", algorithm) - } - } - break - } - } - - return next.HandleSerialize(ctx, in) -} diff --git a/vendor/github.com/aws/smithy-go/properties.go b/vendor/github.com/aws/smithy-go/properties.go deleted file mode 100644 index c9af66c0..00000000 --- a/vendor/github.com/aws/smithy-go/properties.go +++ /dev/null @@ -1,62 +0,0 @@ -package smithy - -// PropertiesReader provides an interface for reading metadata from the -// underlying metadata container. -type PropertiesReader interface { - Get(key interface{}) interface{} -} - -// Properties provides storing and reading metadata values. Keys may be any -// comparable value type. Get and Set will panic if a key is not comparable. -// -// The zero value for a Properties instance is ready for reads/writes without -// any additional initialization. -type Properties struct { - values map[interface{}]interface{} -} - -// Get attempts to retrieve the value the key points to. Returns nil if the -// key was not found. -// -// Panics if key type is not comparable. -func (m *Properties) Get(key interface{}) interface{} { - m.lazyInit() - return m.values[key] -} - -// Set stores the value pointed to by the key. If a value already exists at -// that key it will be replaced with the new value. -// -// Panics if the key type is not comparable. -func (m *Properties) Set(key, value interface{}) { - m.lazyInit() - m.values[key] = value -} - -// Has returns whether the key exists in the metadata. -// -// Panics if the key type is not comparable. -func (m *Properties) Has(key interface{}) bool { - m.lazyInit() - _, ok := m.values[key] - return ok -} - -// SetAll accepts all of the given Properties into the receiver, overwriting -// any existing keys in the case of conflicts. -func (m *Properties) SetAll(other *Properties) { - if other.values == nil { - return - } - - m.lazyInit() - for k, v := range other.values { - m.values[k] = v - } -} - -func (m *Properties) lazyInit() { - if m.values == nil { - m.values = map[interface{}]interface{}{} - } -} diff --git a/vendor/github.com/aws/smithy-go/ptr/doc.go b/vendor/github.com/aws/smithy-go/ptr/doc.go deleted file mode 100644 index bc1f6996..00000000 --- a/vendor/github.com/aws/smithy-go/ptr/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -// Package ptr provides utilities for converting scalar literal type values to and from pointers inline. -package ptr - -//go:generate go run -tags codegen generate.go -//go:generate gofmt -w -s . diff --git a/vendor/github.com/aws/smithy-go/ptr/from_ptr.go b/vendor/github.com/aws/smithy-go/ptr/from_ptr.go deleted file mode 100644 index a2845bb2..00000000 --- a/vendor/github.com/aws/smithy-go/ptr/from_ptr.go +++ /dev/null @@ -1,601 +0,0 @@ -// Code generated by smithy-go/ptr/generate.go DO NOT EDIT. -package ptr - -import ( - "time" -) - -// ToBool returns bool value dereferenced if the passed -// in pointer was not nil. Returns a bool zero value if the -// pointer was nil. -func ToBool(p *bool) (v bool) { - if p == nil { - return v - } - - return *p -} - -// ToBoolSlice returns a slice of bool values, that are -// dereferenced if the passed in pointer was not nil. Returns a bool -// zero value if the pointer was nil. -func ToBoolSlice(vs []*bool) []bool { - ps := make([]bool, len(vs)) - for i, v := range vs { - ps[i] = ToBool(v) - } - - return ps -} - -// ToBoolMap returns a map of bool values, that are -// dereferenced if the passed in pointer was not nil. The bool -// zero value is used if the pointer was nil. -func ToBoolMap(vs map[string]*bool) map[string]bool { - ps := make(map[string]bool, len(vs)) - for k, v := range vs { - ps[k] = ToBool(v) - } - - return ps -} - -// ToByte returns byte value dereferenced if the passed -// in pointer was not nil. Returns a byte zero value if the -// pointer was nil. -func ToByte(p *byte) (v byte) { - if p == nil { - return v - } - - return *p -} - -// ToByteSlice returns a slice of byte values, that are -// dereferenced if the passed in pointer was not nil. Returns a byte -// zero value if the pointer was nil. -func ToByteSlice(vs []*byte) []byte { - ps := make([]byte, len(vs)) - for i, v := range vs { - ps[i] = ToByte(v) - } - - return ps -} - -// ToByteMap returns a map of byte values, that are -// dereferenced if the passed in pointer was not nil. The byte -// zero value is used if the pointer was nil. -func ToByteMap(vs map[string]*byte) map[string]byte { - ps := make(map[string]byte, len(vs)) - for k, v := range vs { - ps[k] = ToByte(v) - } - - return ps -} - -// ToString returns string value dereferenced if the passed -// in pointer was not nil. Returns a string zero value if the -// pointer was nil. -func ToString(p *string) (v string) { - if p == nil { - return v - } - - return *p -} - -// ToStringSlice returns a slice of string values, that are -// dereferenced if the passed in pointer was not nil. Returns a string -// zero value if the pointer was nil. -func ToStringSlice(vs []*string) []string { - ps := make([]string, len(vs)) - for i, v := range vs { - ps[i] = ToString(v) - } - - return ps -} - -// ToStringMap returns a map of string values, that are -// dereferenced if the passed in pointer was not nil. The string -// zero value is used if the pointer was nil. -func ToStringMap(vs map[string]*string) map[string]string { - ps := make(map[string]string, len(vs)) - for k, v := range vs { - ps[k] = ToString(v) - } - - return ps -} - -// ToInt returns int value dereferenced if the passed -// in pointer was not nil. Returns a int zero value if the -// pointer was nil. -func ToInt(p *int) (v int) { - if p == nil { - return v - } - - return *p -} - -// ToIntSlice returns a slice of int values, that are -// dereferenced if the passed in pointer was not nil. Returns a int -// zero value if the pointer was nil. -func ToIntSlice(vs []*int) []int { - ps := make([]int, len(vs)) - for i, v := range vs { - ps[i] = ToInt(v) - } - - return ps -} - -// ToIntMap returns a map of int values, that are -// dereferenced if the passed in pointer was not nil. The int -// zero value is used if the pointer was nil. -func ToIntMap(vs map[string]*int) map[string]int { - ps := make(map[string]int, len(vs)) - for k, v := range vs { - ps[k] = ToInt(v) - } - - return ps -} - -// ToInt8 returns int8 value dereferenced if the passed -// in pointer was not nil. Returns a int8 zero value if the -// pointer was nil. -func ToInt8(p *int8) (v int8) { - if p == nil { - return v - } - - return *p -} - -// ToInt8Slice returns a slice of int8 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int8 -// zero value if the pointer was nil. -func ToInt8Slice(vs []*int8) []int8 { - ps := make([]int8, len(vs)) - for i, v := range vs { - ps[i] = ToInt8(v) - } - - return ps -} - -// ToInt8Map returns a map of int8 values, that are -// dereferenced if the passed in pointer was not nil. The int8 -// zero value is used if the pointer was nil. -func ToInt8Map(vs map[string]*int8) map[string]int8 { - ps := make(map[string]int8, len(vs)) - for k, v := range vs { - ps[k] = ToInt8(v) - } - - return ps -} - -// ToInt16 returns int16 value dereferenced if the passed -// in pointer was not nil. Returns a int16 zero value if the -// pointer was nil. -func ToInt16(p *int16) (v int16) { - if p == nil { - return v - } - - return *p -} - -// ToInt16Slice returns a slice of int16 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int16 -// zero value if the pointer was nil. -func ToInt16Slice(vs []*int16) []int16 { - ps := make([]int16, len(vs)) - for i, v := range vs { - ps[i] = ToInt16(v) - } - - return ps -} - -// ToInt16Map returns a map of int16 values, that are -// dereferenced if the passed in pointer was not nil. The int16 -// zero value is used if the pointer was nil. -func ToInt16Map(vs map[string]*int16) map[string]int16 { - ps := make(map[string]int16, len(vs)) - for k, v := range vs { - ps[k] = ToInt16(v) - } - - return ps -} - -// ToInt32 returns int32 value dereferenced if the passed -// in pointer was not nil. Returns a int32 zero value if the -// pointer was nil. -func ToInt32(p *int32) (v int32) { - if p == nil { - return v - } - - return *p -} - -// ToInt32Slice returns a slice of int32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int32 -// zero value if the pointer was nil. -func ToInt32Slice(vs []*int32) []int32 { - ps := make([]int32, len(vs)) - for i, v := range vs { - ps[i] = ToInt32(v) - } - - return ps -} - -// ToInt32Map returns a map of int32 values, that are -// dereferenced if the passed in pointer was not nil. The int32 -// zero value is used if the pointer was nil. -func ToInt32Map(vs map[string]*int32) map[string]int32 { - ps := make(map[string]int32, len(vs)) - for k, v := range vs { - ps[k] = ToInt32(v) - } - - return ps -} - -// ToInt64 returns int64 value dereferenced if the passed -// in pointer was not nil. Returns a int64 zero value if the -// pointer was nil. -func ToInt64(p *int64) (v int64) { - if p == nil { - return v - } - - return *p -} - -// ToInt64Slice returns a slice of int64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a int64 -// zero value if the pointer was nil. -func ToInt64Slice(vs []*int64) []int64 { - ps := make([]int64, len(vs)) - for i, v := range vs { - ps[i] = ToInt64(v) - } - - return ps -} - -// ToInt64Map returns a map of int64 values, that are -// dereferenced if the passed in pointer was not nil. The int64 -// zero value is used if the pointer was nil. -func ToInt64Map(vs map[string]*int64) map[string]int64 { - ps := make(map[string]int64, len(vs)) - for k, v := range vs { - ps[k] = ToInt64(v) - } - - return ps -} - -// ToUint returns uint value dereferenced if the passed -// in pointer was not nil. Returns a uint zero value if the -// pointer was nil. -func ToUint(p *uint) (v uint) { - if p == nil { - return v - } - - return *p -} - -// ToUintSlice returns a slice of uint values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint -// zero value if the pointer was nil. -func ToUintSlice(vs []*uint) []uint { - ps := make([]uint, len(vs)) - for i, v := range vs { - ps[i] = ToUint(v) - } - - return ps -} - -// ToUintMap returns a map of uint values, that are -// dereferenced if the passed in pointer was not nil. The uint -// zero value is used if the pointer was nil. -func ToUintMap(vs map[string]*uint) map[string]uint { - ps := make(map[string]uint, len(vs)) - for k, v := range vs { - ps[k] = ToUint(v) - } - - return ps -} - -// ToUint8 returns uint8 value dereferenced if the passed -// in pointer was not nil. Returns a uint8 zero value if the -// pointer was nil. -func ToUint8(p *uint8) (v uint8) { - if p == nil { - return v - } - - return *p -} - -// ToUint8Slice returns a slice of uint8 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint8 -// zero value if the pointer was nil. -func ToUint8Slice(vs []*uint8) []uint8 { - ps := make([]uint8, len(vs)) - for i, v := range vs { - ps[i] = ToUint8(v) - } - - return ps -} - -// ToUint8Map returns a map of uint8 values, that are -// dereferenced if the passed in pointer was not nil. The uint8 -// zero value is used if the pointer was nil. -func ToUint8Map(vs map[string]*uint8) map[string]uint8 { - ps := make(map[string]uint8, len(vs)) - for k, v := range vs { - ps[k] = ToUint8(v) - } - - return ps -} - -// ToUint16 returns uint16 value dereferenced if the passed -// in pointer was not nil. Returns a uint16 zero value if the -// pointer was nil. -func ToUint16(p *uint16) (v uint16) { - if p == nil { - return v - } - - return *p -} - -// ToUint16Slice returns a slice of uint16 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint16 -// zero value if the pointer was nil. -func ToUint16Slice(vs []*uint16) []uint16 { - ps := make([]uint16, len(vs)) - for i, v := range vs { - ps[i] = ToUint16(v) - } - - return ps -} - -// ToUint16Map returns a map of uint16 values, that are -// dereferenced if the passed in pointer was not nil. The uint16 -// zero value is used if the pointer was nil. -func ToUint16Map(vs map[string]*uint16) map[string]uint16 { - ps := make(map[string]uint16, len(vs)) - for k, v := range vs { - ps[k] = ToUint16(v) - } - - return ps -} - -// ToUint32 returns uint32 value dereferenced if the passed -// in pointer was not nil. Returns a uint32 zero value if the -// pointer was nil. -func ToUint32(p *uint32) (v uint32) { - if p == nil { - return v - } - - return *p -} - -// ToUint32Slice returns a slice of uint32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint32 -// zero value if the pointer was nil. -func ToUint32Slice(vs []*uint32) []uint32 { - ps := make([]uint32, len(vs)) - for i, v := range vs { - ps[i] = ToUint32(v) - } - - return ps -} - -// ToUint32Map returns a map of uint32 values, that are -// dereferenced if the passed in pointer was not nil. The uint32 -// zero value is used if the pointer was nil. -func ToUint32Map(vs map[string]*uint32) map[string]uint32 { - ps := make(map[string]uint32, len(vs)) - for k, v := range vs { - ps[k] = ToUint32(v) - } - - return ps -} - -// ToUint64 returns uint64 value dereferenced if the passed -// in pointer was not nil. Returns a uint64 zero value if the -// pointer was nil. -func ToUint64(p *uint64) (v uint64) { - if p == nil { - return v - } - - return *p -} - -// ToUint64Slice returns a slice of uint64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a uint64 -// zero value if the pointer was nil. -func ToUint64Slice(vs []*uint64) []uint64 { - ps := make([]uint64, len(vs)) - for i, v := range vs { - ps[i] = ToUint64(v) - } - - return ps -} - -// ToUint64Map returns a map of uint64 values, that are -// dereferenced if the passed in pointer was not nil. The uint64 -// zero value is used if the pointer was nil. -func ToUint64Map(vs map[string]*uint64) map[string]uint64 { - ps := make(map[string]uint64, len(vs)) - for k, v := range vs { - ps[k] = ToUint64(v) - } - - return ps -} - -// ToFloat32 returns float32 value dereferenced if the passed -// in pointer was not nil. Returns a float32 zero value if the -// pointer was nil. -func ToFloat32(p *float32) (v float32) { - if p == nil { - return v - } - - return *p -} - -// ToFloat32Slice returns a slice of float32 values, that are -// dereferenced if the passed in pointer was not nil. Returns a float32 -// zero value if the pointer was nil. -func ToFloat32Slice(vs []*float32) []float32 { - ps := make([]float32, len(vs)) - for i, v := range vs { - ps[i] = ToFloat32(v) - } - - return ps -} - -// ToFloat32Map returns a map of float32 values, that are -// dereferenced if the passed in pointer was not nil. The float32 -// zero value is used if the pointer was nil. -func ToFloat32Map(vs map[string]*float32) map[string]float32 { - ps := make(map[string]float32, len(vs)) - for k, v := range vs { - ps[k] = ToFloat32(v) - } - - return ps -} - -// ToFloat64 returns float64 value dereferenced if the passed -// in pointer was not nil. Returns a float64 zero value if the -// pointer was nil. -func ToFloat64(p *float64) (v float64) { - if p == nil { - return v - } - - return *p -} - -// ToFloat64Slice returns a slice of float64 values, that are -// dereferenced if the passed in pointer was not nil. Returns a float64 -// zero value if the pointer was nil. -func ToFloat64Slice(vs []*float64) []float64 { - ps := make([]float64, len(vs)) - for i, v := range vs { - ps[i] = ToFloat64(v) - } - - return ps -} - -// ToFloat64Map returns a map of float64 values, that are -// dereferenced if the passed in pointer was not nil. The float64 -// zero value is used if the pointer was nil. -func ToFloat64Map(vs map[string]*float64) map[string]float64 { - ps := make(map[string]float64, len(vs)) - for k, v := range vs { - ps[k] = ToFloat64(v) - } - - return ps -} - -// ToTime returns time.Time value dereferenced if the passed -// in pointer was not nil. Returns a time.Time zero value if the -// pointer was nil. -func ToTime(p *time.Time) (v time.Time) { - if p == nil { - return v - } - - return *p -} - -// ToTimeSlice returns a slice of time.Time values, that are -// dereferenced if the passed in pointer was not nil. Returns a time.Time -// zero value if the pointer was nil. -func ToTimeSlice(vs []*time.Time) []time.Time { - ps := make([]time.Time, len(vs)) - for i, v := range vs { - ps[i] = ToTime(v) - } - - return ps -} - -// ToTimeMap returns a map of time.Time values, that are -// dereferenced if the passed in pointer was not nil. The time.Time -// zero value is used if the pointer was nil. -func ToTimeMap(vs map[string]*time.Time) map[string]time.Time { - ps := make(map[string]time.Time, len(vs)) - for k, v := range vs { - ps[k] = ToTime(v) - } - - return ps -} - -// ToDuration returns time.Duration value dereferenced if the passed -// in pointer was not nil. Returns a time.Duration zero value if the -// pointer was nil. -func ToDuration(p *time.Duration) (v time.Duration) { - if p == nil { - return v - } - - return *p -} - -// ToDurationSlice returns a slice of time.Duration values, that are -// dereferenced if the passed in pointer was not nil. Returns a time.Duration -// zero value if the pointer was nil. -func ToDurationSlice(vs []*time.Duration) []time.Duration { - ps := make([]time.Duration, len(vs)) - for i, v := range vs { - ps[i] = ToDuration(v) - } - - return ps -} - -// ToDurationMap returns a map of time.Duration values, that are -// dereferenced if the passed in pointer was not nil. The time.Duration -// zero value is used if the pointer was nil. -func ToDurationMap(vs map[string]*time.Duration) map[string]time.Duration { - ps := make(map[string]time.Duration, len(vs)) - for k, v := range vs { - ps[k] = ToDuration(v) - } - - return ps -} diff --git a/vendor/github.com/aws/smithy-go/ptr/gen_scalars.go b/vendor/github.com/aws/smithy-go/ptr/gen_scalars.go deleted file mode 100644 index 97f01011..00000000 --- a/vendor/github.com/aws/smithy-go/ptr/gen_scalars.go +++ /dev/null @@ -1,83 +0,0 @@ -//go:build codegen -// +build codegen - -package ptr - -import "strings" - -func GetScalars() Scalars { - return Scalars{ - {Type: "bool"}, - {Type: "byte"}, - {Type: "string"}, - {Type: "int"}, - {Type: "int8"}, - {Type: "int16"}, - {Type: "int32"}, - {Type: "int64"}, - {Type: "uint"}, - {Type: "uint8"}, - {Type: "uint16"}, - {Type: "uint32"}, - {Type: "uint64"}, - {Type: "float32"}, - {Type: "float64"}, - {Type: "Time", Import: &Import{Path: "time"}}, - {Type: "Duration", Import: &Import{Path: "time"}}, - } -} - -// Import provides the import path and optional alias -type Import struct { - Path string - Alias string -} - -// Package returns the Go package name for the import. Returns alias if set. -func (i Import) Package() string { - if v := i.Alias; len(v) != 0 { - return v - } - - if v := i.Path; len(v) != 0 { - parts := strings.Split(v, "/") - pkg := parts[len(parts)-1] - return pkg - } - - return "" -} - -// Scalar provides the definition of a type to generate pointer utilities for. -type Scalar struct { - Type string - Import *Import -} - -// Name returns the exported function name for the type. -func (t Scalar) Name() string { - return strings.Title(t.Type) -} - -// Symbol returns the scalar's Go symbol with path if needed. -func (t Scalar) Symbol() string { - if t.Import != nil { - return t.Import.Package() + "." + t.Type - } - return t.Type -} - -// Scalars is a list of scalars. -type Scalars []Scalar - -// Imports returns all imports for the scalars. -func (ts Scalars) Imports() []*Import { - imports := []*Import{} - for _, t := range ts { - if v := t.Import; v != nil { - imports = append(imports, v) - } - } - - return imports -} diff --git a/vendor/github.com/aws/smithy-go/ptr/to_ptr.go b/vendor/github.com/aws/smithy-go/ptr/to_ptr.go deleted file mode 100644 index 0bfbbecb..00000000 --- a/vendor/github.com/aws/smithy-go/ptr/to_ptr.go +++ /dev/null @@ -1,499 +0,0 @@ -// Code generated by smithy-go/ptr/generate.go DO NOT EDIT. -package ptr - -import ( - "time" -) - -// Bool returns a pointer value for the bool value passed in. -func Bool(v bool) *bool { - return &v -} - -// BoolSlice returns a slice of bool pointers from the values -// passed in. -func BoolSlice(vs []bool) []*bool { - ps := make([]*bool, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// BoolMap returns a map of bool pointers from the values -// passed in. -func BoolMap(vs map[string]bool) map[string]*bool { - ps := make(map[string]*bool, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Byte returns a pointer value for the byte value passed in. -func Byte(v byte) *byte { - return &v -} - -// ByteSlice returns a slice of byte pointers from the values -// passed in. -func ByteSlice(vs []byte) []*byte { - ps := make([]*byte, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// ByteMap returns a map of byte pointers from the values -// passed in. -func ByteMap(vs map[string]byte) map[string]*byte { - ps := make(map[string]*byte, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// String returns a pointer value for the string value passed in. -func String(v string) *string { - return &v -} - -// StringSlice returns a slice of string pointers from the values -// passed in. -func StringSlice(vs []string) []*string { - ps := make([]*string, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// StringMap returns a map of string pointers from the values -// passed in. -func StringMap(vs map[string]string) map[string]*string { - ps := make(map[string]*string, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Int returns a pointer value for the int value passed in. -func Int(v int) *int { - return &v -} - -// IntSlice returns a slice of int pointers from the values -// passed in. -func IntSlice(vs []int) []*int { - ps := make([]*int, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// IntMap returns a map of int pointers from the values -// passed in. -func IntMap(vs map[string]int) map[string]*int { - ps := make(map[string]*int, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Int8 returns a pointer value for the int8 value passed in. -func Int8(v int8) *int8 { - return &v -} - -// Int8Slice returns a slice of int8 pointers from the values -// passed in. -func Int8Slice(vs []int8) []*int8 { - ps := make([]*int8, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Int8Map returns a map of int8 pointers from the values -// passed in. -func Int8Map(vs map[string]int8) map[string]*int8 { - ps := make(map[string]*int8, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Int16 returns a pointer value for the int16 value passed in. -func Int16(v int16) *int16 { - return &v -} - -// Int16Slice returns a slice of int16 pointers from the values -// passed in. -func Int16Slice(vs []int16) []*int16 { - ps := make([]*int16, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Int16Map returns a map of int16 pointers from the values -// passed in. -func Int16Map(vs map[string]int16) map[string]*int16 { - ps := make(map[string]*int16, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Int32 returns a pointer value for the int32 value passed in. -func Int32(v int32) *int32 { - return &v -} - -// Int32Slice returns a slice of int32 pointers from the values -// passed in. -func Int32Slice(vs []int32) []*int32 { - ps := make([]*int32, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Int32Map returns a map of int32 pointers from the values -// passed in. -func Int32Map(vs map[string]int32) map[string]*int32 { - ps := make(map[string]*int32, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Int64 returns a pointer value for the int64 value passed in. -func Int64(v int64) *int64 { - return &v -} - -// Int64Slice returns a slice of int64 pointers from the values -// passed in. -func Int64Slice(vs []int64) []*int64 { - ps := make([]*int64, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Int64Map returns a map of int64 pointers from the values -// passed in. -func Int64Map(vs map[string]int64) map[string]*int64 { - ps := make(map[string]*int64, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Uint returns a pointer value for the uint value passed in. -func Uint(v uint) *uint { - return &v -} - -// UintSlice returns a slice of uint pointers from the values -// passed in. -func UintSlice(vs []uint) []*uint { - ps := make([]*uint, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// UintMap returns a map of uint pointers from the values -// passed in. -func UintMap(vs map[string]uint) map[string]*uint { - ps := make(map[string]*uint, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Uint8 returns a pointer value for the uint8 value passed in. -func Uint8(v uint8) *uint8 { - return &v -} - -// Uint8Slice returns a slice of uint8 pointers from the values -// passed in. -func Uint8Slice(vs []uint8) []*uint8 { - ps := make([]*uint8, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Uint8Map returns a map of uint8 pointers from the values -// passed in. -func Uint8Map(vs map[string]uint8) map[string]*uint8 { - ps := make(map[string]*uint8, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Uint16 returns a pointer value for the uint16 value passed in. -func Uint16(v uint16) *uint16 { - return &v -} - -// Uint16Slice returns a slice of uint16 pointers from the values -// passed in. -func Uint16Slice(vs []uint16) []*uint16 { - ps := make([]*uint16, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Uint16Map returns a map of uint16 pointers from the values -// passed in. -func Uint16Map(vs map[string]uint16) map[string]*uint16 { - ps := make(map[string]*uint16, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Uint32 returns a pointer value for the uint32 value passed in. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint32Slice returns a slice of uint32 pointers from the values -// passed in. -func Uint32Slice(vs []uint32) []*uint32 { - ps := make([]*uint32, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Uint32Map returns a map of uint32 pointers from the values -// passed in. -func Uint32Map(vs map[string]uint32) map[string]*uint32 { - ps := make(map[string]*uint32, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Uint64 returns a pointer value for the uint64 value passed in. -func Uint64(v uint64) *uint64 { - return &v -} - -// Uint64Slice returns a slice of uint64 pointers from the values -// passed in. -func Uint64Slice(vs []uint64) []*uint64 { - ps := make([]*uint64, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Uint64Map returns a map of uint64 pointers from the values -// passed in. -func Uint64Map(vs map[string]uint64) map[string]*uint64 { - ps := make(map[string]*uint64, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Float32 returns a pointer value for the float32 value passed in. -func Float32(v float32) *float32 { - return &v -} - -// Float32Slice returns a slice of float32 pointers from the values -// passed in. -func Float32Slice(vs []float32) []*float32 { - ps := make([]*float32, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Float32Map returns a map of float32 pointers from the values -// passed in. -func Float32Map(vs map[string]float32) map[string]*float32 { - ps := make(map[string]*float32, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Float64 returns a pointer value for the float64 value passed in. -func Float64(v float64) *float64 { - return &v -} - -// Float64Slice returns a slice of float64 pointers from the values -// passed in. -func Float64Slice(vs []float64) []*float64 { - ps := make([]*float64, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// Float64Map returns a map of float64 pointers from the values -// passed in. -func Float64Map(vs map[string]float64) map[string]*float64 { - ps := make(map[string]*float64, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Time returns a pointer value for the time.Time value passed in. -func Time(v time.Time) *time.Time { - return &v -} - -// TimeSlice returns a slice of time.Time pointers from the values -// passed in. -func TimeSlice(vs []time.Time) []*time.Time { - ps := make([]*time.Time, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// TimeMap returns a map of time.Time pointers from the values -// passed in. -func TimeMap(vs map[string]time.Time) map[string]*time.Time { - ps := make(map[string]*time.Time, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} - -// Duration returns a pointer value for the time.Duration value passed in. -func Duration(v time.Duration) *time.Duration { - return &v -} - -// DurationSlice returns a slice of time.Duration pointers from the values -// passed in. -func DurationSlice(vs []time.Duration) []*time.Duration { - ps := make([]*time.Duration, len(vs)) - for i, v := range vs { - vv := v - ps[i] = &vv - } - - return ps -} - -// DurationMap returns a map of time.Duration pointers from the values -// passed in. -func DurationMap(vs map[string]time.Duration) map[string]*time.Duration { - ps := make(map[string]*time.Duration, len(vs)) - for k, v := range vs { - vv := v - ps[k] = &vv - } - - return ps -} diff --git a/vendor/github.com/aws/smithy-go/rand/doc.go b/vendor/github.com/aws/smithy-go/rand/doc.go deleted file mode 100644 index f8b25d56..00000000 --- a/vendor/github.com/aws/smithy-go/rand/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package rand provides utilities for creating and working with random value -// generators. -package rand diff --git a/vendor/github.com/aws/smithy-go/rand/rand.go b/vendor/github.com/aws/smithy-go/rand/rand.go deleted file mode 100644 index 9c479f62..00000000 --- a/vendor/github.com/aws/smithy-go/rand/rand.go +++ /dev/null @@ -1,31 +0,0 @@ -package rand - -import ( - "crypto/rand" - "fmt" - "io" - "math/big" -) - -func init() { - Reader = rand.Reader -} - -// Reader provides a random reader that can reset during testing. -var Reader io.Reader - -// Int63n returns a int64 between zero and value of max, read from an io.Reader source. -func Int63n(reader io.Reader, max int64) (int64, error) { - bi, err := rand.Int(reader, big.NewInt(max)) - if err != nil { - return 0, fmt.Errorf("failed to read random value, %w", err) - } - - return bi.Int64(), nil -} - -// CryptoRandInt63n returns a random int64 between zero and value of max -// obtained from the crypto rand source. -func CryptoRandInt63n(max int64) (int64, error) { - return Int63n(Reader, max) -} diff --git a/vendor/github.com/aws/smithy-go/rand/uuid.go b/vendor/github.com/aws/smithy-go/rand/uuid.go deleted file mode 100644 index dc81cbc6..00000000 --- a/vendor/github.com/aws/smithy-go/rand/uuid.go +++ /dev/null @@ -1,87 +0,0 @@ -package rand - -import ( - "encoding/hex" - "io" -) - -const dash byte = '-' - -// UUIDIdempotencyToken provides a utility to get idempotency tokens in the -// UUID format. -type UUIDIdempotencyToken struct { - uuid *UUID -} - -// NewUUIDIdempotencyToken returns a idempotency token provider returning -// tokens in the UUID random format using the reader provided. -func NewUUIDIdempotencyToken(r io.Reader) *UUIDIdempotencyToken { - return &UUIDIdempotencyToken{uuid: NewUUID(r)} -} - -// GetIdempotencyToken returns a random UUID value for Idempotency token. -func (u UUIDIdempotencyToken) GetIdempotencyToken() (string, error) { - return u.uuid.GetUUID() -} - -// UUID provides computing random UUID version 4 values from a random source -// reader. -type UUID struct { - randSrc io.Reader -} - -// NewUUID returns an initialized UUID value that can be used to retrieve -// random UUID version 4 values. -func NewUUID(r io.Reader) *UUID { - return &UUID{randSrc: r} -} - -// GetUUID returns a random UUID version 4 string representation sourced from the random reader the -// UUID was created with. Returns an error if unable to compute the UUID. -func (r *UUID) GetUUID() (string, error) { - var b [16]byte - if _, err := io.ReadFull(r.randSrc, b[:]); err != nil { - return "", err - } - r.makeUUIDv4(b[:]) - return format(b), nil -} - -// GetBytes returns a byte slice containing a random UUID version 4 sourced from the random reader the -// UUID was created with. Returns an error if unable to compute the UUID. -func (r *UUID) GetBytes() (u []byte, err error) { - u = make([]byte, 16) - if _, err = io.ReadFull(r.randSrc, u); err != nil { - return u, err - } - r.makeUUIDv4(u) - return u, nil -} - -func (r *UUID) makeUUIDv4(u []byte) { - // 13th character is "4" - u[6] = (u[6] & 0x0f) | 0x40 // Version 4 - // 17th character is "8", "9", "a", or "b" - u[8] = (u[8] & 0x3f) | 0x80 // Variant most significant bits are 10x where x can be either 1 or 0 -} - -// Format returns the canonical text representation of a UUID. -// This implementation is optimized to not use fmt. -// Example: 82e42f16-b6cc-4d5b-95f5-d403c4befd3d -func format(u [16]byte) string { - // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29 - - var scratch [36]byte - - hex.Encode(scratch[:8], u[0:4]) - scratch[8] = dash - hex.Encode(scratch[9:13], u[4:6]) - scratch[13] = dash - hex.Encode(scratch[14:18], u[6:8]) - scratch[18] = dash - hex.Encode(scratch[19:23], u[8:10]) - scratch[23] = dash - hex.Encode(scratch[24:], u[10:]) - - return string(scratch[:]) -} diff --git a/vendor/github.com/aws/smithy-go/time/time.go b/vendor/github.com/aws/smithy-go/time/time.go deleted file mode 100644 index b552a09f..00000000 --- a/vendor/github.com/aws/smithy-go/time/time.go +++ /dev/null @@ -1,134 +0,0 @@ -package time - -import ( - "context" - "fmt" - "math/big" - "strings" - "time" -) - -const ( - // dateTimeFormat is a IMF-fixdate formatted RFC3339 section 5.6 - dateTimeFormatInput = "2006-01-02T15:04:05.999999999Z" - dateTimeFormatInputNoZ = "2006-01-02T15:04:05.999999999" - dateTimeFormatOutput = "2006-01-02T15:04:05.999Z" - - // httpDateFormat is a date time defined by RFC 7231#section-7.1.1.1 - // IMF-fixdate with no UTC offset. - httpDateFormat = "Mon, 02 Jan 2006 15:04:05 GMT" - // Additional formats needed for compatibility. - httpDateFormatSingleDigitDay = "Mon, _2 Jan 2006 15:04:05 GMT" - httpDateFormatSingleDigitDayTwoDigitYear = "Mon, _2 Jan 06 15:04:05 GMT" -) - -var millisecondFloat = big.NewFloat(1e3) - -// FormatDateTime formats value as a date-time, (RFC3339 section 5.6) -// -// Example: 1985-04-12T23:20:50.52Z -func FormatDateTime(value time.Time) string { - return value.UTC().Format(dateTimeFormatOutput) -} - -// ParseDateTime parses a string as a date-time, (RFC3339 section 5.6) -// -// Example: 1985-04-12T23:20:50.52Z -func ParseDateTime(value string) (time.Time, error) { - return tryParse(value, - dateTimeFormatInput, - dateTimeFormatInputNoZ, - time.RFC3339Nano, - time.RFC3339, - ) -} - -// FormatHTTPDate formats value as a http-date, (RFC 7231#section-7.1.1.1 IMF-fixdate) -// -// Example: Tue, 29 Apr 2014 18:30:38 GMT -func FormatHTTPDate(value time.Time) string { - return value.UTC().Format(httpDateFormat) -} - -// ParseHTTPDate parses a string as a http-date, (RFC 7231#section-7.1.1.1 IMF-fixdate) -// -// Example: Tue, 29 Apr 2014 18:30:38 GMT -func ParseHTTPDate(value string) (time.Time, error) { - return tryParse(value, - httpDateFormat, - httpDateFormatSingleDigitDay, - httpDateFormatSingleDigitDayTwoDigitYear, - time.RFC850, - time.ANSIC, - ) -} - -// FormatEpochSeconds returns value as a Unix time in seconds with with decimal precision -// -// Example: 1515531081.123 -func FormatEpochSeconds(value time.Time) float64 { - ms := value.UnixNano() / int64(time.Millisecond) - return float64(ms) / 1e3 -} - -// ParseEpochSeconds returns value as a Unix time in seconds with with decimal precision -// -// Example: 1515531081.123 -func ParseEpochSeconds(value float64) time.Time { - f := big.NewFloat(value) - f = f.Mul(f, millisecondFloat) - i, _ := f.Int64() - // Offset to `UTC` because time.Unix returns the time value based on system - // local setting. - return time.Unix(0, i*1e6).UTC() -} - -func tryParse(v string, formats ...string) (time.Time, error) { - var errs parseErrors - for _, f := range formats { - t, err := time.Parse(f, v) - if err != nil { - errs = append(errs, parseError{ - Format: f, - Err: err, - }) - continue - } - return t, nil - } - - return time.Time{}, fmt.Errorf("unable to parse time string, %w", errs) -} - -type parseErrors []parseError - -func (es parseErrors) Error() string { - var s strings.Builder - for _, e := range es { - fmt.Fprintf(&s, "\n * %q: %v", e.Format, e.Err) - } - - return "parse errors:" + s.String() -} - -type parseError struct { - Format string - Err error -} - -// SleepWithContext will wait for the timer duration to expire, or until the context -// is canceled. Whichever happens first. If the context is canceled the -// Context's error will be returned. -func SleepWithContext(ctx context.Context, dur time.Duration) error { - t := time.NewTimer(dur) - defer t.Stop() - - select { - case <-t.C: - break - case <-ctx.Done(): - return ctx.Err() - } - - return nil -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/auth.go b/vendor/github.com/aws/smithy-go/transport/http/auth.go deleted file mode 100644 index 58e1ab5e..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/auth.go +++ /dev/null @@ -1,21 +0,0 @@ -package http - -import ( - "context" - - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/auth" -) - -// AuthScheme defines an HTTP authentication scheme. -type AuthScheme interface { - SchemeID() string - IdentityResolver(auth.IdentityResolverOptions) auth.IdentityResolver - Signer() Signer -} - -// Signer defines the interface through which HTTP requests are supplemented -// with an Identity. -type Signer interface { - SignRequest(context.Context, *Request, auth.Identity, smithy.Properties) error -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/auth_schemes.go b/vendor/github.com/aws/smithy-go/transport/http/auth_schemes.go deleted file mode 100644 index d60cf2a6..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/auth_schemes.go +++ /dev/null @@ -1,45 +0,0 @@ -package http - -import ( - "context" - - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/auth" -) - -// NewAnonymousScheme returns the anonymous HTTP auth scheme. -func NewAnonymousScheme() AuthScheme { - return &authScheme{ - schemeID: auth.SchemeIDAnonymous, - signer: &nopSigner{}, - } -} - -// authScheme is parameterized to generically implement the exported AuthScheme -// interface -type authScheme struct { - schemeID string - signer Signer -} - -var _ AuthScheme = (*authScheme)(nil) - -func (s *authScheme) SchemeID() string { - return s.schemeID -} - -func (s *authScheme) IdentityResolver(o auth.IdentityResolverOptions) auth.IdentityResolver { - return o.GetIdentityResolver(s.schemeID) -} - -func (s *authScheme) Signer() Signer { - return s.signer -} - -type nopSigner struct{} - -var _ Signer = (*nopSigner)(nil) - -func (*nopSigner) SignRequest(context.Context, *Request, auth.Identity, smithy.Properties) error { - return nil -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/checksum_middleware.go b/vendor/github.com/aws/smithy-go/transport/http/checksum_middleware.go deleted file mode 100644 index bc4ad6e7..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/checksum_middleware.go +++ /dev/null @@ -1,70 +0,0 @@ -package http - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go/middleware" -) - -const contentMD5Header = "Content-Md5" - -// contentMD5Checksum provides a middleware to compute and set -// content-md5 checksum for a http request -type contentMD5Checksum struct { -} - -// AddContentChecksumMiddleware adds checksum middleware to middleware's -// build step. -func AddContentChecksumMiddleware(stack *middleware.Stack) error { - // This middleware must be executed before request body is set. - return stack.Build.Add(&contentMD5Checksum{}, middleware.Before) -} - -// ID returns the identifier for the checksum middleware -func (m *contentMD5Checksum) ID() string { return "ContentChecksum" } - -// HandleBuild adds behavior to compute md5 checksum and add content-md5 header -// on http request -func (m *contentMD5Checksum) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*Request) - if !ok { - return out, metadata, fmt.Errorf("unknown request type %T", req) - } - - // if Content-MD5 header is already present, return - if v := req.Header.Get(contentMD5Header); len(v) != 0 { - return next.HandleBuild(ctx, in) - } - - // fetch the request stream. - stream := req.GetStream() - // compute checksum if payload is explicit - if stream != nil { - if !req.IsStreamSeekable() { - return out, metadata, fmt.Errorf( - "unseekable stream is not supported for computing md5 checksum") - } - - v, err := computeMD5Checksum(stream) - if err != nil { - return out, metadata, fmt.Errorf("error computing md5 checksum, %w", err) - } - - // reset the request stream - if err := req.RewindStream(); err != nil { - return out, metadata, fmt.Errorf( - "error rewinding request stream after computing md5 checksum, %w", err) - } - - // set the 'Content-MD5' header - req.Header.Set(contentMD5Header, string(v)) - } - - // set md5 header value - return next.HandleBuild(ctx, in) -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/client.go b/vendor/github.com/aws/smithy-go/transport/http/client.go deleted file mode 100644 index e691c69b..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/client.go +++ /dev/null @@ -1,120 +0,0 @@ -package http - -import ( - "context" - "fmt" - "net/http" - - smithy "github.com/aws/smithy-go" - "github.com/aws/smithy-go/middleware" -) - -// ClientDo provides the interface for custom HTTP client implementations. -type ClientDo interface { - Do(*http.Request) (*http.Response, error) -} - -// ClientDoFunc provides a helper to wrap a function as an HTTP client for -// round tripping requests. -type ClientDoFunc func(*http.Request) (*http.Response, error) - -// Do will invoke the underlying func, returning the result. -func (fn ClientDoFunc) Do(r *http.Request) (*http.Response, error) { - return fn(r) -} - -// ClientHandler wraps a client that implements the HTTP Do method. Standard -// implementation is http.Client. -type ClientHandler struct { - client ClientDo -} - -// NewClientHandler returns an initialized middleware handler for the client. -func NewClientHandler(client ClientDo) ClientHandler { - return ClientHandler{ - client: client, - } -} - -// Handle implements the middleware Handler interface, that will invoke the -// underlying HTTP client. Requires the input to be a Smithy *Request. Returns -// a smithy *Response, or error if the request failed. -func (c ClientHandler) Handle(ctx context.Context, input interface{}) ( - out interface{}, metadata middleware.Metadata, err error, -) { - req, ok := input.(*Request) - if !ok { - return nil, metadata, fmt.Errorf("expect Smithy http.Request value as input, got unsupported type %T", input) - } - - builtRequest := req.Build(ctx) - if err := ValidateEndpointHost(builtRequest.Host); err != nil { - return nil, metadata, err - } - - resp, err := c.client.Do(builtRequest) - if resp == nil { - // Ensure a http response value is always present to prevent unexpected - // panics. - resp = &http.Response{ - Header: http.Header{}, - Body: http.NoBody, - } - } - if err != nil { - err = &RequestSendError{Err: err} - - // Override the error with a context canceled error, if that was canceled. - select { - case <-ctx.Done(): - err = &smithy.CanceledError{Err: ctx.Err()} - default: - } - } - - // HTTP RoundTripper *should* close the request body. But this may not happen in a timely manner. - // So instead Smithy *Request Build wraps the body to be sent in a safe closer that will clear the - // stream reference so that it can be safely reused. - if builtRequest.Body != nil { - _ = builtRequest.Body.Close() - } - - return &Response{Response: resp}, metadata, err -} - -// RequestSendError provides a generic request transport error. This error -// should wrap errors making HTTP client requests. -// -// The ClientHandler will wrap the HTTP client's error if the client request -// fails, and did not fail because of context canceled. -type RequestSendError struct { - Err error -} - -// ConnectionError returns that the error is related to not being able to send -// the request, or receive a response from the service. -func (e *RequestSendError) ConnectionError() bool { - return true -} - -// Unwrap returns the underlying error, if there was one. -func (e *RequestSendError) Unwrap() error { - return e.Err -} - -func (e *RequestSendError) Error() string { - return fmt.Sprintf("request send failed, %v", e.Err) -} - -// NopClient provides a client that ignores the request, and returns an empty -// successful HTTP response value. -type NopClient struct{} - -// Do ignores the request and returns a 200 status empty response. -func (NopClient) Do(r *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: 200, - Header: http.Header{}, - Body: http.NoBody, - }, nil -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/doc.go b/vendor/github.com/aws/smithy-go/transport/http/doc.go deleted file mode 100644 index 07366ac8..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/doc.go +++ /dev/null @@ -1,5 +0,0 @@ -/* -Package http provides the HTTP transport client and request/response types -needed to round trip API operation calls with an service. -*/ -package http diff --git a/vendor/github.com/aws/smithy-go/transport/http/headerlist.go b/vendor/github.com/aws/smithy-go/transport/http/headerlist.go deleted file mode 100644 index cbc9deb4..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/headerlist.go +++ /dev/null @@ -1,163 +0,0 @@ -package http - -import ( - "fmt" - "strconv" - "strings" - "unicode" -) - -func splitHeaderListValues(vs []string, splitFn func(string) ([]string, error)) ([]string, error) { - values := make([]string, 0, len(vs)) - - for i := 0; i < len(vs); i++ { - parts, err := splitFn(vs[i]) - if err != nil { - return nil, err - } - values = append(values, parts...) - } - - return values, nil -} - -// SplitHeaderListValues attempts to split the elements of the slice by commas, -// and return a list of all values separated. Returns error if unable to -// separate the values. -func SplitHeaderListValues(vs []string) ([]string, error) { - return splitHeaderListValues(vs, quotedCommaSplit) -} - -func quotedCommaSplit(v string) (parts []string, err error) { - v = strings.TrimSpace(v) - - expectMore := true - for i := 0; i < len(v); i++ { - if unicode.IsSpace(rune(v[i])) { - continue - } - expectMore = false - - // leading space in part is ignored. - // Start of value must be non-space, or quote. - // - // - If quote, enter quoted mode, find next non-escaped quote to - // terminate the value. - // - Otherwise, find next comma to terminate value. - - remaining := v[i:] - - var value string - var valueLen int - if remaining[0] == '"' { - //------------------------------ - // Quoted value - //------------------------------ - var j int - var skipQuote bool - for j += 1; j < len(remaining); j++ { - if remaining[j] == '\\' || (remaining[j] != '\\' && skipQuote) { - skipQuote = !skipQuote - continue - } - if remaining[j] == '"' { - break - } - } - if j == len(remaining) || j == 1 { - return nil, fmt.Errorf("value %v missing closing double quote", - remaining) - } - valueLen = j + 1 - - tail := remaining[valueLen:] - var k int - for ; k < len(tail); k++ { - if !unicode.IsSpace(rune(tail[k])) && tail[k] != ',' { - return nil, fmt.Errorf("value %v has non-space trailing characters", - remaining) - } - if tail[k] == ',' { - expectMore = true - break - } - } - value = remaining[:valueLen] - value, err = strconv.Unquote(value) - if err != nil { - return nil, fmt.Errorf("failed to unquote value %v, %w", value, err) - } - - // Pad valueLen to include trailing space(s) so `i` is updated correctly. - valueLen += k - - } else { - //------------------------------ - // Unquoted value - //------------------------------ - - // Index of the next comma is the length of the value, or end of string. - valueLen = strings.Index(remaining, ",") - if valueLen != -1 { - expectMore = true - } else { - valueLen = len(remaining) - } - value = strings.TrimSpace(remaining[:valueLen]) - } - - i += valueLen - parts = append(parts, value) - - } - - if expectMore { - parts = append(parts, "") - } - - return parts, nil -} - -// SplitHTTPDateTimestampHeaderListValues attempts to split the HTTP-Date -// timestamp values in the slice by commas, and return a list of all values -// separated. The split is aware of the HTTP-Date timestamp format, and will skip -// comma within the timestamp value. Returns an error if unable to split the -// timestamp values. -func SplitHTTPDateTimestampHeaderListValues(vs []string) ([]string, error) { - return splitHeaderListValues(vs, splitHTTPDateHeaderValue) -} - -func splitHTTPDateHeaderValue(v string) ([]string, error) { - if n := strings.Count(v, ","); n <= 1 { - // Nothing to do if only contains a no, or single HTTPDate value - return []string{v}, nil - } else if n%2 == 0 { - return nil, fmt.Errorf("invalid timestamp HTTPDate header comma separations, %q", v) - } - - var parts []string - var i, j int - - var doSplit bool - for ; i < len(v); i++ { - if v[i] == ',' { - if doSplit { - doSplit = false - parts = append(parts, strings.TrimSpace(v[j:i])) - j = i + 1 - } else { - // Skip the first comma in the timestamp value since that - // separates the day from the rest of the timestamp. - // - // Tue, 17 Dec 2019 23:48:18 GMT - doSplit = true - } - } - } - // Add final part - if j < len(v) { - parts = append(parts, strings.TrimSpace(v[j:])) - } - - return parts, nil -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/host.go b/vendor/github.com/aws/smithy-go/transport/http/host.go deleted file mode 100644 index 6b290fec..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/host.go +++ /dev/null @@ -1,89 +0,0 @@ -package http - -import ( - "fmt" - "net" - "strconv" - "strings" -) - -// ValidateEndpointHost validates that the host string passed in is a valid RFC -// 3986 host. Returns error if the host is not valid. -func ValidateEndpointHost(host string) error { - var errors strings.Builder - var hostname string - var port string - var err error - - if strings.Contains(host, ":") { - hostname, port, err = net.SplitHostPort(host) - if err != nil { - errors.WriteString(fmt.Sprintf("\n endpoint %v, failed to parse, got ", host)) - errors.WriteString(err.Error()) - } - - if !ValidPortNumber(port) { - errors.WriteString(fmt.Sprintf("port number should be in range [0-65535], got %v", port)) - } - } else { - hostname = host - } - - labels := strings.Split(hostname, ".") - for i, label := range labels { - if i == len(labels)-1 && len(label) == 0 { - // Allow trailing dot for FQDN hosts. - continue - } - - if !ValidHostLabel(label) { - errors.WriteString("\nendpoint host domain labels must match \"[a-zA-Z0-9-]{1,63}\", but found: ") - errors.WriteString(label) - } - } - - if len(hostname) == 0 && len(port) != 0 { - errors.WriteString("\nendpoint host with port must not be empty") - } - - if len(hostname) > 255 { - errors.WriteString(fmt.Sprintf("\nendpoint host must be less than 255 characters, but was %d", len(hostname))) - } - - if len(errors.String()) > 0 { - return fmt.Errorf("invalid endpoint host%s", errors.String()) - } - return nil -} - -// ValidPortNumber returns whether the port is valid RFC 3986 port. -func ValidPortNumber(port string) bool { - i, err := strconv.Atoi(port) - if err != nil { - return false - } - - if i < 0 || i > 65535 { - return false - } - return true -} - -// ValidHostLabel returns whether the label is a valid RFC 3986 host abel. -func ValidHostLabel(label string) bool { - if l := len(label); l == 0 || l > 63 { - return false - } - for _, r := range label { - switch { - case r >= '0' && r <= '9': - case r >= 'A' && r <= 'Z': - case r >= 'a' && r <= 'z': - case r == '-': - default: - return false - } - } - - return true -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/internal/io/safe.go b/vendor/github.com/aws/smithy-go/transport/http/internal/io/safe.go deleted file mode 100644 index 941a8d6b..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/internal/io/safe.go +++ /dev/null @@ -1,75 +0,0 @@ -package io - -import ( - "io" - "sync" -) - -// NewSafeReadCloser returns a new safeReadCloser that wraps readCloser. -func NewSafeReadCloser(readCloser io.ReadCloser) io.ReadCloser { - sr := &safeReadCloser{ - readCloser: readCloser, - } - - if _, ok := readCloser.(io.WriterTo); ok { - return &safeWriteToReadCloser{safeReadCloser: sr} - } - - return sr -} - -// safeWriteToReadCloser wraps a safeReadCloser but exposes a WriteTo interface implementation. This will panic -// if the underlying io.ReadClose does not support WriteTo. Use NewSafeReadCloser to ensure the proper handling of this -// type. -type safeWriteToReadCloser struct { - *safeReadCloser -} - -// WriteTo implements the io.WriteTo interface. -func (r *safeWriteToReadCloser) WriteTo(w io.Writer) (int64, error) { - r.safeReadCloser.mtx.Lock() - defer r.safeReadCloser.mtx.Unlock() - - if r.safeReadCloser.closed { - return 0, io.EOF - } - - return r.safeReadCloser.readCloser.(io.WriterTo).WriteTo(w) -} - -// safeReadCloser wraps a io.ReadCloser and presents an io.ReadCloser interface. When Close is called on safeReadCloser -// the underlying Close method will be executed, and then the reference to the reader will be dropped. This type -// is meant to be used with the net/http library which will retain a reference to the request body for the lifetime -// of a goroutine connection. Wrapping in this manner will ensure that no data race conditions are falsely reported. -// This type is thread-safe. -type safeReadCloser struct { - readCloser io.ReadCloser - closed bool - mtx sync.Mutex -} - -// Read reads up to len(p) bytes into p from the underlying read. If the reader is closed io.EOF will be returned. -func (r *safeReadCloser) Read(p []byte) (n int, err error) { - r.mtx.Lock() - defer r.mtx.Unlock() - if r.closed { - return 0, io.EOF - } - - return r.readCloser.Read(p) -} - -// Close calls the underlying io.ReadCloser's Close method, removes the reference to the reader, and returns any error -// reported from Close. Subsequent calls to Close will always return a nil error. -func (r *safeReadCloser) Close() error { - r.mtx.Lock() - defer r.mtx.Unlock() - if r.closed { - return nil - } - - r.closed = true - rc := r.readCloser - r.readCloser = nil - return rc.Close() -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/md5_checksum.go b/vendor/github.com/aws/smithy-go/transport/http/md5_checksum.go deleted file mode 100644 index 5d6a4b23..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/md5_checksum.go +++ /dev/null @@ -1,25 +0,0 @@ -package http - -import ( - "crypto/md5" - "encoding/base64" - "fmt" - "io" -) - -// computeMD5Checksum computes base64 md5 checksum of an io.Reader's contents. -// Returns the byte slice of md5 checksum and an error. -func computeMD5Checksum(r io.Reader) ([]byte, error) { - h := md5.New() - // copy errors may be assumed to be from the body. - _, err := io.Copy(h, r) - if err != nil { - return nil, fmt.Errorf("failed to read body: %w", err) - } - - // encode the md5 checksum in base64. - sum := h.Sum(nil) - sum64 := make([]byte, base64.StdEncoding.EncodedLen(len(sum))) - base64.StdEncoding.Encode(sum64, sum) - return sum64, nil -} 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 deleted file mode 100644 index 1d3b218a..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_close_response_body.go +++ /dev/null @@ -1,79 +0,0 @@ -package http - -import ( - "context" - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" - "io" - "io/ioutil" -) - -// AddErrorCloseResponseBodyMiddleware adds the middleware to automatically -// close the response body of an operation request if the request response -// failed. -func AddErrorCloseResponseBodyMiddleware(stack *middleware.Stack) error { - return stack.Deserialize.Insert(&errorCloseResponseBodyMiddleware{}, "OperationDeserializer", middleware.Before) -} - -type errorCloseResponseBodyMiddleware struct{} - -func (*errorCloseResponseBodyMiddleware) ID() string { - return "ErrorCloseResponseBody" -} - -func (m *errorCloseResponseBodyMiddleware) HandleDeserialize( - ctx context.Context, input middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - output middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err := next.HandleDeserialize(ctx, input) - 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) - // Do not validate that the response closes successfully. - resp.Body.Close() - } - } - - return out, metadata, err -} - -// AddCloseResponseBodyMiddleware adds the middleware to automatically close -// the response body of an operation request, after the response had been -// deserialized. -func AddCloseResponseBodyMiddleware(stack *middleware.Stack) error { - return stack.Deserialize.Insert(&closeResponseBody{}, "OperationDeserializer", middleware.Before) -} - -type closeResponseBody struct{} - -func (*closeResponseBody) ID() string { - return "CloseResponseBody" -} - -func (m *closeResponseBody) HandleDeserialize( - ctx context.Context, input middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - output middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - out, metadata, err := next.HandleDeserialize(ctx, input) - if err != nil { - return out, metadata, err - } - - 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) - if copyErr != nil { - middleware.GetLogger(ctx).Logf(logging.Warn, "failed to discard remaining HTTP response body, this may affect connection reuse") - } - - closeErr := resp.Body.Close() - if closeErr != nil { - middleware.GetLogger(ctx).Logf(logging.Warn, "failed to close HTTP response body, this may affect connection reuse") - } - } - - return out, metadata, err -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_content_length.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_content_length.go deleted file mode 100644 index 9969389b..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_content_length.go +++ /dev/null @@ -1,84 +0,0 @@ -package http - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go/middleware" -) - -// ComputeContentLength provides a middleware to set the content-length -// header for the length of a serialize request body. -type ComputeContentLength struct { -} - -// AddComputeContentLengthMiddleware adds ComputeContentLength to the middleware -// stack's Build step. -func AddComputeContentLengthMiddleware(stack *middleware.Stack) error { - return stack.Build.Add(&ComputeContentLength{}, middleware.After) -} - -// ID returns the identifier for the ComputeContentLength. -func (m *ComputeContentLength) ID() string { return "ComputeContentLength" } - -// HandleBuild adds the length of the serialized request to the HTTP header -// if the length can be determined. -func (m *ComputeContentLength) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*Request) - if !ok { - return out, metadata, fmt.Errorf("unknown request type %T", req) - } - - // do nothing if request content-length was set to 0 or above. - if req.ContentLength >= 0 { - return next.HandleBuild(ctx, in) - } - - // attempt to compute stream length - if n, ok, err := req.StreamLength(); err != nil { - return out, metadata, fmt.Errorf( - "failed getting length of request stream, %w", err) - } else if ok { - req.ContentLength = n - } - - return next.HandleBuild(ctx, in) -} - -// validateContentLength provides a middleware to validate the content-length -// is valid (greater than zero), for the serialized request payload. -type validateContentLength struct{} - -// ValidateContentLengthHeader adds middleware that validates request content-length -// is set to value greater than zero. -func ValidateContentLengthHeader(stack *middleware.Stack) error { - return stack.Build.Add(&validateContentLength{}, middleware.After) -} - -// ID returns the identifier for the ComputeContentLength. -func (m *validateContentLength) ID() string { return "ValidateContentLength" } - -// HandleBuild adds the length of the serialized request to the HTTP header -// if the length can be determined. -func (m *validateContentLength) HandleBuild( - ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler, -) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - req, ok := in.Request.(*Request) - if !ok { - return out, metadata, fmt.Errorf("unknown request type %T", req) - } - - // if request content-length was set to less than 0, return an error - if req.ContentLength < 0 { - return out, metadata, fmt.Errorf( - "content length for payload is required and must be at least 0") - } - - return next.HandleBuild(ctx, in) -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_header_comment.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_header_comment.go deleted file mode 100644 index 855c2272..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_header_comment.go +++ /dev/null @@ -1,81 +0,0 @@ -package http - -import ( - "context" - "fmt" - "net/http" - - "github.com/aws/smithy-go/middleware" -) - -// WithHeaderComment instruments a middleware stack to append an HTTP field -// comment to the given header as specified in RFC 9110 -// (https://www.rfc-editor.org/rfc/rfc9110#name-comments). -// -// The header is case-insensitive. If the provided header exists when the -// middleware runs, the content will be inserted as-is enclosed in parentheses. -// -// Note that per the HTTP specification, comments are only allowed in fields -// containing "comment" as part of their field value definition, but this API -// will NOT verify whether the provided header is one of them. -// -// WithHeaderComment MAY be applied more than once to a middleware stack and/or -// more than once per header. -func WithHeaderComment(header, content string) func(*middleware.Stack) error { - return func(s *middleware.Stack) error { - m, err := getOrAddHeaderComment(s) - if err != nil { - return fmt.Errorf("get or add header comment: %v", err) - } - - m.values.Add(header, content) - return nil - } -} - -type headerCommentMiddleware struct { - values http.Header // hijack case-insensitive access APIs -} - -func (*headerCommentMiddleware) ID() string { - return "headerComment" -} - -func (m *headerCommentMiddleware) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) ( - out middleware.BuildOutput, metadata middleware.Metadata, err error, -) { - r, ok := in.Request.(*Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - for h, contents := range m.values { - for _, c := range contents { - if existing := r.Header.Get(h); existing != "" { - r.Header.Set(h, fmt.Sprintf("%s (%s)", existing, c)) - } - } - } - - return next.HandleBuild(ctx, in) -} - -func getOrAddHeaderComment(s *middleware.Stack) (*headerCommentMiddleware, error) { - id := (*headerCommentMiddleware)(nil).ID() - m, ok := s.Build.Get(id) - if !ok { - m := &headerCommentMiddleware{values: http.Header{}} - if err := s.Build.Add(m, middleware.After); err != nil { - return nil, fmt.Errorf("add build: %v", err) - } - - return m, nil - } - - hc, ok := m.(*headerCommentMiddleware) - if !ok { - return nil, fmt.Errorf("existing middleware w/ id %s is not *headerCommentMiddleware", id) - } - - return hc, nil -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_headers.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_headers.go deleted file mode 100644 index eac32b4b..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_headers.go +++ /dev/null @@ -1,167 +0,0 @@ -package http - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go/middleware" -) - -type isContentTypeAutoSet struct{} - -// SetIsContentTypeDefaultValue returns a Context specifying if the request's -// content-type header was set to a default value. -func SetIsContentTypeDefaultValue(ctx context.Context, isDefault bool) context.Context { - return context.WithValue(ctx, isContentTypeAutoSet{}, isDefault) -} - -// GetIsContentTypeDefaultValue returns if the content-type HTTP header on the -// request is a default value that was auto assigned by an operation -// serializer. Allows middleware post serialization to know if the content-type -// was auto set to a default value or not. -// -// Also returns false if the Context value was never updated to include if -// content-type was set to a default value. -func GetIsContentTypeDefaultValue(ctx context.Context) bool { - v, _ := ctx.Value(isContentTypeAutoSet{}).(bool) - return v -} - -// AddNoPayloadDefaultContentTypeRemover Adds the DefaultContentTypeRemover -// middleware to the stack after the operation serializer. This middleware will -// remove the content-type header from the request if it was set as a default -// value, and no request payload is present. -// -// Returns error if unable to add the middleware. -func AddNoPayloadDefaultContentTypeRemover(stack *middleware.Stack) (err error) { - err = stack.Serialize.Insert(removeDefaultContentType{}, - "OperationSerializer", middleware.After) - if err != nil { - return fmt.Errorf("failed to add %s serialize middleware, %w", - removeDefaultContentType{}.ID(), err) - } - - return nil -} - -// RemoveNoPayloadDefaultContentTypeRemover removes the -// DefaultContentTypeRemover middleware from the stack. Returns an error if -// unable to remove the middleware. -func RemoveNoPayloadDefaultContentTypeRemover(stack *middleware.Stack) (err error) { - _, err = stack.Serialize.Remove(removeDefaultContentType{}.ID()) - if err != nil { - return fmt.Errorf("failed to remove %s serialize middleware, %w", - removeDefaultContentType{}.ID(), err) - - } - return nil -} - -// removeDefaultContentType provides after serialization middleware that will -// remove the content-type header from an HTTP request if the header was set as -// a default value by the operation serializer, and there is no request payload. -type removeDefaultContentType struct{} - -// ID returns the middleware ID -func (removeDefaultContentType) ID() string { return "RemoveDefaultContentType" } - -// HandleSerialize implements the serialization middleware. -func (removeDefaultContentType) HandleSerialize( - ctx context.Context, input middleware.SerializeInput, next middleware.SerializeHandler, -) ( - out middleware.SerializeOutput, meta middleware.Metadata, err error, -) { - req, ok := input.Request.(*Request) - if !ok { - return out, meta, fmt.Errorf( - "unexpected request type %T for removeDefaultContentType middleware", - input.Request) - } - - if GetIsContentTypeDefaultValue(ctx) && req.GetStream() == nil { - req.Header.Del("Content-Type") - input.Request = req - } - - return next.HandleSerialize(ctx, input) -} - -type headerValue struct { - header string - value string - append bool -} - -type headerValueHelper struct { - headerValues []headerValue -} - -func (h *headerValueHelper) addHeaderValue(value headerValue) { - h.headerValues = append(h.headerValues, value) -} - -func (h *headerValueHelper) ID() string { - return "HTTPHeaderHelper" -} - -func (h *headerValueHelper) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) (out middleware.BuildOutput, metadata middleware.Metadata, err error) { - req, ok := in.Request.(*Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) - } - - for _, value := range h.headerValues { - if value.append { - req.Header.Add(value.header, value.value) - } else { - req.Header.Set(value.header, value.value) - } - } - - return next.HandleBuild(ctx, in) -} - -func getOrAddHeaderValueHelper(stack *middleware.Stack) (*headerValueHelper, error) { - id := (*headerValueHelper)(nil).ID() - m, ok := stack.Build.Get(id) - if !ok { - m = &headerValueHelper{} - err := stack.Build.Add(m, middleware.After) - if err != nil { - return nil, err - } - } - - requestUserAgent, ok := m.(*headerValueHelper) - if !ok { - return nil, fmt.Errorf("%T for %s middleware did not match expected type", m, id) - } - - return requestUserAgent, nil -} - -// AddHeaderValue returns a stack mutator that adds the header value pair to header. -// Appends to any existing values if present. -func AddHeaderValue(header string, value string) func(stack *middleware.Stack) error { - return func(stack *middleware.Stack) error { - helper, err := getOrAddHeaderValueHelper(stack) - if err != nil { - return err - } - helper.addHeaderValue(headerValue{header: header, value: value, append: true}) - return nil - } -} - -// SetHeaderValue returns a stack mutator that adds the header value pair to header. -// Replaces any existing values if present. -func SetHeaderValue(header string, value string) func(stack *middleware.Stack) error { - return func(stack *middleware.Stack) error { - helper, err := getOrAddHeaderValueHelper(stack) - if err != nil { - return err - } - helper.addHeaderValue(headerValue{header: header, value: value, append: false}) - return nil - } -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_http_logging.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_http_logging.go deleted file mode 100644 index d5909b0a..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_http_logging.go +++ /dev/null @@ -1,75 +0,0 @@ -package http - -import ( - "context" - "fmt" - "net/http/httputil" - - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" -) - -// RequestResponseLogger is a deserialize middleware that will log the request and response HTTP messages and optionally -// their respective bodies. Will not perform any logging if none of the options are set. -type RequestResponseLogger struct { - LogRequest bool - LogRequestWithBody bool - - LogResponse bool - LogResponseWithBody bool -} - -// ID is the middleware identifier. -func (r *RequestResponseLogger) ID() string { - return "RequestResponseLogger" -} - -// HandleDeserialize will log the request and response HTTP messages if configured accordingly. -func (r *RequestResponseLogger) HandleDeserialize( - ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler, -) ( - out middleware.DeserializeOutput, metadata middleware.Metadata, err error, -) { - logger := middleware.GetLogger(ctx) - - if r.LogRequest || r.LogRequestWithBody { - smithyRequest, ok := in.Request.(*Request) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", in) - } - - rc := smithyRequest.Build(ctx) - reqBytes, err := httputil.DumpRequestOut(rc, r.LogRequestWithBody) - if err != nil { - return out, metadata, err - } - - logger.Logf(logging.Debug, "Request\n%v", string(reqBytes)) - - if r.LogRequestWithBody { - smithyRequest, err = smithyRequest.SetStream(rc.Body) - if err != nil { - return out, metadata, err - } - in.Request = smithyRequest - } - } - - out, metadata, err = next.HandleDeserialize(ctx, in) - - if (err == nil) && (r.LogResponse || r.LogResponseWithBody) { - smithyResponse, ok := out.RawResponse.(*Response) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type %T", out.RawResponse) - } - - respBytes, err := httputil.DumpResponse(smithyResponse.Response, r.LogResponseWithBody) - if err != nil { - return out, metadata, fmt.Errorf("failed to dump response %w", err) - } - - logger.Logf(logging.Debug, "Response\n%v", string(respBytes)) - } - - return out, metadata, err -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_metadata.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_metadata.go deleted file mode 100644 index d6079b25..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_metadata.go +++ /dev/null @@ -1,51 +0,0 @@ -package http - -import ( - "context" - - "github.com/aws/smithy-go/middleware" -) - -type ( - hostnameImmutableKey struct{} - hostPrefixDisableKey struct{} -) - -// GetHostnameImmutable retrieves whether the endpoint hostname should be considered -// immutable or not. -// -// Scoped to stack values. Use middleware#ClearStackValues to clear all stack -// values. -func GetHostnameImmutable(ctx context.Context) (v bool) { - v, _ = middleware.GetStackValue(ctx, hostnameImmutableKey{}).(bool) - return v -} - -// SetHostnameImmutable sets or modifies whether the request's endpoint hostname -// should be considered immutable or not. -// -// Scoped to stack values. Use middleware#ClearStackValues to clear all stack -// values. -func SetHostnameImmutable(ctx context.Context, value bool) context.Context { - return middleware.WithStackValue(ctx, hostnameImmutableKey{}, value) -} - -// IsEndpointHostPrefixDisabled retrieves whether the hostname prefixing is -// disabled. -// -// Scoped to stack values. Use middleware#ClearStackValues to clear all stack -// values. -func IsEndpointHostPrefixDisabled(ctx context.Context) (v bool) { - v, _ = middleware.GetStackValue(ctx, hostPrefixDisableKey{}).(bool) - return v -} - -// DisableEndpointHostPrefix sets or modifies whether the request's endpoint host -// prefixing should be disabled. If value is true, endpoint host prefixing -// will be disabled. -// -// Scoped to stack values. Use middleware#ClearStackValues to clear all stack -// values. -func DisableEndpointHostPrefix(ctx context.Context, value bool) context.Context { - return middleware.WithStackValue(ctx, hostPrefixDisableKey{}, value) -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/middleware_min_proto.go b/vendor/github.com/aws/smithy-go/transport/http/middleware_min_proto.go deleted file mode 100644 index 326cb8a6..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/middleware_min_proto.go +++ /dev/null @@ -1,79 +0,0 @@ -package http - -import ( - "context" - "fmt" - "github.com/aws/smithy-go/middleware" - "strings" -) - -// MinimumProtocolError is an error type indicating that the established connection did not meet the expected minimum -// HTTP protocol version. -type MinimumProtocolError struct { - proto string - expectedProtoMajor int - expectedProtoMinor int -} - -// Error returns the error message. -func (m *MinimumProtocolError) Error() string { - return fmt.Sprintf("operation requires minimum HTTP protocol of HTTP/%d.%d, but was %s", - m.expectedProtoMajor, m.expectedProtoMinor, m.proto) -} - -// RequireMinimumProtocol is a deserialization middleware that asserts that the established HTTP connection -// meets the minimum major ad minor version. -type RequireMinimumProtocol struct { - ProtoMajor int - ProtoMinor int -} - -// AddRequireMinimumProtocol adds the RequireMinimumProtocol middleware to the stack using the provided minimum -// protocol major and minor version. -func AddRequireMinimumProtocol(stack *middleware.Stack, major, minor int) error { - return stack.Deserialize.Insert(&RequireMinimumProtocol{ - ProtoMajor: major, - ProtoMinor: minor, - }, "OperationDeserializer", middleware.Before) -} - -// ID returns the middleware identifier string. -func (r *RequireMinimumProtocol) ID() string { - return "RequireMinimumProtocol" -} - -// HandleDeserialize asserts that the established connection is a HTTP connection with the minimum major and minor -// protocol version. -func (r *RequireMinimumProtocol) 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 - } - - response, ok := out.RawResponse.(*Response) - if !ok { - return out, metadata, fmt.Errorf("unknown transport type: %T", out.RawResponse) - } - - if !strings.HasPrefix(response.Proto, "HTTP") { - return out, metadata, &MinimumProtocolError{ - proto: response.Proto, - expectedProtoMajor: r.ProtoMajor, - expectedProtoMinor: r.ProtoMinor, - } - } - - if response.ProtoMajor < r.ProtoMajor || response.ProtoMinor < r.ProtoMinor { - return out, metadata, &MinimumProtocolError{ - proto: response.Proto, - expectedProtoMajor: r.ProtoMajor, - expectedProtoMinor: r.ProtoMinor, - } - } - - return out, metadata, err -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/properties.go b/vendor/github.com/aws/smithy-go/transport/http/properties.go deleted file mode 100644 index c65aa393..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/properties.go +++ /dev/null @@ -1,80 +0,0 @@ -package http - -import smithy "github.com/aws/smithy-go" - -type ( - sigV4SigningNameKey struct{} - sigV4SigningRegionKey struct{} - - sigV4ASigningNameKey struct{} - sigV4ASigningRegionsKey struct{} - - isUnsignedPayloadKey struct{} - disableDoubleEncodingKey struct{} -) - -// GetSigV4SigningName gets the signing name from Properties. -func GetSigV4SigningName(p *smithy.Properties) (string, bool) { - v, ok := p.Get(sigV4SigningNameKey{}).(string) - return v, ok -} - -// SetSigV4SigningName sets the signing name on Properties. -func SetSigV4SigningName(p *smithy.Properties, name string) { - p.Set(sigV4SigningNameKey{}, name) -} - -// GetSigV4SigningRegion gets the signing region from Properties. -func GetSigV4SigningRegion(p *smithy.Properties) (string, bool) { - v, ok := p.Get(sigV4SigningRegionKey{}).(string) - return v, ok -} - -// SetSigV4SigningRegion sets the signing region on Properties. -func SetSigV4SigningRegion(p *smithy.Properties, region string) { - p.Set(sigV4SigningRegionKey{}, region) -} - -// GetSigV4ASigningName gets the v4a signing name from Properties. -func GetSigV4ASigningName(p *smithy.Properties) (string, bool) { - v, ok := p.Get(sigV4ASigningNameKey{}).(string) - return v, ok -} - -// SetSigV4ASigningName sets the signing name on Properties. -func SetSigV4ASigningName(p *smithy.Properties, name string) { - p.Set(sigV4ASigningNameKey{}, name) -} - -// GetSigV4ASigningRegion gets the v4a signing region set from Properties. -func GetSigV4ASigningRegions(p *smithy.Properties) ([]string, bool) { - v, ok := p.Get(sigV4ASigningRegionsKey{}).([]string) - return v, ok -} - -// SetSigV4ASigningRegions sets the v4a signing region set on Properties. -func SetSigV4ASigningRegions(p *smithy.Properties, regions []string) { - p.Set(sigV4ASigningRegionsKey{}, regions) -} - -// GetIsUnsignedPayload gets whether the payload is unsigned from Properties. -func GetIsUnsignedPayload(p *smithy.Properties) (bool, bool) { - v, ok := p.Get(isUnsignedPayloadKey{}).(bool) - return v, ok -} - -// SetIsUnsignedPayload sets whether the payload is unsigned on Properties. -func SetIsUnsignedPayload(p *smithy.Properties, isUnsignedPayload bool) { - p.Set(isUnsignedPayloadKey{}, isUnsignedPayload) -} - -// GetDisableDoubleEncoding gets whether the payload is unsigned from Properties. -func GetDisableDoubleEncoding(p *smithy.Properties) (bool, bool) { - v, ok := p.Get(disableDoubleEncodingKey{}).(bool) - return v, ok -} - -// SetDisableDoubleEncoding sets whether the payload is unsigned on Properties. -func SetDisableDoubleEncoding(p *smithy.Properties, disableDoubleEncoding bool) { - p.Set(disableDoubleEncodingKey{}, disableDoubleEncoding) -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/request.go b/vendor/github.com/aws/smithy-go/transport/http/request.go deleted file mode 100644 index 7177d6f9..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/request.go +++ /dev/null @@ -1,189 +0,0 @@ -package http - -import ( - "context" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "strings" - - iointernal "github.com/aws/smithy-go/transport/http/internal/io" -) - -// Request provides the HTTP specific request structure for HTTP specific -// middleware steps to use to serialize input, and send an operation's request. -type Request struct { - *http.Request - stream io.Reader - isStreamSeekable bool - streamStartPos int64 -} - -// NewStackRequest returns an initialized request ready to be populated with the -// HTTP request details. Returns empty interface so the function can be used as -// a parameter to the Smithy middleware Stack constructor. -func NewStackRequest() interface{} { - return &Request{ - Request: &http.Request{ - URL: &url.URL{}, - Header: http.Header{}, - ContentLength: -1, // default to unknown length - }, - } -} - -// IsHTTPS returns if the request is HTTPS. Returns false if no endpoint URL is set. -func (r *Request) IsHTTPS() bool { - if r.URL == nil { - return false - } - return strings.EqualFold(r.URL.Scheme, "https") -} - -// Clone returns a deep copy of the Request for the new context. A reference to -// the Stream is copied, but the underlying stream is not copied. -func (r *Request) Clone() *Request { - rc := *r - rc.Request = rc.Request.Clone(context.TODO()) - return &rc -} - -// StreamLength returns the number of bytes of the serialized stream attached -// to the request and ok set. If the length cannot be determined, an error will -// be returned. -func (r *Request) StreamLength() (size int64, ok bool, err error) { - return streamLength(r.stream, r.isStreamSeekable, r.streamStartPos) -} - -func streamLength(stream io.Reader, seekable bool, startPos int64) (size int64, ok bool, err error) { - if stream == nil { - return 0, true, nil - } - - if l, ok := stream.(interface{ Len() int }); ok { - return int64(l.Len()), true, nil - } - - if !seekable { - return 0, false, nil - } - - s := stream.(io.Seeker) - endOffset, err := s.Seek(0, io.SeekEnd) - if err != nil { - return 0, false, err - } - - // The reason to seek to streamStartPos instead of 0 is to ensure that the - // SDK only sends the stream from the starting position the user's - // application provided it to the SDK at. For example application opens a - // file, and wants to skip the first N bytes uploading the rest. The - // application would move the file's offset N bytes, then hand it off to - // the SDK to send the remaining. The SDK should respect that initial offset. - _, err = s.Seek(startPos, io.SeekStart) - if err != nil { - return 0, false, err - } - - return endOffset - startPos, true, nil -} - -// RewindStream will rewind the io.Reader to the relative start position if it -// is an io.Seeker. -func (r *Request) RewindStream() error { - // If there is no stream there is nothing to rewind. - if r.stream == nil { - return nil - } - - if !r.isStreamSeekable { - return fmt.Errorf("request stream is not seekable") - } - _, err := r.stream.(io.Seeker).Seek(r.streamStartPos, io.SeekStart) - return err -} - -// GetStream returns the request stream io.Reader if a stream is set. If no -// stream is present nil will be returned. -func (r *Request) GetStream() io.Reader { - return r.stream -} - -// IsStreamSeekable returns whether the stream is seekable. -func (r *Request) IsStreamSeekable() bool { - return r.isStreamSeekable -} - -// SetStream returns a clone of the request with the stream set to the provided -// reader. May return an error if the provided reader is seekable but returns -// an error. -func (r *Request) SetStream(reader io.Reader) (rc *Request, err error) { - rc = r.Clone() - - if reader == http.NoBody { - reader = nil - } - - var isStreamSeekable bool - var streamStartPos int64 - switch v := reader.(type) { - case io.Seeker: - n, err := v.Seek(0, io.SeekCurrent) - if err != nil { - return r, err - } - isStreamSeekable = true - streamStartPos = n - default: - // If the stream length can be determined, and is determined to be empty, - // use a nil stream to prevent confusion between empty vs not-empty - // streams. - length, ok, err := streamLength(reader, false, 0) - if err != nil { - return nil, err - } else if ok && length == 0 { - reader = nil - } - } - - rc.stream = reader - rc.isStreamSeekable = isStreamSeekable - rc.streamStartPos = streamStartPos - - return rc, err -} - -// Build returns a build standard HTTP request value from the Smithy request. -// The request's stream is wrapped in a safe container that allows it to be -// reused for subsequent attempts. -func (r *Request) Build(ctx context.Context) *http.Request { - req := r.Request.Clone(ctx) - - if r.stream == nil && req.ContentLength == -1 { - req.ContentLength = 0 - } - - switch stream := r.stream.(type) { - case *io.PipeReader: - req.Body = ioutil.NopCloser(stream) - req.ContentLength = -1 - default: - // HTTP Client Request must only have a non-nil body if the - // ContentLength is explicitly unknown (-1) or non-zero. The HTTP - // 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)) - } - } - - return req -} - -// RequestCloner is a function that can take an input request type and clone the request -// for use in a subsequent retry attempt. -func RequestCloner(v interface{}) interface{} { - return v.(*Request).Clone() -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/response.go b/vendor/github.com/aws/smithy-go/transport/http/response.go deleted file mode 100644 index 0c13bfcc..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/response.go +++ /dev/null @@ -1,34 +0,0 @@ -package http - -import ( - "fmt" - "net/http" -) - -// Response provides the HTTP specific response structure for HTTP specific -// middleware steps to use to deserialize the response from an operation call. -type Response struct { - *http.Response -} - -// ResponseError provides the HTTP centric error type wrapping the underlying -// error with the HTTP response value. -type ResponseError struct { - Response *Response - Err error -} - -// HTTPStatusCode returns the HTTP response status code received from the service. -func (e *ResponseError) HTTPStatusCode() int { return e.Response.StatusCode } - -// HTTPResponse returns the HTTP response received from the service. -func (e *ResponseError) HTTPResponse() *Response { return e.Response } - -// Unwrap returns the nested error if any, or nil. -func (e *ResponseError) Unwrap() error { return e.Err } - -func (e *ResponseError) Error() string { - return fmt.Sprintf( - "http response error StatusCode: %d, %v", - e.Response.StatusCode, e.Err) -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/time.go b/vendor/github.com/aws/smithy-go/transport/http/time.go deleted file mode 100644 index 607b196a..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/time.go +++ /dev/null @@ -1,13 +0,0 @@ -package http - -import ( - "time" - - smithytime "github.com/aws/smithy-go/time" -) - -// ParseTime parses a time string like the HTTP Date header. This uses a more -// relaxed rule set for date parsing compared to the standard library. -func ParseTime(text string) (t time.Time, err error) { - return smithytime.ParseHTTPDate(text) -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/url.go b/vendor/github.com/aws/smithy-go/transport/http/url.go deleted file mode 100644 index 60a5fc10..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/url.go +++ /dev/null @@ -1,44 +0,0 @@ -package http - -import "strings" - -// JoinPath returns an absolute URL path composed of the two paths provided. -// Enforces that the returned path begins with '/'. If added path is empty the -// returned path suffix will match the first parameter suffix. -func JoinPath(a, b string) string { - if len(a) == 0 { - a = "/" - } else if a[0] != '/' { - a = "/" + a - } - - if len(b) != 0 && b[0] == '/' { - b = b[1:] - } - - if len(b) != 0 && len(a) > 1 && a[len(a)-1] != '/' { - a = a + "/" - } - - return a + b -} - -// JoinRawQuery returns an absolute raw query expression. Any duplicate '&' -// will be collapsed to single separator between values. -func JoinRawQuery(a, b string) string { - a = strings.TrimFunc(a, isAmpersand) - b = strings.TrimFunc(b, isAmpersand) - - if len(a) == 0 { - return b - } - if len(b) == 0 { - return a - } - - return a + "&" + b -} - -func isAmpersand(v rune) bool { - return v == '&' -} diff --git a/vendor/github.com/aws/smithy-go/transport/http/user_agent.go b/vendor/github.com/aws/smithy-go/transport/http/user_agent.go deleted file mode 100644 index 71a7e0d8..00000000 --- a/vendor/github.com/aws/smithy-go/transport/http/user_agent.go +++ /dev/null @@ -1,37 +0,0 @@ -package http - -import ( - "strings" -) - -// UserAgentBuilder is a builder for a HTTP User-Agent string. -type UserAgentBuilder struct { - sb strings.Builder -} - -// NewUserAgentBuilder returns a new UserAgentBuilder. -func NewUserAgentBuilder() *UserAgentBuilder { - return &UserAgentBuilder{sb: strings.Builder{}} -} - -// AddKey adds the named component/product to the agent string -func (u *UserAgentBuilder) AddKey(key string) { - u.appendTo(key) -} - -// AddKeyValue adds the named key to the agent string with the given value. -func (u *UserAgentBuilder) AddKeyValue(key, value string) { - u.appendTo(key + "/" + value) -} - -// Build returns the constructed User-Agent string. May be called multiple times. -func (u *UserAgentBuilder) Build() string { - return u.sb.String() -} - -func (u *UserAgentBuilder) appendTo(value string) { - if u.sb.Len() > 0 { - u.sb.WriteRune(' ') - } - u.sb.WriteString(value) -} diff --git a/vendor/github.com/aws/smithy-go/validation.go b/vendor/github.com/aws/smithy-go/validation.go deleted file mode 100644 index b5eedc1f..00000000 --- a/vendor/github.com/aws/smithy-go/validation.go +++ /dev/null @@ -1,140 +0,0 @@ -package smithy - -import ( - "bytes" - "fmt" - "strings" -) - -// An InvalidParamsError provides wrapping of invalid parameter errors found when -// validating API operation input parameters. -type InvalidParamsError struct { - // Context is the base context of the invalid parameter group. - Context string - errs []InvalidParamError -} - -// Add adds a new invalid parameter error to the collection of invalid -// parameters. The context of the invalid parameter will be updated to reflect -// this collection. -func (e *InvalidParamsError) Add(err InvalidParamError) { - err.SetContext(e.Context) - e.errs = append(e.errs, err) -} - -// AddNested adds the invalid parameter errors from another InvalidParamsError -// value into this collection. The nested errors will have their nested context -// updated and base context to reflect the merging. -// -// Use for nested validations errors. -func (e *InvalidParamsError) AddNested(nestedCtx string, nested InvalidParamsError) { - for _, err := range nested.errs { - err.SetContext(e.Context) - err.AddNestedContext(nestedCtx) - e.errs = append(e.errs, err) - } -} - -// Len returns the number of invalid parameter errors -func (e *InvalidParamsError) Len() int { - return len(e.errs) -} - -// Error returns the string formatted form of the invalid parameters. -func (e InvalidParamsError) Error() string { - w := &bytes.Buffer{} - fmt.Fprintf(w, "%d validation error(s) found.\n", len(e.errs)) - - for _, err := range e.errs { - fmt.Fprintf(w, "- %s\n", err.Error()) - } - - return w.String() -} - -// Errs returns a slice of the invalid parameters -func (e InvalidParamsError) Errs() []error { - errs := make([]error, len(e.errs)) - for i := 0; i < len(errs); i++ { - errs[i] = e.errs[i] - } - - return errs -} - -// An InvalidParamError represents an invalid parameter error type. -type InvalidParamError interface { - error - - // Field name the error occurred on. - Field() string - - // SetContext updates the context of the error. - SetContext(string) - - // AddNestedContext updates the error's context to include a nested level. - AddNestedContext(string) -} - -type invalidParamError struct { - context string - nestedContext string - field string - reason string -} - -// Error returns the string version of the invalid parameter error. -func (e invalidParamError) Error() string { - return fmt.Sprintf("%s, %s.", e.reason, e.Field()) -} - -// Field Returns the field and context the error occurred. -func (e invalidParamError) Field() string { - sb := &strings.Builder{} - sb.WriteString(e.context) - if sb.Len() > 0 { - if len(e.nestedContext) == 0 || (len(e.nestedContext) > 0 && e.nestedContext[:1] != "[") { - sb.WriteRune('.') - } - } - if len(e.nestedContext) > 0 { - sb.WriteString(e.nestedContext) - sb.WriteRune('.') - } - sb.WriteString(e.field) - return sb.String() -} - -// SetContext updates the base context of the error. -func (e *invalidParamError) SetContext(ctx string) { - e.context = ctx -} - -// AddNestedContext prepends a context to the field's path. -func (e *invalidParamError) AddNestedContext(ctx string) { - if len(e.nestedContext) == 0 { - e.nestedContext = ctx - return - } - // Check if our nested context is an index into a slice or map - if e.nestedContext[:1] != "[" { - e.nestedContext = fmt.Sprintf("%s.%s", ctx, e.nestedContext) - return - } - e.nestedContext = ctx + e.nestedContext -} - -// An ParamRequiredError represents an required parameter error. -type ParamRequiredError struct { - invalidParamError -} - -// NewErrParamRequired creates a new required parameter error. -func NewErrParamRequired(field string) *ParamRequiredError { - return &ParamRequiredError{ - invalidParamError{ - field: field, - reason: fmt.Sprintf("missing required field"), - }, - } -} diff --git a/vendor/github.com/aws/smithy-go/waiter/logger.go b/vendor/github.com/aws/smithy-go/waiter/logger.go deleted file mode 100644 index 8d70a03f..00000000 --- a/vendor/github.com/aws/smithy-go/waiter/logger.go +++ /dev/null @@ -1,36 +0,0 @@ -package waiter - -import ( - "context" - "fmt" - - "github.com/aws/smithy-go/logging" - "github.com/aws/smithy-go/middleware" -) - -// Logger is the Logger middleware used by the waiter to log an attempt -type Logger struct { - // Attempt is the current attempt to be logged - Attempt int64 -} - -// ID representing the Logger middleware -func (*Logger) ID() string { - return "WaiterLogger" -} - -// HandleInitialize performs handling of request in initialize stack step -func (m *Logger) HandleInitialize(ctx context.Context, in middleware.InitializeInput, next middleware.InitializeHandler) ( - out middleware.InitializeOutput, metadata middleware.Metadata, err error, -) { - logger := middleware.GetLogger(ctx) - - logger.Logf(logging.Debug, fmt.Sprintf("attempting waiter request, attempt count: %d", m.Attempt)) - - return next.HandleInitialize(ctx, in) -} - -// AddLogger is a helper util to add waiter logger after `SetLogger` middleware in -func (m Logger) AddLogger(stack *middleware.Stack) error { - return stack.Initialize.Insert(&m, "SetLogger", middleware.After) -} diff --git a/vendor/github.com/aws/smithy-go/waiter/waiter.go b/vendor/github.com/aws/smithy-go/waiter/waiter.go deleted file mode 100644 index 03e46e2e..00000000 --- a/vendor/github.com/aws/smithy-go/waiter/waiter.go +++ /dev/null @@ -1,66 +0,0 @@ -package waiter - -import ( - "fmt" - "math" - "time" - - "github.com/aws/smithy-go/rand" -) - -// ComputeDelay computes delay between waiter attempts. The function takes in a current attempt count, -// minimum delay, maximum delay, and remaining wait time for waiter as input. The inputs minDelay and maxDelay -// must always be greater than 0, along with minDelay lesser than or equal to maxDelay. -// -// Returns the computed delay and if next attempt count is possible within the given input time constraints. -// Note that the zeroth attempt results in no delay. -func ComputeDelay(attempt int64, minDelay, maxDelay, remainingTime time.Duration) (delay time.Duration, err error) { - // zeroth attempt, no delay - if attempt <= 0 { - return 0, nil - } - - // remainingTime is zero or less, no delay - if remainingTime <= 0 { - return 0, nil - } - - // validate min delay is greater than 0 - if minDelay == 0 { - return 0, fmt.Errorf("minDelay must be greater than zero when computing Delay") - } - - // validate max delay is greater than 0 - if maxDelay == 0 { - return 0, fmt.Errorf("maxDelay must be greater than zero when computing Delay") - } - - // Get attempt ceiling to prevent integer overflow. - attemptCeiling := (math.Log(float64(maxDelay/minDelay)) / math.Log(2)) + 1 - - if attempt > int64(attemptCeiling) { - delay = maxDelay - } else { - // Compute exponential delay based on attempt. - ri := 1 << uint64(attempt-1) - // compute delay - delay = minDelay * time.Duration(ri) - } - - if delay != minDelay { - // randomize to get jitter between min delay and delay value - d, err := rand.CryptoRandInt63n(int64(delay - minDelay)) - if err != nil { - return 0, fmt.Errorf("error computing retry jitter, %w", err) - } - - delay = time.Duration(d) + minDelay - } - - // check if this is the last attempt possible and compute delay accordingly - if remainingTime-delay <= minDelay { - delay = remainingTime - minDelay - } - - return delay, nil -} diff --git a/vendor/github.com/bgentry/go-netrc/LICENSE b/vendor/github.com/bgentry/go-netrc/LICENSE deleted file mode 100644 index aade9a58..00000000 --- a/vendor/github.com/bgentry/go-netrc/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Original version Copyright © 2010 Fazlul Shahriar . Newer -portions Copyright © 2014 Blake Gentry . - -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/github.com/bgentry/go-netrc/netrc/netrc.go b/vendor/github.com/bgentry/go-netrc/netrc/netrc.go deleted file mode 100644 index ea49987c..00000000 --- a/vendor/github.com/bgentry/go-netrc/netrc/netrc.go +++ /dev/null @@ -1,510 +0,0 @@ -package netrc - -import ( - "bufio" - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -type tkType int - -const ( - tkMachine tkType = iota - tkDefault - tkLogin - tkPassword - tkAccount - tkMacdef - tkComment - tkWhitespace -) - -var keywords = map[string]tkType{ - "machine": tkMachine, - "default": tkDefault, - "login": tkLogin, - "password": tkPassword, - "account": tkAccount, - "macdef": tkMacdef, - "#": tkComment, -} - -type Netrc struct { - tokens []*token - machines []*Machine - macros Macros - updateLock sync.Mutex -} - -// FindMachine returns the Machine in n named by name. If a machine named by -// name exists, it is returned. If no Machine with name name is found and there -// is a ``default'' machine, the ``default'' machine is returned. Otherwise, nil -// is returned. -func (n *Netrc) FindMachine(name string) (m *Machine) { - // TODO(bgentry): not safe for concurrency - var def *Machine - for _, m = range n.machines { - if m.Name == name { - return m - } - if m.IsDefault() { - def = m - } - } - if def == nil { - return nil - } - return def -} - -// MarshalText implements the encoding.TextMarshaler interface to encode a -// Netrc into text format. -func (n *Netrc) MarshalText() (text []byte, err error) { - // TODO(bgentry): not safe for concurrency - for i := range n.tokens { - switch n.tokens[i].kind { - case tkComment, tkDefault, tkWhitespace: // always append these types - text = append(text, n.tokens[i].rawkind...) - default: - if n.tokens[i].value != "" { // skip empty-value tokens - text = append(text, n.tokens[i].rawkind...) - } - } - if n.tokens[i].kind == tkMacdef { - text = append(text, ' ') - text = append(text, n.tokens[i].macroName...) - } - text = append(text, n.tokens[i].rawvalue...) - } - return -} - -func (n *Netrc) NewMachine(name, login, password, account string) *Machine { - n.updateLock.Lock() - defer n.updateLock.Unlock() - - prefix := "\n" - if len(n.tokens) == 0 { - prefix = "" - } - m := &Machine{ - Name: name, - Login: login, - Password: password, - Account: account, - - nametoken: &token{ - kind: tkMachine, - rawkind: []byte(prefix + "machine"), - value: name, - rawvalue: []byte(" " + name), - }, - logintoken: &token{ - kind: tkLogin, - rawkind: []byte("\n\tlogin"), - value: login, - rawvalue: []byte(" " + login), - }, - passtoken: &token{ - kind: tkPassword, - rawkind: []byte("\n\tpassword"), - value: password, - rawvalue: []byte(" " + password), - }, - accounttoken: &token{ - kind: tkAccount, - rawkind: []byte("\n\taccount"), - value: account, - rawvalue: []byte(" " + account), - }, - } - n.insertMachineTokensBeforeDefault(m) - for i := range n.machines { - if n.machines[i].IsDefault() { - n.machines = append(append(n.machines[:i], m), n.machines[i:]...) - return m - } - } - n.machines = append(n.machines, m) - return m -} - -func (n *Netrc) insertMachineTokensBeforeDefault(m *Machine) { - newtokens := []*token{m.nametoken} - if m.logintoken.value != "" { - newtokens = append(newtokens, m.logintoken) - } - if m.passtoken.value != "" { - newtokens = append(newtokens, m.passtoken) - } - if m.accounttoken.value != "" { - newtokens = append(newtokens, m.accounttoken) - } - for i := range n.tokens { - if n.tokens[i].kind == tkDefault { - // found the default, now insert tokens before it - n.tokens = append(n.tokens[:i], append(newtokens, n.tokens[i:]...)...) - return - } - } - // didn't find a default, just add the newtokens to the end - n.tokens = append(n.tokens, newtokens...) - return -} - -func (n *Netrc) RemoveMachine(name string) { - n.updateLock.Lock() - defer n.updateLock.Unlock() - - for i := range n.machines { - if n.machines[i] != nil && n.machines[i].Name == name { - m := n.machines[i] - for _, t := range []*token{ - m.nametoken, m.logintoken, m.passtoken, m.accounttoken, - } { - n.removeToken(t) - } - n.machines = append(n.machines[:i], n.machines[i+1:]...) - return - } - } -} - -func (n *Netrc) removeToken(t *token) { - if t != nil { - for i := range n.tokens { - if n.tokens[i] == t { - n.tokens = append(n.tokens[:i], n.tokens[i+1:]...) - return - } - } - } -} - -// Machine contains information about a remote machine. -type Machine struct { - Name string - Login string - Password string - Account string - - nametoken *token - logintoken *token - passtoken *token - accounttoken *token -} - -// IsDefault returns true if the machine is a "default" token, denoted by an -// empty name. -func (m *Machine) IsDefault() bool { - return m.Name == "" -} - -// UpdatePassword sets the password for the Machine m. -func (m *Machine) UpdatePassword(newpass string) { - m.Password = newpass - updateTokenValue(m.passtoken, newpass) -} - -// UpdateLogin sets the login for the Machine m. -func (m *Machine) UpdateLogin(newlogin string) { - m.Login = newlogin - updateTokenValue(m.logintoken, newlogin) -} - -// UpdateAccount sets the login for the Machine m. -func (m *Machine) UpdateAccount(newaccount string) { - m.Account = newaccount - updateTokenValue(m.accounttoken, newaccount) -} - -func updateTokenValue(t *token, value string) { - oldvalue := t.value - t.value = value - newraw := make([]byte, len(t.rawvalue)) - copy(newraw, t.rawvalue) - t.rawvalue = append( - bytes.TrimSuffix(newraw, []byte(oldvalue)), - []byte(value)..., - ) -} - -// Macros contains all the macro definitions in a netrc file. -type Macros map[string]string - -type token struct { - kind tkType - macroName string - value string - rawkind []byte - rawvalue []byte -} - -// Error represents a netrc file parse error. -type Error struct { - LineNum int // Line number - Msg string // Error message -} - -// Error returns a string representation of error e. -func (e *Error) Error() string { - return fmt.Sprintf("line %d: %s", e.LineNum, e.Msg) -} - -func (e *Error) BadDefaultOrder() bool { - return e.Msg == errBadDefaultOrder -} - -const errBadDefaultOrder = "default token must appear after all machine tokens" - -// scanLinesKeepPrefix is a split function for a Scanner that returns each line -// of text. The returned token may include newlines if they are before the -// first non-space character. The returned line may be empty. The end-of-line -// marker is one optional carriage return followed by one mandatory newline. In -// regular expression notation, it is `\r?\n`. The last non-empty line of -// input will be returned even if it has no newline. -func scanLinesKeepPrefix(data []byte, atEOF bool) (advance int, token []byte, err error) { - if atEOF && len(data) == 0 { - return 0, nil, nil - } - // Skip leading spaces. - start := 0 - for width := 0; start < len(data); start += width { - var r rune - r, width = utf8.DecodeRune(data[start:]) - if !unicode.IsSpace(r) { - break - } - } - if i := bytes.IndexByte(data[start:], '\n'); i >= 0 { - // We have a full newline-terminated line. - return start + i, data[0 : start+i], nil - } - // If we're at EOF, we have a final, non-terminated line. Return it. - if atEOF { - return len(data), data, nil - } - // Request more data. - return 0, nil, nil -} - -// scanWordsKeepPrefix is a split function for a Scanner that returns each -// space-separated word of text, with prefixing spaces included. It will never -// return an empty string. The definition of space is set by unicode.IsSpace. -// -// Adapted from bufio.ScanWords(). -func scanTokensKeepPrefix(data []byte, atEOF bool) (advance int, token []byte, err error) { - // Skip leading spaces. - start := 0 - for width := 0; start < len(data); start += width { - var r rune - r, width = utf8.DecodeRune(data[start:]) - if !unicode.IsSpace(r) { - break - } - } - if atEOF && len(data) == 0 || start == len(data) { - return len(data), data, nil - } - if len(data) > start && data[start] == '#' { - return scanLinesKeepPrefix(data, atEOF) - } - // Scan until space, marking end of word. - for width, i := 0, start; i < len(data); i += width { - var r rune - r, width = utf8.DecodeRune(data[i:]) - if unicode.IsSpace(r) { - return i, data[:i], nil - } - } - // If we're at EOF, we have a final, non-empty, non-terminated word. Return it. - if atEOF && len(data) > start { - return len(data), data, nil - } - // Request more data. - return 0, nil, nil -} - -func newToken(rawb []byte) (*token, error) { - _, tkind, err := bufio.ScanWords(rawb, true) - if err != nil { - return nil, err - } - var ok bool - t := token{rawkind: rawb} - t.kind, ok = keywords[string(tkind)] - if !ok { - trimmed := strings.TrimSpace(string(tkind)) - if trimmed == "" { - t.kind = tkWhitespace // whitespace-only, should happen only at EOF - return &t, nil - } - if strings.HasPrefix(trimmed, "#") { - t.kind = tkComment // this is a comment - return &t, nil - } - return &t, fmt.Errorf("keyword expected; got " + string(tkind)) - } - return &t, nil -} - -func scanValue(scanner *bufio.Scanner, pos int) ([]byte, string, int, error) { - if scanner.Scan() { - raw := scanner.Bytes() - pos += bytes.Count(raw, []byte{'\n'}) - return raw, strings.TrimSpace(string(raw)), pos, nil - } - if err := scanner.Err(); err != nil { - return nil, "", pos, &Error{pos, err.Error()} - } - return nil, "", pos, nil -} - -func parse(r io.Reader, pos int) (*Netrc, error) { - b, err := ioutil.ReadAll(r) - if err != nil { - return nil, err - } - - nrc := Netrc{machines: make([]*Machine, 0, 20), macros: make(Macros, 10)} - - defaultSeen := false - var currentMacro *token - var m *Machine - var t *token - scanner := bufio.NewScanner(bytes.NewReader(b)) - scanner.Split(scanTokensKeepPrefix) - - for scanner.Scan() { - rawb := scanner.Bytes() - if len(rawb) == 0 { - break - } - pos += bytes.Count(rawb, []byte{'\n'}) - t, err = newToken(rawb) - if err != nil { - if currentMacro == nil { - return nil, &Error{pos, err.Error()} - } - currentMacro.rawvalue = append(currentMacro.rawvalue, rawb...) - continue - } - - if currentMacro != nil && bytes.Contains(rawb, []byte{'\n', '\n'}) { - // if macro rawvalue + rawb would contain \n\n, then macro def is over - currentMacro.value = strings.TrimLeft(string(currentMacro.rawvalue), "\r\n") - nrc.macros[currentMacro.macroName] = currentMacro.value - currentMacro = nil - } - - switch t.kind { - case tkMacdef: - if _, t.macroName, pos, err = scanValue(scanner, pos); err != nil { - return nil, &Error{pos, err.Error()} - } - currentMacro = t - case tkDefault: - if defaultSeen { - return nil, &Error{pos, "multiple default token"} - } - if m != nil { - nrc.machines, m = append(nrc.machines, m), nil - } - m = new(Machine) - m.Name = "" - defaultSeen = true - case tkMachine: - if defaultSeen { - return nil, &Error{pos, errBadDefaultOrder} - } - if m != nil { - nrc.machines, m = append(nrc.machines, m), nil - } - m = new(Machine) - if t.rawvalue, m.Name, pos, err = scanValue(scanner, pos); err != nil { - return nil, &Error{pos, err.Error()} - } - t.value = m.Name - m.nametoken = t - case tkLogin: - if m == nil || m.Login != "" { - return nil, &Error{pos, "unexpected token login "} - } - if t.rawvalue, m.Login, pos, err = scanValue(scanner, pos); err != nil { - return nil, &Error{pos, err.Error()} - } - t.value = m.Login - m.logintoken = t - case tkPassword: - if m == nil || m.Password != "" { - return nil, &Error{pos, "unexpected token password"} - } - if t.rawvalue, m.Password, pos, err = scanValue(scanner, pos); err != nil { - return nil, &Error{pos, err.Error()} - } - t.value = m.Password - m.passtoken = t - case tkAccount: - if m == nil || m.Account != "" { - return nil, &Error{pos, "unexpected token account"} - } - if t.rawvalue, m.Account, pos, err = scanValue(scanner, pos); err != nil { - return nil, &Error{pos, err.Error()} - } - t.value = m.Account - m.accounttoken = t - } - - nrc.tokens = append(nrc.tokens, t) - } - - if err := scanner.Err(); err != nil { - return nil, err - } - - if m != nil { - nrc.machines, m = append(nrc.machines, m), nil - } - return &nrc, nil -} - -// ParseFile opens the file at filename and then passes its io.Reader to -// Parse(). -func ParseFile(filename string) (*Netrc, error) { - fd, err := os.Open(filename) - if err != nil { - return nil, err - } - defer fd.Close() - return Parse(fd) -} - -// Parse parses from the the Reader r as a netrc file and returns the set of -// machine information and macros defined in it. The ``default'' machine, -// which is intended to be used when no machine name matches, is identified -// by an empty machine name. There can be only one ``default'' machine. -// -// If there is a parsing error, an Error is returned. -func Parse(r io.Reader) (*Netrc, error) { - return parse(r, 1) -} - -// FindMachine parses the netrc file identified by filename and returns the -// Machine named by name. If a problem occurs parsing the file at filename, an -// error is returned. If a machine named by name exists, it is returned. If no -// Machine with name name is found and there is a ``default'' machine, the -// ``default'' machine is returned. Otherwise, nil is returned. -func FindMachine(filename, name string) (m *Machine, err error) { - n, err := ParseFile(filename) - if err != nil { - return nil, err - } - return n.FindMachine(name), nil -} diff --git a/vendor/github.com/blang/semver/v4/LICENSE b/vendor/github.com/blang/semver/v4/LICENSE deleted file mode 100644 index 5ba5c86f..00000000 --- a/vendor/github.com/blang/semver/v4/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License - -Copyright (c) 2014 Benedikt Lang - -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/github.com/blang/semver/v4/json.go b/vendor/github.com/blang/semver/v4/json.go deleted file mode 100644 index a74bf7c4..00000000 --- a/vendor/github.com/blang/semver/v4/json.go +++ /dev/null @@ -1,23 +0,0 @@ -package semver - -import ( - "encoding/json" -) - -// MarshalJSON implements the encoding/json.Marshaler interface. -func (v Version) MarshalJSON() ([]byte, error) { - return json.Marshal(v.String()) -} - -// UnmarshalJSON implements the encoding/json.Unmarshaler interface. -func (v *Version) UnmarshalJSON(data []byte) (err error) { - var versionString string - - if err = json.Unmarshal(data, &versionString); err != nil { - return - } - - *v, err = Parse(versionString) - - return -} diff --git a/vendor/github.com/blang/semver/v4/range.go b/vendor/github.com/blang/semver/v4/range.go deleted file mode 100644 index 95f7139b..00000000 --- a/vendor/github.com/blang/semver/v4/range.go +++ /dev/null @@ -1,416 +0,0 @@ -package semver - -import ( - "fmt" - "strconv" - "strings" - "unicode" -) - -type wildcardType int - -const ( - noneWildcard wildcardType = iota - majorWildcard wildcardType = 1 - minorWildcard wildcardType = 2 - patchWildcard wildcardType = 3 -) - -func wildcardTypefromInt(i int) wildcardType { - switch i { - case 1: - return majorWildcard - case 2: - return minorWildcard - case 3: - return patchWildcard - default: - return noneWildcard - } -} - -type comparator func(Version, Version) bool - -var ( - compEQ comparator = func(v1 Version, v2 Version) bool { - return v1.Compare(v2) == 0 - } - compNE = func(v1 Version, v2 Version) bool { - return v1.Compare(v2) != 0 - } - compGT = func(v1 Version, v2 Version) bool { - return v1.Compare(v2) == 1 - } - compGE = func(v1 Version, v2 Version) bool { - return v1.Compare(v2) >= 0 - } - compLT = func(v1 Version, v2 Version) bool { - return v1.Compare(v2) == -1 - } - compLE = func(v1 Version, v2 Version) bool { - return v1.Compare(v2) <= 0 - } -) - -type versionRange struct { - v Version - c comparator -} - -// rangeFunc creates a Range from the given versionRange. -func (vr *versionRange) rangeFunc() Range { - return Range(func(v Version) bool { - return vr.c(v, vr.v) - }) -} - -// Range represents a range of versions. -// A Range can be used to check if a Version satisfies it: -// -// range, err := semver.ParseRange(">1.0.0 <2.0.0") -// range(semver.MustParse("1.1.1") // returns true -type Range func(Version) bool - -// OR combines the existing Range with another Range using logical OR. -func (rf Range) OR(f Range) Range { - return Range(func(v Version) bool { - return rf(v) || f(v) - }) -} - -// AND combines the existing Range with another Range using logical AND. -func (rf Range) AND(f Range) Range { - return Range(func(v Version) bool { - return rf(v) && f(v) - }) -} - -// ParseRange parses a range and returns a Range. -// If the range could not be parsed an error is returned. -// -// Valid ranges are: -// - "<1.0.0" -// - "<=1.0.0" -// - ">1.0.0" -// - ">=1.0.0" -// - "1.0.0", "=1.0.0", "==1.0.0" -// - "!1.0.0", "!=1.0.0" -// -// A Range can consist of multiple ranges separated by space: -// Ranges can be linked by logical AND: -// - ">1.0.0 <2.0.0" would match between both ranges, so "1.1.1" and "1.8.7" but not "1.0.0" or "2.0.0" -// - ">1.0.0 <3.0.0 !2.0.3-beta.2" would match every version between 1.0.0 and 3.0.0 except 2.0.3-beta.2 -// -// Ranges can also be linked by logical OR: -// - "<2.0.0 || >=3.0.0" would match "1.x.x" and "3.x.x" but not "2.x.x" -// -// AND has a higher precedence than OR. It's not possible to use brackets. -// -// Ranges can be combined by both AND and OR -// -// - `>1.0.0 <2.0.0 || >3.0.0 !4.2.1` would match `1.2.3`, `1.9.9`, `3.1.1`, but not `4.2.1`, `2.1.1` -func ParseRange(s string) (Range, error) { - parts := splitAndTrim(s) - orParts, err := splitORParts(parts) - if err != nil { - return nil, err - } - expandedParts, err := expandWildcardVersion(orParts) - if err != nil { - return nil, err - } - var orFn Range - for _, p := range expandedParts { - var andFn Range - for _, ap := range p { - opStr, vStr, err := splitComparatorVersion(ap) - if err != nil { - return nil, err - } - vr, err := buildVersionRange(opStr, vStr) - if err != nil { - return nil, fmt.Errorf("Could not parse Range %q: %s", ap, err) - } - rf := vr.rangeFunc() - - // Set function - if andFn == nil { - andFn = rf - } else { // Combine with existing function - andFn = andFn.AND(rf) - } - } - if orFn == nil { - orFn = andFn - } else { - orFn = orFn.OR(andFn) - } - - } - return orFn, nil -} - -// splitORParts splits the already cleaned parts by '||'. -// Checks for invalid positions of the operator and returns an -// error if found. -func splitORParts(parts []string) ([][]string, error) { - var ORparts [][]string - last := 0 - for i, p := range parts { - if p == "||" { - if i == 0 { - return nil, fmt.Errorf("First element in range is '||'") - } - ORparts = append(ORparts, parts[last:i]) - last = i + 1 - } - } - if last == len(parts) { - return nil, fmt.Errorf("Last element in range is '||'") - } - ORparts = append(ORparts, parts[last:]) - return ORparts, nil -} - -// buildVersionRange takes a slice of 2: operator and version -// and builds a versionRange, otherwise an error. -func buildVersionRange(opStr, vStr string) (*versionRange, error) { - c := parseComparator(opStr) - if c == nil { - return nil, fmt.Errorf("Could not parse comparator %q in %q", opStr, strings.Join([]string{opStr, vStr}, "")) - } - v, err := Parse(vStr) - if err != nil { - return nil, fmt.Errorf("Could not parse version %q in %q: %s", vStr, strings.Join([]string{opStr, vStr}, ""), err) - } - - return &versionRange{ - v: v, - c: c, - }, nil - -} - -// inArray checks if a byte is contained in an array of bytes -func inArray(s byte, list []byte) bool { - for _, el := range list { - if el == s { - return true - } - } - return false -} - -// splitAndTrim splits a range string by spaces and cleans whitespaces -func splitAndTrim(s string) (result []string) { - last := 0 - var lastChar byte - excludeFromSplit := []byte{'>', '<', '='} - for i := 0; i < len(s); i++ { - if s[i] == ' ' && !inArray(lastChar, excludeFromSplit) { - if last < i-1 { - result = append(result, s[last:i]) - } - last = i + 1 - } else if s[i] != ' ' { - lastChar = s[i] - } - } - if last < len(s)-1 { - result = append(result, s[last:]) - } - - for i, v := range result { - result[i] = strings.Replace(v, " ", "", -1) - } - - // parts := strings.Split(s, " ") - // for _, x := range parts { - // if s := strings.TrimSpace(x); len(s) != 0 { - // result = append(result, s) - // } - // } - return -} - -// splitComparatorVersion splits the comparator from the version. -// Input must be free of leading or trailing spaces. -func splitComparatorVersion(s string) (string, string, error) { - i := strings.IndexFunc(s, unicode.IsDigit) - if i == -1 { - return "", "", fmt.Errorf("Could not get version from string: %q", s) - } - return strings.TrimSpace(s[0:i]), s[i:], nil -} - -// getWildcardType will return the type of wildcard that the -// passed version contains -func getWildcardType(vStr string) wildcardType { - parts := strings.Split(vStr, ".") - nparts := len(parts) - wildcard := parts[nparts-1] - - possibleWildcardType := wildcardTypefromInt(nparts) - if wildcard == "x" { - return possibleWildcardType - } - - return noneWildcard -} - -// createVersionFromWildcard will convert a wildcard version -// into a regular version, replacing 'x's with '0's, handling -// special cases like '1.x.x' and '1.x' -func createVersionFromWildcard(vStr string) string { - // handle 1.x.x - vStr2 := strings.Replace(vStr, ".x.x", ".x", 1) - vStr2 = strings.Replace(vStr2, ".x", ".0", 1) - parts := strings.Split(vStr2, ".") - - // handle 1.x - if len(parts) == 2 { - return vStr2 + ".0" - } - - return vStr2 -} - -// incrementMajorVersion will increment the major version -// of the passed version -func incrementMajorVersion(vStr string) (string, error) { - parts := strings.Split(vStr, ".") - i, err := strconv.Atoi(parts[0]) - if err != nil { - return "", err - } - parts[0] = strconv.Itoa(i + 1) - - return strings.Join(parts, "."), nil -} - -// incrementMajorVersion will increment the minor version -// of the passed version -func incrementMinorVersion(vStr string) (string, error) { - parts := strings.Split(vStr, ".") - i, err := strconv.Atoi(parts[1]) - if err != nil { - return "", err - } - parts[1] = strconv.Itoa(i + 1) - - return strings.Join(parts, "."), nil -} - -// expandWildcardVersion will expand wildcards inside versions -// following these rules: -// -// * when dealing with patch wildcards: -// >= 1.2.x will become >= 1.2.0 -// <= 1.2.x will become < 1.3.0 -// > 1.2.x will become >= 1.3.0 -// < 1.2.x will become < 1.2.0 -// != 1.2.x will become < 1.2.0 >= 1.3.0 -// -// * when dealing with minor wildcards: -// >= 1.x will become >= 1.0.0 -// <= 1.x will become < 2.0.0 -// > 1.x will become >= 2.0.0 -// < 1.0 will become < 1.0.0 -// != 1.x will become < 1.0.0 >= 2.0.0 -// -// * when dealing with wildcards without -// version operator: -// 1.2.x will become >= 1.2.0 < 1.3.0 -// 1.x will become >= 1.0.0 < 2.0.0 -func expandWildcardVersion(parts [][]string) ([][]string, error) { - var expandedParts [][]string - for _, p := range parts { - var newParts []string - for _, ap := range p { - if strings.Contains(ap, "x") { - opStr, vStr, err := splitComparatorVersion(ap) - if err != nil { - return nil, err - } - - versionWildcardType := getWildcardType(vStr) - flatVersion := createVersionFromWildcard(vStr) - - var resultOperator string - var shouldIncrementVersion bool - switch opStr { - case ">": - resultOperator = ">=" - shouldIncrementVersion = true - case ">=": - resultOperator = ">=" - case "<": - resultOperator = "<" - case "<=": - resultOperator = "<" - shouldIncrementVersion = true - case "", "=", "==": - newParts = append(newParts, ">="+flatVersion) - resultOperator = "<" - shouldIncrementVersion = true - case "!=", "!": - newParts = append(newParts, "<"+flatVersion) - resultOperator = ">=" - shouldIncrementVersion = true - } - - var resultVersion string - if shouldIncrementVersion { - switch versionWildcardType { - case patchWildcard: - resultVersion, _ = incrementMinorVersion(flatVersion) - case minorWildcard: - resultVersion, _ = incrementMajorVersion(flatVersion) - } - } else { - resultVersion = flatVersion - } - - ap = resultOperator + resultVersion - } - newParts = append(newParts, ap) - } - expandedParts = append(expandedParts, newParts) - } - - return expandedParts, nil -} - -func parseComparator(s string) comparator { - switch s { - case "==": - fallthrough - case "": - fallthrough - case "=": - return compEQ - case ">": - return compGT - case ">=": - return compGE - case "<": - return compLT - case "<=": - return compLE - case "!": - fallthrough - case "!=": - return compNE - } - - return nil -} - -// MustParseRange is like ParseRange but panics if the range cannot be parsed. -func MustParseRange(s string) Range { - r, err := ParseRange(s) - if err != nil { - panic(`semver: ParseRange(` + s + `): ` + err.Error()) - } - return r -} diff --git a/vendor/github.com/blang/semver/v4/semver.go b/vendor/github.com/blang/semver/v4/semver.go deleted file mode 100644 index 307de610..00000000 --- a/vendor/github.com/blang/semver/v4/semver.go +++ /dev/null @@ -1,476 +0,0 @@ -package semver - -import ( - "errors" - "fmt" - "strconv" - "strings" -) - -const ( - numbers string = "0123456789" - alphas = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-" - alphanum = alphas + numbers -) - -// SpecVersion is the latest fully supported spec version of semver -var SpecVersion = Version{ - Major: 2, - Minor: 0, - Patch: 0, -} - -// Version represents a semver compatible version -type Version struct { - Major uint64 - Minor uint64 - Patch uint64 - Pre []PRVersion - Build []string //No Precedence -} - -// Version to string -func (v Version) String() string { - b := make([]byte, 0, 5) - b = strconv.AppendUint(b, v.Major, 10) - b = append(b, '.') - b = strconv.AppendUint(b, v.Minor, 10) - b = append(b, '.') - b = strconv.AppendUint(b, v.Patch, 10) - - if len(v.Pre) > 0 { - b = append(b, '-') - b = append(b, v.Pre[0].String()...) - - for _, pre := range v.Pre[1:] { - b = append(b, '.') - b = append(b, pre.String()...) - } - } - - if len(v.Build) > 0 { - b = append(b, '+') - b = append(b, v.Build[0]...) - - for _, build := range v.Build[1:] { - b = append(b, '.') - b = append(b, build...) - } - } - - return string(b) -} - -// FinalizeVersion discards prerelease and build number and only returns -// major, minor and patch number. -func (v Version) FinalizeVersion() string { - b := make([]byte, 0, 5) - b = strconv.AppendUint(b, v.Major, 10) - b = append(b, '.') - b = strconv.AppendUint(b, v.Minor, 10) - b = append(b, '.') - b = strconv.AppendUint(b, v.Patch, 10) - return string(b) -} - -// Equals checks if v is equal to o. -func (v Version) Equals(o Version) bool { - return (v.Compare(o) == 0) -} - -// EQ checks if v is equal to o. -func (v Version) EQ(o Version) bool { - return (v.Compare(o) == 0) -} - -// NE checks if v is not equal to o. -func (v Version) NE(o Version) bool { - return (v.Compare(o) != 0) -} - -// GT checks if v is greater than o. -func (v Version) GT(o Version) bool { - return (v.Compare(o) == 1) -} - -// GTE checks if v is greater than or equal to o. -func (v Version) GTE(o Version) bool { - return (v.Compare(o) >= 0) -} - -// GE checks if v is greater than or equal to o. -func (v Version) GE(o Version) bool { - return (v.Compare(o) >= 0) -} - -// LT checks if v is less than o. -func (v Version) LT(o Version) bool { - return (v.Compare(o) == -1) -} - -// LTE checks if v is less than or equal to o. -func (v Version) LTE(o Version) bool { - return (v.Compare(o) <= 0) -} - -// LE checks if v is less than or equal to o. -func (v Version) LE(o Version) bool { - return (v.Compare(o) <= 0) -} - -// Compare compares Versions v to o: -// -1 == v is less than o -// 0 == v is equal to o -// 1 == v is greater than o -func (v Version) Compare(o Version) int { - if v.Major != o.Major { - if v.Major > o.Major { - return 1 - } - return -1 - } - if v.Minor != o.Minor { - if v.Minor > o.Minor { - return 1 - } - return -1 - } - if v.Patch != o.Patch { - if v.Patch > o.Patch { - return 1 - } - return -1 - } - - // Quick comparison if a version has no prerelease versions - if len(v.Pre) == 0 && len(o.Pre) == 0 { - return 0 - } else if len(v.Pre) == 0 && len(o.Pre) > 0 { - return 1 - } else if len(v.Pre) > 0 && len(o.Pre) == 0 { - return -1 - } - - i := 0 - for ; i < len(v.Pre) && i < len(o.Pre); i++ { - if comp := v.Pre[i].Compare(o.Pre[i]); comp == 0 { - continue - } else if comp == 1 { - return 1 - } else { - return -1 - } - } - - // If all pr versions are the equal but one has further prversion, this one greater - if i == len(v.Pre) && i == len(o.Pre) { - return 0 - } else if i == len(v.Pre) && i < len(o.Pre) { - return -1 - } else { - return 1 - } - -} - -// IncrementPatch increments the patch version -func (v *Version) IncrementPatch() error { - v.Patch++ - return nil -} - -// IncrementMinor increments the minor version -func (v *Version) IncrementMinor() error { - v.Minor++ - v.Patch = 0 - return nil -} - -// IncrementMajor increments the major version -func (v *Version) IncrementMajor() error { - v.Major++ - v.Minor = 0 - v.Patch = 0 - return nil -} - -// Validate validates v and returns error in case -func (v Version) Validate() error { - // Major, Minor, Patch already validated using uint64 - - for _, pre := range v.Pre { - if !pre.IsNum { //Numeric prerelease versions already uint64 - if len(pre.VersionStr) == 0 { - return fmt.Errorf("Prerelease can not be empty %q", pre.VersionStr) - } - if !containsOnly(pre.VersionStr, alphanum) { - return fmt.Errorf("Invalid character(s) found in prerelease %q", pre.VersionStr) - } - } - } - - for _, build := range v.Build { - if len(build) == 0 { - return fmt.Errorf("Build meta data can not be empty %q", build) - } - if !containsOnly(build, alphanum) { - return fmt.Errorf("Invalid character(s) found in build meta data %q", build) - } - } - - return nil -} - -// New is an alias for Parse and returns a pointer, parses version string and returns a validated Version or error -func New(s string) (*Version, error) { - v, err := Parse(s) - vp := &v - return vp, err -} - -// Make is an alias for Parse, parses version string and returns a validated Version or error -func Make(s string) (Version, error) { - return Parse(s) -} - -// ParseTolerant allows for certain version specifications that do not strictly adhere to semver -// specs to be parsed by this library. It does so by normalizing versions before passing them to -// Parse(). It currently trims spaces, removes a "v" prefix, adds a 0 patch number to versions -// with only major and minor components specified, and removes leading 0s. -func ParseTolerant(s string) (Version, error) { - s = strings.TrimSpace(s) - s = strings.TrimPrefix(s, "v") - - // Split into major.minor.(patch+pr+meta) - parts := strings.SplitN(s, ".", 3) - // Remove leading zeros. - for i, p := range parts { - if len(p) > 1 { - p = strings.TrimLeft(p, "0") - if len(p) == 0 || !strings.ContainsAny(p[0:1], "0123456789") { - p = "0" + p - } - parts[i] = p - } - } - // Fill up shortened versions. - if len(parts) < 3 { - if strings.ContainsAny(parts[len(parts)-1], "+-") { - return Version{}, errors.New("Short version cannot contain PreRelease/Build meta data") - } - for len(parts) < 3 { - parts = append(parts, "0") - } - } - s = strings.Join(parts, ".") - - return Parse(s) -} - -// Parse parses version string and returns a validated Version or error -func Parse(s string) (Version, error) { - if len(s) == 0 { - return Version{}, errors.New("Version string empty") - } - - // Split into major.minor.(patch+pr+meta) - parts := strings.SplitN(s, ".", 3) - if len(parts) != 3 { - return Version{}, errors.New("No Major.Minor.Patch elements found") - } - - // Major - if !containsOnly(parts[0], numbers) { - return Version{}, fmt.Errorf("Invalid character(s) found in major number %q", parts[0]) - } - if hasLeadingZeroes(parts[0]) { - return Version{}, fmt.Errorf("Major number must not contain leading zeroes %q", parts[0]) - } - major, err := strconv.ParseUint(parts[0], 10, 64) - if err != nil { - return Version{}, err - } - - // Minor - if !containsOnly(parts[1], numbers) { - return Version{}, fmt.Errorf("Invalid character(s) found in minor number %q", parts[1]) - } - if hasLeadingZeroes(parts[1]) { - return Version{}, fmt.Errorf("Minor number must not contain leading zeroes %q", parts[1]) - } - minor, err := strconv.ParseUint(parts[1], 10, 64) - if err != nil { - return Version{}, err - } - - v := Version{} - v.Major = major - v.Minor = minor - - var build, prerelease []string - patchStr := parts[2] - - if buildIndex := strings.IndexRune(patchStr, '+'); buildIndex != -1 { - build = strings.Split(patchStr[buildIndex+1:], ".") - patchStr = patchStr[:buildIndex] - } - - if preIndex := strings.IndexRune(patchStr, '-'); preIndex != -1 { - prerelease = strings.Split(patchStr[preIndex+1:], ".") - patchStr = patchStr[:preIndex] - } - - if !containsOnly(patchStr, numbers) { - return Version{}, fmt.Errorf("Invalid character(s) found in patch number %q", patchStr) - } - if hasLeadingZeroes(patchStr) { - return Version{}, fmt.Errorf("Patch number must not contain leading zeroes %q", patchStr) - } - patch, err := strconv.ParseUint(patchStr, 10, 64) - if err != nil { - return Version{}, err - } - - v.Patch = patch - - // Prerelease - for _, prstr := range prerelease { - parsedPR, err := NewPRVersion(prstr) - if err != nil { - return Version{}, err - } - v.Pre = append(v.Pre, parsedPR) - } - - // Build meta data - for _, str := range build { - if len(str) == 0 { - return Version{}, errors.New("Build meta data is empty") - } - if !containsOnly(str, alphanum) { - return Version{}, fmt.Errorf("Invalid character(s) found in build meta data %q", str) - } - v.Build = append(v.Build, str) - } - - return v, nil -} - -// MustParse is like Parse but panics if the version cannot be parsed. -func MustParse(s string) Version { - v, err := Parse(s) - if err != nil { - panic(`semver: Parse(` + s + `): ` + err.Error()) - } - return v -} - -// PRVersion represents a PreRelease Version -type PRVersion struct { - VersionStr string - VersionNum uint64 - IsNum bool -} - -// NewPRVersion creates a new valid prerelease version -func NewPRVersion(s string) (PRVersion, error) { - if len(s) == 0 { - return PRVersion{}, errors.New("Prerelease is empty") - } - v := PRVersion{} - if containsOnly(s, numbers) { - if hasLeadingZeroes(s) { - return PRVersion{}, fmt.Errorf("Numeric PreRelease version must not contain leading zeroes %q", s) - } - num, err := strconv.ParseUint(s, 10, 64) - - // Might never be hit, but just in case - if err != nil { - return PRVersion{}, err - } - v.VersionNum = num - v.IsNum = true - } else if containsOnly(s, alphanum) { - v.VersionStr = s - v.IsNum = false - } else { - return PRVersion{}, fmt.Errorf("Invalid character(s) found in prerelease %q", s) - } - return v, nil -} - -// IsNumeric checks if prerelease-version is numeric -func (v PRVersion) IsNumeric() bool { - return v.IsNum -} - -// Compare compares two PreRelease Versions v and o: -// -1 == v is less than o -// 0 == v is equal to o -// 1 == v is greater than o -func (v PRVersion) Compare(o PRVersion) int { - if v.IsNum && !o.IsNum { - return -1 - } else if !v.IsNum && o.IsNum { - return 1 - } else if v.IsNum && o.IsNum { - if v.VersionNum == o.VersionNum { - return 0 - } else if v.VersionNum > o.VersionNum { - return 1 - } else { - return -1 - } - } else { // both are Alphas - if v.VersionStr == o.VersionStr { - return 0 - } else if v.VersionStr > o.VersionStr { - return 1 - } else { - return -1 - } - } -} - -// PreRelease version to string -func (v PRVersion) String() string { - if v.IsNum { - return strconv.FormatUint(v.VersionNum, 10) - } - return v.VersionStr -} - -func containsOnly(s string, set string) bool { - return strings.IndexFunc(s, func(r rune) bool { - return !strings.ContainsRune(set, r) - }) == -1 -} - -func hasLeadingZeroes(s string) bool { - return len(s) > 1 && s[0] == '0' -} - -// NewBuildVersion creates a new valid build version -func NewBuildVersion(s string) (string, error) { - if len(s) == 0 { - return "", errors.New("Buildversion is empty") - } - if !containsOnly(s, alphanum) { - return "", fmt.Errorf("Invalid character(s) found in build meta data %q", s) - } - return s, nil -} - -// FinalizeVersion returns the major, minor and patch number only and discards -// prerelease and build number. -func FinalizeVersion(s string) (string, error) { - v, err := Parse(s) - if err != nil { - return "", err - } - v.Pre = nil - v.Build = nil - - finalVer := v.String() - return finalVer, nil -} diff --git a/vendor/github.com/blang/semver/v4/sort.go b/vendor/github.com/blang/semver/v4/sort.go deleted file mode 100644 index e18f8808..00000000 --- a/vendor/github.com/blang/semver/v4/sort.go +++ /dev/null @@ -1,28 +0,0 @@ -package semver - -import ( - "sort" -) - -// Versions represents multiple versions. -type Versions []Version - -// Len returns length of version collection -func (s Versions) Len() int { - return len(s) -} - -// Swap swaps two versions inside the collection by its indices -func (s Versions) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -// Less checks if version at index i is less than version at index j -func (s Versions) Less(i, j int) bool { - return s[i].LT(s[j]) -} - -// Sort sorts a slice of versions -func Sort(versions []Version) { - sort.Sort(Versions(versions)) -} diff --git a/vendor/github.com/blang/semver/v4/sql.go b/vendor/github.com/blang/semver/v4/sql.go deleted file mode 100644 index db958134..00000000 --- a/vendor/github.com/blang/semver/v4/sql.go +++ /dev/null @@ -1,30 +0,0 @@ -package semver - -import ( - "database/sql/driver" - "fmt" -) - -// Scan implements the database/sql.Scanner interface. -func (v *Version) Scan(src interface{}) (err error) { - var str string - switch src := src.(type) { - case string: - str = src - case []byte: - str = string(src) - default: - return fmt.Errorf("version.Scan: cannot convert %T to string", src) - } - - if t, err := Parse(str); err == nil { - *v = t - } - - return -} - -// Value implements the database/sql/driver.Valuer interface. -func (v Version) Value() (driver.Value, error) { - return v.String(), nil -} diff --git a/vendor/github.com/caspr-io/yamlpath/LICENSE b/vendor/github.com/caspr-io/yamlpath/LICENSE deleted file mode 100644 index 03afde42..00000000 --- a/vendor/github.com/caspr-io/yamlpath/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2020 CASPR.io - -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/github.com/caspr-io/yamlpath/Makefile b/vendor/github.com/caspr-io/yamlpath/Makefile deleted file mode 100644 index deb05547..00000000 --- a/vendor/github.com/caspr-io/yamlpath/Makefile +++ /dev/null @@ -1,14 +0,0 @@ -ROOTPROJECT ?= ../root -APIPROJECT = . -include ${ROOTPROJECT}/include.mk - -# Dummy targets for cluster/up and cluster/teardown -.PHONY: up down - -up: -down: -build: test -# Test code -.PHONY: test - -test: go/test diff --git a/vendor/github.com/caspr-io/yamlpath/error.go b/vendor/github.com/caspr-io/yamlpath/error.go deleted file mode 100644 index ac20d265..00000000 --- a/vendor/github.com/caspr-io/yamlpath/error.go +++ /dev/null @@ -1,20 +0,0 @@ -package yamlpath - -import "fmt" - -type YamlPathError struct { //nolint:golint - path string - wrapped error -} - -func PathError(path string, cause error) *YamlPathError { - return &YamlPathError{path: path, wrapped: cause} -} - -func (e *YamlPathError) Error() string { - return fmt.Sprintf("Could not traverse path '%s' in Yaml: Cause: %s", e.path, e.wrapped.Error()) -} - -func (e *YamlPathError) Unwrap() error { - return e.wrapped -} diff --git a/vendor/github.com/caspr-io/yamlpath/segments/detect.go b/vendor/github.com/caspr-io/yamlpath/segments/detect.go deleted file mode 100644 index e20368d1..00000000 --- a/vendor/github.com/caspr-io/yamlpath/segments/detect.go +++ /dev/null @@ -1,39 +0,0 @@ -package segments - -import ( - "fmt" - "regexp" -) - -const ( - KeySegment = "^[:a-zA-Z0-9_\\.-]+$" - // KeySearchSegment = "^\\[\\.=[a-zA-Z][a-zA-Z0-9_-]*\\]$" - ExplicitIndexSegment = "^\\[[0-9]+\\]$" - ImplicitIndexSegment = "^[0-9]+$" - SliceSegment = "^\\[[0-9]+:[0-9]+\\]$" - ValueSearchSegment = "^\\[\\.[=\\^\\$\\%].+\\]$" -) - -var regexps map[string]*regexp.Regexp = map[string]*regexp.Regexp{ //nolint:gochecknoglobals - KeySegment: regexp.MustCompile(KeySegment), - // KeySearchSegment: regexp.MustCompile(KeySearchSegment), - ExplicitIndexSegment: regexp.MustCompile(ExplicitIndexSegment), - ImplicitIndexSegment: regexp.MustCompile(ImplicitIndexSegment), - SliceSegment: regexp.MustCompile(SliceSegment), - ValueSearchSegment: regexp.MustCompile(ValueSearchSegment), -} - -func DetectSegment(s string) (YamlPathSegment, error) { - switch { - case regexps[ImplicitIndexSegment].MatchString(s), regexps[ExplicitIndexSegment].MatchString(s): - return ParseIndexSegment(s) - case regexps[SliceSegment].MatchString(s): - return ParseSliceSegment(s) - case regexps[ValueSearchSegment].MatchString(s): - return ParseStringValueSearchSegment(s) - case regexps[KeySegment].MatchString(s): - return ParseKeySegment(s) - } - - return nil, fmt.Errorf("segment '%s' not supported yet", s) -} diff --git a/vendor/github.com/caspr-io/yamlpath/segments/index.go b/vendor/github.com/caspr-io/yamlpath/segments/index.go deleted file mode 100644 index 00bb1f8b..00000000 --- a/vendor/github.com/caspr-io/yamlpath/segments/index.go +++ /dev/null @@ -1,37 +0,0 @@ -package segments - -import ( - "fmt" - "strconv" -) - -type Index struct { - idx int -} - -func ParseIndexSegment(s string) (YamlPathSegment, error) { - if s[0] == '[' { - s = s[1 : len(s)-1] - } - - idx, err := strconv.Atoi(s) - if err != nil { - return nil, err - } - - return &Index{ - idx: idx, - }, nil -} - -func (p *Index) NavigateMap(m map[string]interface{}) (interface{}, error) { - return nil, fmt.Errorf("cannot index map") -} - -func (p *Index) NavigateArray(l []interface{}) (interface{}, error) { - if len(l) <= p.idx { - return nil, fmt.Errorf("out of bounds %d (len %d)", p.idx, len(l)) - } - - return l[p.idx], nil -} diff --git a/vendor/github.com/caspr-io/yamlpath/segments/key.go b/vendor/github.com/caspr-io/yamlpath/segments/key.go deleted file mode 100644 index cf295a03..00000000 --- a/vendor/github.com/caspr-io/yamlpath/segments/key.go +++ /dev/null @@ -1,38 +0,0 @@ -package segments - -import ( - "fmt" -) - -type Key struct { - key string -} - -func ParseKeySegment(s string) (YamlPathSegment, error) { - return &Key{ - key: s, - }, nil -} - -func (s *Key) NavigateMap(m map[string]interface{}) (interface{}, error) { - if v, ok := m[s.key]; ok { - return v, nil - } - - return nil, fmt.Errorf("could not find key '%s' in yaml", s.key) -} - -func (s *Key) NavigateArray(l []interface{}) (interface{}, error) { - result := []interface{}{} - - for _, v := range l { - r, err := NavigateYaml(v, s) - if err != nil { - return nil, err - } - - result = append(result, r) - } - - return result, nil -} diff --git a/vendor/github.com/caspr-io/yamlpath/segments/path.go b/vendor/github.com/caspr-io/yamlpath/segments/path.go deleted file mode 100644 index 6280cf55..00000000 --- a/vendor/github.com/caspr-io/yamlpath/segments/path.go +++ /dev/null @@ -1,111 +0,0 @@ -package segments - -import "fmt" - -func ParseSegment(path string) ([]YamlPathSegment, error) { - if path[0] == '/' { - return parseSegment(path[1:], '/') - } - - return parseSegment(path, '.') -} - -func parseSegment(path string, separator rune) ([]YamlPathSegment, error) { - segments := []YamlPathSegment{} - currentSegment := []rune{} - i := 0 - - for i < len(path) { - r := rune(path[i]) - switch r { - case separator: - if err := addSegment(currentSegment, &segments); err != nil { - return nil, err - } - - currentSegment = []rune{} - case '\\': - i++ - r = rune(path[i]) - currentSegment = append(currentSegment, r) - case '"', '\'': - if err := addSegment(currentSegment, &segments); err != nil { - return nil, err - } - - currentSegment = []rune{} - - p, endIdx, err := parsePathUntil(path, i+1, r, false) //nolint:gomnd - if err != nil { - return nil, err - } - - segments = append(segments, p) - i = endIdx - case '[': - if err := addSegment(currentSegment, &segments); err != nil { - return nil, err - } - - currentSegment = []rune{} - - p, endIdx, err := parsePathUntil(path, i, ']', true) - if err != nil { - return nil, err - } - - segments = append(segments, p) - i = endIdx - default: - currentSegment = append(currentSegment, r) - } - i++ - } - - if len(currentSegment) > 0 { - if err := addSegment(currentSegment, &segments); err != nil { - return nil, err - } - } - - return segments, nil -} - -func addSegment(segment []rune, segments *[]YamlPathSegment) error { - if len(segment) == 0 { - return nil - } - - p, err := DetectSegment(string(segment)) - if err != nil { - return err - } - - l := append(*segments, p) - *segments = l - - return nil -} - -func parsePathUntil(path string, idx int, stopOn rune, inclusive bool) (YamlPathSegment, int, error) { - segment := []rune{} - i := idx - - for i < len(path) { - r := rune(path[i]) - segment = append(segment, r) - - if r == stopOn { - if !inclusive { - segment = segment[0 : len(segment)-1] - } - - ypp, err := DetectSegment(string(segment)) - - return ypp, i + 1, err - } - i++ - } - - return nil, -1, fmt.Errorf("could not find terminating '%c' in path '%s'", stopOn, path[idx:]) -} diff --git a/vendor/github.com/caspr-io/yamlpath/segments/segment.go b/vendor/github.com/caspr-io/yamlpath/segments/segment.go deleted file mode 100644 index 76e2e08c..00000000 --- a/vendor/github.com/caspr-io/yamlpath/segments/segment.go +++ /dev/null @@ -1,19 +0,0 @@ -package segments - -import "fmt" - -type YamlPathSegment interface { - NavigateMap(map[string]interface{}) (interface{}, error) - NavigateArray([]interface{}) (interface{}, error) -} - -func NavigateYaml(yaml interface{}, segment YamlPathSegment) (interface{}, error) { - switch y := yaml.(type) { - case map[string]interface{}: - return segment.NavigateMap(y) - case []interface{}: - return segment.NavigateArray(y) - default: - return nil, fmt.Errorf("no support yet for %v", yaml) - } -} diff --git a/vendor/github.com/caspr-io/yamlpath/segments/slice.go b/vendor/github.com/caspr-io/yamlpath/segments/slice.go deleted file mode 100644 index e6d159fc..00000000 --- a/vendor/github.com/caspr-io/yamlpath/segments/slice.go +++ /dev/null @@ -1,56 +0,0 @@ -package segments - -import ( - "fmt" - "strconv" - "strings" -) - -type Slice struct { - startIdx int - endIdx int -} - -func ParseSliceSegment(s string) (YamlPathSegment, error) { - idxs := strings.Split(s[1:len(s)-1], ":") - - start, err := strconv.Atoi(idxs[0]) - if err != nil { - return nil, fmt.Errorf("part '%s' is not an index into an array. %w", s, err) - } - - end, err := strconv.Atoi(idxs[1]) - if err != nil { - return nil, fmt.Errorf("part '%s' is not an index into an array. %w", s, err) - } - - if start > end { - return nil, fmt.Errorf("cannot take slice with reversed indexes '%s'", s) - } - - return &Slice{ - startIdx: start, - endIdx: end, - }, nil -} - -func (s *Slice) NavigateMap(m map[string]interface{}) (interface{}, error) { - return nil, fmt.Errorf("cannot slice map") -} - -func (s *Slice) NavigateArray(l []interface{}) (interface{}, error) { - if s.startIdx >= len(l) { - return nil, fmt.Errorf("start slice index out of bounds '%d' for array length '%d'", s.startIdx, len(l)) - } - - if s.endIdx > len(l) { - return nil, fmt.Errorf("end slice index out of bounds '%d' for array length '%d'", s.endIdx, len(l)) - } - - slice := []interface{}{} - for i := s.startIdx; i < s.endIdx; i++ { - slice = append(slice, l[i]) - } - - return slice, nil -} diff --git a/vendor/github.com/caspr-io/yamlpath/segments/stringvaluesearch.go b/vendor/github.com/caspr-io/yamlpath/segments/stringvaluesearch.go deleted file mode 100644 index 68753bb9..00000000 --- a/vendor/github.com/caspr-io/yamlpath/segments/stringvaluesearch.go +++ /dev/null @@ -1,64 +0,0 @@ -package segments - -import ( - "fmt" - "strings" -) - -// [.=foo], [.^foo], [.$foo], [.%foo] -type StringValueSearch struct { - operator byte - pattern string -} - -func ParseStringValueSearchSegment(s string) (YamlPathSegment, error) { - operator := s[2] - pattern := s[3 : len(s)-1] - - return &StringValueSearch{ - operator: operator, - pattern: pattern, - }, nil -} - -func (s *StringValueSearch) NavigateMap(m map[string]interface{}) (interface{}, error) { - for k, v := range m { - if s.valueMatches(k) { - return v, nil - } - } - - return nil, fmt.Errorf("could not find matching key in hash for pattern '[.%s%s]", string(s.operator), s.pattern) -} - -func (s *StringValueSearch) NavigateArray(l []interface{}) (interface{}, error) { - for _, i := range l { - switch v := i.(type) { - case string: - if s.valueMatches(v) { - return v, nil - } - - continue - default: - return nil, fmt.Errorf("could not search for value '%s' as list does not contain strings", s.pattern) - } - } - - return nil, fmt.Errorf("could not find match for search part '[.%s%s]'", string(s.operator), s.pattern) -} - -func (s *StringValueSearch) valueMatches(v string) bool { - switch s.operator { - case '^': - return strings.HasPrefix(v, s.pattern) - case '$': - return strings.HasSuffix(v, s.pattern) - case '%': - return strings.Contains(v, s.pattern) - case '=': - return v == s.pattern - default: - return false - } -} diff --git a/vendor/github.com/caspr-io/yamlpath/yamlpath.go b/vendor/github.com/caspr-io/yamlpath/yamlpath.go deleted file mode 100644 index 783c01f4..00000000 --- a/vendor/github.com/caspr-io/yamlpath/yamlpath.go +++ /dev/null @@ -1,110 +0,0 @@ -package yamlpath - -import ( - "strings" - - "github.com/caspr-io/yamlpath/segments" -) - -// https://pypi.org/project/yamlpath/#supported-yaml-path-segments - -// YamlPath traverses the yaml document to and returns the retrieved value -func YamlPath(yaml map[string]interface{}, path string) (interface{}, error) { - splitPath, err := segments.ParseSegment(path) - if err != nil { - return nil, PathError(path, err) - } - // fmt.Printf("%v, %d", splitPath, len(splitPath)) - - var value interface{} = yaml - - for _, pathPart := range splitPath { - returned, err := segments.NavigateYaml(value, pathPart) - if err != nil { - return nil, PathError(path, err) - } - - value = returned - } - - return value, nil -} - -// func navigateYaml(yaml interface{}, part string) (interface{}, error) { -// switch y := yaml.(type) { -// case map[string]interface{}: -// return navigateMap(y, part) -// case []interface{}: -// return navigateArray(y, part) -// default: -// return nil, fmt.Errorf("no support yet for %v", yaml) -// } -// } - -// func navigateArray(l []interface{}, part string) (interface{}, error) { -// switch { -// case regexps[ExplicitIndexPart].MatchString(part): -// i, err := strconv.Atoi(part[1 : len(part)-1]) -// if err != nil { -// return nil, err -// } - -// if i < len(l) { -// return l[i], nil -// } - -// return nil, fmt.Errorf("out of bounds '%d' for array of length '%d'", i, len(l)) -// case regexps[SlicePart].MatchString(part): -// case regexps[ImplicitIndexPart].MatchString(part): -// i, err := strconv.Atoi(part) -// if err != nil { -// return nil, fmt.Errorf("part '%s' is not an index into an array. %w", part, err) -// } - -// return l[i], nil -// case regexps[KeyPart].MatchString(part): -// case regexps[ValueSearchPart].MatchString(part): -// toFind := part[3 : len(part)-1] -// operator := part[2] - -// for _, i := range l { -// switch s := i.(type) { -// case string: -// if valueMatches(s, toFind, operator) { -// return s, nil -// } - -// continue -// default: -// return nil, fmt.Errorf("could not search for value '%s' as list does not contain strings", part) -// } -// } - -// return nil, fmt.Errorf("could not find match for search part '%s'", part) -// default: -// return nil, fmt.Errorf("part '%s' not supported for array", part) -// } -// } - -func valueMatches(s string, find string, operator byte) bool { - switch operator { - case '^': - return strings.HasPrefix(s, find) - case '$': - return strings.HasSuffix(s, find) - case '%': - return strings.Contains(s, find) - default: - return false - } -} - -// func navigateMap(m map[string]interface{}, part string) (interface{}, error) { -// switch { -// case regexps[KeySearchPart].MatchString(part): -// key := part[3 : len(part)-1] -// return m[key], nil -// default: -// return nil, fmt.Errorf("no support for part '%s'", part) -// } -// } diff --git a/vendor/github.com/cenkalti/backoff/.gitignore b/vendor/github.com/cenkalti/backoff/.gitignore deleted file mode 100644 index 00268614..00000000 --- a/vendor/github.com/cenkalti/backoff/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe diff --git a/vendor/github.com/cenkalti/backoff/.travis.yml b/vendor/github.com/cenkalti/backoff/.travis.yml deleted file mode 100644 index 47a6a46e..00000000 --- a/vendor/github.com/cenkalti/backoff/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: go -go: - - 1.7 - - 1.x - - tip -before_install: - - go get github.com/mattn/goveralls - - go get golang.org/x/tools/cmd/cover -script: - - $HOME/gopath/bin/goveralls -service=travis-ci diff --git a/vendor/github.com/cenkalti/backoff/LICENSE b/vendor/github.com/cenkalti/backoff/LICENSE deleted file mode 100644 index 89b81799..00000000 --- a/vendor/github.com/cenkalti/backoff/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Cenk Altı - -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/github.com/cenkalti/backoff/README.md b/vendor/github.com/cenkalti/backoff/README.md deleted file mode 100644 index 55ebc98f..00000000 --- a/vendor/github.com/cenkalti/backoff/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# Exponential Backoff [![GoDoc][godoc image]][godoc] [![Build Status][travis image]][travis] [![Coverage Status][coveralls image]][coveralls] - -This is a Go port of the exponential backoff algorithm from [Google's HTTP Client Library for Java][google-http-java-client]. - -[Exponential backoff][exponential backoff wiki] -is an algorithm that uses feedback to multiplicatively decrease the rate of some process, -in order to gradually find an acceptable rate. -The retries exponentially increase and stop increasing when a certain threshold is met. - -## Usage - -See https://godoc.org/github.com/cenkalti/backoff#pkg-examples - -## Contributing - -* I would like to keep this library as small as possible. -* Please don't send a PR without opening an issue and discussing it first. -* If proposed change is not a common use case, I will probably not accept it. - -[godoc]: https://godoc.org/github.com/cenkalti/backoff -[godoc image]: https://godoc.org/github.com/cenkalti/backoff?status.png -[travis]: https://travis-ci.org/cenkalti/backoff -[travis image]: https://travis-ci.org/cenkalti/backoff.png?branch=master -[coveralls]: https://coveralls.io/github/cenkalti/backoff?branch=master -[coveralls image]: https://coveralls.io/repos/github/cenkalti/backoff/badge.svg?branch=master - -[google-http-java-client]: https://github.com/google/google-http-java-client/blob/da1aa993e90285ec18579f1553339b00e19b3ab5/google-http-client/src/main/java/com/google/api/client/util/ExponentialBackOff.java -[exponential backoff wiki]: http://en.wikipedia.org/wiki/Exponential_backoff - -[advanced example]: https://godoc.org/github.com/cenkalti/backoff#example_ diff --git a/vendor/github.com/cenkalti/backoff/backoff.go b/vendor/github.com/cenkalti/backoff/backoff.go deleted file mode 100644 index 3676ee40..00000000 --- a/vendor/github.com/cenkalti/backoff/backoff.go +++ /dev/null @@ -1,66 +0,0 @@ -// Package backoff implements backoff algorithms for retrying operations. -// -// Use Retry function for retrying operations that may fail. -// If Retry does not meet your needs, -// copy/paste the function into your project and modify as you wish. -// -// There is also Ticker type similar to time.Ticker. -// You can use it if you need to work with channels. -// -// See Examples section below for usage examples. -package backoff - -import "time" - -// BackOff is a backoff policy for retrying an operation. -type BackOff interface { - // NextBackOff returns the duration to wait before retrying the operation, - // or backoff. Stop to indicate that no more retries should be made. - // - // Example usage: - // - // duration := backoff.NextBackOff(); - // if (duration == backoff.Stop) { - // // Do not retry operation. - // } else { - // // Sleep for duration and retry operation. - // } - // - NextBackOff() time.Duration - - // Reset to initial state. - Reset() -} - -// Stop indicates that no more retries should be made for use in NextBackOff(). -const Stop time.Duration = -1 - -// ZeroBackOff is a fixed backoff policy whose backoff time is always zero, -// meaning that the operation is retried immediately without waiting, indefinitely. -type ZeroBackOff struct{} - -func (b *ZeroBackOff) Reset() {} - -func (b *ZeroBackOff) NextBackOff() time.Duration { return 0 } - -// StopBackOff is a fixed backoff policy that always returns backoff.Stop for -// NextBackOff(), meaning that the operation should never be retried. -type StopBackOff struct{} - -func (b *StopBackOff) Reset() {} - -func (b *StopBackOff) NextBackOff() time.Duration { return Stop } - -// ConstantBackOff is a backoff policy that always returns the same backoff delay. -// This is in contrast to an exponential backoff policy, -// which returns a delay that grows longer as you call NextBackOff() over and over again. -type ConstantBackOff struct { - Interval time.Duration -} - -func (b *ConstantBackOff) Reset() {} -func (b *ConstantBackOff) NextBackOff() time.Duration { return b.Interval } - -func NewConstantBackOff(d time.Duration) *ConstantBackOff { - return &ConstantBackOff{Interval: d} -} diff --git a/vendor/github.com/cenkalti/backoff/context.go b/vendor/github.com/cenkalti/backoff/context.go deleted file mode 100644 index 7706faa2..00000000 --- a/vendor/github.com/cenkalti/backoff/context.go +++ /dev/null @@ -1,63 +0,0 @@ -package backoff - -import ( - "context" - "time" -) - -// BackOffContext is a backoff policy that stops retrying after the context -// is canceled. -type BackOffContext interface { - BackOff - Context() context.Context -} - -type backOffContext struct { - BackOff - ctx context.Context -} - -// WithContext returns a BackOffContext with context ctx -// -// ctx must not be nil -func WithContext(b BackOff, ctx context.Context) BackOffContext { - if ctx == nil { - panic("nil context") - } - - if b, ok := b.(*backOffContext); ok { - return &backOffContext{ - BackOff: b.BackOff, - ctx: ctx, - } - } - - return &backOffContext{ - BackOff: b, - ctx: ctx, - } -} - -func ensureContext(b BackOff) BackOffContext { - if cb, ok := b.(BackOffContext); ok { - return cb - } - return WithContext(b, context.Background()) -} - -func (b *backOffContext) Context() context.Context { - return b.ctx -} - -func (b *backOffContext) NextBackOff() time.Duration { - select { - case <-b.ctx.Done(): - return Stop - default: - } - next := b.BackOff.NextBackOff() - if deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next { - return Stop - } - return next -} diff --git a/vendor/github.com/cenkalti/backoff/exponential.go b/vendor/github.com/cenkalti/backoff/exponential.go deleted file mode 100644 index a031a659..00000000 --- a/vendor/github.com/cenkalti/backoff/exponential.go +++ /dev/null @@ -1,153 +0,0 @@ -package backoff - -import ( - "math/rand" - "time" -) - -/* -ExponentialBackOff is a backoff implementation that increases the backoff -period for each retry attempt using a randomization function that grows exponentially. - -NextBackOff() is calculated using the following formula: - - randomized interval = - RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor]) - -In other words NextBackOff() will range between the randomization factor -percentage below and above the retry interval. - -For example, given the following parameters: - - RetryInterval = 2 - RandomizationFactor = 0.5 - Multiplier = 2 - -the actual backoff period used in the next retry attempt will range between 1 and 3 seconds, -multiplied by the exponential, that is, between 2 and 6 seconds. - -Note: MaxInterval caps the RetryInterval and not the randomized interval. - -If the time elapsed since an ExponentialBackOff instance is created goes past the -MaxElapsedTime, then the method NextBackOff() starts returning backoff.Stop. - -The elapsed time can be reset by calling Reset(). - -Example: Given the following default arguments, for 10 tries the sequence will be, -and assuming we go over the MaxElapsedTime on the 10th try: - - Request # RetryInterval (seconds) Randomized Interval (seconds) - - 1 0.5 [0.25, 0.75] - 2 0.75 [0.375, 1.125] - 3 1.125 [0.562, 1.687] - 4 1.687 [0.8435, 2.53] - 5 2.53 [1.265, 3.795] - 6 3.795 [1.897, 5.692] - 7 5.692 [2.846, 8.538] - 8 8.538 [4.269, 12.807] - 9 12.807 [6.403, 19.210] - 10 19.210 backoff.Stop - -Note: Implementation is not thread-safe. -*/ -type ExponentialBackOff struct { - InitialInterval time.Duration - RandomizationFactor float64 - Multiplier float64 - MaxInterval time.Duration - // After MaxElapsedTime the ExponentialBackOff stops. - // It never stops if MaxElapsedTime == 0. - MaxElapsedTime time.Duration - Clock Clock - - currentInterval time.Duration - startTime time.Time -} - -// Clock is an interface that returns current time for BackOff. -type Clock interface { - Now() time.Time -} - -// Default values for ExponentialBackOff. -const ( - DefaultInitialInterval = 500 * time.Millisecond - DefaultRandomizationFactor = 0.5 - DefaultMultiplier = 1.5 - DefaultMaxInterval = 60 * time.Second - DefaultMaxElapsedTime = 15 * time.Minute -) - -// NewExponentialBackOff creates an instance of ExponentialBackOff using default values. -func NewExponentialBackOff() *ExponentialBackOff { - b := &ExponentialBackOff{ - InitialInterval: DefaultInitialInterval, - RandomizationFactor: DefaultRandomizationFactor, - Multiplier: DefaultMultiplier, - MaxInterval: DefaultMaxInterval, - MaxElapsedTime: DefaultMaxElapsedTime, - Clock: SystemClock, - } - b.Reset() - return b -} - -type systemClock struct{} - -func (t systemClock) Now() time.Time { - return time.Now() -} - -// SystemClock implements Clock interface that uses time.Now(). -var SystemClock = systemClock{} - -// Reset the interval back to the initial retry interval and restarts the timer. -func (b *ExponentialBackOff) Reset() { - b.currentInterval = b.InitialInterval - b.startTime = b.Clock.Now() -} - -// NextBackOff calculates the next backoff interval using the formula: -// Randomized interval = RetryInterval +/- (RandomizationFactor * RetryInterval) -func (b *ExponentialBackOff) NextBackOff() time.Duration { - // Make sure we have not gone over the maximum elapsed time. - if b.MaxElapsedTime != 0 && b.GetElapsedTime() > b.MaxElapsedTime { - return Stop - } - defer b.incrementCurrentInterval() - return getRandomValueFromInterval(b.RandomizationFactor, rand.Float64(), b.currentInterval) -} - -// GetElapsedTime returns the elapsed time since an ExponentialBackOff instance -// is created and is reset when Reset() is called. -// -// The elapsed time is computed using time.Now().UnixNano(). It is -// safe to call even while the backoff policy is used by a running -// ticker. -func (b *ExponentialBackOff) GetElapsedTime() time.Duration { - return b.Clock.Now().Sub(b.startTime) -} - -// Increments the current interval by multiplying it with the multiplier. -func (b *ExponentialBackOff) incrementCurrentInterval() { - // Check for overflow, if overflow is detected set the current interval to the max interval. - if float64(b.currentInterval) >= float64(b.MaxInterval)/b.Multiplier { - b.currentInterval = b.MaxInterval - } else { - b.currentInterval = time.Duration(float64(b.currentInterval) * b.Multiplier) - } -} - -// Returns a random value from the following interval: -// [randomizationFactor * currentInterval, randomizationFactor * currentInterval]. -func getRandomValueFromInterval(randomizationFactor, random float64, currentInterval time.Duration) time.Duration { - var delta = randomizationFactor * float64(currentInterval) - var minInterval = float64(currentInterval) - delta - var maxInterval = float64(currentInterval) + delta - - // Get a random value from the range [minInterval, maxInterval]. - // The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then - // we want a 33% chance for selecting either 1, 2 or 3. - return time.Duration(minInterval + (random * (maxInterval - minInterval + 1))) -} diff --git a/vendor/github.com/cenkalti/backoff/retry.go b/vendor/github.com/cenkalti/backoff/retry.go deleted file mode 100644 index e936a506..00000000 --- a/vendor/github.com/cenkalti/backoff/retry.go +++ /dev/null @@ -1,82 +0,0 @@ -package backoff - -import "time" - -// An Operation is executing by Retry() or RetryNotify(). -// The operation will be retried using a backoff policy if it returns an error. -type Operation func() error - -// Notify is a notify-on-error function. It receives an operation error and -// backoff delay if the operation failed (with an error). -// -// NOTE that if the backoff policy stated to stop retrying, -// the notify function isn't called. -type Notify func(error, time.Duration) - -// Retry the operation o until it does not return error or BackOff stops. -// o is guaranteed to be run at least once. -// -// If o returns a *PermanentError, the operation is not retried, and the -// wrapped error is returned. -// -// Retry sleeps the goroutine for the duration returned by BackOff after a -// failed operation returns. -func Retry(o Operation, b BackOff) error { return RetryNotify(o, b, nil) } - -// RetryNotify calls notify function with the error and wait duration -// for each failed attempt before sleep. -func RetryNotify(operation Operation, b BackOff, notify Notify) error { - var err error - var next time.Duration - var t *time.Timer - - cb := ensureContext(b) - - b.Reset() - for { - if err = operation(); err == nil { - return nil - } - - if permanent, ok := err.(*PermanentError); ok { - return permanent.Err - } - - if next = cb.NextBackOff(); next == Stop { - return err - } - - if notify != nil { - notify(err, next) - } - - if t == nil { - t = time.NewTimer(next) - defer t.Stop() - } else { - t.Reset(next) - } - - select { - case <-cb.Context().Done(): - return err - case <-t.C: - } - } -} - -// PermanentError signals that the operation should not be retried. -type PermanentError struct { - Err error -} - -func (e *PermanentError) Error() string { - return e.Err.Error() -} - -// Permanent wraps the given err in a *PermanentError. -func Permanent(err error) *PermanentError { - return &PermanentError{ - Err: err, - } -} diff --git a/vendor/github.com/cenkalti/backoff/ticker.go b/vendor/github.com/cenkalti/backoff/ticker.go deleted file mode 100644 index e41084b0..00000000 --- a/vendor/github.com/cenkalti/backoff/ticker.go +++ /dev/null @@ -1,82 +0,0 @@ -package backoff - -import ( - "sync" - "time" -) - -// Ticker holds a channel that delivers `ticks' of a clock at times reported by a BackOff. -// -// Ticks will continue to arrive when the previous operation is still running, -// so operations that take a while to fail could run in quick succession. -type Ticker struct { - C <-chan time.Time - c chan time.Time - b BackOffContext - stop chan struct{} - stopOnce sync.Once -} - -// NewTicker returns a new Ticker containing a channel that will send -// the time at times specified by the BackOff argument. Ticker is -// guaranteed to tick at least once. The channel is closed when Stop -// method is called or BackOff stops. It is not safe to manipulate the -// provided backoff policy (notably calling NextBackOff or Reset) -// while the ticker is running. -func NewTicker(b BackOff) *Ticker { - c := make(chan time.Time) - t := &Ticker{ - C: c, - c: c, - b: ensureContext(b), - stop: make(chan struct{}), - } - t.b.Reset() - go t.run() - return t -} - -// Stop turns off a ticker. After Stop, no more ticks will be sent. -func (t *Ticker) Stop() { - t.stopOnce.Do(func() { close(t.stop) }) -} - -func (t *Ticker) run() { - c := t.c - defer close(c) - - // Ticker is guaranteed to tick at least once. - afterC := t.send(time.Now()) - - for { - if afterC == nil { - return - } - - select { - case tick := <-afterC: - afterC = t.send(tick) - case <-t.stop: - t.c = nil // Prevent future ticks from being sent to the channel. - return - case <-t.b.Context().Done(): - return - } - } -} - -func (t *Ticker) send(tick time.Time) <-chan time.Time { - select { - case t.c <- tick: - case <-t.stop: - return nil - } - - next := t.b.NextBackOff() - if next == Stop { - t.Stop() - return nil - } - - return time.After(next) -} diff --git a/vendor/github.com/cenkalti/backoff/tries.go b/vendor/github.com/cenkalti/backoff/tries.go deleted file mode 100644 index cfeefd9b..00000000 --- a/vendor/github.com/cenkalti/backoff/tries.go +++ /dev/null @@ -1,35 +0,0 @@ -package backoff - -import "time" - -/* -WithMaxRetries creates a wrapper around another BackOff, which will -return Stop if NextBackOff() has been called too many times since -the last time Reset() was called - -Note: Implementation is not thread-safe. -*/ -func WithMaxRetries(b BackOff, max uint64) BackOff { - return &backOffTries{delegate: b, maxTries: max} -} - -type backOffTries struct { - delegate BackOff - maxTries uint64 - numTries uint64 -} - -func (b *backOffTries) NextBackOff() time.Duration { - if b.maxTries > 0 { - if b.maxTries <= b.numTries { - return Stop - } - b.numTries++ - } - return b.delegate.NextBackOff() -} - -func (b *backOffTries) Reset() { - b.numTries = 0 - b.delegate.Reset() -} diff --git a/vendor/github.com/cloudflare/circl/LICENSE b/vendor/github.com/cloudflare/circl/LICENSE deleted file mode 100644 index 67edaa90..00000000 --- a/vendor/github.com/cloudflare/circl/LICENSE +++ /dev/null @@ -1,57 +0,0 @@ -Copyright (c) 2019 Cloudflare. 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 Cloudflare 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. - -======================================================================== - -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/cloudflare/circl/dh/x25519/curve.go b/vendor/github.com/cloudflare/circl/dh/x25519/curve.go deleted file mode 100644 index f9057c2b..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x25519/curve.go +++ /dev/null @@ -1,96 +0,0 @@ -package x25519 - -import ( - fp "github.com/cloudflare/circl/math/fp25519" -) - -// ladderJoye calculates a fixed-point multiplication with the generator point. -// The algorithm is the right-to-left Joye's ladder as described -// in "How to precompute a ladder" in SAC'2017. -func ladderJoye(k *Key) { - w := [5]fp.Elt{} // [mu,x1,z1,x2,z2] order must be preserved. - fp.SetOne(&w[1]) // x1 = 1 - fp.SetOne(&w[2]) // z1 = 1 - w[3] = fp.Elt{ // x2 = G-S - 0xbd, 0xaa, 0x2f, 0xc8, 0xfe, 0xe1, 0x94, 0x7e, - 0xf8, 0xed, 0xb2, 0x14, 0xae, 0x95, 0xf0, 0xbb, - 0xe2, 0x48, 0x5d, 0x23, 0xb9, 0xa0, 0xc7, 0xad, - 0x34, 0xab, 0x7c, 0xe2, 0xee, 0xcd, 0xae, 0x1e, - } - fp.SetOne(&w[4]) // z2 = 1 - - const n = 255 - const h = 3 - swap := uint(1) - for s := 0; s < n-h; s++ { - i := (s + h) / 8 - j := (s + h) % 8 - bit := uint((k[i] >> uint(j)) & 1) - copy(w[0][:], tableGenerator[s*Size:(s+1)*Size]) - diffAdd(&w, swap^bit) - swap = bit - } - for s := 0; s < h; s++ { - double(&w[1], &w[2]) - } - toAffine((*[fp.Size]byte)(k), &w[1], &w[2]) -} - -// ladderMontgomery calculates a generic scalar point multiplication -// The algorithm implemented is the left-to-right Montgomery's ladder. -func ladderMontgomery(k, xP *Key) { - w := [5]fp.Elt{} // [x1, x2, z2, x3, z3] order must be preserved. - w[0] = *(*fp.Elt)(xP) // x1 = xP - fp.SetOne(&w[1]) // x2 = 1 - w[3] = *(*fp.Elt)(xP) // x3 = xP - fp.SetOne(&w[4]) // z3 = 1 - - move := uint(0) - for s := 255 - 1; s >= 0; s-- { - i := s / 8 - j := s % 8 - bit := uint((k[i] >> uint(j)) & 1) - ladderStep(&w, move^bit) - move = bit - } - toAffine((*[fp.Size]byte)(k), &w[1], &w[2]) -} - -func toAffine(k *[fp.Size]byte, x, z *fp.Elt) { - fp.Inv(z, z) - fp.Mul(x, x, z) - _ = fp.ToBytes(k[:], x) -} - -var lowOrderPoints = [5]fp.Elt{ - { /* (0,_,1) point of order 2 on Curve25519 */ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - }, - { /* (1,_,1) point of order 4 on Curve25519 */ - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - }, - { /* (x,_,1) first point of order 8 on Curve25519 */ - 0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae, - 0x16, 0x56, 0xe3, 0xfa, 0xf1, 0x9f, 0xc4, 0x6a, - 0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32, 0xb1, 0xfd, - 0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00, - }, - { /* (x,_,1) second point of order 8 on Curve25519 */ - 0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24, - 0xb1, 0xd0, 0xb1, 0x55, 0x9c, 0x83, 0xef, 0x5b, - 0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c, 0x8e, 0x86, - 0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57, - }, - { /* (-1,_,1) a point of order 4 on the twist of Curve25519 */ - 0xec, 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, 0x7f, - }, -} diff --git a/vendor/github.com/cloudflare/circl/dh/x25519/curve_amd64.go b/vendor/github.com/cloudflare/circl/dh/x25519/curve_amd64.go deleted file mode 100644 index 8a3d54c5..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x25519/curve_amd64.go +++ /dev/null @@ -1,30 +0,0 @@ -//go:build amd64 && !purego -// +build amd64,!purego - -package x25519 - -import ( - fp "github.com/cloudflare/circl/math/fp25519" - "golang.org/x/sys/cpu" -) - -var hasBmi2Adx = cpu.X86.HasBMI2 && cpu.X86.HasADX - -var _ = hasBmi2Adx - -func double(x, z *fp.Elt) { doubleAmd64(x, z) } -func diffAdd(w *[5]fp.Elt, b uint) { diffAddAmd64(w, b) } -func ladderStep(w *[5]fp.Elt, b uint) { ladderStepAmd64(w, b) } -func mulA24(z, x *fp.Elt) { mulA24Amd64(z, x) } - -//go:noescape -func ladderStepAmd64(w *[5]fp.Elt, b uint) - -//go:noescape -func diffAddAmd64(w *[5]fp.Elt, b uint) - -//go:noescape -func doubleAmd64(x, z *fp.Elt) - -//go:noescape -func mulA24Amd64(z, x *fp.Elt) diff --git a/vendor/github.com/cloudflare/circl/dh/x25519/curve_amd64.h b/vendor/github.com/cloudflare/circl/dh/x25519/curve_amd64.h deleted file mode 100644 index 8c1ae4d0..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x25519/curve_amd64.h +++ /dev/null @@ -1,111 +0,0 @@ -#define ladderStepLeg \ - addSub(x2,z2) \ - addSub(x3,z3) \ - integerMulLeg(b0,x2,z3) \ - integerMulLeg(b1,x3,z2) \ - reduceFromDoubleLeg(t0,b0) \ - reduceFromDoubleLeg(t1,b1) \ - addSub(t0,t1) \ - cselect(x2,x3,regMove) \ - cselect(z2,z3,regMove) \ - integerSqrLeg(b0,t0) \ - integerSqrLeg(b1,t1) \ - reduceFromDoubleLeg(x3,b0) \ - reduceFromDoubleLeg(z3,b1) \ - integerMulLeg(b0,x1,z3) \ - reduceFromDoubleLeg(z3,b0) \ - integerSqrLeg(b0,x2) \ - integerSqrLeg(b1,z2) \ - reduceFromDoubleLeg(x2,b0) \ - reduceFromDoubleLeg(z2,b1) \ - subtraction(t0,x2,z2) \ - multiplyA24Leg(t1,t0) \ - additionLeg(t1,t1,z2) \ - integerMulLeg(b0,x2,z2) \ - integerMulLeg(b1,t0,t1) \ - reduceFromDoubleLeg(x2,b0) \ - reduceFromDoubleLeg(z2,b1) - -#define ladderStepBmi2Adx \ - addSub(x2,z2) \ - addSub(x3,z3) \ - integerMulAdx(b0,x2,z3) \ - integerMulAdx(b1,x3,z2) \ - reduceFromDoubleAdx(t0,b0) \ - reduceFromDoubleAdx(t1,b1) \ - addSub(t0,t1) \ - cselect(x2,x3,regMove) \ - cselect(z2,z3,regMove) \ - integerSqrAdx(b0,t0) \ - integerSqrAdx(b1,t1) \ - reduceFromDoubleAdx(x3,b0) \ - reduceFromDoubleAdx(z3,b1) \ - integerMulAdx(b0,x1,z3) \ - reduceFromDoubleAdx(z3,b0) \ - integerSqrAdx(b0,x2) \ - integerSqrAdx(b1,z2) \ - reduceFromDoubleAdx(x2,b0) \ - reduceFromDoubleAdx(z2,b1) \ - subtraction(t0,x2,z2) \ - multiplyA24Adx(t1,t0) \ - additionAdx(t1,t1,z2) \ - integerMulAdx(b0,x2,z2) \ - integerMulAdx(b1,t0,t1) \ - reduceFromDoubleAdx(x2,b0) \ - reduceFromDoubleAdx(z2,b1) - -#define difAddLeg \ - addSub(x1,z1) \ - integerMulLeg(b0,z1,ui) \ - reduceFromDoubleLeg(z1,b0) \ - addSub(x1,z1) \ - integerSqrLeg(b0,x1) \ - integerSqrLeg(b1,z1) \ - reduceFromDoubleLeg(x1,b0) \ - reduceFromDoubleLeg(z1,b1) \ - integerMulLeg(b0,x1,z2) \ - integerMulLeg(b1,z1,x2) \ - reduceFromDoubleLeg(x1,b0) \ - reduceFromDoubleLeg(z1,b1) - -#define difAddBmi2Adx \ - addSub(x1,z1) \ - integerMulAdx(b0,z1,ui) \ - reduceFromDoubleAdx(z1,b0) \ - addSub(x1,z1) \ - integerSqrAdx(b0,x1) \ - integerSqrAdx(b1,z1) \ - reduceFromDoubleAdx(x1,b0) \ - reduceFromDoubleAdx(z1,b1) \ - integerMulAdx(b0,x1,z2) \ - integerMulAdx(b1,z1,x2) \ - reduceFromDoubleAdx(x1,b0) \ - reduceFromDoubleAdx(z1,b1) - -#define doubleLeg \ - addSub(x1,z1) \ - integerSqrLeg(b0,x1) \ - integerSqrLeg(b1,z1) \ - reduceFromDoubleLeg(x1,b0) \ - reduceFromDoubleLeg(z1,b1) \ - subtraction(t0,x1,z1) \ - multiplyA24Leg(t1,t0) \ - additionLeg(t1,t1,z1) \ - integerMulLeg(b0,x1,z1) \ - integerMulLeg(b1,t0,t1) \ - reduceFromDoubleLeg(x1,b0) \ - reduceFromDoubleLeg(z1,b1) - -#define doubleBmi2Adx \ - addSub(x1,z1) \ - integerSqrAdx(b0,x1) \ - integerSqrAdx(b1,z1) \ - reduceFromDoubleAdx(x1,b0) \ - reduceFromDoubleAdx(z1,b1) \ - subtraction(t0,x1,z1) \ - multiplyA24Adx(t1,t0) \ - additionAdx(t1,t1,z1) \ - integerMulAdx(b0,x1,z1) \ - integerMulAdx(b1,t0,t1) \ - reduceFromDoubleAdx(x1,b0) \ - reduceFromDoubleAdx(z1,b1) diff --git a/vendor/github.com/cloudflare/circl/dh/x25519/curve_amd64.s b/vendor/github.com/cloudflare/circl/dh/x25519/curve_amd64.s deleted file mode 100644 index b7723185..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x25519/curve_amd64.s +++ /dev/null @@ -1,156 +0,0 @@ -// +build amd64 - -#include "textflag.h" - -// Depends on circl/math/fp25519 package -#include "../../math/fp25519/fp_amd64.h" -#include "curve_amd64.h" - -// CTE_A24 is (A+2)/4 from Curve25519 -#define CTE_A24 121666 - -#define Size 32 - -// multiplyA24Leg multiplies x times CTE_A24 and stores in z -// Uses: AX, DX, R8-R13, FLAGS -// Instr: x86_64, cmov -#define multiplyA24Leg(z,x) \ - MOVL $CTE_A24, AX; MULQ 0+x; MOVQ AX, R8; MOVQ DX, R9; \ - MOVL $CTE_A24, AX; MULQ 8+x; MOVQ AX, R12; MOVQ DX, R10; \ - MOVL $CTE_A24, AX; MULQ 16+x; MOVQ AX, R13; MOVQ DX, R11; \ - MOVL $CTE_A24, AX; MULQ 24+x; \ - ADDQ R12, R9; \ - ADCQ R13, R10; \ - ADCQ AX, R11; \ - ADCQ $0, DX; \ - MOVL $38, AX; /* 2*C = 38 = 2^256 MOD 2^255-19*/ \ - IMULQ AX, DX; \ - ADDQ DX, R8; \ - ADCQ $0, R9; MOVQ R9, 8+z; \ - ADCQ $0, R10; MOVQ R10, 16+z; \ - ADCQ $0, R11; MOVQ R11, 24+z; \ - MOVQ $0, DX; \ - CMOVQCS AX, DX; \ - ADDQ DX, R8; MOVQ R8, 0+z; - -// multiplyA24Adx multiplies x times CTE_A24 and stores in z -// Uses: AX, DX, R8-R12, FLAGS -// Instr: x86_64, cmov, bmi2 -#define multiplyA24Adx(z,x) \ - MOVQ $CTE_A24, DX; \ - MULXQ 0+x, R8, R10; \ - MULXQ 8+x, R9, R11; ADDQ R10, R9; \ - MULXQ 16+x, R10, AX; ADCQ R11, R10; \ - MULXQ 24+x, R11, R12; ADCQ AX, R11; \ - ;;;;;;;;;;;;;;;;;;;;; ADCQ $0, R12; \ - MOVL $38, DX; /* 2*C = 38 = 2^256 MOD 2^255-19*/ \ - IMULQ DX, R12; \ - ADDQ R12, R8; \ - ADCQ $0, R9; MOVQ R9, 8+z; \ - ADCQ $0, R10; MOVQ R10, 16+z; \ - ADCQ $0, R11; MOVQ R11, 24+z; \ - MOVQ $0, R12; \ - CMOVQCS DX, R12; \ - ADDQ R12, R8; MOVQ R8, 0+z; - -#define mulA24Legacy \ - multiplyA24Leg(0(DI),0(SI)) -#define mulA24Bmi2Adx \ - multiplyA24Adx(0(DI),0(SI)) - -// func mulA24Amd64(z, x *fp255.Elt) -TEXT ·mulA24Amd64(SB),NOSPLIT,$0-16 - MOVQ z+0(FP), DI - MOVQ x+8(FP), SI - CHECK_BMI2ADX(LMA24, mulA24Legacy, mulA24Bmi2Adx) - - -// func ladderStepAmd64(w *[5]fp255.Elt, b uint) -// ladderStepAmd64 calculates a point addition and doubling as follows: -// (x2,z2) = 2*(x2,z2) and (x3,z3) = (x2,z2)+(x3,z3) using as a difference (x1,-). -// work = (x1,x2,z2,x3,z3) are five fp255.Elt of 32 bytes. -// stack = (t0,t1) are two fp.Elt of fp.Size bytes, and -// (b0,b1) are two-double precision fp.Elt of 2*fp.Size bytes. -TEXT ·ladderStepAmd64(SB),NOSPLIT,$192-16 - // Parameters - #define regWork DI - #define regMove SI - #define x1 0*Size(regWork) - #define x2 1*Size(regWork) - #define z2 2*Size(regWork) - #define x3 3*Size(regWork) - #define z3 4*Size(regWork) - // Local variables - #define t0 0*Size(SP) - #define t1 1*Size(SP) - #define b0 2*Size(SP) - #define b1 4*Size(SP) - MOVQ w+0(FP), regWork - MOVQ b+8(FP), regMove - CHECK_BMI2ADX(LLADSTEP, ladderStepLeg, ladderStepBmi2Adx) - #undef regWork - #undef regMove - #undef x1 - #undef x2 - #undef z2 - #undef x3 - #undef z3 - #undef t0 - #undef t1 - #undef b0 - #undef b1 - -// func diffAddAmd64(w *[5]fp255.Elt, b uint) -// diffAddAmd64 calculates a differential point addition using a precomputed point. -// (x1,z1) = (x1,z1)+(mu) using a difference point (x2,z2) -// w = (mu,x1,z1,x2,z2) are five fp.Elt, and -// stack = (b0,b1) are two-double precision fp.Elt of 2*fp.Size bytes. -TEXT ·diffAddAmd64(SB),NOSPLIT,$128-16 - // Parameters - #define regWork DI - #define regSwap SI - #define ui 0*Size(regWork) - #define x1 1*Size(regWork) - #define z1 2*Size(regWork) - #define x2 3*Size(regWork) - #define z2 4*Size(regWork) - // Local variables - #define b0 0*Size(SP) - #define b1 2*Size(SP) - MOVQ w+0(FP), regWork - MOVQ b+8(FP), regSwap - cswap(x1,x2,regSwap) - cswap(z1,z2,regSwap) - CHECK_BMI2ADX(LDIFADD, difAddLeg, difAddBmi2Adx) - #undef regWork - #undef regSwap - #undef ui - #undef x1 - #undef z1 - #undef x2 - #undef z2 - #undef b0 - #undef b1 - -// func doubleAmd64(x, z *fp255.Elt) -// doubleAmd64 calculates a point doubling (x1,z1) = 2*(x1,z1). -// stack = (t0,t1) are two fp.Elt of fp.Size bytes, and -// (b0,b1) are two-double precision fp.Elt of 2*fp.Size bytes. -TEXT ·doubleAmd64(SB),NOSPLIT,$192-16 - // Parameters - #define x1 0(DI) - #define z1 0(SI) - // Local variables - #define t0 0*Size(SP) - #define t1 1*Size(SP) - #define b0 2*Size(SP) - #define b1 4*Size(SP) - MOVQ x+0(FP), DI - MOVQ z+8(FP), SI - CHECK_BMI2ADX(LDOUB,doubleLeg,doubleBmi2Adx) - #undef x1 - #undef z1 - #undef t0 - #undef t1 - #undef b0 - #undef b1 diff --git a/vendor/github.com/cloudflare/circl/dh/x25519/curve_generic.go b/vendor/github.com/cloudflare/circl/dh/x25519/curve_generic.go deleted file mode 100644 index dae67ea3..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x25519/curve_generic.go +++ /dev/null @@ -1,85 +0,0 @@ -package x25519 - -import ( - "encoding/binary" - "math/bits" - - fp "github.com/cloudflare/circl/math/fp25519" -) - -func doubleGeneric(x, z *fp.Elt) { - t0, t1 := &fp.Elt{}, &fp.Elt{} - fp.AddSub(x, z) - fp.Sqr(x, x) - fp.Sqr(z, z) - fp.Sub(t0, x, z) - mulA24Generic(t1, t0) - fp.Add(t1, t1, z) - fp.Mul(x, x, z) - fp.Mul(z, t0, t1) -} - -func diffAddGeneric(w *[5]fp.Elt, b uint) { - mu, x1, z1, x2, z2 := &w[0], &w[1], &w[2], &w[3], &w[4] - fp.Cswap(x1, x2, b) - fp.Cswap(z1, z2, b) - fp.AddSub(x1, z1) - fp.Mul(z1, z1, mu) - fp.AddSub(x1, z1) - fp.Sqr(x1, x1) - fp.Sqr(z1, z1) - fp.Mul(x1, x1, z2) - fp.Mul(z1, z1, x2) -} - -func ladderStepGeneric(w *[5]fp.Elt, b uint) { - x1, x2, z2, x3, z3 := &w[0], &w[1], &w[2], &w[3], &w[4] - t0 := &fp.Elt{} - t1 := &fp.Elt{} - fp.AddSub(x2, z2) - fp.AddSub(x3, z3) - fp.Mul(t0, x2, z3) - fp.Mul(t1, x3, z2) - fp.AddSub(t0, t1) - fp.Cmov(x2, x3, b) - fp.Cmov(z2, z3, b) - fp.Sqr(x3, t0) - fp.Sqr(z3, t1) - fp.Mul(z3, x1, z3) - fp.Sqr(x2, x2) - fp.Sqr(z2, z2) - fp.Sub(t0, x2, z2) - mulA24Generic(t1, t0) - fp.Add(t1, t1, z2) - fp.Mul(x2, x2, z2) - fp.Mul(z2, t0, t1) -} - -func mulA24Generic(z, x *fp.Elt) { - const A24 = 121666 - const n = 8 - var xx [4]uint64 - for i := range xx { - xx[i] = binary.LittleEndian.Uint64(x[i*n : (i+1)*n]) - } - - h0, l0 := bits.Mul64(xx[0], A24) - h1, l1 := bits.Mul64(xx[1], A24) - h2, l2 := bits.Mul64(xx[2], A24) - h3, l3 := bits.Mul64(xx[3], A24) - - var c3 uint64 - l1, c0 := bits.Add64(h0, l1, 0) - l2, c1 := bits.Add64(h1, l2, c0) - l3, c2 := bits.Add64(h2, l3, c1) - l4, _ := bits.Add64(h3, 0, c2) - _, l4 = bits.Mul64(l4, 38) - l0, c0 = bits.Add64(l0, l4, 0) - xx[1], c1 = bits.Add64(l1, 0, c0) - xx[2], c2 = bits.Add64(l2, 0, c1) - xx[3], c3 = bits.Add64(l3, 0, c2) - xx[0], _ = bits.Add64(l0, (-c3)&38, 0) - for i := range xx { - binary.LittleEndian.PutUint64(z[i*n:(i+1)*n], xx[i]) - } -} diff --git a/vendor/github.com/cloudflare/circl/dh/x25519/curve_noasm.go b/vendor/github.com/cloudflare/circl/dh/x25519/curve_noasm.go deleted file mode 100644 index 07fab97d..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x25519/curve_noasm.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !amd64 || purego -// +build !amd64 purego - -package x25519 - -import fp "github.com/cloudflare/circl/math/fp25519" - -func double(x, z *fp.Elt) { doubleGeneric(x, z) } -func diffAdd(w *[5]fp.Elt, b uint) { diffAddGeneric(w, b) } -func ladderStep(w *[5]fp.Elt, b uint) { ladderStepGeneric(w, b) } -func mulA24(z, x *fp.Elt) { mulA24Generic(z, x) } diff --git a/vendor/github.com/cloudflare/circl/dh/x25519/doc.go b/vendor/github.com/cloudflare/circl/dh/x25519/doc.go deleted file mode 100644 index 3ce102d1..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x25519/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Package x25519 provides Diffie-Hellman functions as specified in RFC-7748. - -Validation of public keys. - -The Diffie-Hellman function, as described in RFC-7748 [1], works for any -public key. However, if a different protocol requires contributory -behaviour [2,3], then the public keys must be validated against low-order -points [3,4]. To do that, the Shared function performs this validation -internally and returns false when the public key is invalid (i.e., it -is a low-order point). - -References: - - [1] RFC7748 by Langley, Hamburg, Turner (https://rfc-editor.org/rfc/rfc7748.txt) - - [2] Curve25519 by Bernstein (https://cr.yp.to/ecdh.html) - - [3] Bernstein (https://cr.yp.to/ecdh.html#validate) - - [4] Cremers&Jackson (https://eprint.iacr.org/2019/526) -*/ -package x25519 diff --git a/vendor/github.com/cloudflare/circl/dh/x25519/key.go b/vendor/github.com/cloudflare/circl/dh/x25519/key.go deleted file mode 100644 index bbd37ddd..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x25519/key.go +++ /dev/null @@ -1,47 +0,0 @@ -package x25519 - -import ( - "crypto/subtle" - - fp "github.com/cloudflare/circl/math/fp25519" -) - -// Size is the length in bytes of a X25519 key. -const Size = 32 - -// Key represents a X25519 key. -type Key [Size]byte - -func (k *Key) clamp(in *Key) *Key { - *k = *in - k[0] &= 248 - k[31] = (k[31] & 127) | 64 - return k -} - -// isValidPubKey verifies if the public key is not a low-order point. -func (k *Key) isValidPubKey() bool { - fp.Modp((*fp.Elt)(k)) - isLowOrder := false - for _, P := range lowOrderPoints { - isLowOrder = isLowOrder || subtle.ConstantTimeCompare(P[:], k[:]) != 0 - } - return !isLowOrder -} - -// KeyGen obtains a public key given a secret key. -func KeyGen(public, secret *Key) { - ladderJoye(public.clamp(secret)) -} - -// Shared calculates Alice's shared key from Alice's secret key and Bob's -// public key returning true on success. A failure case happens when the public -// key is a low-order point, thus the shared key is all-zeros and the function -// returns false. -func Shared(shared, secret, public *Key) bool { - validPk := *public - validPk[31] &= (1 << (255 % 8)) - 1 - ok := validPk.isValidPubKey() - ladderMontgomery(shared.clamp(secret), &validPk) - return ok -} diff --git a/vendor/github.com/cloudflare/circl/dh/x25519/table.go b/vendor/github.com/cloudflare/circl/dh/x25519/table.go deleted file mode 100644 index 28c8c4ac..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x25519/table.go +++ /dev/null @@ -1,268 +0,0 @@ -package x25519 - -import "github.com/cloudflare/circl/math/fp25519" - -// tableGenerator contains the set of points: -// -// t[i] = (xi+1)/(xi-1), -// -// where (xi,yi) = 2^iG and G is the generator point -// Size = (256)*(256/8) = 8192 bytes. -var tableGenerator = [256 * fp25519.Size]byte{ - /* (2^ 0)P */ 0xf3, 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, 0x5f, - /* (2^ 1)P */ 0x96, 0xfe, 0xaa, 0x16, 0xf4, 0x20, 0x82, 0x6b, 0x34, 0x6a, 0x56, 0x4f, 0x2b, 0xeb, 0xeb, 0x82, 0x0f, 0x95, 0xa5, 0x75, 0xb0, 0xa5, 0xa9, 0xd5, 0xf4, 0x88, 0x24, 0x4b, 0xcf, 0xb2, 0x42, 0x51, - /* (2^ 2)P */ 0x0c, 0x68, 0x69, 0x00, 0x75, 0xbc, 0xae, 0x6a, 0x41, 0x9c, 0xf9, 0xa0, 0x20, 0x78, 0xcf, 0x89, 0xf4, 0xd0, 0x56, 0x3b, 0x18, 0xd9, 0x58, 0x2a, 0xa4, 0x11, 0x60, 0xe3, 0x80, 0xca, 0x5a, 0x4b, - /* (2^ 3)P */ 0x5d, 0x74, 0x29, 0x8c, 0x34, 0x32, 0x91, 0x32, 0xd7, 0x2f, 0x64, 0xe1, 0x16, 0xe6, 0xa2, 0xf4, 0x34, 0xbc, 0x67, 0xff, 0x03, 0xbb, 0x45, 0x1e, 0x4a, 0x9b, 0x2a, 0xf4, 0xd0, 0x12, 0x69, 0x30, - /* (2^ 4)P */ 0x54, 0x71, 0xaf, 0xe6, 0x07, 0x65, 0x88, 0xff, 0x2f, 0xc8, 0xee, 0xdf, 0x13, 0x0e, 0xf5, 0x04, 0xce, 0xb5, 0xba, 0x2a, 0xe8, 0x2f, 0x51, 0xaa, 0x22, 0xf2, 0xd5, 0x68, 0x1a, 0x25, 0x4e, 0x17, - /* (2^ 5)P */ 0x98, 0x88, 0x02, 0x82, 0x0d, 0x70, 0x96, 0xcf, 0xc5, 0x02, 0x2c, 0x0a, 0x37, 0xe3, 0x43, 0x17, 0xaa, 0x6e, 0xe8, 0xb4, 0x98, 0xec, 0x9e, 0x37, 0x2e, 0x48, 0xe0, 0x51, 0x8a, 0x88, 0x59, 0x0c, - /* (2^ 6)P */ 0x89, 0xd1, 0xb5, 0x99, 0xd6, 0xf1, 0xcb, 0xfb, 0x84, 0xdc, 0x9f, 0x8e, 0xd5, 0xf0, 0xae, 0xac, 0x14, 0x76, 0x1f, 0x23, 0x06, 0x0d, 0xc2, 0xc1, 0x72, 0xf9, 0x74, 0xa2, 0x8d, 0x21, 0x38, 0x29, - /* (2^ 7)P */ 0x18, 0x7f, 0x1d, 0xff, 0xbe, 0x49, 0xaf, 0xf6, 0xc2, 0xc9, 0x7a, 0x38, 0x22, 0x1c, 0x54, 0xcc, 0x6b, 0xc5, 0x15, 0x40, 0xef, 0xc9, 0xfc, 0x96, 0xa9, 0x13, 0x09, 0x69, 0x7c, 0x62, 0xc1, 0x69, - /* (2^ 8)P */ 0x0e, 0xdb, 0x33, 0x47, 0x2f, 0xfd, 0x86, 0x7a, 0xe9, 0x7d, 0x08, 0x9e, 0xf2, 0xc4, 0xb8, 0xfd, 0x29, 0xa2, 0xa2, 0x8e, 0x1a, 0x4b, 0x5e, 0x09, 0x79, 0x7a, 0xb3, 0x29, 0xc8, 0xa7, 0xd7, 0x1a, - /* (2^ 9)P */ 0xc0, 0xa0, 0x7e, 0xd1, 0xca, 0x89, 0x2d, 0x34, 0x51, 0x20, 0xed, 0xcc, 0xa6, 0xdd, 0xbe, 0x67, 0x74, 0x2f, 0xb4, 0x2b, 0xbf, 0x31, 0xca, 0x19, 0xbb, 0xac, 0x80, 0x49, 0xc8, 0xb4, 0xf7, 0x3d, - /* (2^ 10)P */ 0x83, 0xd8, 0x0a, 0xc8, 0x4d, 0x44, 0xc6, 0xa8, 0x85, 0xab, 0xe3, 0x66, 0x03, 0x44, 0x1e, 0xb9, 0xd8, 0xf6, 0x64, 0x01, 0xa0, 0xcd, 0x15, 0xc2, 0x68, 0xe6, 0x47, 0xf2, 0x6e, 0x7c, 0x86, 0x3d, - /* (2^ 11)P */ 0x8c, 0x65, 0x3e, 0xcc, 0x2b, 0x58, 0xdd, 0xc7, 0x28, 0x55, 0x0e, 0xee, 0x48, 0x47, 0x2c, 0xfd, 0x71, 0x4f, 0x9f, 0xcc, 0x95, 0x9b, 0xfd, 0xa0, 0xdf, 0x5d, 0x67, 0xb0, 0x71, 0xd8, 0x29, 0x75, - /* (2^ 12)P */ 0x78, 0xbd, 0x3c, 0x2d, 0xb4, 0x68, 0xf5, 0xb8, 0x82, 0xda, 0xf3, 0x91, 0x1b, 0x01, 0x33, 0x12, 0x62, 0x3b, 0x7c, 0x4a, 0xcd, 0x6c, 0xce, 0x2d, 0x03, 0x86, 0x49, 0x9e, 0x8e, 0xfc, 0xe7, 0x75, - /* (2^ 13)P */ 0xec, 0xb6, 0xd0, 0xfc, 0xf1, 0x13, 0x4f, 0x2f, 0x45, 0x7a, 0xff, 0x29, 0x1f, 0xca, 0xa8, 0xf1, 0x9b, 0xe2, 0x81, 0x29, 0xa7, 0xc1, 0x49, 0xc2, 0x6a, 0xb5, 0x83, 0x8c, 0xbb, 0x0d, 0xbe, 0x6e, - /* (2^ 14)P */ 0x22, 0xb2, 0x0b, 0x17, 0x8d, 0xfa, 0x14, 0x71, 0x5f, 0x93, 0x93, 0xbf, 0xd5, 0xdc, 0xa2, 0x65, 0x9a, 0x97, 0x9c, 0xb5, 0x68, 0x1f, 0xc4, 0xbd, 0x89, 0x92, 0xce, 0xa2, 0x79, 0xef, 0x0e, 0x2f, - /* (2^ 15)P */ 0xce, 0x37, 0x3c, 0x08, 0x0c, 0xbf, 0xec, 0x42, 0x22, 0x63, 0x49, 0xec, 0x09, 0xbc, 0x30, 0x29, 0x0d, 0xac, 0xfe, 0x9c, 0xc1, 0xb0, 0x94, 0xf2, 0x80, 0xbb, 0xfa, 0xed, 0x4b, 0xaa, 0x80, 0x37, - /* (2^ 16)P */ 0x29, 0xd9, 0xea, 0x7c, 0x3e, 0x7d, 0xc1, 0x56, 0xc5, 0x22, 0x57, 0x2e, 0xeb, 0x4b, 0xcb, 0xe7, 0x5a, 0xe1, 0xbf, 0x2d, 0x73, 0x31, 0xe9, 0x0c, 0xf8, 0x52, 0x10, 0x62, 0xc7, 0x83, 0xb8, 0x41, - /* (2^ 17)P */ 0x50, 0x53, 0xd2, 0xc3, 0xa0, 0x5c, 0xf7, 0xdb, 0x51, 0xe3, 0xb1, 0x6e, 0x08, 0xbe, 0x36, 0x29, 0x12, 0xb2, 0xa9, 0xb4, 0x3c, 0xe0, 0x36, 0xc9, 0xaa, 0x25, 0x22, 0x32, 0x82, 0xbf, 0x45, 0x1d, - /* (2^ 18)P */ 0xc5, 0x4c, 0x02, 0x6a, 0x03, 0xb1, 0x1a, 0xe8, 0x72, 0x9a, 0x4c, 0x30, 0x1c, 0x20, 0x12, 0xe2, 0xfc, 0xb1, 0x32, 0x68, 0xba, 0x3f, 0xd7, 0xc5, 0x81, 0x95, 0x83, 0x4d, 0x5a, 0xdb, 0xff, 0x20, - /* (2^ 19)P */ 0xad, 0x0f, 0x5d, 0xbe, 0x67, 0xd3, 0x83, 0xa2, 0x75, 0x44, 0x16, 0x8b, 0xca, 0x25, 0x2b, 0x6c, 0x2e, 0xf2, 0xaa, 0x7c, 0x46, 0x35, 0x49, 0x9d, 0x49, 0xff, 0x85, 0xee, 0x8e, 0x40, 0x66, 0x51, - /* (2^ 20)P */ 0x61, 0xe3, 0xb4, 0xfa, 0xa2, 0xba, 0x67, 0x3c, 0xef, 0x5c, 0xf3, 0x7e, 0xc6, 0x33, 0xe4, 0xb3, 0x1c, 0x9b, 0x15, 0x41, 0x92, 0x72, 0x59, 0x52, 0x33, 0xab, 0xb0, 0xd5, 0x92, 0x18, 0x62, 0x6a, - /* (2^ 21)P */ 0xcb, 0xcd, 0x55, 0x75, 0x38, 0x4a, 0xb7, 0x20, 0x3f, 0x92, 0x08, 0x12, 0x0e, 0xa1, 0x2a, 0x53, 0xd1, 0x1d, 0x28, 0x62, 0x77, 0x7b, 0xa1, 0xea, 0xbf, 0x44, 0x5c, 0xf0, 0x43, 0x34, 0xab, 0x61, - /* (2^ 22)P */ 0xf8, 0xde, 0x24, 0x23, 0x42, 0x6c, 0x7a, 0x25, 0x7f, 0xcf, 0xe3, 0x17, 0x10, 0x6c, 0x1c, 0x13, 0x57, 0xa2, 0x30, 0xf6, 0x39, 0x87, 0x75, 0x23, 0x80, 0x85, 0xa7, 0x01, 0x7a, 0x40, 0x5a, 0x29, - /* (2^ 23)P */ 0xd9, 0xa8, 0x5d, 0x6d, 0x24, 0x43, 0xc4, 0xf8, 0x5d, 0xfa, 0x52, 0x0c, 0x45, 0x75, 0xd7, 0x19, 0x3d, 0xf8, 0x1b, 0x73, 0x92, 0xfc, 0xfc, 0x2a, 0x00, 0x47, 0x2b, 0x1b, 0xe8, 0xc8, 0x10, 0x7d, - /* (2^ 24)P */ 0x0b, 0xa2, 0xba, 0x70, 0x1f, 0x27, 0xe0, 0xc8, 0x57, 0x39, 0xa6, 0x7c, 0x86, 0x48, 0x37, 0x99, 0xbb, 0xd4, 0x7e, 0xcb, 0xb3, 0xef, 0x12, 0x54, 0x75, 0x29, 0xe6, 0x73, 0x61, 0xd3, 0x96, 0x31, - /* (2^ 25)P */ 0xfc, 0xdf, 0xc7, 0x41, 0xd1, 0xca, 0x5b, 0xde, 0x48, 0xc8, 0x95, 0xb3, 0xd2, 0x8c, 0xcc, 0x47, 0xcb, 0xf3, 0x1a, 0xe1, 0x42, 0xd9, 0x4c, 0xa3, 0xc2, 0xce, 0x4e, 0xd0, 0xf2, 0xdb, 0x56, 0x02, - /* (2^ 26)P */ 0x7f, 0x66, 0x0e, 0x4b, 0xe9, 0xb7, 0x5a, 0x87, 0x10, 0x0d, 0x85, 0xc0, 0x83, 0xdd, 0xd4, 0xca, 0x9f, 0xc7, 0x72, 0x4e, 0x8f, 0x2e, 0xf1, 0x47, 0x9b, 0xb1, 0x85, 0x8c, 0xbb, 0x87, 0x1a, 0x5f, - /* (2^ 27)P */ 0xb8, 0x51, 0x7f, 0x43, 0xb6, 0xd0, 0xe9, 0x7a, 0x65, 0x90, 0x87, 0x18, 0x55, 0xce, 0xc7, 0x12, 0xee, 0x7a, 0xf7, 0x5c, 0xfe, 0x09, 0xde, 0x2a, 0x27, 0x56, 0x2c, 0x7d, 0x2f, 0x5a, 0xa0, 0x23, - /* (2^ 28)P */ 0x9a, 0x16, 0x7c, 0xf1, 0x28, 0xe1, 0x08, 0x59, 0x2d, 0x85, 0xd0, 0x8a, 0xdd, 0x98, 0x74, 0xf7, 0x64, 0x2f, 0x10, 0xab, 0xce, 0xc4, 0xb4, 0x74, 0x45, 0x98, 0x13, 0x10, 0xdd, 0xba, 0x3a, 0x18, - /* (2^ 29)P */ 0xac, 0xaa, 0x92, 0xaa, 0x8d, 0xba, 0x65, 0xb1, 0x05, 0x67, 0x38, 0x99, 0x95, 0xef, 0xc5, 0xd5, 0xd1, 0x40, 0xfc, 0xf8, 0x0c, 0x8f, 0x2f, 0xbe, 0x14, 0x45, 0x20, 0xee, 0x35, 0xe6, 0x01, 0x27, - /* (2^ 30)P */ 0x14, 0x65, 0x15, 0x20, 0x00, 0xa8, 0x9f, 0x62, 0xce, 0xc1, 0xa8, 0x64, 0x87, 0x86, 0x23, 0xf2, 0x0e, 0x06, 0x3f, 0x0b, 0xff, 0x4f, 0x89, 0x5b, 0xfa, 0xa3, 0x08, 0xf7, 0x4c, 0x94, 0xd9, 0x60, - /* (2^ 31)P */ 0x1f, 0x20, 0x7a, 0x1c, 0x1a, 0x00, 0xea, 0xae, 0x63, 0xce, 0xe2, 0x3e, 0x63, 0x6a, 0xf1, 0xeb, 0xe1, 0x07, 0x7a, 0x4c, 0x59, 0x09, 0x77, 0x6f, 0xcb, 0x08, 0x02, 0x0d, 0x15, 0x58, 0xb9, 0x79, - /* (2^ 32)P */ 0xe7, 0x10, 0xd4, 0x01, 0x53, 0x5e, 0xb5, 0x24, 0x4d, 0xc8, 0xfd, 0xf3, 0xdf, 0x4e, 0xa3, 0xe3, 0xd8, 0x32, 0x40, 0x90, 0xe4, 0x68, 0x87, 0xd8, 0xec, 0xae, 0x3a, 0x7b, 0x42, 0x84, 0x13, 0x13, - /* (2^ 33)P */ 0x14, 0x4f, 0x23, 0x86, 0x12, 0xe5, 0x05, 0x84, 0x29, 0xc5, 0xb4, 0xad, 0x39, 0x47, 0xdc, 0x14, 0xfd, 0x4f, 0x63, 0x50, 0xb2, 0xb5, 0xa2, 0xb8, 0x93, 0xff, 0xa7, 0xd8, 0x4a, 0xa9, 0xe2, 0x2f, - /* (2^ 34)P */ 0xdd, 0xfa, 0x43, 0xe8, 0xef, 0x57, 0x5c, 0xec, 0x18, 0x99, 0xbb, 0xf0, 0x40, 0xce, 0x43, 0x28, 0x05, 0x63, 0x3d, 0xcf, 0xd6, 0x61, 0xb5, 0xa4, 0x7e, 0x77, 0xfb, 0xe8, 0xbd, 0x29, 0x36, 0x74, - /* (2^ 35)P */ 0x8f, 0x73, 0xaf, 0xbb, 0x46, 0xdd, 0x3e, 0x34, 0x51, 0xa6, 0x01, 0xb1, 0x28, 0x18, 0x98, 0xed, 0x7a, 0x79, 0x2c, 0x88, 0x0b, 0x76, 0x01, 0xa4, 0x30, 0x87, 0xc8, 0x8d, 0xe2, 0x23, 0xc2, 0x1f, - /* (2^ 36)P */ 0x0e, 0xba, 0x0f, 0xfc, 0x91, 0x4e, 0x60, 0x48, 0xa4, 0x6f, 0x2c, 0x05, 0x8f, 0xf7, 0x37, 0xb6, 0x9c, 0x23, 0xe9, 0x09, 0x3d, 0xac, 0xcc, 0x91, 0x7c, 0x68, 0x7a, 0x43, 0xd4, 0xee, 0xf7, 0x23, - /* (2^ 37)P */ 0x00, 0xd8, 0x9b, 0x8d, 0x11, 0xb1, 0x73, 0x51, 0xa7, 0xd4, 0x89, 0x31, 0xb6, 0x41, 0xd6, 0x29, 0x86, 0xc5, 0xbb, 0x88, 0x79, 0x17, 0xbf, 0xfd, 0xf5, 0x1d, 0xd8, 0xca, 0x4f, 0x89, 0x59, 0x29, - /* (2^ 38)P */ 0x99, 0xc8, 0xbb, 0xb4, 0xf3, 0x8e, 0xbc, 0xae, 0xb9, 0x92, 0x69, 0xb2, 0x5a, 0x99, 0x48, 0x41, 0xfb, 0x2c, 0xf9, 0x34, 0x01, 0x0b, 0xe2, 0x24, 0xe8, 0xde, 0x05, 0x4a, 0x89, 0x58, 0xd1, 0x40, - /* (2^ 39)P */ 0xf6, 0x76, 0xaf, 0x85, 0x11, 0x0b, 0xb0, 0x46, 0x79, 0x7a, 0x18, 0x73, 0x78, 0xc7, 0xba, 0x26, 0x5f, 0xff, 0x8f, 0xab, 0x95, 0xbf, 0xc0, 0x3d, 0xd7, 0x24, 0x55, 0x94, 0xd8, 0x8b, 0x60, 0x2a, - /* (2^ 40)P */ 0x02, 0x63, 0x44, 0xbd, 0x88, 0x95, 0x44, 0x26, 0x9c, 0x43, 0x88, 0x03, 0x1c, 0xc2, 0x4b, 0x7c, 0xb2, 0x11, 0xbd, 0x83, 0xf3, 0xa4, 0x98, 0x8e, 0xb9, 0x76, 0xd8, 0xc9, 0x7b, 0x8d, 0x21, 0x26, - /* (2^ 41)P */ 0x8a, 0x17, 0x7c, 0x99, 0x42, 0x15, 0x08, 0xe3, 0x6f, 0x60, 0xb6, 0x6f, 0xa8, 0x29, 0x2d, 0x3c, 0x74, 0x93, 0x27, 0xfa, 0x36, 0x77, 0x21, 0x5c, 0xfa, 0xb1, 0xfe, 0x4a, 0x73, 0x05, 0xde, 0x7d, - /* (2^ 42)P */ 0xab, 0x2b, 0xd4, 0x06, 0x39, 0x0e, 0xf1, 0x3b, 0x9c, 0x64, 0x80, 0x19, 0x3e, 0x80, 0xf7, 0xe4, 0x7a, 0xbf, 0x95, 0x95, 0xf8, 0x3b, 0x05, 0xe6, 0x30, 0x55, 0x24, 0xda, 0x38, 0xaf, 0x4f, 0x39, - /* (2^ 43)P */ 0xf4, 0x28, 0x69, 0x89, 0x58, 0xfb, 0x8e, 0x7a, 0x3c, 0x11, 0x6a, 0xcc, 0xe9, 0x78, 0xc7, 0xfb, 0x6f, 0x59, 0xaf, 0x30, 0xe3, 0x0c, 0x67, 0x72, 0xf7, 0x6c, 0x3d, 0x1d, 0xa8, 0x22, 0xf2, 0x48, - /* (2^ 44)P */ 0xa7, 0xca, 0x72, 0x0d, 0x41, 0xce, 0x1f, 0xf0, 0x95, 0x55, 0x3b, 0x21, 0xc7, 0xec, 0x20, 0x5a, 0x83, 0x14, 0xfa, 0xc1, 0x65, 0x11, 0xc2, 0x7b, 0x41, 0xa7, 0xa8, 0x1d, 0xe3, 0x9a, 0xf8, 0x07, - /* (2^ 45)P */ 0xf9, 0x0f, 0x83, 0xc6, 0xb4, 0xc2, 0xd2, 0x05, 0x93, 0x62, 0x31, 0xc6, 0x0f, 0x33, 0x3e, 0xd4, 0x04, 0xa9, 0xd3, 0x96, 0x0a, 0x59, 0xa5, 0xa5, 0xb6, 0x33, 0x53, 0xa6, 0x91, 0xdb, 0x5e, 0x70, - /* (2^ 46)P */ 0xf7, 0xa5, 0xb9, 0x0b, 0x5e, 0xe1, 0x8e, 0x04, 0x5d, 0xaf, 0x0a, 0x9e, 0xca, 0xcf, 0x40, 0x32, 0x0b, 0xa4, 0xc4, 0xed, 0xce, 0x71, 0x4b, 0x8f, 0x6d, 0x4a, 0x54, 0xde, 0xa3, 0x0d, 0x1c, 0x62, - /* (2^ 47)P */ 0x91, 0x40, 0x8c, 0xa0, 0x36, 0x28, 0x87, 0x92, 0x45, 0x14, 0xc9, 0x10, 0xb0, 0x75, 0x83, 0xce, 0x94, 0x63, 0x27, 0x4f, 0x52, 0xeb, 0x72, 0x8a, 0x35, 0x36, 0xc8, 0x7e, 0xfa, 0xfc, 0x67, 0x26, - /* (2^ 48)P */ 0x2a, 0x75, 0xe8, 0x45, 0x33, 0x17, 0x4c, 0x7f, 0xa5, 0x79, 0x70, 0xee, 0xfe, 0x47, 0x1b, 0x06, 0x34, 0xff, 0x86, 0x9f, 0xfa, 0x9a, 0xdd, 0x25, 0x9c, 0xc8, 0x5d, 0x42, 0xf5, 0xce, 0x80, 0x37, - /* (2^ 49)P */ 0xe9, 0xb4, 0x3b, 0x51, 0x5a, 0x03, 0x46, 0x1a, 0xda, 0x5a, 0x57, 0xac, 0x79, 0xf3, 0x1e, 0x3e, 0x50, 0x4b, 0xa2, 0x5f, 0x1c, 0x5f, 0x8c, 0xc7, 0x22, 0x9f, 0xfd, 0x34, 0x76, 0x96, 0x1a, 0x32, - /* (2^ 50)P */ 0xfa, 0x27, 0x6e, 0x82, 0xb8, 0x07, 0x67, 0x94, 0xd0, 0x6f, 0x50, 0x4c, 0xd6, 0x84, 0xca, 0x3d, 0x36, 0x14, 0xe9, 0x75, 0x80, 0x21, 0x89, 0xc1, 0x84, 0x84, 0x3b, 0x9b, 0x16, 0x84, 0x92, 0x6d, - /* (2^ 51)P */ 0xdf, 0x2d, 0x3f, 0x38, 0x40, 0xe8, 0x67, 0x3a, 0x75, 0x9b, 0x4f, 0x0c, 0xa3, 0xc9, 0xee, 0x33, 0x47, 0xef, 0x83, 0xa7, 0x6f, 0xc8, 0xc7, 0x3e, 0xc4, 0xfb, 0xc9, 0xba, 0x9f, 0x44, 0xec, 0x26, - /* (2^ 52)P */ 0x7d, 0x9e, 0x9b, 0xa0, 0xcb, 0x38, 0x0f, 0x5c, 0x8c, 0x47, 0xa3, 0x62, 0xc7, 0x8c, 0x16, 0x81, 0x1c, 0x12, 0xfc, 0x06, 0xd3, 0xb0, 0x23, 0x3e, 0xdd, 0xdc, 0xef, 0xa5, 0xa0, 0x8a, 0x23, 0x5a, - /* (2^ 53)P */ 0xff, 0x43, 0xea, 0xc4, 0x21, 0x61, 0xa2, 0x1b, 0xb5, 0x32, 0x88, 0x7c, 0x7f, 0xc7, 0xf8, 0x36, 0x9a, 0xf9, 0xdc, 0x0a, 0x0b, 0xea, 0xfb, 0x88, 0xf9, 0xeb, 0x5b, 0xc2, 0x8e, 0x93, 0xa9, 0x5c, - /* (2^ 54)P */ 0xa0, 0xcd, 0xfc, 0x51, 0x5e, 0x6a, 0x43, 0xd5, 0x3b, 0x89, 0xcd, 0xc2, 0x97, 0x47, 0xbc, 0x1d, 0x08, 0x4a, 0x22, 0xd3, 0x65, 0x6a, 0x34, 0x19, 0x66, 0xf4, 0x9a, 0x9b, 0xe4, 0x34, 0x50, 0x0f, - /* (2^ 55)P */ 0x6e, 0xb9, 0xe0, 0xa1, 0x67, 0x39, 0x3c, 0xf2, 0x88, 0x4d, 0x7a, 0x86, 0xfa, 0x08, 0x8b, 0xe5, 0x79, 0x16, 0x34, 0xa7, 0xc6, 0xab, 0x2f, 0xfb, 0x46, 0x69, 0x02, 0xb6, 0x1e, 0x38, 0x75, 0x2a, - /* (2^ 56)P */ 0xac, 0x20, 0x94, 0xc1, 0xe4, 0x3b, 0x0a, 0xc8, 0xdc, 0xb6, 0xf2, 0x81, 0xc6, 0xf6, 0xb1, 0x66, 0x88, 0x33, 0xe9, 0x61, 0x67, 0x03, 0xf7, 0x7c, 0xc4, 0xa4, 0x60, 0xa6, 0xd8, 0xbb, 0xab, 0x25, - /* (2^ 57)P */ 0x98, 0x51, 0xfd, 0x14, 0xba, 0x12, 0xea, 0x91, 0xa9, 0xff, 0x3c, 0x4a, 0xfc, 0x50, 0x49, 0x68, 0x28, 0xad, 0xf5, 0x30, 0x21, 0x84, 0x26, 0xf8, 0x41, 0xa4, 0x01, 0x53, 0xf7, 0x88, 0xa9, 0x3e, - /* (2^ 58)P */ 0x6f, 0x8c, 0x5f, 0x69, 0x9a, 0x10, 0x78, 0xc9, 0xf3, 0xc3, 0x30, 0x05, 0x4a, 0xeb, 0x46, 0x17, 0x95, 0x99, 0x45, 0xb4, 0x77, 0x6d, 0x4d, 0x44, 0xc7, 0x5c, 0x4e, 0x05, 0x8c, 0x2b, 0x95, 0x75, - /* (2^ 59)P */ 0xaa, 0xd6, 0xf4, 0x15, 0x79, 0x3f, 0x70, 0xa3, 0xd8, 0x47, 0x26, 0x2f, 0x20, 0x46, 0xc3, 0x66, 0x4b, 0x64, 0x1d, 0x81, 0xdf, 0x69, 0x14, 0xd0, 0x1f, 0xd7, 0xa5, 0x81, 0x7d, 0xa4, 0xfe, 0x77, - /* (2^ 60)P */ 0x81, 0xa3, 0x7c, 0xf5, 0x9e, 0x52, 0xe9, 0xc5, 0x1a, 0x88, 0x2f, 0xce, 0xb9, 0xb4, 0xee, 0x6e, 0xd6, 0x9b, 0x00, 0xe8, 0x28, 0x1a, 0xe9, 0xb6, 0xec, 0x3f, 0xfc, 0x9a, 0x3e, 0xbe, 0x80, 0x4b, - /* (2^ 61)P */ 0xc5, 0xd2, 0xae, 0x26, 0xc5, 0x73, 0x37, 0x7e, 0x9d, 0xa4, 0xc9, 0x53, 0xb4, 0xfc, 0x4a, 0x1b, 0x4d, 0xb2, 0xff, 0xba, 0xd7, 0xbd, 0x20, 0xa9, 0x0e, 0x40, 0x2d, 0x12, 0x9f, 0x69, 0x54, 0x7c, - /* (2^ 62)P */ 0xc8, 0x4b, 0xa9, 0x4f, 0xe1, 0xc8, 0x46, 0xef, 0x5e, 0xed, 0x52, 0x29, 0xce, 0x74, 0xb0, 0xe0, 0xd5, 0x85, 0xd8, 0xdb, 0xe1, 0x50, 0xa4, 0xbe, 0x2c, 0x71, 0x0f, 0x32, 0x49, 0x86, 0xb6, 0x61, - /* (2^ 63)P */ 0xd1, 0xbd, 0xcc, 0x09, 0x73, 0x5f, 0x48, 0x8a, 0x2d, 0x1a, 0x4d, 0x7d, 0x0d, 0x32, 0x06, 0xbd, 0xf4, 0xbe, 0x2d, 0x32, 0x73, 0x29, 0x23, 0x25, 0x70, 0xf7, 0x17, 0x8c, 0x75, 0xc4, 0x5d, 0x44, - /* (2^ 64)P */ 0x3c, 0x93, 0xc8, 0x7c, 0x17, 0x34, 0x04, 0xdb, 0x9f, 0x05, 0xea, 0x75, 0x21, 0xe8, 0x6f, 0xed, 0x34, 0xdb, 0x53, 0xc0, 0xfd, 0xbe, 0xfe, 0x1e, 0x99, 0xaf, 0x5d, 0xc6, 0x67, 0xe8, 0xdb, 0x4a, - /* (2^ 65)P */ 0xdf, 0x09, 0x06, 0xa9, 0xa2, 0x71, 0xcd, 0x3a, 0x50, 0x40, 0xd0, 0x6d, 0x85, 0x91, 0xe9, 0xe5, 0x3c, 0xc2, 0x57, 0x81, 0x68, 0x9b, 0xc6, 0x1e, 0x4d, 0xfe, 0x5c, 0x88, 0xf6, 0x27, 0x74, 0x69, - /* (2^ 66)P */ 0x51, 0xa8, 0xe1, 0x65, 0x9b, 0x7b, 0xbe, 0xd7, 0xdd, 0x36, 0xc5, 0x22, 0xd5, 0x28, 0x3d, 0xa0, 0x45, 0xb6, 0xd2, 0x8f, 0x65, 0x9d, 0x39, 0x28, 0xe1, 0x41, 0x26, 0x7c, 0xe1, 0xb7, 0xe5, 0x49, - /* (2^ 67)P */ 0xa4, 0x57, 0x04, 0x70, 0x98, 0x3a, 0x8c, 0x6f, 0x78, 0x67, 0xbb, 0x5e, 0xa2, 0xf0, 0x78, 0x50, 0x0f, 0x96, 0x82, 0xc3, 0xcb, 0x3c, 0x3c, 0xd1, 0xb1, 0x84, 0xdf, 0xa7, 0x58, 0x32, 0x00, 0x2e, - /* (2^ 68)P */ 0x1c, 0x6a, 0x29, 0xe6, 0x9b, 0xf3, 0xd1, 0x8a, 0xb2, 0xbf, 0x5f, 0x2a, 0x65, 0xaa, 0xee, 0xc1, 0xcb, 0xf3, 0x26, 0xfd, 0x73, 0x06, 0xee, 0x33, 0xcc, 0x2c, 0x9d, 0xa6, 0x73, 0x61, 0x25, 0x59, - /* (2^ 69)P */ 0x41, 0xfc, 0x18, 0x4e, 0xaa, 0x07, 0xea, 0x41, 0x1e, 0xa5, 0x87, 0x7c, 0x52, 0x19, 0xfc, 0xd9, 0x6f, 0xca, 0x31, 0x58, 0x80, 0xcb, 0xaa, 0xbd, 0x4f, 0x69, 0x16, 0xc9, 0x2d, 0x65, 0x5b, 0x44, - /* (2^ 70)P */ 0x15, 0x23, 0x17, 0xf2, 0xa7, 0xa3, 0x92, 0xce, 0x64, 0x99, 0x1b, 0xe1, 0x2d, 0x28, 0xdc, 0x1e, 0x4a, 0x31, 0x4c, 0xe0, 0xaf, 0x3a, 0x82, 0xa1, 0x86, 0xf5, 0x7c, 0x43, 0x94, 0x2d, 0x0a, 0x79, - /* (2^ 71)P */ 0x09, 0xe0, 0xf6, 0x93, 0xfb, 0x47, 0xc4, 0x71, 0x76, 0x52, 0x84, 0x22, 0x67, 0xa5, 0x22, 0x89, 0x69, 0x51, 0x4f, 0x20, 0x3b, 0x90, 0x70, 0xbf, 0xfe, 0x19, 0xa3, 0x1b, 0x89, 0x89, 0x7a, 0x2f, - /* (2^ 72)P */ 0x0c, 0x14, 0xe2, 0x77, 0xb5, 0x8e, 0xa0, 0x02, 0xf4, 0xdc, 0x7b, 0x42, 0xd4, 0x4e, 0x9a, 0xed, 0xd1, 0x3c, 0x32, 0xe4, 0x44, 0xec, 0x53, 0x52, 0x5b, 0x35, 0xe9, 0x14, 0x3c, 0x36, 0x88, 0x3e, - /* (2^ 73)P */ 0x8c, 0x0b, 0x11, 0x77, 0x42, 0xc1, 0x66, 0xaa, 0x90, 0x33, 0xa2, 0x10, 0x16, 0x39, 0xe0, 0x1a, 0xa2, 0xc2, 0x3f, 0xc9, 0x12, 0xbd, 0x30, 0x20, 0xab, 0xc7, 0x55, 0x95, 0x57, 0x41, 0xe1, 0x3e, - /* (2^ 74)P */ 0x41, 0x7d, 0x6e, 0x6d, 0x3a, 0xde, 0x14, 0x92, 0xfe, 0x7e, 0xf1, 0x07, 0x86, 0xd8, 0xcd, 0x3c, 0x17, 0x12, 0xe1, 0xf8, 0x88, 0x12, 0x4f, 0x67, 0xd0, 0x93, 0x9f, 0x32, 0x0f, 0x25, 0x82, 0x56, - /* (2^ 75)P */ 0x6e, 0x39, 0x2e, 0x6d, 0x13, 0x0b, 0xf0, 0x6c, 0xbf, 0xde, 0x14, 0x10, 0x6f, 0xf8, 0x4c, 0x6e, 0x83, 0x4e, 0xcc, 0xbf, 0xb5, 0xb1, 0x30, 0x59, 0xb6, 0x16, 0xba, 0x8a, 0xb4, 0x69, 0x70, 0x04, - /* (2^ 76)P */ 0x93, 0x07, 0xb2, 0x69, 0xab, 0xe4, 0x4c, 0x0d, 0x9e, 0xfb, 0xd0, 0x97, 0x1a, 0xb9, 0x4d, 0xb2, 0x1d, 0xd0, 0x00, 0x4e, 0xf5, 0x50, 0xfa, 0xcd, 0xb5, 0xdd, 0x8b, 0x36, 0x85, 0x10, 0x1b, 0x22, - /* (2^ 77)P */ 0xd2, 0xd8, 0xe3, 0xb1, 0x68, 0x94, 0xe5, 0xe7, 0x93, 0x2f, 0x12, 0xbd, 0x63, 0x65, 0xc5, 0x53, 0x09, 0x3f, 0x66, 0xe0, 0x03, 0xa9, 0xe8, 0xee, 0x42, 0x3d, 0xbe, 0xcb, 0x62, 0xa6, 0xef, 0x61, - /* (2^ 78)P */ 0x2a, 0xab, 0x6e, 0xde, 0xdd, 0xdd, 0xf8, 0x2c, 0x31, 0xf2, 0x35, 0x14, 0xd5, 0x0a, 0xf8, 0x9b, 0x73, 0x49, 0xf0, 0xc9, 0xce, 0xda, 0xea, 0x5d, 0x27, 0x9b, 0xd2, 0x41, 0x5d, 0x5b, 0x27, 0x29, - /* (2^ 79)P */ 0x4f, 0xf1, 0xeb, 0x95, 0x08, 0x0f, 0xde, 0xcf, 0xa7, 0x05, 0x49, 0x05, 0x6b, 0xb9, 0xaa, 0xb9, 0xfd, 0x20, 0xc4, 0xa1, 0xd9, 0x0d, 0xe8, 0xca, 0xc7, 0xbb, 0x73, 0x16, 0x2f, 0xbf, 0x63, 0x0a, - /* (2^ 80)P */ 0x8c, 0xbc, 0x8f, 0x95, 0x11, 0x6e, 0x2f, 0x09, 0xad, 0x2f, 0x82, 0x04, 0xe8, 0x81, 0x2a, 0x67, 0x17, 0x25, 0xd5, 0x60, 0x15, 0x35, 0xc8, 0xca, 0xf8, 0x92, 0xf1, 0xc8, 0x22, 0x77, 0x3f, 0x6f, - /* (2^ 81)P */ 0xb7, 0x94, 0xe8, 0xc2, 0xcc, 0x90, 0xba, 0xf8, 0x0d, 0x9f, 0xff, 0x38, 0xa4, 0x57, 0x75, 0x2c, 0x59, 0x23, 0xe5, 0x5a, 0x85, 0x1d, 0x4d, 0x89, 0x69, 0x3d, 0x74, 0x7b, 0x15, 0x22, 0xe1, 0x68, - /* (2^ 82)P */ 0xf3, 0x19, 0xb9, 0xcf, 0x70, 0x55, 0x7e, 0xd8, 0xb9, 0x8d, 0x79, 0x95, 0xcd, 0xde, 0x2c, 0x3f, 0xce, 0xa2, 0xc0, 0x10, 0x47, 0x15, 0x21, 0x21, 0xb2, 0xc5, 0x6d, 0x24, 0x15, 0xa1, 0x66, 0x3c, - /* (2^ 83)P */ 0x72, 0xcb, 0x4e, 0x29, 0x62, 0xc5, 0xed, 0xcb, 0x16, 0x0b, 0x28, 0x6a, 0xc3, 0x43, 0x71, 0xba, 0x67, 0x8b, 0x07, 0xd4, 0xef, 0xc2, 0x10, 0x96, 0x1e, 0x4b, 0x6a, 0x94, 0x5d, 0x73, 0x44, 0x61, - /* (2^ 84)P */ 0x50, 0x33, 0x5b, 0xd7, 0x1e, 0x11, 0x6f, 0x53, 0x1b, 0xd8, 0x41, 0x20, 0x8c, 0xdb, 0x11, 0x02, 0x3c, 0x41, 0x10, 0x0e, 0x00, 0xb1, 0x3c, 0xf9, 0x76, 0x88, 0x9e, 0x03, 0x3c, 0xfd, 0x9d, 0x14, - /* (2^ 85)P */ 0x5b, 0x15, 0x63, 0x6b, 0xe4, 0xdd, 0x79, 0xd4, 0x76, 0x79, 0x83, 0x3c, 0xe9, 0x15, 0x6e, 0xb6, 0x38, 0xe0, 0x13, 0x1f, 0x3b, 0xe4, 0xfd, 0xda, 0x35, 0x0b, 0x4b, 0x2e, 0x1a, 0xda, 0xaf, 0x5f, - /* (2^ 86)P */ 0x81, 0x75, 0x19, 0x17, 0xdf, 0xbb, 0x00, 0x36, 0xc2, 0xd2, 0x3c, 0xbe, 0x0b, 0x05, 0x72, 0x39, 0x86, 0xbe, 0xd5, 0xbd, 0x6d, 0x90, 0x38, 0x59, 0x0f, 0x86, 0x9b, 0x3f, 0xe4, 0xe5, 0xfc, 0x34, - /* (2^ 87)P */ 0x02, 0x4d, 0xd1, 0x42, 0xcd, 0xa4, 0xa8, 0x75, 0x65, 0xdf, 0x41, 0x34, 0xc5, 0xab, 0x8d, 0x82, 0xd3, 0x31, 0xe1, 0xd2, 0xed, 0xab, 0xdc, 0x33, 0x5f, 0xd2, 0x14, 0xb8, 0x6f, 0xd7, 0xba, 0x3e, - /* (2^ 88)P */ 0x0f, 0xe1, 0x70, 0x6f, 0x56, 0x6f, 0x90, 0xd4, 0x5a, 0x0f, 0x69, 0x51, 0xaa, 0xf7, 0x12, 0x5d, 0xf2, 0xfc, 0xce, 0x76, 0x6e, 0xb1, 0xad, 0x45, 0x99, 0x29, 0x23, 0xad, 0xae, 0x68, 0xf7, 0x01, - /* (2^ 89)P */ 0xbd, 0xfe, 0x48, 0x62, 0x7b, 0xc7, 0x6c, 0x2b, 0xfd, 0xaf, 0x3a, 0xec, 0x28, 0x06, 0xd3, 0x3c, 0x6a, 0x48, 0xef, 0xd4, 0x80, 0x0b, 0x1c, 0xce, 0x23, 0x6c, 0xf6, 0xa6, 0x2e, 0xff, 0x3b, 0x4c, - /* (2^ 90)P */ 0x5f, 0xeb, 0xea, 0x4a, 0x09, 0xc4, 0x2e, 0x3f, 0xa7, 0x2c, 0x37, 0x6e, 0x28, 0x9b, 0xb1, 0x61, 0x1d, 0x70, 0x2a, 0xde, 0x66, 0xa9, 0xef, 0x5e, 0xef, 0xe3, 0x55, 0xde, 0x65, 0x05, 0xb2, 0x23, - /* (2^ 91)P */ 0x57, 0x85, 0xd5, 0x79, 0x52, 0xca, 0x01, 0xe3, 0x4f, 0x87, 0xc2, 0x27, 0xce, 0xd4, 0xb2, 0x07, 0x67, 0x1d, 0xcf, 0x9d, 0x8a, 0xcd, 0x32, 0xa5, 0x56, 0xff, 0x2b, 0x3f, 0xe2, 0xfe, 0x52, 0x2a, - /* (2^ 92)P */ 0x3d, 0x66, 0xd8, 0x7c, 0xb3, 0xef, 0x24, 0x86, 0x94, 0x75, 0xbd, 0xff, 0x20, 0xac, 0xc7, 0xbb, 0x45, 0x74, 0xd3, 0x82, 0x9c, 0x5e, 0xb8, 0x57, 0x66, 0xec, 0xa6, 0x86, 0xcb, 0x52, 0x30, 0x7b, - /* (2^ 93)P */ 0x1e, 0xe9, 0x25, 0x25, 0xad, 0xf0, 0x82, 0x34, 0xa0, 0xdc, 0x8e, 0xd2, 0x43, 0x80, 0xb6, 0x2c, 0x3a, 0x00, 0x1b, 0x2e, 0x05, 0x6d, 0x4f, 0xaf, 0x0a, 0x1b, 0x78, 0x29, 0x25, 0x8c, 0x5f, 0x18, - /* (2^ 94)P */ 0xd6, 0xe0, 0x0c, 0xd8, 0x5b, 0xde, 0x41, 0xaa, 0xd6, 0xe9, 0x53, 0x68, 0x41, 0xb2, 0x07, 0x94, 0x3a, 0x4c, 0x7f, 0x35, 0x6e, 0xc3, 0x3e, 0x56, 0xce, 0x7b, 0x29, 0x0e, 0xdd, 0xb8, 0xc4, 0x4c, - /* (2^ 95)P */ 0x0e, 0x73, 0xb8, 0xff, 0x52, 0x1a, 0xfc, 0xa2, 0x37, 0x8e, 0x05, 0x67, 0x6e, 0xf1, 0x11, 0x18, 0xe1, 0x4e, 0xdf, 0xcd, 0x66, 0xa3, 0xf9, 0x10, 0x99, 0xf0, 0xb9, 0xa0, 0xc4, 0xa0, 0xf4, 0x72, - /* (2^ 96)P */ 0xa7, 0x4e, 0x3f, 0x66, 0x6f, 0xc0, 0x16, 0x8c, 0xba, 0x0f, 0x97, 0x4e, 0xf7, 0x3a, 0x3b, 0x69, 0x45, 0xc3, 0x9e, 0xd6, 0xf1, 0xe7, 0x02, 0x21, 0x89, 0x80, 0x8a, 0x96, 0xbc, 0x3c, 0xa5, 0x0b, - /* (2^ 97)P */ 0x37, 0x55, 0xa1, 0xfe, 0xc7, 0x9d, 0x3d, 0xca, 0x93, 0x64, 0x53, 0x51, 0xbb, 0x24, 0x68, 0x4c, 0xb1, 0x06, 0x40, 0x84, 0x14, 0x63, 0x88, 0xb9, 0x60, 0xcc, 0x54, 0xb4, 0x2a, 0xa7, 0xd2, 0x40, - /* (2^ 98)P */ 0x75, 0x09, 0x57, 0x12, 0xb7, 0xa1, 0x36, 0x59, 0x57, 0xa6, 0xbd, 0xde, 0x48, 0xd6, 0xb9, 0x91, 0xea, 0x30, 0x43, 0xb6, 0x4b, 0x09, 0x44, 0x33, 0xd0, 0x51, 0xee, 0x12, 0x0d, 0xa1, 0x6b, 0x00, - /* (2^ 99)P */ 0x58, 0x5d, 0xde, 0xf5, 0x68, 0x84, 0x22, 0x19, 0xb0, 0x05, 0xcc, 0x38, 0x4c, 0x2f, 0xb1, 0x0e, 0x90, 0x19, 0x60, 0xd5, 0x9d, 0x9f, 0x03, 0xa1, 0x0b, 0x0e, 0xff, 0x4f, 0xce, 0xd4, 0x02, 0x45, - /* (2^100)P */ 0x89, 0xc1, 0x37, 0x68, 0x10, 0x54, 0x20, 0xeb, 0x3c, 0xb9, 0xd3, 0x6d, 0x4c, 0x54, 0xf6, 0xd0, 0x4f, 0xd7, 0x16, 0xc4, 0x64, 0x70, 0x72, 0x40, 0xf0, 0x2e, 0x50, 0x4b, 0x11, 0xc6, 0x15, 0x6e, - /* (2^101)P */ 0x6b, 0xa7, 0xb1, 0xcf, 0x98, 0xa3, 0xf2, 0x4d, 0xb1, 0xf6, 0xf2, 0x19, 0x74, 0x6c, 0x25, 0x11, 0x43, 0x60, 0x6e, 0x06, 0x62, 0x79, 0x49, 0x4a, 0x44, 0x5b, 0x35, 0x41, 0xab, 0x3a, 0x5b, 0x70, - /* (2^102)P */ 0xd8, 0xb1, 0x97, 0xd7, 0x36, 0xf5, 0x5e, 0x36, 0xdb, 0xf0, 0xdd, 0x22, 0xd6, 0x6b, 0x07, 0x00, 0x88, 0x5a, 0x57, 0xe0, 0xb0, 0x33, 0xbf, 0x3b, 0x4d, 0xca, 0xe4, 0xc8, 0x05, 0xaa, 0x77, 0x37, - /* (2^103)P */ 0x5f, 0xdb, 0x78, 0x55, 0xc8, 0x45, 0x27, 0x39, 0xe2, 0x5a, 0xae, 0xdb, 0x49, 0x41, 0xda, 0x6f, 0x67, 0x98, 0xdc, 0x8a, 0x0b, 0xb0, 0xf0, 0xb1, 0xa3, 0x1d, 0x6f, 0xd3, 0x37, 0x34, 0x96, 0x09, - /* (2^104)P */ 0x53, 0x38, 0xdc, 0xa5, 0x90, 0x4e, 0x82, 0x7e, 0xbd, 0x5c, 0x13, 0x1f, 0x64, 0xf6, 0xb5, 0xcc, 0xcc, 0x8f, 0xce, 0x87, 0x6c, 0xd8, 0x36, 0x67, 0x9f, 0x24, 0x04, 0x66, 0xe2, 0x3c, 0x5f, 0x62, - /* (2^105)P */ 0x3f, 0xf6, 0x02, 0x95, 0x05, 0xc8, 0x8a, 0xaf, 0x69, 0x14, 0x35, 0x2e, 0x0a, 0xe7, 0x05, 0x0c, 0x05, 0x63, 0x4b, 0x76, 0x9c, 0x2e, 0x29, 0x35, 0xc3, 0x3a, 0xe2, 0xc7, 0x60, 0x43, 0x39, 0x1a, - /* (2^106)P */ 0x64, 0x32, 0x18, 0x51, 0x32, 0xd5, 0xc6, 0xd5, 0x4f, 0xb7, 0xc2, 0x43, 0xbd, 0x5a, 0x06, 0x62, 0x9b, 0x3f, 0x97, 0x3b, 0xd0, 0xf5, 0xfb, 0xb5, 0x5e, 0x6e, 0x20, 0x61, 0x36, 0xda, 0xa3, 0x13, - /* (2^107)P */ 0xe5, 0x94, 0x5d, 0x72, 0x37, 0x58, 0xbd, 0xc6, 0xc5, 0x16, 0x50, 0x20, 0x12, 0x09, 0xe3, 0x18, 0x68, 0x3c, 0x03, 0x70, 0x15, 0xce, 0x88, 0x20, 0x87, 0x79, 0x83, 0x5c, 0x49, 0x1f, 0xba, 0x7f, - /* (2^108)P */ 0x9d, 0x07, 0xf9, 0xf2, 0x23, 0x74, 0x8c, 0x5a, 0xc5, 0x3f, 0x02, 0x34, 0x7b, 0x15, 0x35, 0x17, 0x51, 0xb3, 0xfa, 0xd2, 0x9a, 0xb4, 0xf9, 0xe4, 0x3c, 0xe3, 0x78, 0xc8, 0x72, 0xff, 0x91, 0x66, - /* (2^109)P */ 0x3e, 0xff, 0x5e, 0xdc, 0xde, 0x2a, 0x2c, 0x12, 0xf4, 0x6c, 0x95, 0xd8, 0xf1, 0x4b, 0xdd, 0xf8, 0xda, 0x5b, 0x9e, 0x9e, 0x5d, 0x20, 0x86, 0xeb, 0x43, 0xc7, 0x75, 0xd9, 0xb9, 0x92, 0x9b, 0x04, - /* (2^110)P */ 0x5a, 0xc0, 0xf6, 0xb0, 0x30, 0x97, 0x37, 0xa5, 0x53, 0xa5, 0xf3, 0xc6, 0xac, 0xff, 0xa0, 0x72, 0x6d, 0xcd, 0x0d, 0xb2, 0x34, 0x2c, 0x03, 0xb0, 0x4a, 0x16, 0xd5, 0x88, 0xbc, 0x9d, 0x0e, 0x47, - /* (2^111)P */ 0x47, 0xc0, 0x37, 0xa2, 0x0c, 0xf1, 0x9c, 0xb1, 0xa2, 0x81, 0x6c, 0x1f, 0x71, 0x66, 0x54, 0xb6, 0x43, 0x0b, 0xd8, 0x6d, 0xd1, 0x1b, 0x32, 0xb3, 0x8e, 0xbe, 0x5f, 0x0c, 0x60, 0x4f, 0xc1, 0x48, - /* (2^112)P */ 0x03, 0xc8, 0xa6, 0x4a, 0x26, 0x1c, 0x45, 0x66, 0xa6, 0x7d, 0xfa, 0xa4, 0x04, 0x39, 0x6e, 0xb6, 0x95, 0x83, 0x12, 0xb3, 0xb0, 0x19, 0x5f, 0xd4, 0x10, 0xbc, 0xc9, 0xc3, 0x27, 0x26, 0x60, 0x31, - /* (2^113)P */ 0x0d, 0xe1, 0xe4, 0x32, 0x48, 0xdc, 0x20, 0x31, 0xf7, 0x17, 0xc7, 0x56, 0x67, 0xc4, 0x20, 0xeb, 0x94, 0x02, 0x28, 0x67, 0x3f, 0x2e, 0xf5, 0x00, 0x09, 0xc5, 0x30, 0x47, 0xc1, 0x4f, 0x6d, 0x56, - /* (2^114)P */ 0x06, 0x72, 0x83, 0xfd, 0x40, 0x5d, 0x3a, 0x7e, 0x7a, 0x54, 0x59, 0x71, 0xdc, 0x26, 0xe9, 0xc1, 0x95, 0x60, 0x8d, 0xa6, 0xfb, 0x30, 0x67, 0x21, 0xa7, 0xce, 0x69, 0x3f, 0x84, 0xc3, 0xe8, 0x22, - /* (2^115)P */ 0x2b, 0x4b, 0x0e, 0x93, 0xe8, 0x74, 0xd0, 0x33, 0x16, 0x58, 0xd1, 0x84, 0x0e, 0x35, 0xe4, 0xb6, 0x65, 0x23, 0xba, 0xd6, 0x6a, 0xc2, 0x34, 0x55, 0xf3, 0xf3, 0xf1, 0x89, 0x2f, 0xc1, 0x73, 0x77, - /* (2^116)P */ 0xaa, 0x62, 0x79, 0xa5, 0x4d, 0x40, 0xba, 0x8c, 0x56, 0xce, 0x99, 0x19, 0xa8, 0x97, 0x98, 0x5b, 0xfc, 0x92, 0x16, 0x12, 0x2f, 0x86, 0x8e, 0x50, 0x91, 0xc2, 0x93, 0xa0, 0x7f, 0x90, 0x81, 0x3a, - /* (2^117)P */ 0x10, 0xa5, 0x25, 0x47, 0xff, 0xd0, 0xde, 0x0d, 0x03, 0xc5, 0x3f, 0x67, 0x10, 0xcc, 0xd8, 0x10, 0x89, 0x4e, 0x1f, 0x9f, 0x1c, 0x15, 0x9d, 0x5b, 0x4c, 0xa4, 0x09, 0xcb, 0xd5, 0xc1, 0xa5, 0x32, - /* (2^118)P */ 0xfb, 0x41, 0x05, 0xb9, 0x42, 0xa4, 0x0a, 0x1e, 0xdb, 0x85, 0xb4, 0xc1, 0x7c, 0xeb, 0x85, 0x5f, 0xe5, 0xf2, 0x9d, 0x8a, 0xce, 0x95, 0xe5, 0xbe, 0x36, 0x22, 0x42, 0x22, 0xc7, 0x96, 0xe4, 0x25, - /* (2^119)P */ 0xb9, 0xe5, 0x0f, 0xcd, 0x46, 0x3c, 0xdf, 0x5e, 0x88, 0x33, 0xa4, 0xd2, 0x7e, 0x5a, 0xe7, 0x34, 0x52, 0xe3, 0x61, 0xd7, 0x11, 0xde, 0x88, 0xe4, 0x5c, 0x54, 0x85, 0xa0, 0x01, 0x8a, 0x87, 0x0e, - /* (2^120)P */ 0x04, 0xbb, 0x21, 0xe0, 0x77, 0x3c, 0x49, 0xba, 0x9a, 0x89, 0xdf, 0xc7, 0x43, 0x18, 0x4d, 0x2b, 0x67, 0x0d, 0xe8, 0x7a, 0x48, 0x7a, 0xa3, 0x9e, 0x94, 0x17, 0xe4, 0x11, 0x80, 0x95, 0xa9, 0x67, - /* (2^121)P */ 0x65, 0xb0, 0x97, 0x66, 0x1a, 0x05, 0x58, 0x4b, 0xd4, 0xa6, 0x6b, 0x8d, 0x7d, 0x3f, 0xe3, 0x47, 0xc1, 0x46, 0xca, 0x83, 0xd4, 0xa8, 0x4d, 0xbb, 0x0d, 0xdb, 0xc2, 0x81, 0xa1, 0xca, 0xbe, 0x68, - /* (2^122)P */ 0xa5, 0x9a, 0x98, 0x0b, 0xe9, 0x80, 0x89, 0x8d, 0x9b, 0xc9, 0x93, 0x2c, 0x4a, 0xb1, 0x5e, 0xf9, 0xa2, 0x73, 0x6e, 0x79, 0xc4, 0xc7, 0xc6, 0x51, 0x69, 0xb5, 0xef, 0xb5, 0x63, 0x83, 0x22, 0x6e, - /* (2^123)P */ 0xc8, 0x24, 0xd6, 0x2d, 0xb0, 0xc0, 0xbb, 0xc6, 0xee, 0x70, 0x81, 0xec, 0x7d, 0xb4, 0x7e, 0x77, 0xa9, 0xaf, 0xcf, 0x04, 0xa0, 0x15, 0xde, 0x3c, 0x9b, 0xbf, 0x60, 0x71, 0x08, 0xbc, 0xc6, 0x1d, - /* (2^124)P */ 0x02, 0x40, 0xc3, 0xee, 0x43, 0xe0, 0x07, 0x2e, 0x7f, 0xdc, 0x68, 0x7a, 0x67, 0xfc, 0xe9, 0x18, 0x9a, 0x5b, 0xd1, 0x8b, 0x18, 0x03, 0xda, 0xd8, 0x53, 0x82, 0x56, 0x00, 0xbb, 0xc3, 0xfb, 0x48, - /* (2^125)P */ 0xe1, 0x4c, 0x65, 0xfb, 0x4c, 0x7d, 0x54, 0x57, 0xad, 0xe2, 0x58, 0xa0, 0x82, 0x5b, 0x56, 0xd3, 0x78, 0x44, 0x15, 0xbf, 0x0b, 0xaf, 0x3e, 0xf6, 0x18, 0xbb, 0xdf, 0x14, 0xf1, 0x1e, 0x53, 0x47, - /* (2^126)P */ 0x87, 0xc5, 0x78, 0x42, 0x0a, 0x63, 0xec, 0xe1, 0xf3, 0x83, 0x8e, 0xca, 0x46, 0xd5, 0x07, 0x55, 0x2b, 0x0c, 0xdc, 0x3a, 0xc6, 0x35, 0xe1, 0x85, 0x4e, 0x84, 0x82, 0x56, 0xa8, 0xef, 0xa7, 0x0a, - /* (2^127)P */ 0x15, 0xf6, 0xe1, 0xb3, 0xa8, 0x1b, 0x69, 0x72, 0xfa, 0x3f, 0xbe, 0x1f, 0x70, 0xe9, 0xb4, 0x32, 0x68, 0x78, 0xbb, 0x39, 0x2e, 0xd9, 0xb6, 0x97, 0xe8, 0x39, 0x2e, 0xa0, 0xde, 0x53, 0xfe, 0x2c, - /* (2^128)P */ 0xb0, 0x52, 0xcd, 0x85, 0xcd, 0x92, 0x73, 0x68, 0x31, 0x98, 0xe2, 0x10, 0xc9, 0x66, 0xff, 0x27, 0x06, 0x2d, 0x83, 0xa9, 0x56, 0x45, 0x13, 0x97, 0xa0, 0xf8, 0x84, 0x0a, 0x36, 0xb0, 0x9b, 0x26, - /* (2^129)P */ 0x5c, 0xf8, 0x43, 0x76, 0x45, 0x55, 0x6e, 0x70, 0x1b, 0x7d, 0x59, 0x9b, 0x8c, 0xa4, 0x34, 0x37, 0x72, 0xa4, 0xef, 0xc6, 0xe8, 0x91, 0xee, 0x7a, 0xe0, 0xd9, 0xa9, 0x98, 0xc1, 0xab, 0xd6, 0x5c, - /* (2^130)P */ 0x1a, 0xe4, 0x3c, 0xcb, 0x06, 0xde, 0x04, 0x0e, 0x38, 0xe1, 0x02, 0x34, 0x89, 0xeb, 0xc6, 0xd8, 0x72, 0x37, 0x6e, 0x68, 0xbb, 0x59, 0x46, 0x90, 0xc8, 0xa8, 0x6b, 0x74, 0x71, 0xc3, 0x15, 0x72, - /* (2^131)P */ 0xd9, 0xa2, 0xe4, 0xea, 0x7e, 0xa9, 0x12, 0xfd, 0xc5, 0xf2, 0x94, 0x63, 0x51, 0xb7, 0x14, 0x95, 0x94, 0xf2, 0x08, 0x92, 0x80, 0xd5, 0x6f, 0x26, 0xb9, 0x26, 0x9a, 0x61, 0x85, 0x70, 0x84, 0x5c, - /* (2^132)P */ 0xea, 0x94, 0xd6, 0xfe, 0x10, 0x54, 0x98, 0x52, 0x54, 0xd2, 0x2e, 0x4a, 0x93, 0x5b, 0x90, 0x3c, 0x67, 0xe4, 0x3b, 0x2d, 0x69, 0x47, 0xbb, 0x10, 0xe1, 0xe9, 0xe5, 0x69, 0x2d, 0x3d, 0x3b, 0x06, - /* (2^133)P */ 0xeb, 0x7d, 0xa5, 0xdd, 0xee, 0x26, 0x27, 0x47, 0x91, 0x18, 0xf4, 0x10, 0xae, 0xc4, 0xb6, 0xef, 0x14, 0x76, 0x30, 0x7b, 0x91, 0x41, 0x16, 0x2b, 0x7c, 0x5b, 0xf4, 0xc4, 0x4f, 0x55, 0x7c, 0x11, - /* (2^134)P */ 0x12, 0x88, 0x9d, 0x8f, 0x11, 0xf3, 0x7c, 0xc0, 0x39, 0x79, 0x01, 0x50, 0x20, 0xd8, 0xdb, 0x01, 0x27, 0x28, 0x1b, 0x17, 0xf4, 0x03, 0xe8, 0xd7, 0xea, 0x25, 0xd2, 0x87, 0x74, 0xe8, 0x15, 0x10, - /* (2^135)P */ 0x4d, 0xcc, 0x3a, 0xd2, 0xfe, 0xe3, 0x8d, 0xc5, 0x2d, 0xbe, 0xa7, 0x94, 0xc2, 0x91, 0xdb, 0x50, 0x57, 0xf4, 0x9c, 0x1c, 0x3d, 0xd4, 0x94, 0x0b, 0x4a, 0x52, 0x37, 0x6e, 0xfa, 0x40, 0x16, 0x6b, - /* (2^136)P */ 0x09, 0x0d, 0xda, 0x5f, 0x6c, 0x34, 0x2f, 0x69, 0x51, 0x31, 0x4d, 0xfa, 0x59, 0x1c, 0x0b, 0x20, 0x96, 0xa2, 0x77, 0x07, 0x76, 0x6f, 0xc4, 0xb8, 0xcf, 0xfb, 0xfd, 0x3f, 0x5f, 0x39, 0x38, 0x4b, - /* (2^137)P */ 0x71, 0xd6, 0x54, 0xbe, 0x00, 0x5e, 0xd2, 0x18, 0xa6, 0xab, 0xc8, 0xbe, 0x82, 0x05, 0xd5, 0x60, 0x82, 0xb9, 0x78, 0x3b, 0x26, 0x8f, 0xad, 0x87, 0x32, 0x04, 0xda, 0x9c, 0x4e, 0xf6, 0xfd, 0x50, - /* (2^138)P */ 0xf0, 0xdc, 0x78, 0xc5, 0xaa, 0x67, 0xf5, 0x90, 0x3b, 0x13, 0xa3, 0xf2, 0x0e, 0x9b, 0x1e, 0xef, 0x71, 0xde, 0xd9, 0x42, 0x92, 0xba, 0xeb, 0x0e, 0xc7, 0x01, 0x31, 0xf0, 0x9b, 0x3c, 0x47, 0x15, - /* (2^139)P */ 0x95, 0x80, 0xb7, 0x56, 0xae, 0xe8, 0x77, 0x7c, 0x8e, 0x07, 0x6f, 0x6e, 0x66, 0xe7, 0x78, 0xb6, 0x1f, 0xba, 0x48, 0x53, 0x61, 0xb9, 0xa0, 0x2d, 0x0b, 0x3f, 0x73, 0xff, 0xc1, 0x31, 0xf9, 0x7c, - /* (2^140)P */ 0x6c, 0x36, 0x0a, 0x0a, 0xf5, 0x57, 0xb3, 0x26, 0x32, 0xd7, 0x87, 0x2b, 0xf4, 0x8c, 0x70, 0xe9, 0xc0, 0xb2, 0x1c, 0xf9, 0xa5, 0xee, 0x3a, 0xc1, 0x4c, 0xbb, 0x43, 0x11, 0x99, 0x0c, 0xd9, 0x35, - /* (2^141)P */ 0xdc, 0xd9, 0xa0, 0xa9, 0x04, 0xc4, 0xc1, 0x47, 0x51, 0xd2, 0x72, 0x19, 0x45, 0x58, 0x9e, 0x65, 0x31, 0x8c, 0xb3, 0x73, 0xc4, 0xa8, 0x75, 0x38, 0x24, 0x1f, 0x56, 0x79, 0xd3, 0x9e, 0xbd, 0x1f, - /* (2^142)P */ 0x8d, 0xc2, 0x1e, 0xd4, 0x6f, 0xbc, 0xfa, 0x11, 0xca, 0x2d, 0x2a, 0xcd, 0xe3, 0xdf, 0xf8, 0x7e, 0x95, 0x45, 0x40, 0x8c, 0x5d, 0x3b, 0xe7, 0x72, 0x27, 0x2f, 0xb7, 0x54, 0x49, 0xfa, 0x35, 0x61, - /* (2^143)P */ 0x9c, 0xb6, 0x24, 0xde, 0xa2, 0x32, 0xfc, 0xcc, 0x88, 0x5d, 0x09, 0x1f, 0x8c, 0x69, 0x55, 0x3f, 0x29, 0xf9, 0xc3, 0x5a, 0xed, 0x50, 0x33, 0xbe, 0xeb, 0x7e, 0x47, 0xca, 0x06, 0xf8, 0x9b, 0x5e, - /* (2^144)P */ 0x68, 0x9f, 0x30, 0x3c, 0xb6, 0x8f, 0xce, 0xe9, 0xf4, 0xf9, 0xe1, 0x65, 0x35, 0xf6, 0x76, 0x53, 0xf1, 0x93, 0x63, 0x5a, 0xb3, 0xcf, 0xaf, 0xd1, 0x06, 0x35, 0x62, 0xe5, 0xed, 0xa1, 0x32, 0x66, - /* (2^145)P */ 0x4c, 0xed, 0x2d, 0x0c, 0x39, 0x6c, 0x7d, 0x0b, 0x1f, 0xcb, 0x04, 0xdf, 0x81, 0x32, 0xcb, 0x56, 0xc7, 0xc3, 0xec, 0x49, 0x12, 0x5a, 0x30, 0x66, 0x2a, 0xa7, 0x8c, 0xa3, 0x60, 0x8b, 0x58, 0x5d, - /* (2^146)P */ 0x2d, 0xf4, 0xe5, 0xe8, 0x78, 0xbf, 0xec, 0xa6, 0xec, 0x3e, 0x8a, 0x3c, 0x4b, 0xb4, 0xee, 0x86, 0x04, 0x16, 0xd2, 0xfb, 0x48, 0x9c, 0x21, 0xec, 0x31, 0x67, 0xc3, 0x17, 0xf5, 0x1a, 0xaf, 0x1a, - /* (2^147)P */ 0xe7, 0xbd, 0x69, 0x67, 0x83, 0xa2, 0x06, 0xc3, 0xdb, 0x2a, 0x1e, 0x2b, 0x62, 0x80, 0x82, 0x20, 0xa6, 0x94, 0xff, 0xfb, 0x1f, 0xf5, 0x27, 0x80, 0x6b, 0xf2, 0x24, 0x11, 0xce, 0xa1, 0xcf, 0x76, - /* (2^148)P */ 0xb6, 0xab, 0x22, 0x24, 0x56, 0x00, 0xeb, 0x18, 0xc3, 0x29, 0x8c, 0x8f, 0xd5, 0xc4, 0x77, 0xf3, 0x1a, 0x56, 0x31, 0xf5, 0x07, 0xc2, 0xbb, 0x4d, 0x27, 0x8a, 0x12, 0x82, 0xf0, 0xb7, 0x53, 0x02, - /* (2^149)P */ 0xe0, 0x17, 0x2c, 0xb6, 0x1c, 0x09, 0x1f, 0x3d, 0xa9, 0x28, 0x46, 0xd6, 0xab, 0xe1, 0x60, 0x48, 0x53, 0x42, 0x9d, 0x30, 0x36, 0x74, 0xd1, 0x52, 0x76, 0xe5, 0xfa, 0x3e, 0xe1, 0x97, 0x6f, 0x35, - /* (2^150)P */ 0x5b, 0x53, 0x50, 0xa1, 0x1a, 0xe1, 0x51, 0xd3, 0xcc, 0x78, 0xd8, 0x1d, 0xbb, 0x45, 0x6b, 0x3e, 0x98, 0x2c, 0xd9, 0xbe, 0x28, 0x61, 0x77, 0x0c, 0xb8, 0x85, 0x28, 0x03, 0x93, 0xae, 0x34, 0x1d, - /* (2^151)P */ 0xc3, 0xa4, 0x5b, 0xa8, 0x8c, 0x48, 0xa0, 0x4b, 0xce, 0xe6, 0x9c, 0x3c, 0xc3, 0x48, 0x53, 0x98, 0x70, 0xa7, 0xbd, 0x97, 0x6f, 0x4c, 0x12, 0x66, 0x4a, 0x12, 0x54, 0x06, 0x29, 0xa0, 0x81, 0x0f, - /* (2^152)P */ 0xfd, 0x86, 0x9b, 0x56, 0xa6, 0x9c, 0xd0, 0x9e, 0x2d, 0x9a, 0xaf, 0x18, 0xfd, 0x09, 0x10, 0x81, 0x0a, 0xc2, 0xd8, 0x93, 0x3f, 0xd0, 0x08, 0xff, 0x6b, 0xf2, 0xae, 0x9f, 0x19, 0x48, 0xa1, 0x52, - /* (2^153)P */ 0x73, 0x1b, 0x8d, 0x2d, 0xdc, 0xf9, 0x03, 0x3e, 0x70, 0x1a, 0x96, 0x73, 0x18, 0x80, 0x05, 0x42, 0x70, 0x59, 0xa3, 0x41, 0xf0, 0x87, 0xd9, 0xc0, 0x49, 0xd5, 0xc0, 0xa1, 0x15, 0x1f, 0xaa, 0x07, - /* (2^154)P */ 0x24, 0x72, 0xd2, 0x8c, 0xe0, 0x6c, 0xd4, 0xdf, 0x39, 0x42, 0x4e, 0x93, 0x4f, 0x02, 0x0a, 0x6d, 0x59, 0x7b, 0x89, 0x99, 0x63, 0x7a, 0x8a, 0x80, 0xa2, 0x95, 0x3d, 0xe1, 0xe9, 0x56, 0x45, 0x0a, - /* (2^155)P */ 0x45, 0x30, 0xc1, 0xe9, 0x1f, 0x99, 0x1a, 0xd2, 0xb8, 0x51, 0x77, 0xfe, 0x48, 0x85, 0x0e, 0x9b, 0x35, 0x00, 0xf3, 0x4b, 0xcb, 0x43, 0xa6, 0x5d, 0x21, 0xf7, 0x40, 0x39, 0xd6, 0x28, 0xdb, 0x77, - /* (2^156)P */ 0x11, 0x90, 0xdc, 0x4a, 0x61, 0xeb, 0x5e, 0xfc, 0xeb, 0x11, 0xc4, 0xe8, 0x9a, 0x41, 0x29, 0x52, 0x74, 0xcf, 0x1d, 0x7d, 0x78, 0xe7, 0xc3, 0x9e, 0xb5, 0x4c, 0x6e, 0x21, 0x3e, 0x05, 0x0d, 0x34, - /* (2^157)P */ 0xb4, 0xf2, 0x8d, 0xb4, 0x39, 0xaf, 0xc7, 0xca, 0x94, 0x0a, 0xa1, 0x71, 0x28, 0xec, 0xfa, 0xc0, 0xed, 0x75, 0xa5, 0x5c, 0x24, 0x69, 0x0a, 0x14, 0x4c, 0x3a, 0x27, 0x34, 0x71, 0xc3, 0xf1, 0x0c, - /* (2^158)P */ 0xa5, 0xb8, 0x24, 0xc2, 0x6a, 0x30, 0xee, 0xc8, 0xb0, 0x30, 0x49, 0xcb, 0x7c, 0xee, 0xea, 0x57, 0x4f, 0xe7, 0xcb, 0xaa, 0xbd, 0x06, 0xe8, 0xa1, 0x7d, 0x65, 0xeb, 0x2e, 0x74, 0x62, 0x9a, 0x7d, - /* (2^159)P */ 0x30, 0x48, 0x6c, 0x54, 0xef, 0xb6, 0xb6, 0x9e, 0x2e, 0x6e, 0xb3, 0xdd, 0x1f, 0xca, 0x5c, 0x88, 0x05, 0x71, 0x0d, 0xef, 0x83, 0xf3, 0xb9, 0xe6, 0x12, 0x04, 0x2e, 0x9d, 0xef, 0x4f, 0x65, 0x58, - /* (2^160)P */ 0x26, 0x8e, 0x0e, 0xbe, 0xff, 0xc4, 0x05, 0xa9, 0x6e, 0x81, 0x31, 0x9b, 0xdf, 0xe5, 0x2d, 0x94, 0xe1, 0x88, 0x2e, 0x80, 0x3f, 0x72, 0x7d, 0x49, 0x8d, 0x40, 0x2f, 0x60, 0xea, 0x4d, 0x68, 0x30, - /* (2^161)P */ 0x34, 0xcb, 0xe6, 0xa3, 0x78, 0xa2, 0xe5, 0x21, 0xc4, 0x1d, 0x15, 0x5b, 0x6f, 0x6e, 0xfb, 0xae, 0x15, 0xca, 0x77, 0x9d, 0x04, 0x8e, 0x0b, 0xb3, 0x81, 0x89, 0xb9, 0x53, 0xcf, 0xc9, 0xc3, 0x28, - /* (2^162)P */ 0x2a, 0xdd, 0x6c, 0x55, 0x21, 0xb7, 0x7f, 0x28, 0x74, 0x22, 0x02, 0x97, 0xa8, 0x7c, 0x31, 0x0d, 0x58, 0x32, 0x54, 0x3a, 0x42, 0xc7, 0x68, 0x74, 0x2f, 0x64, 0xb5, 0x4e, 0x46, 0x11, 0x7f, 0x4a, - /* (2^163)P */ 0xa6, 0x3a, 0x19, 0x4d, 0x77, 0xa4, 0x37, 0xa2, 0xa1, 0x29, 0x21, 0xa9, 0x6e, 0x98, 0x65, 0xd8, 0x88, 0x1a, 0x7c, 0xf8, 0xec, 0x15, 0xc5, 0x24, 0xeb, 0xf5, 0x39, 0x5f, 0x57, 0x03, 0x40, 0x60, - /* (2^164)P */ 0x27, 0x9b, 0x0a, 0x57, 0x89, 0xf1, 0xb9, 0x47, 0x78, 0x4b, 0x5e, 0x46, 0xde, 0xce, 0x98, 0x2b, 0x20, 0x5c, 0xb8, 0xdb, 0x51, 0xf5, 0x6d, 0x02, 0x01, 0x19, 0xe2, 0x47, 0x10, 0xd9, 0xfc, 0x74, - /* (2^165)P */ 0xa3, 0xbf, 0xc1, 0x23, 0x0a, 0xa9, 0xe2, 0x13, 0xf6, 0x19, 0x85, 0x47, 0x4e, 0x07, 0xb0, 0x0c, 0x44, 0xcf, 0xf6, 0x3a, 0xbe, 0xcb, 0xf1, 0x5f, 0xbe, 0x2d, 0x81, 0xbe, 0x38, 0x54, 0xfe, 0x67, - /* (2^166)P */ 0xb0, 0x05, 0x0f, 0xa4, 0x4f, 0xf6, 0x3c, 0xd1, 0x87, 0x37, 0x28, 0x32, 0x2f, 0xfb, 0x4d, 0x05, 0xea, 0x2a, 0x0d, 0x7f, 0x5b, 0x91, 0x73, 0x41, 0x4e, 0x0d, 0x61, 0x1f, 0x4f, 0x14, 0x2f, 0x48, - /* (2^167)P */ 0x34, 0x82, 0x7f, 0xb4, 0x01, 0x02, 0x21, 0xf6, 0x90, 0xb9, 0x70, 0x9e, 0x92, 0xe1, 0x0a, 0x5d, 0x7c, 0x56, 0x49, 0xb0, 0x55, 0xf4, 0xd7, 0xdc, 0x01, 0x6f, 0x91, 0xf0, 0xf1, 0xd0, 0x93, 0x7e, - /* (2^168)P */ 0xfa, 0xb4, 0x7d, 0x8a, 0xf1, 0xcb, 0x79, 0xdd, 0x2f, 0xc6, 0x74, 0x6f, 0xbf, 0x91, 0x83, 0xbe, 0xbd, 0x91, 0x82, 0x4b, 0xd1, 0x45, 0x71, 0x02, 0x05, 0x17, 0xbf, 0x2c, 0xea, 0x73, 0x5a, 0x58, - /* (2^169)P */ 0xb2, 0x0d, 0x8a, 0x92, 0x3e, 0xa0, 0x5c, 0x48, 0xe7, 0x57, 0x28, 0x74, 0xa5, 0x01, 0xfc, 0x10, 0xa7, 0x51, 0xd5, 0xd6, 0xdb, 0x2e, 0x48, 0x2f, 0x8a, 0xdb, 0x8f, 0x04, 0xb5, 0x33, 0x04, 0x0f, - /* (2^170)P */ 0x47, 0x62, 0xdc, 0xd7, 0x8d, 0x2e, 0xda, 0x60, 0x9a, 0x81, 0xd4, 0x8c, 0xd3, 0xc9, 0xb4, 0x88, 0x97, 0x66, 0xf6, 0x01, 0xc0, 0x3a, 0x03, 0x13, 0x75, 0x7d, 0x36, 0x3b, 0xfe, 0x24, 0x3b, 0x27, - /* (2^171)P */ 0xd4, 0xb9, 0xb3, 0x31, 0x6a, 0xf6, 0xe8, 0xc6, 0xd5, 0x49, 0xdf, 0x94, 0xa4, 0x14, 0x15, 0x28, 0xa7, 0x3d, 0xb2, 0xc8, 0xdf, 0x6f, 0x72, 0xd1, 0x48, 0xe5, 0xde, 0x03, 0xd1, 0xe7, 0x3a, 0x4b, - /* (2^172)P */ 0x7e, 0x9d, 0x4b, 0xce, 0x19, 0x6e, 0x25, 0xc6, 0x1c, 0xc6, 0xe3, 0x86, 0xf1, 0x5c, 0x5c, 0xff, 0x45, 0xc1, 0x8e, 0x4b, 0xa3, 0x3c, 0xc6, 0xac, 0x74, 0x65, 0xe6, 0xfe, 0x88, 0x18, 0x62, 0x74, - /* (2^173)P */ 0x1e, 0x0a, 0x29, 0x45, 0x96, 0x40, 0x6f, 0x95, 0x2e, 0x96, 0x3a, 0x26, 0xe3, 0xf8, 0x0b, 0xef, 0x7b, 0x64, 0xc2, 0x5e, 0xeb, 0x50, 0x6a, 0xed, 0x02, 0x75, 0xca, 0x9d, 0x3a, 0x28, 0x94, 0x06, - /* (2^174)P */ 0xd1, 0xdc, 0xa2, 0x43, 0x36, 0x96, 0x9b, 0x76, 0x53, 0x53, 0xfc, 0x09, 0xea, 0xc8, 0xb7, 0x42, 0xab, 0x7e, 0x39, 0x13, 0xee, 0x2a, 0x00, 0x4f, 0x3a, 0xd6, 0xb7, 0x19, 0x2c, 0x5e, 0x00, 0x63, - /* (2^175)P */ 0xea, 0x3b, 0x02, 0x63, 0xda, 0x36, 0x67, 0xca, 0xb7, 0x99, 0x2a, 0xb1, 0x6d, 0x7f, 0x6c, 0x96, 0xe1, 0xc5, 0x37, 0xc5, 0x90, 0x93, 0xe0, 0xac, 0xee, 0x89, 0xaa, 0xa1, 0x63, 0x60, 0x69, 0x0b, - /* (2^176)P */ 0xe5, 0x56, 0x8c, 0x28, 0x97, 0x3e, 0xb0, 0xeb, 0xe8, 0x8b, 0x8c, 0x93, 0x9f, 0x9f, 0x2a, 0x43, 0x71, 0x7f, 0x71, 0x5b, 0x3d, 0xa9, 0xa5, 0xa6, 0x97, 0x9d, 0x8f, 0xe1, 0xc3, 0xb4, 0x5f, 0x1a, - /* (2^177)P */ 0xce, 0xcd, 0x60, 0x1c, 0xad, 0xe7, 0x94, 0x1c, 0xa0, 0xc4, 0x02, 0xfc, 0x43, 0x2a, 0x20, 0xee, 0x20, 0x6a, 0xc4, 0x67, 0xd8, 0xe4, 0xaf, 0x8d, 0x58, 0x7b, 0xc2, 0x8a, 0x3c, 0x26, 0x10, 0x0a, - /* (2^178)P */ 0x4a, 0x2a, 0x43, 0xe4, 0xdf, 0xa9, 0xde, 0xd0, 0xc5, 0x77, 0x92, 0xbe, 0x7b, 0xf8, 0x6a, 0x85, 0x1a, 0xc7, 0x12, 0xc2, 0xac, 0x72, 0x84, 0xce, 0x91, 0x1e, 0xbb, 0x9b, 0x6d, 0x1b, 0x15, 0x6f, - /* (2^179)P */ 0x6a, 0xd5, 0xee, 0x7c, 0x52, 0x6c, 0x77, 0x26, 0xec, 0xfa, 0xf8, 0xfb, 0xb7, 0x1c, 0x21, 0x7d, 0xcc, 0x09, 0x46, 0xfd, 0xa6, 0x66, 0xae, 0x37, 0x42, 0x0c, 0x77, 0xd2, 0x02, 0xb7, 0x81, 0x1f, - /* (2^180)P */ 0x92, 0x83, 0xc5, 0xea, 0x57, 0xb0, 0xb0, 0x2f, 0x9d, 0x4e, 0x74, 0x29, 0xfe, 0x89, 0xdd, 0xe1, 0xf8, 0xb4, 0xbe, 0x17, 0xeb, 0xf8, 0x64, 0xc9, 0x1e, 0xd4, 0xa2, 0xc9, 0x73, 0x10, 0x57, 0x29, - /* (2^181)P */ 0x54, 0xe2, 0xc0, 0x81, 0x89, 0xa1, 0x48, 0xa9, 0x30, 0x28, 0xb2, 0x65, 0x9b, 0x36, 0xf6, 0x2d, 0xc6, 0xd3, 0xcf, 0x5f, 0xd7, 0xb2, 0x3e, 0xa3, 0x1f, 0xa0, 0x99, 0x41, 0xec, 0xd6, 0x8c, 0x07, - /* (2^182)P */ 0x2f, 0x0d, 0x90, 0xad, 0x41, 0x4a, 0x58, 0x4a, 0x52, 0x4c, 0xc7, 0xe2, 0x78, 0x2b, 0x14, 0x32, 0x78, 0xc9, 0x31, 0x84, 0x33, 0xe8, 0xc4, 0x68, 0xc2, 0x9f, 0x68, 0x08, 0x90, 0xea, 0x69, 0x7f, - /* (2^183)P */ 0x65, 0x82, 0xa3, 0x46, 0x1e, 0xc8, 0xf2, 0x52, 0xfd, 0x32, 0xa8, 0x04, 0x2d, 0x07, 0x78, 0xfd, 0x94, 0x9e, 0x35, 0x25, 0xfa, 0xd5, 0xd7, 0x8c, 0xd2, 0x29, 0xcc, 0x54, 0x74, 0x1b, 0xe7, 0x4d, - /* (2^184)P */ 0xc9, 0x6a, 0xda, 0x1e, 0xad, 0x60, 0xeb, 0x42, 0x3a, 0x9c, 0xc0, 0xdb, 0xdf, 0x37, 0xad, 0x0a, 0x91, 0xc1, 0x3c, 0xe3, 0x71, 0x4b, 0x00, 0x81, 0x3c, 0x80, 0x22, 0x51, 0x34, 0xbe, 0xe6, 0x44, - /* (2^185)P */ 0xdb, 0x20, 0x19, 0xba, 0x88, 0x83, 0xfe, 0x03, 0x08, 0xb0, 0x0d, 0x15, 0x32, 0x7c, 0xd5, 0xf5, 0x29, 0x0c, 0xf6, 0x1a, 0x28, 0xc4, 0xc8, 0x49, 0xee, 0x1a, 0x70, 0xde, 0x18, 0xb5, 0xed, 0x21, - /* (2^186)P */ 0x99, 0xdc, 0x06, 0x8f, 0x41, 0x3e, 0xb6, 0x7f, 0xb8, 0xd7, 0x66, 0xc1, 0x99, 0x0d, 0x46, 0xa4, 0x83, 0x0a, 0x52, 0xce, 0x48, 0x52, 0xdd, 0x24, 0x58, 0x83, 0x92, 0x2b, 0x71, 0xad, 0xc3, 0x5e, - /* (2^187)P */ 0x0f, 0x93, 0x17, 0xbd, 0x5f, 0x2a, 0x02, 0x15, 0xe3, 0x70, 0x25, 0xd8, 0x77, 0x4a, 0xf6, 0xa4, 0x12, 0x37, 0x78, 0x15, 0x69, 0x8d, 0xbc, 0x12, 0xbb, 0x0a, 0x62, 0xfc, 0xc0, 0x94, 0x81, 0x49, - /* (2^188)P */ 0x82, 0x6c, 0x68, 0x55, 0xd2, 0xd9, 0xa2, 0x38, 0xf0, 0x21, 0x3e, 0x19, 0xd9, 0x6b, 0x5c, 0x78, 0x84, 0x54, 0x4a, 0xb2, 0x1a, 0xc8, 0xd5, 0xe4, 0x89, 0x09, 0xe2, 0xb2, 0x60, 0x78, 0x30, 0x56, - /* (2^189)P */ 0xc4, 0x74, 0x4d, 0x8b, 0xf7, 0x55, 0x9d, 0x42, 0x31, 0x01, 0x35, 0x43, 0x46, 0x83, 0xf1, 0x22, 0xff, 0x1f, 0xc7, 0x98, 0x45, 0xc2, 0x60, 0x1e, 0xef, 0x83, 0x99, 0x97, 0x14, 0xf0, 0xf2, 0x59, - /* (2^190)P */ 0x44, 0x4a, 0x49, 0xeb, 0x56, 0x7d, 0xa4, 0x46, 0x8e, 0xa1, 0x36, 0xd6, 0x54, 0xa8, 0x22, 0x3e, 0x3b, 0x1c, 0x49, 0x74, 0x52, 0xe1, 0x46, 0xb3, 0xe7, 0xcd, 0x90, 0x53, 0x4e, 0xfd, 0xea, 0x2c, - /* (2^191)P */ 0x75, 0x66, 0x0d, 0xbe, 0x38, 0x85, 0x8a, 0xba, 0x23, 0x8e, 0x81, 0x50, 0xbb, 0x74, 0x90, 0x4b, 0xc3, 0x04, 0xd3, 0x85, 0x90, 0xb8, 0xda, 0xcb, 0xc4, 0x92, 0x61, 0xe5, 0xe0, 0x4f, 0xa2, 0x61, - /* (2^192)P */ 0xcb, 0x5b, 0x52, 0xdb, 0xe6, 0x15, 0x76, 0xcb, 0xca, 0xe4, 0x67, 0xa5, 0x35, 0x8c, 0x7d, 0xdd, 0x69, 0xdd, 0xfc, 0xca, 0x3a, 0x15, 0xb4, 0xe6, 0x66, 0x97, 0x3c, 0x7f, 0x09, 0x8e, 0x66, 0x2d, - /* (2^193)P */ 0xf0, 0x5e, 0xe5, 0x5c, 0x26, 0x7e, 0x7e, 0xa5, 0x67, 0xb9, 0xd4, 0x7c, 0x52, 0x4e, 0x9f, 0x5d, 0xe5, 0xd1, 0x2f, 0x49, 0x06, 0x36, 0xc8, 0xfb, 0xae, 0xf7, 0xc3, 0xb7, 0xbe, 0x52, 0x0d, 0x09, - /* (2^194)P */ 0x7c, 0x4d, 0x7b, 0x1e, 0x5a, 0x51, 0xb9, 0x09, 0xc0, 0x44, 0xda, 0x99, 0x25, 0x6a, 0x26, 0x1f, 0x04, 0x55, 0xc5, 0xe2, 0x48, 0x95, 0xc4, 0xa1, 0xcc, 0x15, 0x6f, 0x12, 0x87, 0x42, 0xf0, 0x7e, - /* (2^195)P */ 0x15, 0xef, 0x30, 0xbd, 0x9d, 0x65, 0xd1, 0xfe, 0x7b, 0x27, 0xe0, 0xc4, 0xee, 0xb9, 0x4a, 0x8b, 0x91, 0x32, 0xdf, 0xa5, 0x36, 0x62, 0x4d, 0x88, 0x88, 0xf7, 0x5c, 0xbf, 0xa6, 0x6e, 0xd9, 0x1f, - /* (2^196)P */ 0x9a, 0x0d, 0x19, 0x1f, 0x98, 0x61, 0xa1, 0x42, 0xc1, 0x52, 0x60, 0x7e, 0x50, 0x49, 0xd8, 0x61, 0xd5, 0x2c, 0x5a, 0x28, 0xbf, 0x13, 0xe1, 0x9f, 0xd8, 0x85, 0xad, 0xdb, 0x76, 0xd6, 0x22, 0x7c, - /* (2^197)P */ 0x7d, 0xd2, 0xfb, 0x2b, 0xed, 0x70, 0xe7, 0x82, 0xa5, 0xf5, 0x96, 0xe9, 0xec, 0xb2, 0x05, 0x4c, 0x50, 0x01, 0x90, 0xb0, 0xc2, 0xa9, 0x40, 0xcd, 0x64, 0xbf, 0xd9, 0x13, 0x92, 0x31, 0x95, 0x58, - /* (2^198)P */ 0x08, 0x2e, 0xea, 0x3f, 0x70, 0x5d, 0xcc, 0xe7, 0x8c, 0x18, 0xe2, 0x58, 0x12, 0x49, 0x0c, 0xb5, 0xf0, 0x5b, 0x20, 0x48, 0xaa, 0x0b, 0xe3, 0xcc, 0x62, 0x2d, 0xa3, 0xcf, 0x9c, 0x65, 0x7c, 0x53, - /* (2^199)P */ 0x88, 0xc0, 0xcf, 0x98, 0x3a, 0x62, 0xb6, 0x37, 0xa4, 0xac, 0xd6, 0xa4, 0x1f, 0xed, 0x9b, 0xfe, 0xb0, 0xd1, 0xa8, 0x56, 0x8e, 0x9b, 0xd2, 0x04, 0x75, 0x95, 0x51, 0x0b, 0xc4, 0x71, 0x5f, 0x72, - /* (2^200)P */ 0xe6, 0x9c, 0x33, 0xd0, 0x9c, 0xf8, 0xc7, 0x28, 0x8b, 0xc1, 0xdd, 0x69, 0x44, 0xb1, 0x67, 0x83, 0x2c, 0x65, 0xa1, 0xa6, 0x83, 0xda, 0x3a, 0x88, 0x17, 0x6c, 0x4d, 0x03, 0x74, 0x19, 0x5f, 0x58, - /* (2^201)P */ 0x88, 0x91, 0xb1, 0xf1, 0x66, 0xb2, 0xcf, 0x89, 0x17, 0x52, 0xc3, 0xe7, 0x63, 0x48, 0x3b, 0xe6, 0x6a, 0x52, 0xc0, 0xb4, 0xa6, 0x9d, 0x8c, 0xd8, 0x35, 0x46, 0x95, 0xf0, 0x9d, 0x5c, 0x03, 0x3e, - /* (2^202)P */ 0x9d, 0xde, 0x45, 0xfb, 0x12, 0x54, 0x9d, 0xdd, 0x0d, 0xf4, 0xcf, 0xe4, 0x32, 0x45, 0x68, 0xdd, 0x1c, 0x67, 0x1d, 0x15, 0x9b, 0x99, 0x5c, 0x4b, 0x90, 0xf6, 0xe7, 0x11, 0xc8, 0x2c, 0x8c, 0x2d, - /* (2^203)P */ 0x40, 0x5d, 0x05, 0x90, 0x1d, 0xbe, 0x54, 0x7f, 0x40, 0xaf, 0x4a, 0x46, 0xdf, 0xc5, 0x64, 0xa4, 0xbe, 0x17, 0xe9, 0xf0, 0x24, 0x96, 0x97, 0x33, 0x30, 0x6b, 0x35, 0x27, 0xc5, 0x8d, 0x01, 0x2c, - /* (2^204)P */ 0xd4, 0xb3, 0x30, 0xe3, 0x24, 0x50, 0x41, 0xa5, 0xd3, 0x52, 0x16, 0x69, 0x96, 0x3d, 0xff, 0x73, 0xf1, 0x59, 0x9b, 0xef, 0xc4, 0x42, 0xec, 0x94, 0x5a, 0x8e, 0xd0, 0x18, 0x16, 0x20, 0x47, 0x07, - /* (2^205)P */ 0x53, 0x1c, 0x41, 0xca, 0x8a, 0xa4, 0x6c, 0x4d, 0x19, 0x61, 0xa6, 0xcf, 0x2f, 0x5f, 0x41, 0x66, 0xff, 0x27, 0xe2, 0x51, 0x00, 0xd4, 0x4d, 0x9c, 0xeb, 0xf7, 0x02, 0x9a, 0xc0, 0x0b, 0x81, 0x59, - /* (2^206)P */ 0x1d, 0x10, 0xdc, 0xb3, 0x71, 0xb1, 0x7e, 0x2a, 0x8e, 0xf6, 0xfe, 0x9f, 0xb9, 0x5a, 0x1c, 0x44, 0xea, 0x59, 0xb3, 0x93, 0x9b, 0x5c, 0x02, 0x32, 0x2f, 0x11, 0x9d, 0x1e, 0xa7, 0xe0, 0x8c, 0x5e, - /* (2^207)P */ 0xfd, 0x03, 0x95, 0x42, 0x92, 0xcb, 0xcc, 0xbf, 0x55, 0x5d, 0x09, 0x2f, 0x75, 0xba, 0x71, 0xd2, 0x1e, 0x09, 0x2d, 0x97, 0x5e, 0xad, 0x5e, 0x34, 0xba, 0x03, 0x31, 0xa8, 0x11, 0xdf, 0xc8, 0x18, - /* (2^208)P */ 0x4c, 0x0f, 0xed, 0x9a, 0x9a, 0x94, 0xcd, 0x90, 0x7e, 0xe3, 0x60, 0x66, 0xcb, 0xf4, 0xd1, 0xc5, 0x0b, 0x2e, 0xc5, 0x56, 0x2d, 0xc5, 0xca, 0xb8, 0x0d, 0x8e, 0x80, 0xc5, 0x00, 0xe4, 0x42, 0x6e, - /* (2^209)P */ 0x23, 0xfd, 0xae, 0xee, 0x66, 0x69, 0xb4, 0xa3, 0xca, 0xcd, 0x9e, 0xe3, 0x0b, 0x1f, 0x4f, 0x0c, 0x1d, 0xa5, 0x83, 0xd6, 0xc9, 0xc8, 0x9d, 0x18, 0x1b, 0x35, 0x09, 0x4c, 0x05, 0x7f, 0xf2, 0x51, - /* (2^210)P */ 0x82, 0x06, 0x32, 0x2a, 0xcd, 0x7c, 0x48, 0x4c, 0x96, 0x1c, 0xdf, 0xb3, 0x5b, 0xa9, 0x7e, 0x58, 0xe8, 0xb8, 0x5c, 0x55, 0x9e, 0xf7, 0xcc, 0xc8, 0x3d, 0xd7, 0x06, 0xa2, 0x29, 0xc8, 0x7d, 0x54, - /* (2^211)P */ 0x06, 0x9b, 0xc3, 0x80, 0xcd, 0xa6, 0x22, 0xb8, 0xc6, 0xd4, 0x00, 0x20, 0x73, 0x54, 0x6d, 0xe9, 0x4d, 0x3b, 0x46, 0x91, 0x6f, 0x5b, 0x53, 0x28, 0x1d, 0x6e, 0x48, 0xe2, 0x60, 0x46, 0x8f, 0x22, - /* (2^212)P */ 0xbf, 0x3a, 0x8d, 0xde, 0x38, 0x95, 0x79, 0x98, 0x6e, 0xca, 0xeb, 0x45, 0x00, 0x33, 0xd8, 0x8c, 0x38, 0xe7, 0x21, 0x82, 0x00, 0x2a, 0x95, 0x79, 0xbb, 0xd2, 0x5c, 0x53, 0xa7, 0xe1, 0x22, 0x43, - /* (2^213)P */ 0x1c, 0x80, 0xd1, 0x19, 0x18, 0xc1, 0x14, 0xb1, 0xc7, 0x5e, 0x3f, 0x4f, 0xd8, 0xe4, 0x16, 0x20, 0x4c, 0x0f, 0x26, 0x09, 0xf4, 0x2d, 0x0e, 0xdd, 0x66, 0x72, 0x5f, 0xae, 0xc0, 0x62, 0xc3, 0x5e, - /* (2^214)P */ 0xee, 0xb4, 0xb2, 0xb8, 0x18, 0x2b, 0x46, 0xc0, 0xfb, 0x1a, 0x4d, 0x27, 0x50, 0xd9, 0xc8, 0x7c, 0xd2, 0x02, 0x6b, 0x43, 0x05, 0x71, 0x5f, 0xf2, 0xd3, 0xcc, 0xf9, 0xbf, 0xdc, 0xf8, 0xbb, 0x43, - /* (2^215)P */ 0xdf, 0xe9, 0x39, 0xa0, 0x67, 0x17, 0xad, 0xb6, 0x83, 0x35, 0x9d, 0xf6, 0xa8, 0x4d, 0x71, 0xb0, 0xf5, 0x31, 0x29, 0xb4, 0x18, 0xfa, 0x55, 0x5e, 0x61, 0x09, 0xc6, 0x33, 0x8f, 0x55, 0xd5, 0x4e, - /* (2^216)P */ 0xdd, 0xa5, 0x47, 0xc6, 0x01, 0x79, 0xe3, 0x1f, 0x57, 0xd3, 0x81, 0x80, 0x1f, 0xdf, 0x3d, 0x59, 0xa6, 0xd7, 0x3f, 0x81, 0xfd, 0xa4, 0x49, 0x02, 0x61, 0xaf, 0x9c, 0x4e, 0x27, 0xca, 0xac, 0x69, - /* (2^217)P */ 0xc9, 0x21, 0x07, 0x33, 0xea, 0xa3, 0x7b, 0x04, 0xa0, 0x1e, 0x7e, 0x0e, 0xc2, 0x3f, 0x42, 0x83, 0x60, 0x4a, 0x31, 0x01, 0xaf, 0xc0, 0xf4, 0x1d, 0x27, 0x95, 0x28, 0x89, 0xab, 0x2d, 0xa6, 0x09, - /* (2^218)P */ 0x00, 0xcb, 0xc6, 0x9c, 0xa4, 0x25, 0xb3, 0xa5, 0xb6, 0x6c, 0xb5, 0x54, 0xc6, 0x5d, 0x4b, 0xe9, 0xa0, 0x94, 0xc9, 0xad, 0x79, 0x87, 0xe2, 0x3b, 0xad, 0x4a, 0x3a, 0xba, 0xf8, 0xe8, 0x96, 0x42, - /* (2^219)P */ 0xab, 0x1e, 0x45, 0x1e, 0x76, 0x89, 0x86, 0x32, 0x4a, 0x59, 0x59, 0xff, 0x8b, 0x59, 0x4d, 0x2e, 0x4a, 0x08, 0xa7, 0xd7, 0x53, 0x68, 0xb9, 0x49, 0xa8, 0x20, 0x14, 0x60, 0x19, 0xa3, 0x80, 0x49, - /* (2^220)P */ 0x42, 0x2c, 0x55, 0x2f, 0xe1, 0xb9, 0x65, 0x95, 0x96, 0xfe, 0x00, 0x71, 0xdb, 0x18, 0x53, 0x8a, 0xd7, 0xd0, 0xad, 0x43, 0x4d, 0x0b, 0xc9, 0x05, 0xda, 0x4e, 0x5d, 0x6a, 0xd6, 0x4c, 0x8b, 0x53, - /* (2^221)P */ 0x9f, 0x03, 0x9f, 0xe8, 0xc3, 0x4f, 0xe9, 0xf4, 0x45, 0x80, 0x61, 0x6f, 0xf2, 0x9a, 0x2c, 0x59, 0x50, 0x95, 0x4b, 0xfd, 0xb5, 0x6e, 0xa3, 0x08, 0x19, 0x14, 0xed, 0xc2, 0xf6, 0xfa, 0xff, 0x25, - /* (2^222)P */ 0x54, 0xd3, 0x79, 0xcc, 0x59, 0x44, 0x43, 0x34, 0x6b, 0x47, 0xd5, 0xb1, 0xb4, 0xbf, 0xec, 0xee, 0x99, 0x5d, 0x61, 0x61, 0xa0, 0x34, 0xeb, 0xdd, 0x73, 0xb7, 0x64, 0xeb, 0xcc, 0xce, 0x29, 0x51, - /* (2^223)P */ 0x20, 0x35, 0x99, 0x94, 0x58, 0x21, 0x43, 0xee, 0x3b, 0x0b, 0x4c, 0xf1, 0x7c, 0x9c, 0x2f, 0x77, 0xd5, 0xda, 0xbe, 0x06, 0xe3, 0xfc, 0xe2, 0xd2, 0x97, 0x6a, 0xf0, 0x46, 0xb5, 0x42, 0x5f, 0x71, - /* (2^224)P */ 0x1a, 0x5f, 0x5b, 0xda, 0xce, 0xcd, 0x4e, 0x43, 0xa9, 0x41, 0x97, 0xa4, 0x15, 0x71, 0xa1, 0x0d, 0x2e, 0xad, 0xed, 0x73, 0x7c, 0xd7, 0x0b, 0x68, 0x41, 0x90, 0xdd, 0x4e, 0x35, 0x02, 0x7c, 0x48, - /* (2^225)P */ 0xc4, 0xd9, 0x0e, 0xa7, 0xf3, 0xef, 0xef, 0xb8, 0x02, 0xe3, 0x57, 0xe8, 0xa3, 0x2a, 0xa3, 0x56, 0xa0, 0xa5, 0xa2, 0x48, 0xbd, 0x68, 0x3a, 0xdf, 0x44, 0xc4, 0x76, 0x31, 0xb7, 0x50, 0xf6, 0x07, - /* (2^226)P */ 0xb1, 0xcc, 0xe0, 0x26, 0x16, 0x9b, 0x8b, 0xe3, 0x36, 0xfb, 0x09, 0x8b, 0xc1, 0x53, 0xe0, 0x79, 0x64, 0x49, 0xf9, 0xc9, 0x19, 0x03, 0xd9, 0x56, 0xc4, 0xf5, 0x9f, 0xac, 0xe7, 0x41, 0xa9, 0x1c, - /* (2^227)P */ 0xbb, 0xa0, 0x2f, 0x16, 0x29, 0xdf, 0xc4, 0x49, 0x05, 0x33, 0xb3, 0x82, 0x32, 0xcf, 0x88, 0x84, 0x7d, 0x43, 0xbb, 0xca, 0x14, 0xda, 0xdf, 0x95, 0x86, 0xad, 0xd5, 0x64, 0x82, 0xf7, 0x91, 0x33, - /* (2^228)P */ 0x5d, 0x09, 0xb5, 0xe2, 0x6a, 0xe0, 0x9a, 0x72, 0x46, 0xa9, 0x59, 0x32, 0xd7, 0x58, 0x8a, 0xd5, 0xed, 0x21, 0x39, 0xd1, 0x62, 0x42, 0x83, 0xe9, 0x92, 0xb5, 0x4b, 0xa5, 0xfa, 0xda, 0xfe, 0x27, - /* (2^229)P */ 0xbb, 0x48, 0xad, 0x29, 0xb8, 0xc5, 0x9d, 0xa9, 0x60, 0xe2, 0x9e, 0x49, 0x42, 0x57, 0x02, 0x5f, 0xfd, 0x13, 0x75, 0x5d, 0xcd, 0x8e, 0x2c, 0x80, 0x38, 0xd9, 0x6d, 0x3f, 0xef, 0xb3, 0xce, 0x78, - /* (2^230)P */ 0x94, 0x5d, 0x13, 0x8a, 0x4f, 0xf4, 0x42, 0xc3, 0xa3, 0xdd, 0x8c, 0x82, 0x44, 0xdb, 0x9e, 0x7b, 0xe7, 0xcf, 0x37, 0x05, 0x1a, 0xd1, 0x36, 0x94, 0xc8, 0xb4, 0x1a, 0xec, 0x64, 0xb1, 0x64, 0x50, - /* (2^231)P */ 0xfc, 0xb2, 0x7e, 0xd3, 0xcf, 0xec, 0x20, 0x70, 0xfc, 0x25, 0x0d, 0xd9, 0x3e, 0xea, 0x31, 0x1f, 0x34, 0xbb, 0xa1, 0xdf, 0x7b, 0x0d, 0x93, 0x1b, 0x44, 0x30, 0x11, 0x48, 0x7a, 0x46, 0x44, 0x53, - /* (2^232)P */ 0xfb, 0x6d, 0x5e, 0xf2, 0x70, 0x31, 0x07, 0x70, 0xc8, 0x4c, 0x11, 0x50, 0x1a, 0xdc, 0x85, 0xe3, 0x00, 0x4f, 0xfc, 0xc8, 0x8a, 0x69, 0x48, 0x23, 0xd8, 0x40, 0xdd, 0x84, 0x52, 0xa5, 0x77, 0x2a, - /* (2^233)P */ 0xe4, 0x6c, 0x8c, 0xc9, 0xe0, 0xaf, 0x06, 0xfe, 0xe4, 0xd6, 0xdf, 0xdd, 0x96, 0xdf, 0x35, 0xc2, 0xd3, 0x1e, 0xbf, 0x33, 0x1e, 0xd0, 0x28, 0x14, 0xaf, 0xbd, 0x00, 0x93, 0xec, 0x68, 0x57, 0x78, - /* (2^234)P */ 0x3b, 0xb6, 0xde, 0x91, 0x7a, 0xe5, 0x02, 0x97, 0x80, 0x8b, 0xce, 0xe5, 0xbf, 0xb8, 0xbd, 0x61, 0xac, 0x58, 0x1d, 0x3d, 0x6f, 0x42, 0x5b, 0x64, 0xbc, 0x57, 0xa5, 0x27, 0x22, 0xa8, 0x04, 0x48, - /* (2^235)P */ 0x01, 0x26, 0x4d, 0xb4, 0x8a, 0x04, 0x57, 0x8e, 0x35, 0x69, 0x3a, 0x4b, 0x1a, 0x50, 0xd6, 0x68, 0x93, 0xc2, 0xe1, 0xf9, 0xc3, 0x9e, 0x9c, 0xc3, 0xe2, 0x63, 0xde, 0xd4, 0x57, 0xf2, 0x72, 0x41, - /* (2^236)P */ 0x01, 0x64, 0x0c, 0x33, 0x50, 0xb4, 0x68, 0xd3, 0x91, 0x23, 0x8f, 0x41, 0x17, 0x30, 0x0d, 0x04, 0x0d, 0xd9, 0xb7, 0x90, 0x60, 0xbb, 0x34, 0x2c, 0x1f, 0xd5, 0xdf, 0x8f, 0x22, 0x49, 0xf6, 0x16, - /* (2^237)P */ 0xf5, 0x8e, 0x92, 0x2b, 0x8e, 0x81, 0xa6, 0xbe, 0x72, 0x1e, 0xc1, 0xcd, 0x91, 0xcf, 0x8c, 0xe2, 0xcd, 0x36, 0x7a, 0xe7, 0x68, 0xaa, 0x4a, 0x59, 0x0f, 0xfd, 0x7f, 0x6c, 0x80, 0x34, 0x30, 0x31, - /* (2^238)P */ 0x65, 0xbd, 0x49, 0x22, 0xac, 0x27, 0x9d, 0x8a, 0x12, 0x95, 0x8e, 0x01, 0x64, 0xb4, 0xa3, 0x19, 0xc7, 0x7e, 0xb3, 0x52, 0xf3, 0xcf, 0x6c, 0xc2, 0x21, 0x7b, 0x79, 0x1d, 0x34, 0x68, 0x6f, 0x05, - /* (2^239)P */ 0x27, 0x23, 0xfd, 0x7e, 0x75, 0xd6, 0x79, 0x5e, 0x15, 0xfe, 0x3a, 0x55, 0xb6, 0xbc, 0xbd, 0xfa, 0x60, 0x5a, 0xaf, 0x6e, 0x2c, 0x22, 0xe7, 0xd3, 0x3b, 0x74, 0xae, 0x4d, 0x6d, 0xc7, 0x46, 0x70, - /* (2^240)P */ 0x55, 0x4a, 0x8d, 0xb1, 0x72, 0xe8, 0x0b, 0x66, 0x96, 0x14, 0x4e, 0x57, 0x18, 0x25, 0x99, 0x19, 0xbb, 0xdc, 0x2b, 0x30, 0x3a, 0x05, 0x03, 0xc1, 0x8e, 0x8e, 0x21, 0x0b, 0x80, 0xe9, 0xd8, 0x3e, - /* (2^241)P */ 0x3e, 0xe0, 0x75, 0xfa, 0x39, 0x92, 0x0b, 0x7b, 0x83, 0xc0, 0x33, 0x46, 0x68, 0xfb, 0xe9, 0xef, 0x93, 0x77, 0x1a, 0x39, 0xbe, 0x5f, 0xa3, 0x98, 0x34, 0xfe, 0xd0, 0xe2, 0x0f, 0x51, 0x65, 0x60, - /* (2^242)P */ 0x0c, 0xad, 0xab, 0x48, 0x85, 0x66, 0xcb, 0x55, 0x27, 0xe5, 0x87, 0xda, 0x48, 0x45, 0x58, 0xb4, 0xdd, 0xc1, 0x07, 0x01, 0xea, 0xec, 0x43, 0x2c, 0x35, 0xde, 0x72, 0x93, 0x80, 0x28, 0x60, 0x52, - /* (2^243)P */ 0x1f, 0x3b, 0x21, 0xf9, 0x6a, 0xc5, 0x15, 0x34, 0xdb, 0x98, 0x7e, 0x01, 0x4d, 0x1a, 0xee, 0x5b, 0x9b, 0x70, 0xcf, 0xb5, 0x05, 0xb1, 0xf6, 0x13, 0xb6, 0x9a, 0xb2, 0x82, 0x34, 0x0e, 0xf2, 0x5f, - /* (2^244)P */ 0x90, 0x6c, 0x2e, 0xcc, 0x75, 0x9c, 0xa2, 0x0a, 0x06, 0xe2, 0x70, 0x3a, 0xca, 0x73, 0x7d, 0xfc, 0x15, 0xc5, 0xb5, 0xc4, 0x8f, 0xc3, 0x9f, 0x89, 0x07, 0xc2, 0xff, 0x24, 0xb1, 0x86, 0x03, 0x25, - /* (2^245)P */ 0x56, 0x2b, 0x3d, 0xae, 0xd5, 0x28, 0xea, 0x54, 0xce, 0x60, 0xde, 0xd6, 0x9d, 0x14, 0x13, 0x99, 0xc1, 0xd6, 0x06, 0x8f, 0xc5, 0x4f, 0x69, 0x16, 0xc7, 0x8f, 0x01, 0xeb, 0x75, 0x39, 0xb2, 0x46, - /* (2^246)P */ 0xe2, 0xb4, 0xb7, 0xb4, 0x0f, 0x6a, 0x0a, 0x47, 0xde, 0x53, 0x72, 0x8f, 0x5a, 0x47, 0x92, 0x5d, 0xdb, 0x3a, 0xbd, 0x2f, 0xb5, 0xe5, 0xee, 0xab, 0x68, 0x69, 0x80, 0xa0, 0x01, 0x08, 0xa2, 0x7f, - /* (2^247)P */ 0xd2, 0x14, 0x77, 0x9f, 0xf1, 0xfa, 0xf3, 0x76, 0xc3, 0x60, 0x46, 0x2f, 0xc1, 0x40, 0xe8, 0xb3, 0x4e, 0x74, 0x12, 0xf2, 0x8d, 0xcd, 0xb4, 0x0f, 0xd2, 0x2d, 0x3a, 0x1d, 0x25, 0x5a, 0x06, 0x4b, - /* (2^248)P */ 0x4a, 0xcd, 0x77, 0x3d, 0x38, 0xde, 0xeb, 0x5c, 0xb1, 0x9c, 0x2c, 0x88, 0xdf, 0x39, 0xdf, 0x6a, 0x59, 0xf7, 0x9a, 0xb0, 0x2e, 0x24, 0xdd, 0xa2, 0x22, 0x64, 0x5f, 0x0e, 0xe5, 0xc0, 0x47, 0x31, - /* (2^249)P */ 0xdb, 0x50, 0x13, 0x1d, 0x10, 0xa5, 0x4c, 0x16, 0x62, 0xc9, 0x3f, 0xc3, 0x79, 0x34, 0xd1, 0xf8, 0x08, 0xda, 0xe5, 0x13, 0x4d, 0xce, 0x40, 0xe6, 0xba, 0xf8, 0x61, 0x50, 0xc4, 0xe0, 0xde, 0x4b, - /* (2^250)P */ 0xc9, 0xb1, 0xed, 0xa4, 0xc1, 0x6d, 0xc4, 0xd7, 0x8a, 0xd9, 0x7f, 0x43, 0xb6, 0xd7, 0x14, 0x55, 0x0b, 0xc0, 0xa1, 0xb2, 0x6b, 0x2f, 0x94, 0x58, 0x0e, 0x71, 0x70, 0x1d, 0xab, 0xb2, 0xff, 0x2d, - /* (2^251)P */ 0x68, 0x6d, 0x8b, 0xc1, 0x2f, 0xcf, 0xdf, 0xcc, 0x67, 0x61, 0x80, 0xb7, 0xa8, 0xcb, 0xeb, 0xa8, 0xe3, 0x37, 0x29, 0x5e, 0xf9, 0x97, 0x06, 0x98, 0x8c, 0x6e, 0x12, 0xd0, 0x1c, 0xba, 0xfb, 0x02, - /* (2^252)P */ 0x65, 0x45, 0xff, 0xad, 0x60, 0xc3, 0x98, 0xcb, 0x19, 0x15, 0xdb, 0x4b, 0xd2, 0x01, 0x71, 0x44, 0xd5, 0x15, 0xfb, 0x75, 0x74, 0xc8, 0xc4, 0x98, 0x7d, 0xa2, 0x22, 0x6e, 0x6d, 0xc7, 0xf8, 0x05, - /* (2^253)P */ 0x94, 0xf4, 0xb9, 0xfe, 0xdf, 0xe5, 0x69, 0xab, 0x75, 0x6b, 0x40, 0x18, 0x9d, 0xc7, 0x09, 0xae, 0x1d, 0x2d, 0xa4, 0x94, 0xfb, 0x45, 0x9b, 0x19, 0x84, 0xfa, 0x2a, 0xae, 0xeb, 0x0a, 0x71, 0x79, - /* (2^254)P */ 0xdf, 0xd2, 0x34, 0xf3, 0xa7, 0xed, 0xad, 0xa6, 0xb4, 0x57, 0x2a, 0xaf, 0x51, 0x9c, 0xde, 0x7b, 0xa8, 0xea, 0xdc, 0x86, 0x4f, 0xc6, 0x8f, 0xa9, 0x7b, 0xd0, 0x0e, 0xc2, 0x35, 0x03, 0xbe, 0x6b, - /* (2^255)P */ 0x44, 0x43, 0x98, 0x53, 0xbe, 0xdc, 0x7f, 0x66, 0xa8, 0x49, 0x59, 0x00, 0x1c, 0xbc, 0x72, 0x07, 0x8e, 0xd6, 0xbe, 0x4e, 0x9f, 0xa4, 0x07, 0xba, 0xbf, 0x30, 0xdf, 0xba, 0x85, 0xb0, 0xa7, 0x1f, -} diff --git a/vendor/github.com/cloudflare/circl/dh/x448/curve.go b/vendor/github.com/cloudflare/circl/dh/x448/curve.go deleted file mode 100644 index d59564e4..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x448/curve.go +++ /dev/null @@ -1,104 +0,0 @@ -package x448 - -import ( - fp "github.com/cloudflare/circl/math/fp448" -) - -// ladderJoye calculates a fixed-point multiplication with the generator point. -// The algorithm is the right-to-left Joye's ladder as described -// in "How to precompute a ladder" in SAC'2017. -func ladderJoye(k *Key) { - w := [5]fp.Elt{} // [mu,x1,z1,x2,z2] order must be preserved. - w[1] = fp.Elt{ // x1 = S - 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, 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, - } - fp.SetOne(&w[2]) // z1 = 1 - w[3] = fp.Elt{ // x2 = G-S - 0x20, 0x27, 0x9d, 0xc9, 0x7d, 0x19, 0xb1, 0xac, - 0xf8, 0xba, 0x69, 0x1c, 0xff, 0x33, 0xac, 0x23, - 0x51, 0x1b, 0xce, 0x3a, 0x64, 0x65, 0xbd, 0xf1, - 0x23, 0xf8, 0xc1, 0x84, 0x9d, 0x45, 0x54, 0x29, - 0x67, 0xb9, 0x81, 0x1c, 0x03, 0xd1, 0xcd, 0xda, - 0x7b, 0xeb, 0xff, 0x1a, 0x88, 0x03, 0xcf, 0x3a, - 0x42, 0x44, 0x32, 0x01, 0x25, 0xb7, 0xfa, 0xf0, - } - fp.SetOne(&w[4]) // z2 = 1 - - const n = 448 - const h = 2 - swap := uint(1) - for s := 0; s < n-h; s++ { - i := (s + h) / 8 - j := (s + h) % 8 - bit := uint((k[i] >> uint(j)) & 1) - copy(w[0][:], tableGenerator[s*Size:(s+1)*Size]) - diffAdd(&w, swap^bit) - swap = bit - } - for s := 0; s < h; s++ { - double(&w[1], &w[2]) - } - toAffine((*[fp.Size]byte)(k), &w[1], &w[2]) -} - -// ladderMontgomery calculates a generic scalar point multiplication -// The algorithm implemented is the left-to-right Montgomery's ladder. -func ladderMontgomery(k, xP *Key) { - w := [5]fp.Elt{} // [x1, x2, z2, x3, z3] order must be preserved. - w[0] = *(*fp.Elt)(xP) // x1 = xP - fp.SetOne(&w[1]) // x2 = 1 - w[3] = *(*fp.Elt)(xP) // x3 = xP - fp.SetOne(&w[4]) // z3 = 1 - - move := uint(0) - for s := 448 - 1; s >= 0; s-- { - i := s / 8 - j := s % 8 - bit := uint((k[i] >> uint(j)) & 1) - ladderStep(&w, move^bit) - move = bit - } - toAffine((*[fp.Size]byte)(k), &w[1], &w[2]) -} - -func toAffine(k *[fp.Size]byte, x, z *fp.Elt) { - fp.Inv(z, z) - fp.Mul(x, x, z) - _ = fp.ToBytes(k[:], x) -} - -var lowOrderPoints = [3]fp.Elt{ - { /* (0,_,1) point of order 2 on Curve448 */ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - }, - { /* (1,_,1) a point of order 4 on the twist of Curve448 */ - 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - }, - { /* (-1,_,1) point of order 4 on Curve448 */ - 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, 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, - }, -} diff --git a/vendor/github.com/cloudflare/circl/dh/x448/curve_amd64.go b/vendor/github.com/cloudflare/circl/dh/x448/curve_amd64.go deleted file mode 100644 index a0622666..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x448/curve_amd64.go +++ /dev/null @@ -1,30 +0,0 @@ -//go:build amd64 && !purego -// +build amd64,!purego - -package x448 - -import ( - fp "github.com/cloudflare/circl/math/fp448" - "golang.org/x/sys/cpu" -) - -var hasBmi2Adx = cpu.X86.HasBMI2 && cpu.X86.HasADX - -var _ = hasBmi2Adx - -func double(x, z *fp.Elt) { doubleAmd64(x, z) } -func diffAdd(w *[5]fp.Elt, b uint) { diffAddAmd64(w, b) } -func ladderStep(w *[5]fp.Elt, b uint) { ladderStepAmd64(w, b) } -func mulA24(z, x *fp.Elt) { mulA24Amd64(z, x) } - -//go:noescape -func doubleAmd64(x, z *fp.Elt) - -//go:noescape -func diffAddAmd64(w *[5]fp.Elt, b uint) - -//go:noescape -func ladderStepAmd64(w *[5]fp.Elt, b uint) - -//go:noescape -func mulA24Amd64(z, x *fp.Elt) diff --git a/vendor/github.com/cloudflare/circl/dh/x448/curve_amd64.h b/vendor/github.com/cloudflare/circl/dh/x448/curve_amd64.h deleted file mode 100644 index 8c1ae4d0..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x448/curve_amd64.h +++ /dev/null @@ -1,111 +0,0 @@ -#define ladderStepLeg \ - addSub(x2,z2) \ - addSub(x3,z3) \ - integerMulLeg(b0,x2,z3) \ - integerMulLeg(b1,x3,z2) \ - reduceFromDoubleLeg(t0,b0) \ - reduceFromDoubleLeg(t1,b1) \ - addSub(t0,t1) \ - cselect(x2,x3,regMove) \ - cselect(z2,z3,regMove) \ - integerSqrLeg(b0,t0) \ - integerSqrLeg(b1,t1) \ - reduceFromDoubleLeg(x3,b0) \ - reduceFromDoubleLeg(z3,b1) \ - integerMulLeg(b0,x1,z3) \ - reduceFromDoubleLeg(z3,b0) \ - integerSqrLeg(b0,x2) \ - integerSqrLeg(b1,z2) \ - reduceFromDoubleLeg(x2,b0) \ - reduceFromDoubleLeg(z2,b1) \ - subtraction(t0,x2,z2) \ - multiplyA24Leg(t1,t0) \ - additionLeg(t1,t1,z2) \ - integerMulLeg(b0,x2,z2) \ - integerMulLeg(b1,t0,t1) \ - reduceFromDoubleLeg(x2,b0) \ - reduceFromDoubleLeg(z2,b1) - -#define ladderStepBmi2Adx \ - addSub(x2,z2) \ - addSub(x3,z3) \ - integerMulAdx(b0,x2,z3) \ - integerMulAdx(b1,x3,z2) \ - reduceFromDoubleAdx(t0,b0) \ - reduceFromDoubleAdx(t1,b1) \ - addSub(t0,t1) \ - cselect(x2,x3,regMove) \ - cselect(z2,z3,regMove) \ - integerSqrAdx(b0,t0) \ - integerSqrAdx(b1,t1) \ - reduceFromDoubleAdx(x3,b0) \ - reduceFromDoubleAdx(z3,b1) \ - integerMulAdx(b0,x1,z3) \ - reduceFromDoubleAdx(z3,b0) \ - integerSqrAdx(b0,x2) \ - integerSqrAdx(b1,z2) \ - reduceFromDoubleAdx(x2,b0) \ - reduceFromDoubleAdx(z2,b1) \ - subtraction(t0,x2,z2) \ - multiplyA24Adx(t1,t0) \ - additionAdx(t1,t1,z2) \ - integerMulAdx(b0,x2,z2) \ - integerMulAdx(b1,t0,t1) \ - reduceFromDoubleAdx(x2,b0) \ - reduceFromDoubleAdx(z2,b1) - -#define difAddLeg \ - addSub(x1,z1) \ - integerMulLeg(b0,z1,ui) \ - reduceFromDoubleLeg(z1,b0) \ - addSub(x1,z1) \ - integerSqrLeg(b0,x1) \ - integerSqrLeg(b1,z1) \ - reduceFromDoubleLeg(x1,b0) \ - reduceFromDoubleLeg(z1,b1) \ - integerMulLeg(b0,x1,z2) \ - integerMulLeg(b1,z1,x2) \ - reduceFromDoubleLeg(x1,b0) \ - reduceFromDoubleLeg(z1,b1) - -#define difAddBmi2Adx \ - addSub(x1,z1) \ - integerMulAdx(b0,z1,ui) \ - reduceFromDoubleAdx(z1,b0) \ - addSub(x1,z1) \ - integerSqrAdx(b0,x1) \ - integerSqrAdx(b1,z1) \ - reduceFromDoubleAdx(x1,b0) \ - reduceFromDoubleAdx(z1,b1) \ - integerMulAdx(b0,x1,z2) \ - integerMulAdx(b1,z1,x2) \ - reduceFromDoubleAdx(x1,b0) \ - reduceFromDoubleAdx(z1,b1) - -#define doubleLeg \ - addSub(x1,z1) \ - integerSqrLeg(b0,x1) \ - integerSqrLeg(b1,z1) \ - reduceFromDoubleLeg(x1,b0) \ - reduceFromDoubleLeg(z1,b1) \ - subtraction(t0,x1,z1) \ - multiplyA24Leg(t1,t0) \ - additionLeg(t1,t1,z1) \ - integerMulLeg(b0,x1,z1) \ - integerMulLeg(b1,t0,t1) \ - reduceFromDoubleLeg(x1,b0) \ - reduceFromDoubleLeg(z1,b1) - -#define doubleBmi2Adx \ - addSub(x1,z1) \ - integerSqrAdx(b0,x1) \ - integerSqrAdx(b1,z1) \ - reduceFromDoubleAdx(x1,b0) \ - reduceFromDoubleAdx(z1,b1) \ - subtraction(t0,x1,z1) \ - multiplyA24Adx(t1,t0) \ - additionAdx(t1,t1,z1) \ - integerMulAdx(b0,x1,z1) \ - integerMulAdx(b1,t0,t1) \ - reduceFromDoubleAdx(x1,b0) \ - reduceFromDoubleAdx(z1,b1) diff --git a/vendor/github.com/cloudflare/circl/dh/x448/curve_amd64.s b/vendor/github.com/cloudflare/circl/dh/x448/curve_amd64.s deleted file mode 100644 index 810aa9e6..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x448/curve_amd64.s +++ /dev/null @@ -1,193 +0,0 @@ -// +build amd64 - -#include "textflag.h" - -// Depends on circl/math/fp448 package -#include "../../math/fp448/fp_amd64.h" -#include "curve_amd64.h" - -// CTE_A24 is (A+2)/4 from Curve448 -#define CTE_A24 39082 - -#define Size 56 - -// multiplyA24Leg multiplies x times CTE_A24 and stores in z -// Uses: AX, DX, R8-R15, FLAGS -// Instr: x86_64, cmov, adx -#define multiplyA24Leg(z,x) \ - MOVQ $CTE_A24, R15; \ - MOVQ 0+x, AX; MULQ R15; MOVQ AX, R8; ;;;;;;;;;;;; MOVQ DX, R9; \ - MOVQ 8+x, AX; MULQ R15; ADDQ AX, R9; ADCQ $0, DX; MOVQ DX, R10; \ - MOVQ 16+x, AX; MULQ R15; ADDQ AX, R10; ADCQ $0, DX; MOVQ DX, R11; \ - MOVQ 24+x, AX; MULQ R15; ADDQ AX, R11; ADCQ $0, DX; MOVQ DX, R12; \ - MOVQ 32+x, AX; MULQ R15; ADDQ AX, R12; ADCQ $0, DX; MOVQ DX, R13; \ - MOVQ 40+x, AX; MULQ R15; ADDQ AX, R13; ADCQ $0, DX; MOVQ DX, R14; \ - MOVQ 48+x, AX; MULQ R15; ADDQ AX, R14; ADCQ $0, DX; \ - MOVQ DX, AX; \ - SHLQ $32, AX; \ - ADDQ DX, R8; MOVQ $0, DX; \ - ADCQ $0, R9; \ - ADCQ $0, R10; \ - ADCQ AX, R11; \ - ADCQ $0, R12; \ - ADCQ $0, R13; \ - ADCQ $0, R14; \ - ADCQ $0, DX; \ - MOVQ DX, AX; \ - SHLQ $32, AX; \ - ADDQ DX, R8; \ - ADCQ $0, R9; \ - ADCQ $0, R10; \ - ADCQ AX, R11; \ - ADCQ $0, R12; \ - ADCQ $0, R13; \ - ADCQ $0, R14; \ - MOVQ R8, 0+z; \ - MOVQ R9, 8+z; \ - MOVQ R10, 16+z; \ - MOVQ R11, 24+z; \ - MOVQ R12, 32+z; \ - MOVQ R13, 40+z; \ - MOVQ R14, 48+z; - -// multiplyA24Adx multiplies x times CTE_A24 and stores in z -// Uses: AX, DX, R8-R14, FLAGS -// Instr: x86_64, bmi2 -#define multiplyA24Adx(z,x) \ - MOVQ $CTE_A24, DX; \ - MULXQ 0+x, R8, R9; \ - MULXQ 8+x, AX, R10; ADDQ AX, R9; \ - MULXQ 16+x, AX, R11; ADCQ AX, R10; \ - MULXQ 24+x, AX, R12; ADCQ AX, R11; \ - MULXQ 32+x, AX, R13; ADCQ AX, R12; \ - MULXQ 40+x, AX, R14; ADCQ AX, R13; \ - MULXQ 48+x, AX, DX; ADCQ AX, R14; \ - ;;;;;;;;;;;;;;;;;;;; ADCQ $0, DX; \ - MOVQ DX, AX; \ - SHLQ $32, AX; \ - ADDQ DX, R8; MOVQ $0, DX; \ - ADCQ $0, R9; \ - ADCQ $0, R10; \ - ADCQ AX, R11; \ - ADCQ $0, R12; \ - ADCQ $0, R13; \ - ADCQ $0, R14; \ - ADCQ $0, DX; \ - MOVQ DX, AX; \ - SHLQ $32, AX; \ - ADDQ DX, R8; \ - ADCQ $0, R9; \ - ADCQ $0, R10; \ - ADCQ AX, R11; \ - ADCQ $0, R12; \ - ADCQ $0, R13; \ - ADCQ $0, R14; \ - MOVQ R8, 0+z; \ - MOVQ R9, 8+z; \ - MOVQ R10, 16+z; \ - MOVQ R11, 24+z; \ - MOVQ R12, 32+z; \ - MOVQ R13, 40+z; \ - MOVQ R14, 48+z; - -#define mulA24Legacy \ - multiplyA24Leg(0(DI),0(SI)) -#define mulA24Bmi2Adx \ - multiplyA24Adx(0(DI),0(SI)) - -// func mulA24Amd64(z, x *fp448.Elt) -TEXT ·mulA24Amd64(SB),NOSPLIT,$0-16 - MOVQ z+0(FP), DI - MOVQ x+8(FP), SI - CHECK_BMI2ADX(LMA24, mulA24Legacy, mulA24Bmi2Adx) - -// func ladderStepAmd64(w *[5]fp448.Elt, b uint) -// ladderStepAmd64 calculates a point addition and doubling as follows: -// (x2,z2) = 2*(x2,z2) and (x3,z3) = (x2,z2)+(x3,z3) using as a difference (x1,-). -// w = {x1,x2,z2,x3,z4} are five fp255.Elt of 56 bytes. -// stack = (t0,t1) are two fp.Elt of fp.Size bytes, and -// (b0,b1) are two-double precision fp.Elt of 2*fp.Size bytes. -TEXT ·ladderStepAmd64(SB),NOSPLIT,$336-16 - // Parameters - #define regWork DI - #define regMove SI - #define x1 0*Size(regWork) - #define x2 1*Size(regWork) - #define z2 2*Size(regWork) - #define x3 3*Size(regWork) - #define z3 4*Size(regWork) - // Local variables - #define t0 0*Size(SP) - #define t1 1*Size(SP) - #define b0 2*Size(SP) - #define b1 4*Size(SP) - MOVQ w+0(FP), regWork - MOVQ b+8(FP), regMove - CHECK_BMI2ADX(LLADSTEP, ladderStepLeg, ladderStepBmi2Adx) - #undef regWork - #undef regMove - #undef x1 - #undef x2 - #undef z2 - #undef x3 - #undef z3 - #undef t0 - #undef t1 - #undef b0 - #undef b1 - -// func diffAddAmd64(work *[5]fp.Elt, swap uint) -// diffAddAmd64 calculates a differential point addition using a precomputed point. -// (x1,z1) = (x1,z1)+(mu) using a difference point (x2,z2) -// work = {mu,x1,z1,x2,z2} are five fp448.Elt of 56 bytes, and -// stack = (b0,b1) are two-double precision fp.Elt of 2*fp.Size bytes. -// This is Equation 7 at https://eprint.iacr.org/2017/264. -TEXT ·diffAddAmd64(SB),NOSPLIT,$224-16 - // Parameters - #define regWork DI - #define regSwap SI - #define ui 0*Size(regWork) - #define x1 1*Size(regWork) - #define z1 2*Size(regWork) - #define x2 3*Size(regWork) - #define z2 4*Size(regWork) - // Local variables - #define b0 0*Size(SP) - #define b1 2*Size(SP) - MOVQ w+0(FP), regWork - MOVQ b+8(FP), regSwap - cswap(x1,x2,regSwap) - cswap(z1,z2,regSwap) - CHECK_BMI2ADX(LDIFADD, difAddLeg, difAddBmi2Adx) - #undef regWork - #undef regSwap - #undef ui - #undef x1 - #undef z1 - #undef x2 - #undef z2 - #undef b0 - #undef b1 - -// func doubleAmd64(x, z *fp448.Elt) -// doubleAmd64 calculates a point doubling (x1,z1) = 2*(x1,z1). -// stack = (t0,t1) are two fp.Elt of fp.Size bytes, and -// (b0,b1) are two-double precision fp.Elt of 2*fp.Size bytes. -TEXT ·doubleAmd64(SB),NOSPLIT,$336-16 - // Parameters - #define x1 0(DI) - #define z1 0(SI) - // Local variables - #define t0 0*Size(SP) - #define t1 1*Size(SP) - #define b0 2*Size(SP) - #define b1 4*Size(SP) - MOVQ x+0(FP), DI - MOVQ z+8(FP), SI - CHECK_BMI2ADX(LDOUB,doubleLeg,doubleBmi2Adx) - #undef x1 - #undef z1 - #undef t0 - #undef t1 - #undef b0 - #undef b1 diff --git a/vendor/github.com/cloudflare/circl/dh/x448/curve_generic.go b/vendor/github.com/cloudflare/circl/dh/x448/curve_generic.go deleted file mode 100644 index b0b65ccf..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x448/curve_generic.go +++ /dev/null @@ -1,100 +0,0 @@ -package x448 - -import ( - "encoding/binary" - "math/bits" - - "github.com/cloudflare/circl/math/fp448" -) - -func doubleGeneric(x, z *fp448.Elt) { - t0, t1 := &fp448.Elt{}, &fp448.Elt{} - fp448.AddSub(x, z) - fp448.Sqr(x, x) - fp448.Sqr(z, z) - fp448.Sub(t0, x, z) - mulA24Generic(t1, t0) - fp448.Add(t1, t1, z) - fp448.Mul(x, x, z) - fp448.Mul(z, t0, t1) -} - -func diffAddGeneric(w *[5]fp448.Elt, b uint) { - mu, x1, z1, x2, z2 := &w[0], &w[1], &w[2], &w[3], &w[4] - fp448.Cswap(x1, x2, b) - fp448.Cswap(z1, z2, b) - fp448.AddSub(x1, z1) - fp448.Mul(z1, z1, mu) - fp448.AddSub(x1, z1) - fp448.Sqr(x1, x1) - fp448.Sqr(z1, z1) - fp448.Mul(x1, x1, z2) - fp448.Mul(z1, z1, x2) -} - -func ladderStepGeneric(w *[5]fp448.Elt, b uint) { - x1, x2, z2, x3, z3 := &w[0], &w[1], &w[2], &w[3], &w[4] - t0 := &fp448.Elt{} - t1 := &fp448.Elt{} - fp448.AddSub(x2, z2) - fp448.AddSub(x3, z3) - fp448.Mul(t0, x2, z3) - fp448.Mul(t1, x3, z2) - fp448.AddSub(t0, t1) - fp448.Cmov(x2, x3, b) - fp448.Cmov(z2, z3, b) - fp448.Sqr(x3, t0) - fp448.Sqr(z3, t1) - fp448.Mul(z3, x1, z3) - fp448.Sqr(x2, x2) - fp448.Sqr(z2, z2) - fp448.Sub(t0, x2, z2) - mulA24Generic(t1, t0) - fp448.Add(t1, t1, z2) - fp448.Mul(x2, x2, z2) - fp448.Mul(z2, t0, t1) -} - -func mulA24Generic(z, x *fp448.Elt) { - const A24 = 39082 - const n = 8 - var xx [7]uint64 - for i := range xx { - xx[i] = binary.LittleEndian.Uint64(x[i*n : (i+1)*n]) - } - h0, l0 := bits.Mul64(xx[0], A24) - h1, l1 := bits.Mul64(xx[1], A24) - h2, l2 := bits.Mul64(xx[2], A24) - h3, l3 := bits.Mul64(xx[3], A24) - h4, l4 := bits.Mul64(xx[4], A24) - h5, l5 := bits.Mul64(xx[5], A24) - h6, l6 := bits.Mul64(xx[6], A24) - - l1, c0 := bits.Add64(h0, l1, 0) - l2, c1 := bits.Add64(h1, l2, c0) - l3, c2 := bits.Add64(h2, l3, c1) - l4, c3 := bits.Add64(h3, l4, c2) - l5, c4 := bits.Add64(h4, l5, c3) - l6, c5 := bits.Add64(h5, l6, c4) - l7, _ := bits.Add64(h6, 0, c5) - - l0, c0 = bits.Add64(l0, l7, 0) - l1, c1 = bits.Add64(l1, 0, c0) - l2, c2 = bits.Add64(l2, 0, c1) - l3, c3 = bits.Add64(l3, l7<<32, c2) - l4, c4 = bits.Add64(l4, 0, c3) - l5, c5 = bits.Add64(l5, 0, c4) - l6, l7 = bits.Add64(l6, 0, c5) - - xx[0], c0 = bits.Add64(l0, l7, 0) - xx[1], c1 = bits.Add64(l1, 0, c0) - xx[2], c2 = bits.Add64(l2, 0, c1) - xx[3], c3 = bits.Add64(l3, l7<<32, c2) - xx[4], c4 = bits.Add64(l4, 0, c3) - xx[5], c5 = bits.Add64(l5, 0, c4) - xx[6], _ = bits.Add64(l6, 0, c5) - - for i := range xx { - binary.LittleEndian.PutUint64(z[i*n:(i+1)*n], xx[i]) - } -} diff --git a/vendor/github.com/cloudflare/circl/dh/x448/curve_noasm.go b/vendor/github.com/cloudflare/circl/dh/x448/curve_noasm.go deleted file mode 100644 index 3755b7c8..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x448/curve_noasm.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !amd64 || purego -// +build !amd64 purego - -package x448 - -import fp "github.com/cloudflare/circl/math/fp448" - -func double(x, z *fp.Elt) { doubleGeneric(x, z) } -func diffAdd(w *[5]fp.Elt, b uint) { diffAddGeneric(w, b) } -func ladderStep(w *[5]fp.Elt, b uint) { ladderStepGeneric(w, b) } -func mulA24(z, x *fp.Elt) { mulA24Generic(z, x) } diff --git a/vendor/github.com/cloudflare/circl/dh/x448/doc.go b/vendor/github.com/cloudflare/circl/dh/x448/doc.go deleted file mode 100644 index c02904fe..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x448/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Package x448 provides Diffie-Hellman functions as specified in RFC-7748. - -Validation of public keys. - -The Diffie-Hellman function, as described in RFC-7748 [1], works for any -public key. However, if a different protocol requires contributory -behaviour [2,3], then the public keys must be validated against low-order -points [3,4]. To do that, the Shared function performs this validation -internally and returns false when the public key is invalid (i.e., it -is a low-order point). - -References: - - [1] RFC7748 by Langley, Hamburg, Turner (https://rfc-editor.org/rfc/rfc7748.txt) - - [2] Curve25519 by Bernstein (https://cr.yp.to/ecdh.html) - - [3] Bernstein (https://cr.yp.to/ecdh.html#validate) - - [4] Cremers&Jackson (https://eprint.iacr.org/2019/526) -*/ -package x448 diff --git a/vendor/github.com/cloudflare/circl/dh/x448/key.go b/vendor/github.com/cloudflare/circl/dh/x448/key.go deleted file mode 100644 index 82a07a2b..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x448/key.go +++ /dev/null @@ -1,46 +0,0 @@ -package x448 - -import ( - "crypto/subtle" - - fp "github.com/cloudflare/circl/math/fp448" -) - -// Size is the length in bytes of a X448 key. -const Size = 56 - -// Key represents a X448 key. -type Key [Size]byte - -func (k *Key) clamp(in *Key) *Key { - *k = *in - k[0] &= 252 - k[55] |= 128 - return k -} - -// isValidPubKey verifies if the public key is not a low-order point. -func (k *Key) isValidPubKey() bool { - fp.Modp((*fp.Elt)(k)) - isLowOrder := false - for _, P := range lowOrderPoints { - isLowOrder = isLowOrder || subtle.ConstantTimeCompare(P[:], k[:]) != 0 - } - return !isLowOrder -} - -// KeyGen obtains a public key given a secret key. -func KeyGen(public, secret *Key) { - ladderJoye(public.clamp(secret)) -} - -// Shared calculates Alice's shared key from Alice's secret key and Bob's -// public key returning true on success. A failure case happens when the public -// key is a low-order point, thus the shared key is all-zeros and the function -// returns false. -func Shared(shared, secret, public *Key) bool { - validPk := *public - ok := validPk.isValidPubKey() - ladderMontgomery(shared.clamp(secret), &validPk) - return ok -} diff --git a/vendor/github.com/cloudflare/circl/dh/x448/table.go b/vendor/github.com/cloudflare/circl/dh/x448/table.go deleted file mode 100644 index eef53c30..00000000 --- a/vendor/github.com/cloudflare/circl/dh/x448/table.go +++ /dev/null @@ -1,460 +0,0 @@ -package x448 - -import fp "github.com/cloudflare/circl/math/fp448" - -// tableGenerator contains the set of points: -// -// t[i] = (xi+1)/(xi-1), -// -// where (xi,yi) = 2^iG and G is the generator point -// Size = (448)*(448/8) = 25088 bytes. -var tableGenerator = [448 * fp.Size]byte{ - /* (2^ 0)P */ 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 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, 0x7f, - /* (2^ 1)P */ 0x37, 0xfa, 0xaa, 0x0d, 0x86, 0xa6, 0x24, 0xe9, 0x6c, 0x95, 0x08, 0x34, 0xba, 0x1a, 0x81, 0x3a, 0xae, 0x01, 0xa5, 0xa7, 0x05, 0x85, 0x96, 0x00, 0x06, 0x5a, 0xd7, 0xff, 0xee, 0x8e, 0x8f, 0x94, 0xd2, 0xdc, 0xd7, 0xfc, 0xe7, 0xe5, 0x99, 0x1d, 0x05, 0x46, 0x43, 0xe8, 0xbc, 0x12, 0xb7, 0xeb, 0x30, 0x5e, 0x7a, 0x85, 0x68, 0xed, 0x9d, 0x28, - /* (2^ 2)P */ 0xf1, 0x7d, 0x08, 0x2b, 0x32, 0x4a, 0x62, 0x80, 0x36, 0xe7, 0xa4, 0x76, 0x5a, 0x2a, 0x1e, 0xf7, 0x9e, 0x3c, 0x40, 0x46, 0x9a, 0x1b, 0x61, 0xc1, 0xbf, 0x1a, 0x1b, 0xae, 0x91, 0x80, 0xa3, 0x76, 0x6c, 0xd4, 0x8f, 0xa4, 0xee, 0x26, 0x39, 0x23, 0xa4, 0x80, 0xf4, 0x66, 0x92, 0xe4, 0xe1, 0x18, 0x76, 0xc5, 0xe2, 0x19, 0x87, 0xd5, 0xc3, 0xe8, - /* (2^ 3)P */ 0xfb, 0xc9, 0xf0, 0x07, 0xf2, 0x93, 0xd8, 0x50, 0x36, 0xed, 0xfb, 0xbd, 0xb2, 0xd3, 0xfc, 0xdf, 0xd5, 0x2a, 0x6e, 0x26, 0x09, 0xce, 0xd4, 0x07, 0x64, 0x9f, 0x40, 0x74, 0xad, 0x98, 0x2f, 0x1c, 0xb6, 0xdc, 0x2d, 0x42, 0xff, 0xbf, 0x97, 0xd8, 0xdb, 0xef, 0x99, 0xca, 0x73, 0x99, 0x1a, 0x04, 0x3b, 0x56, 0x2c, 0x1f, 0x87, 0x9d, 0x9f, 0x03, - /* (2^ 4)P */ 0x4c, 0x35, 0x97, 0xf7, 0x81, 0x2c, 0x84, 0xa6, 0xe0, 0xcb, 0xce, 0x37, 0x4c, 0x21, 0x1c, 0x67, 0xfa, 0xab, 0x18, 0x4d, 0xef, 0xd0, 0xf0, 0x44, 0xa9, 0xfb, 0xc0, 0x8e, 0xda, 0x57, 0xa1, 0xd8, 0xeb, 0x87, 0xf4, 0x17, 0xea, 0x66, 0x0f, 0x16, 0xea, 0xcd, 0x5f, 0x3e, 0x88, 0xea, 0x09, 0x68, 0x40, 0xdf, 0x43, 0xcc, 0x54, 0x61, 0x58, 0xaa, - /* (2^ 5)P */ 0x8d, 0xe7, 0x59, 0xd7, 0x5e, 0x63, 0x37, 0xa7, 0x3f, 0xd1, 0x49, 0x85, 0x01, 0xdd, 0x5e, 0xb3, 0xe6, 0x29, 0xcb, 0x25, 0x93, 0xdd, 0x08, 0x96, 0x83, 0x52, 0x76, 0x85, 0xf5, 0x5d, 0x02, 0xbf, 0xe9, 0x6d, 0x15, 0x27, 0xc1, 0x09, 0xd1, 0x14, 0x4d, 0x6e, 0xe8, 0xaf, 0x59, 0x58, 0x34, 0x9d, 0x2a, 0x99, 0x85, 0x26, 0xbe, 0x4b, 0x1e, 0xb9, - /* (2^ 6)P */ 0x8d, 0xce, 0x94, 0xe2, 0x18, 0x56, 0x0d, 0x82, 0x8e, 0xdf, 0x85, 0x01, 0x8f, 0x93, 0x3c, 0xc6, 0xbd, 0x61, 0xfb, 0xf4, 0x22, 0xc5, 0x16, 0x87, 0xd1, 0xb1, 0x9e, 0x09, 0xc5, 0x83, 0x2e, 0x4a, 0x07, 0x88, 0xee, 0xe0, 0x29, 0x8d, 0x2e, 0x1f, 0x88, 0xad, 0xfd, 0x18, 0x93, 0xb7, 0xed, 0x42, 0x86, 0x78, 0xf0, 0xb8, 0x70, 0xbe, 0x01, 0x67, - /* (2^ 7)P */ 0xdf, 0x62, 0x2d, 0x94, 0xc7, 0x35, 0x23, 0xda, 0x27, 0xbb, 0x2b, 0xdb, 0x30, 0x80, 0x68, 0x16, 0xa3, 0xae, 0xd7, 0xd2, 0xa7, 0x7c, 0xbf, 0x6a, 0x1d, 0x83, 0xde, 0x96, 0x0a, 0x43, 0xb6, 0x30, 0x37, 0xd6, 0xee, 0x63, 0x59, 0x9a, 0xbf, 0xa3, 0x30, 0x6c, 0xaf, 0x0c, 0xee, 0x3d, 0xcb, 0x35, 0x4b, 0x55, 0x5f, 0x84, 0x85, 0xcb, 0x4f, 0x1e, - /* (2^ 8)P */ 0x9d, 0x04, 0x68, 0x89, 0xa4, 0xa9, 0x0d, 0x87, 0xc1, 0x70, 0xf1, 0xeb, 0xfb, 0x47, 0x0a, 0xf0, 0xde, 0x67, 0xb7, 0x94, 0xcd, 0x36, 0x43, 0xa5, 0x49, 0x43, 0x67, 0xc3, 0xee, 0x3c, 0x6b, 0xec, 0xd0, 0x1a, 0xf4, 0xad, 0xef, 0x06, 0x4a, 0xe8, 0x46, 0x24, 0xd7, 0x93, 0xbf, 0xf0, 0xe3, 0x81, 0x61, 0xec, 0xea, 0x64, 0xfe, 0x67, 0xeb, 0xc7, - /* (2^ 9)P */ 0x95, 0x45, 0x79, 0xcf, 0x2c, 0xfd, 0x9b, 0xfe, 0x84, 0x46, 0x4b, 0x8f, 0xa1, 0xcf, 0xc3, 0x04, 0x94, 0x78, 0xdb, 0xc9, 0xa6, 0x01, 0x75, 0xa4, 0xb4, 0x93, 0x72, 0x43, 0xa7, 0x7d, 0xda, 0x31, 0x38, 0x54, 0xab, 0x4e, 0x3f, 0x89, 0xa6, 0xab, 0x57, 0xc0, 0x16, 0x65, 0xdb, 0x92, 0x96, 0xe4, 0xc8, 0xae, 0xe7, 0x4c, 0x7a, 0xeb, 0xbb, 0x5a, - /* (2^ 10)P */ 0xbe, 0xfe, 0x86, 0xc3, 0x97, 0xe0, 0x6a, 0x18, 0x20, 0x21, 0xca, 0x22, 0x55, 0xa1, 0xeb, 0xf5, 0x74, 0xe5, 0xc9, 0x59, 0xa7, 0x92, 0x65, 0x15, 0x08, 0x71, 0xd1, 0x09, 0x7e, 0x83, 0xfc, 0xbc, 0x5a, 0x93, 0x38, 0x0d, 0x43, 0x42, 0xfd, 0x76, 0x30, 0xe8, 0x63, 0x60, 0x09, 0x8d, 0x6c, 0xd3, 0xf8, 0x56, 0x3d, 0x68, 0x47, 0xab, 0xa0, 0x1d, - /* (2^ 11)P */ 0x38, 0x50, 0x1c, 0xb1, 0xac, 0x88, 0x8f, 0x38, 0xe3, 0x69, 0xe6, 0xfc, 0x4f, 0x8f, 0xe1, 0x9b, 0xb1, 0x1a, 0x09, 0x39, 0x19, 0xdf, 0xcd, 0x98, 0x7b, 0x64, 0x42, 0xf6, 0x11, 0xea, 0xc7, 0xe8, 0x92, 0x65, 0x00, 0x2c, 0x75, 0xb5, 0x94, 0x1e, 0x5b, 0xa6, 0x66, 0x81, 0x77, 0xf3, 0x39, 0x94, 0xac, 0xbd, 0xe4, 0x2a, 0x66, 0x84, 0x9c, 0x60, - /* (2^ 12)P */ 0xb5, 0xb6, 0xd9, 0x03, 0x67, 0xa4, 0xa8, 0x0a, 0x4a, 0x2b, 0x9d, 0xfa, 0x13, 0xe1, 0x99, 0x25, 0x4a, 0x5c, 0x67, 0xb9, 0xb2, 0xb7, 0xdd, 0x1e, 0xaf, 0xeb, 0x63, 0x41, 0xb6, 0xb9, 0xa0, 0x87, 0x0a, 0xe0, 0x06, 0x07, 0xaa, 0x97, 0xf8, 0xf9, 0x38, 0x4f, 0xdf, 0x0c, 0x40, 0x7c, 0xc3, 0x98, 0xa9, 0x74, 0xf1, 0x5d, 0xda, 0xd1, 0xc0, 0x0a, - /* (2^ 13)P */ 0xf2, 0x0a, 0xab, 0xab, 0x94, 0x50, 0xf0, 0xa3, 0x6f, 0xc6, 0x66, 0xba, 0xa6, 0xdc, 0x44, 0xdd, 0xd6, 0x08, 0xf4, 0xd3, 0xed, 0xb1, 0x40, 0x93, 0xee, 0xf6, 0xb8, 0x8e, 0xb4, 0x7c, 0xb9, 0x82, 0xc9, 0x9d, 0x45, 0x3b, 0x8e, 0x10, 0xcb, 0x70, 0x1e, 0xba, 0x3c, 0x62, 0x50, 0xda, 0xa9, 0x93, 0xb5, 0xd7, 0xd0, 0x6f, 0x29, 0x52, 0x95, 0xae, - /* (2^ 14)P */ 0x14, 0x68, 0x69, 0x23, 0xa8, 0x44, 0x87, 0x9e, 0x22, 0x91, 0xe8, 0x92, 0xdf, 0xf7, 0xae, 0xba, 0x1c, 0x96, 0xe1, 0xc3, 0x94, 0xed, 0x6c, 0x95, 0xae, 0x96, 0xa7, 0x15, 0x9f, 0xf1, 0x17, 0x11, 0x92, 0x42, 0xd5, 0xcd, 0x18, 0xe7, 0xa9, 0xb5, 0x2f, 0xcd, 0xde, 0x6c, 0xc9, 0x7d, 0xfc, 0x7e, 0xbd, 0x7f, 0x10, 0x3d, 0x01, 0x00, 0x8d, 0x95, - /* (2^ 15)P */ 0x3b, 0x76, 0x72, 0xae, 0xaf, 0x84, 0xf2, 0xf7, 0xd1, 0x6d, 0x13, 0x9c, 0x47, 0xe1, 0xb7, 0xa3, 0x19, 0x16, 0xee, 0x75, 0x45, 0xf6, 0x1a, 0x7b, 0x78, 0x49, 0x79, 0x05, 0x86, 0xf0, 0x7f, 0x9f, 0xfc, 0xc4, 0xbd, 0x86, 0xf3, 0x41, 0xa7, 0xfe, 0x01, 0xd5, 0x67, 0x16, 0x10, 0x5b, 0xa5, 0x16, 0xf3, 0x7f, 0x60, 0xce, 0xd2, 0x0c, 0x8e, 0x4b, - /* (2^ 16)P */ 0x4a, 0x07, 0x99, 0x4a, 0x0f, 0x74, 0x91, 0x14, 0x68, 0xb9, 0x48, 0xb7, 0x44, 0x77, 0x9b, 0x4a, 0xe0, 0x68, 0x0e, 0x43, 0x4d, 0x98, 0x98, 0xbf, 0xa8, 0x3a, 0xb7, 0x6d, 0x2a, 0x9a, 0x77, 0x5f, 0x62, 0xf5, 0x6b, 0x4a, 0xb7, 0x7d, 0xe5, 0x09, 0x6b, 0xc0, 0x8b, 0x9c, 0x88, 0x37, 0x33, 0xf2, 0x41, 0xac, 0x22, 0x1f, 0xcf, 0x3b, 0x82, 0x34, - /* (2^ 17)P */ 0x00, 0xc3, 0x78, 0x42, 0x32, 0x2e, 0xdc, 0xda, 0xb1, 0x96, 0x21, 0xa4, 0xe4, 0xbb, 0xe9, 0x9d, 0xbb, 0x0f, 0x93, 0xed, 0x26, 0x3d, 0xb5, 0xdb, 0x94, 0x31, 0x37, 0x07, 0xa2, 0xb2, 0xd5, 0x99, 0x0d, 0x93, 0xe1, 0xce, 0x3f, 0x0b, 0x96, 0x82, 0x47, 0xfe, 0x60, 0x6f, 0x8f, 0x61, 0x88, 0xd7, 0x05, 0x95, 0x0b, 0x46, 0x06, 0xb7, 0x32, 0x06, - /* (2^ 18)P */ 0x44, 0xf5, 0x34, 0xdf, 0x2f, 0x9c, 0x5d, 0x9f, 0x53, 0x5c, 0x42, 0x8f, 0xc9, 0xdc, 0xd8, 0x40, 0xa2, 0xe7, 0x6a, 0x4a, 0x05, 0xf7, 0x86, 0x77, 0x2b, 0xae, 0x37, 0xed, 0x48, 0xfb, 0xf7, 0x62, 0x7c, 0x17, 0x59, 0x92, 0x41, 0x61, 0x93, 0x38, 0x30, 0xd1, 0xef, 0x54, 0x54, 0x03, 0x17, 0x57, 0x91, 0x15, 0x11, 0x33, 0xb5, 0xfa, 0xfb, 0x17, - /* (2^ 19)P */ 0x29, 0xbb, 0xd4, 0xb4, 0x9c, 0xf1, 0x72, 0x94, 0xce, 0x6a, 0x29, 0xa8, 0x89, 0x18, 0x19, 0xf7, 0xb7, 0xcc, 0xee, 0x9a, 0x02, 0xe3, 0xc0, 0xb1, 0xe0, 0xee, 0x83, 0x78, 0xb4, 0x9e, 0x07, 0x87, 0xdf, 0xb0, 0x82, 0x26, 0x4e, 0xa4, 0x0c, 0x33, 0xaf, 0x40, 0x59, 0xb6, 0xdd, 0x52, 0x45, 0xf0, 0xb4, 0xf6, 0xe8, 0x4e, 0x4e, 0x79, 0x1a, 0x5d, - /* (2^ 20)P */ 0x27, 0x33, 0x4d, 0x4c, 0x6b, 0x4f, 0x75, 0xb1, 0xbc, 0x1f, 0xab, 0x5b, 0x2b, 0xf0, 0x1c, 0x57, 0x86, 0xdd, 0xfd, 0x60, 0xb0, 0x8c, 0xe7, 0x9a, 0xe5, 0x5c, 0xeb, 0x11, 0x3a, 0xda, 0x22, 0x25, 0x99, 0x06, 0x8d, 0xf4, 0xaf, 0x29, 0x7a, 0xc9, 0xe5, 0xd2, 0x16, 0x9e, 0xd4, 0x63, 0x1d, 0x64, 0xa6, 0x47, 0x96, 0x37, 0x6f, 0x93, 0x2c, 0xcc, - /* (2^ 21)P */ 0xc1, 0x94, 0x74, 0x86, 0x75, 0xf2, 0x91, 0x58, 0x23, 0x85, 0x63, 0x76, 0x54, 0xc7, 0xb4, 0x8c, 0xbc, 0x4e, 0xc4, 0xa7, 0xba, 0xa0, 0x55, 0x26, 0x71, 0xd5, 0x33, 0x72, 0xc9, 0xad, 0x1e, 0xf9, 0x5d, 0x78, 0x70, 0x93, 0x4e, 0x85, 0xfc, 0x39, 0x06, 0x73, 0x76, 0xff, 0xe8, 0x64, 0x69, 0x42, 0x45, 0xb2, 0x69, 0xb5, 0x32, 0xe7, 0x2c, 0xde, - /* (2^ 22)P */ 0xde, 0x16, 0xd8, 0x33, 0x49, 0x32, 0xe9, 0x0e, 0x3a, 0x60, 0xee, 0x2e, 0x24, 0x75, 0xe3, 0x9c, 0x92, 0x07, 0xdb, 0xad, 0x92, 0xf5, 0x11, 0xdf, 0xdb, 0xb0, 0x17, 0x5c, 0xd6, 0x1a, 0x70, 0x00, 0xb7, 0xe2, 0x18, 0xec, 0xdc, 0xc2, 0x02, 0x93, 0xb3, 0xc8, 0x3f, 0x4f, 0x1b, 0x96, 0xe6, 0x33, 0x8c, 0xfb, 0xcc, 0xa5, 0x4e, 0xe8, 0xe7, 0x11, - /* (2^ 23)P */ 0x05, 0x7a, 0x74, 0x52, 0xf8, 0xdf, 0x0d, 0x7c, 0x6a, 0x1a, 0x4e, 0x9a, 0x02, 0x1d, 0xae, 0x77, 0xf8, 0x8e, 0xf9, 0xa2, 0x38, 0x54, 0x50, 0xb2, 0x2c, 0x08, 0x9d, 0x9b, 0x9f, 0xfb, 0x2b, 0x06, 0xde, 0x9d, 0xc2, 0x03, 0x0b, 0x22, 0x2b, 0x10, 0x5b, 0x3a, 0x73, 0x29, 0x8e, 0x3e, 0x37, 0x08, 0x2c, 0x3b, 0xf8, 0x80, 0xc1, 0x66, 0x1e, 0x98, - /* (2^ 24)P */ 0xd8, 0xd6, 0x3e, 0xcd, 0x63, 0x8c, 0x2b, 0x41, 0x81, 0xc0, 0x0c, 0x06, 0x87, 0xd6, 0xe7, 0x92, 0xfe, 0xf1, 0x0c, 0x4a, 0x84, 0x5b, 0xaf, 0x40, 0x53, 0x6f, 0x60, 0xd6, 0x6b, 0x76, 0x4b, 0xc2, 0xad, 0xc9, 0xb6, 0xb6, 0x6a, 0xa2, 0xb3, 0xf5, 0xf5, 0xc2, 0x55, 0x83, 0xb2, 0xd3, 0xe9, 0x41, 0x6c, 0x63, 0x51, 0xb8, 0x81, 0x74, 0xc8, 0x2c, - /* (2^ 25)P */ 0xb2, 0xaf, 0x1c, 0xee, 0x07, 0xb0, 0x58, 0xa8, 0x2c, 0x6a, 0xc9, 0x2d, 0x62, 0x28, 0x75, 0x0c, 0x40, 0xb6, 0x11, 0x33, 0x96, 0x80, 0x28, 0x6d, 0xd5, 0x9e, 0x87, 0x90, 0x01, 0x66, 0x1d, 0x1c, 0xf8, 0xb4, 0x92, 0xac, 0x38, 0x18, 0x05, 0xc2, 0x4c, 0x4b, 0x54, 0x7d, 0x80, 0x46, 0x87, 0x2d, 0x99, 0x8e, 0x70, 0x80, 0x69, 0x71, 0x8b, 0xed, - /* (2^ 26)P */ 0x37, 0xa7, 0x6b, 0x71, 0x36, 0x75, 0x8e, 0xff, 0x0f, 0x42, 0xda, 0x5a, 0x46, 0xa6, 0x97, 0x79, 0x7e, 0x30, 0xb3, 0x8f, 0xc7, 0x3a, 0xa0, 0xcb, 0x1d, 0x9c, 0x78, 0x77, 0x36, 0xc2, 0xe7, 0xf4, 0x2f, 0x29, 0x07, 0xb1, 0x07, 0xfd, 0xed, 0x1b, 0x39, 0x77, 0x06, 0x38, 0x77, 0x0f, 0x50, 0x31, 0x12, 0xbf, 0x92, 0xbf, 0x72, 0x79, 0x54, 0xa9, - /* (2^ 27)P */ 0xbd, 0x4d, 0x46, 0x6b, 0x1a, 0x80, 0x46, 0x2d, 0xed, 0xfd, 0x64, 0x6d, 0x94, 0xbc, 0x4a, 0x6e, 0x0c, 0x12, 0xf6, 0x12, 0xab, 0x54, 0x88, 0xd3, 0x85, 0xac, 0x51, 0xae, 0x6f, 0xca, 0xc4, 0xb7, 0xec, 0x22, 0x54, 0x6d, 0x80, 0xb2, 0x1c, 0x63, 0x33, 0x76, 0x6b, 0x8e, 0x6d, 0x59, 0xcd, 0x73, 0x92, 0x5f, 0xff, 0xad, 0x10, 0x35, 0x70, 0x5f, - /* (2^ 28)P */ 0xb3, 0x84, 0xde, 0xc8, 0x04, 0x43, 0x63, 0xfa, 0x29, 0xd9, 0xf0, 0x69, 0x65, 0x5a, 0x0c, 0xe8, 0x2e, 0x0b, 0xfe, 0xb0, 0x7a, 0x42, 0xb3, 0xc3, 0xfc, 0xe6, 0xb8, 0x92, 0x29, 0xae, 0xed, 0xec, 0xd5, 0xe8, 0x4a, 0xa1, 0xbd, 0x3b, 0xd3, 0xc0, 0x07, 0xab, 0x65, 0x65, 0x35, 0x9a, 0xa6, 0x5e, 0x78, 0x18, 0x76, 0x1c, 0x15, 0x49, 0xe6, 0x75, - /* (2^ 29)P */ 0x45, 0xb3, 0x92, 0xa9, 0xc3, 0xb8, 0x11, 0x68, 0x64, 0x3a, 0x83, 0x5d, 0xa8, 0x94, 0x6a, 0x9d, 0xaa, 0x27, 0x9f, 0x98, 0x5d, 0xc0, 0x29, 0xf0, 0xc0, 0x4b, 0x14, 0x3c, 0x05, 0xe7, 0xf8, 0xbd, 0x38, 0x22, 0x96, 0x75, 0x65, 0x5e, 0x0d, 0x3f, 0xbb, 0x6f, 0xe8, 0x3f, 0x96, 0x76, 0x9f, 0xba, 0xd9, 0x44, 0x92, 0x96, 0x22, 0xe7, 0x52, 0xe7, - /* (2^ 30)P */ 0xf4, 0xa3, 0x95, 0x90, 0x47, 0xdf, 0x7d, 0xdc, 0xf4, 0x13, 0x87, 0x67, 0x7d, 0x4f, 0x9d, 0xa0, 0x00, 0x46, 0x72, 0x08, 0xc3, 0xa2, 0x7a, 0x3e, 0xe7, 0x6d, 0x52, 0x7c, 0x11, 0x36, 0x50, 0x83, 0x89, 0x64, 0xcb, 0x1f, 0x08, 0x83, 0x46, 0xcb, 0xac, 0xa6, 0xd8, 0x9c, 0x1b, 0xe8, 0x05, 0x47, 0xc7, 0x26, 0x06, 0x83, 0x39, 0xe9, 0xb1, 0x1c, - /* (2^ 31)P */ 0x11, 0xe8, 0xc8, 0x42, 0xbf, 0x30, 0x9c, 0xa3, 0xf1, 0x85, 0x96, 0x95, 0x4f, 0x4f, 0x52, 0xa2, 0xf5, 0x8b, 0x68, 0x24, 0x16, 0xac, 0x9b, 0xa9, 0x27, 0x28, 0x0e, 0x84, 0x03, 0x46, 0x22, 0x5f, 0xf7, 0x0d, 0xa6, 0x85, 0x88, 0xc1, 0x45, 0x4b, 0x85, 0x1a, 0x10, 0x7f, 0xc9, 0x94, 0x20, 0xb0, 0x04, 0x28, 0x12, 0x30, 0xb9, 0xe6, 0x40, 0x6b, - /* (2^ 32)P */ 0xac, 0x1b, 0x57, 0xb6, 0x42, 0xdb, 0x81, 0x8d, 0x76, 0xfd, 0x9b, 0x1c, 0x29, 0x30, 0xd5, 0x3a, 0xcc, 0x53, 0xd9, 0x26, 0x7a, 0x0f, 0x9c, 0x2e, 0x79, 0xf5, 0x62, 0xeb, 0x61, 0x9d, 0x9b, 0x80, 0x39, 0xcd, 0x60, 0x2e, 0x1f, 0x08, 0x22, 0xbc, 0x19, 0xb3, 0x2a, 0x43, 0x44, 0xf2, 0x4e, 0x66, 0xf4, 0x36, 0xa6, 0xa7, 0xbc, 0xa4, 0x15, 0x7e, - /* (2^ 33)P */ 0xc1, 0x90, 0x8a, 0xde, 0xff, 0x78, 0xc3, 0x73, 0x16, 0xee, 0x76, 0xa0, 0x84, 0x60, 0x8d, 0xe6, 0x82, 0x0f, 0xde, 0x4e, 0xc5, 0x99, 0x34, 0x06, 0x90, 0x44, 0x55, 0xf8, 0x91, 0xd8, 0xe1, 0xe4, 0x2c, 0x8a, 0xde, 0x94, 0x1e, 0x78, 0x25, 0x3d, 0xfd, 0xd8, 0x59, 0x7d, 0xaf, 0x6e, 0xbe, 0x96, 0xbe, 0x3c, 0x16, 0x23, 0x0f, 0x4c, 0xa4, 0x28, - /* (2^ 34)P */ 0xba, 0x11, 0x35, 0x57, 0x03, 0xb6, 0xf4, 0x24, 0x89, 0xb8, 0x5a, 0x0d, 0x50, 0x9c, 0xaa, 0x51, 0x7f, 0xa4, 0x0e, 0xfc, 0x71, 0xb3, 0x3b, 0xf1, 0x96, 0x50, 0x23, 0x15, 0xf5, 0xf5, 0xd4, 0x23, 0xdc, 0x8b, 0x26, 0x9e, 0xae, 0xb7, 0x50, 0xcd, 0xc4, 0x25, 0xf6, 0x75, 0x40, 0x9c, 0x37, 0x79, 0x33, 0x60, 0xd4, 0x4b, 0x13, 0x32, 0xee, 0xe2, - /* (2^ 35)P */ 0x43, 0xb8, 0x56, 0x59, 0xf0, 0x68, 0x23, 0xb3, 0xea, 0x70, 0x58, 0x4c, 0x1e, 0x5a, 0x16, 0x54, 0x03, 0xb2, 0xf4, 0x73, 0xb6, 0xd9, 0x5c, 0x9c, 0x6f, 0xcf, 0x82, 0x2e, 0x54, 0x15, 0x46, 0x2c, 0xa3, 0xda, 0x4e, 0x87, 0xf5, 0x2b, 0xba, 0x91, 0xa3, 0xa0, 0x89, 0xba, 0x48, 0x2b, 0xfa, 0x64, 0x02, 0x7f, 0x78, 0x03, 0xd1, 0xe8, 0x3b, 0xe9, - /* (2^ 36)P */ 0x15, 0xa4, 0x71, 0xd4, 0x0c, 0x24, 0xe9, 0x07, 0xa1, 0x43, 0xf4, 0x7f, 0xbb, 0xa2, 0xa6, 0x6b, 0xfa, 0xb7, 0xea, 0x58, 0xd1, 0x96, 0xb0, 0x24, 0x5c, 0xc7, 0x37, 0x4e, 0x60, 0x0f, 0x40, 0xf2, 0x2f, 0x44, 0x70, 0xea, 0x80, 0x63, 0xfe, 0xfc, 0x46, 0x59, 0x12, 0x27, 0xb5, 0x27, 0xfd, 0xb7, 0x73, 0x0b, 0xca, 0x8b, 0xc2, 0xd3, 0x71, 0x08, - /* (2^ 37)P */ 0x26, 0x0e, 0xd7, 0x52, 0x6f, 0xf1, 0xf2, 0x9d, 0xb8, 0x3d, 0xbd, 0xd4, 0x75, 0x97, 0xd8, 0xbf, 0xa8, 0x86, 0x96, 0xa5, 0x80, 0xa0, 0x45, 0x75, 0xf6, 0x77, 0x71, 0xdb, 0x77, 0x96, 0x55, 0x99, 0x31, 0xd0, 0x4f, 0x34, 0xf4, 0x35, 0x39, 0x41, 0xd3, 0x7d, 0xf7, 0xe2, 0x74, 0xde, 0xbe, 0x5b, 0x1f, 0x39, 0x10, 0x21, 0xa3, 0x4d, 0x3b, 0xc8, - /* (2^ 38)P */ 0x04, 0x00, 0x2a, 0x45, 0xb2, 0xaf, 0x9b, 0x18, 0x6a, 0xeb, 0x96, 0x28, 0xa4, 0x77, 0xd0, 0x13, 0xcf, 0x17, 0x65, 0xe8, 0xc5, 0x81, 0x28, 0xad, 0x39, 0x7a, 0x0b, 0xaa, 0x55, 0x2b, 0xf3, 0xfc, 0x86, 0x40, 0xad, 0x0d, 0x1e, 0x28, 0xa2, 0x2d, 0xc5, 0xd6, 0x04, 0x15, 0xa2, 0x30, 0x3d, 0x12, 0x8e, 0xd6, 0xb5, 0xf7, 0x69, 0xbb, 0x84, 0x20, - /* (2^ 39)P */ 0xd7, 0x7a, 0x77, 0x2c, 0xfb, 0x81, 0x80, 0xe9, 0x1e, 0xc6, 0x36, 0x31, 0x79, 0xc3, 0x7c, 0xa9, 0x57, 0x6b, 0xb5, 0x70, 0xfb, 0xe4, 0xa1, 0xff, 0xfd, 0x21, 0xa5, 0x7c, 0xfa, 0x44, 0xba, 0x0d, 0x96, 0x3d, 0xc4, 0x5c, 0x39, 0x52, 0x87, 0xd7, 0x22, 0x0f, 0x52, 0x88, 0x91, 0x87, 0x96, 0xac, 0xfa, 0x3b, 0xdf, 0xdc, 0x83, 0x8c, 0x99, 0x29, - /* (2^ 40)P */ 0x98, 0x6b, 0x3a, 0x8d, 0x83, 0x17, 0xe1, 0x62, 0xd8, 0x80, 0x4c, 0x97, 0xce, 0x6b, 0xaa, 0x10, 0xa7, 0xc4, 0xe9, 0xeb, 0xa5, 0xfb, 0xc9, 0xdd, 0x2d, 0xeb, 0xfc, 0x9a, 0x71, 0xcd, 0x68, 0x6e, 0xc0, 0x35, 0x64, 0x62, 0x1b, 0x95, 0x12, 0xe8, 0x53, 0xec, 0xf0, 0xf4, 0x86, 0x86, 0x78, 0x18, 0xc4, 0xc6, 0xbc, 0x5a, 0x59, 0x8f, 0x7c, 0x7e, - /* (2^ 41)P */ 0x7f, 0xd7, 0x1e, 0xc5, 0x83, 0xdc, 0x1f, 0xbe, 0x0b, 0xcf, 0x2e, 0x01, 0x01, 0xed, 0xac, 0x17, 0x3b, 0xed, 0xa4, 0x30, 0x96, 0x0e, 0x14, 0x7e, 0x19, 0x2b, 0xa5, 0x67, 0x1e, 0xb3, 0x34, 0x03, 0xa8, 0xbb, 0x0a, 0x7d, 0x08, 0x2d, 0xd5, 0x53, 0x19, 0x6f, 0x13, 0xd5, 0xc0, 0x90, 0x8a, 0xcc, 0xc9, 0x5c, 0xab, 0x24, 0xd7, 0x03, 0xf6, 0x57, - /* (2^ 42)P */ 0x49, 0xcb, 0xb4, 0x96, 0x5f, 0xa6, 0xf8, 0x71, 0x6f, 0x59, 0xad, 0x05, 0x24, 0x2d, 0xaf, 0x67, 0xa8, 0xbe, 0x95, 0xdf, 0x0d, 0x28, 0x5a, 0x7f, 0x6e, 0x87, 0x8c, 0x6e, 0x67, 0x0c, 0xf4, 0xe0, 0x1c, 0x30, 0xc2, 0x66, 0xae, 0x20, 0xa1, 0x34, 0xec, 0x9c, 0xbc, 0xae, 0x3d, 0xa1, 0x28, 0x28, 0x95, 0x1d, 0xc9, 0x3a, 0xa8, 0xfd, 0xfc, 0xa1, - /* (2^ 43)P */ 0xe2, 0x2b, 0x9d, 0xed, 0x02, 0x99, 0x67, 0xbb, 0x2e, 0x16, 0x62, 0x05, 0x70, 0xc7, 0x27, 0xb9, 0x1c, 0x3f, 0xf2, 0x11, 0x01, 0xd8, 0x51, 0xa4, 0x18, 0x92, 0xa9, 0x5d, 0xfb, 0xa9, 0xe4, 0x42, 0xba, 0x38, 0x34, 0x1a, 0x4a, 0xc5, 0x6a, 0x37, 0xde, 0xa7, 0x0c, 0xb4, 0x7e, 0x7f, 0xde, 0xa6, 0xee, 0xcd, 0x55, 0x57, 0x05, 0x06, 0xfd, 0x5d, - /* (2^ 44)P */ 0x2f, 0x32, 0xcf, 0x2e, 0x2c, 0x7b, 0xbe, 0x9a, 0x0c, 0x57, 0x35, 0xf8, 0x87, 0xda, 0x9c, 0xec, 0x48, 0xf2, 0xbb, 0xe2, 0xda, 0x10, 0x58, 0x20, 0xc6, 0xd3, 0x87, 0xe9, 0xc7, 0x26, 0xd1, 0x9a, 0x46, 0x87, 0x90, 0xda, 0xdc, 0xde, 0xc3, 0xb3, 0xf2, 0xe8, 0x6f, 0x4a, 0xe6, 0xe8, 0x9d, 0x98, 0x36, 0x20, 0x03, 0x47, 0x15, 0x3f, 0x64, 0x59, - /* (2^ 45)P */ 0xd4, 0x71, 0x49, 0x0a, 0x67, 0x97, 0xaa, 0x3f, 0xf4, 0x1b, 0x3a, 0x6e, 0x5e, 0x17, 0xcc, 0x0a, 0x8f, 0x81, 0x6a, 0x41, 0x38, 0x77, 0x40, 0x8a, 0x11, 0x42, 0x62, 0xd2, 0x50, 0x32, 0x79, 0x78, 0x28, 0xc2, 0x2e, 0x10, 0x01, 0x94, 0x30, 0x4f, 0x7f, 0x18, 0x17, 0x56, 0x85, 0x4e, 0xad, 0xf7, 0xcb, 0x87, 0x3c, 0x3f, 0x50, 0x2c, 0xc0, 0xba, - /* (2^ 46)P */ 0xbc, 0x30, 0x8e, 0x65, 0x8e, 0x57, 0x5b, 0x38, 0x7a, 0xd4, 0x95, 0x52, 0x7a, 0x32, 0x59, 0x69, 0xcd, 0x9d, 0x47, 0x34, 0x5b, 0x55, 0xa5, 0x24, 0x60, 0xdd, 0xc0, 0xc1, 0x62, 0x73, 0x44, 0xae, 0x4c, 0x9c, 0x65, 0x55, 0x1b, 0x9d, 0x8a, 0x29, 0xb0, 0x1a, 0x52, 0xa8, 0xf1, 0xe6, 0x9a, 0xb3, 0xf6, 0xa3, 0xc9, 0x0a, 0x70, 0x7d, 0x0f, 0xee, - /* (2^ 47)P */ 0x77, 0xd3, 0xe5, 0x8e, 0xfa, 0x00, 0xeb, 0x1b, 0x7f, 0xdc, 0x68, 0x3f, 0x92, 0xbd, 0xb7, 0x0b, 0xb7, 0xb5, 0x24, 0xdf, 0xc5, 0x67, 0x53, 0xd4, 0x36, 0x79, 0xc4, 0x7b, 0x57, 0xbc, 0x99, 0x97, 0x60, 0xef, 0xe4, 0x01, 0xa1, 0xa7, 0xaa, 0x12, 0x36, 0x29, 0xb1, 0x03, 0xc2, 0x83, 0x1c, 0x2b, 0x83, 0xef, 0x2e, 0x2c, 0x23, 0x92, 0xfd, 0xd1, - /* (2^ 48)P */ 0x94, 0xef, 0x03, 0x59, 0xfa, 0x8a, 0x18, 0x76, 0xee, 0x58, 0x08, 0x4d, 0x44, 0xce, 0xf1, 0x52, 0x33, 0x49, 0xf6, 0x69, 0x71, 0xe3, 0xa9, 0xbc, 0x86, 0xe3, 0x43, 0xde, 0x33, 0x7b, 0x90, 0x8b, 0x3e, 0x7d, 0xd5, 0x4a, 0xf0, 0x23, 0x99, 0xa6, 0xea, 0x5f, 0x08, 0xe5, 0xb9, 0x49, 0x8b, 0x0d, 0x6a, 0x21, 0xab, 0x07, 0x62, 0xcd, 0xc4, 0xbe, - /* (2^ 49)P */ 0x61, 0xbf, 0x70, 0x14, 0xfa, 0x4e, 0x9e, 0x7c, 0x0c, 0xf8, 0xb2, 0x48, 0x71, 0x62, 0x83, 0xd6, 0xd1, 0xdc, 0x9c, 0x29, 0x66, 0xb1, 0x34, 0x9c, 0x8d, 0xe6, 0x88, 0xaf, 0xbe, 0xdc, 0x4d, 0xeb, 0xb0, 0xe7, 0x28, 0xae, 0xb2, 0x05, 0x56, 0xc6, 0x0e, 0x10, 0x26, 0xab, 0x2c, 0x59, 0x72, 0x03, 0x66, 0xfe, 0x8f, 0x2c, 0x51, 0x2d, 0xdc, 0xae, - /* (2^ 50)P */ 0xdc, 0x63, 0xf1, 0x8b, 0x5c, 0x65, 0x0b, 0xf1, 0xa6, 0x22, 0xe2, 0xd9, 0xdb, 0x49, 0xb1, 0x3c, 0x47, 0xc2, 0xfe, 0xac, 0x86, 0x07, 0x52, 0xec, 0xb0, 0x08, 0x69, 0xfb, 0xd1, 0x06, 0xdc, 0x48, 0x5c, 0x3d, 0xb2, 0x4d, 0xb8, 0x1a, 0x4e, 0xda, 0xb9, 0xc1, 0x2b, 0xab, 0x4b, 0x62, 0x81, 0x21, 0x9a, 0xfc, 0x3d, 0x39, 0x83, 0x11, 0x36, 0xeb, - /* (2^ 51)P */ 0x94, 0xf3, 0x17, 0xef, 0xf9, 0x60, 0x54, 0xc3, 0xd7, 0x27, 0x35, 0xc5, 0x98, 0x5e, 0xf6, 0x63, 0x6c, 0xa0, 0x4a, 0xd3, 0xa3, 0x98, 0xd9, 0x42, 0xe3, 0xf1, 0xf8, 0x81, 0x96, 0xa9, 0xea, 0x6d, 0x4b, 0x8e, 0x33, 0xca, 0x94, 0x0d, 0xa0, 0xf7, 0xbb, 0x64, 0xa3, 0x36, 0x6f, 0xdc, 0x5a, 0x94, 0x42, 0xca, 0x06, 0xb2, 0x2b, 0x9a, 0x9f, 0x71, - /* (2^ 52)P */ 0xec, 0xdb, 0xa6, 0x1f, 0xdf, 0x15, 0x36, 0xa3, 0xda, 0x8a, 0x7a, 0xb6, 0xa7, 0xe3, 0xaf, 0x52, 0xe0, 0x8d, 0xe8, 0xf2, 0x44, 0x20, 0xeb, 0xa1, 0x20, 0xc4, 0x65, 0x3c, 0x7c, 0x6c, 0x49, 0xed, 0x2f, 0x66, 0x23, 0x68, 0x61, 0x91, 0x40, 0x9f, 0x50, 0x19, 0xd1, 0x84, 0xa7, 0xe2, 0xed, 0x34, 0x37, 0xe3, 0xe4, 0x11, 0x7f, 0x87, 0x55, 0x0f, - /* (2^ 53)P */ 0xb3, 0xa1, 0x0f, 0xb0, 0x48, 0xc0, 0x4d, 0x96, 0xa7, 0xcf, 0x5a, 0x81, 0xb8, 0x4a, 0x46, 0xef, 0x0a, 0xd3, 0x40, 0x7e, 0x02, 0xe3, 0x63, 0xaa, 0x50, 0xd1, 0x2a, 0x37, 0x22, 0x4a, 0x7f, 0x4f, 0xb6, 0xf9, 0x01, 0x82, 0x78, 0x3d, 0x93, 0x14, 0x11, 0x8a, 0x90, 0x60, 0xcd, 0x45, 0x4e, 0x7b, 0x42, 0xb9, 0x3e, 0x6e, 0x68, 0x1f, 0x36, 0x41, - /* (2^ 54)P */ 0x13, 0x73, 0x0e, 0x4f, 0x79, 0x93, 0x9e, 0x29, 0x70, 0x7b, 0x4a, 0x59, 0x1a, 0x9a, 0xf4, 0x55, 0x08, 0xf0, 0xdb, 0x17, 0x58, 0xec, 0x64, 0xad, 0x7f, 0x29, 0xeb, 0x3f, 0x85, 0x4e, 0x60, 0x28, 0x98, 0x1f, 0x73, 0x4e, 0xe6, 0xa8, 0xab, 0xd5, 0xd6, 0xfc, 0xa1, 0x36, 0x6d, 0x15, 0xc6, 0x13, 0x83, 0xa0, 0xc2, 0x6e, 0xd9, 0xdb, 0xc9, 0xcc, - /* (2^ 55)P */ 0xff, 0xd8, 0x52, 0xa3, 0xdc, 0x99, 0xcf, 0x3e, 0x19, 0xb3, 0x68, 0xd0, 0xb5, 0x0d, 0xb8, 0xee, 0x3f, 0xef, 0x6e, 0xc0, 0x38, 0x28, 0x44, 0x92, 0x78, 0x91, 0x1a, 0x08, 0x78, 0x6c, 0x65, 0x24, 0xf3, 0xa2, 0x3d, 0xf2, 0xe5, 0x79, 0x62, 0x69, 0x29, 0xf4, 0x22, 0xc5, 0xdb, 0x6a, 0xae, 0xf4, 0x44, 0xa3, 0x6f, 0xc7, 0x86, 0xab, 0xef, 0xef, - /* (2^ 56)P */ 0xbf, 0x54, 0x9a, 0x09, 0x5d, 0x17, 0xd0, 0xde, 0xfb, 0xf5, 0xca, 0xff, 0x13, 0x20, 0x88, 0x82, 0x3a, 0xe2, 0xd0, 0x3b, 0xfb, 0x05, 0x76, 0xd1, 0xc0, 0x02, 0x71, 0x3b, 0x94, 0xe8, 0xc9, 0x84, 0xcf, 0xa4, 0xe9, 0x28, 0x7b, 0xf5, 0x09, 0xc3, 0x2b, 0x22, 0x40, 0xf1, 0x68, 0x24, 0x24, 0x7d, 0x9f, 0x6e, 0xcd, 0xfe, 0xb0, 0x19, 0x61, 0xf5, - /* (2^ 57)P */ 0xe8, 0x63, 0x51, 0xb3, 0x95, 0x6b, 0x7b, 0x74, 0x92, 0x52, 0x45, 0xa4, 0xed, 0xea, 0x0e, 0x0d, 0x2b, 0x01, 0x1e, 0x2c, 0xbc, 0x91, 0x06, 0x69, 0xdb, 0x1f, 0xb5, 0x77, 0x1d, 0x56, 0xf5, 0xb4, 0x02, 0x80, 0x49, 0x56, 0x12, 0xce, 0x86, 0x05, 0xc9, 0xd9, 0xae, 0xf3, 0x6d, 0xe6, 0x3f, 0x40, 0x52, 0xe9, 0x49, 0x2b, 0x31, 0x06, 0x86, 0x14, - /* (2^ 58)P */ 0xf5, 0x09, 0x3b, 0xd2, 0xff, 0xdf, 0x11, 0xa5, 0x1c, 0x99, 0xe8, 0x1b, 0xa4, 0x2c, 0x7d, 0x8e, 0xc8, 0xf7, 0x03, 0x46, 0xfa, 0xb6, 0xde, 0x73, 0x91, 0x7e, 0x5a, 0x7a, 0xd7, 0x9a, 0x5b, 0x80, 0x24, 0x62, 0x5e, 0x92, 0xf1, 0xa3, 0x45, 0xa3, 0x43, 0x92, 0x8a, 0x2a, 0x5b, 0x0c, 0xb4, 0xc8, 0xad, 0x1c, 0xb6, 0x6c, 0x5e, 0x81, 0x18, 0x91, - /* (2^ 59)P */ 0x96, 0xb3, 0xca, 0x2b, 0xe3, 0x7a, 0x59, 0x72, 0x17, 0x74, 0x29, 0x21, 0xe7, 0x78, 0x07, 0xad, 0xda, 0xb6, 0xcd, 0xf9, 0x27, 0x4d, 0xc8, 0xf2, 0x98, 0x22, 0xca, 0xf2, 0x33, 0x74, 0x7a, 0xdd, 0x1e, 0x71, 0xec, 0xe3, 0x3f, 0xe2, 0xa2, 0xd2, 0x38, 0x75, 0xb0, 0xd0, 0x0a, 0xcf, 0x7d, 0x36, 0xdc, 0x49, 0x38, 0x25, 0x34, 0x4f, 0x20, 0x9a, - /* (2^ 60)P */ 0x2b, 0x6e, 0x04, 0x0d, 0x4f, 0x3d, 0x3b, 0x24, 0xf6, 0x4e, 0x5e, 0x0a, 0xbd, 0x48, 0x96, 0xba, 0x81, 0x8f, 0x39, 0x82, 0x13, 0xe6, 0x72, 0xf3, 0x0f, 0xb6, 0x94, 0xf4, 0xc5, 0x90, 0x74, 0x91, 0xa8, 0xf2, 0xc9, 0xca, 0x9a, 0x4d, 0x98, 0xf2, 0xdf, 0x52, 0x4e, 0x97, 0x2f, 0xeb, 0x84, 0xd3, 0xaf, 0xc2, 0xcc, 0xfb, 0x4c, 0x26, 0x4b, 0xe4, - /* (2^ 61)P */ 0x12, 0x9e, 0xfb, 0x9d, 0x78, 0x79, 0x99, 0xdd, 0xb3, 0x0b, 0x2e, 0x56, 0x41, 0x8e, 0x3f, 0x39, 0xb8, 0x97, 0x89, 0x53, 0x9b, 0x8a, 0x3c, 0x40, 0x9d, 0xa4, 0x6c, 0x2e, 0x31, 0x71, 0xc6, 0x0a, 0x41, 0xd4, 0x95, 0x06, 0x5e, 0xc1, 0xab, 0xc2, 0x14, 0xc4, 0xc7, 0x15, 0x08, 0x3a, 0xad, 0x7a, 0xb4, 0x62, 0xa3, 0x0c, 0x90, 0xf4, 0x47, 0x08, - /* (2^ 62)P */ 0x7f, 0xec, 0x09, 0x82, 0xf5, 0x94, 0x09, 0x93, 0x32, 0xd3, 0xdc, 0x56, 0x80, 0x7b, 0x5b, 0x22, 0x80, 0x6a, 0x96, 0x72, 0xb1, 0xc2, 0xd9, 0xa1, 0x8b, 0x66, 0x42, 0x16, 0xe2, 0x07, 0xb3, 0x2d, 0xf1, 0x75, 0x35, 0x72, 0xc7, 0x98, 0xbe, 0x63, 0x3b, 0x20, 0x75, 0x05, 0xc1, 0x3e, 0x31, 0x5a, 0xf7, 0xaa, 0xae, 0x4b, 0xdb, 0x1d, 0xd0, 0x74, - /* (2^ 63)P */ 0x36, 0x5c, 0x74, 0xe6, 0x5d, 0x59, 0x3f, 0x15, 0x4b, 0x4d, 0x4e, 0x67, 0x41, 0xfe, 0x98, 0x1f, 0x49, 0x76, 0x91, 0x0f, 0x9b, 0xf4, 0xaf, 0x86, 0xaf, 0x66, 0x19, 0xed, 0x46, 0xf1, 0x05, 0x9a, 0xcc, 0xd1, 0x14, 0x1f, 0x82, 0x12, 0x8e, 0xe6, 0xf4, 0xc3, 0x42, 0x5c, 0x4e, 0x33, 0x93, 0xbe, 0x30, 0xe7, 0x64, 0xa9, 0x35, 0x00, 0x4d, 0xf9, - /* (2^ 64)P */ 0x1f, 0xc1, 0x1e, 0xb7, 0xe3, 0x7c, 0xfa, 0xa3, 0x6b, 0x76, 0xaf, 0x9c, 0x05, 0x85, 0x4a, 0xa9, 0xfb, 0xe3, 0x7e, 0xf2, 0x49, 0x56, 0xdc, 0x2f, 0x57, 0x10, 0xba, 0x37, 0xb2, 0x62, 0xf5, 0x6b, 0xe5, 0x8f, 0x0a, 0x87, 0xd1, 0x6a, 0xcb, 0x9d, 0x07, 0xd0, 0xf6, 0x38, 0x99, 0x2c, 0x61, 0x4a, 0x4e, 0xd8, 0xd2, 0x88, 0x29, 0x99, 0x11, 0x95, - /* (2^ 65)P */ 0x6f, 0xdc, 0xd5, 0xd6, 0xd6, 0xa7, 0x4c, 0x46, 0x93, 0x65, 0x62, 0x23, 0x95, 0x32, 0x9c, 0xde, 0x40, 0x41, 0x68, 0x2c, 0x18, 0x4e, 0x5a, 0x8c, 0xc0, 0xc5, 0xc5, 0xea, 0x5c, 0x45, 0x0f, 0x60, 0x78, 0x39, 0xb6, 0x36, 0x23, 0x12, 0xbc, 0x21, 0x9a, 0xf8, 0x91, 0xac, 0xc4, 0x70, 0xdf, 0x85, 0x8e, 0x3c, 0xec, 0x22, 0x04, 0x98, 0xa8, 0xaa, - /* (2^ 66)P */ 0xcc, 0x52, 0x10, 0x5b, 0x4b, 0x6c, 0xc5, 0xfa, 0x3e, 0xd4, 0xf8, 0x1c, 0x04, 0x14, 0x48, 0x33, 0xd9, 0xfc, 0x5f, 0xb0, 0xa5, 0x48, 0x8c, 0x45, 0x8a, 0xee, 0x3e, 0xa7, 0xc1, 0x2e, 0x34, 0xca, 0xf6, 0xc9, 0xeb, 0x10, 0xbb, 0xe1, 0x59, 0x84, 0x25, 0xe8, 0x81, 0x70, 0xc0, 0x09, 0x42, 0xa7, 0x3b, 0x0d, 0x33, 0x00, 0xb5, 0x77, 0xbe, 0x25, - /* (2^ 67)P */ 0xcd, 0x1f, 0xbc, 0x7d, 0xef, 0xe5, 0xca, 0x91, 0xaf, 0xa9, 0x59, 0x6a, 0x09, 0xca, 0xd6, 0x1b, 0x3d, 0x55, 0xde, 0xa2, 0x6a, 0x80, 0xd6, 0x95, 0x47, 0xe4, 0x5f, 0x68, 0x54, 0x08, 0xdf, 0x29, 0xba, 0x2a, 0x02, 0x84, 0xe8, 0xe9, 0x00, 0x77, 0x99, 0x36, 0x03, 0xf6, 0x4a, 0x3e, 0x21, 0x81, 0x7d, 0xb8, 0xa4, 0x8a, 0xa2, 0x05, 0xef, 0xbc, - /* (2^ 68)P */ 0x7c, 0x59, 0x5f, 0x66, 0xd9, 0xb7, 0x83, 0x43, 0x8a, 0xa1, 0x8d, 0x51, 0x70, 0xba, 0xf2, 0x9b, 0x95, 0xc0, 0x4b, 0x4c, 0xa0, 0x14, 0xd3, 0xa4, 0x5d, 0x4a, 0x37, 0x36, 0x97, 0x31, 0x1e, 0x12, 0xe7, 0xbb, 0x08, 0x67, 0xa5, 0x23, 0xd7, 0xfb, 0x97, 0xd8, 0x6a, 0x03, 0xb1, 0xf8, 0x7f, 0xda, 0x58, 0xd9, 0x3f, 0x73, 0x4a, 0x53, 0xe1, 0x7b, - /* (2^ 69)P */ 0x55, 0x83, 0x98, 0x78, 0x6c, 0x56, 0x5e, 0xed, 0xf7, 0x23, 0x3e, 0x4c, 0x7d, 0x09, 0x2d, 0x09, 0x9c, 0x58, 0x8b, 0x32, 0xca, 0xfe, 0xbf, 0x47, 0x03, 0xeb, 0x4d, 0xe7, 0xeb, 0x9c, 0x83, 0x05, 0x68, 0xaa, 0x80, 0x89, 0x44, 0xf9, 0xd4, 0xdc, 0xdb, 0xb1, 0xdb, 0x77, 0xac, 0xf9, 0x2a, 0xae, 0x35, 0xac, 0x74, 0xb5, 0x95, 0x62, 0x18, 0x85, - /* (2^ 70)P */ 0xab, 0x82, 0x7e, 0x10, 0xd7, 0xe6, 0x57, 0xd1, 0x66, 0x12, 0x31, 0x9c, 0x9c, 0xa6, 0x27, 0x59, 0x71, 0x2e, 0xeb, 0xa0, 0x68, 0xc5, 0x87, 0x51, 0xf4, 0xca, 0x3f, 0x98, 0x56, 0xb0, 0x89, 0xb1, 0xc7, 0x7b, 0x46, 0xb3, 0xae, 0x36, 0xf2, 0xee, 0x15, 0x1a, 0x60, 0xf4, 0x50, 0x76, 0x4f, 0xc4, 0x53, 0x0d, 0x36, 0x4d, 0x31, 0xb1, 0x20, 0x51, - /* (2^ 71)P */ 0xf7, 0x1d, 0x8c, 0x1b, 0x5e, 0xe5, 0x02, 0x6f, 0xc5, 0xa5, 0xe0, 0x5f, 0xc6, 0xb6, 0x63, 0x43, 0xaf, 0x3c, 0x19, 0x6c, 0xf4, 0xaf, 0xa4, 0x33, 0xb1, 0x0a, 0x37, 0x3d, 0xd9, 0x4d, 0xe2, 0x29, 0x24, 0x26, 0x94, 0x7c, 0x02, 0xe4, 0xe2, 0xf2, 0xbe, 0xbd, 0xac, 0x1b, 0x48, 0xb8, 0xdd, 0xe9, 0x0d, 0x9a, 0x50, 0x1a, 0x98, 0x71, 0x6e, 0xdc, - /* (2^ 72)P */ 0x9f, 0x40, 0xb1, 0xb3, 0x66, 0x28, 0x6c, 0xfe, 0xa6, 0x7d, 0xf8, 0x3e, 0xb8, 0xf3, 0xde, 0x52, 0x76, 0x52, 0xa3, 0x92, 0x98, 0x23, 0xab, 0x4f, 0x88, 0x97, 0xfc, 0x22, 0xe1, 0x6b, 0x67, 0xcd, 0x13, 0x95, 0xda, 0x65, 0xdd, 0x3b, 0x67, 0x3f, 0x5f, 0x4c, 0xf2, 0x8a, 0xad, 0x98, 0xa7, 0x94, 0x24, 0x45, 0x87, 0x11, 0x7c, 0x75, 0x79, 0x85, - /* (2^ 73)P */ 0x70, 0xbf, 0xf9, 0x3b, 0xa9, 0x44, 0x57, 0x72, 0x96, 0xc9, 0xa4, 0x98, 0x65, 0xbf, 0x87, 0xb3, 0x3a, 0x39, 0x12, 0xde, 0xe5, 0x39, 0x01, 0x4f, 0xf7, 0xc0, 0x71, 0x52, 0x36, 0x85, 0xb3, 0x18, 0xf8, 0x14, 0xc0, 0x6d, 0xae, 0x9e, 0x4f, 0xb0, 0x72, 0x87, 0xac, 0x5c, 0xd1, 0x6c, 0x41, 0x6c, 0x90, 0x9d, 0x22, 0x81, 0xe4, 0x2b, 0xea, 0xe5, - /* (2^ 74)P */ 0xfc, 0xea, 0x1a, 0x65, 0xd9, 0x49, 0x6a, 0x39, 0xb5, 0x96, 0x72, 0x7b, 0x32, 0xf1, 0xd0, 0xe9, 0x45, 0xd9, 0x31, 0x55, 0xc7, 0x34, 0xe9, 0x5a, 0xec, 0x73, 0x0b, 0x03, 0xc4, 0xb3, 0xe6, 0xc9, 0x5e, 0x0a, 0x17, 0xfe, 0x53, 0x66, 0x7f, 0x21, 0x18, 0x74, 0x54, 0x1b, 0xc9, 0x49, 0x16, 0xd2, 0x48, 0xaf, 0x5b, 0x47, 0x7b, 0xeb, 0xaa, 0xc9, - /* (2^ 75)P */ 0x47, 0x04, 0xf5, 0x5a, 0x87, 0x77, 0x9e, 0x21, 0x34, 0x4e, 0x83, 0x88, 0xaf, 0x02, 0x1d, 0xb0, 0x5a, 0x1d, 0x1d, 0x7d, 0x8d, 0x2c, 0xd3, 0x8d, 0x63, 0xa9, 0x45, 0xfb, 0x15, 0x6d, 0x86, 0x45, 0xcd, 0x38, 0x0e, 0xf7, 0x37, 0x79, 0xed, 0x6d, 0x5a, 0xbc, 0x32, 0xcc, 0x66, 0xf1, 0x3a, 0xb2, 0x87, 0x6f, 0x70, 0x71, 0xd9, 0xf2, 0xfa, 0x7b, - /* (2^ 76)P */ 0x68, 0x07, 0xdc, 0x61, 0x40, 0xe4, 0xec, 0x32, 0xc8, 0xbe, 0x66, 0x30, 0x54, 0x80, 0xfd, 0x13, 0x7a, 0xef, 0xae, 0xed, 0x2e, 0x00, 0x6d, 0x3f, 0xbd, 0xfc, 0x91, 0x24, 0x53, 0x7f, 0x63, 0x9d, 0x2e, 0xe3, 0x76, 0xe0, 0xf3, 0xe1, 0x8f, 0x7a, 0xc4, 0x77, 0x0c, 0x91, 0xc0, 0xc2, 0x18, 0x6b, 0x04, 0xad, 0xb6, 0x70, 0x9a, 0x64, 0xc5, 0x82, - /* (2^ 77)P */ 0x7f, 0xea, 0x13, 0xd8, 0x9e, 0xfc, 0x5b, 0x06, 0xb5, 0x4f, 0xda, 0x38, 0xe0, 0x9c, 0xd2, 0x3a, 0xc1, 0x1c, 0x62, 0x70, 0x7f, 0xc6, 0x24, 0x0a, 0x47, 0x04, 0x01, 0xc4, 0x55, 0x09, 0xd1, 0x7a, 0x07, 0xba, 0xa3, 0x80, 0x4f, 0xc1, 0x65, 0x36, 0x6d, 0xc0, 0x10, 0xcf, 0x94, 0xa9, 0xa2, 0x01, 0x44, 0xd1, 0xf9, 0x1c, 0x4c, 0xfb, 0xf8, 0x99, - /* (2^ 78)P */ 0x6c, 0xb9, 0x6b, 0xee, 0x43, 0x5b, 0xb9, 0xbb, 0xee, 0x2e, 0x52, 0xc1, 0xc6, 0xb9, 0x61, 0xd2, 0x93, 0xa5, 0xaf, 0x52, 0xf4, 0xa4, 0x1a, 0x51, 0x61, 0xa7, 0xcb, 0x9e, 0xbb, 0x56, 0x65, 0xe2, 0xbf, 0x75, 0xb9, 0x9c, 0x50, 0x96, 0x60, 0x81, 0x74, 0x47, 0xc0, 0x04, 0x88, 0x71, 0x76, 0x39, 0x9a, 0xa7, 0xb1, 0x4e, 0x43, 0x15, 0xe0, 0xbb, - /* (2^ 79)P */ 0xbb, 0xce, 0xe2, 0xbb, 0xf9, 0x17, 0x0f, 0x82, 0x40, 0xad, 0x73, 0xe3, 0xeb, 0x3b, 0x06, 0x1a, 0xcf, 0x8e, 0x6e, 0x28, 0xb8, 0x26, 0xd9, 0x5b, 0xb7, 0xb3, 0xcf, 0xb4, 0x6a, 0x1c, 0xbf, 0x7f, 0xb8, 0xb5, 0x79, 0xcf, 0x45, 0x68, 0x7d, 0xc5, 0xeb, 0xf3, 0xbe, 0x39, 0x40, 0xfc, 0x07, 0x90, 0x7a, 0x62, 0xad, 0x86, 0x08, 0x71, 0x25, 0xe1, - /* (2^ 80)P */ 0x9b, 0x46, 0xac, 0xef, 0xc1, 0x4e, 0xa1, 0x97, 0x95, 0x76, 0xf9, 0x1b, 0xc2, 0xb2, 0x6a, 0x41, 0xea, 0x80, 0x3d, 0xe9, 0x08, 0x52, 0x5a, 0xe3, 0xf2, 0x08, 0xc5, 0xea, 0x39, 0x3f, 0x44, 0x71, 0x4d, 0xea, 0x0d, 0x05, 0x23, 0xe4, 0x2e, 0x3c, 0x89, 0xfe, 0x12, 0x8a, 0x95, 0x42, 0x0a, 0x68, 0xea, 0x5a, 0x28, 0x06, 0x9e, 0xe3, 0x5f, 0xe0, - /* (2^ 81)P */ 0x00, 0x61, 0x6c, 0x98, 0x9b, 0xe7, 0xb9, 0x06, 0x1c, 0xc5, 0x1b, 0xed, 0xbe, 0xc8, 0xb3, 0xea, 0x87, 0xf0, 0xc4, 0x24, 0x7d, 0xbb, 0x5d, 0xa4, 0x1d, 0x7a, 0x16, 0x00, 0x55, 0x94, 0x67, 0x78, 0xbd, 0x58, 0x02, 0x82, 0x90, 0x53, 0x76, 0xd4, 0x72, 0x99, 0x51, 0x6f, 0x7b, 0xcf, 0x80, 0x30, 0x31, 0x3b, 0x01, 0xc7, 0xc1, 0xef, 0xe6, 0x42, - /* (2^ 82)P */ 0xe2, 0x35, 0xaf, 0x4b, 0x79, 0xc6, 0x12, 0x24, 0x99, 0xc0, 0x68, 0xb0, 0x43, 0x3e, 0xe5, 0xef, 0xe2, 0x29, 0xea, 0xb8, 0xb3, 0xbc, 0x6a, 0x53, 0x2c, 0x69, 0x18, 0x5a, 0xf9, 0x15, 0xae, 0x66, 0x58, 0x18, 0xd3, 0x2d, 0x4b, 0x00, 0xfd, 0x84, 0xab, 0x4f, 0xae, 0x70, 0x6b, 0x9e, 0x9a, 0xdf, 0x83, 0xfd, 0x2e, 0x3c, 0xcf, 0xf8, 0x88, 0x5b, - /* (2^ 83)P */ 0xa4, 0x90, 0x31, 0x85, 0x13, 0xcd, 0xdf, 0x64, 0xc9, 0xa1, 0x0b, 0xe7, 0xb6, 0x73, 0x8a, 0x1b, 0x22, 0x78, 0x4c, 0xd4, 0xae, 0x48, 0x18, 0x00, 0x00, 0xa8, 0x9f, 0x06, 0xf9, 0xfb, 0x2d, 0xc3, 0xb1, 0x2a, 0xbc, 0x13, 0x99, 0x57, 0xaf, 0xf0, 0x8d, 0x61, 0x54, 0x29, 0xd5, 0xf2, 0x72, 0x00, 0x96, 0xd1, 0x85, 0x12, 0x8a, 0xf0, 0x23, 0xfb, - /* (2^ 84)P */ 0x69, 0xc7, 0xdb, 0xd9, 0x92, 0x75, 0x08, 0x9b, 0xeb, 0xa5, 0x93, 0xd1, 0x1a, 0xf4, 0xf5, 0xaf, 0xe6, 0xc4, 0x4a, 0x0d, 0x35, 0x26, 0x39, 0x9d, 0xd3, 0x17, 0x3e, 0xae, 0x2d, 0xbf, 0x73, 0x9f, 0xb7, 0x74, 0x91, 0xd1, 0xd8, 0x5c, 0x14, 0xf9, 0x75, 0xdf, 0xeb, 0xc2, 0x22, 0xd8, 0x14, 0x8d, 0x86, 0x23, 0x4d, 0xd1, 0x2d, 0xdb, 0x6b, 0x42, - /* (2^ 85)P */ 0x8c, 0xda, 0xc6, 0xf8, 0x71, 0xba, 0x2b, 0x06, 0x78, 0xae, 0xcc, 0x3a, 0xe3, 0xe3, 0xa1, 0x8b, 0xe2, 0x34, 0x6d, 0x28, 0x9e, 0x46, 0x13, 0x4d, 0x9e, 0xa6, 0x73, 0x49, 0x65, 0x79, 0x88, 0xb9, 0x3a, 0xd1, 0x6d, 0x2f, 0x48, 0x2b, 0x0a, 0x7f, 0x58, 0x20, 0x37, 0xf4, 0x0e, 0xbb, 0x4a, 0x95, 0x58, 0x0c, 0x88, 0x30, 0xc4, 0x74, 0xdd, 0xfd, - /* (2^ 86)P */ 0x6d, 0x13, 0x4e, 0x89, 0x2d, 0xa9, 0xa3, 0xed, 0x09, 0xe3, 0x0e, 0x71, 0x3e, 0x4a, 0xab, 0x90, 0xde, 0x03, 0xeb, 0x56, 0x46, 0x60, 0x06, 0xf5, 0x71, 0xe5, 0xee, 0x9b, 0xef, 0xff, 0xc4, 0x2c, 0x9f, 0x37, 0x48, 0x45, 0x94, 0x12, 0x41, 0x81, 0x15, 0x70, 0x91, 0x99, 0x5e, 0x56, 0x6b, 0xf4, 0xa6, 0xc9, 0xf5, 0x69, 0x9d, 0x78, 0x37, 0x57, - /* (2^ 87)P */ 0xf3, 0x51, 0x57, 0x7e, 0x43, 0x6f, 0xc6, 0x67, 0x59, 0x0c, 0xcf, 0x94, 0xe6, 0x3d, 0xb5, 0x07, 0xc9, 0x77, 0x48, 0xc9, 0x68, 0x0d, 0x98, 0x36, 0x62, 0x35, 0x38, 0x1c, 0xf5, 0xc5, 0xec, 0x66, 0x78, 0xfe, 0x47, 0xab, 0x26, 0xd6, 0x44, 0xb6, 0x06, 0x0f, 0x89, 0xe3, 0x19, 0x40, 0x1a, 0xe7, 0xd8, 0x65, 0x55, 0xf7, 0x1a, 0xfc, 0xa3, 0x0e, - /* (2^ 88)P */ 0x0e, 0x30, 0xa6, 0xb7, 0x58, 0x60, 0x62, 0x2a, 0x6c, 0x13, 0xa8, 0x14, 0x9b, 0xb8, 0xf2, 0x70, 0xd8, 0xb1, 0x71, 0x88, 0x8c, 0x18, 0x31, 0x25, 0x93, 0x90, 0xb4, 0xc7, 0x49, 0xd8, 0xd4, 0xdb, 0x1e, 0x1e, 0x7f, 0xaa, 0xba, 0xc9, 0xf2, 0x5d, 0xa9, 0x3a, 0x43, 0xb4, 0x5c, 0xee, 0x7b, 0xc7, 0x97, 0xb7, 0x66, 0xd7, 0x23, 0xd9, 0x22, 0x59, - /* (2^ 89)P */ 0x28, 0x19, 0xa6, 0xf9, 0x89, 0x20, 0x78, 0xd4, 0x6d, 0xcb, 0x79, 0x8f, 0x61, 0x6f, 0xb2, 0x5c, 0x4f, 0xa6, 0x54, 0x84, 0x95, 0x24, 0x36, 0x64, 0xcb, 0x39, 0xe7, 0x8f, 0x97, 0x9c, 0x5c, 0x3c, 0xfb, 0x51, 0x11, 0x01, 0x17, 0xdb, 0xc9, 0x9b, 0x51, 0x03, 0x9a, 0xe9, 0xe5, 0x24, 0x1e, 0xf5, 0xda, 0xe0, 0x48, 0x02, 0x23, 0xd0, 0x2c, 0x81, - /* (2^ 90)P */ 0x42, 0x1b, 0xe4, 0x91, 0x85, 0x2a, 0x0c, 0xd2, 0x28, 0x66, 0x57, 0x9e, 0x33, 0x8d, 0x25, 0x71, 0x10, 0x65, 0x76, 0xa2, 0x8c, 0x21, 0x86, 0x81, 0x15, 0xc2, 0x27, 0xeb, 0x54, 0x2d, 0x4f, 0x6c, 0xe6, 0xd6, 0x24, 0x9c, 0x1a, 0x12, 0xb8, 0x81, 0xe2, 0x0a, 0xf3, 0xd3, 0xf0, 0xd3, 0xe1, 0x74, 0x1f, 0x9b, 0x11, 0x47, 0xd0, 0xcf, 0xb6, 0x54, - /* (2^ 91)P */ 0x26, 0x45, 0xa2, 0x10, 0xd4, 0x2d, 0xae, 0xc0, 0xb0, 0xe8, 0x86, 0xb3, 0xc7, 0xea, 0x70, 0x87, 0x61, 0xb5, 0xa5, 0x55, 0xbe, 0x88, 0x1d, 0x7a, 0xd9, 0x6f, 0xeb, 0x83, 0xe2, 0x44, 0x7f, 0x98, 0x04, 0xd6, 0x50, 0x9d, 0xa7, 0x86, 0x66, 0x09, 0x63, 0xe1, 0xed, 0x72, 0xb1, 0xe4, 0x1d, 0x3a, 0xfd, 0x47, 0xce, 0x1c, 0xaa, 0x3b, 0x8f, 0x1b, - /* (2^ 92)P */ 0xf4, 0x3c, 0x4a, 0xb6, 0xc2, 0x9c, 0xe0, 0x2e, 0xb7, 0x38, 0xea, 0x61, 0x35, 0x97, 0x10, 0x90, 0xae, 0x22, 0x48, 0xb3, 0xa9, 0xc6, 0x7a, 0xbb, 0x23, 0xf2, 0xf8, 0x1b, 0xa7, 0xa1, 0x79, 0xcc, 0xc4, 0xf8, 0x08, 0x76, 0x8a, 0x5a, 0x1c, 0x1b, 0xc5, 0x33, 0x91, 0xa9, 0xb8, 0xb9, 0xd3, 0xf8, 0x49, 0xcd, 0xe5, 0x82, 0x43, 0xf7, 0xca, 0x68, - /* (2^ 93)P */ 0x38, 0xba, 0xae, 0x44, 0xfe, 0x57, 0x64, 0x56, 0x7c, 0x0e, 0x9c, 0xca, 0xff, 0xa9, 0x82, 0xbb, 0x38, 0x4a, 0xa7, 0xf7, 0x47, 0xab, 0xbe, 0x6d, 0x23, 0x0b, 0x8a, 0xed, 0xc2, 0xb9, 0x8f, 0xf1, 0xec, 0x91, 0x44, 0x73, 0x64, 0xba, 0xd5, 0x8f, 0x37, 0x38, 0x0d, 0xd5, 0xf8, 0x73, 0x57, 0xb6, 0xc2, 0x45, 0xdc, 0x25, 0xb2, 0xb6, 0xea, 0xd9, - /* (2^ 94)P */ 0xbf, 0xe9, 0x1a, 0x40, 0x4d, 0xcc, 0xe6, 0x1d, 0x70, 0x1a, 0x65, 0xcc, 0x34, 0x2c, 0x37, 0x2c, 0x2d, 0x6b, 0x6d, 0xe5, 0x2f, 0x19, 0x9e, 0xe4, 0xe1, 0xaa, 0xd4, 0xab, 0x54, 0xf4, 0xa8, 0xe4, 0x69, 0x2d, 0x8e, 0x4d, 0xd7, 0xac, 0xb0, 0x5b, 0xfe, 0xe3, 0x26, 0x07, 0xc3, 0xf8, 0x1b, 0x43, 0xa8, 0x1d, 0x64, 0xa5, 0x25, 0x88, 0xbb, 0x77, - /* (2^ 95)P */ 0x92, 0xcd, 0x6e, 0xa0, 0x79, 0x04, 0x18, 0xf4, 0x11, 0x58, 0x48, 0xb5, 0x3c, 0x7b, 0xd1, 0xcc, 0xd3, 0x14, 0x2c, 0xa0, 0xdd, 0x04, 0x44, 0x11, 0xb3, 0x6d, 0x2f, 0x0d, 0xf5, 0x2a, 0x75, 0x5d, 0x1d, 0xda, 0x86, 0x8d, 0x7d, 0x6b, 0x32, 0x68, 0xb6, 0x6c, 0x64, 0x9e, 0xde, 0x80, 0x88, 0xce, 0x08, 0xbf, 0x0b, 0xe5, 0x8e, 0x4f, 0x1d, 0xfb, - /* (2^ 96)P */ 0xaf, 0xe8, 0x85, 0xbf, 0x7f, 0x37, 0x8d, 0x66, 0x7c, 0xd5, 0xd3, 0x96, 0xa5, 0x81, 0x67, 0x95, 0xff, 0x48, 0xde, 0xde, 0xd7, 0x7a, 0x46, 0x34, 0xb1, 0x13, 0x70, 0x29, 0xed, 0x87, 0x90, 0xb0, 0x40, 0x2c, 0xa6, 0x43, 0x6e, 0xb6, 0xbc, 0x48, 0x8a, 0xc1, 0xae, 0xb8, 0xd4, 0xe2, 0xc0, 0x32, 0xb2, 0xa6, 0x2a, 0x8f, 0xb5, 0x16, 0x9e, 0xc3, - /* (2^ 97)P */ 0xff, 0x4d, 0xd2, 0xd6, 0x74, 0xef, 0x2c, 0x96, 0xc1, 0x11, 0xa8, 0xb8, 0xfe, 0x94, 0x87, 0x3e, 0xa0, 0xfb, 0x57, 0xa3, 0xfc, 0x7a, 0x7e, 0x6a, 0x59, 0x6c, 0x54, 0xbb, 0xbb, 0xa2, 0x25, 0x38, 0x1b, 0xdf, 0x5d, 0x7b, 0x94, 0x14, 0xde, 0x07, 0x6e, 0xd3, 0xab, 0x02, 0x26, 0x74, 0x16, 0x12, 0xdf, 0x2e, 0x2a, 0xa7, 0xb0, 0xe8, 0x29, 0xc0, - /* (2^ 98)P */ 0x6a, 0x38, 0x0b, 0xd3, 0xba, 0x45, 0x23, 0xe0, 0x04, 0x3b, 0x83, 0x39, 0xc5, 0x11, 0xe6, 0xcf, 0x39, 0x0a, 0xb3, 0xb0, 0x3b, 0x27, 0x29, 0x63, 0x1c, 0xf3, 0x00, 0xe6, 0xd2, 0x55, 0x21, 0x1f, 0x84, 0x97, 0x9f, 0x01, 0x49, 0x43, 0x30, 0x5f, 0xe0, 0x1d, 0x24, 0xc4, 0x4e, 0xa0, 0x2b, 0x0b, 0x12, 0x55, 0xc3, 0x27, 0xae, 0x08, 0x83, 0x7c, - /* (2^ 99)P */ 0x5d, 0x1a, 0xb7, 0xa9, 0xf5, 0xfd, 0xec, 0xad, 0xb7, 0x87, 0x02, 0x5f, 0x0d, 0x30, 0x4d, 0xe2, 0x65, 0x87, 0xa4, 0x41, 0x45, 0x1d, 0x67, 0xe0, 0x30, 0x5c, 0x13, 0x87, 0xf6, 0x2e, 0x08, 0xc1, 0xc7, 0x12, 0x45, 0xc8, 0x9b, 0xad, 0xb8, 0xd5, 0x57, 0xbb, 0x5c, 0x48, 0x3a, 0xe1, 0x91, 0x5e, 0xf6, 0x4d, 0x8a, 0x63, 0x75, 0x69, 0x0c, 0x01, - /* (2^100)P */ 0x8f, 0x53, 0x2d, 0xa0, 0x71, 0x3d, 0xfc, 0x45, 0x10, 0x96, 0xcf, 0x56, 0xf9, 0xbb, 0x40, 0x3c, 0x86, 0x52, 0x76, 0xbe, 0x84, 0xf9, 0xa6, 0x9d, 0x3d, 0x27, 0xbe, 0xb4, 0x00, 0x49, 0x94, 0xf5, 0x5d, 0xe1, 0x62, 0x85, 0x66, 0xe5, 0xb8, 0x20, 0x2c, 0x09, 0x7d, 0x9d, 0x3d, 0x6e, 0x74, 0x39, 0xab, 0xad, 0xa0, 0x90, 0x97, 0x5f, 0xbb, 0xa7, - /* (2^101)P */ 0xdb, 0x2d, 0x99, 0x08, 0x16, 0x46, 0x83, 0x7a, 0xa8, 0xea, 0x3d, 0x28, 0x5b, 0x49, 0xfc, 0xb9, 0x6d, 0x00, 0x9e, 0x54, 0x4f, 0x47, 0x64, 0x9b, 0x58, 0x4d, 0x07, 0x0c, 0x6f, 0x29, 0x56, 0x0b, 0x00, 0x14, 0x85, 0x96, 0x41, 0x04, 0xb9, 0x5c, 0xa4, 0xf6, 0x16, 0x73, 0x6a, 0xc7, 0x62, 0x0c, 0x65, 0x2f, 0x93, 0xbf, 0xf7, 0xb9, 0xb7, 0xf1, - /* (2^102)P */ 0xeb, 0x6d, 0xb3, 0x46, 0x32, 0xd2, 0xcb, 0x08, 0x94, 0x14, 0xbf, 0x3f, 0xc5, 0xcb, 0x5f, 0x9f, 0x8a, 0x89, 0x0c, 0x1b, 0x45, 0xad, 0x4c, 0x50, 0xb4, 0xe1, 0xa0, 0x6b, 0x11, 0x92, 0xaf, 0x1f, 0x00, 0xcc, 0xe5, 0x13, 0x7e, 0xe4, 0x2e, 0xa0, 0x57, 0xf3, 0xa7, 0x84, 0x79, 0x7a, 0xc2, 0xb7, 0xb7, 0xfc, 0x5d, 0xa5, 0xa9, 0x64, 0xcc, 0xd8, - /* (2^103)P */ 0xa9, 0xc4, 0x12, 0x8b, 0x34, 0x78, 0x3e, 0x38, 0xfd, 0x3f, 0x87, 0xfa, 0x88, 0x94, 0xd5, 0xd9, 0x7f, 0xeb, 0x58, 0xff, 0xb9, 0x45, 0xdb, 0xa1, 0xed, 0x22, 0x28, 0x1d, 0x00, 0x6d, 0x79, 0x85, 0x7a, 0x75, 0x5d, 0xf0, 0xb1, 0x9e, 0x47, 0x28, 0x8c, 0x62, 0xdf, 0xfb, 0x4c, 0x7b, 0xc5, 0x1a, 0x42, 0x95, 0xef, 0x9a, 0xb7, 0x27, 0x7e, 0xda, - /* (2^104)P */ 0xca, 0xd5, 0xc0, 0x17, 0xa1, 0x66, 0x79, 0x9c, 0x2a, 0xb7, 0x0a, 0xfe, 0x62, 0xe4, 0x26, 0x78, 0x90, 0xa7, 0xcb, 0xb0, 0x4f, 0x6d, 0xf9, 0x8f, 0xf7, 0x7d, 0xac, 0xb8, 0x78, 0x1f, 0x41, 0xea, 0x97, 0x1e, 0x62, 0x97, 0x43, 0x80, 0x58, 0x80, 0xb6, 0x69, 0x7d, 0xee, 0x16, 0xd2, 0xa1, 0x81, 0xd7, 0xb1, 0x27, 0x03, 0x48, 0xda, 0xab, 0xec, - /* (2^105)P */ 0x5b, 0xed, 0x40, 0x8e, 0x8c, 0xc1, 0x66, 0x90, 0x7f, 0x0c, 0xb2, 0xfc, 0xbd, 0x16, 0xac, 0x7d, 0x4c, 0x6a, 0xf9, 0xae, 0xe7, 0x4e, 0x11, 0x12, 0xe9, 0xbe, 0x17, 0x09, 0xc6, 0xc1, 0x5e, 0xb5, 0x7b, 0x50, 0x5c, 0x27, 0xfb, 0x80, 0xab, 0x01, 0xfa, 0x5b, 0x9b, 0x75, 0x16, 0x6e, 0xb2, 0x5c, 0x8c, 0x2f, 0xa5, 0x6a, 0x1a, 0x68, 0xa6, 0x90, - /* (2^106)P */ 0x75, 0xfe, 0xb6, 0x96, 0x96, 0x87, 0x4c, 0x12, 0xa9, 0xd1, 0xd8, 0x03, 0xa3, 0xc1, 0x15, 0x96, 0xe8, 0xa0, 0x75, 0x82, 0xa0, 0x6d, 0xea, 0x54, 0xdc, 0x5f, 0x0d, 0x7e, 0xf6, 0x70, 0xb5, 0xdc, 0x7a, 0xf6, 0xc4, 0xd4, 0x21, 0x49, 0xf5, 0xd4, 0x14, 0x6d, 0x48, 0x1d, 0x7c, 0x99, 0x42, 0xdf, 0x78, 0x6b, 0x9d, 0xb9, 0x30, 0x3c, 0xd0, 0x29, - /* (2^107)P */ 0x85, 0xd6, 0xd8, 0xf3, 0x91, 0x74, 0xdd, 0xbd, 0x72, 0x96, 0x10, 0xe4, 0x76, 0x02, 0x5a, 0x72, 0x67, 0xd3, 0x17, 0x72, 0x14, 0x9a, 0x20, 0x5b, 0x0f, 0x8d, 0xed, 0x6d, 0x4e, 0xe3, 0xd9, 0x82, 0xc2, 0x99, 0xee, 0x39, 0x61, 0x69, 0x8a, 0x24, 0x01, 0x92, 0x15, 0xe7, 0xfc, 0xf9, 0x4d, 0xac, 0xf1, 0x30, 0x49, 0x01, 0x0b, 0x6e, 0x0f, 0x20, - /* (2^108)P */ 0xd8, 0x25, 0x94, 0x5e, 0x43, 0x29, 0xf5, 0xcc, 0xe8, 0xe3, 0x55, 0x41, 0x3c, 0x9f, 0x58, 0x5b, 0x00, 0xeb, 0xc5, 0xdf, 0xcf, 0xfb, 0xfd, 0x6e, 0x92, 0xec, 0x99, 0x30, 0xd6, 0x05, 0xdd, 0x80, 0x7a, 0x5d, 0x6d, 0x16, 0x85, 0xd8, 0x9d, 0x43, 0x65, 0xd8, 0x2c, 0x33, 0x2f, 0x5c, 0x41, 0xea, 0xb7, 0x95, 0x77, 0xf2, 0x9e, 0x59, 0x09, 0xe8, - /* (2^109)P */ 0x00, 0xa0, 0x03, 0x80, 0xcd, 0x60, 0xe5, 0x17, 0xd4, 0x15, 0x99, 0xdd, 0x4f, 0xbf, 0x66, 0xb8, 0xc0, 0xf5, 0xf9, 0xfc, 0x6d, 0x42, 0x18, 0x34, 0x1c, 0x7d, 0x5b, 0xb5, 0x09, 0xd0, 0x99, 0x57, 0x81, 0x0b, 0x62, 0xb3, 0xa2, 0xf9, 0x0b, 0xae, 0x95, 0xb8, 0xc2, 0x3b, 0x0d, 0x5b, 0x00, 0xf1, 0xed, 0xbc, 0x05, 0x9d, 0x61, 0xbc, 0x73, 0x9d, - /* (2^110)P */ 0xd4, 0xdb, 0x29, 0xe5, 0x85, 0xe9, 0xc6, 0x89, 0x2a, 0xa8, 0x54, 0xab, 0xb3, 0x7f, 0x88, 0xc0, 0x4d, 0xe0, 0xd1, 0x74, 0x6e, 0xa3, 0xa7, 0x39, 0xd5, 0xcc, 0xa1, 0x8a, 0xcb, 0x5b, 0x34, 0xad, 0x92, 0xb4, 0xd8, 0xd5, 0x17, 0xf6, 0x77, 0x18, 0x9e, 0xaf, 0x45, 0x3b, 0x03, 0xe2, 0xf8, 0x52, 0x60, 0xdc, 0x15, 0x20, 0x9e, 0xdf, 0xd8, 0x5d, - /* (2^111)P */ 0x02, 0xc1, 0xac, 0x1a, 0x15, 0x8e, 0x6c, 0xf5, 0x1e, 0x1e, 0xba, 0x7e, 0xc2, 0xda, 0x7d, 0x02, 0xda, 0x43, 0xae, 0x04, 0x70, 0x28, 0x54, 0x78, 0x94, 0xf5, 0x4f, 0x07, 0x84, 0x8f, 0xed, 0xaa, 0xc0, 0xb8, 0xcd, 0x7f, 0x7e, 0x33, 0xa3, 0xbe, 0x21, 0x29, 0xc8, 0x56, 0x34, 0xc0, 0x76, 0x87, 0x8f, 0xc7, 0x73, 0x58, 0x90, 0x16, 0xfc, 0xd6, - /* (2^112)P */ 0xb8, 0x3f, 0xe1, 0xdf, 0x3a, 0x91, 0x25, 0x0c, 0xf6, 0x47, 0xa8, 0x89, 0xc4, 0xc6, 0x61, 0xec, 0x86, 0x2c, 0xfd, 0xbe, 0xa4, 0x6f, 0xc2, 0xd4, 0x46, 0x19, 0x70, 0x5d, 0x09, 0x02, 0x86, 0xd3, 0x4b, 0xe9, 0x16, 0x7b, 0xf0, 0x0d, 0x6c, 0xff, 0x91, 0x05, 0xbf, 0x55, 0xb4, 0x00, 0x8d, 0xe5, 0x6d, 0x68, 0x20, 0x90, 0x12, 0xb5, 0x5c, 0x32, - /* (2^113)P */ 0x80, 0x45, 0xc8, 0x51, 0x87, 0xba, 0x1c, 0x5c, 0xcf, 0x5f, 0x4b, 0x3c, 0x9e, 0x3b, 0x36, 0xd2, 0x26, 0xa2, 0x7f, 0xab, 0xb7, 0xbf, 0xda, 0x68, 0x23, 0x8f, 0xc3, 0xa0, 0xfd, 0xad, 0xf1, 0x56, 0x3b, 0xd0, 0x75, 0x2b, 0x44, 0x61, 0xd8, 0xf4, 0xf1, 0x05, 0x49, 0x53, 0x07, 0xee, 0x47, 0xef, 0xc0, 0x7c, 0x9d, 0xe4, 0x15, 0x88, 0xc5, 0x47, - /* (2^114)P */ 0x2d, 0xb5, 0x09, 0x80, 0xb9, 0xd3, 0xd8, 0xfe, 0x4c, 0xd2, 0xa6, 0x6e, 0xd3, 0x75, 0xcf, 0xb0, 0x99, 0xcb, 0x50, 0x8d, 0xe9, 0x67, 0x9b, 0x20, 0xe8, 0x57, 0xd8, 0x14, 0x85, 0x73, 0x6a, 0x74, 0xe0, 0x99, 0xf0, 0x6b, 0x6e, 0x59, 0x30, 0x31, 0x33, 0x96, 0x5f, 0xa1, 0x0c, 0x1b, 0xf4, 0xca, 0x09, 0xe1, 0x9b, 0xb5, 0xcf, 0x6d, 0x0b, 0xeb, - /* (2^115)P */ 0x1a, 0xde, 0x50, 0xa9, 0xac, 0x3e, 0x10, 0x43, 0x4f, 0x82, 0x4f, 0xc0, 0xfe, 0x3f, 0x33, 0xd2, 0x64, 0x86, 0x50, 0xa9, 0x51, 0x76, 0x5e, 0x50, 0x97, 0x6c, 0x73, 0x8d, 0x77, 0xa3, 0x75, 0x03, 0xbc, 0xc9, 0xfb, 0x50, 0xd9, 0x6d, 0x16, 0xad, 0x5d, 0x32, 0x3d, 0xac, 0x44, 0xdf, 0x51, 0xf7, 0x19, 0xd4, 0x0b, 0x57, 0x78, 0x0b, 0x81, 0x4e, - /* (2^116)P */ 0x32, 0x24, 0xf1, 0x6c, 0x55, 0x62, 0x1d, 0xb3, 0x1f, 0xda, 0xfa, 0x6a, 0x8f, 0x98, 0x01, 0x16, 0xde, 0x44, 0x50, 0x0d, 0x2e, 0x6c, 0x0b, 0xa2, 0xd3, 0x74, 0x0e, 0xa9, 0xbf, 0x8d, 0xa9, 0xc8, 0xc8, 0x2f, 0x62, 0xc1, 0x35, 0x5e, 0xfd, 0x3a, 0xb3, 0x83, 0x2d, 0xee, 0x4e, 0xfd, 0x5c, 0x5e, 0xad, 0x85, 0xa5, 0x10, 0xb5, 0x4f, 0x34, 0xa7, - /* (2^117)P */ 0xd1, 0x58, 0x6f, 0xe6, 0x54, 0x2c, 0xc2, 0xcd, 0xcf, 0x83, 0xdc, 0x88, 0x0c, 0xb9, 0xb4, 0x62, 0x18, 0x89, 0x65, 0x28, 0xe9, 0x72, 0x4b, 0x65, 0xcf, 0xd6, 0x90, 0x88, 0xd7, 0x76, 0x17, 0x4f, 0x74, 0x64, 0x1e, 0xcb, 0xd3, 0xf5, 0x4b, 0xaa, 0x2e, 0x4d, 0x2d, 0x7c, 0x13, 0x1f, 0xfd, 0xd9, 0x60, 0x83, 0x7e, 0xda, 0x64, 0x1c, 0xdc, 0x9f, - /* (2^118)P */ 0xad, 0xef, 0xac, 0x1b, 0xc1, 0x30, 0x5a, 0x15, 0xc9, 0x1f, 0xac, 0xf1, 0xca, 0x44, 0x95, 0x95, 0xea, 0xf2, 0x22, 0xe7, 0x8d, 0x25, 0xf0, 0xff, 0xd8, 0x71, 0xf7, 0xf8, 0x8f, 0x8f, 0xcd, 0xf4, 0x1e, 0xfe, 0x6c, 0x68, 0x04, 0xb8, 0x78, 0xa1, 0x5f, 0xa6, 0x5d, 0x5e, 0xf9, 0x8d, 0xea, 0x80, 0xcb, 0xf3, 0x17, 0xa6, 0x03, 0xc9, 0x38, 0xd5, - /* (2^119)P */ 0x79, 0x14, 0x31, 0xc3, 0x38, 0xe5, 0xaa, 0xbf, 0x17, 0xa3, 0x04, 0x4e, 0x80, 0x59, 0x9c, 0x9f, 0x19, 0x39, 0xe4, 0x2d, 0x23, 0x54, 0x4a, 0x7f, 0x3e, 0xf3, 0xd9, 0xc7, 0xba, 0x6c, 0x8f, 0x6b, 0xfa, 0x34, 0xb5, 0x23, 0x17, 0x1d, 0xff, 0x1d, 0xea, 0x1f, 0xd7, 0xba, 0x61, 0xb2, 0xe0, 0x38, 0x6a, 0xe9, 0xcf, 0x48, 0x5d, 0x6a, 0x10, 0x9c, - /* (2^120)P */ 0xc8, 0xbb, 0x13, 0x1c, 0x3f, 0x3c, 0x34, 0xfd, 0xac, 0x37, 0x52, 0x44, 0x25, 0xa8, 0xde, 0x1d, 0x63, 0xf4, 0x81, 0x9a, 0xbe, 0x0b, 0x74, 0x2e, 0xc8, 0x51, 0x16, 0xd3, 0xac, 0x4a, 0xaf, 0xe2, 0x5f, 0x3a, 0x89, 0x32, 0xd1, 0x9b, 0x7c, 0x90, 0x0d, 0xac, 0xdc, 0x8b, 0x73, 0x45, 0x45, 0x97, 0xb1, 0x90, 0x2c, 0x1b, 0x31, 0xca, 0xb1, 0x94, - /* (2^121)P */ 0x07, 0x28, 0xdd, 0x10, 0x14, 0xa5, 0x95, 0x7e, 0xf3, 0xe4, 0xd4, 0x14, 0xb4, 0x7e, 0x76, 0xdb, 0x42, 0xd6, 0x94, 0x3e, 0xeb, 0x44, 0x64, 0x88, 0x0d, 0xec, 0xc1, 0x21, 0xf0, 0x79, 0xe0, 0x83, 0x67, 0x55, 0x53, 0xc2, 0xf6, 0xc5, 0xc5, 0x89, 0x39, 0xe8, 0x42, 0xd0, 0x17, 0xbd, 0xff, 0x35, 0x59, 0x0e, 0xc3, 0x06, 0x86, 0xd4, 0x64, 0xcf, - /* (2^122)P */ 0x91, 0xa8, 0xdb, 0x57, 0x9b, 0xe2, 0x96, 0x31, 0x10, 0x6e, 0xd7, 0x9a, 0x97, 0xb3, 0xab, 0xb5, 0x15, 0x66, 0xbe, 0xcc, 0x6d, 0x9a, 0xac, 0x06, 0xb3, 0x0d, 0xaa, 0x4b, 0x9c, 0x96, 0x79, 0x6c, 0x34, 0xee, 0x9e, 0x53, 0x4d, 0x6e, 0xbd, 0x88, 0x02, 0xbf, 0x50, 0x54, 0x12, 0x5d, 0x01, 0x02, 0x46, 0xc6, 0x74, 0x02, 0x8c, 0x24, 0xae, 0xb1, - /* (2^123)P */ 0xf5, 0x22, 0xea, 0xac, 0x7d, 0x9c, 0x33, 0x8a, 0xa5, 0x36, 0x79, 0x6a, 0x4f, 0xa4, 0xdc, 0xa5, 0x73, 0x64, 0xc4, 0x6f, 0x43, 0x02, 0x3b, 0x94, 0x66, 0xd2, 0x4b, 0x4f, 0xf6, 0x45, 0x33, 0x5d, 0x10, 0x33, 0x18, 0x1e, 0xa3, 0xfc, 0xf7, 0xd2, 0xb8, 0xc8, 0xa7, 0xe0, 0x76, 0x8a, 0xcd, 0xff, 0x4f, 0x99, 0x34, 0x47, 0x84, 0x91, 0x96, 0x9f, - /* (2^124)P */ 0x8a, 0x48, 0x3b, 0x48, 0x4a, 0xbc, 0xac, 0xe2, 0x80, 0xd6, 0xd2, 0x35, 0xde, 0xd0, 0x56, 0x42, 0x33, 0xb3, 0x56, 0x5a, 0xcd, 0xb8, 0x3d, 0xb5, 0x25, 0xc1, 0xed, 0xff, 0x87, 0x0b, 0x79, 0xff, 0xf2, 0x62, 0xe1, 0x76, 0xc6, 0xa2, 0x0f, 0xa8, 0x9b, 0x0d, 0xcc, 0x3f, 0x3d, 0x35, 0x27, 0x8d, 0x0b, 0x74, 0xb0, 0xc3, 0x78, 0x8c, 0xcc, 0xc8, - /* (2^125)P */ 0xfc, 0x9a, 0x0c, 0xa8, 0x49, 0x42, 0xb8, 0xdf, 0xcf, 0xb3, 0x19, 0xa6, 0x64, 0x57, 0xfe, 0xe8, 0xf8, 0xa6, 0x4b, 0x86, 0xa1, 0xd5, 0x83, 0x7f, 0x14, 0x99, 0x18, 0x0c, 0x7d, 0x5b, 0xf7, 0x3d, 0xf9, 0x4b, 0x79, 0xb1, 0x86, 0x30, 0xb4, 0x5e, 0x6a, 0xe8, 0x9d, 0xfa, 0x8a, 0x41, 0xc4, 0x30, 0xfc, 0x56, 0x74, 0x14, 0x42, 0xc8, 0x96, 0x0e, - /* (2^126)P */ 0xdf, 0x66, 0xec, 0xbc, 0x44, 0xdb, 0x19, 0xce, 0xd4, 0xb5, 0x49, 0x40, 0x07, 0x49, 0xe0, 0x3a, 0x61, 0x10, 0xfb, 0x7d, 0xba, 0xb1, 0xe0, 0x28, 0x5b, 0x99, 0x59, 0x96, 0xa2, 0xee, 0xe0, 0x23, 0x37, 0x39, 0x1f, 0xe6, 0x57, 0x9f, 0xf8, 0xf8, 0xdc, 0x74, 0xf6, 0x8f, 0x4f, 0x5e, 0x51, 0xa4, 0x12, 0xac, 0xbe, 0xe4, 0xf3, 0xd1, 0xf0, 0x24, - /* (2^127)P */ 0x1e, 0x3e, 0x9a, 0x5f, 0xdf, 0x9f, 0xd6, 0x4e, 0x8a, 0x28, 0xc3, 0xcd, 0x96, 0x9d, 0x57, 0xc7, 0x61, 0x81, 0x90, 0xff, 0xae, 0xb1, 0x4f, 0xc2, 0x96, 0x8b, 0x1a, 0x18, 0xf4, 0x50, 0xcb, 0x31, 0xe1, 0x57, 0xf4, 0x90, 0xa8, 0xea, 0xac, 0xe7, 0x61, 0x98, 0xb6, 0x15, 0xc1, 0x7b, 0x29, 0xa4, 0xc3, 0x18, 0xef, 0xb9, 0xd8, 0xdf, 0xf6, 0xac, - /* (2^128)P */ 0xca, 0xa8, 0x6c, 0xf1, 0xb4, 0xca, 0xfe, 0x31, 0xee, 0x48, 0x38, 0x8b, 0x0e, 0xbb, 0x7a, 0x30, 0xaa, 0xf9, 0xee, 0x27, 0x53, 0x24, 0xdc, 0x2e, 0x15, 0xa6, 0x48, 0x8f, 0xa0, 0x7e, 0xf1, 0xdc, 0x93, 0x87, 0x39, 0xeb, 0x7f, 0x38, 0x92, 0x92, 0x4c, 0x29, 0xe9, 0x57, 0xd8, 0x59, 0xfc, 0xe9, 0x9c, 0x44, 0xc0, 0x65, 0xcf, 0xac, 0x4b, 0xdc, - /* (2^129)P */ 0xa3, 0xd0, 0x37, 0x8f, 0x86, 0x2f, 0xc6, 0x47, 0x55, 0x46, 0x65, 0x26, 0x4b, 0x91, 0xe2, 0x18, 0x5c, 0x4f, 0x23, 0xc1, 0x37, 0x29, 0xb9, 0xc1, 0x27, 0xc5, 0x3c, 0xbf, 0x7e, 0x23, 0xdb, 0x73, 0x99, 0xbd, 0x1b, 0xb2, 0x31, 0x68, 0x3a, 0xad, 0xb7, 0xb0, 0x10, 0xc5, 0xe5, 0x11, 0x51, 0xba, 0xa7, 0x60, 0x66, 0x54, 0xf0, 0x08, 0xd7, 0x69, - /* (2^130)P */ 0x89, 0x41, 0x79, 0xcc, 0xeb, 0x0a, 0xf5, 0x4b, 0xa3, 0x4c, 0xce, 0x52, 0xb0, 0xa7, 0xe4, 0x41, 0x75, 0x7d, 0x04, 0xbb, 0x09, 0x4c, 0x50, 0x9f, 0xdf, 0xea, 0x74, 0x61, 0x02, 0xad, 0xb4, 0x9d, 0xb7, 0x05, 0xb9, 0xea, 0xeb, 0x91, 0x35, 0xe7, 0x49, 0xea, 0xd3, 0x4f, 0x3c, 0x60, 0x21, 0x7a, 0xde, 0xc7, 0xe2, 0x5a, 0xee, 0x8e, 0x93, 0xc7, - /* (2^131)P */ 0x00, 0xe8, 0xed, 0xd0, 0xb3, 0x0d, 0xaf, 0xb2, 0xde, 0x2c, 0xf6, 0x00, 0xe2, 0xea, 0x6d, 0xf8, 0x0e, 0xd9, 0x67, 0x59, 0xa9, 0x50, 0xbb, 0x17, 0x8f, 0xff, 0xb1, 0x9f, 0x17, 0xb6, 0xf2, 0xb5, 0xba, 0x80, 0xf7, 0x0f, 0xba, 0xd5, 0x09, 0x43, 0xaa, 0x4e, 0x3a, 0x67, 0x6a, 0x89, 0x9b, 0x18, 0x65, 0x35, 0xf8, 0x3a, 0x49, 0x91, 0x30, 0x51, - /* (2^132)P */ 0x8d, 0x25, 0xe9, 0x0e, 0x7d, 0x50, 0x76, 0xe4, 0x58, 0x7e, 0xb9, 0x33, 0xe6, 0x65, 0x90, 0xc2, 0x50, 0x9d, 0x50, 0x2e, 0x11, 0xad, 0xd5, 0x43, 0x52, 0x32, 0x41, 0x4f, 0x7b, 0xb6, 0xa0, 0xec, 0x81, 0x75, 0x36, 0x7c, 0x77, 0x85, 0x59, 0x70, 0xe4, 0xf9, 0xef, 0x66, 0x8d, 0x35, 0xc8, 0x2a, 0x6e, 0x5b, 0xc6, 0x0d, 0x0b, 0x29, 0x60, 0x68, - /* (2^133)P */ 0xf8, 0xce, 0xb0, 0x3a, 0x56, 0x7d, 0x51, 0x9a, 0x25, 0x73, 0xea, 0xdd, 0xe4, 0xe0, 0x0e, 0xf0, 0x07, 0xc0, 0x31, 0x00, 0x73, 0x35, 0xd0, 0x39, 0xc4, 0x9b, 0xb7, 0x95, 0xe0, 0x62, 0x70, 0x36, 0x0b, 0xcb, 0xa0, 0x42, 0xde, 0x51, 0xcf, 0x41, 0xe0, 0xb8, 0xb4, 0xc0, 0xe5, 0x46, 0x99, 0x9f, 0x02, 0x7f, 0x14, 0x8c, 0xc1, 0x4e, 0xef, 0xe8, - /* (2^134)P */ 0x10, 0x01, 0x57, 0x0a, 0xbe, 0x8b, 0x18, 0xc8, 0xca, 0x00, 0x28, 0x77, 0x4a, 0x9a, 0xc7, 0x55, 0x2a, 0xcc, 0x0c, 0x7b, 0xb9, 0xe9, 0xc8, 0x97, 0x7c, 0x02, 0xe3, 0x09, 0x2f, 0x62, 0x30, 0xb8, 0x40, 0x09, 0x65, 0xe9, 0x55, 0x63, 0xb5, 0x07, 0xca, 0x9f, 0x00, 0xdf, 0x9d, 0x5c, 0xc7, 0xee, 0x57, 0xa5, 0x90, 0x15, 0x1e, 0x22, 0xa0, 0x12, - /* (2^135)P */ 0x71, 0x2d, 0xc9, 0xef, 0x27, 0xb9, 0xd8, 0x12, 0x43, 0x6b, 0xa8, 0xce, 0x3b, 0x6d, 0x6e, 0x91, 0x43, 0x23, 0xbc, 0x32, 0xb3, 0xbf, 0xe1, 0xc7, 0x39, 0xcf, 0x7c, 0x42, 0x4c, 0xb1, 0x30, 0xe2, 0xdd, 0x69, 0x06, 0xe5, 0xea, 0xf0, 0x2a, 0x16, 0x50, 0x71, 0xca, 0x92, 0xdf, 0xc1, 0xcc, 0xec, 0xe6, 0x54, 0x07, 0xf3, 0x18, 0x8d, 0xd8, 0x29, - /* (2^136)P */ 0x98, 0x51, 0x48, 0x8f, 0xfa, 0x2e, 0x5e, 0x67, 0xb0, 0xc6, 0x17, 0x12, 0xb6, 0x7d, 0xc9, 0xad, 0x81, 0x11, 0xad, 0x0c, 0x1c, 0x2d, 0x45, 0xdf, 0xac, 0x66, 0xbd, 0x08, 0x6f, 0x7c, 0xc7, 0x06, 0x6e, 0x19, 0x08, 0x39, 0x64, 0xd7, 0xe4, 0xd1, 0x11, 0x5f, 0x1c, 0xf4, 0x67, 0xc3, 0x88, 0x6a, 0xe6, 0x07, 0xa3, 0x83, 0xd7, 0xfd, 0x2a, 0xf9, - /* (2^137)P */ 0x87, 0xed, 0xeb, 0xd9, 0xdf, 0xff, 0x43, 0x8b, 0xaa, 0x20, 0x58, 0xb0, 0xb4, 0x6b, 0x14, 0xb8, 0x02, 0xc5, 0x40, 0x20, 0x22, 0xbb, 0xf7, 0xb4, 0xf3, 0x05, 0x1e, 0x4d, 0x94, 0xff, 0xe3, 0xc5, 0x22, 0x82, 0xfe, 0xaf, 0x90, 0x42, 0x98, 0x6b, 0x76, 0x8b, 0x3e, 0x89, 0x3f, 0x42, 0x2a, 0xa7, 0x26, 0x00, 0xda, 0x5c, 0xa2, 0x2b, 0xec, 0xdd, - /* (2^138)P */ 0x5c, 0x21, 0x16, 0x0d, 0x46, 0xb8, 0xd0, 0xa7, 0x88, 0xe7, 0x25, 0xcb, 0x3e, 0x50, 0x73, 0x61, 0xe7, 0xaf, 0x5a, 0x3f, 0x47, 0x8b, 0x3d, 0x97, 0x79, 0x2c, 0xe6, 0x6d, 0x95, 0x74, 0x65, 0x70, 0x36, 0xfd, 0xd1, 0x9e, 0x13, 0x18, 0x63, 0xb1, 0x2d, 0x0b, 0xb5, 0x36, 0x3e, 0xe7, 0x35, 0x42, 0x3b, 0xe6, 0x1f, 0x4d, 0x9d, 0x59, 0xa2, 0x43, - /* (2^139)P */ 0x8c, 0x0c, 0x7c, 0x24, 0x9e, 0xe0, 0xf8, 0x05, 0x1c, 0x9e, 0x1f, 0x31, 0xc0, 0x70, 0xb3, 0xfb, 0x4e, 0xf8, 0x0a, 0x57, 0xb7, 0x49, 0xb5, 0x73, 0xa1, 0x5f, 0x9b, 0x6a, 0x07, 0x6c, 0x87, 0x71, 0x87, 0xd4, 0xbe, 0x98, 0x1e, 0x98, 0xee, 0x52, 0xc1, 0x7b, 0x95, 0x0f, 0x28, 0x32, 0x36, 0x28, 0xd0, 0x3a, 0x0f, 0x7d, 0x2a, 0xa9, 0x62, 0xb9, - /* (2^140)P */ 0x97, 0xe6, 0x18, 0x77, 0xf9, 0x34, 0xac, 0xbc, 0xe0, 0x62, 0x9f, 0x42, 0xde, 0xbd, 0x2f, 0xf7, 0x1f, 0xb7, 0x14, 0x52, 0x8a, 0x79, 0xb2, 0x3f, 0xd2, 0x95, 0x71, 0x01, 0xe8, 0xaf, 0x8c, 0xa4, 0xa4, 0xa7, 0x27, 0xf3, 0x5c, 0xdf, 0x3e, 0x57, 0x7a, 0xf1, 0x76, 0x49, 0xe6, 0x42, 0x3f, 0x8f, 0x1e, 0x63, 0x4a, 0x65, 0xb5, 0x41, 0xf5, 0x02, - /* (2^141)P */ 0x72, 0x85, 0xc5, 0x0b, 0xe1, 0x47, 0x64, 0x02, 0xc5, 0x4d, 0x81, 0x69, 0xb2, 0xcf, 0x0f, 0x6c, 0xd4, 0x6d, 0xd0, 0xc7, 0xb4, 0x1c, 0xd0, 0x32, 0x59, 0x89, 0xe2, 0xe0, 0x96, 0x8b, 0x12, 0x98, 0xbf, 0x63, 0x7a, 0x4c, 0x76, 0x7e, 0x58, 0x17, 0x8f, 0x5b, 0x0a, 0x59, 0x65, 0x75, 0xbc, 0x61, 0x1f, 0xbe, 0xc5, 0x6e, 0x0a, 0x57, 0x52, 0x70, - /* (2^142)P */ 0x92, 0x1c, 0x77, 0xbb, 0x62, 0x02, 0x6c, 0x25, 0x9c, 0x66, 0x07, 0x83, 0xab, 0xcc, 0x80, 0x5d, 0xd2, 0x76, 0x0c, 0xa4, 0xc5, 0xb4, 0x8a, 0x68, 0x23, 0x31, 0x32, 0x29, 0x8a, 0x47, 0x92, 0x12, 0x80, 0xb3, 0xfa, 0x18, 0xe4, 0x8d, 0xc0, 0x4d, 0xfe, 0x97, 0x5f, 0x72, 0x41, 0xb5, 0x5c, 0x7a, 0xbd, 0xf0, 0xcf, 0x5e, 0x97, 0xaa, 0x64, 0x32, - /* (2^143)P */ 0x35, 0x3f, 0x75, 0xc1, 0x7a, 0x75, 0x7e, 0xa9, 0xc6, 0x0b, 0x4e, 0x32, 0x62, 0xec, 0xe3, 0x5c, 0xfb, 0x01, 0x43, 0xb6, 0xd4, 0x5b, 0x75, 0xd2, 0xee, 0x7f, 0x5d, 0x23, 0x2b, 0xb3, 0x54, 0x34, 0x4c, 0xd3, 0xb4, 0x32, 0x84, 0x81, 0xb5, 0x09, 0x76, 0x19, 0xda, 0x58, 0xda, 0x7c, 0xdb, 0x2e, 0xdd, 0x4c, 0x8e, 0xdd, 0x5d, 0x89, 0x10, 0x10, - /* (2^144)P */ 0x57, 0x25, 0x6a, 0x08, 0x37, 0x92, 0xa8, 0xdf, 0x24, 0xef, 0x8f, 0x33, 0x34, 0x52, 0xa4, 0x4c, 0xf0, 0x77, 0x9f, 0x69, 0x77, 0xd5, 0x8f, 0xd2, 0x9a, 0xb3, 0xb6, 0x1d, 0x2d, 0xa6, 0xf7, 0x1f, 0xda, 0xd7, 0xcb, 0x75, 0x11, 0xc3, 0x6b, 0xc0, 0x38, 0xb1, 0xd5, 0x2d, 0x96, 0x84, 0x16, 0xfa, 0x26, 0xb9, 0xcc, 0x3f, 0x16, 0x47, 0x23, 0x74, - /* (2^145)P */ 0x9b, 0x61, 0x2a, 0x1c, 0xdd, 0x39, 0xa5, 0xfa, 0x1c, 0x7d, 0x63, 0x50, 0xca, 0xe6, 0x9d, 0xfa, 0xb7, 0xc4, 0x4c, 0x6a, 0x97, 0x5f, 0x36, 0x4e, 0x47, 0xdd, 0x17, 0xf7, 0xf9, 0x19, 0xce, 0x75, 0x17, 0xad, 0xce, 0x2a, 0xf3, 0xfe, 0x27, 0x8f, 0x3e, 0x48, 0xc0, 0x60, 0x87, 0x24, 0x19, 0xae, 0x59, 0xe4, 0x5a, 0x00, 0x2a, 0xba, 0xa2, 0x1f, - /* (2^146)P */ 0x26, 0x88, 0x42, 0x60, 0x9f, 0x6e, 0x2c, 0x7c, 0x39, 0x0f, 0x47, 0x6a, 0x0e, 0x02, 0xbb, 0x4b, 0x34, 0x29, 0x55, 0x18, 0x36, 0xcf, 0x3b, 0x47, 0xf1, 0x2e, 0xfc, 0x6e, 0x94, 0xff, 0xe8, 0x6b, 0x06, 0xd2, 0xba, 0x77, 0x5e, 0x60, 0xd7, 0x19, 0xef, 0x02, 0x9d, 0x3a, 0xc2, 0xb7, 0xa9, 0xd8, 0x57, 0xee, 0x7e, 0x2b, 0xf2, 0x6d, 0x28, 0xda, - /* (2^147)P */ 0xdf, 0xd9, 0x92, 0x11, 0x98, 0x23, 0xe2, 0x45, 0x2f, 0x74, 0x70, 0xee, 0x0e, 0x55, 0x65, 0x79, 0x86, 0x38, 0x17, 0x92, 0x85, 0x87, 0x99, 0x50, 0xd9, 0x7c, 0xdb, 0xa1, 0x10, 0xec, 0x30, 0xb7, 0x40, 0xa3, 0x23, 0x9b, 0x0e, 0x27, 0x49, 0x29, 0x03, 0x94, 0xff, 0x53, 0xdc, 0xd7, 0xed, 0x49, 0xa9, 0x5a, 0x3b, 0xee, 0xd7, 0xc7, 0x65, 0xaf, - /* (2^148)P */ 0xa0, 0xbd, 0xbe, 0x03, 0xee, 0x0c, 0xbe, 0x32, 0x00, 0x7b, 0x52, 0xcb, 0x92, 0x29, 0xbf, 0xa0, 0xc6, 0xd9, 0xd2, 0xd6, 0x15, 0xe8, 0x3a, 0x75, 0x61, 0x65, 0x56, 0xae, 0xad, 0x3c, 0x2a, 0x64, 0x14, 0x3f, 0x8e, 0xc1, 0x2d, 0x0c, 0x8d, 0x20, 0xdb, 0x58, 0x4b, 0xe5, 0x40, 0x15, 0x4b, 0xdc, 0xa8, 0xbd, 0xef, 0x08, 0xa7, 0xd1, 0xf4, 0xb0, - /* (2^149)P */ 0xa9, 0x0f, 0x05, 0x94, 0x66, 0xac, 0x1f, 0x65, 0x3f, 0xe1, 0xb8, 0xe1, 0x34, 0x5e, 0x1d, 0x8f, 0xe3, 0x93, 0x03, 0x15, 0xff, 0xb6, 0x65, 0xb6, 0x6e, 0xc0, 0x2f, 0xd4, 0x2e, 0xb9, 0x2c, 0x13, 0x3c, 0x99, 0x1c, 0xb5, 0x87, 0xba, 0x79, 0xcb, 0xf0, 0x18, 0x06, 0x86, 0x04, 0x14, 0x25, 0x09, 0xcd, 0x1c, 0x14, 0xda, 0x35, 0xd0, 0x38, 0x3b, - /* (2^150)P */ 0x1b, 0x04, 0xa3, 0x27, 0xb4, 0xd3, 0x37, 0x48, 0x1e, 0x8f, 0x69, 0xd3, 0x5a, 0x2f, 0x20, 0x02, 0x36, 0xbe, 0x06, 0x7b, 0x6b, 0x6c, 0x12, 0x5b, 0x80, 0x74, 0x44, 0xe6, 0xf8, 0xf5, 0x95, 0x59, 0x29, 0xab, 0x51, 0x47, 0x83, 0x28, 0xe0, 0xad, 0xde, 0xaa, 0xd3, 0xb1, 0x1a, 0xcb, 0xa3, 0xcd, 0x8b, 0x6a, 0xb1, 0xa7, 0x0a, 0xd1, 0xf9, 0xbe, - /* (2^151)P */ 0xce, 0x2f, 0x85, 0xca, 0x74, 0x6d, 0x49, 0xb8, 0xce, 0x80, 0x44, 0xe0, 0xda, 0x5b, 0xcf, 0x2f, 0x79, 0x74, 0xfe, 0xb4, 0x2c, 0x99, 0x20, 0x6e, 0x09, 0x04, 0xfb, 0x6d, 0x57, 0x5b, 0x95, 0x0c, 0x45, 0xda, 0x4f, 0x7f, 0x63, 0xcc, 0x85, 0x5a, 0x67, 0x50, 0x68, 0x71, 0xb4, 0x67, 0xb1, 0x2e, 0xc1, 0x1c, 0xdc, 0xff, 0x2a, 0x7c, 0x10, 0x5e, - /* (2^152)P */ 0xa6, 0xde, 0xf3, 0xd4, 0x22, 0x30, 0x24, 0x9e, 0x0b, 0x30, 0x54, 0x59, 0x7e, 0xa2, 0xeb, 0x89, 0x54, 0x65, 0x3e, 0x40, 0xd1, 0xde, 0xe6, 0xee, 0x4d, 0xbf, 0x5e, 0x40, 0x1d, 0xee, 0x4f, 0x68, 0xd9, 0xa7, 0x2f, 0xb3, 0x64, 0xb3, 0xf5, 0xc8, 0xd3, 0xaa, 0x70, 0x70, 0x3d, 0xef, 0xd3, 0x95, 0x54, 0xdb, 0x3e, 0x94, 0x95, 0x92, 0x1f, 0x45, - /* (2^153)P */ 0x22, 0x80, 0x1d, 0x9d, 0x96, 0xa5, 0x78, 0x6f, 0xe0, 0x1e, 0x1b, 0x66, 0x42, 0xc8, 0xae, 0x9e, 0x46, 0x45, 0x08, 0x41, 0xdf, 0x80, 0xae, 0x6f, 0xdb, 0x15, 0x5a, 0x21, 0x31, 0x7a, 0xd0, 0xf2, 0x54, 0x15, 0x88, 0xd3, 0x0f, 0x7f, 0x14, 0x5a, 0x14, 0x97, 0xab, 0xf4, 0x58, 0x6a, 0x9f, 0xea, 0x74, 0xe5, 0x6b, 0x90, 0x59, 0x2b, 0x48, 0xd9, - /* (2^154)P */ 0x12, 0x24, 0x04, 0xf5, 0x50, 0xc2, 0x8c, 0xb0, 0x7c, 0x46, 0x98, 0xd5, 0x24, 0xad, 0xf6, 0x72, 0xdc, 0x82, 0x1a, 0x60, 0xc1, 0xeb, 0x48, 0xef, 0x7f, 0x6e, 0xe6, 0xcc, 0xdb, 0x7b, 0xae, 0xbe, 0x5e, 0x1e, 0x5c, 0xe6, 0x0a, 0x70, 0xdf, 0xa4, 0xa3, 0x85, 0x1b, 0x1b, 0x7f, 0x72, 0xb9, 0x96, 0x6f, 0xdc, 0x03, 0x76, 0x66, 0xfb, 0xa0, 0x33, - /* (2^155)P */ 0x37, 0x40, 0xbb, 0xbc, 0x68, 0x58, 0x86, 0xca, 0xbb, 0xa5, 0x24, 0x76, 0x3d, 0x48, 0xd1, 0xad, 0xb4, 0xa8, 0xcf, 0xc3, 0xb6, 0xa8, 0xba, 0x1a, 0x3a, 0xbe, 0x33, 0x75, 0x04, 0x5c, 0x13, 0x8c, 0x0d, 0x70, 0x8d, 0xa6, 0x4e, 0x2a, 0xeb, 0x17, 0x3c, 0x22, 0xdd, 0x3e, 0x96, 0x40, 0x11, 0x9e, 0x4e, 0xae, 0x3d, 0xf8, 0x91, 0xd7, 0x50, 0xc8, - /* (2^156)P */ 0xd8, 0xca, 0xde, 0x19, 0xcf, 0x00, 0xe4, 0x73, 0x18, 0x7f, 0x9b, 0x9f, 0xf4, 0x5b, 0x49, 0x49, 0x99, 0xdc, 0xa4, 0x46, 0x21, 0xb5, 0xd7, 0x3e, 0xb7, 0x47, 0x1b, 0xa9, 0x9f, 0x4c, 0x69, 0x7d, 0xec, 0x33, 0xd6, 0x1c, 0x51, 0x7f, 0x47, 0x74, 0x7a, 0x6c, 0xf3, 0xd2, 0x2e, 0xbf, 0xdf, 0x6c, 0x9e, 0x77, 0x3b, 0x34, 0xf6, 0x73, 0x80, 0xed, - /* (2^157)P */ 0x16, 0xfb, 0x16, 0xc3, 0xc2, 0x83, 0xe4, 0xf4, 0x03, 0x7f, 0x52, 0xb0, 0x67, 0x51, 0x7b, 0x24, 0x5a, 0x51, 0xd3, 0xb6, 0x4e, 0x59, 0x76, 0xcd, 0x08, 0x7b, 0x1d, 0x7a, 0x9c, 0x65, 0xae, 0xce, 0xaa, 0xd2, 0x1c, 0x85, 0x66, 0x68, 0x06, 0x15, 0xa8, 0x06, 0xe6, 0x16, 0x37, 0xf4, 0x49, 0x9e, 0x0f, 0x50, 0x37, 0xb1, 0xb2, 0x93, 0x70, 0x43, - /* (2^158)P */ 0x18, 0x3a, 0x16, 0xe5, 0x8d, 0xc8, 0x35, 0xd6, 0x7b, 0x09, 0xec, 0x61, 0x5f, 0x5c, 0x2a, 0x19, 0x96, 0x2e, 0xc3, 0xfd, 0xab, 0xe6, 0x23, 0xae, 0xab, 0xc5, 0xcb, 0xb9, 0x7b, 0x2d, 0x34, 0x51, 0xb9, 0x41, 0x9e, 0x7d, 0xca, 0xda, 0x25, 0x45, 0x14, 0xb0, 0xc7, 0x4d, 0x26, 0x2b, 0xfe, 0x43, 0xb0, 0x21, 0x5e, 0xfa, 0xdc, 0x7c, 0xf9, 0x5a, - /* (2^159)P */ 0x94, 0xad, 0x42, 0x17, 0xf5, 0xcd, 0x1c, 0x0d, 0xf6, 0x41, 0xd2, 0x55, 0xbb, 0x50, 0xf1, 0xc6, 0xbc, 0xa6, 0xc5, 0x3a, 0xfd, 0x9b, 0x75, 0x3e, 0xf6, 0x1a, 0xa7, 0xb2, 0x6e, 0x64, 0x12, 0xdc, 0x3c, 0xe5, 0xf6, 0xfc, 0x3b, 0xfa, 0x43, 0x81, 0xd4, 0xa5, 0xee, 0xf5, 0x9c, 0x47, 0x2f, 0xd0, 0x9c, 0xde, 0xa1, 0x48, 0x91, 0x9a, 0x34, 0xc1, - /* (2^160)P */ 0x37, 0x1b, 0xb3, 0x88, 0xc9, 0x98, 0x4e, 0xfb, 0x84, 0x4f, 0x2b, 0x0a, 0xb6, 0x8f, 0x35, 0x15, 0xcd, 0x61, 0x7a, 0x5f, 0x5c, 0xa0, 0xca, 0x23, 0xa0, 0x93, 0x1f, 0xcc, 0x3c, 0x39, 0x3a, 0x24, 0xa7, 0x49, 0xad, 0x8d, 0x59, 0xcc, 0x94, 0x5a, 0x16, 0xf5, 0x70, 0xe8, 0x52, 0x1e, 0xee, 0x20, 0x30, 0x17, 0x7e, 0xf0, 0x4c, 0x93, 0x06, 0x5a, - /* (2^161)P */ 0x81, 0xba, 0x3b, 0xd7, 0x3e, 0xb4, 0x32, 0x3a, 0x22, 0x39, 0x2a, 0xfc, 0x19, 0xd9, 0xd2, 0xf6, 0xc5, 0x79, 0x6c, 0x0e, 0xde, 0xda, 0x01, 0xff, 0x52, 0xfb, 0xb6, 0x95, 0x4e, 0x7a, 0x10, 0xb8, 0x06, 0x86, 0x3c, 0xcd, 0x56, 0xd6, 0x15, 0xbf, 0x6e, 0x3e, 0x4f, 0x35, 0x5e, 0xca, 0xbc, 0xa5, 0x95, 0xa2, 0xdf, 0x2d, 0x1d, 0xaf, 0x59, 0xf9, - /* (2^162)P */ 0x69, 0xe5, 0xe2, 0xfa, 0xc9, 0x7f, 0xdd, 0x09, 0xf5, 0x6b, 0x4e, 0x2e, 0xbe, 0xb4, 0xbf, 0x3e, 0xb2, 0xf2, 0x81, 0x30, 0xe1, 0x07, 0xa8, 0x0d, 0x2b, 0xd2, 0x5a, 0x55, 0xbe, 0x4b, 0x86, 0x5d, 0xb0, 0x5e, 0x7c, 0x8f, 0xc1, 0x3c, 0x81, 0x4c, 0xf7, 0x6d, 0x7d, 0xe6, 0x4f, 0x8a, 0x85, 0xc2, 0x2f, 0x28, 0xef, 0x8c, 0x69, 0xc2, 0xc2, 0x1a, - /* (2^163)P */ 0xd9, 0xe4, 0x0e, 0x1e, 0xc2, 0xf7, 0x2f, 0x9f, 0xa1, 0x40, 0xfe, 0x46, 0x16, 0xaf, 0x2e, 0xd1, 0xec, 0x15, 0x9b, 0x61, 0x92, 0xce, 0xfc, 0x10, 0x43, 0x1d, 0x00, 0xf6, 0xbe, 0x20, 0x80, 0x80, 0x6f, 0x3c, 0x16, 0x94, 0x59, 0xba, 0x03, 0x53, 0x6e, 0xb6, 0xdd, 0x25, 0x7b, 0x86, 0xbf, 0x96, 0xf4, 0x2f, 0xa1, 0x96, 0x8d, 0xf9, 0xb3, 0x29, - /* (2^164)P */ 0x3b, 0x04, 0x60, 0x6e, 0xce, 0xab, 0xd2, 0x63, 0x18, 0x53, 0x88, 0x16, 0x4a, 0x6a, 0xab, 0x72, 0x03, 0x68, 0xa5, 0xd4, 0x0d, 0xb2, 0x82, 0x81, 0x1f, 0x2b, 0x5c, 0x75, 0xe8, 0xd2, 0x1d, 0x7f, 0xe7, 0x1b, 0x35, 0x02, 0xde, 0xec, 0xbd, 0xcb, 0xc7, 0x01, 0xd3, 0x95, 0x61, 0xfe, 0xb2, 0x7a, 0x66, 0x09, 0x4c, 0x6d, 0xfd, 0x39, 0xf7, 0x52, - /* (2^165)P */ 0x42, 0xc1, 0x5f, 0xf8, 0x35, 0x52, 0xc1, 0xfe, 0xc5, 0x11, 0x80, 0x1c, 0x11, 0x46, 0x31, 0x11, 0xbe, 0xd0, 0xc4, 0xb6, 0x07, 0x13, 0x38, 0xa0, 0x8d, 0x65, 0xf0, 0x56, 0x9e, 0x16, 0xbf, 0x9d, 0xcd, 0x51, 0x34, 0xf9, 0x08, 0x48, 0x7b, 0x76, 0x0c, 0x7b, 0x30, 0x07, 0xa8, 0x76, 0xaf, 0xa3, 0x29, 0x38, 0xb0, 0x58, 0xde, 0x72, 0x4b, 0x45, - /* (2^166)P */ 0xd4, 0x16, 0xa7, 0xc0, 0xb4, 0x9f, 0xdf, 0x1a, 0x37, 0xc8, 0x35, 0xed, 0xc5, 0x85, 0x74, 0x64, 0x09, 0x22, 0xef, 0xe9, 0x0c, 0xaf, 0x12, 0x4c, 0x9e, 0xf8, 0x47, 0x56, 0xe0, 0x7f, 0x4e, 0x24, 0x6b, 0x0c, 0xe7, 0xad, 0xc6, 0x47, 0x1d, 0xa4, 0x0d, 0x86, 0x89, 0x65, 0xe8, 0x5f, 0x71, 0xc7, 0xe9, 0xcd, 0xec, 0x6c, 0x62, 0xc7, 0xe3, 0xb3, - /* (2^167)P */ 0xb5, 0xea, 0x86, 0xe3, 0x15, 0x18, 0x3f, 0x6d, 0x7b, 0x05, 0x95, 0x15, 0x53, 0x26, 0x1c, 0xeb, 0xbe, 0x7e, 0x16, 0x42, 0x4b, 0xa2, 0x3d, 0xdd, 0x0e, 0xff, 0xba, 0x67, 0xb5, 0xae, 0x7a, 0x17, 0xde, 0x23, 0xad, 0x14, 0xcc, 0xd7, 0xaf, 0x57, 0x01, 0xe0, 0xdd, 0x48, 0xdd, 0xd7, 0xe3, 0xdf, 0xe9, 0x2d, 0xda, 0x67, 0xa4, 0x9f, 0x29, 0x04, - /* (2^168)P */ 0x16, 0x53, 0xe6, 0x9c, 0x4e, 0xe5, 0x1e, 0x70, 0x81, 0x25, 0x02, 0x9b, 0x47, 0x6d, 0xd2, 0x08, 0x73, 0xbe, 0x0a, 0xf1, 0x7b, 0xeb, 0x24, 0xeb, 0x38, 0x23, 0x5c, 0xb6, 0x3e, 0xce, 0x1e, 0xe3, 0xbc, 0x82, 0x35, 0x1f, 0xaf, 0x3a, 0x3a, 0xe5, 0x4e, 0xc1, 0xca, 0xbf, 0x47, 0xb4, 0xbb, 0xbc, 0x5f, 0xea, 0xc6, 0xca, 0xf3, 0xa0, 0xa2, 0x73, - /* (2^169)P */ 0xef, 0xa4, 0x7a, 0x4e, 0xe4, 0xc7, 0xb6, 0x43, 0x2e, 0xa5, 0xe4, 0xa5, 0xba, 0x1e, 0xa5, 0xfe, 0x9e, 0xce, 0xa9, 0x80, 0x04, 0xcb, 0x4f, 0xd8, 0x74, 0x05, 0x48, 0xfa, 0x99, 0x11, 0x5d, 0x97, 0x3b, 0x07, 0x0d, 0xdd, 0xe6, 0xb1, 0x74, 0x87, 0x1a, 0xd3, 0x26, 0xb7, 0x8f, 0xe1, 0x63, 0x3d, 0xec, 0x53, 0x93, 0xb0, 0x81, 0x78, 0x34, 0xa4, - /* (2^170)P */ 0xe1, 0xe7, 0xd4, 0x58, 0x9d, 0x0e, 0x8b, 0x65, 0x66, 0x37, 0x16, 0x48, 0x6f, 0xaa, 0x42, 0x37, 0x77, 0xad, 0xb1, 0x56, 0x48, 0xdf, 0x65, 0x36, 0x30, 0xb8, 0x00, 0x12, 0xd8, 0x32, 0x28, 0x7f, 0xc1, 0x71, 0xeb, 0x93, 0x0f, 0x48, 0x04, 0xe1, 0x5a, 0x6a, 0x96, 0xc1, 0xca, 0x89, 0x6d, 0x1b, 0x82, 0x4c, 0x18, 0x6d, 0x55, 0x4b, 0xea, 0xfd, - /* (2^171)P */ 0x62, 0x1a, 0x53, 0xb4, 0xb1, 0xbe, 0x6f, 0x15, 0x18, 0x88, 0xd4, 0x66, 0x61, 0xc7, 0x12, 0x69, 0x02, 0xbd, 0x03, 0x23, 0x2b, 0xef, 0xf9, 0x54, 0xa4, 0x85, 0xa8, 0xe3, 0xb7, 0xbd, 0xa9, 0xa3, 0xf3, 0x2a, 0xdd, 0xf1, 0xd4, 0x03, 0x0f, 0xa9, 0xa1, 0xd8, 0xa3, 0xcd, 0xb2, 0x71, 0x90, 0x4b, 0x35, 0x62, 0xf2, 0x2f, 0xce, 0x67, 0x1f, 0xaa, - /* (2^172)P */ 0x9e, 0x1e, 0xcd, 0x43, 0x7e, 0x87, 0x37, 0x94, 0x3a, 0x97, 0x4c, 0x7e, 0xee, 0xc9, 0x37, 0x85, 0xf1, 0xd9, 0x4f, 0xbf, 0xf9, 0x6f, 0x39, 0x9a, 0x39, 0x87, 0x2e, 0x25, 0x84, 0x42, 0xc3, 0x80, 0xcb, 0x07, 0x22, 0xae, 0x30, 0xd5, 0x50, 0xa1, 0x23, 0xcc, 0x31, 0x81, 0x9d, 0xf1, 0x30, 0xd9, 0x2b, 0x73, 0x41, 0x16, 0x50, 0xab, 0x2d, 0xa2, - /* (2^173)P */ 0xa4, 0x69, 0x4f, 0xa1, 0x4e, 0xb9, 0xbf, 0x14, 0xe8, 0x2b, 0x04, 0x93, 0xb7, 0x6e, 0x9f, 0x7d, 0x73, 0x0a, 0xc5, 0x14, 0xb8, 0xde, 0x8c, 0xc1, 0xfe, 0xc0, 0xa7, 0xa4, 0xcc, 0x42, 0x42, 0x81, 0x15, 0x65, 0x8a, 0x80, 0xb9, 0xde, 0x1f, 0x60, 0x33, 0x0e, 0xcb, 0xfc, 0xe0, 0xdb, 0x83, 0xa1, 0xe5, 0xd0, 0x16, 0x86, 0x2c, 0xe2, 0x87, 0xed, - /* (2^174)P */ 0x7a, 0xc0, 0xeb, 0x6b, 0xf6, 0x0d, 0x4c, 0x6d, 0x1e, 0xdb, 0xab, 0xe7, 0x19, 0x45, 0xc6, 0xe3, 0xb2, 0x06, 0xbb, 0xbc, 0x70, 0x99, 0x83, 0x33, 0xeb, 0x28, 0xc8, 0x77, 0xf6, 0x4d, 0x01, 0xb7, 0x59, 0xa0, 0xd2, 0xb3, 0x2a, 0x72, 0x30, 0xe7, 0x11, 0x39, 0xb6, 0x41, 0x29, 0x65, 0x5a, 0x14, 0xb9, 0x86, 0x08, 0xe0, 0x7d, 0x32, 0x8c, 0xf0, - /* (2^175)P */ 0x5c, 0x11, 0x30, 0x9e, 0x05, 0x27, 0xf5, 0x45, 0x0f, 0xb3, 0xc9, 0x75, 0xc3, 0xd7, 0xe1, 0x82, 0x3b, 0x8e, 0x87, 0x23, 0x00, 0x15, 0x19, 0x07, 0xd9, 0x21, 0x53, 0xc7, 0xf1, 0xa3, 0xbf, 0x70, 0x64, 0x15, 0x18, 0xca, 0x23, 0x9e, 0xd3, 0x08, 0xc3, 0x2a, 0x8b, 0xe5, 0x83, 0x04, 0x89, 0x14, 0xfd, 0x28, 0x25, 0x1c, 0xe3, 0x26, 0xa7, 0x22, - /* (2^176)P */ 0xdc, 0xd4, 0x75, 0x60, 0x99, 0x94, 0xea, 0x09, 0x8e, 0x8a, 0x3c, 0x1b, 0xf9, 0xbd, 0x33, 0x0d, 0x51, 0x3d, 0x12, 0x6f, 0x4e, 0x72, 0xe0, 0x17, 0x20, 0xe9, 0x75, 0xe6, 0x3a, 0xb2, 0x13, 0x83, 0x4e, 0x7a, 0x08, 0x9e, 0xd1, 0x04, 0x5f, 0x6b, 0x42, 0x0b, 0x76, 0x2a, 0x2d, 0x77, 0x53, 0x6c, 0x65, 0x6d, 0x8e, 0x25, 0x3c, 0xb6, 0x8b, 0x69, - /* (2^177)P */ 0xb9, 0x49, 0x28, 0xd0, 0xdc, 0x6c, 0x8f, 0x4c, 0xc9, 0x14, 0x8a, 0x38, 0xa3, 0xcb, 0xc4, 0x9d, 0x53, 0xcf, 0xe9, 0xe3, 0xcf, 0xe0, 0xb1, 0xf2, 0x1b, 0x4c, 0x7f, 0x83, 0x2a, 0x7a, 0xe9, 0x8b, 0x3b, 0x86, 0x61, 0x30, 0xe9, 0x99, 0xbd, 0xba, 0x19, 0x6e, 0x65, 0x2a, 0x12, 0x3e, 0x9c, 0xa8, 0xaf, 0xc3, 0xcf, 0xf8, 0x1f, 0x77, 0x86, 0xea, - /* (2^178)P */ 0x30, 0xde, 0xe7, 0xff, 0x54, 0xf7, 0xa2, 0x59, 0xf6, 0x0b, 0xfb, 0x7a, 0xf2, 0x39, 0xf0, 0xdb, 0x39, 0xbc, 0xf0, 0xfa, 0x60, 0xeb, 0x6b, 0x4f, 0x47, 0x17, 0xc8, 0x00, 0x65, 0x6d, 0x25, 0x1c, 0xd0, 0x48, 0x56, 0x53, 0x45, 0x11, 0x30, 0x02, 0x49, 0x20, 0x27, 0xac, 0xf2, 0x4c, 0xac, 0x64, 0x3d, 0x52, 0xb8, 0x89, 0xe0, 0x93, 0x16, 0x0f, - /* (2^179)P */ 0x84, 0x09, 0xba, 0x40, 0xb2, 0x2f, 0xa3, 0xa8, 0xc2, 0xba, 0x46, 0x33, 0x05, 0x9d, 0x62, 0xad, 0xa1, 0x3c, 0x33, 0xef, 0x0d, 0xeb, 0xf0, 0x77, 0x11, 0x5a, 0xb0, 0x21, 0x9c, 0xdf, 0x55, 0x24, 0x25, 0x35, 0x51, 0x61, 0x92, 0xf0, 0xb1, 0xce, 0xf5, 0xd4, 0x7b, 0x6c, 0x21, 0x9d, 0x56, 0x52, 0xf8, 0xa1, 0x4c, 0xe9, 0x27, 0x55, 0xac, 0x91, - /* (2^180)P */ 0x03, 0x3e, 0x30, 0xd2, 0x0a, 0xfa, 0x7d, 0x82, 0x3d, 0x1f, 0x8b, 0xcb, 0xb6, 0x04, 0x5c, 0xcc, 0x8b, 0xda, 0xe2, 0x68, 0x74, 0x08, 0x8c, 0x44, 0x83, 0x57, 0x6d, 0x6f, 0x80, 0xb0, 0x7e, 0xa9, 0x82, 0x91, 0x7b, 0x4c, 0x37, 0x97, 0xd1, 0x63, 0xd1, 0xbd, 0x45, 0xe6, 0x8a, 0x86, 0xd6, 0x89, 0x54, 0xfd, 0xd2, 0xb1, 0xd7, 0x54, 0xad, 0xaf, - /* (2^181)P */ 0x8b, 0x33, 0x62, 0x49, 0x9f, 0x63, 0xf9, 0x87, 0x42, 0x58, 0xbf, 0xb3, 0xe6, 0x68, 0x02, 0x60, 0x5c, 0x76, 0x62, 0xf7, 0x61, 0xd7, 0x36, 0x31, 0xf7, 0x9c, 0xb5, 0xe5, 0x13, 0x6c, 0xea, 0x78, 0xae, 0xcf, 0xde, 0xbf, 0xb6, 0xeb, 0x4f, 0xc8, 0x2a, 0xb4, 0x9a, 0x9f, 0xf3, 0xd1, 0x6a, 0xec, 0x0c, 0xbd, 0x85, 0x98, 0x40, 0x06, 0x1c, 0x2a, - /* (2^182)P */ 0x74, 0x3b, 0xe7, 0x81, 0xd5, 0xae, 0x54, 0x56, 0x03, 0xe8, 0x97, 0x16, 0x76, 0xcf, 0x24, 0x96, 0x96, 0x5b, 0xcc, 0x09, 0xab, 0x23, 0x6f, 0x54, 0xae, 0x8f, 0xe4, 0x12, 0xcb, 0xfd, 0xbc, 0xac, 0x93, 0x45, 0x3d, 0x68, 0x08, 0x22, 0x59, 0xc6, 0xf0, 0x47, 0x19, 0x8c, 0x79, 0x93, 0x1e, 0x0e, 0x30, 0xb0, 0x94, 0xfb, 0x17, 0x1d, 0x5a, 0x12, - /* (2^183)P */ 0x85, 0xff, 0x40, 0x18, 0x85, 0xff, 0x44, 0x37, 0x69, 0x23, 0x4d, 0x34, 0xe1, 0xeb, 0xa3, 0x1b, 0x55, 0x40, 0xc1, 0x64, 0xf4, 0xd4, 0x13, 0x0a, 0x9f, 0xb9, 0x19, 0xfc, 0x88, 0x7d, 0xc0, 0x72, 0xcf, 0x69, 0x2f, 0xd2, 0x0c, 0x82, 0x0f, 0xda, 0x08, 0xba, 0x0f, 0xaa, 0x3b, 0xe9, 0xe5, 0x83, 0x7a, 0x06, 0xe8, 0x1b, 0x38, 0x43, 0xc3, 0x54, - /* (2^184)P */ 0x14, 0xaa, 0xb3, 0x6e, 0xe6, 0x28, 0xee, 0xc5, 0x22, 0x6c, 0x7c, 0xf9, 0xa8, 0x71, 0xcc, 0xfe, 0x68, 0x7e, 0xd3, 0xb8, 0x37, 0x96, 0xca, 0x0b, 0xd9, 0xb6, 0x06, 0xa9, 0xf6, 0x71, 0xe8, 0x31, 0xf7, 0xd8, 0xf1, 0x5d, 0xab, 0xb9, 0xf0, 0x5c, 0x98, 0xcf, 0x22, 0xa2, 0x2a, 0xf6, 0xd0, 0x59, 0xf0, 0x9d, 0xd9, 0x6a, 0x4f, 0x59, 0x57, 0xad, - /* (2^185)P */ 0xd7, 0x2b, 0x3d, 0x38, 0x4c, 0x2e, 0x23, 0x4d, 0x49, 0xa2, 0x62, 0x62, 0xf9, 0x0f, 0xde, 0x08, 0xf3, 0x86, 0x71, 0xb6, 0xc7, 0xf9, 0x85, 0x9c, 0x33, 0xa1, 0xcf, 0x16, 0xaa, 0x60, 0xb9, 0xb7, 0xea, 0xed, 0x01, 0x1c, 0x59, 0xdb, 0x3f, 0x3f, 0x97, 0x2e, 0xf0, 0x09, 0x9f, 0x10, 0x85, 0x5f, 0x53, 0x39, 0xf3, 0x13, 0x40, 0x56, 0x95, 0xf9, - /* (2^186)P */ 0xb4, 0xe3, 0xda, 0xc6, 0x1f, 0x78, 0x8e, 0xac, 0xd4, 0x20, 0x1d, 0xa0, 0xbf, 0x4c, 0x09, 0x16, 0xa7, 0x30, 0xb5, 0x8d, 0x9e, 0xa1, 0x5f, 0x6d, 0x52, 0xf4, 0x71, 0xb6, 0x32, 0x2d, 0x21, 0x51, 0xc6, 0xfc, 0x2f, 0x08, 0xf4, 0x13, 0x6c, 0x55, 0xba, 0x72, 0x81, 0x24, 0x49, 0x0e, 0x4f, 0x06, 0x36, 0x39, 0x6a, 0xc5, 0x81, 0xfc, 0xeb, 0xb2, - /* (2^187)P */ 0x7d, 0x8d, 0xc8, 0x6c, 0xea, 0xb4, 0xb9, 0xe8, 0x40, 0xc9, 0x69, 0xc9, 0x30, 0x05, 0xfd, 0x34, 0x46, 0xfd, 0x94, 0x05, 0x16, 0xf5, 0x4b, 0x13, 0x3d, 0x24, 0x1a, 0xd6, 0x64, 0x2b, 0x9c, 0xe2, 0xa5, 0xd9, 0x98, 0xe0, 0xe8, 0xf4, 0xbc, 0x2c, 0xbd, 0xa2, 0x56, 0xe3, 0x9e, 0x14, 0xdb, 0xbf, 0x05, 0xbf, 0x9a, 0x13, 0x5d, 0xf7, 0x91, 0xa3, - /* (2^188)P */ 0x8b, 0xcb, 0x27, 0xf3, 0x15, 0x26, 0x05, 0x40, 0x0f, 0xa6, 0x15, 0x13, 0x71, 0x95, 0xa2, 0xc6, 0x38, 0x04, 0x67, 0xf8, 0x9a, 0x83, 0x06, 0xaa, 0x25, 0x36, 0x72, 0x01, 0x6f, 0x74, 0x5f, 0xe5, 0x6e, 0x44, 0x99, 0xce, 0x13, 0xbc, 0x82, 0xc2, 0x0d, 0xa4, 0x98, 0x50, 0x38, 0xf3, 0xa2, 0xc5, 0xe5, 0x24, 0x1f, 0x6f, 0x56, 0x3e, 0x07, 0xb2, - /* (2^189)P */ 0xbd, 0x0f, 0x32, 0x60, 0x07, 0xb1, 0xd7, 0x0b, 0x11, 0x07, 0x57, 0x02, 0x89, 0xe8, 0x8b, 0xe8, 0x5a, 0x1f, 0xee, 0x54, 0x6b, 0xff, 0xb3, 0x04, 0x07, 0x57, 0x13, 0x0b, 0x94, 0xa8, 0x4d, 0x81, 0xe2, 0x17, 0x16, 0x45, 0xd4, 0x4b, 0xf7, 0x7e, 0x64, 0x66, 0x20, 0xe8, 0x0b, 0x26, 0xfd, 0xa9, 0x8a, 0x47, 0x52, 0x89, 0x14, 0xd0, 0xd1, 0xa1, - /* (2^190)P */ 0xdc, 0x03, 0xe6, 0x20, 0x44, 0x47, 0x8f, 0x04, 0x16, 0x24, 0x22, 0xc1, 0x55, 0x5c, 0xbe, 0x43, 0xc3, 0x92, 0xc5, 0x54, 0x3d, 0x5d, 0xd1, 0x05, 0x9c, 0xc6, 0x7c, 0xbf, 0x23, 0x84, 0x1a, 0xba, 0x4f, 0x1f, 0xfc, 0xa1, 0xae, 0x1a, 0x64, 0x02, 0x51, 0xf1, 0xcb, 0x7a, 0x20, 0xce, 0xb2, 0x34, 0x3c, 0xca, 0xe0, 0xe4, 0xba, 0x22, 0xd4, 0x7b, - /* (2^191)P */ 0xca, 0xfd, 0xca, 0xd7, 0xde, 0x61, 0xae, 0xf0, 0x79, 0x0c, 0x20, 0xab, 0xbc, 0x6f, 0x4d, 0x61, 0xf0, 0xc7, 0x9c, 0x8d, 0x4b, 0x52, 0xf3, 0xb9, 0x48, 0x63, 0x0b, 0xb6, 0xd2, 0x25, 0x9a, 0x96, 0x72, 0xc1, 0x6b, 0x0c, 0xb5, 0xfb, 0x71, 0xaa, 0xad, 0x47, 0x5b, 0xe7, 0xc0, 0x0a, 0x55, 0xb2, 0xd4, 0x16, 0x2f, 0xb1, 0x01, 0xfd, 0xce, 0x27, - /* (2^192)P */ 0x64, 0x11, 0x4b, 0xab, 0x57, 0x09, 0xc6, 0x49, 0x4a, 0x37, 0xc3, 0x36, 0xc4, 0x7b, 0x81, 0x1f, 0x42, 0xed, 0xbb, 0xe0, 0xa0, 0x8d, 0x51, 0xe6, 0xca, 0x8b, 0xb9, 0xcd, 0x99, 0x2d, 0x91, 0x53, 0xa9, 0x47, 0xcb, 0x32, 0xc7, 0xa4, 0x92, 0xec, 0x46, 0x74, 0x44, 0x6d, 0x71, 0x9f, 0x6d, 0x0c, 0x69, 0xa4, 0xf8, 0xbe, 0x9f, 0x7f, 0xa0, 0xd7, - /* (2^193)P */ 0x5f, 0x33, 0xb6, 0x91, 0xc8, 0xa5, 0x3f, 0x5d, 0x7f, 0x38, 0x6e, 0x74, 0x20, 0x4a, 0xd6, 0x2b, 0x98, 0x2a, 0x41, 0x4b, 0x83, 0x64, 0x0b, 0x92, 0x7a, 0x06, 0x1e, 0xc6, 0x2c, 0xf6, 0xe4, 0x91, 0xe5, 0xb1, 0x2e, 0x6e, 0x4e, 0xa8, 0xc8, 0x14, 0x32, 0x57, 0x44, 0x1c, 0xe4, 0xb9, 0x7f, 0x54, 0x51, 0x08, 0x81, 0xaa, 0x4e, 0xce, 0xa1, 0x5d, - /* (2^194)P */ 0x5c, 0xd5, 0x9b, 0x5e, 0x7c, 0xb5, 0xb1, 0x52, 0x73, 0x00, 0x41, 0x56, 0x79, 0x08, 0x7e, 0x07, 0x28, 0x06, 0xa6, 0xfb, 0x7f, 0x69, 0xbd, 0x7a, 0x3c, 0xae, 0x9f, 0x39, 0xbb, 0x54, 0xa2, 0x79, 0xb9, 0x0e, 0x7f, 0xbb, 0xe0, 0xe6, 0xb7, 0x27, 0x64, 0x38, 0x45, 0xdb, 0x84, 0xe4, 0x61, 0x72, 0x3f, 0xe2, 0x24, 0xfe, 0x7a, 0x31, 0x9a, 0xc9, - /* (2^195)P */ 0xa1, 0xd2, 0xa4, 0xee, 0x24, 0x96, 0xe5, 0x5b, 0x79, 0x78, 0x3c, 0x7b, 0x82, 0x3b, 0x8b, 0x58, 0x0b, 0xa3, 0x63, 0x2d, 0xbc, 0x75, 0x46, 0xe8, 0x83, 0x1a, 0xc0, 0x2a, 0x92, 0x61, 0xa8, 0x75, 0x37, 0x3c, 0xbf, 0x0f, 0xef, 0x8f, 0x6c, 0x97, 0x75, 0x10, 0x05, 0x7a, 0xde, 0x23, 0xe8, 0x2a, 0x35, 0xeb, 0x41, 0x64, 0x7d, 0xcf, 0xe0, 0x52, - /* (2^196)P */ 0x4a, 0xd0, 0x49, 0x93, 0xae, 0xf3, 0x24, 0x8c, 0xe1, 0x09, 0x98, 0x45, 0xd8, 0xb9, 0xfe, 0x8e, 0x8c, 0xa8, 0x2c, 0xc9, 0x9f, 0xce, 0x01, 0xdc, 0x38, 0x11, 0xab, 0x85, 0xb9, 0xe8, 0x00, 0x51, 0xfd, 0x82, 0xe1, 0x9b, 0x4e, 0xfc, 0xb5, 0x2a, 0x0f, 0x8b, 0xda, 0x4e, 0x02, 0xca, 0xcc, 0xe3, 0x91, 0xc4, 0xe0, 0xcf, 0x7b, 0xd6, 0xe6, 0x6a, - /* (2^197)P */ 0xfe, 0x11, 0xd7, 0xaa, 0xe3, 0x0c, 0x52, 0x2e, 0x04, 0xe0, 0xe0, 0x61, 0xc8, 0x05, 0xd7, 0x31, 0x4c, 0xc3, 0x9b, 0x2d, 0xce, 0x59, 0xbe, 0x12, 0xb7, 0x30, 0x21, 0xfc, 0x81, 0xb8, 0x5e, 0x57, 0x73, 0xd0, 0xad, 0x8e, 0x9e, 0xe4, 0xeb, 0xcd, 0xcf, 0xd2, 0x0f, 0x01, 0x35, 0x16, 0xed, 0x7a, 0x43, 0x8e, 0x42, 0xdc, 0xea, 0x4c, 0xa8, 0x7c, - /* (2^198)P */ 0x37, 0x26, 0xcc, 0x76, 0x0b, 0xe5, 0x76, 0xdd, 0x3e, 0x19, 0x3c, 0xc4, 0x6c, 0x7f, 0xd0, 0x03, 0xc1, 0xb8, 0x59, 0x82, 0xca, 0x36, 0xc1, 0xe4, 0xc8, 0xb2, 0x83, 0x69, 0x9c, 0xc5, 0x9d, 0x12, 0x82, 0x1c, 0xea, 0xb2, 0x84, 0x9f, 0xf3, 0x52, 0x6b, 0xbb, 0xd8, 0x81, 0x56, 0x83, 0x04, 0x66, 0x05, 0x22, 0x49, 0x37, 0x93, 0xb1, 0xfd, 0xd5, - /* (2^199)P */ 0xaf, 0x96, 0xbf, 0x03, 0xbe, 0xe6, 0x5d, 0x78, 0x19, 0xba, 0x37, 0x46, 0x0a, 0x2b, 0x52, 0x7c, 0xd8, 0x51, 0x9e, 0x3d, 0x29, 0x42, 0xdb, 0x0e, 0x31, 0x20, 0x94, 0xf8, 0x43, 0x9a, 0x2d, 0x22, 0xd3, 0xe3, 0xa1, 0x79, 0x68, 0xfb, 0x2d, 0x7e, 0xd6, 0x79, 0xda, 0x0b, 0xc6, 0x5b, 0x76, 0x68, 0xf0, 0xfe, 0x72, 0x59, 0xbb, 0xa1, 0x9c, 0x74, - /* (2^200)P */ 0x0a, 0xd9, 0xec, 0xc5, 0xbd, 0xf0, 0xda, 0xcf, 0x82, 0xab, 0x46, 0xc5, 0x32, 0x13, 0xdc, 0x5b, 0xac, 0xc3, 0x53, 0x9a, 0x7f, 0xef, 0xa5, 0x40, 0x5a, 0x1f, 0xc1, 0x12, 0x91, 0x54, 0x83, 0x6a, 0xb0, 0x9a, 0x85, 0x4d, 0xbf, 0x36, 0x8e, 0xd3, 0xa2, 0x2b, 0xe5, 0xd6, 0xc6, 0xe1, 0x58, 0x5b, 0x82, 0x9b, 0xc8, 0xf2, 0x03, 0xba, 0xf5, 0x92, - /* (2^201)P */ 0xfb, 0x21, 0x7e, 0xde, 0xe7, 0xb4, 0xc0, 0x56, 0x86, 0x3a, 0x5b, 0x78, 0xf8, 0xf0, 0xf4, 0xe7, 0x5c, 0x00, 0xd2, 0xd7, 0xd6, 0xf8, 0x75, 0x5e, 0x0f, 0x3e, 0xd1, 0x4b, 0x77, 0xd8, 0xad, 0xb0, 0xc9, 0x8b, 0x59, 0x7d, 0x30, 0x76, 0x64, 0x7a, 0x76, 0xd9, 0x51, 0x69, 0xfc, 0xbd, 0x8e, 0xb5, 0x55, 0xe0, 0xd2, 0x07, 0x15, 0xa9, 0xf7, 0xa4, - /* (2^202)P */ 0xaa, 0x2d, 0x2f, 0x2b, 0x3c, 0x15, 0xdd, 0xcd, 0xe9, 0x28, 0x82, 0x4f, 0xa2, 0xaa, 0x31, 0x48, 0xcc, 0xfa, 0x07, 0x73, 0x8a, 0x34, 0x74, 0x0d, 0xab, 0x1a, 0xca, 0xd2, 0xbf, 0x3a, 0xdb, 0x1a, 0x5f, 0x50, 0x62, 0xf4, 0x6b, 0x83, 0x38, 0x43, 0x96, 0xee, 0x6b, 0x39, 0x1e, 0xf0, 0x17, 0x80, 0x1e, 0x9b, 0xed, 0x2b, 0x2f, 0xcc, 0x65, 0xf7, - /* (2^203)P */ 0x03, 0xb3, 0x23, 0x9c, 0x0d, 0xd1, 0xeb, 0x7e, 0x34, 0x17, 0x8a, 0x4c, 0xde, 0x54, 0x39, 0xc4, 0x11, 0x82, 0xd3, 0xa4, 0x00, 0x32, 0x95, 0x9c, 0xa6, 0x64, 0x76, 0x6e, 0xd6, 0x53, 0x27, 0xb4, 0x6a, 0x14, 0x8c, 0x54, 0xf6, 0x58, 0x9e, 0x22, 0x4a, 0x55, 0x18, 0x77, 0xd0, 0x08, 0x6b, 0x19, 0x8a, 0xb5, 0xe7, 0x19, 0xb8, 0x60, 0x92, 0xb1, - /* (2^204)P */ 0x66, 0xec, 0xf3, 0x12, 0xde, 0x67, 0x7f, 0xd4, 0x5b, 0xf6, 0x70, 0x64, 0x0a, 0xb5, 0xc2, 0xf9, 0xb3, 0x64, 0xab, 0x56, 0x46, 0xc7, 0x93, 0xc2, 0x8b, 0x2d, 0xd0, 0xd6, 0x39, 0x3b, 0x1f, 0xcd, 0xb3, 0xac, 0xcc, 0x2c, 0x27, 0x6a, 0xbc, 0xb3, 0x4b, 0xa8, 0x3c, 0x69, 0x20, 0xe2, 0x18, 0x35, 0x17, 0xe1, 0x8a, 0xd3, 0x11, 0x74, 0xaa, 0x4d, - /* (2^205)P */ 0x96, 0xc4, 0x16, 0x7e, 0xfd, 0xf5, 0xd0, 0x7d, 0x1f, 0x32, 0x1b, 0xdb, 0xa6, 0xfd, 0x51, 0x75, 0x4d, 0xd7, 0x00, 0xe5, 0x7f, 0x58, 0x5b, 0xeb, 0x4b, 0x6a, 0x78, 0xfe, 0xe5, 0xd6, 0x8f, 0x99, 0x17, 0xca, 0x96, 0x45, 0xf7, 0x52, 0xdf, 0x84, 0x06, 0x77, 0xb9, 0x05, 0x63, 0x5d, 0xe9, 0x91, 0xb1, 0x4b, 0x82, 0x5a, 0xdb, 0xd7, 0xca, 0x69, - /* (2^206)P */ 0x02, 0xd3, 0x38, 0x38, 0x87, 0xea, 0xbd, 0x9f, 0x11, 0xca, 0xf3, 0x21, 0xf1, 0x9b, 0x35, 0x97, 0x98, 0xff, 0x8e, 0x6d, 0x3d, 0xd6, 0xb2, 0xfa, 0x68, 0xcb, 0x7e, 0x62, 0x85, 0xbb, 0xc7, 0x5d, 0xee, 0x32, 0x30, 0x2e, 0x71, 0x96, 0x63, 0x43, 0x98, 0xc4, 0xa7, 0xde, 0x60, 0xb2, 0xd9, 0x43, 0x4a, 0xfa, 0x97, 0x2d, 0x5f, 0x21, 0xd4, 0xfe, - /* (2^207)P */ 0x3b, 0x20, 0x29, 0x07, 0x07, 0xb5, 0x78, 0xc3, 0xc7, 0xab, 0x56, 0xba, 0x40, 0xde, 0x1d, 0xcf, 0xc3, 0x00, 0x56, 0x21, 0x0c, 0xc8, 0x42, 0xd9, 0x0e, 0xcd, 0x02, 0x7c, 0x07, 0xb9, 0x11, 0xd7, 0x96, 0xaf, 0xff, 0xad, 0xc5, 0xba, 0x30, 0x6d, 0x82, 0x3a, 0xbf, 0xef, 0x7b, 0xf7, 0x0a, 0x74, 0xbd, 0x31, 0x0c, 0xe4, 0xec, 0x1a, 0xe5, 0xc5, - /* (2^208)P */ 0xcc, 0xf2, 0x28, 0x16, 0x12, 0xbf, 0xef, 0x85, 0xbc, 0xf7, 0xcb, 0x9f, 0xdb, 0xa8, 0xb2, 0x49, 0x53, 0x48, 0xa8, 0x24, 0xa8, 0x68, 0x8d, 0xbb, 0x21, 0x0a, 0x5a, 0xbd, 0xb2, 0x91, 0x61, 0x47, 0xc4, 0x43, 0x08, 0xa6, 0x19, 0xef, 0x8e, 0x88, 0x39, 0xc6, 0x33, 0x30, 0xf3, 0x0e, 0xc5, 0x92, 0x66, 0xd6, 0xfe, 0xc5, 0x12, 0xd9, 0x4c, 0x2d, - /* (2^209)P */ 0x30, 0x34, 0x07, 0xbf, 0x9c, 0x5a, 0x4e, 0x65, 0xf1, 0x39, 0x35, 0x38, 0xae, 0x7b, 0x55, 0xac, 0x6a, 0x92, 0x24, 0x7e, 0x50, 0xd3, 0xba, 0x78, 0x51, 0xfe, 0x4d, 0x32, 0x05, 0x11, 0xf5, 0x52, 0xf1, 0x31, 0x45, 0x39, 0x98, 0x7b, 0x28, 0x56, 0xc3, 0x5d, 0x4f, 0x07, 0x6f, 0x84, 0xb8, 0x1a, 0x58, 0x0b, 0xc4, 0x7c, 0xc4, 0x8d, 0x32, 0x8e, - /* (2^210)P */ 0x7e, 0xaf, 0x98, 0xce, 0xc5, 0x2b, 0x9d, 0xf6, 0xfa, 0x2c, 0xb6, 0x2a, 0x5a, 0x1d, 0xc0, 0x24, 0x8d, 0xa4, 0xce, 0xb1, 0x12, 0x01, 0xf9, 0x79, 0xc6, 0x79, 0x38, 0x0c, 0xd4, 0x07, 0xc9, 0xf7, 0x37, 0xa1, 0x0b, 0xfe, 0x72, 0xec, 0x5d, 0xd6, 0xb0, 0x1c, 0x70, 0xbe, 0x70, 0x01, 0x13, 0xe0, 0x86, 0x95, 0xc7, 0x2e, 0x12, 0x3b, 0xe6, 0xa6, - /* (2^211)P */ 0x24, 0x82, 0x67, 0xe0, 0x14, 0x7b, 0x56, 0x08, 0x38, 0x44, 0xdb, 0xa0, 0x3a, 0x05, 0x47, 0xb2, 0xc0, 0xac, 0xd1, 0xcc, 0x3f, 0x82, 0xb8, 0x8a, 0x88, 0xbc, 0xf5, 0x33, 0xa1, 0x35, 0x0f, 0xf6, 0xe2, 0xef, 0x6c, 0xf7, 0x37, 0x9e, 0xe8, 0x10, 0xca, 0xb0, 0x8e, 0x80, 0x86, 0x00, 0x23, 0xd0, 0x4a, 0x76, 0x9f, 0xf7, 0x2c, 0x52, 0x15, 0x0e, - /* (2^212)P */ 0x5e, 0x49, 0xe1, 0x2c, 0x9a, 0x01, 0x76, 0xa6, 0xb3, 0x07, 0x5b, 0xa4, 0x07, 0xef, 0x1d, 0xc3, 0x6a, 0xbb, 0x64, 0xbe, 0x71, 0x15, 0x6e, 0x32, 0x31, 0x46, 0x9a, 0x9e, 0x8f, 0x45, 0x73, 0xce, 0x0b, 0x94, 0x1a, 0x52, 0x07, 0xf4, 0x50, 0x30, 0x49, 0x53, 0x50, 0xfb, 0x71, 0x1f, 0x5a, 0x03, 0xa9, 0x76, 0xf2, 0x8f, 0x42, 0xff, 0xed, 0xed, - /* (2^213)P */ 0xed, 0x08, 0xdb, 0x91, 0x1c, 0xee, 0xa2, 0xb4, 0x47, 0xa2, 0xfa, 0xcb, 0x03, 0xd1, 0xff, 0x8c, 0xad, 0x64, 0x50, 0x61, 0xcd, 0xfc, 0x88, 0xa0, 0x31, 0x95, 0x30, 0xb9, 0x58, 0xdd, 0xd7, 0x43, 0xe4, 0x46, 0xc2, 0x16, 0xd9, 0x72, 0x4a, 0x56, 0x51, 0x70, 0x85, 0xf1, 0xa1, 0x80, 0x40, 0xd5, 0xba, 0x67, 0x81, 0xda, 0xcd, 0x03, 0xea, 0x51, - /* (2^214)P */ 0x42, 0x50, 0xf0, 0xef, 0x37, 0x61, 0x72, 0x85, 0xe1, 0xf1, 0xff, 0x6f, 0x3d, 0xe8, 0x7b, 0x21, 0x5c, 0xe5, 0x50, 0x03, 0xde, 0x00, 0xc1, 0xf7, 0x3a, 0x55, 0x12, 0x1c, 0x9e, 0x1e, 0xce, 0xd1, 0x2f, 0xaf, 0x05, 0x70, 0x5b, 0x47, 0xf2, 0x04, 0x7a, 0x89, 0xbc, 0x78, 0xa6, 0x65, 0x6c, 0xaa, 0x3c, 0xa2, 0x3c, 0x8b, 0x5c, 0xa9, 0x22, 0x48, - /* (2^215)P */ 0x7e, 0x8c, 0x8f, 0x2f, 0x60, 0xe3, 0x5a, 0x94, 0xd4, 0xce, 0xdd, 0x9d, 0x83, 0x3b, 0x77, 0x78, 0x43, 0x1d, 0xfd, 0x8f, 0xc8, 0xe8, 0x02, 0x90, 0xab, 0xf6, 0xc9, 0xfc, 0xf1, 0x63, 0xaa, 0x5f, 0x42, 0xf1, 0x78, 0x34, 0x64, 0x16, 0x75, 0x9c, 0x7d, 0xd0, 0xe4, 0x74, 0x5a, 0xa8, 0xfb, 0xcb, 0xac, 0x20, 0xa3, 0xc2, 0xa6, 0x20, 0xf8, 0x1b, - /* (2^216)P */ 0x00, 0x4f, 0x1e, 0x56, 0xb5, 0x34, 0xb2, 0x87, 0x31, 0xe5, 0xee, 0x8d, 0xf1, 0x41, 0x67, 0xb7, 0x67, 0x3a, 0x54, 0x86, 0x5c, 0xf0, 0x0b, 0x37, 0x2f, 0x1b, 0x92, 0x5d, 0x58, 0x93, 0xdc, 0xd8, 0x58, 0xcc, 0x9e, 0x67, 0xd0, 0x97, 0x3a, 0xaf, 0x49, 0x39, 0x2d, 0x3b, 0xd8, 0x98, 0xfb, 0x76, 0x6b, 0xe7, 0xaf, 0xc3, 0x45, 0x44, 0x53, 0x94, - /* (2^217)P */ 0x30, 0xbd, 0x90, 0x75, 0xd3, 0xbd, 0x3b, 0x58, 0x27, 0x14, 0x9f, 0x6b, 0xd4, 0x31, 0x99, 0xcd, 0xde, 0x3a, 0x21, 0x1e, 0xb4, 0x02, 0xe4, 0x33, 0x04, 0x02, 0xb0, 0x50, 0x66, 0x68, 0x90, 0xdd, 0x7b, 0x69, 0x31, 0xd9, 0xcf, 0x68, 0x73, 0xf1, 0x60, 0xdd, 0xc8, 0x1d, 0x5d, 0xe3, 0xd6, 0x5b, 0x2a, 0xa4, 0xea, 0xc4, 0x3f, 0x08, 0xcd, 0x9c, - /* (2^218)P */ 0x6b, 0x1a, 0xbf, 0x55, 0xc1, 0x1b, 0x0c, 0x05, 0x09, 0xdf, 0xf5, 0x5e, 0xa3, 0x77, 0x95, 0xe9, 0xdf, 0x19, 0xdd, 0xc7, 0x94, 0xcb, 0x06, 0x73, 0xd0, 0x88, 0x02, 0x33, 0x94, 0xca, 0x7a, 0x2f, 0x8e, 0x3d, 0x72, 0x61, 0x2d, 0x4d, 0xa6, 0x61, 0x1f, 0x32, 0x5e, 0x87, 0x53, 0x36, 0x11, 0x15, 0x20, 0xb3, 0x5a, 0x57, 0x51, 0x93, 0x20, 0xd8, - /* (2^219)P */ 0xb7, 0x56, 0xf4, 0xab, 0x7d, 0x0c, 0xfb, 0x99, 0x1a, 0x30, 0x29, 0xb0, 0x75, 0x2a, 0xf8, 0x53, 0x71, 0x23, 0xbd, 0xa7, 0xd8, 0x0a, 0xe2, 0x27, 0x65, 0xe9, 0x74, 0x26, 0x98, 0x4a, 0x69, 0x19, 0xb2, 0x4d, 0x0a, 0x17, 0x98, 0xb2, 0xa9, 0x57, 0x4e, 0xf6, 0x86, 0xc8, 0x01, 0xa4, 0xc6, 0x98, 0xad, 0x5a, 0x90, 0x2c, 0x05, 0x46, 0x64, 0xb7, - /* (2^220)P */ 0x7b, 0x91, 0xdf, 0xfc, 0xf8, 0x1c, 0x8c, 0x15, 0x9e, 0xf7, 0xd5, 0xa8, 0xe8, 0xe7, 0xe3, 0xa3, 0xb0, 0x04, 0x74, 0xfa, 0x78, 0xfb, 0x26, 0xbf, 0x67, 0x42, 0xf9, 0x8c, 0x9b, 0xb4, 0x69, 0x5b, 0x02, 0x13, 0x6d, 0x09, 0x6c, 0xd6, 0x99, 0x61, 0x7b, 0x89, 0x4a, 0x67, 0x75, 0xa3, 0x98, 0x13, 0x23, 0x1d, 0x18, 0x24, 0x0e, 0xef, 0x41, 0x79, - /* (2^221)P */ 0x86, 0x33, 0xab, 0x08, 0xcb, 0xbf, 0x1e, 0x76, 0x3c, 0x0b, 0xbd, 0x30, 0xdb, 0xe9, 0xa3, 0x35, 0x87, 0x1b, 0xe9, 0x07, 0x00, 0x66, 0x7f, 0x3b, 0x35, 0x0c, 0x8a, 0x3f, 0x61, 0xbc, 0xe0, 0xae, 0xf6, 0xcc, 0x54, 0xe1, 0x72, 0x36, 0x2d, 0xee, 0x93, 0x24, 0xf8, 0xd7, 0xc5, 0xf9, 0xcb, 0xb0, 0xe5, 0x88, 0x0d, 0x23, 0x4b, 0x76, 0x15, 0xa2, - /* (2^222)P */ 0x37, 0xdb, 0x83, 0xd5, 0x6d, 0x06, 0x24, 0x37, 0x1b, 0x15, 0x85, 0x15, 0xe2, 0xc0, 0x4e, 0x02, 0xa9, 0x6d, 0x0a, 0x3a, 0x94, 0x4a, 0x6f, 0x49, 0x00, 0x01, 0x72, 0xbb, 0x60, 0x14, 0x35, 0xae, 0xb4, 0xc6, 0x01, 0x0a, 0x00, 0x9e, 0xc3, 0x58, 0xc5, 0xd1, 0x5e, 0x30, 0x73, 0x96, 0x24, 0x85, 0x9d, 0xf0, 0xf9, 0xec, 0x09, 0xd3, 0xe7, 0x70, - /* (2^223)P */ 0xf3, 0xbd, 0x96, 0x87, 0xe9, 0x71, 0xbd, 0xd6, 0xa2, 0x45, 0xeb, 0x0a, 0xcd, 0x2c, 0xf1, 0x72, 0xa6, 0x31, 0xa9, 0x6f, 0x09, 0xa1, 0x5e, 0xdd, 0xc8, 0x8d, 0x0d, 0xbc, 0x5a, 0x8d, 0xb1, 0x2c, 0x9a, 0xcc, 0x37, 0x74, 0xc2, 0xa9, 0x4e, 0xd6, 0xc0, 0x3c, 0xa0, 0x23, 0xb0, 0xa0, 0x77, 0x14, 0x80, 0x45, 0x71, 0x6a, 0x2d, 0x41, 0xc3, 0x82, - /* (2^224)P */ 0x37, 0x44, 0xec, 0x8a, 0x3e, 0xc1, 0x0c, 0xa9, 0x12, 0x9c, 0x08, 0x88, 0xcb, 0xd9, 0xf8, 0xba, 0x00, 0xd6, 0xc3, 0xdf, 0xef, 0x7a, 0x44, 0x7e, 0x25, 0x69, 0xc9, 0xc1, 0x46, 0xe5, 0x20, 0x9e, 0xcc, 0x0b, 0x05, 0x3e, 0xf4, 0x78, 0x43, 0x0c, 0xa6, 0x2f, 0xc1, 0xfa, 0x70, 0xb2, 0x3c, 0x31, 0x7a, 0x63, 0x58, 0xab, 0x17, 0xcf, 0x4c, 0x4f, - /* (2^225)P */ 0x2b, 0x08, 0x31, 0x59, 0x75, 0x8b, 0xec, 0x0a, 0xa9, 0x79, 0x70, 0xdd, 0xf1, 0x11, 0xc3, 0x11, 0x1f, 0xab, 0x37, 0xaa, 0x26, 0xea, 0x53, 0xc4, 0x79, 0xa7, 0x91, 0x00, 0xaa, 0x08, 0x42, 0xeb, 0x8b, 0x8b, 0xe8, 0xc3, 0x2f, 0xb8, 0x78, 0x90, 0x38, 0x0e, 0x8a, 0x42, 0x0c, 0x0f, 0xbf, 0x3e, 0xf8, 0xd8, 0x07, 0xcf, 0x6a, 0x34, 0xc9, 0xfa, - /* (2^226)P */ 0x11, 0xe0, 0x76, 0x4d, 0x23, 0xc5, 0xa6, 0xcc, 0x9f, 0x9a, 0x2a, 0xde, 0x3a, 0xb5, 0x92, 0x39, 0x19, 0x8a, 0xf1, 0x8d, 0xf9, 0x4d, 0xc9, 0xb4, 0x39, 0x9f, 0x57, 0xd8, 0x72, 0xab, 0x1d, 0x61, 0x6a, 0xb2, 0xff, 0x52, 0xba, 0x54, 0x0e, 0xfb, 0x83, 0x30, 0x8a, 0xf7, 0x3b, 0xf4, 0xd8, 0xae, 0x1a, 0x94, 0x3a, 0xec, 0x63, 0xfe, 0x6e, 0x7c, - /* (2^227)P */ 0xdc, 0x70, 0x8e, 0x55, 0x44, 0xbf, 0xd2, 0x6a, 0xa0, 0x14, 0x61, 0x89, 0xd5, 0x55, 0x45, 0x3c, 0xf6, 0x40, 0x0d, 0x83, 0x85, 0x44, 0xb4, 0x62, 0x56, 0xfe, 0x60, 0xd7, 0x07, 0x1d, 0x47, 0x30, 0x3b, 0x73, 0xa4, 0xb5, 0xb7, 0xea, 0xac, 0xda, 0xf1, 0x17, 0xaa, 0x60, 0xdf, 0xe9, 0x84, 0xda, 0x31, 0x32, 0x61, 0xbf, 0xd0, 0x7e, 0x8a, 0x02, - /* (2^228)P */ 0xb9, 0x51, 0xb3, 0x89, 0x21, 0x5d, 0xa2, 0xfe, 0x79, 0x2a, 0xb3, 0x2a, 0x3b, 0xe6, 0x6f, 0x2b, 0x22, 0x03, 0xea, 0x7b, 0x1f, 0xaf, 0x85, 0xc3, 0x38, 0x55, 0x5b, 0x8e, 0xb4, 0xaa, 0x77, 0xfe, 0x03, 0x6e, 0xda, 0x91, 0x24, 0x0c, 0x48, 0x39, 0x27, 0x43, 0x16, 0xd2, 0x0a, 0x0d, 0x43, 0xa3, 0x0e, 0xca, 0x45, 0xd1, 0x7f, 0xf5, 0xd3, 0x16, - /* (2^229)P */ 0x3d, 0x32, 0x9b, 0x38, 0xf8, 0x06, 0x93, 0x78, 0x5b, 0x50, 0x2b, 0x06, 0xd8, 0x66, 0xfe, 0xab, 0x9b, 0x58, 0xc7, 0xd1, 0x4d, 0xd5, 0xf8, 0x3b, 0x10, 0x7e, 0x85, 0xde, 0x58, 0x4e, 0xdf, 0x53, 0xd9, 0x58, 0xe0, 0x15, 0x81, 0x9f, 0x1a, 0x78, 0xfc, 0x9f, 0x10, 0xc2, 0x23, 0xd6, 0x78, 0xd1, 0x9d, 0xd2, 0xd5, 0x1c, 0x53, 0xe2, 0xc9, 0x76, - /* (2^230)P */ 0x98, 0x1e, 0x38, 0x7b, 0x71, 0x18, 0x4b, 0x15, 0xaf, 0xa1, 0xa6, 0x98, 0xcb, 0x26, 0xa3, 0xc8, 0x07, 0x46, 0xda, 0x3b, 0x70, 0x65, 0xec, 0x7a, 0x2b, 0x34, 0x94, 0xa8, 0xb6, 0x14, 0xf8, 0x1a, 0xce, 0xf7, 0xc8, 0x60, 0xf3, 0x88, 0xf4, 0x33, 0x60, 0x7b, 0xd1, 0x02, 0xe7, 0xda, 0x00, 0x4a, 0xea, 0xd2, 0xfd, 0x88, 0xd2, 0x99, 0x28, 0xf3, - /* (2^231)P */ 0x28, 0x24, 0x1d, 0x26, 0xc2, 0xeb, 0x8b, 0x3b, 0xb4, 0x6b, 0xbe, 0x6b, 0x77, 0xff, 0xf3, 0x21, 0x3b, 0x26, 0x6a, 0x8c, 0x8e, 0x2a, 0x44, 0xa8, 0x01, 0x2b, 0x71, 0xea, 0x64, 0x30, 0xfd, 0xfd, 0x95, 0xcb, 0x39, 0x38, 0x48, 0xfa, 0x96, 0x97, 0x8c, 0x2f, 0x33, 0xca, 0x03, 0xe6, 0xd7, 0x94, 0x55, 0x6c, 0xc3, 0xb3, 0xa8, 0xf7, 0xae, 0x8c, - /* (2^232)P */ 0xea, 0x62, 0x8a, 0xb4, 0xeb, 0x74, 0xf7, 0xb8, 0xae, 0xc5, 0x20, 0x71, 0x06, 0xd6, 0x7c, 0x62, 0x9b, 0x69, 0x74, 0xef, 0xa7, 0x6d, 0xd6, 0x8c, 0x37, 0xb9, 0xbf, 0xcf, 0xeb, 0xe4, 0x2f, 0x04, 0x02, 0x21, 0x7d, 0x75, 0x6b, 0x92, 0x48, 0xf8, 0x70, 0xad, 0x69, 0xe2, 0xea, 0x0e, 0x88, 0x67, 0x72, 0xcc, 0x2d, 0x10, 0xce, 0x2d, 0xcf, 0x65, - /* (2^233)P */ 0x49, 0xf3, 0x57, 0x64, 0xe5, 0x5c, 0xc5, 0x65, 0x49, 0x97, 0xc4, 0x8a, 0xcc, 0xa9, 0xca, 0x94, 0x7b, 0x86, 0x88, 0xb6, 0x51, 0x27, 0x69, 0xa5, 0x0f, 0x8b, 0x06, 0x59, 0xa0, 0x94, 0xef, 0x63, 0x1a, 0x01, 0x9e, 0x4f, 0xd2, 0x5a, 0x93, 0xc0, 0x7c, 0xe6, 0x61, 0x77, 0xb6, 0xf5, 0x40, 0xd9, 0x98, 0x43, 0x5b, 0x56, 0x68, 0xe9, 0x37, 0x8f, - /* (2^234)P */ 0xee, 0x87, 0xd2, 0x05, 0x1b, 0x39, 0x89, 0x10, 0x07, 0x6d, 0xe8, 0xfd, 0x8b, 0x4d, 0xb2, 0xa7, 0x7b, 0x1e, 0xa0, 0x6c, 0x0d, 0x3d, 0x3d, 0x49, 0xba, 0x61, 0x36, 0x1f, 0xc2, 0x84, 0x4a, 0xcc, 0x87, 0xa9, 0x1b, 0x23, 0x04, 0xe2, 0x3e, 0x97, 0xe1, 0xdb, 0xd5, 0x5a, 0xe8, 0x41, 0x6b, 0xe5, 0x5a, 0xa1, 0x99, 0xe5, 0x7b, 0xa7, 0xe0, 0x3b, - /* (2^235)P */ 0xea, 0xa3, 0x6a, 0xdd, 0x77, 0x7f, 0x77, 0x41, 0xc5, 0x6a, 0xe4, 0xaf, 0x11, 0x5f, 0x88, 0xa5, 0x10, 0xee, 0xd0, 0x8c, 0x0c, 0xb4, 0xa5, 0x2a, 0xd0, 0xd8, 0x1d, 0x47, 0x06, 0xc0, 0xd5, 0xce, 0x51, 0x54, 0x9b, 0x2b, 0xe6, 0x2f, 0xe7, 0xe7, 0x31, 0x5f, 0x5c, 0x23, 0x81, 0x3e, 0x03, 0x93, 0xaa, 0x2d, 0x71, 0x84, 0xa0, 0x89, 0x32, 0xa6, - /* (2^236)P */ 0x55, 0xa3, 0x13, 0x92, 0x4e, 0x93, 0x7d, 0xec, 0xca, 0x57, 0xfb, 0x37, 0xae, 0xd2, 0x18, 0x2e, 0x54, 0x05, 0x6c, 0xd1, 0x28, 0xca, 0x90, 0x40, 0x82, 0x2e, 0x79, 0xc6, 0x5a, 0xc7, 0xdd, 0x84, 0x93, 0xdf, 0x15, 0xb8, 0x1f, 0xb1, 0xf9, 0xaf, 0x2c, 0xe5, 0x32, 0xcd, 0xc2, 0x99, 0x6d, 0xac, 0x85, 0x5c, 0x63, 0xd3, 0xe2, 0xff, 0x24, 0xda, - /* (2^237)P */ 0x2d, 0x8d, 0xfd, 0x65, 0xcc, 0xe5, 0x02, 0xa0, 0xe5, 0xb9, 0xec, 0x59, 0x09, 0x50, 0x27, 0xb7, 0x3d, 0x2a, 0x79, 0xb2, 0x76, 0x5d, 0x64, 0x95, 0xf8, 0xc5, 0xaf, 0x8a, 0x62, 0x11, 0x5c, 0x56, 0x1c, 0x05, 0x64, 0x9e, 0x5e, 0xbd, 0x54, 0x04, 0xe6, 0x9e, 0xab, 0xe6, 0x22, 0x7e, 0x42, 0x54, 0xb5, 0xa5, 0xd0, 0x8d, 0x28, 0x6b, 0x0f, 0x0b, - /* (2^238)P */ 0x2d, 0xb2, 0x8c, 0x59, 0x10, 0x37, 0x84, 0x3b, 0x9b, 0x65, 0x1b, 0x0f, 0x10, 0xf9, 0xea, 0x60, 0x1b, 0x02, 0xf5, 0xee, 0x8b, 0xe6, 0x32, 0x7d, 0x10, 0x7f, 0x5f, 0x8c, 0x72, 0x09, 0x4e, 0x1f, 0x29, 0xff, 0x65, 0xcb, 0x3e, 0x3a, 0xd2, 0x96, 0x50, 0x1e, 0xea, 0x64, 0x99, 0xb5, 0x4c, 0x7a, 0x69, 0xb8, 0x95, 0xae, 0x48, 0xc0, 0x7c, 0xb1, - /* (2^239)P */ 0xcd, 0x7c, 0x4f, 0x3e, 0xea, 0xf3, 0x90, 0xcb, 0x12, 0x76, 0xd1, 0x17, 0xdc, 0x0d, 0x13, 0x0f, 0xfd, 0x4d, 0xb5, 0x1f, 0xe4, 0xdd, 0xf2, 0x4d, 0x58, 0xea, 0xa5, 0x66, 0x92, 0xcf, 0xe5, 0x54, 0xea, 0x9b, 0x35, 0x83, 0x1a, 0x44, 0x8e, 0x62, 0x73, 0x45, 0x98, 0xa3, 0x89, 0x95, 0x52, 0x93, 0x1a, 0x8d, 0x63, 0x0f, 0xc2, 0x57, 0x3c, 0xb1, - /* (2^240)P */ 0x72, 0xb4, 0xdf, 0x51, 0xb7, 0xf6, 0x52, 0xa2, 0x14, 0x56, 0xe5, 0x0a, 0x2e, 0x75, 0x81, 0x02, 0xee, 0x93, 0x48, 0x0a, 0x92, 0x4e, 0x0c, 0x0f, 0xdf, 0x09, 0x89, 0x99, 0xf6, 0xf9, 0x22, 0xa2, 0x32, 0xf8, 0xb0, 0x76, 0x0c, 0xb2, 0x4d, 0x6e, 0xbe, 0x83, 0x35, 0x61, 0x44, 0xd2, 0x58, 0xc7, 0xdd, 0x14, 0xcf, 0xc3, 0x4b, 0x7c, 0x07, 0xee, - /* (2^241)P */ 0x8b, 0x03, 0xee, 0xcb, 0xa7, 0x2e, 0x28, 0xbd, 0x97, 0xd1, 0x4c, 0x2b, 0xd1, 0x92, 0x67, 0x5b, 0x5a, 0x12, 0xbf, 0x29, 0x17, 0xfc, 0x50, 0x09, 0x74, 0x76, 0xa2, 0xd4, 0x82, 0xfd, 0x2c, 0x0c, 0x90, 0xf7, 0xe7, 0xe5, 0x9a, 0x2c, 0x16, 0x40, 0xb9, 0x6c, 0xd9, 0xe0, 0x22, 0x9e, 0xf8, 0xdd, 0x73, 0xe4, 0x7b, 0x9e, 0xbe, 0x4f, 0x66, 0x22, - /* (2^242)P */ 0xa4, 0x10, 0xbe, 0xb8, 0x83, 0x3a, 0x77, 0x8e, 0xea, 0x0a, 0xc4, 0x97, 0x3e, 0xb6, 0x6c, 0x81, 0xd7, 0x65, 0xd9, 0xf7, 0xae, 0xe6, 0xbe, 0xab, 0x59, 0x81, 0x29, 0x4b, 0xff, 0xe1, 0x0f, 0xc3, 0x2b, 0xad, 0x4b, 0xef, 0xc4, 0x50, 0x9f, 0x88, 0x31, 0xf2, 0xde, 0x80, 0xd6, 0xf4, 0x20, 0x9c, 0x77, 0x9b, 0xbe, 0xbe, 0x08, 0xf5, 0xf0, 0x95, - /* (2^243)P */ 0x0e, 0x7c, 0x7b, 0x7c, 0xb3, 0xd8, 0x83, 0xfc, 0x8c, 0x75, 0x51, 0x74, 0x1b, 0xe1, 0x6d, 0x11, 0x05, 0x46, 0x24, 0x0d, 0xa4, 0x2b, 0x32, 0xfd, 0x2c, 0x4e, 0x21, 0xdf, 0x39, 0x6b, 0x96, 0xfc, 0xff, 0x92, 0xfc, 0x35, 0x0d, 0x9a, 0x4b, 0xc0, 0x70, 0x46, 0x32, 0x7d, 0xc0, 0xc4, 0x04, 0xe0, 0x2d, 0x83, 0xa7, 0x00, 0xc7, 0xcb, 0xb4, 0x8f, - /* (2^244)P */ 0xa9, 0x5a, 0x7f, 0x0e, 0xdd, 0x2c, 0x85, 0xaa, 0x4d, 0xac, 0xde, 0xb3, 0xb6, 0xaf, 0xe6, 0xd1, 0x06, 0x7b, 0x2c, 0xa4, 0x01, 0x19, 0x22, 0x7d, 0x78, 0xf0, 0x3a, 0xea, 0x89, 0xfe, 0x21, 0x61, 0x6d, 0xb8, 0xfe, 0xa5, 0x2a, 0xab, 0x0d, 0x7b, 0x51, 0x39, 0xb6, 0xde, 0xbc, 0xf0, 0xc5, 0x48, 0xd7, 0x09, 0x82, 0x6e, 0x66, 0x75, 0xc5, 0xcd, - /* (2^245)P */ 0xee, 0xdf, 0x2b, 0x6c, 0xa8, 0xde, 0x61, 0xe1, 0x27, 0xfa, 0x2a, 0x0f, 0x68, 0xe7, 0x7a, 0x9b, 0x13, 0xe9, 0x56, 0xd2, 0x1c, 0x3d, 0x2f, 0x3c, 0x7a, 0xf6, 0x6f, 0x45, 0xee, 0xe8, 0xf4, 0xa0, 0xa6, 0xe8, 0xa5, 0x27, 0xee, 0xf2, 0x85, 0xa9, 0xd5, 0x0e, 0xa9, 0x26, 0x60, 0xfe, 0xee, 0xc7, 0x59, 0x99, 0x5e, 0xa3, 0xdf, 0x23, 0x36, 0xd5, - /* (2^246)P */ 0x15, 0x66, 0x6f, 0xd5, 0x78, 0xa4, 0x0a, 0xf7, 0xb1, 0xe8, 0x75, 0x6b, 0x48, 0x7d, 0xa6, 0x4d, 0x3d, 0x36, 0x9b, 0xc7, 0xcc, 0x68, 0x9a, 0xfe, 0x2f, 0x39, 0x2a, 0x51, 0x31, 0x39, 0x7d, 0x73, 0x6f, 0xc8, 0x74, 0x72, 0x6f, 0x6e, 0xda, 0x5f, 0xad, 0x48, 0xc8, 0x40, 0xe1, 0x06, 0x01, 0x36, 0xa1, 0x88, 0xc8, 0x99, 0x9c, 0xd1, 0x11, 0x8f, - /* (2^247)P */ 0xab, 0xc5, 0xcb, 0xcf, 0xbd, 0x73, 0x21, 0xd0, 0x82, 0xb1, 0x2e, 0x2d, 0xd4, 0x36, 0x1b, 0xed, 0xa9, 0x8a, 0x26, 0x79, 0xc4, 0x17, 0xae, 0xe5, 0x09, 0x0a, 0x0c, 0xa4, 0x21, 0xa0, 0x6e, 0xdd, 0x62, 0x8e, 0x44, 0x62, 0xcc, 0x50, 0xff, 0x93, 0xb3, 0x9a, 0x72, 0x8c, 0x3f, 0xa1, 0xa6, 0x4d, 0x87, 0xd5, 0x1c, 0x5a, 0xc0, 0x0b, 0x1a, 0xd6, - /* (2^248)P */ 0x67, 0x36, 0x6a, 0x1f, 0x96, 0xe5, 0x80, 0x20, 0xa9, 0xe8, 0x0b, 0x0e, 0x21, 0x29, 0x3f, 0xc8, 0x0a, 0x6d, 0x27, 0x47, 0xca, 0xd9, 0x05, 0x55, 0xbf, 0x11, 0xcf, 0x31, 0x7a, 0x37, 0xc7, 0x90, 0xa9, 0xf4, 0x07, 0x5e, 0xd5, 0xc3, 0x92, 0xaa, 0x95, 0xc8, 0x23, 0x2a, 0x53, 0x45, 0xe3, 0x3a, 0x24, 0xe9, 0x67, 0x97, 0x3a, 0x82, 0xf9, 0xa6, - /* (2^249)P */ 0x92, 0x9e, 0x6d, 0x82, 0x67, 0xe9, 0xf9, 0x17, 0x96, 0x2c, 0xa7, 0xd3, 0x89, 0xf9, 0xdb, 0xd8, 0x20, 0xc6, 0x2e, 0xec, 0x4a, 0x76, 0x64, 0xbf, 0x27, 0x40, 0xe2, 0xb4, 0xdf, 0x1f, 0xa0, 0xef, 0x07, 0x80, 0xfb, 0x8e, 0x12, 0xf8, 0xb8, 0xe1, 0xc6, 0xdf, 0x7c, 0x69, 0x35, 0x5a, 0xe1, 0x8e, 0x5d, 0x69, 0x84, 0x56, 0xb6, 0x31, 0x1c, 0x0b, - /* (2^250)P */ 0xd6, 0x94, 0x5c, 0xef, 0xbb, 0x46, 0x45, 0x44, 0x5b, 0xa1, 0xae, 0x03, 0x65, 0xdd, 0xb5, 0x66, 0x88, 0x35, 0x29, 0x95, 0x16, 0x54, 0xa6, 0xf5, 0xc9, 0x78, 0x34, 0xe6, 0x0f, 0xc4, 0x2b, 0x5b, 0x79, 0x51, 0x68, 0x48, 0x3a, 0x26, 0x87, 0x05, 0x70, 0xaf, 0x8b, 0xa6, 0xc7, 0x2e, 0xb3, 0xa9, 0x10, 0x01, 0xb0, 0xb9, 0x31, 0xfd, 0xdc, 0x80, - /* (2^251)P */ 0x25, 0xf2, 0xad, 0xd6, 0x75, 0xa3, 0x04, 0x05, 0x64, 0x8a, 0x97, 0x60, 0x27, 0x2a, 0xe5, 0x6d, 0xb0, 0x73, 0xf4, 0x07, 0x2a, 0x9d, 0xe9, 0x46, 0xb4, 0x1c, 0x51, 0xf8, 0x63, 0x98, 0x7e, 0xe5, 0x13, 0x51, 0xed, 0x98, 0x65, 0x98, 0x4f, 0x8f, 0xe7, 0x7e, 0x72, 0xd7, 0x64, 0x11, 0x2f, 0xcd, 0x12, 0xf8, 0xc4, 0x63, 0x52, 0x0f, 0x7f, 0xc4, - /* (2^252)P */ 0x5c, 0xd9, 0x85, 0x63, 0xc7, 0x8a, 0x65, 0x9a, 0x25, 0x83, 0x31, 0x73, 0x49, 0xf0, 0x93, 0x96, 0x70, 0x67, 0x6d, 0xb1, 0xff, 0x95, 0x54, 0xe4, 0xf8, 0x15, 0x6c, 0x5f, 0xbd, 0xf6, 0x0f, 0x38, 0x7b, 0x68, 0x7d, 0xd9, 0x3d, 0xf0, 0xa9, 0xa0, 0xe4, 0xd1, 0xb6, 0x34, 0x6d, 0x14, 0x16, 0xc2, 0x4c, 0x30, 0x0e, 0x67, 0xd3, 0xbe, 0x2e, 0xc0, - /* (2^253)P */ 0x06, 0x6b, 0x52, 0xc8, 0x14, 0xcd, 0xae, 0x03, 0x93, 0xea, 0xc1, 0xf2, 0xf6, 0x8b, 0xc5, 0xb6, 0xdc, 0x82, 0x42, 0x29, 0x94, 0xe0, 0x25, 0x6c, 0x3f, 0x9f, 0x5d, 0xe4, 0x96, 0xf6, 0x8e, 0x3f, 0xf9, 0x72, 0xc4, 0x77, 0x60, 0x8b, 0xa4, 0xf9, 0xa8, 0xc3, 0x0a, 0x81, 0xb1, 0x97, 0x70, 0x18, 0xab, 0xea, 0x37, 0x8a, 0x08, 0xc7, 0xe2, 0x95, - /* (2^254)P */ 0x94, 0x49, 0xd9, 0x5f, 0x76, 0x72, 0x82, 0xad, 0x2d, 0x50, 0x1a, 0x7a, 0x5b, 0xe6, 0x95, 0x1e, 0x95, 0x65, 0x87, 0x1c, 0x52, 0xd7, 0x44, 0xe6, 0x9b, 0x56, 0xcd, 0x6f, 0x05, 0xff, 0x67, 0xc5, 0xdb, 0xa2, 0xac, 0xe4, 0xa2, 0x28, 0x63, 0x5f, 0xfb, 0x0c, 0x3b, 0xf1, 0x87, 0xc3, 0x36, 0x78, 0x3f, 0x77, 0xfa, 0x50, 0x85, 0xf9, 0xd7, 0x82, - /* (2^255)P */ 0x64, 0xc0, 0xe0, 0xd8, 0x2d, 0xed, 0xcb, 0x6a, 0xfd, 0xcd, 0xbc, 0x7e, 0x9f, 0xc8, 0x85, 0xe9, 0xc1, 0x7c, 0x0f, 0xe5, 0x18, 0xea, 0xd4, 0x51, 0xad, 0x59, 0x13, 0x75, 0xd9, 0x3d, 0xd4, 0x8a, 0xb2, 0xbe, 0x78, 0x52, 0x2b, 0x52, 0x94, 0x37, 0x41, 0xd6, 0xb4, 0xb6, 0x45, 0x20, 0x76, 0xe0, 0x1f, 0x31, 0xdb, 0xb1, 0xa1, 0x43, 0xf0, 0x18, - /* (2^256)P */ 0x74, 0xa9, 0xa4, 0xa9, 0xdd, 0x6e, 0x3e, 0x68, 0xe5, 0xc3, 0x2e, 0x92, 0x17, 0xa4, 0xcb, 0x80, 0xb1, 0xf0, 0x06, 0x93, 0xef, 0xe6, 0x00, 0xe6, 0x3b, 0xb1, 0x32, 0x65, 0x7b, 0x83, 0xb6, 0x8a, 0x49, 0x1b, 0x14, 0x89, 0xee, 0xba, 0xf5, 0x6a, 0x8d, 0x36, 0xef, 0xb0, 0xd8, 0xb2, 0x16, 0x99, 0x17, 0x35, 0x02, 0x16, 0x55, 0x58, 0xdd, 0x82, - /* (2^257)P */ 0x36, 0x95, 0xe8, 0xf4, 0x36, 0x42, 0xbb, 0xc5, 0x3e, 0xfa, 0x30, 0x84, 0x9e, 0x59, 0xfd, 0xd2, 0x95, 0x42, 0xf8, 0x64, 0xd9, 0xb9, 0x0e, 0x9f, 0xfa, 0xd0, 0x7b, 0x20, 0x31, 0x77, 0x48, 0x29, 0x4d, 0xd0, 0x32, 0x57, 0x56, 0x30, 0xa6, 0x17, 0x53, 0x04, 0xbf, 0x08, 0x28, 0xec, 0xb8, 0x46, 0xc1, 0x03, 0x89, 0xdc, 0xed, 0xa0, 0x35, 0x53, - /* (2^258)P */ 0xc5, 0x7f, 0x9e, 0xd8, 0xc5, 0xba, 0x5f, 0x68, 0xc8, 0x23, 0x75, 0xea, 0x0d, 0xd9, 0x5a, 0xfd, 0x61, 0x1a, 0xa3, 0x2e, 0x45, 0x63, 0x14, 0x55, 0x86, 0x21, 0x29, 0xbe, 0xef, 0x5e, 0x50, 0xe5, 0x18, 0x59, 0xe7, 0xe3, 0xce, 0x4d, 0x8c, 0x15, 0x8f, 0x89, 0x66, 0x44, 0x52, 0x3d, 0xfa, 0xc7, 0x9a, 0x59, 0x90, 0x8e, 0xc0, 0x06, 0x3f, 0xc9, - /* (2^259)P */ 0x8e, 0x04, 0xd9, 0x16, 0x50, 0x1d, 0x8c, 0x9f, 0xd5, 0xe3, 0xce, 0xfd, 0x47, 0x04, 0x27, 0x4d, 0xc2, 0xfa, 0x71, 0xd9, 0x0b, 0xb8, 0x65, 0xf4, 0x11, 0xf3, 0x08, 0xee, 0x81, 0xc8, 0x67, 0x99, 0x0b, 0x8d, 0x77, 0xa3, 0x4f, 0xb5, 0x9b, 0xdb, 0x26, 0xf1, 0x97, 0xeb, 0x04, 0x54, 0xeb, 0x80, 0x08, 0x1d, 0x1d, 0xf6, 0x3d, 0x1f, 0x5a, 0xb8, - /* (2^260)P */ 0xb7, 0x9c, 0x9d, 0xee, 0xb9, 0x5c, 0xad, 0x0d, 0x9e, 0xfd, 0x60, 0x3c, 0x27, 0x4e, 0xa2, 0x95, 0xfb, 0x64, 0x7e, 0x79, 0x64, 0x87, 0x10, 0xb4, 0x73, 0xe0, 0x9d, 0x46, 0x4d, 0x3d, 0xee, 0x83, 0xe4, 0x16, 0x88, 0x97, 0xe6, 0x4d, 0xba, 0x70, 0xb6, 0x96, 0x7b, 0xff, 0x4b, 0xc8, 0xcf, 0x72, 0x83, 0x3e, 0x5b, 0x24, 0x2e, 0x57, 0xf1, 0x82, - /* (2^261)P */ 0x30, 0x71, 0x40, 0x51, 0x4f, 0x44, 0xbb, 0xc7, 0xf0, 0x54, 0x6e, 0x9d, 0xeb, 0x15, 0xad, 0xf8, 0x61, 0x43, 0x5a, 0xef, 0xc0, 0xb1, 0x57, 0xae, 0x03, 0x40, 0xe8, 0x68, 0x6f, 0x03, 0x20, 0x4f, 0x8a, 0x51, 0x2a, 0x9e, 0xd2, 0x45, 0xaf, 0xb4, 0xf5, 0xd4, 0x95, 0x7f, 0x3d, 0x3d, 0xb7, 0xb6, 0x28, 0xc5, 0x08, 0x8b, 0x44, 0xd6, 0x3f, 0xe7, - /* (2^262)P */ 0xa9, 0x52, 0x04, 0x67, 0xcb, 0x20, 0x63, 0xf8, 0x18, 0x01, 0x44, 0x21, 0x6a, 0x8a, 0x83, 0x48, 0xd4, 0xaf, 0x23, 0x0f, 0x35, 0x8d, 0xe5, 0x5a, 0xc4, 0x7c, 0x55, 0x46, 0x19, 0x5f, 0x35, 0xe0, 0x5d, 0x97, 0x4c, 0x2d, 0x04, 0xed, 0x59, 0xd4, 0xb0, 0xb2, 0xc6, 0xe3, 0x51, 0xe1, 0x38, 0xc6, 0x30, 0x49, 0x8f, 0xae, 0x61, 0x64, 0xce, 0xa8, - /* (2^263)P */ 0x9b, 0x64, 0x83, 0x3c, 0xd3, 0xdf, 0xb9, 0x27, 0xe7, 0x5b, 0x7f, 0xeb, 0xf3, 0x26, 0xcf, 0xb1, 0x8f, 0xaf, 0x26, 0xc8, 0x48, 0xce, 0xa1, 0xac, 0x7d, 0x10, 0x34, 0x28, 0xe1, 0x1f, 0x69, 0x03, 0x64, 0x77, 0x61, 0xdd, 0x4a, 0x9b, 0x18, 0x47, 0xf8, 0xca, 0x63, 0xc9, 0x03, 0x2d, 0x20, 0x2a, 0x69, 0x6e, 0x42, 0xd0, 0xe7, 0xaa, 0xb5, 0xf3, - /* (2^264)P */ 0xea, 0x31, 0x0c, 0x57, 0x0f, 0x3e, 0xe3, 0x35, 0xd8, 0x30, 0xa5, 0x6f, 0xdd, 0x95, 0x43, 0xc6, 0x66, 0x07, 0x4f, 0x34, 0xc3, 0x7e, 0x04, 0x10, 0x2d, 0xc4, 0x1c, 0x94, 0x52, 0x2e, 0x5b, 0x9a, 0x65, 0x2f, 0x91, 0xaa, 0x4f, 0x3c, 0xdc, 0x23, 0x18, 0xe1, 0x4f, 0x85, 0xcd, 0xf4, 0x8c, 0x51, 0xf7, 0xab, 0x4f, 0xdc, 0x15, 0x5c, 0x9e, 0xc5, - /* (2^265)P */ 0x54, 0x57, 0x23, 0x17, 0xe7, 0x82, 0x2f, 0x04, 0x7d, 0xfe, 0xe7, 0x1f, 0xa2, 0x57, 0x79, 0xe9, 0x58, 0x9b, 0xbe, 0xc6, 0x16, 0x4a, 0x17, 0x50, 0x90, 0x4a, 0x34, 0x70, 0x87, 0x37, 0x01, 0x26, 0xd8, 0xa3, 0x5f, 0x07, 0x7c, 0xd0, 0x7d, 0x05, 0x8a, 0x93, 0x51, 0x2f, 0x99, 0xea, 0xcf, 0x00, 0xd8, 0xc7, 0xe6, 0x9b, 0x8c, 0x62, 0x45, 0x87, - /* (2^266)P */ 0xc3, 0xfd, 0x29, 0x66, 0xe7, 0x30, 0x29, 0x77, 0xe0, 0x0d, 0x63, 0x5b, 0xe6, 0x90, 0x1a, 0x1e, 0x99, 0xc2, 0xa7, 0xab, 0xff, 0xa7, 0xbd, 0x79, 0x01, 0x97, 0xfd, 0x27, 0x1b, 0x43, 0x2b, 0xe6, 0xfe, 0x5e, 0xf1, 0xb9, 0x35, 0x38, 0x08, 0x25, 0x55, 0x90, 0x68, 0x2e, 0xc3, 0x67, 0x39, 0x9f, 0x2b, 0x2c, 0x70, 0x48, 0x8c, 0x47, 0xee, 0x56, - /* (2^267)P */ 0xf7, 0x32, 0x70, 0xb5, 0xe6, 0x42, 0xfd, 0x0a, 0x39, 0x9b, 0x07, 0xfe, 0x0e, 0xf4, 0x47, 0xba, 0x6a, 0x3f, 0xf5, 0x2c, 0x15, 0xf3, 0x60, 0x3f, 0xb1, 0x83, 0x7b, 0x2e, 0x34, 0x58, 0x1a, 0x6e, 0x4a, 0x49, 0x05, 0x45, 0xca, 0xdb, 0x00, 0x01, 0x0c, 0x42, 0x5e, 0x60, 0x40, 0x5f, 0xd9, 0xc7, 0x3a, 0x9e, 0x1c, 0x8d, 0xab, 0x11, 0x55, 0x65, - /* (2^268)P */ 0x87, 0x40, 0xb7, 0x0d, 0xaa, 0x34, 0x89, 0x90, 0x75, 0x6d, 0xa2, 0xfe, 0x3b, 0x6d, 0x5c, 0x39, 0x98, 0x10, 0x9e, 0x15, 0xc5, 0x35, 0xa2, 0x27, 0x23, 0x0a, 0x2d, 0x60, 0xe2, 0xa8, 0x7f, 0x3e, 0x77, 0x8f, 0xcc, 0x44, 0xcc, 0x30, 0x28, 0xe2, 0xf0, 0x04, 0x8c, 0xee, 0xe4, 0x5f, 0x68, 0x8c, 0xdf, 0x70, 0xbf, 0x31, 0xee, 0x2a, 0xfc, 0xce, - /* (2^269)P */ 0x92, 0xf2, 0xa0, 0xd9, 0x58, 0x3b, 0x7c, 0x1a, 0x99, 0x46, 0x59, 0x54, 0x60, 0x06, 0x8d, 0x5e, 0xf0, 0x22, 0xa1, 0xed, 0x92, 0x8a, 0x4d, 0x76, 0x95, 0x05, 0x0b, 0xff, 0xfc, 0x9a, 0xd1, 0xcc, 0x05, 0xb9, 0x5e, 0x99, 0xe8, 0x2a, 0x76, 0x7b, 0xfd, 0xa6, 0xe2, 0xd1, 0x1a, 0xd6, 0x76, 0x9f, 0x2f, 0x0e, 0xd1, 0xa8, 0x77, 0x5a, 0x40, 0x5a, - /* (2^270)P */ 0xff, 0xf9, 0x3f, 0xa9, 0xa6, 0x6c, 0x6d, 0x03, 0x8b, 0xa7, 0x10, 0x5d, 0x3f, 0xec, 0x3e, 0x1c, 0x0b, 0x6b, 0xa2, 0x6a, 0x22, 0xa9, 0x28, 0xd0, 0x66, 0xc9, 0xc2, 0x3d, 0x47, 0x20, 0x7d, 0xa6, 0x1d, 0xd8, 0x25, 0xb5, 0xf2, 0xf9, 0x70, 0x19, 0x6b, 0xf8, 0x43, 0x36, 0xc5, 0x1f, 0xe4, 0x5a, 0x4c, 0x13, 0xe4, 0x6d, 0x08, 0x0b, 0x1d, 0xb1, - /* (2^271)P */ 0x3f, 0x20, 0x9b, 0xfb, 0xec, 0x7d, 0x31, 0xc5, 0xfc, 0x88, 0x0b, 0x30, 0xed, 0x36, 0xc0, 0x63, 0xb1, 0x7d, 0x10, 0xda, 0xb6, 0x2e, 0xad, 0xf3, 0xec, 0x94, 0xe7, 0xec, 0xb5, 0x9c, 0xfe, 0xf5, 0x35, 0xf0, 0xa2, 0x2d, 0x7f, 0xca, 0x6b, 0x67, 0x1a, 0xf6, 0xb3, 0xda, 0x09, 0x2a, 0xaa, 0xdf, 0xb1, 0xca, 0x9b, 0xfb, 0xeb, 0xb3, 0xcd, 0xc0, - /* (2^272)P */ 0xcd, 0x4d, 0x89, 0x00, 0xa4, 0x3b, 0x48, 0xf0, 0x76, 0x91, 0x35, 0xa5, 0xf8, 0xc9, 0xb6, 0x46, 0xbc, 0xf6, 0x9a, 0x45, 0x47, 0x17, 0x96, 0x80, 0x5b, 0x3a, 0x28, 0x33, 0xf9, 0x5a, 0xef, 0x43, 0x07, 0xfe, 0x3b, 0xf4, 0x8e, 0x19, 0xce, 0xd2, 0x94, 0x4b, 0x6d, 0x8e, 0x67, 0x20, 0xc7, 0x4f, 0x2f, 0x59, 0x8e, 0xe1, 0xa1, 0xa9, 0xf9, 0x0e, - /* (2^273)P */ 0xdc, 0x7b, 0xb5, 0x50, 0x2e, 0xe9, 0x7e, 0x8b, 0x78, 0xa1, 0x38, 0x96, 0x22, 0xc3, 0x61, 0x67, 0x6d, 0xc8, 0x58, 0xed, 0x41, 0x1d, 0x5d, 0x86, 0x98, 0x7f, 0x2f, 0x1b, 0x8d, 0x3e, 0xaa, 0xc1, 0xd2, 0x0a, 0xf3, 0xbf, 0x95, 0x04, 0xf3, 0x10, 0x3c, 0x2b, 0x7f, 0x90, 0x46, 0x04, 0xaa, 0x6a, 0xa9, 0x35, 0x76, 0xac, 0x49, 0xb5, 0x00, 0x45, - /* (2^274)P */ 0xb1, 0x93, 0x79, 0x84, 0x4a, 0x2a, 0x30, 0x78, 0x16, 0xaa, 0xc5, 0x74, 0x06, 0xce, 0xa5, 0xa7, 0x32, 0x86, 0xe0, 0xf9, 0x10, 0xd2, 0x58, 0x76, 0xfb, 0x66, 0x49, 0x76, 0x3a, 0x90, 0xba, 0xb5, 0xcc, 0x99, 0xcd, 0x09, 0xc1, 0x9a, 0x74, 0x23, 0xdf, 0x0c, 0xfe, 0x99, 0x52, 0x80, 0xa3, 0x7c, 0x1c, 0x71, 0x5f, 0x2c, 0x49, 0x57, 0xf4, 0xf9, - /* (2^275)P */ 0x6d, 0xbf, 0x52, 0xe6, 0x25, 0x98, 0xed, 0xcf, 0xe3, 0xbc, 0x08, 0xa2, 0x1a, 0x90, 0xae, 0xa0, 0xbf, 0x07, 0x15, 0xad, 0x0a, 0x9f, 0x3e, 0x47, 0x44, 0xc2, 0x10, 0x46, 0xa6, 0x7a, 0x9e, 0x2f, 0x57, 0xbc, 0xe2, 0xf0, 0x1d, 0xd6, 0x9a, 0x06, 0xed, 0xfc, 0x54, 0x95, 0x92, 0x15, 0xa2, 0xf7, 0x8d, 0x6b, 0xef, 0xb2, 0x05, 0xed, 0x5c, 0x63, - /* (2^276)P */ 0xbc, 0x0b, 0x27, 0x3a, 0x3a, 0xf8, 0xe1, 0x48, 0x02, 0x7e, 0x27, 0xe6, 0x81, 0x62, 0x07, 0x73, 0x74, 0xe5, 0x52, 0xd7, 0xf8, 0x26, 0xca, 0x93, 0x4d, 0x3e, 0x9b, 0x55, 0x09, 0x8e, 0xe3, 0xd7, 0xa6, 0xe3, 0xb6, 0x2a, 0xa9, 0xb3, 0xb0, 0xa0, 0x8c, 0x01, 0xbb, 0x07, 0x90, 0x78, 0x6d, 0x6d, 0xe9, 0xf0, 0x7a, 0x90, 0xbd, 0xdc, 0x0c, 0x36, - /* (2^277)P */ 0x7f, 0x20, 0x12, 0x0f, 0x40, 0x00, 0x53, 0xd8, 0x0c, 0x27, 0x47, 0x47, 0x22, 0x80, 0xfb, 0x62, 0xe4, 0xa7, 0xf7, 0xbd, 0x42, 0xa5, 0xc3, 0x2b, 0xb2, 0x7f, 0x50, 0xcc, 0xe2, 0xfb, 0xd5, 0xc0, 0x63, 0xdd, 0x24, 0x5f, 0x7c, 0x08, 0x91, 0xbf, 0x6e, 0x47, 0x44, 0xd4, 0x6a, 0xc0, 0xc3, 0x09, 0x39, 0x27, 0xdd, 0xc7, 0xca, 0x06, 0x29, 0x55, - /* (2^278)P */ 0x76, 0x28, 0x58, 0xb0, 0xd2, 0xf3, 0x0f, 0x04, 0xe9, 0xc9, 0xab, 0x66, 0x5b, 0x75, 0x51, 0xdc, 0xe5, 0x8f, 0xe8, 0x1f, 0xdb, 0x03, 0x0f, 0xb0, 0x7d, 0xf9, 0x20, 0x64, 0x89, 0xe9, 0xdc, 0xe6, 0x24, 0xc3, 0xd5, 0xd2, 0x41, 0xa6, 0xe4, 0xe3, 0xc4, 0x79, 0x7c, 0x0f, 0xa1, 0x61, 0x2f, 0xda, 0xa4, 0xc9, 0xfd, 0xad, 0x5c, 0x65, 0x6a, 0xf3, - /* (2^279)P */ 0xd5, 0xab, 0x72, 0x7a, 0x3b, 0x59, 0xea, 0xcf, 0xd5, 0x17, 0xd2, 0xb2, 0x5f, 0x2d, 0xab, 0xad, 0x9e, 0x88, 0x64, 0x55, 0x96, 0x6e, 0xf3, 0x44, 0xa9, 0x11, 0xf5, 0xf8, 0x3a, 0xf1, 0xcd, 0x79, 0x4c, 0x99, 0x6d, 0x23, 0x6a, 0xa0, 0xc2, 0x1a, 0x19, 0x45, 0xb5, 0xd8, 0x95, 0x2f, 0x49, 0xe9, 0x46, 0x39, 0x26, 0x60, 0x04, 0x15, 0x8b, 0xcc, - /* (2^280)P */ 0x66, 0x0c, 0xf0, 0x54, 0x41, 0x02, 0x91, 0xab, 0xe5, 0x85, 0x8a, 0x44, 0xa6, 0x34, 0x96, 0x32, 0xc0, 0xdf, 0x6c, 0x41, 0x39, 0xd4, 0xc6, 0xe1, 0xe3, 0x81, 0xb0, 0x4c, 0x34, 0x4f, 0xe5, 0xf4, 0x35, 0x46, 0x1f, 0xeb, 0x75, 0xfd, 0x43, 0x37, 0x50, 0x99, 0xab, 0xad, 0xb7, 0x8c, 0xa1, 0x57, 0xcb, 0xe6, 0xce, 0x16, 0x2e, 0x85, 0xcc, 0xf9, - /* (2^281)P */ 0x63, 0xd1, 0x3f, 0x9e, 0xa2, 0x17, 0x2e, 0x1d, 0x3e, 0xce, 0x48, 0x2d, 0xbb, 0x8f, 0x69, 0xc9, 0xa6, 0x3d, 0x4e, 0xfe, 0x09, 0x56, 0xb3, 0x02, 0x5f, 0x99, 0x97, 0x0c, 0x54, 0xda, 0x32, 0x97, 0x9b, 0xf4, 0x95, 0xf1, 0xad, 0xe3, 0x2b, 0x04, 0xa7, 0x9b, 0x3f, 0xbb, 0xe7, 0x87, 0x2e, 0x1f, 0x8b, 0x4b, 0x7a, 0xa4, 0x43, 0x0c, 0x0f, 0x35, - /* (2^282)P */ 0x05, 0xdc, 0xe0, 0x2c, 0xa1, 0xc1, 0xd0, 0xf1, 0x1f, 0x4e, 0xc0, 0x6c, 0x35, 0x7b, 0xca, 0x8f, 0x8b, 0x02, 0xb1, 0xf7, 0xd6, 0x2e, 0xe7, 0x93, 0x80, 0x85, 0x18, 0x88, 0x19, 0xb9, 0xb4, 0x4a, 0xbc, 0xeb, 0x5a, 0x78, 0x38, 0xed, 0xc6, 0x27, 0x2a, 0x74, 0x76, 0xf0, 0x1b, 0x79, 0x92, 0x2f, 0xd2, 0x81, 0x98, 0xdf, 0xa9, 0x50, 0x19, 0xeb, - /* (2^283)P */ 0xb5, 0xe7, 0xb4, 0x11, 0x3a, 0x81, 0xb6, 0xb4, 0xf8, 0xa2, 0xb3, 0x6c, 0xfc, 0x9d, 0xe0, 0xc0, 0xe0, 0x59, 0x7f, 0x05, 0x37, 0xef, 0x2c, 0xa9, 0x3a, 0x24, 0xac, 0x7b, 0x25, 0xa0, 0x55, 0xd2, 0x44, 0x82, 0x82, 0x6e, 0x64, 0xa3, 0x58, 0xc8, 0x67, 0xae, 0x26, 0xa7, 0x0f, 0x42, 0x63, 0xe1, 0x93, 0x01, 0x52, 0x19, 0xaf, 0x49, 0x3e, 0x33, - /* (2^284)P */ 0x05, 0x85, 0xe6, 0x66, 0xaf, 0x5f, 0xdf, 0xbf, 0x9d, 0x24, 0x62, 0x60, 0x90, 0xe2, 0x4c, 0x7d, 0x4e, 0xc3, 0x74, 0x5d, 0x4f, 0x53, 0xf3, 0x63, 0x13, 0xf4, 0x74, 0x28, 0x6b, 0x7d, 0x57, 0x0c, 0x9d, 0x84, 0xa7, 0x1a, 0xff, 0xa0, 0x79, 0xdf, 0xfc, 0x65, 0x98, 0x8e, 0x22, 0x0d, 0x62, 0x7e, 0xf2, 0x34, 0x60, 0x83, 0x05, 0x14, 0xb1, 0xc1, - /* (2^285)P */ 0x64, 0x22, 0xcc, 0xdf, 0x5c, 0xbc, 0x88, 0x68, 0x4c, 0xd9, 0xbc, 0x0e, 0xc9, 0x8b, 0xb4, 0x23, 0x52, 0xad, 0xb0, 0xb3, 0xf1, 0x17, 0xd8, 0x15, 0x04, 0x6b, 0x99, 0xf0, 0xc4, 0x7d, 0x48, 0x22, 0x4a, 0xf8, 0x6f, 0xaa, 0x88, 0x0d, 0xc5, 0x5e, 0xa9, 0x1c, 0x61, 0x3d, 0x95, 0xa9, 0x7b, 0x6a, 0x79, 0x33, 0x0a, 0x2b, 0x99, 0xe3, 0x4e, 0x48, - /* (2^286)P */ 0x6b, 0x9b, 0x6a, 0x2a, 0xf1, 0x60, 0x31, 0xb4, 0x73, 0xd1, 0x87, 0x45, 0x9c, 0x15, 0x58, 0x4b, 0x91, 0x6d, 0x94, 0x1c, 0x41, 0x11, 0x4a, 0x83, 0xec, 0xaf, 0x65, 0xbc, 0x34, 0xaa, 0x26, 0xe2, 0xaf, 0xed, 0x46, 0x05, 0x4e, 0xdb, 0xc6, 0x4e, 0x10, 0x28, 0x4e, 0x72, 0xe5, 0x31, 0xa3, 0x20, 0xd7, 0xb1, 0x96, 0x64, 0xf6, 0xce, 0x08, 0x08, - /* (2^287)P */ 0x16, 0xa9, 0x5c, 0x9f, 0x9a, 0xb4, 0xb8, 0xc8, 0x32, 0x78, 0xc0, 0x3a, 0xd9, 0x5f, 0x94, 0xac, 0x3a, 0x42, 0x1f, 0x43, 0xd6, 0x80, 0x47, 0x2c, 0xdc, 0x76, 0x27, 0xfa, 0x50, 0xe5, 0xa1, 0xe4, 0xc3, 0xcb, 0x61, 0x31, 0xe1, 0x2e, 0xde, 0x81, 0x3b, 0x77, 0x1c, 0x39, 0x3c, 0xdb, 0xda, 0x87, 0x4b, 0x84, 0x12, 0xeb, 0xdd, 0x54, 0xbf, 0xe7, - /* (2^288)P */ 0xbf, 0xcb, 0x73, 0x21, 0x3d, 0x7e, 0x13, 0x8c, 0xa6, 0x34, 0x21, 0x2b, 0xa5, 0xe4, 0x9f, 0x8e, 0x9c, 0x01, 0x9c, 0x43, 0xd9, 0xc7, 0xb9, 0xf1, 0xbe, 0x7f, 0x45, 0x51, 0x97, 0xa1, 0x8e, 0x01, 0xf8, 0xbd, 0xd2, 0xbf, 0x81, 0x3a, 0x8b, 0xab, 0xe4, 0x89, 0xb7, 0xbd, 0xf2, 0xcd, 0xa9, 0x8a, 0x8a, 0xde, 0xfb, 0x8a, 0x55, 0x12, 0x7b, 0x17, - /* (2^289)P */ 0x1b, 0x95, 0x58, 0x4d, 0xe6, 0x51, 0x31, 0x52, 0x1c, 0xd8, 0x15, 0x84, 0xb1, 0x0d, 0x36, 0x25, 0x88, 0x91, 0x46, 0x71, 0x42, 0x56, 0xe2, 0x90, 0x08, 0x9e, 0x77, 0x1b, 0xee, 0x22, 0x3f, 0xec, 0xee, 0x8c, 0x7b, 0x2e, 0x79, 0xc4, 0x6c, 0x07, 0xa1, 0x7e, 0x52, 0xf5, 0x26, 0x5c, 0x84, 0x2a, 0x50, 0x6e, 0x82, 0xb3, 0x76, 0xda, 0x35, 0x16, - /* (2^290)P */ 0x0a, 0x6f, 0x99, 0x87, 0xc0, 0x7d, 0x8a, 0xb2, 0xca, 0xae, 0xe8, 0x65, 0x98, 0x0f, 0xb3, 0x44, 0xe1, 0xdc, 0x52, 0x79, 0x75, 0xec, 0x8f, 0x95, 0x87, 0x45, 0xd1, 0x32, 0x18, 0x55, 0x15, 0xce, 0x64, 0x9b, 0x08, 0x4f, 0x2c, 0xea, 0xba, 0x1c, 0x57, 0x06, 0x63, 0xc8, 0xb1, 0xfd, 0xc5, 0x67, 0xe7, 0x1f, 0x87, 0x9e, 0xde, 0x72, 0x7d, 0xec, - /* (2^291)P */ 0x36, 0x8b, 0x4d, 0x2c, 0xc2, 0x46, 0xe8, 0x96, 0xac, 0x0b, 0x8c, 0xc5, 0x09, 0x10, 0xfc, 0xf2, 0xda, 0xea, 0x22, 0xb2, 0xd3, 0x89, 0xeb, 0xb2, 0x85, 0x0f, 0xff, 0x59, 0x50, 0x2c, 0x99, 0x5a, 0x1f, 0xec, 0x2a, 0x6f, 0xec, 0xcf, 0xe9, 0xce, 0x12, 0x6b, 0x19, 0xd8, 0xde, 0x9b, 0xce, 0x0e, 0x6a, 0xaa, 0xe1, 0x32, 0xea, 0x4c, 0xfe, 0x92, - /* (2^292)P */ 0x5f, 0x17, 0x70, 0x53, 0x26, 0x03, 0x0b, 0xab, 0xd1, 0xc1, 0x42, 0x0b, 0xab, 0x2b, 0x3d, 0x31, 0xa4, 0xd5, 0x2b, 0x5e, 0x00, 0xd5, 0x9a, 0x22, 0x34, 0xe0, 0x53, 0x3f, 0x59, 0x7f, 0x2c, 0x6d, 0x72, 0x9a, 0xa4, 0xbe, 0x3d, 0x42, 0x05, 0x1b, 0xf2, 0x7f, 0x88, 0x56, 0xd1, 0x7c, 0x7d, 0x6b, 0x9f, 0x43, 0xfe, 0x65, 0x19, 0xae, 0x9c, 0x4c, - /* (2^293)P */ 0xf3, 0x7c, 0x20, 0xa9, 0xfc, 0xf2, 0xf2, 0x3b, 0x3c, 0x57, 0x41, 0x94, 0xe5, 0xcc, 0x6a, 0x37, 0x5d, 0x09, 0xf2, 0xab, 0xc2, 0xca, 0x60, 0x38, 0x6b, 0x7a, 0xe1, 0x78, 0x2b, 0xc1, 0x1d, 0xe8, 0xfd, 0xbc, 0x3d, 0x5c, 0xa2, 0xdb, 0x49, 0x20, 0x79, 0xe6, 0x1b, 0x9b, 0x65, 0xd9, 0x6d, 0xec, 0x57, 0x1d, 0xd2, 0xe9, 0x90, 0xeb, 0x43, 0x7b, - /* (2^294)P */ 0x2a, 0x8b, 0x2e, 0x19, 0x18, 0x10, 0xb8, 0x83, 0xe7, 0x7d, 0x2d, 0x9a, 0x3a, 0xe5, 0xd1, 0xe4, 0x7c, 0x38, 0xe5, 0x59, 0x2a, 0x6e, 0xd9, 0x01, 0x29, 0x3d, 0x23, 0xf7, 0x52, 0xba, 0x61, 0x04, 0x9a, 0xde, 0xc4, 0x31, 0x50, 0xeb, 0x1b, 0xaa, 0xde, 0x39, 0x58, 0xd8, 0x1b, 0x1e, 0xfc, 0x57, 0x9a, 0x28, 0x43, 0x9e, 0x97, 0x5e, 0xaa, 0xa3, - /* (2^295)P */ 0x97, 0x0a, 0x74, 0xc4, 0x39, 0x99, 0x6b, 0x40, 0xc7, 0x3e, 0x8c, 0xa7, 0xb1, 0x4e, 0x9a, 0x59, 0x6e, 0x1c, 0xfe, 0xfc, 0x2a, 0x5e, 0x73, 0x2b, 0x8c, 0xa9, 0x71, 0xf5, 0xda, 0x6b, 0x15, 0xab, 0xf7, 0xbe, 0x2a, 0x44, 0x5f, 0xba, 0xae, 0x67, 0x93, 0xc5, 0x86, 0xc1, 0xb8, 0xdf, 0xdc, 0xcb, 0xd7, 0xff, 0xb1, 0x71, 0x7c, 0x6f, 0x88, 0xf8, - /* (2^296)P */ 0x3f, 0x89, 0xb1, 0xbf, 0x24, 0x16, 0xac, 0x56, 0xfe, 0xdf, 0x94, 0x71, 0xbf, 0xd6, 0x57, 0x0c, 0xb4, 0x77, 0x37, 0xaa, 0x2a, 0x70, 0x76, 0x49, 0xaf, 0x0c, 0x97, 0x8e, 0x78, 0x2a, 0x67, 0xc9, 0x3b, 0x3d, 0x5b, 0x01, 0x2f, 0xda, 0xd5, 0xa8, 0xde, 0x02, 0xa9, 0xac, 0x76, 0x00, 0x0b, 0x46, 0xc6, 0x2d, 0xdc, 0x08, 0xf4, 0x10, 0x2c, 0xbe, - /* (2^297)P */ 0xcb, 0x07, 0xf9, 0x91, 0xc6, 0xd5, 0x3e, 0x54, 0x63, 0xae, 0xfc, 0x10, 0xbe, 0x3a, 0x20, 0x73, 0x4e, 0x65, 0x0e, 0x2d, 0x86, 0x77, 0x83, 0x9d, 0xe2, 0x0a, 0xe9, 0xac, 0x22, 0x52, 0x76, 0xd4, 0x6e, 0xfa, 0xe0, 0x09, 0xef, 0x78, 0x82, 0x9f, 0x26, 0xf9, 0x06, 0xb5, 0xe7, 0x05, 0x0e, 0xf2, 0x46, 0x72, 0x93, 0xd3, 0x24, 0xbd, 0x87, 0x60, - /* (2^298)P */ 0x14, 0x55, 0x84, 0x7b, 0x6c, 0x60, 0x80, 0x73, 0x8c, 0xbe, 0x2d, 0xd6, 0x69, 0xd6, 0x17, 0x26, 0x44, 0x9f, 0x88, 0xa2, 0x39, 0x7c, 0x89, 0xbc, 0x6d, 0x9e, 0x46, 0xb6, 0x68, 0x66, 0xea, 0xdc, 0x31, 0xd6, 0x21, 0x51, 0x9f, 0x28, 0x28, 0xaf, 0x9e, 0x47, 0x2c, 0x4c, 0x8f, 0xf3, 0xaf, 0x1f, 0xe4, 0xab, 0xac, 0xe9, 0x0c, 0x91, 0x3a, 0x61, - /* (2^299)P */ 0xb0, 0x37, 0x55, 0x4b, 0xe9, 0xc3, 0xb1, 0xce, 0x42, 0xe6, 0xc5, 0x11, 0x7f, 0x2c, 0x11, 0xfc, 0x4e, 0x71, 0x17, 0x00, 0x74, 0x7f, 0xbf, 0x07, 0x4d, 0xfd, 0x40, 0xb2, 0x87, 0xb0, 0xef, 0x1f, 0x35, 0x2c, 0x2d, 0xd7, 0xe1, 0xe4, 0xad, 0x0e, 0x7f, 0x63, 0x66, 0x62, 0x23, 0x41, 0xf6, 0xc1, 0x14, 0xa6, 0xd7, 0xa9, 0x11, 0x56, 0x9d, 0x1b, - /* (2^300)P */ 0x02, 0x82, 0x42, 0x18, 0x4f, 0x1b, 0xc9, 0x5d, 0x78, 0x5f, 0xee, 0xed, 0x01, 0x49, 0x8f, 0xf2, 0xa0, 0xe2, 0x6e, 0xbb, 0x6b, 0x04, 0x8d, 0xb2, 0x41, 0xae, 0xc8, 0x1b, 0x59, 0x34, 0xb8, 0x2a, 0xdb, 0x1f, 0xd2, 0x52, 0xdf, 0x3f, 0x35, 0x00, 0x8b, 0x61, 0xbc, 0x97, 0xa0, 0xc4, 0x77, 0xd1, 0xe4, 0x2c, 0x59, 0x68, 0xff, 0x30, 0xf2, 0xe2, - /* (2^301)P */ 0x79, 0x08, 0xb1, 0xdb, 0x55, 0xae, 0xd0, 0xed, 0xda, 0xa0, 0xec, 0x6c, 0xae, 0x68, 0xf2, 0x0b, 0x61, 0xb3, 0xf5, 0x21, 0x69, 0x87, 0x0b, 0x03, 0xea, 0x8a, 0x15, 0xd9, 0x7e, 0xca, 0xf7, 0xcd, 0xf3, 0x33, 0xb3, 0x4c, 0x5b, 0x23, 0x4e, 0x6f, 0x90, 0xad, 0x91, 0x4b, 0x4f, 0x46, 0x37, 0xe5, 0xe8, 0xb7, 0xeb, 0xd5, 0xca, 0x34, 0x4e, 0x23, - /* (2^302)P */ 0x09, 0x02, 0xdd, 0xfd, 0x70, 0xac, 0x56, 0x80, 0x36, 0x5e, 0x49, 0xd0, 0x3f, 0xc2, 0xe0, 0xba, 0x46, 0x7f, 0x5c, 0xf7, 0xc5, 0xbd, 0xd5, 0x55, 0x7d, 0x3f, 0xd5, 0x7d, 0x06, 0xdf, 0x27, 0x20, 0x4f, 0xe9, 0x30, 0xec, 0x1b, 0xa0, 0x0c, 0xd4, 0x2c, 0xe1, 0x2b, 0x65, 0x73, 0xea, 0x75, 0x35, 0xe8, 0xe6, 0x56, 0xd6, 0x07, 0x15, 0x99, 0xdf, - /* (2^303)P */ 0x4e, 0x10, 0xb7, 0xd0, 0x63, 0x8c, 0xcf, 0x16, 0x00, 0x7c, 0x58, 0xdf, 0x86, 0xdc, 0x4e, 0xca, 0x9c, 0x40, 0x5a, 0x42, 0xfd, 0xec, 0x98, 0xa4, 0x42, 0x53, 0xae, 0x16, 0x9d, 0xfd, 0x75, 0x5a, 0x12, 0x56, 0x1e, 0xc6, 0x57, 0xcc, 0x79, 0x27, 0x96, 0x00, 0xcf, 0x80, 0x4f, 0x8a, 0x36, 0x5c, 0xbb, 0xe9, 0x12, 0xdb, 0xb6, 0x2b, 0xad, 0x96, - /* (2^304)P */ 0x92, 0x32, 0x1f, 0xfd, 0xc6, 0x02, 0x94, 0x08, 0x1b, 0x60, 0x6a, 0x9f, 0x8b, 0xd6, 0xc8, 0xad, 0xd5, 0x1b, 0x27, 0x4e, 0xa4, 0x4d, 0x4a, 0x00, 0x10, 0x5f, 0x86, 0x11, 0xf5, 0xe3, 0x14, 0x32, 0x43, 0xee, 0xb9, 0xc7, 0xab, 0xf4, 0x6f, 0xe5, 0x66, 0x0c, 0x06, 0x0d, 0x96, 0x79, 0x28, 0xaf, 0x45, 0x2b, 0x56, 0xbe, 0xe4, 0x4a, 0x52, 0xd6, - /* (2^305)P */ 0x15, 0x16, 0x69, 0xef, 0x60, 0xca, 0x82, 0x25, 0x0f, 0xc6, 0x30, 0xa0, 0x0a, 0xd1, 0x83, 0x29, 0xcd, 0xb6, 0x89, 0x6c, 0xf5, 0xb2, 0x08, 0x38, 0xe6, 0xca, 0x6b, 0x19, 0x93, 0xc6, 0x5f, 0x75, 0x8e, 0x60, 0x34, 0x23, 0xc4, 0x13, 0x17, 0x69, 0x55, 0xcc, 0x72, 0x9c, 0x2b, 0x6c, 0x80, 0xf4, 0x4b, 0x8b, 0xb6, 0x97, 0x65, 0x07, 0xb6, 0xfb, - /* (2^306)P */ 0x01, 0x99, 0x74, 0x28, 0xa6, 0x67, 0xa3, 0xe5, 0x25, 0xfb, 0xdf, 0x82, 0x93, 0xe7, 0x35, 0x74, 0xce, 0xe3, 0x15, 0x1c, 0x1d, 0x79, 0x52, 0x84, 0x08, 0x04, 0x2f, 0x5c, 0xb8, 0xcd, 0x7f, 0x89, 0xb0, 0x39, 0x93, 0x63, 0xc9, 0x5d, 0x06, 0x01, 0x59, 0xf7, 0x7e, 0xf1, 0x4c, 0x3d, 0x12, 0x8d, 0x69, 0x1d, 0xb7, 0x21, 0x5e, 0x88, 0x82, 0xa2, - /* (2^307)P */ 0x8e, 0x69, 0xaf, 0x9a, 0x41, 0x0d, 0x9d, 0xcf, 0x8e, 0x8d, 0x5c, 0x51, 0x6e, 0xde, 0x0e, 0x48, 0x23, 0x89, 0xe5, 0x37, 0x80, 0xd6, 0x9d, 0x72, 0x32, 0x26, 0x38, 0x2d, 0x63, 0xa0, 0xfa, 0xd3, 0x40, 0xc0, 0x8c, 0x68, 0x6f, 0x2b, 0x1e, 0x9a, 0x39, 0x51, 0x78, 0x74, 0x9a, 0x7b, 0x4a, 0x8f, 0x0c, 0xa0, 0x88, 0x60, 0xa5, 0x21, 0xcd, 0xc7, - /* (2^308)P */ 0x3a, 0x7f, 0x73, 0x14, 0xbf, 0x89, 0x6a, 0x4c, 0x09, 0x5d, 0xf2, 0x93, 0x20, 0x2d, 0xc4, 0x29, 0x86, 0x06, 0x95, 0xab, 0x22, 0x76, 0x4c, 0x54, 0xe1, 0x7e, 0x80, 0x6d, 0xab, 0x29, 0x61, 0x87, 0x77, 0xf6, 0xc0, 0x3e, 0xda, 0xab, 0x65, 0x7e, 0x39, 0x12, 0xa1, 0x6b, 0x42, 0xf7, 0xc5, 0x97, 0x77, 0xec, 0x6f, 0x22, 0xbe, 0x44, 0xc7, 0x03, - /* (2^309)P */ 0xa5, 0x23, 0x90, 0x41, 0xa3, 0xc5, 0x3e, 0xe0, 0xa5, 0x32, 0x49, 0x1f, 0x39, 0x78, 0xb1, 0xd8, 0x24, 0xea, 0xd4, 0x87, 0x53, 0x42, 0x51, 0xf4, 0xd9, 0x46, 0x25, 0x2f, 0x62, 0xa9, 0x90, 0x9a, 0x4a, 0x25, 0x8a, 0xd2, 0x10, 0xe7, 0x3c, 0xbc, 0x58, 0x8d, 0x16, 0x14, 0x96, 0xa4, 0x6f, 0xf8, 0x12, 0x69, 0x91, 0x73, 0xe2, 0xfa, 0xf4, 0x57, - /* (2^310)P */ 0x51, 0x45, 0x3f, 0x96, 0xdc, 0x97, 0x38, 0xa6, 0x01, 0x63, 0x09, 0xea, 0xc2, 0x13, 0x30, 0xb0, 0x00, 0xb8, 0x0a, 0xce, 0xd1, 0x8f, 0x3e, 0x69, 0x62, 0x46, 0x33, 0x9c, 0xbf, 0x4b, 0xcb, 0x0c, 0x90, 0x1c, 0x45, 0xcf, 0x37, 0x5b, 0xf7, 0x4b, 0x5e, 0x95, 0xc3, 0x28, 0x9f, 0x08, 0x83, 0x53, 0x74, 0xab, 0x0c, 0xb4, 0xc0, 0xa1, 0xbc, 0x89, - /* (2^311)P */ 0x06, 0xb1, 0x51, 0x15, 0x65, 0x60, 0x21, 0x17, 0x7a, 0x20, 0x65, 0xee, 0x12, 0x35, 0x4d, 0x46, 0xf4, 0xf8, 0xd0, 0xb1, 0xca, 0x09, 0x30, 0x08, 0x89, 0x23, 0x3b, 0xe7, 0xab, 0x8b, 0x77, 0xa6, 0xad, 0x25, 0xdd, 0xea, 0x3c, 0x7d, 0xa5, 0x24, 0xb3, 0xe8, 0xfa, 0xfb, 0xc9, 0xf2, 0x71, 0xe9, 0xfa, 0xf2, 0xdc, 0x54, 0xdd, 0x55, 0x2e, 0x2f, - /* (2^312)P */ 0x7f, 0x96, 0x96, 0xfb, 0x52, 0x86, 0xcf, 0xea, 0x62, 0x18, 0xf1, 0x53, 0x1f, 0x61, 0x2a, 0x9f, 0x8c, 0x51, 0xca, 0x2c, 0xde, 0x6d, 0xce, 0xab, 0x58, 0x32, 0x0b, 0x33, 0x9b, 0x99, 0xb4, 0x5c, 0x88, 0x2a, 0x76, 0xcc, 0x3e, 0x54, 0x1e, 0x9d, 0xa2, 0x89, 0xe4, 0x19, 0xba, 0x80, 0xc8, 0x39, 0x32, 0x7f, 0x0f, 0xc7, 0x84, 0xbb, 0x43, 0x56, - /* (2^313)P */ 0x9b, 0x07, 0xb4, 0x42, 0xa9, 0xa0, 0x78, 0x4f, 0x28, 0x70, 0x2b, 0x7e, 0x61, 0xe0, 0xdd, 0x02, 0x98, 0xfc, 0xed, 0x31, 0x80, 0xf1, 0x15, 0x52, 0x89, 0x23, 0xcd, 0x5d, 0x2b, 0xc5, 0x19, 0x32, 0xfb, 0x70, 0x50, 0x7a, 0x97, 0x6b, 0x42, 0xdb, 0xca, 0xdb, 0xc4, 0x59, 0x99, 0xe0, 0x12, 0x1f, 0x17, 0xba, 0x8b, 0xf0, 0xc4, 0x38, 0x5d, 0x27, - /* (2^314)P */ 0x29, 0x1d, 0xdc, 0x2b, 0xf6, 0x5b, 0x04, 0x61, 0x36, 0x76, 0xa0, 0x56, 0x36, 0x6e, 0xd7, 0x24, 0x4d, 0xe7, 0xef, 0x44, 0xd2, 0xd5, 0x07, 0xcd, 0xc4, 0x9d, 0x80, 0x48, 0xc3, 0x38, 0xcf, 0xd8, 0xa3, 0xdd, 0xb2, 0x5e, 0xb5, 0x70, 0x15, 0xbb, 0x36, 0x85, 0x8a, 0xd7, 0xfb, 0x56, 0x94, 0x73, 0x9c, 0x81, 0xbe, 0xb1, 0x44, 0x28, 0xf1, 0x37, - /* (2^315)P */ 0xbf, 0xcf, 0x5c, 0xd2, 0xe2, 0xea, 0xc2, 0xcd, 0x70, 0x7a, 0x9d, 0xcb, 0x81, 0xc1, 0xe9, 0xf1, 0x56, 0x71, 0x52, 0xf7, 0x1b, 0x87, 0xc6, 0xd8, 0xcc, 0xb2, 0x69, 0xf3, 0xb0, 0xbd, 0xba, 0x83, 0x12, 0x26, 0xc4, 0xce, 0x72, 0xde, 0x3b, 0x21, 0x28, 0x9e, 0x5a, 0x94, 0xf5, 0x04, 0xa3, 0xc8, 0x0f, 0x5e, 0xbc, 0x71, 0xf9, 0x0d, 0xce, 0xf5, - /* (2^316)P */ 0x93, 0x97, 0x00, 0x85, 0xf4, 0xb4, 0x40, 0xec, 0xd9, 0x2b, 0x6c, 0xd6, 0x63, 0x9e, 0x93, 0x0a, 0x5a, 0xf4, 0xa7, 0x9a, 0xe3, 0x3c, 0xf0, 0x55, 0xd1, 0x96, 0x6c, 0xf5, 0x2a, 0xce, 0xd7, 0x95, 0x72, 0xbf, 0xc5, 0x0c, 0xce, 0x79, 0xa2, 0x0a, 0x78, 0xe0, 0x72, 0xd0, 0x66, 0x28, 0x05, 0x75, 0xd3, 0x23, 0x09, 0x91, 0xed, 0x7e, 0xc4, 0xbc, - /* (2^317)P */ 0x77, 0xc2, 0x9a, 0xf7, 0xa6, 0xe6, 0x18, 0xb4, 0xe7, 0xf6, 0xda, 0xec, 0x44, 0x6d, 0xfb, 0x08, 0xee, 0x65, 0xa8, 0x92, 0x85, 0x1f, 0xba, 0x38, 0x93, 0x20, 0x5c, 0x4d, 0xd2, 0x18, 0x0f, 0x24, 0xbe, 0x1a, 0x96, 0x44, 0x7d, 0xeb, 0xb3, 0xda, 0x95, 0xf4, 0xaf, 0x6c, 0x06, 0x0f, 0x47, 0x37, 0xc8, 0x77, 0x63, 0xe1, 0x29, 0xef, 0xff, 0xa5, - /* (2^318)P */ 0x16, 0x12, 0xd9, 0x47, 0x90, 0x22, 0x9b, 0x05, 0xf2, 0xa5, 0x9a, 0xae, 0x83, 0x98, 0xb5, 0xac, 0xab, 0x29, 0xaa, 0xdc, 0x5f, 0xde, 0xcd, 0xf7, 0x42, 0xad, 0x3b, 0x96, 0xd6, 0x3e, 0x6e, 0x52, 0x47, 0xb1, 0xab, 0x51, 0xde, 0x49, 0x7c, 0x87, 0x8d, 0x86, 0xe2, 0x70, 0x13, 0x21, 0x51, 0x1c, 0x0c, 0x25, 0xc1, 0xb0, 0xe6, 0x19, 0xcf, 0x12, - /* (2^319)P */ 0xf0, 0xbc, 0x97, 0x8f, 0x4b, 0x2f, 0xd1, 0x1f, 0x8c, 0x57, 0xed, 0x3c, 0xf4, 0x26, 0x19, 0xbb, 0x60, 0xca, 0x24, 0xc5, 0xd9, 0x97, 0xe2, 0x5f, 0x76, 0x49, 0x39, 0x7e, 0x2d, 0x12, 0x21, 0x98, 0xda, 0xe6, 0xdb, 0xd2, 0xd8, 0x9f, 0x18, 0xd8, 0x83, 0x6c, 0xba, 0x89, 0x8d, 0x29, 0xfa, 0x46, 0x33, 0x8c, 0x28, 0xdf, 0x6a, 0xb3, 0x69, 0x28, - /* (2^320)P */ 0x86, 0x17, 0xbc, 0xd6, 0x7c, 0xba, 0x1e, 0x83, 0xbb, 0x84, 0xb5, 0x8c, 0xad, 0xdf, 0xa1, 0x24, 0x81, 0x70, 0x40, 0x0f, 0xad, 0xad, 0x3b, 0x23, 0xd0, 0x93, 0xa0, 0x49, 0x5c, 0x4b, 0x51, 0xbe, 0x20, 0x49, 0x4e, 0xda, 0x2d, 0xd3, 0xad, 0x1b, 0x74, 0x08, 0x41, 0xf0, 0xef, 0x19, 0xe9, 0x45, 0x5d, 0x02, 0xae, 0x26, 0x25, 0xd9, 0xd1, 0xc2, - /* (2^321)P */ 0x48, 0x81, 0x3e, 0xb2, 0x83, 0xf8, 0x4d, 0xb3, 0xd0, 0x4c, 0x75, 0xb3, 0xa0, 0x52, 0x26, 0xf2, 0xaf, 0x5d, 0x36, 0x70, 0x72, 0xd6, 0xb7, 0x88, 0x08, 0x69, 0xbd, 0x15, 0x25, 0xb1, 0x45, 0x1b, 0xb7, 0x0b, 0x5f, 0x71, 0x5d, 0x83, 0x49, 0xb9, 0x84, 0x3b, 0x7c, 0xc1, 0x50, 0x93, 0x05, 0x53, 0xe0, 0x61, 0xea, 0xc1, 0xef, 0xdb, 0x82, 0x97, - /* (2^322)P */ 0x00, 0xd5, 0xc3, 0x3a, 0x4d, 0x8a, 0x23, 0x7a, 0xef, 0xff, 0x37, 0xef, 0xf3, 0xbc, 0xa9, 0xb6, 0xae, 0xd7, 0x3a, 0x7b, 0xfd, 0x3e, 0x8e, 0x9b, 0xab, 0x44, 0x54, 0x60, 0x28, 0x6c, 0xbf, 0x15, 0x24, 0x4a, 0x56, 0x60, 0x7f, 0xa9, 0x7a, 0x28, 0x59, 0x2c, 0x8a, 0xd1, 0x7d, 0x6b, 0x00, 0xfd, 0xa5, 0xad, 0xbc, 0x19, 0x3f, 0xcb, 0x73, 0xe0, - /* (2^323)P */ 0xcf, 0x9e, 0x66, 0x06, 0x4d, 0x2b, 0xf5, 0x9c, 0xc2, 0x9d, 0x9e, 0xed, 0x5a, 0x5c, 0x2d, 0x00, 0xbf, 0x29, 0x90, 0x88, 0xe4, 0x5d, 0xfd, 0xe2, 0xf0, 0x38, 0xec, 0x4d, 0x26, 0xea, 0x54, 0xf0, 0x3c, 0x84, 0x10, 0x6a, 0xf9, 0x66, 0x9c, 0xe7, 0x21, 0xfd, 0x0f, 0xc7, 0x13, 0x50, 0x81, 0xb6, 0x50, 0xf9, 0x04, 0x7f, 0xa4, 0x37, 0x85, 0x14, - /* (2^324)P */ 0xdb, 0x87, 0x49, 0xc7, 0xa8, 0x39, 0x0c, 0x32, 0x98, 0x0c, 0xb9, 0x1a, 0x1b, 0x4d, 0xe0, 0x8a, 0x9a, 0x8e, 0x8f, 0xab, 0x5a, 0x17, 0x3d, 0x04, 0x21, 0xce, 0x3e, 0x2c, 0xf9, 0xa3, 0x97, 0xe4, 0x77, 0x95, 0x0e, 0xb6, 0xa5, 0x15, 0xad, 0x3a, 0x1e, 0x46, 0x53, 0x17, 0x09, 0x83, 0x71, 0x4e, 0x86, 0x38, 0xd5, 0x23, 0x44, 0x16, 0x8d, 0xc8, - /* (2^325)P */ 0x05, 0x5e, 0x99, 0x08, 0xbb, 0xc3, 0xc0, 0xb7, 0x6c, 0x12, 0xf2, 0xf3, 0xf4, 0x7c, 0x6a, 0x4d, 0x9e, 0xeb, 0x3d, 0xb9, 0x63, 0x94, 0xce, 0x81, 0xd8, 0x11, 0xcb, 0x55, 0x69, 0x4a, 0x20, 0x0b, 0x4c, 0x2e, 0x14, 0xb8, 0xd4, 0x6a, 0x7c, 0xf0, 0xed, 0xfc, 0x8f, 0xef, 0xa0, 0xeb, 0x6c, 0x01, 0xe2, 0xdc, 0x10, 0x22, 0xa2, 0x01, 0x85, 0x64, - /* (2^326)P */ 0x58, 0xe1, 0x9c, 0x27, 0x55, 0xc6, 0x25, 0xa6, 0x7d, 0x67, 0x88, 0x65, 0x99, 0x6c, 0xcb, 0xdb, 0x27, 0x4f, 0x44, 0x29, 0xf5, 0x4a, 0x23, 0x10, 0xbc, 0x03, 0x3f, 0x36, 0x1e, 0xef, 0xb0, 0xba, 0x75, 0xe8, 0x74, 0x5f, 0x69, 0x3e, 0x26, 0x40, 0xb4, 0x2f, 0xdc, 0x43, 0xbf, 0xa1, 0x8b, 0xbd, 0xca, 0x6e, 0xc1, 0x6e, 0x21, 0x79, 0xa0, 0xd0, - /* (2^327)P */ 0x78, 0x93, 0x4a, 0x2d, 0x22, 0x6e, 0x6e, 0x7d, 0x74, 0xd2, 0x66, 0x58, 0xce, 0x7b, 0x1d, 0x97, 0xb1, 0xf2, 0xda, 0x1c, 0x79, 0xfb, 0xba, 0xd1, 0xc0, 0xc5, 0x6e, 0xc9, 0x11, 0x89, 0xd2, 0x41, 0x8d, 0x70, 0xb9, 0xcc, 0xea, 0x6a, 0xb3, 0x45, 0xb6, 0x05, 0x2e, 0xf2, 0x17, 0xf1, 0x27, 0xb8, 0xed, 0x06, 0x1f, 0xdb, 0x9d, 0x1f, 0x69, 0x28, - /* (2^328)P */ 0x93, 0x12, 0xa8, 0x11, 0xe1, 0x92, 0x30, 0x8d, 0xac, 0xe1, 0x1c, 0x60, 0x7c, 0xed, 0x2d, 0x2e, 0xd3, 0x03, 0x5c, 0x9c, 0xc5, 0xbd, 0x64, 0x4a, 0x8c, 0xba, 0x76, 0xfe, 0xc6, 0xc1, 0xea, 0xc2, 0x4f, 0xbe, 0x70, 0x3d, 0x64, 0xcf, 0x8e, 0x18, 0xcb, 0xcd, 0x57, 0xa7, 0xf7, 0x36, 0xa9, 0x6b, 0x3e, 0xb8, 0x69, 0xee, 0x47, 0xa2, 0x7e, 0xb2, - /* (2^329)P */ 0x96, 0xaf, 0x3a, 0xf5, 0xed, 0xcd, 0xaf, 0xf7, 0x82, 0xaf, 0x59, 0x62, 0x0b, 0x36, 0x85, 0xf9, 0xaf, 0xd6, 0x38, 0xff, 0x87, 0x2e, 0x1d, 0x6c, 0x8b, 0xaf, 0x3b, 0xdf, 0x28, 0xa2, 0xd6, 0x4d, 0x80, 0x92, 0xc3, 0x0f, 0x34, 0xa8, 0xae, 0x69, 0x5d, 0x7b, 0x9d, 0xbc, 0xf5, 0xfd, 0x1d, 0xb1, 0x96, 0x55, 0x86, 0xe1, 0x5c, 0xb6, 0xac, 0xb9, - /* (2^330)P */ 0x50, 0x9e, 0x37, 0x28, 0x7d, 0xa8, 0x33, 0x63, 0xda, 0x3f, 0x20, 0x98, 0x0e, 0x09, 0xa8, 0x77, 0x3b, 0x7a, 0xfc, 0x16, 0x85, 0x44, 0x64, 0x77, 0x65, 0x68, 0x92, 0x41, 0xc6, 0x1f, 0xdf, 0x27, 0xf9, 0xec, 0xa0, 0x61, 0x22, 0xea, 0x19, 0xe7, 0x75, 0x8b, 0x4e, 0xe5, 0x0f, 0xb7, 0xf7, 0xd2, 0x53, 0xf4, 0xdd, 0x4a, 0xaa, 0x78, 0x40, 0xb7, - /* (2^331)P */ 0xd4, 0x89, 0xe3, 0x79, 0xba, 0xb6, 0xc3, 0xda, 0xe6, 0x78, 0x65, 0x7d, 0x6e, 0x22, 0x62, 0xb1, 0x3d, 0xea, 0x90, 0x84, 0x30, 0x5e, 0xd4, 0x39, 0x84, 0x78, 0xd9, 0x75, 0xd6, 0xce, 0x2a, 0x11, 0x29, 0x69, 0xa4, 0x5e, 0xaa, 0x2a, 0x98, 0x5a, 0xe5, 0x91, 0x8f, 0xb2, 0xfb, 0xda, 0x97, 0xe8, 0x83, 0x6f, 0x04, 0xb9, 0x5d, 0xaf, 0xe1, 0x9b, - /* (2^332)P */ 0x8b, 0xe4, 0xe1, 0x48, 0x9c, 0xc4, 0x83, 0x89, 0xdf, 0x65, 0xd3, 0x35, 0x55, 0x13, 0xf4, 0x1f, 0x36, 0x92, 0x33, 0x38, 0xcb, 0xed, 0x15, 0xe6, 0x60, 0x2d, 0x25, 0xf5, 0x36, 0x60, 0x3a, 0x37, 0x9b, 0x71, 0x9d, 0x42, 0xb0, 0x14, 0xc8, 0xba, 0x62, 0xa3, 0x49, 0xb0, 0x88, 0xc1, 0x72, 0x73, 0xdd, 0x62, 0x40, 0xa9, 0x62, 0x88, 0x99, 0xca, - /* (2^333)P */ 0x47, 0x7b, 0xea, 0xda, 0x46, 0x2f, 0x45, 0xc6, 0xe3, 0xb4, 0x4d, 0x8d, 0xac, 0x0b, 0x54, 0x22, 0x06, 0x31, 0x16, 0x66, 0x3e, 0xe4, 0x38, 0x12, 0xcd, 0xf3, 0xe7, 0x99, 0x37, 0xd9, 0x62, 0x24, 0x4b, 0x05, 0xf2, 0x58, 0xe6, 0x29, 0x4b, 0x0d, 0xf6, 0xc1, 0xba, 0xa0, 0x1e, 0x0f, 0xcb, 0x1f, 0xc6, 0x2b, 0x19, 0xfc, 0x82, 0x01, 0xd0, 0x86, - /* (2^334)P */ 0xa2, 0xae, 0x77, 0x20, 0xfb, 0xa8, 0x18, 0xb4, 0x61, 0xef, 0xe8, 0x52, 0x79, 0xbb, 0x86, 0x90, 0x5d, 0x2e, 0x76, 0xed, 0x66, 0x60, 0x5d, 0x00, 0xb5, 0xa4, 0x00, 0x40, 0x89, 0xec, 0xd1, 0xd2, 0x0d, 0x26, 0xb9, 0x30, 0xb2, 0xd2, 0xb8, 0xe8, 0x0e, 0x56, 0xf9, 0x67, 0x94, 0x2e, 0x62, 0xe1, 0x79, 0x48, 0x2b, 0xa9, 0xfa, 0xea, 0xdb, 0x28, - /* (2^335)P */ 0x35, 0xf1, 0xb0, 0x43, 0xbd, 0x27, 0xef, 0x18, 0x44, 0xa2, 0x04, 0xb4, 0x69, 0xa1, 0x97, 0x1f, 0x8c, 0x04, 0x82, 0x9b, 0x00, 0x6d, 0xf8, 0xbf, 0x7d, 0xc1, 0x5b, 0xab, 0xe8, 0xb2, 0x34, 0xbd, 0xaf, 0x7f, 0xb2, 0x0d, 0xf3, 0xed, 0xfc, 0x5b, 0x50, 0xee, 0xe7, 0x4a, 0x20, 0xd9, 0xf5, 0xc6, 0x9a, 0x97, 0x6d, 0x07, 0x2f, 0xb9, 0x31, 0x02, - /* (2^336)P */ 0xf9, 0x54, 0x4a, 0xc5, 0x61, 0x7e, 0x1d, 0xa6, 0x0e, 0x1a, 0xa8, 0xd3, 0x8c, 0x36, 0x7d, 0xf1, 0x06, 0xb1, 0xac, 0x93, 0xcd, 0xe9, 0x8f, 0x61, 0x6c, 0x5d, 0x03, 0x23, 0xdf, 0x85, 0x53, 0x39, 0x63, 0x5e, 0xeb, 0xf3, 0xd3, 0xd3, 0x75, 0x97, 0x9b, 0x62, 0x9b, 0x01, 0xb3, 0x19, 0xd8, 0x2b, 0x36, 0xf2, 0x2c, 0x2c, 0x6f, 0x36, 0xc6, 0x3c, - /* (2^337)P */ 0x05, 0x74, 0x43, 0x10, 0xb6, 0xb0, 0xf8, 0xbf, 0x02, 0x46, 0x9a, 0xee, 0xc1, 0xaf, 0xc1, 0xe5, 0x5a, 0x2e, 0xbb, 0xe1, 0xdc, 0xc6, 0xce, 0x51, 0x29, 0x50, 0xbf, 0x1b, 0xde, 0xff, 0xba, 0x4d, 0x8d, 0x8b, 0x7e, 0xe7, 0xbd, 0x5b, 0x8f, 0xbe, 0xe3, 0x75, 0x71, 0xff, 0x37, 0x05, 0x5a, 0x10, 0xeb, 0x54, 0x7e, 0x44, 0x72, 0x2c, 0xd4, 0xfc, - /* (2^338)P */ 0x03, 0x12, 0x1c, 0xb2, 0x08, 0x90, 0xa1, 0x2d, 0x50, 0xa0, 0xad, 0x7f, 0x8d, 0xa6, 0x97, 0xc1, 0xbd, 0xdc, 0xc3, 0xa7, 0xad, 0x31, 0xdf, 0xb8, 0x03, 0x84, 0xc3, 0xb9, 0x29, 0x3d, 0x92, 0x2e, 0xc3, 0x90, 0x07, 0xe8, 0xa7, 0xc7, 0xbc, 0x61, 0xe9, 0x3e, 0xa0, 0x35, 0xda, 0x1d, 0xab, 0x48, 0xfe, 0x50, 0xc9, 0x25, 0x59, 0x23, 0x69, 0x3f, - /* (2^339)P */ 0x8e, 0x91, 0xab, 0x6b, 0x91, 0x4f, 0x89, 0x76, 0x67, 0xad, 0xb2, 0x65, 0x9d, 0xad, 0x02, 0x36, 0xdc, 0xac, 0x96, 0x93, 0x97, 0x21, 0x14, 0xd0, 0xe8, 0x11, 0x60, 0x1e, 0xeb, 0x96, 0x06, 0xf2, 0x53, 0xf2, 0x6d, 0xb7, 0x93, 0x6f, 0x26, 0x91, 0x23, 0xe3, 0x34, 0x04, 0x92, 0x91, 0x37, 0x08, 0x50, 0xd6, 0x28, 0x09, 0x27, 0xa1, 0x0c, 0x00, - /* (2^340)P */ 0x1f, 0xbb, 0x21, 0x26, 0x33, 0xcb, 0xa4, 0xd1, 0xee, 0x85, 0xf9, 0xd9, 0x3c, 0x90, 0xc3, 0xd1, 0x26, 0xa2, 0x25, 0x93, 0x43, 0x61, 0xed, 0x91, 0x6e, 0x54, 0x03, 0x2e, 0x42, 0x9d, 0xf7, 0xa6, 0x02, 0x0f, 0x2f, 0x9c, 0x7a, 0x8d, 0x12, 0xc2, 0x18, 0xfc, 0x41, 0xff, 0x85, 0x26, 0x1a, 0x44, 0x55, 0x0b, 0x89, 0xab, 0x6f, 0x62, 0x33, 0x8c, - /* (2^341)P */ 0xe0, 0x3c, 0x5d, 0x70, 0x64, 0x87, 0x81, 0x35, 0xf2, 0x37, 0xa6, 0x24, 0x3e, 0xe0, 0x62, 0xd5, 0x71, 0xe7, 0x93, 0xfb, 0xac, 0xc3, 0xe7, 0xc7, 0x04, 0xe2, 0x70, 0xd3, 0x29, 0x5b, 0x21, 0xbf, 0xf4, 0x26, 0x5d, 0xf3, 0x95, 0xb4, 0x2a, 0x6a, 0x07, 0x55, 0xa6, 0x4b, 0x3b, 0x15, 0xf2, 0x25, 0x8a, 0x95, 0x3f, 0x63, 0x2f, 0x7a, 0x23, 0x96, - /* (2^342)P */ 0x0d, 0x3d, 0xd9, 0x13, 0xa7, 0xb3, 0x5e, 0x67, 0xf7, 0x02, 0x23, 0xee, 0x84, 0xff, 0x99, 0xda, 0xb9, 0x53, 0xf8, 0xf0, 0x0e, 0x39, 0x2f, 0x3c, 0x64, 0x34, 0xe3, 0x09, 0xfd, 0x2b, 0x33, 0xc7, 0xfe, 0x62, 0x2b, 0x84, 0xdf, 0x2b, 0xd2, 0x7c, 0x26, 0x01, 0x70, 0x66, 0x5b, 0x85, 0xc2, 0xbe, 0x88, 0x37, 0xf1, 0x30, 0xac, 0xb8, 0x76, 0xa3, - /* (2^343)P */ 0x6e, 0x01, 0xf0, 0x55, 0x35, 0xe4, 0xbd, 0x43, 0x62, 0x9d, 0xd6, 0x11, 0xef, 0x6f, 0xb8, 0x8c, 0xaa, 0x98, 0x87, 0xc6, 0x6d, 0xc4, 0xcc, 0x74, 0x92, 0x53, 0x4a, 0xdf, 0xe4, 0x08, 0x89, 0x17, 0xd0, 0x0f, 0xf4, 0x00, 0x60, 0x78, 0x08, 0x44, 0xb5, 0xda, 0x18, 0xed, 0x98, 0xc8, 0x61, 0x3d, 0x39, 0xdb, 0xcf, 0x1d, 0x49, 0x40, 0x65, 0x75, - /* (2^344)P */ 0x8e, 0x10, 0xae, 0x5f, 0x06, 0xd2, 0x95, 0xfd, 0x20, 0x16, 0x49, 0x5b, 0x57, 0xbe, 0x22, 0x8b, 0x43, 0xfb, 0xe6, 0xcc, 0x26, 0xa5, 0x5d, 0xd3, 0x68, 0xc5, 0xf9, 0x5a, 0x86, 0x24, 0x87, 0x27, 0x05, 0xfd, 0xe2, 0xff, 0xb3, 0xa3, 0x7b, 0x37, 0x59, 0xc5, 0x4e, 0x14, 0x94, 0xf9, 0x3b, 0xcb, 0x7c, 0xed, 0xca, 0x1d, 0xb2, 0xac, 0x05, 0x4a, - /* (2^345)P */ 0xf4, 0xd1, 0x81, 0xeb, 0x89, 0xbf, 0xfe, 0x1e, 0x41, 0x92, 0x29, 0xee, 0xe1, 0x43, 0xf5, 0x86, 0x1d, 0x2f, 0xbb, 0x1e, 0x84, 0x5d, 0x7b, 0x8d, 0xd5, 0xda, 0xee, 0x1e, 0x8a, 0xd0, 0x27, 0xf2, 0x60, 0x51, 0x59, 0x82, 0xf4, 0x84, 0x2b, 0x5b, 0x14, 0x2d, 0x81, 0x82, 0x3e, 0x2b, 0xb4, 0x6d, 0x51, 0x4f, 0xc5, 0xcb, 0xbf, 0x74, 0xe3, 0xb4, - /* (2^346)P */ 0x19, 0x2f, 0x22, 0xb3, 0x04, 0x5f, 0x81, 0xca, 0x05, 0x60, 0xb9, 0xaa, 0xee, 0x0e, 0x2f, 0x48, 0x38, 0xf9, 0x91, 0xb4, 0x66, 0xe4, 0x57, 0x28, 0x54, 0x10, 0xe9, 0x61, 0x9d, 0xd4, 0x90, 0x75, 0xb1, 0x39, 0x23, 0xb6, 0xfc, 0x82, 0xe0, 0xfa, 0xbb, 0x5c, 0x6e, 0xc3, 0x44, 0x13, 0x00, 0x83, 0x55, 0x9e, 0x8e, 0x10, 0x61, 0x81, 0x91, 0x04, - /* (2^347)P */ 0x5f, 0x2a, 0xd7, 0x81, 0xd9, 0x9c, 0xbb, 0x79, 0xbc, 0x62, 0x56, 0x98, 0x03, 0x5a, 0x18, 0x85, 0x2a, 0x9c, 0xd0, 0xfb, 0xd2, 0xb1, 0xaf, 0xef, 0x0d, 0x24, 0xc5, 0xfa, 0x39, 0xbb, 0x6b, 0xed, 0xa4, 0xdf, 0xe4, 0x87, 0xcd, 0x41, 0xd3, 0x72, 0x32, 0xc6, 0x28, 0x21, 0xb1, 0xba, 0x8b, 0xa3, 0x91, 0x79, 0x76, 0x22, 0x25, 0x10, 0x61, 0xd1, - /* (2^348)P */ 0x73, 0xb5, 0x32, 0x97, 0xdd, 0xeb, 0xdd, 0x22, 0x22, 0xf1, 0x33, 0x3c, 0x77, 0x56, 0x7d, 0x6b, 0x48, 0x2b, 0x05, 0x81, 0x03, 0x03, 0x91, 0x9a, 0xe3, 0x5e, 0xd4, 0xee, 0x3f, 0xf8, 0xbb, 0x50, 0x21, 0x32, 0x4c, 0x4a, 0x58, 0x49, 0xde, 0x0c, 0xde, 0x30, 0x82, 0x3d, 0x92, 0xf0, 0x6c, 0xcc, 0x32, 0x3e, 0xd2, 0x78, 0x8a, 0x6e, 0x2c, 0xd0, - /* (2^349)P */ 0xf0, 0xf7, 0xa1, 0x0b, 0xc1, 0x74, 0x85, 0xa8, 0xe9, 0xdd, 0x48, 0xa1, 0xc0, 0x16, 0xd8, 0x2b, 0x61, 0x08, 0xc2, 0x2b, 0x30, 0x26, 0x79, 0xce, 0x9e, 0xfd, 0x39, 0xd7, 0x81, 0xa4, 0x63, 0x8c, 0xd5, 0x74, 0xa0, 0x88, 0xfa, 0x03, 0x30, 0xe9, 0x7f, 0x2b, 0xc6, 0x02, 0xc9, 0x5e, 0xe4, 0xd5, 0x4d, 0x92, 0xd0, 0xf6, 0xf2, 0x5b, 0x79, 0x08, - /* (2^350)P */ 0x34, 0x89, 0x81, 0x43, 0xd1, 0x94, 0x2c, 0x10, 0x54, 0x9b, 0xa0, 0xe5, 0x44, 0xe8, 0xc2, 0x2f, 0x3e, 0x0e, 0x74, 0xae, 0xba, 0xe2, 0xac, 0x85, 0x6b, 0xd3, 0x5c, 0x97, 0xf7, 0x90, 0xf1, 0x12, 0xc0, 0x03, 0xc8, 0x1f, 0x37, 0x72, 0x8c, 0x9b, 0x9c, 0x17, 0x96, 0x9d, 0xc7, 0xbf, 0xa3, 0x3f, 0x44, 0x3d, 0x87, 0x81, 0xbd, 0x81, 0xa6, 0x5f, - /* (2^351)P */ 0xe4, 0xff, 0x78, 0x62, 0x82, 0x5b, 0x76, 0x58, 0xf5, 0x5b, 0xa6, 0xc4, 0x53, 0x11, 0x3b, 0x7b, 0xaa, 0x67, 0xf8, 0xea, 0x3b, 0x5d, 0x9a, 0x2e, 0x04, 0xeb, 0x4a, 0x24, 0xfb, 0x56, 0xf0, 0xa8, 0xd4, 0x14, 0xed, 0x0f, 0xfd, 0xc5, 0x26, 0x17, 0x2a, 0xf0, 0xb9, 0x13, 0x8c, 0xbd, 0x65, 0x14, 0x24, 0x95, 0x27, 0x12, 0x63, 0x2a, 0x09, 0x18, - /* (2^352)P */ 0xe1, 0x5c, 0xe7, 0xe0, 0x00, 0x6a, 0x96, 0xf2, 0x49, 0x6a, 0x39, 0xa5, 0xe0, 0x17, 0x79, 0x4a, 0x63, 0x07, 0x62, 0x09, 0x61, 0x1b, 0x6e, 0xa9, 0xb5, 0x62, 0xb7, 0xde, 0xdf, 0x80, 0x4c, 0x5a, 0x99, 0x73, 0x59, 0x9d, 0xfb, 0xb1, 0x5e, 0xbe, 0xb8, 0xb7, 0x63, 0x93, 0xe8, 0xad, 0x5e, 0x1f, 0xae, 0x59, 0x1c, 0xcd, 0xb4, 0xc2, 0xb3, 0x8a, - /* (2^353)P */ 0x78, 0x53, 0xa1, 0x4c, 0x70, 0x9c, 0x63, 0x7e, 0xb3, 0x12, 0x40, 0x5f, 0xbb, 0x23, 0xa7, 0xf7, 0x77, 0x96, 0x5b, 0x4d, 0x91, 0x10, 0x52, 0x85, 0x9e, 0xa5, 0x38, 0x0b, 0xfd, 0x25, 0x01, 0x4b, 0xfa, 0x4d, 0xd3, 0x3f, 0x78, 0x74, 0x42, 0xff, 0x62, 0x2d, 0x27, 0xdc, 0x9d, 0xd1, 0x29, 0x76, 0x2e, 0x78, 0xb3, 0x35, 0xfa, 0x15, 0xd5, 0x38, - /* (2^354)P */ 0x8b, 0xc7, 0x43, 0xce, 0xf0, 0x5e, 0xf1, 0x0d, 0x02, 0x38, 0xe8, 0x82, 0xc9, 0x25, 0xad, 0x2d, 0x27, 0xa4, 0x54, 0x18, 0xb2, 0x30, 0x73, 0xa4, 0x41, 0x08, 0xe4, 0x86, 0xe6, 0x8c, 0xe9, 0x2a, 0x34, 0xb3, 0xd6, 0x61, 0x8f, 0x66, 0x26, 0x08, 0xb6, 0x06, 0x33, 0xaa, 0x12, 0xac, 0x72, 0xec, 0x2e, 0x52, 0xa3, 0x25, 0x3e, 0xd7, 0x62, 0xe8, - /* (2^355)P */ 0xc4, 0xbb, 0x89, 0xc8, 0x40, 0xcc, 0x84, 0xec, 0x4a, 0xd9, 0xc4, 0x55, 0x78, 0x00, 0xcf, 0xd8, 0xe9, 0x24, 0x59, 0xdc, 0x5e, 0xf0, 0x66, 0xa1, 0x83, 0xae, 0x97, 0x18, 0xc5, 0x54, 0x27, 0xa2, 0x21, 0x52, 0x03, 0x31, 0x5b, 0x11, 0x67, 0xf6, 0x12, 0x00, 0x87, 0x2f, 0xff, 0x59, 0x70, 0x8f, 0x6d, 0x71, 0xab, 0xab, 0x24, 0xb8, 0xba, 0x35, - /* (2^356)P */ 0x69, 0x43, 0xa7, 0x14, 0x06, 0x96, 0xe9, 0xc2, 0xe3, 0x2b, 0x45, 0x22, 0xc0, 0xd0, 0x2f, 0x34, 0xd1, 0x01, 0x99, 0xfc, 0x99, 0x38, 0xa1, 0x25, 0x2e, 0x59, 0x6c, 0x27, 0xc9, 0xeb, 0x7b, 0xdc, 0x4e, 0x26, 0x68, 0xba, 0xfa, 0xec, 0x02, 0x05, 0x64, 0x80, 0x30, 0x20, 0x5c, 0x26, 0x7f, 0xaf, 0x95, 0x17, 0x3d, 0x5c, 0x9e, 0x96, 0x96, 0xaf, - /* (2^357)P */ 0xa6, 0xba, 0x21, 0x29, 0x32, 0xe2, 0x98, 0xde, 0x9b, 0x6d, 0x0b, 0x44, 0x91, 0xa8, 0x3e, 0xd4, 0xb8, 0x04, 0x6c, 0xf6, 0x04, 0x39, 0xbd, 0x52, 0x05, 0x15, 0x27, 0x78, 0x8e, 0x55, 0xac, 0x79, 0xc5, 0xe6, 0x00, 0x7f, 0x90, 0xa2, 0xdd, 0x07, 0x13, 0xe0, 0x24, 0x70, 0x5c, 0x0f, 0x4d, 0xa9, 0xf9, 0xae, 0xcb, 0x34, 0x10, 0x9d, 0x89, 0x9d, - /* (2^358)P */ 0x12, 0xe0, 0xb3, 0x9f, 0xc4, 0x96, 0x1d, 0xcf, 0xed, 0x99, 0x64, 0x28, 0x8d, 0xc7, 0x31, 0x82, 0xee, 0x5e, 0x75, 0x48, 0xff, 0x3a, 0xf2, 0x09, 0x34, 0x03, 0x93, 0x52, 0x19, 0xb2, 0xc5, 0x81, 0x93, 0x45, 0x5e, 0x59, 0x21, 0x2b, 0xec, 0x89, 0xba, 0x36, 0x6e, 0xf9, 0x82, 0x75, 0x7e, 0x82, 0x3f, 0xaa, 0xe2, 0xe3, 0x3b, 0x94, 0xfd, 0x98, - /* (2^359)P */ 0x7c, 0xdb, 0x75, 0x31, 0x61, 0xfb, 0x15, 0x28, 0x94, 0xd7, 0xc3, 0x5a, 0xa9, 0xa1, 0x0a, 0x66, 0x0f, 0x2b, 0x13, 0x3e, 0x42, 0xb5, 0x28, 0x3a, 0xca, 0x83, 0xf3, 0x61, 0x22, 0xf4, 0x40, 0xc5, 0xdf, 0xe7, 0x31, 0x9f, 0x7e, 0x51, 0x75, 0x06, 0x9d, 0x51, 0xc8, 0xe7, 0x9f, 0xc3, 0x71, 0x4f, 0x3d, 0x5b, 0xfb, 0xe9, 0x8e, 0x08, 0x40, 0x8e, - /* (2^360)P */ 0xf7, 0x31, 0xad, 0x50, 0x5d, 0x25, 0x93, 0x73, 0x68, 0xf6, 0x7c, 0x89, 0x5a, 0x3d, 0x9f, 0x9b, 0x05, 0x82, 0xe7, 0x70, 0x4b, 0x19, 0xaa, 0xcf, 0xff, 0xde, 0x50, 0x8f, 0x2f, 0x69, 0xd3, 0xf0, 0x99, 0x51, 0x6b, 0x9d, 0xb6, 0x56, 0x6f, 0xf8, 0x4c, 0x74, 0x8b, 0x4c, 0x91, 0xf9, 0xa9, 0xb1, 0x3e, 0x07, 0xdf, 0x0b, 0x27, 0x8a, 0xb1, 0xed, - /* (2^361)P */ 0xfb, 0x67, 0xd9, 0x48, 0xd2, 0xe4, 0x44, 0x9b, 0x43, 0x15, 0x8a, 0xeb, 0x00, 0x53, 0xad, 0x25, 0xc7, 0x7e, 0x19, 0x30, 0x87, 0xb7, 0xd5, 0x5f, 0x04, 0xf8, 0xaa, 0xdd, 0x57, 0xae, 0x34, 0x75, 0xe2, 0x84, 0x4b, 0x54, 0x60, 0x37, 0x95, 0xe4, 0xd3, 0xec, 0xac, 0xef, 0x47, 0x31, 0xa3, 0xc8, 0x31, 0x22, 0xdb, 0x26, 0xe7, 0x6a, 0xb5, 0xad, - /* (2^362)P */ 0x44, 0x09, 0x5c, 0x95, 0xe4, 0x72, 0x3c, 0x1a, 0xd1, 0xac, 0x42, 0x51, 0x99, 0x6f, 0xfa, 0x1f, 0xf2, 0x22, 0xbe, 0xff, 0x7b, 0x66, 0xf5, 0x6c, 0xb3, 0x66, 0xc7, 0x4d, 0x78, 0x31, 0x83, 0x80, 0xf5, 0x41, 0xe9, 0x7f, 0xbe, 0xf7, 0x23, 0x49, 0x6b, 0x84, 0x4e, 0x7e, 0x47, 0x07, 0x6e, 0x74, 0xdf, 0xe5, 0x9d, 0x9e, 0x56, 0x2a, 0xc0, 0xbc, - /* (2^363)P */ 0xac, 0x10, 0x80, 0x8c, 0x7c, 0xfa, 0x83, 0xdf, 0xb3, 0xd0, 0xc4, 0xbe, 0xfb, 0x9f, 0xac, 0xc9, 0xc3, 0x40, 0x95, 0x0b, 0x09, 0x23, 0xda, 0x63, 0x67, 0xcf, 0xe7, 0x9f, 0x7d, 0x7b, 0x6b, 0xe2, 0xe6, 0x6d, 0xdb, 0x87, 0x9e, 0xa6, 0xff, 0x6d, 0xab, 0xbd, 0xfb, 0x54, 0x84, 0x68, 0xcf, 0x89, 0xf1, 0xd0, 0xe2, 0x85, 0x61, 0xdc, 0x22, 0xd1, - /* (2^364)P */ 0xa8, 0x48, 0xfb, 0x8c, 0x6a, 0x63, 0x01, 0x72, 0x43, 0x43, 0xeb, 0x21, 0xa3, 0x00, 0x8a, 0xc0, 0x87, 0x51, 0x9e, 0x86, 0x75, 0x16, 0x79, 0xf9, 0x6b, 0x11, 0x80, 0x62, 0xc2, 0x9d, 0xb8, 0x8c, 0x30, 0x8e, 0x8d, 0x03, 0x52, 0x7e, 0x31, 0x59, 0x38, 0xf9, 0x25, 0xc7, 0x0f, 0xc7, 0xa8, 0x2b, 0x5c, 0x80, 0xfa, 0x90, 0xa2, 0x63, 0xca, 0xe7, - /* (2^365)P */ 0xf1, 0x5d, 0xb5, 0xd9, 0x20, 0x10, 0x7d, 0x0f, 0xc5, 0x50, 0x46, 0x07, 0xff, 0x02, 0x75, 0x2b, 0x4a, 0xf3, 0x39, 0x91, 0x72, 0xb7, 0xd5, 0xcc, 0x38, 0xb8, 0xe7, 0x36, 0x26, 0x5e, 0x11, 0x97, 0x25, 0xfb, 0x49, 0x68, 0xdc, 0xb4, 0x46, 0x87, 0x5c, 0xc2, 0x7f, 0xaa, 0x7d, 0x36, 0x23, 0xa6, 0xc6, 0x53, 0xec, 0xbc, 0x57, 0x47, 0xc1, 0x2b, - /* (2^366)P */ 0x25, 0x5d, 0x7d, 0x95, 0xda, 0x0b, 0x8f, 0x78, 0x1e, 0x19, 0x09, 0xfa, 0x67, 0xe0, 0xa0, 0x17, 0x24, 0x76, 0x6c, 0x30, 0x1f, 0x62, 0x3d, 0xbe, 0x45, 0x70, 0xcc, 0xb6, 0x1e, 0x68, 0x06, 0x25, 0x68, 0x16, 0x1a, 0x33, 0x3f, 0x90, 0xc7, 0x78, 0x2d, 0x98, 0x3c, 0x2f, 0xb9, 0x2d, 0x94, 0x0b, 0xfb, 0x49, 0x56, 0x30, 0xd7, 0xc1, 0xe6, 0x48, - /* (2^367)P */ 0x7a, 0xd1, 0xe0, 0x8e, 0x67, 0xfc, 0x0b, 0x50, 0x1f, 0x84, 0x98, 0xfa, 0xaf, 0xae, 0x2e, 0x31, 0x27, 0xcf, 0x3f, 0xf2, 0x6e, 0x8d, 0x81, 0x8f, 0xd2, 0x5f, 0xde, 0xd3, 0x5e, 0xe9, 0xe7, 0x13, 0x48, 0x83, 0x5a, 0x4e, 0x84, 0xd1, 0x58, 0xcf, 0x6b, 0x84, 0xdf, 0x13, 0x1d, 0x91, 0x85, 0xe8, 0xcb, 0x29, 0x79, 0xd2, 0xca, 0xac, 0x6a, 0x93, - /* (2^368)P */ 0x53, 0x82, 0xce, 0x61, 0x96, 0x88, 0x6f, 0xe1, 0x4a, 0x4c, 0x1e, 0x30, 0x73, 0xe8, 0x74, 0xde, 0x40, 0x2b, 0xe0, 0xc4, 0xb5, 0xd8, 0x7c, 0x15, 0xe7, 0xe1, 0xb1, 0xe0, 0xd6, 0x88, 0xb1, 0x6a, 0x57, 0x19, 0x6a, 0x22, 0x66, 0x57, 0xf6, 0x8d, 0xfd, 0xc0, 0xf2, 0xa3, 0x03, 0x56, 0xfb, 0x2e, 0x75, 0x5e, 0xc7, 0x8e, 0x22, 0x96, 0x5c, 0x06, - /* (2^369)P */ 0x98, 0x7e, 0xbf, 0x3e, 0xbf, 0x24, 0x9d, 0x15, 0xd3, 0xf6, 0xd3, 0xd2, 0xf0, 0x11, 0xf2, 0xdb, 0x36, 0x23, 0x38, 0xf7, 0x1d, 0x71, 0x20, 0xd2, 0x54, 0x7f, 0x1e, 0x24, 0x8f, 0xe2, 0xaa, 0xf7, 0x3f, 0x6b, 0x41, 0x4e, 0xdc, 0x0e, 0xec, 0xe8, 0x35, 0x0a, 0x08, 0x6d, 0x89, 0x5b, 0x32, 0x91, 0x01, 0xb6, 0xe0, 0x2c, 0xc6, 0xa1, 0xbe, 0xb4, - /* (2^370)P */ 0x29, 0xf2, 0x1e, 0x1c, 0xdc, 0x68, 0x8a, 0x43, 0x87, 0x2c, 0x48, 0xb3, 0x9e, 0xed, 0xd2, 0x82, 0x46, 0xac, 0x2f, 0xef, 0x93, 0x34, 0x37, 0xca, 0x64, 0x8d, 0xc9, 0x06, 0x90, 0xbb, 0x78, 0x0a, 0x3c, 0x4c, 0xcf, 0x35, 0x7a, 0x0f, 0xf7, 0xa7, 0xf4, 0x2f, 0x45, 0x69, 0x3f, 0xa9, 0x5d, 0xce, 0x7b, 0x8a, 0x84, 0xc3, 0xae, 0xf4, 0xda, 0xd5, - /* (2^371)P */ 0xca, 0xba, 0x95, 0x43, 0x05, 0x7b, 0x06, 0xd9, 0x5c, 0x0a, 0x18, 0x5f, 0x6a, 0x6a, 0xce, 0xc0, 0x3d, 0x95, 0x51, 0x0e, 0x1a, 0xbe, 0x85, 0x7a, 0xf2, 0x69, 0xec, 0xc0, 0x8c, 0xca, 0xa3, 0x32, 0x0a, 0x76, 0x50, 0xc6, 0x76, 0x61, 0x00, 0x89, 0xbf, 0x6e, 0x0f, 0x48, 0x90, 0x31, 0x93, 0xec, 0x34, 0x70, 0xf0, 0xc3, 0x8d, 0xf0, 0x0f, 0xb5, - /* (2^372)P */ 0xbe, 0x23, 0xe2, 0x18, 0x99, 0xf1, 0xed, 0x8a, 0xf6, 0xc9, 0xac, 0xb8, 0x1e, 0x9a, 0x3c, 0x15, 0xae, 0xd7, 0x6d, 0xb3, 0x04, 0xee, 0x5b, 0x0d, 0x1e, 0x79, 0xb7, 0xf9, 0xf9, 0x8d, 0xad, 0xf9, 0x8f, 0x5a, 0x6a, 0x7b, 0xd7, 0x9b, 0xca, 0x62, 0xfe, 0x9c, 0xc0, 0x6f, 0x6d, 0x9d, 0x76, 0xa3, 0x69, 0xb9, 0x4c, 0xa1, 0xc4, 0x0c, 0x76, 0xaa, - /* (2^373)P */ 0x1c, 0x06, 0xfe, 0x3f, 0x45, 0x70, 0xcd, 0x97, 0xa9, 0xa2, 0xb1, 0xd3, 0xf2, 0xa5, 0x0c, 0x49, 0x2c, 0x75, 0x73, 0x1f, 0xcf, 0x00, 0xaf, 0xd5, 0x2e, 0xde, 0x0d, 0x8f, 0x8f, 0x7c, 0xc4, 0x58, 0xce, 0xd4, 0xf6, 0x24, 0x19, 0x2e, 0xd8, 0xc5, 0x1d, 0x1a, 0x3f, 0xb8, 0x4f, 0xbc, 0x7d, 0xbd, 0x68, 0xe3, 0x81, 0x98, 0x1b, 0xa8, 0xc9, 0xd9, - /* (2^374)P */ 0x39, 0x95, 0x78, 0x24, 0x6c, 0x38, 0xe4, 0xe7, 0xd0, 0x8d, 0xb9, 0x38, 0x71, 0x5e, 0xc1, 0x62, 0x80, 0xcc, 0xcb, 0x8c, 0x97, 0xca, 0xf8, 0xb9, 0xd9, 0x9c, 0xce, 0x72, 0x7b, 0x70, 0xee, 0x5f, 0xea, 0xa2, 0xdf, 0xa9, 0x14, 0x10, 0xf9, 0x6e, 0x59, 0x9f, 0x9c, 0xe0, 0x0c, 0xb2, 0x07, 0x97, 0xcd, 0xd2, 0x89, 0x16, 0xfd, 0x9c, 0xa8, 0xa5, - /* (2^375)P */ 0x5a, 0x61, 0xf1, 0x59, 0x7c, 0x38, 0xda, 0xe2, 0x85, 0x99, 0x68, 0xe9, 0xc9, 0xf7, 0x32, 0x7e, 0xc4, 0xca, 0xb7, 0x11, 0x08, 0x69, 0x2b, 0x66, 0x02, 0xf7, 0x2e, 0x18, 0xc3, 0x8e, 0xe1, 0xf9, 0xc5, 0x19, 0x9a, 0x0a, 0x9c, 0x07, 0xba, 0xc7, 0x9c, 0x03, 0x34, 0x89, 0x99, 0x67, 0x0b, 0x16, 0x4b, 0x07, 0x36, 0x16, 0x36, 0x2c, 0xe2, 0xa1, - /* (2^376)P */ 0x70, 0x10, 0x91, 0x27, 0xa8, 0x24, 0x8e, 0x29, 0x04, 0x6f, 0x79, 0x1f, 0xd3, 0xa5, 0x68, 0xd3, 0x0b, 0x7d, 0x56, 0x4d, 0x14, 0x57, 0x7b, 0x2e, 0x00, 0x9f, 0x9a, 0xfd, 0x6c, 0x63, 0x18, 0x81, 0xdb, 0x9d, 0xb7, 0xd7, 0xa4, 0x1e, 0xe8, 0x40, 0xf1, 0x4c, 0xa3, 0x01, 0xd5, 0x4b, 0x75, 0xea, 0xdd, 0x97, 0xfd, 0x5b, 0xb2, 0x66, 0x6a, 0x24, - /* (2^377)P */ 0x72, 0x11, 0xfe, 0x73, 0x1b, 0xd3, 0xea, 0x7f, 0x93, 0x15, 0x15, 0x05, 0xfe, 0x40, 0xe8, 0x28, 0xd8, 0x50, 0x47, 0x66, 0xfa, 0xb7, 0xb5, 0x04, 0xba, 0x35, 0x1e, 0x32, 0x9f, 0x5f, 0x32, 0xba, 0x3d, 0xd1, 0xed, 0x9a, 0x76, 0xca, 0xa3, 0x3e, 0x77, 0xd8, 0xd8, 0x7c, 0x5f, 0x68, 0x42, 0xb5, 0x86, 0x7f, 0x3b, 0xc9, 0xc1, 0x89, 0x64, 0xda, - /* (2^378)P */ 0xd5, 0xd4, 0x17, 0x31, 0xfc, 0x6a, 0xfd, 0xb8, 0xe8, 0xe5, 0x3e, 0x39, 0x06, 0xe4, 0xd1, 0x90, 0x2a, 0xca, 0xf6, 0x54, 0x6c, 0x1b, 0x2f, 0x49, 0x97, 0xb1, 0x2a, 0x82, 0x43, 0x3d, 0x1f, 0x8b, 0xe2, 0x47, 0xc5, 0x24, 0xa8, 0xd5, 0x53, 0x29, 0x7d, 0xc6, 0x87, 0xa6, 0x25, 0x3a, 0x64, 0xdd, 0x71, 0x08, 0x9e, 0xcd, 0xe9, 0x45, 0xc7, 0xba, - /* (2^379)P */ 0x37, 0x72, 0x6d, 0x13, 0x7a, 0x8d, 0x04, 0x31, 0xe6, 0xe3, 0x9e, 0x36, 0x71, 0x3e, 0xc0, 0x1e, 0xe3, 0x71, 0xd3, 0x49, 0x4e, 0x4a, 0x36, 0x42, 0x68, 0x68, 0x61, 0xc7, 0x3c, 0xdb, 0x81, 0x49, 0xf7, 0x91, 0x4d, 0xea, 0x4c, 0x4f, 0x98, 0xc6, 0x7e, 0x60, 0x84, 0x4b, 0x6a, 0x37, 0xbb, 0x52, 0xf7, 0xce, 0x02, 0xe4, 0xad, 0xd1, 0x3c, 0xa7, - /* (2^380)P */ 0x51, 0x06, 0x2d, 0xf8, 0x08, 0xe8, 0xf1, 0x0c, 0xe5, 0xa9, 0xac, 0x29, 0x73, 0x3b, 0xed, 0x98, 0x5f, 0x55, 0x08, 0x38, 0x51, 0x44, 0x36, 0x5d, 0xea, 0xc3, 0xb8, 0x0e, 0xa0, 0x4f, 0xd2, 0x79, 0xe9, 0x98, 0xc3, 0xf5, 0x00, 0xb9, 0x26, 0x27, 0x42, 0xa8, 0x07, 0xc1, 0x12, 0x31, 0xc1, 0xc3, 0x3c, 0x3b, 0x7a, 0x72, 0x97, 0xc2, 0x70, 0x3a, - /* (2^381)P */ 0xf4, 0xb2, 0xba, 0x32, 0xbc, 0xa9, 0x2f, 0x87, 0xc7, 0x3c, 0x45, 0xcd, 0xae, 0xe2, 0x13, 0x6d, 0x3a, 0xf2, 0xf5, 0x66, 0x97, 0x29, 0xaf, 0x53, 0x9f, 0xda, 0xea, 0x14, 0xdf, 0x04, 0x98, 0x19, 0x95, 0x9e, 0x2a, 0x00, 0x5c, 0x9d, 0x1d, 0xf0, 0x39, 0x23, 0xff, 0xfc, 0xca, 0x36, 0xb7, 0xde, 0xdf, 0x37, 0x78, 0x52, 0x21, 0xfa, 0x19, 0x10, - /* (2^382)P */ 0x50, 0x20, 0x73, 0x74, 0x62, 0x21, 0xf2, 0xf7, 0x9b, 0x66, 0x85, 0x34, 0x74, 0xd4, 0x9d, 0x60, 0xd7, 0xbc, 0xc8, 0x46, 0x3b, 0xb8, 0x80, 0x42, 0x15, 0x0a, 0x6c, 0x35, 0x1a, 0x69, 0xf0, 0x1d, 0x4b, 0x29, 0x54, 0x5a, 0x9a, 0x48, 0xec, 0x9f, 0x37, 0x74, 0x91, 0xd0, 0xd1, 0x9e, 0x00, 0xc2, 0x76, 0x56, 0xd6, 0xa0, 0x15, 0x14, 0x83, 0x59, - /* (2^383)P */ 0xc2, 0xf8, 0x22, 0x20, 0x23, 0x07, 0xbd, 0x1d, 0x6f, 0x1e, 0x8c, 0x56, 0x06, 0x6a, 0x4b, 0x9f, 0xe2, 0xa9, 0x92, 0x46, 0x4b, 0x46, 0x59, 0xd7, 0xe1, 0xda, 0x14, 0x98, 0x07, 0x65, 0x7e, 0x28, 0x20, 0xf2, 0x9d, 0x4f, 0x36, 0x5c, 0x92, 0xe0, 0x9d, 0xfe, 0x3e, 0xda, 0xe4, 0x47, 0x19, 0x3c, 0x00, 0x7f, 0x22, 0xf2, 0x9e, 0x51, 0xae, 0x4d, - /* (2^384)P */ 0xbe, 0x8c, 0x1b, 0x10, 0xb6, 0xad, 0xcc, 0xcc, 0xd8, 0x5e, 0x21, 0xa6, 0xfb, 0xf1, 0xf6, 0xbd, 0x0a, 0x24, 0x67, 0xb4, 0x57, 0x7a, 0xbc, 0xe8, 0xe9, 0xff, 0xee, 0x0a, 0x1f, 0xee, 0xbd, 0xc8, 0x44, 0xed, 0x2b, 0xbb, 0x55, 0x1f, 0xdd, 0x7c, 0xb3, 0xeb, 0x3f, 0x63, 0xa1, 0x28, 0x91, 0x21, 0xab, 0x71, 0xc6, 0x4c, 0xd0, 0xe9, 0xb0, 0x21, - /* (2^385)P */ 0xad, 0xc9, 0x77, 0x2b, 0xee, 0x89, 0xa4, 0x7b, 0xfd, 0xf9, 0xf6, 0x14, 0xe4, 0xed, 0x1a, 0x16, 0x9b, 0x78, 0x41, 0x43, 0xa8, 0x83, 0x72, 0x06, 0x2e, 0x7c, 0xdf, 0xeb, 0x7e, 0xdd, 0xd7, 0x8b, 0xea, 0x9a, 0x2b, 0x03, 0xba, 0x57, 0xf3, 0xf1, 0xd9, 0xe5, 0x09, 0xc5, 0x98, 0x61, 0x1c, 0x51, 0x6d, 0x5d, 0x6e, 0xfb, 0x5e, 0x95, 0x9f, 0xb5, - /* (2^386)P */ 0x23, 0xe2, 0x1e, 0x95, 0xa3, 0x5e, 0x42, 0x10, 0xc7, 0xc3, 0x70, 0xbf, 0x4b, 0x6b, 0x83, 0x36, 0x93, 0xb7, 0x68, 0x47, 0x88, 0x3a, 0x10, 0x88, 0x48, 0x7f, 0x8c, 0xae, 0x54, 0x10, 0x02, 0xa4, 0x52, 0x8f, 0x8d, 0xf7, 0x26, 0x4f, 0x50, 0xc3, 0x6a, 0xe2, 0x4e, 0x3b, 0x4c, 0xb9, 0x8a, 0x14, 0x15, 0x6d, 0x21, 0x29, 0xb3, 0x6e, 0x4e, 0xd0, - /* (2^387)P */ 0x4c, 0x8a, 0x18, 0x3f, 0xb7, 0x20, 0xfd, 0x3e, 0x54, 0xca, 0x68, 0x3c, 0xea, 0x6f, 0xf4, 0x6b, 0xa2, 0xbd, 0x01, 0xbd, 0xfe, 0x08, 0xa8, 0xd8, 0xc2, 0x20, 0x36, 0x05, 0xcd, 0xe9, 0xf3, 0x9e, 0xfa, 0x85, 0x66, 0x8f, 0x4b, 0x1d, 0x8c, 0x64, 0x4f, 0xb8, 0xc6, 0x0f, 0x5b, 0x57, 0xd8, 0x24, 0x19, 0x5a, 0x14, 0x4b, 0x92, 0xd3, 0x96, 0xbc, - /* (2^388)P */ 0xa9, 0x3f, 0xc9, 0x6c, 0xca, 0x64, 0x1e, 0x6f, 0xdf, 0x65, 0x7f, 0x9a, 0x47, 0x6b, 0x8a, 0x60, 0x31, 0xa6, 0x06, 0xac, 0x69, 0x30, 0xe6, 0xea, 0x63, 0x42, 0x26, 0x5f, 0xdb, 0xd0, 0xf2, 0x8e, 0x34, 0x0a, 0x3a, 0xeb, 0xf3, 0x79, 0xc8, 0xb7, 0x60, 0x56, 0x5c, 0x37, 0x95, 0x71, 0xf8, 0x7f, 0x49, 0x3e, 0x9e, 0x01, 0x26, 0x1e, 0x80, 0x9f, - /* (2^389)P */ 0xf8, 0x16, 0x9a, 0xaa, 0xb0, 0x28, 0xb5, 0x8e, 0xd0, 0x60, 0xe5, 0x26, 0xa9, 0x47, 0xc4, 0x5c, 0xa9, 0x39, 0xfe, 0x0a, 0xd8, 0x07, 0x2b, 0xb3, 0xce, 0xf1, 0xea, 0x1a, 0xf4, 0x7b, 0x98, 0x31, 0x3d, 0x13, 0x29, 0x80, 0xe8, 0x0d, 0xcf, 0x56, 0x39, 0x86, 0x50, 0x0c, 0xb3, 0x18, 0xf4, 0xc5, 0xca, 0xf2, 0x6f, 0xcd, 0x8d, 0xd5, 0x02, 0xb0, - /* (2^390)P */ 0xbf, 0x39, 0x3f, 0xac, 0x6d, 0x1a, 0x6a, 0xe4, 0x42, 0x24, 0xd6, 0x41, 0x9d, 0xb9, 0x5b, 0x46, 0x73, 0x93, 0x76, 0xaa, 0xb7, 0x37, 0x36, 0xa6, 0x09, 0xe5, 0x04, 0x3b, 0x66, 0xc4, 0x29, 0x3e, 0x41, 0xc2, 0xcb, 0xe5, 0x17, 0xd7, 0x34, 0x67, 0x1d, 0x2c, 0x12, 0xec, 0x24, 0x7a, 0x40, 0xa2, 0x45, 0x41, 0xf0, 0x75, 0xed, 0x43, 0x30, 0xc9, - /* (2^391)P */ 0x80, 0xf6, 0x47, 0x5b, 0xad, 0x54, 0x02, 0xbc, 0xdd, 0xa4, 0xb2, 0xd7, 0x42, 0x95, 0xf2, 0x0d, 0x1b, 0xef, 0x37, 0xa7, 0xb4, 0x34, 0x04, 0x08, 0x71, 0x1b, 0xd3, 0xdf, 0xa1, 0xf0, 0x2b, 0xfa, 0xc0, 0x1f, 0xf3, 0x44, 0xb5, 0xc6, 0x47, 0x3d, 0x65, 0x67, 0x45, 0x4d, 0x2f, 0xde, 0x52, 0x73, 0xfc, 0x30, 0x01, 0x6b, 0xc1, 0x03, 0xd8, 0xd7, - /* (2^392)P */ 0x1c, 0x67, 0x55, 0x3e, 0x01, 0x17, 0x0f, 0x3e, 0xe5, 0x34, 0x58, 0xfc, 0xcb, 0x71, 0x24, 0x74, 0x5d, 0x36, 0x1e, 0x89, 0x2a, 0x63, 0xf8, 0xf8, 0x9f, 0x50, 0x9f, 0x32, 0x92, 0x29, 0xd8, 0x1a, 0xec, 0x76, 0x57, 0x6c, 0x67, 0x12, 0x6a, 0x6e, 0xef, 0x97, 0x1f, 0xc3, 0x77, 0x60, 0x3c, 0x22, 0xcb, 0xc7, 0x04, 0x1a, 0x89, 0x2d, 0x10, 0xa6, - /* (2^393)P */ 0x12, 0xf5, 0xa9, 0x26, 0x16, 0xd9, 0x3c, 0x65, 0x5d, 0x83, 0xab, 0xd1, 0x70, 0x6b, 0x1c, 0xdb, 0xe7, 0x86, 0x0d, 0xfb, 0xe7, 0xf8, 0x2a, 0x58, 0x6e, 0x7a, 0x66, 0x13, 0x53, 0x3a, 0x6f, 0x8d, 0x43, 0x5f, 0x14, 0x23, 0x14, 0xff, 0x3d, 0x52, 0x7f, 0xee, 0xbd, 0x7a, 0x34, 0x8b, 0x35, 0x24, 0xc3, 0x7a, 0xdb, 0xcf, 0x22, 0x74, 0x9a, 0x8f, - /* (2^394)P */ 0xdb, 0x20, 0xfc, 0xe5, 0x39, 0x4e, 0x7d, 0x78, 0xee, 0x0b, 0xbf, 0x1d, 0x80, 0xd4, 0x05, 0x4f, 0xb9, 0xd7, 0x4e, 0x94, 0x88, 0x9a, 0x50, 0x78, 0x1a, 0x70, 0x8c, 0xcc, 0x25, 0xb6, 0x61, 0x09, 0xdc, 0x7b, 0xea, 0x3f, 0x7f, 0xea, 0x2a, 0x0d, 0x47, 0x1c, 0x8e, 0xa6, 0x5b, 0xd2, 0xa3, 0x61, 0x93, 0x3c, 0x68, 0x9f, 0x8b, 0xea, 0xb0, 0xcb, - /* (2^395)P */ 0xff, 0x54, 0x02, 0x19, 0xae, 0x8b, 0x4c, 0x2c, 0x3a, 0xe0, 0xe4, 0xac, 0x87, 0xf7, 0x51, 0x45, 0x41, 0x43, 0xdc, 0xaa, 0xcd, 0xcb, 0xdc, 0x40, 0xe3, 0x44, 0x3b, 0x1d, 0x9e, 0x3d, 0xb9, 0x82, 0xcc, 0x7a, 0xc5, 0x12, 0xf8, 0x1e, 0xdd, 0xdb, 0x8d, 0xb0, 0x2a, 0xe8, 0xe6, 0x6c, 0x94, 0x3b, 0xb7, 0x2d, 0xba, 0x79, 0x3b, 0xb5, 0x86, 0xfb, - /* (2^396)P */ 0x82, 0x88, 0x13, 0xdd, 0x6c, 0xcd, 0x85, 0x2b, 0x90, 0x86, 0xb7, 0xac, 0x16, 0xa6, 0x6e, 0x6a, 0x94, 0xd8, 0x1e, 0x4e, 0x41, 0x0f, 0xce, 0x81, 0x6a, 0xa8, 0x26, 0x56, 0x43, 0x52, 0x52, 0xe6, 0xff, 0x88, 0xcf, 0x47, 0x05, 0x1d, 0xff, 0xf3, 0xa0, 0x10, 0xb2, 0x97, 0x87, 0xeb, 0x47, 0xbb, 0xfa, 0x1f, 0xe8, 0x4c, 0xce, 0xc4, 0xcd, 0x93, - /* (2^397)P */ 0xf4, 0x11, 0xf5, 0x8d, 0x89, 0x29, 0x79, 0xb3, 0x59, 0x0b, 0x29, 0x7d, 0x9c, 0x12, 0x4a, 0x65, 0x72, 0x3a, 0xf9, 0xec, 0x37, 0x18, 0x86, 0xef, 0x44, 0x07, 0x25, 0x74, 0x76, 0x53, 0xed, 0x51, 0x01, 0xc6, 0x28, 0xc5, 0xc3, 0x4a, 0x0f, 0x99, 0xec, 0xc8, 0x40, 0x5a, 0x83, 0x30, 0x79, 0xa2, 0x3e, 0x63, 0x09, 0x2d, 0x6f, 0x23, 0x54, 0x1c, - /* (2^398)P */ 0x5c, 0x6f, 0x3b, 0x1c, 0x30, 0x77, 0x7e, 0x87, 0x66, 0x83, 0x2e, 0x7e, 0x85, 0x50, 0xfd, 0xa0, 0x7a, 0xc2, 0xf5, 0x0f, 0xc1, 0x64, 0xe7, 0x0b, 0xbd, 0x59, 0xa7, 0xe7, 0x65, 0x53, 0xc3, 0xf5, 0x55, 0x5b, 0xe1, 0x82, 0x30, 0x5a, 0x61, 0xcd, 0xa0, 0x89, 0x32, 0xdb, 0x87, 0xfc, 0x21, 0x8a, 0xab, 0x6d, 0x82, 0xa8, 0x42, 0x81, 0x4f, 0xf2, - /* (2^399)P */ 0xb3, 0xeb, 0x88, 0x18, 0xf6, 0x56, 0x96, 0xbf, 0xba, 0x5d, 0x71, 0xa1, 0x5a, 0xd1, 0x04, 0x7b, 0xd5, 0x46, 0x01, 0x74, 0xfe, 0x15, 0x25, 0xb7, 0xff, 0x0c, 0x24, 0x47, 0xac, 0xfd, 0xab, 0x47, 0x32, 0xe1, 0x6a, 0x4e, 0xca, 0xcf, 0x7f, 0xdd, 0xf8, 0xd2, 0x4b, 0x3b, 0xf5, 0x17, 0xba, 0xba, 0x8b, 0xa1, 0xec, 0x28, 0x3f, 0x97, 0xab, 0x2a, - /* (2^400)P */ 0x51, 0x38, 0xc9, 0x5e, 0xc6, 0xb3, 0x64, 0xf2, 0x24, 0x4d, 0x04, 0x7d, 0xc8, 0x39, 0x0c, 0x4a, 0xc9, 0x73, 0x74, 0x1b, 0x5c, 0xb2, 0xc5, 0x41, 0x62, 0xa0, 0x4c, 0x6d, 0x8d, 0x91, 0x9a, 0x7b, 0x88, 0xab, 0x9c, 0x7e, 0x23, 0xdb, 0x6f, 0xb5, 0x72, 0xd6, 0x47, 0x40, 0xef, 0x22, 0x58, 0x62, 0x19, 0x6c, 0x38, 0xba, 0x5b, 0x00, 0x30, 0x9f, - /* (2^401)P */ 0x65, 0xbb, 0x3b, 0x9b, 0xe9, 0xae, 0xbf, 0xbe, 0xe4, 0x13, 0x95, 0xf3, 0xe3, 0x77, 0xcb, 0xe4, 0x9a, 0x22, 0xb5, 0x4a, 0x08, 0x9d, 0xb3, 0x9e, 0x27, 0xe0, 0x15, 0x6c, 0x9f, 0x7e, 0x9a, 0x5e, 0x15, 0x45, 0x25, 0x8d, 0x01, 0x0a, 0xd2, 0x2b, 0xbd, 0x48, 0x06, 0x0d, 0x18, 0x97, 0x4b, 0xdc, 0xbc, 0xf0, 0xcd, 0xb2, 0x52, 0x3c, 0xac, 0xf5, - /* (2^402)P */ 0x3e, 0xed, 0x47, 0x6b, 0x5c, 0xf6, 0x76, 0xd0, 0xe9, 0x15, 0xa3, 0xcb, 0x36, 0x00, 0x21, 0xa3, 0x79, 0x20, 0xa5, 0x3e, 0x88, 0x03, 0xcb, 0x7e, 0x63, 0xbb, 0xed, 0xa9, 0x13, 0x35, 0x16, 0xaf, 0x2e, 0xb4, 0x70, 0x14, 0x93, 0xfb, 0xc4, 0x9b, 0xd8, 0xb1, 0xbe, 0x43, 0xd1, 0x85, 0xb8, 0x97, 0xef, 0xea, 0x88, 0xa1, 0x25, 0x52, 0x62, 0x75, - /* (2^403)P */ 0x8e, 0x4f, 0xaa, 0x23, 0x62, 0x7e, 0x2b, 0x37, 0x89, 0x00, 0x11, 0x30, 0xc5, 0x33, 0x4a, 0x89, 0x8a, 0xe2, 0xfc, 0x5c, 0x6a, 0x75, 0xe5, 0xf7, 0x02, 0x4a, 0x9b, 0xf7, 0xb5, 0x6a, 0x85, 0x31, 0xd3, 0x5a, 0xcf, 0xc3, 0xf8, 0xde, 0x2f, 0xcf, 0xb5, 0x24, 0xf4, 0xe3, 0xa1, 0xad, 0x42, 0xae, 0x09, 0xb9, 0x2e, 0x04, 0x2d, 0x01, 0x22, 0x3f, - /* (2^404)P */ 0x41, 0x16, 0xfb, 0x7d, 0x50, 0xfd, 0xb5, 0xba, 0x88, 0x24, 0xba, 0xfd, 0x3d, 0xb2, 0x90, 0x15, 0xb7, 0xfa, 0xa2, 0xe1, 0x4c, 0x7d, 0xb9, 0xc6, 0xff, 0x81, 0x57, 0xb6, 0xc2, 0x9e, 0xcb, 0xc4, 0x35, 0xbd, 0x01, 0xb7, 0xaa, 0xce, 0xd0, 0xe9, 0xb5, 0xd6, 0x72, 0xbf, 0xd2, 0xee, 0xc7, 0xac, 0x94, 0xff, 0x29, 0x57, 0x02, 0x49, 0x09, 0xad, - /* (2^405)P */ 0x27, 0xa5, 0x78, 0x1b, 0xbf, 0x6b, 0xaf, 0x0b, 0x8c, 0xd9, 0xa8, 0x37, 0xb0, 0x67, 0x18, 0xb6, 0xc7, 0x05, 0x8a, 0x67, 0x03, 0x30, 0x62, 0x6e, 0x56, 0x82, 0xa9, 0x54, 0x3e, 0x0c, 0x4e, 0x07, 0xe1, 0x5a, 0x38, 0xed, 0xfa, 0xc8, 0x55, 0x6b, 0x08, 0xa3, 0x6b, 0x64, 0x2a, 0x15, 0xd6, 0x39, 0x6f, 0x47, 0x99, 0x42, 0x3f, 0x33, 0x84, 0x8f, - /* (2^406)P */ 0xbc, 0x45, 0x29, 0x81, 0x0e, 0xa4, 0xc5, 0x72, 0x3a, 0x10, 0xe1, 0xc4, 0x1e, 0xda, 0xc3, 0xfe, 0xb0, 0xce, 0xd2, 0x13, 0x34, 0x67, 0x21, 0xc6, 0x7e, 0xf9, 0x8c, 0xff, 0x39, 0x50, 0xae, 0x92, 0x60, 0x35, 0x2f, 0x8b, 0x6e, 0xc9, 0xc1, 0x27, 0x3a, 0x94, 0x66, 0x3e, 0x26, 0x84, 0x93, 0xc8, 0x6c, 0xcf, 0xd2, 0x03, 0xa1, 0x10, 0xcf, 0xb7, - /* (2^407)P */ 0x64, 0xda, 0x19, 0xf6, 0xc5, 0x73, 0x17, 0x44, 0x88, 0x81, 0x07, 0x0d, 0x34, 0xb2, 0x75, 0xf9, 0xd9, 0xe2, 0xe0, 0x8b, 0x71, 0xcf, 0x72, 0x34, 0x83, 0xb4, 0xce, 0xfc, 0xd7, 0x29, 0x09, 0x5a, 0x98, 0xbf, 0x14, 0xac, 0x77, 0x55, 0x38, 0x47, 0x5b, 0x0f, 0x40, 0x24, 0xe5, 0xa5, 0xa6, 0xac, 0x2d, 0xa6, 0xff, 0x9c, 0x73, 0xfe, 0x5c, 0x7e, - /* (2^408)P */ 0x1e, 0x33, 0xcc, 0x68, 0xb2, 0xbc, 0x8c, 0x93, 0xaf, 0xcc, 0x38, 0xf8, 0xd9, 0x16, 0x72, 0x50, 0xac, 0xd9, 0xb5, 0x0b, 0x9a, 0xbe, 0x46, 0x7a, 0xf1, 0xee, 0xf1, 0xad, 0xec, 0x5b, 0x59, 0x27, 0x9c, 0x05, 0xa3, 0x87, 0xe0, 0x37, 0x2c, 0x83, 0xce, 0xb3, 0x65, 0x09, 0x8e, 0xc3, 0x9c, 0xbf, 0x6a, 0xa2, 0x00, 0xcc, 0x12, 0x36, 0xc5, 0x95, - /* (2^409)P */ 0x36, 0x11, 0x02, 0x14, 0x9c, 0x3c, 0xeb, 0x2f, 0x23, 0x5b, 0x6b, 0x2b, 0x08, 0x54, 0x53, 0xac, 0xb2, 0xa3, 0xe0, 0x26, 0x62, 0x3c, 0xe4, 0xe1, 0x81, 0xee, 0x13, 0x3e, 0xa4, 0x97, 0xef, 0xf9, 0x92, 0x27, 0x01, 0xce, 0x54, 0x8b, 0x3e, 0x31, 0xbe, 0xa7, 0x88, 0xcf, 0x47, 0x99, 0x3c, 0x10, 0x6f, 0x60, 0xb3, 0x06, 0x4e, 0xee, 0x1b, 0xf0, - /* (2^410)P */ 0x59, 0x49, 0x66, 0xcf, 0x22, 0xe6, 0xf6, 0x73, 0xfe, 0xa3, 0x1c, 0x09, 0xfa, 0x5f, 0x65, 0xa8, 0xf0, 0x82, 0xc2, 0xef, 0x16, 0x63, 0x6e, 0x79, 0x69, 0x51, 0x39, 0x07, 0x65, 0xc4, 0x81, 0xec, 0x73, 0x0f, 0x15, 0x93, 0xe1, 0x30, 0x33, 0xe9, 0x37, 0x86, 0x42, 0x4c, 0x1f, 0x9b, 0xad, 0xee, 0x3f, 0xf1, 0x2a, 0x8e, 0x6a, 0xa3, 0xc8, 0x35, - /* (2^411)P */ 0x1e, 0x49, 0xf1, 0xdd, 0xd2, 0x9c, 0x8e, 0x78, 0xb2, 0x06, 0xe4, 0x6a, 0xab, 0x3a, 0xdc, 0xcd, 0xf4, 0xeb, 0xe1, 0xe7, 0x2f, 0xaa, 0xeb, 0x40, 0x31, 0x9f, 0xb9, 0xab, 0x13, 0xa9, 0x78, 0xbf, 0x38, 0x89, 0x0e, 0x85, 0x14, 0x8b, 0x46, 0x76, 0x14, 0xda, 0xcf, 0x33, 0xc8, 0x79, 0xd3, 0xd5, 0xa3, 0x6a, 0x69, 0x45, 0x70, 0x34, 0xc3, 0xe9, - /* (2^412)P */ 0x5e, 0xe7, 0x78, 0xe9, 0x24, 0xcc, 0xe9, 0xf4, 0xc8, 0x6b, 0xe0, 0xfb, 0x3a, 0xbe, 0xcc, 0x42, 0x4a, 0x00, 0x22, 0xf8, 0xe6, 0x32, 0xbe, 0x6d, 0x18, 0x55, 0x60, 0xe9, 0x72, 0x69, 0x50, 0x56, 0xca, 0x04, 0x18, 0x38, 0xa1, 0xee, 0xd8, 0x38, 0x3c, 0xa7, 0x70, 0xe2, 0xb9, 0x4c, 0xa0, 0xc8, 0x89, 0x72, 0xcf, 0x49, 0x7f, 0xdf, 0xbc, 0x67, - /* (2^413)P */ 0x1d, 0x17, 0xcb, 0x0b, 0xbd, 0xb2, 0x36, 0xe3, 0xa8, 0x99, 0x31, 0xb6, 0x26, 0x9c, 0x0c, 0x74, 0xaf, 0x4d, 0x24, 0x61, 0xcf, 0x31, 0x7b, 0xed, 0xdd, 0xc3, 0xf6, 0x32, 0x70, 0xfe, 0x17, 0xf6, 0x51, 0x37, 0x65, 0xce, 0x5d, 0xaf, 0xa5, 0x2f, 0x2a, 0xfe, 0x00, 0x71, 0x7c, 0x50, 0xbe, 0x21, 0xc7, 0xed, 0xc6, 0xfc, 0x67, 0xcf, 0x9c, 0xdd, - /* (2^414)P */ 0x26, 0x3e, 0xf8, 0xbb, 0xd0, 0xb1, 0x01, 0xd8, 0xeb, 0x0b, 0x62, 0x87, 0x35, 0x4c, 0xde, 0xca, 0x99, 0x9c, 0x6d, 0xf7, 0xb6, 0xf0, 0x57, 0x0a, 0x52, 0x29, 0x6a, 0x3f, 0x26, 0x31, 0x04, 0x07, 0x2a, 0xc9, 0xfa, 0x9b, 0x0e, 0x62, 0x8e, 0x72, 0xf2, 0xad, 0xce, 0xb6, 0x35, 0x7a, 0xc1, 0xae, 0x35, 0xc7, 0xa3, 0x14, 0xcf, 0x0c, 0x28, 0xb7, - /* (2^415)P */ 0xa6, 0xf1, 0x32, 0x3a, 0x20, 0xd2, 0x24, 0x97, 0xcf, 0x5d, 0x37, 0x99, 0xaf, 0x33, 0x7a, 0x5b, 0x7a, 0xcc, 0x4e, 0x41, 0x38, 0xb1, 0x4e, 0xad, 0xc9, 0xd9, 0x71, 0x7e, 0xb2, 0xf5, 0xd5, 0x01, 0x6c, 0x4d, 0xfd, 0xa1, 0xda, 0x03, 0x38, 0x9b, 0x3d, 0x92, 0x92, 0xf2, 0xca, 0xbf, 0x1f, 0x24, 0xa4, 0xbb, 0x30, 0x6a, 0x74, 0x56, 0xc8, 0xce, - /* (2^416)P */ 0x27, 0xf4, 0xed, 0xc9, 0xc3, 0xb1, 0x79, 0x85, 0xbe, 0xf6, 0xeb, 0xf3, 0x55, 0xc7, 0xaa, 0xa6, 0xe9, 0x07, 0x5d, 0xf4, 0xeb, 0xa6, 0x81, 0xe3, 0x0e, 0xcf, 0xa3, 0xc1, 0xef, 0xe7, 0x34, 0xb2, 0x03, 0x73, 0x8a, 0x91, 0xf1, 0xad, 0x05, 0xc7, 0x0b, 0x43, 0x99, 0x12, 0x31, 0xc8, 0xc7, 0xc5, 0xa4, 0x3d, 0xcd, 0xe5, 0x4e, 0x6d, 0x24, 0xdd, - /* (2^417)P */ 0x61, 0x54, 0xd0, 0x95, 0x2c, 0x45, 0x75, 0xac, 0xb5, 0x1a, 0x9d, 0x11, 0xeb, 0xed, 0x6b, 0x57, 0xa3, 0xe6, 0xcd, 0x77, 0xd4, 0x83, 0x8e, 0x39, 0xf1, 0x0f, 0x98, 0xcb, 0x40, 0x02, 0x6e, 0x10, 0x82, 0x9e, 0xb4, 0x93, 0x76, 0xd7, 0x97, 0xa3, 0x53, 0x12, 0x86, 0xc6, 0x15, 0x78, 0x73, 0x93, 0xe7, 0x7f, 0xcf, 0x1f, 0xbf, 0xcd, 0xd2, 0x7a, - /* (2^418)P */ 0xc2, 0x21, 0xdc, 0xd5, 0x69, 0xff, 0xca, 0x49, 0x3a, 0xe1, 0xc3, 0x69, 0x41, 0x56, 0xc1, 0x76, 0x63, 0x24, 0xbd, 0x64, 0x1b, 0x3d, 0x92, 0xf9, 0x13, 0x04, 0x25, 0xeb, 0x27, 0xa6, 0xef, 0x39, 0x3a, 0x80, 0xe0, 0xf8, 0x27, 0xee, 0xc9, 0x49, 0x77, 0xef, 0x3f, 0x29, 0x3d, 0x5e, 0xe6, 0x66, 0x83, 0xd1, 0xf6, 0xfe, 0x9d, 0xbc, 0xf1, 0x96, - /* (2^419)P */ 0x6b, 0xc6, 0x99, 0x26, 0x3c, 0xf3, 0x63, 0xf9, 0xc7, 0x29, 0x8c, 0x52, 0x62, 0x2d, 0xdc, 0x8a, 0x66, 0xce, 0x2c, 0xa7, 0xe4, 0xf0, 0xd7, 0x37, 0x17, 0x1e, 0xe4, 0xa3, 0x53, 0x7b, 0x29, 0x8e, 0x60, 0x99, 0xf9, 0x0c, 0x7c, 0x6f, 0xa2, 0xcc, 0x9f, 0x80, 0xdd, 0x5e, 0x46, 0xaa, 0x0d, 0x6c, 0xc9, 0x6c, 0xf7, 0x78, 0x5b, 0x38, 0xe3, 0x24, - /* (2^420)P */ 0x4b, 0x75, 0x6a, 0x2f, 0x08, 0xe1, 0x72, 0x76, 0xab, 0x82, 0x96, 0xdf, 0x3b, 0x1f, 0x9b, 0xd8, 0xed, 0xdb, 0xcd, 0x15, 0x09, 0x5a, 0x1e, 0xb7, 0xc5, 0x26, 0x72, 0x07, 0x0c, 0x50, 0xcd, 0x3b, 0x4d, 0x3f, 0xa2, 0x67, 0xc2, 0x02, 0x61, 0x2e, 0x68, 0xe9, 0x6f, 0xf0, 0x21, 0x2a, 0xa7, 0x3b, 0x88, 0x04, 0x11, 0x64, 0x49, 0x0d, 0xb4, 0x46, - /* (2^421)P */ 0x63, 0x85, 0xf3, 0xc5, 0x2b, 0x5a, 0x9f, 0xf0, 0x17, 0xcb, 0x45, 0x0a, 0xf3, 0x6e, 0x7e, 0xb0, 0x7c, 0xbc, 0xf0, 0x4f, 0x3a, 0xb0, 0xbc, 0x36, 0x36, 0x52, 0x51, 0xcb, 0xfe, 0x9a, 0xcb, 0xe8, 0x7e, 0x4b, 0x06, 0x7f, 0xaa, 0x35, 0xc8, 0x0e, 0x7a, 0x30, 0xa3, 0xb1, 0x09, 0xbb, 0x86, 0x4c, 0xbe, 0xb8, 0xbd, 0xe0, 0x32, 0xa5, 0xd4, 0xf7, - /* (2^422)P */ 0x7d, 0x50, 0x37, 0x68, 0x4e, 0x22, 0xb2, 0x2c, 0xd5, 0x0f, 0x2b, 0x6d, 0xb1, 0x51, 0xf2, 0x82, 0xe9, 0x98, 0x7c, 0x50, 0xc7, 0x96, 0x7e, 0x0e, 0xdc, 0xb1, 0x0e, 0xb2, 0x63, 0x8c, 0x30, 0x37, 0x72, 0x21, 0x9c, 0x61, 0xc2, 0xa7, 0x33, 0xd9, 0xb2, 0x63, 0x93, 0xd1, 0x6b, 0x6a, 0x73, 0xa5, 0x58, 0x80, 0xff, 0x04, 0xc7, 0x83, 0x21, 0x29, - /* (2^423)P */ 0x29, 0x04, 0xbc, 0x99, 0x39, 0xc9, 0x58, 0xc9, 0x6b, 0x17, 0xe8, 0x90, 0xb3, 0xe6, 0xa9, 0xb6, 0x28, 0x9b, 0xcb, 0x3b, 0x28, 0x90, 0x68, 0x71, 0xff, 0xcf, 0x08, 0x78, 0xc9, 0x8d, 0xa8, 0x4e, 0x43, 0xd1, 0x1c, 0x9e, 0xa4, 0xe3, 0xdf, 0xbf, 0x92, 0xf4, 0xf9, 0x41, 0xba, 0x4d, 0x1c, 0xf9, 0xdd, 0x74, 0x76, 0x1c, 0x6e, 0x3e, 0x94, 0x87, - /* (2^424)P */ 0xe4, 0xda, 0xc5, 0xd7, 0xfb, 0x87, 0xc5, 0x4d, 0x6b, 0x19, 0xaa, 0xb9, 0xbc, 0x8c, 0xf2, 0x8a, 0xd8, 0x5d, 0xdb, 0x4d, 0xef, 0xa6, 0xf2, 0x65, 0xf1, 0x22, 0x9c, 0xf1, 0x46, 0x30, 0x71, 0x7c, 0xe4, 0x53, 0x8e, 0x55, 0x2e, 0x9c, 0x9a, 0x31, 0x2a, 0xc3, 0xab, 0x0f, 0xde, 0xe4, 0xbe, 0xd8, 0x96, 0x50, 0x6e, 0x0c, 0x54, 0x49, 0xe6, 0xec, - /* (2^425)P */ 0x3c, 0x1d, 0x5a, 0xa5, 0xda, 0xad, 0xdd, 0xc2, 0xae, 0xac, 0x6f, 0x86, 0x75, 0x31, 0x91, 0x64, 0x45, 0x9d, 0xa4, 0xf0, 0x81, 0xf1, 0x0e, 0xba, 0x74, 0xaf, 0x7b, 0xcd, 0x6f, 0xfe, 0xac, 0x4e, 0xdb, 0x4e, 0x45, 0x35, 0x36, 0xc5, 0xc0, 0x6c, 0x3d, 0x64, 0xf4, 0xd8, 0x07, 0x62, 0xd1, 0xec, 0xf3, 0xfc, 0x93, 0xc9, 0x28, 0x0c, 0x2c, 0xf3, - /* (2^426)P */ 0x0c, 0x69, 0x2b, 0x5c, 0xb6, 0x41, 0x69, 0xf1, 0xa4, 0xf1, 0x5b, 0x75, 0x4c, 0x42, 0x8b, 0x47, 0xeb, 0x69, 0xfb, 0xa8, 0xe6, 0xf9, 0x7b, 0x48, 0x50, 0xaf, 0xd3, 0xda, 0xb2, 0x35, 0x10, 0xb5, 0x5b, 0x40, 0x90, 0x39, 0xc9, 0x07, 0x06, 0x73, 0x26, 0x20, 0x95, 0x01, 0xa4, 0x2d, 0xf0, 0xe7, 0x2e, 0x00, 0x7d, 0x41, 0x09, 0x68, 0x13, 0xc4, - /* (2^427)P */ 0xbe, 0x38, 0x78, 0xcf, 0xc9, 0x4f, 0x36, 0xca, 0x09, 0x61, 0x31, 0x3c, 0x57, 0x2e, 0xec, 0x17, 0xa4, 0x7d, 0x19, 0x2b, 0x9b, 0x5b, 0xbe, 0x8f, 0xd6, 0xc5, 0x2f, 0x86, 0xf2, 0x64, 0x76, 0x17, 0x00, 0x6e, 0x1a, 0x8c, 0x67, 0x1b, 0x68, 0xeb, 0x15, 0xa2, 0xd6, 0x09, 0x91, 0xdd, 0x23, 0x0d, 0x98, 0xb2, 0x10, 0x19, 0x55, 0x9b, 0x63, 0xf2, - /* (2^428)P */ 0x51, 0x1f, 0x93, 0xea, 0x2a, 0x3a, 0xfa, 0x41, 0xc0, 0x57, 0xfb, 0x74, 0xa6, 0x65, 0x09, 0x56, 0x14, 0xb6, 0x12, 0xaa, 0xb3, 0x1a, 0x8d, 0x3b, 0x76, 0x91, 0x7a, 0x23, 0x56, 0x9c, 0x6a, 0xc0, 0xe0, 0x3c, 0x3f, 0xb5, 0x1a, 0xf4, 0x57, 0x71, 0x93, 0x2b, 0xb1, 0xa7, 0x70, 0x57, 0x22, 0x80, 0xf5, 0xb8, 0x07, 0x77, 0x87, 0x0c, 0xbe, 0x83, - /* (2^429)P */ 0x07, 0x9b, 0x0e, 0x52, 0x38, 0x63, 0x13, 0x86, 0x6a, 0xa6, 0xb4, 0xd2, 0x60, 0x68, 0x9a, 0x99, 0x82, 0x0a, 0x04, 0x5f, 0x89, 0x7a, 0x1a, 0x2a, 0xae, 0x2d, 0x35, 0x0c, 0x1e, 0xad, 0xef, 0x4f, 0x9a, 0xfc, 0xc8, 0xd9, 0xcf, 0x9d, 0x48, 0x71, 0xa5, 0x55, 0x79, 0x73, 0x39, 0x1b, 0xd8, 0x73, 0xec, 0x9b, 0x03, 0x16, 0xd8, 0x82, 0xf7, 0x67, - /* (2^430)P */ 0x52, 0x67, 0x42, 0x21, 0xc9, 0x40, 0x78, 0x82, 0x2b, 0x95, 0x2d, 0x20, 0x92, 0xd1, 0xe2, 0x61, 0x25, 0xb0, 0xc6, 0x9c, 0x20, 0x59, 0x8e, 0x28, 0x6f, 0xf3, 0xfd, 0xd3, 0xc1, 0x32, 0x43, 0xc9, 0xa6, 0x08, 0x7a, 0x77, 0x9c, 0x4c, 0x8c, 0x33, 0x71, 0x13, 0x69, 0xe3, 0x52, 0x30, 0xa7, 0xf5, 0x07, 0x67, 0xac, 0xad, 0x46, 0x8a, 0x26, 0x25, - /* (2^431)P */ 0xda, 0x86, 0xc4, 0xa2, 0x71, 0x56, 0xdd, 0xd2, 0x48, 0xd3, 0xde, 0x42, 0x63, 0x01, 0xa7, 0x2c, 0x92, 0x83, 0x6f, 0x2e, 0xd8, 0x1e, 0x3f, 0xc1, 0xc5, 0x42, 0x4e, 0x34, 0x19, 0x54, 0x6e, 0x35, 0x2c, 0x51, 0x2e, 0xfd, 0x0f, 0x9a, 0x45, 0x66, 0x5e, 0x4a, 0x83, 0xda, 0x0a, 0x53, 0x68, 0x63, 0xfa, 0xce, 0x47, 0x20, 0xd3, 0x34, 0xba, 0x0d, - /* (2^432)P */ 0xd0, 0xe9, 0x64, 0xa4, 0x61, 0x4b, 0x86, 0xe5, 0x93, 0x6f, 0xda, 0x0e, 0x31, 0x7e, 0x6e, 0xe3, 0xc6, 0x73, 0xd8, 0xa3, 0x08, 0x57, 0x52, 0xcd, 0x51, 0x63, 0x1d, 0x9f, 0x93, 0x00, 0x62, 0x91, 0x26, 0x21, 0xa7, 0xdd, 0x25, 0x0f, 0x09, 0x0d, 0x35, 0xad, 0xcf, 0x11, 0x8e, 0x6e, 0xe8, 0xae, 0x1d, 0x95, 0xcb, 0x88, 0xf8, 0x70, 0x7b, 0x91, - /* (2^433)P */ 0x0c, 0x19, 0x5c, 0xd9, 0x8d, 0xda, 0x9d, 0x2c, 0x90, 0x54, 0x65, 0xe8, 0xb6, 0x35, 0x50, 0xae, 0xea, 0xae, 0x43, 0xb7, 0x1e, 0x99, 0x8b, 0x4c, 0x36, 0x4e, 0xe4, 0x1e, 0xc4, 0x64, 0x43, 0xb6, 0xeb, 0xd4, 0xe9, 0x60, 0x22, 0xee, 0xcf, 0xb8, 0x52, 0x1b, 0xf0, 0x04, 0xce, 0xbc, 0x2b, 0xf0, 0xbe, 0xcd, 0x44, 0x74, 0x1e, 0x1f, 0x63, 0xf9, - /* (2^434)P */ 0xe1, 0x3f, 0x95, 0x94, 0xb2, 0xb6, 0x31, 0xa9, 0x1b, 0xdb, 0xfd, 0x0e, 0xdb, 0xdd, 0x1a, 0x22, 0x78, 0x60, 0x9f, 0x75, 0x5f, 0x93, 0x06, 0x0c, 0xd8, 0xbb, 0xa2, 0x85, 0x2b, 0x5e, 0xc0, 0x9b, 0xa8, 0x5d, 0xaf, 0x93, 0x91, 0x91, 0x47, 0x41, 0x1a, 0xfc, 0xb4, 0x51, 0x85, 0xad, 0x69, 0x4d, 0x73, 0x69, 0xd5, 0x4e, 0x82, 0xfb, 0x66, 0xcb, - /* (2^435)P */ 0x7c, 0xbe, 0xc7, 0x51, 0xc4, 0x74, 0x6e, 0xab, 0xfd, 0x41, 0x4f, 0x76, 0x4f, 0x24, 0x03, 0xd6, 0x2a, 0xb7, 0x42, 0xb4, 0xda, 0x41, 0x2c, 0x82, 0x48, 0x4c, 0x7f, 0x6f, 0x25, 0x5d, 0x36, 0xd4, 0x69, 0xf5, 0xef, 0x02, 0x81, 0xea, 0x6f, 0x19, 0x69, 0xe8, 0x6f, 0x5b, 0x2f, 0x14, 0x0e, 0x6f, 0x89, 0xb4, 0xb5, 0xd8, 0xae, 0xef, 0x7b, 0x87, - /* (2^436)P */ 0xe9, 0x91, 0xa0, 0x8b, 0xc9, 0xe0, 0x01, 0x90, 0x37, 0xc1, 0x6f, 0xdc, 0x5e, 0xf7, 0xbf, 0x43, 0x00, 0xaa, 0x10, 0x76, 0x76, 0x18, 0x6e, 0x19, 0x1e, 0x94, 0x50, 0x11, 0x0a, 0xd1, 0xe2, 0xdb, 0x08, 0x21, 0xa0, 0x1f, 0xdb, 0x54, 0xfe, 0xea, 0x6e, 0xa3, 0x68, 0x56, 0x87, 0x0b, 0x22, 0x4e, 0x66, 0xf3, 0x82, 0x82, 0x00, 0xcd, 0xd4, 0x12, - /* (2^437)P */ 0x25, 0x8e, 0x24, 0x77, 0x64, 0x4c, 0xe0, 0xf8, 0x18, 0xc0, 0xdc, 0xc7, 0x1b, 0x35, 0x65, 0xde, 0x67, 0x41, 0x5e, 0x6f, 0x90, 0x82, 0xa7, 0x2e, 0x6d, 0xf1, 0x47, 0xb4, 0x92, 0x9c, 0xfd, 0x6a, 0x9a, 0x41, 0x36, 0x20, 0x24, 0x58, 0xc3, 0x59, 0x07, 0x9a, 0xfa, 0x9f, 0x03, 0xcb, 0xc7, 0x69, 0x37, 0x60, 0xe1, 0xab, 0x13, 0x72, 0xee, 0xa2, - /* (2^438)P */ 0x74, 0x78, 0xfb, 0x13, 0xcb, 0x8e, 0x37, 0x1a, 0xf6, 0x1d, 0x17, 0x83, 0x06, 0xd4, 0x27, 0x06, 0x21, 0xe8, 0xda, 0xdf, 0x6b, 0xf3, 0x83, 0x6b, 0x34, 0x8a, 0x8c, 0xee, 0x01, 0x05, 0x5b, 0xed, 0xd3, 0x1b, 0xc9, 0x64, 0x83, 0xc9, 0x49, 0xc2, 0x57, 0x1b, 0xdd, 0xcf, 0xf1, 0x9d, 0x63, 0xee, 0x1c, 0x0d, 0xa0, 0x0a, 0x73, 0x1f, 0x5b, 0x32, - /* (2^439)P */ 0x29, 0xce, 0x1e, 0xc0, 0x6a, 0xf5, 0xeb, 0x99, 0x5a, 0x39, 0x23, 0xe9, 0xdd, 0xac, 0x44, 0x88, 0xbc, 0x80, 0x22, 0xde, 0x2c, 0xcb, 0xa8, 0x3b, 0xff, 0xf7, 0x6f, 0xc7, 0x71, 0x72, 0xa8, 0xa3, 0xf6, 0x4d, 0xc6, 0x75, 0xda, 0x80, 0xdc, 0xd9, 0x30, 0xd9, 0x07, 0x50, 0x5a, 0x54, 0x7d, 0xda, 0x39, 0x6f, 0x78, 0x94, 0xbf, 0x25, 0x98, 0xdc, - /* (2^440)P */ 0x01, 0x26, 0x62, 0x44, 0xfb, 0x0f, 0x11, 0x72, 0x73, 0x0a, 0x16, 0xc7, 0x16, 0x9c, 0x9b, 0x37, 0xd8, 0xff, 0x4f, 0xfe, 0x57, 0xdb, 0xae, 0xef, 0x7d, 0x94, 0x30, 0x04, 0x70, 0x83, 0xde, 0x3c, 0xd4, 0xb5, 0x70, 0xda, 0xa7, 0x55, 0xc8, 0x19, 0xe1, 0x36, 0x15, 0x61, 0xe7, 0x3b, 0x7d, 0x85, 0xbb, 0xf3, 0x42, 0x5a, 0x94, 0xf4, 0x53, 0x2a, - /* (2^441)P */ 0x14, 0x60, 0xa6, 0x0b, 0x83, 0xe1, 0x23, 0x77, 0xc0, 0xce, 0x50, 0xed, 0x35, 0x8d, 0x98, 0x99, 0x7d, 0xf5, 0x8d, 0xce, 0x94, 0x25, 0xc8, 0x0f, 0x6d, 0xfa, 0x4a, 0xa4, 0x3a, 0x1f, 0x66, 0xfb, 0x5a, 0x64, 0xaf, 0x8b, 0x54, 0x54, 0x44, 0x3f, 0x5b, 0x88, 0x61, 0xe4, 0x48, 0x45, 0x26, 0x20, 0xbe, 0x0d, 0x06, 0xbb, 0x65, 0x59, 0xe1, 0x36, - /* (2^442)P */ 0xb7, 0x98, 0xce, 0xa3, 0xe3, 0xee, 0x11, 0x1b, 0x9e, 0x24, 0x59, 0x75, 0x31, 0x37, 0x44, 0x6f, 0x6b, 0x9e, 0xec, 0xb7, 0x44, 0x01, 0x7e, 0xab, 0xbb, 0x69, 0x5d, 0x11, 0xb0, 0x30, 0x64, 0xea, 0x91, 0xb4, 0x7a, 0x8c, 0x02, 0x4c, 0xb9, 0x10, 0xa7, 0xc7, 0x79, 0xe6, 0xdc, 0x77, 0xe3, 0xc8, 0xef, 0x3e, 0xf9, 0x38, 0x81, 0xce, 0x9a, 0xb2, - /* (2^443)P */ 0x91, 0x12, 0x76, 0xd0, 0x10, 0xb4, 0xaf, 0xe1, 0x89, 0x3a, 0x93, 0x6b, 0x5c, 0x19, 0x5f, 0x24, 0xed, 0x04, 0x92, 0xc7, 0xf0, 0x00, 0x08, 0xc1, 0x92, 0xff, 0x90, 0xdb, 0xb2, 0xbf, 0xdf, 0x49, 0xcd, 0xbd, 0x5c, 0x6e, 0xbf, 0x16, 0xbb, 0x61, 0xf9, 0x20, 0x33, 0x35, 0x93, 0x11, 0xbc, 0x59, 0x69, 0xce, 0x18, 0x9f, 0xf8, 0x7b, 0xa1, 0x6e, - /* (2^444)P */ 0xa1, 0xf4, 0xaf, 0xad, 0xf8, 0xe6, 0x99, 0xd2, 0xa1, 0x4d, 0xde, 0x56, 0xc9, 0x7b, 0x0b, 0x11, 0x3e, 0xbf, 0x89, 0x1a, 0x9a, 0x90, 0xe5, 0xe2, 0xa6, 0x37, 0x88, 0xa1, 0x68, 0x59, 0xae, 0x8c, 0xec, 0x02, 0x14, 0x8d, 0xb7, 0x2e, 0x25, 0x75, 0x7f, 0x76, 0x1a, 0xd3, 0x4d, 0xad, 0x8a, 0x00, 0x6c, 0x96, 0x49, 0xa4, 0xc3, 0x2e, 0x5c, 0x7b, - /* (2^445)P */ 0x26, 0x53, 0xf7, 0xda, 0xa8, 0x01, 0x14, 0xb1, 0x63, 0xe3, 0xc3, 0x89, 0x88, 0xb0, 0x85, 0x40, 0x2b, 0x26, 0x9a, 0x10, 0x1a, 0x70, 0x33, 0xf4, 0x50, 0x9d, 0x4d, 0xd8, 0x64, 0xc6, 0x0f, 0xe1, 0x17, 0xc8, 0x10, 0x4b, 0xfc, 0xa0, 0xc9, 0xba, 0x2c, 0x98, 0x09, 0xf5, 0x84, 0xb6, 0x7c, 0x4e, 0xa3, 0xe3, 0x81, 0x1b, 0x32, 0x60, 0x02, 0xdd, - /* (2^446)P */ 0xa3, 0xe5, 0x86, 0xd4, 0x43, 0xa8, 0xd1, 0x98, 0x9d, 0x9d, 0xdb, 0x04, 0xcf, 0x6e, 0x35, 0x05, 0x30, 0x53, 0x3b, 0xbc, 0x90, 0x00, 0x4a, 0xc5, 0x40, 0x2a, 0x0f, 0xde, 0x1a, 0xd7, 0x36, 0x27, 0x44, 0x62, 0xa6, 0xac, 0x9d, 0xd2, 0x70, 0x69, 0x14, 0x39, 0x9b, 0xd1, 0xc3, 0x0a, 0x3a, 0x82, 0x0e, 0xf1, 0x94, 0xd7, 0x42, 0x94, 0xd5, 0x7d, - /* (2^447)P */ 0x04, 0xc0, 0x6e, 0x12, 0x90, 0x70, 0xf9, 0xdf, 0xf7, 0xc9, 0x86, 0xc0, 0xe6, 0x92, 0x8b, 0x0a, 0xa1, 0xc1, 0x3b, 0xcc, 0x33, 0xb7, 0xf0, 0xeb, 0x51, 0x50, 0x80, 0x20, 0x69, 0x1c, 0x4f, 0x89, 0x05, 0x1e, 0xe4, 0x7a, 0x0a, 0xc2, 0xf0, 0xf5, 0x78, 0x91, 0x76, 0x34, 0x45, 0xdc, 0x24, 0x53, 0x24, 0x98, 0xe2, 0x73, 0x6f, 0xe6, 0x46, 0x67, -} diff --git a/vendor/github.com/cloudflare/circl/ecc/goldilocks/constants.go b/vendor/github.com/cloudflare/circl/ecc/goldilocks/constants.go deleted file mode 100644 index b6b236e5..00000000 --- a/vendor/github.com/cloudflare/circl/ecc/goldilocks/constants.go +++ /dev/null @@ -1,71 +0,0 @@ -package goldilocks - -import fp "github.com/cloudflare/circl/math/fp448" - -var ( - // genX is the x-coordinate of the generator of Goldilocks curve. - genX = fp.Elt{ - 0x5e, 0xc0, 0x0c, 0xc7, 0x2b, 0xa8, 0x26, 0x26, - 0x8e, 0x93, 0x00, 0x8b, 0xe1, 0x80, 0x3b, 0x43, - 0x11, 0x65, 0xb6, 0x2a, 0xf7, 0x1a, 0xae, 0x12, - 0x64, 0xa4, 0xd3, 0xa3, 0x24, 0xe3, 0x6d, 0xea, - 0x67, 0x17, 0x0f, 0x47, 0x70, 0x65, 0x14, 0x9e, - 0xda, 0x36, 0xbf, 0x22, 0xa6, 0x15, 0x1d, 0x22, - 0xed, 0x0d, 0xed, 0x6b, 0xc6, 0x70, 0x19, 0x4f, - } - // genY is the y-coordinate of the generator of Goldilocks curve. - genY = fp.Elt{ - 0x14, 0xfa, 0x30, 0xf2, 0x5b, 0x79, 0x08, 0x98, - 0xad, 0xc8, 0xd7, 0x4e, 0x2c, 0x13, 0xbd, 0xfd, - 0xc4, 0x39, 0x7c, 0xe6, 0x1c, 0xff, 0xd3, 0x3a, - 0xd7, 0xc2, 0xa0, 0x05, 0x1e, 0x9c, 0x78, 0x87, - 0x40, 0x98, 0xa3, 0x6c, 0x73, 0x73, 0xea, 0x4b, - 0x62, 0xc7, 0xc9, 0x56, 0x37, 0x20, 0x76, 0x88, - 0x24, 0xbc, 0xb6, 0x6e, 0x71, 0x46, 0x3f, 0x69, - } - // paramD is -39081 in Fp. - paramD = fp.Elt{ - 0x56, 0x67, 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, 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, - } - // order is 2^446-0x8335dc163bb124b65129c96fde933d8d723a70aadc873d6d54a7bb0d, - // which is the number of points in the prime subgroup. - order = Scalar{ - 0xf3, 0x44, 0x58, 0xab, 0x92, 0xc2, 0x78, 0x23, - 0x55, 0x8f, 0xc5, 0x8d, 0x72, 0xc2, 0x6c, 0x21, - 0x90, 0x36, 0xd6, 0xae, 0x49, 0xdb, 0x4e, 0xc4, - 0xe9, 0x23, 0xca, 0x7c, 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, 0x3f, - } - // residue448 is 2^448 mod order. - residue448 = [4]uint64{ - 0x721cf5b5529eec34, 0x7a4cf635c8e9c2ab, 0xeec492d944a725bf, 0x20cd77058, - } - // invFour is 1/4 mod order. - invFour = Scalar{ - 0x3d, 0x11, 0xd6, 0xaa, 0xa4, 0x30, 0xde, 0x48, - 0xd5, 0x63, 0x71, 0xa3, 0x9c, 0x30, 0x5b, 0x08, - 0xa4, 0x8d, 0xb5, 0x6b, 0xd2, 0xb6, 0x13, 0x71, - 0xfa, 0x88, 0x32, 0xdf, 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, 0x0f, - } - // paramDTwist is -39082 in Fp. The D parameter of the twist curve. - paramDTwist = fp.Elt{ - 0x55, 0x67, 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, 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, - } -) diff --git a/vendor/github.com/cloudflare/circl/ecc/goldilocks/curve.go b/vendor/github.com/cloudflare/circl/ecc/goldilocks/curve.go deleted file mode 100644 index 5a939100..00000000 --- a/vendor/github.com/cloudflare/circl/ecc/goldilocks/curve.go +++ /dev/null @@ -1,80 +0,0 @@ -// Package goldilocks provides elliptic curve operations over the goldilocks curve. -package goldilocks - -import fp "github.com/cloudflare/circl/math/fp448" - -// Curve is the Goldilocks curve x^2+y^2=z^2-39081x^2y^2. -type Curve struct{} - -// Identity returns the identity point. -func (Curve) Identity() *Point { - return &Point{ - y: fp.One(), - z: fp.One(), - } -} - -// IsOnCurve returns true if the point lies on the curve. -func (Curve) IsOnCurve(P *Point) bool { - x2, y2, t, t2, z2 := &fp.Elt{}, &fp.Elt{}, &fp.Elt{}, &fp.Elt{}, &fp.Elt{} - rhs, lhs := &fp.Elt{}, &fp.Elt{} - fp.Mul(t, &P.ta, &P.tb) // t = ta*tb - fp.Sqr(x2, &P.x) // x^2 - fp.Sqr(y2, &P.y) // y^2 - fp.Sqr(z2, &P.z) // z^2 - fp.Sqr(t2, t) // t^2 - fp.Add(lhs, x2, y2) // x^2 + y^2 - fp.Mul(rhs, t2, ¶mD) // dt^2 - fp.Add(rhs, rhs, z2) // z^2 + dt^2 - fp.Sub(lhs, lhs, rhs) // x^2 + y^2 - (z^2 + dt^2) - eq0 := fp.IsZero(lhs) - - fp.Mul(lhs, &P.x, &P.y) // xy - fp.Mul(rhs, t, &P.z) // tz - fp.Sub(lhs, lhs, rhs) // xy - tz - eq1 := fp.IsZero(lhs) - return eq0 && eq1 -} - -// Generator returns the generator point. -func (Curve) Generator() *Point { - return &Point{ - x: genX, - y: genY, - z: fp.One(), - ta: genX, - tb: genY, - } -} - -// Order returns the number of points in the prime subgroup. -func (Curve) Order() Scalar { return order } - -// Double returns 2P. -func (Curve) Double(P *Point) *Point { R := *P; R.Double(); return &R } - -// Add returns P+Q. -func (Curve) Add(P, Q *Point) *Point { R := *P; R.Add(Q); return &R } - -// ScalarMult returns kP. This function runs in constant time. -func (e Curve) ScalarMult(k *Scalar, P *Point) *Point { - k4 := &Scalar{} - k4.divBy4(k) - return e.pull(twistCurve{}.ScalarMult(k4, e.push(P))) -} - -// ScalarBaseMult returns kG where G is the generator point. This function runs in constant time. -func (e Curve) ScalarBaseMult(k *Scalar) *Point { - k4 := &Scalar{} - k4.divBy4(k) - return e.pull(twistCurve{}.ScalarBaseMult(k4)) -} - -// CombinedMult returns mG+nP, where G is the generator point. This function is non-constant time. -func (e Curve) CombinedMult(m, n *Scalar, P *Point) *Point { - m4 := &Scalar{} - n4 := &Scalar{} - m4.divBy4(m) - n4.divBy4(n) - return e.pull(twistCurve{}.CombinedMult(m4, n4, twistCurve{}.pull(P))) -} diff --git a/vendor/github.com/cloudflare/circl/ecc/goldilocks/isogeny.go b/vendor/github.com/cloudflare/circl/ecc/goldilocks/isogeny.go deleted file mode 100644 index b1daab85..00000000 --- a/vendor/github.com/cloudflare/circl/ecc/goldilocks/isogeny.go +++ /dev/null @@ -1,52 +0,0 @@ -package goldilocks - -import fp "github.com/cloudflare/circl/math/fp448" - -func (Curve) pull(P *twistPoint) *Point { return twistCurve{}.push(P) } -func (twistCurve) pull(P *Point) *twistPoint { return Curve{}.push(P) } - -// push sends a point on the Goldilocks curve to a point on the twist curve. -func (Curve) push(P *Point) *twistPoint { - Q := &twistPoint{} - Px, Py, Pz := &P.x, &P.y, &P.z - a, b, c, d, e, f, g, h := &Q.x, &Q.y, &Q.z, &fp.Elt{}, &Q.ta, &Q.x, &Q.y, &Q.tb - fp.Add(e, Px, Py) // x+y - fp.Sqr(a, Px) // A = x^2 - fp.Sqr(b, Py) // B = y^2 - fp.Sqr(c, Pz) // z^2 - fp.Add(c, c, c) // C = 2*z^2 - *d = *a // D = A - fp.Sqr(e, e) // (x+y)^2 - fp.Sub(e, e, a) // (x+y)^2-A - fp.Sub(e, e, b) // E = (x+y)^2-A-B - fp.Add(h, b, d) // H = B+D - fp.Sub(g, b, d) // G = B-D - fp.Sub(f, c, h) // F = C-H - fp.Mul(&Q.z, f, g) // Z = F * G - fp.Mul(&Q.x, e, f) // X = E * F - fp.Mul(&Q.y, g, h) // Y = G * H, // T = E * H - return Q -} - -// push sends a point on the twist curve to a point on the Goldilocks curve. -func (twistCurve) push(P *twistPoint) *Point { - Q := &Point{} - Px, Py, Pz := &P.x, &P.y, &P.z - a, b, c, d, e, f, g, h := &Q.x, &Q.y, &Q.z, &fp.Elt{}, &Q.ta, &Q.x, &Q.y, &Q.tb - fp.Add(e, Px, Py) // x+y - fp.Sqr(a, Px) // A = x^2 - fp.Sqr(b, Py) // B = y^2 - fp.Sqr(c, Pz) // z^2 - fp.Add(c, c, c) // C = 2*z^2 - fp.Neg(d, a) // D = -A - fp.Sqr(e, e) // (x+y)^2 - fp.Sub(e, e, a) // (x+y)^2-A - fp.Sub(e, e, b) // E = (x+y)^2-A-B - fp.Add(h, b, d) // H = B+D - fp.Sub(g, b, d) // G = B-D - fp.Sub(f, c, h) // F = C-H - fp.Mul(&Q.z, f, g) // Z = F * G - fp.Mul(&Q.x, e, f) // X = E * F - fp.Mul(&Q.y, g, h) // Y = G * H, // T = E * H - return Q -} diff --git a/vendor/github.com/cloudflare/circl/ecc/goldilocks/point.go b/vendor/github.com/cloudflare/circl/ecc/goldilocks/point.go deleted file mode 100644 index 11f73de0..00000000 --- a/vendor/github.com/cloudflare/circl/ecc/goldilocks/point.go +++ /dev/null @@ -1,171 +0,0 @@ -package goldilocks - -import ( - "errors" - "fmt" - - fp "github.com/cloudflare/circl/math/fp448" -) - -// Point is a point on the Goldilocks Curve. -type Point struct{ x, y, z, ta, tb fp.Elt } - -func (P Point) String() string { - return fmt.Sprintf("x: %v\ny: %v\nz: %v\nta: %v\ntb: %v", P.x, P.y, P.z, P.ta, P.tb) -} - -// FromAffine creates a point from affine coordinates. -func FromAffine(x, y *fp.Elt) (*Point, error) { - P := &Point{ - x: *x, - y: *y, - z: fp.One(), - ta: *x, - tb: *y, - } - if !(Curve{}).IsOnCurve(P) { - return P, errors.New("point not on curve") - } - return P, nil -} - -// isLessThan returns true if 0 <= x < y, and assumes that slices are of the -// same length and are interpreted in little-endian order. -func isLessThan(x, y []byte) bool { - i := len(x) - 1 - for i > 0 && x[i] == y[i] { - i-- - } - return x[i] < y[i] -} - -// FromBytes returns a point from the input buffer. -func FromBytes(in []byte) (*Point, error) { - if len(in) < fp.Size+1 { - return nil, errors.New("wrong input length") - } - err := errors.New("invalid decoding") - P := &Point{} - signX := in[fp.Size] >> 7 - copy(P.y[:], in[:fp.Size]) - p := fp.P() - if !isLessThan(P.y[:], p[:]) { - return nil, err - } - - u, v := &fp.Elt{}, &fp.Elt{} - one := fp.One() - fp.Sqr(u, &P.y) // u = y^2 - fp.Mul(v, u, ¶mD) // v = dy^2 - fp.Sub(u, u, &one) // u = y^2-1 - fp.Sub(v, v, &one) // v = dy^2-1 - isQR := fp.InvSqrt(&P.x, u, v) // x = sqrt(u/v) - if !isQR { - return nil, err - } - fp.Modp(&P.x) // x = x mod p - if fp.IsZero(&P.x) && signX == 1 { - return nil, err - } - if signX != (P.x[0] & 1) { - fp.Neg(&P.x, &P.x) - } - P.ta = P.x - P.tb = P.y - P.z = fp.One() - return P, nil -} - -// IsIdentity returns true is P is the identity Point. -func (P *Point) IsIdentity() bool { - return fp.IsZero(&P.x) && !fp.IsZero(&P.y) && !fp.IsZero(&P.z) && P.y == P.z -} - -// IsEqual returns true if P is equivalent to Q. -func (P *Point) IsEqual(Q *Point) bool { - l, r := &fp.Elt{}, &fp.Elt{} - fp.Mul(l, &P.x, &Q.z) - fp.Mul(r, &Q.x, &P.z) - fp.Sub(l, l, r) - b := fp.IsZero(l) - fp.Mul(l, &P.y, &Q.z) - fp.Mul(r, &Q.y, &P.z) - fp.Sub(l, l, r) - b = b && fp.IsZero(l) - fp.Mul(l, &P.ta, &P.tb) - fp.Mul(l, l, &Q.z) - fp.Mul(r, &Q.ta, &Q.tb) - fp.Mul(r, r, &P.z) - fp.Sub(l, l, r) - b = b && fp.IsZero(l) - return b -} - -// Neg obtains the inverse of the Point. -func (P *Point) Neg() { fp.Neg(&P.x, &P.x); fp.Neg(&P.ta, &P.ta) } - -// ToAffine returns the x,y affine coordinates of P. -func (P *Point) ToAffine() (x, y fp.Elt) { - fp.Inv(&P.z, &P.z) // 1/z - fp.Mul(&P.x, &P.x, &P.z) // x/z - fp.Mul(&P.y, &P.y, &P.z) // y/z - fp.Modp(&P.x) - fp.Modp(&P.y) - fp.SetOne(&P.z) - P.ta = P.x - P.tb = P.y - return P.x, P.y -} - -// ToBytes stores P into a slice of bytes. -func (P *Point) ToBytes(out []byte) error { - if len(out) < fp.Size+1 { - return errors.New("invalid decoding") - } - x, y := P.ToAffine() - out[fp.Size] = (x[0] & 1) << 7 - return fp.ToBytes(out[:fp.Size], &y) -} - -// MarshalBinary encodes the receiver into a binary form and returns the result. -func (P *Point) MarshalBinary() (data []byte, err error) { - data = make([]byte, fp.Size+1) - err = P.ToBytes(data[:fp.Size+1]) - return data, err -} - -// UnmarshalBinary must be able to decode the form generated by MarshalBinary. -func (P *Point) UnmarshalBinary(data []byte) error { Q, err := FromBytes(data); *P = *Q; return err } - -// Double sets P = 2Q. -func (P *Point) Double() { P.Add(P) } - -// Add sets P =P+Q.. -func (P *Point) Add(Q *Point) { - // This is formula (5) from "Twisted Edwards Curves Revisited" by - // Hisil H., Wong K.KH., Carter G., Dawson E. (2008) - // https://doi.org/10.1007/978-3-540-89255-7_20 - x1, y1, z1, ta1, tb1 := &P.x, &P.y, &P.z, &P.ta, &P.tb - x2, y2, z2, ta2, tb2 := &Q.x, &Q.y, &Q.z, &Q.ta, &Q.tb - x3, y3, z3, E, H := &P.x, &P.y, &P.z, &P.ta, &P.tb - A, B, C, D := &fp.Elt{}, &fp.Elt{}, &fp.Elt{}, &fp.Elt{} - t1, t2, F, G := C, D, &fp.Elt{}, &fp.Elt{} - fp.Mul(t1, ta1, tb1) // t1 = ta1*tb1 - fp.Mul(t2, ta2, tb2) // t2 = ta2*tb2 - fp.Mul(A, x1, x2) // A = x1*x2 - fp.Mul(B, y1, y2) // B = y1*y2 - fp.Mul(C, t1, t2) // t1*t2 - fp.Mul(C, C, ¶mD) // C = d*t1*t2 - fp.Mul(D, z1, z2) // D = z1*z2 - fp.Add(F, x1, y1) // x1+y1 - fp.Add(E, x2, y2) // x2+y2 - fp.Mul(E, E, F) // (x1+y1)*(x2+y2) - fp.Sub(E, E, A) // (x1+y1)*(x2+y2)-A - fp.Sub(E, E, B) // E = (x1+y1)*(x2+y2)-A-B - fp.Sub(F, D, C) // F = D-C - fp.Add(G, D, C) // G = D+C - fp.Sub(H, B, A) // H = B-A - fp.Mul(z3, F, G) // Z = F * G - fp.Mul(x3, E, F) // X = E * F - fp.Mul(y3, G, H) // Y = G * H, T = E * H -} diff --git a/vendor/github.com/cloudflare/circl/ecc/goldilocks/scalar.go b/vendor/github.com/cloudflare/circl/ecc/goldilocks/scalar.go deleted file mode 100644 index f98117b2..00000000 --- a/vendor/github.com/cloudflare/circl/ecc/goldilocks/scalar.go +++ /dev/null @@ -1,203 +0,0 @@ -package goldilocks - -import ( - "encoding/binary" - "math/bits" -) - -// ScalarSize is the size (in bytes) of scalars. -const ScalarSize = 56 // 448 / 8 - -// _N is the number of 64-bit words to store scalars. -const _N = 7 // 448 / 64 - -// Scalar represents a positive integer stored in little-endian order. -type Scalar [ScalarSize]byte - -type scalar64 [_N]uint64 - -func (z *scalar64) fromScalar(x *Scalar) { - z[0] = binary.LittleEndian.Uint64(x[0*8 : 1*8]) - z[1] = binary.LittleEndian.Uint64(x[1*8 : 2*8]) - z[2] = binary.LittleEndian.Uint64(x[2*8 : 3*8]) - z[3] = binary.LittleEndian.Uint64(x[3*8 : 4*8]) - z[4] = binary.LittleEndian.Uint64(x[4*8 : 5*8]) - z[5] = binary.LittleEndian.Uint64(x[5*8 : 6*8]) - z[6] = binary.LittleEndian.Uint64(x[6*8 : 7*8]) -} - -func (z *scalar64) toScalar(x *Scalar) { - binary.LittleEndian.PutUint64(x[0*8:1*8], z[0]) - binary.LittleEndian.PutUint64(x[1*8:2*8], z[1]) - binary.LittleEndian.PutUint64(x[2*8:3*8], z[2]) - binary.LittleEndian.PutUint64(x[3*8:4*8], z[3]) - binary.LittleEndian.PutUint64(x[4*8:5*8], z[4]) - binary.LittleEndian.PutUint64(x[5*8:6*8], z[5]) - binary.LittleEndian.PutUint64(x[6*8:7*8], z[6]) -} - -// add calculates z = x + y. Assumes len(z) > max(len(x),len(y)). -func add(z, x, y []uint64) uint64 { - l, L, zz := len(x), len(y), y - if l > L { - l, L, zz = L, l, x - } - c := uint64(0) - for i := 0; i < l; i++ { - z[i], c = bits.Add64(x[i], y[i], c) - } - for i := l; i < L; i++ { - z[i], c = bits.Add64(zz[i], 0, c) - } - return c -} - -// sub calculates z = x - y. Assumes len(z) > max(len(x),len(y)). -func sub(z, x, y []uint64) uint64 { - l, L, zz := len(x), len(y), y - if l > L { - l, L, zz = L, l, x - } - c := uint64(0) - for i := 0; i < l; i++ { - z[i], c = bits.Sub64(x[i], y[i], c) - } - for i := l; i < L; i++ { - z[i], c = bits.Sub64(zz[i], 0, c) - } - return c -} - -// mulWord calculates z = x * y. Assumes len(z) >= len(x)+1. -func mulWord(z, x []uint64, y uint64) { - for i := range z { - z[i] = 0 - } - carry := uint64(0) - for i := range x { - hi, lo := bits.Mul64(x[i], y) - lo, cc := bits.Add64(lo, z[i], 0) - hi, _ = bits.Add64(hi, 0, cc) - z[i], cc = bits.Add64(lo, carry, 0) - carry, _ = bits.Add64(hi, 0, cc) - } - z[len(x)] = carry -} - -// Cmov moves x into z if b=1. -func (z *scalar64) Cmov(b uint64, x *scalar64) { - m := uint64(0) - b - for i := range z { - z[i] = (z[i] &^ m) | (x[i] & m) - } -} - -// leftShift shifts to the left the words of z returning the more significant word. -func (z *scalar64) leftShift(low uint64) uint64 { - high := z[_N-1] - for i := _N - 1; i > 0; i-- { - z[i] = z[i-1] - } - z[0] = low - return high -} - -// reduceOneWord calculates z = z + 2^448*x such that the result fits in a Scalar. -func (z *scalar64) reduceOneWord(x uint64) { - prod := (&scalar64{})[:] - mulWord(prod, residue448[:], x) - cc := add(z[:], z[:], prod) - mulWord(prod, residue448[:], cc) - add(z[:], z[:], prod) -} - -// modOrder reduces z mod order. -func (z *scalar64) modOrder() { - var o64, x scalar64 - o64.fromScalar(&order) - // Performs: while (z >= order) { z = z-order } - // At most 8 (eight) iterations reduce 3 bits by subtracting. - for i := 0; i < 8; i++ { - c := sub(x[:], z[:], o64[:]) // (c || x) = z-order - z.Cmov(1-c, &x) // if c != 0 { z = x } - } -} - -// FromBytes stores z = x mod order, where x is a number stored in little-endian order. -func (z *Scalar) FromBytes(x []byte) { - n := len(x) - nCeil := (n + 7) >> 3 - for i := range z { - z[i] = 0 - } - if nCeil < _N { - copy(z[:], x) - return - } - copy(z[:], x[8*(nCeil-_N):]) - var z64 scalar64 - z64.fromScalar(z) - for i := nCeil - _N - 1; i >= 0; i-- { - low := binary.LittleEndian.Uint64(x[8*i:]) - high := z64.leftShift(low) - z64.reduceOneWord(high) - } - z64.modOrder() - z64.toScalar(z) -} - -// divBy4 calculates z = x/4 mod order. -func (z *Scalar) divBy4(x *Scalar) { z.Mul(x, &invFour) } - -// Red reduces z mod order. -func (z *Scalar) Red() { var t scalar64; t.fromScalar(z); t.modOrder(); t.toScalar(z) } - -// Neg calculates z = -z mod order. -func (z *Scalar) Neg() { z.Sub(&order, z) } - -// Add calculates z = x+y mod order. -func (z *Scalar) Add(x, y *Scalar) { - var z64, x64, y64, t scalar64 - x64.fromScalar(x) - y64.fromScalar(y) - c := add(z64[:], x64[:], y64[:]) - add(t[:], z64[:], residue448[:]) - z64.Cmov(c, &t) - z64.modOrder() - z64.toScalar(z) -} - -// Sub calculates z = x-y mod order. -func (z *Scalar) Sub(x, y *Scalar) { - var z64, x64, y64, t scalar64 - x64.fromScalar(x) - y64.fromScalar(y) - c := sub(z64[:], x64[:], y64[:]) - sub(t[:], z64[:], residue448[:]) - z64.Cmov(c, &t) - z64.modOrder() - z64.toScalar(z) -} - -// Mul calculates z = x*y mod order. -func (z *Scalar) Mul(x, y *Scalar) { - var z64, x64, y64 scalar64 - prod := (&[_N + 1]uint64{})[:] - x64.fromScalar(x) - y64.fromScalar(y) - mulWord(prod, x64[:], y64[_N-1]) - copy(z64[:], prod[:_N]) - z64.reduceOneWord(prod[_N]) - for i := _N - 2; i >= 0; i-- { - h := z64.leftShift(0) - z64.reduceOneWord(h) - mulWord(prod, x64[:], y64[i]) - c := add(z64[:], z64[:], prod[:_N]) - z64.reduceOneWord(prod[_N] + c) - } - z64.modOrder() - z64.toScalar(z) -} - -// IsZero returns true if z=0. -func (z *Scalar) IsZero() bool { z.Red(); return *z == Scalar{} } diff --git a/vendor/github.com/cloudflare/circl/ecc/goldilocks/twist.go b/vendor/github.com/cloudflare/circl/ecc/goldilocks/twist.go deleted file mode 100644 index 8cd4e333..00000000 --- a/vendor/github.com/cloudflare/circl/ecc/goldilocks/twist.go +++ /dev/null @@ -1,138 +0,0 @@ -package goldilocks - -import ( - "crypto/subtle" - "math/bits" - - "github.com/cloudflare/circl/internal/conv" - "github.com/cloudflare/circl/math" - fp "github.com/cloudflare/circl/math/fp448" -) - -// twistCurve is -x^2+y^2=1-39082x^2y^2 and is 4-isogeneous to Goldilocks. -type twistCurve struct{} - -// Identity returns the identity point. -func (twistCurve) Identity() *twistPoint { - return &twistPoint{ - y: fp.One(), - z: fp.One(), - } -} - -// subYDiv16 update x = (x - y) / 16. -func subYDiv16(x *scalar64, y int64) { - s := uint64(y >> 63) - x0, b0 := bits.Sub64((*x)[0], uint64(y), 0) - x1, b1 := bits.Sub64((*x)[1], s, b0) - x2, b2 := bits.Sub64((*x)[2], s, b1) - x3, b3 := bits.Sub64((*x)[3], s, b2) - x4, b4 := bits.Sub64((*x)[4], s, b3) - x5, b5 := bits.Sub64((*x)[5], s, b4) - x6, _ := bits.Sub64((*x)[6], s, b5) - x[0] = (x0 >> 4) | (x1 << 60) - x[1] = (x1 >> 4) | (x2 << 60) - x[2] = (x2 >> 4) | (x3 << 60) - x[3] = (x3 >> 4) | (x4 << 60) - x[4] = (x4 >> 4) | (x5 << 60) - x[5] = (x5 >> 4) | (x6 << 60) - x[6] = (x6 >> 4) -} - -func recodeScalar(d *[113]int8, k *Scalar) { - var k64 scalar64 - k64.fromScalar(k) - for i := 0; i < 112; i++ { - d[i] = int8((k64[0] & 0x1f) - 16) - subYDiv16(&k64, int64(d[i])) - } - d[112] = int8(k64[0]) -} - -// ScalarMult returns kP. -func (e twistCurve) ScalarMult(k *Scalar, P *twistPoint) *twistPoint { - var TabP [8]preTwistPointProy - var S preTwistPointProy - var d [113]int8 - - var isZero int - if k.IsZero() { - isZero = 1 - } - subtle.ConstantTimeCopy(isZero, k[:], order[:]) - - minusK := *k - isEven := 1 - int(k[0]&0x1) - minusK.Neg() - subtle.ConstantTimeCopy(isEven, k[:], minusK[:]) - recodeScalar(&d, k) - - P.oddMultiples(TabP[:]) - Q := e.Identity() - for i := 112; i >= 0; i-- { - Q.Double() - Q.Double() - Q.Double() - Q.Double() - mask := d[i] >> 7 - absDi := (d[i] + mask) ^ mask - inx := int32((absDi - 1) >> 1) - sig := int((d[i] >> 7) & 0x1) - for j := range TabP { - S.cmov(&TabP[j], uint(subtle.ConstantTimeEq(inx, int32(j)))) - } - S.cneg(sig) - Q.mixAdd(&S) - } - Q.cneg(uint(isEven)) - return Q -} - -const ( - omegaFix = 7 - omegaVar = 5 -) - -// CombinedMult returns mG+nP. -func (e twistCurve) CombinedMult(m, n *Scalar, P *twistPoint) *twistPoint { - nafFix := math.OmegaNAF(conv.BytesLe2BigInt(m[:]), omegaFix) - nafVar := math.OmegaNAF(conv.BytesLe2BigInt(n[:]), omegaVar) - - if len(nafFix) > len(nafVar) { - nafVar = append(nafVar, make([]int32, len(nafFix)-len(nafVar))...) - } else if len(nafFix) < len(nafVar) { - nafFix = append(nafFix, make([]int32, len(nafVar)-len(nafFix))...) - } - - var TabQ [1 << (omegaVar - 2)]preTwistPointProy - P.oddMultiples(TabQ[:]) - Q := e.Identity() - for i := len(nafFix) - 1; i >= 0; i-- { - Q.Double() - // Generator point - if nafFix[i] != 0 { - idxM := absolute(nafFix[i]) >> 1 - R := tabVerif[idxM] - if nafFix[i] < 0 { - R.neg() - } - Q.mixAddZ1(&R) - } - // Variable input point - if nafVar[i] != 0 { - idxN := absolute(nafVar[i]) >> 1 - S := TabQ[idxN] - if nafVar[i] < 0 { - S.neg() - } - Q.mixAdd(&S) - } - } - return Q -} - -// absolute returns always a positive value. -func absolute(x int32) int32 { - mask := x >> 31 - return (x + mask) ^ mask -} diff --git a/vendor/github.com/cloudflare/circl/ecc/goldilocks/twistPoint.go b/vendor/github.com/cloudflare/circl/ecc/goldilocks/twistPoint.go deleted file mode 100644 index c55db77b..00000000 --- a/vendor/github.com/cloudflare/circl/ecc/goldilocks/twistPoint.go +++ /dev/null @@ -1,135 +0,0 @@ -package goldilocks - -import ( - "fmt" - - fp "github.com/cloudflare/circl/math/fp448" -) - -type twistPoint struct{ x, y, z, ta, tb fp.Elt } - -type preTwistPointAffine struct{ addYX, subYX, dt2 fp.Elt } - -type preTwistPointProy struct { - preTwistPointAffine - z2 fp.Elt -} - -func (P *twistPoint) String() string { - return fmt.Sprintf("x: %v\ny: %v\nz: %v\nta: %v\ntb: %v", P.x, P.y, P.z, P.ta, P.tb) -} - -// cneg conditionally negates the point if b=1. -func (P *twistPoint) cneg(b uint) { - t := &fp.Elt{} - fp.Neg(t, &P.x) - fp.Cmov(&P.x, t, b) - fp.Neg(t, &P.ta) - fp.Cmov(&P.ta, t, b) -} - -// Double updates P with 2P. -func (P *twistPoint) Double() { - // This is formula (7) from "Twisted Edwards Curves Revisited" by - // Hisil H., Wong K.KH., Carter G., Dawson E. (2008) - // https://doi.org/10.1007/978-3-540-89255-7_20 - Px, Py, Pz, Pta, Ptb := &P.x, &P.y, &P.z, &P.ta, &P.tb - a, b, c, e, f, g, h := Px, Py, Pz, Pta, Px, Py, Ptb - fp.Add(e, Px, Py) // x+y - fp.Sqr(a, Px) // A = x^2 - fp.Sqr(b, Py) // B = y^2 - fp.Sqr(c, Pz) // z^2 - fp.Add(c, c, c) // C = 2*z^2 - fp.Add(h, a, b) // H = A+B - fp.Sqr(e, e) // (x+y)^2 - fp.Sub(e, e, h) // E = (x+y)^2-A-B - fp.Sub(g, b, a) // G = B-A - fp.Sub(f, c, g) // F = C-G - fp.Mul(Pz, f, g) // Z = F * G - fp.Mul(Px, e, f) // X = E * F - fp.Mul(Py, g, h) // Y = G * H, T = E * H -} - -// mixAdd calculates P= P+Q, where Q is a precomputed point with Z_Q = 1. -func (P *twistPoint) mixAddZ1(Q *preTwistPointAffine) { - fp.Add(&P.z, &P.z, &P.z) // D = 2*z1 (z2=1) - P.coreAddition(Q) -} - -// coreAddition calculates P=P+Q for curves with A=-1. -func (P *twistPoint) coreAddition(Q *preTwistPointAffine) { - // This is the formula following (5) from "Twisted Edwards Curves Revisited" by - // Hisil H., Wong K.KH., Carter G., Dawson E. (2008) - // https://doi.org/10.1007/978-3-540-89255-7_20 - Px, Py, Pz, Pta, Ptb := &P.x, &P.y, &P.z, &P.ta, &P.tb - addYX2, subYX2, dt2 := &Q.addYX, &Q.subYX, &Q.dt2 - a, b, c, d, e, f, g, h := Px, Py, &fp.Elt{}, Pz, Pta, Px, Py, Ptb - fp.Mul(c, Pta, Ptb) // t1 = ta*tb - fp.Sub(h, Py, Px) // y1-x1 - fp.Add(b, Py, Px) // y1+x1 - fp.Mul(a, h, subYX2) // A = (y1-x1)*(y2-x2) - fp.Mul(b, b, addYX2) // B = (y1+x1)*(y2+x2) - fp.Mul(c, c, dt2) // C = 2*D*t1*t2 - fp.Sub(e, b, a) // E = B-A - fp.Add(h, b, a) // H = B+A - fp.Sub(f, d, c) // F = D-C - fp.Add(g, d, c) // G = D+C - fp.Mul(Pz, f, g) // Z = F * G - fp.Mul(Px, e, f) // X = E * F - fp.Mul(Py, g, h) // Y = G * H, T = E * H -} - -func (P *preTwistPointAffine) neg() { - P.addYX, P.subYX = P.subYX, P.addYX - fp.Neg(&P.dt2, &P.dt2) -} - -func (P *preTwistPointAffine) cneg(b int) { - t := &fp.Elt{} - fp.Cswap(&P.addYX, &P.subYX, uint(b)) - fp.Neg(t, &P.dt2) - fp.Cmov(&P.dt2, t, uint(b)) -} - -func (P *preTwistPointAffine) cmov(Q *preTwistPointAffine, b uint) { - fp.Cmov(&P.addYX, &Q.addYX, b) - fp.Cmov(&P.subYX, &Q.subYX, b) - fp.Cmov(&P.dt2, &Q.dt2, b) -} - -// mixAdd calculates P= P+Q, where Q is a precomputed point with Z_Q != 1. -func (P *twistPoint) mixAdd(Q *preTwistPointProy) { - fp.Mul(&P.z, &P.z, &Q.z2) // D = 2*z1*z2 - P.coreAddition(&Q.preTwistPointAffine) -} - -// oddMultiples calculates T[i] = (2*i-1)P for 0 < i < len(T). -func (P *twistPoint) oddMultiples(T []preTwistPointProy) { - if n := len(T); n > 0 { - T[0].FromTwistPoint(P) - _2P := *P - _2P.Double() - R := &preTwistPointProy{} - R.FromTwistPoint(&_2P) - for i := 1; i < n; i++ { - P.mixAdd(R) - T[i].FromTwistPoint(P) - } - } -} - -// cmov conditionally moves Q into P if b=1. -func (P *preTwistPointProy) cmov(Q *preTwistPointProy, b uint) { - P.preTwistPointAffine.cmov(&Q.preTwistPointAffine, b) - fp.Cmov(&P.z2, &Q.z2, b) -} - -// FromTwistPoint precomputes some coordinates of Q for missed addition. -func (P *preTwistPointProy) FromTwistPoint(Q *twistPoint) { - fp.Add(&P.addYX, &Q.y, &Q.x) // addYX = X + Y - fp.Sub(&P.subYX, &Q.y, &Q.x) // subYX = Y - X - fp.Mul(&P.dt2, &Q.ta, &Q.tb) // T = ta*tb - fp.Mul(&P.dt2, &P.dt2, ¶mDTwist) // D*T - fp.Add(&P.dt2, &P.dt2, &P.dt2) // dt2 = 2*D*T - fp.Add(&P.z2, &Q.z, &Q.z) // z2 = 2*Z -} diff --git a/vendor/github.com/cloudflare/circl/ecc/goldilocks/twistTables.go b/vendor/github.com/cloudflare/circl/ecc/goldilocks/twistTables.go deleted file mode 100644 index ed432e02..00000000 --- a/vendor/github.com/cloudflare/circl/ecc/goldilocks/twistTables.go +++ /dev/null @@ -1,216 +0,0 @@ -package goldilocks - -import fp "github.com/cloudflare/circl/math/fp448" - -var tabFixMult = [fxV][fx2w1]preTwistPointAffine{ - { - { - addYX: fp.Elt{0x65, 0x4a, 0xdd, 0xdf, 0xb4, 0x79, 0x60, 0xc8, 0xa1, 0x70, 0xb4, 0x3a, 0x1e, 0x0c, 0x9b, 0x19, 0xe5, 0x48, 0x3f, 0xd7, 0x44, 0x18, 0x18, 0x14, 0x14, 0x27, 0x45, 0xd0, 0x2b, 0x24, 0xd5, 0x93, 0xc3, 0x74, 0x4c, 0x50, 0x70, 0x43, 0x26, 0x05, 0x08, 0x24, 0xca, 0x78, 0x30, 0xc1, 0x06, 0x8d, 0xd4, 0x86, 0x42, 0xf0, 0x14, 0xde, 0x08, 0x05}, - subYX: fp.Elt{0x64, 0x4a, 0xdd, 0xdf, 0xb4, 0x79, 0x60, 0xc8, 0xa1, 0x70, 0xb4, 0x3a, 0x1e, 0x0c, 0x9b, 0x19, 0xe5, 0x48, 0x3f, 0xd7, 0x44, 0x18, 0x18, 0x14, 0x14, 0x27, 0x45, 0xd0, 0x2d, 0x24, 0xd5, 0x93, 0xc3, 0x74, 0x4c, 0x50, 0x70, 0x43, 0x26, 0x05, 0x08, 0x24, 0xca, 0x78, 0x30, 0xc1, 0x06, 0x8d, 0xd4, 0x86, 0x42, 0xf0, 0x14, 0xde, 0x08, 0x05}, - dt2: fp.Elt{0x1a, 0x33, 0xea, 0x64, 0x45, 0x1c, 0xdf, 0x17, 0x1d, 0x16, 0x34, 0x28, 0xd6, 0x61, 0x19, 0x67, 0x79, 0xb4, 0x13, 0xcf, 0x3e, 0x7c, 0x0e, 0x72, 0xda, 0xf1, 0x5f, 0xda, 0xe6, 0xcf, 0x42, 0xd3, 0xb6, 0x17, 0xc2, 0x68, 0x13, 0x2d, 0xd9, 0x60, 0x3e, 0xae, 0xf0, 0x5b, 0x96, 0xf0, 0xcd, 0xaf, 0xea, 0xb7, 0x0d, 0x59, 0x16, 0xa7, 0xff, 0x55}, - }, - { - addYX: fp.Elt{0xca, 0xd8, 0x7d, 0x86, 0x1a, 0xef, 0xad, 0x11, 0xe3, 0x27, 0x41, 0x7e, 0x7f, 0x3e, 0xa9, 0xd2, 0xb5, 0x4e, 0x50, 0xe0, 0x77, 0x91, 0xc2, 0x13, 0x52, 0x73, 0x41, 0x09, 0xa6, 0x57, 0x9a, 0xc8, 0xa8, 0x90, 0x9d, 0x26, 0x14, 0xbb, 0xa1, 0x2a, 0xf7, 0x45, 0x43, 0x4e, 0xea, 0x35, 0x62, 0xe1, 0x08, 0x85, 0x46, 0xb8, 0x24, 0x05, 0x2d, 0xab}, - subYX: fp.Elt{0x9b, 0xe6, 0xd3, 0xe5, 0xfe, 0x50, 0x36, 0x3c, 0x3c, 0x6d, 0x74, 0x1d, 0x74, 0xc0, 0xde, 0x5b, 0x45, 0x27, 0xe5, 0x12, 0xee, 0x63, 0x35, 0x6b, 0x13, 0xe2, 0x41, 0x6b, 0x3a, 0x05, 0x2b, 0xb1, 0x89, 0x26, 0xb6, 0xc6, 0xd1, 0x84, 0xff, 0x0e, 0x9b, 0xa3, 0xfb, 0x21, 0x36, 0x6b, 0x01, 0xf7, 0x9f, 0x7c, 0xeb, 0xf5, 0x18, 0x7a, 0x2a, 0x70}, - dt2: fp.Elt{0x09, 0xad, 0x99, 0x1a, 0x38, 0xd3, 0xdf, 0x22, 0x37, 0x32, 0x61, 0x8b, 0xf3, 0x19, 0x48, 0x08, 0xe8, 0x49, 0xb6, 0x4a, 0xa7, 0xed, 0xa4, 0xa2, 0xee, 0x86, 0xd7, 0x31, 0x5e, 0xce, 0x95, 0x76, 0x86, 0x42, 0x1c, 0x9d, 0x07, 0x14, 0x8c, 0x34, 0x18, 0x9c, 0x6d, 0x3a, 0xdf, 0xa9, 0xe8, 0x36, 0x7e, 0xe4, 0x95, 0xbe, 0xb5, 0x09, 0xf8, 0x9c}, - }, - { - addYX: fp.Elt{0x51, 0xdb, 0x49, 0xa8, 0x9f, 0xe3, 0xd7, 0xec, 0x0d, 0x0f, 0x49, 0xe8, 0xb6, 0xc5, 0x0f, 0x5a, 0x1c, 0xce, 0x54, 0x0d, 0xb1, 0x8d, 0x5b, 0xbf, 0xf4, 0xaa, 0x34, 0x77, 0xc4, 0x5d, 0x59, 0xb6, 0xc5, 0x0e, 0x5a, 0xd8, 0x5b, 0x30, 0xc2, 0x1d, 0xec, 0x85, 0x1c, 0x42, 0xbe, 0x24, 0x2e, 0x50, 0x55, 0x44, 0xb2, 0x3a, 0x01, 0xaa, 0x98, 0xfb}, - subYX: fp.Elt{0xe7, 0x29, 0xb7, 0xd0, 0xaa, 0x4f, 0x32, 0x53, 0x56, 0xde, 0xbc, 0xd1, 0x92, 0x5d, 0x19, 0xbe, 0xa3, 0xe3, 0x75, 0x48, 0xe0, 0x7a, 0x1b, 0x54, 0x7a, 0xb7, 0x41, 0x77, 0x84, 0x38, 0xdd, 0x14, 0x9f, 0xca, 0x3f, 0xa3, 0xc8, 0xa7, 0x04, 0x70, 0xf1, 0x4d, 0x3d, 0xb3, 0x84, 0x79, 0xcb, 0xdb, 0xe4, 0xc5, 0x42, 0x9b, 0x57, 0x19, 0xf1, 0x2d}, - dt2: fp.Elt{0x20, 0xb4, 0x94, 0x9e, 0xdf, 0x31, 0x44, 0x0b, 0xc9, 0x7b, 0x75, 0x40, 0x9d, 0xd1, 0x96, 0x39, 0x70, 0x71, 0x15, 0xc8, 0x93, 0xd5, 0xc5, 0xe5, 0xba, 0xfe, 0xee, 0x08, 0x6a, 0x98, 0x0a, 0x1b, 0xb2, 0xaa, 0x3a, 0xf4, 0xa4, 0x79, 0xf9, 0x8e, 0x4d, 0x65, 0x10, 0x9b, 0x3a, 0x6e, 0x7c, 0x87, 0x94, 0x92, 0x11, 0x65, 0xbf, 0x1a, 0x09, 0xde}, - }, - { - addYX: fp.Elt{0xf3, 0x84, 0x76, 0x77, 0xa5, 0x6b, 0x27, 0x3b, 0x83, 0x3d, 0xdf, 0xa0, 0xeb, 0x32, 0x6d, 0x58, 0x81, 0x57, 0x64, 0xc2, 0x21, 0x7c, 0x9b, 0xea, 0xe6, 0xb0, 0x93, 0xf9, 0xe7, 0xc3, 0xed, 0x5a, 0x8e, 0xe2, 0xb4, 0x72, 0x76, 0x66, 0x0f, 0x22, 0x29, 0x94, 0x3e, 0x63, 0x48, 0x5e, 0x80, 0xcb, 0xac, 0xfa, 0x95, 0xb6, 0x4b, 0xc4, 0x95, 0x33}, - subYX: fp.Elt{0x0c, 0x55, 0xd1, 0x5e, 0x5f, 0xbf, 0xbf, 0xe2, 0x4c, 0xfc, 0x37, 0x4a, 0xc4, 0xb1, 0xf4, 0x83, 0x61, 0x93, 0x60, 0x8e, 0x9f, 0x31, 0xf0, 0xa0, 0x41, 0xff, 0x1d, 0xe2, 0x7f, 0xca, 0x40, 0xd6, 0x88, 0xe8, 0x91, 0x61, 0xe2, 0x11, 0x18, 0x83, 0xf3, 0x25, 0x2f, 0x3f, 0x49, 0x40, 0xd4, 0x83, 0xe2, 0xd7, 0x74, 0x6a, 0x16, 0x86, 0x4e, 0xab}, - dt2: fp.Elt{0xdd, 0x58, 0x65, 0xd8, 0x9f, 0xdd, 0x70, 0x7f, 0x0f, 0xec, 0xbd, 0x5c, 0x5c, 0x9b, 0x7e, 0x1b, 0x9f, 0x79, 0x36, 0x1f, 0xfd, 0x79, 0x10, 0x1c, 0x52, 0xf3, 0x22, 0xa4, 0x1f, 0x71, 0x6e, 0x63, 0x14, 0xf4, 0xa7, 0x3e, 0xbe, 0xad, 0x43, 0x30, 0x38, 0x8c, 0x29, 0xc6, 0xcf, 0x50, 0x75, 0x21, 0xe5, 0x78, 0xfd, 0xb0, 0x9a, 0xc4, 0x6d, 0xd4}, - }, - }, - { - { - addYX: fp.Elt{0x7a, 0xa1, 0x38, 0xa6, 0xfd, 0x0e, 0x96, 0xd5, 0x26, 0x76, 0x86, 0x70, 0x80, 0x30, 0xa6, 0x67, 0xeb, 0xf4, 0x39, 0xdb, 0x22, 0xf5, 0x9f, 0x98, 0xe4, 0xb5, 0x3a, 0x0c, 0x59, 0xbf, 0x85, 0xc6, 0xf0, 0x0b, 0x1c, 0x41, 0x38, 0x09, 0x01, 0xdb, 0xd6, 0x3c, 0xb7, 0xf1, 0x08, 0x6b, 0x4b, 0x9e, 0x63, 0x53, 0x83, 0xd3, 0xab, 0xa3, 0x72, 0x0d}, - subYX: fp.Elt{0x84, 0x68, 0x25, 0xe8, 0xe9, 0x8f, 0x91, 0xbf, 0xf7, 0xa4, 0x30, 0xae, 0xea, 0x9f, 0xdd, 0x56, 0x64, 0x09, 0xc9, 0x54, 0x68, 0x4e, 0x33, 0xc5, 0x6f, 0x7b, 0x2d, 0x52, 0x2e, 0x42, 0xbe, 0xbe, 0xf5, 0x64, 0xbf, 0x77, 0x54, 0xdf, 0xb0, 0x10, 0xd2, 0x16, 0x5d, 0xce, 0xaf, 0x9f, 0xfb, 0xa3, 0x63, 0x50, 0xcb, 0xc0, 0xd0, 0x88, 0x44, 0xa3}, - dt2: fp.Elt{0xc3, 0x8b, 0xa5, 0xf1, 0x44, 0xe4, 0x41, 0xcd, 0x75, 0xe3, 0x17, 0x69, 0x5b, 0xb9, 0xbb, 0xee, 0x82, 0xbb, 0xce, 0x57, 0xdf, 0x2a, 0x9c, 0x12, 0xab, 0x66, 0x08, 0x68, 0x05, 0x1b, 0x87, 0xee, 0x5d, 0x1e, 0x18, 0x14, 0x22, 0x4b, 0x99, 0x61, 0x75, 0x28, 0xe7, 0x65, 0x1c, 0x36, 0xb6, 0x18, 0x09, 0xa8, 0xdf, 0xef, 0x30, 0x35, 0xbc, 0x58}, - }, - { - addYX: fp.Elt{0xc5, 0xd3, 0x0e, 0x6f, 0xaf, 0x06, 0x69, 0xc4, 0x07, 0x9e, 0x58, 0x6e, 0x3f, 0x49, 0xd9, 0x0a, 0x3c, 0x2c, 0x37, 0xcd, 0x27, 0x4d, 0x87, 0x91, 0x7a, 0xb0, 0x28, 0xad, 0x2f, 0x68, 0x92, 0x05, 0x97, 0xf1, 0x30, 0x5f, 0x4c, 0x10, 0x20, 0x30, 0xd3, 0x08, 0x3f, 0xc1, 0xc6, 0xb7, 0xb5, 0xd1, 0x71, 0x7b, 0xa8, 0x0a, 0xd8, 0xf5, 0x17, 0xcf}, - subYX: fp.Elt{0x64, 0xd4, 0x8f, 0x91, 0x40, 0xab, 0x6e, 0x1a, 0x62, 0x83, 0xdc, 0xd7, 0x30, 0x1a, 0x4a, 0x2a, 0x4c, 0x54, 0x86, 0x19, 0x81, 0x5d, 0x04, 0x52, 0xa3, 0xca, 0x82, 0x38, 0xdc, 0x1e, 0xf0, 0x7a, 0x78, 0x76, 0x49, 0x4f, 0x71, 0xc4, 0x74, 0x2f, 0xf0, 0x5b, 0x2e, 0x5e, 0xac, 0xef, 0x17, 0xe4, 0x8e, 0x6e, 0xed, 0x43, 0x23, 0x61, 0x99, 0x49}, - dt2: fp.Elt{0x64, 0x90, 0x72, 0x76, 0xf8, 0x2c, 0x7d, 0x57, 0xf9, 0x30, 0x5e, 0x7a, 0x10, 0x74, 0x19, 0x39, 0xd9, 0xaf, 0x0a, 0xf1, 0x43, 0xed, 0x88, 0x9c, 0x8b, 0xdc, 0x9b, 0x1c, 0x90, 0xe7, 0xf7, 0xa3, 0xa5, 0x0d, 0xc6, 0xbc, 0x30, 0xfb, 0x91, 0x1a, 0x51, 0xba, 0x2d, 0xbe, 0x89, 0xdf, 0x1d, 0xdc, 0x53, 0xa8, 0x82, 0x8a, 0xd3, 0x8d, 0x16, 0x68}, - }, - { - addYX: fp.Elt{0xef, 0x5c, 0xe3, 0x74, 0xbf, 0x13, 0x4a, 0xbf, 0x66, 0x73, 0x64, 0xb7, 0xd4, 0xce, 0x98, 0x82, 0x05, 0xfa, 0x98, 0x0c, 0x0a, 0xae, 0xe5, 0x6b, 0x9f, 0xac, 0xbb, 0x6e, 0x1f, 0xcf, 0xff, 0xa6, 0x71, 0x9a, 0xa8, 0x7a, 0x9e, 0x64, 0x1f, 0x20, 0x4a, 0x61, 0xa2, 0xd6, 0x50, 0xe3, 0xba, 0x81, 0x0c, 0x50, 0x59, 0x69, 0x59, 0x15, 0x55, 0xdb}, - subYX: fp.Elt{0xe8, 0x77, 0x4d, 0xe8, 0x66, 0x3d, 0xc1, 0x00, 0x3c, 0xf2, 0x25, 0x00, 0xdc, 0xb2, 0xe5, 0x9b, 0x12, 0x89, 0xf3, 0xd6, 0xea, 0x85, 0x60, 0xfe, 0x67, 0x91, 0xfd, 0x04, 0x7c, 0xe0, 0xf1, 0x86, 0x06, 0x11, 0x66, 0xee, 0xd4, 0xd5, 0xbe, 0x3b, 0x0f, 0xe3, 0x59, 0xb3, 0x4f, 0x00, 0xb6, 0xce, 0x80, 0xc1, 0x61, 0xf7, 0xaf, 0x04, 0x6a, 0x3c}, - dt2: fp.Elt{0x00, 0xd7, 0x32, 0x93, 0x67, 0x70, 0x6f, 0xd7, 0x69, 0xab, 0xb1, 0xd3, 0xdc, 0xd6, 0xa8, 0xdd, 0x35, 0x25, 0xca, 0xd3, 0x8a, 0x6d, 0xce, 0xfb, 0xfd, 0x2b, 0x83, 0xf0, 0xd4, 0xac, 0x66, 0xfb, 0x72, 0x87, 0x7e, 0x55, 0xb7, 0x91, 0x58, 0x10, 0xc3, 0x11, 0x7e, 0x15, 0xfe, 0x7c, 0x55, 0x90, 0xa3, 0x9e, 0xed, 0x9a, 0x7f, 0xa7, 0xb7, 0xeb}, - }, - { - addYX: fp.Elt{0x25, 0x0f, 0xc2, 0x09, 0x9c, 0x10, 0xc8, 0x7c, 0x93, 0xa7, 0xbe, 0xe9, 0x26, 0x25, 0x7c, 0x21, 0xfe, 0xe7, 0x5f, 0x3c, 0x02, 0x83, 0xa7, 0x9e, 0xdf, 0xc0, 0x94, 0x2b, 0x7d, 0x1a, 0xd0, 0x1d, 0xcc, 0x2e, 0x7d, 0xd4, 0x85, 0xe7, 0xc1, 0x15, 0x66, 0xd6, 0xd6, 0x32, 0xb8, 0xf7, 0x63, 0xaa, 0x3b, 0xa5, 0xea, 0x49, 0xad, 0x88, 0x9b, 0x66}, - subYX: fp.Elt{0x09, 0x97, 0x79, 0x36, 0x41, 0x56, 0x9b, 0xdf, 0x15, 0xd8, 0x43, 0x28, 0x17, 0x5b, 0x96, 0xc9, 0xcf, 0x39, 0x1f, 0x13, 0xf7, 0x4d, 0x1d, 0x1f, 0xda, 0x51, 0x56, 0xe7, 0x0a, 0x5a, 0x65, 0xb6, 0x2a, 0x87, 0x49, 0x86, 0xc2, 0x2b, 0xcd, 0xfe, 0x07, 0xf6, 0x4c, 0xe2, 0x1d, 0x9b, 0xd8, 0x82, 0x09, 0x5b, 0x11, 0x10, 0x62, 0x56, 0x89, 0xbd}, - dt2: fp.Elt{0xd9, 0x15, 0x73, 0xf2, 0x96, 0x35, 0x53, 0xb0, 0xe7, 0xa8, 0x0b, 0x93, 0x35, 0x0b, 0x3a, 0x00, 0xf5, 0x18, 0xb1, 0xc3, 0x12, 0x3f, 0x91, 0x17, 0xc1, 0x4c, 0x15, 0x5a, 0x86, 0x92, 0x11, 0xbd, 0x44, 0x40, 0x5a, 0x7b, 0x15, 0x89, 0xba, 0xc1, 0xc1, 0xbc, 0x43, 0x45, 0xe6, 0x52, 0x02, 0x73, 0x0a, 0xd0, 0x2a, 0x19, 0xda, 0x47, 0xa8, 0xff}, - }, - }, -} - -// tabVerif contains the odd multiples of P. The entry T[i] = (2i+1)P, where -// P = phi(G) and G is the generator of the Goldilocks curve, and phi is a -// 4-degree isogeny. -var tabVerif = [1 << (omegaFix - 2)]preTwistPointAffine{ - { /* 1P*/ - addYX: fp.Elt{0x65, 0x4a, 0xdd, 0xdf, 0xb4, 0x79, 0x60, 0xc8, 0xa1, 0x70, 0xb4, 0x3a, 0x1e, 0x0c, 0x9b, 0x19, 0xe5, 0x48, 0x3f, 0xd7, 0x44, 0x18, 0x18, 0x14, 0x14, 0x27, 0x45, 0xd0, 0x2b, 0x24, 0xd5, 0x93, 0xc3, 0x74, 0x4c, 0x50, 0x70, 0x43, 0x26, 0x05, 0x08, 0x24, 0xca, 0x78, 0x30, 0xc1, 0x06, 0x8d, 0xd4, 0x86, 0x42, 0xf0, 0x14, 0xde, 0x08, 0x05}, - subYX: fp.Elt{0x64, 0x4a, 0xdd, 0xdf, 0xb4, 0x79, 0x60, 0xc8, 0xa1, 0x70, 0xb4, 0x3a, 0x1e, 0x0c, 0x9b, 0x19, 0xe5, 0x48, 0x3f, 0xd7, 0x44, 0x18, 0x18, 0x14, 0x14, 0x27, 0x45, 0xd0, 0x2d, 0x24, 0xd5, 0x93, 0xc3, 0x74, 0x4c, 0x50, 0x70, 0x43, 0x26, 0x05, 0x08, 0x24, 0xca, 0x78, 0x30, 0xc1, 0x06, 0x8d, 0xd4, 0x86, 0x42, 0xf0, 0x14, 0xde, 0x08, 0x05}, - dt2: fp.Elt{0x1a, 0x33, 0xea, 0x64, 0x45, 0x1c, 0xdf, 0x17, 0x1d, 0x16, 0x34, 0x28, 0xd6, 0x61, 0x19, 0x67, 0x79, 0xb4, 0x13, 0xcf, 0x3e, 0x7c, 0x0e, 0x72, 0xda, 0xf1, 0x5f, 0xda, 0xe6, 0xcf, 0x42, 0xd3, 0xb6, 0x17, 0xc2, 0x68, 0x13, 0x2d, 0xd9, 0x60, 0x3e, 0xae, 0xf0, 0x5b, 0x96, 0xf0, 0xcd, 0xaf, 0xea, 0xb7, 0x0d, 0x59, 0x16, 0xa7, 0xff, 0x55}, - }, - { /* 3P*/ - addYX: fp.Elt{0xd1, 0xe9, 0xa8, 0x33, 0x20, 0x76, 0x18, 0x08, 0x45, 0x2a, 0xc9, 0x67, 0x2a, 0xc3, 0x15, 0x24, 0xf9, 0x74, 0x21, 0x30, 0x99, 0x59, 0x8b, 0xb2, 0xf0, 0xa4, 0x07, 0xe2, 0x6a, 0x36, 0x8d, 0xd9, 0xd2, 0x4a, 0x7f, 0x73, 0x50, 0x39, 0x3d, 0xaa, 0xa7, 0x51, 0x73, 0x0d, 0x2b, 0x8b, 0x96, 0x47, 0xac, 0x3c, 0x5d, 0xaa, 0x39, 0x9c, 0xcf, 0xd5}, - subYX: fp.Elt{0x6b, 0x11, 0x5d, 0x1a, 0xf9, 0x41, 0x9d, 0xc5, 0x30, 0x3e, 0xad, 0x25, 0x2c, 0x04, 0x45, 0xea, 0xcc, 0x67, 0x07, 0x85, 0xe9, 0xda, 0x0e, 0xb5, 0x40, 0xb7, 0x32, 0xb4, 0x49, 0xdd, 0xff, 0xaa, 0xfc, 0xbb, 0x19, 0xca, 0x8b, 0x79, 0x2b, 0x8f, 0x8d, 0x00, 0x33, 0xc2, 0xad, 0xe9, 0xd3, 0x12, 0xa8, 0xaa, 0x87, 0x62, 0xad, 0x2d, 0xff, 0xa4}, - dt2: fp.Elt{0xb0, 0xaf, 0x3b, 0xea, 0xf0, 0x42, 0x0b, 0x5e, 0x88, 0xd3, 0x98, 0x08, 0x87, 0x59, 0x72, 0x0a, 0xc2, 0xdf, 0xcb, 0x7f, 0x59, 0xb5, 0x4c, 0x63, 0x68, 0xe8, 0x41, 0x38, 0x67, 0x4f, 0xe9, 0xc6, 0xb2, 0x6b, 0x08, 0xa7, 0xf7, 0x0e, 0xcd, 0xea, 0xca, 0x3d, 0xaf, 0x8e, 0xda, 0x4b, 0x2e, 0xd2, 0x88, 0x64, 0x8d, 0xc5, 0x5f, 0x76, 0x0f, 0x3d}, - }, - { /* 5P*/ - addYX: fp.Elt{0xe5, 0x65, 0xc9, 0xe2, 0x75, 0xf0, 0x7d, 0x1a, 0xba, 0xa4, 0x40, 0x4b, 0x93, 0x12, 0xa2, 0x80, 0x95, 0x0d, 0x03, 0x93, 0xe8, 0xa5, 0x4d, 0xe2, 0x3d, 0x81, 0xf5, 0xce, 0xd4, 0x2d, 0x25, 0x59, 0x16, 0x5c, 0xe7, 0xda, 0xc7, 0x45, 0xd2, 0x7e, 0x2c, 0x38, 0xd4, 0x37, 0x64, 0xb2, 0xc2, 0x28, 0xc5, 0x72, 0x16, 0x32, 0x45, 0x36, 0x6f, 0x9f}, - subYX: fp.Elt{0x09, 0xf4, 0x7e, 0xbd, 0x89, 0xdb, 0x19, 0x58, 0xe1, 0x08, 0x00, 0x8a, 0xf4, 0x5f, 0x2a, 0x32, 0x40, 0xf0, 0x2c, 0x3f, 0x5d, 0xe4, 0xfc, 0x89, 0x11, 0x24, 0xb4, 0x2f, 0x97, 0xad, 0xac, 0x8f, 0x19, 0xab, 0xfa, 0x12, 0xe5, 0xf9, 0x50, 0x4e, 0x50, 0x6f, 0x32, 0x30, 0x88, 0xa6, 0xe5, 0x48, 0x28, 0xa2, 0x1b, 0x9f, 0xcd, 0xe2, 0x43, 0x38}, - dt2: fp.Elt{0xa9, 0xcc, 0x53, 0x39, 0x86, 0x02, 0x60, 0x75, 0x34, 0x99, 0x57, 0xbd, 0xfc, 0x5a, 0x8e, 0xce, 0x5e, 0x98, 0x22, 0xd0, 0xa5, 0x24, 0xff, 0x90, 0x28, 0x9f, 0x58, 0xf3, 0x39, 0xe9, 0xba, 0x36, 0x23, 0xfb, 0x7f, 0x41, 0xcc, 0x2b, 0x5a, 0x25, 0x3f, 0x4c, 0x2a, 0xf1, 0x52, 0x6f, 0x2f, 0x07, 0xe3, 0x88, 0x81, 0x77, 0xdd, 0x7c, 0x88, 0x82}, - }, - { /* 7P*/ - addYX: fp.Elt{0xf7, 0xee, 0x88, 0xfd, 0x3a, 0xbf, 0x7e, 0x28, 0x39, 0x23, 0x79, 0xe6, 0x5c, 0x56, 0xcb, 0xb5, 0x48, 0x6a, 0x80, 0x6d, 0x37, 0x60, 0x6c, 0x10, 0x35, 0x49, 0x4b, 0x46, 0x60, 0xd4, 0x79, 0xd4, 0x53, 0xd3, 0x67, 0x88, 0xd0, 0x41, 0xd5, 0x43, 0x85, 0xc8, 0x71, 0xe3, 0x1c, 0xb6, 0xda, 0x22, 0x64, 0x8f, 0x80, 0xac, 0xad, 0x7d, 0xd5, 0x82}, - subYX: fp.Elt{0x92, 0x40, 0xc1, 0x83, 0x21, 0x9b, 0xd5, 0x7d, 0x3f, 0x29, 0xb6, 0x26, 0xef, 0x12, 0xb9, 0x27, 0x39, 0x42, 0x37, 0x97, 0x09, 0x9a, 0x08, 0xe1, 0x68, 0xb6, 0x7a, 0x3f, 0x9f, 0x45, 0xf8, 0x37, 0x19, 0x83, 0x97, 0xe6, 0x73, 0x30, 0x32, 0x35, 0xcf, 0xae, 0x5c, 0x12, 0x68, 0xdf, 0x6e, 0x2b, 0xde, 0x83, 0xa0, 0x44, 0x74, 0x2e, 0x4a, 0xe9}, - dt2: fp.Elt{0xcb, 0x22, 0x0a, 0xda, 0x6b, 0xc1, 0x8a, 0x29, 0xa1, 0xac, 0x8b, 0x5b, 0x8b, 0x32, 0x20, 0xf2, 0x21, 0xae, 0x0c, 0x43, 0xc4, 0xd7, 0x19, 0x37, 0x3d, 0x79, 0x25, 0x98, 0x6c, 0x9c, 0x22, 0x31, 0x2a, 0x55, 0x9f, 0xda, 0x5e, 0xa8, 0x13, 0xdb, 0x8e, 0x2e, 0x16, 0x39, 0xf4, 0x91, 0x6f, 0xec, 0x71, 0x71, 0xc9, 0x10, 0xf2, 0xa4, 0x8f, 0x11}, - }, - { /* 9P*/ - addYX: fp.Elt{0x85, 0xdd, 0x37, 0x62, 0x74, 0x8e, 0x33, 0x5b, 0x25, 0x12, 0x1b, 0xe7, 0xdf, 0x47, 0xe5, 0x12, 0xfd, 0x3a, 0x3a, 0xf5, 0x5d, 0x4c, 0xa2, 0x29, 0x3c, 0x5c, 0x2f, 0xee, 0x18, 0x19, 0x0a, 0x2b, 0xef, 0x67, 0x50, 0x7a, 0x0d, 0x29, 0xae, 0x55, 0x82, 0xcd, 0xd6, 0x41, 0x90, 0xb4, 0x13, 0x31, 0x5d, 0x11, 0xb8, 0xaa, 0x12, 0x86, 0x08, 0xac}, - subYX: fp.Elt{0xcc, 0x37, 0x8d, 0x83, 0x5f, 0xfd, 0xde, 0xd5, 0xf7, 0xf1, 0xae, 0x0a, 0xa7, 0x0b, 0xeb, 0x6d, 0x19, 0x8a, 0xb6, 0x1a, 0x59, 0xd8, 0xff, 0x3c, 0xbc, 0xbc, 0xef, 0x9c, 0xda, 0x7b, 0x75, 0x12, 0xaf, 0x80, 0x8f, 0x2c, 0x3c, 0xaa, 0x0b, 0x17, 0x86, 0x36, 0x78, 0x18, 0xc8, 0x8a, 0xf6, 0xb8, 0x2c, 0x2f, 0x57, 0x2c, 0x62, 0x57, 0xf6, 0x90}, - dt2: fp.Elt{0x83, 0xbc, 0xa2, 0x07, 0xa5, 0x38, 0x96, 0xea, 0xfe, 0x11, 0x46, 0x1d, 0x3b, 0xcd, 0x42, 0xc5, 0xee, 0x67, 0x04, 0x72, 0x08, 0xd8, 0xd9, 0x96, 0x07, 0xf7, 0xac, 0xc3, 0x64, 0xf1, 0x98, 0x2c, 0x55, 0xd7, 0x7d, 0xc8, 0x6c, 0xbd, 0x2c, 0xff, 0x15, 0xd6, 0x6e, 0xb8, 0x17, 0x8e, 0xa8, 0x27, 0x66, 0xb1, 0x73, 0x79, 0x96, 0xff, 0x29, 0x10}, - }, - { /* 11P*/ - addYX: fp.Elt{0x76, 0xcb, 0x9b, 0x0c, 0x5b, 0xfe, 0xe1, 0x2a, 0xdd, 0x6f, 0x6c, 0xdd, 0x6f, 0xb4, 0xc0, 0xc2, 0x1b, 0x4b, 0x38, 0xe8, 0x66, 0x8c, 0x1e, 0x31, 0x63, 0xb9, 0x94, 0xcd, 0xc3, 0x8c, 0x44, 0x25, 0x7b, 0xd5, 0x39, 0x80, 0xfc, 0x01, 0xaa, 0xf7, 0x2a, 0x61, 0x8a, 0x25, 0xd2, 0x5f, 0xc5, 0x66, 0x38, 0xa4, 0x17, 0xcf, 0x3e, 0x11, 0x0f, 0xa3}, - subYX: fp.Elt{0xe0, 0xb6, 0xd1, 0x9c, 0x71, 0x49, 0x2e, 0x7b, 0xde, 0x00, 0xda, 0x6b, 0xf1, 0xec, 0xe6, 0x7a, 0x15, 0x38, 0x71, 0xe9, 0x7b, 0xdb, 0xf8, 0x98, 0xc0, 0x91, 0x2e, 0x53, 0xee, 0x92, 0x87, 0x25, 0xc9, 0xb0, 0xbb, 0x33, 0x15, 0x46, 0x7f, 0xfd, 0x4f, 0x8b, 0x77, 0x05, 0x96, 0xb6, 0xe2, 0x08, 0xdb, 0x0d, 0x09, 0xee, 0x5b, 0xd1, 0x2a, 0x63}, - dt2: fp.Elt{0x8f, 0x7b, 0x57, 0x8c, 0xbf, 0x06, 0x0d, 0x43, 0x21, 0x92, 0x94, 0x2d, 0x6a, 0x38, 0x07, 0x0f, 0xa0, 0xf1, 0xe3, 0xd8, 0x2a, 0xbf, 0x46, 0xc6, 0x9e, 0x1f, 0x8f, 0x2b, 0x46, 0x84, 0x0b, 0x74, 0xed, 0xff, 0xf8, 0xa5, 0x94, 0xae, 0xf1, 0x67, 0xb1, 0x9b, 0xdd, 0x4a, 0xd0, 0xdb, 0xc2, 0xb5, 0x58, 0x49, 0x0c, 0xa9, 0x1d, 0x7d, 0xa9, 0xd3}, - }, - { /* 13P*/ - addYX: fp.Elt{0x73, 0x84, 0x2e, 0x31, 0x1f, 0xdc, 0xed, 0x9f, 0x74, 0xfa, 0xe0, 0x35, 0xb1, 0x85, 0x6a, 0x8d, 0x86, 0xd0, 0xff, 0xd6, 0x08, 0x43, 0x73, 0x1a, 0xd5, 0xf8, 0x43, 0xd4, 0xb3, 0xe5, 0x3f, 0xa8, 0x84, 0x17, 0x59, 0x65, 0x4e, 0xe6, 0xee, 0x54, 0x9c, 0xda, 0x5e, 0x7e, 0x98, 0x29, 0x6d, 0x73, 0x34, 0x1f, 0x99, 0x80, 0x54, 0x54, 0x81, 0x0b}, - subYX: fp.Elt{0xb1, 0xe5, 0xbb, 0x80, 0x22, 0x9c, 0x81, 0x6d, 0xaf, 0x27, 0x65, 0x6f, 0x7e, 0x9c, 0xb6, 0x8d, 0x35, 0x5c, 0x2e, 0x20, 0x48, 0x7a, 0x28, 0xf0, 0x97, 0xfe, 0xb7, 0x71, 0xce, 0xd6, 0xad, 0x3a, 0x81, 0xf6, 0x74, 0x5e, 0xf3, 0xfd, 0x1b, 0xd4, 0x1e, 0x7c, 0xc2, 0xb7, 0xc8, 0xa6, 0xc9, 0x89, 0x03, 0x47, 0xec, 0x24, 0xd6, 0x0e, 0xec, 0x9c}, - dt2: fp.Elt{0x91, 0x0a, 0x43, 0x34, 0x20, 0xc2, 0x64, 0xf7, 0x4e, 0x48, 0xc8, 0xd2, 0x95, 0x83, 0xd1, 0xa4, 0xfb, 0x4e, 0x41, 0x3b, 0x0d, 0xd5, 0x07, 0xd9, 0xf1, 0x13, 0x16, 0x78, 0x54, 0x57, 0xd0, 0xf1, 0x4f, 0x20, 0xac, 0xcf, 0x9c, 0x3b, 0x33, 0x0b, 0x99, 0x54, 0xc3, 0x7f, 0x3e, 0x57, 0x26, 0x86, 0xd5, 0xa5, 0x2b, 0x8d, 0xe3, 0x19, 0x36, 0xf7}, - }, - { /* 15P*/ - addYX: fp.Elt{0x23, 0x69, 0x47, 0x14, 0xf9, 0x9a, 0x50, 0xff, 0x64, 0xd1, 0x50, 0x35, 0xc3, 0x11, 0xd3, 0x19, 0xcf, 0x87, 0xda, 0x30, 0x0b, 0x50, 0xda, 0xc0, 0xe0, 0x25, 0x00, 0xe5, 0x68, 0x93, 0x04, 0xc2, 0xaf, 0xbd, 0x2f, 0x36, 0x5f, 0x47, 0x96, 0x10, 0xa8, 0xbd, 0xe4, 0x88, 0xac, 0x80, 0x52, 0x61, 0x73, 0xe9, 0x63, 0xdd, 0x99, 0xad, 0x20, 0x5b}, - subYX: fp.Elt{0x1b, 0x5e, 0xa2, 0x2a, 0x25, 0x0f, 0x86, 0xc0, 0xb1, 0x2e, 0x0c, 0x13, 0x40, 0x8d, 0xf0, 0xe6, 0x00, 0x55, 0x08, 0xc5, 0x7d, 0xf4, 0xc9, 0x31, 0x25, 0x3a, 0x99, 0x69, 0xdd, 0x67, 0x63, 0x9a, 0xd6, 0x89, 0x2e, 0xa1, 0x19, 0xca, 0x2c, 0xd9, 0x59, 0x5f, 0x5d, 0xc3, 0x6e, 0x62, 0x36, 0x12, 0x59, 0x15, 0xe1, 0xdc, 0xa4, 0xad, 0xc9, 0xd0}, - dt2: fp.Elt{0xbc, 0xea, 0xfc, 0xaf, 0x66, 0x23, 0xb7, 0x39, 0x6b, 0x2a, 0x96, 0xa8, 0x54, 0x43, 0xe9, 0xaa, 0x32, 0x40, 0x63, 0x92, 0x5e, 0xdf, 0x35, 0xc2, 0x9f, 0x24, 0x0c, 0xed, 0xfc, 0xde, 0x73, 0x8f, 0xa7, 0xd5, 0xa3, 0x2b, 0x18, 0x1f, 0xb0, 0xf8, 0xeb, 0x55, 0xd9, 0xc3, 0xfd, 0x28, 0x7c, 0x4f, 0xce, 0x0d, 0xf7, 0xae, 0xc2, 0x83, 0xc3, 0x78}, - }, - { /* 17P*/ - addYX: fp.Elt{0x71, 0xe6, 0x60, 0x93, 0x37, 0xdb, 0x01, 0xa5, 0x4c, 0xba, 0xe8, 0x8e, 0xd5, 0xf9, 0xd3, 0x98, 0xe5, 0xeb, 0xab, 0x3a, 0x15, 0x8b, 0x35, 0x60, 0xbe, 0xe5, 0x9c, 0x2d, 0x10, 0x9b, 0x2e, 0xcf, 0x65, 0x64, 0xea, 0x8f, 0x72, 0xce, 0xf5, 0x18, 0xe5, 0xe2, 0xf0, 0x0e, 0xae, 0x04, 0xec, 0xa0, 0x20, 0x65, 0x63, 0x07, 0xb1, 0x9f, 0x03, 0x97}, - subYX: fp.Elt{0x9e, 0x41, 0x64, 0x30, 0x95, 0x7f, 0x3a, 0x89, 0x7b, 0x0a, 0x79, 0x59, 0x23, 0x9a, 0x3b, 0xfe, 0xa4, 0x13, 0x08, 0xb2, 0x2e, 0x04, 0x50, 0x10, 0x30, 0xcd, 0x2e, 0xa4, 0x91, 0x71, 0x50, 0x36, 0x4a, 0x02, 0xf4, 0x8d, 0xa3, 0x36, 0x1b, 0xf4, 0x52, 0xba, 0x15, 0x04, 0x8b, 0x80, 0x25, 0xd9, 0xae, 0x67, 0x20, 0xd9, 0x88, 0x8f, 0x97, 0xa6}, - dt2: fp.Elt{0xb5, 0xe7, 0x46, 0xbd, 0x55, 0x23, 0xa0, 0x68, 0xc0, 0x12, 0xd9, 0xf1, 0x0a, 0x75, 0xe2, 0xda, 0xf4, 0x6b, 0xca, 0x14, 0xe4, 0x9f, 0x0f, 0xb5, 0x3c, 0xa6, 0xa5, 0xa2, 0x63, 0x94, 0xd1, 0x1c, 0x39, 0x58, 0x57, 0x02, 0x27, 0x98, 0xb6, 0x47, 0xc6, 0x61, 0x4b, 0x5c, 0xab, 0x6f, 0x2d, 0xab, 0xe3, 0xc1, 0x69, 0xf9, 0x12, 0xb0, 0xc8, 0xd5}, - }, - { /* 19P*/ - addYX: fp.Elt{0x19, 0x7d, 0xd5, 0xac, 0x79, 0xa2, 0x82, 0x9b, 0x28, 0x31, 0x22, 0xc0, 0x73, 0x02, 0x76, 0x17, 0x10, 0x70, 0x79, 0x57, 0xc9, 0x84, 0x62, 0x8e, 0x04, 0x04, 0x61, 0x67, 0x08, 0x48, 0xb4, 0x4b, 0xde, 0x53, 0x8c, 0xff, 0x36, 0x1b, 0x62, 0x86, 0x5d, 0xe1, 0x9b, 0xb1, 0xe5, 0xe8, 0x44, 0x64, 0xa1, 0x68, 0x3f, 0xa8, 0x45, 0x52, 0x91, 0xed}, - subYX: fp.Elt{0x42, 0x1a, 0x36, 0x1f, 0x90, 0x15, 0x24, 0x8d, 0x24, 0x80, 0xe6, 0xfe, 0x1e, 0xf0, 0xad, 0xaf, 0x6a, 0x93, 0xf0, 0xa6, 0x0d, 0x5d, 0xea, 0xf6, 0x62, 0x96, 0x7a, 0x05, 0x76, 0x85, 0x74, 0x32, 0xc7, 0xc8, 0x64, 0x53, 0x62, 0xe7, 0x54, 0x84, 0xe0, 0x40, 0x66, 0x19, 0x70, 0x40, 0x95, 0x35, 0x68, 0x64, 0x43, 0xcd, 0xba, 0x29, 0x32, 0xa8}, - dt2: fp.Elt{0x3e, 0xf6, 0xd6, 0xe4, 0x99, 0xeb, 0x20, 0x66, 0x08, 0x2e, 0x26, 0x64, 0xd7, 0x76, 0xf3, 0xb4, 0xc5, 0xa4, 0x35, 0x92, 0xd2, 0x99, 0x70, 0x5a, 0x1a, 0xe9, 0xe9, 0x3d, 0x3b, 0xe1, 0xcd, 0x0e, 0xee, 0x24, 0x13, 0x03, 0x22, 0xd6, 0xd6, 0x72, 0x08, 0x2b, 0xde, 0xfd, 0x93, 0xed, 0x0c, 0x7f, 0x5e, 0x31, 0x22, 0x4d, 0x80, 0x78, 0xc0, 0x48}, - }, - { /* 21P*/ - addYX: fp.Elt{0x8f, 0x72, 0xd2, 0x9e, 0xc4, 0xcd, 0x2c, 0xbf, 0xa8, 0xd3, 0x24, 0x62, 0x28, 0xee, 0x39, 0x0a, 0x19, 0x3a, 0x58, 0xff, 0x21, 0x2e, 0x69, 0x6c, 0x6e, 0x18, 0xd0, 0xcd, 0x61, 0xc1, 0x18, 0x02, 0x5a, 0xe9, 0xe3, 0xef, 0x1f, 0x8e, 0x10, 0xe8, 0x90, 0x2b, 0x48, 0xcd, 0xee, 0x38, 0xbd, 0x3a, 0xca, 0xbc, 0x2d, 0xe2, 0x3a, 0x03, 0x71, 0x02}, - subYX: fp.Elt{0xf8, 0xa4, 0x32, 0x26, 0x66, 0xaf, 0x3b, 0x53, 0xe7, 0xb0, 0x91, 0x92, 0xf5, 0x3c, 0x74, 0xce, 0xf2, 0xdd, 0x68, 0xa9, 0xf4, 0xcd, 0x5f, 0x60, 0xab, 0x71, 0xdf, 0xcd, 0x5c, 0x5d, 0x51, 0x72, 0x3a, 0x96, 0xea, 0xd6, 0xde, 0x54, 0x8e, 0x55, 0x4c, 0x08, 0x4c, 0x60, 0xdd, 0x34, 0xa9, 0x6f, 0xf3, 0x04, 0x02, 0xa8, 0xa6, 0x4e, 0x4d, 0x62}, - dt2: fp.Elt{0x76, 0x4a, 0xae, 0x38, 0x62, 0x69, 0x72, 0xdc, 0xe8, 0x43, 0xbe, 0x1d, 0x61, 0xde, 0x31, 0xc3, 0x42, 0x8f, 0x33, 0x9d, 0xca, 0xc7, 0x9c, 0xec, 0x6a, 0xe2, 0xaa, 0x01, 0x49, 0x78, 0x8d, 0x72, 0x4f, 0x38, 0xea, 0x52, 0xc2, 0xd3, 0xc9, 0x39, 0x71, 0xba, 0xb9, 0x09, 0x9b, 0xa3, 0x7f, 0x45, 0x43, 0x65, 0x36, 0x29, 0xca, 0xe7, 0x5c, 0x5f}, - }, - { /* 23P*/ - addYX: fp.Elt{0x89, 0x42, 0x35, 0x48, 0x6d, 0x74, 0xe5, 0x1f, 0xc3, 0xdd, 0x28, 0x5b, 0x84, 0x41, 0x33, 0x9f, 0x42, 0xf3, 0x1d, 0x5d, 0x15, 0x6d, 0x76, 0x33, 0x36, 0xaf, 0xe9, 0xdd, 0xfa, 0x63, 0x4f, 0x7a, 0x9c, 0xeb, 0x1c, 0x4f, 0x34, 0x65, 0x07, 0x54, 0xbb, 0x4c, 0x8b, 0x62, 0x9d, 0xd0, 0x06, 0x99, 0xb3, 0xe9, 0xda, 0x85, 0x19, 0xb0, 0x3d, 0x3c}, - subYX: fp.Elt{0xbb, 0x99, 0xf6, 0xbf, 0xaf, 0x2c, 0x22, 0x0d, 0x7a, 0xaa, 0x98, 0x6f, 0x01, 0x82, 0x99, 0xcf, 0x88, 0xbd, 0x0e, 0x3a, 0x89, 0xe0, 0x9c, 0x8c, 0x17, 0x20, 0xc4, 0xe0, 0xcf, 0x43, 0x7a, 0xef, 0x0d, 0x9f, 0x87, 0xd4, 0xfb, 0xf2, 0x96, 0xb8, 0x03, 0xe8, 0xcb, 0x5c, 0xec, 0x65, 0x5f, 0x49, 0xa4, 0x7c, 0x85, 0xb4, 0xf6, 0xc7, 0xdb, 0xa3}, - dt2: fp.Elt{0x11, 0xf3, 0x32, 0xa3, 0xa7, 0xb2, 0x7d, 0x51, 0x82, 0x44, 0xeb, 0xa2, 0x7d, 0x72, 0xcb, 0xc6, 0xf6, 0xc7, 0xb2, 0x38, 0x0e, 0x0f, 0x4f, 0x29, 0x00, 0xe4, 0x5b, 0x94, 0x46, 0x86, 0x66, 0xa1, 0x83, 0xb3, 0xeb, 0x15, 0xb6, 0x31, 0x50, 0x28, 0xeb, 0xed, 0x0d, 0x32, 0x39, 0xe9, 0x23, 0x81, 0x99, 0x3e, 0xff, 0x17, 0x4c, 0x11, 0x43, 0xd1}, - }, - { /* 25P*/ - addYX: fp.Elt{0xce, 0xe7, 0xf8, 0x94, 0x8f, 0x96, 0xf8, 0x96, 0xe6, 0x72, 0x20, 0x44, 0x2c, 0xa7, 0xfc, 0xba, 0xc8, 0xe1, 0xbb, 0xc9, 0x16, 0x85, 0xcd, 0x0b, 0xe5, 0xb5, 0x5a, 0x7f, 0x51, 0x43, 0x63, 0x8b, 0x23, 0x8e, 0x1d, 0x31, 0xff, 0x46, 0x02, 0x66, 0xcc, 0x9e, 0x4d, 0xa2, 0xca, 0xe2, 0xc7, 0xfd, 0x22, 0xb1, 0xdb, 0xdf, 0x6f, 0xe6, 0xa5, 0x82}, - subYX: fp.Elt{0xd0, 0xf5, 0x65, 0x40, 0xec, 0x8e, 0x65, 0x42, 0x78, 0xc1, 0x65, 0xe4, 0x10, 0xc8, 0x0b, 0x1b, 0xdd, 0x96, 0x68, 0xce, 0xee, 0x45, 0x55, 0xd8, 0x6e, 0xd3, 0xe6, 0x77, 0x19, 0xae, 0xc2, 0x8d, 0x8d, 0x3e, 0x14, 0x3f, 0x6d, 0x00, 0x2f, 0x9b, 0xd1, 0x26, 0x60, 0x28, 0x0f, 0x3a, 0x47, 0xb3, 0xe6, 0x68, 0x28, 0x24, 0x25, 0xca, 0xc8, 0x06}, - dt2: fp.Elt{0x54, 0xbb, 0x60, 0x92, 0xdb, 0x8f, 0x0f, 0x38, 0xe0, 0xe6, 0xe4, 0xc9, 0xcc, 0x14, 0x62, 0x01, 0xc4, 0x2b, 0x0f, 0xcf, 0xed, 0x7d, 0x8e, 0xa4, 0xd9, 0x73, 0x0b, 0xba, 0x0c, 0xaf, 0x0c, 0xf9, 0xe2, 0xeb, 0x29, 0x2a, 0x53, 0xdf, 0x2c, 0x5a, 0xfa, 0x8f, 0xc1, 0x01, 0xd7, 0xb1, 0x45, 0x73, 0x92, 0x32, 0x83, 0x85, 0x12, 0x74, 0x89, 0x44}, - }, - { /* 27P*/ - addYX: fp.Elt{0x0b, 0x73, 0x3c, 0xc2, 0xb1, 0x2e, 0xe1, 0xa7, 0xf5, 0xc9, 0x7a, 0xfb, 0x3d, 0x2d, 0xac, 0x59, 0xdb, 0xfa, 0x36, 0x11, 0xd1, 0x13, 0x04, 0x51, 0x1d, 0xab, 0x9b, 0x6b, 0x93, 0xfe, 0xda, 0xb0, 0x8e, 0xb4, 0x79, 0x11, 0x21, 0x0f, 0x65, 0xb9, 0xbb, 0x79, 0x96, 0x2a, 0xfd, 0x30, 0xe0, 0xb4, 0x2d, 0x9a, 0x55, 0x25, 0x5d, 0xd4, 0xad, 0x2a}, - subYX: fp.Elt{0x9e, 0xc5, 0x04, 0xfe, 0xec, 0x3c, 0x64, 0x1c, 0xed, 0x95, 0xed, 0xae, 0xaf, 0x5c, 0x6e, 0x08, 0x9e, 0x02, 0x29, 0x59, 0x7e, 0x5f, 0xc4, 0x9a, 0xd5, 0x32, 0x72, 0x86, 0xe1, 0x4e, 0x3c, 0xce, 0x99, 0x69, 0x3b, 0xc4, 0xdd, 0x4d, 0xb7, 0xbb, 0xda, 0x3b, 0x1a, 0x99, 0xaa, 0x62, 0x15, 0xc1, 0xf0, 0xb6, 0x6c, 0xec, 0x56, 0xc1, 0xff, 0x0c}, - dt2: fp.Elt{0x2f, 0xf1, 0x3f, 0x7a, 0x2d, 0x56, 0x19, 0x7f, 0xea, 0xbe, 0x59, 0x2e, 0x13, 0x67, 0x81, 0xfb, 0xdb, 0xc8, 0xa3, 0x1d, 0xd5, 0xe9, 0x13, 0x8b, 0x29, 0xdf, 0xcf, 0x9f, 0xe7, 0xd9, 0x0b, 0x70, 0xd3, 0x15, 0x57, 0x4a, 0xe9, 0x50, 0x12, 0x1b, 0x81, 0x4b, 0x98, 0x98, 0xa8, 0x31, 0x1d, 0x27, 0x47, 0x38, 0xed, 0x57, 0x99, 0x26, 0xb2, 0xee}, - }, - { /* 29P*/ - addYX: fp.Elt{0x1c, 0xb2, 0xb2, 0x67, 0x3b, 0x8b, 0x3d, 0x5a, 0x30, 0x7e, 0x38, 0x7e, 0x3c, 0x3d, 0x28, 0x56, 0x59, 0xd8, 0x87, 0x53, 0x8b, 0xe6, 0x6c, 0x5d, 0xe5, 0x0a, 0x33, 0x10, 0xce, 0xa2, 0x17, 0x0d, 0xe8, 0x76, 0xee, 0x68, 0xa8, 0x72, 0x54, 0xbd, 0xa6, 0x24, 0x94, 0x6e, 0x77, 0xc7, 0x53, 0xb7, 0x89, 0x1c, 0x7a, 0xe9, 0x78, 0x9a, 0x74, 0x5f}, - subYX: fp.Elt{0x76, 0x96, 0x1c, 0xcf, 0x08, 0x55, 0xd8, 0x1e, 0x0d, 0xa3, 0x59, 0x95, 0x32, 0xf4, 0xc2, 0x8e, 0x84, 0x5e, 0x4b, 0x04, 0xda, 0x71, 0xc9, 0x78, 0x52, 0xde, 0x14, 0xb4, 0x31, 0xf4, 0xd4, 0xb8, 0x58, 0xc5, 0x20, 0xe8, 0xdd, 0x15, 0xb5, 0xee, 0xea, 0x61, 0xe0, 0xf5, 0xd6, 0xae, 0x55, 0x59, 0x05, 0x3e, 0xaf, 0x74, 0xac, 0x1f, 0x17, 0x82}, - dt2: fp.Elt{0x59, 0x24, 0xcd, 0xfc, 0x11, 0x7e, 0x85, 0x18, 0x3d, 0x69, 0xf7, 0x71, 0x31, 0x66, 0x98, 0x42, 0x95, 0x00, 0x8c, 0xb2, 0xae, 0x39, 0x7e, 0x85, 0xd6, 0xb0, 0x02, 0xec, 0xce, 0xfc, 0x25, 0xb2, 0xe3, 0x99, 0x8e, 0x5b, 0x61, 0x96, 0x2e, 0x6d, 0x96, 0x57, 0x71, 0xa5, 0x93, 0x41, 0x0e, 0x6f, 0xfd, 0x0a, 0xbf, 0xa9, 0xf7, 0x56, 0xa9, 0x3e}, - }, - { /* 31P*/ - addYX: fp.Elt{0xa2, 0x2e, 0x0c, 0x17, 0x4d, 0xcc, 0x85, 0x2c, 0x18, 0xa0, 0xd2, 0x08, 0xba, 0x11, 0xfa, 0x47, 0x71, 0x86, 0xaf, 0x36, 0x6a, 0xd7, 0xfe, 0xb9, 0xb0, 0x2f, 0x89, 0x98, 0x49, 0x69, 0xf8, 0x6a, 0xad, 0x27, 0x5e, 0x0a, 0x22, 0x60, 0x5e, 0x5d, 0xca, 0x06, 0x51, 0x27, 0x99, 0x29, 0x85, 0x68, 0x98, 0xe1, 0xc4, 0x21, 0x50, 0xa0, 0xe9, 0xc1}, - subYX: fp.Elt{0x4d, 0x70, 0xee, 0x91, 0x92, 0x3f, 0xb7, 0xd3, 0x1d, 0xdb, 0x8d, 0x6e, 0x16, 0xf5, 0x65, 0x7d, 0x5f, 0xb5, 0x6c, 0x59, 0x26, 0x70, 0x4b, 0xf2, 0xfc, 0xe7, 0xdf, 0x86, 0xfe, 0xa5, 0xa7, 0xa6, 0x5d, 0xfb, 0x06, 0xe9, 0xf9, 0xcc, 0xc0, 0x37, 0xcc, 0xd8, 0x09, 0x04, 0xd2, 0xa5, 0x1d, 0xd7, 0xb7, 0xce, 0x92, 0xac, 0x3c, 0xad, 0xfb, 0xae}, - dt2: fp.Elt{0x17, 0xa3, 0x9a, 0xc7, 0x86, 0x2a, 0x51, 0xf7, 0x96, 0x79, 0x49, 0x22, 0x2e, 0x5a, 0x01, 0x5c, 0xb5, 0x95, 0xd4, 0xe8, 0xcb, 0x00, 0xca, 0x2d, 0x55, 0xb6, 0x34, 0x36, 0x0b, 0x65, 0x46, 0xf0, 0x49, 0xfc, 0x87, 0x86, 0xe5, 0xc3, 0x15, 0xdb, 0x32, 0xcd, 0xf2, 0xd3, 0x82, 0x4c, 0xe6, 0x61, 0x8a, 0xaf, 0xd4, 0x9e, 0x0f, 0x5a, 0xf2, 0x81}, - }, - { /* 33P*/ - addYX: fp.Elt{0x88, 0x10, 0xc0, 0xcb, 0xf5, 0x77, 0xae, 0xa5, 0xbe, 0xf6, 0xcd, 0x2e, 0x8b, 0x7e, 0xbd, 0x79, 0x62, 0x4a, 0xeb, 0x69, 0xc3, 0x28, 0xaa, 0x72, 0x87, 0xa9, 0x25, 0x87, 0x46, 0xea, 0x0e, 0x62, 0xa3, 0x6a, 0x1a, 0xe2, 0xba, 0xdc, 0x81, 0x10, 0x33, 0x01, 0xf6, 0x16, 0x89, 0x80, 0xc6, 0xcd, 0xdb, 0xdc, 0xba, 0x0e, 0x09, 0x4a, 0x35, 0x4a}, - subYX: fp.Elt{0x86, 0xb2, 0x2b, 0xd0, 0xb8, 0x4a, 0x6d, 0x66, 0x7b, 0x32, 0xdf, 0x3b, 0x1a, 0x19, 0x1f, 0x63, 0xee, 0x1f, 0x3d, 0x1c, 0x5c, 0x14, 0x60, 0x5b, 0x72, 0x49, 0x07, 0xb1, 0x0d, 0x72, 0xc6, 0x35, 0xf0, 0xbc, 0x5e, 0xda, 0x80, 0x6b, 0x64, 0x5b, 0xe5, 0x34, 0x54, 0x39, 0xdd, 0xe6, 0x3c, 0xcb, 0xe5, 0x29, 0x32, 0x06, 0xc6, 0xb1, 0x96, 0x34}, - dt2: fp.Elt{0x85, 0x86, 0xf5, 0x84, 0x86, 0xe6, 0x77, 0x8a, 0x71, 0x85, 0x0c, 0x4f, 0x81, 0x5b, 0x29, 0x06, 0xb5, 0x2e, 0x26, 0x71, 0x07, 0x78, 0x07, 0xae, 0xbc, 0x95, 0x46, 0xc3, 0x65, 0xac, 0xe3, 0x76, 0x51, 0x7d, 0xd4, 0x85, 0x31, 0xe3, 0x43, 0xf3, 0x1b, 0x7c, 0xf7, 0x6b, 0x2c, 0xf8, 0x1c, 0xbb, 0x8d, 0xca, 0xab, 0x4b, 0xba, 0x7f, 0xa4, 0xe2}, - }, - { /* 35P*/ - addYX: fp.Elt{0x1a, 0xee, 0xe7, 0xa4, 0x8a, 0x9d, 0x53, 0x80, 0xc6, 0xb8, 0x4e, 0xdc, 0x89, 0xe0, 0xc4, 0x2b, 0x60, 0x52, 0x6f, 0xec, 0x81, 0xd2, 0x55, 0x6b, 0x1b, 0x6f, 0x17, 0x67, 0x8e, 0x42, 0x26, 0x4c, 0x65, 0x23, 0x29, 0xc6, 0x7b, 0xcd, 0x9f, 0xad, 0x4b, 0x42, 0xd3, 0x0c, 0x75, 0xc3, 0x8a, 0xf5, 0xbe, 0x9e, 0x55, 0xf7, 0x47, 0x5d, 0xbd, 0x3a}, - subYX: fp.Elt{0x0d, 0xa8, 0x3b, 0xf9, 0xc7, 0x7e, 0xc6, 0x86, 0x94, 0xc0, 0x01, 0xff, 0x27, 0xce, 0x43, 0xac, 0xe5, 0xe1, 0xd2, 0x8d, 0xc1, 0x22, 0x31, 0xbe, 0xe1, 0xaf, 0xf9, 0x4a, 0x78, 0xa1, 0x0c, 0xaa, 0xd4, 0x80, 0xe4, 0x09, 0x8d, 0xfb, 0x1d, 0x52, 0xc8, 0x60, 0x2d, 0xf2, 0xa2, 0x89, 0x02, 0x56, 0x3d, 0x56, 0x27, 0x85, 0xc7, 0xf0, 0x2b, 0x9a}, - dt2: fp.Elt{0x62, 0x7c, 0xc7, 0x6b, 0x2c, 0x9d, 0x0a, 0x7c, 0xe5, 0x50, 0x3c, 0xe6, 0x87, 0x1c, 0x82, 0x30, 0x67, 0x3c, 0x39, 0xb6, 0xa0, 0x31, 0xfb, 0x03, 0x7b, 0xa1, 0x58, 0xdf, 0x12, 0x76, 0x5d, 0x5d, 0x0a, 0x8f, 0x9b, 0x37, 0x32, 0xc3, 0x60, 0x33, 0xea, 0x9f, 0x0a, 0x99, 0xfa, 0x20, 0xd0, 0x33, 0x21, 0xc3, 0x94, 0xd4, 0x86, 0x49, 0x7c, 0x4e}, - }, - { /* 37P*/ - addYX: fp.Elt{0xc7, 0x0c, 0x71, 0xfe, 0x55, 0xd1, 0x95, 0x8f, 0x43, 0xbb, 0x6b, 0x74, 0x30, 0xbd, 0xe8, 0x6f, 0x1c, 0x1b, 0x06, 0x62, 0xf5, 0xfc, 0x65, 0xa0, 0xeb, 0x81, 0x12, 0xc9, 0x64, 0x66, 0x61, 0xde, 0xf3, 0x6d, 0xd4, 0xae, 0x8e, 0xb1, 0x72, 0xe0, 0xcd, 0x37, 0x01, 0x28, 0x52, 0xd7, 0x39, 0x46, 0x0c, 0x55, 0xcf, 0x47, 0x70, 0xef, 0xa1, 0x17}, - subYX: fp.Elt{0x8d, 0x58, 0xde, 0x83, 0x88, 0x16, 0x0e, 0x12, 0x42, 0x03, 0x50, 0x60, 0x4b, 0xdf, 0xbf, 0x95, 0xcc, 0x7d, 0x18, 0x17, 0x7e, 0x31, 0x5d, 0x8a, 0x66, 0xc1, 0xcf, 0x14, 0xea, 0xf4, 0xf4, 0xe5, 0x63, 0x2d, 0x32, 0x86, 0x9b, 0xed, 0x1f, 0x4f, 0x03, 0xaf, 0x33, 0x92, 0xcb, 0xaf, 0x9c, 0x05, 0x0d, 0x47, 0x1b, 0x42, 0xba, 0x13, 0x22, 0x98}, - dt2: fp.Elt{0xb5, 0x48, 0xeb, 0x7d, 0x3d, 0x10, 0x9f, 0x59, 0xde, 0xf8, 0x1c, 0x4f, 0x7d, 0x9d, 0x40, 0x4d, 0x9e, 0x13, 0x24, 0xb5, 0x21, 0x09, 0xb7, 0xee, 0x98, 0x5c, 0x56, 0xbc, 0x5e, 0x2b, 0x78, 0x38, 0x06, 0xac, 0xe3, 0xe0, 0xfa, 0x2e, 0xde, 0x4f, 0xd2, 0xb3, 0xfb, 0x2d, 0x71, 0x84, 0xd1, 0x9d, 0x12, 0x5b, 0x35, 0xc8, 0x03, 0x68, 0x67, 0xc7}, - }, - { /* 39P*/ - addYX: fp.Elt{0xb6, 0x65, 0xfb, 0xa7, 0x06, 0x35, 0xbb, 0xe0, 0x31, 0x8d, 0x91, 0x40, 0x98, 0xab, 0x30, 0xe4, 0xca, 0x12, 0x59, 0x89, 0xed, 0x65, 0x5d, 0x7f, 0xae, 0x69, 0xa0, 0xa4, 0xfa, 0x78, 0xb4, 0xf7, 0xed, 0xae, 0x86, 0x78, 0x79, 0x64, 0x24, 0xa6, 0xd4, 0xe1, 0xf6, 0xd3, 0xa0, 0x89, 0xba, 0x20, 0xf4, 0x54, 0x0d, 0x8f, 0xdb, 0x1a, 0x79, 0xdb}, - subYX: fp.Elt{0xe1, 0x82, 0x0c, 0x4d, 0xde, 0x9f, 0x40, 0xf0, 0xc1, 0xbd, 0x8b, 0xd3, 0x24, 0x03, 0xcd, 0xf2, 0x92, 0x7d, 0xe2, 0x68, 0x7f, 0xf1, 0xbe, 0x69, 0xde, 0x34, 0x67, 0x4c, 0x85, 0x3b, 0xec, 0x98, 0xcc, 0x4d, 0x3e, 0xc0, 0x96, 0x27, 0xe6, 0x75, 0xfc, 0xdf, 0x37, 0xc0, 0x1e, 0x27, 0xe0, 0xf6, 0xc2, 0xbd, 0xbc, 0x3d, 0x9b, 0x39, 0xdc, 0xe2}, - dt2: fp.Elt{0xd8, 0x29, 0xa7, 0x39, 0xe3, 0x9f, 0x2f, 0x0e, 0x4b, 0x24, 0x21, 0x70, 0xef, 0xfd, 0x91, 0xea, 0xbf, 0xe1, 0x72, 0x90, 0xcc, 0xc9, 0x84, 0x0e, 0xad, 0xd5, 0xe6, 0xbb, 0xc5, 0x99, 0x7f, 0xa4, 0xf0, 0x2e, 0xcc, 0x95, 0x64, 0x27, 0x19, 0xd8, 0x4c, 0x27, 0x0d, 0xff, 0xb6, 0x29, 0xe2, 0x6c, 0xfa, 0xbb, 0x4d, 0x9c, 0xbb, 0xaf, 0xa5, 0xec}, - }, - { /* 41P*/ - addYX: fp.Elt{0xd6, 0x33, 0x3f, 0x9f, 0xcf, 0xfd, 0x4c, 0xd1, 0xfe, 0xe5, 0xeb, 0x64, 0x27, 0xae, 0x7a, 0xa2, 0x82, 0x50, 0x6d, 0xaa, 0xe3, 0x5d, 0xe2, 0x48, 0x60, 0xb3, 0x76, 0x04, 0xd9, 0x19, 0xa7, 0xa1, 0x73, 0x8d, 0x38, 0xa9, 0xaf, 0x45, 0xb5, 0xb2, 0x62, 0x9b, 0xf1, 0x35, 0x7b, 0x84, 0x66, 0xeb, 0x06, 0xef, 0xf1, 0xb2, 0x2d, 0x6a, 0x61, 0x15}, - subYX: fp.Elt{0x86, 0x50, 0x42, 0xf7, 0xda, 0x59, 0xb2, 0xcf, 0x0d, 0x3d, 0xee, 0x8e, 0x53, 0x5d, 0xf7, 0x9e, 0x6a, 0x26, 0x2d, 0xc7, 0x8c, 0x8e, 0x18, 0x50, 0x6d, 0xb7, 0x51, 0x4c, 0xa7, 0x52, 0x6e, 0x0e, 0x0a, 0x16, 0x74, 0xb2, 0x81, 0x8b, 0x56, 0x27, 0x22, 0x84, 0xf4, 0x56, 0xc5, 0x06, 0xe1, 0x8b, 0xca, 0x2d, 0xdb, 0x9a, 0xf6, 0x10, 0x9c, 0x51}, - dt2: fp.Elt{0x1f, 0x16, 0xa2, 0x78, 0x96, 0x1b, 0x85, 0x9c, 0x76, 0x49, 0xd4, 0x0f, 0xac, 0xb0, 0xf4, 0xd0, 0x06, 0x2c, 0x7e, 0x6d, 0x6e, 0x8e, 0xc7, 0x9f, 0x18, 0xad, 0xfc, 0x88, 0x0c, 0x0c, 0x09, 0x05, 0x05, 0xa0, 0x79, 0x72, 0x32, 0x72, 0x87, 0x0f, 0x49, 0x87, 0x0c, 0xb4, 0x12, 0xc2, 0x09, 0xf8, 0x9f, 0x30, 0x72, 0xa9, 0x47, 0x13, 0x93, 0x49}, - }, - { /* 43P*/ - addYX: fp.Elt{0xcc, 0xb1, 0x4c, 0xd3, 0xc0, 0x9e, 0x9e, 0x4d, 0x6d, 0x28, 0x0b, 0xa5, 0x94, 0xa7, 0x2e, 0xc2, 0xc7, 0xaf, 0x29, 0x73, 0xc9, 0x68, 0xea, 0x0f, 0x34, 0x37, 0x8d, 0x96, 0x8f, 0x3a, 0x3d, 0x73, 0x1e, 0x6d, 0x9f, 0xcf, 0x8d, 0x83, 0xb5, 0x71, 0xb9, 0xe1, 0x4b, 0x67, 0x71, 0xea, 0xcf, 0x56, 0xe5, 0xeb, 0x72, 0x15, 0x2f, 0x9e, 0xa8, 0xaa}, - subYX: fp.Elt{0xf4, 0x3e, 0x85, 0x1c, 0x1a, 0xef, 0x50, 0xd1, 0xb4, 0x20, 0xb2, 0x60, 0x05, 0x98, 0xfe, 0x47, 0x3b, 0xc1, 0x76, 0xca, 0x2c, 0x4e, 0x5a, 0x42, 0xa3, 0xf7, 0x20, 0xaa, 0x57, 0x39, 0xee, 0x34, 0x1f, 0xe1, 0x68, 0xd3, 0x7e, 0x06, 0xc4, 0x6c, 0xc7, 0x76, 0x2b, 0xe4, 0x1c, 0x48, 0x44, 0xe6, 0xe5, 0x44, 0x24, 0x8d, 0xb3, 0xb6, 0x88, 0x32}, - dt2: fp.Elt{0x18, 0xa7, 0xba, 0xd0, 0x44, 0x6f, 0x33, 0x31, 0x00, 0xf8, 0xf6, 0x12, 0xe3, 0xc5, 0xc7, 0xb5, 0x91, 0x9c, 0x91, 0xb5, 0x75, 0x18, 0x18, 0x8a, 0xab, 0xed, 0x24, 0x11, 0x2e, 0xce, 0x5a, 0x0f, 0x94, 0x5f, 0x2e, 0xca, 0xd3, 0x80, 0xea, 0xe5, 0x34, 0x96, 0x67, 0x8b, 0x6a, 0x26, 0x5e, 0xc8, 0x9d, 0x2c, 0x5e, 0x6c, 0xa2, 0x0c, 0xbf, 0xf0}, - }, - { /* 45P*/ - addYX: fp.Elt{0xb3, 0xbf, 0xa3, 0x85, 0xee, 0xf6, 0x58, 0x02, 0x78, 0xc4, 0x30, 0xd6, 0x57, 0x59, 0x8c, 0x88, 0x08, 0x7c, 0xbc, 0xbe, 0x0a, 0x74, 0xa9, 0xde, 0x69, 0xe7, 0x41, 0xd8, 0xbf, 0x66, 0x8d, 0x3d, 0x28, 0x00, 0x8c, 0x47, 0x65, 0x34, 0xfe, 0x86, 0x9e, 0x6a, 0xf2, 0x41, 0x6a, 0x94, 0xc4, 0x88, 0x75, 0x23, 0x0d, 0x52, 0x69, 0xee, 0x07, 0x89}, - subYX: fp.Elt{0x22, 0x3c, 0xa1, 0x70, 0x58, 0x97, 0x93, 0xbe, 0x59, 0xa8, 0x0b, 0x8a, 0x46, 0x2a, 0x38, 0x1e, 0x08, 0x6b, 0x61, 0x9f, 0xf2, 0x4a, 0x8b, 0x80, 0x68, 0x6e, 0xc8, 0x92, 0x60, 0xf3, 0xc9, 0x89, 0xb2, 0x6d, 0x63, 0xb0, 0xeb, 0x83, 0x15, 0x63, 0x0e, 0x64, 0xbb, 0xb8, 0xfe, 0xb4, 0x81, 0x90, 0x01, 0x28, 0x10, 0xb9, 0x74, 0x6e, 0xde, 0xa4}, - dt2: fp.Elt{0x1a, 0x23, 0x45, 0xa8, 0x6f, 0x4e, 0xa7, 0x4a, 0x0c, 0xeb, 0xb0, 0x43, 0xf9, 0xef, 0x99, 0x60, 0x5b, 0xdb, 0x66, 0xc0, 0x86, 0x71, 0x43, 0xb1, 0x22, 0x7b, 0x1c, 0xe7, 0x8d, 0x09, 0x1d, 0x83, 0x76, 0x9c, 0xd3, 0x5a, 0xdd, 0x42, 0xd9, 0x2f, 0x2d, 0xba, 0x7a, 0xc2, 0xd9, 0x6b, 0xd4, 0x7a, 0xf1, 0xd5, 0x5f, 0x6b, 0x85, 0xbf, 0x0b, 0xf1}, - }, - { /* 47P*/ - addYX: fp.Elt{0xb2, 0x83, 0xfa, 0x1f, 0xd2, 0xce, 0xb6, 0xf2, 0x2d, 0xea, 0x1b, 0xe5, 0x29, 0xa5, 0x72, 0xf9, 0x25, 0x48, 0x4e, 0xf2, 0x50, 0x1b, 0x39, 0xda, 0x34, 0xc5, 0x16, 0x13, 0xb4, 0x0c, 0xa1, 0x00, 0x79, 0x7a, 0xf5, 0x8b, 0xf3, 0x70, 0x14, 0xb6, 0xfc, 0x9a, 0x47, 0x68, 0x1e, 0x42, 0x70, 0x64, 0x2a, 0x84, 0x3e, 0x3d, 0x20, 0x58, 0xf9, 0x6a}, - subYX: fp.Elt{0xd9, 0xee, 0xc0, 0xc4, 0xf5, 0xc2, 0x86, 0xaf, 0x45, 0xd2, 0xd2, 0x87, 0x1b, 0x64, 0xd5, 0xe0, 0x8c, 0x44, 0x00, 0x4f, 0x43, 0x89, 0x04, 0x48, 0x4a, 0x0b, 0xca, 0x94, 0x06, 0x2f, 0x23, 0x5b, 0x6c, 0x8d, 0x44, 0x66, 0x53, 0xf5, 0x5a, 0x20, 0x72, 0x28, 0x58, 0x84, 0xcc, 0x73, 0x22, 0x5e, 0xd1, 0x0b, 0x56, 0x5e, 0x6a, 0xa3, 0x11, 0x91}, - dt2: fp.Elt{0x6e, 0x9f, 0x88, 0xa8, 0x68, 0x2f, 0x12, 0x37, 0x88, 0xfc, 0x92, 0x8f, 0x24, 0xeb, 0x5b, 0x2a, 0x2a, 0xd0, 0x14, 0x40, 0x4c, 0xa9, 0xa4, 0x03, 0x0c, 0x45, 0x48, 0x13, 0xe8, 0xa6, 0x37, 0xab, 0xc0, 0x06, 0x38, 0x6c, 0x96, 0x73, 0x40, 0x6c, 0xc6, 0xea, 0x56, 0xc6, 0xe9, 0x1a, 0x69, 0xeb, 0x7a, 0xd1, 0x33, 0x69, 0x58, 0x2b, 0xea, 0x2f}, - }, - { /* 49P*/ - addYX: fp.Elt{0x58, 0xa8, 0x05, 0x41, 0x00, 0x9d, 0xaa, 0xd9, 0x98, 0xcf, 0xb9, 0x41, 0xb5, 0x4a, 0x8d, 0xe2, 0xe7, 0xc0, 0x72, 0xef, 0xc8, 0x28, 0x6b, 0x68, 0x9d, 0xc9, 0xdf, 0x05, 0x8b, 0xd0, 0x04, 0x74, 0x79, 0x45, 0x52, 0x05, 0xa3, 0x6e, 0x35, 0x3a, 0xe3, 0xef, 0xb2, 0xdc, 0x08, 0x6f, 0x4e, 0x76, 0x85, 0x67, 0xba, 0x23, 0x8f, 0xdd, 0xaf, 0x09}, - subYX: fp.Elt{0xb4, 0x38, 0xc8, 0xff, 0x4f, 0x65, 0x2a, 0x7e, 0xad, 0xb1, 0xc6, 0xb9, 0x3d, 0xd6, 0xf7, 0x14, 0xcf, 0xf6, 0x98, 0x75, 0xbb, 0x47, 0x83, 0x90, 0xe7, 0xe1, 0xf6, 0x14, 0x99, 0x7e, 0xfa, 0xe4, 0x77, 0x24, 0xe3, 0xe7, 0xf0, 0x1e, 0xdb, 0x27, 0x4e, 0x16, 0x04, 0xf2, 0x08, 0x52, 0xfc, 0xec, 0x55, 0xdb, 0x2e, 0x67, 0xe1, 0x94, 0x32, 0x89}, - dt2: fp.Elt{0x00, 0xad, 0x03, 0x35, 0x1a, 0xb1, 0x88, 0xf0, 0xc9, 0x11, 0xe4, 0x12, 0x52, 0x61, 0xfd, 0x8a, 0x1b, 0x6a, 0x0a, 0x4c, 0x42, 0x46, 0x22, 0x0e, 0xa5, 0xf9, 0xe2, 0x50, 0xf2, 0xb2, 0x1f, 0x20, 0x78, 0x10, 0xf6, 0xbf, 0x7f, 0x0c, 0x9c, 0xad, 0x40, 0x8b, 0x82, 0xd4, 0xba, 0x69, 0x09, 0xac, 0x4b, 0x6d, 0xc4, 0x49, 0x17, 0x81, 0x57, 0x3b}, - }, - { /* 51P*/ - addYX: fp.Elt{0x0d, 0xfe, 0xb4, 0x35, 0x11, 0xbd, 0x1d, 0x6b, 0xc2, 0xc5, 0x3b, 0xd2, 0x23, 0x2c, 0x72, 0xe3, 0x48, 0xb1, 0x48, 0x73, 0xfb, 0xa3, 0x21, 0x6e, 0xc0, 0x09, 0x69, 0xac, 0xe1, 0x60, 0xbc, 0x24, 0x03, 0x99, 0x63, 0x0a, 0x00, 0xf0, 0x75, 0xf6, 0x92, 0xc5, 0xd6, 0xdb, 0x51, 0xd4, 0x7d, 0xe6, 0xf4, 0x11, 0x79, 0xd7, 0xc3, 0xaf, 0x48, 0xd0}, - subYX: fp.Elt{0xf4, 0x4f, 0xaf, 0x31, 0xe3, 0x10, 0x89, 0x95, 0xf0, 0x8a, 0xf6, 0x31, 0x9f, 0x48, 0x02, 0xba, 0x42, 0x2b, 0x3c, 0x22, 0x8b, 0xcc, 0x12, 0x98, 0x6e, 0x7a, 0x64, 0x3a, 0xc4, 0xca, 0x32, 0x2a, 0x72, 0xf8, 0x2c, 0xcf, 0x78, 0x5e, 0x7a, 0x75, 0x6e, 0x72, 0x46, 0x48, 0x62, 0x28, 0xac, 0x58, 0x1a, 0xc6, 0x59, 0x88, 0x2a, 0x44, 0x9e, 0x83}, - dt2: fp.Elt{0xb3, 0xde, 0x36, 0xfd, 0xeb, 0x1b, 0xd4, 0x24, 0x1b, 0x08, 0x8c, 0xfe, 0xa9, 0x41, 0xa1, 0x64, 0xf2, 0x6d, 0xdb, 0xf9, 0x94, 0xae, 0x86, 0x71, 0xab, 0x10, 0xbf, 0xa3, 0xb2, 0xa0, 0xdf, 0x10, 0x8c, 0x74, 0xce, 0xb3, 0xfc, 0xdb, 0xba, 0x15, 0xf6, 0x91, 0x7a, 0x9c, 0x36, 0x1e, 0x45, 0x07, 0x3c, 0xec, 0x1a, 0x61, 0x26, 0x93, 0xe3, 0x50}, - }, - { /* 53P*/ - addYX: fp.Elt{0xc5, 0x50, 0xc5, 0x83, 0xb0, 0xbd, 0xd9, 0xf6, 0x6d, 0x15, 0x5e, 0xc1, 0x1a, 0x33, 0xa0, 0xce, 0x13, 0x70, 0x3b, 0xe1, 0x31, 0xc6, 0xc4, 0x02, 0xec, 0x8c, 0xd5, 0x9c, 0x97, 0xd3, 0x12, 0xc4, 0xa2, 0xf9, 0xd5, 0xfb, 0x22, 0x69, 0x94, 0x09, 0x2f, 0x59, 0xce, 0xdb, 0xf2, 0xf2, 0x00, 0xe0, 0xa9, 0x08, 0x44, 0x2e, 0x8b, 0x6b, 0xf5, 0xb3}, - subYX: fp.Elt{0x90, 0xdd, 0xec, 0xa2, 0x65, 0xb7, 0x61, 0xbc, 0xaa, 0x70, 0xa2, 0x15, 0xd8, 0xb0, 0xf8, 0x8e, 0x23, 0x3d, 0x9f, 0x46, 0xa3, 0x29, 0x20, 0xd1, 0xa1, 0x15, 0x81, 0xc6, 0xb6, 0xde, 0xbe, 0x60, 0x63, 0x24, 0xac, 0x15, 0xfb, 0xeb, 0xd3, 0xea, 0x57, 0x13, 0x86, 0x38, 0x1e, 0x22, 0xf4, 0x8c, 0x5d, 0xaf, 0x1b, 0x27, 0x21, 0x4f, 0xa3, 0x63}, - dt2: fp.Elt{0x07, 0x15, 0x87, 0xc4, 0xfd, 0xa1, 0x97, 0x7a, 0x07, 0x1f, 0x56, 0xcc, 0xe3, 0x6a, 0x01, 0x90, 0xce, 0xf9, 0xfa, 0x50, 0xb2, 0xe0, 0x87, 0x8b, 0x6c, 0x63, 0x6c, 0xf6, 0x2a, 0x09, 0xef, 0xef, 0xd2, 0x31, 0x40, 0x25, 0xf6, 0x84, 0xcb, 0xe0, 0xc4, 0x23, 0xc1, 0xcb, 0xe2, 0x02, 0x83, 0x2d, 0xed, 0x74, 0x74, 0x8b, 0xf8, 0x7c, 0x81, 0x18}, - }, - { /* 55P*/ - addYX: fp.Elt{0x9e, 0xe5, 0x59, 0x95, 0x63, 0x2e, 0xac, 0x8b, 0x03, 0x3c, 0xc1, 0x8e, 0xe1, 0x5b, 0x56, 0x3c, 0x16, 0x41, 0xe4, 0xc2, 0x60, 0x0c, 0x6d, 0x65, 0x9f, 0xfc, 0x27, 0x68, 0x43, 0x44, 0x05, 0x12, 0x6c, 0xda, 0x04, 0xef, 0xcf, 0xcf, 0xdc, 0x0a, 0x1a, 0x7f, 0x12, 0xd3, 0xeb, 0x02, 0xb6, 0x04, 0xca, 0xd6, 0xcb, 0xf0, 0x22, 0xba, 0x35, 0x6d}, - subYX: fp.Elt{0x09, 0x6d, 0xf9, 0x64, 0x4c, 0xe6, 0x41, 0xff, 0x01, 0x4d, 0xce, 0x1e, 0xfa, 0x38, 0xa2, 0x25, 0x62, 0xff, 0x03, 0x39, 0x18, 0x91, 0xbb, 0x9d, 0xce, 0x02, 0xf0, 0xf1, 0x3c, 0x55, 0x18, 0xa9, 0xab, 0x4d, 0xd2, 0x35, 0xfd, 0x8d, 0xa9, 0xb2, 0xad, 0xb7, 0x06, 0x6e, 0xc6, 0x69, 0x49, 0xd6, 0x98, 0x98, 0x0b, 0x22, 0x81, 0x6b, 0xbd, 0xa0}, - dt2: fp.Elt{0x22, 0xf4, 0x85, 0x5d, 0x2b, 0xf1, 0x55, 0xa5, 0xd6, 0x27, 0x86, 0x57, 0x12, 0x1f, 0x16, 0x0a, 0x5a, 0x9b, 0xf2, 0x38, 0xb6, 0x28, 0xd8, 0x99, 0x0c, 0x89, 0x1d, 0x7f, 0xca, 0x21, 0x17, 0x1a, 0x0b, 0x02, 0x5f, 0x77, 0x2f, 0x73, 0x30, 0x7c, 0xc8, 0xd7, 0x2b, 0xcc, 0xe7, 0xf3, 0x21, 0xac, 0x53, 0xa7, 0x11, 0x5d, 0xd8, 0x1d, 0x9b, 0xf5}, - }, - { /* 57P*/ - addYX: fp.Elt{0x94, 0x63, 0x5d, 0xef, 0xfd, 0x6d, 0x25, 0x4e, 0x6d, 0x29, 0x03, 0xed, 0x24, 0x28, 0x27, 0x57, 0x47, 0x3e, 0x6a, 0x1a, 0xfe, 0x37, 0xee, 0x5f, 0x83, 0x29, 0x14, 0xfd, 0x78, 0x25, 0x8a, 0xe1, 0x02, 0x38, 0xd8, 0xca, 0x65, 0x55, 0x40, 0x7d, 0x48, 0x2c, 0x7c, 0x7e, 0x60, 0xb6, 0x0c, 0x6d, 0xf7, 0xe8, 0xb3, 0x62, 0x53, 0xd6, 0x9c, 0x2b}, - subYX: fp.Elt{0x47, 0x25, 0x70, 0x62, 0xf5, 0x65, 0x93, 0x62, 0x08, 0xac, 0x59, 0x66, 0xdb, 0x08, 0xd9, 0x1a, 0x19, 0xaf, 0xf4, 0xef, 0x02, 0xa2, 0x78, 0xa9, 0x55, 0x1c, 0xfa, 0x08, 0x11, 0xcb, 0xa3, 0x71, 0x74, 0xb1, 0x62, 0xe7, 0xc7, 0xf3, 0x5a, 0xb5, 0x8b, 0xd4, 0xf6, 0x10, 0x57, 0x79, 0x72, 0x2f, 0x13, 0x86, 0x7b, 0x44, 0x5f, 0x48, 0xfd, 0x88}, - dt2: fp.Elt{0x10, 0x02, 0xcd, 0x05, 0x9a, 0xc3, 0x32, 0x6d, 0x10, 0x3a, 0x74, 0xba, 0x06, 0xc4, 0x3b, 0x34, 0xbc, 0x36, 0xed, 0xa3, 0xba, 0x9a, 0xdb, 0x6d, 0xd4, 0x69, 0x99, 0x97, 0xd0, 0xe4, 0xdd, 0xf5, 0xd4, 0x7c, 0xd3, 0x4e, 0xab, 0xd1, 0x3b, 0xbb, 0xe9, 0xc7, 0x6a, 0x94, 0x25, 0x61, 0xf0, 0x06, 0xc5, 0x12, 0xa8, 0x86, 0xe5, 0x35, 0x46, 0xeb}, - }, - { /* 59P*/ - addYX: fp.Elt{0x9e, 0x95, 0x11, 0xc6, 0xc7, 0xe8, 0xee, 0x5a, 0x26, 0xa0, 0x72, 0x72, 0x59, 0x91, 0x59, 0x16, 0x49, 0x99, 0x7e, 0xbb, 0xd7, 0x15, 0xb4, 0xf2, 0x40, 0xf9, 0x5a, 0x4d, 0xc8, 0xa0, 0xe2, 0x34, 0x7b, 0x34, 0xf3, 0x99, 0xbf, 0xa9, 0xf3, 0x79, 0xc1, 0x1a, 0x0c, 0xf4, 0x86, 0x74, 0x4e, 0xcb, 0xbc, 0x90, 0xad, 0xb6, 0x51, 0x6d, 0xaa, 0x33}, - subYX: fp.Elt{0x9f, 0xd1, 0xc5, 0xa2, 0x6c, 0x24, 0x88, 0x15, 0x71, 0x68, 0xf6, 0x07, 0x45, 0x02, 0xc4, 0x73, 0x7e, 0x75, 0x87, 0xca, 0x7c, 0xf0, 0x92, 0x00, 0x75, 0xd6, 0x5a, 0xdd, 0xe0, 0x64, 0x16, 0x9d, 0x62, 0x80, 0x33, 0x9f, 0xf4, 0x8e, 0x1a, 0x15, 0x1c, 0xd3, 0x0f, 0x4d, 0x4f, 0x62, 0x2d, 0xd7, 0xa5, 0x77, 0xe3, 0xea, 0xf0, 0xfb, 0x1a, 0xdb}, - dt2: fp.Elt{0x6a, 0xa2, 0xb1, 0xaa, 0xfb, 0x5a, 0x32, 0x4e, 0xff, 0x47, 0x06, 0xd5, 0x9a, 0x4f, 0xce, 0x83, 0x5b, 0x82, 0x34, 0x3e, 0x47, 0xb8, 0xf8, 0xe9, 0x7c, 0x67, 0x69, 0x8d, 0x9c, 0xb7, 0xde, 0x57, 0xf4, 0x88, 0x41, 0x56, 0x0c, 0x87, 0x1e, 0xc9, 0x2f, 0x54, 0xbf, 0x5c, 0x68, 0x2c, 0xd9, 0xc4, 0xef, 0x53, 0x73, 0x1e, 0xa6, 0x38, 0x02, 0x10}, - }, - { /* 61P*/ - addYX: fp.Elt{0x08, 0x80, 0x4a, 0xc9, 0xb7, 0xa8, 0x88, 0xd9, 0xfc, 0x6a, 0xc0, 0x3e, 0xc2, 0x33, 0x4d, 0x2b, 0x2a, 0xa3, 0x6d, 0x72, 0x3e, 0xdc, 0x34, 0x68, 0x08, 0xbf, 0x27, 0xef, 0xf4, 0xff, 0xe2, 0x0c, 0x31, 0x0c, 0xa2, 0x0a, 0x1f, 0x65, 0xc1, 0x4c, 0x61, 0xd3, 0x1b, 0xbc, 0x25, 0xb1, 0xd0, 0xd4, 0x89, 0xb2, 0x53, 0xfb, 0x43, 0xa5, 0xaf, 0x04}, - subYX: fp.Elt{0xe3, 0xe1, 0x37, 0xad, 0x58, 0xa9, 0x55, 0x81, 0xee, 0x64, 0x21, 0xb9, 0xf5, 0x4c, 0x35, 0xea, 0x4a, 0xd3, 0x26, 0xaa, 0x90, 0xd4, 0x60, 0x46, 0x09, 0x4b, 0x4a, 0x62, 0xf9, 0xcd, 0xe1, 0xee, 0xbb, 0xc2, 0x09, 0x0b, 0xb0, 0x96, 0x8e, 0x43, 0x77, 0xaf, 0x25, 0x20, 0x5e, 0x47, 0xe4, 0x1d, 0x50, 0x69, 0x74, 0x08, 0xd7, 0xb9, 0x90, 0x13}, - dt2: fp.Elt{0x51, 0x91, 0x95, 0x64, 0x03, 0x16, 0xfd, 0x6e, 0x26, 0x94, 0x6b, 0x61, 0xe7, 0xd9, 0xe0, 0x4a, 0x6d, 0x7c, 0xfa, 0xc0, 0xe2, 0x43, 0x23, 0x53, 0x70, 0xf5, 0x6f, 0x73, 0x8b, 0x81, 0xb0, 0x0c, 0xee, 0x2e, 0x46, 0xf2, 0x8d, 0xa6, 0xfb, 0xb5, 0x1c, 0x33, 0xbf, 0x90, 0x59, 0xc9, 0x7c, 0xb8, 0x6f, 0xad, 0x75, 0x02, 0x90, 0x8e, 0x59, 0x75}, - }, - { /* 63P*/ - addYX: fp.Elt{0x36, 0x4d, 0x77, 0x04, 0xb8, 0x7d, 0x4a, 0xd1, 0xc5, 0xbb, 0x7b, 0x50, 0x5f, 0x8d, 0x9d, 0x62, 0x0f, 0x66, 0x71, 0xec, 0x87, 0xc5, 0x80, 0x82, 0xc8, 0xf4, 0x6a, 0x94, 0x92, 0x5b, 0xb0, 0x16, 0x9b, 0xb2, 0xc9, 0x6f, 0x2b, 0x2d, 0xee, 0x95, 0x73, 0x2e, 0xc2, 0x1b, 0xc5, 0x55, 0x36, 0x86, 0x24, 0xf8, 0x20, 0x05, 0x0d, 0x93, 0xd7, 0x76}, - subYX: fp.Elt{0x7f, 0x01, 0xeb, 0x2e, 0x48, 0x4d, 0x1d, 0xf1, 0x06, 0x7e, 0x7c, 0x2a, 0x43, 0xbf, 0x28, 0xac, 0xe9, 0x58, 0x13, 0xc8, 0xbf, 0x8e, 0xc0, 0xef, 0xe8, 0x4f, 0x46, 0x8a, 0xe7, 0xc0, 0xf6, 0x0f, 0x0a, 0x03, 0x48, 0x91, 0x55, 0x39, 0x2a, 0xe3, 0xdc, 0xf6, 0x22, 0x9d, 0x4d, 0x71, 0x55, 0x68, 0x25, 0x6e, 0x95, 0x52, 0xee, 0x4c, 0xd9, 0x01}, - dt2: fp.Elt{0xac, 0x33, 0x3f, 0x7c, 0x27, 0x35, 0x15, 0x91, 0x33, 0x8d, 0xf9, 0xc4, 0xf4, 0xf3, 0x90, 0x09, 0x75, 0x69, 0x62, 0x9f, 0x61, 0x35, 0x83, 0x92, 0x04, 0xef, 0x96, 0x38, 0x80, 0x9e, 0x88, 0xb3, 0x67, 0x95, 0xbe, 0x79, 0x3c, 0x35, 0xd8, 0xdc, 0xb2, 0x3e, 0x2d, 0xe6, 0x46, 0xbe, 0x81, 0xf3, 0x32, 0x0e, 0x37, 0x23, 0x75, 0x2a, 0x3d, 0xa0}, - }, -} diff --git a/vendor/github.com/cloudflare/circl/ecc/goldilocks/twist_basemult.go b/vendor/github.com/cloudflare/circl/ecc/goldilocks/twist_basemult.go deleted file mode 100644 index f6ac5edb..00000000 --- a/vendor/github.com/cloudflare/circl/ecc/goldilocks/twist_basemult.go +++ /dev/null @@ -1,62 +0,0 @@ -package goldilocks - -import ( - "crypto/subtle" - - mlsb "github.com/cloudflare/circl/math/mlsbset" -) - -const ( - // MLSBRecoding parameters - fxT = 448 - fxV = 2 - fxW = 3 - fx2w1 = 1 << (uint(fxW) - 1) -) - -// ScalarBaseMult returns kG where G is the generator point. -func (e twistCurve) ScalarBaseMult(k *Scalar) *twistPoint { - m, err := mlsb.New(fxT, fxV, fxW) - if err != nil { - panic(err) - } - if m.IsExtended() { - panic("not extended") - } - - var isZero int - if k.IsZero() { - isZero = 1 - } - subtle.ConstantTimeCopy(isZero, k[:], order[:]) - - minusK := *k - isEven := 1 - int(k[0]&0x1) - minusK.Neg() - subtle.ConstantTimeCopy(isEven, k[:], minusK[:]) - c, err := m.Encode(k[:]) - if err != nil { - panic(err) - } - - gP := c.Exp(groupMLSB{}) - P := gP.(*twistPoint) - P.cneg(uint(isEven)) - return P -} - -type groupMLSB struct{} - -func (e groupMLSB) ExtendedEltP() mlsb.EltP { return nil } -func (e groupMLSB) Sqr(x mlsb.EltG) { x.(*twistPoint).Double() } -func (e groupMLSB) Mul(x mlsb.EltG, y mlsb.EltP) { x.(*twistPoint).mixAddZ1(y.(*preTwistPointAffine)) } -func (e groupMLSB) Identity() mlsb.EltG { return twistCurve{}.Identity() } -func (e groupMLSB) NewEltP() mlsb.EltP { return &preTwistPointAffine{} } -func (e groupMLSB) Lookup(a mlsb.EltP, v uint, s, u int32) { - Tabj := &tabFixMult[v] - P := a.(*preTwistPointAffine) - for k := range Tabj { - P.cmov(&Tabj[k], uint(subtle.ConstantTimeEq(int32(k), u))) - } - P.cneg(int(s >> 31)) -} diff --git a/vendor/github.com/cloudflare/circl/internal/conv/conv.go b/vendor/github.com/cloudflare/circl/internal/conv/conv.go deleted file mode 100644 index 649a8e93..00000000 --- a/vendor/github.com/cloudflare/circl/internal/conv/conv.go +++ /dev/null @@ -1,140 +0,0 @@ -package conv - -import ( - "encoding/binary" - "fmt" - "math/big" - "strings" -) - -// BytesLe2Hex returns an hexadecimal string of a number stored in a -// little-endian order slice x. -func BytesLe2Hex(x []byte) string { - b := &strings.Builder{} - b.Grow(2*len(x) + 2) - fmt.Fprint(b, "0x") - if len(x) == 0 { - fmt.Fprint(b, "00") - } - for i := len(x) - 1; i >= 0; i-- { - fmt.Fprintf(b, "%02x", x[i]) - } - return b.String() -} - -// BytesLe2BigInt converts a little-endian slice x into a big-endian -// math/big.Int. -func BytesLe2BigInt(x []byte) *big.Int { - n := len(x) - b := new(big.Int) - if len(x) > 0 { - y := make([]byte, n) - for i := 0; i < n; i++ { - y[n-1-i] = x[i] - } - b.SetBytes(y) - } - return b -} - -// BytesBe2Uint64Le converts a big-endian slice x to a little-endian slice of uint64. -func BytesBe2Uint64Le(x []byte) []uint64 { - l := len(x) - z := make([]uint64, (l+7)/8) - blocks := l / 8 - for i := 0; i < blocks; i++ { - z[i] = binary.BigEndian.Uint64(x[l-8*(i+1):]) - } - remBytes := l % 8 - for i := 0; i < remBytes; i++ { - z[blocks] |= uint64(x[l-1-8*blocks-i]) << uint(8*i) - } - return z -} - -// BigInt2BytesLe stores a positive big.Int number x into a little-endian slice z. -// The slice is modified if the bitlength of x <= 8*len(z) (padding with zeros). -// If x does not fit in the slice or is negative, z is not modified. -func BigInt2BytesLe(z []byte, x *big.Int) { - xLen := (x.BitLen() + 7) >> 3 - zLen := len(z) - if zLen >= xLen && x.Sign() >= 0 { - y := x.Bytes() - for i := 0; i < xLen; i++ { - z[i] = y[xLen-1-i] - } - for i := xLen; i < zLen; i++ { - z[i] = 0 - } - } -} - -// Uint64Le2BigInt converts a little-endian slice x into a big number. -func Uint64Le2BigInt(x []uint64) *big.Int { - n := len(x) - b := new(big.Int) - var bi big.Int - for i := n - 1; i >= 0; i-- { - bi.SetUint64(x[i]) - b.Lsh(b, 64) - b.Add(b, &bi) - } - return b -} - -// Uint64Le2BytesLe converts a little-endian slice x to a little-endian slice of bytes. -func Uint64Le2BytesLe(x []uint64) []byte { - b := make([]byte, 8*len(x)) - n := len(x) - for i := 0; i < n; i++ { - binary.LittleEndian.PutUint64(b[i*8:], x[i]) - } - return b -} - -// Uint64Le2BytesBe converts a little-endian slice x to a big-endian slice of bytes. -func Uint64Le2BytesBe(x []uint64) []byte { - b := make([]byte, 8*len(x)) - n := len(x) - for i := 0; i < n; i++ { - binary.BigEndian.PutUint64(b[i*8:], x[n-1-i]) - } - return b -} - -// Uint64Le2Hex returns an hexadecimal string of a number stored in a -// little-endian order slice x. -func Uint64Le2Hex(x []uint64) string { - b := new(strings.Builder) - b.Grow(16*len(x) + 2) - fmt.Fprint(b, "0x") - if len(x) == 0 { - fmt.Fprint(b, "00") - } - for i := len(x) - 1; i >= 0; i-- { - fmt.Fprintf(b, "%016x", x[i]) - } - return b.String() -} - -// BigInt2Uint64Le stores a positive big.Int number x into a little-endian slice z. -// The slice is modified if the bitlength of x <= 8*len(z) (padding with zeros). -// If x does not fit in the slice or is negative, z is not modified. -func BigInt2Uint64Le(z []uint64, x *big.Int) { - xLen := (x.BitLen() + 63) >> 6 // number of 64-bit words - zLen := len(z) - if zLen >= xLen && x.Sign() > 0 { - var y, yi big.Int - y.Set(x) - two64 := big.NewInt(1) - two64.Lsh(two64, 64).Sub(two64, big.NewInt(1)) - for i := 0; i < xLen; i++ { - yi.And(&y, two64) - z[i] = yi.Uint64() - y.Rsh(&y, 64) - } - } - for i := xLen; i < zLen; i++ { - z[i] = 0 - } -} diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/doc.go b/vendor/github.com/cloudflare/circl/internal/sha3/doc.go deleted file mode 100644 index 7e023090..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/doc.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2014 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 sha3 implements the SHA-3 fixed-output-length hash functions and -// the SHAKE variable-output-length hash functions defined by FIPS-202. -// -// Both types of hash function use the "sponge" construction and the Keccak -// permutation. For a detailed specification see http://keccak.noekeon.org/ -// -// # Guidance -// -// If you aren't sure what function you need, use SHAKE256 with at least 64 -// bytes of output. The SHAKE instances are faster than the SHA3 instances; -// the latter have to allocate memory to conform to the hash.Hash interface. -// -// If you need a secret-key MAC (message authentication code), prepend the -// secret key to the input, hash with SHAKE256 and read at least 32 bytes of -// output. -// -// # Security strengths -// -// The SHA3-x (x equals 224, 256, 384, or 512) functions have a security -// strength against preimage attacks of x bits. Since they only produce "x" -// bits of output, their collision-resistance is only "x/2" bits. -// -// The SHAKE-256 and -128 functions have a generic security strength of 256 and -// 128 bits against all attacks, provided that at least 2x bits of their output -// is used. Requesting more than 64 or 32 bytes of output, respectively, does -// not increase the collision-resistance of the SHAKE functions. -// -// # The sponge construction -// -// A sponge builds a pseudo-random function from a public pseudo-random -// permutation, by applying the permutation to a state of "rate + capacity" -// bytes, but hiding "capacity" of the bytes. -// -// A sponge starts out with a zero state. To hash an input using a sponge, up -// to "rate" bytes of the input are XORed into the sponge's state. The sponge -// is then "full" and the permutation is applied to "empty" it. This process is -// repeated until all the input has been "absorbed". The input is then padded. -// The digest is "squeezed" from the sponge in the same way, except that output -// is copied out instead of input being XORed in. -// -// A sponge is parameterized by its generic security strength, which is equal -// to half its capacity; capacity + rate is equal to the permutation's width. -// Since the KeccakF-1600 permutation is 1600 bits (200 bytes) wide, this means -// that the security strength of a sponge instance is equal to (1600 - bitrate) / 2. -// -// # Recommendations -// -// The SHAKE functions are recommended for most new uses. They can produce -// output of arbitrary length. SHAKE256, with an output length of at least -// 64 bytes, provides 256-bit security against all attacks. The Keccak team -// recommends it for most applications upgrading from SHA2-512. (NIST chose a -// much stronger, but much slower, sponge instance for SHA3-512.) -// -// The SHA-3 functions are "drop-in" replacements for the SHA-2 functions. -// They produce output of the same length, with the same security strengths -// against all attacks. This means, in particular, that SHA3-256 only has -// 128-bit collision resistance, because its output length is 32 bytes. -package sha3 diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/hashes.go b/vendor/github.com/cloudflare/circl/internal/sha3/hashes.go deleted file mode 100644 index 7d2365a7..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/hashes.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2014 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 sha3 - -// This file provides functions for creating instances of the SHA-3 -// and SHAKE hash functions, as well as utility functions for hashing -// bytes. - -// New224 creates a new SHA3-224 hash. -// Its generic security strength is 224 bits against preimage attacks, -// and 112 bits against collision attacks. -func New224() State { - return State{rate: 144, outputLen: 28, dsbyte: 0x06} -} - -// New256 creates a new SHA3-256 hash. -// Its generic security strength is 256 bits against preimage attacks, -// and 128 bits against collision attacks. -func New256() State { - return State{rate: 136, outputLen: 32, dsbyte: 0x06} -} - -// New384 creates a new SHA3-384 hash. -// Its generic security strength is 384 bits against preimage attacks, -// and 192 bits against collision attacks. -func New384() State { - return State{rate: 104, outputLen: 48, dsbyte: 0x06} -} - -// New512 creates a new SHA3-512 hash. -// Its generic security strength is 512 bits against preimage attacks, -// and 256 bits against collision attacks. -func New512() State { - return State{rate: 72, outputLen: 64, dsbyte: 0x06} -} - -// Sum224 returns the SHA3-224 digest of the data. -func Sum224(data []byte) (digest [28]byte) { - h := New224() - _, _ = h.Write(data) - h.Sum(digest[:0]) - return -} - -// Sum256 returns the SHA3-256 digest of the data. -func Sum256(data []byte) (digest [32]byte) { - h := New256() - _, _ = h.Write(data) - h.Sum(digest[:0]) - return -} - -// Sum384 returns the SHA3-384 digest of the data. -func Sum384(data []byte) (digest [48]byte) { - h := New384() - _, _ = h.Write(data) - h.Sum(digest[:0]) - return -} - -// Sum512 returns the SHA3-512 digest of the data. -func Sum512(data []byte) (digest [64]byte) { - h := New512() - _, _ = h.Write(data) - h.Sum(digest[:0]) - return -} diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/keccakf.go b/vendor/github.com/cloudflare/circl/internal/sha3/keccakf.go deleted file mode 100644 index e606f0ca..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/keccakf.go +++ /dev/null @@ -1,385 +0,0 @@ -// Copyright 2014 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 || appengine || gccgo -// +build !amd64 appengine gccgo - -package sha3 - -// KeccakF1600 applies the Keccak permutation to a 1600b-wide -// state represented as a slice of 25 uint64s. -func KeccakF1600(a *[25]uint64) { - // Implementation translated from Keccak-inplace.c - // in the keccak reference code. - var t, bc0, bc1, bc2, bc3, bc4, d0, d1, d2, d3, d4 uint64 - - for i := 0; i < 24; i += 4 { - // Combines the 5 steps in each round into 2 steps. - // Unrolls 4 rounds per loop and spreads some steps across rounds. - - // Round 1 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[6] ^ d1 - bc1 = t<<44 | t>>(64-44) - t = a[12] ^ d2 - bc2 = t<<43 | t>>(64-43) - t = a[18] ^ d3 - bc3 = t<<21 | t>>(64-21) - t = a[24] ^ d4 - bc4 = t<<14 | t>>(64-14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ RC[i] - a[6] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc2 = t<<3 | t>>(64-3) - t = a[16] ^ d1 - bc3 = t<<45 | t>>(64-45) - t = a[22] ^ d2 - bc4 = t<<61 | t>>(64-61) - t = a[3] ^ d3 - bc0 = t<<28 | t>>(64-28) - t = a[9] ^ d4 - bc1 = t<<20 | t>>(64-20) - a[10] = bc0 ^ (bc2 &^ bc1) - a[16] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc4 = t<<18 | t>>(64-18) - t = a[1] ^ d1 - bc0 = t<<1 | t>>(64-1) - t = a[7] ^ d2 - bc1 = t<<6 | t>>(64-6) - t = a[13] ^ d3 - bc2 = t<<25 | t>>(64-25) - t = a[19] ^ d4 - bc3 = t<<8 | t>>(64-8) - a[20] = bc0 ^ (bc2 &^ bc1) - a[1] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc1 = t<<36 | t>>(64-36) - t = a[11] ^ d1 - bc2 = t<<10 | t>>(64-10) - t = a[17] ^ d2 - bc3 = t<<15 | t>>(64-15) - t = a[23] ^ d3 - bc4 = t<<56 | t>>(64-56) - t = a[4] ^ d4 - bc0 = t<<27 | t>>(64-27) - a[5] = bc0 ^ (bc2 &^ bc1) - a[11] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc3 = t<<41 | t>>(64-41) - t = a[21] ^ d1 - bc4 = t<<2 | t>>(64-2) - t = a[2] ^ d2 - bc0 = t<<62 | t>>(64-62) - t = a[8] ^ d3 - bc1 = t<<55 | t>>(64-55) - t = a[14] ^ d4 - bc2 = t<<39 | t>>(64-39) - a[15] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - // Round 2 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[16] ^ d1 - bc1 = t<<44 | t>>(64-44) - t = a[7] ^ d2 - bc2 = t<<43 | t>>(64-43) - t = a[23] ^ d3 - bc3 = t<<21 | t>>(64-21) - t = a[14] ^ d4 - bc4 = t<<14 | t>>(64-14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ RC[i+1] - a[16] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc2 = t<<3 | t>>(64-3) - t = a[11] ^ d1 - bc3 = t<<45 | t>>(64-45) - t = a[2] ^ d2 - bc4 = t<<61 | t>>(64-61) - t = a[18] ^ d3 - bc0 = t<<28 | t>>(64-28) - t = a[9] ^ d4 - bc1 = t<<20 | t>>(64-20) - a[20] = bc0 ^ (bc2 &^ bc1) - a[11] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc4 = t<<18 | t>>(64-18) - t = a[6] ^ d1 - bc0 = t<<1 | t>>(64-1) - t = a[22] ^ d2 - bc1 = t<<6 | t>>(64-6) - t = a[13] ^ d3 - bc2 = t<<25 | t>>(64-25) - t = a[4] ^ d4 - bc3 = t<<8 | t>>(64-8) - a[15] = bc0 ^ (bc2 &^ bc1) - a[6] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc1 = t<<36 | t>>(64-36) - t = a[1] ^ d1 - bc2 = t<<10 | t>>(64-10) - t = a[17] ^ d2 - bc3 = t<<15 | t>>(64-15) - t = a[8] ^ d3 - bc4 = t<<56 | t>>(64-56) - t = a[24] ^ d4 - bc0 = t<<27 | t>>(64-27) - a[10] = bc0 ^ (bc2 &^ bc1) - a[1] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc3 = t<<41 | t>>(64-41) - t = a[21] ^ d1 - bc4 = t<<2 | t>>(64-2) - t = a[12] ^ d2 - bc0 = t<<62 | t>>(64-62) - t = a[3] ^ d3 - bc1 = t<<55 | t>>(64-55) - t = a[19] ^ d4 - bc2 = t<<39 | t>>(64-39) - a[5] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - // Round 3 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[11] ^ d1 - bc1 = t<<44 | t>>(64-44) - t = a[22] ^ d2 - bc2 = t<<43 | t>>(64-43) - t = a[8] ^ d3 - bc3 = t<<21 | t>>(64-21) - t = a[19] ^ d4 - bc4 = t<<14 | t>>(64-14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ RC[i+2] - a[11] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc2 = t<<3 | t>>(64-3) - t = a[1] ^ d1 - bc3 = t<<45 | t>>(64-45) - t = a[12] ^ d2 - bc4 = t<<61 | t>>(64-61) - t = a[23] ^ d3 - bc0 = t<<28 | t>>(64-28) - t = a[9] ^ d4 - bc1 = t<<20 | t>>(64-20) - a[15] = bc0 ^ (bc2 &^ bc1) - a[1] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc4 = t<<18 | t>>(64-18) - t = a[16] ^ d1 - bc0 = t<<1 | t>>(64-1) - t = a[2] ^ d2 - bc1 = t<<6 | t>>(64-6) - t = a[13] ^ d3 - bc2 = t<<25 | t>>(64-25) - t = a[24] ^ d4 - bc3 = t<<8 | t>>(64-8) - a[5] = bc0 ^ (bc2 &^ bc1) - a[16] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc1 = t<<36 | t>>(64-36) - t = a[6] ^ d1 - bc2 = t<<10 | t>>(64-10) - t = a[17] ^ d2 - bc3 = t<<15 | t>>(64-15) - t = a[3] ^ d3 - bc4 = t<<56 | t>>(64-56) - t = a[14] ^ d4 - bc0 = t<<27 | t>>(64-27) - a[20] = bc0 ^ (bc2 &^ bc1) - a[6] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc3 = t<<41 | t>>(64-41) - t = a[21] ^ d1 - bc4 = t<<2 | t>>(64-2) - t = a[7] ^ d2 - bc0 = t<<62 | t>>(64-62) - t = a[18] ^ d3 - bc1 = t<<55 | t>>(64-55) - t = a[4] ^ d4 - bc2 = t<<39 | t>>(64-39) - a[10] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - // Round 4 - bc0 = a[0] ^ a[5] ^ a[10] ^ a[15] ^ a[20] - bc1 = a[1] ^ a[6] ^ a[11] ^ a[16] ^ a[21] - bc2 = a[2] ^ a[7] ^ a[12] ^ a[17] ^ a[22] - bc3 = a[3] ^ a[8] ^ a[13] ^ a[18] ^ a[23] - bc4 = a[4] ^ a[9] ^ a[14] ^ a[19] ^ a[24] - d0 = bc4 ^ (bc1<<1 | bc1>>63) - d1 = bc0 ^ (bc2<<1 | bc2>>63) - d2 = bc1 ^ (bc3<<1 | bc3>>63) - d3 = bc2 ^ (bc4<<1 | bc4>>63) - d4 = bc3 ^ (bc0<<1 | bc0>>63) - - bc0 = a[0] ^ d0 - t = a[1] ^ d1 - bc1 = t<<44 | t>>(64-44) - t = a[2] ^ d2 - bc2 = t<<43 | t>>(64-43) - t = a[3] ^ d3 - bc3 = t<<21 | t>>(64-21) - t = a[4] ^ d4 - bc4 = t<<14 | t>>(64-14) - a[0] = bc0 ^ (bc2 &^ bc1) ^ RC[i+3] - a[1] = bc1 ^ (bc3 &^ bc2) - a[2] = bc2 ^ (bc4 &^ bc3) - a[3] = bc3 ^ (bc0 &^ bc4) - a[4] = bc4 ^ (bc1 &^ bc0) - - t = a[5] ^ d0 - bc2 = t<<3 | t>>(64-3) - t = a[6] ^ d1 - bc3 = t<<45 | t>>(64-45) - t = a[7] ^ d2 - bc4 = t<<61 | t>>(64-61) - t = a[8] ^ d3 - bc0 = t<<28 | t>>(64-28) - t = a[9] ^ d4 - bc1 = t<<20 | t>>(64-20) - a[5] = bc0 ^ (bc2 &^ bc1) - a[6] = bc1 ^ (bc3 &^ bc2) - a[7] = bc2 ^ (bc4 &^ bc3) - a[8] = bc3 ^ (bc0 &^ bc4) - a[9] = bc4 ^ (bc1 &^ bc0) - - t = a[10] ^ d0 - bc4 = t<<18 | t>>(64-18) - t = a[11] ^ d1 - bc0 = t<<1 | t>>(64-1) - t = a[12] ^ d2 - bc1 = t<<6 | t>>(64-6) - t = a[13] ^ d3 - bc2 = t<<25 | t>>(64-25) - t = a[14] ^ d4 - bc3 = t<<8 | t>>(64-8) - a[10] = bc0 ^ (bc2 &^ bc1) - a[11] = bc1 ^ (bc3 &^ bc2) - a[12] = bc2 ^ (bc4 &^ bc3) - a[13] = bc3 ^ (bc0 &^ bc4) - a[14] = bc4 ^ (bc1 &^ bc0) - - t = a[15] ^ d0 - bc1 = t<<36 | t>>(64-36) - t = a[16] ^ d1 - bc2 = t<<10 | t>>(64-10) - t = a[17] ^ d2 - bc3 = t<<15 | t>>(64-15) - t = a[18] ^ d3 - bc4 = t<<56 | t>>(64-56) - t = a[19] ^ d4 - bc0 = t<<27 | t>>(64-27) - a[15] = bc0 ^ (bc2 &^ bc1) - a[16] = bc1 ^ (bc3 &^ bc2) - a[17] = bc2 ^ (bc4 &^ bc3) - a[18] = bc3 ^ (bc0 &^ bc4) - a[19] = bc4 ^ (bc1 &^ bc0) - - t = a[20] ^ d0 - bc3 = t<<41 | t>>(64-41) - t = a[21] ^ d1 - bc4 = t<<2 | t>>(64-2) - t = a[22] ^ d2 - bc0 = t<<62 | t>>(64-62) - t = a[23] ^ d3 - bc1 = t<<55 | t>>(64-55) - t = a[24] ^ d4 - bc2 = t<<39 | t>>(64-39) - a[20] = bc0 ^ (bc2 &^ bc1) - a[21] = bc1 ^ (bc3 &^ bc2) - a[22] = bc2 ^ (bc4 &^ bc3) - a[23] = bc3 ^ (bc0 &^ bc4) - a[24] = bc4 ^ (bc1 &^ bc0) - } -} diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/keccakf_amd64.go b/vendor/github.com/cloudflare/circl/internal/sha3/keccakf_amd64.go deleted file mode 100644 index e7364eb0..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/keccakf_amd64.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2015 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 && !appengine && !gccgo -// +build amd64,!appengine,!gccgo - -package sha3 - -// This function is implemented in keccakf_amd64.s. - -//go:noescape - -func KeccakF1600(state *[25]uint64) diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/keccakf_amd64.s b/vendor/github.com/cloudflare/circl/internal/sha3/keccakf_amd64.s deleted file mode 100644 index 8589363a..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/keccakf_amd64.s +++ /dev/null @@ -1,390 +0,0 @@ -// Copyright 2015 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. - -// +build amd64,!appengine,!gccgo - -// This code was translated into a form compatible with 6a from the public -// domain sources at https://github.com/gvanas/KeccakCodePackage - -// Offsets in state -#define _ba (0*8) -#define _be (1*8) -#define _bi (2*8) -#define _bo (3*8) -#define _bu (4*8) -#define _ga (5*8) -#define _ge (6*8) -#define _gi (7*8) -#define _go (8*8) -#define _gu (9*8) -#define _ka (10*8) -#define _ke (11*8) -#define _ki (12*8) -#define _ko (13*8) -#define _ku (14*8) -#define _ma (15*8) -#define _me (16*8) -#define _mi (17*8) -#define _mo (18*8) -#define _mu (19*8) -#define _sa (20*8) -#define _se (21*8) -#define _si (22*8) -#define _so (23*8) -#define _su (24*8) - -// Temporary registers -#define rT1 AX - -// Round vars -#define rpState DI -#define rpStack SP - -#define rDa BX -#define rDe CX -#define rDi DX -#define rDo R8 -#define rDu R9 - -#define rBa R10 -#define rBe R11 -#define rBi R12 -#define rBo R13 -#define rBu R14 - -#define rCa SI -#define rCe BP -#define rCi rBi -#define rCo rBo -#define rCu R15 - -#define MOVQ_RBI_RCE MOVQ rBi, rCe -#define XORQ_RT1_RCA XORQ rT1, rCa -#define XORQ_RT1_RCE XORQ rT1, rCe -#define XORQ_RBA_RCU XORQ rBa, rCu -#define XORQ_RBE_RCU XORQ rBe, rCu -#define XORQ_RDU_RCU XORQ rDu, rCu -#define XORQ_RDA_RCA XORQ rDa, rCa -#define XORQ_RDE_RCE XORQ rDe, rCe - -#define mKeccakRound(iState, oState, rc, B_RBI_RCE, G_RT1_RCA, G_RT1_RCE, G_RBA_RCU, K_RT1_RCA, K_RT1_RCE, K_RBA_RCU, M_RT1_RCA, M_RT1_RCE, M_RBE_RCU, S_RDU_RCU, S_RDA_RCA, S_RDE_RCE) \ - /* Prepare round */ \ - MOVQ rCe, rDa; \ - ROLQ $1, rDa; \ - \ - MOVQ _bi(iState), rCi; \ - XORQ _gi(iState), rDi; \ - XORQ rCu, rDa; \ - XORQ _ki(iState), rCi; \ - XORQ _mi(iState), rDi; \ - XORQ rDi, rCi; \ - \ - MOVQ rCi, rDe; \ - ROLQ $1, rDe; \ - \ - MOVQ _bo(iState), rCo; \ - XORQ _go(iState), rDo; \ - XORQ rCa, rDe; \ - XORQ _ko(iState), rCo; \ - XORQ _mo(iState), rDo; \ - XORQ rDo, rCo; \ - \ - MOVQ rCo, rDi; \ - ROLQ $1, rDi; \ - \ - MOVQ rCu, rDo; \ - XORQ rCe, rDi; \ - ROLQ $1, rDo; \ - \ - MOVQ rCa, rDu; \ - XORQ rCi, rDo; \ - ROLQ $1, rDu; \ - \ - /* Result b */ \ - MOVQ _ba(iState), rBa; \ - MOVQ _ge(iState), rBe; \ - XORQ rCo, rDu; \ - MOVQ _ki(iState), rBi; \ - MOVQ _mo(iState), rBo; \ - MOVQ _su(iState), rBu; \ - XORQ rDe, rBe; \ - ROLQ $44, rBe; \ - XORQ rDi, rBi; \ - XORQ rDa, rBa; \ - ROLQ $43, rBi; \ - \ - MOVQ rBe, rCa; \ - MOVQ rc, rT1; \ - ORQ rBi, rCa; \ - XORQ rBa, rT1; \ - XORQ rT1, rCa; \ - MOVQ rCa, _ba(oState); \ - \ - XORQ rDu, rBu; \ - ROLQ $14, rBu; \ - MOVQ rBa, rCu; \ - ANDQ rBe, rCu; \ - XORQ rBu, rCu; \ - MOVQ rCu, _bu(oState); \ - \ - XORQ rDo, rBo; \ - ROLQ $21, rBo; \ - MOVQ rBo, rT1; \ - ANDQ rBu, rT1; \ - XORQ rBi, rT1; \ - MOVQ rT1, _bi(oState); \ - \ - NOTQ rBi; \ - ORQ rBa, rBu; \ - ORQ rBo, rBi; \ - XORQ rBo, rBu; \ - XORQ rBe, rBi; \ - MOVQ rBu, _bo(oState); \ - MOVQ rBi, _be(oState); \ - B_RBI_RCE; \ - \ - /* Result g */ \ - MOVQ _gu(iState), rBe; \ - XORQ rDu, rBe; \ - MOVQ _ka(iState), rBi; \ - ROLQ $20, rBe; \ - XORQ rDa, rBi; \ - ROLQ $3, rBi; \ - MOVQ _bo(iState), rBa; \ - MOVQ rBe, rT1; \ - ORQ rBi, rT1; \ - XORQ rDo, rBa; \ - MOVQ _me(iState), rBo; \ - MOVQ _si(iState), rBu; \ - ROLQ $28, rBa; \ - XORQ rBa, rT1; \ - MOVQ rT1, _ga(oState); \ - G_RT1_RCA; \ - \ - XORQ rDe, rBo; \ - ROLQ $45, rBo; \ - MOVQ rBi, rT1; \ - ANDQ rBo, rT1; \ - XORQ rBe, rT1; \ - MOVQ rT1, _ge(oState); \ - G_RT1_RCE; \ - \ - XORQ rDi, rBu; \ - ROLQ $61, rBu; \ - MOVQ rBu, rT1; \ - ORQ rBa, rT1; \ - XORQ rBo, rT1; \ - MOVQ rT1, _go(oState); \ - \ - ANDQ rBe, rBa; \ - XORQ rBu, rBa; \ - MOVQ rBa, _gu(oState); \ - NOTQ rBu; \ - G_RBA_RCU; \ - \ - ORQ rBu, rBo; \ - XORQ rBi, rBo; \ - MOVQ rBo, _gi(oState); \ - \ - /* Result k */ \ - MOVQ _be(iState), rBa; \ - MOVQ _gi(iState), rBe; \ - MOVQ _ko(iState), rBi; \ - MOVQ _mu(iState), rBo; \ - MOVQ _sa(iState), rBu; \ - XORQ rDi, rBe; \ - ROLQ $6, rBe; \ - XORQ rDo, rBi; \ - ROLQ $25, rBi; \ - MOVQ rBe, rT1; \ - ORQ rBi, rT1; \ - XORQ rDe, rBa; \ - ROLQ $1, rBa; \ - XORQ rBa, rT1; \ - MOVQ rT1, _ka(oState); \ - K_RT1_RCA; \ - \ - XORQ rDu, rBo; \ - ROLQ $8, rBo; \ - MOVQ rBi, rT1; \ - ANDQ rBo, rT1; \ - XORQ rBe, rT1; \ - MOVQ rT1, _ke(oState); \ - K_RT1_RCE; \ - \ - XORQ rDa, rBu; \ - ROLQ $18, rBu; \ - NOTQ rBo; \ - MOVQ rBo, rT1; \ - ANDQ rBu, rT1; \ - XORQ rBi, rT1; \ - MOVQ rT1, _ki(oState); \ - \ - MOVQ rBu, rT1; \ - ORQ rBa, rT1; \ - XORQ rBo, rT1; \ - MOVQ rT1, _ko(oState); \ - \ - ANDQ rBe, rBa; \ - XORQ rBu, rBa; \ - MOVQ rBa, _ku(oState); \ - K_RBA_RCU; \ - \ - /* Result m */ \ - MOVQ _ga(iState), rBe; \ - XORQ rDa, rBe; \ - MOVQ _ke(iState), rBi; \ - ROLQ $36, rBe; \ - XORQ rDe, rBi; \ - MOVQ _bu(iState), rBa; \ - ROLQ $10, rBi; \ - MOVQ rBe, rT1; \ - MOVQ _mi(iState), rBo; \ - ANDQ rBi, rT1; \ - XORQ rDu, rBa; \ - MOVQ _so(iState), rBu; \ - ROLQ $27, rBa; \ - XORQ rBa, rT1; \ - MOVQ rT1, _ma(oState); \ - M_RT1_RCA; \ - \ - XORQ rDi, rBo; \ - ROLQ $15, rBo; \ - MOVQ rBi, rT1; \ - ORQ rBo, rT1; \ - XORQ rBe, rT1; \ - MOVQ rT1, _me(oState); \ - M_RT1_RCE; \ - \ - XORQ rDo, rBu; \ - ROLQ $56, rBu; \ - NOTQ rBo; \ - MOVQ rBo, rT1; \ - ORQ rBu, rT1; \ - XORQ rBi, rT1; \ - MOVQ rT1, _mi(oState); \ - \ - ORQ rBa, rBe; \ - XORQ rBu, rBe; \ - MOVQ rBe, _mu(oState); \ - \ - ANDQ rBa, rBu; \ - XORQ rBo, rBu; \ - MOVQ rBu, _mo(oState); \ - M_RBE_RCU; \ - \ - /* Result s */ \ - MOVQ _bi(iState), rBa; \ - MOVQ _go(iState), rBe; \ - MOVQ _ku(iState), rBi; \ - XORQ rDi, rBa; \ - MOVQ _ma(iState), rBo; \ - ROLQ $62, rBa; \ - XORQ rDo, rBe; \ - MOVQ _se(iState), rBu; \ - ROLQ $55, rBe; \ - \ - XORQ rDu, rBi; \ - MOVQ rBa, rDu; \ - XORQ rDe, rBu; \ - ROLQ $2, rBu; \ - ANDQ rBe, rDu; \ - XORQ rBu, rDu; \ - MOVQ rDu, _su(oState); \ - \ - ROLQ $39, rBi; \ - S_RDU_RCU; \ - NOTQ rBe; \ - XORQ rDa, rBo; \ - MOVQ rBe, rDa; \ - ANDQ rBi, rDa; \ - XORQ rBa, rDa; \ - MOVQ rDa, _sa(oState); \ - S_RDA_RCA; \ - \ - ROLQ $41, rBo; \ - MOVQ rBi, rDe; \ - ORQ rBo, rDe; \ - XORQ rBe, rDe; \ - MOVQ rDe, _se(oState); \ - S_RDE_RCE; \ - \ - MOVQ rBo, rDi; \ - MOVQ rBu, rDo; \ - ANDQ rBu, rDi; \ - ORQ rBa, rDo; \ - XORQ rBi, rDi; \ - XORQ rBo, rDo; \ - MOVQ rDi, _si(oState); \ - MOVQ rDo, _so(oState) \ - -// func KeccakF1600(state *[25]uint64) -TEXT ·KeccakF1600(SB), 0, $200-8 - MOVQ state+0(FP), rpState - - // Convert the user state into an internal state - NOTQ _be(rpState) - NOTQ _bi(rpState) - NOTQ _go(rpState) - NOTQ _ki(rpState) - NOTQ _mi(rpState) - NOTQ _sa(rpState) - - // Execute the KeccakF permutation - MOVQ _ba(rpState), rCa - MOVQ _be(rpState), rCe - MOVQ _bu(rpState), rCu - - XORQ _ga(rpState), rCa - XORQ _ge(rpState), rCe - XORQ _gu(rpState), rCu - - XORQ _ka(rpState), rCa - XORQ _ke(rpState), rCe - XORQ _ku(rpState), rCu - - XORQ _ma(rpState), rCa - XORQ _me(rpState), rCe - XORQ _mu(rpState), rCu - - XORQ _sa(rpState), rCa - XORQ _se(rpState), rCe - MOVQ _si(rpState), rDi - MOVQ _so(rpState), rDo - XORQ _su(rpState), rCu - - mKeccakRound(rpState, rpStack, $0x0000000000000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x0000000000008082, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x800000000000808a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000080008000, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x000000000000808b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x0000000080000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x8000000080008081, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000000008009, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x000000000000008a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x0000000000000088, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x0000000080008009, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x000000008000000a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x000000008000808b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x800000000000008b, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x8000000000008089, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000000008003, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x8000000000008002, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000000000080, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x000000000000800a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x800000008000000a, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x8000000080008081, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000000008080, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpState, rpStack, $0x0000000080000001, MOVQ_RBI_RCE, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBA_RCU, XORQ_RT1_RCA, XORQ_RT1_RCE, XORQ_RBE_RCU, XORQ_RDU_RCU, XORQ_RDA_RCA, XORQ_RDE_RCE) - mKeccakRound(rpStack, rpState, $0x8000000080008008, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP, NOP) - - // Revert the internal state to the user state - NOTQ _be(rpState) - NOTQ _bi(rpState) - NOTQ _go(rpState) - NOTQ _ki(rpState) - NOTQ _mi(rpState) - NOTQ _sa(rpState) - - RET diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/rc.go b/vendor/github.com/cloudflare/circl/internal/sha3/rc.go deleted file mode 100644 index 6a3df42f..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/rc.go +++ /dev/null @@ -1,29 +0,0 @@ -package sha3 - -// RC stores the round constants for use in the ι step. -var RC = [24]uint64{ - 0x0000000000000001, - 0x0000000000008082, - 0x800000000000808A, - 0x8000000080008000, - 0x000000000000808B, - 0x0000000080000001, - 0x8000000080008081, - 0x8000000000008009, - 0x000000000000008A, - 0x0000000000000088, - 0x0000000080008009, - 0x000000008000000A, - 0x000000008000808B, - 0x800000000000008B, - 0x8000000000008089, - 0x8000000000008003, - 0x8000000000008002, - 0x8000000000000080, - 0x000000000000800A, - 0x800000008000000A, - 0x8000000080008081, - 0x8000000000008080, - 0x0000000080000001, - 0x8000000080008008, -} diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/sha3.go b/vendor/github.com/cloudflare/circl/internal/sha3/sha3.go deleted file mode 100644 index b35cd006..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/sha3.go +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright 2014 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 sha3 - -// spongeDirection indicates the direction bytes are flowing through the sponge. -type spongeDirection int - -const ( - // spongeAbsorbing indicates that the sponge is absorbing input. - spongeAbsorbing spongeDirection = iota - // spongeSqueezing indicates that the sponge is being squeezed. - spongeSqueezing -) - -const ( - // maxRate is the maximum size of the internal buffer. SHAKE-256 - // currently needs the largest buffer. - maxRate = 168 -) - -func (d *State) buf() []byte { - return d.storage.asBytes()[d.bufo:d.bufe] -} - -type State struct { - // Generic sponge components. - a [25]uint64 // main state of the hash - rate int // the number of bytes of state to use - - bufo int // offset of buffer in storage - bufe int // end of buffer in storage - - // dsbyte contains the "domain separation" bits and the first bit of - // the padding. Sections 6.1 and 6.2 of [1] separate the outputs of the - // SHA-3 and SHAKE functions by appending bitstrings to the message. - // Using a little-endian bit-ordering convention, these are "01" for SHA-3 - // and "1111" for SHAKE, or 00000010b and 00001111b, respectively. Then the - // padding rule from section 5.1 is applied to pad the message to a multiple - // of the rate, which involves adding a "1" bit, zero or more "0" bits, and - // a final "1" bit. We merge the first "1" bit from the padding into dsbyte, - // giving 00000110b (0x06) and 00011111b (0x1f). - // [1] http://csrc.nist.gov/publications/drafts/fips-202/fips_202_draft.pdf - // "Draft FIPS 202: SHA-3 Standard: Permutation-Based Hash and - // Extendable-Output Functions (May 2014)" - dsbyte byte - - storage storageBuf - - // Specific to SHA-3 and SHAKE. - outputLen int // the default output size in bytes - state spongeDirection // whether the sponge is absorbing or squeezing -} - -// BlockSize returns the rate of sponge underlying this hash function. -func (d *State) BlockSize() int { return d.rate } - -// Size returns the output size of the hash function in bytes. -func (d *State) Size() int { return d.outputLen } - -// Reset clears the internal state by zeroing the sponge state and -// the byte buffer, and setting Sponge.state to absorbing. -func (d *State) Reset() { - // Zero the permutation's state. - for i := range d.a { - d.a[i] = 0 - } - d.state = spongeAbsorbing - d.bufo = 0 - d.bufe = 0 -} - -func (d *State) clone() *State { - ret := *d - return &ret -} - -// permute applies the KeccakF-1600 permutation. It handles -// any input-output buffering. -func (d *State) permute() { - switch d.state { - case spongeAbsorbing: - // If we're absorbing, we need to xor the input into the state - // before applying the permutation. - xorIn(d, d.buf()) - d.bufe = 0 - d.bufo = 0 - KeccakF1600(&d.a) - case spongeSqueezing: - // If we're squeezing, we need to apply the permutation before - // copying more output. - KeccakF1600(&d.a) - d.bufe = d.rate - d.bufo = 0 - copyOut(d, d.buf()) - } -} - -// pads appends the domain separation bits in dsbyte, applies -// the multi-bitrate 10..1 padding rule, and permutes the state. -func (d *State) padAndPermute(dsbyte byte) { - // Pad with this instance's domain-separator bits. We know that there's - // at least one byte of space in d.buf() because, if it were full, - // permute would have been called to empty it. dsbyte also contains the - // first one bit for the padding. See the comment in the state struct. - zerosStart := d.bufe + 1 - d.bufe = d.rate - buf := d.buf() - buf[zerosStart-1] = dsbyte - for i := zerosStart; i < d.rate; i++ { - buf[i] = 0 - } - // This adds the final one bit for the padding. Because of the way that - // bits are numbered from the LSB upwards, the final bit is the MSB of - // the last byte. - buf[d.rate-1] ^= 0x80 - // Apply the permutation - d.permute() - d.state = spongeSqueezing - d.bufe = d.rate - copyOut(d, buf) -} - -// Write absorbs more data into the hash's state. It produces an error -// if more data is written to the ShakeHash after writing -func (d *State) Write(p []byte) (written int, err error) { - if d.state != spongeAbsorbing { - panic("sha3: write to sponge after read") - } - written = len(p) - - for len(p) > 0 { - bufl := d.bufe - d.bufo - if bufl == 0 && len(p) >= d.rate { - // The fast path; absorb a full "rate" bytes of input and apply the permutation. - xorIn(d, p[:d.rate]) - p = p[d.rate:] - KeccakF1600(&d.a) - } else { - // The slow path; buffer the input until we can fill the sponge, and then xor it in. - todo := d.rate - bufl - if todo > len(p) { - todo = len(p) - } - d.bufe += todo - buf := d.buf() - copy(buf[bufl:], p[:todo]) - p = p[todo:] - - // If the sponge is full, apply the permutation. - if d.bufe == d.rate { - d.permute() - } - } - } - - return written, nil -} - -// Read squeezes an arbitrary number of bytes from the sponge. -func (d *State) Read(out []byte) (n int, err error) { - // If we're still absorbing, pad and apply the permutation. - if d.state == spongeAbsorbing { - d.padAndPermute(d.dsbyte) - } - - n = len(out) - - // Now, do the squeezing. - for len(out) > 0 { - buf := d.buf() - n := copy(out, buf) - d.bufo += n - out = out[n:] - - // Apply the permutation if we've squeezed the sponge dry. - if d.bufo == d.bufe { - d.permute() - } - } - - return -} - -// Sum applies padding to the hash state and then squeezes out the desired -// number of output bytes. -func (d *State) Sum(in []byte) []byte { - // Make a copy of the original hash so that caller can keep writing - // and summing. - dup := d.clone() - hash := make([]byte, dup.outputLen) - _, _ = dup.Read(hash) - return append(in, hash...) -} diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/sha3_s390x.s b/vendor/github.com/cloudflare/circl/internal/sha3/sha3_s390x.s deleted file mode 100644 index 8a4458f6..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/sha3_s390x.s +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 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. - -// +build !gccgo,!appengine - -#include "textflag.h" - -// func kimd(function code, chain *[200]byte, src []byte) -TEXT ·kimd(SB), NOFRAME|NOSPLIT, $0-40 - MOVD function+0(FP), R0 - MOVD chain+8(FP), R1 - LMG src+16(FP), R2, R3 // R2=base, R3=len - -continue: - WORD $0xB93E0002 // KIMD --, R2 - BVS continue // continue if interrupted - MOVD $0, R0 // reset R0 for pre-go1.8 compilers - RET - -// func klmd(function code, chain *[200]byte, dst, src []byte) -TEXT ·klmd(SB), NOFRAME|NOSPLIT, $0-64 - // TODO: SHAKE support - MOVD function+0(FP), R0 - MOVD chain+8(FP), R1 - LMG dst+16(FP), R2, R3 // R2=base, R3=len - LMG src+40(FP), R4, R5 // R4=base, R5=len - -continue: - WORD $0xB93F0024 // KLMD R2, R4 - BVS continue // continue if interrupted - MOVD $0, R0 // reset R0 for pre-go1.8 compilers - RET diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/shake.go b/vendor/github.com/cloudflare/circl/internal/sha3/shake.go deleted file mode 100644 index b92c5b7d..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/shake.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2014 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 sha3 - -// This file defines the ShakeHash interface, and provides -// functions for creating SHAKE and cSHAKE instances, as well as utility -// functions for hashing bytes to arbitrary-length output. -// -// -// SHAKE implementation is based on FIPS PUB 202 [1] -// cSHAKE implementations is based on NIST SP 800-185 [2] -// -// [1] https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf -// [2] https://doi.org/10.6028/NIST.SP.800-185 - -import ( - "io" -) - -// ShakeHash defines the interface to hash functions that -// support arbitrary-length output. -type ShakeHash interface { - // Write absorbs more data into the hash's state. It panics if input is - // written to it after output has been read from it. - io.Writer - - // Read reads more output from the hash; reading affects the hash's - // state. (ShakeHash.Read is thus very different from Hash.Sum) - // It never returns an error. - io.Reader - - // Clone returns a copy of the ShakeHash in its current state. - Clone() ShakeHash - - // Reset resets the ShakeHash to its initial state. - Reset() -} - -// Consts for configuring initial SHA-3 state -const ( - dsbyteShake = 0x1f - rate128 = 168 - rate256 = 136 -) - -// Clone returns copy of SHAKE context within its current state. -func (d *State) Clone() ShakeHash { - return d.clone() -} - -// NewShake128 creates a new SHAKE128 variable-output-length ShakeHash. -// Its generic security strength is 128 bits against all attacks if at -// least 32 bytes of its output are used. -func NewShake128() State { - return State{rate: rate128, dsbyte: dsbyteShake} -} - -// NewShake256 creates a new SHAKE256 variable-output-length ShakeHash. -// Its generic security strength is 256 bits against all attacks if -// at least 64 bytes of its output are used. -func NewShake256() State { - return State{rate: rate256, dsbyte: dsbyteShake} -} - -// ShakeSum128 writes an arbitrary-length digest of data into hash. -func ShakeSum128(hash, data []byte) { - h := NewShake128() - _, _ = h.Write(data) - _, _ = h.Read(hash) -} - -// ShakeSum256 writes an arbitrary-length digest of data into hash. -func ShakeSum256(hash, data []byte) { - h := NewShake256() - _, _ = h.Write(data) - _, _ = h.Read(hash) -} diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/xor.go b/vendor/github.com/cloudflare/circl/internal/sha3/xor.go deleted file mode 100644 index 1e213374..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/xor.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2015 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 && !386 && !ppc64le) || appengine -// +build !amd64,!386,!ppc64le appengine - -package sha3 - -// A storageBuf is an aligned array of maxRate bytes. -type storageBuf [maxRate]byte - -func (b *storageBuf) asBytes() *[maxRate]byte { - return (*[maxRate]byte)(b) -} diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/xor_generic.go b/vendor/github.com/cloudflare/circl/internal/sha3/xor_generic.go deleted file mode 100644 index 2b0c6617..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/xor_generic.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015 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 || appengine) && (!386 || appengine) && (!ppc64le || appengine) -// +build !amd64 appengine -// +build !386 appengine -// +build !ppc64le appengine - -package sha3 - -import "encoding/binary" - -// xorIn xors the bytes in buf into the state; it -// makes no non-portable assumptions about memory layout -// or alignment. -func xorIn(d *State, buf []byte) { - n := len(buf) / 8 - - for i := 0; i < n; i++ { - a := binary.LittleEndian.Uint64(buf) - d.a[i] ^= a - buf = buf[8:] - } -} - -// copyOut copies ulint64s to a byte buffer. -func copyOut(d *State, b []byte) { - for i := 0; len(b) >= 8; i++ { - binary.LittleEndian.PutUint64(b, d.a[i]) - b = b[8:] - } -} diff --git a/vendor/github.com/cloudflare/circl/internal/sha3/xor_unaligned.go b/vendor/github.com/cloudflare/circl/internal/sha3/xor_unaligned.go deleted file mode 100644 index 052fc8d3..00000000 --- a/vendor/github.com/cloudflare/circl/internal/sha3/xor_unaligned.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2015 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 || 386 || ppc64le) && !appengine -// +build amd64 386 ppc64le -// +build !appengine - -package sha3 - -import "unsafe" - -// A storageBuf is an aligned array of maxRate bytes. -type storageBuf [maxRate / 8]uint64 - -func (b *storageBuf) asBytes() *[maxRate]byte { - return (*[maxRate]byte)(unsafe.Pointer(b)) -} - -// xorInuses unaligned reads and writes to update d.a to contain d.a -// XOR buf. -func xorIn(d *State, buf []byte) { - n := len(buf) - bw := (*[maxRate / 8]uint64)(unsafe.Pointer(&buf[0]))[: n/8 : n/8] - if n >= 72 { - d.a[0] ^= bw[0] - d.a[1] ^= bw[1] - d.a[2] ^= bw[2] - d.a[3] ^= bw[3] - d.a[4] ^= bw[4] - d.a[5] ^= bw[5] - d.a[6] ^= bw[6] - d.a[7] ^= bw[7] - d.a[8] ^= bw[8] - } - if n >= 104 { - d.a[9] ^= bw[9] - d.a[10] ^= bw[10] - d.a[11] ^= bw[11] - d.a[12] ^= bw[12] - } - if n >= 136 { - d.a[13] ^= bw[13] - d.a[14] ^= bw[14] - d.a[15] ^= bw[15] - d.a[16] ^= bw[16] - } - if n >= 144 { - d.a[17] ^= bw[17] - } - if n >= 168 { - d.a[18] ^= bw[18] - d.a[19] ^= bw[19] - d.a[20] ^= bw[20] - } -} - -func copyOut(d *State, buf []byte) { - ab := (*[maxRate]uint8)(unsafe.Pointer(&d.a[0])) - copy(buf, ab[:]) -} diff --git a/vendor/github.com/cloudflare/circl/math/fp25519/fp.go b/vendor/github.com/cloudflare/circl/math/fp25519/fp.go deleted file mode 100644 index 57a50ff5..00000000 --- a/vendor/github.com/cloudflare/circl/math/fp25519/fp.go +++ /dev/null @@ -1,205 +0,0 @@ -// Package fp25519 provides prime field arithmetic over GF(2^255-19). -package fp25519 - -import ( - "errors" - - "github.com/cloudflare/circl/internal/conv" -) - -// Size in bytes of an element. -const Size = 32 - -// Elt is a prime field element. -type Elt [Size]byte - -func (e Elt) String() string { return conv.BytesLe2Hex(e[:]) } - -// p is the prime modulus 2^255-19. -var p = Elt{ - 0xed, 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, 0x7f, -} - -// P returns the prime modulus 2^255-19. -func P() Elt { return p } - -// ToBytes stores in b the little-endian byte representation of x. -func ToBytes(b []byte, x *Elt) error { - if len(b) != Size { - return errors.New("wrong size") - } - Modp(x) - copy(b, x[:]) - return nil -} - -// IsZero returns true if x is equal to 0. -func IsZero(x *Elt) bool { Modp(x); return *x == Elt{} } - -// SetOne assigns x=1. -func SetOne(x *Elt) { *x = Elt{}; x[0] = 1 } - -// Neg calculates z = -x. -func Neg(z, x *Elt) { Sub(z, &p, x) } - -// InvSqrt calculates z = sqrt(x/y) iff x/y is a quadratic-residue, which is -// indicated by returning isQR = true. Otherwise, when x/y is a quadratic -// non-residue, z will have an undetermined value and isQR = false. -func InvSqrt(z, x, y *Elt) (isQR bool) { - sqrtMinusOne := &Elt{ - 0xb0, 0xa0, 0x0e, 0x4a, 0x27, 0x1b, 0xee, 0xc4, - 0x78, 0xe4, 0x2f, 0xad, 0x06, 0x18, 0x43, 0x2f, - 0xa7, 0xd7, 0xfb, 0x3d, 0x99, 0x00, 0x4d, 0x2b, - 0x0b, 0xdf, 0xc1, 0x4f, 0x80, 0x24, 0x83, 0x2b, - } - t0, t1, t2, t3 := &Elt{}, &Elt{}, &Elt{}, &Elt{} - - Mul(t0, x, y) // t0 = u*v - Sqr(t1, y) // t1 = v^2 - Mul(t2, t0, t1) // t2 = u*v^3 - Sqr(t0, t1) // t0 = v^4 - Mul(t1, t0, t2) // t1 = u*v^7 - - var Tab [4]*Elt - Tab[0] = &Elt{} - Tab[1] = &Elt{} - Tab[2] = t3 - Tab[3] = t1 - - *Tab[0] = *t1 - Sqr(Tab[0], Tab[0]) - Sqr(Tab[1], Tab[0]) - Sqr(Tab[1], Tab[1]) - Mul(Tab[1], Tab[1], Tab[3]) - Mul(Tab[0], Tab[0], Tab[1]) - Sqr(Tab[0], Tab[0]) - Mul(Tab[0], Tab[0], Tab[1]) - Sqr(Tab[1], Tab[0]) - for i := 0; i < 4; i++ { - Sqr(Tab[1], Tab[1]) - } - Mul(Tab[1], Tab[1], Tab[0]) - Sqr(Tab[2], Tab[1]) - for i := 0; i < 4; i++ { - Sqr(Tab[2], Tab[2]) - } - Mul(Tab[2], Tab[2], Tab[0]) - Sqr(Tab[1], Tab[2]) - for i := 0; i < 14; i++ { - Sqr(Tab[1], Tab[1]) - } - Mul(Tab[1], Tab[1], Tab[2]) - Sqr(Tab[2], Tab[1]) - for i := 0; i < 29; i++ { - Sqr(Tab[2], Tab[2]) - } - Mul(Tab[2], Tab[2], Tab[1]) - Sqr(Tab[1], Tab[2]) - for i := 0; i < 59; i++ { - Sqr(Tab[1], Tab[1]) - } - Mul(Tab[1], Tab[1], Tab[2]) - for i := 0; i < 5; i++ { - Sqr(Tab[1], Tab[1]) - } - Mul(Tab[1], Tab[1], Tab[0]) - Sqr(Tab[2], Tab[1]) - for i := 0; i < 124; i++ { - Sqr(Tab[2], Tab[2]) - } - Mul(Tab[2], Tab[2], Tab[1]) - Sqr(Tab[2], Tab[2]) - Sqr(Tab[2], Tab[2]) - Mul(Tab[2], Tab[2], Tab[3]) - - Mul(z, t3, t2) // z = xy^(p+3)/8 = xy^3*(xy^7)^(p-5)/8 - // Checking whether y z^2 == x - Sqr(t0, z) // t0 = z^2 - Mul(t0, t0, y) // t0 = yz^2 - Sub(t1, t0, x) // t1 = t0-u - Add(t2, t0, x) // t2 = t0+u - if IsZero(t1) { - return true - } else if IsZero(t2) { - Mul(z, z, sqrtMinusOne) // z = z*sqrt(-1) - return true - } else { - return false - } -} - -// Inv calculates z = 1/x mod p. -func Inv(z, x *Elt) { - x0, x1, x2 := &Elt{}, &Elt{}, &Elt{} - Sqr(x1, x) - Sqr(x0, x1) - Sqr(x0, x0) - Mul(x0, x0, x) - Mul(z, x0, x1) - Sqr(x1, z) - Mul(x0, x0, x1) - Sqr(x1, x0) - for i := 0; i < 4; i++ { - Sqr(x1, x1) - } - Mul(x0, x0, x1) - Sqr(x1, x0) - for i := 0; i < 9; i++ { - Sqr(x1, x1) - } - Mul(x1, x1, x0) - Sqr(x2, x1) - for i := 0; i < 19; i++ { - Sqr(x2, x2) - } - Mul(x2, x2, x1) - for i := 0; i < 10; i++ { - Sqr(x2, x2) - } - Mul(x2, x2, x0) - Sqr(x0, x2) - for i := 0; i < 49; i++ { - Sqr(x0, x0) - } - Mul(x0, x0, x2) - Sqr(x1, x0) - for i := 0; i < 99; i++ { - Sqr(x1, x1) - } - Mul(x1, x1, x0) - for i := 0; i < 50; i++ { - Sqr(x1, x1) - } - Mul(x1, x1, x2) - for i := 0; i < 5; i++ { - Sqr(x1, x1) - } - Mul(z, z, x1) -} - -// Cmov assigns y to x if n is 1. -func Cmov(x, y *Elt, n uint) { cmov(x, y, n) } - -// Cswap interchanges x and y if n is 1. -func Cswap(x, y *Elt, n uint) { cswap(x, y, n) } - -// Add calculates z = x+y mod p. -func Add(z, x, y *Elt) { add(z, x, y) } - -// Sub calculates z = x-y mod p. -func Sub(z, x, y *Elt) { sub(z, x, y) } - -// AddSub calculates (x,y) = (x+y mod p, x-y mod p). -func AddSub(x, y *Elt) { addsub(x, y) } - -// Mul calculates z = x*y mod p. -func Mul(z, x, y *Elt) { mul(z, x, y) } - -// Sqr calculates z = x^2 mod p. -func Sqr(z, x *Elt) { sqr(z, x) } - -// Modp ensures that z is between [0,p-1]. -func Modp(z *Elt) { modp(z) } diff --git a/vendor/github.com/cloudflare/circl/math/fp25519/fp_amd64.go b/vendor/github.com/cloudflare/circl/math/fp25519/fp_amd64.go deleted file mode 100644 index 057f0d28..00000000 --- a/vendor/github.com/cloudflare/circl/math/fp25519/fp_amd64.go +++ /dev/null @@ -1,45 +0,0 @@ -//go:build amd64 && !purego -// +build amd64,!purego - -package fp25519 - -import ( - "golang.org/x/sys/cpu" -) - -var hasBmi2Adx = cpu.X86.HasBMI2 && cpu.X86.HasADX - -var _ = hasBmi2Adx - -func cmov(x, y *Elt, n uint) { cmovAmd64(x, y, n) } -func cswap(x, y *Elt, n uint) { cswapAmd64(x, y, n) } -func add(z, x, y *Elt) { addAmd64(z, x, y) } -func sub(z, x, y *Elt) { subAmd64(z, x, y) } -func addsub(x, y *Elt) { addsubAmd64(x, y) } -func mul(z, x, y *Elt) { mulAmd64(z, x, y) } -func sqr(z, x *Elt) { sqrAmd64(z, x) } -func modp(z *Elt) { modpAmd64(z) } - -//go:noescape -func cmovAmd64(x, y *Elt, n uint) - -//go:noescape -func cswapAmd64(x, y *Elt, n uint) - -//go:noescape -func addAmd64(z, x, y *Elt) - -//go:noescape -func subAmd64(z, x, y *Elt) - -//go:noescape -func addsubAmd64(x, y *Elt) - -//go:noescape -func mulAmd64(z, x, y *Elt) - -//go:noescape -func sqrAmd64(z, x *Elt) - -//go:noescape -func modpAmd64(z *Elt) diff --git a/vendor/github.com/cloudflare/circl/math/fp25519/fp_amd64.h b/vendor/github.com/cloudflare/circl/math/fp25519/fp_amd64.h deleted file mode 100644 index 7b25f16e..00000000 --- a/vendor/github.com/cloudflare/circl/math/fp25519/fp_amd64.h +++ /dev/null @@ -1,350 +0,0 @@ -// This code was imported from https://github.com/armfazh/rfc7748_precomputed - -// CHECK_BMI2ADX triggers bmi2adx if supported, -// otherwise it fallbacks to legacy code. -#define CHECK_BMI2ADX(label, legacy, bmi2adx) \ - CMPB ·hasBmi2Adx(SB), $0 \ - JE label \ - bmi2adx \ - RET \ - label: \ - legacy \ - RET - -// cselect is a conditional move -// if b=1: it copies y into x; -// if b=0: x remains with the same value; -// if b<> 0,1: undefined. -// Uses: AX, DX, FLAGS -// Instr: x86_64, cmov -#define cselect(x,y,b) \ - TESTQ b, b \ - MOVQ 0+x, AX; MOVQ 0+y, DX; CMOVQNE DX, AX; MOVQ AX, 0+x; \ - MOVQ 8+x, AX; MOVQ 8+y, DX; CMOVQNE DX, AX; MOVQ AX, 8+x; \ - MOVQ 16+x, AX; MOVQ 16+y, DX; CMOVQNE DX, AX; MOVQ AX, 16+x; \ - MOVQ 24+x, AX; MOVQ 24+y, DX; CMOVQNE DX, AX; MOVQ AX, 24+x; - -// cswap is a conditional swap -// if b=1: x,y <- y,x; -// if b=0: x,y remain with the same values; -// if b<> 0,1: undefined. -// Uses: AX, DX, R8, FLAGS -// Instr: x86_64, cmov -#define cswap(x,y,b) \ - TESTQ b, b \ - MOVQ 0+x, AX; MOVQ AX, R8; MOVQ 0+y, DX; CMOVQNE DX, AX; CMOVQNE R8, DX; MOVQ AX, 0+x; MOVQ DX, 0+y; \ - MOVQ 8+x, AX; MOVQ AX, R8; MOVQ 8+y, DX; CMOVQNE DX, AX; CMOVQNE R8, DX; MOVQ AX, 8+x; MOVQ DX, 8+y; \ - MOVQ 16+x, AX; MOVQ AX, R8; MOVQ 16+y, DX; CMOVQNE DX, AX; CMOVQNE R8, DX; MOVQ AX, 16+x; MOVQ DX, 16+y; \ - MOVQ 24+x, AX; MOVQ AX, R8; MOVQ 24+y, DX; CMOVQNE DX, AX; CMOVQNE R8, DX; MOVQ AX, 24+x; MOVQ DX, 24+y; - -// additionLeg adds x and y and stores in z -// Uses: AX, DX, R8-R11, FLAGS -// Instr: x86_64, cmov -#define additionLeg(z,x,y) \ - MOVL $38, AX; \ - MOVL $0, DX; \ - MOVQ 0+x, R8; ADDQ 0+y, R8; \ - MOVQ 8+x, R9; ADCQ 8+y, R9; \ - MOVQ 16+x, R10; ADCQ 16+y, R10; \ - MOVQ 24+x, R11; ADCQ 24+y, R11; \ - CMOVQCS AX, DX; \ - ADDQ DX, R8; \ - ADCQ $0, R9; MOVQ R9, 8+z; \ - ADCQ $0, R10; MOVQ R10, 16+z; \ - ADCQ $0, R11; MOVQ R11, 24+z; \ - MOVL $0, DX; \ - CMOVQCS AX, DX; \ - ADDQ DX, R8; MOVQ R8, 0+z; - -// additionAdx adds x and y and stores in z -// Uses: AX, DX, R8-R11, FLAGS -// Instr: x86_64, cmov, adx -#define additionAdx(z,x,y) \ - MOVL $38, AX; \ - XORL DX, DX; \ - MOVQ 0+x, R8; ADCXQ 0+y, R8; \ - MOVQ 8+x, R9; ADCXQ 8+y, R9; \ - MOVQ 16+x, R10; ADCXQ 16+y, R10; \ - MOVQ 24+x, R11; ADCXQ 24+y, R11; \ - CMOVQCS AX, DX ; \ - XORL AX, AX; \ - ADCXQ DX, R8; \ - ADCXQ AX, R9; MOVQ R9, 8+z; \ - ADCXQ AX, R10; MOVQ R10, 16+z; \ - ADCXQ AX, R11; MOVQ R11, 24+z; \ - MOVL $38, DX; \ - CMOVQCS DX, AX; \ - ADDQ AX, R8; MOVQ R8, 0+z; - -// subtraction subtracts y from x and stores in z -// Uses: AX, DX, R8-R11, FLAGS -// Instr: x86_64, cmov -#define subtraction(z,x,y) \ - MOVL $38, AX; \ - MOVQ 0+x, R8; SUBQ 0+y, R8; \ - MOVQ 8+x, R9; SBBQ 8+y, R9; \ - MOVQ 16+x, R10; SBBQ 16+y, R10; \ - MOVQ 24+x, R11; SBBQ 24+y, R11; \ - MOVL $0, DX; \ - CMOVQCS AX, DX; \ - SUBQ DX, R8; \ - SBBQ $0, R9; MOVQ R9, 8+z; \ - SBBQ $0, R10; MOVQ R10, 16+z; \ - SBBQ $0, R11; MOVQ R11, 24+z; \ - MOVL $0, DX; \ - CMOVQCS AX, DX; \ - SUBQ DX, R8; MOVQ R8, 0+z; - -// integerMulAdx multiplies x and y and stores in z -// Uses: AX, DX, R8-R15, FLAGS -// Instr: x86_64, bmi2, adx -#define integerMulAdx(z,x,y) \ - MOVQ 0+y, DX; XORL AX, AX; \ - MULXQ 0+x, AX, R8; MOVQ AX, 0+z; \ - MULXQ 8+x, AX, R9; ADCXQ AX, R8; \ - MULXQ 16+x, AX, R10; ADCXQ AX, R9; \ - MULXQ 24+x, AX, R11; ADCXQ AX, R10; \ - MOVL $0, AX;;;;;;;;; ADCXQ AX, R11; \ - MOVQ 8+y, DX; XORL AX, AX; \ - MULXQ 0+x, AX, R12; ADCXQ R8, AX; MOVQ AX, 8+z; \ - MULXQ 8+x, AX, R13; ADCXQ R9, R12; ADOXQ AX, R12; \ - MULXQ 16+x, AX, R14; ADCXQ R10, R13; ADOXQ AX, R13; \ - MULXQ 24+x, AX, R15; ADCXQ R11, R14; ADOXQ AX, R14; \ - MOVL $0, AX;;;;;;;;; ADCXQ AX, R15; ADOXQ AX, R15; \ - MOVQ 16+y, DX; XORL AX, AX; \ - MULXQ 0+x, AX, R8; ADCXQ R12, AX; MOVQ AX, 16+z; \ - MULXQ 8+x, AX, R9; ADCXQ R13, R8; ADOXQ AX, R8; \ - MULXQ 16+x, AX, R10; ADCXQ R14, R9; ADOXQ AX, R9; \ - MULXQ 24+x, AX, R11; ADCXQ R15, R10; ADOXQ AX, R10; \ - MOVL $0, AX;;;;;;;;; ADCXQ AX, R11; ADOXQ AX, R11; \ - MOVQ 24+y, DX; XORL AX, AX; \ - MULXQ 0+x, AX, R12; ADCXQ R8, AX; MOVQ AX, 24+z; \ - MULXQ 8+x, AX, R13; ADCXQ R9, R12; ADOXQ AX, R12; MOVQ R12, 32+z; \ - MULXQ 16+x, AX, R14; ADCXQ R10, R13; ADOXQ AX, R13; MOVQ R13, 40+z; \ - MULXQ 24+x, AX, R15; ADCXQ R11, R14; ADOXQ AX, R14; MOVQ R14, 48+z; \ - MOVL $0, AX;;;;;;;;; ADCXQ AX, R15; ADOXQ AX, R15; MOVQ R15, 56+z; - -// integerMulLeg multiplies x and y and stores in z -// Uses: AX, DX, R8-R15, FLAGS -// Instr: x86_64 -#define integerMulLeg(z,x,y) \ - MOVQ 0+y, R8; \ - MOVQ 0+x, AX; MULQ R8; MOVQ AX, 0+z; MOVQ DX, R15; \ - MOVQ 8+x, AX; MULQ R8; MOVQ AX, R13; MOVQ DX, R10; \ - MOVQ 16+x, AX; MULQ R8; MOVQ AX, R14; MOVQ DX, R11; \ - MOVQ 24+x, AX; MULQ R8; \ - ADDQ R13, R15; \ - ADCQ R14, R10; MOVQ R10, 16+z; \ - ADCQ AX, R11; MOVQ R11, 24+z; \ - ADCQ $0, DX; MOVQ DX, 32+z; \ - MOVQ 8+y, R8; \ - MOVQ 0+x, AX; MULQ R8; MOVQ AX, R12; MOVQ DX, R9; \ - MOVQ 8+x, AX; MULQ R8; MOVQ AX, R13; MOVQ DX, R10; \ - MOVQ 16+x, AX; MULQ R8; MOVQ AX, R14; MOVQ DX, R11; \ - MOVQ 24+x, AX; MULQ R8; \ - ADDQ R12, R15; MOVQ R15, 8+z; \ - ADCQ R13, R9; \ - ADCQ R14, R10; \ - ADCQ AX, R11; \ - ADCQ $0, DX; \ - ADCQ 16+z, R9; MOVQ R9, R15; \ - ADCQ 24+z, R10; MOVQ R10, 24+z; \ - ADCQ 32+z, R11; MOVQ R11, 32+z; \ - ADCQ $0, DX; MOVQ DX, 40+z; \ - MOVQ 16+y, R8; \ - MOVQ 0+x, AX; MULQ R8; MOVQ AX, R12; MOVQ DX, R9; \ - MOVQ 8+x, AX; MULQ R8; MOVQ AX, R13; MOVQ DX, R10; \ - MOVQ 16+x, AX; MULQ R8; MOVQ AX, R14; MOVQ DX, R11; \ - MOVQ 24+x, AX; MULQ R8; \ - ADDQ R12, R15; MOVQ R15, 16+z; \ - ADCQ R13, R9; \ - ADCQ R14, R10; \ - ADCQ AX, R11; \ - ADCQ $0, DX; \ - ADCQ 24+z, R9; MOVQ R9, R15; \ - ADCQ 32+z, R10; MOVQ R10, 32+z; \ - ADCQ 40+z, R11; MOVQ R11, 40+z; \ - ADCQ $0, DX; MOVQ DX, 48+z; \ - MOVQ 24+y, R8; \ - MOVQ 0+x, AX; MULQ R8; MOVQ AX, R12; MOVQ DX, R9; \ - MOVQ 8+x, AX; MULQ R8; MOVQ AX, R13; MOVQ DX, R10; \ - MOVQ 16+x, AX; MULQ R8; MOVQ AX, R14; MOVQ DX, R11; \ - MOVQ 24+x, AX; MULQ R8; \ - ADDQ R12, R15; MOVQ R15, 24+z; \ - ADCQ R13, R9; \ - ADCQ R14, R10; \ - ADCQ AX, R11; \ - ADCQ $0, DX; \ - ADCQ 32+z, R9; MOVQ R9, 32+z; \ - ADCQ 40+z, R10; MOVQ R10, 40+z; \ - ADCQ 48+z, R11; MOVQ R11, 48+z; \ - ADCQ $0, DX; MOVQ DX, 56+z; - -// integerSqrLeg squares x and stores in z -// Uses: AX, CX, DX, R8-R15, FLAGS -// Instr: x86_64 -#define integerSqrLeg(z,x) \ - MOVQ 0+x, R8; \ - MOVQ 8+x, AX; MULQ R8; MOVQ AX, R9; MOVQ DX, R10; /* A[0]*A[1] */ \ - MOVQ 16+x, AX; MULQ R8; MOVQ AX, R14; MOVQ DX, R11; /* A[0]*A[2] */ \ - MOVQ 24+x, AX; MULQ R8; MOVQ AX, R15; MOVQ DX, R12; /* A[0]*A[3] */ \ - MOVQ 24+x, R8; \ - MOVQ 8+x, AX; MULQ R8; MOVQ AX, CX; MOVQ DX, R13; /* A[3]*A[1] */ \ - MOVQ 16+x, AX; MULQ R8; /* A[3]*A[2] */ \ - \ - ADDQ R14, R10;\ - ADCQ R15, R11; MOVL $0, R15;\ - ADCQ CX, R12;\ - ADCQ AX, R13;\ - ADCQ $0, DX; MOVQ DX, R14;\ - MOVQ 8+x, AX; MULQ 16+x;\ - \ - ADDQ AX, R11;\ - ADCQ DX, R12;\ - ADCQ $0, R13;\ - ADCQ $0, R14;\ - ADCQ $0, R15;\ - \ - SHLQ $1, R14, R15; MOVQ R15, 56+z;\ - SHLQ $1, R13, R14; MOVQ R14, 48+z;\ - SHLQ $1, R12, R13; MOVQ R13, 40+z;\ - SHLQ $1, R11, R12; MOVQ R12, 32+z;\ - SHLQ $1, R10, R11; MOVQ R11, 24+z;\ - SHLQ $1, R9, R10; MOVQ R10, 16+z;\ - SHLQ $1, R9; MOVQ R9, 8+z;\ - \ - MOVQ 0+x,AX; MULQ AX; MOVQ AX, 0+z; MOVQ DX, R9;\ - MOVQ 8+x,AX; MULQ AX; MOVQ AX, R10; MOVQ DX, R11;\ - MOVQ 16+x,AX; MULQ AX; MOVQ AX, R12; MOVQ DX, R13;\ - MOVQ 24+x,AX; MULQ AX; MOVQ AX, R14; MOVQ DX, R15;\ - \ - ADDQ 8+z, R9; MOVQ R9, 8+z;\ - ADCQ 16+z, R10; MOVQ R10, 16+z;\ - ADCQ 24+z, R11; MOVQ R11, 24+z;\ - ADCQ 32+z, R12; MOVQ R12, 32+z;\ - ADCQ 40+z, R13; MOVQ R13, 40+z;\ - ADCQ 48+z, R14; MOVQ R14, 48+z;\ - ADCQ 56+z, R15; MOVQ R15, 56+z; - -// integerSqrAdx squares x and stores in z -// Uses: AX, CX, DX, R8-R15, FLAGS -// Instr: x86_64, bmi2, adx -#define integerSqrAdx(z,x) \ - MOVQ 0+x, DX; /* A[0] */ \ - MULXQ 8+x, R8, R14; /* A[1]*A[0] */ XORL R15, R15; \ - MULXQ 16+x, R9, R10; /* A[2]*A[0] */ ADCXQ R14, R9; \ - MULXQ 24+x, AX, CX; /* A[3]*A[0] */ ADCXQ AX, R10; \ - MOVQ 24+x, DX; /* A[3] */ \ - MULXQ 8+x, R11, R12; /* A[1]*A[3] */ ADCXQ CX, R11; \ - MULXQ 16+x, AX, R13; /* A[2]*A[3] */ ADCXQ AX, R12; \ - MOVQ 8+x, DX; /* A[1] */ ADCXQ R15, R13; \ - MULXQ 16+x, AX, CX; /* A[2]*A[1] */ MOVL $0, R14; \ - ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ADCXQ R15, R14; \ - XORL R15, R15; \ - ADOXQ AX, R10; ADCXQ R8, R8; \ - ADOXQ CX, R11; ADCXQ R9, R9; \ - ADOXQ R15, R12; ADCXQ R10, R10; \ - ADOXQ R15, R13; ADCXQ R11, R11; \ - ADOXQ R15, R14; ADCXQ R12, R12; \ - ;;;;;;;;;;;;;;; ADCXQ R13, R13; \ - ;;;;;;;;;;;;;;; ADCXQ R14, R14; \ - MOVQ 0+x, DX; MULXQ DX, AX, CX; /* A[0]^2 */ \ - ;;;;;;;;;;;;;;; MOVQ AX, 0+z; \ - ADDQ CX, R8; MOVQ R8, 8+z; \ - MOVQ 8+x, DX; MULXQ DX, AX, CX; /* A[1]^2 */ \ - ADCQ AX, R9; MOVQ R9, 16+z; \ - ADCQ CX, R10; MOVQ R10, 24+z; \ - MOVQ 16+x, DX; MULXQ DX, AX, CX; /* A[2]^2 */ \ - ADCQ AX, R11; MOVQ R11, 32+z; \ - ADCQ CX, R12; MOVQ R12, 40+z; \ - MOVQ 24+x, DX; MULXQ DX, AX, CX; /* A[3]^2 */ \ - ADCQ AX, R13; MOVQ R13, 48+z; \ - ADCQ CX, R14; MOVQ R14, 56+z; - -// reduceFromDouble finds z congruent to x modulo p such that 0> 63) - // PUT BIT 255 IN CARRY FLAG AND CLEAR - x3 &^= 1 << 63 - - x0, c0 := bits.Add64(x0, cx, 0) - x1, c1 := bits.Add64(x1, 0, c0) - x2, c2 := bits.Add64(x2, 0, c1) - x3, _ = bits.Add64(x3, 0, c2) - - // TEST FOR BIT 255 AGAIN; ONLY TRIGGERED ON OVERFLOW MODULO 2^255-19 - // cx = C[255] ? 0 : 19 - cx = uint64(19) &^ (-(x3 >> 63)) - // CLEAR BIT 255 - x3 &^= 1 << 63 - - x0, c0 = bits.Sub64(x0, cx, 0) - x1, c1 = bits.Sub64(x1, 0, c0) - x2, c2 = bits.Sub64(x2, 0, c1) - x3, _ = bits.Sub64(x3, 0, c2) - - binary.LittleEndian.PutUint64(x[0*8:1*8], x0) - binary.LittleEndian.PutUint64(x[1*8:2*8], x1) - binary.LittleEndian.PutUint64(x[2*8:3*8], x2) - binary.LittleEndian.PutUint64(x[3*8:4*8], x3) -} - -func red64(z *Elt, x0, x1, x2, x3, x4, x5, x6, x7 uint64) { - h0, l0 := bits.Mul64(x4, 38) - h1, l1 := bits.Mul64(x5, 38) - h2, l2 := bits.Mul64(x6, 38) - h3, l3 := bits.Mul64(x7, 38) - - l1, c0 := bits.Add64(h0, l1, 0) - l2, c1 := bits.Add64(h1, l2, c0) - l3, c2 := bits.Add64(h2, l3, c1) - l4, _ := bits.Add64(h3, 0, c2) - - l0, c0 = bits.Add64(l0, x0, 0) - l1, c1 = bits.Add64(l1, x1, c0) - l2, c2 = bits.Add64(l2, x2, c1) - l3, c3 := bits.Add64(l3, x3, c2) - l4, _ = bits.Add64(l4, 0, c3) - - _, l4 = bits.Mul64(l4, 38) - l0, c0 = bits.Add64(l0, l4, 0) - z1, c1 := bits.Add64(l1, 0, c0) - z2, c2 := bits.Add64(l2, 0, c1) - z3, c3 := bits.Add64(l3, 0, c2) - z0, _ := bits.Add64(l0, (-c3)&38, 0) - - binary.LittleEndian.PutUint64(z[0*8:1*8], z0) - binary.LittleEndian.PutUint64(z[1*8:2*8], z1) - binary.LittleEndian.PutUint64(z[2*8:3*8], z2) - binary.LittleEndian.PutUint64(z[3*8:4*8], z3) -} diff --git a/vendor/github.com/cloudflare/circl/math/fp25519/fp_noasm.go b/vendor/github.com/cloudflare/circl/math/fp25519/fp_noasm.go deleted file mode 100644 index 26ca4d01..00000000 --- a/vendor/github.com/cloudflare/circl/math/fp25519/fp_noasm.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build !amd64 || purego -// +build !amd64 purego - -package fp25519 - -func cmov(x, y *Elt, n uint) { cmovGeneric(x, y, n) } -func cswap(x, y *Elt, n uint) { cswapGeneric(x, y, n) } -func add(z, x, y *Elt) { addGeneric(z, x, y) } -func sub(z, x, y *Elt) { subGeneric(z, x, y) } -func addsub(x, y *Elt) { addsubGeneric(x, y) } -func mul(z, x, y *Elt) { mulGeneric(z, x, y) } -func sqr(z, x *Elt) { sqrGeneric(z, x) } -func modp(z *Elt) { modpGeneric(z) } diff --git a/vendor/github.com/cloudflare/circl/math/fp448/fp.go b/vendor/github.com/cloudflare/circl/math/fp448/fp.go deleted file mode 100644 index a5e36600..00000000 --- a/vendor/github.com/cloudflare/circl/math/fp448/fp.go +++ /dev/null @@ -1,164 +0,0 @@ -// Package fp448 provides prime field arithmetic over GF(2^448-2^224-1). -package fp448 - -import ( - "errors" - - "github.com/cloudflare/circl/internal/conv" -) - -// Size in bytes of an element. -const Size = 56 - -// Elt is a prime field element. -type Elt [Size]byte - -func (e Elt) String() string { return conv.BytesLe2Hex(e[:]) } - -// p is the prime modulus 2^448-2^224-1. -var p = Elt{ - 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, 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, -} - -// P returns the prime modulus 2^448-2^224-1. -func P() Elt { return p } - -// ToBytes stores in b the little-endian byte representation of x. -func ToBytes(b []byte, x *Elt) error { - if len(b) != Size { - return errors.New("wrong size") - } - Modp(x) - copy(b, x[:]) - return nil -} - -// IsZero returns true if x is equal to 0. -func IsZero(x *Elt) bool { Modp(x); return *x == Elt{} } - -// IsOne returns true if x is equal to 1. -func IsOne(x *Elt) bool { Modp(x); return *x == Elt{1} } - -// SetOne assigns x=1. -func SetOne(x *Elt) { *x = Elt{1} } - -// One returns the 1 element. -func One() (x Elt) { x = Elt{1}; return } - -// Neg calculates z = -x. -func Neg(z, x *Elt) { Sub(z, &p, x) } - -// Modp ensures that z is between [0,p-1]. -func Modp(z *Elt) { Sub(z, z, &p) } - -// InvSqrt calculates z = sqrt(x/y) iff x/y is a quadratic-residue. If so, -// isQR = true; otherwise, isQR = false, since x/y is a quadratic non-residue, -// and z = sqrt(-x/y). -func InvSqrt(z, x, y *Elt) (isQR bool) { - // First note that x^(2(k+1)) = x^(p-1)/2 * x = legendre(x) * x - // so that's x if x is a quadratic residue and -x otherwise. - // Next, y^(6k+3) = y^(4k+2) * y^(2k+1) = y^(p-1) * y^((p-1)/2) = legendre(y). - // So the z we compute satisfies z^2 y = x^(2(k+1)) y^(6k+3) = legendre(x)*legendre(y). - // Thus if x and y are quadratic residues, then z is indeed sqrt(x/y). - t0, t1 := &Elt{}, &Elt{} - Mul(t0, x, y) // x*y - Sqr(t1, y) // y^2 - Mul(t1, t0, t1) // x*y^3 - powPminus3div4(z, t1) // (x*y^3)^k - Mul(z, z, t0) // z = x*y*(x*y^3)^k = x^(k+1) * y^(3k+1) - - // Check if x/y is a quadratic residue - Sqr(t0, z) // z^2 - Mul(t0, t0, y) // y*z^2 - Sub(t0, t0, x) // y*z^2-x - return IsZero(t0) -} - -// Inv calculates z = 1/x mod p. -func Inv(z, x *Elt) { - // Calculates z = x^(4k+1) = x^(p-3+1) = x^(p-2) = x^-1, where k = (p-3)/4. - t := &Elt{} - powPminus3div4(t, x) // t = x^k - Sqr(t, t) // t = x^2k - Sqr(t, t) // t = x^4k - Mul(z, t, x) // z = x^(4k+1) -} - -// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. -func powPminus3div4(z, x *Elt) { - x0, x1 := &Elt{}, &Elt{} - Sqr(z, x) - Mul(z, z, x) - Sqr(x0, z) - Mul(x0, x0, x) - Sqr(z, x0) - Sqr(z, z) - Sqr(z, z) - Mul(z, z, x0) - Sqr(x1, z) - for i := 0; i < 5; i++ { - Sqr(x1, x1) - } - Mul(x1, x1, z) - Sqr(z, x1) - for i := 0; i < 11; i++ { - Sqr(z, z) - } - Mul(z, z, x1) - Sqr(z, z) - Sqr(z, z) - Sqr(z, z) - Mul(z, z, x0) - Sqr(x1, z) - for i := 0; i < 26; i++ { - Sqr(x1, x1) - } - Mul(x1, x1, z) - Sqr(z, x1) - for i := 0; i < 53; i++ { - Sqr(z, z) - } - Mul(z, z, x1) - Sqr(z, z) - Sqr(z, z) - Sqr(z, z) - Mul(z, z, x0) - Sqr(x1, z) - for i := 0; i < 110; i++ { - Sqr(x1, x1) - } - Mul(x1, x1, z) - Sqr(z, x1) - Mul(z, z, x) - for i := 0; i < 223; i++ { - Sqr(z, z) - } - Mul(z, z, x1) -} - -// Cmov assigns y to x if n is 1. -func Cmov(x, y *Elt, n uint) { cmov(x, y, n) } - -// Cswap interchanges x and y if n is 1. -func Cswap(x, y *Elt, n uint) { cswap(x, y, n) } - -// Add calculates z = x+y mod p. -func Add(z, x, y *Elt) { add(z, x, y) } - -// Sub calculates z = x-y mod p. -func Sub(z, x, y *Elt) { sub(z, x, y) } - -// AddSub calculates (x,y) = (x+y mod p, x-y mod p). -func AddSub(x, y *Elt) { addsub(x, y) } - -// Mul calculates z = x*y mod p. -func Mul(z, x, y *Elt) { mul(z, x, y) } - -// Sqr calculates z = x^2 mod p. -func Sqr(z, x *Elt) { sqr(z, x) } diff --git a/vendor/github.com/cloudflare/circl/math/fp448/fp_amd64.go b/vendor/github.com/cloudflare/circl/math/fp448/fp_amd64.go deleted file mode 100644 index 6a12209a..00000000 --- a/vendor/github.com/cloudflare/circl/math/fp448/fp_amd64.go +++ /dev/null @@ -1,43 +0,0 @@ -//go:build amd64 && !purego -// +build amd64,!purego - -package fp448 - -import ( - "golang.org/x/sys/cpu" -) - -var hasBmi2Adx = cpu.X86.HasBMI2 && cpu.X86.HasADX - -var _ = hasBmi2Adx - -func cmov(x, y *Elt, n uint) { cmovAmd64(x, y, n) } -func cswap(x, y *Elt, n uint) { cswapAmd64(x, y, n) } -func add(z, x, y *Elt) { addAmd64(z, x, y) } -func sub(z, x, y *Elt) { subAmd64(z, x, y) } -func addsub(x, y *Elt) { addsubAmd64(x, y) } -func mul(z, x, y *Elt) { mulAmd64(z, x, y) } -func sqr(z, x *Elt) { sqrAmd64(z, x) } - -/* Functions defined in fp_amd64.s */ - -//go:noescape -func cmovAmd64(x, y *Elt, n uint) - -//go:noescape -func cswapAmd64(x, y *Elt, n uint) - -//go:noescape -func addAmd64(z, x, y *Elt) - -//go:noescape -func subAmd64(z, x, y *Elt) - -//go:noescape -func addsubAmd64(x, y *Elt) - -//go:noescape -func mulAmd64(z, x, y *Elt) - -//go:noescape -func sqrAmd64(z, x *Elt) diff --git a/vendor/github.com/cloudflare/circl/math/fp448/fp_amd64.h b/vendor/github.com/cloudflare/circl/math/fp448/fp_amd64.h deleted file mode 100644 index 0b7dea17..00000000 --- a/vendor/github.com/cloudflare/circl/math/fp448/fp_amd64.h +++ /dev/null @@ -1,590 +0,0 @@ -// This code was imported from https://github.com/armfazh/rfc7748_precomputed - -// CHECK_BMI2ADX triggers bmi2adx if supported, -// otherwise it fallbacks to legacy code. -#define CHECK_BMI2ADX(label, legacy, bmi2adx) \ - CMPB ·hasBmi2Adx(SB), $0 \ - JE label \ - bmi2adx \ - RET \ - label: \ - legacy \ - RET - -// cselect is a conditional move -// if b=1: it copies y into x; -// if b=0: x remains with the same value; -// if b<> 0,1: undefined. -// Uses: AX, DX, FLAGS -// Instr: x86_64, cmov -#define cselect(x,y,b) \ - TESTQ b, b \ - MOVQ 0+x, AX; MOVQ 0+y, DX; CMOVQNE DX, AX; MOVQ AX, 0+x; \ - MOVQ 8+x, AX; MOVQ 8+y, DX; CMOVQNE DX, AX; MOVQ AX, 8+x; \ - MOVQ 16+x, AX; MOVQ 16+y, DX; CMOVQNE DX, AX; MOVQ AX, 16+x; \ - MOVQ 24+x, AX; MOVQ 24+y, DX; CMOVQNE DX, AX; MOVQ AX, 24+x; \ - MOVQ 32+x, AX; MOVQ 32+y, DX; CMOVQNE DX, AX; MOVQ AX, 32+x; \ - MOVQ 40+x, AX; MOVQ 40+y, DX; CMOVQNE DX, AX; MOVQ AX, 40+x; \ - MOVQ 48+x, AX; MOVQ 48+y, DX; CMOVQNE DX, AX; MOVQ AX, 48+x; - -// cswap is a conditional swap -// if b=1: x,y <- y,x; -// if b=0: x,y remain with the same values; -// if b<> 0,1: undefined. -// Uses: AX, DX, R8, FLAGS -// Instr: x86_64, cmov -#define cswap(x,y,b) \ - TESTQ b, b \ - MOVQ 0+x, AX; MOVQ AX, R8; MOVQ 0+y, DX; CMOVQNE DX, AX; CMOVQNE R8, DX; MOVQ AX, 0+x; MOVQ DX, 0+y; \ - MOVQ 8+x, AX; MOVQ AX, R8; MOVQ 8+y, DX; CMOVQNE DX, AX; CMOVQNE R8, DX; MOVQ AX, 8+x; MOVQ DX, 8+y; \ - MOVQ 16+x, AX; MOVQ AX, R8; MOVQ 16+y, DX; CMOVQNE DX, AX; CMOVQNE R8, DX; MOVQ AX, 16+x; MOVQ DX, 16+y; \ - MOVQ 24+x, AX; MOVQ AX, R8; MOVQ 24+y, DX; CMOVQNE DX, AX; CMOVQNE R8, DX; MOVQ AX, 24+x; MOVQ DX, 24+y; \ - MOVQ 32+x, AX; MOVQ AX, R8; MOVQ 32+y, DX; CMOVQNE DX, AX; CMOVQNE R8, DX; MOVQ AX, 32+x; MOVQ DX, 32+y; \ - MOVQ 40+x, AX; MOVQ AX, R8; MOVQ 40+y, DX; CMOVQNE DX, AX; CMOVQNE R8, DX; MOVQ AX, 40+x; MOVQ DX, 40+y; \ - MOVQ 48+x, AX; MOVQ AX, R8; MOVQ 48+y, DX; CMOVQNE DX, AX; CMOVQNE R8, DX; MOVQ AX, 48+x; MOVQ DX, 48+y; - -// additionLeg adds x and y and stores in z -// Uses: AX, DX, R8-R14, FLAGS -// Instr: x86_64 -#define additionLeg(z,x,y) \ - MOVQ 0+x, R8; ADDQ 0+y, R8; \ - MOVQ 8+x, R9; ADCQ 8+y, R9; \ - MOVQ 16+x, R10; ADCQ 16+y, R10; \ - MOVQ 24+x, R11; ADCQ 24+y, R11; \ - MOVQ 32+x, R12; ADCQ 32+y, R12; \ - MOVQ 40+x, R13; ADCQ 40+y, R13; \ - MOVQ 48+x, R14; ADCQ 48+y, R14; \ - MOVQ $0, AX; ADCQ $0, AX; \ - MOVQ AX, DX; \ - SHLQ $32, DX; \ - ADDQ AX, R8; MOVQ $0, AX; \ - ADCQ $0, R9; \ - ADCQ $0, R10; \ - ADCQ DX, R11; \ - ADCQ $0, R12; \ - ADCQ $0, R13; \ - ADCQ $0, R14; \ - ADCQ $0, AX; \ - MOVQ AX, DX; \ - SHLQ $32, DX; \ - ADDQ AX, R8; MOVQ R8, 0+z; \ - ADCQ $0, R9; MOVQ R9, 8+z; \ - ADCQ $0, R10; MOVQ R10, 16+z; \ - ADCQ DX, R11; MOVQ R11, 24+z; \ - ADCQ $0, R12; MOVQ R12, 32+z; \ - ADCQ $0, R13; MOVQ R13, 40+z; \ - ADCQ $0, R14; MOVQ R14, 48+z; - - -// additionAdx adds x and y and stores in z -// Uses: AX, DX, R8-R15, FLAGS -// Instr: x86_64, adx -#define additionAdx(z,x,y) \ - MOVL $32, R15; \ - XORL DX, DX; \ - MOVQ 0+x, R8; ADCXQ 0+y, R8; \ - MOVQ 8+x, R9; ADCXQ 8+y, R9; \ - MOVQ 16+x, R10; ADCXQ 16+y, R10; \ - MOVQ 24+x, R11; ADCXQ 24+y, R11; \ - MOVQ 32+x, R12; ADCXQ 32+y, R12; \ - MOVQ 40+x, R13; ADCXQ 40+y, R13; \ - MOVQ 48+x, R14; ADCXQ 48+y, R14; \ - ;;;;;;;;;;;;;;; ADCXQ DX, DX; \ - XORL AX, AX; \ - ADCXQ DX, R8; SHLXQ R15, DX, DX; \ - ADCXQ AX, R9; \ - ADCXQ AX, R10; \ - ADCXQ DX, R11; \ - ADCXQ AX, R12; \ - ADCXQ AX, R13; \ - ADCXQ AX, R14; \ - ADCXQ AX, AX; \ - XORL DX, DX; \ - ADCXQ AX, R8; MOVQ R8, 0+z; SHLXQ R15, AX, AX; \ - ADCXQ DX, R9; MOVQ R9, 8+z; \ - ADCXQ DX, R10; MOVQ R10, 16+z; \ - ADCXQ AX, R11; MOVQ R11, 24+z; \ - ADCXQ DX, R12; MOVQ R12, 32+z; \ - ADCXQ DX, R13; MOVQ R13, 40+z; \ - ADCXQ DX, R14; MOVQ R14, 48+z; - -// subtraction subtracts y from x and stores in z -// Uses: AX, DX, R8-R14, FLAGS -// Instr: x86_64 -#define subtraction(z,x,y) \ - MOVQ 0+x, R8; SUBQ 0+y, R8; \ - MOVQ 8+x, R9; SBBQ 8+y, R9; \ - MOVQ 16+x, R10; SBBQ 16+y, R10; \ - MOVQ 24+x, R11; SBBQ 24+y, R11; \ - MOVQ 32+x, R12; SBBQ 32+y, R12; \ - MOVQ 40+x, R13; SBBQ 40+y, R13; \ - MOVQ 48+x, R14; SBBQ 48+y, R14; \ - MOVQ $0, AX; SETCS AX; \ - MOVQ AX, DX; \ - SHLQ $32, DX; \ - SUBQ AX, R8; MOVQ $0, AX; \ - SBBQ $0, R9; \ - SBBQ $0, R10; \ - SBBQ DX, R11; \ - SBBQ $0, R12; \ - SBBQ $0, R13; \ - SBBQ $0, R14; \ - SETCS AX; \ - MOVQ AX, DX; \ - SHLQ $32, DX; \ - SUBQ AX, R8; MOVQ R8, 0+z; \ - SBBQ $0, R9; MOVQ R9, 8+z; \ - SBBQ $0, R10; MOVQ R10, 16+z; \ - SBBQ DX, R11; MOVQ R11, 24+z; \ - SBBQ $0, R12; MOVQ R12, 32+z; \ - SBBQ $0, R13; MOVQ R13, 40+z; \ - SBBQ $0, R14; MOVQ R14, 48+z; - -// maddBmi2Adx multiplies x and y and accumulates in z -// Uses: AX, DX, R15, FLAGS -// Instr: x86_64, bmi2, adx -#define maddBmi2Adx(z,x,y,i,r0,r1,r2,r3,r4,r5,r6) \ - MOVQ i+y, DX; XORL AX, AX; \ - MULXQ 0+x, AX, R8; ADOXQ AX, r0; ADCXQ R8, r1; MOVQ r0,i+z; \ - MULXQ 8+x, AX, r0; ADOXQ AX, r1; ADCXQ r0, r2; MOVQ $0, R8; \ - MULXQ 16+x, AX, r0; ADOXQ AX, r2; ADCXQ r0, r3; \ - MULXQ 24+x, AX, r0; ADOXQ AX, r3; ADCXQ r0, r4; \ - MULXQ 32+x, AX, r0; ADOXQ AX, r4; ADCXQ r0, r5; \ - MULXQ 40+x, AX, r0; ADOXQ AX, r5; ADCXQ r0, r6; \ - MULXQ 48+x, AX, r0; ADOXQ AX, r6; ADCXQ R8, r0; \ - ;;;;;;;;;;;;;;;;;;; ADOXQ R8, r0; - -// integerMulAdx multiplies x and y and stores in z -// Uses: AX, DX, R8-R15, FLAGS -// Instr: x86_64, bmi2, adx -#define integerMulAdx(z,x,y) \ - MOVQ 0+y, DX; XORL AX, AX; MOVQ $0, R8; \ - MULXQ 0+x, AX, R9; MOVQ AX, 0+z; \ - MULXQ 8+x, AX, R10; ADCXQ AX, R9; \ - MULXQ 16+x, AX, R11; ADCXQ AX, R10; \ - MULXQ 24+x, AX, R12; ADCXQ AX, R11; \ - MULXQ 32+x, AX, R13; ADCXQ AX, R12; \ - MULXQ 40+x, AX, R14; ADCXQ AX, R13; \ - MULXQ 48+x, AX, R15; ADCXQ AX, R14; \ - ;;;;;;;;;;;;;;;;;;;; ADCXQ R8, R15; \ - maddBmi2Adx(z,x,y, 8, R9,R10,R11,R12,R13,R14,R15) \ - maddBmi2Adx(z,x,y,16,R10,R11,R12,R13,R14,R15, R9) \ - maddBmi2Adx(z,x,y,24,R11,R12,R13,R14,R15, R9,R10) \ - maddBmi2Adx(z,x,y,32,R12,R13,R14,R15, R9,R10,R11) \ - maddBmi2Adx(z,x,y,40,R13,R14,R15, R9,R10,R11,R12) \ - maddBmi2Adx(z,x,y,48,R14,R15, R9,R10,R11,R12,R13) \ - MOVQ R15, 56+z; \ - MOVQ R9, 64+z; \ - MOVQ R10, 72+z; \ - MOVQ R11, 80+z; \ - MOVQ R12, 88+z; \ - MOVQ R13, 96+z; \ - MOVQ R14, 104+z; - -// maddLegacy multiplies x and y and accumulates in z -// Uses: AX, DX, R15, FLAGS -// Instr: x86_64 -#define maddLegacy(z,x,y,i) \ - MOVQ i+y, R15; \ - MOVQ 0+x, AX; MULQ R15; MOVQ AX, R8; ;;;;;;;;;;;; MOVQ DX, R9; \ - MOVQ 8+x, AX; MULQ R15; ADDQ AX, R9; ADCQ $0, DX; MOVQ DX, R10; \ - MOVQ 16+x, AX; MULQ R15; ADDQ AX, R10; ADCQ $0, DX; MOVQ DX, R11; \ - MOVQ 24+x, AX; MULQ R15; ADDQ AX, R11; ADCQ $0, DX; MOVQ DX, R12; \ - MOVQ 32+x, AX; MULQ R15; ADDQ AX, R12; ADCQ $0, DX; MOVQ DX, R13; \ - MOVQ 40+x, AX; MULQ R15; ADDQ AX, R13; ADCQ $0, DX; MOVQ DX, R14; \ - MOVQ 48+x, AX; MULQ R15; ADDQ AX, R14; ADCQ $0, DX; \ - ADDQ 0+i+z, R8; MOVQ R8, 0+i+z; \ - ADCQ 8+i+z, R9; MOVQ R9, 8+i+z; \ - ADCQ 16+i+z, R10; MOVQ R10, 16+i+z; \ - ADCQ 24+i+z, R11; MOVQ R11, 24+i+z; \ - ADCQ 32+i+z, R12; MOVQ R12, 32+i+z; \ - ADCQ 40+i+z, R13; MOVQ R13, 40+i+z; \ - ADCQ 48+i+z, R14; MOVQ R14, 48+i+z; \ - ADCQ $0, DX; MOVQ DX, 56+i+z; - -// integerMulLeg multiplies x and y and stores in z -// Uses: AX, DX, R8-R15, FLAGS -// Instr: x86_64 -#define integerMulLeg(z,x,y) \ - MOVQ 0+y, R15; \ - MOVQ 0+x, AX; MULQ R15; MOVQ AX, 0+z; ;;;;;;;;;;;; MOVQ DX, R8; \ - MOVQ 8+x, AX; MULQ R15; ADDQ AX, R8; ADCQ $0, DX; MOVQ DX, R9; MOVQ R8, 8+z; \ - MOVQ 16+x, AX; MULQ R15; ADDQ AX, R9; ADCQ $0, DX; MOVQ DX, R10; MOVQ R9, 16+z; \ - MOVQ 24+x, AX; MULQ R15; ADDQ AX, R10; ADCQ $0, DX; MOVQ DX, R11; MOVQ R10, 24+z; \ - MOVQ 32+x, AX; MULQ R15; ADDQ AX, R11; ADCQ $0, DX; MOVQ DX, R12; MOVQ R11, 32+z; \ - MOVQ 40+x, AX; MULQ R15; ADDQ AX, R12; ADCQ $0, DX; MOVQ DX, R13; MOVQ R12, 40+z; \ - MOVQ 48+x, AX; MULQ R15; ADDQ AX, R13; ADCQ $0, DX; MOVQ DX,56+z; MOVQ R13, 48+z; \ - maddLegacy(z,x,y, 8) \ - maddLegacy(z,x,y,16) \ - maddLegacy(z,x,y,24) \ - maddLegacy(z,x,y,32) \ - maddLegacy(z,x,y,40) \ - maddLegacy(z,x,y,48) - -// integerSqrLeg squares x and stores in z -// Uses: AX, CX, DX, R8-R15, FLAGS -// Instr: x86_64 -#define integerSqrLeg(z,x) \ - XORL R15, R15; \ - MOVQ 0+x, CX; \ - MOVQ CX, AX; MULQ CX; MOVQ AX, 0+z; MOVQ DX, R8; \ - ADDQ CX, CX; ADCQ $0, R15; \ - MOVQ 8+x, AX; MULQ CX; ADDQ AX, R8; ADCQ $0, DX; MOVQ DX, R9; MOVQ R8, 8+z; \ - MOVQ 16+x, AX; MULQ CX; ADDQ AX, R9; ADCQ $0, DX; MOVQ DX, R10; \ - MOVQ 24+x, AX; MULQ CX; ADDQ AX, R10; ADCQ $0, DX; MOVQ DX, R11; \ - MOVQ 32+x, AX; MULQ CX; ADDQ AX, R11; ADCQ $0, DX; MOVQ DX, R12; \ - MOVQ 40+x, AX; MULQ CX; ADDQ AX, R12; ADCQ $0, DX; MOVQ DX, R13; \ - MOVQ 48+x, AX; MULQ CX; ADDQ AX, R13; ADCQ $0, DX; MOVQ DX, R14; \ - \ - MOVQ 8+x, CX; \ - MOVQ CX, AX; ADDQ R15, CX; MOVQ $0, R15; ADCQ $0, R15; \ - ;;;;;;;;;;;;;; MULQ CX; ADDQ AX, R9; ADCQ $0, DX; MOVQ R9,16+z; \ - MOVQ R15, AX; NEGQ AX; ANDQ 8+x, AX; ADDQ AX, DX; ADCQ $0, R11; MOVQ DX, R8; \ - ADDQ 8+x, CX; ADCQ $0, R15; \ - MOVQ 16+x, AX; MULQ CX; ADDQ AX, R10; ADCQ $0, DX; ADDQ R8, R10; ADCQ $0, DX; MOVQ DX, R8; MOVQ R10, 24+z; \ - MOVQ 24+x, AX; MULQ CX; ADDQ AX, R11; ADCQ $0, DX; ADDQ R8, R11; ADCQ $0, DX; MOVQ DX, R8; \ - MOVQ 32+x, AX; MULQ CX; ADDQ AX, R12; ADCQ $0, DX; ADDQ R8, R12; ADCQ $0, DX; MOVQ DX, R8; \ - MOVQ 40+x, AX; MULQ CX; ADDQ AX, R13; ADCQ $0, DX; ADDQ R8, R13; ADCQ $0, DX; MOVQ DX, R8; \ - MOVQ 48+x, AX; MULQ CX; ADDQ AX, R14; ADCQ $0, DX; ADDQ R8, R14; ADCQ $0, DX; MOVQ DX, R9; \ - \ - MOVQ 16+x, CX; \ - MOVQ CX, AX; ADDQ R15, CX; MOVQ $0, R15; ADCQ $0, R15; \ - ;;;;;;;;;;;;;; MULQ CX; ADDQ AX, R11; ADCQ $0, DX; MOVQ R11, 32+z; \ - MOVQ R15, AX; NEGQ AX; ANDQ 16+x,AX; ADDQ AX, DX; ADCQ $0, R13; MOVQ DX, R8; \ - ADDQ 16+x, CX; ADCQ $0, R15; \ - MOVQ 24+x, AX; MULQ CX; ADDQ AX, R12; ADCQ $0, DX; ADDQ R8, R12; ADCQ $0, DX; MOVQ DX, R8; MOVQ R12, 40+z; \ - MOVQ 32+x, AX; MULQ CX; ADDQ AX, R13; ADCQ $0, DX; ADDQ R8, R13; ADCQ $0, DX; MOVQ DX, R8; \ - MOVQ 40+x, AX; MULQ CX; ADDQ AX, R14; ADCQ $0, DX; ADDQ R8, R14; ADCQ $0, DX; MOVQ DX, R8; \ - MOVQ 48+x, AX; MULQ CX; ADDQ AX, R9; ADCQ $0, DX; ADDQ R8, R9; ADCQ $0, DX; MOVQ DX,R10; \ - \ - MOVQ 24+x, CX; \ - MOVQ CX, AX; ADDQ R15, CX; MOVQ $0, R15; ADCQ $0, R15; \ - ;;;;;;;;;;;;;; MULQ CX; ADDQ AX, R13; ADCQ $0, DX; MOVQ R13, 48+z; \ - MOVQ R15, AX; NEGQ AX; ANDQ 24+x,AX; ADDQ AX, DX; ADCQ $0, R9; MOVQ DX, R8; \ - ADDQ 24+x, CX; ADCQ $0, R15; \ - MOVQ 32+x, AX; MULQ CX; ADDQ AX, R14; ADCQ $0, DX; ADDQ R8, R14; ADCQ $0, DX; MOVQ DX, R8; MOVQ R14, 56+z; \ - MOVQ 40+x, AX; MULQ CX; ADDQ AX, R9; ADCQ $0, DX; ADDQ R8, R9; ADCQ $0, DX; MOVQ DX, R8; \ - MOVQ 48+x, AX; MULQ CX; ADDQ AX, R10; ADCQ $0, DX; ADDQ R8, R10; ADCQ $0, DX; MOVQ DX,R11; \ - \ - MOVQ 32+x, CX; \ - MOVQ CX, AX; ADDQ R15, CX; MOVQ $0, R15; ADCQ $0, R15; \ - ;;;;;;;;;;;;;; MULQ CX; ADDQ AX, R9; ADCQ $0, DX; MOVQ R9, 64+z; \ - MOVQ R15, AX; NEGQ AX; ANDQ 32+x,AX; ADDQ AX, DX; ADCQ $0, R11; MOVQ DX, R8; \ - ADDQ 32+x, CX; ADCQ $0, R15; \ - MOVQ 40+x, AX; MULQ CX; ADDQ AX, R10; ADCQ $0, DX; ADDQ R8, R10; ADCQ $0, DX; MOVQ DX, R8; MOVQ R10, 72+z; \ - MOVQ 48+x, AX; MULQ CX; ADDQ AX, R11; ADCQ $0, DX; ADDQ R8, R11; ADCQ $0, DX; MOVQ DX,R12; \ - \ - XORL R13, R13; \ - XORL R14, R14; \ - MOVQ 40+x, CX; \ - MOVQ CX, AX; ADDQ R15, CX; MOVQ $0, R15; ADCQ $0, R15; \ - ;;;;;;;;;;;;;; MULQ CX; ADDQ AX, R11; ADCQ $0, DX; MOVQ R11, 80+z; \ - MOVQ R15, AX; NEGQ AX; ANDQ 40+x,AX; ADDQ AX, DX; ADCQ $0, R13; MOVQ DX, R8; \ - ADDQ 40+x, CX; ADCQ $0, R15; \ - MOVQ 48+x, AX; MULQ CX; ADDQ AX, R12; ADCQ $0, DX; ADDQ R8, R12; ADCQ $0, DX; MOVQ DX, R8; MOVQ R12, 88+z; \ - ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ADDQ R8, R13; ADCQ $0,R14; \ - \ - XORL R9, R9; \ - MOVQ 48+x, CX; \ - MOVQ CX, AX; ADDQ R15, CX; MOVQ $0, R15; ADCQ $0, R15; \ - ;;;;;;;;;;;;;; MULQ CX; ADDQ AX, R13; ADCQ $0, DX; MOVQ R13, 96+z; \ - MOVQ R15, AX; NEGQ AX; ANDQ 48+x,AX; ADDQ AX, DX; ADCQ $0, R9; MOVQ DX, R8; \ - ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ADDQ R8,R14; ADCQ $0, R9; MOVQ R14, 104+z; - - -// integerSqrAdx squares x and stores in z -// Uses: AX, CX, DX, R8-R15, FLAGS -// Instr: x86_64, bmi2, adx -#define integerSqrAdx(z,x) \ - XORL R15, R15; \ - MOVQ 0+x, DX; \ - ;;;;;;;;;;;;;; MULXQ DX, AX, R8; MOVQ AX, 0+z; \ - ADDQ DX, DX; ADCQ $0, R15; CLC; \ - MULXQ 8+x, AX, R9; ADCXQ AX, R8; MOVQ R8, 8+z; \ - MULXQ 16+x, AX, R10; ADCXQ AX, R9; MOVQ $0, R8;\ - MULXQ 24+x, AX, R11; ADCXQ AX, R10; \ - MULXQ 32+x, AX, R12; ADCXQ AX, R11; \ - MULXQ 40+x, AX, R13; ADCXQ AX, R12; \ - MULXQ 48+x, AX, R14; ADCXQ AX, R13; \ - ;;;;;;;;;;;;;;;;;;;; ADCXQ R8, R14; \ - \ - MOVQ 8+x, DX; \ - MOVQ DX, AX; ADDQ R15, DX; MOVQ $0, R15; ADCQ $0, R15; \ - MULXQ AX, AX, CX; \ - MOVQ R15, R8; NEGQ R8; ANDQ 8+x, R8; \ - ADDQ AX, R9; MOVQ R9, 16+z; \ - ADCQ CX, R8; \ - ADCQ $0, R11; \ - ADDQ 8+x, DX; \ - ADCQ $0, R15; \ - XORL R9, R9; ;;;;;;;;;;;;;;;;;;;;; ADOXQ R8, R10; \ - MULXQ 16+x, AX, CX; ADCXQ AX, R10; ADOXQ CX, R11; MOVQ R10, 24+z; \ - MULXQ 24+x, AX, CX; ADCXQ AX, R11; ADOXQ CX, R12; MOVQ $0, R10; \ - MULXQ 32+x, AX, CX; ADCXQ AX, R12; ADOXQ CX, R13; \ - MULXQ 40+x, AX, CX; ADCXQ AX, R13; ADOXQ CX, R14; \ - MULXQ 48+x, AX, CX; ADCXQ AX, R14; ADOXQ CX, R9; \ - ;;;;;;;;;;;;;;;;;;; ADCXQ R10, R9; \ - \ - MOVQ 16+x, DX; \ - MOVQ DX, AX; ADDQ R15, DX; MOVQ $0, R15; ADCQ $0, R15; \ - MULXQ AX, AX, CX; \ - MOVQ R15, R8; NEGQ R8; ANDQ 16+x, R8; \ - ADDQ AX, R11; MOVQ R11, 32+z; \ - ADCQ CX, R8; \ - ADCQ $0, R13; \ - ADDQ 16+x, DX; \ - ADCQ $0, R15; \ - XORL R11, R11; ;;;;;;;;;;;;;;;;;;; ADOXQ R8, R12; \ - MULXQ 24+x, AX, CX; ADCXQ AX, R12; ADOXQ CX, R13; MOVQ R12, 40+z; \ - MULXQ 32+x, AX, CX; ADCXQ AX, R13; ADOXQ CX, R14; MOVQ $0, R12; \ - MULXQ 40+x, AX, CX; ADCXQ AX, R14; ADOXQ CX, R9; \ - MULXQ 48+x, AX, CX; ADCXQ AX, R9; ADOXQ CX, R10; \ - ;;;;;;;;;;;;;;;;;;; ADCXQ R11,R10; \ - \ - MOVQ 24+x, DX; \ - MOVQ DX, AX; ADDQ R15, DX; MOVQ $0, R15; ADCQ $0, R15; \ - MULXQ AX, AX, CX; \ - MOVQ R15, R8; NEGQ R8; ANDQ 24+x, R8; \ - ADDQ AX, R13; MOVQ R13, 48+z; \ - ADCQ CX, R8; \ - ADCQ $0, R9; \ - ADDQ 24+x, DX; \ - ADCQ $0, R15; \ - XORL R13, R13; ;;;;;;;;;;;;;;;;;;; ADOXQ R8, R14; \ - MULXQ 32+x, AX, CX; ADCXQ AX, R14; ADOXQ CX, R9; MOVQ R14, 56+z; \ - MULXQ 40+x, AX, CX; ADCXQ AX, R9; ADOXQ CX, R10; MOVQ $0, R14; \ - MULXQ 48+x, AX, CX; ADCXQ AX, R10; ADOXQ CX, R11; \ - ;;;;;;;;;;;;;;;;;;; ADCXQ R12,R11; \ - \ - MOVQ 32+x, DX; \ - MOVQ DX, AX; ADDQ R15, DX; MOVQ $0, R15; ADCQ $0, R15; \ - MULXQ AX, AX, CX; \ - MOVQ R15, R8; NEGQ R8; ANDQ 32+x, R8; \ - ADDQ AX, R9; MOVQ R9, 64+z; \ - ADCQ CX, R8; \ - ADCQ $0, R11; \ - ADDQ 32+x, DX; \ - ADCQ $0, R15; \ - XORL R9, R9; ;;;;;;;;;;;;;;;;;;;;; ADOXQ R8, R10; \ - MULXQ 40+x, AX, CX; ADCXQ AX, R10; ADOXQ CX, R11; MOVQ R10, 72+z; \ - MULXQ 48+x, AX, CX; ADCXQ AX, R11; ADOXQ CX, R12; \ - ;;;;;;;;;;;;;;;;;;; ADCXQ R13,R12; \ - \ - MOVQ 40+x, DX; \ - MOVQ DX, AX; ADDQ R15, DX; MOVQ $0, R15; ADCQ $0, R15; \ - MULXQ AX, AX, CX; \ - MOVQ R15, R8; NEGQ R8; ANDQ 40+x, R8; \ - ADDQ AX, R11; MOVQ R11, 80+z; \ - ADCQ CX, R8; \ - ADCQ $0, R13; \ - ADDQ 40+x, DX; \ - ADCQ $0, R15; \ - XORL R11, R11; ;;;;;;;;;;;;;;;;;;; ADOXQ R8, R12; \ - MULXQ 48+x, AX, CX; ADCXQ AX, R12; ADOXQ CX, R13; MOVQ R12, 88+z; \ - ;;;;;;;;;;;;;;;;;;; ADCXQ R14,R13; \ - \ - MOVQ 48+x, DX; \ - MOVQ DX, AX; ADDQ R15, DX; MOVQ $0, R15; ADCQ $0, R15; \ - MULXQ AX, AX, CX; \ - MOVQ R15, R8; NEGQ R8; ANDQ 48+x, R8; \ - XORL R10, R10; ;;;;;;;;;;;;;; ADOXQ CX, R14; \ - ;;;;;;;;;;;;;; ADCXQ AX, R13; ;;;;;;;;;;;;;; MOVQ R13, 96+z; \ - ;;;;;;;;;;;;;; ADCXQ R8, R14; MOVQ R14, 104+z; - -// reduceFromDoubleLeg finds a z=x modulo p such that z<2^448 and stores in z -// Uses: AX, R8-R15, FLAGS -// Instr: x86_64 -#define reduceFromDoubleLeg(z,x) \ - /* ( ,2C13,2C12,2C11,2C10|C10,C9,C8, C7) + (C6,...,C0) */ \ - /* (r14, r13, r12, r11, r10,r9,r8,r15) */ \ - MOVQ 80+x,AX; MOVQ AX,R10; \ - MOVQ $0xFFFFFFFF00000000, R8; \ - ANDQ R8,R10; \ - \ - MOVQ $0,R14; \ - MOVQ 104+x,R13; SHLQ $1,R13,R14; \ - MOVQ 96+x,R12; SHLQ $1,R12,R13; \ - MOVQ 88+x,R11; SHLQ $1,R11,R12; \ - MOVQ 72+x, R9; SHLQ $1,R10,R11; \ - MOVQ 64+x, R8; SHLQ $1,R10; \ - MOVQ $0xFFFFFFFF,R15; ANDQ R15,AX; ORQ AX,R10; \ - MOVQ 56+x,R15; \ - \ - ADDQ 0+x,R15; MOVQ R15, 0+z; MOVQ 56+x,R15; \ - ADCQ 8+x, R8; MOVQ R8, 8+z; MOVQ 64+x, R8; \ - ADCQ 16+x, R9; MOVQ R9,16+z; MOVQ 72+x, R9; \ - ADCQ 24+x,R10; MOVQ R10,24+z; MOVQ 80+x,R10; \ - ADCQ 32+x,R11; MOVQ R11,32+z; MOVQ 88+x,R11; \ - ADCQ 40+x,R12; MOVQ R12,40+z; MOVQ 96+x,R12; \ - ADCQ 48+x,R13; MOVQ R13,48+z; MOVQ 104+x,R13; \ - ADCQ $0,R14; \ - /* (c10c9,c9c8,c8c7,c7c13,c13c12,c12c11,c11c10) + (c6,...,c0) */ \ - /* ( r9, r8, r15, r13, r12, r11, r10) */ \ - MOVQ R10, AX; \ - SHRQ $32,R11,R10; \ - SHRQ $32,R12,R11; \ - SHRQ $32,R13,R12; \ - SHRQ $32,R15,R13; \ - SHRQ $32, R8,R15; \ - SHRQ $32, R9, R8; \ - SHRQ $32, AX, R9; \ - \ - ADDQ 0+z,R10; \ - ADCQ 8+z,R11; \ - ADCQ 16+z,R12; \ - ADCQ 24+z,R13; \ - ADCQ 32+z,R15; \ - ADCQ 40+z, R8; \ - ADCQ 48+z, R9; \ - ADCQ $0,R14; \ - /* ( c7) + (c6,...,c0) */ \ - /* (r14) */ \ - MOVQ R14, AX; SHLQ $32, AX; \ - ADDQ R14,R10; MOVQ $0,R14; \ - ADCQ $0,R11; \ - ADCQ $0,R12; \ - ADCQ AX,R13; \ - ADCQ $0,R15; \ - ADCQ $0, R8; \ - ADCQ $0, R9; \ - ADCQ $0,R14; \ - /* ( c7) + (c6,...,c0) */ \ - /* (r14) */ \ - MOVQ R14, AX; SHLQ $32,AX; \ - ADDQ R14,R10; MOVQ R10, 0+z; \ - ADCQ $0,R11; MOVQ R11, 8+z; \ - ADCQ $0,R12; MOVQ R12,16+z; \ - ADCQ AX,R13; MOVQ R13,24+z; \ - ADCQ $0,R15; MOVQ R15,32+z; \ - ADCQ $0, R8; MOVQ R8,40+z; \ - ADCQ $0, R9; MOVQ R9,48+z; - -// reduceFromDoubleAdx finds a z=x modulo p such that z<2^448 and stores in z -// Uses: AX, R8-R15, FLAGS -// Instr: x86_64, adx -#define reduceFromDoubleAdx(z,x) \ - /* ( ,2C13,2C12,2C11,2C10|C10,C9,C8, C7) + (C6,...,C0) */ \ - /* (r14, r13, r12, r11, r10,r9,r8,r15) */ \ - MOVQ 80+x,AX; MOVQ AX,R10; \ - MOVQ $0xFFFFFFFF00000000, R8; \ - ANDQ R8,R10; \ - \ - MOVQ $0,R14; \ - MOVQ 104+x,R13; SHLQ $1,R13,R14; \ - MOVQ 96+x,R12; SHLQ $1,R12,R13; \ - MOVQ 88+x,R11; SHLQ $1,R11,R12; \ - MOVQ 72+x, R9; SHLQ $1,R10,R11; \ - MOVQ 64+x, R8; SHLQ $1,R10; \ - MOVQ $0xFFFFFFFF,R15; ANDQ R15,AX; ORQ AX,R10; \ - MOVQ 56+x,R15; \ - \ - XORL AX,AX; \ - ADCXQ 0+x,R15; MOVQ R15, 0+z; MOVQ 56+x,R15; \ - ADCXQ 8+x, R8; MOVQ R8, 8+z; MOVQ 64+x, R8; \ - ADCXQ 16+x, R9; MOVQ R9,16+z; MOVQ 72+x, R9; \ - ADCXQ 24+x,R10; MOVQ R10,24+z; MOVQ 80+x,R10; \ - ADCXQ 32+x,R11; MOVQ R11,32+z; MOVQ 88+x,R11; \ - ADCXQ 40+x,R12; MOVQ R12,40+z; MOVQ 96+x,R12; \ - ADCXQ 48+x,R13; MOVQ R13,48+z; MOVQ 104+x,R13; \ - ADCXQ AX,R14; \ - /* (c10c9,c9c8,c8c7,c7c13,c13c12,c12c11,c11c10) + (c6,...,c0) */ \ - /* ( r9, r8, r15, r13, r12, r11, r10) */ \ - MOVQ R10, AX; \ - SHRQ $32,R11,R10; \ - SHRQ $32,R12,R11; \ - SHRQ $32,R13,R12; \ - SHRQ $32,R15,R13; \ - SHRQ $32, R8,R15; \ - SHRQ $32, R9, R8; \ - SHRQ $32, AX, R9; \ - \ - XORL AX,AX; \ - ADCXQ 0+z,R10; \ - ADCXQ 8+z,R11; \ - ADCXQ 16+z,R12; \ - ADCXQ 24+z,R13; \ - ADCXQ 32+z,R15; \ - ADCXQ 40+z, R8; \ - ADCXQ 48+z, R9; \ - ADCXQ AX,R14; \ - /* ( c7) + (c6,...,c0) */ \ - /* (r14) */ \ - MOVQ R14, AX; SHLQ $32, AX; \ - CLC; \ - ADCXQ R14,R10; MOVQ $0,R14; \ - ADCXQ R14,R11; \ - ADCXQ R14,R12; \ - ADCXQ AX,R13; \ - ADCXQ R14,R15; \ - ADCXQ R14, R8; \ - ADCXQ R14, R9; \ - ADCXQ R14,R14; \ - /* ( c7) + (c6,...,c0) */ \ - /* (r14) */ \ - MOVQ R14, AX; SHLQ $32, AX; \ - CLC; \ - ADCXQ R14,R10; MOVQ R10, 0+z; MOVQ $0,R14; \ - ADCXQ R14,R11; MOVQ R11, 8+z; \ - ADCXQ R14,R12; MOVQ R12,16+z; \ - ADCXQ AX,R13; MOVQ R13,24+z; \ - ADCXQ R14,R15; MOVQ R15,32+z; \ - ADCXQ R14, R8; MOVQ R8,40+z; \ - ADCXQ R14, R9; MOVQ R9,48+z; - -// addSub calculates two operations: x,y = x+y,x-y -// Uses: AX, DX, R8-R15, FLAGS -#define addSub(x,y) \ - MOVQ 0+x, R8; ADDQ 0+y, R8; \ - MOVQ 8+x, R9; ADCQ 8+y, R9; \ - MOVQ 16+x, R10; ADCQ 16+y, R10; \ - MOVQ 24+x, R11; ADCQ 24+y, R11; \ - MOVQ 32+x, R12; ADCQ 32+y, R12; \ - MOVQ 40+x, R13; ADCQ 40+y, R13; \ - MOVQ 48+x, R14; ADCQ 48+y, R14; \ - MOVQ $0, AX; ADCQ $0, AX; \ - MOVQ AX, DX; \ - SHLQ $32, DX; \ - ADDQ AX, R8; MOVQ $0, AX; \ - ADCQ $0, R9; \ - ADCQ $0, R10; \ - ADCQ DX, R11; \ - ADCQ $0, R12; \ - ADCQ $0, R13; \ - ADCQ $0, R14; \ - ADCQ $0, AX; \ - MOVQ AX, DX; \ - SHLQ $32, DX; \ - ADDQ AX, R8; MOVQ 0+x,AX; MOVQ R8, 0+x; MOVQ AX, R8; \ - ADCQ $0, R9; MOVQ 8+x,AX; MOVQ R9, 8+x; MOVQ AX, R9; \ - ADCQ $0, R10; MOVQ 16+x,AX; MOVQ R10, 16+x; MOVQ AX, R10; \ - ADCQ DX, R11; MOVQ 24+x,AX; MOVQ R11, 24+x; MOVQ AX, R11; \ - ADCQ $0, R12; MOVQ 32+x,AX; MOVQ R12, 32+x; MOVQ AX, R12; \ - ADCQ $0, R13; MOVQ 40+x,AX; MOVQ R13, 40+x; MOVQ AX, R13; \ - ADCQ $0, R14; MOVQ 48+x,AX; MOVQ R14, 48+x; MOVQ AX, R14; \ - SUBQ 0+y, R8; \ - SBBQ 8+y, R9; \ - SBBQ 16+y, R10; \ - SBBQ 24+y, R11; \ - SBBQ 32+y, R12; \ - SBBQ 40+y, R13; \ - SBBQ 48+y, R14; \ - MOVQ $0, AX; SETCS AX; \ - MOVQ AX, DX; \ - SHLQ $32, DX; \ - SUBQ AX, R8; MOVQ $0, AX; \ - SBBQ $0, R9; \ - SBBQ $0, R10; \ - SBBQ DX, R11; \ - SBBQ $0, R12; \ - SBBQ $0, R13; \ - SBBQ $0, R14; \ - SETCS AX; \ - MOVQ AX, DX; \ - SHLQ $32, DX; \ - SUBQ AX, R8; MOVQ R8, 0+y; \ - SBBQ $0, R9; MOVQ R9, 8+y; \ - SBBQ $0, R10; MOVQ R10, 16+y; \ - SBBQ DX, R11; MOVQ R11, 24+y; \ - SBBQ $0, R12; MOVQ R12, 32+y; \ - SBBQ $0, R13; MOVQ R13, 40+y; \ - SBBQ $0, R14; MOVQ R14, 48+y; diff --git a/vendor/github.com/cloudflare/circl/math/fp448/fp_amd64.s b/vendor/github.com/cloudflare/circl/math/fp448/fp_amd64.s deleted file mode 100644 index 435addf5..00000000 --- a/vendor/github.com/cloudflare/circl/math/fp448/fp_amd64.s +++ /dev/null @@ -1,74 +0,0 @@ -// +build amd64 - -#include "textflag.h" -#include "fp_amd64.h" - -// func cmovAmd64(x, y *Elt, n uint) -TEXT ·cmovAmd64(SB),NOSPLIT,$0-24 - MOVQ x+0(FP), DI - MOVQ y+8(FP), SI - MOVQ n+16(FP), BX - cselect(0(DI),0(SI),BX) - RET - -// func cswapAmd64(x, y *Elt, n uint) -TEXT ·cswapAmd64(SB),NOSPLIT,$0-24 - MOVQ x+0(FP), DI - MOVQ y+8(FP), SI - MOVQ n+16(FP), BX - cswap(0(DI),0(SI),BX) - RET - -// func subAmd64(z, x, y *Elt) -TEXT ·subAmd64(SB),NOSPLIT,$0-24 - MOVQ z+0(FP), DI - MOVQ x+8(FP), SI - MOVQ y+16(FP), BX - subtraction(0(DI),0(SI),0(BX)) - RET - -// func addsubAmd64(x, y *Elt) -TEXT ·addsubAmd64(SB),NOSPLIT,$0-16 - MOVQ x+0(FP), DI - MOVQ y+8(FP), SI - addSub(0(DI),0(SI)) - RET - -#define addLegacy \ - additionLeg(0(DI),0(SI),0(BX)) -#define addBmi2Adx \ - additionAdx(0(DI),0(SI),0(BX)) - -#define mulLegacy \ - integerMulLeg(0(SP),0(SI),0(BX)) \ - reduceFromDoubleLeg(0(DI),0(SP)) -#define mulBmi2Adx \ - integerMulAdx(0(SP),0(SI),0(BX)) \ - reduceFromDoubleAdx(0(DI),0(SP)) - -#define sqrLegacy \ - integerSqrLeg(0(SP),0(SI)) \ - reduceFromDoubleLeg(0(DI),0(SP)) -#define sqrBmi2Adx \ - integerSqrAdx(0(SP),0(SI)) \ - reduceFromDoubleAdx(0(DI),0(SP)) - -// func addAmd64(z, x, y *Elt) -TEXT ·addAmd64(SB),NOSPLIT,$0-24 - MOVQ z+0(FP), DI - MOVQ x+8(FP), SI - MOVQ y+16(FP), BX - CHECK_BMI2ADX(LADD, addLegacy, addBmi2Adx) - -// func mulAmd64(z, x, y *Elt) -TEXT ·mulAmd64(SB),NOSPLIT,$112-24 - MOVQ z+0(FP), DI - MOVQ x+8(FP), SI - MOVQ y+16(FP), BX - CHECK_BMI2ADX(LMUL, mulLegacy, mulBmi2Adx) - -// func sqrAmd64(z, x *Elt) -TEXT ·sqrAmd64(SB),NOSPLIT,$112-16 - MOVQ z+0(FP), DI - MOVQ x+8(FP), SI - CHECK_BMI2ADX(LSQR, sqrLegacy, sqrBmi2Adx) diff --git a/vendor/github.com/cloudflare/circl/math/fp448/fp_generic.go b/vendor/github.com/cloudflare/circl/math/fp448/fp_generic.go deleted file mode 100644 index 47a0b632..00000000 --- a/vendor/github.com/cloudflare/circl/math/fp448/fp_generic.go +++ /dev/null @@ -1,339 +0,0 @@ -package fp448 - -import ( - "encoding/binary" - "math/bits" -) - -func cmovGeneric(x, y *Elt, n uint) { - m := -uint64(n & 0x1) - x0 := binary.LittleEndian.Uint64(x[0*8 : 1*8]) - x1 := binary.LittleEndian.Uint64(x[1*8 : 2*8]) - x2 := binary.LittleEndian.Uint64(x[2*8 : 3*8]) - x3 := binary.LittleEndian.Uint64(x[3*8 : 4*8]) - x4 := binary.LittleEndian.Uint64(x[4*8 : 5*8]) - x5 := binary.LittleEndian.Uint64(x[5*8 : 6*8]) - x6 := binary.LittleEndian.Uint64(x[6*8 : 7*8]) - - y0 := binary.LittleEndian.Uint64(y[0*8 : 1*8]) - y1 := binary.LittleEndian.Uint64(y[1*8 : 2*8]) - y2 := binary.LittleEndian.Uint64(y[2*8 : 3*8]) - y3 := binary.LittleEndian.Uint64(y[3*8 : 4*8]) - y4 := binary.LittleEndian.Uint64(y[4*8 : 5*8]) - y5 := binary.LittleEndian.Uint64(y[5*8 : 6*8]) - y6 := binary.LittleEndian.Uint64(y[6*8 : 7*8]) - - x0 = (x0 &^ m) | (y0 & m) - x1 = (x1 &^ m) | (y1 & m) - x2 = (x2 &^ m) | (y2 & m) - x3 = (x3 &^ m) | (y3 & m) - x4 = (x4 &^ m) | (y4 & m) - x5 = (x5 &^ m) | (y5 & m) - x6 = (x6 &^ m) | (y6 & m) - - binary.LittleEndian.PutUint64(x[0*8:1*8], x0) - binary.LittleEndian.PutUint64(x[1*8:2*8], x1) - binary.LittleEndian.PutUint64(x[2*8:3*8], x2) - binary.LittleEndian.PutUint64(x[3*8:4*8], x3) - binary.LittleEndian.PutUint64(x[4*8:5*8], x4) - binary.LittleEndian.PutUint64(x[5*8:6*8], x5) - binary.LittleEndian.PutUint64(x[6*8:7*8], x6) -} - -func cswapGeneric(x, y *Elt, n uint) { - m := -uint64(n & 0x1) - x0 := binary.LittleEndian.Uint64(x[0*8 : 1*8]) - x1 := binary.LittleEndian.Uint64(x[1*8 : 2*8]) - x2 := binary.LittleEndian.Uint64(x[2*8 : 3*8]) - x3 := binary.LittleEndian.Uint64(x[3*8 : 4*8]) - x4 := binary.LittleEndian.Uint64(x[4*8 : 5*8]) - x5 := binary.LittleEndian.Uint64(x[5*8 : 6*8]) - x6 := binary.LittleEndian.Uint64(x[6*8 : 7*8]) - - y0 := binary.LittleEndian.Uint64(y[0*8 : 1*8]) - y1 := binary.LittleEndian.Uint64(y[1*8 : 2*8]) - y2 := binary.LittleEndian.Uint64(y[2*8 : 3*8]) - y3 := binary.LittleEndian.Uint64(y[3*8 : 4*8]) - y4 := binary.LittleEndian.Uint64(y[4*8 : 5*8]) - y5 := binary.LittleEndian.Uint64(y[5*8 : 6*8]) - y6 := binary.LittleEndian.Uint64(y[6*8 : 7*8]) - - t0 := m & (x0 ^ y0) - t1 := m & (x1 ^ y1) - t2 := m & (x2 ^ y2) - t3 := m & (x3 ^ y3) - t4 := m & (x4 ^ y4) - t5 := m & (x5 ^ y5) - t6 := m & (x6 ^ y6) - x0 ^= t0 - x1 ^= t1 - x2 ^= t2 - x3 ^= t3 - x4 ^= t4 - x5 ^= t5 - x6 ^= t6 - y0 ^= t0 - y1 ^= t1 - y2 ^= t2 - y3 ^= t3 - y4 ^= t4 - y5 ^= t5 - y6 ^= t6 - - binary.LittleEndian.PutUint64(x[0*8:1*8], x0) - binary.LittleEndian.PutUint64(x[1*8:2*8], x1) - binary.LittleEndian.PutUint64(x[2*8:3*8], x2) - binary.LittleEndian.PutUint64(x[3*8:4*8], x3) - binary.LittleEndian.PutUint64(x[4*8:5*8], x4) - binary.LittleEndian.PutUint64(x[5*8:6*8], x5) - binary.LittleEndian.PutUint64(x[6*8:7*8], x6) - - binary.LittleEndian.PutUint64(y[0*8:1*8], y0) - binary.LittleEndian.PutUint64(y[1*8:2*8], y1) - binary.LittleEndian.PutUint64(y[2*8:3*8], y2) - binary.LittleEndian.PutUint64(y[3*8:4*8], y3) - binary.LittleEndian.PutUint64(y[4*8:5*8], y4) - binary.LittleEndian.PutUint64(y[5*8:6*8], y5) - binary.LittleEndian.PutUint64(y[6*8:7*8], y6) -} - -func addGeneric(z, x, y *Elt) { - x0 := binary.LittleEndian.Uint64(x[0*8 : 1*8]) - x1 := binary.LittleEndian.Uint64(x[1*8 : 2*8]) - x2 := binary.LittleEndian.Uint64(x[2*8 : 3*8]) - x3 := binary.LittleEndian.Uint64(x[3*8 : 4*8]) - x4 := binary.LittleEndian.Uint64(x[4*8 : 5*8]) - x5 := binary.LittleEndian.Uint64(x[5*8 : 6*8]) - x6 := binary.LittleEndian.Uint64(x[6*8 : 7*8]) - - y0 := binary.LittleEndian.Uint64(y[0*8 : 1*8]) - y1 := binary.LittleEndian.Uint64(y[1*8 : 2*8]) - y2 := binary.LittleEndian.Uint64(y[2*8 : 3*8]) - y3 := binary.LittleEndian.Uint64(y[3*8 : 4*8]) - y4 := binary.LittleEndian.Uint64(y[4*8 : 5*8]) - y5 := binary.LittleEndian.Uint64(y[5*8 : 6*8]) - y6 := binary.LittleEndian.Uint64(y[6*8 : 7*8]) - - z0, c0 := bits.Add64(x0, y0, 0) - z1, c1 := bits.Add64(x1, y1, c0) - z2, c2 := bits.Add64(x2, y2, c1) - z3, c3 := bits.Add64(x3, y3, c2) - z4, c4 := bits.Add64(x4, y4, c3) - z5, c5 := bits.Add64(x5, y5, c4) - z6, z7 := bits.Add64(x6, y6, c5) - - z0, c0 = bits.Add64(z0, z7, 0) - z1, c1 = bits.Add64(z1, 0, c0) - z2, c2 = bits.Add64(z2, 0, c1) - z3, c3 = bits.Add64(z3, z7<<32, c2) - z4, c4 = bits.Add64(z4, 0, c3) - z5, c5 = bits.Add64(z5, 0, c4) - z6, z7 = bits.Add64(z6, 0, c5) - - z0, c0 = bits.Add64(z0, z7, 0) - z1, c1 = bits.Add64(z1, 0, c0) - z2, c2 = bits.Add64(z2, 0, c1) - z3, c3 = bits.Add64(z3, z7<<32, c2) - z4, c4 = bits.Add64(z4, 0, c3) - z5, c5 = bits.Add64(z5, 0, c4) - z6, _ = bits.Add64(z6, 0, c5) - - binary.LittleEndian.PutUint64(z[0*8:1*8], z0) - binary.LittleEndian.PutUint64(z[1*8:2*8], z1) - binary.LittleEndian.PutUint64(z[2*8:3*8], z2) - binary.LittleEndian.PutUint64(z[3*8:4*8], z3) - binary.LittleEndian.PutUint64(z[4*8:5*8], z4) - binary.LittleEndian.PutUint64(z[5*8:6*8], z5) - binary.LittleEndian.PutUint64(z[6*8:7*8], z6) -} - -func subGeneric(z, x, y *Elt) { - x0 := binary.LittleEndian.Uint64(x[0*8 : 1*8]) - x1 := binary.LittleEndian.Uint64(x[1*8 : 2*8]) - x2 := binary.LittleEndian.Uint64(x[2*8 : 3*8]) - x3 := binary.LittleEndian.Uint64(x[3*8 : 4*8]) - x4 := binary.LittleEndian.Uint64(x[4*8 : 5*8]) - x5 := binary.LittleEndian.Uint64(x[5*8 : 6*8]) - x6 := binary.LittleEndian.Uint64(x[6*8 : 7*8]) - - y0 := binary.LittleEndian.Uint64(y[0*8 : 1*8]) - y1 := binary.LittleEndian.Uint64(y[1*8 : 2*8]) - y2 := binary.LittleEndian.Uint64(y[2*8 : 3*8]) - y3 := binary.LittleEndian.Uint64(y[3*8 : 4*8]) - y4 := binary.LittleEndian.Uint64(y[4*8 : 5*8]) - y5 := binary.LittleEndian.Uint64(y[5*8 : 6*8]) - y6 := binary.LittleEndian.Uint64(y[6*8 : 7*8]) - - z0, c0 := bits.Sub64(x0, y0, 0) - z1, c1 := bits.Sub64(x1, y1, c0) - z2, c2 := bits.Sub64(x2, y2, c1) - z3, c3 := bits.Sub64(x3, y3, c2) - z4, c4 := bits.Sub64(x4, y4, c3) - z5, c5 := bits.Sub64(x5, y5, c4) - z6, z7 := bits.Sub64(x6, y6, c5) - - z0, c0 = bits.Sub64(z0, z7, 0) - z1, c1 = bits.Sub64(z1, 0, c0) - z2, c2 = bits.Sub64(z2, 0, c1) - z3, c3 = bits.Sub64(z3, z7<<32, c2) - z4, c4 = bits.Sub64(z4, 0, c3) - z5, c5 = bits.Sub64(z5, 0, c4) - z6, z7 = bits.Sub64(z6, 0, c5) - - z0, c0 = bits.Sub64(z0, z7, 0) - z1, c1 = bits.Sub64(z1, 0, c0) - z2, c2 = bits.Sub64(z2, 0, c1) - z3, c3 = bits.Sub64(z3, z7<<32, c2) - z4, c4 = bits.Sub64(z4, 0, c3) - z5, c5 = bits.Sub64(z5, 0, c4) - z6, _ = bits.Sub64(z6, 0, c5) - - binary.LittleEndian.PutUint64(z[0*8:1*8], z0) - binary.LittleEndian.PutUint64(z[1*8:2*8], z1) - binary.LittleEndian.PutUint64(z[2*8:3*8], z2) - binary.LittleEndian.PutUint64(z[3*8:4*8], z3) - binary.LittleEndian.PutUint64(z[4*8:5*8], z4) - binary.LittleEndian.PutUint64(z[5*8:6*8], z5) - binary.LittleEndian.PutUint64(z[6*8:7*8], z6) -} - -func addsubGeneric(x, y *Elt) { - z := &Elt{} - addGeneric(z, x, y) - subGeneric(y, x, y) - *x = *z -} - -func mulGeneric(z, x, y *Elt) { - x0 := binary.LittleEndian.Uint64(x[0*8 : 1*8]) - x1 := binary.LittleEndian.Uint64(x[1*8 : 2*8]) - x2 := binary.LittleEndian.Uint64(x[2*8 : 3*8]) - x3 := binary.LittleEndian.Uint64(x[3*8 : 4*8]) - x4 := binary.LittleEndian.Uint64(x[4*8 : 5*8]) - x5 := binary.LittleEndian.Uint64(x[5*8 : 6*8]) - x6 := binary.LittleEndian.Uint64(x[6*8 : 7*8]) - - y0 := binary.LittleEndian.Uint64(y[0*8 : 1*8]) - y1 := binary.LittleEndian.Uint64(y[1*8 : 2*8]) - y2 := binary.LittleEndian.Uint64(y[2*8 : 3*8]) - y3 := binary.LittleEndian.Uint64(y[3*8 : 4*8]) - y4 := binary.LittleEndian.Uint64(y[4*8 : 5*8]) - y5 := binary.LittleEndian.Uint64(y[5*8 : 6*8]) - y6 := binary.LittleEndian.Uint64(y[6*8 : 7*8]) - - yy := [7]uint64{y0, y1, y2, y3, y4, y5, y6} - zz := [7]uint64{} - - yi := yy[0] - h0, l0 := bits.Mul64(x0, yi) - h1, l1 := bits.Mul64(x1, yi) - h2, l2 := bits.Mul64(x2, yi) - h3, l3 := bits.Mul64(x3, yi) - h4, l4 := bits.Mul64(x4, yi) - h5, l5 := bits.Mul64(x5, yi) - h6, l6 := bits.Mul64(x6, yi) - - zz[0] = l0 - a0, c0 := bits.Add64(h0, l1, 0) - a1, c1 := bits.Add64(h1, l2, c0) - a2, c2 := bits.Add64(h2, l3, c1) - a3, c3 := bits.Add64(h3, l4, c2) - a4, c4 := bits.Add64(h4, l5, c3) - a5, c5 := bits.Add64(h5, l6, c4) - a6, _ := bits.Add64(h6, 0, c5) - - for i := 1; i < 7; i++ { - yi = yy[i] - h0, l0 = bits.Mul64(x0, yi) - h1, l1 = bits.Mul64(x1, yi) - h2, l2 = bits.Mul64(x2, yi) - h3, l3 = bits.Mul64(x3, yi) - h4, l4 = bits.Mul64(x4, yi) - h5, l5 = bits.Mul64(x5, yi) - h6, l6 = bits.Mul64(x6, yi) - - zz[i], c0 = bits.Add64(a0, l0, 0) - a0, c1 = bits.Add64(a1, l1, c0) - a1, c2 = bits.Add64(a2, l2, c1) - a2, c3 = bits.Add64(a3, l3, c2) - a3, c4 = bits.Add64(a4, l4, c3) - a4, c5 = bits.Add64(a5, l5, c4) - a5, a6 = bits.Add64(a6, l6, c5) - - a0, c0 = bits.Add64(a0, h0, 0) - a1, c1 = bits.Add64(a1, h1, c0) - a2, c2 = bits.Add64(a2, h2, c1) - a3, c3 = bits.Add64(a3, h3, c2) - a4, c4 = bits.Add64(a4, h4, c3) - a5, c5 = bits.Add64(a5, h5, c4) - a6, _ = bits.Add64(a6, h6, c5) - } - red64(z, &zz, &[7]uint64{a0, a1, a2, a3, a4, a5, a6}) -} - -func sqrGeneric(z, x *Elt) { mulGeneric(z, x, x) } - -func red64(z *Elt, l, h *[7]uint64) { - /* (2C13, 2C12, 2C11, 2C10|C10, C9, C8, C7) + (C6,...,C0) */ - h0 := h[0] - h1 := h[1] - h2 := h[2] - h3 := ((h[3] & (0xFFFFFFFF << 32)) << 1) | (h[3] & 0xFFFFFFFF) - h4 := (h[3] >> 63) | (h[4] << 1) - h5 := (h[4] >> 63) | (h[5] << 1) - h6 := (h[5] >> 63) | (h[6] << 1) - h7 := (h[6] >> 63) - - l0, c0 := bits.Add64(h0, l[0], 0) - l1, c1 := bits.Add64(h1, l[1], c0) - l2, c2 := bits.Add64(h2, l[2], c1) - l3, c3 := bits.Add64(h3, l[3], c2) - l4, c4 := bits.Add64(h4, l[4], c3) - l5, c5 := bits.Add64(h5, l[5], c4) - l6, c6 := bits.Add64(h6, l[6], c5) - l7, _ := bits.Add64(h7, 0, c6) - - /* (C10C9, C9C8,C8C7,C7C13,C13C12,C12C11,C11C10) + (C6,...,C0) */ - h0 = (h[3] >> 32) | (h[4] << 32) - h1 = (h[4] >> 32) | (h[5] << 32) - h2 = (h[5] >> 32) | (h[6] << 32) - h3 = (h[6] >> 32) | (h[0] << 32) - h4 = (h[0] >> 32) | (h[1] << 32) - h5 = (h[1] >> 32) | (h[2] << 32) - h6 = (h[2] >> 32) | (h[3] << 32) - - l0, c0 = bits.Add64(l0, h0, 0) - l1, c1 = bits.Add64(l1, h1, c0) - l2, c2 = bits.Add64(l2, h2, c1) - l3, c3 = bits.Add64(l3, h3, c2) - l4, c4 = bits.Add64(l4, h4, c3) - l5, c5 = bits.Add64(l5, h5, c4) - l6, c6 = bits.Add64(l6, h6, c5) - l7, _ = bits.Add64(l7, 0, c6) - - /* (C7) + (C6,...,C0) */ - l0, c0 = bits.Add64(l0, l7, 0) - l1, c1 = bits.Add64(l1, 0, c0) - l2, c2 = bits.Add64(l2, 0, c1) - l3, c3 = bits.Add64(l3, l7<<32, c2) - l4, c4 = bits.Add64(l4, 0, c3) - l5, c5 = bits.Add64(l5, 0, c4) - l6, l7 = bits.Add64(l6, 0, c5) - - /* (C7) + (C6,...,C0) */ - l0, c0 = bits.Add64(l0, l7, 0) - l1, c1 = bits.Add64(l1, 0, c0) - l2, c2 = bits.Add64(l2, 0, c1) - l3, c3 = bits.Add64(l3, l7<<32, c2) - l4, c4 = bits.Add64(l4, 0, c3) - l5, c5 = bits.Add64(l5, 0, c4) - l6, _ = bits.Add64(l6, 0, c5) - - binary.LittleEndian.PutUint64(z[0*8:1*8], l0) - binary.LittleEndian.PutUint64(z[1*8:2*8], l1) - binary.LittleEndian.PutUint64(z[2*8:3*8], l2) - binary.LittleEndian.PutUint64(z[3*8:4*8], l3) - binary.LittleEndian.PutUint64(z[4*8:5*8], l4) - binary.LittleEndian.PutUint64(z[5*8:6*8], l5) - binary.LittleEndian.PutUint64(z[6*8:7*8], l6) -} diff --git a/vendor/github.com/cloudflare/circl/math/fp448/fp_noasm.go b/vendor/github.com/cloudflare/circl/math/fp448/fp_noasm.go deleted file mode 100644 index a62225d2..00000000 --- a/vendor/github.com/cloudflare/circl/math/fp448/fp_noasm.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build !amd64 || purego -// +build !amd64 purego - -package fp448 - -func cmov(x, y *Elt, n uint) { cmovGeneric(x, y, n) } -func cswap(x, y *Elt, n uint) { cswapGeneric(x, y, n) } -func add(z, x, y *Elt) { addGeneric(z, x, y) } -func sub(z, x, y *Elt) { subGeneric(z, x, y) } -func addsub(x, y *Elt) { addsubGeneric(x, y) } -func mul(z, x, y *Elt) { mulGeneric(z, x, y) } -func sqr(z, x *Elt) { sqrGeneric(z, x) } diff --git a/vendor/github.com/cloudflare/circl/math/fp448/fuzzer.go b/vendor/github.com/cloudflare/circl/math/fp448/fuzzer.go deleted file mode 100644 index 2d7afc80..00000000 --- a/vendor/github.com/cloudflare/circl/math/fp448/fuzzer.go +++ /dev/null @@ -1,75 +0,0 @@ -//go:build gofuzz -// +build gofuzz - -// How to run the fuzzer: -// -// $ go get -u github.com/dvyukov/go-fuzz/go-fuzz -// $ go get -u github.com/dvyukov/go-fuzz/go-fuzz-build -// $ go-fuzz-build -libfuzzer -func FuzzReduction -o lib.a -// $ clang -fsanitize=fuzzer lib.a -o fu.exe -// $ ./fu.exe -package fp448 - -import ( - "encoding/binary" - "fmt" - "math/big" - - "github.com/cloudflare/circl/internal/conv" -) - -// FuzzReduction is a fuzzer target for red64 function, which reduces t -// (112 bits) to a number t' (56 bits) congruent modulo p448. -func FuzzReduction(data []byte) int { - if len(data) != 2*Size { - return -1 - } - var got, want Elt - var lo, hi [7]uint64 - a := data[:Size] - b := data[Size:] - lo[0] = binary.LittleEndian.Uint64(a[0*8 : 1*8]) - lo[1] = binary.LittleEndian.Uint64(a[1*8 : 2*8]) - lo[2] = binary.LittleEndian.Uint64(a[2*8 : 3*8]) - lo[3] = binary.LittleEndian.Uint64(a[3*8 : 4*8]) - lo[4] = binary.LittleEndian.Uint64(a[4*8 : 5*8]) - lo[5] = binary.LittleEndian.Uint64(a[5*8 : 6*8]) - lo[6] = binary.LittleEndian.Uint64(a[6*8 : 7*8]) - - hi[0] = binary.LittleEndian.Uint64(b[0*8 : 1*8]) - hi[1] = binary.LittleEndian.Uint64(b[1*8 : 2*8]) - hi[2] = binary.LittleEndian.Uint64(b[2*8 : 3*8]) - hi[3] = binary.LittleEndian.Uint64(b[3*8 : 4*8]) - hi[4] = binary.LittleEndian.Uint64(b[4*8 : 5*8]) - hi[5] = binary.LittleEndian.Uint64(b[5*8 : 6*8]) - hi[6] = binary.LittleEndian.Uint64(b[6*8 : 7*8]) - - red64(&got, &lo, &hi) - - t := conv.BytesLe2BigInt(data[:2*Size]) - - two448 := big.NewInt(1) - two448.Lsh(two448, 448) // 2^448 - mask448 := big.NewInt(1) - mask448.Sub(two448, mask448) // 2^448-1 - two224plus1 := big.NewInt(1) - two224plus1.Lsh(two224plus1, 224) - two224plus1.Add(two224plus1, big.NewInt(1)) // 2^224+1 - - var loBig, hiBig big.Int - for t.Cmp(two448) >= 0 { - loBig.And(t, mask448) - hiBig.Rsh(t, 448) - t.Mul(&hiBig, two224plus1) - t.Add(t, &loBig) - } - conv.BigInt2BytesLe(want[:], t) - - if got != want { - fmt.Printf("in: %v\n", conv.BytesLe2BigInt(data[:2*Size])) - fmt.Printf("got: %v\n", got) - fmt.Printf("want: %v\n", want) - panic("error found") - } - return 1 -} diff --git a/vendor/github.com/cloudflare/circl/math/mlsbset/mlsbset.go b/vendor/github.com/cloudflare/circl/math/mlsbset/mlsbset.go deleted file mode 100644 index a43851b8..00000000 --- a/vendor/github.com/cloudflare/circl/math/mlsbset/mlsbset.go +++ /dev/null @@ -1,122 +0,0 @@ -// Package mlsbset provides a constant-time exponentiation method with precomputation. -// -// References: "Efficient and secure algorithms for GLV-based scalar -// multiplication and their implementation on GLV–GLS curves" by (Faz-Hernandez et al.) -// - https://doi.org/10.1007/s13389-014-0085-7 -// - https://eprint.iacr.org/2013/158 -package mlsbset - -import ( - "errors" - "fmt" - "math/big" - - "github.com/cloudflare/circl/internal/conv" -) - -// EltG is a group element. -type EltG interface{} - -// EltP is a precomputed group element. -type EltP interface{} - -// Group defines the operations required by MLSBSet exponentiation method. -type Group interface { - Identity() EltG // Returns the identity of the group. - Sqr(x EltG) // Calculates x = x^2. - Mul(x EltG, y EltP) // Calculates x = x*y. - NewEltP() EltP // Returns an arbitrary precomputed element. - ExtendedEltP() EltP // Returns the precomputed element x^(2^(w*d)). - Lookup(a EltP, v uint, s, u int32) // Sets a = s*T[v][u]. -} - -// Params contains the parameters of the encoding. -type Params struct { - T uint // T is the maximum size (in bits) of exponents. - V uint // V is the number of tables. - W uint // W is the window size. - E uint // E is the number of digits per table. - D uint // D is the number of digits in total. - L uint // L is the length of the code. -} - -// Encoder allows to convert integers into valid powers. -type Encoder struct{ p Params } - -// New produces an encoder of the MLSBSet algorithm. -func New(t, v, w uint) (Encoder, error) { - if !(t > 1 && v >= 1 && w >= 2) { - return Encoder{}, errors.New("t>1, v>=1, w>=2") - } - e := (t + w*v - 1) / (w * v) - d := e * v - l := d * w - return Encoder{Params{t, v, w, e, d, l}}, nil -} - -// Encode converts an odd integer k into a valid power for exponentiation. -func (m Encoder) Encode(k []byte) (*Power, error) { - if len(k) == 0 { - return nil, errors.New("empty slice") - } - if !(len(k) <= int(m.p.L+7)>>3) { - return nil, errors.New("k too big") - } - if k[0]%2 == 0 { - return nil, errors.New("k must be odd") - } - ap := int((m.p.L+7)/8) - len(k) - k = append(k, make([]byte, ap)...) - s := m.signs(k) - b := make([]int32, m.p.L-m.p.D) - c := conv.BytesLe2BigInt(k) - c.Rsh(c, m.p.D) - var bi big.Int - for i := m.p.D; i < m.p.L; i++ { - c0 := int32(c.Bit(0)) - b[i-m.p.D] = s[i%m.p.D] * c0 - bi.SetInt64(int64(b[i-m.p.D] >> 1)) - c.Rsh(c, 1) - c.Sub(c, &bi) - } - carry := int(c.Int64()) - return &Power{m, s, b, carry}, nil -} - -// signs calculates the set of signs. -func (m Encoder) signs(k []byte) []int32 { - s := make([]int32, m.p.D) - s[m.p.D-1] = 1 - for i := uint(1); i < m.p.D; i++ { - ki := int32((k[i>>3] >> (i & 0x7)) & 0x1) - s[i-1] = 2*ki - 1 - } - return s -} - -// GetParams returns the complementary parameters of the encoding. -func (m Encoder) GetParams() Params { return m.p } - -// tableSize returns the size of each table. -func (m Encoder) tableSize() uint { return 1 << (m.p.W - 1) } - -// Elts returns the total number of elements that must be precomputed. -func (m Encoder) Elts() uint { return m.p.V * m.tableSize() } - -// IsExtended returns true if the element x^(2^(wd)) must be calculated. -func (m Encoder) IsExtended() bool { q := m.p.T / (m.p.V * m.p.W); return m.p.T == q*m.p.V*m.p.W } - -// Ops returns the number of squares and multiplications executed during an exponentiation. -func (m Encoder) Ops() (S uint, M uint) { - S = m.p.E - M = m.p.E * m.p.V - if m.IsExtended() { - M++ - } - return -} - -func (m Encoder) String() string { - return fmt.Sprintf("T: %v W: %v V: %v e: %v d: %v l: %v wv|t: %v", - m.p.T, m.p.W, m.p.V, m.p.E, m.p.D, m.p.L, m.IsExtended()) -} diff --git a/vendor/github.com/cloudflare/circl/math/mlsbset/power.go b/vendor/github.com/cloudflare/circl/math/mlsbset/power.go deleted file mode 100644 index 3f214c30..00000000 --- a/vendor/github.com/cloudflare/circl/math/mlsbset/power.go +++ /dev/null @@ -1,64 +0,0 @@ -package mlsbset - -import "fmt" - -// Power is a valid exponent produced by the MLSBSet encoding algorithm. -type Power struct { - set Encoder // parameters of code. - s []int32 // set of signs. - b []int32 // set of digits. - c int // carry is {0,1}. -} - -// Exp is calculates x^k, where x is a predetermined element of a group G. -func (p *Power) Exp(G Group) EltG { - a, b := G.Identity(), G.NewEltP() - for e := int(p.set.p.E - 1); e >= 0; e-- { - G.Sqr(a) - for v := uint(0); v < p.set.p.V; v++ { - sgnElt, idElt := p.Digit(v, uint(e)) - G.Lookup(b, v, sgnElt, idElt) - G.Mul(a, b) - } - } - if p.set.IsExtended() && p.c == 1 { - G.Mul(a, G.ExtendedEltP()) - } - return a -} - -// Digit returns the (v,e)-th digit and its sign. -func (p *Power) Digit(v, e uint) (sgn, dig int32) { - sgn = p.bit(0, v, e) - dig = 0 - for i := p.set.p.W - 1; i > 0; i-- { - dig = 2*dig + p.bit(i, v, e) - } - mask := dig >> 31 - dig = (dig + mask) ^ mask - return sgn, dig -} - -// bit returns the (w,v,e)-th bit of the code. -func (p *Power) bit(w, v, e uint) int32 { - if !(w < p.set.p.W && - v < p.set.p.V && - e < p.set.p.E) { - panic(fmt.Errorf("indexes outside (%v,%v,%v)", w, v, e)) - } - if w == 0 { - return p.s[p.set.p.E*v+e] - } - return p.b[p.set.p.D*(w-1)+p.set.p.E*v+e] -} - -func (p *Power) String() string { - dig := "" - for j := uint(0); j < p.set.p.V; j++ { - for i := uint(0); i < p.set.p.E; i++ { - s, d := p.Digit(j, i) - dig += fmt.Sprintf("(%2v,%2v) = %+2v %+2v\n", j, i, s, d) - } - } - return fmt.Sprintf("len: %v\ncarry: %v\ndigits:\n%v", len(p.b)+len(p.s), p.c, dig) -} diff --git a/vendor/github.com/cloudflare/circl/math/wnaf.go b/vendor/github.com/cloudflare/circl/math/wnaf.go deleted file mode 100644 index 94a1ec50..00000000 --- a/vendor/github.com/cloudflare/circl/math/wnaf.go +++ /dev/null @@ -1,84 +0,0 @@ -// Package math provides some utility functions for big integers. -package math - -import "math/big" - -// SignedDigit obtains the signed-digit recoding of n and returns a list L of -// digits such that n = sum( L[i]*2^(i*(w-1)) ), and each L[i] is an odd number -// in the set {±1, ±3, ..., ±2^(w-1)-1}. The third parameter ensures that the -// output has ceil(l/(w-1)) digits. -// -// Restrictions: -// - n is odd and n > 0. -// - 1 < w < 32. -// - l >= bit length of n. -// -// References: -// - Alg.6 in "Exponent Recoding and Regular Exponentiation Algorithms" -// by Joye-Tunstall. http://doi.org/10.1007/978-3-642-02384-2_21 -// - Alg.6 in "Selecting Elliptic Curves for Cryptography: An Efficiency and -// Security Analysis" by Bos et al. http://doi.org/10.1007/s13389-015-0097-y -func SignedDigit(n *big.Int, w, l uint) []int32 { - if n.Sign() <= 0 || n.Bit(0) == 0 { - panic("n must be non-zero, odd, and positive") - } - if w <= 1 || w >= 32 { - panic("Verify that 1 < w < 32") - } - if uint(n.BitLen()) > l { - panic("n is too big to fit in l digits") - } - lenN := (l + (w - 1) - 1) / (w - 1) // ceil(l/(w-1)) - L := make([]int32, lenN+1) - var k, v big.Int - k.Set(n) - - var i uint - for i = 0; i < lenN; i++ { - words := k.Bits() - value := int32(words[0] & ((1 << w) - 1)) - value -= int32(1) << (w - 1) - L[i] = value - v.SetInt64(int64(value)) - k.Sub(&k, &v) - k.Rsh(&k, w-1) - } - L[i] = int32(k.Int64()) - return L -} - -// OmegaNAF obtains the window-w Non-Adjacent Form of a positive number n and -// 1 < w < 32. The returned slice L holds n = sum( L[i]*2^i ). -// -// Reference: -// - Alg.9 "Efficient arithmetic on Koblitz curves" by Solinas. -// http://doi.org/10.1023/A:1008306223194 -func OmegaNAF(n *big.Int, w uint) (L []int32) { - if n.Sign() < 0 { - panic("n must be positive") - } - if w <= 1 || w >= 32 { - panic("Verify that 1 < w < 32") - } - - L = make([]int32, n.BitLen()+1) - var k, v big.Int - k.Set(n) - - i := 0 - for ; k.Sign() > 0; i++ { - value := int32(0) - if k.Bit(0) == 1 { - words := k.Bits() - value = int32(words[0] & ((1 << w) - 1)) - if value >= (int32(1) << (w - 1)) { - value -= int32(1) << w - } - v.SetInt64(int64(value)) - k.Sub(&k, &v) - } - L[i] = value - k.Rsh(&k, 1) - } - return L[:i] -} diff --git a/vendor/github.com/cloudflare/circl/sign/ed25519/ed25519.go b/vendor/github.com/cloudflare/circl/sign/ed25519/ed25519.go deleted file mode 100644 index 08ca65d7..00000000 --- a/vendor/github.com/cloudflare/circl/sign/ed25519/ed25519.go +++ /dev/null @@ -1,453 +0,0 @@ -// Package ed25519 implements Ed25519 signature scheme as described in RFC-8032. -// -// This package provides optimized implementations of the three signature -// variants and maintaining closer compatiblilty with crypto/ed25519. -// -// | Scheme Name | Sign Function | Verification | Context | -// |-------------|-------------------|---------------|-------------------| -// | Ed25519 | Sign | Verify | None | -// | Ed25519Ph | SignPh | VerifyPh | Yes, can be empty | -// | Ed25519Ctx | SignWithCtx | VerifyWithCtx | Yes, non-empty | -// | All above | (PrivateKey).Sign | VerifyAny | As above | -// -// Specific functions for sign and verify are defined. A generic signing -// function for all schemes is available through the crypto.Signer interface, -// which is implemented by the PrivateKey type. A correspond all-in-one -// verification method is provided by the VerifyAny function. -// -// Signing with Ed25519Ph or Ed25519Ctx requires a context string for domain -// separation. This parameter is passed using a SignerOptions struct defined -// in this package. While Ed25519Ph accepts an empty context, Ed25519Ctx -// enforces non-empty context strings. -// -// # Compatibility with crypto.ed25519 -// -// These functions are compatible with the “Ed25519” function defined in -// RFC-8032. However, unlike RFC 8032's formulation, this package's private -// key representation includes a public key suffix to make multiple signing -// operations with the same key more efficient. This package refers to the -// RFC-8032 private key as the “seed”. -// -// References -// -// - RFC-8032: https://rfc-editor.org/rfc/rfc8032.txt -// - Ed25519: https://ed25519.cr.yp.to/ -// - EdDSA: High-speed high-security signatures. https://doi.org/10.1007/s13389-012-0027-1 -package ed25519 - -import ( - "bytes" - "crypto" - cryptoRand "crypto/rand" - "crypto/sha512" - "crypto/subtle" - "errors" - "fmt" - "io" - "strconv" - - "github.com/cloudflare/circl/sign" -) - -const ( - // ContextMaxSize is the maximum length (in bytes) allowed for context. - ContextMaxSize = 255 - // PublicKeySize is the size, in bytes, of public keys as used in this package. - PublicKeySize = 32 - // PrivateKeySize is the size, in bytes, of private keys as used in this package. - PrivateKeySize = 64 - // SignatureSize is the size, in bytes, of signatures generated and verified by this package. - SignatureSize = 64 - // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032. - SeedSize = 32 -) - -const ( - paramB = 256 / 8 // Size of keys in bytes. -) - -// SignerOptions implements crypto.SignerOpts and augments with parameters -// that are specific to the Ed25519 signature schemes. -type SignerOptions struct { - // Hash must be crypto.Hash(0) for Ed25519/Ed25519ctx, or crypto.SHA512 - // for Ed25519ph. - crypto.Hash - - // Context is an optional domain separation string for Ed25519ph and a - // must for Ed25519ctx. Its length must be less or equal than 255 bytes. - Context string - - // Scheme is an identifier for choosing a signature scheme. The zero value - // is ED25519. - Scheme SchemeID -} - -// SchemeID is an identifier for each signature scheme. -type SchemeID uint - -const ( - ED25519 SchemeID = iota - ED25519Ph - ED25519Ctx -) - -// PrivateKey is the type of Ed25519 private keys. It implements crypto.Signer. -type PrivateKey []byte - -// Equal reports whether priv and x have the same value. -func (priv PrivateKey) Equal(x crypto.PrivateKey) bool { - xx, ok := x.(PrivateKey) - return ok && subtle.ConstantTimeCompare(priv, xx) == 1 -} - -// Public returns the PublicKey corresponding to priv. -func (priv PrivateKey) Public() crypto.PublicKey { - publicKey := make(PublicKey, PublicKeySize) - copy(publicKey, priv[SeedSize:]) - return publicKey -} - -// Seed returns the private key seed corresponding to priv. It is provided for -// interoperability with RFC 8032. RFC 8032's private keys correspond to seeds -// in this package. -func (priv PrivateKey) Seed() []byte { - seed := make([]byte, SeedSize) - copy(seed, priv[:SeedSize]) - return seed -} - -func (priv PrivateKey) Scheme() sign.Scheme { return sch } - -func (pub PublicKey) Scheme() sign.Scheme { return sch } - -func (priv PrivateKey) MarshalBinary() (data []byte, err error) { - privateKey := make(PrivateKey, PrivateKeySize) - copy(privateKey, priv) - return privateKey, nil -} - -func (pub PublicKey) MarshalBinary() (data []byte, err error) { - publicKey := make(PublicKey, PublicKeySize) - copy(publicKey, pub) - return publicKey, nil -} - -// Equal reports whether pub and x have the same value. -func (pub PublicKey) Equal(x crypto.PublicKey) bool { - xx, ok := x.(PublicKey) - return ok && bytes.Equal(pub, xx) -} - -// Sign creates a signature of a message with priv key. -// This function is compatible with crypto.ed25519 and also supports the -// three signature variants defined in RFC-8032, namely Ed25519 (or pure -// EdDSA), Ed25519Ph, and Ed25519Ctx. -// The opts.HashFunc() must return zero to specify either Ed25519 or Ed25519Ctx -// variant. This can be achieved by passing crypto.Hash(0) as the value for -// opts. -// The opts.HashFunc() must return SHA512 to specify the Ed25519Ph variant. -// This can be achieved by passing crypto.SHA512 as the value for opts. -// Use a SignerOptions struct (defined in this package) to pass a context -// string for signing. -func (priv PrivateKey) Sign( - rand io.Reader, - message []byte, - opts crypto.SignerOpts, -) (signature []byte, err error) { - var ctx string - var scheme SchemeID - if o, ok := opts.(SignerOptions); ok { - ctx = o.Context - scheme = o.Scheme - } - - switch true { - case scheme == ED25519 && opts.HashFunc() == crypto.Hash(0): - return Sign(priv, message), nil - case scheme == ED25519Ph && opts.HashFunc() == crypto.SHA512: - return SignPh(priv, message, ctx), nil - case scheme == ED25519Ctx && opts.HashFunc() == crypto.Hash(0) && len(ctx) > 0: - return SignWithCtx(priv, message, ctx), nil - default: - return nil, errors.New("ed25519: bad hash algorithm") - } -} - -// GenerateKey generates a public/private key pair using entropy from rand. -// If rand is nil, crypto/rand.Reader will be used. -func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) { - if rand == nil { - rand = cryptoRand.Reader - } - - seed := make([]byte, SeedSize) - if _, err := io.ReadFull(rand, seed); err != nil { - return nil, nil, err - } - - privateKey := NewKeyFromSeed(seed) - publicKey := make(PublicKey, PublicKeySize) - copy(publicKey, privateKey[SeedSize:]) - - return publicKey, privateKey, nil -} - -// NewKeyFromSeed calculates a private key from a seed. It will panic if -// len(seed) is not SeedSize. This function is provided for interoperability -// with RFC 8032. RFC 8032's private keys correspond to seeds in this -// package. -func NewKeyFromSeed(seed []byte) PrivateKey { - privateKey := make(PrivateKey, PrivateKeySize) - newKeyFromSeed(privateKey, seed) - return privateKey -} - -func newKeyFromSeed(privateKey, seed []byte) { - if l := len(seed); l != SeedSize { - panic("ed25519: bad seed length: " + strconv.Itoa(l)) - } - var P pointR1 - k := sha512.Sum512(seed) - clamp(k[:]) - reduceModOrder(k[:paramB], false) - P.fixedMult(k[:paramB]) - copy(privateKey[:SeedSize], seed) - _ = P.ToBytes(privateKey[SeedSize:]) -} - -func signAll(signature []byte, privateKey PrivateKey, message, ctx []byte, preHash bool) { - if l := len(privateKey); l != PrivateKeySize { - panic("ed25519: bad private key length: " + strconv.Itoa(l)) - } - - H := sha512.New() - var PHM []byte - - if preHash { - _, _ = H.Write(message) - PHM = H.Sum(nil) - H.Reset() - } else { - PHM = message - } - - // 1. Hash the 32-byte private key using SHA-512. - _, _ = H.Write(privateKey[:SeedSize]) - h := H.Sum(nil) - clamp(h[:]) - prefix, s := h[paramB:], h[:paramB] - - // 2. Compute SHA-512(dom2(F, C) || prefix || PH(M)) - H.Reset() - - writeDom(H, ctx, preHash) - - _, _ = H.Write(prefix) - _, _ = H.Write(PHM) - r := H.Sum(nil) - reduceModOrder(r[:], true) - - // 3. Compute the point [r]B. - var P pointR1 - P.fixedMult(r[:paramB]) - R := (&[paramB]byte{})[:] - if err := P.ToBytes(R); err != nil { - panic(err) - } - - // 4. Compute SHA512(dom2(F, C) || R || A || PH(M)). - H.Reset() - - writeDom(H, ctx, preHash) - - _, _ = H.Write(R) - _, _ = H.Write(privateKey[SeedSize:]) - _, _ = H.Write(PHM) - hRAM := H.Sum(nil) - - reduceModOrder(hRAM[:], true) - - // 5. Compute S = (r + k * s) mod order. - S := (&[paramB]byte{})[:] - calculateS(S, r[:paramB], hRAM[:paramB], s) - - // 6. The signature is the concatenation of R and S. - copy(signature[:paramB], R[:]) - copy(signature[paramB:], S[:]) -} - -// Sign signs the message with privateKey and returns a signature. -// This function supports the signature variant defined in RFC-8032: Ed25519, -// also known as the pure version of EdDSA. -// It will panic if len(privateKey) is not PrivateKeySize. -func Sign(privateKey PrivateKey, message []byte) []byte { - signature := make([]byte, SignatureSize) - signAll(signature, privateKey, message, []byte(""), false) - return signature -} - -// SignPh creates a signature of a message with private key and context. -// This function supports the signature variant defined in RFC-8032: Ed25519ph, -// meaning it internally hashes the message using SHA-512, and optionally -// accepts a context string. -// It will panic if len(privateKey) is not PrivateKeySize. -// Context could be passed to this function, which length should be no more than -// ContextMaxSize=255. It can be empty. -func SignPh(privateKey PrivateKey, message []byte, ctx string) []byte { - if len(ctx) > ContextMaxSize { - panic(fmt.Errorf("ed25519: bad context length: %v", len(ctx))) - } - - signature := make([]byte, SignatureSize) - signAll(signature, privateKey, message, []byte(ctx), true) - return signature -} - -// SignWithCtx creates a signature of a message with private key and context. -// This function supports the signature variant defined in RFC-8032: Ed25519ctx, -// meaning it accepts a non-empty context string. -// It will panic if len(privateKey) is not PrivateKeySize. -// Context must be passed to this function, which length should be no more than -// ContextMaxSize=255 and cannot be empty. -func SignWithCtx(privateKey PrivateKey, message []byte, ctx string) []byte { - if len(ctx) == 0 || len(ctx) > ContextMaxSize { - panic(fmt.Errorf("ed25519: bad context length: %v > %v", len(ctx), ContextMaxSize)) - } - - signature := make([]byte, SignatureSize) - signAll(signature, privateKey, message, []byte(ctx), false) - return signature -} - -func verify(public PublicKey, message, signature, ctx []byte, preHash bool) bool { - if len(public) != PublicKeySize || - len(signature) != SignatureSize || - !isLessThanOrder(signature[paramB:]) { - return false - } - - var P pointR1 - if ok := P.FromBytes(public); !ok { - return false - } - - H := sha512.New() - var PHM []byte - - if preHash { - _, _ = H.Write(message) - PHM = H.Sum(nil) - H.Reset() - } else { - PHM = message - } - - R := signature[:paramB] - - writeDom(H, ctx, preHash) - - _, _ = H.Write(R) - _, _ = H.Write(public) - _, _ = H.Write(PHM) - hRAM := H.Sum(nil) - reduceModOrder(hRAM[:], true) - - var Q pointR1 - encR := (&[paramB]byte{})[:] - P.neg() - Q.doubleMult(&P, signature[paramB:], hRAM[:paramB]) - _ = Q.ToBytes(encR) - return bytes.Equal(R, encR) -} - -// VerifyAny returns true if the signature is valid. Failure cases are invalid -// signature, or when the public key cannot be decoded. -// This function supports all the three signature variants defined in RFC-8032, -// namely Ed25519 (or pure EdDSA), Ed25519Ph, and Ed25519Ctx. -// The opts.HashFunc() must return zero to specify either Ed25519 or Ed25519Ctx -// variant. This can be achieved by passing crypto.Hash(0) as the value for opts. -// The opts.HashFunc() must return SHA512 to specify the Ed25519Ph variant. -// This can be achieved by passing crypto.SHA512 as the value for opts. -// Use a SignerOptions struct to pass a context string for signing. -func VerifyAny(public PublicKey, message, signature []byte, opts crypto.SignerOpts) bool { - var ctx string - var scheme SchemeID - if o, ok := opts.(SignerOptions); ok { - ctx = o.Context - scheme = o.Scheme - } - - switch true { - case scheme == ED25519 && opts.HashFunc() == crypto.Hash(0): - return Verify(public, message, signature) - case scheme == ED25519Ph && opts.HashFunc() == crypto.SHA512: - return VerifyPh(public, message, signature, ctx) - case scheme == ED25519Ctx && opts.HashFunc() == crypto.Hash(0) && len(ctx) > 0: - return VerifyWithCtx(public, message, signature, ctx) - default: - return false - } -} - -// Verify returns true if the signature is valid. Failure cases are invalid -// signature, or when the public key cannot be decoded. -// This function supports the signature variant defined in RFC-8032: Ed25519, -// also known as the pure version of EdDSA. -func Verify(public PublicKey, message, signature []byte) bool { - return verify(public, message, signature, []byte(""), false) -} - -// VerifyPh returns true if the signature is valid. Failure cases are invalid -// signature, or when the public key cannot be decoded. -// This function supports the signature variant defined in RFC-8032: Ed25519ph, -// meaning it internally hashes the message using SHA-512. -// Context could be passed to this function, which length should be no more than -// 255. It can be empty. -func VerifyPh(public PublicKey, message, signature []byte, ctx string) bool { - return verify(public, message, signature, []byte(ctx), true) -} - -// VerifyWithCtx returns true if the signature is valid. Failure cases are invalid -// signature, or when the public key cannot be decoded, or when context is -// not provided. -// This function supports the signature variant defined in RFC-8032: Ed25519ctx, -// meaning it does not handle prehashed messages. Non-empty context string must be -// provided, and must not be more than 255 of length. -func VerifyWithCtx(public PublicKey, message, signature []byte, ctx string) bool { - if len(ctx) == 0 || len(ctx) > ContextMaxSize { - return false - } - - return verify(public, message, signature, []byte(ctx), false) -} - -func clamp(k []byte) { - k[0] &= 248 - k[paramB-1] = (k[paramB-1] & 127) | 64 -} - -// isLessThanOrder returns true if 0 <= x < order. -func isLessThanOrder(x []byte) bool { - i := len(order) - 1 - for i > 0 && x[i] == order[i] { - i-- - } - return x[i] < order[i] -} - -func writeDom(h io.Writer, ctx []byte, preHash bool) { - dom2 := "SigEd25519 no Ed25519 collisions" - - if len(ctx) > 0 { - _, _ = h.Write([]byte(dom2)) - if preHash { - _, _ = h.Write([]byte{byte(0x01), byte(len(ctx))}) - } else { - _, _ = h.Write([]byte{byte(0x00), byte(len(ctx))}) - } - _, _ = h.Write(ctx) - } else if preHash { - _, _ = h.Write([]byte(dom2)) - _, _ = h.Write([]byte{0x01, 0x00}) - } -} diff --git a/vendor/github.com/cloudflare/circl/sign/ed25519/modular.go b/vendor/github.com/cloudflare/circl/sign/ed25519/modular.go deleted file mode 100644 index 10efafdc..00000000 --- a/vendor/github.com/cloudflare/circl/sign/ed25519/modular.go +++ /dev/null @@ -1,175 +0,0 @@ -package ed25519 - -import ( - "encoding/binary" - "math/bits" -) - -var order = [paramB]byte{ - 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, - 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, -} - -// isLessThan returns true if 0 <= x < y, and assumes that slices have the same length. -func isLessThan(x, y []byte) bool { - i := len(x) - 1 - for i > 0 && x[i] == y[i] { - i-- - } - return x[i] < y[i] -} - -// reduceModOrder calculates k = k mod order of the curve. -func reduceModOrder(k []byte, is512Bit bool) { - var X [((2 * paramB) * 8) / 64]uint64 - numWords := len(k) >> 3 - for i := 0; i < numWords; i++ { - X[i] = binary.LittleEndian.Uint64(k[i*8 : (i+1)*8]) - } - red512(&X, is512Bit) - for i := 0; i < numWords; i++ { - binary.LittleEndian.PutUint64(k[i*8:(i+1)*8], X[i]) - } -} - -// red512 calculates x = x mod Order of the curve. -func red512(x *[8]uint64, full bool) { - // Implementation of Algs.(14.47)+(14.52) of Handbook of Applied - // Cryptography, by A. Menezes, P. van Oorschot, and S. Vanstone. - const ( - ell0 = uint64(0x5812631a5cf5d3ed) - ell1 = uint64(0x14def9dea2f79cd6) - ell160 = uint64(0x812631a5cf5d3ed0) - ell161 = uint64(0x4def9dea2f79cd65) - ell162 = uint64(0x0000000000000001) - ) - - var c0, c1, c2, c3 uint64 - r0, r1, r2, r3, r4 := x[0], x[1], x[2], x[3], uint64(0) - - if full { - q0, q1, q2, q3 := x[4], x[5], x[6], x[7] - - for i := 0; i < 3; i++ { - h0, s0 := bits.Mul64(q0, ell160) - h1, s1 := bits.Mul64(q1, ell160) - h2, s2 := bits.Mul64(q2, ell160) - h3, s3 := bits.Mul64(q3, ell160) - - s1, c0 = bits.Add64(h0, s1, 0) - s2, c1 = bits.Add64(h1, s2, c0) - s3, c2 = bits.Add64(h2, s3, c1) - s4, _ := bits.Add64(h3, 0, c2) - - h0, l0 := bits.Mul64(q0, ell161) - h1, l1 := bits.Mul64(q1, ell161) - h2, l2 := bits.Mul64(q2, ell161) - h3, l3 := bits.Mul64(q3, ell161) - - l1, c0 = bits.Add64(h0, l1, 0) - l2, c1 = bits.Add64(h1, l2, c0) - l3, c2 = bits.Add64(h2, l3, c1) - l4, _ := bits.Add64(h3, 0, c2) - - s1, c0 = bits.Add64(s1, l0, 0) - s2, c1 = bits.Add64(s2, l1, c0) - s3, c2 = bits.Add64(s3, l2, c1) - s4, c3 = bits.Add64(s4, l3, c2) - s5, s6 := bits.Add64(l4, 0, c3) - - s2, c0 = bits.Add64(s2, q0, 0) - s3, c1 = bits.Add64(s3, q1, c0) - s4, c2 = bits.Add64(s4, q2, c1) - s5, c3 = bits.Add64(s5, q3, c2) - s6, s7 := bits.Add64(s6, 0, c3) - - q := q0 | q1 | q2 | q3 - m := -((q | -q) >> 63) // if q=0 then m=0...0 else m=1..1 - s0 &= m - s1 &= m - s2 &= m - s3 &= m - q0, q1, q2, q3 = s4, s5, s6, s7 - - if (i+1)%2 == 0 { - r0, c0 = bits.Add64(r0, s0, 0) - r1, c1 = bits.Add64(r1, s1, c0) - r2, c2 = bits.Add64(r2, s2, c1) - r3, c3 = bits.Add64(r3, s3, c2) - r4, _ = bits.Add64(r4, 0, c3) - } else { - r0, c0 = bits.Sub64(r0, s0, 0) - r1, c1 = bits.Sub64(r1, s1, c0) - r2, c2 = bits.Sub64(r2, s2, c1) - r3, c3 = bits.Sub64(r3, s3, c2) - r4, _ = bits.Sub64(r4, 0, c3) - } - } - - m := -(r4 >> 63) - r0, c0 = bits.Add64(r0, m&ell160, 0) - r1, c1 = bits.Add64(r1, m&ell161, c0) - r2, c2 = bits.Add64(r2, m&ell162, c1) - r3, c3 = bits.Add64(r3, 0, c2) - r4, _ = bits.Add64(r4, m&1, c3) - x[4], x[5], x[6], x[7] = 0, 0, 0, 0 - } - - q0 := (r4 << 4) | (r3 >> 60) - r3 &= (uint64(1) << 60) - 1 - - h0, s0 := bits.Mul64(ell0, q0) - h1, s1 := bits.Mul64(ell1, q0) - s1, c0 = bits.Add64(h0, s1, 0) - s2, _ := bits.Add64(h1, 0, c0) - - r0, c0 = bits.Sub64(r0, s0, 0) - r1, c1 = bits.Sub64(r1, s1, c0) - r2, c2 = bits.Sub64(r2, s2, c1) - r3, _ = bits.Sub64(r3, 0, c2) - - x[0], x[1], x[2], x[3] = r0, r1, r2, r3 -} - -// calculateS performs s = r+k*a mod Order of the curve. -func calculateS(s, r, k, a []byte) { - K := [4]uint64{ - binary.LittleEndian.Uint64(k[0*8 : 1*8]), - binary.LittleEndian.Uint64(k[1*8 : 2*8]), - binary.LittleEndian.Uint64(k[2*8 : 3*8]), - binary.LittleEndian.Uint64(k[3*8 : 4*8]), - } - S := [8]uint64{ - binary.LittleEndian.Uint64(r[0*8 : 1*8]), - binary.LittleEndian.Uint64(r[1*8 : 2*8]), - binary.LittleEndian.Uint64(r[2*8 : 3*8]), - binary.LittleEndian.Uint64(r[3*8 : 4*8]), - } - var c3 uint64 - for i := range K { - ai := binary.LittleEndian.Uint64(a[i*8 : (i+1)*8]) - - h0, l0 := bits.Mul64(K[0], ai) - h1, l1 := bits.Mul64(K[1], ai) - h2, l2 := bits.Mul64(K[2], ai) - h3, l3 := bits.Mul64(K[3], ai) - - l1, c0 := bits.Add64(h0, l1, 0) - l2, c1 := bits.Add64(h1, l2, c0) - l3, c2 := bits.Add64(h2, l3, c1) - l4, _ := bits.Add64(h3, 0, c2) - - S[i+0], c0 = bits.Add64(S[i+0], l0, 0) - S[i+1], c1 = bits.Add64(S[i+1], l1, c0) - S[i+2], c2 = bits.Add64(S[i+2], l2, c1) - S[i+3], c3 = bits.Add64(S[i+3], l3, c2) - S[i+4], _ = bits.Add64(S[i+4], l4, c3) - } - red512(&S, true) - binary.LittleEndian.PutUint64(s[0*8:1*8], S[0]) - binary.LittleEndian.PutUint64(s[1*8:2*8], S[1]) - binary.LittleEndian.PutUint64(s[2*8:3*8], S[2]) - binary.LittleEndian.PutUint64(s[3*8:4*8], S[3]) -} diff --git a/vendor/github.com/cloudflare/circl/sign/ed25519/mult.go b/vendor/github.com/cloudflare/circl/sign/ed25519/mult.go deleted file mode 100644 index 3216aae3..00000000 --- a/vendor/github.com/cloudflare/circl/sign/ed25519/mult.go +++ /dev/null @@ -1,180 +0,0 @@ -package ed25519 - -import ( - "crypto/subtle" - "encoding/binary" - "math/bits" - - "github.com/cloudflare/circl/internal/conv" - "github.com/cloudflare/circl/math" - fp "github.com/cloudflare/circl/math/fp25519" -) - -var paramD = fp.Elt{ - 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, -} - -// mLSBRecoding parameters. -const ( - fxT = 257 - fxV = 2 - fxW = 3 - fx2w1 = 1 << (uint(fxW) - 1) - numWords64 = (paramB * 8 / 64) -) - -// mLSBRecoding is the odd-only modified LSB-set. -// -// Reference: -// -// "Efficient and secure algorithms for GLV-based scalar multiplication and -// their implementation on GLV–GLS curves" by (Faz-Hernandez et al.) -// http://doi.org/10.1007/s13389-014-0085-7. -func mLSBRecoding(L []int8, k []byte) { - const ee = (fxT + fxW*fxV - 1) / (fxW * fxV) - const dd = ee * fxV - const ll = dd * fxW - if len(L) == (ll + 1) { - var m [numWords64 + 1]uint64 - for i := 0; i < numWords64; i++ { - m[i] = binary.LittleEndian.Uint64(k[8*i : 8*i+8]) - } - condAddOrderN(&m) - L[dd-1] = 1 - for i := 0; i < dd-1; i++ { - kip1 := (m[(i+1)/64] >> (uint(i+1) % 64)) & 0x1 - L[i] = int8(kip1<<1) - 1 - } - { // right-shift by d - right := uint(dd % 64) - left := uint(64) - right - lim := ((numWords64+1)*64 - dd) / 64 - j := dd / 64 - for i := 0; i < lim; i++ { - m[i] = (m[i+j] >> right) | (m[i+j+1] << left) - } - m[lim] = m[lim+j] >> right - } - for i := dd; i < ll; i++ { - L[i] = L[i%dd] * int8(m[0]&0x1) - div2subY(m[:], int64(L[i]>>1), numWords64) - } - L[ll] = int8(m[0]) - } -} - -// absolute returns always a positive value. -func absolute(x int32) int32 { - mask := x >> 31 - return (x + mask) ^ mask -} - -// condAddOrderN updates x = x+order if x is even, otherwise x remains unchanged. -func condAddOrderN(x *[numWords64 + 1]uint64) { - isOdd := (x[0] & 0x1) - 1 - c := uint64(0) - for i := 0; i < numWords64; i++ { - orderWord := binary.LittleEndian.Uint64(order[8*i : 8*i+8]) - o := isOdd & orderWord - x0, c0 := bits.Add64(x[i], o, c) - x[i] = x0 - c = c0 - } - x[numWords64], _ = bits.Add64(x[numWords64], 0, c) -} - -// div2subY update x = (x/2) - y. -func div2subY(x []uint64, y int64, l int) { - s := uint64(y >> 63) - for i := 0; i < l-1; i++ { - x[i] = (x[i] >> 1) | (x[i+1] << 63) - } - x[l-1] = (x[l-1] >> 1) - - b := uint64(0) - x0, b0 := bits.Sub64(x[0], uint64(y), b) - x[0] = x0 - b = b0 - for i := 1; i < l-1; i++ { - x0, b0 := bits.Sub64(x[i], s, b) - x[i] = x0 - b = b0 - } - x[l-1], _ = bits.Sub64(x[l-1], s, b) -} - -func (P *pointR1) fixedMult(scalar []byte) { - if len(scalar) != paramB { - panic("wrong scalar size") - } - const ee = (fxT + fxW*fxV - 1) / (fxW * fxV) - const dd = ee * fxV - const ll = dd * fxW - - L := make([]int8, ll+1) - mLSBRecoding(L[:], scalar) - S := &pointR3{} - P.SetIdentity() - for ii := ee - 1; ii >= 0; ii-- { - P.double() - for j := 0; j < fxV; j++ { - dig := L[fxW*dd-j*ee+ii-ee] - for i := (fxW-1)*dd - j*ee + ii - ee; i >= (2*dd - j*ee + ii - ee); i = i - dd { - dig = 2*dig + L[i] - } - idx := absolute(int32(dig)) - sig := L[dd-j*ee+ii-ee] - Tabj := &tabSign[fxV-j-1] - for k := 0; k < fx2w1; k++ { - S.cmov(&Tabj[k], subtle.ConstantTimeEq(int32(k), idx)) - } - S.cneg(subtle.ConstantTimeEq(int32(sig), -1)) - P.mixAdd(S) - } - } -} - -const ( - omegaFix = 7 - omegaVar = 5 -) - -// doubleMult returns P=mG+nQ. -func (P *pointR1) doubleMult(Q *pointR1, m, n []byte) { - nafFix := math.OmegaNAF(conv.BytesLe2BigInt(m), omegaFix) - nafVar := math.OmegaNAF(conv.BytesLe2BigInt(n), omegaVar) - - if len(nafFix) > len(nafVar) { - nafVar = append(nafVar, make([]int32, len(nafFix)-len(nafVar))...) - } else if len(nafFix) < len(nafVar) { - nafFix = append(nafFix, make([]int32, len(nafVar)-len(nafFix))...) - } - - var TabQ [1 << (omegaVar - 2)]pointR2 - Q.oddMultiples(TabQ[:]) - P.SetIdentity() - for i := len(nafFix) - 1; i >= 0; i-- { - P.double() - // Generator point - if nafFix[i] != 0 { - idxM := absolute(nafFix[i]) >> 1 - R := tabVerif[idxM] - if nafFix[i] < 0 { - R.neg() - } - P.mixAdd(&R) - } - // Variable input point - if nafVar[i] != 0 { - idxN := absolute(nafVar[i]) >> 1 - S := TabQ[idxN] - if nafVar[i] < 0 { - S.neg() - } - P.add(&S) - } - } -} diff --git a/vendor/github.com/cloudflare/circl/sign/ed25519/point.go b/vendor/github.com/cloudflare/circl/sign/ed25519/point.go deleted file mode 100644 index 374a6950..00000000 --- a/vendor/github.com/cloudflare/circl/sign/ed25519/point.go +++ /dev/null @@ -1,195 +0,0 @@ -package ed25519 - -import fp "github.com/cloudflare/circl/math/fp25519" - -type ( - pointR1 struct{ x, y, z, ta, tb fp.Elt } - pointR2 struct { - pointR3 - z2 fp.Elt - } -) -type pointR3 struct{ addYX, subYX, dt2 fp.Elt } - -func (P *pointR1) neg() { - fp.Neg(&P.x, &P.x) - fp.Neg(&P.ta, &P.ta) -} - -func (P *pointR1) SetIdentity() { - P.x = fp.Elt{} - fp.SetOne(&P.y) - fp.SetOne(&P.z) - P.ta = fp.Elt{} - P.tb = fp.Elt{} -} - -func (P *pointR1) toAffine() { - fp.Inv(&P.z, &P.z) - fp.Mul(&P.x, &P.x, &P.z) - fp.Mul(&P.y, &P.y, &P.z) - fp.Modp(&P.x) - fp.Modp(&P.y) - fp.SetOne(&P.z) - P.ta = P.x - P.tb = P.y -} - -func (P *pointR1) ToBytes(k []byte) error { - P.toAffine() - var x [fp.Size]byte - err := fp.ToBytes(k[:fp.Size], &P.y) - if err != nil { - return err - } - err = fp.ToBytes(x[:], &P.x) - if err != nil { - return err - } - b := x[0] & 1 - k[paramB-1] = k[paramB-1] | (b << 7) - return nil -} - -func (P *pointR1) FromBytes(k []byte) bool { - if len(k) != paramB { - panic("wrong size") - } - signX := k[paramB-1] >> 7 - copy(P.y[:], k[:fp.Size]) - P.y[fp.Size-1] &= 0x7F - p := fp.P() - if !isLessThan(P.y[:], p[:]) { - return false - } - - one, u, v := &fp.Elt{}, &fp.Elt{}, &fp.Elt{} - fp.SetOne(one) - fp.Sqr(u, &P.y) // u = y^2 - fp.Mul(v, u, ¶mD) // v = dy^2 - fp.Sub(u, u, one) // u = y^2-1 - fp.Add(v, v, one) // v = dy^2+1 - isQR := fp.InvSqrt(&P.x, u, v) // x = sqrt(u/v) - if !isQR { - return false - } - fp.Modp(&P.x) // x = x mod p - if fp.IsZero(&P.x) && signX == 1 { - return false - } - if signX != (P.x[0] & 1) { - fp.Neg(&P.x, &P.x) - } - P.ta = P.x - P.tb = P.y - fp.SetOne(&P.z) - return true -} - -// double calculates 2P for curves with A=-1. -func (P *pointR1) double() { - Px, Py, Pz, Pta, Ptb := &P.x, &P.y, &P.z, &P.ta, &P.tb - a, b, c, e, f, g, h := Px, Py, Pz, Pta, Px, Py, Ptb - fp.Add(e, Px, Py) // x+y - fp.Sqr(a, Px) // A = x^2 - fp.Sqr(b, Py) // B = y^2 - fp.Sqr(c, Pz) // z^2 - fp.Add(c, c, c) // C = 2*z^2 - fp.Add(h, a, b) // H = A+B - fp.Sqr(e, e) // (x+y)^2 - fp.Sub(e, e, h) // E = (x+y)^2-A-B - fp.Sub(g, b, a) // G = B-A - fp.Sub(f, c, g) // F = C-G - fp.Mul(Pz, f, g) // Z = F * G - fp.Mul(Px, e, f) // X = E * F - fp.Mul(Py, g, h) // Y = G * H, T = E * H -} - -func (P *pointR1) mixAdd(Q *pointR3) { - fp.Add(&P.z, &P.z, &P.z) // D = 2*z1 - P.coreAddition(Q) -} - -func (P *pointR1) add(Q *pointR2) { - fp.Mul(&P.z, &P.z, &Q.z2) // D = 2*z1*z2 - P.coreAddition(&Q.pointR3) -} - -// coreAddition calculates P=P+Q for curves with A=-1. -func (P *pointR1) coreAddition(Q *pointR3) { - Px, Py, Pz, Pta, Ptb := &P.x, &P.y, &P.z, &P.ta, &P.tb - addYX2, subYX2, dt2 := &Q.addYX, &Q.subYX, &Q.dt2 - a, b, c, d, e, f, g, h := Px, Py, &fp.Elt{}, Pz, Pta, Px, Py, Ptb - fp.Mul(c, Pta, Ptb) // t1 = ta*tb - fp.Sub(h, Py, Px) // y1-x1 - fp.Add(b, Py, Px) // y1+x1 - fp.Mul(a, h, subYX2) // A = (y1-x1)*(y2-x2) - fp.Mul(b, b, addYX2) // B = (y1+x1)*(y2+x2) - fp.Mul(c, c, dt2) // C = 2*D*t1*t2 - fp.Sub(e, b, a) // E = B-A - fp.Add(h, b, a) // H = B+A - fp.Sub(f, d, c) // F = D-C - fp.Add(g, d, c) // G = D+C - fp.Mul(Pz, f, g) // Z = F * G - fp.Mul(Px, e, f) // X = E * F - fp.Mul(Py, g, h) // Y = G * H, T = E * H -} - -func (P *pointR1) oddMultiples(T []pointR2) { - var R pointR2 - n := len(T) - T[0].fromR1(P) - _2P := *P - _2P.double() - R.fromR1(&_2P) - for i := 1; i < n; i++ { - P.add(&R) - T[i].fromR1(P) - } -} - -func (P *pointR1) isEqual(Q *pointR1) bool { - l, r := &fp.Elt{}, &fp.Elt{} - fp.Mul(l, &P.x, &Q.z) - fp.Mul(r, &Q.x, &P.z) - fp.Sub(l, l, r) - b := fp.IsZero(l) - fp.Mul(l, &P.y, &Q.z) - fp.Mul(r, &Q.y, &P.z) - fp.Sub(l, l, r) - b = b && fp.IsZero(l) - fp.Mul(l, &P.ta, &P.tb) - fp.Mul(l, l, &Q.z) - fp.Mul(r, &Q.ta, &Q.tb) - fp.Mul(r, r, &P.z) - fp.Sub(l, l, r) - b = b && fp.IsZero(l) - return b -} - -func (P *pointR3) neg() { - P.addYX, P.subYX = P.subYX, P.addYX - fp.Neg(&P.dt2, &P.dt2) -} - -func (P *pointR2) fromR1(Q *pointR1) { - fp.Add(&P.addYX, &Q.y, &Q.x) - fp.Sub(&P.subYX, &Q.y, &Q.x) - fp.Mul(&P.dt2, &Q.ta, &Q.tb) - fp.Mul(&P.dt2, &P.dt2, ¶mD) - fp.Add(&P.dt2, &P.dt2, &P.dt2) - fp.Add(&P.z2, &Q.z, &Q.z) -} - -func (P *pointR3) cneg(b int) { - t := &fp.Elt{} - fp.Cswap(&P.addYX, &P.subYX, uint(b)) - fp.Neg(t, &P.dt2) - fp.Cmov(&P.dt2, t, uint(b)) -} - -func (P *pointR3) cmov(Q *pointR3, b int) { - fp.Cmov(&P.addYX, &Q.addYX, uint(b)) - fp.Cmov(&P.subYX, &Q.subYX, uint(b)) - fp.Cmov(&P.dt2, &Q.dt2, uint(b)) -} diff --git a/vendor/github.com/cloudflare/circl/sign/ed25519/pubkey.go b/vendor/github.com/cloudflare/circl/sign/ed25519/pubkey.go deleted file mode 100644 index c3505b67..00000000 --- a/vendor/github.com/cloudflare/circl/sign/ed25519/pubkey.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build go1.13 -// +build go1.13 - -package ed25519 - -import cryptoEd25519 "crypto/ed25519" - -// PublicKey is the type of Ed25519 public keys. -type PublicKey cryptoEd25519.PublicKey diff --git a/vendor/github.com/cloudflare/circl/sign/ed25519/pubkey112.go b/vendor/github.com/cloudflare/circl/sign/ed25519/pubkey112.go deleted file mode 100644 index d57d86ef..00000000 --- a/vendor/github.com/cloudflare/circl/sign/ed25519/pubkey112.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build !go1.13 -// +build !go1.13 - -package ed25519 - -// PublicKey is the type of Ed25519 public keys. -type PublicKey []byte diff --git a/vendor/github.com/cloudflare/circl/sign/ed25519/signapi.go b/vendor/github.com/cloudflare/circl/sign/ed25519/signapi.go deleted file mode 100644 index e4520f52..00000000 --- a/vendor/github.com/cloudflare/circl/sign/ed25519/signapi.go +++ /dev/null @@ -1,87 +0,0 @@ -package ed25519 - -import ( - "crypto/rand" - "encoding/asn1" - - "github.com/cloudflare/circl/sign" -) - -var sch sign.Scheme = &scheme{} - -// Scheme returns a signature interface. -func Scheme() sign.Scheme { return sch } - -type scheme struct{} - -func (*scheme) Name() string { return "Ed25519" } -func (*scheme) PublicKeySize() int { return PublicKeySize } -func (*scheme) PrivateKeySize() int { return PrivateKeySize } -func (*scheme) SignatureSize() int { return SignatureSize } -func (*scheme) SeedSize() int { return SeedSize } -func (*scheme) TLSIdentifier() uint { return 0x0807 } -func (*scheme) SupportsContext() bool { return false } -func (*scheme) Oid() asn1.ObjectIdentifier { - return asn1.ObjectIdentifier{1, 3, 101, 112} -} - -func (*scheme) GenerateKey() (sign.PublicKey, sign.PrivateKey, error) { - return GenerateKey(rand.Reader) -} - -func (*scheme) Sign( - sk sign.PrivateKey, - message []byte, - opts *sign.SignatureOpts, -) []byte { - priv, ok := sk.(PrivateKey) - if !ok { - panic(sign.ErrTypeMismatch) - } - if opts != nil && opts.Context != "" { - panic(sign.ErrContextNotSupported) - } - return Sign(priv, message) -} - -func (*scheme) Verify( - pk sign.PublicKey, - message, signature []byte, - opts *sign.SignatureOpts, -) bool { - pub, ok := pk.(PublicKey) - if !ok { - panic(sign.ErrTypeMismatch) - } - if opts != nil { - if opts.Context != "" { - panic(sign.ErrContextNotSupported) - } - } - return Verify(pub, message, signature) -} - -func (*scheme) DeriveKey(seed []byte) (sign.PublicKey, sign.PrivateKey) { - privateKey := NewKeyFromSeed(seed) - publicKey := make(PublicKey, PublicKeySize) - copy(publicKey, privateKey[SeedSize:]) - return publicKey, privateKey -} - -func (*scheme) UnmarshalBinaryPublicKey(buf []byte) (sign.PublicKey, error) { - if len(buf) < PublicKeySize { - return nil, sign.ErrPubKeySize - } - pub := make(PublicKey, PublicKeySize) - copy(pub, buf[:PublicKeySize]) - return pub, nil -} - -func (*scheme) UnmarshalBinaryPrivateKey(buf []byte) (sign.PrivateKey, error) { - if len(buf) < PrivateKeySize { - return nil, sign.ErrPrivKeySize - } - priv := make(PrivateKey, PrivateKeySize) - copy(priv, buf[:PrivateKeySize]) - return priv, nil -} diff --git a/vendor/github.com/cloudflare/circl/sign/ed25519/tables.go b/vendor/github.com/cloudflare/circl/sign/ed25519/tables.go deleted file mode 100644 index 8763b426..00000000 --- a/vendor/github.com/cloudflare/circl/sign/ed25519/tables.go +++ /dev/null @@ -1,213 +0,0 @@ -package ed25519 - -import fp "github.com/cloudflare/circl/math/fp25519" - -var tabSign = [fxV][fx2w1]pointR3{ - { - pointR3{ - addYX: fp.Elt{0x85, 0x3b, 0x8c, 0xf5, 0xc6, 0x93, 0xbc, 0x2f, 0x19, 0x0e, 0x8c, 0xfb, 0xc6, 0x2d, 0x93, 0xcf, 0xc2, 0x42, 0x3d, 0x64, 0x98, 0x48, 0x0b, 0x27, 0x65, 0xba, 0xd4, 0x33, 0x3a, 0x9d, 0xcf, 0x07}, - subYX: fp.Elt{0x3e, 0x91, 0x40, 0xd7, 0x05, 0x39, 0x10, 0x9d, 0xb3, 0xbe, 0x40, 0xd1, 0x05, 0x9f, 0x39, 0xfd, 0x09, 0x8a, 0x8f, 0x68, 0x34, 0x84, 0xc1, 0xa5, 0x67, 0x12, 0xf8, 0x98, 0x92, 0x2f, 0xfd, 0x44}, - dt2: fp.Elt{0x68, 0xaa, 0x7a, 0x87, 0x05, 0x12, 0xc9, 0xab, 0x9e, 0xc4, 0xaa, 0xcc, 0x23, 0xe8, 0xd9, 0x26, 0x8c, 0x59, 0x43, 0xdd, 0xcb, 0x7d, 0x1b, 0x5a, 0xa8, 0x65, 0x0c, 0x9f, 0x68, 0x7b, 0x11, 0x6f}, - }, - { - addYX: fp.Elt{0x7c, 0xb0, 0x9e, 0xe6, 0xc5, 0xbf, 0xfa, 0x13, 0x8e, 0x0d, 0x22, 0xde, 0xc8, 0xd1, 0xce, 0x52, 0x02, 0xd5, 0x62, 0x31, 0x71, 0x0e, 0x8e, 0x9d, 0xb0, 0xd6, 0x00, 0xa5, 0x5a, 0x0e, 0xce, 0x72}, - subYX: fp.Elt{0x1a, 0x8e, 0x5c, 0xdc, 0xa4, 0xb3, 0x6c, 0x51, 0x18, 0xa0, 0x09, 0x80, 0x9a, 0x46, 0x33, 0xd5, 0xe0, 0x3c, 0x4d, 0x3b, 0xfc, 0x49, 0xa2, 0x43, 0x29, 0xe1, 0x29, 0xa9, 0x93, 0xea, 0x7c, 0x35}, - dt2: fp.Elt{0x08, 0x46, 0x6f, 0x68, 0x7f, 0x0b, 0x7c, 0x9e, 0xad, 0xba, 0x07, 0x61, 0x74, 0x83, 0x2f, 0xfc, 0x26, 0xd6, 0x09, 0xb9, 0x00, 0x34, 0x36, 0x4f, 0x01, 0xf3, 0x48, 0xdb, 0x43, 0xba, 0x04, 0x44}, - }, - { - addYX: fp.Elt{0x4c, 0xda, 0x0d, 0x13, 0x66, 0xfd, 0x82, 0x84, 0x9f, 0x75, 0x5b, 0xa2, 0x17, 0xfe, 0x34, 0xbf, 0x1f, 0xcb, 0xba, 0x90, 0x55, 0x80, 0x83, 0xfd, 0x63, 0xb9, 0x18, 0xf8, 0x5b, 0x5d, 0x94, 0x1e}, - subYX: fp.Elt{0xb9, 0xdb, 0x6c, 0x04, 0x88, 0x22, 0xd8, 0x79, 0x83, 0x2f, 0x8d, 0x65, 0x6b, 0xd2, 0xab, 0x1b, 0xdd, 0x65, 0xe5, 0x93, 0x63, 0xf8, 0xa2, 0xd8, 0x3c, 0xf1, 0x4b, 0xc5, 0x99, 0xd1, 0xf2, 0x12}, - dt2: fp.Elt{0x05, 0x4c, 0xb8, 0x3b, 0xfe, 0xf5, 0x9f, 0x2e, 0xd1, 0xb2, 0xb8, 0xff, 0xfe, 0x6d, 0xd9, 0x37, 0xe0, 0xae, 0xb4, 0x5a, 0x51, 0x80, 0x7e, 0x9b, 0x1d, 0xd1, 0x8d, 0x8c, 0x56, 0xb1, 0x84, 0x35}, - }, - { - addYX: fp.Elt{0x39, 0x71, 0x43, 0x34, 0xe3, 0x42, 0x45, 0xa1, 0xf2, 0x68, 0x71, 0xa7, 0xe8, 0x23, 0xfd, 0x9f, 0x86, 0x48, 0xff, 0xe5, 0x96, 0x74, 0xcf, 0x05, 0x49, 0xe2, 0xb3, 0x6c, 0x17, 0x77, 0x2f, 0x6d}, - subYX: fp.Elt{0x73, 0x3f, 0xc1, 0xc7, 0x6a, 0x66, 0xa1, 0x20, 0xdd, 0x11, 0xfb, 0x7a, 0x6e, 0xa8, 0x51, 0xb8, 0x3f, 0x9d, 0xa2, 0x97, 0x84, 0xb5, 0xc7, 0x90, 0x7c, 0xab, 0x48, 0xd6, 0x84, 0xa3, 0xd5, 0x1a}, - dt2: fp.Elt{0x63, 0x27, 0x3c, 0x49, 0x4b, 0xfc, 0x22, 0xf2, 0x0b, 0x50, 0xc2, 0x0f, 0xb4, 0x1f, 0x31, 0x0c, 0x2f, 0x53, 0xab, 0xaa, 0x75, 0x6f, 0xe0, 0x69, 0x39, 0x56, 0xe0, 0x3b, 0xb7, 0xa8, 0xbf, 0x45}, - }, - }, - { - { - addYX: fp.Elt{0x00, 0x45, 0xd9, 0x0d, 0x58, 0x03, 0xfc, 0x29, 0x93, 0xec, 0xbb, 0x6f, 0xa4, 0x7a, 0xd2, 0xec, 0xf8, 0xa7, 0xe2, 0xc2, 0x5f, 0x15, 0x0a, 0x13, 0xd5, 0xa1, 0x06, 0xb7, 0x1a, 0x15, 0x6b, 0x41}, - subYX: fp.Elt{0x85, 0x8c, 0xb2, 0x17, 0xd6, 0x3b, 0x0a, 0xd3, 0xea, 0x3b, 0x77, 0x39, 0xb7, 0x77, 0xd3, 0xc5, 0xbf, 0x5c, 0x6a, 0x1e, 0x8c, 0xe7, 0xc6, 0xc6, 0xc4, 0xb7, 0x2a, 0x8b, 0xf7, 0xb8, 0x61, 0x0d}, - dt2: fp.Elt{0xb0, 0x36, 0xc1, 0xe9, 0xef, 0xd7, 0xa8, 0x56, 0x20, 0x4b, 0xe4, 0x58, 0xcd, 0xe5, 0x07, 0xbd, 0xab, 0xe0, 0x57, 0x1b, 0xda, 0x2f, 0xe6, 0xaf, 0xd2, 0xe8, 0x77, 0x42, 0xf7, 0x2a, 0x1a, 0x19}, - }, - { - addYX: fp.Elt{0x6a, 0x6d, 0x6d, 0xd1, 0xfa, 0xf5, 0x03, 0x30, 0xbd, 0x6d, 0xc2, 0xc8, 0xf5, 0x38, 0x80, 0x4f, 0xb2, 0xbe, 0xa1, 0x76, 0x50, 0x1a, 0x73, 0xf2, 0x78, 0x2b, 0x8e, 0x3a, 0x1e, 0x34, 0x47, 0x7b}, - subYX: fp.Elt{0xc3, 0x2c, 0x36, 0xdc, 0xc5, 0x45, 0xbc, 0xef, 0x1b, 0x64, 0xd6, 0x65, 0x28, 0xe9, 0xda, 0x84, 0x13, 0xbe, 0x27, 0x8e, 0x3f, 0x98, 0x2a, 0x37, 0xee, 0x78, 0x97, 0xd6, 0xc0, 0x6f, 0xb4, 0x53}, - dt2: fp.Elt{0x58, 0x5d, 0xa7, 0xa3, 0x68, 0xbb, 0x20, 0x30, 0x2e, 0x03, 0xe9, 0xb1, 0xd4, 0x90, 0x72, 0xe3, 0x71, 0xb2, 0x36, 0x3e, 0x73, 0xa0, 0x2e, 0x3d, 0xd1, 0x85, 0x33, 0x62, 0x4e, 0xa7, 0x7b, 0x31}, - }, - { - addYX: fp.Elt{0xbf, 0xc4, 0x38, 0x53, 0xfb, 0x68, 0xa9, 0x77, 0xce, 0x55, 0xf9, 0x05, 0xcb, 0xeb, 0xfb, 0x8c, 0x46, 0xc2, 0x32, 0x7c, 0xf0, 0xdb, 0xd7, 0x2c, 0x62, 0x8e, 0xdd, 0x54, 0x75, 0xcf, 0x3f, 0x33}, - subYX: fp.Elt{0x49, 0x50, 0x1f, 0x4e, 0x6e, 0x55, 0x55, 0xde, 0x8c, 0x4e, 0x77, 0x96, 0x38, 0x3b, 0xfe, 0xb6, 0x43, 0x3c, 0x86, 0x69, 0xc2, 0x72, 0x66, 0x1f, 0x6b, 0xf9, 0x87, 0xbc, 0x4f, 0x37, 0x3e, 0x3c}, - dt2: fp.Elt{0xd2, 0x2f, 0x06, 0x6b, 0x08, 0x07, 0x69, 0x77, 0xc0, 0x94, 0xcc, 0xae, 0x43, 0x00, 0x59, 0x6e, 0xa3, 0x63, 0xa8, 0xdd, 0xfa, 0x24, 0x18, 0xd0, 0x35, 0xc7, 0x78, 0xf7, 0x0d, 0xd4, 0x5a, 0x1e}, - }, - { - addYX: fp.Elt{0x45, 0xc1, 0x17, 0x51, 0xf8, 0xed, 0x7e, 0xc7, 0xa9, 0x1a, 0x11, 0x6e, 0x2d, 0xef, 0x0b, 0xd5, 0x3f, 0x98, 0xb0, 0xa3, 0x9d, 0x65, 0xf1, 0xcd, 0x53, 0x4a, 0x8a, 0x18, 0x70, 0x0a, 0x7f, 0x23}, - subYX: fp.Elt{0xdd, 0xef, 0xbe, 0x3a, 0x31, 0xe0, 0xbc, 0xbe, 0x6d, 0x5d, 0x79, 0x87, 0xd6, 0xbe, 0x68, 0xe3, 0x59, 0x76, 0x8c, 0x86, 0x0e, 0x7a, 0x92, 0x13, 0x14, 0x8f, 0x67, 0xb3, 0xcb, 0x1a, 0x76, 0x76}, - dt2: fp.Elt{0x56, 0x7a, 0x1c, 0x9d, 0xca, 0x96, 0xf9, 0xf9, 0x03, 0x21, 0xd4, 0xe8, 0xb3, 0xd5, 0xe9, 0x52, 0xc8, 0x54, 0x1e, 0x1b, 0x13, 0xb6, 0xfd, 0x47, 0x7d, 0x02, 0x32, 0x33, 0x27, 0xe2, 0x1f, 0x19}, - }, - }, -} - -var tabVerif = [1 << (omegaFix - 2)]pointR3{ - { /* 1P */ - addYX: fp.Elt{0x85, 0x3b, 0x8c, 0xf5, 0xc6, 0x93, 0xbc, 0x2f, 0x19, 0x0e, 0x8c, 0xfb, 0xc6, 0x2d, 0x93, 0xcf, 0xc2, 0x42, 0x3d, 0x64, 0x98, 0x48, 0x0b, 0x27, 0x65, 0xba, 0xd4, 0x33, 0x3a, 0x9d, 0xcf, 0x07}, - subYX: fp.Elt{0x3e, 0x91, 0x40, 0xd7, 0x05, 0x39, 0x10, 0x9d, 0xb3, 0xbe, 0x40, 0xd1, 0x05, 0x9f, 0x39, 0xfd, 0x09, 0x8a, 0x8f, 0x68, 0x34, 0x84, 0xc1, 0xa5, 0x67, 0x12, 0xf8, 0x98, 0x92, 0x2f, 0xfd, 0x44}, - dt2: fp.Elt{0x68, 0xaa, 0x7a, 0x87, 0x05, 0x12, 0xc9, 0xab, 0x9e, 0xc4, 0xaa, 0xcc, 0x23, 0xe8, 0xd9, 0x26, 0x8c, 0x59, 0x43, 0xdd, 0xcb, 0x7d, 0x1b, 0x5a, 0xa8, 0x65, 0x0c, 0x9f, 0x68, 0x7b, 0x11, 0x6f}, - }, - { /* 3P */ - addYX: fp.Elt{0x30, 0x97, 0xee, 0x4c, 0xa8, 0xb0, 0x25, 0xaf, 0x8a, 0x4b, 0x86, 0xe8, 0x30, 0x84, 0x5a, 0x02, 0x32, 0x67, 0x01, 0x9f, 0x02, 0x50, 0x1b, 0xc1, 0xf4, 0xf8, 0x80, 0x9a, 0x1b, 0x4e, 0x16, 0x7a}, - subYX: fp.Elt{0x65, 0xd2, 0xfc, 0xa4, 0xe8, 0x1f, 0x61, 0x56, 0x7d, 0xba, 0xc1, 0xe5, 0xfd, 0x53, 0xd3, 0x3b, 0xbd, 0xd6, 0x4b, 0x21, 0x1a, 0xf3, 0x31, 0x81, 0x62, 0xda, 0x5b, 0x55, 0x87, 0x15, 0xb9, 0x2a}, - dt2: fp.Elt{0x89, 0xd8, 0xd0, 0x0d, 0x3f, 0x93, 0xae, 0x14, 0x62, 0xda, 0x35, 0x1c, 0x22, 0x23, 0x94, 0x58, 0x4c, 0xdb, 0xf2, 0x8c, 0x45, 0xe5, 0x70, 0xd1, 0xc6, 0xb4, 0xb9, 0x12, 0xaf, 0x26, 0x28, 0x5a}, - }, - { /* 5P */ - addYX: fp.Elt{0x33, 0xbb, 0xa5, 0x08, 0x44, 0xbc, 0x12, 0xa2, 0x02, 0xed, 0x5e, 0xc7, 0xc3, 0x48, 0x50, 0x8d, 0x44, 0xec, 0xbf, 0x5a, 0x0c, 0xeb, 0x1b, 0xdd, 0xeb, 0x06, 0xe2, 0x46, 0xf1, 0xcc, 0x45, 0x29}, - subYX: fp.Elt{0xba, 0xd6, 0x47, 0xa4, 0xc3, 0x82, 0x91, 0x7f, 0xb7, 0x29, 0x27, 0x4b, 0xd1, 0x14, 0x00, 0xd5, 0x87, 0xa0, 0x64, 0xb8, 0x1c, 0xf1, 0x3c, 0xe3, 0xf3, 0x55, 0x1b, 0xeb, 0x73, 0x7e, 0x4a, 0x15}, - dt2: fp.Elt{0x85, 0x82, 0x2a, 0x81, 0xf1, 0xdb, 0xbb, 0xbc, 0xfc, 0xd1, 0xbd, 0xd0, 0x07, 0x08, 0x0e, 0x27, 0x2d, 0xa7, 0xbd, 0x1b, 0x0b, 0x67, 0x1b, 0xb4, 0x9a, 0xb6, 0x3b, 0x6b, 0x69, 0xbe, 0xaa, 0x43}, - }, - { /* 7P */ - addYX: fp.Elt{0xbf, 0xa3, 0x4e, 0x94, 0xd0, 0x5c, 0x1a, 0x6b, 0xd2, 0xc0, 0x9d, 0xb3, 0x3a, 0x35, 0x70, 0x74, 0x49, 0x2e, 0x54, 0x28, 0x82, 0x52, 0xb2, 0x71, 0x7e, 0x92, 0x3c, 0x28, 0x69, 0xea, 0x1b, 0x46}, - subYX: fp.Elt{0xb1, 0x21, 0x32, 0xaa, 0x9a, 0x2c, 0x6f, 0xba, 0xa7, 0x23, 0xba, 0x3b, 0x53, 0x21, 0xa0, 0x6c, 0x3a, 0x2c, 0x19, 0x92, 0x4f, 0x76, 0xea, 0x9d, 0xe0, 0x17, 0x53, 0x2e, 0x5d, 0xdd, 0x6e, 0x1d}, - dt2: fp.Elt{0xa2, 0xb3, 0xb8, 0x01, 0xc8, 0x6d, 0x83, 0xf1, 0x9a, 0xa4, 0x3e, 0x05, 0x47, 0x5f, 0x03, 0xb3, 0xf3, 0xad, 0x77, 0x58, 0xba, 0x41, 0x9c, 0x52, 0xa7, 0x90, 0x0f, 0x6a, 0x1c, 0xbb, 0x9f, 0x7a}, - }, - { /* 9P */ - addYX: fp.Elt{0x2f, 0x63, 0xa8, 0xa6, 0x8a, 0x67, 0x2e, 0x9b, 0xc5, 0x46, 0xbc, 0x51, 0x6f, 0x9e, 0x50, 0xa6, 0xb5, 0xf5, 0x86, 0xc6, 0xc9, 0x33, 0xb2, 0xce, 0x59, 0x7f, 0xdd, 0x8a, 0x33, 0xed, 0xb9, 0x34}, - subYX: fp.Elt{0x64, 0x80, 0x9d, 0x03, 0x7e, 0x21, 0x6e, 0xf3, 0x9b, 0x41, 0x20, 0xf5, 0xb6, 0x81, 0xa0, 0x98, 0x44, 0xb0, 0x5e, 0xe7, 0x08, 0xc6, 0xcb, 0x96, 0x8f, 0x9c, 0xdc, 0xfa, 0x51, 0x5a, 0xc0, 0x49}, - dt2: fp.Elt{0x1b, 0xaf, 0x45, 0x90, 0xbf, 0xe8, 0xb4, 0x06, 0x2f, 0xd2, 0x19, 0xa7, 0xe8, 0x83, 0xff, 0xe2, 0x16, 0xcf, 0xd4, 0x93, 0x29, 0xfc, 0xf6, 0xaa, 0x06, 0x8b, 0x00, 0x1b, 0x02, 0x72, 0xc1, 0x73}, - }, - { /* 11P */ - addYX: fp.Elt{0xde, 0x2a, 0x80, 0x8a, 0x84, 0x00, 0xbf, 0x2f, 0x27, 0x2e, 0x30, 0x02, 0xcf, 0xfe, 0xd9, 0xe5, 0x06, 0x34, 0x70, 0x17, 0x71, 0x84, 0x3e, 0x11, 0xaf, 0x8f, 0x6d, 0x54, 0xe2, 0xaa, 0x75, 0x42}, - subYX: fp.Elt{0x48, 0x43, 0x86, 0x49, 0x02, 0x5b, 0x5f, 0x31, 0x81, 0x83, 0x08, 0x77, 0x69, 0xb3, 0xd6, 0x3e, 0x95, 0xeb, 0x8d, 0x6a, 0x55, 0x75, 0xa0, 0xa3, 0x7f, 0xc7, 0xd5, 0x29, 0x80, 0x59, 0xab, 0x18}, - dt2: fp.Elt{0xe9, 0x89, 0x60, 0xfd, 0xc5, 0x2c, 0x2b, 0xd8, 0xa4, 0xe4, 0x82, 0x32, 0xa1, 0xb4, 0x1e, 0x03, 0x22, 0x86, 0x1a, 0xb5, 0x99, 0x11, 0x31, 0x44, 0x48, 0xf9, 0x3d, 0xb5, 0x22, 0x55, 0xc6, 0x3d}, - }, - { /* 13P */ - addYX: fp.Elt{0x6d, 0x7f, 0x00, 0xa2, 0x22, 0xc2, 0x70, 0xbf, 0xdb, 0xde, 0xbc, 0xb5, 0x9a, 0xb3, 0x84, 0xbf, 0x07, 0xba, 0x07, 0xfb, 0x12, 0x0e, 0x7a, 0x53, 0x41, 0xf2, 0x46, 0xc3, 0xee, 0xd7, 0x4f, 0x23}, - subYX: fp.Elt{0x93, 0xbf, 0x7f, 0x32, 0x3b, 0x01, 0x6f, 0x50, 0x6b, 0x6f, 0x77, 0x9b, 0xc9, 0xeb, 0xfc, 0xae, 0x68, 0x59, 0xad, 0xaa, 0x32, 0xb2, 0x12, 0x9d, 0xa7, 0x24, 0x60, 0x17, 0x2d, 0x88, 0x67, 0x02}, - dt2: fp.Elt{0x78, 0xa3, 0x2e, 0x73, 0x19, 0xa1, 0x60, 0x53, 0x71, 0xd4, 0x8d, 0xdf, 0xb1, 0xe6, 0x37, 0x24, 0x33, 0xe5, 0xa7, 0x91, 0xf8, 0x37, 0xef, 0xa2, 0x63, 0x78, 0x09, 0xaa, 0xfd, 0xa6, 0x7b, 0x49}, - }, - { /* 15P */ - addYX: fp.Elt{0xa0, 0xea, 0xcf, 0x13, 0x03, 0xcc, 0xce, 0x24, 0x6d, 0x24, 0x9c, 0x18, 0x8d, 0xc2, 0x48, 0x86, 0xd0, 0xd4, 0xf2, 0xc1, 0xfa, 0xbd, 0xbd, 0x2d, 0x2b, 0xe7, 0x2d, 0xf1, 0x17, 0x29, 0xe2, 0x61}, - subYX: fp.Elt{0x0b, 0xcf, 0x8c, 0x46, 0x86, 0xcd, 0x0b, 0x04, 0xd6, 0x10, 0x99, 0x2a, 0xa4, 0x9b, 0x82, 0xd3, 0x92, 0x51, 0xb2, 0x07, 0x08, 0x30, 0x08, 0x75, 0xbf, 0x5e, 0xd0, 0x18, 0x42, 0xcd, 0xb5, 0x43}, - dt2: fp.Elt{0x16, 0xb5, 0xd0, 0x9b, 0x2f, 0x76, 0x9a, 0x5d, 0xee, 0xde, 0x3f, 0x37, 0x4e, 0xaf, 0x38, 0xeb, 0x70, 0x42, 0xd6, 0x93, 0x7d, 0x5a, 0x2e, 0x03, 0x42, 0xd8, 0xe4, 0x0a, 0x21, 0x61, 0x1d, 0x51}, - }, - { /* 17P */ - addYX: fp.Elt{0x81, 0x9d, 0x0e, 0x95, 0xef, 0x76, 0xc6, 0x92, 0x4f, 0x04, 0xd7, 0xc0, 0xcd, 0x20, 0x46, 0xa5, 0x48, 0x12, 0x8f, 0x6f, 0x64, 0x36, 0x9b, 0xaa, 0xe3, 0x55, 0xb8, 0xdd, 0x24, 0x59, 0x32, 0x6d}, - subYX: fp.Elt{0x87, 0xde, 0x20, 0x44, 0x48, 0x86, 0x13, 0x08, 0xb4, 0xed, 0x92, 0xb5, 0x16, 0xf0, 0x1c, 0x8a, 0x25, 0x2d, 0x94, 0x29, 0x27, 0x4e, 0xfa, 0x39, 0x10, 0x28, 0x48, 0xe2, 0x6f, 0xfe, 0xa7, 0x71}, - dt2: fp.Elt{0x54, 0xc8, 0xc8, 0xa5, 0xb8, 0x82, 0x71, 0x6c, 0x03, 0x2a, 0x5f, 0xfe, 0x79, 0x14, 0xfd, 0x33, 0x0c, 0x8d, 0x77, 0x83, 0x18, 0x59, 0xcf, 0x72, 0xa9, 0xea, 0x9e, 0x55, 0xb6, 0xc4, 0x46, 0x47}, - }, - { /* 19P */ - addYX: fp.Elt{0x2b, 0x9a, 0xc6, 0x6d, 0x3c, 0x7b, 0x77, 0xd3, 0x17, 0xf6, 0x89, 0x6f, 0x27, 0xb2, 0xfa, 0xde, 0xb5, 0x16, 0x3a, 0xb5, 0xf7, 0x1c, 0x65, 0x45, 0xb7, 0x9f, 0xfe, 0x34, 0xde, 0x51, 0x9a, 0x5c}, - subYX: fp.Elt{0x47, 0x11, 0x74, 0x64, 0xc8, 0x46, 0x85, 0x34, 0x49, 0xc8, 0xfc, 0x0e, 0xdd, 0xae, 0x35, 0x7d, 0x32, 0xa3, 0x72, 0x06, 0x76, 0x9a, 0x93, 0xff, 0xd6, 0xe6, 0xb5, 0x7d, 0x49, 0x63, 0x96, 0x21}, - dt2: fp.Elt{0x67, 0x0e, 0xf1, 0x79, 0xcf, 0xf1, 0x10, 0xf5, 0x5b, 0x51, 0x58, 0xe6, 0xa1, 0xda, 0xdd, 0xff, 0x77, 0x22, 0x14, 0x10, 0x17, 0xa7, 0xc3, 0x09, 0xbb, 0x23, 0x82, 0x60, 0x3c, 0x50, 0x04, 0x48}, - }, - { /* 21P */ - addYX: fp.Elt{0xc7, 0x7f, 0xa3, 0x2c, 0xd0, 0x9e, 0x24, 0xc4, 0xab, 0xac, 0x15, 0xa6, 0xe3, 0xa0, 0x59, 0xa0, 0x23, 0x0e, 0x6e, 0xc9, 0xd7, 0x6e, 0xa9, 0x88, 0x6d, 0x69, 0x50, 0x16, 0xa5, 0x98, 0x33, 0x55}, - subYX: fp.Elt{0x75, 0xd1, 0x36, 0x3a, 0xd2, 0x21, 0x68, 0x3b, 0x32, 0x9e, 0x9b, 0xe9, 0xa7, 0x0a, 0xb4, 0xbb, 0x47, 0x8a, 0x83, 0x20, 0xe4, 0x5c, 0x9e, 0x5d, 0x5e, 0x4c, 0xde, 0x58, 0x88, 0x09, 0x1e, 0x77}, - dt2: fp.Elt{0xdf, 0x1e, 0x45, 0x78, 0xd2, 0xf5, 0x12, 0x9a, 0xcb, 0x9c, 0x89, 0x85, 0x79, 0x5d, 0xda, 0x3a, 0x08, 0x95, 0xa5, 0x9f, 0x2d, 0x4a, 0x7f, 0x47, 0x11, 0xa6, 0xf5, 0x8f, 0xd6, 0xd1, 0x5e, 0x5a}, - }, - { /* 23P */ - addYX: fp.Elt{0x83, 0x0e, 0x15, 0xfe, 0x2a, 0x12, 0x95, 0x11, 0xd8, 0x35, 0x4b, 0x7e, 0x25, 0x9a, 0x20, 0xcf, 0x20, 0x1e, 0x71, 0x1e, 0x29, 0xf8, 0x87, 0x73, 0xf0, 0x92, 0xbf, 0xd8, 0x97, 0xb8, 0xac, 0x44}, - subYX: fp.Elt{0x59, 0x73, 0x52, 0x58, 0xc5, 0xe0, 0xe5, 0xba, 0x7e, 0x9d, 0xdb, 0xca, 0x19, 0x5c, 0x2e, 0x39, 0xe9, 0xab, 0x1c, 0xda, 0x1e, 0x3c, 0x65, 0x28, 0x44, 0xdc, 0xef, 0x5f, 0x13, 0x60, 0x9b, 0x01}, - dt2: fp.Elt{0x83, 0x4b, 0x13, 0x5e, 0x14, 0x68, 0x60, 0x1e, 0x16, 0x4c, 0x30, 0x24, 0x4f, 0xe6, 0xf5, 0xc4, 0xd7, 0x3e, 0x1a, 0xfc, 0xa8, 0x88, 0x6e, 0x50, 0x92, 0x2f, 0xad, 0xe6, 0xfd, 0x49, 0x0c, 0x15}, - }, - { /* 25P */ - addYX: fp.Elt{0x38, 0x11, 0x47, 0x09, 0x95, 0xf2, 0x7b, 0x8e, 0x51, 0xa6, 0x75, 0x4f, 0x39, 0xef, 0x6f, 0x5d, 0xad, 0x08, 0xa7, 0x25, 0xc4, 0x79, 0xaf, 0x10, 0x22, 0x99, 0xb9, 0x5b, 0x07, 0x5a, 0x2b, 0x6b}, - subYX: fp.Elt{0x68, 0xa8, 0xdc, 0x9c, 0x3c, 0x86, 0x49, 0xb8, 0xd0, 0x4a, 0x71, 0xb8, 0xdb, 0x44, 0x3f, 0xc8, 0x8d, 0x16, 0x36, 0x0c, 0x56, 0xe3, 0x3e, 0xfe, 0xc1, 0xfb, 0x05, 0x1e, 0x79, 0xd7, 0xa6, 0x78}, - dt2: fp.Elt{0x76, 0xb9, 0xa0, 0x47, 0x4b, 0x70, 0xbf, 0x58, 0xd5, 0x48, 0x17, 0x74, 0x55, 0xb3, 0x01, 0xa6, 0x90, 0xf5, 0x42, 0xd5, 0xb1, 0x1f, 0x2b, 0xaa, 0x00, 0x5d, 0xd5, 0x4a, 0xfc, 0x7f, 0x5c, 0x72}, - }, - { /* 27P */ - addYX: fp.Elt{0xb2, 0x99, 0xcf, 0xd1, 0x15, 0x67, 0x42, 0xe4, 0x34, 0x0d, 0xa2, 0x02, 0x11, 0xd5, 0x52, 0x73, 0x9f, 0x10, 0x12, 0x8b, 0x7b, 0x15, 0xd1, 0x23, 0xa3, 0xf3, 0xb1, 0x7c, 0x27, 0xc9, 0x4c, 0x79}, - subYX: fp.Elt{0xc0, 0x98, 0xd0, 0x1c, 0xf7, 0x2b, 0x80, 0x91, 0x66, 0x63, 0x5e, 0xed, 0xa4, 0x6c, 0x41, 0xfe, 0x4c, 0x99, 0x02, 0x49, 0x71, 0x5d, 0x58, 0xdf, 0xe7, 0xfa, 0x55, 0xf8, 0x25, 0x46, 0xd5, 0x4c}, - dt2: fp.Elt{0x53, 0x50, 0xac, 0xc2, 0x26, 0xc4, 0xf6, 0x4a, 0x58, 0x72, 0xf6, 0x32, 0xad, 0xed, 0x9a, 0xbc, 0x21, 0x10, 0x31, 0x0a, 0xf1, 0x32, 0xd0, 0x2a, 0x85, 0x8e, 0xcc, 0x6f, 0x7b, 0x35, 0x08, 0x70}, - }, - { /* 29P */ - addYX: fp.Elt{0x01, 0x3f, 0x77, 0x38, 0x27, 0x67, 0x88, 0x0b, 0xfb, 0xcc, 0xfb, 0x95, 0xfa, 0xc8, 0xcc, 0xb8, 0xb6, 0x29, 0xad, 0xb9, 0xa3, 0xd5, 0x2d, 0x8d, 0x6a, 0x0f, 0xad, 0x51, 0x98, 0x7e, 0xef, 0x06}, - subYX: fp.Elt{0x34, 0x4a, 0x58, 0x82, 0xbb, 0x9f, 0x1b, 0xd0, 0x2b, 0x79, 0xb4, 0xd2, 0x63, 0x64, 0xab, 0x47, 0x02, 0x62, 0x53, 0x48, 0x9c, 0x63, 0x31, 0xb6, 0x28, 0xd4, 0xd6, 0x69, 0x36, 0x2a, 0xa9, 0x13}, - dt2: fp.Elt{0xe5, 0x7d, 0x57, 0xc0, 0x1c, 0x77, 0x93, 0xca, 0x5c, 0xdc, 0x35, 0x50, 0x1e, 0xe4, 0x40, 0x75, 0x71, 0xe0, 0x02, 0xd8, 0x01, 0x0f, 0x68, 0x24, 0x6a, 0xf8, 0x2a, 0x8a, 0xdf, 0x6d, 0x29, 0x3c}, - }, - { /* 31P */ - addYX: fp.Elt{0x13, 0xa7, 0x14, 0xd9, 0xf9, 0x15, 0xad, 0xae, 0x12, 0xf9, 0x8f, 0x8c, 0xf9, 0x7b, 0x2f, 0xa9, 0x30, 0xd7, 0x53, 0x9f, 0x17, 0x23, 0xf8, 0xaf, 0xba, 0x77, 0x0c, 0x49, 0x93, 0xd3, 0x99, 0x7a}, - subYX: fp.Elt{0x41, 0x25, 0x1f, 0xbb, 0x2e, 0x4d, 0xeb, 0xfc, 0x1f, 0xb9, 0xad, 0x40, 0xc7, 0x10, 0x95, 0xb8, 0x05, 0xad, 0xa1, 0xd0, 0x7d, 0xa3, 0x71, 0xfc, 0x7b, 0x71, 0x47, 0x07, 0x70, 0x2c, 0x89, 0x0a}, - dt2: fp.Elt{0xe8, 0xa3, 0xbd, 0x36, 0x24, 0xed, 0x52, 0x8f, 0x94, 0x07, 0xe8, 0x57, 0x41, 0xc8, 0xa8, 0x77, 0xe0, 0x9c, 0x2f, 0x26, 0x63, 0x65, 0xa9, 0xa5, 0xd2, 0xf7, 0x02, 0x83, 0xd2, 0x62, 0x67, 0x28}, - }, - { /* 33P */ - addYX: fp.Elt{0x25, 0x5b, 0xe3, 0x3c, 0x09, 0x36, 0x78, 0x4e, 0x97, 0xaa, 0x6b, 0xb2, 0x1d, 0x18, 0xe1, 0x82, 0x3f, 0xb8, 0xc7, 0xcb, 0xd3, 0x92, 0xc1, 0x0c, 0x3a, 0x9d, 0x9d, 0x6a, 0x04, 0xda, 0xf1, 0x32}, - subYX: fp.Elt{0xbd, 0xf5, 0x2e, 0xce, 0x2b, 0x8e, 0x55, 0x7c, 0x63, 0xbc, 0x47, 0x67, 0xb4, 0x6c, 0x98, 0xe4, 0xb8, 0x89, 0xbb, 0x3b, 0x9f, 0x17, 0x4a, 0x15, 0x7a, 0x76, 0xf1, 0xd6, 0xa3, 0xf2, 0x86, 0x76}, - dt2: fp.Elt{0x6a, 0x7c, 0x59, 0x6d, 0xa6, 0x12, 0x8d, 0xaa, 0x2b, 0x85, 0xd3, 0x04, 0x03, 0x93, 0x11, 0x8f, 0x22, 0xb0, 0x09, 0xc2, 0x73, 0xdc, 0x91, 0x3f, 0xa6, 0x28, 0xad, 0xa9, 0xf8, 0x05, 0x13, 0x56}, - }, - { /* 35P */ - addYX: fp.Elt{0xd1, 0xae, 0x92, 0xec, 0x8d, 0x97, 0x0c, 0x10, 0xe5, 0x73, 0x6d, 0x4d, 0x43, 0xd5, 0x43, 0xca, 0x48, 0xba, 0x47, 0xd8, 0x22, 0x1b, 0x13, 0x83, 0x2c, 0x4d, 0x5d, 0xe3, 0x53, 0xec, 0xaa}, - subYX: fp.Elt{0xd5, 0xc0, 0xb0, 0xe7, 0x28, 0xcc, 0x22, 0x67, 0x53, 0x5c, 0x07, 0xdb, 0xbb, 0xe9, 0x9d, 0x70, 0x61, 0x0a, 0x01, 0xd7, 0xa7, 0x8d, 0xf6, 0xca, 0x6c, 0xcc, 0x57, 0x2c, 0xef, 0x1a, 0x0a, 0x03}, - dt2: fp.Elt{0xaa, 0xd2, 0x3a, 0x00, 0x73, 0xf7, 0xb1, 0x7b, 0x08, 0x66, 0x21, 0x2b, 0x80, 0x29, 0x3f, 0x0b, 0x3e, 0xd2, 0x0e, 0x52, 0x86, 0xdc, 0x21, 0x78, 0x80, 0x54, 0x06, 0x24, 0x1c, 0x9c, 0xbe, 0x20}, - }, - { /* 37P */ - addYX: fp.Elt{0xa6, 0x73, 0x96, 0x24, 0xd8, 0x87, 0x53, 0xe1, 0x93, 0xe4, 0x46, 0xf5, 0x2d, 0xbc, 0x43, 0x59, 0xb5, 0x63, 0x6f, 0xc3, 0x81, 0x9a, 0x7f, 0x1c, 0xde, 0xc1, 0x0a, 0x1f, 0x36, 0xb3, 0x0a, 0x75}, - subYX: fp.Elt{0x60, 0x5e, 0x02, 0xe2, 0x4a, 0xe4, 0xe0, 0x20, 0x38, 0xb9, 0xdc, 0xcb, 0x2f, 0x3b, 0x3b, 0xb0, 0x1c, 0x0d, 0x5a, 0xf9, 0x9c, 0x63, 0x5d, 0x10, 0x11, 0xe3, 0x67, 0x50, 0x54, 0x4c, 0x76, 0x69}, - dt2: fp.Elt{0x37, 0x10, 0xf8, 0xa2, 0x83, 0x32, 0x8a, 0x1e, 0xf1, 0xcb, 0x7f, 0xbd, 0x23, 0xda, 0x2e, 0x6f, 0x63, 0x25, 0x2e, 0xac, 0x5b, 0xd1, 0x2f, 0xb7, 0x40, 0x50, 0x07, 0xb7, 0x3f, 0x6b, 0xf9, 0x54}, - }, - { /* 39P */ - addYX: fp.Elt{0x79, 0x92, 0x66, 0x29, 0x04, 0xf2, 0xad, 0x0f, 0x4a, 0x72, 0x7d, 0x7d, 0x04, 0xa2, 0xdd, 0x3a, 0xf1, 0x60, 0x57, 0x8c, 0x82, 0x94, 0x3d, 0x6f, 0x9e, 0x53, 0xb7, 0x2b, 0xc5, 0xe9, 0x7f, 0x3d}, - subYX: fp.Elt{0xcd, 0x1e, 0xb1, 0x16, 0xc6, 0xaf, 0x7d, 0x17, 0x79, 0x64, 0x57, 0xfa, 0x9c, 0x4b, 0x76, 0x89, 0x85, 0xe7, 0xec, 0xe6, 0x10, 0xa1, 0xa8, 0xb7, 0xf0, 0xdb, 0x85, 0xbe, 0x9f, 0x83, 0xe6, 0x78}, - dt2: fp.Elt{0x6b, 0x85, 0xb8, 0x37, 0xf7, 0x2d, 0x33, 0x70, 0x8a, 0x17, 0x1a, 0x04, 0x43, 0x5d, 0xd0, 0x75, 0x22, 0x9e, 0xe5, 0xa0, 0x4a, 0xf7, 0x0f, 0x32, 0x42, 0x82, 0x08, 0x50, 0xf3, 0x68, 0xf2, 0x70}, - }, - { /* 41P */ - addYX: fp.Elt{0x47, 0x5f, 0x80, 0xb1, 0x83, 0x45, 0x86, 0x66, 0x19, 0x7c, 0xdd, 0x60, 0xd1, 0xc5, 0x35, 0xf5, 0x06, 0xb0, 0x4c, 0x1e, 0xb7, 0x4e, 0x87, 0xe9, 0xd9, 0x89, 0xd8, 0xfa, 0x5c, 0x34, 0x0d, 0x7c}, - subYX: fp.Elt{0x55, 0xf3, 0xdc, 0x70, 0x20, 0x11, 0x24, 0x23, 0x17, 0xe1, 0xfc, 0xe7, 0x7e, 0xc9, 0x0c, 0x38, 0x98, 0xb6, 0x52, 0x35, 0xed, 0xde, 0x1d, 0xb3, 0xb9, 0xc4, 0xb8, 0x39, 0xc0, 0x56, 0x4e, 0x40}, - dt2: fp.Elt{0x8a, 0x33, 0x78, 0x8c, 0x4b, 0x1f, 0x1f, 0x59, 0xe1, 0xb5, 0xe0, 0x67, 0xb1, 0x6a, 0x36, 0xa0, 0x44, 0x3d, 0x5f, 0xb4, 0x52, 0x41, 0xbc, 0x5c, 0x77, 0xc7, 0xae, 0x2a, 0x76, 0x54, 0xd7, 0x20}, - }, - { /* 43P */ - addYX: fp.Elt{0x58, 0xb7, 0x3b, 0xc7, 0x6f, 0xc3, 0x8f, 0x5e, 0x9a, 0xbb, 0x3c, 0x36, 0xa5, 0x43, 0xe5, 0xac, 0x22, 0xc9, 0x3b, 0x90, 0x7d, 0x4a, 0x93, 0xa9, 0x62, 0xec, 0xce, 0xf3, 0x46, 0x1e, 0x8f, 0x2b}, - subYX: fp.Elt{0x43, 0xf5, 0xb9, 0x35, 0xb1, 0xfe, 0x74, 0x9d, 0x6c, 0x95, 0x8c, 0xde, 0xf1, 0x7d, 0xb3, 0x84, 0xa9, 0x8b, 0x13, 0x57, 0x07, 0x2b, 0x32, 0xe9, 0xe1, 0x4c, 0x0b, 0x79, 0xa8, 0xad, 0xb8, 0x38}, - dt2: fp.Elt{0x5d, 0xf9, 0x51, 0xdf, 0x9c, 0x4a, 0xc0, 0xb5, 0xac, 0xde, 0x1f, 0xcb, 0xae, 0x52, 0x39, 0x2b, 0xda, 0x66, 0x8b, 0x32, 0x8b, 0x6d, 0x10, 0x1d, 0x53, 0x19, 0xba, 0xce, 0x32, 0xeb, 0x9a, 0x04}, - }, - { /* 45P */ - addYX: fp.Elt{0x31, 0x79, 0xfc, 0x75, 0x0b, 0x7d, 0x50, 0xaa, 0xd3, 0x25, 0x67, 0x7a, 0x4b, 0x92, 0xef, 0x0f, 0x30, 0x39, 0x6b, 0x39, 0x2b, 0x54, 0x82, 0x1d, 0xfc, 0x74, 0xf6, 0x30, 0x75, 0xe1, 0x5e, 0x79}, - subYX: fp.Elt{0x7e, 0xfe, 0xdc, 0x63, 0x3c, 0x7d, 0x76, 0xd7, 0x40, 0x6e, 0x85, 0x97, 0x48, 0x59, 0x9c, 0x20, 0x13, 0x7c, 0x4f, 0xe1, 0x61, 0x68, 0x67, 0xb6, 0xfc, 0x25, 0xd6, 0xc8, 0xe0, 0x65, 0xc6, 0x51}, - dt2: fp.Elt{0x81, 0xbd, 0xec, 0x52, 0x0a, 0x5b, 0x4a, 0x25, 0xe7, 0xaf, 0x34, 0xe0, 0x6e, 0x1f, 0x41, 0x5d, 0x31, 0x4a, 0xee, 0xca, 0x0d, 0x4d, 0xa2, 0xe6, 0x77, 0x44, 0xc5, 0x9d, 0xf4, 0x9b, 0xd1, 0x6c}, - }, - { /* 47P */ - addYX: fp.Elt{0x86, 0xc3, 0xaf, 0x65, 0x21, 0x61, 0xfe, 0x1f, 0x10, 0x1b, 0xd5, 0xb8, 0x88, 0x2a, 0x2a, 0x08, 0xaa, 0x0b, 0x99, 0x20, 0x7e, 0x62, 0xf6, 0x76, 0xe7, 0x43, 0x9e, 0x42, 0xa7, 0xb3, 0x01, 0x5e}, - subYX: fp.Elt{0xa3, 0x9c, 0x17, 0x52, 0x90, 0x61, 0x87, 0x7e, 0x85, 0x9f, 0x2c, 0x0b, 0x06, 0x0a, 0x1d, 0x57, 0x1e, 0x71, 0x99, 0x84, 0xa8, 0xba, 0xa2, 0x80, 0x38, 0xe6, 0xb2, 0x40, 0xdb, 0xf3, 0x20, 0x75}, - dt2: fp.Elt{0xa1, 0x57, 0x93, 0xd3, 0xe3, 0x0b, 0xb5, 0x3d, 0xa5, 0x94, 0x9e, 0x59, 0xdd, 0x6c, 0x7b, 0x96, 0x6e, 0x1e, 0x31, 0xdf, 0x64, 0x9a, 0x30, 0x1a, 0x86, 0xc9, 0xf3, 0xce, 0x9c, 0x2c, 0x09, 0x71}, - }, - { /* 49P */ - addYX: fp.Elt{0xcf, 0x1d, 0x05, 0x74, 0xac, 0xd8, 0x6b, 0x85, 0x1e, 0xaa, 0xb7, 0x55, 0x08, 0xa4, 0xf6, 0x03, 0xeb, 0x3c, 0x74, 0xc9, 0xcb, 0xe7, 0x4a, 0x3a, 0xde, 0xab, 0x37, 0x71, 0xbb, 0xa5, 0x73, 0x41}, - subYX: fp.Elt{0x8c, 0x91, 0x64, 0x03, 0x3f, 0x52, 0xd8, 0x53, 0x1c, 0x6b, 0xab, 0x3f, 0xf4, 0x04, 0xb4, 0xa2, 0xa4, 0xe5, 0x81, 0x66, 0x9e, 0x4a, 0x0b, 0x08, 0xa7, 0x7b, 0x25, 0xd0, 0x03, 0x5b, 0xa1, 0x0e}, - dt2: fp.Elt{0x8a, 0x21, 0xf9, 0xf0, 0x31, 0x6e, 0xc5, 0x17, 0x08, 0x47, 0xfc, 0x1a, 0x2b, 0x6e, 0x69, 0x5a, 0x76, 0xf1, 0xb2, 0xf4, 0x68, 0x16, 0x93, 0xf7, 0x67, 0x3a, 0x4e, 0x4a, 0x61, 0x65, 0xc5, 0x5f}, - }, - { /* 51P */ - addYX: fp.Elt{0x8e, 0x98, 0x90, 0x77, 0xe6, 0xe1, 0x92, 0x48, 0x22, 0xd7, 0x5c, 0x1c, 0x0f, 0x95, 0xd5, 0x01, 0xed, 0x3e, 0x92, 0xe5, 0x9a, 0x81, 0xb0, 0xe3, 0x1b, 0x65, 0x46, 0x9d, 0x40, 0xc7, 0x14, 0x32}, - subYX: fp.Elt{0xe5, 0x7a, 0x6d, 0xc4, 0x0d, 0x57, 0x6e, 0x13, 0x8f, 0xdc, 0xf8, 0x54, 0xcc, 0xaa, 0xd0, 0x0f, 0x86, 0xad, 0x0d, 0x31, 0x03, 0x9f, 0x54, 0x59, 0xa1, 0x4a, 0x45, 0x4c, 0x41, 0x1c, 0x71, 0x62}, - dt2: fp.Elt{0x70, 0x17, 0x65, 0x06, 0x74, 0x82, 0x29, 0x13, 0x36, 0x94, 0x27, 0x8a, 0x66, 0xa0, 0xa4, 0x3b, 0x3c, 0x22, 0x5d, 0x18, 0xec, 0xb8, 0xb6, 0xd9, 0x3c, 0x83, 0xcb, 0x3e, 0x07, 0x94, 0xea, 0x5b}, - }, - { /* 53P */ - addYX: fp.Elt{0xf8, 0xd2, 0x43, 0xf3, 0x63, 0xce, 0x70, 0xb4, 0xf1, 0xe8, 0x43, 0x05, 0x8f, 0xba, 0x67, 0x00, 0x6f, 0x7b, 0x11, 0xa2, 0xa1, 0x51, 0xda, 0x35, 0x2f, 0xbd, 0xf1, 0x44, 0x59, 0x78, 0xd0, 0x4a}, - subYX: fp.Elt{0xe4, 0x9b, 0xc8, 0x12, 0x09, 0xbf, 0x1d, 0x64, 0x9c, 0x57, 0x6e, 0x7d, 0x31, 0x8b, 0xf3, 0xac, 0x65, 0xb0, 0x97, 0xf6, 0x02, 0x9e, 0xfe, 0xab, 0xec, 0x1e, 0xf6, 0x48, 0xc1, 0xd5, 0xac, 0x3a}, - dt2: fp.Elt{0x01, 0x83, 0x31, 0xc3, 0x34, 0x3b, 0x8e, 0x85, 0x26, 0x68, 0x31, 0x07, 0x47, 0xc0, 0x99, 0xdc, 0x8c, 0xa8, 0x9d, 0xd3, 0x2e, 0x5b, 0x08, 0x34, 0x3d, 0x85, 0x02, 0xd9, 0xb1, 0x0c, 0xff, 0x3a}, - }, - { /* 55P */ - addYX: fp.Elt{0x05, 0x35, 0xc5, 0xf4, 0x0b, 0x43, 0x26, 0x92, 0x83, 0x22, 0x1f, 0x26, 0x13, 0x9c, 0xe4, 0x68, 0xc6, 0x27, 0xd3, 0x8f, 0x78, 0x33, 0xef, 0x09, 0x7f, 0x9e, 0xd9, 0x2b, 0x73, 0x9f, 0xcf, 0x2c}, - subYX: fp.Elt{0x5e, 0x40, 0x20, 0x3a, 0xeb, 0xc7, 0xc5, 0x87, 0xc9, 0x56, 0xad, 0xed, 0xef, 0x11, 0xe3, 0x8e, 0xf9, 0xd5, 0x29, 0xad, 0x48, 0x2e, 0x25, 0x29, 0x1d, 0x25, 0xcd, 0xf4, 0x86, 0x7e, 0x0e, 0x11}, - dt2: fp.Elt{0xe4, 0xf5, 0x03, 0xd6, 0x9e, 0xd8, 0xc0, 0x57, 0x0c, 0x20, 0xb0, 0xf0, 0x28, 0x86, 0x88, 0x12, 0xb7, 0x3b, 0x2e, 0xa0, 0x09, 0x27, 0x17, 0x53, 0x37, 0x3a, 0x69, 0xb9, 0xe0, 0x57, 0xc5, 0x05}, - }, - { /* 57P */ - addYX: fp.Elt{0xb0, 0x0e, 0xc2, 0x89, 0xb0, 0xbb, 0x76, 0xf7, 0x5c, 0xd8, 0x0f, 0xfa, 0xf6, 0x5b, 0xf8, 0x61, 0xfb, 0x21, 0x44, 0x63, 0x4e, 0x3f, 0xb9, 0xb6, 0x05, 0x12, 0x86, 0x41, 0x08, 0xef, 0x9f, 0x28}, - subYX: fp.Elt{0x6f, 0x7e, 0xc9, 0x1f, 0x31, 0xce, 0xf9, 0xd8, 0xae, 0xfd, 0xf9, 0x11, 0x30, 0x26, 0x3f, 0x7a, 0xdd, 0x25, 0xed, 0x8b, 0xa0, 0x7e, 0x5b, 0xe1, 0x5a, 0x87, 0xe9, 0x8f, 0x17, 0x4c, 0x15, 0x6e}, - dt2: fp.Elt{0xbf, 0x9a, 0xd6, 0xfe, 0x36, 0x63, 0x61, 0xcf, 0x4f, 0xc9, 0x35, 0x83, 0xe7, 0xe4, 0x16, 0x9b, 0xe7, 0x7f, 0x3a, 0x75, 0x65, 0x97, 0x78, 0x13, 0x19, 0xa3, 0x5c, 0xa9, 0x42, 0xf6, 0xfb, 0x6a}, - }, - { /* 59P */ - addYX: fp.Elt{0xcc, 0xa8, 0x13, 0xf9, 0x70, 0x50, 0xe5, 0x5d, 0x61, 0xf5, 0x0c, 0x2b, 0x7b, 0x16, 0x1d, 0x7d, 0x89, 0xd4, 0xea, 0x90, 0xb6, 0x56, 0x29, 0xda, 0xd9, 0x1e, 0x80, 0xdb, 0xce, 0x93, 0xc0, 0x12}, - subYX: fp.Elt{0xc1, 0xd2, 0xf5, 0x62, 0x0c, 0xde, 0xa8, 0x7d, 0x9a, 0x7b, 0x0e, 0xb0, 0xa4, 0x3d, 0xfc, 0x98, 0xe0, 0x70, 0xad, 0x0d, 0xda, 0x6a, 0xeb, 0x7d, 0xc4, 0x38, 0x50, 0xb9, 0x51, 0xb8, 0xb4, 0x0d}, - dt2: fp.Elt{0x0f, 0x19, 0xb8, 0x08, 0x93, 0x7f, 0x14, 0xfc, 0x10, 0xe3, 0x1a, 0xa1, 0xa0, 0x9d, 0x96, 0x06, 0xfd, 0xd7, 0xc7, 0xda, 0x72, 0x55, 0xe7, 0xce, 0xe6, 0x5c, 0x63, 0xc6, 0x99, 0x87, 0xaa, 0x33}, - }, - { /* 61P */ - addYX: fp.Elt{0xb1, 0x6c, 0x15, 0xfc, 0x88, 0xf5, 0x48, 0x83, 0x27, 0x6d, 0x0a, 0x1a, 0x9b, 0xba, 0xa2, 0x6d, 0xb6, 0x5a, 0xca, 0x87, 0x5c, 0x2d, 0x26, 0xe2, 0xa6, 0x89, 0xd5, 0xc8, 0xc1, 0xd0, 0x2c, 0x21}, - subYX: fp.Elt{0xf2, 0x5c, 0x08, 0xbd, 0x1e, 0xf5, 0x0f, 0xaf, 0x1f, 0x3f, 0xd3, 0x67, 0x89, 0x1a, 0xf5, 0x78, 0x3c, 0x03, 0x60, 0x50, 0xe1, 0xbf, 0xc2, 0x6e, 0x86, 0x1a, 0xe2, 0xe8, 0x29, 0x6f, 0x3c, 0x23}, - dt2: fp.Elt{0x81, 0xc7, 0x18, 0x7f, 0x10, 0xd5, 0xf4, 0xd2, 0x28, 0x9d, 0x7e, 0x52, 0xf2, 0xcd, 0x2e, 0x12, 0x41, 0x33, 0x3d, 0x3d, 0x2a, 0x86, 0x0a, 0xa7, 0xe3, 0x4c, 0x91, 0x11, 0x89, 0x77, 0xb7, 0x1d}, - }, - { /* 63P */ - addYX: fp.Elt{0xb6, 0x1a, 0x70, 0xdd, 0x69, 0x47, 0x39, 0xb3, 0xa5, 0x8d, 0xcf, 0x19, 0xd4, 0xde, 0xb8, 0xe2, 0x52, 0xc8, 0x2a, 0xfd, 0x61, 0x41, 0xdf, 0x15, 0xbe, 0x24, 0x7d, 0x01, 0x8a, 0xca, 0xe2, 0x7a}, - subYX: fp.Elt{0x6f, 0xc2, 0x6b, 0x7c, 0x39, 0x52, 0xf3, 0xdd, 0x13, 0x01, 0xd5, 0x53, 0xcc, 0xe2, 0x97, 0x7a, 0x30, 0xa3, 0x79, 0xbf, 0x3a, 0xf4, 0x74, 0x7c, 0xfc, 0xad, 0xe2, 0x26, 0xad, 0x97, 0xad, 0x31}, - dt2: fp.Elt{0x62, 0xb9, 0x20, 0x09, 0xed, 0x17, 0xe8, 0xb7, 0x9d, 0xda, 0x19, 0x3f, 0xcc, 0x18, 0x85, 0x1e, 0x64, 0x0a, 0x56, 0x25, 0x4f, 0xc1, 0x91, 0xe4, 0x83, 0x2c, 0x62, 0xa6, 0x53, 0xfc, 0xd1, 0x1e}, - }, -} diff --git a/vendor/github.com/cloudflare/circl/sign/ed448/ed448.go b/vendor/github.com/cloudflare/circl/sign/ed448/ed448.go deleted file mode 100644 index 324bd8f3..00000000 --- a/vendor/github.com/cloudflare/circl/sign/ed448/ed448.go +++ /dev/null @@ -1,411 +0,0 @@ -// Package ed448 implements Ed448 signature scheme as described in RFC-8032. -// -// This package implements two signature variants. -// -// | Scheme Name | Sign Function | Verification | Context | -// |-------------|-------------------|---------------|-------------------| -// | Ed448 | Sign | Verify | Yes, can be empty | -// | Ed448Ph | SignPh | VerifyPh | Yes, can be empty | -// | All above | (PrivateKey).Sign | VerifyAny | As above | -// -// Specific functions for sign and verify are defined. A generic signing -// function for all schemes is available through the crypto.Signer interface, -// which is implemented by the PrivateKey type. A correspond all-in-one -// verification method is provided by the VerifyAny function. -// -// Both schemes require a context string for domain separation. This parameter -// is passed using a SignerOptions struct defined in this package. -// -// References: -// -// - RFC8032: https://rfc-editor.org/rfc/rfc8032.txt -// - EdDSA for more curves: https://eprint.iacr.org/2015/677 -// - High-speed high-security signatures: https://doi.org/10.1007/s13389-012-0027-1 -package ed448 - -import ( - "bytes" - "crypto" - cryptoRand "crypto/rand" - "crypto/subtle" - "errors" - "fmt" - "io" - "strconv" - - "github.com/cloudflare/circl/ecc/goldilocks" - "github.com/cloudflare/circl/internal/sha3" - "github.com/cloudflare/circl/sign" -) - -const ( - // ContextMaxSize is the maximum length (in bytes) allowed for context. - ContextMaxSize = 255 - // PublicKeySize is the length in bytes of Ed448 public keys. - PublicKeySize = 57 - // PrivateKeySize is the length in bytes of Ed448 private keys. - PrivateKeySize = 114 - // SignatureSize is the length in bytes of signatures. - SignatureSize = 114 - // SeedSize is the size, in bytes, of private key seeds. These are the private key representations used by RFC 8032. - SeedSize = 57 -) - -const ( - paramB = 456 / 8 // Size of keys in bytes. - hashSize = 2 * paramB // Size of the hash function's output. -) - -// SignerOptions implements crypto.SignerOpts and augments with parameters -// that are specific to the Ed448 signature schemes. -type SignerOptions struct { - // Hash must be crypto.Hash(0) for both Ed448 and Ed448Ph. - crypto.Hash - - // Context is an optional domain separation string for signing. - // Its length must be less or equal than 255 bytes. - Context string - - // Scheme is an identifier for choosing a signature scheme. - Scheme SchemeID -} - -// SchemeID is an identifier for each signature scheme. -type SchemeID uint - -const ( - ED448 SchemeID = iota - ED448Ph -) - -// PublicKey is the type of Ed448 public keys. -type PublicKey []byte - -// Equal reports whether pub and x have the same value. -func (pub PublicKey) Equal(x crypto.PublicKey) bool { - xx, ok := x.(PublicKey) - return ok && bytes.Equal(pub, xx) -} - -// PrivateKey is the type of Ed448 private keys. It implements crypto.Signer. -type PrivateKey []byte - -// Equal reports whether priv and x have the same value. -func (priv PrivateKey) Equal(x crypto.PrivateKey) bool { - xx, ok := x.(PrivateKey) - return ok && subtle.ConstantTimeCompare(priv, xx) == 1 -} - -// Public returns the PublicKey corresponding to priv. -func (priv PrivateKey) Public() crypto.PublicKey { - publicKey := make([]byte, PublicKeySize) - copy(publicKey, priv[SeedSize:]) - return PublicKey(publicKey) -} - -// Seed returns the private key seed corresponding to priv. It is provided for -// interoperability with RFC 8032. RFC 8032's private keys correspond to seeds -// in this package. -func (priv PrivateKey) Seed() []byte { - seed := make([]byte, SeedSize) - copy(seed, priv[:SeedSize]) - return seed -} - -func (priv PrivateKey) Scheme() sign.Scheme { return sch } - -func (pub PublicKey) Scheme() sign.Scheme { return sch } - -func (priv PrivateKey) MarshalBinary() (data []byte, err error) { - privateKey := make(PrivateKey, PrivateKeySize) - copy(privateKey, priv) - return privateKey, nil -} - -func (pub PublicKey) MarshalBinary() (data []byte, err error) { - publicKey := make(PublicKey, PublicKeySize) - copy(publicKey, pub) - return publicKey, nil -} - -// Sign creates a signature of a message given a key pair. -// This function supports all the two signature variants defined in RFC-8032, -// namely Ed448 (or pure EdDSA) and Ed448Ph. -// The opts.HashFunc() must return zero to the specify Ed448 variant. This can -// be achieved by passing crypto.Hash(0) as the value for opts. -// Use an Options struct to pass a bool indicating that the ed448Ph variant -// should be used. -// The struct can also be optionally used to pass a context string for signing. -func (priv PrivateKey) Sign( - rand io.Reader, - message []byte, - opts crypto.SignerOpts, -) (signature []byte, err error) { - var ctx string - var scheme SchemeID - - if o, ok := opts.(SignerOptions); ok { - ctx = o.Context - scheme = o.Scheme - } - - switch true { - case scheme == ED448 && opts.HashFunc() == crypto.Hash(0): - return Sign(priv, message, ctx), nil - case scheme == ED448Ph && opts.HashFunc() == crypto.Hash(0): - return SignPh(priv, message, ctx), nil - default: - return nil, errors.New("ed448: bad hash algorithm") - } -} - -// GenerateKey generates a public/private key pair using entropy from rand. -// If rand is nil, crypto/rand.Reader will be used. -func GenerateKey(rand io.Reader) (PublicKey, PrivateKey, error) { - if rand == nil { - rand = cryptoRand.Reader - } - - seed := make(PrivateKey, SeedSize) - if _, err := io.ReadFull(rand, seed); err != nil { - return nil, nil, err - } - - privateKey := NewKeyFromSeed(seed) - publicKey := make([]byte, PublicKeySize) - copy(publicKey, privateKey[SeedSize:]) - - return publicKey, privateKey, nil -} - -// NewKeyFromSeed calculates a private key from a seed. It will panic if -// len(seed) is not SeedSize. This function is provided for interoperability -// with RFC 8032. RFC 8032's private keys correspond to seeds in this -// package. -func NewKeyFromSeed(seed []byte) PrivateKey { - privateKey := make([]byte, PrivateKeySize) - newKeyFromSeed(privateKey, seed) - return privateKey -} - -func newKeyFromSeed(privateKey, seed []byte) { - if l := len(seed); l != SeedSize { - panic("ed448: bad seed length: " + strconv.Itoa(l)) - } - - var h [hashSize]byte - H := sha3.NewShake256() - _, _ = H.Write(seed) - _, _ = H.Read(h[:]) - s := &goldilocks.Scalar{} - deriveSecretScalar(s, h[:paramB]) - - copy(privateKey[:SeedSize], seed) - _ = goldilocks.Curve{}.ScalarBaseMult(s).ToBytes(privateKey[SeedSize:]) -} - -func signAll(signature []byte, privateKey PrivateKey, message, ctx []byte, preHash bool) { - if len(ctx) > ContextMaxSize { - panic(fmt.Errorf("ed448: bad context length: " + strconv.Itoa(len(ctx)))) - } - - H := sha3.NewShake256() - var PHM []byte - - if preHash { - var h [64]byte - _, _ = H.Write(message) - _, _ = H.Read(h[:]) - PHM = h[:] - H.Reset() - } else { - PHM = message - } - - // 1. Hash the 57-byte private key using SHAKE256(x, 114). - var h [hashSize]byte - _, _ = H.Write(privateKey[:SeedSize]) - _, _ = H.Read(h[:]) - s := &goldilocks.Scalar{} - deriveSecretScalar(s, h[:paramB]) - prefix := h[paramB:] - - // 2. Compute SHAKE256(dom4(F, C) || prefix || PH(M), 114). - var rPM [hashSize]byte - H.Reset() - - writeDom(&H, ctx, preHash) - - _, _ = H.Write(prefix) - _, _ = H.Write(PHM) - _, _ = H.Read(rPM[:]) - - // 3. Compute the point [r]B. - r := &goldilocks.Scalar{} - r.FromBytes(rPM[:]) - R := (&[paramB]byte{})[:] - if err := (goldilocks.Curve{}.ScalarBaseMult(r).ToBytes(R)); err != nil { - panic(err) - } - // 4. Compute SHAKE256(dom4(F, C) || R || A || PH(M), 114) - var hRAM [hashSize]byte - H.Reset() - - writeDom(&H, ctx, preHash) - - _, _ = H.Write(R) - _, _ = H.Write(privateKey[SeedSize:]) - _, _ = H.Write(PHM) - _, _ = H.Read(hRAM[:]) - - // 5. Compute S = (r + k * s) mod order. - k := &goldilocks.Scalar{} - k.FromBytes(hRAM[:]) - S := &goldilocks.Scalar{} - S.Mul(k, s) - S.Add(S, r) - - // 6. The signature is the concatenation of R and S. - copy(signature[:paramB], R[:]) - copy(signature[paramB:], S[:]) -} - -// Sign signs the message with privateKey and returns a signature. -// This function supports the signature variant defined in RFC-8032: Ed448, -// also known as the pure version of EdDSA. -// It will panic if len(privateKey) is not PrivateKeySize. -func Sign(priv PrivateKey, message []byte, ctx string) []byte { - signature := make([]byte, SignatureSize) - signAll(signature, priv, message, []byte(ctx), false) - return signature -} - -// SignPh creates a signature of a message given a keypair. -// This function supports the signature variant defined in RFC-8032: Ed448ph, -// meaning it internally hashes the message using SHAKE-256. -// Context could be passed to this function, which length should be no more than -// 255. It can be empty. -func SignPh(priv PrivateKey, message []byte, ctx string) []byte { - signature := make([]byte, SignatureSize) - signAll(signature, priv, message, []byte(ctx), true) - return signature -} - -func verify(public PublicKey, message, signature, ctx []byte, preHash bool) bool { - if len(public) != PublicKeySize || - len(signature) != SignatureSize || - len(ctx) > ContextMaxSize || - !isLessThanOrder(signature[paramB:]) { - return false - } - - P, err := goldilocks.FromBytes(public) - if err != nil { - return false - } - - H := sha3.NewShake256() - var PHM []byte - - if preHash { - var h [64]byte - _, _ = H.Write(message) - _, _ = H.Read(h[:]) - PHM = h[:] - H.Reset() - } else { - PHM = message - } - - var hRAM [hashSize]byte - R := signature[:paramB] - - writeDom(&H, ctx, preHash) - - _, _ = H.Write(R) - _, _ = H.Write(public) - _, _ = H.Write(PHM) - _, _ = H.Read(hRAM[:]) - - k := &goldilocks.Scalar{} - k.FromBytes(hRAM[:]) - S := &goldilocks.Scalar{} - S.FromBytes(signature[paramB:]) - - encR := (&[paramB]byte{})[:] - P.Neg() - _ = goldilocks.Curve{}.CombinedMult(S, k, P).ToBytes(encR) - return bytes.Equal(R, encR) -} - -// VerifyAny returns true if the signature is valid. Failure cases are invalid -// signature, or when the public key cannot be decoded. -// This function supports all the two signature variants defined in RFC-8032, -// namely Ed448 (or pure EdDSA) and Ed448Ph. -// The opts.HashFunc() must return zero, this can be achieved by passing -// crypto.Hash(0) as the value for opts. -// Use a SignerOptions struct to pass a context string for signing. -func VerifyAny(public PublicKey, message, signature []byte, opts crypto.SignerOpts) bool { - var ctx string - var scheme SchemeID - if o, ok := opts.(SignerOptions); ok { - ctx = o.Context - scheme = o.Scheme - } - - switch true { - case scheme == ED448 && opts.HashFunc() == crypto.Hash(0): - return Verify(public, message, signature, ctx) - case scheme == ED448Ph && opts.HashFunc() == crypto.Hash(0): - return VerifyPh(public, message, signature, ctx) - default: - return false - } -} - -// Verify returns true if the signature is valid. Failure cases are invalid -// signature, or when the public key cannot be decoded. -// This function supports the signature variant defined in RFC-8032: Ed448, -// also known as the pure version of EdDSA. -func Verify(public PublicKey, message, signature []byte, ctx string) bool { - return verify(public, message, signature, []byte(ctx), false) -} - -// VerifyPh returns true if the signature is valid. Failure cases are invalid -// signature, or when the public key cannot be decoded. -// This function supports the signature variant defined in RFC-8032: Ed448ph, -// meaning it internally hashes the message using SHAKE-256. -// Context could be passed to this function, which length should be no more than -// 255. It can be empty. -func VerifyPh(public PublicKey, message, signature []byte, ctx string) bool { - return verify(public, message, signature, []byte(ctx), true) -} - -func deriveSecretScalar(s *goldilocks.Scalar, h []byte) { - h[0] &= 0xFC // The two least significant bits of the first octet are cleared, - h[paramB-1] = 0x00 // all eight bits the last octet are cleared, and - h[paramB-2] |= 0x80 // the highest bit of the second to last octet is set. - s.FromBytes(h[:paramB]) -} - -// isLessThanOrder returns true if 0 <= x < order and if the last byte of x is zero. -func isLessThanOrder(x []byte) bool { - order := goldilocks.Curve{}.Order() - i := len(order) - 1 - for i > 0 && x[i] == order[i] { - i-- - } - return x[paramB-1] == 0 && x[i] < order[i] -} - -func writeDom(h io.Writer, ctx []byte, preHash bool) { - dom4 := "SigEd448" - _, _ = h.Write([]byte(dom4)) - - if preHash { - _, _ = h.Write([]byte{byte(0x01), byte(len(ctx))}) - } else { - _, _ = h.Write([]byte{byte(0x00), byte(len(ctx))}) - } - _, _ = h.Write(ctx) -} diff --git a/vendor/github.com/cloudflare/circl/sign/ed448/signapi.go b/vendor/github.com/cloudflare/circl/sign/ed448/signapi.go deleted file mode 100644 index 22da8bc0..00000000 --- a/vendor/github.com/cloudflare/circl/sign/ed448/signapi.go +++ /dev/null @@ -1,87 +0,0 @@ -package ed448 - -import ( - "crypto/rand" - "encoding/asn1" - - "github.com/cloudflare/circl/sign" -) - -var sch sign.Scheme = &scheme{} - -// Scheme returns a signature interface. -func Scheme() sign.Scheme { return sch } - -type scheme struct{} - -func (*scheme) Name() string { return "Ed448" } -func (*scheme) PublicKeySize() int { return PublicKeySize } -func (*scheme) PrivateKeySize() int { return PrivateKeySize } -func (*scheme) SignatureSize() int { return SignatureSize } -func (*scheme) SeedSize() int { return SeedSize } -func (*scheme) TLSIdentifier() uint { return 0x0808 } -func (*scheme) SupportsContext() bool { return true } -func (*scheme) Oid() asn1.ObjectIdentifier { - return asn1.ObjectIdentifier{1, 3, 101, 113} -} - -func (*scheme) GenerateKey() (sign.PublicKey, sign.PrivateKey, error) { - return GenerateKey(rand.Reader) -} - -func (*scheme) Sign( - sk sign.PrivateKey, - message []byte, - opts *sign.SignatureOpts, -) []byte { - priv, ok := sk.(PrivateKey) - if !ok { - panic(sign.ErrTypeMismatch) - } - ctx := "" - if opts != nil { - ctx = opts.Context - } - return Sign(priv, message, ctx) -} - -func (*scheme) Verify( - pk sign.PublicKey, - message, signature []byte, - opts *sign.SignatureOpts, -) bool { - pub, ok := pk.(PublicKey) - if !ok { - panic(sign.ErrTypeMismatch) - } - ctx := "" - if opts != nil { - ctx = opts.Context - } - return Verify(pub, message, signature, ctx) -} - -func (*scheme) DeriveKey(seed []byte) (sign.PublicKey, sign.PrivateKey) { - privateKey := NewKeyFromSeed(seed) - publicKey := make(PublicKey, PublicKeySize) - copy(publicKey, privateKey[SeedSize:]) - return publicKey, privateKey -} - -func (*scheme) UnmarshalBinaryPublicKey(buf []byte) (sign.PublicKey, error) { - if len(buf) < PublicKeySize { - return nil, sign.ErrPubKeySize - } - pub := make(PublicKey, PublicKeySize) - copy(pub, buf[:PublicKeySize]) - return pub, nil -} - -func (*scheme) UnmarshalBinaryPrivateKey(buf []byte) (sign.PrivateKey, error) { - if len(buf) < PrivateKeySize { - return nil, sign.ErrPrivKeySize - } - priv := make(PrivateKey, PrivateKeySize) - copy(priv, buf[:PrivateKeySize]) - return priv, nil -} diff --git a/vendor/github.com/cloudflare/circl/sign/sign.go b/vendor/github.com/cloudflare/circl/sign/sign.go deleted file mode 100644 index 13b20fa4..00000000 --- a/vendor/github.com/cloudflare/circl/sign/sign.go +++ /dev/null @@ -1,110 +0,0 @@ -// Package sign provides unified interfaces for signature schemes. -// -// A register of schemes is available in the package -// -// github.com/cloudflare/circl/sign/schemes -package sign - -import ( - "crypto" - "encoding" - "errors" -) - -type SignatureOpts struct { - // If non-empty, includes the given context in the signature if supported - // and will cause an error during signing otherwise. - Context string -} - -// A public key is used to verify a signature set by the corresponding private -// key. -type PublicKey interface { - // Returns the signature scheme for this public key. - Scheme() Scheme - Equal(crypto.PublicKey) bool - encoding.BinaryMarshaler - crypto.PublicKey -} - -// A private key allows one to create signatures. -type PrivateKey interface { - // Returns the signature scheme for this private key. - Scheme() Scheme - Equal(crypto.PrivateKey) bool - // For compatibility with Go standard library - crypto.Signer - crypto.PrivateKey - encoding.BinaryMarshaler -} - -// A Scheme represents a specific instance of a signature scheme. -type Scheme interface { - // Name of the scheme. - Name() string - - // GenerateKey creates a new key-pair. - GenerateKey() (PublicKey, PrivateKey, error) - - // Creates a signature using the PrivateKey on the given message and - // returns the signature. opts are additional options which can be nil. - // - // Panics if key is nil or wrong type or opts context is not supported. - Sign(sk PrivateKey, message []byte, opts *SignatureOpts) []byte - - // Checks whether the given signature is a valid signature set by - // the private key corresponding to the given public key on the - // given message. opts are additional options which can be nil. - // - // Panics if key is nil or wrong type or opts context is not supported. - Verify(pk PublicKey, message []byte, signature []byte, opts *SignatureOpts) bool - - // Deterministically derives a keypair from a seed. If you're unsure, - // you're better off using GenerateKey(). - // - // Panics if seed is not of length SeedSize(). - DeriveKey(seed []byte) (PublicKey, PrivateKey) - - // Unmarshals a PublicKey from the provided buffer. - UnmarshalBinaryPublicKey([]byte) (PublicKey, error) - - // Unmarshals a PublicKey from the provided buffer. - UnmarshalBinaryPrivateKey([]byte) (PrivateKey, error) - - // Size of binary marshalled public keys. - PublicKeySize() int - - // Size of binary marshalled public keys. - PrivateKeySize() int - - // Size of signatures. - SignatureSize() int - - // Size of seeds. - SeedSize() int - - // Returns whether contexts are supported. - SupportsContext() bool -} - -var ( - // ErrTypeMismatch is the error used if types of, for instance, private - // and public keys don't match. - ErrTypeMismatch = errors.New("types mismatch") - - // ErrSeedSize is the error used if the provided seed is of the wrong - // size. - ErrSeedSize = errors.New("wrong seed size") - - // ErrPubKeySize is the error used if the provided public key is of - // the wrong size. - ErrPubKeySize = errors.New("wrong size for public key") - - // ErrPrivKeySize is the error used if the provided private key is of - // the wrong size. - ErrPrivKeySize = errors.New("wrong size for private key") - - // ErrContextNotSupported is the error used if a context is not - // supported. - ErrContextNotSupported = errors.New("context not supported") -) diff --git a/vendor/github.com/cloudflare/cloudflare-go/.gitignore b/vendor/github.com/cloudflare/cloudflare-go/.gitignore deleted file mode 100644 index d817ce77..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.idea -.vscode/ -cmd/flarectl/dist/ -cmd/flarectl/flarectl diff --git a/vendor/github.com/cloudflare/cloudflare-go/.golintci.yaml b/vendor/github.com/cloudflare/cloudflare-go/.golintci.yaml deleted file mode 100644 index 7f311855..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/.golintci.yaml +++ /dev/null @@ -1,19 +0,0 @@ -run: - - # timeout for analysis, e.g. 30s, 5m, default is 1m - timeout: 1m - - # exit code when at least one issue was found, default is 1 - issues-exit-code: 1 - - # include test files or not, default is true - tests: true - - # default is true. Enables skipping of directories: - # vendor$, third_party$, testdata$, examples$, Godeps$, builtin$ - skip-dirs-use-default: true - - modules-download-mode: readonly - -output: - format: colored-line-number diff --git a/vendor/github.com/cloudflare/cloudflare-go/CODE_OF_CONDUCT.md b/vendor/github.com/cloudflare/cloudflare-go/CODE_OF_CONDUCT.md deleted file mode 100644 index bfbc69d2..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,77 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, sex characteristics, gender identity and expression, -level of experience, education, socio-economic status, nationality, personal -appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ggalow@cloudflare.com. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html - -[homepage]: https://www.contributor-covenant.org - -For answers to common questions about this code of conduct, see -https://www.contributor-covenant.org/faq - diff --git a/vendor/github.com/cloudflare/cloudflare-go/LICENSE b/vendor/github.com/cloudflare/cloudflare-go/LICENSE deleted file mode 100644 index 20451115..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/LICENSE +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2015-2021, Cloudflare. 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. - -2. 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. - -3. Neither the name of the copyright holder 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 HOLDER 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/cloudflare/cloudflare-go/README.md b/vendor/github.com/cloudflare/cloudflare-go/README.md deleted file mode 100644 index f2fff48d..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/README.md +++ /dev/null @@ -1,114 +0,0 @@ -# cloudflare-go - -[![Go Reference](https://pkg.go.dev/badge/github.com/cloudflare/cloudflare-go.svg)](https://pkg.go.dev/github.com/cloudflare/cloudflare-go) -![Test](https://github.com/cloudflare/cloudflare-go/workflows/Test/badge.svg) -[![Go Report Card](https://goreportcard.com/badge/github.com/cloudflare/cloudflare-go?style=flat-square)](https://goreportcard.com/report/github.com/cloudflare/cloudflare-go) - -> **Note**: This library is under active development as we expand it to cover -> our (expanding!) API. Consider the public API of this package a little -> unstable as we work towards a v1.0. - -A Go library for interacting with -[Cloudflare's API v4](https://api.cloudflare.com/). This library allows you to: - -* Manage and automate changes to your DNS records within Cloudflare -* Manage and automate changes to your zones (domains) on Cloudflare, including - adding new zones to your account -* List and modify the status of WAF (Web Application Firewall) rules for your - zones -* Fetch Cloudflare's IP ranges for automating your firewall whitelisting - -A command-line client, [flarectl](cmd/flarectl), is also available as part of -this project. - -## Features - -The current feature list includes: - -* [x] Cache purging -* [x] Cloudflare IPs -* [x] Custom hostnames -* [x] DNS Records -* [x] Firewall (partial) -* [x] [Keyless SSL](https://blog.cloudflare.com/keyless-ssl-the-nitty-gritty-technical-details/) -* [x] [Load Balancing](https://blog.cloudflare.com/introducing-load-balancing-intelligent-failover-with-cloudflare/) -* [x] [Logpush Jobs](https://developers.cloudflare.com/logs/logpush/) -* [ ] Organization Administration -* [x] [Origin CA](https://blog.cloudflare.com/universal-ssl-encryption-all-the-way-to-the-origin-for-free/) -* [x] [Railgun](https://www.cloudflare.com/railgun/) administration -* [x] Rate Limiting -* [x] User Administration (partial) -* [x] Virtual DNS Management -* [x] Web Application Firewall (WAF) -* [x] Zone Lockdown and User-Agent Block rules -* [x] Zones -* [x] Workers KV -* [x] Notifications -* [x] Gateway Locations - -Pull Requests are welcome, but please open an issue (or comment in an existing -issue) to discuss any non-trivial changes before submitting code. - -## Installation - -You need a working Go environment. - -``` -go get github.com/cloudflare/cloudflare-go -``` - -## Getting Started - -```go -package main - -import ( - "context" - "fmt" - "log" - "os" - - "github.com/cloudflare/cloudflare-go" -) - -func main() { - // Construct a new API object - api, err := cloudflare.New(os.Getenv("CLOUDFLARE_API_KEY"), os.Getenv("CLOUDFLARE_API_EMAIL")) - if err != nil { - log.Fatal(err) - } - - // Most API calls require a Context - ctx := context.Background() - - // Fetch user details on the account - u, err := api.UserDetails(ctx) - if err != nil { - log.Fatal(err) - } - // Print user details - fmt.Println(u) - - // Fetch the zone ID - id, err := api.ZoneIDByName("example.com") // Assuming example.com exists in your Cloudflare account already - if err != nil { - log.Fatal(err) - } - - // Fetch zone details - zone, err := api.ZoneDetails(ctx, id) - if err != nil { - log.Fatal(err) - } - // Print zone details - fmt.Println(zone) -} -``` - -Also refer to the -[API documentation](https://pkg.go.dev/github.com/cloudflare/cloudflare-go) for -how to use this package in-depth. - -# License - -BSD licensed. See the [LICENSE](LICENSE) file for details. diff --git a/vendor/github.com/cloudflare/cloudflare-go/access_application.go b/vendor/github.com/cloudflare/cloudflare-go/access_application.go deleted file mode 100644 index ecda1b48..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/access_application.go +++ /dev/null @@ -1,287 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -// AccessApplicationType represents the application type. -type AccessApplicationType string - -// These constants represent all valid application types. -const ( - SelfHosted AccessApplicationType = "self_hosted" - SSH AccessApplicationType = "ssh" - VNC AccessApplicationType = "vnc" - File AccessApplicationType = "file" -) - -// AccessApplication represents an Access application. -type AccessApplication struct { - ID string `json:"id,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - AUD string `json:"aud,omitempty"` - Name string `json:"name"` - Domain string `json:"domain"` - Type AccessApplicationType `json:"type,omitempty"` - SessionDuration string `json:"session_duration,omitempty"` - AutoRedirectToIdentity bool `json:"auto_redirect_to_identity,omitempty"` - EnableBindingCookie bool `json:"enable_binding_cookie,omitempty"` - AllowedIdps []string `json:"allowed_idps,omitempty"` - CorsHeaders *AccessApplicationCorsHeaders `json:"cors_headers,omitempty"` - CustomDenyMessage string `json:"custom_deny_message,omitempty"` - CustomDenyURL string `json:"custom_deny_url,omitempty"` - HttpOnlyCookieAttribute bool `json:"http_only_cookie_attribute,omitempty"` - SameSiteCookieAttribute string `json:"same_site_cookie_attribute,omitempty"` -} - -// AccessApplicationCorsHeaders represents the CORS HTTP headers for an Access -// Application. -type AccessApplicationCorsHeaders struct { - AllowedMethods []string `json:"allowed_methods,omitempty"` - AllowedOrigins []string `json:"allowed_origins,omitempty"` - AllowedHeaders []string `json:"allowed_headers,omitempty"` - AllowAllMethods bool `json:"allow_all_methods,omitempty"` - AllowAllHeaders bool `json:"allow_all_headers,omitempty"` - AllowAllOrigins bool `json:"allow_all_origins,omitempty"` - AllowCredentials bool `json:"allow_credentials,omitempty"` - MaxAge int `json:"max_age,omitempty"` -} - -// AccessApplicationListResponse represents the response from the list -// access applications endpoint. -type AccessApplicationListResponse struct { - Result []AccessApplication `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccessApplicationDetailResponse is the API response, containing a single -// access application. -type AccessApplicationDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result AccessApplication `json:"result"` -} - -// AccessApplications returns all applications within an account. -// -// API reference: https://api.cloudflare.com/#access-applications-list-access-applications -func (api *API) AccessApplications(ctx context.Context, accountID string, pageOpts PaginationOptions) ([]AccessApplication, ResultInfo, error) { - return api.accessApplications(ctx, accountID, pageOpts, AccountRouteRoot) -} - -// ZoneLevelAccessApplications returns all applications within a zone. -// -// API reference: https://api.cloudflare.com/#zone-level-access-applications-list-access-applications -func (api *API) ZoneLevelAccessApplications(ctx context.Context, zoneID string, pageOpts PaginationOptions) ([]AccessApplication, ResultInfo, error) { - return api.accessApplications(ctx, zoneID, pageOpts, ZoneRouteRoot) -} - -func (api *API) accessApplications(ctx context.Context, id string, pageOpts PaginationOptions, routeRoot RouteRoot) ([]AccessApplication, ResultInfo, error) { - v := url.Values{} - if pageOpts.PerPage > 0 { - v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) - } - if pageOpts.Page > 0 { - v.Set("page", strconv.Itoa(pageOpts.Page)) - } - - uri := fmt.Sprintf("/%s/%s/access/apps", routeRoot, id) - if len(v) > 0 { - uri = fmt.Sprintf("%s?%s", uri, v.Encode()) - } - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []AccessApplication{}, ResultInfo{}, err - } - - var accessApplicationListResponse AccessApplicationListResponse - err = json.Unmarshal(res, &accessApplicationListResponse) - if err != nil { - return []AccessApplication{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return accessApplicationListResponse.Result, accessApplicationListResponse.ResultInfo, nil -} - -// AccessApplication returns a single application based on the -// application ID. -// -// API reference: https://api.cloudflare.com/#access-applications-access-applications-details -func (api *API) AccessApplication(ctx context.Context, accountID, applicationID string) (AccessApplication, error) { - return api.accessApplication(ctx, accountID, applicationID, AccountRouteRoot) -} - -// ZoneLevelAccessApplication returns a single zone level application based on the -// application ID. -// -// API reference: https://api.cloudflare.com/#zone-level-access-applications-access-applications-details -func (api *API) ZoneLevelAccessApplication(ctx context.Context, zoneID, applicationID string) (AccessApplication, error) { - return api.accessApplication(ctx, zoneID, applicationID, ZoneRouteRoot) -} - -func (api *API) accessApplication(ctx context.Context, id, applicationID string, routeRoot RouteRoot) (AccessApplication, error) { - uri := fmt.Sprintf( - "/%s/%s/access/apps/%s", - routeRoot, - id, - applicationID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return AccessApplication{}, err - } - - var accessApplicationDetailResponse AccessApplicationDetailResponse - err = json.Unmarshal(res, &accessApplicationDetailResponse) - if err != nil { - return AccessApplication{}, errors.Wrap(err, errUnmarshalError) - } - - return accessApplicationDetailResponse.Result, nil -} - -// CreateAccessApplication creates a new access application. -// -// API reference: https://api.cloudflare.com/#access-applications-create-access-application -func (api *API) CreateAccessApplication(ctx context.Context, accountID string, accessApplication AccessApplication) (AccessApplication, error) { - return api.createAccessApplication(ctx, accountID, accessApplication, AccountRouteRoot) -} - -// CreateZoneLevelAccessApplication creates a new zone level access application. -// -// API reference: https://api.cloudflare.com/#zone-level-access-applications-create-access-application -func (api *API) CreateZoneLevelAccessApplication(ctx context.Context, zoneID string, accessApplication AccessApplication) (AccessApplication, error) { - return api.createAccessApplication(ctx, zoneID, accessApplication, ZoneRouteRoot) -} - -func (api *API) createAccessApplication(ctx context.Context, id string, accessApplication AccessApplication, routeRoot RouteRoot) (AccessApplication, error) { - uri := fmt.Sprintf("/%s/%s/access/apps", routeRoot, id) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, accessApplication) - if err != nil { - return AccessApplication{}, err - } - - var accessApplicationDetailResponse AccessApplicationDetailResponse - err = json.Unmarshal(res, &accessApplicationDetailResponse) - if err != nil { - return AccessApplication{}, errors.Wrap(err, errUnmarshalError) - } - - return accessApplicationDetailResponse.Result, nil -} - -// UpdateAccessApplication updates an existing access application. -// -// API reference: https://api.cloudflare.com/#access-applications-update-access-application -func (api *API) UpdateAccessApplication(ctx context.Context, accountID string, accessApplication AccessApplication) (AccessApplication, error) { - return api.updateAccessApplication(ctx, accountID, accessApplication, AccountRouteRoot) -} - -// UpdateZoneLevelAccessApplication updates an existing zone level access application. -// -// API reference: https://api.cloudflare.com/#zone-level-access-applications-update-access-application -func (api *API) UpdateZoneLevelAccessApplication(ctx context.Context, zoneID string, accessApplication AccessApplication) (AccessApplication, error) { - return api.updateAccessApplication(ctx, zoneID, accessApplication, ZoneRouteRoot) -} - -func (api *API) updateAccessApplication(ctx context.Context, id string, accessApplication AccessApplication, routeRoot RouteRoot) (AccessApplication, error) { - if accessApplication.ID == "" { - return AccessApplication{}, errors.Errorf("access application ID cannot be empty") - } - - uri := fmt.Sprintf( - "/%s/%s/access/apps/%s", - routeRoot, - id, - accessApplication.ID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, accessApplication) - if err != nil { - return AccessApplication{}, err - } - - var accessApplicationDetailResponse AccessApplicationDetailResponse - err = json.Unmarshal(res, &accessApplicationDetailResponse) - if err != nil { - return AccessApplication{}, errors.Wrap(err, errUnmarshalError) - } - - return accessApplicationDetailResponse.Result, nil -} - -// DeleteAccessApplication deletes an access application. -// -// API reference: https://api.cloudflare.com/#access-applications-delete-access-application -func (api *API) DeleteAccessApplication(ctx context.Context, accountID, applicationID string) error { - return api.deleteAccessApplication(ctx, accountID, applicationID, AccountRouteRoot) -} - -// DeleteZoneLevelAccessApplication deletes a zone level access application. -// -// API reference: https://api.cloudflare.com/#zone-level-access-applications-delete-access-application -func (api *API) DeleteZoneLevelAccessApplication(ctx context.Context, zoneID, applicationID string) error { - return api.deleteAccessApplication(ctx, zoneID, applicationID, ZoneRouteRoot) -} - -func (api *API) deleteAccessApplication(ctx context.Context, id, applicationID string, routeRoot RouteRoot) error { - uri := fmt.Sprintf( - "/%s/%s/access/apps/%s", - routeRoot, - id, - applicationID, - ) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} - -// RevokeAccessApplicationTokens revokes tokens associated with an -// access application. -// -// API reference: https://api.cloudflare.com/#access-applications-revoke-access-tokens -func (api *API) RevokeAccessApplicationTokens(ctx context.Context, accountID, applicationID string) error { - return api.revokeAccessApplicationTokens(ctx, accountID, applicationID, AccountRouteRoot) -} - -// RevokeZoneLevelAccessApplicationTokens revokes tokens associated with a zone level -// access application. -// -// API reference: https://api.cloudflare.com/#zone-level-access-applications-revoke-access-tokens -func (api *API) RevokeZoneLevelAccessApplicationTokens(ctx context.Context, zoneID, applicationID string) error { - return api.revokeAccessApplicationTokens(ctx, zoneID, applicationID, ZoneRouteRoot) -} - -func (api *API) revokeAccessApplicationTokens(ctx context.Context, id string, applicationID string, routeRoot RouteRoot) error { - uri := fmt.Sprintf( - "/%s/%s/access/apps/%s/revoke-tokens", - routeRoot, - id, - applicationID, - ) - - _, err := api.makeRequestContext(ctx, http.MethodPost, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/access_audit_log.go b/vendor/github.com/cloudflare/cloudflare-go/access_audit_log.go deleted file mode 100644 index af67b72c..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/access_audit_log.go +++ /dev/null @@ -1,87 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -// AccessAuditLogRecord is the structure of a single Access Audit Log entry. -type AccessAuditLogRecord struct { - UserEmail string `json:"user_email"` - IPAddress string `json:"ip_address"` - AppUID string `json:"app_uid"` - AppDomain string `json:"app_domain"` - Action string `json:"action"` - Connection string `json:"connection"` - Allowed bool `json:"allowed"` - CreatedAt *time.Time `json:"created_at"` - RayID string `json:"ray_id"` -} - -// AccessAuditLogListResponse represents the response from the list -// access applications endpoint. -type AccessAuditLogListResponse struct { - Result []AccessAuditLogRecord `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccessAuditLogFilterOptions provides the structure of available audit log -// filters. -type AccessAuditLogFilterOptions struct { - Direction string - Since *time.Time - Until *time.Time - Limit int -} - -// AccessAuditLogs retrieves all audit logs for the Access service. -// -// API reference: https://api.cloudflare.com/#access-requests-access-requests-audit -func (api *API) AccessAuditLogs(ctx context.Context, accountID string, opts AccessAuditLogFilterOptions) ([]AccessAuditLogRecord, error) { - uri := fmt.Sprintf("/accounts/%s/access/logs/access-requests?%s", accountID, opts.Encode()) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []AccessAuditLogRecord{}, err - } - - var accessAuditLogListResponse AccessAuditLogListResponse - err = json.Unmarshal(res, &accessAuditLogListResponse) - if err != nil { - return []AccessAuditLogRecord{}, errors.Wrap(err, errUnmarshalError) - } - - return accessAuditLogListResponse.Result, nil -} - -// Encode is a custom method for encoding the filter options into a usable HTTP -// query parameter string. -func (a AccessAuditLogFilterOptions) Encode() string { - v := url.Values{} - - if a.Direction != "" { - v.Set("direction", a.Direction) - } - - if a.Limit > 0 { - v.Set("limit", strconv.Itoa(a.Limit)) - } - - if a.Since != nil { - v.Set("since", (*a.Since).Format(time.RFC3339)) - } - - if a.Until != nil { - v.Set("until", (*a.Until).Format(time.RFC3339)) - } - - return v.Encode() -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/access_ca_certificate.go b/vendor/github.com/cloudflare/cloudflare-go/access_ca_certificate.go deleted file mode 100644 index d19765bc..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/access_ca_certificate.go +++ /dev/null @@ -1,166 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -// AccessCACertificate is the structure of the CA certificate used for -// short lived certificates. -type AccessCACertificate struct { - ID string `json:"id"` - Aud string `json:"aud"` - PublicKey string `json:"public_key"` -} - -// AccessCACertificateListResponse represents the response of all CA -// certificates within Access. -type AccessCACertificateListResponse struct { - Response - Result []AccessCACertificate `json:"result"` -} - -// AccessCACertificateResponse represents the response of a single CA -// certificate. -type AccessCACertificateResponse struct { - Response - Result AccessCACertificate `json:"result"` -} - -// AccessCACertificates returns all CA certificates within Access. -// -// API reference: https://api.cloudflare.com/#access-short-lived-certificates-list-short-lived-certificates -func (api *API) AccessCACertificates(ctx context.Context, accountID string) ([]AccessCACertificate, error) { - return api.accessCACertificates(ctx, accountID, AccountRouteRoot) -} - -// ZoneLevelAccessCACertificates returns all zone level CA certificates within Access. -// -// API reference: https://api.cloudflare.com/#zone-level-access-short-lived-certificates-list-short-lived-certificates -func (api *API) ZoneLevelAccessCACertificates(ctx context.Context, zoneID string) ([]AccessCACertificate, error) { - return api.accessCACertificates(ctx, zoneID, ZoneRouteRoot) -} - -func (api *API) accessCACertificates(ctx context.Context, id string, routeRoot RouteRoot) ([]AccessCACertificate, error) { - uri := fmt.Sprintf("/%s/%s/access/apps/ca", routeRoot, id) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []AccessCACertificate{}, err - } - - var accessCAListResponse AccessCACertificateListResponse - err = json.Unmarshal(res, &accessCAListResponse) - if err != nil { - return []AccessCACertificate{}, errors.Wrap(err, errUnmarshalError) - } - - return accessCAListResponse.Result, nil -} - -// AccessCACertificate returns a single CA certificate associated with an Access -// Application. -// -// API reference: https://api.cloudflare.com/#access-short-lived-certificates-short-lived-certificate-details -func (api *API) AccessCACertificate(ctx context.Context, accountID, applicationID string) (AccessCACertificate, error) { - return api.accessCACertificate(ctx, accountID, applicationID, AccountRouteRoot) -} - -// ZoneLevelAccessCACertificate returns a single zone level CA certificate associated with an Access -// Application. -// -// API reference: https://api.cloudflare.com/#zone-level-access-short-lived-certificates-short-lived-certificate-details -func (api *API) ZoneLevelAccessCACertificate(ctx context.Context, zoneID, applicationID string) (AccessCACertificate, error) { - return api.accessCACertificate(ctx, zoneID, applicationID, ZoneRouteRoot) -} - -func (api *API) accessCACertificate(ctx context.Context, id, applicationID string, routeRoot RouteRoot) (AccessCACertificate, error) { - uri := fmt.Sprintf("/%s/%s/access/apps/%s/ca", routeRoot, id, applicationID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return AccessCACertificate{}, err - } - - var accessCAResponse AccessCACertificateResponse - err = json.Unmarshal(res, &accessCAResponse) - if err != nil { - return AccessCACertificate{}, errors.Wrap(err, errUnmarshalError) - } - - return accessCAResponse.Result, nil -} - -// CreateAccessCACertificate creates a new CA certificate for an Access -// Application. -// -// API reference: https://api.cloudflare.com/#access-short-lived-certificates-create-short-lived-certificate -func (api *API) CreateAccessCACertificate(ctx context.Context, accountID, applicationID string) (AccessCACertificate, error) { - return api.createAccessCACertificate(ctx, accountID, applicationID, AccountRouteRoot) -} - -// CreateZoneLevelAccessCACertificate creates a new zone level CA certificate for an Access -// Application. -// -// API reference: https://api.cloudflare.com/#zone-level-access-short-lived-certificates-create-short-lived-certificate -func (api *API) CreateZoneLevelAccessCACertificate(ctx context.Context, zoneID string, applicationID string) (AccessCACertificate, error) { - return api.createAccessCACertificate(ctx, zoneID, applicationID, ZoneRouteRoot) -} - -func (api *API) createAccessCACertificate(ctx context.Context, id string, applicationID string, routeRoot RouteRoot) (AccessCACertificate, error) { - uri := fmt.Sprintf( - "/%s/%s/access/apps/%s/ca", - routeRoot, - id, - applicationID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, nil) - if err != nil { - return AccessCACertificate{}, err - } - - var accessCACertificate AccessCACertificateResponse - err = json.Unmarshal(res, &accessCACertificate) - if err != nil { - return AccessCACertificate{}, errors.Wrap(err, errUnmarshalError) - } - - return accessCACertificate.Result, nil -} - -// DeleteAccessCACertificate deletes an Access CA certificate on a defined -// Access Application. -// -// API reference: https://api.cloudflare.com/#access-short-lived-certificates-delete-access-certificate -func (api *API) DeleteAccessCACertificate(ctx context.Context, accountID, applicationID string) error { - return api.deleteAccessCACertificate(ctx, accountID, applicationID, AccountRouteRoot) -} - -// DeleteZoneLevelAccessCACertificate deletes a zone level Access CA certificate on a defined -// Access Application. -// -// API reference: https://api.cloudflare.com/#zone-level-access-short-lived-certificates-delete-access-certificate -func (api *API) DeleteZoneLevelAccessCACertificate(ctx context.Context, zoneID, applicationID string) error { - return api.deleteAccessCACertificate(ctx, zoneID, applicationID, ZoneRouteRoot) -} - -func (api *API) deleteAccessCACertificate(ctx context.Context, id string, applicationID string, routeRoot RouteRoot) error { - uri := fmt.Sprintf( - "/%s/%s/access/apps/%s/ca", - routeRoot, - id, - applicationID, - ) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/access_group.go b/vendor/github.com/cloudflare/cloudflare-go/access_group.go deleted file mode 100644 index 26faffce..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/access_group.go +++ /dev/null @@ -1,380 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -// AccessGroup defines a group for allowing or disallowing access to -// one or more Access applications. -type AccessGroup struct { - ID string `json:"id,omitempty"` - CreatedAt *time.Time `json:"created_at"` - UpdatedAt *time.Time `json:"updated_at"` - Name string `json:"name"` - - // The include group works like an OR logical operator. The user must - // satisfy one of the rules. - Include []interface{} `json:"include"` - - // The exclude group works like a NOT logical operator. The user must - // not satisfy all of the rules in exclude. - Exclude []interface{} `json:"exclude"` - - // The require group works like a AND logical operator. The user must - // satisfy all of the rules in require. - Require []interface{} `json:"require"` -} - -// AccessGroupEmail is used for managing access based on the email. -// For example, restrict access to users with the email addresses -// `test@example.com` or `someone@example.com`. -type AccessGroupEmail struct { - Email struct { - Email string `json:"email"` - } `json:"email"` -} - -// AccessGroupEmailDomain is used for managing access based on an email -// domain domain such as `example.com` instead of individual addresses. -type AccessGroupEmailDomain struct { - EmailDomain struct { - Domain string `json:"domain"` - } `json:"email_domain"` -} - -// AccessGroupIP is used for managing access based in the IP. It -// accepts individual IPs or CIDRs. -type AccessGroupIP struct { - IP struct { - IP string `json:"ip"` - } `json:"ip"` -} - -// AccessGroupGeo is used for managing access based on the country code. -type AccessGroupGeo struct { - Geo struct { - CountryCode string `json:"country_code"` - } `json:"geo"` -} - -// AccessGroupEveryone is used for managing access to everyone. -type AccessGroupEveryone struct { - Everyone struct{} `json:"everyone"` -} - -// AccessGroupServiceToken is used for managing access based on a specific -// service token. -type AccessGroupServiceToken struct { - ServiceToken struct { - ID string `json:"token_id"` - } `json:"service_token"` -} - -// AccessGroupAnyValidServiceToken is used for managing access for all valid -// service tokens (not restricted). -type AccessGroupAnyValidServiceToken struct { - AnyValidServiceToken struct{} `json:"any_valid_service_token"` -} - -// AccessGroupAccessGroup is used for managing access based on an -// access group. -type AccessGroupAccessGroup struct { - Group struct { - ID string `json:"id"` - } `json:"group"` -} - -// AccessGroupCertificate is used for managing access to based on a valid -// mTLS certificate being presented. -type AccessGroupCertificate struct { - Certificate struct{} `json:"certificate"` -} - -// AccessGroupCertificateCommonName is used for managing access based on a -// common name within a certificate. -type AccessGroupCertificateCommonName struct { - CommonName struct { - CommonName string `json:"common_name"` - } `json:"common_name"` -} - -// AccessGroupGSuite is used to configure access based on GSuite group. -type AccessGroupGSuite struct { - Gsuite struct { - Email string `json:"email"` - IdentityProviderID string `json:"identity_provider_id"` - } `json:"gsuite"` -} - -// AccessGroupGitHub is used to configure access based on a GitHub organisation. -type AccessGroupGitHub struct { - GitHubOrganization struct { - Name string `json:"name"` - Team string `json:"team,omitempty"` - IdentityProviderID string `json:"identity_provider_id"` - } `json:"github-organization"` -} - -// AccessGroupAzure is used to configure access based on a Azure group. -type AccessGroupAzure struct { - AzureAD struct { - ID string `json:"id"` - IdentityProviderID string `json:"identity_provider_id"` - } `json:"azureAD"` -} - -// AccessGroupOkta is used to configure access based on a Okta group. -type AccessGroupOkta struct { - Okta struct { - Name string `json:"name"` - IdentityProviderID string `json:"identity_provider_id"` - } `json:"okta"` -} - -// AccessGroupSAML is used to allow SAML users with a specific attribute -// configuration. -type AccessGroupSAML struct { - Saml struct { - AttributeName string `json:"attribute_name"` - AttributeValue string `json:"attribute_value"` - IdentityProviderID string `json:"identity_provider_id"` - } `json:"saml"` -} - -// AccessGroupAuthMethod is used for managing access by the "amr" -// (Authentication Methods References) identifier. For example, an -// application may want to require that users authenticate using a hardware -// key by setting the "auth_method" to "swk". A list of values are listed -// here: https://tools.ietf.org/html/rfc8176#section-2. Custom values are -// supported as well. -type AccessGroupAuthMethod struct { - AuthMethod struct { - AuthMethod string `json:"auth_method"` - } `json:"auth_method"` -} - -// AccessGroupLoginMethod restricts the application to specific IdP instances. -type AccessGroupLoginMethod struct { - LoginMethod struct { - ID string `json:"id"` - } `json:"login_method"` -} - -// AccessGroupDevicePosture restricts the application to specific devices -type AccessGroupDevicePosture struct { - DevicePosture struct { - ID string `json:"integration_uid"` - } `json:"device_posture"` -} - -// AccessGroupListResponse represents the response from the list -// access group endpoint. -type AccessGroupListResponse struct { - Result []AccessGroup `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccessGroupDetailResponse is the API response, containing a single -// access group. -type AccessGroupDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result AccessGroup `json:"result"` -} - -// AccessGroups returns all access groups for an access application. -// -// API reference: https://api.cloudflare.com/#access-groups-list-access-groups -func (api *API) AccessGroups(ctx context.Context, accountID string, pageOpts PaginationOptions) ([]AccessGroup, ResultInfo, error) { - return api.accessGroups(ctx, accountID, pageOpts, AccountRouteRoot) -} - -// ZoneLevelAccessGroups returns all zone level access groups for an access application. -// -// API reference: https://api.cloudflare.com/#zone-level-access-groups-list-access-groups -func (api *API) ZoneLevelAccessGroups(ctx context.Context, zoneID string, pageOpts PaginationOptions) ([]AccessGroup, ResultInfo, error) { - return api.accessGroups(ctx, zoneID, pageOpts, ZoneRouteRoot) -} - -func (api *API) accessGroups(ctx context.Context, id string, pageOpts PaginationOptions, routeRoot RouteRoot) ([]AccessGroup, ResultInfo, error) { - v := url.Values{} - if pageOpts.PerPage > 0 { - v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) - } - if pageOpts.Page > 0 { - v.Set("page", strconv.Itoa(pageOpts.Page)) - } - - uri := fmt.Sprintf( - "/%s/%s/access/groups", - routeRoot, - id, - ) - - if len(v) > 0 { - uri = fmt.Sprintf("%s?%s", uri, v.Encode()) - } - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []AccessGroup{}, ResultInfo{}, err - } - - var accessGroupListResponse AccessGroupListResponse - err = json.Unmarshal(res, &accessGroupListResponse) - if err != nil { - return []AccessGroup{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return accessGroupListResponse.Result, accessGroupListResponse.ResultInfo, nil -} - -// AccessGroup returns a single group based on the group ID. -// -// API reference: https://api.cloudflare.com/#access-groups-access-group-details -func (api *API) AccessGroup(ctx context.Context, accountID, groupID string) (AccessGroup, error) { - return api.accessGroup(ctx, accountID, groupID, AccountRouteRoot) -} - -// ZoneLevelAccessGroup returns a single zone level group based on the group ID. -// -// API reference: https://api.cloudflare.com/#zone-level-access-groups-access-group-details -func (api *API) ZoneLevelAccessGroup(ctx context.Context, zoneID, groupID string) (AccessGroup, error) { - return api.accessGroup(ctx, zoneID, groupID, ZoneRouteRoot) -} - -func (api *API) accessGroup(ctx context.Context, id, groupID string, routeRoot RouteRoot) (AccessGroup, error) { - uri := fmt.Sprintf( - "/%s/%s/access/groups/%s", - routeRoot, - id, - groupID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return AccessGroup{}, err - } - - var accessGroupDetailResponse AccessGroupDetailResponse - err = json.Unmarshal(res, &accessGroupDetailResponse) - if err != nil { - return AccessGroup{}, errors.Wrap(err, errUnmarshalError) - } - - return accessGroupDetailResponse.Result, nil -} - -// CreateAccessGroup creates a new access group. -// -// API reference: https://api.cloudflare.com/#access-groups-create-access-group -func (api *API) CreateAccessGroup(ctx context.Context, accountID string, accessGroup AccessGroup) (AccessGroup, error) { - return api.createAccessGroup(ctx, accountID, accessGroup, AccountRouteRoot) -} - -// CreateZoneLevelAccessGroup creates a new zone level access group. -// -// API reference: https://api.cloudflare.com/#zone-level-access-groups-create-access-group -func (api *API) CreateZoneLevelAccessGroup(ctx context.Context, zoneID string, accessGroup AccessGroup) (AccessGroup, error) { - return api.createAccessGroup(ctx, zoneID, accessGroup, ZoneRouteRoot) -} - -func (api *API) createAccessGroup(ctx context.Context, id string, accessGroup AccessGroup, routeRoot RouteRoot) (AccessGroup, error) { - uri := fmt.Sprintf( - "/%s/%s/access/groups", - routeRoot, - id, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, accessGroup) - if err != nil { - return AccessGroup{}, err - } - - var accessGroupDetailResponse AccessGroupDetailResponse - err = json.Unmarshal(res, &accessGroupDetailResponse) - if err != nil { - return AccessGroup{}, errors.Wrap(err, errUnmarshalError) - } - - return accessGroupDetailResponse.Result, nil -} - -// UpdateAccessGroup updates an existing access group. -// -// API reference: https://api.cloudflare.com/#access-groups-update-access-group -func (api *API) UpdateAccessGroup(ctx context.Context, accountID string, accessGroup AccessGroup) (AccessGroup, error) { - return api.updateAccessGroup(ctx, accountID, accessGroup, AccountRouteRoot) -} - -// UpdateZoneLevelAccessGroup updates an existing zone level access group. -// -// API reference: https://api.cloudflare.com/#zone-level-access-groups-update-access-group -func (api *API) UpdateZoneLevelAccessGroup(ctx context.Context, zoneID string, accessGroup AccessGroup) (AccessGroup, error) { - return api.updateAccessGroup(ctx, zoneID, accessGroup, ZoneRouteRoot) -} - -func (api *API) updateAccessGroup(ctx context.Context, id string, accessGroup AccessGroup, routeRoot RouteRoot) (AccessGroup, error) { - if accessGroup.ID == "" { - return AccessGroup{}, errors.Errorf("access group ID cannot be empty") - } - uri := fmt.Sprintf( - "/%s/%s/access/groups/%s", - routeRoot, - id, - accessGroup.ID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, accessGroup) - if err != nil { - return AccessGroup{}, err - } - - var accessGroupDetailResponse AccessGroupDetailResponse - err = json.Unmarshal(res, &accessGroupDetailResponse) - if err != nil { - return AccessGroup{}, errors.Wrap(err, errUnmarshalError) - } - - return accessGroupDetailResponse.Result, nil -} - -// DeleteAccessGroup deletes an access group. -// -// API reference: https://api.cloudflare.com/#access-groups-delete-access-group -func (api *API) DeleteAccessGroup(ctx context.Context, accountID, groupID string) error { - return api.deleteAccessGroup(ctx, accountID, groupID, AccountRouteRoot) -} - -// DeleteZoneLevelAccessGroup deletes a zone level access group. -// -// API reference: https://api.cloudflare.com/#zone-level-access-groups-delete-access-group -func (api *API) DeleteZoneLevelAccessGroup(ctx context.Context, zoneID, groupID string) error { - return api.deleteAccessGroup(ctx, zoneID, groupID, ZoneRouteRoot) -} - -func (api *API) deleteAccessGroup(ctx context.Context, id string, groupID string, routeRoot RouteRoot) error { - uri := fmt.Sprintf( - "/%s/%s/access/groups/%s", - routeRoot, - id, - groupID, - ) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/access_identity_provider.go b/vendor/github.com/cloudflare/cloudflare-go/access_identity_provider.go deleted file mode 100644 index 0fbc4239..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/access_identity_provider.go +++ /dev/null @@ -1,236 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -// AccessIdentityProvider is the structure of the provider object. -type AccessIdentityProvider struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Type string `json:"type"` - Config AccessIdentityProviderConfiguration `json:"config"` -} - -// AccessIdentityProviderConfiguration is the combined structure of *all* -// identity provider configuration fields. This is done to simplify the use of -// Access products and their relationship to each other. -// -// API reference: https://developers.cloudflare.com/access/configuring-identity-providers/ -type AccessIdentityProviderConfiguration struct { - APIToken string `json:"api_token,omitempty"` - AppsDomain string `json:"apps_domain,omitempty"` - Attributes []string `json:"attributes,omitempty"` - AuthURL string `json:"auth_url,omitempty"` - CentrifyAccount string `json:"centrify_account,omitempty"` - CentrifyAppID string `json:"centrify_app_id,omitempty"` - CertsURL string `json:"certs_url,omitempty"` - ClientID string `json:"client_id,omitempty"` - ClientSecret string `json:"client_secret,omitempty"` - DirectoryID string `json:"directory_id,omitempty"` - EmailAttributeName string `json:"email_attribute_name,omitempty"` - IdpPublicCert string `json:"idp_public_cert,omitempty"` - IssuerURL string `json:"issuer_url,omitempty"` - OktaAccount string `json:"okta_account,omitempty"` - OneloginAccount string `json:"onelogin_account,omitempty"` - RedirectURL string `json:"redirect_url,omitempty"` - SignRequest bool `json:"sign_request,omitempty"` - SsoTargetURL string `json:"sso_target_url,omitempty"` - SupportGroups bool `json:"support_groups,omitempty"` - TokenURL string `json:"token_url,omitempty"` -} - -// AccessIdentityProvidersListResponse is the API response for multiple -// Access Identity Providers. -type AccessIdentityProvidersListResponse struct { - Response - Result []AccessIdentityProvider `json:"result"` -} - -// AccessIdentityProviderListResponse is the API response for a single -// Access Identity Provider. -type AccessIdentityProviderListResponse struct { - Response - Result AccessIdentityProvider `json:"result"` -} - -// AccessIdentityProviders returns all Access Identity Providers for an -// account. -// -// API reference: https://api.cloudflare.com/#access-identity-providers-list-access-identity-providers -func (api *API) AccessIdentityProviders(ctx context.Context, accountID string) ([]AccessIdentityProvider, error) { - return api.accessIdentityProviders(ctx, accountID, AccountRouteRoot) -} - -// ZoneLevelAccessIdentityProviders returns all Access Identity Providers for an -// account. -// -// API reference: https://api.cloudflare.com/#zone-level-access-identity-providers-list-access-identity-providers -func (api *API) ZoneLevelAccessIdentityProviders(ctx context.Context, zoneID string) ([]AccessIdentityProvider, error) { - return api.accessIdentityProviders(ctx, zoneID, ZoneRouteRoot) -} - -func (api *API) accessIdentityProviders(ctx context.Context, id string, routeRoot RouteRoot) ([]AccessIdentityProvider, error) { - uri := fmt.Sprintf("/%s/%s/access/identity_providers", routeRoot, id) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []AccessIdentityProvider{}, err - } - - var accessIdentityProviderResponse AccessIdentityProvidersListResponse - err = json.Unmarshal(res, &accessIdentityProviderResponse) - if err != nil { - return []AccessIdentityProvider{}, errors.Wrap(err, errUnmarshalError) - } - - return accessIdentityProviderResponse.Result, nil -} - -// AccessIdentityProviderDetails returns a single Access Identity -// Provider for an account. -// -// API reference: https://api.cloudflare.com/#access-identity-providers-access-identity-providers-details -func (api *API) AccessIdentityProviderDetails(ctx context.Context, accountID, identityProviderID string) (AccessIdentityProvider, error) { - return api.accessIdentityProviderDetails(ctx, accountID, identityProviderID, AccountRouteRoot) -} - -// ZoneLevelAccessIdentityProviderDetails returns a single zone level Access Identity -// Provider for an account. -// -// API reference: https://api.cloudflare.com/#zone-level-access-identity-providers-access-identity-providers-details -func (api *API) ZoneLevelAccessIdentityProviderDetails(ctx context.Context, zoneID, identityProviderID string) (AccessIdentityProvider, error) { - return api.accessIdentityProviderDetails(ctx, zoneID, identityProviderID, ZoneRouteRoot) -} - -func (api *API) accessIdentityProviderDetails(ctx context.Context, id string, identityProviderID string, routeRoot RouteRoot) (AccessIdentityProvider, error) { - uri := fmt.Sprintf( - "/%s/%s/access/identity_providers/%s", - routeRoot, - id, - identityProviderID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return AccessIdentityProvider{}, err - } - - var accessIdentityProviderResponse AccessIdentityProviderListResponse - err = json.Unmarshal(res, &accessIdentityProviderResponse) - if err != nil { - return AccessIdentityProvider{}, errors.Wrap(err, errUnmarshalError) - } - - return accessIdentityProviderResponse.Result, nil -} - -// CreateAccessIdentityProvider creates a new Access Identity Provider. -// -// API reference: https://api.cloudflare.com/#access-identity-providers-create-access-identity-provider -func (api *API) CreateAccessIdentityProvider(ctx context.Context, accountID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { - return api.createAccessIdentityProvider(ctx, accountID, identityProviderConfiguration, AccountRouteRoot) -} - -// CreateZoneLevelAccessIdentityProvider creates a new zone level Access Identity Provider. -// -// API reference: https://api.cloudflare.com/#zone-level-access-identity-providers-create-access-identity-provider -func (api *API) CreateZoneLevelAccessIdentityProvider(ctx context.Context, zoneID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { - return api.createAccessIdentityProvider(ctx, zoneID, identityProviderConfiguration, ZoneRouteRoot) -} - -func (api *API) createAccessIdentityProvider(ctx context.Context, id string, identityProviderConfiguration AccessIdentityProvider, routeRoot RouteRoot) (AccessIdentityProvider, error) { - uri := fmt.Sprintf("/%s/%s/access/identity_providers", routeRoot, id) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, identityProviderConfiguration) - if err != nil { - return AccessIdentityProvider{}, err - } - - var accessIdentityProviderResponse AccessIdentityProviderListResponse - err = json.Unmarshal(res, &accessIdentityProviderResponse) - if err != nil { - return AccessIdentityProvider{}, errors.Wrap(err, errUnmarshalError) - } - - return accessIdentityProviderResponse.Result, nil -} - -// UpdateAccessIdentityProvider updates an existing Access Identity -// Provider. -// -// API reference: https://api.cloudflare.com/#access-identity-providers-create-access-identity-provider -func (api *API) UpdateAccessIdentityProvider(ctx context.Context, accountID, identityProviderUUID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { - return api.updateAccessIdentityProvider(ctx, accountID, identityProviderUUID, identityProviderConfiguration, AccountRouteRoot) -} - -// UpdateZoneLevelAccessIdentityProvider updates an existing zone level Access Identity -// Provider. -// -// API reference: https://api.cloudflare.com/#zone-level-access-identity-providers-update-access-identity-provider -func (api *API) UpdateZoneLevelAccessIdentityProvider(ctx context.Context, zoneID, identityProviderUUID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { - return api.updateAccessIdentityProvider(ctx, zoneID, identityProviderUUID, identityProviderConfiguration, ZoneRouteRoot) -} - -func (api *API) updateAccessIdentityProvider(ctx context.Context, id string, identityProviderUUID string, identityProviderConfiguration AccessIdentityProvider, routeRoot RouteRoot) (AccessIdentityProvider, error) { - uri := fmt.Sprintf( - "/%s/%s/access/identity_providers/%s", - routeRoot, - id, - identityProviderUUID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, identityProviderConfiguration) - if err != nil { - return AccessIdentityProvider{}, err - } - - var accessIdentityProviderResponse AccessIdentityProviderListResponse - err = json.Unmarshal(res, &accessIdentityProviderResponse) - if err != nil { - return AccessIdentityProvider{}, errors.Wrap(err, errUnmarshalError) - } - - return accessIdentityProviderResponse.Result, nil -} - -// DeleteAccessIdentityProvider deletes an Access Identity Provider. -// -// API reference: https://api.cloudflare.com/#access-identity-providers-create-access-identity-provider -func (api *API) DeleteAccessIdentityProvider(ctx context.Context, accountID, identityProviderUUID string) (AccessIdentityProvider, error) { - return api.deleteAccessIdentityProvider(ctx, accountID, identityProviderUUID, AccountRouteRoot) -} - -// DeleteZoneLevelAccessIdentityProvider deletes a zone level Access Identity Provider. -// -// API reference: https://api.cloudflare.com/#zone-level-access-identity-providers-delete-access-identity-provider -func (api *API) DeleteZoneLevelAccessIdentityProvider(ctx context.Context, zoneID, identityProviderUUID string) (AccessIdentityProvider, error) { - return api.deleteAccessIdentityProvider(ctx, zoneID, identityProviderUUID, ZoneRouteRoot) -} - -func (api *API) deleteAccessIdentityProvider(ctx context.Context, id string, identityProviderUUID string, routeRoot RouteRoot) (AccessIdentityProvider, error) { - uri := fmt.Sprintf( - "/%s/%s/access/identity_providers/%s", - routeRoot, - id, - identityProviderUUID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return AccessIdentityProvider{}, err - } - - var accessIdentityProviderResponse AccessIdentityProviderListResponse - err = json.Unmarshal(res, &accessIdentityProviderResponse) - if err != nil { - return AccessIdentityProvider{}, errors.Wrap(err, errUnmarshalError) - } - - return accessIdentityProviderResponse.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/access_keys.go b/vendor/github.com/cloudflare/cloudflare-go/access_keys.go deleted file mode 100644 index 1816dc6c..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/access_keys.go +++ /dev/null @@ -1,64 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "github.com/pkg/errors" - "net/http" - "time" -) - -type AccessKeysConfig struct { - KeyRotationIntervalDays int `json:"key_rotation_interval_days"` - LastKeyRotationAt time.Time `json:"last_key_rotation_at"` - DaysUntilNextRotation int `json:"days_until_next_rotation"` -} - -type AccessKeysConfigUpdateRequest struct { - KeyRotationIntervalDays int `json:"key_rotation_interval_days"` -} - -type accessKeysConfigResponse struct { - Response - Result AccessKeysConfig `json:"result"` -} - -// AccessKeysConfig returns the Access Keys Configuration for an account. -// -// API reference: https://api.cloudflare.com/#access-keys-configuration-get-access-keys-configuration -func (api *API) AccessKeysConfig(ctx context.Context, accountID string) (AccessKeysConfig, error) { - uri := fmt.Sprintf("/%s/%s/access/keys", AccountRouteRoot, accountID) - - return api.accessKeysRequest(ctx, http.MethodGet, uri, nil) -} - -// UpdateAccessKeysConfig updates the Access Keys Configuration for an account. -// -// API reference: https://api.cloudflare.com/#access-keys-configuration-update-access-keys-configuration -func (api *API) UpdateAccessKeysConfig(ctx context.Context, accountID string, request AccessKeysConfigUpdateRequest) (AccessKeysConfig, error) { - uri := fmt.Sprintf("/%s/%s/access/keys", AccountRouteRoot, accountID) - - return api.accessKeysRequest(ctx, http.MethodPut, uri, request) -} - -// RotateAccessKeys rotates the Access Keys for an account and returns the updated Access Keys Configuration -// -// API reference: https://api.cloudflare.com/#access-keys-configuration-rotate-access-keys -func (api *API) RotateAccessKeys(ctx context.Context, accountID string) (AccessKeysConfig, error) { - uri := fmt.Sprintf("/%s/%s/access/keys/rotate", AccountRouteRoot, accountID) - return api.accessKeysRequest(ctx, http.MethodPost, uri, nil) -} - -func (api *API) accessKeysRequest(ctx context.Context, method, uri string, params interface{}) (AccessKeysConfig, error) { - res, err := api.makeRequestContext(ctx, method, uri, params) - if err != nil { - return AccessKeysConfig{}, err - } - - var keysConfigResponse accessKeysConfigResponse - if err := json.Unmarshal(res, &keysConfigResponse); err != nil { - return AccessKeysConfig{}, errors.Wrap(err, errUnmarshalError) - } - return keysConfigResponse.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/access_mutual_tls_certificates.go b/vendor/github.com/cloudflare/cloudflare-go/access_mutual_tls_certificates.go deleted file mode 100644 index 007ddef2..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/access_mutual_tls_certificates.go +++ /dev/null @@ -1,226 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// AccessMutualTLSCertificate is the structure of a single Access Mutual TLS -// certificate. -type AccessMutualTLSCertificate struct { - ID string `json:"id,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` - ExpiresOn time.Time `json:"expires_on,omitempty"` - Name string `json:"name,omitempty"` - Fingerprint string `json:"fingerprint,omitempty"` - Certificate string `json:"certificate,omitempty"` - AssociatedHostnames []string `json:"associated_hostnames,omitempty"` -} - -// AccessMutualTLSCertificateListResponse is the API response for all Access -// Mutual TLS certificates. -type AccessMutualTLSCertificateListResponse struct { - Response - Result []AccessMutualTLSCertificate `json:"result"` -} - -// AccessMutualTLSCertificateDetailResponse is the API response for a single -// Access Mutual TLS certificate. -type AccessMutualTLSCertificateDetailResponse struct { - Response - Result AccessMutualTLSCertificate `json:"result"` -} - -// AccessMutualTLSCertificates returns all Access TLS certificates for the account -// level. -// -// API reference: https://api.cloudflare.com/#access-mutual-tls-authentication-properties -func (api *API) AccessMutualTLSCertificates(ctx context.Context, accountID string) ([]AccessMutualTLSCertificate, error) { - return api.accessMutualTLSCertificates(ctx, accountID, AccountRouteRoot) -} - -// ZoneAccessMutualTLSCertificates returns all Access TLS certificates for the -// zone level. -// -// API reference: https://api.cloudflare.com/#zone-level-access-mutual-tls-authentication-properties -func (api *API) ZoneAccessMutualTLSCertificates(ctx context.Context, zoneID string) ([]AccessMutualTLSCertificate, error) { - return api.accessMutualTLSCertificates(ctx, zoneID, ZoneRouteRoot) -} - -func (api *API) accessMutualTLSCertificates(ctx context.Context, id string, routeRoot RouteRoot) ([]AccessMutualTLSCertificate, error) { - uri := fmt.Sprintf( - "/%s/%s/access/certificates", - routeRoot, - id, - ) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []AccessMutualTLSCertificate{}, err - } - - var accessMutualTLSCertificateListResponse AccessMutualTLSCertificateListResponse - err = json.Unmarshal(res, &accessMutualTLSCertificateListResponse) - if err != nil { - return []AccessMutualTLSCertificate{}, errors.Wrap(err, errUnmarshalError) - } - - return accessMutualTLSCertificateListResponse.Result, nil -} - -// AccessMutualTLSCertificate returns a single account level Access Mutual TLS -// certificate. -// -// API reference: https://api.cloudflare.com/#access-mutual-tls-authentication-access-certificate-details -func (api *API) AccessMutualTLSCertificate(ctx context.Context, accountID, certificateID string) (AccessMutualTLSCertificate, error) { - return api.accessMutualTLSCertificate(ctx, accountID, certificateID, AccountRouteRoot) -} - -// ZoneAccessMutualTLSCertificate returns a single zone level Access Mutual TLS -// certificate. -// -// API reference: https://api.cloudflare.com/#zone-level-access-mutual-tls-authentication-access-certificate-details -func (api *API) ZoneAccessMutualTLSCertificate(ctx context.Context, zoneID, certificateID string) (AccessMutualTLSCertificate, error) { - return api.accessMutualTLSCertificate(ctx, zoneID, certificateID, ZoneRouteRoot) -} - -func (api *API) accessMutualTLSCertificate(ctx context.Context, id, certificateID string, routeRoot RouteRoot) (AccessMutualTLSCertificate, error) { - uri := fmt.Sprintf( - "/%s/%s/access/certificates/%s", - routeRoot, - id, - certificateID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return AccessMutualTLSCertificate{}, err - } - - var accessMutualTLSCertificateDetailResponse AccessMutualTLSCertificateDetailResponse - err = json.Unmarshal(res, &accessMutualTLSCertificateDetailResponse) - if err != nil { - return AccessMutualTLSCertificate{}, errors.Wrap(err, errUnmarshalError) - } - - return accessMutualTLSCertificateDetailResponse.Result, nil -} - -// CreateAccessMutualTLSCertificate creates an account level Access TLS Mutual -// certificate. -// -// API reference: https://api.cloudflare.com/#access-mutual-tls-authentication-create-access-certificate -func (api *API) CreateAccessMutualTLSCertificate(ctx context.Context, accountID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { - return api.createAccessMutualTLSCertificate(ctx, accountID, certificate, AccountRouteRoot) -} - -// CreateZoneAccessMutualTLSCertificate creates a zone level Access TLS Mutual -// certificate. -// -// API reference: https://api.cloudflare.com/#zone-level-access-mutual-tls-authentication-create-access-certificate -func (api *API) CreateZoneAccessMutualTLSCertificate(ctx context.Context, zoneID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { - return api.createAccessMutualTLSCertificate(ctx, zoneID, certificate, ZoneRouteRoot) -} - -func (api *API) createAccessMutualTLSCertificate(ctx context.Context, id string, certificate AccessMutualTLSCertificate, routeRoot RouteRoot) (AccessMutualTLSCertificate, error) { - uri := fmt.Sprintf( - "/%s/%s/access/certificates", - routeRoot, - id, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, certificate) - if err != nil { - return AccessMutualTLSCertificate{}, err - } - - var accessMutualTLSCertificateDetailResponse AccessMutualTLSCertificateDetailResponse - err = json.Unmarshal(res, &accessMutualTLSCertificateDetailResponse) - if err != nil { - return AccessMutualTLSCertificate{}, errors.Wrap(err, errUnmarshalError) - } - - return accessMutualTLSCertificateDetailResponse.Result, nil -} - -// UpdateAccessMutualTLSCertificate updates an account level Access TLS Mutual -// certificate. -// -// API reference: https://api.cloudflare.com/#access-mutual-tls-authentication-update-access-certificate -func (api *API) UpdateAccessMutualTLSCertificate(ctx context.Context, accountID, certificateID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { - return api.updateAccessMutualTLSCertificate(ctx, accountID, certificateID, certificate, AccountRouteRoot) -} - -// UpdateZoneAccessMutualTLSCertificate updates a zone level Access TLS Mutual -// certificate. -// -// API reference: https://api.cloudflare.com/#zone-level-access-mutual-tls-authentication-update-access-certificate -func (api *API) UpdateZoneAccessMutualTLSCertificate(ctx context.Context, zoneID, certificateID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { - return api.updateAccessMutualTLSCertificate(ctx, zoneID, certificateID, certificate, ZoneRouteRoot) -} - -func (api *API) updateAccessMutualTLSCertificate(ctx context.Context, id string, certificateID string, certificate AccessMutualTLSCertificate, routeRoot RouteRoot) (AccessMutualTLSCertificate, error) { - uri := fmt.Sprintf( - "/%s/%s/access/certificates/%s", - routeRoot, - id, - certificateID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, certificate) - if err != nil { - return AccessMutualTLSCertificate{}, err - } - - var accessMutualTLSCertificateDetailResponse AccessMutualTLSCertificateDetailResponse - err = json.Unmarshal(res, &accessMutualTLSCertificateDetailResponse) - if err != nil { - return AccessMutualTLSCertificate{}, errors.Wrap(err, errUnmarshalError) - } - - return accessMutualTLSCertificateDetailResponse.Result, nil -} - -// DeleteAccessMutualTLSCertificate destroys an account level Access Mutual -// TLS certificate. -// -// API reference: https://api.cloudflare.com/#access-mutual-tls-authentication-update-access-certificate -func (api *API) DeleteAccessMutualTLSCertificate(ctx context.Context, accountID, certificateID string) error { - return api.deleteAccessMutualTLSCertificate(ctx, accountID, certificateID, AccountRouteRoot) -} - -// DeleteZoneAccessMutualTLSCertificate destroys a zone level Access Mutual TLS -// certificate. -// -// API reference: https://api.cloudflare.com/#zone-level-access-mutual-tls-authentication-update-access-certificate -func (api *API) DeleteZoneAccessMutualTLSCertificate(ctx context.Context, zoneID, certificateID string) error { - return api.deleteAccessMutualTLSCertificate(ctx, zoneID, certificateID, ZoneRouteRoot) -} - -func (api *API) deleteAccessMutualTLSCertificate(ctx context.Context, id, certificateID string, routeRoot RouteRoot) error { - uri := fmt.Sprintf( - "/%s/%s/access/certificates/%s", - routeRoot, - id, - certificateID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - var accessMutualTLSCertificateDetailResponse AccessMutualTLSCertificateDetailResponse - err = json.Unmarshal(res, &accessMutualTLSCertificateDetailResponse) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/access_organization.go b/vendor/github.com/cloudflare/cloudflare-go/access_organization.go deleted file mode 100644 index 774c3feb..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/access_organization.go +++ /dev/null @@ -1,137 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// AccessOrganization represents an Access organization. -type AccessOrganization struct { - CreatedAt *time.Time `json:"created_at"` - UpdatedAt *time.Time `json:"updated_at"` - Name string `json:"name"` - AuthDomain string `json:"auth_domain"` - LoginDesign AccessOrganizationLoginDesign `json:"login_design"` -} - -// AccessOrganizationLoginDesign represents the login design options. -type AccessOrganizationLoginDesign struct { - BackgroundColor string `json:"background_color"` - TextColor string `json:"text_color"` - LogoPath string `json:"logo_path"` -} - -// AccessOrganizationListResponse represents the response from the list -// access organization endpoint. -type AccessOrganizationListResponse struct { - Result AccessOrganization `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccessOrganizationDetailResponse is the API response, containing a -// single access organization. -type AccessOrganizationDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result AccessOrganization `json:"result"` -} - -// AccessOrganization returns the Access organisation details. -// -// API reference: https://api.cloudflare.com/#access-organizations-access-organization-details -func (api *API) AccessOrganization(ctx context.Context, accountID string) (AccessOrganization, ResultInfo, error) { - return api.accessOrganization(ctx, accountID, AccountRouteRoot) -} - -// ZoneLevelAccessOrganization returns the zone level Access organisation details. -// -// API reference: https://api.cloudflare.com/#zone-level-access-organizations-access-organization-details -func (api *API) ZoneLevelAccessOrganization(ctx context.Context, zoneID string) (AccessOrganization, ResultInfo, error) { - return api.accessOrganization(ctx, zoneID, ZoneRouteRoot) -} - -func (api *API) accessOrganization(ctx context.Context, id string, routeRoot RouteRoot) (AccessOrganization, ResultInfo, error) { - uri := fmt.Sprintf("/%s/%s/access/organizations", routeRoot, id) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return AccessOrganization{}, ResultInfo{}, err - } - - var accessOrganizationListResponse AccessOrganizationListResponse - err = json.Unmarshal(res, &accessOrganizationListResponse) - if err != nil { - return AccessOrganization{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return accessOrganizationListResponse.Result, accessOrganizationListResponse.ResultInfo, nil -} - -// CreateAccessOrganization creates the Access organisation details. -// -// API reference: https://api.cloudflare.com/#access-organizations-create-access-organization -func (api *API) CreateAccessOrganization(ctx context.Context, accountID string, accessOrganization AccessOrganization) (AccessOrganization, error) { - return api.createAccessOrganization(ctx, accountID, accessOrganization, AccountRouteRoot) -} - -// CreateZoneLevelAccessOrganization creates the zone level Access organisation details. -// -// API reference: https://api.cloudflare.com/#zone-level-access-organizations-create-access-organization -func (api *API) CreateZoneLevelAccessOrganization(ctx context.Context, zoneID string, accessOrganization AccessOrganization) (AccessOrganization, error) { - return api.createAccessOrganization(ctx, zoneID, accessOrganization, ZoneRouteRoot) -} - -func (api *API) createAccessOrganization(ctx context.Context, id string, accessOrganization AccessOrganization, routeRoot RouteRoot) (AccessOrganization, error) { - uri := fmt.Sprintf("/%s/%s/access/organizations", routeRoot, id) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, accessOrganization) - if err != nil { - return AccessOrganization{}, err - } - - var accessOrganizationDetailResponse AccessOrganizationDetailResponse - err = json.Unmarshal(res, &accessOrganizationDetailResponse) - if err != nil { - return AccessOrganization{}, errors.Wrap(err, errUnmarshalError) - } - - return accessOrganizationDetailResponse.Result, nil -} - -// UpdateAccessOrganization updates the Access organisation details. -// -// API reference: https://api.cloudflare.com/#access-organizations-update-access-organization -func (api *API) UpdateAccessOrganization(ctx context.Context, accountID string, accessOrganization AccessOrganization) (AccessOrganization, error) { - return api.updateAccessOrganization(ctx, accountID, accessOrganization, AccountRouteRoot) -} - -// UpdateZoneLevelAccessOrganization updates the zone level Access organisation details. -// -// API reference: https://api.cloudflare.com/#zone-level-access-organizations-update-access-organization -func (api *API) UpdateZoneLevelAccessOrganization(ctx context.Context, zoneID string, accessOrganization AccessOrganization) (AccessOrganization, error) { - return api.updateAccessOrganization(ctx, zoneID, accessOrganization, ZoneRouteRoot) -} - -func (api *API) updateAccessOrganization(ctx context.Context, id string, accessOrganization AccessOrganization, routeRoot RouteRoot) (AccessOrganization, error) { - uri := fmt.Sprintf("/%s/%s/access/organizations", routeRoot, id) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, accessOrganization) - if err != nil { - return AccessOrganization{}, err - } - - var accessOrganizationDetailResponse AccessOrganizationDetailResponse - err = json.Unmarshal(res, &accessOrganizationDetailResponse) - if err != nil { - return AccessOrganization{}, errors.Wrap(err, errUnmarshalError) - } - - return accessOrganizationDetailResponse.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/access_policy.go b/vendor/github.com/cloudflare/cloudflare-go/access_policy.go deleted file mode 100644 index 022ab449..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/access_policy.go +++ /dev/null @@ -1,256 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -type AccessApprovalGroup struct { - EmailListUuid string `json:"email_list_uuid,omitempty"` - EmailAddresses []string `json:"email_addresses,omitempty"` - ApprovalsNeeded int `json:"approvals_needed,omitempty"` -} - -// AccessPolicy defines a policy for allowing or disallowing access to -// one or more Access applications. -type AccessPolicy struct { - ID string `json:"id,omitempty"` - Precedence int `json:"precedence"` - Decision string `json:"decision"` - CreatedAt *time.Time `json:"created_at"` - UpdatedAt *time.Time `json:"updated_at"` - Name string `json:"name"` - - PurposeJustificationRequired *bool `json:"purpose_justification_required,omitempty"` - PurposeJustificationPrompt *string `json:"purpose_justification_prompt,omitempty"` - ApprovalRequired *bool `json:"approval_required,omitempty"` - ApprovalGroups []AccessApprovalGroup `json:"approval_groups"` - - // The include policy works like an OR logical operator. The user must - // satisfy one of the rules. - Include []interface{} `json:"include"` - - // The exclude policy works like a NOT logical operator. The user must - // not satisfy all of the rules in exclude. - Exclude []interface{} `json:"exclude"` - - // The require policy works like a AND logical operator. The user must - // satisfy all of the rules in require. - Require []interface{} `json:"require"` -} - -// AccessPolicyListResponse represents the response from the list -// access policies endpoint. -type AccessPolicyListResponse struct { - Result []AccessPolicy `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccessPolicyDetailResponse is the API response, containing a single -// access policy. -type AccessPolicyDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result AccessPolicy `json:"result"` -} - -// AccessPolicies returns all access policies for an access application. -// -// API reference: https://api.cloudflare.com/#access-policy-list-access-policies -func (api *API) AccessPolicies(ctx context.Context, accountID, applicationID string, pageOpts PaginationOptions) ([]AccessPolicy, ResultInfo, error) { - return api.accessPolicies(ctx, accountID, applicationID, pageOpts, AccountRouteRoot) -} - -// ZoneLevelAccessPolicies returns all zone level access policies for an access application. -// -// API reference: https://api.cloudflare.com/#zone-level-access-policy-list-access-policies -func (api *API) ZoneLevelAccessPolicies(ctx context.Context, zoneID, applicationID string, pageOpts PaginationOptions) ([]AccessPolicy, ResultInfo, error) { - return api.accessPolicies(ctx, zoneID, applicationID, pageOpts, ZoneRouteRoot) -} - -func (api *API) accessPolicies(ctx context.Context, id string, applicationID string, pageOpts PaginationOptions, routeRoot RouteRoot) ([]AccessPolicy, ResultInfo, error) { - v := url.Values{} - if pageOpts.PerPage > 0 { - v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) - } - if pageOpts.Page > 0 { - v.Set("page", strconv.Itoa(pageOpts.Page)) - } - - uri := fmt.Sprintf( - "/%s/%s/access/apps/%s/policies", - routeRoot, - id, - applicationID, - ) - - if len(v) > 0 { - uri = fmt.Sprintf("%s?%s", uri, v.Encode()) - } - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []AccessPolicy{}, ResultInfo{}, err - } - - var accessPolicyListResponse AccessPolicyListResponse - err = json.Unmarshal(res, &accessPolicyListResponse) - if err != nil { - return []AccessPolicy{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return accessPolicyListResponse.Result, accessPolicyListResponse.ResultInfo, nil -} - -// AccessPolicy returns a single policy based on the policy ID. -// -// API reference: https://api.cloudflare.com/#access-policy-access-policy-details -func (api *API) AccessPolicy(ctx context.Context, accountID, applicationID, policyID string) (AccessPolicy, error) { - return api.accessPolicy(ctx, accountID, applicationID, policyID, AccountRouteRoot) -} - -// ZoneLevelAccessPolicy returns a single zone level policy based on the policy ID. -// -// API reference: https://api.cloudflare.com/#zone-level-access-policy-access-policy-details -func (api *API) ZoneLevelAccessPolicy(ctx context.Context, zoneID, applicationID, policyID string) (AccessPolicy, error) { - return api.accessPolicy(ctx, zoneID, applicationID, policyID, ZoneRouteRoot) -} - -func (api *API) accessPolicy(ctx context.Context, id string, applicationID string, policyID string, routeRoot RouteRoot) (AccessPolicy, error) { - uri := fmt.Sprintf( - "/%s/%s/access/apps/%s/policies/%s", - routeRoot, - id, - applicationID, - policyID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return AccessPolicy{}, err - } - - var accessPolicyDetailResponse AccessPolicyDetailResponse - err = json.Unmarshal(res, &accessPolicyDetailResponse) - if err != nil { - return AccessPolicy{}, errors.Wrap(err, errUnmarshalError) - } - - return accessPolicyDetailResponse.Result, nil -} - -// CreateAccessPolicy creates a new access policy. -// -// API reference: https://api.cloudflare.com/#access-policy-create-access-policy -func (api *API) CreateAccessPolicy(ctx context.Context, accountID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { - return api.createAccessPolicy(ctx, accountID, applicationID, accessPolicy, AccountRouteRoot) -} - -// CreateZoneLevelAccessPolicy creates a new zone level access policy. -// -// API reference: https://api.cloudflare.com/#zone-level-access-policy-create-access-policy -func (api *API) CreateZoneLevelAccessPolicy(ctx context.Context, zoneID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { - return api.createAccessPolicy(ctx, zoneID, applicationID, accessPolicy, ZoneRouteRoot) -} - -func (api *API) createAccessPolicy(ctx context.Context, id, applicationID string, accessPolicy AccessPolicy, routeRoot RouteRoot) (AccessPolicy, error) { - uri := fmt.Sprintf( - "/%s/%s/access/apps/%s/policies", - routeRoot, - id, - applicationID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, accessPolicy) - if err != nil { - return AccessPolicy{}, err - } - - var accessPolicyDetailResponse AccessPolicyDetailResponse - err = json.Unmarshal(res, &accessPolicyDetailResponse) - if err != nil { - return AccessPolicy{}, errors.Wrap(err, errUnmarshalError) - } - - return accessPolicyDetailResponse.Result, nil -} - -// UpdateAccessPolicy updates an existing access policy. -// -// API reference: https://api.cloudflare.com/#access-policy-update-access-policy -func (api *API) UpdateAccessPolicy(ctx context.Context, accountID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { - return api.updateAccessPolicy(ctx, accountID, applicationID, accessPolicy, AccountRouteRoot) -} - -// UpdateZoneLevelAccessPolicy updates an existing zone level access policy. -// -// API reference: https://api.cloudflare.com/#zone-level-access-policy-update-access-policy -func (api *API) UpdateZoneLevelAccessPolicy(ctx context.Context, zoneID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { - return api.updateAccessPolicy(ctx, zoneID, applicationID, accessPolicy, ZoneRouteRoot) -} - -func (api *API) updateAccessPolicy(ctx context.Context, id, applicationID string, accessPolicy AccessPolicy, routeRoot RouteRoot) (AccessPolicy, error) { - if accessPolicy.ID == "" { - return AccessPolicy{}, errors.Errorf("access policy ID cannot be empty") - } - uri := fmt.Sprintf( - "/%s/%s/access/apps/%s/policies/%s", - routeRoot, - id, - applicationID, - accessPolicy.ID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, accessPolicy) - if err != nil { - return AccessPolicy{}, err - } - - var accessPolicyDetailResponse AccessPolicyDetailResponse - err = json.Unmarshal(res, &accessPolicyDetailResponse) - if err != nil { - return AccessPolicy{}, errors.Wrap(err, errUnmarshalError) - } - - return accessPolicyDetailResponse.Result, nil -} - -// DeleteAccessPolicy deletes an access policy. -// -// API reference: https://api.cloudflare.com/#access-policy-update-access-policy -func (api *API) DeleteAccessPolicy(ctx context.Context, accountID, applicationID, accessPolicyID string) error { - return api.deleteAccessPolicy(ctx, accountID, applicationID, accessPolicyID, AccountRouteRoot) -} - -// DeleteZoneLevelAccessPolicy deletes a zone level access policy. -// -// API reference: https://api.cloudflare.com/#zone-level-access-policy-delete-access-policy -func (api *API) DeleteZoneLevelAccessPolicy(ctx context.Context, zoneID, applicationID, accessPolicyID string) error { - return api.deleteAccessPolicy(ctx, zoneID, applicationID, accessPolicyID, ZoneRouteRoot) -} - -func (api *API) deleteAccessPolicy(ctx context.Context, id, applicationID, accessPolicyID string, routeRoot RouteRoot) error { - uri := fmt.Sprintf( - "/%s/%s/access/apps/%s/policies/%s", - routeRoot, - id, - applicationID, - accessPolicyID, - ) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/access_service_tokens.go b/vendor/github.com/cloudflare/cloudflare-go/access_service_tokens.go deleted file mode 100644 index 110c1dbe..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/access_service_tokens.go +++ /dev/null @@ -1,217 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// AccessServiceToken represents an Access Service Token. -type AccessServiceToken struct { - ClientID string `json:"client_id"` - CreatedAt *time.Time `json:"created_at"` - ExpiresAt *time.Time `json:"expires_at"` - ID string `json:"id"` - Name string `json:"name"` - UpdatedAt *time.Time `json:"updated_at"` -} - -// AccessServiceTokenUpdateResponse represents the response from the API -// when a new Service Token is updated. This base struct is also used in the -// Create as they are very similar responses. -type AccessServiceTokenUpdateResponse struct { - CreatedAt *time.Time `json:"created_at"` - UpdatedAt *time.Time `json:"updated_at"` - ExpiresAt *time.Time `json:"expires_at"` - ID string `json:"id"` - Name string `json:"name"` - ClientID string `json:"client_id"` -} - -// AccessServiceTokenCreateResponse is the same API response as the Update -// operation with the exception that the `ClientSecret` is present in a -// Create operation. -type AccessServiceTokenCreateResponse struct { - CreatedAt *time.Time `json:"created_at"` - UpdatedAt *time.Time `json:"updated_at"` - ExpiresAt *time.Time `json:"expires_at"` - ID string `json:"id"` - Name string `json:"name"` - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` -} - -// AccessServiceTokensListResponse represents the response from the list -// Access Service Tokens endpoint. -type AccessServiceTokensListResponse struct { - Result []AccessServiceToken `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccessServiceTokensDetailResponse is the API response, containing a single -// Access Service Token. -type AccessServiceTokensDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result AccessServiceToken `json:"result"` -} - -// AccessServiceTokensCreationDetailResponse is the API response, containing a -// single Access Service Token. -type AccessServiceTokensCreationDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result AccessServiceTokenCreateResponse `json:"result"` -} - -// AccessServiceTokensUpdateDetailResponse is the API response, containing a -// single Access Service Token. -type AccessServiceTokensUpdateDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result AccessServiceTokenUpdateResponse `json:"result"` -} - -// AccessServiceTokens returns all Access Service Tokens for an account. -// -// API reference: https://api.cloudflare.com/#access-service-tokens-list-access-service-tokens -func (api *API) AccessServiceTokens(ctx context.Context, accountID string) ([]AccessServiceToken, ResultInfo, error) { - return api.accessServiceTokens(ctx, accountID, AccountRouteRoot) -} - -// ZoneLevelAccessServiceTokens returns all Access Service Tokens for a zone. -// -// API reference: https://api.cloudflare.com/#zone-level-access-service-tokens-list-access-service-tokens -func (api *API) ZoneLevelAccessServiceTokens(ctx context.Context, zoneID string) ([]AccessServiceToken, ResultInfo, error) { - return api.accessServiceTokens(ctx, zoneID, ZoneRouteRoot) -} - -func (api *API) accessServiceTokens(ctx context.Context, id string, routeRoot RouteRoot) ([]AccessServiceToken, ResultInfo, error) { - uri := fmt.Sprintf("/%s/%s/access/service_tokens", routeRoot, id) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []AccessServiceToken{}, ResultInfo{}, err - } - - var accessServiceTokensListResponse AccessServiceTokensListResponse - err = json.Unmarshal(res, &accessServiceTokensListResponse) - if err != nil { - return []AccessServiceToken{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return accessServiceTokensListResponse.Result, accessServiceTokensListResponse.ResultInfo, nil -} - -// CreateAccessServiceToken creates a new Access Service Token for an account. -// -// API reference: https://api.cloudflare.com/#access-service-tokens-create-access-service-token -func (api *API) CreateAccessServiceToken(ctx context.Context, accountID, name string) (AccessServiceTokenCreateResponse, error) { - return api.createAccessServiceToken(ctx, accountID, name, AccountRouteRoot) -} - -// CreateZoneLevelAccessServiceToken creates a new Access Service Token for a zone. -// -// API reference: https://api.cloudflare.com/#zone-level-access-service-tokens-create-access-service-token -func (api *API) CreateZoneLevelAccessServiceToken(ctx context.Context, zoneID, name string) (AccessServiceTokenCreateResponse, error) { - return api.createAccessServiceToken(ctx, zoneID, name, ZoneRouteRoot) -} - -func (api *API) createAccessServiceToken(ctx context.Context, id, name string, routeRoot RouteRoot) (AccessServiceTokenCreateResponse, error) { - uri := fmt.Sprintf("/%s/%s/access/service_tokens", routeRoot, id) - marshalledName, _ := json.Marshal(struct { - Name string `json:"name"` - }{name}) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, marshalledName) - - if err != nil { - return AccessServiceTokenCreateResponse{}, err - } - - var accessServiceTokenCreation AccessServiceTokensCreationDetailResponse - err = json.Unmarshal(res, &accessServiceTokenCreation) - if err != nil { - return AccessServiceTokenCreateResponse{}, errors.Wrap(err, errUnmarshalError) - } - - return accessServiceTokenCreation.Result, nil -} - -// UpdateAccessServiceToken updates an existing Access Service Token for an -// account. -// -// API reference: https://api.cloudflare.com/#access-service-tokens-update-access-service-token -func (api *API) UpdateAccessServiceToken(ctx context.Context, accountID, uuid, name string) (AccessServiceTokenUpdateResponse, error) { - return api.updateAccessServiceToken(ctx, accountID, uuid, name, AccountRouteRoot) -} - -// UpdateZoneLevelAccessServiceToken updates an existing Access Service Token for a -// zone. -// -// API reference: https://api.cloudflare.com/#zone-level-access-service-tokens-update-access-service-token -func (api *API) UpdateZoneLevelAccessServiceToken(ctx context.Context, zoneID, uuid, name string) (AccessServiceTokenUpdateResponse, error) { - return api.updateAccessServiceToken(ctx, zoneID, uuid, name, ZoneRouteRoot) -} - -func (api *API) updateAccessServiceToken(ctx context.Context, id, uuid, name string, routeRoot RouteRoot) (AccessServiceTokenUpdateResponse, error) { - uri := fmt.Sprintf("/%s/%s/access/service_tokens/%s", routeRoot, id, uuid) - - marshalledName, _ := json.Marshal(struct { - Name string `json:"name"` - }{name}) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, marshalledName) - if err != nil { - return AccessServiceTokenUpdateResponse{}, err - } - - var accessServiceTokenUpdate AccessServiceTokensUpdateDetailResponse - err = json.Unmarshal(res, &accessServiceTokenUpdate) - if err != nil { - return AccessServiceTokenUpdateResponse{}, errors.Wrap(err, errUnmarshalError) - } - - return accessServiceTokenUpdate.Result, nil -} - -// DeleteAccessServiceToken removes an existing Access Service Token for an -// account. -// -// API reference: https://api.cloudflare.com/#access-service-tokens-delete-access-service-token -func (api *API) DeleteAccessServiceToken(ctx context.Context, accountID, uuid string) (AccessServiceTokenUpdateResponse, error) { - return api.deleteAccessServiceToken(ctx, accountID, uuid, AccountRouteRoot) -} - -// DeleteZoneLevelAccessServiceToken removes an existing Access Service Token for a -// zone. -// -// API reference: https://api.cloudflare.com/#zone-level-access-service-tokens-delete-access-service-token -func (api *API) DeleteZoneLevelAccessServiceToken(ctx context.Context, zoneID, uuid string) (AccessServiceTokenUpdateResponse, error) { - return api.deleteAccessServiceToken(ctx, zoneID, uuid, ZoneRouteRoot) -} - -func (api *API) deleteAccessServiceToken(ctx context.Context, id, uuid string, routeRoot RouteRoot) (AccessServiceTokenUpdateResponse, error) { - uri := fmt.Sprintf("/%s/%s/access/service_tokens/%s", routeRoot, id, uuid) - - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return AccessServiceTokenUpdateResponse{}, err - } - - var accessServiceTokenUpdate AccessServiceTokensUpdateDetailResponse - err = json.Unmarshal(res, &accessServiceTokenUpdate) - if err != nil { - return AccessServiceTokenUpdateResponse{}, errors.Wrap(err, errUnmarshalError) - } - - return accessServiceTokenUpdate.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/account_members.go b/vendor/github.com/cloudflare/cloudflare-go/account_members.go deleted file mode 100644 index ba2c5544..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/account_members.go +++ /dev/null @@ -1,200 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// AccountMember is the definition of a member of an account. -type AccountMember struct { - ID string `json:"id"` - Code string `json:"code"` - User AccountMemberUserDetails `json:"user"` - Status string `json:"status"` - Roles []AccountRole `json:"roles"` -} - -// AccountMemberUserDetails outlines all the personal information about -// a member. -type AccountMemberUserDetails struct { - ID string `json:"id"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - Email string `json:"email"` - TwoFactorAuthenticationEnabled bool `json:"two_factor_authentication_enabled"` -} - -// AccountMembersListResponse represents the response from the list -// account members endpoint. -type AccountMembersListResponse struct { - Result []AccountMember `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccountMemberDetailResponse is the API response, containing a single -// account member. -type AccountMemberDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result AccountMember `json:"result"` -} - -// AccountMemberInvitation represents the invitation for a new member to -// the account. -type AccountMemberInvitation struct { - Email string `json:"email"` - Roles []string `json:"roles"` - Status string `json:"status,omitempty"` -} - -// AccountMembers returns all members of an account. -// -// API reference: https://api.cloudflare.com/#accounts-list-accounts -func (api *API) AccountMembers(ctx context.Context, accountID string, pageOpts PaginationOptions) ([]AccountMember, ResultInfo, error) { - if accountID == "" { - return []AccountMember{}, ResultInfo{}, errors.New(errMissingAccountID) - } - - v := url.Values{} - if pageOpts.PerPage > 0 { - v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) - } - if pageOpts.Page > 0 { - v.Set("page", strconv.Itoa(pageOpts.Page)) - } - - uri := fmt.Sprintf("/accounts/%s/members", accountID) - if len(v) > 0 { - uri = fmt.Sprintf("%s?%s", uri, v.Encode()) - } - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []AccountMember{}, ResultInfo{}, err - } - - var accountMemberListresponse AccountMembersListResponse - err = json.Unmarshal(res, &accountMemberListresponse) - if err != nil { - return []AccountMember{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return accountMemberListresponse.Result, accountMemberListresponse.ResultInfo, nil -} - -// CreateAccountMemberWithStatus invites a new member to join an account, allowing setting the status. -// -// Refer to the API reference for valid statuses. -// -// API reference: https://api.cloudflare.com/#account-members-add-member -func (api *API) CreateAccountMemberWithStatus(ctx context.Context, accountID string, emailAddress string, roles []string, status string) (AccountMember, error) { - if accountID == "" { - return AccountMember{}, errors.New(errMissingAccountID) - } - - uri := fmt.Sprintf("/accounts/%s/members", accountID) - - var newMember = AccountMemberInvitation{ - Email: emailAddress, - Roles: roles, - Status: status, - } - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, newMember) - if err != nil { - return AccountMember{}, err - } - - var accountMemberListResponse AccountMemberDetailResponse - err = json.Unmarshal(res, &accountMemberListResponse) - if err != nil { - return AccountMember{}, errors.Wrap(err, errUnmarshalError) - } - - return accountMemberListResponse.Result, nil -} - -// CreateAccountMember invites a new member to join an account. -// The member will be placed into "pending" status and receive an email confirmation. -// -// API reference: https://api.cloudflare.com/#account-members-add-member -func (api *API) CreateAccountMember(ctx context.Context, accountID string, emailAddress string, roles []string) (AccountMember, error) { - return api.CreateAccountMemberWithStatus(ctx, accountID, emailAddress, roles, "") -} - -// DeleteAccountMember removes a member from an account. -// -// API reference: https://api.cloudflare.com/#account-members-remove-member -func (api *API) DeleteAccountMember(ctx context.Context, accountID string, userID string) error { - if accountID == "" { - return errors.New(errMissingAccountID) - } - - uri := fmt.Sprintf("/accounts/%s/members/%s", accountID, userID) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} - -// UpdateAccountMember modifies an existing account member. -// -// API reference: https://api.cloudflare.com/#account-members-update-member -func (api *API) UpdateAccountMember(ctx context.Context, accountID string, userID string, member AccountMember) (AccountMember, error) { - if accountID == "" { - return AccountMember{}, errors.New(errMissingAccountID) - } - - uri := fmt.Sprintf("/accounts/%s/members/%s", accountID, userID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, member) - if err != nil { - return AccountMember{}, err - } - - var accountMemberListResponse AccountMemberDetailResponse - err = json.Unmarshal(res, &accountMemberListResponse) - if err != nil { - return AccountMember{}, errors.Wrap(err, errUnmarshalError) - } - - return accountMemberListResponse.Result, nil -} - -// AccountMember returns details of a single account member. -// -// API reference: https://api.cloudflare.com/#account-members-member-details -func (api *API) AccountMember(ctx context.Context, accountID string, memberID string) (AccountMember, error) { - if accountID == "" { - return AccountMember{}, errors.New(errMissingAccountID) - } - - uri := fmt.Sprintf( - "/accounts/%s/members/%s", - accountID, - memberID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return AccountMember{}, err - } - - var accountMemberResponse AccountMemberDetailResponse - err = json.Unmarshal(res, &accountMemberResponse) - if err != nil { - return AccountMember{}, errors.Wrap(err, errUnmarshalError) - } - - return accountMemberResponse.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/account_roles.go b/vendor/github.com/cloudflare/cloudflare-go/account_roles.go deleted file mode 100644 index 0a0662ec..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/account_roles.go +++ /dev/null @@ -1,82 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -// AccountRole defines the roles that a member can have attached. -type AccountRole struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Permissions map[string]AccountRolePermission `json:"permissions"` -} - -// AccountRolePermission is the shared structure for all permissions -// that can be assigned to a member. -type AccountRolePermission struct { - Read bool `json:"read"` - Edit bool `json:"edit"` -} - -// AccountRolesListResponse represents the list response from the -// account roles. -type AccountRolesListResponse struct { - Result []AccountRole `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccountRoleDetailResponse is the API response, containing a single -// account role. -type AccountRoleDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result AccountRole `json:"result"` -} - -// AccountRoles returns all roles of an account. -// -// API reference: https://api.cloudflare.com/#account-roles-list-roles -func (api *API) AccountRoles(ctx context.Context, accountID string) ([]AccountRole, error) { - uri := fmt.Sprintf("/accounts/%s/roles", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []AccountRole{}, err - } - - var accountRolesListResponse AccountRolesListResponse - err = json.Unmarshal(res, &accountRolesListResponse) - if err != nil { - return []AccountRole{}, errors.Wrap(err, errUnmarshalError) - } - - return accountRolesListResponse.Result, nil -} - -// AccountRole returns the details of a single account role. -// -// API reference: https://api.cloudflare.com/#account-roles-role-details -func (api *API) AccountRole(ctx context.Context, accountID string, roleID string) (AccountRole, error) { - uri := fmt.Sprintf("/accounts/%s/roles/%s", accountID, roleID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return AccountRole{}, err - } - - var accountRole AccountRoleDetailResponse - err = json.Unmarshal(res, &accountRole) - if err != nil { - return AccountRole{}, errors.Wrap(err, errUnmarshalError) - } - - return accountRole.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/accounts.go b/vendor/github.com/cloudflare/cloudflare-go/accounts.go deleted file mode 100644 index b4f9ce8f..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/accounts.go +++ /dev/null @@ -1,158 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// AccountSettings outlines the available options for an account. -type AccountSettings struct { - EnforceTwoFactor bool `json:"enforce_twofactor"` -} - -// Account represents the root object that owns resources. -type Account struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` - Settings *AccountSettings `json:"settings,omitempty"` -} - -// AccountResponse represents the response from the accounts endpoint for a -// single account ID. -type AccountResponse struct { - Result Account `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccountListResponse represents the response from the list accounts endpoint. -type AccountListResponse struct { - Result []Account `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccountDetailResponse is the API response, containing a single Account. -type AccountDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result Account `json:"result"` -} - -// Accounts returns all accounts the logged in user has access to. -// -// API reference: https://api.cloudflare.com/#accounts-list-accounts -func (api *API) Accounts(ctx context.Context, pageOpts PaginationOptions) ([]Account, ResultInfo, error) { - v := url.Values{} - if pageOpts.PerPage > 0 { - v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) - } - if pageOpts.Page > 0 { - v.Set("page", strconv.Itoa(pageOpts.Page)) - } - - uri := "/accounts" - if len(v) > 0 { - uri = fmt.Sprintf("%s?%s", uri, v.Encode()) - } - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []Account{}, ResultInfo{}, err - } - - var accListResponse AccountListResponse - err = json.Unmarshal(res, &accListResponse) - if err != nil { - return []Account{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - return accListResponse.Result, accListResponse.ResultInfo, nil -} - -// Account returns a single account based on the ID. -// -// API reference: https://api.cloudflare.com/#accounts-account-details -func (api *API) Account(ctx context.Context, accountID string) (Account, ResultInfo, error) { - uri := fmt.Sprintf("/accounts/%s", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return Account{}, ResultInfo{}, err - } - - var accResponse AccountResponse - err = json.Unmarshal(res, &accResponse) - if err != nil { - return Account{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return accResponse.Result, accResponse.ResultInfo, nil -} - -// UpdateAccount allows management of an account using the account ID. -// -// API reference: https://api.cloudflare.com/#accounts-update-account -func (api *API) UpdateAccount(ctx context.Context, accountID string, account Account) (Account, error) { - uri := fmt.Sprintf("/accounts/%s", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, account) - if err != nil { - return Account{}, err - } - - var a AccountDetailResponse - err = json.Unmarshal(res, &a) - if err != nil { - return Account{}, errors.Wrap(err, errUnmarshalError) - } - - return a.Result, nil -} - -// CreateAccount creates a new account. Note: This requires the Tenant -// entitlement. -// -// API reference: https://developers.cloudflare.com/tenant/tutorial/provisioning-resources#creating-an-account -func (api *API) CreateAccount(ctx context.Context, account Account) (Account, error) { - uri := "/accounts" - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, account) - if err != nil { - return Account{}, err - } - - var a AccountDetailResponse - err = json.Unmarshal(res, &a) - if err != nil { - return Account{}, errors.Wrap(err, errUnmarshalError) - } - - return a.Result, nil -} - -// DeleteAccount removes an account. Note: This requires the Tenant -// entitlement. -// -// API reference: https://developers.cloudflare.com/tenant/tutorial/provisioning-resources#optional-deleting-accounts -func (api *API) DeleteAccount(ctx context.Context, accountID string) error { - if accountID == "" { - return errors.New(errMissingAccountID) - } - - uri := fmt.Sprintf("/accounts/%s", accountID) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/api_token.go b/vendor/github.com/cloudflare/cloudflare-go/api_token.go deleted file mode 100644 index 0eb9bf7a..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/api_token.go +++ /dev/null @@ -1,239 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// APIToken is the full API token. -type APIToken struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Status string `json:"status,omitempty"` - IssuedOn *time.Time `json:"issued_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - NotBefore *time.Time `json:"not_before,omitempty"` - ExpiresOn *time.Time `json:"expires_on,omitempty"` - Policies []APITokenPolicies `json:"policies"` - Condition *APITokenCondition `json:"condition,omitempty"` - Value string `json:"value,omitempty"` -} - -// APITokenPermissionGroups is the permission groups associated with API tokens. -type APITokenPermissionGroups struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Scopes []string `json:"scopes,omitempty"` -} - -// APITokenPolicies are policies attached to an API token. -type APITokenPolicies struct { - ID string `json:"id,omitempty"` - Effect string `json:"effect"` - Resources map[string]interface{} `json:"resources"` - PermissionGroups []APITokenPermissionGroups `json:"permission_groups"` -} - -// APITokenRequestIPCondition is the struct for adding an IP restriction to an -// API token. -type APITokenRequestIPCondition struct { - In []string `json:"in,omitempty"` - NotIn []string `json:"not_in,omitempty"` -} - -// APITokenCondition is the outer structure for request conditions (currently -// only IPs). -type APITokenCondition struct { - RequestIP *APITokenRequestIPCondition `json:"request.ip,omitempty"` -} - -// APITokenResponse is the API response for a single API token. -type APITokenResponse struct { - Response - Result APIToken `json:"result"` -} - -// APITokenListResponse is the API response for multiple API tokens. -type APITokenListResponse struct { - Response - Result []APIToken `json:"result"` -} - -// APITokenRollResponse is the API response when rolling the token. -type APITokenRollResponse struct { - Response - Result string `json:"result"` -} - -// APITokenVerifyResponse is the API response for verifying a token. -type APITokenVerifyResponse struct { - Response - Result APITokenVerifyBody `json:"result"` -} - -// APITokenPermissionGroupsResponse is the API response for the available -// permission groups. -type APITokenPermissionGroupsResponse struct { - Response - Result []APITokenPermissionGroups `json:"result"` -} - -// APITokenVerifyBody is the API body for verifying a token. -type APITokenVerifyBody struct { - ID string `json:"id"` - Status string `json:"status"` - NotBefore time.Time `json:"not_before"` - ExpiresOn time.Time `json:"expires_on"` -} - -// GetAPIToken returns a single API token based on the ID. -// -// API reference: https://api.cloudflare.com/#user-api-tokens-token-details -func (api *API) GetAPIToken(ctx context.Context, tokenID string) (APIToken, error) { - uri := fmt.Sprintf("/user/tokens/%s", tokenID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return APIToken{}, err - } - - var apiTokenResponse APITokenResponse - err = json.Unmarshal(res, &apiTokenResponse) - if err != nil { - return APIToken{}, errors.Wrap(err, errUnmarshalError) - } - - return apiTokenResponse.Result, nil -} - -// APITokens returns all available API tokens. -// -// API reference: https://api.cloudflare.com/#user-api-tokens-list-tokens -func (api *API) APITokens(ctx context.Context) ([]APIToken, error) { - res, err := api.makeRequestContext(ctx, http.MethodGet, "/user/tokens", nil) - if err != nil { - return []APIToken{}, err - } - - var apiTokenListResponse APITokenListResponse - err = json.Unmarshal(res, &apiTokenListResponse) - if err != nil { - return []APIToken{}, errors.Wrap(err, errUnmarshalError) - } - - return apiTokenListResponse.Result, nil -} - -// CreateAPIToken creates a new token. Returns the API token that has been -// generated. -// -// The token value itself is only shown once (post create) and will present as -// `Value` from this method. If you fail to capture it at this point, you will -// need to roll the token in order to get a new value. -// -// API reference: https://api.cloudflare.com/#user-api-tokens-create-token -func (api *API) CreateAPIToken(ctx context.Context, token APIToken) (APIToken, error) { - res, err := api.makeRequestContext(ctx, http.MethodPost, "/user/tokens", token) - if err != nil { - return APIToken{}, err - } - - var createTokenAPIResponse APITokenResponse - err = json.Unmarshal(res, &createTokenAPIResponse) - if err != nil { - return APIToken{}, errors.Wrap(err, errUnmarshalError) - } - - return createTokenAPIResponse.Result, nil -} - -// UpdateAPIToken updates an existing API token. -// -// API reference: https://api.cloudflare.com/#user-api-tokens-update-token -func (api *API) UpdateAPIToken(ctx context.Context, tokenID string, token APIToken) (APIToken, error) { - res, err := api.makeRequestContext(ctx, http.MethodPut, "/user/tokens/"+tokenID, token) - if err != nil { - return APIToken{}, err - } - - var updatedTokenResponse APITokenResponse - err = json.Unmarshal(res, &updatedTokenResponse) - if err != nil { - return APIToken{}, errors.Wrap(err, errUnmarshalError) - } - - return updatedTokenResponse.Result, nil -} - -// RollAPIToken rolls the credential associated with the token. -// -// API reference: https://api.cloudflare.com/#user-api-tokens-roll-token -func (api *API) RollAPIToken(ctx context.Context, tokenID string) (string, error) { - uri := fmt.Sprintf("/user/tokens/%s/value", tokenID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, nil) - if err != nil { - return "", err - } - - var apiTokenRollResponse APITokenRollResponse - err = json.Unmarshal(res, &apiTokenRollResponse) - if err != nil { - return "", errors.Wrap(err, errUnmarshalError) - } - - return apiTokenRollResponse.Result, nil -} - -// VerifyAPIToken tests the validity of the token. -// -// API reference: https://api.cloudflare.com/#user-api-tokens-verify-token -func (api *API) VerifyAPIToken(ctx context.Context) (APITokenVerifyBody, error) { - res, err := api.makeRequestContext(ctx, http.MethodGet, "/user/tokens/verify", nil) - if err != nil { - return APITokenVerifyBody{}, err - } - - var apiTokenVerifyResponse APITokenVerifyResponse - err = json.Unmarshal(res, &apiTokenVerifyResponse) - if err != nil { - return APITokenVerifyBody{}, errors.Wrap(err, errUnmarshalError) - } - - return apiTokenVerifyResponse.Result, nil -} - -// DeleteAPIToken deletes a single API token. -// -// API reference: https://api.cloudflare.com/#user-api-tokens-delete-token -func (api *API) DeleteAPIToken(ctx context.Context, tokenID string) error { - _, err := api.makeRequestContext(ctx, http.MethodDelete, "/user/tokens/"+tokenID, nil) - if err != nil { - return err - } - - return nil -} - -// ListAPITokensPermissionGroups returns all available API token permission groups. -// -// API reference: https://api.cloudflare.com/#permission-groups-list-permission-groups -func (api *API) ListAPITokensPermissionGroups(ctx context.Context) ([]APITokenPermissionGroups, error) { - var r APITokenPermissionGroupsResponse - res, err := api.makeRequestContext(ctx, http.MethodGet, "/user/tokens/permission_groups", nil) - if err != nil { - return []APITokenPermissionGroups{}, err - } - - err = json.Unmarshal(res, &r) - if err != nil { - return []APITokenPermissionGroups{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/argo.go b/vendor/github.com/cloudflare/cloudflare-go/argo.go deleted file mode 100644 index 24b57516..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/argo.go +++ /dev/null @@ -1,122 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -var validSettingValues = []string{"on", "off"} - -// ArgoFeatureSetting is the structure of the API object for the -// argo smart routing and tiered caching settings. -type ArgoFeatureSetting struct { - Editable bool `json:"editable,omitempty"` - ID string `json:"id,omitempty"` - ModifiedOn time.Time `json:"modified_on,omitempty"` - Value string `json:"value"` -} - -// ArgoDetailsResponse is the API response for the argo smart routing -// and tiered caching response. -type ArgoDetailsResponse struct { - Result ArgoFeatureSetting `json:"result"` - Response -} - -// ArgoSmartRouting returns the current settings for smart routing. -// -// API reference: https://api.cloudflare.com/#argo-smart-routing-get-argo-smart-routing-setting -func (api *API) ArgoSmartRouting(ctx context.Context, zoneID string) (ArgoFeatureSetting, error) { - uri := fmt.Sprintf("/zones/%s/argo/smart_routing", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return ArgoFeatureSetting{}, err - } - - var argoDetailsResponse ArgoDetailsResponse - err = json.Unmarshal(res, &argoDetailsResponse) - if err != nil { - return ArgoFeatureSetting{}, errors.Wrap(err, errUnmarshalError) - } - return argoDetailsResponse.Result, nil -} - -// UpdateArgoSmartRouting updates the setting for smart routing. -// -// API reference: https://api.cloudflare.com/#argo-smart-routing-patch-argo-smart-routing-setting -func (api *API) UpdateArgoSmartRouting(ctx context.Context, zoneID, settingValue string) (ArgoFeatureSetting, error) { - if !contains(validSettingValues, settingValue) { - return ArgoFeatureSetting{}, errors.New(fmt.Sprintf("invalid setting value '%s'. must be 'on' or 'off'", settingValue)) - } - - uri := fmt.Sprintf("/zones/%s/argo/smart_routing", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, ArgoFeatureSetting{Value: settingValue}) - if err != nil { - return ArgoFeatureSetting{}, err - } - - var argoDetailsResponse ArgoDetailsResponse - err = json.Unmarshal(res, &argoDetailsResponse) - if err != nil { - return ArgoFeatureSetting{}, errors.Wrap(err, errUnmarshalError) - } - return argoDetailsResponse.Result, nil -} - -// ArgoTieredCaching returns the current settings for tiered caching. -// -// API reference: TBA -func (api *API) ArgoTieredCaching(ctx context.Context, zoneID string) (ArgoFeatureSetting, error) { - uri := fmt.Sprintf("/zones/%s/argo/tiered_caching", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return ArgoFeatureSetting{}, err - } - - var argoDetailsResponse ArgoDetailsResponse - err = json.Unmarshal(res, &argoDetailsResponse) - if err != nil { - return ArgoFeatureSetting{}, errors.Wrap(err, errUnmarshalError) - } - return argoDetailsResponse.Result, nil -} - -// UpdateArgoTieredCaching updates the setting for tiered caching. -// -// API reference: TBA -func (api *API) UpdateArgoTieredCaching(ctx context.Context, zoneID, settingValue string) (ArgoFeatureSetting, error) { - if !contains(validSettingValues, settingValue) { - return ArgoFeatureSetting{}, errors.New(fmt.Sprintf("invalid setting value '%s'. must be 'on' or 'off'", settingValue)) - } - - uri := fmt.Sprintf("/zones/%s/argo/tiered_caching", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, ArgoFeatureSetting{Value: settingValue}) - if err != nil { - return ArgoFeatureSetting{}, err - } - - var argoDetailsResponse ArgoDetailsResponse - err = json.Unmarshal(res, &argoDetailsResponse) - if err != nil { - return ArgoFeatureSetting{}, errors.Wrap(err, errUnmarshalError) - } - return argoDetailsResponse.Result, nil -} - -func contains(s []string, e string) bool { - for _, a := range s { - if a == e { - return true - } - } - return false -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/argo_tunnel.go b/vendor/github.com/cloudflare/cloudflare-go/argo_tunnel.go deleted file mode 100644 index 4ad69ca6..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/argo_tunnel.go +++ /dev/null @@ -1,153 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// ArgoTunnel is the struct definition of a tunnel. -type ArgoTunnel struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Secret string `json:"tunnel_secret,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - DeletedAt *time.Time `json:"deleted_at,omitempty"` - Connections []ArgoTunnelConnection `json:"connections,omitempty"` -} - -// ArgoTunnelConnection represents the connections associated with a tunnel. -type ArgoTunnelConnection struct { - ColoName string `json:"colo_name"` - UUID string `json:"uuid"` - IsPendingReconnect bool `json:"is_pending_reconnect"` -} - -// ArgoTunnelsDetailResponse is used for representing the API response payload for -// multiple tunnels. -type ArgoTunnelsDetailResponse struct { - Result []ArgoTunnel `json:"result"` - Response -} - -// ArgoTunnelDetailResponse is used for representing the API response payload for -// a single tunnel. -type ArgoTunnelDetailResponse struct { - Result ArgoTunnel `json:"result"` - Response -} - -// ArgoTunnels lists all tunnels. -// -// API reference: https://api.cloudflare.com/#argo-tunnel-list-argo-tunnels -func (api *API) ArgoTunnels(ctx context.Context, accountID string) ([]ArgoTunnel, error) { - uri := fmt.Sprintf("/accounts/%s/tunnels", accountID) - - res, err := api.makeRequestContextWithHeaders(ctx, http.MethodGet, uri, nil, argoV1Header()) - if err != nil { - return []ArgoTunnel{}, err - } - - var argoDetailsResponse ArgoTunnelsDetailResponse - err = json.Unmarshal(res, &argoDetailsResponse) - if err != nil { - return []ArgoTunnel{}, errors.Wrap(err, errUnmarshalError) - } - return argoDetailsResponse.Result, nil -} - -// ArgoTunnel returns a single Argo tunnel. -// -// API reference: https://api.cloudflare.com/#argo-tunnel-get-argo-tunnel -func (api *API) ArgoTunnel(ctx context.Context, accountID, tunnelUUID string) (ArgoTunnel, error) { - uri := fmt.Sprintf("/accounts/%s/tunnels/%s", accountID, tunnelUUID) - - res, err := api.makeRequestContextWithHeaders(ctx, http.MethodGet, uri, nil, argoV1Header()) - if err != nil { - return ArgoTunnel{}, err - } - - var argoDetailsResponse ArgoTunnelDetailResponse - err = json.Unmarshal(res, &argoDetailsResponse) - if err != nil { - return ArgoTunnel{}, errors.Wrap(err, errUnmarshalError) - } - return argoDetailsResponse.Result, nil -} - -// CreateArgoTunnel creates a new tunnel for the account. -// -// API reference: https://api.cloudflare.com/#argo-tunnel-create-argo-tunnel -func (api *API) CreateArgoTunnel(ctx context.Context, accountID, name, secret string) (ArgoTunnel, error) { - uri := fmt.Sprintf("/accounts/%s/tunnels", accountID) - - tunnel := ArgoTunnel{Name: name, Secret: secret} - - res, err := api.makeRequestContextWithHeaders(ctx, http.MethodPost, uri, tunnel, argoV1Header()) - if err != nil { - return ArgoTunnel{}, err - } - - var argoDetailsResponse ArgoTunnelDetailResponse - err = json.Unmarshal(res, &argoDetailsResponse) - if err != nil { - return ArgoTunnel{}, errors.Wrap(err, errUnmarshalError) - } - - return argoDetailsResponse.Result, nil -} - -// DeleteArgoTunnel removes a single Argo tunnel. -// -// API reference: https://api.cloudflare.com/#argo-tunnel-delete-argo-tunnel -func (api *API) DeleteArgoTunnel(ctx context.Context, accountID, tunnelUUID string) error { - uri := fmt.Sprintf("/accounts/%s/tunnels/%s", accountID, tunnelUUID) - - res, err := api.makeRequestContextWithHeaders(ctx, http.MethodDelete, uri, nil, argoV1Header()) - if err != nil { - return err - } - - var argoDetailsResponse ArgoTunnelDetailResponse - err = json.Unmarshal(res, &argoDetailsResponse) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} - -// CleanupArgoTunnelConnections deletes any inactive connections on a tunnel. -// -// API reference: https://api.cloudflare.com/#argo-tunnel-clean-up-argo-tunnel-connections -func (api *API) CleanupArgoTunnelConnections(ctx context.Context, accountID, tunnelUUID string) error { - uri := fmt.Sprintf("/accounts/%s/tunnels/%s/connections", accountID, tunnelUUID) - - res, err := api.makeRequestContextWithHeaders(ctx, http.MethodDelete, uri, nil, argoV1Header()) - if err != nil { - return err - } - - var argoDetailsResponse ArgoTunnelDetailResponse - err = json.Unmarshal(res, &argoDetailsResponse) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} - -// The early implementation of Argo Tunnel endpoints didn't conform to the V4 -// API standard response structure. This has been remedied going forward however -// to support older clients this isn't yet the default. An explicit `Accept` -// header is used to get the V4 compatible version. -func argoV1Header() http.Header { - header := make(http.Header) - header.Set("Accept", "application/json;version=1") - - return header -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/auditlogs.go b/vendor/github.com/cloudflare/cloudflare-go/auditlogs.go deleted file mode 100644 index 114ede5e..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/auditlogs.go +++ /dev/null @@ -1,153 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "net/http" - "net/url" - "path" - "strconv" - "time" -) - -// AuditLogAction is a member of AuditLog, the action that was taken. -type AuditLogAction struct { - Result bool `json:"result"` - Type string `json:"type"` -} - -// AuditLogActor is a member of AuditLog, who performed the action. -type AuditLogActor struct { - Email string `json:"email"` - ID string `json:"id"` - IP string `json:"ip"` - Type string `json:"type"` -} - -// AuditLogOwner is a member of AuditLog, who owns this audit log. -type AuditLogOwner struct { - ID string `json:"id"` -} - -// AuditLogResource is a member of AuditLog, what was the action performed on. -type AuditLogResource struct { - ID string `json:"id"` - Type string `json:"type"` -} - -// AuditLog is an resource that represents an update in the cloudflare dash -type AuditLog struct { - Action AuditLogAction `json:"action"` - Actor AuditLogActor `json:"actor"` - ID string `json:"id"` - Metadata map[string]interface{} `json:"metadata"` - NewValue string `json:"newValue"` - NewValueJSON map[string]interface{} `json:"newValueJson"` - OldValue string `json:"oldValue"` - OldValueJSON map[string]interface{} `json:"oldValueJson"` - Owner AuditLogOwner `json:"owner"` - Resource AuditLogResource `json:"resource"` - When time.Time `json:"when"` -} - -// AuditLogResponse is the response returned from the cloudflare v4 api -type AuditLogResponse struct { - Response Response - Result []AuditLog `json:"result"` - ResultInfo `json:"result_info"` -} - -// AuditLogFilter is an object for filtering the audit log response from the api. -type AuditLogFilter struct { - ID string - ActorIP string - ActorEmail string - Direction string - ZoneName string - Since string - Before string - PerPage int - Page int -} - -// ToQuery turns an audit log filter in to an HTTP Query Param -// list, suitable for use in a url.URL.RawQuery. It will not include empty -// members of the struct in the query parameters. -func (a AuditLogFilter) ToQuery() url.Values { - v := url.Values{} - - if a.ID != "" { - v.Add("id", a.ID) - } - if a.ActorIP != "" { - v.Add("actor.ip", a.ActorIP) - } - if a.ActorEmail != "" { - v.Add("actor.email", a.ActorEmail) - } - if a.ZoneName != "" { - v.Add("zone.name", a.ZoneName) - } - if a.Direction != "" { - v.Add("direction", a.Direction) - } - if a.Since != "" { - v.Add("since", a.Since) - } - if a.Before != "" { - v.Add("before", a.Before) - } - if a.PerPage > 0 { - v.Add("per_page", strconv.Itoa(a.PerPage)) - } - if a.Page > 0 { - v.Add("page", strconv.Itoa(a.Page)) - } - - return v -} - -// GetOrganizationAuditLogs will return the audit logs of a specific -// organization, based on the ID passed in. The audit logs can be -// filtered based on any argument in the AuditLogFilter -// -// API Reference: https://api.cloudflare.com/#audit-logs-list-organization-audit-logs -func (api *API) GetOrganizationAuditLogs(ctx context.Context, organizationID string, a AuditLogFilter) (AuditLogResponse, error) { - uri := url.URL{ - Path: path.Join("/accounts", organizationID, "audit_logs"), - ForceQuery: true, - RawQuery: a.ToQuery().Encode(), - } - res, err := api.makeRequestContext(ctx, http.MethodGet, uri.String(), nil) - if err != nil { - return AuditLogResponse{}, err - } - return unmarshalReturn(res) -} - -// unmarshalReturn will unmarshal bytes and return an auditlogresponse -func unmarshalReturn(res []byte) (AuditLogResponse, error) { - var auditResponse AuditLogResponse - err := json.Unmarshal(res, &auditResponse) - if err != nil { - return auditResponse, err - } - return auditResponse, nil -} - -// GetUserAuditLogs will return your user's audit logs. The audit logs can be -// filtered based on any argument in the AuditLogFilter -// -// API Reference: https://api.cloudflare.com/#audit-logs-list-user-audit-logs -func (api *API) GetUserAuditLogs(ctx context.Context, a AuditLogFilter) (AuditLogResponse, error) { - uri := url.URL{ - Path: path.Join("/user", "audit_logs"), - ForceQuery: true, - RawQuery: a.ToQuery().Encode(), - } - res, err := api.makeRequestContext(ctx, http.MethodGet, uri.String(), nil) - if err != nil { - return AuditLogResponse{}, err - } - return unmarshalReturn(res) -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/authenticated_origin_pulls.go b/vendor/github.com/cloudflare/cloudflare-go/authenticated_origin_pulls.go deleted file mode 100644 index 0efa33c9..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/authenticated_origin_pulls.go +++ /dev/null @@ -1,68 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// AuthenticatedOriginPulls represents global AuthenticatedOriginPulls (tls_client_auth) metadata. -type AuthenticatedOriginPulls struct { - ID string `json:"id"` - Value string `json:"value"` - Editable bool `json:"editable"` - ModifiedOn time.Time `json:"modified_on"` -} - -// AuthenticatedOriginPullsResponse represents the response from the global AuthenticatedOriginPulls (tls_client_auth) details endpoint. -type AuthenticatedOriginPullsResponse struct { - Response - Result AuthenticatedOriginPulls `json:"result"` -} - -// GetAuthenticatedOriginPullsStatus returns the configuration details for global AuthenticatedOriginPulls (tls_client_auth). -// -// API reference: https://api.cloudflare.com/#zone-settings-get-tls-client-auth-setting -func (api *API) GetAuthenticatedOriginPullsStatus(ctx context.Context, zoneID string) (AuthenticatedOriginPulls, error) { - uri := fmt.Sprintf("/zones/%s/settings/tls_client_auth", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return AuthenticatedOriginPulls{}, err - } - var r AuthenticatedOriginPullsResponse - if err := json.Unmarshal(res, &r); err != nil { - return AuthenticatedOriginPulls{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// SetAuthenticatedOriginPullsStatus toggles whether global AuthenticatedOriginPulls is enabled for the zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-change-tls-client-auth-setting -func (api *API) SetAuthenticatedOriginPullsStatus(ctx context.Context, zoneID string, enable bool) (AuthenticatedOriginPulls, error) { - uri := fmt.Sprintf("/zones/%s/settings/tls_client_auth", zoneID) - var val string - if enable { - val = "on" - } else { - val = "off" - } - params := struct { - Value string `json:"value"` - }{ - Value: val, - } - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, params) - if err != nil { - return AuthenticatedOriginPulls{}, err - } - var r AuthenticatedOriginPullsResponse - if err := json.Unmarshal(res, &r); err != nil { - return AuthenticatedOriginPulls{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/authenticated_origin_pulls_per_hostname.go b/vendor/github.com/cloudflare/cloudflare-go/authenticated_origin_pulls_per_hostname.go deleted file mode 100644 index 4242e075..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/authenticated_origin_pulls_per_hostname.go +++ /dev/null @@ -1,176 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// PerHostnameAuthenticatedOriginPullsCertificateDetails represents the metadata for a Per Hostname AuthenticatedOriginPulls certificate. -type PerHostnameAuthenticatedOriginPullsCertificateDetails struct { - ID string `json:"id"` - Certificate string `json:"certificate"` - Issuer string `json:"issuer"` - Signature string `json:"signature"` - SerialNumber string `json:"serial_number"` - ExpiresOn time.Time `json:"expires_on"` - Status string `json:"status"` - UploadedOn time.Time `json:"uploaded_on"` -} - -// PerHostnameAuthenticatedOriginPullsCertificateResponse represents the response from endpoints relating to creating and deleting a Per Hostname AuthenticatedOriginPulls certificate. -type PerHostnameAuthenticatedOriginPullsCertificateResponse struct { - Response - Result PerHostnameAuthenticatedOriginPullsCertificateDetails `json:"result"` -} - -// PerHostnameAuthenticatedOriginPullsDetails contains metadata about the Per Hostname AuthenticatedOriginPulls configuration on a hostname. -type PerHostnameAuthenticatedOriginPullsDetails struct { - Hostname string `json:"hostname"` - CertID string `json:"cert_id"` - Enabled bool `json:"enabled"` - Status string `json:"status"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - CertStatus string `json:"cert_status"` - Issuer string `json:"issuer"` - Signature string `json:"signature"` - SerialNumber string `json:"serial_number"` - Certificate string `json:"certificate"` - CertUploadedOn time.Time `json:"cert_uploaded_on"` - CertUpdatedAt time.Time `json:"cert_updated_at"` - ExpiresOn time.Time `json:"expires_on"` -} - -// PerHostnameAuthenticatedOriginPullsDetailsResponse represents Per Hostname AuthenticatedOriginPulls configuration metadata for a single hostname. -type PerHostnameAuthenticatedOriginPullsDetailsResponse struct { - Response - Result PerHostnameAuthenticatedOriginPullsDetails `json:"result"` -} - -// PerHostnamesAuthenticatedOriginPullsDetailsResponse represents Per Hostname AuthenticatedOriginPulls configuration metadata for multiple hostnames. -type PerHostnamesAuthenticatedOriginPullsDetailsResponse struct { - Response - Result []PerHostnameAuthenticatedOriginPullsDetails `json:"result"` -} - -// PerHostnameAuthenticatedOriginPullsCertificateParams represents the required data related to the client certificate being uploaded to be used in Per Hostname AuthenticatedOriginPulls. -type PerHostnameAuthenticatedOriginPullsCertificateParams struct { - Certificate string `json:"certificate"` - PrivateKey string `json:"private_key"` -} - -// PerHostnameAuthenticatedOriginPullsConfig represents the config state for Per Hostname AuthenticatedOriginPulls applied on a hostname. -type PerHostnameAuthenticatedOriginPullsConfig struct { - Hostname string `json:"hostname"` - CertID string `json:"cert_id"` - Enabled bool `json:"enabled"` -} - -// PerHostnameAuthenticatedOriginPullsConfigParams represents the expected config param format for Per Hostname AuthenticatedOriginPulls applied on a hostname. -type PerHostnameAuthenticatedOriginPullsConfigParams struct { - Config []PerHostnameAuthenticatedOriginPullsConfig `json:"config"` -} - -// ListPerHostnameAuthenticatedOriginPullsCertificates will get all certificate under Per Hostname AuthenticatedOriginPulls zone. -// -// API reference: https://api.cloudflare.com/#per-hostname-authenticated-origin-pull-list-certificates -func (api *API) ListPerHostnameAuthenticatedOriginPullsCertificates(ctx context.Context, zoneID string) ([]PerHostnameAuthenticatedOriginPullsDetails, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth/hostnames/certificates", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []PerHostnameAuthenticatedOriginPullsDetails{}, err - } - var r PerHostnamesAuthenticatedOriginPullsDetailsResponse - if err := json.Unmarshal(res, &r); err != nil { - return []PerHostnameAuthenticatedOriginPullsDetails{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UploadPerHostnameAuthenticatedOriginPullsCertificate will upload the provided certificate and private key to the edge under Per Hostname AuthenticatedOriginPulls. -// -// API reference: https://api.cloudflare.com/#per-hostname-authenticated-origin-pull-upload-a-hostname-client-certificate -func (api *API) UploadPerHostnameAuthenticatedOriginPullsCertificate(ctx context.Context, zoneID string, params PerHostnameAuthenticatedOriginPullsCertificateParams) (PerHostnameAuthenticatedOriginPullsCertificateDetails, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth/hostnames/certificates", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, params) - if err != nil { - return PerHostnameAuthenticatedOriginPullsCertificateDetails{}, err - } - var r PerHostnameAuthenticatedOriginPullsCertificateResponse - if err := json.Unmarshal(res, &r); err != nil { - return PerHostnameAuthenticatedOriginPullsCertificateDetails{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// GetPerHostnameAuthenticatedOriginPullsCertificate retrieves certificate metadata about the requested Per Hostname certificate. -// -// API reference: https://api.cloudflare.com/#per-hostname-authenticated-origin-pull-get-the-hostname-client-certificate -func (api *API) GetPerHostnameAuthenticatedOriginPullsCertificate(ctx context.Context, zoneID, certificateID string) (PerHostnameAuthenticatedOriginPullsCertificateDetails, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth/hostnames/certificates/%s", zoneID, certificateID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return PerHostnameAuthenticatedOriginPullsCertificateDetails{}, err - } - var r PerHostnameAuthenticatedOriginPullsCertificateResponse - if err := json.Unmarshal(res, &r); err != nil { - return PerHostnameAuthenticatedOriginPullsCertificateDetails{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeletePerHostnameAuthenticatedOriginPullsCertificate will remove the requested Per Hostname certificate from the edge. -// -// API reference: https://api.cloudflare.com/#per-hostname-authenticated-origin-pull-delete-hostname-client-certificate -func (api *API) DeletePerHostnameAuthenticatedOriginPullsCertificate(ctx context.Context, zoneID, certificateID string) (PerHostnameAuthenticatedOriginPullsCertificateDetails, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth/hostnames/certificates/%s", zoneID, certificateID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return PerHostnameAuthenticatedOriginPullsCertificateDetails{}, err - } - var r PerHostnameAuthenticatedOriginPullsCertificateResponse - if err := json.Unmarshal(res, &r); err != nil { - return PerHostnameAuthenticatedOriginPullsCertificateDetails{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// EditPerHostnameAuthenticatedOriginPullsConfig applies the supplied Per Hostname AuthenticatedOriginPulls config onto a hostname(s) in the edge. -// -// API reference: https://api.cloudflare.com/#per-hostname-authenticated-origin-pull-enable-or-disable-a-hostname-for-client-authentication -func (api *API) EditPerHostnameAuthenticatedOriginPullsConfig(ctx context.Context, zoneID string, config []PerHostnameAuthenticatedOriginPullsConfig) ([]PerHostnameAuthenticatedOriginPullsDetails, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth/hostnames", zoneID) - conf := PerHostnameAuthenticatedOriginPullsConfigParams{ - Config: config, - } - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, conf) - if err != nil { - return []PerHostnameAuthenticatedOriginPullsDetails{}, err - } - var r PerHostnamesAuthenticatedOriginPullsDetailsResponse - if err := json.Unmarshal(res, &r); err != nil { - return []PerHostnameAuthenticatedOriginPullsDetails{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// GetPerHostnameAuthenticatedOriginPullsConfig returns the config state of Per Hostname AuthenticatedOriginPulls of the provided hostname within a zone. -// -// API reference: https://api.cloudflare.com/#per-hostname-authenticated-origin-pull-get-the-hostname-status-for-client-authentication -func (api *API) GetPerHostnameAuthenticatedOriginPullsConfig(ctx context.Context, zoneID, hostname string) (PerHostnameAuthenticatedOriginPullsDetails, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth/hostnames/%s", zoneID, hostname) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return PerHostnameAuthenticatedOriginPullsDetails{}, err - } - var r PerHostnameAuthenticatedOriginPullsDetailsResponse - if err := json.Unmarshal(res, &r); err != nil { - return PerHostnameAuthenticatedOriginPullsDetails{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/authenticated_origin_pulls_per_zone.go b/vendor/github.com/cloudflare/cloudflare-go/authenticated_origin_pulls_per_zone.go deleted file mode 100644 index 7c32be9f..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/authenticated_origin_pulls_per_zone.go +++ /dev/null @@ -1,152 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// PerZoneAuthenticatedOriginPullsSettings represents the settings for Per Zone AuthenticatedOriginPulls. -type PerZoneAuthenticatedOriginPullsSettings struct { - Enabled bool `json:"enabled"` -} - -// PerZoneAuthenticatedOriginPullsSettingsResponse represents the response from the Per Zone AuthenticatedOriginPulls settings endpoint. -type PerZoneAuthenticatedOriginPullsSettingsResponse struct { - Response - Result PerZoneAuthenticatedOriginPullsSettings `json:"result"` -} - -// PerZoneAuthenticatedOriginPullsCertificateDetails represents the metadata for a Per Zone AuthenticatedOriginPulls client certificate. -type PerZoneAuthenticatedOriginPullsCertificateDetails struct { - ID string `json:"id"` - Certificate string `json:"certificate"` - Issuer string `json:"issuer"` - Signature string `json:"signature"` - ExpiresOn time.Time `json:"expires_on"` - Status string `json:"status"` - UploadedOn time.Time `json:"uploaded_on"` -} - -// PerZoneAuthenticatedOriginPullsCertificateResponse represents the response from endpoints relating to creating and deleting a per zone AuthenticatedOriginPulls certificate. -type PerZoneAuthenticatedOriginPullsCertificateResponse struct { - Response - Result PerZoneAuthenticatedOriginPullsCertificateDetails `json:"result"` -} - -// PerZoneAuthenticatedOriginPullsCertificatesResponse represents the response from the per zone AuthenticatedOriginPulls certificate list endpoint. -type PerZoneAuthenticatedOriginPullsCertificatesResponse struct { - Response - Result []PerZoneAuthenticatedOriginPullsCertificateDetails `json:"result"` -} - -// PerZoneAuthenticatedOriginPullsCertificateParams represents the required data related to the client certificate being uploaded to be used in Per Zone AuthenticatedOriginPulls. -type PerZoneAuthenticatedOriginPullsCertificateParams struct { - Certificate string `json:"certificate"` - PrivateKey string `json:"private_key"` -} - -// GetPerZoneAuthenticatedOriginPullsStatus returns whether per zone AuthenticatedOriginPulls is enabled or not. It is false by default. -// -// API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-get-enablement-setting-for-zone -func (api *API) GetPerZoneAuthenticatedOriginPullsStatus(ctx context.Context, zoneID string) (PerZoneAuthenticatedOriginPullsSettings, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth/settings", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return PerZoneAuthenticatedOriginPullsSettings{}, err - } - var r PerZoneAuthenticatedOriginPullsSettingsResponse - if err := json.Unmarshal(res, &r); err != nil { - return PerZoneAuthenticatedOriginPullsSettings{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// SetPerZoneAuthenticatedOriginPullsStatus will update whether Per Zone AuthenticatedOriginPulls is enabled for the zone. -// -// API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-set-enablement-for-zone -func (api *API) SetPerZoneAuthenticatedOriginPullsStatus(ctx context.Context, zoneID string, enable bool) (PerZoneAuthenticatedOriginPullsSettings, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth/settings", zoneID) - params := struct { - Enabled bool `json:"enabled"` - }{ - Enabled: enable, - } - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, params) - if err != nil { - return PerZoneAuthenticatedOriginPullsSettings{}, err - } - var r PerZoneAuthenticatedOriginPullsSettingsResponse - if err := json.Unmarshal(res, &r); err != nil { - return PerZoneAuthenticatedOriginPullsSettings{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UploadPerZoneAuthenticatedOriginPullsCertificate will upload a provided client certificate and enable it to be used in all AuthenticatedOriginPulls requests for the zone. -// -// API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-upload-certificate -func (api *API) UploadPerZoneAuthenticatedOriginPullsCertificate(ctx context.Context, zoneID string, params PerZoneAuthenticatedOriginPullsCertificateParams) (PerZoneAuthenticatedOriginPullsCertificateDetails, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, params) - if err != nil { - return PerZoneAuthenticatedOriginPullsCertificateDetails{}, err - } - var r PerZoneAuthenticatedOriginPullsCertificateResponse - if err := json.Unmarshal(res, &r); err != nil { - return PerZoneAuthenticatedOriginPullsCertificateDetails{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListPerZoneAuthenticatedOriginPullsCertificates returns a list of all user uploaded client certificates to Per Zone AuthenticatedOriginPulls. -// -// API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-list-certificates -func (api *API) ListPerZoneAuthenticatedOriginPullsCertificates(ctx context.Context, zoneID string) ([]PerZoneAuthenticatedOriginPullsCertificateDetails, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []PerZoneAuthenticatedOriginPullsCertificateDetails{}, err - } - var r PerZoneAuthenticatedOriginPullsCertificatesResponse - if err := json.Unmarshal(res, &r); err != nil { - return []PerZoneAuthenticatedOriginPullsCertificateDetails{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// GetPerZoneAuthenticatedOriginPullsCertificateDetails returns the metadata associated with a user uploaded client certificate to Per Zone AuthenticatedOriginPulls. -// -// API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-get-certificate-details -func (api *API) GetPerZoneAuthenticatedOriginPullsCertificateDetails(ctx context.Context, zoneID, certificateID string) (PerZoneAuthenticatedOriginPullsCertificateDetails, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth/%s", zoneID, certificateID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return PerZoneAuthenticatedOriginPullsCertificateDetails{}, err - } - var r PerZoneAuthenticatedOriginPullsCertificateResponse - if err := json.Unmarshal(res, &r); err != nil { - return PerZoneAuthenticatedOriginPullsCertificateDetails{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeletePerZoneAuthenticatedOriginPullsCertificate removes the specified client certificate from the edge. -// -// API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-delete-certificate -func (api *API) DeletePerZoneAuthenticatedOriginPullsCertificate(ctx context.Context, zoneID, certificateID string) (PerZoneAuthenticatedOriginPullsCertificateDetails, error) { - uri := fmt.Sprintf("/zones/%s/origin_tls_client_auth/%s", zoneID, certificateID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return PerZoneAuthenticatedOriginPullsCertificateDetails{}, err - } - var r PerZoneAuthenticatedOriginPullsCertificateResponse - if err := json.Unmarshal(res, &r); err != nil { - return PerZoneAuthenticatedOriginPullsCertificateDetails{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/certificate_packs.go b/vendor/github.com/cloudflare/cloudflare-go/certificate_packs.go deleted file mode 100644 index 89e43060..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/certificate_packs.go +++ /dev/null @@ -1,191 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// CertificatePackGeoRestrictions is for the structure of the geographic -// restrictions for a TLS certificate. -type CertificatePackGeoRestrictions struct { - Label string `json:"label"` -} - -// CertificatePackCertificate is the base structure of a TLS certificate that is -// contained within a certificate pack. -type CertificatePackCertificate struct { - ID string `json:"id"` - Hosts []string `json:"hosts"` - Issuer string `json:"issuer"` - Signature string `json:"signature"` - Status string `json:"status"` - BundleMethod string `json:"bundle_method"` - GeoRestrictions CertificatePackGeoRestrictions `json:"geo_restrictions"` - ZoneID string `json:"zone_id"` - UploadedOn time.Time `json:"uploaded_on"` - ModifiedOn time.Time `json:"modified_on"` - ExpiresOn time.Time `json:"expires_on"` - Priority int `json:"priority"` -} - -// CertificatePack is the overarching structure of a certificate pack response. -type CertificatePack struct { - ID string `json:"id"` - Type string `json:"type"` - Hosts []string `json:"hosts"` - Certificates []CertificatePackCertificate `json:"certificates"` - PrimaryCertificate string `json:"primary_certificate"` -} - -// CertificatePackRequest is used for requesting a new certificate. -type CertificatePackRequest struct { - Type string `json:"type"` - Hosts []string `json:"hosts"` -} - -// CertificatePackAdvancedCertificate is the structure of the advanced -// certificate pack certificate. -type CertificatePackAdvancedCertificate struct { - ID string `json:"id"` - Type string `json:"type"` - Hosts []string `json:"hosts"` - ValidationMethod string `json:"validation_method"` - ValidityDays int `json:"validity_days"` - CertificateAuthority string `json:"certificate_authority"` - CloudflareBranding bool `json:"cloudflare_branding"` -} - -// CertificatePacksResponse is for responses where multiple certificates are -// expected. -type CertificatePacksResponse struct { - Response - Result []CertificatePack `json:"result"` -} - -// CertificatePacksDetailResponse contains a single certificate pack in the -// response. -type CertificatePacksDetailResponse struct { - Response - Result CertificatePack `json:"result"` -} - -// CertificatePacksAdvancedDetailResponse contains a single advanced certificate -// pack in the response. -type CertificatePacksAdvancedDetailResponse struct { - Response - Result CertificatePackAdvancedCertificate `json:"result"` -} - -// ListCertificatePacks returns all available TLS certificate packs for a zone. -// -// API Reference: https://api.cloudflare.com/#certificate-packs-list-certificate-packs -func (api *API) ListCertificatePacks(ctx context.Context, zoneID string) ([]CertificatePack, error) { - uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs?status=all", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []CertificatePack{}, err - } - - var certificatePacksResponse CertificatePacksResponse - err = json.Unmarshal(res, &certificatePacksResponse) - if err != nil { - return []CertificatePack{}, errors.Wrap(err, errUnmarshalError) - } - - return certificatePacksResponse.Result, nil -} - -// CertificatePack returns a single TLS certificate pack on a zone. -// -// API Reference: https://api.cloudflare.com/#certificate-packs-get-certificate-pack -func (api *API) CertificatePack(ctx context.Context, zoneID, certificatePackID string) (CertificatePack, error) { - uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs/%s", zoneID, certificatePackID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return CertificatePack{}, err - } - - var certificatePacksDetailResponse CertificatePacksDetailResponse - err = json.Unmarshal(res, &certificatePacksDetailResponse) - if err != nil { - return CertificatePack{}, errors.Wrap(err, errUnmarshalError) - } - - return certificatePacksDetailResponse.Result, nil -} - -// CreateCertificatePack creates a new certificate pack associated with a zone. -// -// API Reference: https://api.cloudflare.com/#certificate-packs-order-certificate-pack -func (api *API) CreateCertificatePack(ctx context.Context, zoneID string, cert CertificatePackRequest) (CertificatePack, error) { - uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, cert) - if err != nil { - return CertificatePack{}, err - } - - var certificatePacksDetailResponse CertificatePacksDetailResponse - err = json.Unmarshal(res, &certificatePacksDetailResponse) - if err != nil { - return CertificatePack{}, errors.Wrap(err, errUnmarshalError) - } - - return certificatePacksDetailResponse.Result, nil -} - -// DeleteCertificatePack removes a certificate pack associated with a zone. -// -// API Reference: https://api.cloudflare.com/#certificate-packs-delete-advanced-certificate-manager-certificate-pack -func (api *API) DeleteCertificatePack(ctx context.Context, zoneID, certificateID string) error { - uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs/%s", zoneID, certificateID) - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} - -// CreateAdvancedCertificatePack creates a new certificate pack associated with a zone. -// -// API Reference: https://api.cloudflare.com/#certificate-packs-order-certificate-pack -func (api *API) CreateAdvancedCertificatePack(ctx context.Context, zoneID string, cert CertificatePackAdvancedCertificate) (CertificatePackAdvancedCertificate, error) { - uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs/order", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, cert) - if err != nil { - return CertificatePackAdvancedCertificate{}, err - } - - var advancedCertificatePacksDetailResponse CertificatePacksAdvancedDetailResponse - err = json.Unmarshal(res, &advancedCertificatePacksDetailResponse) - if err != nil { - return CertificatePackAdvancedCertificate{}, errors.Wrap(err, errUnmarshalError) - } - - return advancedCertificatePacksDetailResponse.Result, nil -} - -// RestartAdvancedCertificateValidation kicks off the validation process for a -// pending certificate pack. -// -// API Reference: https://api.cloudflare.com/#certificate-packs-restart-validation-for-advanced-certificate-manager-certificate-pack -func (api *API) RestartAdvancedCertificateValidation(ctx context.Context, zoneID, certificateID string) (CertificatePackAdvancedCertificate, error) { - uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs/%s", zoneID, certificateID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, nil) - if err != nil { - return CertificatePackAdvancedCertificate{}, err - } - - var advancedCertificatePacksDetailResponse CertificatePacksAdvancedDetailResponse - err = json.Unmarshal(res, &advancedCertificatePacksDetailResponse) - if err != nil { - return CertificatePackAdvancedCertificate{}, errors.Wrap(err, errUnmarshalError) - } - - return advancedCertificatePacksDetailResponse.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/cloudflare.go b/vendor/github.com/cloudflare/cloudflare-go/cloudflare.go deleted file mode 100644 index 2bfa8374..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/cloudflare.go +++ /dev/null @@ -1,507 +0,0 @@ -// Package cloudflare implements the Cloudflare v4 API. -package cloudflare - -import ( - "bytes" - "context" - "encoding/json" - "io" - "io/ioutil" - "log" - "math" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "github.com/pkg/errors" - "golang.org/x/time/rate" -) - -const apiURL = "https://api.cloudflare.com/client/v4" - -const ( - originCARootCertEccURL = "https://developers.cloudflare.com/ssl/0d2cd0f374da0fb6dbf53128b60bbbf7/origin_ca_ecc_root.pem" - originCARootCertRsaURL = "https://developers.cloudflare.com/ssl/e2b9968022bf23b071d95229b5678452/origin_ca_rsa_root.pem" -) - -const ( - // AuthKeyEmail specifies that we should authenticate with API key and email address - AuthKeyEmail = 1 << iota - // AuthUserService specifies that we should authenticate with a User-Service key - AuthUserService - // AuthToken specifies that we should authenticate with an API Token - AuthToken -) - -// API holds the configuration for the current API client. A client should not -// be modified concurrently. -type API struct { - APIKey string - APIEmail string - APIUserServiceKey string - APIToken string - BaseURL string - AccountID string - UserAgent string - headers http.Header - httpClient *http.Client - authType int - rateLimiter *rate.Limiter - retryPolicy RetryPolicy - logger Logger -} - -// newClient provides shared logic for New and NewWithUserServiceKey -func newClient(opts ...Option) (*API, error) { - silentLogger := log.New(ioutil.Discard, "", log.LstdFlags) - - api := &API{ - BaseURL: apiURL, - headers: make(http.Header), - rateLimiter: rate.NewLimiter(rate.Limit(4), 1), // 4rps equates to default api limit (1200 req/5 min) - retryPolicy: RetryPolicy{ - MaxRetries: 3, - MinRetryDelay: time.Duration(1) * time.Second, - MaxRetryDelay: time.Duration(30) * time.Second, - }, - logger: silentLogger, - } - - err := api.parseOptions(opts...) - if err != nil { - return nil, errors.Wrap(err, "options parsing failed") - } - - // Fall back to http.DefaultClient if the package user does not provide - // their own. - if api.httpClient == nil { - api.httpClient = http.DefaultClient - } - - return api, nil -} - -// New creates a new Cloudflare v4 API client. -func New(key, email string, opts ...Option) (*API, error) { - if key == "" || email == "" { - return nil, errors.New(errEmptyCredentials) - } - - api, err := newClient(opts...) - if err != nil { - return nil, err - } - - api.APIKey = key - api.APIEmail = email - api.authType = AuthKeyEmail - - return api, nil -} - -// NewWithAPIToken creates a new Cloudflare v4 API client using API Tokens -func NewWithAPIToken(token string, opts ...Option) (*API, error) { - if token == "" { - return nil, errors.New(errEmptyAPIToken) - } - - api, err := newClient(opts...) - if err != nil { - return nil, err - } - - api.APIToken = token - api.authType = AuthToken - - return api, nil -} - -// NewWithUserServiceKey creates a new Cloudflare v4 API client using service key authentication. -func NewWithUserServiceKey(key string, opts ...Option) (*API, error) { - if key == "" { - return nil, errors.New(errEmptyCredentials) - } - - api, err := newClient(opts...) - if err != nil { - return nil, err - } - - api.APIUserServiceKey = key - api.authType = AuthUserService - - return api, nil -} - -// SetAuthType sets the authentication method (AuthKeyEmail, AuthToken, or AuthUserService). -func (api *API) SetAuthType(authType int) { - api.authType = authType -} - -// ZoneIDByName retrieves a zone's ID from the name. -func (api *API) ZoneIDByName(zoneName string) (string, error) { - zoneName = normalizeZoneName(zoneName) - res, err := api.ListZonesContext(context.Background(), WithZoneFilters(zoneName, api.AccountID, "")) - if err != nil { - return "", errors.Wrap(err, "ListZonesContext command failed") - } - - switch len(res.Result) { - case 0: - return "", errors.New("zone could not be found") - case 1: - return res.Result[0].ID, nil - default: - return "", errors.New("ambiguous zone name; an account ID might help") - } -} - -// makeRequest makes a HTTP request and returns the body as a byte slice, -// closing it before returning. params will be serialized to JSON. -func (api *API) makeRequest(method, uri string, params interface{}) ([]byte, error) { - return api.makeRequestWithAuthType(context.Background(), method, uri, params, api.authType) -} - -func (api *API) makeRequestContext(ctx context.Context, method, uri string, params interface{}) ([]byte, error) { - return api.makeRequestWithAuthType(ctx, method, uri, params, api.authType) -} - -func (api *API) makeRequestContextWithHeaders(ctx context.Context, method, uri string, params interface{}, headers http.Header) ([]byte, error) { - return api.makeRequestWithAuthTypeAndHeaders(ctx, method, uri, params, api.authType, headers) -} - -func (api *API) makeRequestWithHeaders(method, uri string, params interface{}, headers http.Header) ([]byte, error) { - return api.makeRequestWithAuthTypeAndHeaders(context.Background(), method, uri, params, api.authType, headers) -} - -func (api *API) makeRequestWithAuthType(ctx context.Context, method, uri string, params interface{}, authType int) ([]byte, error) { - return api.makeRequestWithAuthTypeAndHeaders(ctx, method, uri, params, authType, nil) -} - -func (api *API) makeRequestWithAuthTypeAndHeaders(ctx context.Context, method, uri string, params interface{}, authType int, headers http.Header) ([]byte, error) { - // Replace nil with a JSON object if needed - var jsonBody []byte - var err error - - if params != nil { - if paramBytes, ok := params.([]byte); ok { - jsonBody = paramBytes - } else { - jsonBody, err = json.Marshal(params) - if err != nil { - return nil, errors.Wrap(err, "error marshalling params to JSON") - } - } - } else { - jsonBody = nil - } - - var resp *http.Response - var respErr error - var reqBody io.Reader - var respBody []byte - for i := 0; i <= api.retryPolicy.MaxRetries; i++ { - if jsonBody != nil { - reqBody = bytes.NewReader(jsonBody) - } - if i > 0 { - // expect the backoff introduced here on errored requests to dominate the effect of rate limiting - // don't need a random component here as the rate limiter should do something similar - // nb time duration could truncate an arbitrary float. Since our inputs are all ints, we should be ok - sleepDuration := time.Duration(math.Pow(2, float64(i-1)) * float64(api.retryPolicy.MinRetryDelay)) - - if sleepDuration > api.retryPolicy.MaxRetryDelay { - sleepDuration = api.retryPolicy.MaxRetryDelay - } - // useful to do some simple logging here, maybe introduce levels later - api.logger.Printf("Sleeping %s before retry attempt number %d for request %s %s", sleepDuration.String(), i, method, uri) - - select { - case <-time.After(sleepDuration): - case <-ctx.Done(): - return nil, errors.Wrap(ctx.Err(), "operation aborted during backoff") - } - - } - err = api.rateLimiter.Wait(context.Background()) - if err != nil { - return nil, errors.Wrap(err, "Error caused by request rate limiting") - } - resp, respErr = api.request(ctx, method, uri, reqBody, authType, headers) - - // retry if the server is rate limiting us or if it failed - // assumes server operations are rolled back on failure - if respErr != nil || resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 { - // if we got a valid http response, try to read body so we can reuse the connection - // see https://golang.org/pkg/net/http/#Client.Do - if respErr == nil { - respBody, err = ioutil.ReadAll(resp.Body) - resp.Body.Close() - - respErr = errors.Wrap(err, "could not read response body") - - api.logger.Printf("Request: %s %s got an error response %d: %s\n", method, uri, resp.StatusCode, - strings.Replace(strings.Replace(string(respBody), "\n", "", -1), "\t", "", -1)) - } else { - api.logger.Printf("Error performing request: %s %s : %s \n", method, uri, respErr.Error()) - } - continue - } else { - respBody, err = ioutil.ReadAll(resp.Body) - defer resp.Body.Close() - if err != nil { - return nil, errors.Wrap(err, "could not read response body") - } - break - } - } - if respErr != nil { - return nil, respErr - } - - if resp.StatusCode >= http.StatusBadRequest { - if strings.HasSuffix(resp.Request.URL.Path, "/filters/validate-expr") { - return nil, errors.Errorf("%s", respBody) - } - - if resp.StatusCode > http.StatusInternalServerError { - return nil, errors.Errorf("HTTP status %d: service failure", resp.StatusCode) - } - - errBody := &Response{} - err = json.Unmarshal(respBody, &errBody) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalErrorBody) - } - - return nil, &APIRequestError{ - StatusCode: resp.StatusCode, - Errors: errBody.Errors, - } - } - - return respBody, nil -} - -// request makes a HTTP request to the given API endpoint, returning the raw -// *http.Response, or an error if one occurred. The caller is responsible for -// closing the response body. -func (api *API) request(ctx context.Context, method, uri string, reqBody io.Reader, authType int, headers http.Header) (*http.Response, error) { - req, err := http.NewRequestWithContext(ctx, method, api.BaseURL+uri, reqBody) - if err != nil { - return nil, errors.Wrap(err, "HTTP request creation failed") - } - - combinedHeaders := make(http.Header) - copyHeader(combinedHeaders, api.headers) - copyHeader(combinedHeaders, headers) - req.Header = combinedHeaders - - if authType&AuthKeyEmail != 0 { - req.Header.Set("X-Auth-Key", api.APIKey) - req.Header.Set("X-Auth-Email", api.APIEmail) - } - if authType&AuthUserService != 0 { - req.Header.Set("X-Auth-User-Service-Key", api.APIUserServiceKey) - } - if authType&AuthToken != 0 { - req.Header.Set("Authorization", "Bearer "+api.APIToken) - } - - if api.UserAgent != "" { - req.Header.Set("User-Agent", api.UserAgent) - } - - if req.Header.Get("Content-Type") == "" { - req.Header.Set("Content-Type", "application/json") - } - - resp, err := api.httpClient.Do(req) - if err != nil { - return nil, errors.Wrap(err, "HTTP request failed") - } - - return resp, nil -} - -// Returns the base URL to use for API endpoints that exist for accounts. -// If an account option was used when creating the API instance, returns -// the account URL. -// -// accountBase is the base URL for endpoints referring to the current user. -// It exists as a parameter because it is not consistent across APIs. -func (api *API) userBaseURL(accountBase string) string { - if api.AccountID != "" { - return "/accounts/" + api.AccountID - } - return accountBase -} - -// copyHeader copies all headers for `source` and sets them on `target`. -// based on https://godoc.org/github.com/golang/gddo/httputil/header#Copy -func copyHeader(target, source http.Header) { - for k, vs := range source { - target[k] = vs - } -} - -// ResponseInfo contains a code and message returned by the API as errors or -// informational messages inside the response. -type ResponseInfo struct { - Code int `json:"code"` - Message string `json:"message"` -} - -// Response is a template. There will also be a result struct. There will be a -// unique response type for each response, which will include this type. -type Response struct { - Success bool `json:"success"` - Errors []ResponseInfo `json:"errors"` - Messages []ResponseInfo `json:"messages"` -} - -// ResultInfoCursors contains information about cursors. -type ResultInfoCursors struct { - Before string `json:"before"` - After string `json:"after"` -} - -// ResultInfo contains metadata about the Response. -type ResultInfo struct { - Page int `json:"page"` - PerPage int `json:"per_page"` - TotalPages int `json:"total_pages"` - Count int `json:"count"` - Total int `json:"total_count"` - Cursor string `json:"cursor"` - Cursors ResultInfoCursors `json:"cursors"` -} - -// RawResponse keeps the result as JSON form -type RawResponse struct { - Response - Result json.RawMessage `json:"result"` -} - -// Raw makes a HTTP request with user provided params and returns the -// result as untouched JSON. -func (api *API) Raw(method, endpoint string, data interface{}) (json.RawMessage, error) { - res, err := api.makeRequest(method, endpoint, data) - if err != nil { - return nil, err - } - - var r RawResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// PaginationOptions can be passed to a list request to configure paging -// These values will be defaulted if omitted, and PerPage has min/max limits set by resource -type PaginationOptions struct { - Page int `json:"page,omitempty"` - PerPage int `json:"per_page,omitempty"` -} - -// RetryPolicy specifies number of retries and min/max retry delays -// This config is used when the client exponentially backs off after errored requests -type RetryPolicy struct { - MaxRetries int - MinRetryDelay time.Duration - MaxRetryDelay time.Duration -} - -// Logger defines the interface this library needs to use logging -// This is a subset of the methods implemented in the log package -type Logger interface { - Printf(format string, v ...interface{}) -} - -// ReqOption is a functional option for configuring API requests -type ReqOption func(opt *reqOption) -type reqOption struct { - params url.Values -} - -// WithZoneFilters applies a filter based on zone properties. -func WithZoneFilters(zoneName, accountID, status string) ReqOption { - return func(opt *reqOption) { - if zoneName != "" { - opt.params.Set("name", normalizeZoneName(zoneName)) - } - - if accountID != "" { - opt.params.Set("account.id", accountID) - } - - if status != "" { - opt.params.Set("status", status) - } - } -} - -// WithPagination configures the pagination for a response. -func WithPagination(opts PaginationOptions) ReqOption { - return func(opt *reqOption) { - if opts.Page > 0 { - opt.params.Set("page", strconv.Itoa(opts.Page)) - } - - if opts.PerPage > 0 { - opt.params.Set("per_page", strconv.Itoa(opts.PerPage)) - } - } -} - -// checkResultInfo checks whether ResultInfo is reasonable except that it currently -// ignores the cursor information. perPage, page, and count are the requested #items -// per page, the requested page number, and the actual length of the Result array. -// -// Responses from the actual Cloudflare servers should pass all these checks (or we -// discover a serious bug in the Cloudflare servers). However, the unit tests can -// easily violate these constraints and this utility function can help debugging. -// Correct pagination information is crucial for more advanced List* functions that -// handle pagination automatically and fetch different pages in parallel. -// -// TODO: check cursors as well. -func checkResultInfo(perPage, page, count int, info *ResultInfo) bool { - if info.Cursor != "" || info.Cursors.Before != "" || info.Cursors.After != "" { - panic("checkResultInfo could not handle cursors yet.") - } - - switch { - case info.PerPage != perPage || info.Page != page || info.Count != count: - return false - - case info.PerPage <= 0: - return false - - case info.Total == 0 && info.TotalPages == 0 && info.Page == 1 && info.Count == 0: - return true - - case info.Total <= 0 || info.TotalPages <= 0: - return false - - case info.Total > info.PerPage*info.TotalPages || info.Total <= info.PerPage*(info.TotalPages-1): - return false - } - - switch { - case info.Page > info.TotalPages || info.Page <= 0: - return false - - case info.Page < info.TotalPages: - return info.Count == info.PerPage - - case info.Page == info.TotalPages: - return info.Count == info.Total-info.PerPage*(info.TotalPages-1) - - default: - // This is actually impossible, but Go compiler does not know trichotomy - panic("checkResultInfo: impossible") - } -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/consts.go b/vendor/github.com/cloudflare/cloudflare-go/consts.go deleted file mode 100644 index 3faffc87..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/consts.go +++ /dev/null @@ -1,17 +0,0 @@ -package cloudflare - -// RouteRoot represents the name of the route namespace -type RouteRoot string - -const ( - // AccountRouteRoot is the accounts route namespace - AccountRouteRoot RouteRoot = "accounts" - - // ZoneRouteRoot is the zones route namespace - ZoneRouteRoot RouteRoot = "zones" - - // Used for testing - testAccountID = "01a7362d577a6c3019a474fd6f485823" - testZoneID = "d56084adb405e0b7e32c52321bf07be6" - testCertPackUUID = "a77f8bd7-3b47-46b4-a6f1-75cf98109948" -) diff --git a/vendor/github.com/cloudflare/cloudflare-go/custom_hostname.go b/vendor/github.com/cloudflare/cloudflare-go/custom_hostname.go deleted file mode 100644 index bb5112ac..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/custom_hostname.go +++ /dev/null @@ -1,314 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -// CustomHostnameStatus is the enumeration of valid state values in the CustomHostnameSSL -type CustomHostnameStatus string - -const ( - // PENDING status represents state of CustomHostname is pending. - PENDING CustomHostnameStatus = "pending" - // ACTIVE status represents state of CustomHostname is active. - ACTIVE CustomHostnameStatus = "active" - // MOVED status represents state of CustomHostname is moved. - MOVED CustomHostnameStatus = "moved" - // DELETED status represents state of CustomHostname is removed. - DELETED CustomHostnameStatus = "deleted" -) - -// CustomHostnameSSLSettings represents the SSL settings for a custom hostname. -type CustomHostnameSSLSettings struct { - HTTP2 string `json:"http2,omitempty"` - TLS13 string `json:"tls_1_3,omitempty"` - MinTLSVersion string `json:"min_tls_version,omitempty"` - Ciphers []string `json:"ciphers,omitempty"` -} - -//CustomHostnameOwnershipVerification represents ownership verification status of a given custom hostname. -type CustomHostnameOwnershipVerification struct { - Type string `json:"type,omitempty"` - Name string `json:"name,omitempty"` - Value string `json:"value,omitempty"` -} - -//CustomHostnameSSLValidationErrors represents errors that occurred during SSL validation. -type CustomHostnameSSLValidationErrors struct { - Message string `json:"message,omitempty"` -} - -// CustomHostnameSSL represents the SSL section in a given custom hostname. -type CustomHostnameSSL struct { - ID string `json:"id,omitempty"` - Status string `json:"status,omitempty"` - Method string `json:"method,omitempty"` - Type string `json:"type,omitempty"` - CnameTarget string `json:"cname_target,omitempty"` - CnameName string `json:"cname,omitempty"` - TxtName string `json:"txt_name,omitempty"` - TxtValue string `json:"txt_value,omitempty"` - Wildcard *bool `json:"wildcard,omitempty"` - CustomCertificate string `json:"custom_certificate,omitempty"` - CustomKey string `json:"custom_key,omitempty"` - CertificateAuthority string `json:"certificate_authority,omitempty"` - Issuer string `json:"issuer,omitempty"` - SerialNumber string `json:"serial_number,omitempty"` - Settings CustomHostnameSSLSettings `json:"settings,omitempty"` - ValidationErrors []CustomHostnameSSLValidationErrors `json:"validation_errors,omitempty"` - HTTPUrl string `json:"http_url,omitempty"` - HTTPBody string `json:"http_body,omitempty"` -} - -// CustomMetadata defines custom metadata for the hostname. This requires logic to be implemented by Cloudflare to act on the data provided. -type CustomMetadata map[string]interface{} - -// CustomHostname represents a custom hostname in a zone. -type CustomHostname struct { - ID string `json:"id,omitempty"` - Hostname string `json:"hostname,omitempty"` - CustomOriginServer string `json:"custom_origin_server,omitempty"` - SSL *CustomHostnameSSL `json:"ssl,omitempty"` - CustomMetadata CustomMetadata `json:"custom_metadata,omitempty"` - Status CustomHostnameStatus `json:"status,omitempty"` - VerificationErrors []string `json:"verification_errors,omitempty"` - OwnershipVerification CustomHostnameOwnershipVerification `json:"ownership_verification,omitempty"` - OwnershipVerificationHTTP CustomHostnameOwnershipVerificationHTTP `json:"ownership_verification_http,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` -} - -// CustomHostnameOwnershipVerificationHTTP represents a response from the Custom Hostnames endpoints. -type CustomHostnameOwnershipVerificationHTTP struct { - HTTPUrl string `json:"http_url,omitempty"` - HTTPBody string `json:"http_body,omitempty"` -} - -// CustomHostnameResponse represents a response from the Custom Hostnames endpoints. -type CustomHostnameResponse struct { - Result CustomHostname `json:"result"` - Response -} - -// CustomHostnameListResponse represents a response from the Custom Hostnames endpoints. -type CustomHostnameListResponse struct { - Result []CustomHostname `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// CustomHostnameFallbackOrigin represents a Custom Hostnames Fallback Origin -type CustomHostnameFallbackOrigin struct { - Origin string `json:"origin,omitempty"` - Status string `json:"status,omitempty"` - Errors []string `json:"errors,omitempty"` -} - -// CustomHostnameFallbackOriginResponse represents a response from the Custom Hostnames Fallback Origin endpoint. -type CustomHostnameFallbackOriginResponse struct { - Result CustomHostnameFallbackOrigin `json:"result"` - Response -} - -// UpdateCustomHostnameSSL modifies SSL configuration for the given custom -// hostname in the given zone. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-update-custom-hostname-configuration -func (api *API) UpdateCustomHostnameSSL(ctx context.Context, zoneID string, customHostnameID string, ssl *CustomHostnameSSL) (*CustomHostnameResponse, error) { - uri := fmt.Sprintf("/zones/%s/custom_hostnames/%s", zoneID, customHostnameID) - ch := CustomHostname{ - SSL: ssl, - } - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, ch) - if err != nil { - return nil, err - } - - var response *CustomHostnameResponse - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return response, nil -} - -// UpdateCustomHostname modifies configuration for the given custom -// hostname in the given zone. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-update-custom-hostname-configuration -func (api *API) UpdateCustomHostname(ctx context.Context, zoneID string, customHostnameID string, ch CustomHostname) (*CustomHostnameResponse, error) { - uri := fmt.Sprintf("/zones/%s/custom_hostnames/%s", zoneID, customHostnameID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, ch) - if err != nil { - return nil, err - } - - var response *CustomHostnameResponse - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return response, nil -} - -// DeleteCustomHostname deletes a custom hostname (and any issued SSL -// certificates). -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-delete-a-custom-hostname-and-any-issued-ssl-certificates- -func (api *API) DeleteCustomHostname(ctx context.Context, zoneID string, customHostnameID string) error { - uri := fmt.Sprintf("/zones/%s/custom_hostnames/%s", zoneID, customHostnameID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - var response *CustomHostnameResponse - err = json.Unmarshal(res, &response) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} - -// CreateCustomHostname creates a new custom hostname and requests that an SSL certificate be issued for it. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-create-custom-hostname -func (api *API) CreateCustomHostname(ctx context.Context, zoneID string, ch CustomHostname) (*CustomHostnameResponse, error) { - uri := fmt.Sprintf("/zones/%s/custom_hostnames", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, ch) - if err != nil { - return nil, err - } - - var response *CustomHostnameResponse - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// CustomHostnames fetches custom hostnames for the given zone, -// by applying filter.Hostname if not empty and scoping the result to page'th 50 items. -// -// The returned ResultInfo can be used to implement pagination. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-list-custom-hostnames -func (api *API) CustomHostnames(ctx context.Context, zoneID string, page int, filter CustomHostname) ([]CustomHostname, ResultInfo, error) { - v := url.Values{} - v.Set("per_page", "50") - v.Set("page", strconv.Itoa(page)) - if filter.Hostname != "" { - v.Set("hostname", filter.Hostname) - } - - uri := fmt.Sprintf("/zones/%s/custom_hostnames?%s", zoneID, v.Encode()) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []CustomHostname{}, ResultInfo{}, err - } - var customHostnameListResponse CustomHostnameListResponse - err = json.Unmarshal(res, &customHostnameListResponse) - if err != nil { - return []CustomHostname{}, ResultInfo{}, err - } - - return customHostnameListResponse.Result, customHostnameListResponse.ResultInfo, nil -} - -// CustomHostname inspects the given custom hostname in the given zone. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-custom-hostname-configuration-details -func (api *API) CustomHostname(ctx context.Context, zoneID string, customHostnameID string) (CustomHostname, error) { - uri := fmt.Sprintf("/zones/%s/custom_hostnames/%s", zoneID, customHostnameID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return CustomHostname{}, err - } - - var response CustomHostnameResponse - err = json.Unmarshal(res, &response) - if err != nil { - return CustomHostname{}, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// CustomHostnameIDByName retrieves the ID for the given hostname in the given zone. -func (api *API) CustomHostnameIDByName(ctx context.Context, zoneID string, hostname string) (string, error) { - customHostnames, _, err := api.CustomHostnames(ctx, zoneID, 1, CustomHostname{Hostname: hostname}) - if err != nil { - return "", errors.Wrap(err, "CustomHostnames command failed") - } - for _, ch := range customHostnames { - if ch.Hostname == hostname { - return ch.ID, nil - } - } - return "", errors.New("CustomHostname could not be found") -} - -// UpdateCustomHostnameFallbackOrigin modifies the Custom Hostname Fallback origin in the given zone. -// -// API reference: https://api.cloudflare.com/#custom-hostname-fallback-origin-for-a-zone-update-fallback-origin-for-custom-hostnames -func (api *API) UpdateCustomHostnameFallbackOrigin(ctx context.Context, zoneID string, chfo CustomHostnameFallbackOrigin) (*CustomHostnameFallbackOriginResponse, error) { - uri := fmt.Sprintf("/zones/%s/custom_hostnames/fallback_origin", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, chfo) - if err != nil { - return nil, err - } - - var response *CustomHostnameFallbackOriginResponse - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return response, nil -} - -// DeleteCustomHostnameFallbackOrigin deletes the Custom Hostname Fallback origin in the given zone. -// -// API reference: https://api.cloudflare.com/#custom-hostname-fallback-origin-for-a-zone-delete-fallback-origin-for-custom-hostnames -func (api *API) DeleteCustomHostnameFallbackOrigin(ctx context.Context, zoneID string) error { - uri := fmt.Sprintf("/zones/%s/custom_hostnames/fallback_origin", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - var response *CustomHostnameFallbackOriginResponse - err = json.Unmarshal(res, &response) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// CustomHostnameFallbackOrigin inspects the Custom Hostname Fallback origin in the given zone. -// -// API reference: https://api.cloudflare.com/#custom-hostname-fallback-origin-for-a-zone-properties -func (api *API) CustomHostnameFallbackOrigin(ctx context.Context, zoneID string) (CustomHostnameFallbackOrigin, error) { - uri := fmt.Sprintf("/zones/%s/custom_hostnames/fallback_origin", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return CustomHostnameFallbackOrigin{}, err - } - - var response CustomHostnameFallbackOriginResponse - err = json.Unmarshal(res, &response) - if err != nil { - return CustomHostnameFallbackOrigin{}, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/custom_pages.go b/vendor/github.com/cloudflare/cloudflare-go/custom_pages.go deleted file mode 100644 index 45fd504a..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/custom_pages.go +++ /dev/null @@ -1,178 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// CustomPage represents a custom page configuration. -type CustomPage struct { - CreatedOn time.Time `json:"created_on"` - ModifiedOn time.Time `json:"modified_on"` - URL interface{} `json:"url"` - State string `json:"state"` - RequiredTokens []string `json:"required_tokens"` - PreviewTarget string `json:"preview_target"` - Description string `json:"description"` - ID string `json:"id"` -} - -// CustomPageResponse represents the response from the custom pages endpoint. -type CustomPageResponse struct { - Response - Result []CustomPage `json:"result"` -} - -// CustomPageDetailResponse represents the response from the custom page endpoint. -type CustomPageDetailResponse struct { - Response - Result CustomPage `json:"result"` -} - -// CustomPageOptions is used to determine whether or not the operation -// should take place on an account or zone level based on which is -// provided to the function. -// -// A non-empty value denotes desired use. -type CustomPageOptions struct { - AccountID string - ZoneID string -} - -// CustomPageParameters is used to update a particular custom page with -// the values provided. -type CustomPageParameters struct { - URL interface{} `json:"url"` - State string `json:"state"` -} - -// CustomPages lists custom pages for a zone or account. -// -// Zone API reference: https://api.cloudflare.com/#custom-pages-for-a-zone-list-available-custom-pages -// Account API reference: https://api.cloudflare.com/#custom-pages-account--list-custom-pages -func (api *API) CustomPages(ctx context.Context, options *CustomPageOptions) ([]CustomPage, error) { - var ( - pageType, identifier string - ) - - if options.AccountID == "" && options.ZoneID == "" { - return nil, errors.New("either account ID or zone ID must be provided") - } - - if options.AccountID != "" && options.ZoneID != "" { - return nil, errors.New("account ID and zone ID are mutually exclusive") - } - - // Should the account ID be defined, treat this as an account level operation. - if options.AccountID != "" { - pageType = "accounts" - identifier = options.AccountID - } else { - pageType = "zones" - identifier = options.ZoneID - } - - uri := fmt.Sprintf("/%s/%s/custom_pages", pageType, identifier) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - var customPageResponse CustomPageResponse - err = json.Unmarshal(res, &customPageResponse) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return customPageResponse.Result, nil -} - -// CustomPage lists a single custom page based on the ID. -// -// Zone API reference: https://api.cloudflare.com/#custom-pages-for-a-zone-custom-page-details -// Account API reference: https://api.cloudflare.com/#custom-pages-account--custom-page-details -func (api *API) CustomPage(ctx context.Context, options *CustomPageOptions, customPageID string) (CustomPage, error) { - var ( - pageType, identifier string - ) - - if options.AccountID == "" && options.ZoneID == "" { - return CustomPage{}, errors.New("either account ID or zone ID must be provided") - } - - if options.AccountID != "" && options.ZoneID != "" { - return CustomPage{}, errors.New("account ID and zone ID are mutually exclusive") - } - - // Should the account ID be defined, treat this as an account level operation. - if options.AccountID != "" { - pageType = "accounts" - identifier = options.AccountID - } else { - pageType = "zones" - identifier = options.ZoneID - } - - uri := fmt.Sprintf("/%s/%s/custom_pages/%s", pageType, identifier, customPageID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return CustomPage{}, err - } - - var customPageResponse CustomPageDetailResponse - err = json.Unmarshal(res, &customPageResponse) - if err != nil { - return CustomPage{}, errors.Wrap(err, errUnmarshalError) - } - - return customPageResponse.Result, nil -} - -// UpdateCustomPage updates a single custom page setting. -// -// Zone API reference: https://api.cloudflare.com/#custom-pages-for-a-zone-update-custom-page-url -// Account API reference: https://api.cloudflare.com/#custom-pages-account--update-custom-page -func (api *API) UpdateCustomPage(ctx context.Context, options *CustomPageOptions, customPageID string, pageParameters CustomPageParameters) (CustomPage, error) { - var ( - pageType, identifier string - ) - - if options.AccountID == "" && options.ZoneID == "" { - return CustomPage{}, errors.New("either account ID or zone ID must be provided") - } - - if options.AccountID != "" && options.ZoneID != "" { - return CustomPage{}, errors.New("account ID and zone ID are mutually exclusive") - } - - // Should the account ID be defined, treat this as an account level operation. - if options.AccountID != "" { - pageType = "accounts" - identifier = options.AccountID - } else { - pageType = "zones" - identifier = options.ZoneID - } - - uri := fmt.Sprintf("/%s/%s/custom_pages/%s", pageType, identifier, customPageID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, pageParameters) - if err != nil { - return CustomPage{}, err - } - - var customPageResponse CustomPageDetailResponse - err = json.Unmarshal(res, &customPageResponse) - if err != nil { - return CustomPage{}, errors.Wrap(err, errUnmarshalError) - } - - return customPageResponse.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/device_posture_rule.go b/vendor/github.com/cloudflare/cloudflare-go/device_posture_rule.go deleted file mode 100644 index f28af576..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/device_posture_rule.go +++ /dev/null @@ -1,169 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -// DevicePostureRule represents a device posture rule. -type DevicePostureRule struct { - ID string `json:"id,omitempty"` - Type string `json:"type"` - Name string `json:"name"` - Description string `json:"description,omitempty"` - Schedule string `json:"schedule,omitempty"` - Match []DevicePostureRuleMatch `json:"match,omitempty"` - Input DevicePostureRuleInput `json:"input,omitempty"` -} - -// DevicePostureRuleMatch represents the conditions that the client must match to run the rule. -type DevicePostureRuleMatch struct { - Platform string `json:"platform,omitempty"` -} - -// DevicePostureRuleInput represents the value to be checked against. -type DevicePostureRuleInput struct { - ID string `json:"id,omitempty"` - Path string `json:"path,omitempty"` - Exists bool `json:"exists,omitempty"` - Thumbprint string `json:"thumbprint,omitempty"` - Sha256 string `json:"sha256,omitempty"` - Running bool `json:"running,omitempty"` - RequireAll bool `json:"requireAll,omitempty"` - Enabled bool `json:"enabled,omitempty"` - Version string `json:"version,omitempty"` - Operator string `json:"operator,omitempty"` - Domain string `json:"domain,omitempty"` -} - -// DevicePostureRuleListResponse represents the response from the list -// device posture rules endpoint. -type DevicePostureRuleListResponse struct { - Result []DevicePostureRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// DevicePostureRuleDetailResponse is the API response, containing a single -// device posture rule. -type DevicePostureRuleDetailResponse struct { - Response - Result DevicePostureRule `json:"result"` -} - -// DevicePostureRules returns all device posture rules within an account. -// -// API reference: https://api.cloudflare.com/#device-posture-rules-list-device-posture-rules -func (api *API) DevicePostureRules(ctx context.Context, accountID string) ([]DevicePostureRule, ResultInfo, error) { - uri := fmt.Sprintf("/%s/%s/devices/posture", AccountRouteRoot, accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []DevicePostureRule{}, ResultInfo{}, err - } - - var devicePostureRuleListResponse DevicePostureRuleListResponse - err = json.Unmarshal(res, &devicePostureRuleListResponse) - if err != nil { - return []DevicePostureRule{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return devicePostureRuleListResponse.Result, devicePostureRuleListResponse.ResultInfo, nil -} - -// DevicePostureRule returns a single device posture rule based on the rule ID. -// -// API reference: https://api.cloudflare.com/#device-posture-rules-device-posture-rules-details -func (api *API) DevicePostureRule(ctx context.Context, accountID, ruleID string) (DevicePostureRule, error) { - uri := fmt.Sprintf( - "/%s/%s/devices/posture/%s", - AccountRouteRoot, - accountID, - ruleID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return DevicePostureRule{}, err - } - - var devicePostureRuleDetailResponse DevicePostureRuleDetailResponse - err = json.Unmarshal(res, &devicePostureRuleDetailResponse) - if err != nil { - return DevicePostureRule{}, errors.Wrap(err, errUnmarshalError) - } - - return devicePostureRuleDetailResponse.Result, nil -} - -// CreateDevicePostureRule creates a new device posture rule. -// -// API reference: https://api.cloudflare.com/#device-posture-rules-create-device-posture-rule -func (api *API) CreateDevicePostureRule(ctx context.Context, accountID string, rule DevicePostureRule) (DevicePostureRule, error) { - uri := fmt.Sprintf("/%s/%s/devices/posture", AccountRouteRoot, accountID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, rule) - if err != nil { - return DevicePostureRule{}, err - } - - var devicePostureRuleDetailResponse DevicePostureRuleDetailResponse - err = json.Unmarshal(res, &devicePostureRuleDetailResponse) - if err != nil { - return DevicePostureRule{}, errors.Wrap(err, errUnmarshalError) - } - - return devicePostureRuleDetailResponse.Result, nil -} - -// UpdateDevicePostureRule updates an existing device posture rule. -// -// API reference: https://api.cloudflare.com/#device-posture-rules-update-device-posture-rule -func (api *API) UpdateDevicePostureRule(ctx context.Context, accountID string, rule DevicePostureRule) (DevicePostureRule, error) { - if rule.ID == "" { - return DevicePostureRule{}, errors.Errorf("device posture rule ID cannot be empty") - } - - uri := fmt.Sprintf( - "/%s/%s/devices/posture/%s", - AccountRouteRoot, - accountID, - rule.ID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, rule) - if err != nil { - return DevicePostureRule{}, err - } - - var devicePostureRuleDetailResponse DevicePostureRuleDetailResponse - err = json.Unmarshal(res, &devicePostureRuleDetailResponse) - if err != nil { - return DevicePostureRule{}, errors.Wrap(err, errUnmarshalError) - } - - return devicePostureRuleDetailResponse.Result, nil -} - -// DeleteDevicePostureRule deletes a device posture rule. -// -// API reference: https://api.cloudflare.com/#device-posture-rules-delete-device-posture-rule -func (api *API) DeleteDevicePostureRule(ctx context.Context, accountID, ruleID string) error { - uri := fmt.Sprintf( - "/%s/%s/devices/posture/%s", - AccountRouteRoot, - accountID, - ruleID, - ) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/diagnostics.go b/vendor/github.com/cloudflare/cloudflare-go/diagnostics.go deleted file mode 100644 index 6fc2daac..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/diagnostics.go +++ /dev/null @@ -1,103 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -// DiagnosticsTracerouteConfiguration is the overarching structure of the -// diagnostics traceroute requests. -type DiagnosticsTracerouteConfiguration struct { - Targets []string `json:"targets"` - Colos []string `json:"colos,omitempty"` - Options DiagnosticsTracerouteConfigurationOptions `json:"options,omitempty"` -} - -// DiagnosticsTracerouteConfigurationOptions contains the options for performing -// traceroutes. -type DiagnosticsTracerouteConfigurationOptions struct { - PacketsPerTTL int `json:"packets_per_ttl"` - PacketType string `json:"packet_type"` - MaxTTL int `json:"max_ttl"` - WaitTime int `json:"wait_time"` -} - -// DiagnosticsTracerouteResponse is the outer response of the API response. -type DiagnosticsTracerouteResponse struct { - Response - Result []DiagnosticsTracerouteResponseResult `json:"result"` -} - -// DiagnosticsTracerouteResponseResult is the inner API response for the -// traceroute request. -type DiagnosticsTracerouteResponseResult struct { - Target string `json:"target"` - Colos []DiagnosticsTracerouteResponseColos `json:"colos"` -} - -// DiagnosticsTracerouteResponseColo contains the Name and City of a colocation. -type DiagnosticsTracerouteResponseColo struct { - Name string `json:"name"` - City string `json:"city"` -} - -// DiagnosticsTracerouteResponseNodes holds a summary of nodes contacted in the -// traceroute. -type DiagnosticsTracerouteResponseNodes struct { - Asn string `json:"asn"` - IP string `json:"ip"` - Name string `json:"name"` - PacketCount int `json:"packet_count"` - MeanRttMs float64 `json:"mean_rtt_ms"` - StdDevRttMs float64 `json:"std_dev_rtt_ms"` - MinRttMs float64 `json:"min_rtt_ms"` - MaxRttMs float64 `json:"max_rtt_ms"` -} - -// DiagnosticsTracerouteResponseHops holds packet and node information of the -// hops. -type DiagnosticsTracerouteResponseHops struct { - PacketsTTL int `json:"packets_ttl"` - PacketsSent int `json:"packets_sent"` - PacketsLost int `json:"packets_lost"` - Nodes []DiagnosticsTracerouteResponseNodes `json:"nodes"` -} - -// DiagnosticsTracerouteResponseColos is the summary struct of a colocation test. -type DiagnosticsTracerouteResponseColos struct { - Error string `json:"error"` - Colo DiagnosticsTracerouteResponseColo `json:"colo"` - TracerouteTimeMs int `json:"traceroute_time_ms"` - TargetSummary DiagnosticsTracerouteResponseNodes `json:"target_summary"` - Hops []DiagnosticsTracerouteResponseHops `json:"hops"` -} - -// PerformTraceroute initiates a traceroute from the Cloudflare network to the -// requested targets. -// -// API documentation: https://api.cloudflare.com/#diagnostics-traceroute -func (api *API) PerformTraceroute(ctx context.Context, accountID string, targets, colos []string, tracerouteOptions DiagnosticsTracerouteConfigurationOptions) ([]DiagnosticsTracerouteResponseResult, error) { - uri := fmt.Sprintf("/accounts/%s/diagnostics/traceroute", accountID) - diagnosticsPayload := DiagnosticsTracerouteConfiguration{ - Targets: targets, - Colos: colos, - Options: tracerouteOptions, - } - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, diagnosticsPayload) - if err != nil { - return []DiagnosticsTracerouteResponseResult{}, err - } - - var diagnosticsResponse DiagnosticsTracerouteResponse - err = json.Unmarshal(res, &diagnosticsResponse) - if err != nil { - return []DiagnosticsTracerouteResponseResult{}, errors.Wrap(err, errUnmarshalError) - } - - return diagnosticsResponse.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/dns.go b/vendor/github.com/cloudflare/cloudflare-go/dns.go deleted file mode 100644 index fa1a367a..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/dns.go +++ /dev/null @@ -1,204 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" - "golang.org/x/net/idna" -) - -// DNSRecord represents a DNS record in a zone. -type DNSRecord struct { - ID string `json:"id,omitempty"` - Type string `json:"type,omitempty"` - Name string `json:"name,omitempty"` - Content string `json:"content,omitempty"` - Proxiable bool `json:"proxiable,omitempty"` - Proxied *bool `json:"proxied,omitempty"` - TTL int `json:"ttl,omitempty"` - Locked bool `json:"locked,omitempty"` - ZoneID string `json:"zone_id,omitempty"` - ZoneName string `json:"zone_name,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` - ModifiedOn time.Time `json:"modified_on,omitempty"` - Data interface{} `json:"data,omitempty"` // data returned by: SRV, LOC - Meta interface{} `json:"meta,omitempty"` - Priority *uint16 `json:"priority,omitempty"` -} - -// DNSRecordResponse represents the response from the DNS endpoint. -type DNSRecordResponse struct { - Result DNSRecord `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// DNSListResponse represents the response from the list DNS records endpoint. -type DNSListResponse struct { - Result []DNSRecord `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// nontransitionalLookup implements the nontransitional processing as specified in -// Unicode Technical Standard 46 with almost all checkings off to maximize user freedom. -var nontransitionalLookup = idna.New( - idna.MapForLookup(), - idna.StrictDomainName(false), - idna.ValidateLabels(false), -) - -// toUTS46ASCII tries to convert IDNs (international domain names) -// from Unicode form to Punycode, using non-transitional process specified -// in UTS 46. -// -// Note: conversion errors are silently discarded and partial conversion -// results are used. -func toUTS46ASCII(name string) string { - name, _ = nontransitionalLookup.ToASCII(name) - return name -} - -// CreateDNSRecord creates a DNS record for the zone identifier. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-create-dns-record -func (api *API) CreateDNSRecord(ctx context.Context, zoneID string, rr DNSRecord) (*DNSRecordResponse, error) { - rr.Name = toUTS46ASCII(rr.Name) - - uri := fmt.Sprintf("/zones/%s/dns_records", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, rr) - if err != nil { - return nil, err - } - - var recordResp *DNSRecordResponse - err = json.Unmarshal(res, &recordResp) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return recordResp, nil -} - -// DNSRecords returns a slice of DNS records for the given zone identifier. -// -// This takes a DNSRecord to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records -func (api *API) DNSRecords(ctx context.Context, zoneID string, rr DNSRecord) ([]DNSRecord, error) { - // Construct a query string - v := url.Values{} - // Request as many records as possible per page - API max is 100 - v.Set("per_page", "100") - if rr.Name != "" { - v.Set("name", toUTS46ASCII(rr.Name)) - } - if rr.Type != "" { - v.Set("type", rr.Type) - } - if rr.Content != "" { - v.Set("content", rr.Content) - } - - var records []DNSRecord - page := 1 - - // Loop over makeRequest until what we've fetched all records - for { - v.Set("page", strconv.Itoa(page)) - uri := fmt.Sprintf("/zones/%s/dns_records?%s", zoneID, v.Encode()) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []DNSRecord{}, err - } - var r DNSListResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []DNSRecord{}, errors.Wrap(err, errUnmarshalError) - } - records = append(records, r.Result...) - if r.ResultInfo.Page >= r.ResultInfo.TotalPages { - break - } - // Loop around and fetch the next page - page++ - } - return records, nil -} - -// DNSRecord returns a single DNS record for the given zone & record -// identifiers. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-dns-record-details -func (api *API) DNSRecord(ctx context.Context, zoneID, recordID string) (DNSRecord, error) { - uri := fmt.Sprintf("/zones/%s/dns_records/%s", zoneID, recordID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return DNSRecord{}, err - } - var r DNSRecordResponse - err = json.Unmarshal(res, &r) - if err != nil { - return DNSRecord{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateDNSRecord updates a single DNS record for the given zone & record -// identifiers. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record -func (api *API) UpdateDNSRecord(ctx context.Context, zoneID, recordID string, rr DNSRecord) error { - rr.Name = toUTS46ASCII(rr.Name) - - // Populate the record name from the existing one if the update didn't - // specify it. - if rr.Name == "" || rr.Type == "" { - rec, err := api.DNSRecord(ctx, zoneID, recordID) - if err != nil { - return err - } - - if rr.Name == "" { - rr.Name = rec.Name - } - if rr.Type == "" { - rr.Type = rec.Type - } - } - uri := fmt.Sprintf("/zones/%s/dns_records/%s", zoneID, recordID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, rr) - if err != nil { - return err - } - var r DNSRecordResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// DeleteDNSRecord deletes a single DNS record for the given zone & record -// identifiers. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-delete-dns-record -func (api *API) DeleteDNSRecord(ctx context.Context, zoneID, recordID string) error { - uri := fmt.Sprintf("/zones/%s/dns_records/%s", zoneID, recordID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - var r DNSRecordResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/duration.go b/vendor/github.com/cloudflare/cloudflare-go/duration.go deleted file mode 100644 index ba2418ac..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/duration.go +++ /dev/null @@ -1,40 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "time" -) - -// Duration implements json.Marshaler and json.Unmarshaler for time.Duration -// using the fmt.Stringer interface of time.Duration and time.ParseDuration. -type Duration struct { - time.Duration -} - -// MarshalJSON encodes a Duration as a JSON string formatted using String. -func (d Duration) MarshalJSON() ([]byte, error) { - return json.Marshal(d.Duration.String()) -} - -// UnmarshalJSON decodes a Duration from a JSON string parsed using time.ParseDuration. -func (d *Duration) UnmarshalJSON(buf []byte) error { - var str string - - err := json.Unmarshal(buf, &str) - if err != nil { - return err - } - - dur, err := time.ParseDuration(str) - if err != nil { - return err - } - - d.Duration = dur - return nil -} - -var ( - _ = json.Marshaler((*Duration)(nil)) - _ = json.Unmarshaler((*Duration)(nil)) -) diff --git a/vendor/github.com/cloudflare/cloudflare-go/errors.go b/vendor/github.com/cloudflare/cloudflare-go/errors.go deleted file mode 100644 index a08b1f36..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/errors.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudflare - -import ( - "fmt" - "net/http" - "strings" -) - -// Error messages -const ( - errEmptyCredentials = "invalid credentials: key & email must not be empty" - errEmptyAPIToken = "invalid credentials: API Token must not be empty" - errMakeRequestError = "error from makeRequest" - errUnmarshalError = "error unmarshalling the JSON response" - errUnmarshalErrorBody = "error unmarshalling the JSON response error body" - errRequestNotSuccessful = "error reported by API" - errMissingAccountID = "account ID is empty and must be provided" - errOperationStillRunning = "bulk operation did not finish before timeout" - errOperationUnexpectedStatus = "bulk operation returned an unexpected status" - errResultInfo = "incorrect pagination info (result_info) in responses" - errManualPagination = "unexpected pagination options passed to functions that handle pagination automatically" -) - -// APIRequestError is a type of error raised by API calls made by this library. -type APIRequestError struct { - StatusCode int - Errors []ResponseInfo -} - -func (e APIRequestError) Error() string { - errString := "" - errString += fmt.Sprintf("HTTP status %d", e.StatusCode) - - if len(e.Errors) > 0 { - errString += ": " - } - - errMessages := []string{} - for _, err := range e.Errors { - m := "" - if err.Message != "" { - m += err.Message - } - - if err.Code != 0 { - m += fmt.Sprintf(" (%d)", err.Code) - } - - errMessages = append(errMessages, m) - } - - return errString + strings.Join(errMessages, ", ") -} - -// HTTPStatusCode exposes the HTTP status from the error response encountered. -func (e APIRequestError) HTTPStatusCode() int { - return e.StatusCode -} - -// ErrorMessages exposes the error messages as a slice of strings from the error -// response encountered. -func (e *APIRequestError) ErrorMessages() []string { - messages := []string{} - - for _, e := range e.Errors { - messages = append(messages, e.Message) - } - - return messages -} - -// InternalErrorCodes exposes the internal error codes as a slice of int from -// the error response encountered. -func (e *APIRequestError) InternalErrorCodes() []int { - ec := []int{} - - for _, e := range e.Errors { - ec = append(ec, e.Code) - } - - return ec -} - -// ServiceError returns a boolean whether or not the raised error was caused by -// an internal service. -func (e *APIRequestError) ServiceError() bool { - return e.StatusCode >= http.StatusInternalServerError && - e.StatusCode < 600 -} - -// ClientError returns a boolean whether or not the raised error was caused by -// something client side. -func (e *APIRequestError) ClientError() bool { - return e.StatusCode >= http.StatusBadRequest && - e.StatusCode < http.StatusInternalServerError -} - -// ClientRateLimited returns a boolean whether or not the raised error was -// caused by too many requests from the client. -func (e *APIRequestError) ClientRateLimited() bool { - return e.StatusCode == http.StatusTooManyRequests -} - -// InternalErrorCodeIs returns a boolean whether or not the desired internal -// error code is present in `e.InternalErrorCodes`. -func (e *APIRequestError) InternalErrorCodeIs(code int) bool { - for _, errCode := range e.InternalErrorCodes() { - if errCode == code { - return true - } - } - - return false -} - -// ErrorMessageContains returns a boolean whether or not a substring exists in -// any of the `e.ErrorMessages` slice entries. -func (e *APIRequestError) ErrorMessageContains(s string) bool { - for _, errMsg := range e.ErrorMessages() { - if strings.Contains(errMsg, s) { - return true - } - } - return false -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/filter.go b/vendor/github.com/cloudflare/cloudflare-go/filter.go deleted file mode 100644 index f657303a..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/filter.go +++ /dev/null @@ -1,242 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - "strings" - - "github.com/pkg/errors" -) - -// Filter holds the structure of the filter type. -type Filter struct { - ID string `json:"id,omitempty"` - Expression string `json:"expression"` - Paused bool `json:"paused"` - Description string `json:"description"` - - // Property is mentioned in documentation however isn't populated in - // any of the API requests. For now, let's just omit it unless it's - // provided. - Ref string `json:"ref,omitempty"` -} - -// FiltersDetailResponse is the API response that is returned -// for requesting all filters on a zone. -type FiltersDetailResponse struct { - Result []Filter `json:"result"` - ResultInfo `json:"result_info"` - Response -} - -// FilterDetailResponse is the API response that is returned -// for requesting a single filter on a zone. -type FilterDetailResponse struct { - Result Filter `json:"result"` - ResultInfo `json:"result_info"` - Response -} - -// FilterValidateExpression represents the JSON payload for checking -// an expression. -type FilterValidateExpression struct { - Expression string `json:"expression"` -} - -// FilterValidateExpressionResponse represents the API response for -// checking the expression. It conforms to the JSON API approach however -// we don't need all of the fields exposed. -type FilterValidateExpressionResponse struct { - Success bool `json:"success"` - Errors []FilterValidationExpressionMessage `json:"errors"` -} - -// FilterValidationExpressionMessage represents the API error message. -type FilterValidationExpressionMessage struct { - Message string `json:"message"` -} - -// Filter returns a single filter in a zone based on the filter ID. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-filters/get/#get-by-filter-id -func (api *API) Filter(ctx context.Context, zoneID, filterID string) (Filter, error) { - uri := fmt.Sprintf("/zones/%s/filters/%s", zoneID, filterID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return Filter{}, err - } - - var filterResponse FilterDetailResponse - err = json.Unmarshal(res, &filterResponse) - if err != nil { - return Filter{}, errors.Wrap(err, errUnmarshalError) - } - - return filterResponse.Result, nil -} - -// Filters returns all filters for a zone. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-filters/get/#get-all-filters -func (api *API) Filters(ctx context.Context, zoneID string, pageOpts PaginationOptions) ([]Filter, error) { - uri := fmt.Sprintf("/zones/%s/filters", zoneID) - v := url.Values{} - - if pageOpts.PerPage > 0 { - v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) - } - - if pageOpts.Page > 0 { - v.Set("page", strconv.Itoa(pageOpts.Page)) - } - - if len(v) > 0 { - uri = fmt.Sprintf("%s?%s", uri, v.Encode()) - } - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []Filter{}, err - } - - var filtersResponse FiltersDetailResponse - err = json.Unmarshal(res, &filtersResponse) - if err != nil { - return []Filter{}, errors.Wrap(err, errUnmarshalError) - } - - return filtersResponse.Result, nil -} - -// CreateFilters creates new filters. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-filters/post/ -func (api *API) CreateFilters(ctx context.Context, zoneID string, filters []Filter) ([]Filter, error) { - uri := fmt.Sprintf("/zones/%s/filters", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, filters) - if err != nil { - return []Filter{}, err - } - - var filtersResponse FiltersDetailResponse - err = json.Unmarshal(res, &filtersResponse) - if err != nil { - return []Filter{}, errors.Wrap(err, errUnmarshalError) - } - - return filtersResponse.Result, nil -} - -// UpdateFilter updates a single filter. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-filters/put/#update-a-single-filter -func (api *API) UpdateFilter(ctx context.Context, zoneID string, filter Filter) (Filter, error) { - if filter.ID == "" { - return Filter{}, errors.Errorf("filter ID cannot be empty") - } - - uri := fmt.Sprintf("/zones/%s/filters/%s", zoneID, filter.ID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, filter) - if err != nil { - return Filter{}, err - } - - var filterResponse FilterDetailResponse - err = json.Unmarshal(res, &filterResponse) - if err != nil { - return Filter{}, errors.Wrap(err, errUnmarshalError) - } - - return filterResponse.Result, nil -} - -// UpdateFilters updates many filters at once. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-filters/put/#update-multiple-filters -func (api *API) UpdateFilters(ctx context.Context, zoneID string, filters []Filter) ([]Filter, error) { - for _, filter := range filters { - if filter.ID == "" { - return []Filter{}, errors.Errorf("filter ID cannot be empty") - } - } - - uri := fmt.Sprintf("/zones/%s/filters", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, filters) - if err != nil { - return []Filter{}, err - } - - var filtersResponse FiltersDetailResponse - err = json.Unmarshal(res, &filtersResponse) - if err != nil { - return []Filter{}, errors.Wrap(err, errUnmarshalError) - } - - return filtersResponse.Result, nil -} - -// DeleteFilter deletes a single filter. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-filters/delete/#delete-a-single-filter -func (api *API) DeleteFilter(ctx context.Context, zoneID, filterID string) error { - if filterID == "" { - return errors.Errorf("filter ID cannot be empty") - } - - uri := fmt.Sprintf("/zones/%s/filters/%s", zoneID, filterID) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} - -// DeleteFilters deletes multiple filters. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-filters/delete/#delete-multiple-filters -func (api *API) DeleteFilters(ctx context.Context, zoneID string, filterIDs []string) error { - ids := strings.Join(filterIDs, ",") - uri := fmt.Sprintf("/zones/%s/filters?id=%s", zoneID, ids) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} - -// ValidateFilterExpression checks correctness of a filter expression. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-filters/validation/ -func (api *API) ValidateFilterExpression(ctx context.Context, expression string) error { - expressionPayload := FilterValidateExpression{Expression: expression} - - _, err := api.makeRequestContext(ctx, http.MethodPost, "/filters/validate-expr", expressionPayload) - if err != nil { - var filterValidationResponse FilterValidateExpressionResponse - - jsonErr := json.Unmarshal([]byte(err.Error()), &filterValidationResponse) - if jsonErr != nil { - return errors.Wrap(jsonErr, errUnmarshalError) - } - - if !filterValidationResponse.Success { - // Unsure why but the API returns `errors` as an array but it only - // ever shows the issue with one problem at a time ¯\_(ツ)_/¯ - return errors.Errorf(filterValidationResponse.Errors[0].Message) - } - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/firewall.go b/vendor/github.com/cloudflare/cloudflare-go/firewall.go deleted file mode 100644 index cbf78da5..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/firewall.go +++ /dev/null @@ -1,282 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -// AccessRule represents a firewall access rule. -type AccessRule struct { - ID string `json:"id,omitempty"` - Notes string `json:"notes,omitempty"` - AllowedModes []string `json:"allowed_modes,omitempty"` - Mode string `json:"mode,omitempty"` - Configuration AccessRuleConfiguration `json:"configuration,omitempty"` - Scope AccessRuleScope `json:"scope,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` - ModifiedOn time.Time `json:"modified_on,omitempty"` -} - -// AccessRuleConfiguration represents the configuration of a firewall -// access rule. -type AccessRuleConfiguration struct { - Target string `json:"target,omitempty"` - Value string `json:"value,omitempty"` -} - -// AccessRuleScope represents the scope of a firewall access rule. -type AccessRuleScope struct { - ID string `json:"id,omitempty"` - Email string `json:"email,omitempty"` - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` -} - -// AccessRuleResponse represents the response from the firewall access -// rule endpoint. -type AccessRuleResponse struct { - Result AccessRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccessRuleListResponse represents the response from the list access rules -// endpoint. -type AccessRuleListResponse struct { - Result []AccessRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// ListUserAccessRules returns a slice of access rules for the logged-in user. -// -// This takes an AccessRule to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-list-access-rules -func (api *API) ListUserAccessRules(ctx context.Context, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules(ctx, "/user", accessRule, page) -} - -// CreateUserAccessRule creates a firewall access rule for the logged-in user. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-create-access-rule -func (api *API) CreateUserAccessRule(ctx context.Context, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule(ctx, "/user", accessRule) -} - -// UserAccessRule returns the details of a user's account access rule. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-list-access-rules -func (api *API) UserAccessRule(ctx context.Context, accessRuleID string) (*AccessRuleResponse, error) { - return api.retrieveAccessRule(ctx, "/user", accessRuleID) -} - -// UpdateUserAccessRule updates a single access rule for the logged-in user & -// given access rule identifier. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-update-access-rule -func (api *API) UpdateUserAccessRule(ctx context.Context, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule(ctx, "/user", accessRuleID, accessRule) -} - -// DeleteUserAccessRule deletes a single access rule for the logged-in user and -// access rule identifiers. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-update-access-rule -func (api *API) DeleteUserAccessRule(ctx context.Context, accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule(ctx, "/user", accessRuleID) -} - -// ListZoneAccessRules returns a slice of access rules for the given zone -// identifier. -// -// This takes an AccessRule to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-list-access-rules -func (api *API) ListZoneAccessRules(ctx context.Context, zoneID string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules(ctx, fmt.Sprintf("/zones/%s", zoneID), accessRule, page) -} - -// CreateZoneAccessRule creates a firewall access rule for the given zone -// identifier. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-create-access-rule -func (api *API) CreateZoneAccessRule(ctx context.Context, zoneID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule(ctx, fmt.Sprintf("/zones/%s", zoneID), accessRule) -} - -// ZoneAccessRule returns the details of a zone's access rule. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-list-access-rules -func (api *API) ZoneAccessRule(ctx context.Context, zoneID string, accessRuleID string) (*AccessRuleResponse, error) { - return api.retrieveAccessRule(ctx, fmt.Sprintf("/zones/%s", zoneID), accessRuleID) -} - -// UpdateZoneAccessRule updates a single access rule for the given zone & -// access rule identifiers. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-update-access-rule -func (api *API) UpdateZoneAccessRule(ctx context.Context, zoneID, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule(ctx, fmt.Sprintf("/zones/%s", zoneID), accessRuleID, accessRule) -} - -// DeleteZoneAccessRule deletes a single access rule for the given zone and -// access rule identifiers. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-delete-access-rule -func (api *API) DeleteZoneAccessRule(ctx context.Context, zoneID, accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule(ctx, fmt.Sprintf("/zones/%s", zoneID), accessRuleID) -} - -// ListAccountAccessRules returns a slice of access rules for the given -// account identifier. -// -// This takes an AccessRule to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#account-level-firewall-access-rule-list-access-rules -func (api *API) ListAccountAccessRules(ctx context.Context, accountID string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules(ctx, fmt.Sprintf("/accounts/%s", accountID), accessRule, page) -} - -// CreateAccountAccessRule creates a firewall access rule for the given -// account identifier. -// -// API reference: https://api.cloudflare.com/#account-level-firewall-access-rule-create-access-rule -func (api *API) CreateAccountAccessRule(ctx context.Context, accountID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule(ctx, fmt.Sprintf("/accounts/%s", accountID), accessRule) -} - -// AccountAccessRule returns the details of an account's access rule. -// -// API reference: https://api.cloudflare.com/#account-level-firewall-access-rule-access-rule-details -func (api *API) AccountAccessRule(ctx context.Context, accountID string, accessRuleID string) (*AccessRuleResponse, error) { - return api.retrieveAccessRule(ctx, fmt.Sprintf("/accounts/%s", accountID), accessRuleID) -} - -// UpdateAccountAccessRule updates a single access rule for the given -// account & access rule identifiers. -// -// API reference: https://api.cloudflare.com/#account-level-firewall-access-rule-update-access-rule -func (api *API) UpdateAccountAccessRule(ctx context.Context, accountID, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule(ctx, fmt.Sprintf("/accounts/%s", accountID), accessRuleID, accessRule) -} - -// DeleteAccountAccessRule deletes a single access rule for the given -// account and access rule identifiers. -// -// API reference: https://api.cloudflare.com/#account-level-firewall-access-rule-delete-access-rule -func (api *API) DeleteAccountAccessRule(ctx context.Context, accountID, accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule(ctx, fmt.Sprintf("/accounts/%s", accountID), accessRuleID) -} - -func (api *API) listAccessRules(ctx context.Context, prefix string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - // Construct a query string - v := url.Values{} - if page <= 0 { - page = 1 - } - v.Set("page", strconv.Itoa(page)) - // Request as many rules as possible per page - API max is 100 - v.Set("per_page", "100") - if accessRule.Notes != "" { - v.Set("notes", accessRule.Notes) - } - if accessRule.Mode != "" { - v.Set("mode", accessRule.Mode) - } - if accessRule.Scope.Type != "" { - v.Set("scope_type", accessRule.Scope.Type) - } - if accessRule.Configuration.Value != "" { - v.Set("configuration_value", accessRule.Configuration.Value) - } - if accessRule.Configuration.Target != "" { - v.Set("configuration_target", accessRule.Configuration.Target) - } - v.Set("page", strconv.Itoa(page)) - - uri := fmt.Sprintf("%s/firewall/access_rules/rules?%s", prefix, v.Encode()) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - response := &AccessRuleListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return response, nil -} - -func (api *API) createAccessRule(ctx context.Context, prefix string, accessRule AccessRule) (*AccessRuleResponse, error) { - uri := fmt.Sprintf("%s/firewall/access_rules/rules", prefix) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, accessRule) - if err != nil { - return nil, err - } - - response := &AccessRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -func (api *API) retrieveAccessRule(ctx context.Context, prefix, accessRuleID string) (*AccessRuleResponse, error) { - uri := fmt.Sprintf("%s/firewall/access_rules/rules/%s", prefix, accessRuleID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - - if err != nil { - return nil, err - } - - response := &AccessRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -func (api *API) updateAccessRule(ctx context.Context, prefix, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - uri := fmt.Sprintf("%s/firewall/access_rules/rules/%s", prefix, accessRuleID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, accessRule) - if err != nil { - return nil, err - } - - response := &AccessRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return response, nil -} - -func (api *API) deleteAccessRule(ctx context.Context, prefix, accessRuleID string) (*AccessRuleResponse, error) { - uri := fmt.Sprintf("%s/firewall/access_rules/rules/%s", prefix, accessRuleID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return nil, err - } - - response := &AccessRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/firewall_rules.go b/vendor/github.com/cloudflare/cloudflare-go/firewall_rules.go deleted file mode 100644 index 480b3895..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/firewall_rules.go +++ /dev/null @@ -1,203 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -// FirewallRule is the struct of the firewall rule. -type FirewallRule struct { - ID string `json:"id,omitempty"` - Paused bool `json:"paused"` - Description string `json:"description"` - Action string `json:"action"` - Priority interface{} `json:"priority"` - Filter Filter `json:"filter"` - Products []string `json:"products,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` - ModifiedOn time.Time `json:"modified_on,omitempty"` -} - -// FirewallRulesDetailResponse is the API response for the firewall -// rules. -type FirewallRulesDetailResponse struct { - Result []FirewallRule `json:"result"` - ResultInfo `json:"result_info"` - Response -} - -// FirewallRuleResponse is the API response that is returned -// for requesting a single firewall rule on a zone. -type FirewallRuleResponse struct { - Result FirewallRule `json:"result"` - ResultInfo `json:"result_info"` - Response -} - -// FirewallRules returns all firewall rules. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/get/#get-all-rules -func (api *API) FirewallRules(ctx context.Context, zoneID string, pageOpts PaginationOptions) ([]FirewallRule, error) { - uri := fmt.Sprintf("/zones/%s/firewall/rules", zoneID) - v := url.Values{} - - if pageOpts.PerPage > 0 { - v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) - } - - if pageOpts.Page > 0 { - v.Set("page", strconv.Itoa(pageOpts.Page)) - } - - if len(v) > 0 { - uri = fmt.Sprintf("%s?%s", uri, v.Encode()) - } - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []FirewallRule{}, err - } - - var firewallDetailResponse FirewallRulesDetailResponse - err = json.Unmarshal(res, &firewallDetailResponse) - if err != nil { - return []FirewallRule{}, errors.Wrap(err, errUnmarshalError) - } - - return firewallDetailResponse.Result, nil -} - -// FirewallRule returns a single firewall rule based on the ID. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/get/#get-by-rule-id -func (api *API) FirewallRule(ctx context.Context, zoneID, firewallRuleID string) (FirewallRule, error) { - uri := fmt.Sprintf("/zones/%s/firewall/rules/%s", zoneID, firewallRuleID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return FirewallRule{}, err - } - - var firewallRuleResponse FirewallRuleResponse - err = json.Unmarshal(res, &firewallRuleResponse) - if err != nil { - return FirewallRule{}, errors.Wrap(err, errUnmarshalError) - } - - return firewallRuleResponse.Result, nil -} - -// CreateFirewallRules creates new firewall rules. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/post/ -func (api *API) CreateFirewallRules(ctx context.Context, zoneID string, firewallRules []FirewallRule) ([]FirewallRule, error) { - uri := fmt.Sprintf("/zones/%s/firewall/rules", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, firewallRules) - if err != nil { - return []FirewallRule{}, err - } - - var firewallRulesDetailResponse FirewallRulesDetailResponse - err = json.Unmarshal(res, &firewallRulesDetailResponse) - if err != nil { - return []FirewallRule{}, errors.Wrap(err, errUnmarshalError) - } - - return firewallRulesDetailResponse.Result, nil -} - -// UpdateFirewallRule updates a single firewall rule. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/put/#update-a-single-rule -func (api *API) UpdateFirewallRule(ctx context.Context, zoneID string, firewallRule FirewallRule) (FirewallRule, error) { - if firewallRule.ID == "" { - return FirewallRule{}, errors.Errorf("firewall rule ID cannot be empty") - } - - uri := fmt.Sprintf("/zones/%s/firewall/rules/%s", zoneID, firewallRule.ID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, firewallRule) - if err != nil { - return FirewallRule{}, err - } - - var firewallRuleResponse FirewallRuleResponse - err = json.Unmarshal(res, &firewallRuleResponse) - if err != nil { - return FirewallRule{}, errors.Wrap(err, errUnmarshalError) - } - - return firewallRuleResponse.Result, nil -} - -// UpdateFirewallRules updates a single firewall rule. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/put/#update-multiple-rules -func (api *API) UpdateFirewallRules(ctx context.Context, zoneID string, firewallRules []FirewallRule) ([]FirewallRule, error) { - for _, firewallRule := range firewallRules { - if firewallRule.ID == "" { - return []FirewallRule{}, errors.Errorf("firewall ID cannot be empty") - } - } - - uri := fmt.Sprintf("/zones/%s/firewall/rules", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, firewallRules) - if err != nil { - return []FirewallRule{}, err - } - - var firewallRulesDetailResponse FirewallRulesDetailResponse - err = json.Unmarshal(res, &firewallRulesDetailResponse) - if err != nil { - return []FirewallRule{}, errors.Wrap(err, errUnmarshalError) - } - - return firewallRulesDetailResponse.Result, nil -} - -// DeleteFirewallRule deletes a single firewall rule. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/delete/#delete-a-single-rule -func (api *API) DeleteFirewallRule(ctx context.Context, zoneID, firewallRuleID string) error { - if firewallRuleID == "" { - return errors.Errorf("firewall rule ID cannot be empty") - } - - uri := fmt.Sprintf("/zones/%s/firewall/rules/%s", zoneID, firewallRuleID) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} - -// DeleteFirewallRules deletes multiple firewall rules at once. -// -// API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/delete/#delete-multiple-rules -func (api *API) DeleteFirewallRules(ctx context.Context, zoneID string, firewallRuleIDs []string) error { - v := url.Values{} - - for _, ruleID := range firewallRuleIDs { - v.Add("id", ruleID) - } - - uri := fmt.Sprintf("/zones/%s/firewall/rules?%s", zoneID, v.Encode()) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/healthchecks.go b/vendor/github.com/cloudflare/cloudflare-go/healthchecks.go deleted file mode 100644 index 24d33ce8..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/healthchecks.go +++ /dev/null @@ -1,207 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// Healthcheck describes a Healthcheck object. -type Healthcheck struct { - ID string `json:"id,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - Name string `json:"name"` - Description string `json:"description"` - Suspended bool `json:"suspended"` - Address string `json:"address"` - Retries int `json:"retries,omitempty"` - Timeout int `json:"timeout,omitempty"` - Interval int `json:"interval,omitempty"` - ConsecutiveSuccesses int `json:"consecutive_successes,omitempty"` - ConsecutiveFails int `json:"consecutive_fails,omitempty"` - Type string `json:"type,omitempty"` - CheckRegions []string `json:"check_regions"` - HTTPConfig *HealthcheckHTTPConfig `json:"http_config,omitempty"` - TCPConfig *HealthcheckTCPConfig `json:"tcp_config,omitempty"` - Notification HealthcheckNotification `json:"notification,omitempty"` - Status string `json:"status"` - FailureReason string `json:"failure_reason"` -} - -// HealthcheckHTTPConfig describes configuration for a HTTP healthcheck. -type HealthcheckHTTPConfig struct { - Method string `json:"method"` - Port uint16 `json:"port,omitempty"` - Path string `json:"path"` - ExpectedCodes []string `json:"expected_codes"` - ExpectedBody string `json:"expected_body"` - FollowRedirects bool `json:"follow_redirects"` - AllowInsecure bool `json:"allow_insecure"` - Header map[string][]string `json:"header"` -} - -// HealthcheckTCPConfig describes configuration for a TCP healthcheck. -type HealthcheckTCPConfig struct { - Method string `json:"method"` - Port uint16 `json:"port,omitempty"` -} - -// HealthcheckNotification describes notification configuration for a healthcheck. -type HealthcheckNotification struct { - Suspended bool `json:"suspended,omitempty"` - EmailAddresses []string `json:"email_addresses,omitempty"` -} - -// HealthcheckListResponse is the API response, containing an array of healthchecks. -type HealthcheckListResponse struct { - Response - Result []Healthcheck `json:"result"` - ResultInfo `json:"result_info"` -} - -// HealthcheckResponse is the API response, containing a single healthcheck. -type HealthcheckResponse struct { - Response - Result Healthcheck `json:"result"` -} - -// Healthchecks returns all healthchecks for a zone. -// -// API reference: https://api.cloudflare.com/#health-checks-list-health-checks -func (api *API) Healthchecks(ctx context.Context, zoneID string) ([]Healthcheck, error) { - uri := fmt.Sprintf("/zones/%s/healthchecks", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []Healthcheck{}, err - } - var r HealthcheckListResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []Healthcheck{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// Healthcheck returns a single healthcheck by ID. -// -// API reference: https://api.cloudflare.com/#health-checks-health-check-details -func (api *API) Healthcheck(ctx context.Context, zoneID, healthcheckID string) (Healthcheck, error) { - uri := fmt.Sprintf("/zones/%s/healthchecks/%s", zoneID, healthcheckID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return Healthcheck{}, err - } - var r HealthcheckResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Healthcheck{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// CreateHealthcheck creates a new healthcheck in a zone. -// -// API reference: https://api.cloudflare.com/#health-checks-create-health-check -func (api *API) CreateHealthcheck(ctx context.Context, zoneID string, healthcheck Healthcheck) (Healthcheck, error) { - uri := fmt.Sprintf("/zones/%s/healthchecks", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, healthcheck) - if err != nil { - return Healthcheck{}, err - } - var r HealthcheckResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Healthcheck{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateHealthcheck updates an existing healthcheck. -// -// API reference: https://api.cloudflare.com/#health-checks-update-health-check -func (api *API) UpdateHealthcheck(ctx context.Context, zoneID string, healthcheckID string, healthcheck Healthcheck) (Healthcheck, error) { - uri := fmt.Sprintf("/zones/%s/healthchecks/%s", zoneID, healthcheckID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, healthcheck) - if err != nil { - return Healthcheck{}, err - } - var r HealthcheckResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Healthcheck{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteHealthcheck deletes a healthcheck in a zone. -// -// API reference: https://api.cloudflare.com/#health-checks-delete-health-check -func (api *API) DeleteHealthcheck(ctx context.Context, zoneID string, healthcheckID string) error { - uri := fmt.Sprintf("/zones/%s/healthchecks/%s", zoneID, healthcheckID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - var r HealthcheckResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// CreateHealthcheckPreview creates a new preview of a healthcheck in a zone. -// -// API reference: https://api.cloudflare.com/#health-checks-create-preview-health-check -func (api *API) CreateHealthcheckPreview(ctx context.Context, zoneID string, healthcheck Healthcheck) (Healthcheck, error) { - uri := fmt.Sprintf("/zones/%s/healthchecks/preview", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, healthcheck) - if err != nil { - return Healthcheck{}, err - } - var r HealthcheckResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Healthcheck{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// HealthcheckPreview returns a single healthcheck preview by its ID. -// -// API reference: https://api.cloudflare.com/#health-checks-health-check-preview-details -func (api *API) HealthcheckPreview(ctx context.Context, zoneID, id string) (Healthcheck, error) { - uri := fmt.Sprintf("/zones/%s/healthchecks/preview/%s", zoneID, id) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return Healthcheck{}, err - } - var r HealthcheckResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Healthcheck{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteHealthcheckPreview deletes a healthcheck preview in a zone if it exists. -// -// API reference: https://api.cloudflare.com/#health-checks-delete-preview-health-check -func (api *API) DeleteHealthcheckPreview(ctx context.Context, zoneID string, id string) error { - uri := fmt.Sprintf("/zones/%s/healthchecks/preview/%s", zoneID, id) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - var r HealthcheckResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/ip_address_management.go b/vendor/github.com/cloudflare/cloudflare-go/ip_address_management.go deleted file mode 100644 index de6fcb76..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/ip_address_management.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// IPPrefix contains information about an IP prefix -type IPPrefix struct { - ID string `json:"id"` - CreatedAt *time.Time `json:"created_at"` - ModifiedAt *time.Time `json:"modified_at"` - CIDR string `json:"cidr"` - AccountID string `json:"account_id"` - Description string `json:"description"` - Approved string `json:"approved"` - OnDemandEnabled bool `json:"on_demand_enabled"` - OnDemandLocked bool `json:"on_demand_locked"` - Advertised bool `json:"advertised"` - AdvertisedModifiedAt *time.Time `json:"advertised_modified_at"` -} - -// AdvertisementStatus contains information about the BGP status of an IP prefix -type AdvertisementStatus struct { - Advertised bool `json:"advertised"` - AdvertisedModifiedAt *time.Time `json:"advertised_modified_at"` -} - -// ListIPPrefixResponse contains a slice of IP prefixes -type ListIPPrefixResponse struct { - Response - Result []IPPrefix `json:"result"` -} - -// GetIPPrefixResponse contains a specific IP prefix's API Response -type GetIPPrefixResponse struct { - Response - Result IPPrefix `json:"result"` -} - -// GetAdvertisementStatusResponse contains an API Response for the BGP status of the IP Prefix -type GetAdvertisementStatusResponse struct { - Response - Result AdvertisementStatus `json:"result"` -} - -// IPPrefixUpdateRequest contains information about prefix updates -type IPPrefixUpdateRequest struct { - Description string `json:"description"` -} - -// AdvertisementStatusUpdateRequest contains information about bgp status updates -type AdvertisementStatusUpdateRequest struct { - Advertised bool `json:"advertised"` -} - -// ListPrefixes lists all IP prefixes for a given account -// -// API reference: https://api.cloudflare.com/#ip-address-management-prefixes-list-prefixes -func (api *API) ListPrefixes(ctx context.Context) ([]IPPrefix, error) { - uri := fmt.Sprintf("/accounts/%s/addressing/prefixes", api.AccountID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []IPPrefix{}, err - } - - result := ListIPPrefixResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return []IPPrefix{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// GetPrefix returns a specific IP prefix -// -// API reference: https://api.cloudflare.com/#ip-address-management-prefixes-prefix-details -func (api *API) GetPrefix(ctx context.Context, id string) (IPPrefix, error) { - uri := fmt.Sprintf("/accounts/%s/addressing/prefixes/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return IPPrefix{}, err - } - - result := GetIPPrefixResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPPrefix{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// UpdatePrefixDescription edits the description of the IP prefix -// -// API reference: https://api.cloudflare.com/#ip-address-management-prefixes-update-prefix-description -func (api *API) UpdatePrefixDescription(ctx context.Context, id string, description string) (IPPrefix, error) { - uri := fmt.Sprintf("/accounts/%s/addressing/prefixes/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, IPPrefixUpdateRequest{Description: description}) - if err != nil { - return IPPrefix{}, err - } - - result := GetIPPrefixResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPPrefix{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// GetAdvertisementStatus returns the BGP status of the IP prefix -// -// API reference: https://api.cloudflare.com/#ip-address-management-prefixes-update-prefix-description -func (api *API) GetAdvertisementStatus(ctx context.Context, id string) (AdvertisementStatus, error) { - uri := fmt.Sprintf("/accounts/%s/addressing/prefixes/%s/bgp/status", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return AdvertisementStatus{}, err - } - - result := GetAdvertisementStatusResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return AdvertisementStatus{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// UpdateAdvertisementStatus changes the BGP status of an IP prefix -// -// API reference: https://api.cloudflare.com/#ip-address-management-prefixes-update-prefix-description -func (api *API) UpdateAdvertisementStatus(ctx context.Context, id string, advertised bool) (AdvertisementStatus, error) { - uri := fmt.Sprintf("/accounts/%s/addressing/prefixes/%s/bgp/status", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, AdvertisementStatusUpdateRequest{Advertised: advertised}) - if err != nil { - return AdvertisementStatus{}, err - } - - result := GetAdvertisementStatusResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return AdvertisementStatus{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/ip_list.go b/vendor/github.com/cloudflare/cloudflare-go/ip_list.go deleted file mode 100644 index e09b1f1a..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/ip_list.go +++ /dev/null @@ -1,463 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -const ( - // IPListTypeIP specifies a list containing IP addresses - IPListTypeIP = "ip" -) - -// IPListBulkOperation contains information about a Bulk Operation -type IPListBulkOperation struct { - ID string `json:"id"` - Status string `json:"status"` - Error string `json:"error"` - Completed *time.Time `json:"completed"` -} - -// IPList contains information about an IP List -type IPList struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Kind string `json:"kind"` - NumItems int `json:"num_items"` - NumReferencingFilters int `json:"num_referencing_filters"` - CreatedOn *time.Time `json:"created_on"` - ModifiedOn *time.Time `json:"modified_on"` -} - -// IPListItem contains information about a single IP List Item -type IPListItem struct { - ID string `json:"id"` - IP string `json:"ip"` - Comment string `json:"comment"` - CreatedOn *time.Time `json:"created_on"` - ModifiedOn *time.Time `json:"modified_on"` -} - -// IPListCreateRequest contains data for a new IP List -type IPListCreateRequest struct { - Name string `json:"name"` - Description string `json:"description"` - Kind string `json:"kind"` -} - -// IPListItemCreateRequest contains data for a new IP List Item -type IPListItemCreateRequest struct { - IP string `json:"ip"` - Comment string `json:"comment"` -} - -// IPListItemDeleteRequest wraps IP List Items that shall be deleted -type IPListItemDeleteRequest struct { - Items []IPListItemDeleteItemRequest `json:"items"` -} - -// IPListItemDeleteItemRequest contains single IP List Items that shall be deleted -type IPListItemDeleteItemRequest struct { - ID string `json:"id"` -} - -// IPListUpdateRequest contains data for an IP List update -type IPListUpdateRequest struct { - Description string `json:"description"` -} - -// IPListResponse contains a single IP List -type IPListResponse struct { - Response - Result IPList `json:"result"` -} - -// IPListItemCreateResponse contains information about the creation of an IP List Item -type IPListItemCreateResponse struct { - Response - Result struct { - OperationID string `json:"operation_id"` - } `json:"result"` -} - -// IPListListResponse contains a slice of IP Lists -type IPListListResponse struct { - Response - Result []IPList `json:"result"` -} - -// IPListBulkOperationResponse contains information about a Bulk Operation -type IPListBulkOperationResponse struct { - Response - Result IPListBulkOperation `json:"result"` -} - -// IPListDeleteResponse contains information about the deletion of an IP List -type IPListDeleteResponse struct { - Response - Result struct { - ID string `json:"id"` - } `json:"result"` -} - -// IPListItemsListResponse contains information about IP List Items -type IPListItemsListResponse struct { - Response - ResultInfo `json:"result_info"` - Result []IPListItem `json:"result"` -} - -// IPListItemDeleteResponse contains information about the deletion of an IP List Item -type IPListItemDeleteResponse struct { - Response - Result struct { - OperationID string `json:"operation_id"` - } `json:"result"` -} - -// IPListItemsGetResponse contains information about a single IP List Item -type IPListItemsGetResponse struct { - Response - Result IPListItem `json:"result"` -} - -// ListIPLists lists all IP Lists -// -// API reference: https://api.cloudflare.com/#rules-lists-list-lists -func (api *API) ListIPLists(ctx context.Context) ([]IPList, error) { - uri := fmt.Sprintf("/accounts/%s/rules/lists", api.AccountID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []IPList{}, err - } - - result := IPListListResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return []IPList{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// CreateIPList creates a new IP List -// -// API reference: https://api.cloudflare.com/#rules-lists-create-list -func (api *API) CreateIPList(ctx context.Context, name string, description string, kind string) (IPList, - error) { - uri := fmt.Sprintf("/accounts/%s/rules/lists", api.AccountID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, - IPListCreateRequest{Name: name, Description: description, Kind: kind}) - if err != nil { - return IPList{}, err - } - - result := IPListResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPList{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// GetIPList returns a single IP List -// -// API reference: https://api.cloudflare.com/#rules-lists-get-list -func (api *API) GetIPList(ctx context.Context, id string) (IPList, error) { - uri := fmt.Sprintf("/accounts/%s/rules/lists/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return IPList{}, err - } - - result := IPListResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPList{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// UpdateIPList updates the description of an existing IP List -// -// API reference: https://api.cloudflare.com/#rules-lists-update-list -func (api *API) UpdateIPList(ctx context.Context, id string, description string) (IPList, error) { - uri := fmt.Sprintf("/accounts/%s/rules/lists/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, IPListUpdateRequest{Description: description}) - if err != nil { - return IPList{}, err - } - - result := IPListResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPList{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// DeleteIPList deletes an IP List -// -// API reference: https://api.cloudflare.com/#rules-lists-delete-list -func (api *API) DeleteIPList(ctx context.Context, id string) (IPListDeleteResponse, error) { - uri := fmt.Sprintf("/accounts/%s/rules/lists/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return IPListDeleteResponse{}, err - } - - result := IPListDeleteResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPListDeleteResponse{}, errors.Wrap(err, errUnmarshalError) - } - - return result, nil -} - -// ListIPListItems returns a list with all items in an IP List -// -// API reference: https://api.cloudflare.com/#rules-lists-list-list-items -func (api *API) ListIPListItems(ctx context.Context, id string) ([]IPListItem, error) { - var list []IPListItem - var cursor string - var cursorQuery string - - for { - if len(cursor) > 0 { - cursorQuery = fmt.Sprintf("?cursor=%s", cursor) - } - uri := fmt.Sprintf("/accounts/%s/rules/lists/%s/items%s", api.AccountID, id, cursorQuery) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []IPListItem{}, err - } - - result := IPListItemsListResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return []IPListItem{}, errors.Wrap(err, errUnmarshalError) - } - - list = append(list, result.Result...) - if cursor = result.ResultInfo.Cursors.After; cursor == "" { - break - } - } - - return list, nil -} - -// CreateIPListItemAsync creates a new IP List Item asynchronously. Users have to poll the operation status by -// using the operation_id returned by this function. -// -// API reference: https://api.cloudflare.com/#rules-lists-create-list-items -func (api *API) CreateIPListItemAsync(ctx context.Context, id, ip, comment string) (IPListItemCreateResponse, error) { - uri := fmt.Sprintf("/accounts/%s/rules/lists/%s/items", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, []IPListItemCreateRequest{{IP: ip, Comment: comment}}) - if err != nil { - return IPListItemCreateResponse{}, err - } - - result := IPListItemCreateResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPListItemCreateResponse{}, errors.Wrap(err, errUnmarshalError) - } - - return result, nil -} - -// CreateIPListItem creates a new IP List Item synchronously and returns the current set of IP List Items -func (api *API) CreateIPListItem(ctx context.Context, id, ip, comment string) ([]IPListItem, error) { - result, err := api.CreateIPListItemAsync(ctx, id, ip, comment) - - if err != nil { - return []IPListItem{}, err - } - - err = api.pollIPListBulkOperation(ctx, result.Result.OperationID) - if err != nil { - return []IPListItem{}, err - } - - return api.ListIPListItems(ctx, id) -} - -// CreateIPListItemsAsync bulk creates many IP List Items asynchronously. Users have to poll the operation status by -// using the operation_id returned by this function. -// -// API reference: https://api.cloudflare.com/#rules-lists-create-list-items -func (api *API) CreateIPListItemsAsync(ctx context.Context, id string, items []IPListItemCreateRequest) ( - IPListItemCreateResponse, error) { - uri := fmt.Sprintf("/accounts/%s/rules/lists/%s/items", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, items) - if err != nil { - return IPListItemCreateResponse{}, err - } - - result := IPListItemCreateResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPListItemCreateResponse{}, errors.Wrap(err, errUnmarshalError) - } - - return result, nil -} - -// CreateIPListItems bulk creates many IP List Items synchronously and returns the current set of IP List Items -func (api *API) CreateIPListItems(ctx context.Context, id string, items []IPListItemCreateRequest) ( - []IPListItem, error) { - result, err := api.CreateIPListItemsAsync(ctx, id, items) - if err != nil { - return []IPListItem{}, err - } - - err = api.pollIPListBulkOperation(ctx, result.Result.OperationID) - if err != nil { - return []IPListItem{}, err - } - - return api.ListIPListItems(ctx, id) -} - -// ReplaceIPListItemsAsync replaces all IP List Items asynchronously. Users have to poll the operation status by -// using the operation_id returned by this function. -// -// API reference: https://api.cloudflare.com/#rules-lists-replace-list-items -func (api *API) ReplaceIPListItemsAsync(ctx context.Context, id string, items []IPListItemCreateRequest) ( - IPListItemCreateResponse, error) { - uri := fmt.Sprintf("/accounts/%s/rules/lists/%s/items", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, items) - if err != nil { - return IPListItemCreateResponse{}, err - } - - result := IPListItemCreateResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPListItemCreateResponse{}, errors.Wrap(err, errUnmarshalError) - } - - return result, nil -} - -// ReplaceIPListItems replaces all IP List Items synchronously and returns the current set of IP List Items -func (api *API) ReplaceIPListItems(ctx context.Context, id string, items []IPListItemCreateRequest) ( - []IPListItem, error) { - result, err := api.ReplaceIPListItemsAsync(ctx, id, items) - if err != nil { - return []IPListItem{}, err - } - - err = api.pollIPListBulkOperation(ctx, result.Result.OperationID) - if err != nil { - return []IPListItem{}, err - } - - return api.ListIPListItems(ctx, id) -} - -// DeleteIPListItemsAsync removes specific Items of an IP List by their ID asynchronously. Users have to poll the -// operation status by using the operation_id returned by this function. -// -// API reference: https://api.cloudflare.com/#rules-lists-delete-list-items -func (api *API) DeleteIPListItemsAsync(ctx context.Context, id string, items IPListItemDeleteRequest) ( - IPListItemDeleteResponse, error) { - uri := fmt.Sprintf("/accounts/%s/rules/lists/%s/items", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, items) - if err != nil { - return IPListItemDeleteResponse{}, err - } - - result := IPListItemDeleteResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPListItemDeleteResponse{}, errors.Wrap(err, errUnmarshalError) - } - - return result, nil -} - -// DeleteIPListItems removes specific Items of an IP List by their ID synchronously and returns the current set -// of IP List Items -func (api *API) DeleteIPListItems(ctx context.Context, id string, items IPListItemDeleteRequest) ( - []IPListItem, error) { - result, err := api.DeleteIPListItemsAsync(ctx, id, items) - if err != nil { - return []IPListItem{}, err - } - - err = api.pollIPListBulkOperation(ctx, result.Result.OperationID) - if err != nil { - return []IPListItem{}, err - } - - return api.ListIPListItems(ctx, id) -} - -// GetIPListItem returns a single IP List Item -// -// API reference: https://api.cloudflare.com/#rules-lists-get-list-item -func (api *API) GetIPListItem(ctx context.Context, listID, id string) (IPListItem, error) { - uri := fmt.Sprintf("/accounts/%s/rules/lists/%s/items/%s", api.AccountID, listID, id) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return IPListItem{}, err - } - - result := IPListItemsGetResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPListItem{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// GetIPListBulkOperation returns the status of a bulk operation -// -// API reference: https://api.cloudflare.com/#rules-lists-get-bulk-operation -func (api *API) GetIPListBulkOperation(ctx context.Context, id string) (IPListBulkOperation, error) { - uri := fmt.Sprintf("/accounts/%s/rules/lists/bulk_operations/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return IPListBulkOperation{}, err - } - - result := IPListBulkOperationResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return IPListBulkOperation{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// pollIPListBulkOperation implements synchronous behaviour for some asynchronous endpoints. -// bulk-operation status can be either pending, running, failed or completed -func (api *API) pollIPListBulkOperation(ctx context.Context, id string) error { - for i := uint8(0); i < 16; i++ { - sleepDuration := 1 << (i / 2) * time.Second - select { - case <-time.After(sleepDuration): - case <-ctx.Done(): - return errors.Wrap(ctx.Err(), "operation aborted during backoff") - } - - bulkResult, err := api.GetIPListBulkOperation(ctx, id) - if err != nil { - return err - } - - switch bulkResult.Status { - case "failed": - return errors.New(bulkResult.Error) - case "pending", "running": - continue - case "completed": - return nil - default: - return errors.New(fmt.Sprintf("%s: %s", errOperationUnexpectedStatus, bulkResult.Status)) - } - } - - return errors.New(errOperationStillRunning) -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/ips.go b/vendor/github.com/cloudflare/cloudflare-go/ips.go deleted file mode 100644 index db54751a..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/ips.go +++ /dev/null @@ -1,69 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" - - "github.com/pkg/errors" -) - -// IPRangesResponse contains the structure for the API response, not modified. -type IPRangesResponse struct { - IPv4CIDRs []string `json:"ipv4_cidrs"` - IPv6CIDRs []string `json:"ipv6_cidrs"` - ChinaColos []string `json:"china_colos"` -} - -// IPRanges contains lists of IPv4 and IPv6 CIDRs. -type IPRanges struct { - IPv4CIDRs []string `json:"ipv4_cidrs"` - IPv6CIDRs []string `json:"ipv6_cidrs"` - ChinaIPv4CIDRs []string `json:"china_ipv4_cidrs"` - ChinaIPv6CIDRs []string `json:"china_ipv6_cidrs"` -} - -// IPsResponse is the API response containing a list of IPs. -type IPsResponse struct { - Response - Result IPRangesResponse `json:"result"` -} - -// IPs gets a list of Cloudflare's IP ranges. -// -// This does not require logging in to the API. -// -// API reference: https://api.cloudflare.com/#cloudflare-ips -func IPs() (IPRanges, error) { - uri := fmt.Sprintf("%s/ips?china_colo=1", apiURL) - resp, err := http.Get(uri) - if err != nil { - return IPRanges{}, errors.Wrap(err, "HTTP request failed") - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return IPRanges{}, errors.Wrap(err, "Response body could not be read") - } - var r IPsResponse - err = json.Unmarshal(body, &r) - if err != nil { - return IPRanges{}, errors.Wrap(err, errUnmarshalError) - } - - var ips IPRanges - ips.IPv4CIDRs = r.Result.IPv4CIDRs - ips.IPv6CIDRs = r.Result.IPv6CIDRs - - for _, ip := range r.Result.ChinaColos { - if strings.Contains(ip, ":") { - ips.ChinaIPv6CIDRs = append(ips.ChinaIPv6CIDRs, ip) - } else { - ips.ChinaIPv4CIDRs = append(ips.ChinaIPv4CIDRs, ip) - } - } - - return ips, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/keyless.go b/vendor/github.com/cloudflare/cloudflare-go/keyless.go deleted file mode 100644 index 4558091d..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/keyless.go +++ /dev/null @@ -1,147 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// KeylessSSL represents Keyless SSL configuration. -type KeylessSSL struct { - ID string `json:"id"` - Name string `json:"name"` - Host string `json:"host"` - Port int `json:"port"` - Status string `json:"status"` - Enabled bool `json:"enabled"` - Permissions []string `json:"permissions"` - CreatedOn time.Time `json:"created_on"` - ModifiedOn time.Time `json:"modified_on"` -} - -// KeylessSSLCreateRequest represents the request format made for creating KeylessSSL. -type KeylessSSLCreateRequest struct { - Host string `json:"host"` - Port int `json:"port"` - Certificate string `json:"certificate"` - Name string `json:"name,omitempty"` - BundleMethod string `json:"bundle_method,omitempty"` -} - -// KeylessSSLDetailResponse is the API response, containing a single Keyless SSL. -type KeylessSSLDetailResponse struct { - Response - Result KeylessSSL `json:"result"` -} - -// KeylessSSLListResponse represents the response from the Keyless SSL list endpoint. -type KeylessSSLListResponse struct { - Response - Result []KeylessSSL `json:"result"` -} - -// KeylessSSLUpdateRequest represents the request for updating KeylessSSL. -type KeylessSSLUpdateRequest struct { - Host string `json:"host,omitempty"` - Name string `json:"name,omitempty"` - Port int `json:"port,omitempty"` - Enabled *bool `json:"enabled,omitempty"` -} - -// CreateKeylessSSL creates a new Keyless SSL configuration for the zone. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-create-keyless-ssl-configuration -func (api *API) CreateKeylessSSL(ctx context.Context, zoneID string, keylessSSL KeylessSSLCreateRequest) (KeylessSSL, error) { - uri := fmt.Sprintf("/zones/%s/keyless_certificates", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, keylessSSL) - if err != nil { - return KeylessSSL{}, err - } - - var keylessSSLDetailResponse KeylessSSLDetailResponse - err = json.Unmarshal(res, &keylessSSLDetailResponse) - if err != nil { - return KeylessSSL{}, errors.Wrap(err, errUnmarshalError) - } - - return keylessSSLDetailResponse.Result, nil -} - -// ListKeylessSSL lists Keyless SSL configurations for a zone. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-list-keyless-ssl-configurations -func (api *API) ListKeylessSSL(ctx context.Context, zoneID string) ([]KeylessSSL, error) { - uri := fmt.Sprintf("/zones/%s/keyless_certificates", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - var keylessSSLListResponse KeylessSSLListResponse - err = json.Unmarshal(res, &keylessSSLListResponse) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return keylessSSLListResponse.Result, nil -} - -// KeylessSSL provides the configuration for a given Keyless SSL identifier. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-keyless-ssl-details -func (api *API) KeylessSSL(ctx context.Context, zoneID, keylessSSLID string) (KeylessSSL, error) { - uri := fmt.Sprintf("/zones/%s/keyless_certificates/%s", zoneID, keylessSSLID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return KeylessSSL{}, err - } - - var keylessResponse KeylessSSLDetailResponse - err = json.Unmarshal(res, &keylessResponse) - if err != nil { - return KeylessSSL{}, errors.Wrap(err, errUnmarshalError) - } - - return keylessResponse.Result, nil -} - -// UpdateKeylessSSL updates an existing Keyless SSL configuration. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-edit-keyless-ssl-configuration -func (api *API) UpdateKeylessSSL(ctx context.Context, zoneID, kelessSSLID string, keylessSSL KeylessSSLUpdateRequest) (KeylessSSL, error) { - uri := fmt.Sprintf("/zones/%s/keyless_certificates/%s", zoneID, kelessSSLID) - - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, keylessSSL) - if err != nil { - return KeylessSSL{}, err - } - - var keylessSSLDetailResponse KeylessSSLDetailResponse - err = json.Unmarshal(res, &keylessSSLDetailResponse) - if err != nil { - return KeylessSSL{}, errors.Wrap(err, errUnmarshalError) - } - - return keylessSSLDetailResponse.Result, nil -} - -// DeleteKeylessSSL deletes an existing Keyless SSL configuration. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-delete-keyless-ssl-configuration -func (api *API) DeleteKeylessSSL(ctx context.Context, zoneID, keylessSSLID string) error { - uri := fmt.Sprintf("/zones/%s/keyless_certificates/%s", zoneID, keylessSSLID) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/load_balancing.go b/vendor/github.com/cloudflare/cloudflare-go/load_balancing.go deleted file mode 100644 index 1c2a7d4f..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/load_balancing.go +++ /dev/null @@ -1,479 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// LoadBalancerPool represents a load balancer pool's properties. -type LoadBalancerPool struct { - ID string `json:"id,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - Description string `json:"description"` - Name string `json:"name"` - Enabled bool `json:"enabled"` - MinimumOrigins int `json:"minimum_origins,omitempty"` - Monitor string `json:"monitor,omitempty"` - Origins []LoadBalancerOrigin `json:"origins"` - NotificationEmail string `json:"notification_email,omitempty"` - Latitude *float32 `json:"latitude,omitempty"` - Longitude *float32 `json:"longitude,omitempty"` - LoadShedding *LoadBalancerLoadShedding `json:"load_shedding,omitempty"` - OriginSteering *LoadBalancerOriginSteering `json:"origin_steering,omitempty"` - - // CheckRegions defines the geographic region(s) from where to run health-checks from - e.g. "WNAM", "WEU", "SAF", "SAM". - // Providing a null/empty value means "all regions", which may not be available to all plan types. - CheckRegions []string `json:"check_regions"` -} - -// LoadBalancerOrigin represents a Load Balancer origin's properties. -type LoadBalancerOrigin struct { - Name string `json:"name"` - Address string `json:"address"` - Enabled bool `json:"enabled"` - Weight float64 `json:"weight"` - Header map[string][]string `json:"header"` -} - -// LoadBalancerOriginSteering controls origin selection for new sessions and traffic without session affinity. -type LoadBalancerOriginSteering struct { - // Policy defaults to "random" (weighted) when empty or unspecified. - Policy string `json:"policy,omitempty"` -} - -// LoadBalancerMonitor represents a load balancer monitor's properties. -type LoadBalancerMonitor struct { - ID string `json:"id,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - Type string `json:"type"` - Description string `json:"description"` - Method string `json:"method"` - Path string `json:"path"` - Header map[string][]string `json:"header"` - Timeout int `json:"timeout"` - Retries int `json:"retries"` - Interval int `json:"interval"` - Port uint16 `json:"port,omitempty"` - ExpectedBody string `json:"expected_body"` - ExpectedCodes string `json:"expected_codes"` - FollowRedirects bool `json:"follow_redirects"` - AllowInsecure bool `json:"allow_insecure"` - ProbeZone string `json:"probe_zone"` -} - -// LoadBalancer represents a load balancer's properties. -type LoadBalancer struct { - ID string `json:"id,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - Description string `json:"description"` - Name string `json:"name"` - TTL int `json:"ttl,omitempty"` - FallbackPool string `json:"fallback_pool"` - DefaultPools []string `json:"default_pools"` - RegionPools map[string][]string `json:"region_pools"` - PopPools map[string][]string `json:"pop_pools"` - Proxied bool `json:"proxied"` - Enabled *bool `json:"enabled,omitempty"` - Persistence string `json:"session_affinity,omitempty"` - PersistenceTTL int `json:"session_affinity_ttl,omitempty"` - SessionAffinityAttributes *SessionAffinityAttributes `json:"session_affinity_attributes,omitempty"` - Rules []*LoadBalancerRule `json:"rules,omitempty"` - - // SteeringPolicy controls pool selection logic. - // "off" select pools in DefaultPools order - // "geo" select pools based on RegionPools/PopPools - // "dynamic_latency" select pools based on RTT (requires health checks) - // "random" selects pools in a random order - // "proximity" select pools based on 'distance' from request - // "" maps to "geo" if RegionPools or PopPools have entries otherwise "off" - SteeringPolicy string `json:"steering_policy,omitempty"` -} - -// LoadBalancerLoadShedding contains the settings for controlling load shedding -type LoadBalancerLoadShedding struct { - DefaultPercent float32 `json:"default_percent,omitempty"` - DefaultPolicy string `json:"default_policy,omitempty"` - SessionPercent float32 `json:"session_percent,omitempty"` - SessionPolicy string `json:"session_policy,omitempty"` -} - -// LoadBalancerRule represents a single rule entry for a Load Balancer. Each rules -// is run one after the other in priority order. Disabled rules are skipped. -type LoadBalancerRule struct { - // Name is required but is only used for human readability - Name string `json:"name"` - // Priority controls the order of rule execution the lowest value will be invoked first - Priority int `json:"priority"` - Disabled bool `json:"disabled"` - - Condition string `json:"condition"` - Overrides LoadBalancerRuleOverrides `json:"overrides"` - - // Terminates flag this rule as 'terminating'. No further rules will - // be executed after this one. - Terminates bool `json:"terminates,omitempty"` - - // FixedResponse if set and the condition is true we will not run - // routing logic but rather directly respond with the provided fields. - // FixedResponse implies terminates. - FixedResponse *LoadBalancerFixedResponseData `json:"fixed_response,omitempty"` -} - -// LoadBalancerFixedResponseData contains all the data needed to generate -// a fixed response from a Load Balancer. This behavior can be enabled via Rules. -type LoadBalancerFixedResponseData struct { - // MessageBody data to write into the http body - MessageBody string `json:"message_body,omitempty"` - // StatusCode the http status code to response with - StatusCode int `json:"status_code,omitempty"` - // ContentType value of the http 'content-type' header - ContentType string `json:"content_type,omitempty"` - // Location value of the http 'location' header - Location string `json:"location,omitempty"` -} - -// LoadBalancerRuleOverrides are the set of field overridable by the rules system. -type LoadBalancerRuleOverrides struct { - // session affinity - Persistence string `json:"session_affinity,omitempty"` - PersistenceTTL *uint `json:"session_affinity_ttl,omitempty"` - - SessionAffinityAttrs *LoadBalancerRuleOverridesSessionAffinityAttrs `json:"session_affinity_attributes,omitempty"` - - TTL uint `json:"ttl,omitempty"` - - SteeringPolicy string `json:"steering_policy,omitempty"` - FallbackPool string `json:"fallback_pool,omitempty"` - - DefaultPools []string `json:"default_pools,omitempty"` - PoPPools map[string][]string `json:"pop_pools,omitempty"` - RegionPools map[string][]string `json:"region_pools,omitempty"` -} - -// LoadBalancerRuleOverridesSessionAffinityAttrs mimics SessionAffinityAttributes without the -// DrainDuration field as that field can not be overwritten via rules. -type LoadBalancerRuleOverridesSessionAffinityAttrs struct { - SameSite string `json:"samesite,omitempty"` - Secure string `json:"secure,omitempty"` -} - -// SessionAffinityAttributes represents the fields used to set attributes in a load balancer session affinity cookie. -type SessionAffinityAttributes struct { - SameSite string `json:"samesite,omitempty"` - Secure string `json:"secure,omitempty"` - DrainDuration int `json:"drain_duration,omitempty"` -} - -// LoadBalancerOriginHealth represents the health of the origin. -type LoadBalancerOriginHealth struct { - Healthy bool `json:"healthy,omitempty"` - RTT Duration `json:"rtt,omitempty"` - FailureReason string `json:"failure_reason,omitempty"` - ResponseCode int `json:"response_code,omitempty"` -} - -// LoadBalancerPoolPopHealth represents the health of the pool for given PoP. -type LoadBalancerPoolPopHealth struct { - Healthy bool `json:"healthy,omitempty"` - Origins []map[string]LoadBalancerOriginHealth `json:"origins,omitempty"` -} - -// LoadBalancerPoolHealth represents the healthchecks from different PoPs for a pool. -type LoadBalancerPoolHealth struct { - ID string `json:"pool_id,omitempty"` - PopHealth map[string]LoadBalancerPoolPopHealth `json:"pop_health,omitempty"` -} - -// loadBalancerPoolResponse represents the response from the load balancer pool endpoints. -type loadBalancerPoolResponse struct { - Response - Result LoadBalancerPool `json:"result"` -} - -// loadBalancerPoolListResponse represents the response from the List Pools endpoint. -type loadBalancerPoolListResponse struct { - Response - Result []LoadBalancerPool `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// loadBalancerMonitorResponse represents the response from the load balancer monitor endpoints. -type loadBalancerMonitorResponse struct { - Response - Result LoadBalancerMonitor `json:"result"` -} - -// loadBalancerMonitorListResponse represents the response from the List Monitors endpoint. -type loadBalancerMonitorListResponse struct { - Response - Result []LoadBalancerMonitor `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// loadBalancerResponse represents the response from the load balancer endpoints. -type loadBalancerResponse struct { - Response - Result LoadBalancer `json:"result"` -} - -// loadBalancerListResponse represents the response from the List Load Balancers endpoint. -type loadBalancerListResponse struct { - Response - Result []LoadBalancer `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// loadBalancerPoolHealthResponse represents the response from the Pool Health Details endpoint. -type loadBalancerPoolHealthResponse struct { - Response - Result LoadBalancerPoolHealth `json:"result"` -} - -// CreateLoadBalancerPool creates a new load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-create-pool -func (api *API) CreateLoadBalancerPool(ctx context.Context, pool LoadBalancerPool) (LoadBalancerPool, error) { - uri := fmt.Sprintf("%s/load_balancers/pools", api.userBaseURL("/user")) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, pool) - if err != nil { - return LoadBalancerPool{}, err - } - var r loadBalancerPoolResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListLoadBalancerPools lists load balancer pools connected to an account. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-list-pools -func (api *API) ListLoadBalancerPools(ctx context.Context) ([]LoadBalancerPool, error) { - uri := fmt.Sprintf("%s/load_balancers/pools", api.userBaseURL("/user")) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - var r loadBalancerPoolListResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LoadBalancerPoolDetails returns the details for a load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-pool-details -func (api *API) LoadBalancerPoolDetails(ctx context.Context, poolID string) (LoadBalancerPool, error) { - uri := fmt.Sprintf("%s/load_balancers/pools/%s", api.userBaseURL("/user"), poolID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return LoadBalancerPool{}, err - } - var r loadBalancerPoolResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteLoadBalancerPool disables and deletes a load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-delete-pool -func (api *API) DeleteLoadBalancerPool(ctx context.Context, poolID string) error { - uri := fmt.Sprintf("%s/load_balancers/pools/%s", api.userBaseURL("/user"), poolID) - if _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil); err != nil { - return err - } - return nil -} - -// ModifyLoadBalancerPool modifies a configured load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-update-pool -func (api *API) ModifyLoadBalancerPool(ctx context.Context, pool LoadBalancerPool) (LoadBalancerPool, error) { - uri := fmt.Sprintf("%s/load_balancers/pools/%s", api.userBaseURL("/user"), pool.ID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, pool) - if err != nil { - return LoadBalancerPool{}, err - } - var r loadBalancerPoolResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// CreateLoadBalancerMonitor creates a new load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-create-monitor -func (api *API) CreateLoadBalancerMonitor(ctx context.Context, monitor LoadBalancerMonitor) (LoadBalancerMonitor, error) { - uri := fmt.Sprintf("%s/load_balancers/monitors", api.userBaseURL("/user")) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, monitor) - if err != nil { - return LoadBalancerMonitor{}, err - } - var r loadBalancerMonitorResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListLoadBalancerMonitors lists load balancer monitors connected to an account. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-list-monitors -func (api *API) ListLoadBalancerMonitors(ctx context.Context) ([]LoadBalancerMonitor, error) { - uri := fmt.Sprintf("%s/load_balancers/monitors", api.userBaseURL("/user")) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - var r loadBalancerMonitorListResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LoadBalancerMonitorDetails returns the details for a load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-monitor-details -func (api *API) LoadBalancerMonitorDetails(ctx context.Context, monitorID string) (LoadBalancerMonitor, error) { - uri := fmt.Sprintf("%s/load_balancers/monitors/%s", api.userBaseURL("/user"), monitorID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return LoadBalancerMonitor{}, err - } - var r loadBalancerMonitorResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteLoadBalancerMonitor disables and deletes a load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-delete-monitor -func (api *API) DeleteLoadBalancerMonitor(ctx context.Context, monitorID string) error { - uri := fmt.Sprintf("%s/load_balancers/monitors/%s", api.userBaseURL("/user"), monitorID) - if _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil); err != nil { - return err - } - return nil -} - -// ModifyLoadBalancerMonitor modifies a configured load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-update-monitor -func (api *API) ModifyLoadBalancerMonitor(ctx context.Context, monitor LoadBalancerMonitor) (LoadBalancerMonitor, error) { - uri := fmt.Sprintf("%s/load_balancers/monitors/%s", api.userBaseURL("/user"), monitor.ID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, monitor) - if err != nil { - return LoadBalancerMonitor{}, err - } - var r loadBalancerMonitorResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// CreateLoadBalancer creates a new load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-create-load-balancer -func (api *API) CreateLoadBalancer(ctx context.Context, zoneID string, lb LoadBalancer) (LoadBalancer, error) { - uri := fmt.Sprintf("/zones/%s/load_balancers", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, lb) - if err != nil { - return LoadBalancer{}, err - } - var r loadBalancerResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancer{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListLoadBalancers lists load balancers configured on a zone. -// -// API reference: https://api.cloudflare.com/#load-balancers-list-load-balancers -func (api *API) ListLoadBalancers(ctx context.Context, zoneID string) ([]LoadBalancer, error) { - uri := fmt.Sprintf("/zones/%s/load_balancers", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - var r loadBalancerListResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LoadBalancerDetails returns the details for a load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-load-balancer-details -func (api *API) LoadBalancerDetails(ctx context.Context, zoneID, lbID string) (LoadBalancer, error) { - uri := fmt.Sprintf("/zones/%s/load_balancers/%s", zoneID, lbID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return LoadBalancer{}, err - } - var r loadBalancerResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancer{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteLoadBalancer disables and deletes a load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-delete-load-balancer -func (api *API) DeleteLoadBalancer(ctx context.Context, zoneID, lbID string) error { - uri := fmt.Sprintf("/zones/%s/load_balancers/%s", zoneID, lbID) - if _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil); err != nil { - return err - } - return nil -} - -// ModifyLoadBalancer modifies a configured load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-update-load-balancer -func (api *API) ModifyLoadBalancer(ctx context.Context, zoneID string, lb LoadBalancer) (LoadBalancer, error) { - uri := fmt.Sprintf("/zones/%s/load_balancers/%s", zoneID, lb.ID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, lb) - if err != nil { - return LoadBalancer{}, err - } - var r loadBalancerResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancer{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// PoolHealthDetails fetches the latest healtcheck details for a single pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-pool-health-details -func (api *API) PoolHealthDetails(ctx context.Context, poolID string) (LoadBalancerPoolHealth, error) { - uri := fmt.Sprintf("%s/load_balancers/pools/%s/health", api.userBaseURL("/user"), poolID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return LoadBalancerPoolHealth{}, err - } - var r loadBalancerPoolHealthResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerPoolHealth{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/lockdown.go b/vendor/github.com/cloudflare/cloudflare-go/lockdown.go deleted file mode 100644 index ef17ac8f..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/lockdown.go +++ /dev/null @@ -1,156 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -// ZoneLockdown represents a Zone Lockdown rule. A rule only permits access to -// the provided URL pattern(s) from the given IP address(es) or subnet(s). -type ZoneLockdown struct { - ID string `json:"id"` - Description string `json:"description"` - URLs []string `json:"urls"` - Configurations []ZoneLockdownConfig `json:"configurations"` - Paused bool `json:"paused"` - Priority int `json:"priority,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` -} - -// ZoneLockdownConfig represents a Zone Lockdown config, which comprises -// a Target ("ip" or "ip_range") and a Value (an IP address or IP+mask, -// respectively.) -type ZoneLockdownConfig struct { - Target string `json:"target"` - Value string `json:"value"` -} - -// ZoneLockdownResponse represents a response from the Zone Lockdown endpoint. -type ZoneLockdownResponse struct { - Result ZoneLockdown `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// ZoneLockdownListResponse represents a response from the List Zone Lockdown -// endpoint. -type ZoneLockdownListResponse struct { - Result []ZoneLockdown `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// CreateZoneLockdown creates a Zone ZoneLockdown rule for the given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-create-a-ZoneLockdown-rule -func (api *API) CreateZoneLockdown(ctx context.Context, zoneID string, ld ZoneLockdown) (*ZoneLockdownResponse, error) { - uri := fmt.Sprintf("/zones/%s/firewall/lockdowns", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, ld) - if err != nil { - return nil, err - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UpdateZoneLockdown updates a Zone ZoneLockdown rule (based on the ID) for the -// given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-update-ZoneLockdown-rule -func (api *API) UpdateZoneLockdown(ctx context.Context, zoneID string, id string, ld ZoneLockdown) (*ZoneLockdownResponse, error) { - uri := fmt.Sprintf("/zones/%s/firewall/lockdowns/%s", zoneID, id) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, ld) - if err != nil { - return nil, err - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// DeleteZoneLockdown deletes a Zone ZoneLockdown rule (based on the ID) for the -// given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-delete-ZoneLockdown-rule -func (api *API) DeleteZoneLockdown(ctx context.Context, zoneID string, id string) (*ZoneLockdownResponse, error) { - uri := fmt.Sprintf("/zones/%s/firewall/lockdowns/%s", zoneID, id) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return nil, err - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ZoneLockdown retrieves a Zone ZoneLockdown rule (based on the ID) for the -// given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-ZoneLockdown-rule-details -func (api *API) ZoneLockdown(ctx context.Context, zoneID string, id string) (*ZoneLockdownResponse, error) { - uri := fmt.Sprintf("/zones/%s/firewall/lockdowns/%s", zoneID, id) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ListZoneLockdowns retrieves a list of Zone ZoneLockdown rules for a given -// zone ID by page number. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-list-ZoneLockdown-rules -func (api *API) ListZoneLockdowns(ctx context.Context, zoneID string, page int) (*ZoneLockdownListResponse, error) { - v := url.Values{} - if page <= 0 { - page = 1 - } - - v.Set("page", strconv.Itoa(page)) - v.Set("per_page", strconv.Itoa(100)) - - uri := fmt.Sprintf("/zones/%s/firewall/lockdowns?%s", zoneID, v.Encode()) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - response := &ZoneLockdownListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/logpull.go b/vendor/github.com/cloudflare/cloudflare-go/logpull.go deleted file mode 100644 index 24c401f7..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/logpull.go +++ /dev/null @@ -1,59 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -// LogpullRetentionConfiguration describes a the structure of a Logpull Retention -// payload. -type LogpullRetentionConfiguration struct { - Flag bool `json:"flag"` -} - -// LogpullRetentionConfigurationResponse is the API response, containing the -// Logpull retention result. -type LogpullRetentionConfigurationResponse struct { - Response - Result LogpullRetentionConfiguration `json:"result"` -} - -// GetLogpullRetentionFlag gets the current setting flag. -// -// API reference: https://developers.cloudflare.com/logs/logpull-api/enabling-log-retention/ -func (api *API) GetLogpullRetentionFlag(ctx context.Context, zoneID string) (*LogpullRetentionConfiguration, error) { - uri := fmt.Sprintf("/zones/%s/logs/control/retention/flag", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return &LogpullRetentionConfiguration{}, err - } - var r LogpullRetentionConfigurationResponse - err = json.Unmarshal(res, &r) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return &r.Result, nil -} - -// SetLogpullRetentionFlag updates the retention flag to the defined boolean. -// -// API reference: https://developers.cloudflare.com/logs/logpull-api/enabling-log-retention/ -func (api *API) SetLogpullRetentionFlag(ctx context.Context, zoneID string, enabled bool) (*LogpullRetentionConfiguration, error) { - uri := fmt.Sprintf("/zones/%s/logs/control/retention/flag", zoneID) - flagPayload := LogpullRetentionConfiguration{Flag: enabled} - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, flagPayload) - if err != nil { - return &LogpullRetentionConfiguration{}, err - } - var r LogpullRetentionConfigurationResponse - err = json.Unmarshal(res, &r) - if err != nil { - return &LogpullRetentionConfiguration{}, err - } - return &r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/logpush.go b/vendor/github.com/cloudflare/cloudflare-go/logpush.go deleted file mode 100644 index 1e5f363a..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/logpush.go +++ /dev/null @@ -1,275 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// LogpushJob describes a Logpush job. -type LogpushJob struct { - ID int `json:"id,omitempty"` - Dataset string `json:"dataset"` - Enabled bool `json:"enabled"` - Name string `json:"name"` - LogpullOptions string `json:"logpull_options"` - DestinationConf string `json:"destination_conf"` - OwnershipChallenge string `json:"ownership_challenge,omitempty"` - LastComplete *time.Time `json:"last_complete,omitempty"` - LastError *time.Time `json:"last_error,omitempty"` - ErrorMessage string `json:"error_message,omitempty"` -} - -// LogpushJobsResponse is the API response, containing an array of Logpush Jobs. -type LogpushJobsResponse struct { - Response - Result []LogpushJob `json:"result"` -} - -// LogpushJobDetailsResponse is the API response, containing a single Logpush Job. -type LogpushJobDetailsResponse struct { - Response - Result LogpushJob `json:"result"` -} - -// LogpushFieldsResponse is the API response for a datasets fields -type LogpushFieldsResponse struct { - Response - Result LogpushFields `json:"result"` -} - -// LogpushFields is a map of available Logpush field names & descriptions -type LogpushFields map[string]string - -// LogpushGetOwnershipChallenge describes a ownership validation. -type LogpushGetOwnershipChallenge struct { - Filename string `json:"filename"` - Valid bool `json:"valid"` - Message string `json:"message"` -} - -// LogpushGetOwnershipChallengeResponse is the API response, containing a ownership challenge. -type LogpushGetOwnershipChallengeResponse struct { - Response - Result LogpushGetOwnershipChallenge `json:"result"` -} - -// LogpushGetOwnershipChallengeRequest is the API request for get ownership challenge. -type LogpushGetOwnershipChallengeRequest struct { - DestinationConf string `json:"destination_conf"` -} - -// LogpushOwnershipChallengeValidationResponse is the API response, -// containing a ownership challenge validation result. -type LogpushOwnershipChallengeValidationResponse struct { - Response - Result struct { - Valid bool `json:"valid"` - } -} - -// LogpushValidateOwnershipChallengeRequest is the API request for validate ownership challenge. -type LogpushValidateOwnershipChallengeRequest struct { - DestinationConf string `json:"destination_conf"` - OwnershipChallenge string `json:"ownership_challenge"` -} - -// LogpushDestinationExistsResponse is the API response, -// containing a destination exists check result. -type LogpushDestinationExistsResponse struct { - Response - Result struct { - Exists bool `json:"exists"` - } -} - -// LogpushDestinationExistsRequest is the API request for check destination exists. -type LogpushDestinationExistsRequest struct { - DestinationConf string `json:"destination_conf"` -} - -// CreateLogpushJob creates a new LogpushJob for a zone. -// -// API reference: https://api.cloudflare.com/#logpush-jobs-create-logpush-job -func (api *API) CreateLogpushJob(ctx context.Context, zoneID string, job LogpushJob) (*LogpushJob, error) { - uri := fmt.Sprintf("/zones/%s/logpush/jobs", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, job) - if err != nil { - return nil, err - } - var r LogpushJobDetailsResponse - err = json.Unmarshal(res, &r) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return &r.Result, nil -} - -// LogpushJobs returns all Logpush Jobs for a zone. -// -// API reference: https://api.cloudflare.com/#logpush-jobs-list-logpush-jobs -func (api *API) LogpushJobs(ctx context.Context, zoneID string) ([]LogpushJob, error) { - uri := fmt.Sprintf("/zones/%s/logpush/jobs", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []LogpushJob{}, err - } - var r LogpushJobsResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []LogpushJob{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LogpushJobsForDataset returns all Logpush Jobs for a dataset in a zone. -// -// API reference: https://api.cloudflare.com/#logpush-jobs-list-logpush-jobs-for-a-dataset -func (api *API) LogpushJobsForDataset(ctx context.Context, zoneID, dataset string) ([]LogpushJob, error) { - uri := fmt.Sprintf("/zones/%s/logpush/datasets/%s/jobs", zoneID, dataset) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []LogpushJob{}, err - } - var r LogpushJobsResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []LogpushJob{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LogpushFields returns fields for a given dataset. -// -// API reference: https://api.cloudflare.com/#logpush-jobs-list-logpush-jobs -func (api *API) LogpushFields(ctx context.Context, zoneID, dataset string) (LogpushFields, error) { - uri := fmt.Sprintf("/zones/%s/logpush/datasets/%s/fields", zoneID, dataset) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return LogpushFields{}, err - } - var r LogpushFieldsResponse - err = json.Unmarshal(res, &r) - if err != nil { - return LogpushFields{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LogpushJob fetches detail about one Logpush Job for a zone. -// -// API reference: https://api.cloudflare.com/#logpush-jobs-logpush-job-details -func (api *API) LogpushJob(ctx context.Context, zoneID string, jobID int) (LogpushJob, error) { - uri := fmt.Sprintf("/zones/%s/logpush/jobs/%d", zoneID, jobID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return LogpushJob{}, err - } - var r LogpushJobDetailsResponse - err = json.Unmarshal(res, &r) - if err != nil { - return LogpushJob{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateLogpushJob lets you update a Logpush Job. -// -// API reference: https://api.cloudflare.com/#logpush-jobs-update-logpush-job -func (api *API) UpdateLogpushJob(ctx context.Context, zoneID string, jobID int, job LogpushJob) error { - uri := fmt.Sprintf("/zones/%s/logpush/jobs/%d", zoneID, jobID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, job) - if err != nil { - return err - } - var r LogpushJobDetailsResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// DeleteLogpushJob deletes a Logpush Job for a zone. -// -// API reference: https://api.cloudflare.com/#logpush-jobs-delete-logpush-job -func (api *API) DeleteLogpushJob(ctx context.Context, zoneID string, jobID int) error { - uri := fmt.Sprintf("/zones/%s/logpush/jobs/%d", zoneID, jobID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - var r LogpushJobDetailsResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// GetLogpushOwnershipChallenge returns ownership challenge. -// -// API reference: https://api.cloudflare.com/#logpush-jobs-get-ownership-challenge -func (api *API) GetLogpushOwnershipChallenge(ctx context.Context, zoneID, destinationConf string) (*LogpushGetOwnershipChallenge, error) { - uri := fmt.Sprintf("/zones/%s/logpush/ownership", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, LogpushGetOwnershipChallengeRequest{ - DestinationConf: destinationConf, - }) - if err != nil { - return nil, err - } - var r LogpushGetOwnershipChallengeResponse - err = json.Unmarshal(res, &r) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !r.Result.Valid { - return nil, errors.New(r.Result.Message) - } - - return &r.Result, nil -} - -// ValidateLogpushOwnershipChallenge returns ownership challenge validation result. -// -// API reference: https://api.cloudflare.com/#logpush-jobs-validate-ownership-challenge -func (api *API) ValidateLogpushOwnershipChallenge(ctx context.Context, zoneID, destinationConf, ownershipChallenge string) (bool, error) { - uri := fmt.Sprintf("/zones/%s/logpush/ownership/validate", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, LogpushValidateOwnershipChallengeRequest{ - DestinationConf: destinationConf, - OwnershipChallenge: ownershipChallenge, - }) - if err != nil { - return false, err - } - var r LogpushGetOwnershipChallengeResponse - err = json.Unmarshal(res, &r) - if err != nil { - return false, errors.Wrap(err, errUnmarshalError) - } - return r.Result.Valid, nil -} - -// CheckLogpushDestinationExists returns destination exists check result. -// -// API reference: https://api.cloudflare.com/#logpush-jobs-check-destination-exists -func (api *API) CheckLogpushDestinationExists(ctx context.Context, zoneID, destinationConf string) (bool, error) { - uri := fmt.Sprintf("/zones/%s/logpush/validate/destination/exists", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, LogpushDestinationExistsRequest{ - DestinationConf: destinationConf, - }) - if err != nil { - return false, err - } - var r LogpushDestinationExistsResponse - err = json.Unmarshal(res, &r) - if err != nil { - return false, errors.Wrap(err, errUnmarshalError) - } - return r.Result.Exists, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/magic_firewall_rulesets.go b/vendor/github.com/cloudflare/cloudflare-go/magic_firewall_rulesets.go deleted file mode 100644 index c463569a..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/magic_firewall_rulesets.go +++ /dev/null @@ -1,224 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -const ( - // MagicFirewallRulesetKindRoot specifies a root Ruleset - MagicFirewallRulesetKindRoot = "root" - - // MagicFirewallRulesetPhaseMagicTransit specifies the Magic Transit Ruleset phase - MagicFirewallRulesetPhaseMagicTransit = "magic_transit" - - // MagicFirewallRulesetRuleActionSkip specifies a skip (allow) action - MagicFirewallRulesetRuleActionSkip MagicFirewallRulesetRuleAction = "skip" - - // MagicFirewallRulesetRuleActionBlock specifies a block action - MagicFirewallRulesetRuleActionBlock MagicFirewallRulesetRuleAction = "block" -) - -// MagicFirewallRulesetRuleAction specifies the action for a Firewall rule -type MagicFirewallRulesetRuleAction string - -// MagicFirewallRuleset contains information about a Firewall Ruleset -type MagicFirewallRuleset struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Kind string `json:"kind"` - Version string `json:"version,omitempty"` - LastUpdated *time.Time `json:"last_updated,omitempty"` - Phase string `json:"phase"` - Rules []MagicFirewallRulesetRule `json:"rules"` -} - -// MagicFirewallRulesetRuleActionParameters specifies the action parameters for a Firewall rule -type MagicFirewallRulesetRuleActionParameters struct { - Ruleset string `json:"ruleset,omitempty"` -} - -// MagicFirewallRulesetRule contains information about a single Magic Firewall rule -type MagicFirewallRulesetRule struct { - ID string `json:"id,omitempty"` - Version string `json:"version,omitempty"` - Action MagicFirewallRulesetRuleAction `json:"action"` - ActionParameters *MagicFirewallRulesetRuleActionParameters `json:"action_parameters,omitempty"` - Expression string `json:"expression"` - Description string `json:"description"` - LastUpdated *time.Time `json:"last_updated,omitempty"` - Ref string `json:"ref,omitempty"` - Enabled bool `json:"enabled"` -} - -// CreateMagicFirewallRulesetRequest contains data for a new Firewall ruleset -type CreateMagicFirewallRulesetRequest struct { - Name string `json:"name"` - Description string `json:"description"` - Kind string `json:"kind"` - Phase string `json:"phase"` - Rules []MagicFirewallRulesetRule `json:"rules"` -} - -// UpdateMagicFirewallRulesetRequest contains data for a Magic Firewall ruleset update -type UpdateMagicFirewallRulesetRequest struct { - Description string `json:"description"` - Rules []MagicFirewallRulesetRule `json:"rules"` -} - -// ListMagicFirewallRulesetResponse contains a list of Magic Firewall rulesets -type ListMagicFirewallRulesetResponse struct { - Response - Result []MagicFirewallRuleset `json:"result"` -} - -// GetMagicFirewallRulesetResponse contains a single Magic Firewall Ruleset -type GetMagicFirewallRulesetResponse struct { - Response - Result MagicFirewallRuleset `json:"result"` -} - -// CreateMagicFirewallRulesetResponse contains response data when creating a new Magic Firewall ruleset -type CreateMagicFirewallRulesetResponse struct { - Response - Result MagicFirewallRuleset `json:"result"` -} - -// UpdateMagicFirewallRulesetResponse contains response data when updating an existing Magic Firewall ruleset -type UpdateMagicFirewallRulesetResponse struct { - Response - Result MagicFirewallRuleset `json:"result"` -} - -// ListMagicFirewallRulesets lists all Rulesets for a given account -// -// API reference: https://api.cloudflare.com/#rulesets-list-rulesets -func (api *API) ListMagicFirewallRulesets(ctx context.Context) ([]MagicFirewallRuleset, error) { - if err := api.checkAccountID(); err != nil { - return []MagicFirewallRuleset{}, err - } - - uri := fmt.Sprintf("/accounts/%s/rulesets", api.AccountID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []MagicFirewallRuleset{}, err - } - - result := ListMagicFirewallRulesetResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return []MagicFirewallRuleset{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// GetMagicFirewallRuleset returns a specific Magic Firewall Ruleset -// -// API reference: https://api.cloudflare.com/#rulesets-get-a-ruleset -func (api *API) GetMagicFirewallRuleset(ctx context.Context, id string) (MagicFirewallRuleset, error) { - if err := api.checkAccountID(); err != nil { - return MagicFirewallRuleset{}, err - } - - uri := fmt.Sprintf("/accounts/%s/rulesets/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return MagicFirewallRuleset{}, err - } - - result := GetMagicFirewallRulesetResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return MagicFirewallRuleset{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// CreateMagicFirewallRuleset creates a Magic Firewall ruleset -// -// API reference: https://api.cloudflare.com/#rulesets-list-rulesets -func (api *API) CreateMagicFirewallRuleset(ctx context.Context, name string, description string, rules []MagicFirewallRulesetRule) (MagicFirewallRuleset, error) { - if err := api.checkAccountID(); err != nil { - return MagicFirewallRuleset{}, err - } - - uri := fmt.Sprintf("/accounts/%s/rulesets", api.AccountID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, - CreateMagicFirewallRulesetRequest{ - Name: name, - Description: description, - Kind: MagicFirewallRulesetKindRoot, - Phase: MagicFirewallRulesetPhaseMagicTransit, - Rules: rules}) - if err != nil { - return MagicFirewallRuleset{}, err - } - - result := CreateMagicFirewallRulesetResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return MagicFirewallRuleset{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// DeleteMagicFirewallRuleset deletes a Magic Firewall ruleset -// -// API reference: https://api.cloudflare.com/#rulesets-delete-ruleset -func (api *API) DeleteMagicFirewallRuleset(ctx context.Context, id string) error { - if err := api.checkAccountID(); err != nil { - return err - } - - uri := fmt.Sprintf("/accounts/%s/rulesets/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - - if err != nil { - return err - } - - // Firewall API is not implementing the standard response blob but returns an empty response (204) in case - // of a success. So we are checking for the response body size here - if len(res) > 0 { - return errors.Wrap(errors.New(string(res)), errMakeRequestError) - } - - return nil -} - -// UpdateMagicFirewallRuleset updates a Magic Firewall ruleset -// -// API reference: https://api.cloudflare.com/#rulesets-update-ruleset -func (api *API) UpdateMagicFirewallRuleset(ctx context.Context, id string, description string, rules []MagicFirewallRulesetRule) (MagicFirewallRuleset, error) { - if err := api.checkAccountID(); err != nil { - return MagicFirewallRuleset{}, err - } - - uri := fmt.Sprintf("/accounts/%s/rulesets/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, - UpdateMagicFirewallRulesetRequest{Description: description, Rules: rules}) - if err != nil { - return MagicFirewallRuleset{}, err - } - - result := UpdateMagicFirewallRulesetResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return MagicFirewallRuleset{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -func (api *API) checkAccountID() error { - if api.AccountID == "" { - return fmt.Errorf("account ID must not be empty") - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/magic_transit_static_routes.go b/vendor/github.com/cloudflare/cloudflare-go/magic_transit_static_routes.go deleted file mode 100644 index cb402a68..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/magic_transit_static_routes.go +++ /dev/null @@ -1,199 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "github.com/pkg/errors" - "net/http" - "time" -) - -// Magic Transit Static Routes Error messages -const ( - errMagicTransitStaticRouteNotModified = "When trying to modify static route, API returned modified: false" - errMagicTransitStaticRouteNotDeleted = "When trying to delete static route, API returned deleted: false" -) - -// MagicTransitStaticRouteScope contains information about a static route's scope -type MagicTransitStaticRouteScope struct { - ColoRegions []string `json:"colo_regions,omitempty"` - ColoNames []string `json:"colo_names,omitempty"` -} - -// MagicTransitStaticRoute contains information about a static route -type MagicTransitStaticRoute struct { - ID string `json:"id,omitempty"` - Prefix string `json:"prefix"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - Nexthop string `json:"nexthop"` - Priority int `json:"priority,omitempty"` - Description string `json:"description,omitempty"` - Weight int `json:"weight,omitempty"` - Scope MagicTransitStaticRouteScope `json:"scope,omitempty"` -} - -// ListMagicTransitStaticRoutesResponse contains a response including Magic Transit static routes -type ListMagicTransitStaticRoutesResponse struct { - Response - Result struct { - Routes []MagicTransitStaticRoute `json:"routes"` - } `json:"result"` -} - -// GetMagicTransitStaticRouteResponse contains a response including exactly one static route -type GetMagicTransitStaticRouteResponse struct { - Response - Result struct { - Route MagicTransitStaticRoute `json:"route"` - } `json:"result"` -} - -// UpdateMagicTransitStaticRouteResponse contains a static route update response -type UpdateMagicTransitStaticRouteResponse struct { - Response - Result struct { - Modified bool `json:"modified"` - ModifiedRoute MagicTransitStaticRoute `json:"modified_route"` - } `json:"result"` -} - -// DeleteMagicTransitStaticRouteResponse contains a static route deletion response -type DeleteMagicTransitStaticRouteResponse struct { - Response - Result struct { - Deleted bool `json:"deleted"` - DeletedRoute MagicTransitStaticRoute `json:"deleted_route"` - } `json:"result"` -} - -// CreateMagicTransitStaticRoutesRequest is an array of static routes to create -type CreateMagicTransitStaticRoutesRequest struct { - Routes []MagicTransitStaticRoute `json:"routes"` -} - -// ListMagicTransitStaticRoutes lists all static routes for a given account -// -// API reference: https://api.cloudflare.com/#magic-transit-static-routes-list-routes -func (api *API) ListMagicTransitStaticRoutes(ctx context.Context) ([]MagicTransitStaticRoute, error) { - if err := api.checkAccountID(); err != nil { - return []MagicTransitStaticRoute{}, err - } - - uri := fmt.Sprintf("/accounts/%s/magic/routes", api.AccountID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []MagicTransitStaticRoute{}, err - } - - result := ListMagicTransitStaticRoutesResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return []MagicTransitStaticRoute{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result.Routes, nil -} - -// GetMagicTransitStaticRoute returns exactly one static route -// -// API reference: https://api.cloudflare.com/#magic-transit-static-routes-route-details -func (api *API) GetMagicTransitStaticRoute(ctx context.Context, id string) (MagicTransitStaticRoute, error) { - if err := api.checkAccountID(); err != nil { - return MagicTransitStaticRoute{}, err - } - - uri := fmt.Sprintf("/accounts/%s/magic/routes/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return MagicTransitStaticRoute{}, err - } - - result := GetMagicTransitStaticRouteResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return MagicTransitStaticRoute{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result.Route, nil -} - -// CreateMagicTransitStaticRoute creates a new static route -// -// API reference: https://api.cloudflare.com/#magic-transit-static-routes-create-routes -func (api *API) CreateMagicTransitStaticRoute(ctx context.Context, route MagicTransitStaticRoute) ([]MagicTransitStaticRoute, error) { - if err := api.checkAccountID(); err != nil { - return []MagicTransitStaticRoute{}, err - } - - uri := fmt.Sprintf("/accounts/%s/magic/routes", api.AccountID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, CreateMagicTransitStaticRoutesRequest{ - Routes: []MagicTransitStaticRoute{ - route, - }, - }) - - if err != nil { - return []MagicTransitStaticRoute{}, err - } - - result := ListMagicTransitStaticRoutesResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return []MagicTransitStaticRoute{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result.Routes, nil -} - -// UpdateMagicTransitStaticRoute updates a static route -// -// API reference: https://api.cloudflare.com/#magic-transit-static-routes-update-route -func (api *API) UpdateMagicTransitStaticRoute(ctx context.Context, id string, route MagicTransitStaticRoute) (MagicTransitStaticRoute, error) { - if err := api.checkAccountID(); err != nil { - return MagicTransitStaticRoute{}, err - } - - uri := fmt.Sprintf("/accounts/%s/magic/routes/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, route) - - if err != nil { - return MagicTransitStaticRoute{}, err - } - - result := UpdateMagicTransitStaticRouteResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return MagicTransitStaticRoute{}, errors.Wrap(err, errUnmarshalError) - } - - if !result.Result.Modified { - return MagicTransitStaticRoute{}, errors.New(errMagicTransitStaticRouteNotModified) - } - - return result.Result.ModifiedRoute, nil -} - -// DeleteMagicTransitStaticRoute deletes a static route -// -// API reference: https://api.cloudflare.com/#magic-transit-static-routes-delete-route -func (api *API) DeleteMagicTransitStaticRoute(ctx context.Context, id string) (MagicTransitStaticRoute, error) { - if err := api.checkAccountID(); err != nil { - return MagicTransitStaticRoute{}, err - } - - uri := fmt.Sprintf("/accounts/%s/magic/routes/%s", api.AccountID, id) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - - if err != nil { - return MagicTransitStaticRoute{}, err - } - - result := DeleteMagicTransitStaticRouteResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return MagicTransitStaticRoute{}, errors.Wrap(err, errUnmarshalError) - } - - if !result.Result.Deleted { - return MagicTransitStaticRoute{}, errors.New(errMagicTransitStaticRouteNotDeleted) - } - - return result.Result.DeletedRoute, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/notifications.go b/vendor/github.com/cloudflare/cloudflare-go/notifications.go deleted file mode 100644 index 1c322f9d..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/notifications.go +++ /dev/null @@ -1,395 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" -) - -// NotificationMechanismData holds a single public facing mechanism data -// integation. -type NotificationMechanismData struct { - Name string `json:"name"` - ID string `json:"id"` -} - -// NotificationMechanismIntegrations is a list of all the integrations of a -// certain mechanism type e.g. all email integrations -type NotificationMechanismIntegrations []NotificationMechanismData - -// NotificationPolicy represents the notification policy created along with -// the destinations. -type NotificationPolicy struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Enabled bool `json:"enabled"` - AlertType string `json:"alert_type"` - Mechanisms map[string]NotificationMechanismIntegrations `json:"mechanisms"` - Created time.Time `json:"created"` - Modified time.Time `json:"modified"` - Conditions map[string]interface{} `json:"conditions"` - Filters map[string][]string `json:"filters"` -} - -// NotificationPoliciesResponse holds the response for listing all -// notification policies for an account. -type NotificationPoliciesResponse struct { - Response - ResultInfo - Result []NotificationPolicy -} - -// NotificationPolicyResponse holds the response type when a single policy -// is retrieved. -type NotificationPolicyResponse struct { - Response - Result NotificationPolicy -} - -// NotificationWebhookIntegration describes the webhook information along -// with its status. -type NotificationWebhookIntegration struct { - ID string `json:"id"` - Name string `json:"name"` - Type string `json:"type"` - URL string `json:"url"` - CreatedAt time.Time `json:"created_at"` - LastSuccess *time.Time `json:"last_success"` - LastFailure *time.Time `json:"last_failure"` -} - -// NotificationWebhookResponse describes a single webhook retrieved. -type NotificationWebhookResponse struct { - Response - ResultInfo - Result NotificationWebhookIntegration -} - -// NotificationWebhooksResponse describes a list of webhooks retrieved. -type NotificationWebhooksResponse struct { - Response - ResultInfo - Result []NotificationWebhookIntegration -} - -// NotificationUpsertWebhooks describes a valid webhook request. -type NotificationUpsertWebhooks struct { - Name string `json:"name"` - URL string `json:"url"` - Secret string `json:"secret"` -} - -// NotificationPagerDutyResource describes a PagerDuty integration. -type NotificationPagerDutyResource struct { - ID string `json:"id"` - Name string `json:"name"` -} - -// NotificationPagerDutyResponse describes the PagerDuty integration -// retrieved. -type NotificationPagerDutyResponse struct { - Response - ResultInfo - Result NotificationPagerDutyResource -} - -// NotificationResource describes the id of an inserted/updated/deleted -// resource. -type NotificationResource struct { - ID string -} - -// SaveResponse is returned when a resource is inserted/updated/deleted. -type SaveResponse struct { - Response - Result NotificationResource -} - -// NotificationMechanismMetaData represents the state of the delivery -// mechanism. -type NotificationMechanismMetaData struct { - Eligible bool `json:"eligible"` - Ready bool `json:"ready"` - Type string `json:"type"` -} - -// NotificationMechanisms are the different possible delivery mechanisms. -type NotificationMechanisms struct { - Email NotificationMechanismMetaData `json:"email"` - PagerDuty NotificationMechanismMetaData `json:"pagerduty"` - Webhooks NotificationMechanismMetaData `json:"webhooks,omitempty"` -} - -// NotificationEligibilityResponse describes the eligible mechanisms that -// can be configured for a notification. -type NotificationEligibilityResponse struct { - Response - Result NotificationMechanisms -} - -// NotificationsGroupedByProduct are grouped by products. -type NotificationsGroupedByProduct map[string][]NotificationAlertWithDescription - -// NotificationAlertWithDescription represents the alert/notification -// available. -type NotificationAlertWithDescription struct { - DisplayName string `json:"display_name"` - Type string `json:"type"` - Description string `json:"description"` -} - -// NotificationAvailableAlertsResponse describes the available -// alerts/notifications grouped by products. -type NotificationAvailableAlertsResponse struct { - Response - Result NotificationsGroupedByProduct -} - -// ListNotificationPolicies will return the notification policies -// created by a user for a specific account. -// -// API Reference: https://api.cloudflare.com/#notification-policies-properties -func (api *API) ListNotificationPolicies(ctx context.Context, accountID string) (NotificationPoliciesResponse, error) { - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/policies", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, baseURL, nil) - if err != nil { - return NotificationPoliciesResponse{}, err - } - var r NotificationPoliciesResponse - err = json.Unmarshal(res, &r) - if err != nil { - return r, err - } - return r, nil -} - -// GetNotificationPolicy returns a specific created by a user, given the account -// id and the policy id. -// -// API Reference: https://api.cloudflare.com/#notification-policies-properties -func (api *API) GetNotificationPolicy(ctx context.Context, accountID, policyID string) (NotificationPolicyResponse, error) { - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/policies/%s", accountID, policyID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, baseURL, nil) - if err != nil { - return NotificationPolicyResponse{}, err - } - var r NotificationPolicyResponse - err = json.Unmarshal(res, &r) - if err != nil { - return r, err - } - return r, nil -} - -// CreateNotificationPolicy creates a notification policy for an account. -// -// API Reference: https://api.cloudflare.com/#notification-policies-create-notification-policy -func (api *API) CreateNotificationPolicy(ctx context.Context, accountID string, policy NotificationPolicy) (SaveResponse, error) { - - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/policies", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, baseURL, policy) - if err != nil { - return SaveResponse{}, err - } - return unmarshalNotificationSaveResponse(res) -} - -// UpdateNotificationPolicy updates a notification policy, given the -// account id and the policy id and returns the policy id. -// -// API Reference: https://api.cloudflare.com/#notification-policies-update-notification-policy -func (api *API) UpdateNotificationPolicy(ctx context.Context, accountID string, policy *NotificationPolicy) (SaveResponse, error) { - if policy == nil { - return SaveResponse{}, fmt.Errorf("policy cannot be nil") - } - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/policies/%s", accountID, policy.ID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, baseURL, policy) - if err != nil { - return SaveResponse{}, err - } - return unmarshalNotificationSaveResponse(res) -} - -// DeleteNotificationPolicy deletes a notification policy for an account. -// -// API Reference: https://api.cloudflare.com/#notification-policies-delete-notification-policy -func (api *API) DeleteNotificationPolicy(ctx context.Context, accountID, policyID string) (SaveResponse, error) { - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/policies/%s", accountID, policyID) - - res, err := api.makeRequestContext(ctx, http.MethodDelete, baseURL, nil) - if err != nil { - return SaveResponse{}, err - } - return unmarshalNotificationSaveResponse(res) -} - -// ListNotificationWebhooks will return the webhook destinations configured -// for an account. -// -// API Reference: https://api.cloudflare.com/#notification-webhooks-list-webhooks -func (api *API) ListNotificationWebhooks(ctx context.Context, accountID string) (NotificationWebhooksResponse, error) { - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/destinations/webhooks", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, baseURL, nil) - if err != nil { - return NotificationWebhooksResponse{}, err - } - var r NotificationWebhooksResponse - err = json.Unmarshal(res, &r) - if err != nil { - return r, err - } - return r, nil - -} - -// CreateNotificationWebhooks will help connect a webhooks destination. -// A test message will be sent to the webhooks endpoint during creation. -// If added successfully, the webhooks can be setup as a destination mechanism -// while creating policies. -// -// Notifications will be posted to this URL. -// -// API Reference: https://api.cloudflare.com/#notification-webhooks-create-webhook -func (api *API) CreateNotificationWebhooks(ctx context.Context, accountID string, webhooks *NotificationUpsertWebhooks) (SaveResponse, error) { - if webhooks == nil { - return SaveResponse{}, fmt.Errorf("webhooks cannot be nil") - } - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/destinations/webhooks", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, baseURL, webhooks) - if err != nil { - return SaveResponse{}, err - } - - return unmarshalNotificationSaveResponse(res) -} - -// GetNotificationWebhooks will return a specific webhook destination, -// given the account and webhooks ids. -// -// API Reference: https://api.cloudflare.com/#notification-webhooks-get-webhook -func (api *API) GetNotificationWebhooks(ctx context.Context, accountID, webhookID string) (NotificationWebhookResponse, error) { - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/destinations/webhooks/%s", accountID, webhookID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, baseURL, nil) - if err != nil { - return NotificationWebhookResponse{}, err - } - var r NotificationWebhookResponse - err = json.Unmarshal(res, &r) - if err != nil { - return r, err - } - return r, nil -} - -// UpdateNotificationWebhooks will update a particular webhook's name, -// given the account and webhooks ids. -// -// The webhook url and secret cannot be updated. -// -// API Reference: https://api.cloudflare.com/#notification-webhooks-update-webhook -func (api *API) UpdateNotificationWebhooks(ctx context.Context, accountID, webhookID string, webhooks *NotificationUpsertWebhooks) (SaveResponse, error) { - if webhooks == nil { - return SaveResponse{}, fmt.Errorf("webhooks cannot be nil") - } - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/destinations/webhooks/%s", accountID, webhookID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, baseURL, webhooks) - if err != nil { - return SaveResponse{}, err - } - - return unmarshalNotificationSaveResponse(res) -} - -// DeleteNotificationWebhooks will delete a webhook, given the account and -// webhooks ids. Deleting the webhooks will remove it from any connected -// notification policies. -// -// API Reference: https://api.cloudflare.com/#notification-webhooks-delete-webhook -func (api *API) DeleteNotificationWebhooks(ctx context.Context, accountID, webhookID string) (SaveResponse, error) { - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/destinations/webhooks/%s", accountID, webhookID) - - res, err := api.makeRequestContext(ctx, http.MethodDelete, baseURL, nil) - if err != nil { - return SaveResponse{}, err - } - - return unmarshalNotificationSaveResponse(res) -} - -// ListPagerDutyNotificationDestinations will return the pagerduty -// destinations configured for an account. -// -// API Reference: https://api.cloudflare.com/#notification-destinations-with-pagerduty-list-pagerduty-services -func (api *API) ListPagerDutyNotificationDestinations(ctx context.Context, accountID string) (NotificationPagerDutyResponse, error) { - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/destinations/pagerduty", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, baseURL, nil) - if err != nil { - return NotificationPagerDutyResponse{}, err - } - var r NotificationPagerDutyResponse - err = json.Unmarshal(res, &r) - if err != nil { - return r, err - } - return r, nil -} - -// GetEligibleNotificationDestinations will return the types of -// destinations an account is eligible to configure. -// -// API Reference: https://api.cloudflare.com/#notification-mechanism-eligibility-properties -func (api *API) GetEligibleNotificationDestinations(ctx context.Context, accountID string) (NotificationEligibilityResponse, error) { - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/destinations/eligible", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, baseURL, nil) - if err != nil { - return NotificationEligibilityResponse{}, err - } - var r NotificationEligibilityResponse - err = json.Unmarshal(res, &r) - if err != nil { - return r, err - } - return r, nil -} - -// GetAvailableNotificationTypes will return the alert types available for -// a given account. -// -// API Reference: https://api.cloudflare.com/#notification-mechanism-eligibility-properties -func (api *API) GetAvailableNotificationTypes(ctx context.Context, accountID string) (NotificationAvailableAlertsResponse, error) { - baseURL := fmt.Sprintf("/accounts/%s/alerting/v3/available_alerts", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, baseURL, nil) - if err != nil { - return NotificationAvailableAlertsResponse{}, err - } - var r NotificationAvailableAlertsResponse - err = json.Unmarshal(res, &r) - if err != nil { - return r, err - } - return r, nil -} - -// unmarshal will unmarshal bytes and return a SaveResponse -func unmarshalNotificationSaveResponse(res []byte) (SaveResponse, error) { - var r SaveResponse - err := json.Unmarshal(res, &r) - if err != nil { - return r, err - } - return r, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/options.go b/vendor/github.com/cloudflare/cloudflare-go/options.go deleted file mode 100644 index 35f10f3b..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/options.go +++ /dev/null @@ -1,109 +0,0 @@ -package cloudflare - -import ( - "net/http" - - "time" - - "golang.org/x/time/rate" -) - -// Option is a functional option for configuring the API client. -type Option func(*API) error - -// HTTPClient accepts a custom *http.Client for making API calls. -func HTTPClient(client *http.Client) Option { - return func(api *API) error { - api.httpClient = client - return nil - } -} - -// Headers allows you to set custom HTTP headers when making API calls (e.g. for -// satisfying HTTP proxies, or for debugging). -func Headers(headers http.Header) Option { - return func(api *API) error { - api.headers = headers - return nil - } -} - -// UsingAccount allows you to apply account-level changes (Load Balancing, -// Railguns) to an account instead. -func UsingAccount(accountID string) Option { - return func(api *API) error { - api.AccountID = accountID - return nil - } -} - -// UsingRateLimit applies a non-default rate limit to client API requests -// If not specified the default of 4rps will be applied -func UsingRateLimit(rps float64) Option { - return func(api *API) error { - // because ratelimiter doesnt do any windowing - // setting burst makes it difficult to enforce a fixed rate - // so setting it equal to 1 this effectively disables bursting - // this doesn't check for sensible values, ultimately the api will enforce that the value is ok - api.rateLimiter = rate.NewLimiter(rate.Limit(rps), 1) - return nil - } -} - -// UsingRetryPolicy applies a non-default number of retries and min/max retry delays -// This will be used when the client exponentially backs off after errored requests -func UsingRetryPolicy(maxRetries int, minRetryDelaySecs int, maxRetryDelaySecs int) Option { - // seconds is very granular for a minimum delay - but this is only in case of failure - return func(api *API) error { - api.retryPolicy = RetryPolicy{ - MaxRetries: maxRetries, - MinRetryDelay: time.Duration(minRetryDelaySecs) * time.Second, - MaxRetryDelay: time.Duration(maxRetryDelaySecs) * time.Second, - } - return nil - } -} - -// UsingLogger can be set if you want to get log output from this API instance -// By default no log output is emitted -func UsingLogger(logger Logger) Option { - return func(api *API) error { - api.logger = logger - return nil - } -} - -// UserAgent can be set if you want to send a software name and version for HTTP access logs. -// It is recommended to set it in order to help future Customer Support diagnostics -// and prevent collateral damage by sharing generic User-Agent string with abusive users. -// E.g. "my-software/1.2.3". By default generic Go User-Agent is used. -func UserAgent(userAgent string) Option { - return func(api *API) error { - api.UserAgent = userAgent - return nil - } -} - -// BaseURL allows you to override the default HTTP base URL used for API calls. -func BaseURL(baseURL string) Option { - return func(api *API) error { - api.BaseURL = baseURL - return nil - } -} - -// parseOptions parses the supplied options functions and returns a configured -// *API instance. -func (api *API) parseOptions(opts ...Option) error { - // Range over each options function and apply it to our API type to - // configure it. Options functions are applied in order, with any - // conflicting options overriding earlier calls. - for _, option := range opts { - err := option(api) - if err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/origin_ca.go b/vendor/github.com/cloudflare/cloudflare-go/origin_ca.go deleted file mode 100644 index 4d6181d9..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/origin_ca.go +++ /dev/null @@ -1,230 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "time" - - "github.com/pkg/errors" -) - -// OriginCACertificate represents a Cloudflare-issued certificate. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca -type OriginCACertificate struct { - ID string `json:"id"` - Certificate string `json:"certificate"` - Hostnames []string `json:"hostnames"` - ExpiresOn time.Time `json:"expires_on"` - RequestType string `json:"request_type"` - RequestValidity int `json:"requested_validity"` - RevokedAt time.Time `json:"revoked_at,omitempty"` - CSR string `json:"csr"` -} - -// UnmarshalJSON handles custom parsing from an API response to an OriginCACertificate -// http://choly.ca/post/go-json-marshalling/ -func (c *OriginCACertificate) UnmarshalJSON(data []byte) error { - type alias OriginCACertificate - - aux := &struct { - ExpiresOn string `json:"expires_on"` - *alias - }{ - alias: (*alias)(c), - } - - var err error - - if err = json.Unmarshal(data, &aux); err != nil { - return err - } - - // This format comes from time.Time.String() source - c.ExpiresOn, err = time.Parse("2006-01-02 15:04:05.999999999 -0700 MST", aux.ExpiresOn) - - if err != nil { - c.ExpiresOn, err = time.Parse(time.RFC3339, aux.ExpiresOn) - } - - if err != nil { - return err - } - - return nil -} - -// OriginCACertificateListOptions represents the parameters used to list Cloudflare-issued certificates. -type OriginCACertificateListOptions struct { - ZoneID string -} - -// OriginCACertificateID represents the ID of the revoked certificate from the Revoke Certificate endpoint. -type OriginCACertificateID struct { - ID string `json:"id"` -} - -// originCACertificateResponse represents the response from the Create Certificate and the Certificate Details endpoints. -type originCACertificateResponse struct { - Response - Result OriginCACertificate `json:"result"` -} - -// originCACertificateResponseList represents the response from the List Certificates endpoint. -type originCACertificateResponseList struct { - Response - Result []OriginCACertificate `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// originCACertificateResponseRevoke represents the response from the Revoke Certificate endpoint. -type originCACertificateResponseRevoke struct { - Response - Result OriginCACertificateID `json:"result"` -} - -// CreateOriginCertificate creates a Cloudflare-signed certificate. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-create-certificate -func (api *API) CreateOriginCertificate(ctx context.Context, certificate OriginCACertificate) (*OriginCACertificate, error) { - uri := "/certificates" - res, err := api.makeRequestWithAuthType(ctx, http.MethodPost, uri, certificate, AuthUserService) - - if err != nil { - return nil, err - } - - var originResponse *originCACertificateResponse - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return &originResponse.Result, nil -} - -// OriginCertificates lists all Cloudflare-issued certificates. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-list-certificates -func (api *API) OriginCertificates(ctx context.Context, options OriginCACertificateListOptions) ([]OriginCACertificate, error) { - v := url.Values{} - if options.ZoneID != "" { - v.Set("zone_id", options.ZoneID) - } - uri := fmt.Sprintf("/certificates?%s", v.Encode()) - res, err := api.makeRequestWithAuthType(ctx, http.MethodGet, uri, nil, AuthUserService) - - if err != nil { - return nil, err - } - - var originResponse *originCACertificateResponseList - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return originResponse.Result, nil -} - -// OriginCertificate returns the details for a Cloudflare-issued certificate. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-certificate-details -func (api *API) OriginCertificate(ctx context.Context, certificateID string) (*OriginCACertificate, error) { - uri := fmt.Sprintf("/certificates/%s", certificateID) - res, err := api.makeRequestWithAuthType(ctx, http.MethodGet, uri, nil, AuthUserService) - - if err != nil { - return nil, err - } - - var originResponse *originCACertificateResponse - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return &originResponse.Result, nil -} - -// RevokeOriginCertificate revokes a created certificate for a zone. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-revoke-certificate -func (api *API) RevokeOriginCertificate(ctx context.Context, certificateID string) (*OriginCACertificateID, error) { - uri := fmt.Sprintf("/certificates/%s", certificateID) - res, err := api.makeRequestWithAuthType(ctx, http.MethodDelete, uri, nil, AuthUserService) - - if err != nil { - return nil, err - } - - var originResponse *originCACertificateResponseRevoke - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return &originResponse.Result, nil -} - -// Gets the Cloudflare Origin CA Root Certificate for a given algorithm in PEM format. -// Algorithm must be one of ['ecc', 'rsa']. -func OriginCARootCertificate(algorithm string) ([]byte, error) { - var url string - switch algorithm { - case "ecc": - url = originCARootCertEccURL - case "rsa": - url = originCARootCertRsaURL - default: - return nil, fmt.Errorf("invalid algorithm: must be one of ['ecc', 'rsa']") - } - - resp, err := http.Get(url) - if err != nil { - return nil, errors.Wrap(err, "HTTP request failed") - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, errors.Wrap(err, "Response body could not be read") - } - - return body, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/page_rules.go b/vendor/github.com/cloudflare/cloudflare-go/page_rules.go deleted file mode 100644 index f345b646..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/page_rules.go +++ /dev/null @@ -1,240 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// PageRuleTarget is the target to evaluate on a request. -// -// Currently Target must always be "url" and Operator must be "matches". Value -// is the URL pattern to match against. -type PageRuleTarget struct { - Target string `json:"target"` - Constraint struct { - Operator string `json:"operator"` - Value string `json:"value"` - } `json:"constraint"` -} - -/* -PageRuleAction is the action to take when the target is matched. - -Valid IDs are: - always_online - always_use_https - automatic_https_rewrites - browser_cache_ttl - browser_check - bypass_cache_on_cookie - cache_by_device_type - cache_deception_armor - cache_level - cache_key_fields - cache_on_cookie - disable_apps - disable_performance - disable_railgun - disable_security - edge_cache_ttl - email_obfuscation - explicit_cache_control - forwarding_url - host_header_override - ip_geolocation - minify - mirage - opportunistic_encryption - origin_error_page_pass_thru - polish - resolve_override - respect_strong_etag - response_buffering - rocket_loader - security_level - server_side_exclude - sort_query_string_for_cache - ssl - true_client_ip_header - waf -*/ -type PageRuleAction struct { - ID string `json:"id"` - Value interface{} `json:"value"` -} - -// PageRuleActions maps API action IDs to human-readable strings. -var PageRuleActions = map[string]string{ - "always_online": "Always Online", // Value of type string - "always_use_https": "Always Use HTTPS", // Value of type interface{} - "automatic_https_rewrites": "Automatic HTTPS Rewrites", // Value of type string - "browser_cache_ttl": "Browser Cache TTL", // Value of type int - "browser_check": "Browser Integrity Check", // Value of type string - "bypass_cache_on_cookie": "Bypass Cache on Cookie", // Value of type string - "cache_by_device_type": "Cache By Device Type", // Value of type string - "cache_deception_armor": "Cache Deception Armor", // Value of type string - "cache_level": "Cache Level", // Value of type string - "cache_key_fields": "Custom Cache Key", // Value of type map[string]interface - "cache_on_cookie": "Cache On Cookie", // Value of type string - "disable_apps": "Disable Apps", // Value of type interface{} - "disable_performance": "Disable Performance", // Value of type interface{} - "disable_railgun": "Disable Railgun", // Value of type string - "disable_security": "Disable Security", // Value of type interface{} - "edge_cache_ttl": "Edge Cache TTL", // Value of type int - "email_obfuscation": "Email Obfuscation", // Value of type string - "explicit_cache_control": "Origin Cache Control", // Value of type string - "forwarding_url": "Forwarding URL", // Value of type map[string]interface - "host_header_override": "Host Header Override", // Value of type string - "ip_geolocation": "IP Geolocation Header", // Value of type string - "minify": "Minify", // Value of type map[string]interface - "mirage": "Mirage", // Value of type string - "opportunistic_encryption": "Opportunistic Encryption", // Value of type string - "origin_error_page_pass_thru": "Origin Error Page Pass-thru", // Value of type string - "polish": "Polish", // Value of type string - "resolve_override": "Resolve Override", // Value of type string - "respect_strong_etag": "Respect Strong ETags", // Value of type string - "response_buffering": "Response Buffering", // Value of type string - "rocket_loader": "Rocker Loader", // Value of type string - "security_level": "Security Level", // Value of type string - "server_side_exclude": "Server Side Excludes", // Value of type string - "sort_query_string_for_cache": "Query String Sort", // Value of type string - "ssl": "SSL", // Value of type string - "true_client_ip_header": "True Client IP Header", // Value of type string - "waf": "Web Application Firewall", // Value of type string -} - -// PageRule describes a Page Rule. -type PageRule struct { - ID string `json:"id,omitempty"` - Targets []PageRuleTarget `json:"targets"` - Actions []PageRuleAction `json:"actions"` - Priority int `json:"priority"` - Status string `json:"status"` - ModifiedOn time.Time `json:"modified_on,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` -} - -// PageRuleDetailResponse is the API response, containing a single PageRule. -type PageRuleDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result PageRule `json:"result"` -} - -// PageRulesResponse is the API response, containing an array of PageRules. -type PageRulesResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result []PageRule `json:"result"` -} - -// CreatePageRule creates a new Page Rule for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-create-a-page-rule -func (api *API) CreatePageRule(ctx context.Context, zoneID string, rule PageRule) (*PageRule, error) { - uri := fmt.Sprintf("/zones/%s/pagerules", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, rule) - if err != nil { - return nil, err - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return &r.Result, nil -} - -// ListPageRules returns all Page Rules for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-list-page-rules -func (api *API) ListPageRules(ctx context.Context, zoneID string) ([]PageRule, error) { - uri := fmt.Sprintf("/zones/%s/pagerules", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []PageRule{}, err - } - var r PageRulesResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []PageRule{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// PageRule fetches detail about one Page Rule for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-page-rule-details -func (api *API) PageRule(ctx context.Context, zoneID, ruleID string) (PageRule, error) { - uri := fmt.Sprintf("/zones/%s/pagerules/%s", zoneID, ruleID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return PageRule{}, err - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return PageRule{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ChangePageRule lets you change individual settings for a Page Rule. This is -// in contrast to UpdatePageRule which replaces the entire Page Rule. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-change-a-page-rule -func (api *API) ChangePageRule(ctx context.Context, zoneID, ruleID string, rule PageRule) error { - uri := fmt.Sprintf("/zones/%s/pagerules/%s", zoneID, ruleID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, rule) - if err != nil { - return err - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// UpdatePageRule lets you replace a Page Rule. This is in contrast to -// ChangePageRule which lets you change individual settings. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-update-a-page-rule -func (api *API) UpdatePageRule(ctx context.Context, zoneID, ruleID string, rule PageRule) error { - uri := fmt.Sprintf("/zones/%s/pagerules/%s", zoneID, ruleID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, rule) - if err != nil { - return err - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// DeletePageRule deletes a Page Rule for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-delete-a-page-rule -func (api *API) DeletePageRule(ctx context.Context, zoneID, ruleID string) error { - uri := fmt.Sprintf("/zones/%s/pagerules/%s", zoneID, ruleID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/railgun.go b/vendor/github.com/cloudflare/cloudflare-go/railgun.go deleted file mode 100644 index b85e0336..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/railgun.go +++ /dev/null @@ -1,300 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "time" - - "github.com/pkg/errors" -) - -// Railgun represents a Railgun's properties. -type Railgun struct { - ID string `json:"id"` - Name string `json:"name"` - Status string `json:"status"` - Enabled bool `json:"enabled"` - ZonesConnected int `json:"zones_connected"` - Build string `json:"build"` - Version string `json:"version"` - Revision string `json:"revision"` - ActivationKey string `json:"activation_key"` - ActivatedOn time.Time `json:"activated_on"` - CreatedOn time.Time `json:"created_on"` - ModifiedOn time.Time `json:"modified_on"` - UpgradeInfo struct { - LatestVersion string `json:"latest_version"` - DownloadLink string `json:"download_link"` - } `json:"upgrade_info"` -} - -// RailgunListOptions represents the parameters used to list railguns. -type RailgunListOptions struct { - Direction string -} - -// railgunResponse represents the response from the Create Railgun and the Railgun Details endpoints. -type railgunResponse struct { - Response - Result Railgun `json:"result"` -} - -// railgunsResponse represents the response from the List Railguns endpoint. -type railgunsResponse struct { - Response - Result []Railgun `json:"result"` -} - -// CreateRailgun creates a new Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-create-railgun -func (api *API) CreateRailgun(ctx context.Context, name string) (Railgun, error) { - uri := fmt.Sprintf("%s/railguns", api.userBaseURL("")) - params := struct { - Name string `json:"name"` - }{ - Name: name, - } - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, params) - if err != nil { - return Railgun{}, err - } - var r railgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return Railgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListRailguns lists Railguns connected to an account. -// -// API reference: https://api.cloudflare.com/#railgun-list-railguns -func (api *API) ListRailguns(ctx context.Context, options RailgunListOptions) ([]Railgun, error) { - v := url.Values{} - if options.Direction != "" { - v.Set("direction", options.Direction) - } - uri := fmt.Sprintf("%s/railguns?%s", api.userBaseURL(""), v.Encode()) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - var r railgunsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// RailgunDetails returns the details for a Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-railgun-details -func (api *API) RailgunDetails(ctx context.Context, railgunID string) (Railgun, error) { - uri := fmt.Sprintf("%s/railguns/%s", api.userBaseURL(""), railgunID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return Railgun{}, err - } - var r railgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return Railgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// RailgunZones returns the zones that are currently using a Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-get-zones-connected-to-a-railgun -func (api *API) RailgunZones(ctx context.Context, railgunID string) ([]Zone, error) { - uri := fmt.Sprintf("%s/railguns/%s/zones", api.userBaseURL(""), railgunID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - var r ZonesResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// enableRailgun enables (true) or disables (false) a Railgun for all zones connected to it. -// -// API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) enableRailgun(ctx context.Context, railgunID string, enable bool) (Railgun, error) { - uri := fmt.Sprintf("%s/railguns/%s", api.userBaseURL(""), railgunID) - params := struct { - Enabled bool `json:"enabled"` - }{ - Enabled: enable, - } - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, params) - if err != nil { - return Railgun{}, err - } - var r railgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return Railgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// EnableRailgun enables a Railgun for all zones connected to it. -// -// API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) EnableRailgun(ctx context.Context, railgunID string) (Railgun, error) { - return api.enableRailgun(ctx, railgunID, true) -} - -// DisableRailgun enables a Railgun for all zones connected to it. -// -// API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) DisableRailgun(ctx context.Context, railgunID string) (Railgun, error) { - return api.enableRailgun(ctx, railgunID, false) -} - -// DeleteRailgun disables and deletes a Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-delete-railgun -func (api *API) DeleteRailgun(ctx context.Context, railgunID string) error { - uri := fmt.Sprintf("%s/railguns/%s", api.userBaseURL(""), railgunID) - if _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil); err != nil { - return err - } - return nil -} - -// ZoneRailgun represents the status of a Railgun on a zone. -type ZoneRailgun struct { - ID string `json:"id"` - Name string `json:"name"` - Enabled bool `json:"enabled"` - Connected bool `json:"connected"` -} - -// zoneRailgunResponse represents the response from the Zone Railgun Details endpoint. -type zoneRailgunResponse struct { - Response - Result ZoneRailgun `json:"result"` -} - -// zoneRailgunsResponse represents the response from the Zone Railgun endpoint. -type zoneRailgunsResponse struct { - Response - Result []ZoneRailgun `json:"result"` -} - -// RailgunDiagnosis represents the test results from testing railgun connections -// to a zone. -type RailgunDiagnosis struct { - Method string `json:"method"` - HostName string `json:"host_name"` - HTTPStatus int `json:"http_status"` - Railgun string `json:"railgun"` - URL string `json:"url"` - ResponseStatus string `json:"response_status"` - Protocol string `json:"protocol"` - ElapsedTime string `json:"elapsed_time"` - BodySize string `json:"body_size"` - BodyHash string `json:"body_hash"` - MissingHeaders string `json:"missing_headers"` - ConnectionClose bool `json:"connection_close"` - Cloudflare string `json:"cloudflare"` - CFRay string `json:"cf-ray"` - // NOTE: Cloudflare's online API documentation does not yet have definitions - // for the following fields. See: https://api.cloudflare.com/#railgun-connections-for-a-zone-test-railgun-connection/ - CFWANError string `json:"cf-wan-error"` - CFCacheStatus string `json:"cf-cache-status"` -} - -// railgunDiagnosisResponse represents the response from the Test Railgun Connection endpoint. -type railgunDiagnosisResponse struct { - Response - Result RailgunDiagnosis `json:"result"` -} - -// ZoneRailguns returns the available Railguns for a zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-get-available-railguns -func (api *API) ZoneRailguns(ctx context.Context, zoneID string) ([]ZoneRailgun, error) { - uri := fmt.Sprintf("/zones/%s/railguns", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - var r zoneRailgunsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneRailgunDetails returns the configuration for a given Railgun. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-get-railgun-details -func (api *API) ZoneRailgunDetails(ctx context.Context, zoneID, railgunID string) (ZoneRailgun, error) { - uri := fmt.Sprintf("/zones/%s/railguns/%s", zoneID, railgunID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return ZoneRailgun{}, err - } - var r zoneRailgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneRailgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// TestRailgunConnection tests a Railgun connection for a given zone. -// -// API reference: https://api.cloudflare.com/#railgun-connections-for-a-zone-test-railgun-connection -func (api *API) TestRailgunConnection(ctx context.Context, zoneID, railgunID string) (RailgunDiagnosis, error) { - uri := fmt.Sprintf("/zones/%s/railguns/%s/diagnose", zoneID, railgunID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return RailgunDiagnosis{}, err - } - var r railgunDiagnosisResponse - if err := json.Unmarshal(res, &r); err != nil { - return RailgunDiagnosis{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// connectZoneRailgun connects (true) or disconnects (false) a Railgun for a given zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) connectZoneRailgun(ctx context.Context, zoneID, railgunID string, connect bool) (ZoneRailgun, error) { - uri := fmt.Sprintf("/zones/%s/railguns/%s", zoneID, railgunID) - params := struct { - Connected bool `json:"connected"` - }{ - Connected: connect, - } - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, params) - if err != nil { - return ZoneRailgun{}, err - } - var r zoneRailgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneRailgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ConnectZoneRailgun connects a Railgun for a given zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) ConnectZoneRailgun(ctx context.Context, zoneID, railgunID string) (ZoneRailgun, error) { - return api.connectZoneRailgun(ctx, zoneID, railgunID, true) -} - -// DisconnectZoneRailgun disconnects a Railgun for a given zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) DisconnectZoneRailgun(ctx context.Context, zoneID, railgunID string) (ZoneRailgun, error) { - return api.connectZoneRailgun(ctx, zoneID, railgunID, false) -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/rate_limiting.go b/vendor/github.com/cloudflare/cloudflare-go/rate_limiting.go deleted file mode 100644 index d0be433d..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/rate_limiting.go +++ /dev/null @@ -1,213 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// RateLimit is a policy than can be applied to limit traffic within a customer domain -type RateLimit struct { - ID string `json:"id,omitempty"` - Disabled bool `json:"disabled,omitempty"` - Description string `json:"description,omitempty"` - Match RateLimitTrafficMatcher `json:"match"` - Bypass []RateLimitKeyValue `json:"bypass,omitempty"` - Threshold int `json:"threshold"` - Period int `json:"period"` - Action RateLimitAction `json:"action"` - Correlate *RateLimitCorrelate `json:"correlate,omitempty"` -} - -// RateLimitTrafficMatcher contains the rules that will be used to apply a rate limit to traffic -type RateLimitTrafficMatcher struct { - Request RateLimitRequestMatcher `json:"request"` - Response RateLimitResponseMatcher `json:"response"` -} - -// RateLimitRequestMatcher contains the matching rules pertaining to requests -type RateLimitRequestMatcher struct { - Methods []string `json:"methods,omitempty"` - Schemes []string `json:"schemes,omitempty"` - URLPattern string `json:"url,omitempty"` -} - -// RateLimitResponseMatcher contains the matching rules pertaining to responses -type RateLimitResponseMatcher struct { - Statuses []int `json:"status,omitempty"` - OriginTraffic *bool `json:"origin_traffic,omitempty"` // api defaults to true so we need an explicit empty value - Headers []RateLimitResponseMatcherHeader `json:"headers,omitempty"` -} - -// RateLimitResponseMatcherHeader contains the structure of the origin -// HTTP headers used in request matcher checks. -type RateLimitResponseMatcherHeader struct { - Name string `json:"name"` - Op string `json:"op"` - Value string `json:"value"` -} - -// RateLimitKeyValue is k-v formatted as expected in the rate limit description -type RateLimitKeyValue struct { - Name string `json:"name"` - Value string `json:"value"` -} - -// RateLimitAction is the action that will be taken when the rate limit threshold is reached -type RateLimitAction struct { - Mode string `json:"mode"` - Timeout int `json:"timeout"` - Response *RateLimitActionResponse `json:"response"` -} - -// RateLimitActionResponse is the response that will be returned when rate limit action is triggered -type RateLimitActionResponse struct { - ContentType string `json:"content_type"` - Body string `json:"body"` -} - -// RateLimitCorrelate pertainings to NAT support -type RateLimitCorrelate struct { - By string `json:"by"` -} - -type rateLimitResponse struct { - Response - Result RateLimit `json:"result"` -} - -type rateLimitListResponse struct { - Response - Result []RateLimit `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// CreateRateLimit creates a new rate limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-create-a-ratelimit -func (api *API) CreateRateLimit(ctx context.Context, zoneID string, limit RateLimit) (RateLimit, error) { - uri := fmt.Sprintf("/zones/%s/rate_limits", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, limit) - if err != nil { - return RateLimit{}, err - } - var r rateLimitResponse - if err := json.Unmarshal(res, &r); err != nil { - return RateLimit{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListRateLimits returns Rate Limits for a zone, paginated according to the provided options -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-list-rate-limits -func (api *API) ListRateLimits(ctx context.Context, zoneID string, pageOpts PaginationOptions) ([]RateLimit, ResultInfo, error) { - v := url.Values{} - if pageOpts.PerPage > 0 { - v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) - } - if pageOpts.Page > 0 { - v.Set("page", strconv.Itoa(pageOpts.Page)) - } - - uri := fmt.Sprintf("/zones/%s/rate_limits", zoneID) - if len(v) > 0 { - uri = fmt.Sprintf("%s?%s", uri, v.Encode()) - } - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []RateLimit{}, ResultInfo{}, err - } - - var r rateLimitListResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []RateLimit{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, r.ResultInfo, nil -} - -// ListAllRateLimits returns all Rate Limits for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-list-rate-limits -func (api *API) ListAllRateLimits(ctx context.Context, zoneID string) ([]RateLimit, error) { - pageOpts := PaginationOptions{ - PerPage: 100, // this is the max page size allowed - Page: 1, - } - - allRateLimits := make([]RateLimit, 0) - for { - rateLimits, resultInfo, err := api.ListRateLimits(ctx, zoneID, pageOpts) - if err != nil { - return []RateLimit{}, err - } - allRateLimits = append(allRateLimits, rateLimits...) - // total pages is not returned on this call - // if number of records is less than the max, this must be the last page - // in case TotalCount % PerPage = 0, the last request will return an empty list - if resultInfo.Count < resultInfo.PerPage { - break - } - // continue with the next page - pageOpts.Page = pageOpts.Page + 1 - } - - return allRateLimits, nil -} - -// RateLimit fetches detail about one Rate Limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-rate-limit-details -func (api *API) RateLimit(ctx context.Context, zoneID, limitID string) (RateLimit, error) { - uri := fmt.Sprintf("/zones/%s/rate_limits/%s", zoneID, limitID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return RateLimit{}, err - } - var r rateLimitResponse - err = json.Unmarshal(res, &r) - if err != nil { - return RateLimit{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateRateLimit lets you replace a Rate Limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-update-rate-limit -func (api *API) UpdateRateLimit(ctx context.Context, zoneID, limitID string, limit RateLimit) (RateLimit, error) { - uri := fmt.Sprintf("/zones/%s/rate_limits/%s", zoneID, limitID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, limit) - if err != nil { - return RateLimit{}, err - } - var r rateLimitResponse - if err := json.Unmarshal(res, &r); err != nil { - return RateLimit{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteRateLimit deletes a Rate Limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-delete-rate-limit -func (api *API) DeleteRateLimit(ctx context.Context, zoneID, limitID string) error { - uri := fmt.Sprintf("/zones/%s/rate_limits/%s", zoneID, limitID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - var r rateLimitResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/registrar.go b/vendor/github.com/cloudflare/cloudflare-go/registrar.go deleted file mode 100644 index 9f3aa784..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/registrar.go +++ /dev/null @@ -1,177 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// RegistrarDomain is the structure of the API response for a new -// Cloudflare Registrar domain. -type RegistrarDomain struct { - ID string `json:"id"` - Available bool `json:"available"` - SupportedTLD bool `json:"supported_tld"` - CanRegister bool `json:"can_register"` - TransferIn RegistrarTransferIn `json:"transfer_in"` - CurrentRegistrar string `json:"current_registrar"` - ExpiresAt time.Time `json:"expires_at"` - RegistryStatuses string `json:"registry_statuses"` - Locked bool `json:"locked"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` - RegistrantContact RegistrantContact `json:"registrant_contact"` -} - -// RegistrarTransferIn contains the structure for a domain transfer in -// request. -type RegistrarTransferIn struct { - UnlockDomain string `json:"unlock_domain"` - DisablePrivacy string `json:"disable_privacy"` - EnterAuthCode string `json:"enter_auth_code"` - ApproveTransfer string `json:"approve_transfer"` - AcceptFoa string `json:"accept_foa"` - CanCancelTransfer bool `json:"can_cancel_transfer"` -} - -// RegistrantContact is the contact details for the domain registration. -type RegistrantContact struct { - ID string `json:"id"` - FirstName string `json:"first_name"` - LastName string `json:"last_name"` - Organization string `json:"organization"` - Address string `json:"address"` - Address2 string `json:"address2"` - City string `json:"city"` - State string `json:"state"` - Zip string `json:"zip"` - Country string `json:"country"` - Phone string `json:"phone"` - Email string `json:"email"` - Fax string `json:"fax"` -} - -// RegistrarDomainConfiguration is the structure for making updates to -// and existing domain. -type RegistrarDomainConfiguration struct { - NameServers []string `json:"name_servers"` - Privacy bool `json:"privacy"` - Locked bool `json:"locked"` - AutoRenew bool `json:"auto_renew"` -} - -// RegistrarDomainDetailResponse is the structure of the detailed -// response from the API for a single domain. -type RegistrarDomainDetailResponse struct { - Response - Result RegistrarDomain `json:"result"` -} - -// RegistrarDomainsDetailResponse is the structure of the detailed -// response from the API. -type RegistrarDomainsDetailResponse struct { - Response - Result []RegistrarDomain `json:"result"` -} - -// RegistrarDomain returns a single domain based on the account ID and -// domain name. -// -// API reference: https://api.cloudflare.com/#registrar-domains-get-domain -func (api *API) RegistrarDomain(ctx context.Context, accountID, domainName string) (RegistrarDomain, error) { - uri := fmt.Sprintf("/accounts/%s/registrar/domains/%s", accountID, domainName) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return RegistrarDomain{}, err - } - - var r RegistrarDomainDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return RegistrarDomain{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// RegistrarDomains returns all registrar domains based on the account -// ID. -// -// API reference: https://api.cloudflare.com/#registrar-domains-list-domains -func (api *API) RegistrarDomains(ctx context.Context, accountID string) ([]RegistrarDomain, error) { - uri := fmt.Sprintf("/accounts/%s/registrar/domains", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, nil) - if err != nil { - return []RegistrarDomain{}, err - } - - var r RegistrarDomainsDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []RegistrarDomain{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// TransferRegistrarDomain initiates the transfer from another registrar -// to Cloudflare Registrar. -// -// API reference: https://api.cloudflare.com/#registrar-domains-transfer-domain -func (api *API) TransferRegistrarDomain(ctx context.Context, accountID, domainName string) ([]RegistrarDomain, error) { - uri := fmt.Sprintf("/accounts/%s/registrar/domains/%s/transfer", accountID, domainName) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, nil) - if err != nil { - return []RegistrarDomain{}, err - } - - var r RegistrarDomainsDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []RegistrarDomain{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// CancelRegistrarDomainTransfer cancels a pending domain transfer. -// -// API reference: https://api.cloudflare.com/#registrar-domains-cancel-transfer -func (api *API) CancelRegistrarDomainTransfer(ctx context.Context, accountID, domainName string) ([]RegistrarDomain, error) { - uri := fmt.Sprintf("/accounts/%s/registrar/domains/%s/cancel_transfer", accountID, domainName) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, nil) - if err != nil { - return []RegistrarDomain{}, err - } - - var r RegistrarDomainsDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []RegistrarDomain{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateRegistrarDomain updates an existing Registrar Domain configuration. -// -// API reference: https://api.cloudflare.com/#registrar-domains-update-domain -func (api *API) UpdateRegistrarDomain(ctx context.Context, accountID, domainName string, domainConfiguration RegistrarDomainConfiguration) (RegistrarDomain, error) { - uri := fmt.Sprintf("/accounts/%s/registrar/domains/%s", accountID, domainName) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, domainConfiguration) - if err != nil { - return RegistrarDomain{}, err - } - - var r RegistrarDomainDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return RegistrarDomain{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/rulesets.go b/vendor/github.com/cloudflare/cloudflare-go/rulesets.go deleted file mode 100644 index 26fa8a91..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/rulesets.go +++ /dev/null @@ -1,505 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -const ( - RulesetKindCustom RulesetKind = "custom" - RulesetKindManaged RulesetKind = "managed" - RulesetKindRoot RulesetKind = "root" - RulesetKindSchema RulesetKind = "schema" - RulesetKindZone RulesetKind = "zone" - - RulesetPhaseDDoSL4 RulesetPhase = "ddos_l4" - RulesetPhaseDDoSL7 RulesetPhase = "ddos_l7" - RulesetPhaseHTTPRequestFirewallCustom RulesetPhase = "http_request_firewall_custom" - RulesetPhaseHTTPRequestFirewallManaged RulesetPhase = "http_request_firewall_managed" - RulesetPhaseHTTPRequestLateTransform RulesetPhase = "http_request_late_transform" - RulesetPhaseHTTPRequestMain RulesetPhase = "http_request_main" - RulesetPhaseHTTPRequestSanitize RulesetPhase = "http_request_sanitize" - RulesetPhaseHTTPRequestTransform RulesetPhase = "http_request_transform" - RulesetPhaseHTTPResponseFirewallManaged RulesetPhase = "http_response_firewall_managed" - RulesetPhaseMagicTransit RulesetPhase = "magic_transit" - RulesetPhaseRateLimit RulesetPhase = "http_ratelimit" - - RulesetRuleActionBlock RulesetRuleAction = "block" - RulesetRuleActionChallenge RulesetRuleAction = "challenge" - RulesetRuleActionDDoSDynamic RulesetRuleAction = "ddos_dynamic" - RulesetRuleActionExecute RulesetRuleAction = "execute" - RulesetRuleActionForceConnectionClose RulesetRuleAction = "force_connection_close" - RulesetRuleActionJSChallenge RulesetRuleAction = "js_challenge" - RulesetRuleActionLog RulesetRuleAction = "log" - RulesetRuleActionRewrite RulesetRuleAction = "rewrite" - RulesetRuleActionScore RulesetRuleAction = "score" - RulesetRuleActionSkip RulesetRuleAction = "skip" - - RulesetActionParameterProductBIC RulesetActionParameterProduct = "bic" - RulesetActionParameterProductHOT RulesetActionParameterProduct = "hot" - RulesetActionParameterProductRateLimit RulesetActionParameterProduct = "ratelimit" - RulesetActionParameterProductSecurityLevel RulesetActionParameterProduct = "securityLevel" - RulesetActionParameterProductUABlock RulesetActionParameterProduct = "uablock" - RulesetActionParameterProductWAF RulesetActionParameterProduct = "waf" - RulesetActionParameterProductZoneLockdown RulesetActionParameterProduct = "zonelockdown" - - RulesetRuleActionParametersHTTPHeaderOperationRemove RulesetRuleActionParametersHTTPHeaderOperation = "remove" - RulesetRuleActionParametersHTTPHeaderOperationSet RulesetRuleActionParametersHTTPHeaderOperation = "set" -) - -// RulesetKindValues exposes all the available `RulesetKind` values as a slice -// of strings. -func RulesetKindValues() []string { - return []string{ - string(RulesetKindCustom), - string(RulesetKindManaged), - string(RulesetKindRoot), - string(RulesetKindSchema), - string(RulesetKindZone), - } -} - -// RulesetPhaseValues exposes all the available `RulesetPhase` values as a slice -// of strings. -func RulesetPhaseValues() []string { - return []string{ - string(RulesetPhaseDDoSL4), - string(RulesetPhaseDDoSL7), - string(RulesetPhaseHTTPRequestFirewallCustom), - string(RulesetPhaseHTTPRequestFirewallManaged), - string(RulesetPhaseHTTPRequestLateTransform), - string(RulesetPhaseHTTPRequestMain), - string(RulesetPhaseHTTPRequestSanitize), - string(RulesetPhaseHTTPRequestTransform), - string(RulesetPhaseHTTPResponseFirewallManaged), - string(RulesetPhaseMagicTransit), - string(RulesetPhaseRateLimit), - } -} - -// RulesetRuleActionValues exposes all the available `RulesetRuleAction` values -// as a slice of strings. -func RulesetRuleActionValues() []string { - return []string{ - string(RulesetRuleActionBlock), - string(RulesetRuleActionChallenge), - string(RulesetRuleActionDDoSDynamic), - string(RulesetRuleActionExecute), - string(RulesetRuleActionForceConnectionClose), - string(RulesetRuleActionJSChallenge), - string(RulesetRuleActionLog), - string(RulesetRuleActionRewrite), - string(RulesetRuleActionScore), - string(RulesetRuleActionSkip), - } -} - -// RulesetActionParameterProductValues exposes all the available -// `RulesetActionParameterProduct` values as a slice of strings. -func RulesetActionParameterProductValues() []string { - return []string{ - string(RulesetActionParameterProductBIC), - string(RulesetActionParameterProductHOT), - string(RulesetActionParameterProductRateLimit), - string(RulesetActionParameterProductSecurityLevel), - string(RulesetActionParameterProductUABlock), - string(RulesetActionParameterProductWAF), - string(RulesetActionParameterProductZoneLockdown), - } -} - -func RulesetRuleActionParametersHTTPHeaderOperationValues() []string { - return []string{ - string(RulesetRuleActionParametersHTTPHeaderOperationRemove), - string(RulesetRuleActionParametersHTTPHeaderOperationSet), - } -} - -// RulesetRuleAction defines a custom type that is used to express allowed -// values for the rule action. -type RulesetRuleAction string - -// RulesetKind is the custom type for allowed variances of rulesets. -type RulesetKind string - -// RulesetPhase is the custom type for defining at what point the ruleset will -// be applied in the request pipeline. -type RulesetPhase string - -// RulesetActionParameterProduct is the custom type for defining what products -// can be used within the action parameters of a ruleset. -type RulesetActionParameterProduct string - -// RulesetRuleActionParametersHTTPHeaderOperation defines available options for -// HTTP header operations in actions. -type RulesetRuleActionParametersHTTPHeaderOperation string - -// Ruleset contains the structure of a Ruleset. Using `string` for Kind and -// Phase is a developer nicety to support downstream clients like Terraform who -// don't really have a strong and expansive type system. As always, the -// recommendation is to use the types provided where possible to avoid -// surprises. -type Ruleset struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - Kind string `json:"kind,omitempty"` - Version string `json:"version,omitempty"` - LastUpdated *time.Time `json:"last_updated,omitempty"` - Phase string `json:"phase,omitempty"` - Rules []RulesetRule `json:"rules"` - ShareableEntitlementName string `json:"shareable_entitlement_name,omitempty"` -} - -// RulesetRuleActionParameters specifies the action parameters for a Ruleset -// rule. -type RulesetRuleActionParameters struct { - ID string `json:"id,omitempty"` - Ruleset string `json:"ruleset,omitempty"` - Rulesets []string `json:"rulesets,omitempty"` - Rules map[string][]string `json:"rules,omitempty"` - Increment int `json:"increment,omitempty"` - URI *RulesetRuleActionParametersURI `json:"uri,omitempty"` - Headers map[string]RulesetRuleActionParametersHTTPHeader `json:"headers,omitempty"` - Products []string `json:"products,omitempty"` - Overrides *RulesetRuleActionParametersOverrides `json:"overrides,omitempty"` - MatchedData *RulesetRuleActionParametersMatchedData `json:"matched_data,omitempty"` - Version string `json:"version,omitempty"` -} - -// RulesetRuleActionParametersURI holds the URI struct for an action parameter. -type RulesetRuleActionParametersURI struct { - Path *RulesetRuleActionParametersURIPath `json:"path,omitempty"` - Query *RulesetRuleActionParametersURIQuery `json:"query,omitempty"` - Origin bool `json:"origin,omitempty"` -} - -// RulesetRuleActionParametersURIPath holds the path specific portion of a URI -// action parameter. -type RulesetRuleActionParametersURIPath struct { - Value string `json:"value,omitempty"` - Expression string `json:"expression,omitempty"` -} - -// RulesetRuleActionParametersURIQuery holds the query specific portion of a URI -// action parameter. -type RulesetRuleActionParametersURIQuery struct { - Value string `json:"value,omitempty"` - Expression string `json:"expression,omitempty"` -} - -// RulesetRuleActionParametersHTTPHeader is the definition for define action -// parameters that involve HTTP headers. -type RulesetRuleActionParametersHTTPHeader struct { - Operation string `json:"operation,omitempty"` - Value string `json:"value,omitempty"` - Expression string `json:"expression,omitempty"` -} - -type RulesetRuleActionParametersOverrides struct { - Enabled bool `json:"enabled,omitempty"` - Categories []RulesetRuleActionParametersCategories `json:"categories,omitempty"` - Rules []RulesetRuleActionParametersRules `json:"rules,omitempty"` -} - -type RulesetRuleActionParametersCategories struct { - Category string `json:"category"` - Action string `json:"action,omitempty"` - Enabled bool `json:"enabled"` -} - -type RulesetRuleActionParametersRules struct { - ID string `json:"id"` - Action string `json:"action,omitempty"` - Enabled *bool `json:"enabled,omitempty"` - ScoreThreshold int `json:"score_threshold,omitempty"` - SensitivityLevel string `json:"sensitivity_level,omitempty"` -} - -// RulesetRuleActionParametersMatchedData holds the structure for WAF based -// payload logging. -type RulesetRuleActionParametersMatchedData struct { - PublicKey string `json:"public_key,omitempty"` -} - -// RulesetRule contains information about a single Ruleset Rule. -type RulesetRule struct { - ID string `json:"id,omitempty"` - Version string `json:"version,omitempty"` - Action string `json:"action"` - ActionParameters *RulesetRuleActionParameters `json:"action_parameters,omitempty"` - Expression string `json:"expression"` - Description string `json:"description"` - LastUpdated *time.Time `json:"last_updated,omitempty"` - Ref string `json:"ref,omitempty"` - Enabled bool `json:"enabled"` - ScoreThreshold int `json:"score_threshold,omitempty"` - RateLimit *RulesetRuleRateLimit `json:"ratelimit,omitempty"` -} - -// RulesetRuleRateLimit contains the structure of a HTTP rate limit Ruleset Rule. -type RulesetRuleRateLimit struct { - Characteristics []string `json:"characteristics,omitempty"` - RequestsPerPeriod int `json:"requests_per_period,omitempty"` - Period int `json:"period,omitempty"` - MitigationTimeout int `json:"mitigation_timeout,omitempty"` - - // Should always be sent as "" will trigger the service to use the Ruleset - // expression instead. - MitigationExpression string `json:"mitigation_expression"` -} - -// UpdateRulesetRequest is the representation of a Ruleset update. -type UpdateRulesetRequest struct { - Description string `json:"description"` - Rules []RulesetRule `json:"rules"` -} - -// ListRulesetResponse contains all Rulesets. -type ListRulesetResponse struct { - Response - Result []Ruleset `json:"result"` -} - -// GetRulesetResponse contains a single Ruleset. -type GetRulesetResponse struct { - Response - Result Ruleset `json:"result"` -} - -// CreateRulesetResponse contains response data when creating a new Ruleset. -type CreateRulesetResponse struct { - Response - Result Ruleset `json:"result"` -} - -// UpdateRulesetResponse contains response data when updating an existing -// Ruleset. -type UpdateRulesetResponse struct { - Response - Result Ruleset `json:"result"` -} - -// ListZoneRulesets fetches all rulesets for a zone. -// -// API reference: https://api.cloudflare.com/#zone-rulesets-list-zone-rulesets -func (api *API) ListZoneRulesets(ctx context.Context, zoneID string) ([]Ruleset, error) { - return api.listRulesets(ctx, ZoneRouteRoot, zoneID) -} - -// ListAccountRulesets fetches all rulesets for an account. -// -// API reference: https://api.cloudflare.com/#account-rulesets-list-account-rulesets -func (api *API) ListAccountRulesets(ctx context.Context, accountID string) ([]Ruleset, error) { - return api.listRulesets(ctx, AccountRouteRoot, accountID) -} - -// listRulesets lists all Rulesets for a given zone or account depending on the -// identifier type provided. -func (api *API) listRulesets(ctx context.Context, identifierType RouteRoot, identifier string) ([]Ruleset, error) { - uri := fmt.Sprintf("/%s/%s/rulesets", identifierType, identifier) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []Ruleset{}, err - } - - result := ListRulesetResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return []Ruleset{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// GetZoneRuleset fetches a single ruleset for a zone. -// -// API reference: https://api.cloudflare.com/#zone-rulesets-get-a-zone-ruleset -func (api *API) GetZoneRuleset(ctx context.Context, zoneID, rulesetID string) (Ruleset, error) { - return api.getRuleset(ctx, ZoneRouteRoot, zoneID, rulesetID) -} - -// GetAccountRuleset fetches a single ruleset for an account. -// -// API reference: https://api.cloudflare.com/#account-rulesets-get-an-account-ruleset -func (api *API) GetAccountRuleset(ctx context.Context, accountID, rulesetID string) (Ruleset, error) { - return api.getRuleset(ctx, AccountRouteRoot, accountID, rulesetID) -} - -// getRuleset fetches a single ruleset based on the zone or account, the -// identifer and the ruleset ID. -func (api *API) getRuleset(ctx context.Context, identifierType RouteRoot, identifier, rulesetID string) (Ruleset, error) { - uri := fmt.Sprintf("/%s/%s/rulesets/%s", identifierType, identifier, rulesetID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return Ruleset{}, err - } - - result := GetRulesetResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return Ruleset{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// CreateZoneRuleset creates a new ruleset for a zone. -// -// API reference: https://api.cloudflare.com/#zone-rulesets-create-zone-ruleset -func (api *API) CreateZoneRuleset(ctx context.Context, zoneID string, ruleset Ruleset) (Ruleset, error) { - return api.createRuleset(ctx, ZoneRouteRoot, zoneID, ruleset) -} - -// CreateAccountRuleset creates a new ruleset for an account. -// -// API reference: https://api.cloudflare.com/#account-rulesets-create-account-ruleset -func (api *API) CreateAccountRuleset(ctx context.Context, accountID string, ruleset Ruleset) (Ruleset, error) { - return api.createRuleset(ctx, AccountRouteRoot, accountID, ruleset) -} - -func (api *API) createRuleset(ctx context.Context, identifierType RouteRoot, identifier string, ruleset Ruleset) (Ruleset, error) { - uri := fmt.Sprintf("/%s/%s/rulesets", identifierType, identifier) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, ruleset) - - if err != nil { - return Ruleset{}, err - } - - result := CreateRulesetResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return Ruleset{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// DeleteZoneRuleset deletes a single ruleset for a zone. -// -// API reference: https://api.cloudflare.com/#zone-rulesets-delete-zone-ruleset -func (api *API) DeleteZoneRuleset(ctx context.Context, zoneID, rulesetID string) error { - return api.deleteRuleset(ctx, ZoneRouteRoot, zoneID, rulesetID) -} - -// DeleteAccountRuleset deletes a single ruleset for an account. -// -// API reference: https://api.cloudflare.com/#account-rulesets-delete-account-ruleset -func (api *API) DeleteAccountRuleset(ctx context.Context, accountID, rulesetID string) error { - return api.deleteRuleset(ctx, AccountRouteRoot, accountID, rulesetID) -} - -// deleteRuleset removes a ruleset based on the ruleset ID. -func (api *API) deleteRuleset(ctx context.Context, identifierType RouteRoot, identifier, rulesetID string) error { - uri := fmt.Sprintf("/%s/%s/rulesets/%s", identifierType, identifier, rulesetID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - - if err != nil { - return err - } - - // The API is not implementing the standard response blob but returns an - // empty response (204) in case of a success. So we are checking for the - // response body size here. - if len(res) > 0 { - return errors.Wrap(errors.New(string(res)), errMakeRequestError) - } - - return nil -} - -// UpdateZoneRuleset updates a single ruleset for a zone. -// -// API reference: https://api.cloudflare.com/#zone-rulesets-update-a-zone-ruleset -func (api *API) UpdateZoneRuleset(ctx context.Context, zoneID, rulesetID, description string, rules []RulesetRule) (Ruleset, error) { - return api.updateRuleset(ctx, ZoneRouteRoot, zoneID, rulesetID, description, rules) -} - -// UpdateAccountRuleset updates a single ruleset for an account. -// -// API reference: https://api.cloudflare.com/#account-rulesets-update-account-ruleset -func (api *API) UpdateAccountRuleset(ctx context.Context, accountID, rulesetID, description string, rules []RulesetRule) (Ruleset, error) { - return api.updateRuleset(ctx, AccountRouteRoot, accountID, rulesetID, description, rules) -} - -// updateRuleset updates a ruleset based on the ruleset ID. -func (api *API) updateRuleset(ctx context.Context, identifierType RouteRoot, identifier, rulesetID, description string, rules []RulesetRule) (Ruleset, error) { - uri := fmt.Sprintf("/%s/%s/rulesets/%s", identifierType, identifier, rulesetID) - payload := UpdateRulesetRequest{Description: description, Rules: rules} - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, payload) - if err != nil { - return Ruleset{}, err - } - - result := UpdateRulesetResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return Ruleset{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// GetZoneRulesetPhase returns a ruleset phase for a zone. -// -// API reference: TBA -func (api *API) GetZoneRulesetPhase(ctx context.Context, zoneID, rulesetPhase string) (Ruleset, error) { - return api.getRulesetPhase(ctx, ZoneRouteRoot, zoneID, rulesetPhase) -} - -// GetAccountRulesetPhase returns a ruleset phase for an account. -// -// API reference: TBA -func (api *API) GetAccountRulesetPhase(ctx context.Context, accountID, rulesetPhase string) (Ruleset, error) { - return api.getRulesetPhase(ctx, AccountRouteRoot, accountID, rulesetPhase) -} - -// getRulesetPhase returns a ruleset phase based on the zone or account and the -// identifer. -func (api *API) getRulesetPhase(ctx context.Context, identifierType RouteRoot, identifier, rulesetPhase string) (Ruleset, error) { - uri := fmt.Sprintf("/%s/%s/rulesets/phases/%s/entrypoint", identifierType, identifier, rulesetPhase) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return Ruleset{}, err - } - - result := GetRulesetResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return Ruleset{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// UpdateZoneRulesetPhase updates a ruleset phase for a zone. -// -// API reference: TBA -func (api *API) UpdateZoneRulesetPhase(ctx context.Context, zoneID, rulesetPhase string, ruleset Ruleset) (Ruleset, error) { - return api.updateRulesetPhase(ctx, ZoneRouteRoot, zoneID, rulesetPhase, ruleset) -} - -// UpdateAccountRulesetPhase updates a ruleset phase for an account. -// -// API reference: TBA -func (api *API) UpdateAccountRulesetPhase(ctx context.Context, accountID, rulesetPhase string, ruleset Ruleset) (Ruleset, error) { - return api.updateRulesetPhase(ctx, AccountRouteRoot, accountID, rulesetPhase, ruleset) -} - -// updateRulesetPhase updates a ruleset phase based on the zone or account, the -// identifer and the rules. -func (api *API) updateRulesetPhase(ctx context.Context, identifierType RouteRoot, identifier, rulesetPhase string, ruleset Ruleset) (Ruleset, error) { - uri := fmt.Sprintf("/%s/%s/rulesets/phases/%s/entrypoint", identifierType, identifier, rulesetPhase) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, ruleset) - if err != nil { - return Ruleset{}, err - } - - result := GetRulesetResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return Ruleset{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/secondary_dns_primaries.go b/vendor/github.com/cloudflare/cloudflare-go/secondary_dns_primaries.go deleted file mode 100644 index dc0b57a4..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/secondary_dns_primaries.go +++ /dev/null @@ -1,165 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -const ( - errSecondaryDNSInvalidPrimaryID = "secondary DNS primary ID is required" - errSecondaryDNSInvalidPrimaryIP = "secondary DNS primary IP invalid" - errSecondaryDNSInvalidPrimaryPort = "secondary DNS primary port invalid" -) - -// SecondaryDNSPrimary is the representation of the DNS Primary. -type SecondaryDNSPrimary struct { - ID string `json:"id,omitempty"` - IP string `json:"ip"` - Port int `json:"port"` - IxfrEnable bool `json:"ixfr_enable"` - TsigID string `json:"tsig_id"` - Name string `json:"name"` -} - -// SecondaryDNSPrimaryDetailResponse is the API representation of a single -// secondary DNS primary response. -type SecondaryDNSPrimaryDetailResponse struct { - Response - Result SecondaryDNSPrimary `json:"result"` -} - -// SecondaryDNSPrimaryListResponse is the API representation of all secondary DNS -// primaries. -type SecondaryDNSPrimaryListResponse struct { - Response - Result []SecondaryDNSPrimary `json:"result"` -} - -// GetSecondaryDNSPrimary returns a single secondary DNS primary. -// -// API reference: https://api.cloudflare.com/#secondary-dns-primary--primary-details -func (api *API) GetSecondaryDNSPrimary(ctx context.Context, accountID, primaryID string) (SecondaryDNSPrimary, error) { - uri := fmt.Sprintf("/accounts/%s/secondary_dns/primaries/%s", accountID, primaryID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return SecondaryDNSPrimary{}, err - } - - var r SecondaryDNSPrimaryDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return SecondaryDNSPrimary{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListSecondaryDNSPrimaries returns all secondary DNS primaries for an account. -// -// API reference: https://api.cloudflare.com/#secondary-dns-primary--list-primaries -func (api *API) ListSecondaryDNSPrimaries(ctx context.Context, accountID string) ([]SecondaryDNSPrimary, error) { - uri := fmt.Sprintf("/accounts/%s/secondary_dns/primaries", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []SecondaryDNSPrimary{}, err - } - - var r SecondaryDNSPrimaryListResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []SecondaryDNSPrimary{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// CreateSecondaryDNSPrimary creates a secondary DNS primary. -// -// API reference: https://api.cloudflare.com/#secondary-dns-primary--create-primary -func (api *API) CreateSecondaryDNSPrimary(ctx context.Context, accountID string, primary SecondaryDNSPrimary) (SecondaryDNSPrimary, error) { - if err := validateRequiredSecondaryDNSPrimaries(primary); err != nil { - return SecondaryDNSPrimary{}, err - } - - uri := fmt.Sprintf("/accounts/%s/secondary_dns/primaries", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, SecondaryDNSPrimary{ - IP: primary.IP, - Port: primary.Port, - IxfrEnable: primary.IxfrEnable, - TsigID: primary.TsigID, - Name: primary.Name, - }) - if err != nil { - return SecondaryDNSPrimary{}, err - } - - var r SecondaryDNSPrimaryDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return SecondaryDNSPrimary{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateSecondaryDNSPrimary creates a secondary DNS primary. -// -// API reference: https://api.cloudflare.com/#secondary-dns-primary--update-primary -func (api *API) UpdateSecondaryDNSPrimary(ctx context.Context, accountID string, primary SecondaryDNSPrimary) (SecondaryDNSPrimary, error) { - if primary.ID == "" { - return SecondaryDNSPrimary{}, errors.New(errSecondaryDNSInvalidPrimaryID) - } - - if err := validateRequiredSecondaryDNSPrimaries(primary); err != nil { - return SecondaryDNSPrimary{}, err - } - - uri := fmt.Sprintf("/accounts/%s/secondary_dns/primaries/%s", accountID, primary.ID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, SecondaryDNSPrimary{ - IP: primary.IP, - Port: primary.Port, - IxfrEnable: primary.IxfrEnable, - TsigID: primary.TsigID, - Name: primary.Name, - }) - if err != nil { - return SecondaryDNSPrimary{}, err - } - - var r SecondaryDNSPrimaryDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return SecondaryDNSPrimary{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteSecondaryDNSPrimary deletes a secondary DNS primary. -// -// API reference: https://api.cloudflare.com/#secondary-dns-primary--delete-primary -func (api *API) DeleteSecondaryDNSPrimary(ctx context.Context, accountID, primaryID string) error { - uri := fmt.Sprintf("/zones/%s/secondary_dns/primaries/%s", accountID, primaryID) - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - - if err != nil { - return err - } - - return nil -} - -func validateRequiredSecondaryDNSPrimaries(p SecondaryDNSPrimary) error { - if p.IP == "" { - return errors.New(errSecondaryDNSInvalidPrimaryIP) - } - - if p.Port == 0 { - return errors.New(errSecondaryDNSInvalidPrimaryPort) - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/secondary_dns_tsig.go b/vendor/github.com/cloudflare/cloudflare-go/secondary_dns_tsig.go deleted file mode 100644 index 255c409b..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/secondary_dns_tsig.go +++ /dev/null @@ -1,132 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -const ( - errSecondaryDNSTSIGMissingID = "secondary DNS TSIG ID is required" -) - -// SecondaryDNSTSIG contains the structure for a secondary DNS TSIG. -type SecondaryDNSTSIG struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Secret string `json:"secret"` - Algo string `json:"algo"` -} - -// SecondaryDNSTSIGDetailResponse is the API response for a single secondary -// DNS TSIG. -type SecondaryDNSTSIGDetailResponse struct { - Response - Result SecondaryDNSTSIG `json:"result"` -} - -// SecondaryDNSTSIGListResponse is the API response for all secondary DNS TSIGs. -type SecondaryDNSTSIGListResponse struct { - Response - Result []SecondaryDNSTSIG `json:"result"` -} - -// GetSecondaryDNSTSIG gets a single account level TSIG for a secondary DNS -// configuration. -// -// API reference: https://api.cloudflare.com/#secondary-dns-tsig--tsig-details -func (api *API) GetSecondaryDNSTSIG(ctx context.Context, accountID, tsigID string) (SecondaryDNSTSIG, error) { - uri := fmt.Sprintf("/accounts/%s/secondary_dns/tsigs/%s", accountID, tsigID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return SecondaryDNSTSIG{}, err - } - - var r SecondaryDNSTSIGDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return SecondaryDNSTSIG{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListSecondaryDNSTSIGs gets all account level TSIG for a secondary DNS -// configuration. -// -// API reference: https://api.cloudflare.com/#secondary-dns-tsig--list-tsigs -func (api *API) ListSecondaryDNSTSIGs(ctx context.Context, accountID string) ([]SecondaryDNSTSIG, error) { - uri := fmt.Sprintf("/accounts/%s/secondary_dns/tsigs", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []SecondaryDNSTSIG{}, err - } - - var r SecondaryDNSTSIGListResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []SecondaryDNSTSIG{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// CreateSecondaryDNSTSIG creates a secondary DNS TSIG at the account level. -// -// API reference: https://api.cloudflare.com/#secondary-dns-tsig--create-tsig -func (api *API) CreateSecondaryDNSTSIG(ctx context.Context, accountID string, tsig SecondaryDNSTSIG) (SecondaryDNSTSIG, error) { - uri := fmt.Sprintf("/accounts/%s/secondary_dns/tsigs", accountID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, tsig) - - if err != nil { - return SecondaryDNSTSIG{}, err - } - - result := SecondaryDNSTSIGDetailResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return SecondaryDNSTSIG{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// UpdateSecondaryDNSTSIG updates an existing secondary DNS TSIG at -// the account level. -// -// API reference: https://api.cloudflare.com/#secondary-dns-tsig--update-tsig -func (api *API) UpdateSecondaryDNSTSIG(ctx context.Context, accountID string, tsig SecondaryDNSTSIG) (SecondaryDNSTSIG, error) { - if tsig.ID == "" { - return SecondaryDNSTSIG{}, errors.New(errSecondaryDNSTSIGMissingID) - } - - uri := fmt.Sprintf("/accounts/%s/secondary_dns/tsigs/%s", accountID, tsig.ID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, tsig) - - if err != nil { - return SecondaryDNSTSIG{}, err - } - - result := SecondaryDNSTSIGDetailResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return SecondaryDNSTSIG{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// DeleteSecondaryDNSTSIG deletes a secondary DNS TSIG. -// -// API reference: https://api.cloudflare.com/#secondary-dns-tsig--delete-tsig -func (api *API) DeleteSecondaryDNSTSIG(ctx context.Context, accountID, tsigID string) error { - uri := fmt.Sprintf("/accounts/%s/secondary_dns/tsigs/%s", accountID, tsigID) - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/secondary_dns_zone.go b/vendor/github.com/cloudflare/cloudflare-go/secondary_dns_zone.go deleted file mode 100644 index 034defc9..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/secondary_dns_zone.go +++ /dev/null @@ -1,172 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -const ( - errSecondaryDNSInvalidAutoRefreshValue = "secondary DNS auto refresh value is invalid" - errSecondaryDNSInvalidZoneName = "secondary DNS zone name is invalid" - errSecondaryDNSInvalidPrimaries = "secondary DNS primaries value is invalid" -) - -// SecondaryDNSZone contains the high level structure of a secondary DNS zone. -type SecondaryDNSZone struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Primaries []string `json:"primaries,omitempty"` - AutoRefreshSeconds int `json:"auto_refresh_seconds,omitempty"` - SoaSerial int `json:"soa_serial,omitempty"` - CreatedTime time.Time `json:"created_time,omitempty"` - CheckedTime time.Time `json:"checked_time,omitempty"` - ModifiedTime time.Time `json:"modified_time,omitempty"` -} - -// SecondaryDNSZoneDetailResponse is the API response for a single secondary -// DNS zone. -type SecondaryDNSZoneDetailResponse struct { - Response - Result SecondaryDNSZone `json:"result"` -} - -// SecondaryDNSZoneAXFRResponse is the API response for a single secondary -// DNS AXFR response. -type SecondaryDNSZoneAXFRResponse struct { - Response - Result string `json:"result"` -} - -// GetSecondaryDNSZone returns the secondary DNS zone configuration for a -// single zone. -// -// API reference: https://api.cloudflare.com/#secondary-dns-secondary-zone-configuration-details -func (api *API) GetSecondaryDNSZone(ctx context.Context, zoneID string) (SecondaryDNSZone, error) { - uri := fmt.Sprintf("/zones/%s/secondary_dns", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return SecondaryDNSZone{}, err - } - - var r SecondaryDNSZoneDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return SecondaryDNSZone{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// CreateSecondaryDNSZone creates a secondary DNS zone. -// -// API reference: https://api.cloudflare.com/#secondary-dns-create-secondary-zone-configuration -func (api *API) CreateSecondaryDNSZone(ctx context.Context, zoneID string, zone SecondaryDNSZone) (SecondaryDNSZone, error) { - if err := validateRequiredSecondaryDNSZoneValues(zone); err != nil { - return SecondaryDNSZone{}, err - } - - uri := fmt.Sprintf("/zones/%s/secondary_dns", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, - SecondaryDNSZone{ - Name: zone.Name, - AutoRefreshSeconds: zone.AutoRefreshSeconds, - Primaries: zone.Primaries, - }, - ) - - if err != nil { - return SecondaryDNSZone{}, err - } - - result := SecondaryDNSZoneDetailResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return SecondaryDNSZone{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// UpdateSecondaryDNSZone updates an existing secondary DNS zone. -// -// API reference: https://api.cloudflare.com/#secondary-dns-update-secondary-zone-configuration -func (api *API) UpdateSecondaryDNSZone(ctx context.Context, zoneID string, zone SecondaryDNSZone) (SecondaryDNSZone, error) { - if err := validateRequiredSecondaryDNSZoneValues(zone); err != nil { - return SecondaryDNSZone{}, err - } - - uri := fmt.Sprintf("/zones/%s/secondary_dns", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, - SecondaryDNSZone{ - Name: zone.Name, - AutoRefreshSeconds: zone.AutoRefreshSeconds, - Primaries: zone.Primaries, - }, - ) - - if err != nil { - return SecondaryDNSZone{}, err - } - - result := SecondaryDNSZoneDetailResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return SecondaryDNSZone{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result, nil -} - -// DeleteSecondaryDNSZone deletes a secondary DNS zone. -// -// API reference: https://api.cloudflare.com/#secondary-dns-delete-secondary-zone-configuration -func (api *API) DeleteSecondaryDNSZone(ctx context.Context, zoneID string) error { - uri := fmt.Sprintf("/zones/%s/secondary_dns", zoneID) - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - - if err != nil { - return err - } - - return nil -} - -// ForceSecondaryDNSZoneAXFR requests an immediate AXFR request. -// -// API reference: https://api.cloudflare.com/#secondary-dns-update-secondary-zone-configuration -func (api *API) ForceSecondaryDNSZoneAXFR(ctx context.Context, zoneID string) error { - uri := fmt.Sprintf("/zones/%s/secondary_dns/force_axfr", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, nil) - - if err != nil { - return err - } - - result := SecondaryDNSZoneAXFRResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} - -// validateRequiredSecondaryDNSZoneValues ensures that the payload matches the -// API requirements for required fields. -func validateRequiredSecondaryDNSZoneValues(zone SecondaryDNSZone) error { - if zone.Name == "" { - return errors.New(errSecondaryDNSInvalidZoneName) - } - - if zone.AutoRefreshSeconds == 0 || zone.AutoRefreshSeconds < 0 { - return errors.New(errSecondaryDNSInvalidAutoRefreshValue) - } - - if len(zone.Primaries) == 0 { - return errors.New(errSecondaryDNSInvalidPrimaries) - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/spectrum.go b/vendor/github.com/cloudflare/cloudflare-go/spectrum.go deleted file mode 100644 index 7e5247a9..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/spectrum.go +++ /dev/null @@ -1,368 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net" - "net/http" - "strconv" - "strings" - "time" - - "github.com/pkg/errors" -) - -// ProxyProtocol implements json.Unmarshaler in order to support deserializing of the deprecated boolean -// value for `proxy_protocol` -type ProxyProtocol string - -// UnmarshalJSON handles deserializing of both the deprecated boolean value and the current string value -// for the `proxy_protocol` field. -func (p *ProxyProtocol) UnmarshalJSON(data []byte) error { - var raw interface{} - if err := json.Unmarshal(data, &raw); err != nil { - return err - } - - switch pp := raw.(type) { - case string: - *p = ProxyProtocol(pp) - case bool: - if pp { - *p = "v1" - } else { - *p = "off" - } - default: - return fmt.Errorf("invalid type for proxy_protocol field: %T", pp) - } - return nil -} - -// SpectrumApplicationOriginPort defines a union of a single port or range of ports -type SpectrumApplicationOriginPort struct { - Port, Start, End uint16 -} - -// ErrOriginPortInvalid is a common error for failing to parse a single port or port range -var ErrOriginPortInvalid = errors.New("invalid origin port") - -func (p *SpectrumApplicationOriginPort) parse(s string) error { - switch split := strings.Split(s, "-"); len(split) { - case 1: - i, err := strconv.ParseUint(split[0], 10, 16) - if err != nil { - return err - } - p.Port = uint16(i) - case 2: - start, err := strconv.ParseUint(split[0], 10, 16) - if err != nil { - return err - } - end, err := strconv.ParseUint(split[1], 10, 16) - if err != nil { - return err - } - if start >= end { - return ErrOriginPortInvalid - } - p.Start = uint16(start) - p.End = uint16(end) - default: - return ErrOriginPortInvalid - } - return nil -} - -// UnmarshalJSON converts a byte slice into a single port or port range -func (p *SpectrumApplicationOriginPort) UnmarshalJSON(b []byte) error { - var port interface{} - if err := json.Unmarshal(b, &port); err != nil { - return err - } - - switch i := port.(type) { - case float64: - p.Port = uint16(i) - case string: - if err := p.parse(i); err != nil { - return err - } - } - - return nil -} - -// MarshalJSON converts a single port or port range to a suitable byte slice -func (p *SpectrumApplicationOriginPort) MarshalJSON() ([]byte, error) { - if p.End > 0 { - return json.Marshal(fmt.Sprintf("%d-%d", p.Start, p.End)) - } - return json.Marshal(p.Port) -} - -// SpectrumApplication defines a single Spectrum Application. -type SpectrumApplication struct { - ID string `json:"id,omitempty"` - Protocol string `json:"protocol,omitempty"` - IPv4 bool `json:"ipv4,omitempty"` - DNS SpectrumApplicationDNS `json:"dns,omitempty"` - OriginDirect []string `json:"origin_direct,omitempty"` - OriginPort *SpectrumApplicationOriginPort `json:"origin_port,omitempty"` - OriginDNS *SpectrumApplicationOriginDNS `json:"origin_dns,omitempty"` - IPFirewall bool `json:"ip_firewall,omitempty"` - ProxyProtocol ProxyProtocol `json:"proxy_protocol,omitempty"` - TLS string `json:"tls,omitempty"` - TrafficType string `json:"traffic_type,omitempty"` - EdgeIPs *SpectrumApplicationEdgeIPs `json:"edge_ips,omitempty"` - ArgoSmartRouting bool `json:"argo_smart_routing,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` -} - -// UnmarshalJSON handles setting the `ProxyProtocol` field based on the value of the deprecated `spp` field. -func (a *SpectrumApplication) UnmarshalJSON(data []byte) error { - var body map[string]interface{} - if err := json.Unmarshal(data, &body); err != nil { - return err - } - - var app spectrumApplicationRaw - if err := json.Unmarshal(data, &app); err != nil { - return err - } - - if spp, ok := body["spp"]; ok && spp.(bool) { - app.ProxyProtocol = "simple" - } - - *a = SpectrumApplication(app) - return nil -} - -// spectrumApplicationRaw is used to inspect an application body to support the deprecated boolean value for `spp` -type spectrumApplicationRaw SpectrumApplication - -// SpectrumApplicationDNS holds the external DNS configuration for a Spectrum -// Application. -type SpectrumApplicationDNS struct { - Type string `json:"type"` - Name string `json:"name"` -} - -// SpectrumApplicationOriginDNS holds the origin DNS configuration for a Spectrum -// Application. -type SpectrumApplicationOriginDNS struct { - Name string `json:"name"` -} - -// SpectrumApplicationDetailResponse is the structure of the detailed response -// from the API. -type SpectrumApplicationDetailResponse struct { - Response - Result SpectrumApplication `json:"result"` -} - -// SpectrumApplicationsDetailResponse is the structure of the detailed response -// from the API. -type SpectrumApplicationsDetailResponse struct { - Response - Result []SpectrumApplication `json:"result"` -} - -// SpectrumApplicationEdgeIPs represents configuration for Bring-Your-Own-IP -// https://developers.cloudflare.com/spectrum/getting-started/byoip/ -type SpectrumApplicationEdgeIPs struct { - Type SpectrumApplicationEdgeType `json:"type"` - Connectivity *SpectrumApplicationConnectivity `json:"connectivity,omitempty"` - IPs []net.IP `json:"ips,omitempty"` -} - -// SpectrumApplicationEdgeType for possible Edge configurations -type SpectrumApplicationEdgeType string - -const ( - // SpectrumEdgeTypeDynamic IP config - SpectrumEdgeTypeDynamic SpectrumApplicationEdgeType = "dynamic" - // SpectrumEdgeTypeStatic IP config - SpectrumEdgeTypeStatic SpectrumApplicationEdgeType = "static" -) - -// UnmarshalJSON function for SpectrumApplicationEdgeType enum -func (t *SpectrumApplicationEdgeType) UnmarshalJSON(b []byte) error { - var s string - err := json.Unmarshal(b, &s) - if err != nil { - return err - } - - newEdgeType := SpectrumApplicationEdgeType(strings.ToLower(s)) - switch newEdgeType { - case SpectrumEdgeTypeDynamic, SpectrumEdgeTypeStatic: - *t = newEdgeType - return nil - } - - return errors.New(errUnmarshalError) -} - -func (t SpectrumApplicationEdgeType) String() string { - return string(t) -} - -// SpectrumApplicationConnectivity specifies IP address type on the edge configuration -type SpectrumApplicationConnectivity string - -const ( - // SpectrumConnectivityAll specifies IPv4/6 edge IP - SpectrumConnectivityAll SpectrumApplicationConnectivity = "all" - // SpectrumConnectivityIPv4 specifies IPv4 edge IP - SpectrumConnectivityIPv4 SpectrumApplicationConnectivity = "ipv4" - // SpectrumConnectivityIPv6 specifies IPv6 edge IP - SpectrumConnectivityIPv6 SpectrumApplicationConnectivity = "ipv6" - // SpectrumConnectivityStatic specifies static edge IP configuration - SpectrumConnectivityStatic SpectrumApplicationConnectivity = "static" -) - -func (c SpectrumApplicationConnectivity) String() string { - return string(c) -} - -// UnmarshalJSON function for SpectrumApplicationConnectivity enum -func (c *SpectrumApplicationConnectivity) UnmarshalJSON(b []byte) error { - var s string - err := json.Unmarshal(b, &s) - if err != nil { - return err - } - - newConnectivity := SpectrumApplicationConnectivity(strings.ToLower(s)) - if newConnectivity.Dynamic() { - *c = newConnectivity - return nil - } - - return errors.New(errUnmarshalError) -} - -// Dynamic checks if address family is specified as dynamic config -func (c SpectrumApplicationConnectivity) Dynamic() bool { - switch c { - case SpectrumConnectivityAll, SpectrumConnectivityIPv4, SpectrumConnectivityIPv6: - return true - } - return false -} - -// Static checks if address family is specified as static config -func (c SpectrumApplicationConnectivity) Static() bool { - return c == SpectrumConnectivityStatic -} - -// SpectrumApplications fetches all of the Spectrum applications for a zone. -// -// API reference: https://developers.cloudflare.com/spectrum/api-reference/#list-spectrum-applications -func (api *API) SpectrumApplications(ctx context.Context, zoneID string) ([]SpectrumApplication, error) { - uri := fmt.Sprintf("/zones/%s/spectrum/apps", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []SpectrumApplication{}, err - } - - var spectrumApplications SpectrumApplicationsDetailResponse - err = json.Unmarshal(res, &spectrumApplications) - if err != nil { - return []SpectrumApplication{}, errors.Wrap(err, errUnmarshalError) - } - - return spectrumApplications.Result, nil -} - -// SpectrumApplication fetches a single Spectrum application based on the ID. -// -// API reference: https://developers.cloudflare.com/spectrum/api-reference/#list-spectrum-applications -func (api *API) SpectrumApplication(ctx context.Context, zoneID string, applicationID string) (SpectrumApplication, error) { - uri := fmt.Sprintf( - "/zones/%s/spectrum/apps/%s", - zoneID, - applicationID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return SpectrumApplication{}, err - } - - var spectrumApplication SpectrumApplicationDetailResponse - err = json.Unmarshal(res, &spectrumApplication) - if err != nil { - return SpectrumApplication{}, errors.Wrap(err, errUnmarshalError) - } - - return spectrumApplication.Result, nil -} - -// CreateSpectrumApplication creates a new Spectrum application. -// -// API reference: https://developers.cloudflare.com/spectrum/api-reference/#create-a-spectrum-application -func (api *API) CreateSpectrumApplication(ctx context.Context, zoneID string, appDetails SpectrumApplication) (SpectrumApplication, error) { - uri := fmt.Sprintf("/zones/%s/spectrum/apps", zoneID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, appDetails) - if err != nil { - return SpectrumApplication{}, err - } - - var spectrumApplication SpectrumApplicationDetailResponse - err = json.Unmarshal(res, &spectrumApplication) - if err != nil { - return SpectrumApplication{}, errors.Wrap(err, errUnmarshalError) - } - - return spectrumApplication.Result, nil -} - -// UpdateSpectrumApplication updates an existing Spectrum application. -// -// API reference: https://developers.cloudflare.com/spectrum/api-reference/#update-a-spectrum-application -func (api *API) UpdateSpectrumApplication(ctx context.Context, zoneID, appID string, appDetails SpectrumApplication) (SpectrumApplication, error) { - uri := fmt.Sprintf( - "/zones/%s/spectrum/apps/%s", - zoneID, - appID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, appDetails) - if err != nil { - return SpectrumApplication{}, err - } - - var spectrumApplication SpectrumApplicationDetailResponse - err = json.Unmarshal(res, &spectrumApplication) - if err != nil { - return SpectrumApplication{}, errors.Wrap(err, errUnmarshalError) - } - - return spectrumApplication.Result, nil -} - -// DeleteSpectrumApplication removes a Spectrum application based on the ID. -// -// API reference: https://developers.cloudflare.com/spectrum/api-reference/#delete-a-spectrum-application -func (api *API) DeleteSpectrumApplication(ctx context.Context, zoneID string, applicationID string) error { - uri := fmt.Sprintf( - "/zones/%s/spectrum/apps/%s", - zoneID, - applicationID, - ) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/split_tunnel.go b/vendor/github.com/cloudflare/cloudflare-go/split_tunnel.go deleted file mode 100644 index 04a34bed..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/split_tunnel.go +++ /dev/null @@ -1,66 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -// SplitTunnelResponse represents the response from the get split -// tunnel endpoints. -type SplitTunnelResponse struct { - Response - Result []SplitTunnel `json:"result"` -} - -// SplitTunnel represents the individual tunnel struct. -type SplitTunnel struct { - Address string `json:"address,omitempty"` - Host string `json:"host,omitempty"` - Description string `json:"description,omitempty"` -} - -// ListSplitTunnel returns all include or exclude split tunnel within an account. -// -// API reference for include: https://api.cloudflare.com/#device-policy-get-split-tunnel-include-list -// API reference for exclude: https://api.cloudflare.com/#device-policy-get-split-tunnel-exclude-list -func (api *API) ListSplitTunnels(ctx context.Context, accountID string, mode string) ([]SplitTunnel, error) { - uri := fmt.Sprintf("/%s/%s/devices/policy/%s", AccountRouteRoot, accountID, mode) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []SplitTunnel{}, err - } - - var splitTunnelResponse SplitTunnelResponse - err = json.Unmarshal(res, &splitTunnelResponse) - if err != nil { - return []SplitTunnel{}, errors.Wrap(err, errUnmarshalError) - } - - return splitTunnelResponse.Result, nil -} - -// UpdateSplitTunnel updates the existing split tunnel policy. -// -// API reference for include: https://api.cloudflare.com/#device-policy-set-split-tunnel-include-list -// API reference for exclude: https://api.cloudflare.com/#device-policy-set-split-tunnel-exclude-list -func (api *API) UpdateSplitTunnel(ctx context.Context, accountID string, mode string, tunnels []SplitTunnel) ([]SplitTunnel, error) { - uri := fmt.Sprintf("/%s/%s/devices/policy/%s", AccountRouteRoot, accountID, mode) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, tunnels) - if err != nil { - return []SplitTunnel{}, err - } - - var splitTunnelResponse SplitTunnelResponse - err = json.Unmarshal(res, &splitTunnelResponse) - if err != nil { - return []SplitTunnel{}, errors.Wrap(err, errUnmarshalError) - } - - return splitTunnelResponse.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/ssl.go b/vendor/github.com/cloudflare/cloudflare-go/ssl.go deleted file mode 100644 index 23ae2638..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/ssl.go +++ /dev/null @@ -1,160 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// ZoneCustomSSL represents custom SSL certificate metadata. -type ZoneCustomSSL struct { - ID string `json:"id"` - Hosts []string `json:"hosts"` - Issuer string `json:"issuer"` - Signature string `json:"signature"` - Status string `json:"status"` - BundleMethod string `json:"bundle_method"` - GeoRestrictions ZoneCustomSSLGeoRestrictions `json:"geo_restrictions"` - ZoneID string `json:"zone_id"` - UploadedOn time.Time `json:"uploaded_on"` - ModifiedOn time.Time `json:"modified_on"` - ExpiresOn time.Time `json:"expires_on"` - Priority int `json:"priority"` - KeylessServer KeylessSSL `json:"keyless_server"` -} - -// ZoneCustomSSLGeoRestrictions represents the parameter to create or update -// geographic restrictions on a custom ssl certificate. -type ZoneCustomSSLGeoRestrictions struct { - Label string `json:"label"` -} - -// zoneCustomSSLResponse represents the response from the zone SSL details endpoint. -type zoneCustomSSLResponse struct { - Response - Result ZoneCustomSSL `json:"result"` -} - -// zoneCustomSSLsResponse represents the response from the zone SSL list endpoint. -type zoneCustomSSLsResponse struct { - Response - Result []ZoneCustomSSL `json:"result"` -} - -// ZoneCustomSSLOptions represents the parameters to create or update an existing -// custom SSL configuration. -type ZoneCustomSSLOptions struct { - Certificate string `json:"certificate"` - PrivateKey string `json:"private_key"` - BundleMethod string `json:"bundle_method,omitempty"` - GeoRestrictions *ZoneCustomSSLGeoRestrictions `json:"geo_restrictions,omitempty"` - Type string `json:"type,omitempty"` -} - -// ZoneCustomSSLPriority represents a certificate's ID and priority. It is a -// subset of ZoneCustomSSL used for patch requests. -type ZoneCustomSSLPriority struct { - ID string `json:"ID"` - Priority int `json:"priority"` -} - -// CreateSSL allows you to add a custom SSL certificate to the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-create-ssl-configuration -func (api *API) CreateSSL(ctx context.Context, zoneID string, options ZoneCustomSSLOptions) (ZoneCustomSSL, error) { - uri := fmt.Sprintf("/zones/%s/custom_certificates", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, options) - if err != nil { - return ZoneCustomSSL{}, err - } - var r zoneCustomSSLResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListSSL lists the custom certificates for the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-list-ssl-configurations -func (api *API) ListSSL(ctx context.Context, zoneID string) ([]ZoneCustomSSL, error) { - uri := fmt.Sprintf("/zones/%s/custom_certificates", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - var r zoneCustomSSLsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// SSLDetails returns the configuration details for a custom SSL certificate. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-ssl-configuration-details -func (api *API) SSLDetails(ctx context.Context, zoneID, certificateID string) (ZoneCustomSSL, error) { - uri := fmt.Sprintf("/zones/%s/custom_certificates/%s", zoneID, certificateID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return ZoneCustomSSL{}, err - } - var r zoneCustomSSLResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateSSL updates (replaces) a custom SSL certificate. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-update-ssl-configuration -func (api *API) UpdateSSL(ctx context.Context, zoneID, certificateID string, options ZoneCustomSSLOptions) (ZoneCustomSSL, error) { - uri := fmt.Sprintf("/zones/%s/custom_certificates/%s", zoneID, certificateID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, options) - if err != nil { - return ZoneCustomSSL{}, err - } - var r zoneCustomSSLResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ReprioritizeSSL allows you to change the priority (which is served for a given -// request) of custom SSL certificates associated with the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-re-prioritize-ssl-certificates -func (api *API) ReprioritizeSSL(ctx context.Context, zoneID string, p []ZoneCustomSSLPriority) ([]ZoneCustomSSL, error) { - uri := fmt.Sprintf("/zones/%s/custom_certificates/prioritize", zoneID) - params := struct { - Certificates []ZoneCustomSSLPriority `json:"certificates"` - }{ - Certificates: p, - } - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, params) - if err != nil { - return nil, err - } - var r zoneCustomSSLsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteSSL deletes a custom SSL certificate from the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-delete-an-ssl-certificate -func (api *API) DeleteSSL(ctx context.Context, zoneID, certificateID string) error { - uri := fmt.Sprintf("/zones/%s/custom_certificates/%s", zoneID, certificateID) - if _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/teams_accounts.go b/vendor/github.com/cloudflare/cloudflare-go/teams_accounts.go deleted file mode 100644 index cb34fb1e..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/teams_accounts.go +++ /dev/null @@ -1,128 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -type TeamsAccount struct { - GatewayTag string `json:"gateway_tag"` // Internal teams ID - ProviderName string `json:"provider_name"` // Auth provider - ID string `json:"id"` // cloudflare account ID -} - -// TeamsAccountResponse is the API response, containing information on teams -// account. -type TeamsAccountResponse struct { - Response - Result TeamsAccount `json:"result"` -} - -// TeamsConfigResponse is the API response, containing information on teams -// account config. -type TeamsConfigResponse struct { - Response - Result TeamsConfiguration `json:"result"` -} - -// TeamsConfiguration data model. -type TeamsConfiguration struct { - Settings TeamsAccountSettings `json:"settings"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` -} - -type TeamsAccountSettings struct { - Antivirus *TeamsAntivirus `json:"antivirus,omitempty"` - TLSDecrypt *TeamsTLSDecrypt `json:"tls_decrypt,omitempty"` - ActivityLog *TeamsActivityLog `json:"activity_log,omitempty"` - BlockPage *TeamsBlockPage `json:"block_page,omitempty"` -} - -type TeamsAntivirus struct { - EnabledDownloadPhase bool `json:"enabled_download_phase"` - EnabledUploadPhase bool `json:"enabled_upload_phase"` - FailClosed bool `json:"fail_closed"` -} - -type TeamsTLSDecrypt struct { - Enabled bool `json:"enabled"` -} - -type TeamsActivityLog struct { - Enabled bool `json:"enabled"` -} - -type TeamsBlockPage struct { - Enabled *bool `json:"enabled,omitempty"` - FooterText string `json:"footer_text,omitempty"` - HeaderText string `json:"header_text,omitempty"` - LogoPath string `json:"logo_path,omitempty"` - BackgroundColor string `json:"background_color,omitempty"` - Name string `json:"name,omitempty"` -} - -// TeamsAccount returns teams account information with internal and external ID. -// -// API reference: TBA -func (api *API) TeamsAccount(ctx context.Context, accountID string) (TeamsAccount, error) { - uri := fmt.Sprintf("/accounts/%s/gateway", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return TeamsAccount{}, err - } - - var teamsAccountResponse TeamsAccountResponse - err = json.Unmarshal(res, &teamsAccountResponse) - if err != nil { - return TeamsAccount{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsAccountResponse.Result, nil -} - -// TeamsAccountConfiguration returns teams account configuration. -// -// API reference: TBA -func (api *API) TeamsAccountConfiguration(ctx context.Context, accountID string) (TeamsConfiguration, error) { - uri := fmt.Sprintf("/accounts/%s/gateway/configuration", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return TeamsConfiguration{}, err - } - - var teamsConfigResponse TeamsConfigResponse - err = json.Unmarshal(res, &teamsConfigResponse) - if err != nil { - return TeamsConfiguration{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsConfigResponse.Result, nil -} - -// TeamsAccountUpdateConfiguration updates a teams account configuration. -// -// API reference: TBA -func (api *API) TeamsAccountUpdateConfiguration(ctx context.Context, accountID string, config TeamsConfiguration) (TeamsConfiguration, error) { - uri := fmt.Sprintf("/accounts/%s/gateway/configuration", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, config) - if err != nil { - return TeamsConfiguration{}, err - } - - var teamsConfigResponse TeamsConfigResponse - err = json.Unmarshal(res, &teamsConfigResponse) - if err != nil { - return TeamsConfiguration{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsConfigResponse.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/teams_list.go b/vendor/github.com/cloudflare/cloudflare-go/teams_list.go deleted file mode 100644 index 32b3d25b..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/teams_list.go +++ /dev/null @@ -1,221 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// TeamsList represents a Teams List. -type TeamsList struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Type string `json:"type"` - Description string `json:"description,omitempty"` - Items []TeamsListItem `json:"items,omitempty"` - Count uint64 `json:"count,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` -} - -// TeamsListItem represents a single list item. -type TeamsListItem struct { - Value string `json:"value"` - CreatedAt *time.Time `json:"created_at,omitempty"` -} - -// PatchTeamsList represents a patch request for appending/removing list items. -type PatchTeamsList struct { - ID string `json:"id"` - Append []TeamsListItem `json:"append"` - Remove []string `json:"remove"` -} - -// TeamsListListResponse represents the response from the list -// teams lists endpoint. -type TeamsListListResponse struct { - Result []TeamsList `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// TeamsListItemsListResponse represents the response from the list -// teams list items endpoint. -type TeamsListItemsListResponse struct { - Result []TeamsListItem `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// TeamsListDetailResponse is the API response, containing a single -// teams list. -type TeamsListDetailResponse struct { - Response - Result TeamsList `json:"result"` -} - -// TeamsLists returns all lists within an account. -// -// API reference: https://api.cloudflare.com/#teams-lists-list-teams-lists -func (api *API) TeamsLists(ctx context.Context, accountID string) ([]TeamsList, ResultInfo, error) { - uri := fmt.Sprintf("/%s/%s/gateway/lists", AccountRouteRoot, accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []TeamsList{}, ResultInfo{}, err - } - - var teamsListListResponse TeamsListListResponse - err = json.Unmarshal(res, &teamsListListResponse) - if err != nil { - return []TeamsList{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsListListResponse.Result, teamsListListResponse.ResultInfo, nil -} - -// TeamsList returns a single list based on the list ID. -// -// API reference: https://api.cloudflare.com/#teams-lists-teams-list-details -func (api *API) TeamsList(ctx context.Context, accountID, listID string) (TeamsList, error) { - uri := fmt.Sprintf( - "/%s/%s/gateway/lists/%s", - AccountRouteRoot, - accountID, - listID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return TeamsList{}, err - } - - var teamsListDetailResponse TeamsListDetailResponse - err = json.Unmarshal(res, &teamsListDetailResponse) - if err != nil { - return TeamsList{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsListDetailResponse.Result, nil -} - -// TeamsListItems returns all list items for a list. -// -// API reference: https://api.cloudflare.com/#teams-lists-teams-list-items -func (api *API) TeamsListItems(ctx context.Context, accountID, listID string) ([]TeamsListItem, ResultInfo, error) { - uri := fmt.Sprintf("/%s/%s/gateway/lists/%s/items", AccountRouteRoot, accountID, listID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []TeamsListItem{}, ResultInfo{}, err - } - - var teamsListItemsListResponse TeamsListItemsListResponse - err = json.Unmarshal(res, &teamsListItemsListResponse) - if err != nil { - return []TeamsListItem{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsListItemsListResponse.Result, teamsListItemsListResponse.ResultInfo, nil -} - -// CreateTeamsList creates a new teams list. -// -// API reference: https://api.cloudflare.com/#teams-lists-create-teams-list -func (api *API) CreateTeamsList(ctx context.Context, accountID string, teamsList TeamsList) (TeamsList, error) { - uri := fmt.Sprintf("/%s/%s/gateway/lists", AccountRouteRoot, accountID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, teamsList) - if err != nil { - return TeamsList{}, err - } - - var teamsListDetailResponse TeamsListDetailResponse - err = json.Unmarshal(res, &teamsListDetailResponse) - if err != nil { - return TeamsList{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsListDetailResponse.Result, nil -} - -// UpdateTeamsList updates an existing teams list. -// -// API reference: https://api.cloudflare.com/#teams-lists-update-teams-list -func (api *API) UpdateTeamsList(ctx context.Context, accountID string, teamsList TeamsList) (TeamsList, error) { - if teamsList.ID == "" { - return TeamsList{}, errors.Errorf("teams list ID cannot be empty") - } - - uri := fmt.Sprintf( - "/%s/%s/gateway/lists/%s", - AccountRouteRoot, - accountID, - teamsList.ID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, teamsList) - if err != nil { - return TeamsList{}, err - } - - var teamsListDetailResponse TeamsListDetailResponse - err = json.Unmarshal(res, &teamsListDetailResponse) - if err != nil { - return TeamsList{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsListDetailResponse.Result, nil -} - -// PatchTeamsList updates the items in an existing teams list. -// -// API reference: https://api.cloudflare.com/#teams-lists-patch-teams-list -func (api *API) PatchTeamsList(ctx context.Context, accountID string, listPatch PatchTeamsList) (TeamsList, error) { - if listPatch.ID == "" { - return TeamsList{}, errors.Errorf("teams list ID cannot be empty") - } - - uri := fmt.Sprintf( - "/%s/%s/gateway/lists/%s", - AccountRouteRoot, - accountID, - listPatch.ID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, listPatch) - if err != nil { - return TeamsList{}, err - } - - var teamsListDetailResponse TeamsListDetailResponse - err = json.Unmarshal(res, &teamsListDetailResponse) - if err != nil { - return TeamsList{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsListDetailResponse.Result, nil -} - -// DeleteTeamsList deletes a teams list. -// -// API reference: https://api.cloudflare.com/#teams-lists-delete-teams-list -func (api *API) DeleteTeamsList(ctx context.Context, accountID, teamsListID string) error { - uri := fmt.Sprintf( - "/%s/%s/gateway/lists/%s", - AccountRouteRoot, - accountID, - teamsListID, - ) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/teams_locations.go b/vendor/github.com/cloudflare/cloudflare-go/teams_locations.go deleted file mode 100644 index b6b95a49..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/teams_locations.go +++ /dev/null @@ -1,155 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -type TeamsLocationsListResponse struct { - Response - ResultInfo `json:"result_info"` - Result []TeamsLocation `json:"result"` -} - -type TeamsLocationDetailResponse struct { - Response - Result TeamsLocation `json:"result"` -} - -type TeamsLocationNetwork struct { - ID string `json:"id"` - Network string `json:"network"` -} - -type TeamsLocation struct { - ID string `json:"id"` - Name string `json:"name"` - Networks []TeamsLocationNetwork `json:"networks"` - PolicyIDs []string `json:"policy_ids"` - Ip string `json:"ip,omitempty"` - Subdomain string `json:"doh_subdomain"` - AnonymizedLogsEnabled bool `json:"anonymized_logs_enabled"` - IPv4Destination string `json:"ipv4_destination"` - ClientDefault bool `json:"client_default"` - - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` -} - -// TeamsLocations returns all locations within an account. -// -// API reference: https://api.cloudflare.com/#teams-locations-list-teams-locations -func (api *API) TeamsLocations(ctx context.Context, accountID string) ([]TeamsLocation, ResultInfo, error) { - uri := fmt.Sprintf("/%s/%s/gateway/locations", AccountRouteRoot, accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []TeamsLocation{}, ResultInfo{}, err - } - - var teamsLocationsListResponse TeamsLocationsListResponse - err = json.Unmarshal(res, &teamsLocationsListResponse) - if err != nil { - return []TeamsLocation{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsLocationsListResponse.Result, teamsLocationsListResponse.ResultInfo, nil -} - -// TeamsLocation returns a single location based on the ID. -// -// API reference: https://api.cloudflare.com/#teams-locations-teams-location-details -func (api *API) TeamsLocation(ctx context.Context, accountID, locationID string) (TeamsLocation, error) { - uri := fmt.Sprintf( - "/%s/%s/gateway/locations/%s", - AccountRouteRoot, - accountID, - locationID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return TeamsLocation{}, err - } - - var teamsLocationDetailResponse TeamsLocationDetailResponse - err = json.Unmarshal(res, &teamsLocationDetailResponse) - if err != nil { - return TeamsLocation{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsLocationDetailResponse.Result, nil -} - -// CreateTeamsLocation creates a new teams location. -// -// API reference: https://api.cloudflare.com/#teams-locations-create-teams-location -func (api *API) CreateTeamsLocation(ctx context.Context, accountID string, teamsLocation TeamsLocation) (TeamsLocation, error) { - uri := fmt.Sprintf("/%s/%s/gateway/locations", AccountRouteRoot, accountID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, teamsLocation) - if err != nil { - return TeamsLocation{}, err - } - - var teamsLocationDetailResponse TeamsLocationDetailResponse - err = json.Unmarshal(res, &teamsLocationDetailResponse) - if err != nil { - return TeamsLocation{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsLocationDetailResponse.Result, nil -} - -// UpdateTeamsLocation updates an existing teams location. -// -// API reference: https://api.cloudflare.com/#teams-locations-update-teams-location -func (api *API) UpdateTeamsLocation(ctx context.Context, accountID string, teamsLocation TeamsLocation) (TeamsLocation, error) { - if teamsLocation.ID == "" { - return TeamsLocation{}, errors.Errorf("teams location ID cannot be empty") - } - - uri := fmt.Sprintf( - "/%s/%s/gateway/locations/%s", - AccountRouteRoot, - accountID, - teamsLocation.ID, - ) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, teamsLocation) - if err != nil { - return TeamsLocation{}, err - } - - var teamsLocationDetailResponse TeamsLocationDetailResponse - err = json.Unmarshal(res, &teamsLocationDetailResponse) - if err != nil { - return TeamsLocation{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsLocationDetailResponse.Result, nil -} - -// DeleteTeamsLocation deletes a teams location. -// -// API reference: https://api.cloudflare.com/#teams-locations-delete-teams-location -func (api *API) DeleteTeamsLocation(ctx context.Context, accountID, teamsLocationID string) error { - uri := fmt.Sprintf( - "/%s/%s/gateway/locations/%s", - AccountRouteRoot, - accountID, - teamsLocationID, - ) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/teams_rules.go b/vendor/github.com/cloudflare/cloudflare-go/teams_rules.go deleted file mode 100644 index 177cf2d6..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/teams_rules.go +++ /dev/null @@ -1,239 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -type TeamsRuleSettings struct { - // Enable block page on rules with action block - BlockPageEnabled bool `json:"block_page_enabled"` - - // show this string at block page caused by this rule - BlockReason string `json:"block_reason"` - - // list of ipv4 or ipv6 ips to override with, when action is set to dns override - OverrideIPs []string `json:"override_ips"` - - // host name to override with when action is set to dns override. Can not be used with OverrideIPs - OverrideHost string `json:"override_host"` - - // settings for l4(network) level overrides - L4Override *TeamsL4OverrideSettings `json:"l4override"` - - // settings for browser isolation actions - BISOAdminControls *TeamsBISOAdminControlSettings `json:"biso_admin_controls"` -} - -// TeamsL4OverrideSettings used in l4 filter type rule with action set to override -type TeamsL4OverrideSettings struct { - IP string `json:"ip,omitempty"` - Port int `json:"port,omitempty"` -} - -type TeamsBISOAdminControlSettings struct { - DisablePrinting bool `json:"dp"` - DisableCopyPaste bool `json:"dcp"` -} - -type TeamsFilterType string - -type TeamsGatewayAction string - -const ( - HttpFilter TeamsFilterType = "http" - DnsFilter TeamsFilterType = "dns" - L4Filter TeamsFilterType = "l4" -) - -const ( - Allow TeamsGatewayAction = "allow" - Block TeamsGatewayAction = "block" - SafeSearch TeamsGatewayAction = "safesearch" - YTRestricted TeamsGatewayAction = "ytrestricted" - On TeamsGatewayAction = "on" - Off TeamsGatewayAction = "off" - Scan TeamsGatewayAction = "scan" - NoScan TeamsGatewayAction = "noscan" - Isolate TeamsGatewayAction = "isolate" - NoIsolate TeamsGatewayAction = "noisolate" - Override TeamsGatewayAction = "override" - L4Override TeamsGatewayAction = "l4_override" -) - -func TeamsRulesActionValues() []string { - return []string{ - string(Allow), - string(Block), - string(SafeSearch), - string(YTRestricted), - string(On), - string(Off), - string(Scan), - string(NoScan), - string(Isolate), - string(NoIsolate), - string(Override), - string(L4Override), - } -} - -// TeamsRule represents an Teams wirefilter rule. -type TeamsRule struct { - ID string `json:"id,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - DeletedAt *time.Time `json:"deleted_at,omitempty"` - Name string `json:"name"` - Description string `json:"description"` - Precedence uint64 `json:"precedence"` - Enabled bool `json:"enabled"` - Action TeamsGatewayAction `json:"action"` - Filters []TeamsFilterType `json:"filters"` - Traffic string `json:"traffic"` - Identity string `json:"identity"` - Version uint64 `json:"version"` - RuleSettings TeamsRuleSettings `json:"rule_settings,omitempty"` -} - -// TeamsRuleResponse is the API response, containing a single rule. -type TeamsRuleResponse struct { - Response - Result TeamsRule `json:"result"` -} - -// TeamsRuleResponse is the API response, containing an array of rules. -type TeamsRulesResponse struct { - Response - Result []TeamsRule `json:"result"` -} - -// TeamsRulePatchRequest is used to patch an existing rule. -type TeamsRulePatchRequest struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Precedence uint64 `json:"precedence"` - Enabled bool `json:"enabled"` - Action TeamsGatewayAction `json:"action"` - RuleSettings TeamsRuleSettings `json:"rule_settings,omitempty"` -} - -// TeamsRules returns all rules within an account. -// -// API reference: https://api.cloudflare.com/#teams-rules-properties -func (api *API) TeamsRules(ctx context.Context, accountID string) ([]TeamsRule, error) { - uri := fmt.Sprintf("/accounts/%s/gateway/rules", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []TeamsRule{}, err - } - - var teamsRulesResponse TeamsRulesResponse - err = json.Unmarshal(res, &teamsRulesResponse) - if err != nil { - return []TeamsRule{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsRulesResponse.Result, nil -} - -// TeamsRule returns the rule with rule ID in the URL. -// -// API reference: https://api.cloudflare.com/#teams-rules-properties -func (api *API) TeamsRule(ctx context.Context, accountID string, ruleId string) (TeamsRule, error) { - uri := fmt.Sprintf("/accounts/%s/gateway/rules/%s", accountID, ruleId) - - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return TeamsRule{}, err - } - - var teamsRuleResponse TeamsRuleResponse - err = json.Unmarshal(res, &teamsRuleResponse) - if err != nil { - return TeamsRule{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsRuleResponse.Result, nil -} - -// TeamsCreateRule creates a rule with wirefilter expression. -// -// API reference: https://api.cloudflare.com/#teams-rules-properties -func (api *API) TeamsCreateRule(ctx context.Context, accountID string, rule TeamsRule) (TeamsRule, error) { - uri := fmt.Sprintf("/accounts/%s/gateway/rules", accountID) - - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, rule) - if err != nil { - return TeamsRule{}, err - } - - var teamsRuleResponse TeamsRuleResponse - err = json.Unmarshal(res, &teamsRuleResponse) - if err != nil { - return TeamsRule{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsRuleResponse.Result, nil -} - -// TeamsUpdateRule updates a rule with wirefilter expression. -// -// API reference: https://api.cloudflare.com/#teams-rules-properties -func (api *API) TeamsUpdateRule(ctx context.Context, accountID string, ruleId string, rule TeamsRule) (TeamsRule, error) { - uri := fmt.Sprintf("/accounts/%s/gateway/rules/%s", accountID, ruleId) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, rule) - if err != nil { - return TeamsRule{}, err - } - - var teamsRuleResponse TeamsRuleResponse - err = json.Unmarshal(res, &teamsRuleResponse) - if err != nil { - return TeamsRule{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsRuleResponse.Result, nil -} - -// TeamsPatchRule patches a rule associated values. -// -// API reference: https://api.cloudflare.com/#teams-rules-properties -func (api *API) TeamsPatchRule(ctx context.Context, accountID string, ruleId string, rule TeamsRulePatchRequest) (TeamsRule, error) { - uri := fmt.Sprintf("/accounts/%s/gateway/rules/%s", accountID, ruleId) - - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, rule) - if err != nil { - return TeamsRule{}, err - } - - var teamsRuleResponse TeamsRuleResponse - err = json.Unmarshal(res, &teamsRuleResponse) - if err != nil { - return TeamsRule{}, errors.Wrap(err, errUnmarshalError) - } - - return teamsRuleResponse.Result, nil -} - -// TeamsDeleteRule deletes a rule. -// -// API reference: https://api.cloudflare.com/#teams-rules-properties -func (api *API) TeamsDeleteRule(ctx context.Context, accountID string, ruleId string) error { - uri := fmt.Sprintf("/accounts/%s/gateway/rules/%s", accountID, ruleId) - - _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/universal_ssl.go b/vendor/github.com/cloudflare/cloudflare-go/universal_ssl.go deleted file mode 100644 index 7e233c43..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/universal_ssl.go +++ /dev/null @@ -1,116 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -// UniversalSSLSetting represents a universal ssl setting's properties. -type UniversalSSLSetting struct { - Enabled bool `json:"enabled"` -} - -type universalSSLSettingResponse struct { - Response - Result UniversalSSLSetting `json:"result"` -} - -// UniversalSSLVerificationDetails represents a universal ssl verification's properties. -type UniversalSSLVerificationDetails struct { - CertificateStatus string `json:"certificate_status"` - VerificationType string `json:"verification_type"` - ValidationMethod string `json:"validation_method"` - CertPackUUID string `json:"cert_pack_uuid"` - VerificationStatus bool `json:"verification_status"` - BrandCheck bool `json:"brand_check"` - VerificationInfo UniversalSSLVerificationInfo `json:"verification_info"` -} - -// UniversalSSLVerificationInfo represents DCV record. -type UniversalSSLVerificationInfo struct { - RecordName string `json:"record_name"` - RecordTarget string `json:"record_target"` -} - -type universalSSLVerificationResponse struct { - Response - Result []UniversalSSLVerificationDetails `json:"result"` -} - -type UniversalSSLCertificatePackValidationMethodSetting struct { - ValidationMethod string `json:"validation_method"` -} - -type universalSSLCertificatePackValidationMethodSettingResponse struct { - Response - Result UniversalSSLCertificatePackValidationMethodSetting `json:"result"` -} - -// UniversalSSLSettingDetails returns the details for a universal ssl setting -// -// API reference: https://api.cloudflare.com/#universal-ssl-settings-for-a-zone-universal-ssl-settings-details -func (api *API) UniversalSSLSettingDetails(ctx context.Context, zoneID string) (UniversalSSLSetting, error) { - uri := fmt.Sprintf("/zones/%s/ssl/universal/settings", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return UniversalSSLSetting{}, err - } - var r universalSSLSettingResponse - if err := json.Unmarshal(res, &r); err != nil { - return UniversalSSLSetting{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// EditUniversalSSLSetting edits the universal ssl setting for a zone -// -// API reference: https://api.cloudflare.com/#universal-ssl-settings-for-a-zone-edit-universal-ssl-settings -func (api *API) EditUniversalSSLSetting(ctx context.Context, zoneID string, setting UniversalSSLSetting) (UniversalSSLSetting, error) { - uri := fmt.Sprintf("/zones/%s/ssl/universal/settings", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, setting) - if err != nil { - return UniversalSSLSetting{}, err - } - var r universalSSLSettingResponse - if err := json.Unmarshal(res, &r); err != nil { - return UniversalSSLSetting{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil - -} - -// UniversalSSLVerificationDetails returns the details for a universal ssl verification -// -// API reference: https://api.cloudflare.com/#ssl-verification-ssl-verification-details -func (api *API) UniversalSSLVerificationDetails(ctx context.Context, zoneID string) ([]UniversalSSLVerificationDetails, error) { - uri := fmt.Sprintf("/zones/%s/ssl/verification", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []UniversalSSLVerificationDetails{}, err - } - var r universalSSLVerificationResponse - if err := json.Unmarshal(res, &r); err != nil { - return []UniversalSSLVerificationDetails{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateUniversalSSLCertificatePackValidationMethod changes the validation method for a certificate pack -// -// API reference: https://api.cloudflare.com/#ssl-verification-ssl-verification-details -func (api *API) UpdateUniversalSSLCertificatePackValidationMethod(ctx context.Context, zoneID string, certPackUUID string, setting UniversalSSLCertificatePackValidationMethodSetting) (UniversalSSLCertificatePackValidationMethodSetting, error) { - uri := fmt.Sprintf("/zones/%s/ssl/verification/%s", zoneID, certPackUUID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, setting) - if err != nil { - return UniversalSSLCertificatePackValidationMethodSetting{}, err - } - var r universalSSLCertificatePackValidationMethodSettingResponse - if err := json.Unmarshal(res, &r); err != nil { - return UniversalSSLCertificatePackValidationMethodSetting{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/user.go b/vendor/github.com/cloudflare/cloudflare-go/user.go deleted file mode 100644 index 50b7f207..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/user.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// User describes a user account. -type User struct { - ID string `json:"id,omitempty"` - Email string `json:"email,omitempty"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - Username string `json:"username,omitempty"` - Telephone string `json:"telephone,omitempty"` - Country string `json:"country,omitempty"` - Zipcode string `json:"zipcode,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - APIKey string `json:"api_key,omitempty"` - TwoFA bool `json:"two_factor_authentication_enabled,omitempty"` - Betas []string `json:"betas,omitempty"` - Accounts []Account `json:"organizations,omitempty"` -} - -// UserResponse wraps a response containing User accounts. -type UserResponse struct { - Response - Result User `json:"result"` -} - -// userBillingProfileResponse wraps a response containing Billing Profile information. -type userBillingProfileResponse struct { - Response - Result UserBillingProfile -} - -// UserBillingProfile contains Billing Profile information. -type UserBillingProfile struct { - ID string `json:"id,omitempty"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - Address string `json:"address,omitempty"` - Address2 string `json:"address2,omitempty"` - Company string `json:"company,omitempty"` - City string `json:"city,omitempty"` - State string `json:"state,omitempty"` - ZipCode string `json:"zipcode,omitempty"` - Country string `json:"country,omitempty"` - Telephone string `json:"telephone,omitempty"` - CardNumber string `json:"card_number,omitempty"` - CardExpiryYear int `json:"card_expiry_year,omitempty"` - CardExpiryMonth int `json:"card_expiry_month,omitempty"` - VAT string `json:"vat,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - EditedOn *time.Time `json:"edited_on,omitempty"` -} - -// UserDetails provides information about the logged-in user. -// -// API reference: https://api.cloudflare.com/#user-user-details -func (api *API) UserDetails(ctx context.Context) (User, error) { - var r UserResponse - res, err := api.makeRequestContext(ctx, http.MethodGet, "/user", nil) - if err != nil { - return User{}, err - } - - err = json.Unmarshal(res, &r) - if err != nil { - return User{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// UpdateUser updates the properties of the given user. -// -// API reference: https://api.cloudflare.com/#user-update-user -func (api *API) UpdateUser(ctx context.Context, user *User) (User, error) { - var r UserResponse - res, err := api.makeRequestContext(ctx, http.MethodPatch, "/user", user) - if err != nil { - return User{}, err - } - - err = json.Unmarshal(res, &r) - if err != nil { - return User{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// UserBillingProfile returns the billing profile of the user. -// -// API reference: https://api.cloudflare.com/#user-billing-profile -func (api *API) UserBillingProfile(ctx context.Context) (UserBillingProfile, error) { - var r userBillingProfileResponse - res, err := api.makeRequestContext(ctx, http.MethodGet, "/user/billing/profile", nil) - if err != nil { - return UserBillingProfile{}, err - } - - err = json.Unmarshal(res, &r) - if err != nil { - return UserBillingProfile{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/user_agent.go b/vendor/github.com/cloudflare/cloudflare-go/user_agent.go deleted file mode 100644 index bb48ef81..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/user_agent.go +++ /dev/null @@ -1,151 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// UserAgentRule represents a User-Agent Block. These rules can be used to -// challenge, block or whitelist specific User-Agents for a given zone. -type UserAgentRule struct { - ID string `json:"id"` - Description string `json:"description"` - Mode string `json:"mode"` - Configuration UserAgentRuleConfig `json:"configuration"` - Paused bool `json:"paused"` -} - -// UserAgentRuleConfig represents a Zone Lockdown config, which comprises -// a Target ("ip" or "ip_range") and a Value (an IP address or IP+mask, -// respectively.) -type UserAgentRuleConfig ZoneLockdownConfig - -// UserAgentRuleResponse represents a response from the Zone Lockdown endpoint. -type UserAgentRuleResponse struct { - Result UserAgentRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// UserAgentRuleListResponse represents a response from the List Zone Lockdown endpoint. -type UserAgentRuleListResponse struct { - Result []UserAgentRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// CreateUserAgentRule creates a User-Agent Block rule for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-create-a-useragent-rule -func (api *API) CreateUserAgentRule(ctx context.Context, zoneID string, ld UserAgentRule) (*UserAgentRuleResponse, error) { - switch ld.Mode { - case "block", "challenge", "js_challenge", "whitelist": - break - default: - return nil, errors.New(`the User-Agent Block rule mode must be one of "block", "challenge", "js_challenge", "whitelist"`) - } - - uri := fmt.Sprintf("/zones/%s/firewall/ua_rules", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, ld) - if err != nil { - return nil, err - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UpdateUserAgentRule updates a User-Agent Block rule (based on the ID) for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-update-useragent-rule -func (api *API) UpdateUserAgentRule(ctx context.Context, zoneID string, id string, ld UserAgentRule) (*UserAgentRuleResponse, error) { - uri := fmt.Sprintf("/zones/%s/firewall/ua_rules/%s", zoneID, id) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, ld) - if err != nil { - return nil, err - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// DeleteUserAgentRule deletes a User-Agent Block rule (based on the ID) for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-delete-useragent-rule -func (api *API) DeleteUserAgentRule(ctx context.Context, zoneID string, id string) (*UserAgentRuleResponse, error) { - uri := fmt.Sprintf("/zones/%s/firewall/ua_rules/%s", zoneID, id) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return nil, err - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UserAgentRule retrieves a User-Agent Block rule (based on the ID) for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-useragent-rule-details -func (api *API) UserAgentRule(ctx context.Context, zoneID string, id string) (*UserAgentRuleResponse, error) { - uri := fmt.Sprintf("/zones/%s/firewall/ua_rules/%s", zoneID, id) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ListUserAgentRules retrieves a list of User-Agent Block rules for a given zone ID by page number. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-list-useragent-rules -func (api *API) ListUserAgentRules(ctx context.Context, zoneID string, page int) (*UserAgentRuleListResponse, error) { - v := url.Values{} - if page <= 0 { - page = 1 - } - - v.Set("page", strconv.Itoa(page)) - v.Set("per_page", strconv.Itoa(100)) - - uri := fmt.Sprintf("/zones/%s/firewall/ua_rules?%s", zoneID, v.Encode()) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - response := &UserAgentRuleListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/virtualdns.go b/vendor/github.com/cloudflare/cloudflare-go/virtualdns.go deleted file mode 100644 index 08058447..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/virtualdns.go +++ /dev/null @@ -1,197 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strings" - "time" - - "github.com/pkg/errors" -) - -// VirtualDNS represents a Virtual DNS configuration. -type VirtualDNS struct { - ID string `json:"id"` - Name string `json:"name"` - OriginIPs []string `json:"origin_ips"` - VirtualDNSIPs []string `json:"virtual_dns_ips"` - MinimumCacheTTL uint `json:"minimum_cache_ttl"` - MaximumCacheTTL uint `json:"maximum_cache_ttl"` - DeprecateAnyRequests bool `json:"deprecate_any_requests"` - ModifiedOn string `json:"modified_on"` -} - -// VirtualDNSAnalyticsMetrics represents a group of aggregated Virtual DNS metrics. -type VirtualDNSAnalyticsMetrics struct { - QueryCount *int64 `json:"queryCount"` - UncachedCount *int64 `json:"uncachedCount"` - StaleCount *int64 `json:"staleCount"` - ResponseTimeAvg *float64 `json:"responseTimeAvg"` - ResponseTimeMedian *float64 `json:"responseTimeMedian"` - ResponseTime90th *float64 `json:"responseTime90th"` - ResponseTime99th *float64 `json:"responseTime99th"` -} - -// VirtualDNSAnalytics represents a set of aggregated Virtual DNS metrics. -// TODO: Add the queried data and not only the aggregated values. -type VirtualDNSAnalytics struct { - Totals VirtualDNSAnalyticsMetrics `json:"totals"` - Min VirtualDNSAnalyticsMetrics `json:"min"` - Max VirtualDNSAnalyticsMetrics `json:"max"` -} - -// VirtualDNSUserAnalyticsOptions represents range and dimension selection on analytics endpoint -type VirtualDNSUserAnalyticsOptions struct { - Metrics []string - Since *time.Time - Until *time.Time -} - -// VirtualDNSResponse represents a Virtual DNS response. -type VirtualDNSResponse struct { - Response - Result *VirtualDNS `json:"result"` -} - -// VirtualDNSListResponse represents an array of Virtual DNS responses. -type VirtualDNSListResponse struct { - Response - Result []*VirtualDNS `json:"result"` -} - -// VirtualDNSAnalyticsResponse represents a Virtual DNS analytics response. -type VirtualDNSAnalyticsResponse struct { - Response - Result VirtualDNSAnalytics `json:"result"` -} - -// CreateVirtualDNS creates a new Virtual DNS cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--create-a-virtual-dns-cluster -func (api *API) CreateVirtualDNS(ctx context.Context, v *VirtualDNS) (*VirtualDNS, error) { - uri := fmt.Sprintf("%s/virtual_dns", api.userBaseURL("/user")) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, v) - if err != nil { - return nil, err - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// VirtualDNS fetches a single virtual DNS cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--get-a-virtual-dns-cluster -func (api *API) VirtualDNS(ctx context.Context, virtualDNSID string) (*VirtualDNS, error) { - uri := fmt.Sprintf("%s/virtual_dns/%s", api.userBaseURL("/user"), virtualDNSID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// ListVirtualDNS lists the virtual DNS clusters associated with an account. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--get-virtual-dns-clusters -func (api *API) ListVirtualDNS(ctx context.Context) ([]*VirtualDNS, error) { - uri := fmt.Sprintf("%s/virtual_dns", api.userBaseURL("/user")) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - response := &VirtualDNSListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// UpdateVirtualDNS updates a Virtual DNS cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--modify-a-virtual-dns-cluster -func (api *API) UpdateVirtualDNS(ctx context.Context, virtualDNSID string, vv VirtualDNS) error { - uri := fmt.Sprintf("%s/virtual_dns/%s", api.userBaseURL("/user"), virtualDNSID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, vv) - if err != nil { - return err - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} - -// DeleteVirtualDNS deletes a Virtual DNS cluster. Note that this cannot be -// undone, and will stop all traffic to that cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--delete-a-virtual-dns-cluster -func (api *API) DeleteVirtualDNS(ctx context.Context, virtualDNSID string) error { - uri := fmt.Sprintf("%s/virtual_dns/%s", api.userBaseURL("/user"), virtualDNSID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} - -// encode encodes non-nil fields into URL encoded form. -func (o VirtualDNSUserAnalyticsOptions) encode() string { - v := url.Values{} - if o.Since != nil { - v.Set("since", (*o.Since).UTC().Format(time.RFC3339)) - } - if o.Until != nil { - v.Set("until", (*o.Until).UTC().Format(time.RFC3339)) - } - if o.Metrics != nil { - v.Set("metrics", strings.Join(o.Metrics, ",")) - } - return v.Encode() -} - -// VirtualDNSUserAnalytics retrieves analytics report for a specified dimension and time range -func (api *API) VirtualDNSUserAnalytics(ctx context.Context, virtualDNSID string, o VirtualDNSUserAnalyticsOptions) (VirtualDNSAnalytics, error) { - uri := fmt.Sprintf("%s/virtual_dns/%s/dns_analytics/report?%s", api.userBaseURL("/user"), virtualDNSID, o.encode()) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return VirtualDNSAnalytics{}, err - } - - response := VirtualDNSAnalyticsResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return VirtualDNSAnalytics{}, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/waf.go b/vendor/github.com/cloudflare/cloudflare-go/waf.go deleted file mode 100644 index 596ef37f..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/waf.go +++ /dev/null @@ -1,353 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// WAFPackage represents a WAF package configuration. -type WAFPackage struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - ZoneID string `json:"zone_id"` - DetectionMode string `json:"detection_mode"` - Sensitivity string `json:"sensitivity"` - ActionMode string `json:"action_mode"` -} - -// WAFPackagesResponse represents the response from the WAF packages endpoint. -type WAFPackagesResponse struct { - Response - Result []WAFPackage `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// WAFPackageResponse represents the response from the WAF package endpoint. -type WAFPackageResponse struct { - Response - Result WAFPackage `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// WAFPackageOptions represents options to edit a WAF package. -type WAFPackageOptions struct { - Sensitivity string `json:"sensitivity,omitempty"` - ActionMode string `json:"action_mode,omitempty"` -} - -// WAFGroup represents a WAF rule group. -type WAFGroup struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - RulesCount int `json:"rules_count"` - ModifiedRulesCount int `json:"modified_rules_count"` - PackageID string `json:"package_id"` - Mode string `json:"mode"` - AllowedModes []string `json:"allowed_modes"` -} - -// WAFGroupsResponse represents the response from the WAF groups endpoint. -type WAFGroupsResponse struct { - Response - Result []WAFGroup `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// WAFGroupResponse represents the response from the WAF group endpoint. -type WAFGroupResponse struct { - Response - Result WAFGroup `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// WAFRule represents a WAF rule. -type WAFRule struct { - ID string `json:"id"` - Description string `json:"description"` - Priority string `json:"priority"` - PackageID string `json:"package_id"` - Group struct { - ID string `json:"id"` - Name string `json:"name"` - } `json:"group"` - Mode string `json:"mode"` - DefaultMode string `json:"default_mode"` - AllowedModes []string `json:"allowed_modes"` -} - -// WAFRulesResponse represents the response from the WAF rules endpoint. -type WAFRulesResponse struct { - Response - Result []WAFRule `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// WAFRuleResponse represents the response from the WAF rule endpoint. -type WAFRuleResponse struct { - Response - Result WAFRule `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// WAFRuleOptions is a subset of WAFRule, for editable options. -type WAFRuleOptions struct { - Mode string `json:"mode"` -} - -// ListWAFPackages returns a slice of the WAF packages for the given zone. -// -// API Reference: https://api.cloudflare.com/#waf-rule-packages-list-firewall-packages -func (api *API) ListWAFPackages(ctx context.Context, zoneID string) ([]WAFPackage, error) { - // Construct a query string - v := url.Values{} - // Request as many WAF packages as possible per page - API max is 100 - v.Set("per_page", "100") - - var packages []WAFPackage - var res []byte - var err error - page := 1 - - // Loop over makeRequest until what we've fetched all records - for { - v.Set("page", strconv.Itoa(page)) - uri := fmt.Sprintf("/zones/%s/firewall/waf/packages?%s", zoneID, v.Encode()) - res, err = api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []WAFPackage{}, err - } - - var p WAFPackagesResponse - err = json.Unmarshal(res, &p) - if err != nil { - return []WAFPackage{}, errors.Wrap(err, errUnmarshalError) - } - - if !p.Success { - // TODO: Provide an actual error message instead of always returning nil - return []WAFPackage{}, err - } - - packages = append(packages, p.Result...) - if p.ResultInfo.Page >= p.ResultInfo.TotalPages { - break - } - - // Loop around and fetch the next page - page++ - } - - return packages, nil -} - -// WAFPackage returns a WAF package for the given zone. -// -// API Reference: https://api.cloudflare.com/#waf-rule-packages-firewall-package-details -func (api *API) WAFPackage(ctx context.Context, zoneID, packageID string) (WAFPackage, error) { - uri := fmt.Sprintf("/zones/%s/firewall/waf/packages/%s", zoneID, packageID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return WAFPackage{}, err - } - - var r WAFPackageResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WAFPackage{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// UpdateWAFPackage lets you update the a WAF Package. -// -// API Reference: https://api.cloudflare.com/#waf-rule-packages-edit-firewall-package -func (api *API) UpdateWAFPackage(ctx context.Context, zoneID, packageID string, opts WAFPackageOptions) (WAFPackage, error) { - uri := fmt.Sprintf("/zones/%s/firewall/waf/packages/%s", zoneID, packageID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, opts) - if err != nil { - return WAFPackage{}, err - } - - var r WAFPackageResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WAFPackage{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListWAFGroups returns a slice of the WAF groups for the given WAF package. -// -// API Reference: https://api.cloudflare.com/#waf-rule-groups-list-rule-groups -func (api *API) ListWAFGroups(ctx context.Context, zoneID, packageID string) ([]WAFGroup, error) { - // Construct a query string - v := url.Values{} - // Request as many WAF groups as possible per page - API max is 100 - v.Set("per_page", "100") - - var groups []WAFGroup - var res []byte - var err error - page := 1 - - // Loop over makeRequest until what we've fetched all records - for { - v.Set("page", strconv.Itoa(page)) - uri := fmt.Sprintf("/zones/%s/firewall/waf/packages/%s/groups?%s", zoneID, packageID, v.Encode()) - res, err = api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []WAFGroup{}, err - } - - var r WAFGroupsResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []WAFGroup{}, errors.Wrap(err, errUnmarshalError) - } - - if !r.Success { - // TODO: Provide an actual error message instead of always returning nil - return []WAFGroup{}, err - } - - groups = append(groups, r.Result...) - if r.ResultInfo.Page >= r.ResultInfo.TotalPages { - break - } - - // Loop around and fetch the next page - page++ - } - return groups, nil -} - -// WAFGroup returns a WAF rule group from the given WAF package. -// -// API Reference: https://api.cloudflare.com/#waf-rule-groups-rule-group-details -func (api *API) WAFGroup(ctx context.Context, zoneID, packageID, groupID string) (WAFGroup, error) { - uri := fmt.Sprintf("/zones/%s/firewall/waf/packages/%s/groups/%s", zoneID, packageID, groupID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return WAFGroup{}, err - } - - var r WAFGroupResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WAFGroup{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// UpdateWAFGroup lets you update the mode of a WAF Group. -// -// API Reference: https://api.cloudflare.com/#waf-rule-groups-edit-rule-group -func (api *API) UpdateWAFGroup(ctx context.Context, zoneID, packageID, groupID, mode string) (WAFGroup, error) { - opts := WAFRuleOptions{Mode: mode} - uri := fmt.Sprintf("/zones/%s/firewall/waf/packages/%s/groups/%s", zoneID, packageID, groupID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, opts) - if err != nil { - return WAFGroup{}, err - } - - var r WAFGroupResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WAFGroup{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListWAFRules returns a slice of the WAF rules for the given WAF package. -// -// API Reference: https://api.cloudflare.com/#waf-rules-list-rules -func (api *API) ListWAFRules(ctx context.Context, zoneID, packageID string) ([]WAFRule, error) { - // Construct a query string - v := url.Values{} - // Request as many WAF rules as possible per page - API max is 100 - v.Set("per_page", "100") - - var rules []WAFRule - var res []byte - var err error - page := 1 - - // Loop over makeRequest until what we've fetched all records - for { - v.Set("page", strconv.Itoa(page)) - uri := fmt.Sprintf("/zones/%s/firewall/waf/packages/%s/rules?%s", zoneID, packageID, v.Encode()) - res, err = api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []WAFRule{}, err - } - - var r WAFRulesResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []WAFRule{}, errors.Wrap(err, errUnmarshalError) - } - - if !r.Success { - // TODO: Provide an actual error message instead of always returning nil - return []WAFRule{}, err - } - - rules = append(rules, r.Result...) - if r.ResultInfo.Page >= r.ResultInfo.TotalPages { - break - } - - // Loop around and fetch the next page - page++ - } - - return rules, nil -} - -// WAFRule returns a WAF rule from the given WAF package. -// -// API Reference: https://api.cloudflare.com/#waf-rules-rule-details -func (api *API) WAFRule(ctx context.Context, zoneID, packageID, ruleID string) (WAFRule, error) { - uri := fmt.Sprintf("/zones/%s/firewall/waf/packages/%s/rules/%s", zoneID, packageID, ruleID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return WAFRule{}, err - } - - var r WAFRuleResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WAFRule{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// UpdateWAFRule lets you update the mode of a WAF Rule. -// -// API Reference: https://api.cloudflare.com/#waf-rules-edit-rule -func (api *API) UpdateWAFRule(ctx context.Context, zoneID, packageID, ruleID, mode string) (WAFRule, error) { - opts := WAFRuleOptions{Mode: mode} - uri := fmt.Sprintf("/zones/%s/firewall/waf/packages/%s/rules/%s", zoneID, packageID, ruleID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, opts) - if err != nil { - return WAFRule{}, err - } - - var r WAFRuleResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WAFRule{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/waf_overrides.go b/vendor/github.com/cloudflare/cloudflare-go/waf_overrides.go deleted file mode 100644 index d061425c..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/waf_overrides.go +++ /dev/null @@ -1,139 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -// WAFOverridesResponse represents the response form the WAF overrides endpoint. -type WAFOverridesResponse struct { - Response - Result []WAFOverride `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// WAFOverrideResponse represents the response form the WAF override endpoint. -type WAFOverrideResponse struct { - Response - Result WAFOverride `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// WAFOverride represents a WAF override. -type WAFOverride struct { - ID string `json:"id,omitempty"` - Description string `json:"description"` - URLs []string `json:"urls"` - Priority int `json:"priority"` - Groups map[string]string `json:"groups"` - RewriteAction map[string]string `json:"rewrite_action"` - Rules map[string]string `json:"rules"` - Paused bool `json:"paused"` -} - -// ListWAFOverrides returns a slice of the WAF overrides. -// -// API Reference: https://api.cloudflare.com/#waf-overrides-list-uri-controlled-waf-configurations -func (api *API) ListWAFOverrides(ctx context.Context, zoneID string) ([]WAFOverride, error) { - var overrides []WAFOverride - var res []byte - var err error - - uri := fmt.Sprintf("/zones/%s/firewall/waf/overrides", zoneID) - res, err = api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []WAFOverride{}, err - } - - var r WAFOverridesResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []WAFOverride{}, errors.Wrap(err, errUnmarshalError) - } - - if !r.Success { - // TODO: Provide an actual error message instead of always returning nil - return []WAFOverride{}, err - } - - for ri := range r.Result { - overrides = append(overrides, r.Result[ri]) - } - return overrides, nil -} - -// WAFOverride returns a WAF override from the given override ID. -// -// API Reference: https://api.cloudflare.com/#waf-overrides-uri-controlled-waf-configuration-details -func (api *API) WAFOverride(ctx context.Context, zoneID, overrideID string) (WAFOverride, error) { - uri := fmt.Sprintf("/zones/%s/firewall/waf/overrides/%s", zoneID, overrideID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return WAFOverride{}, err - } - - var r WAFOverrideResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WAFOverride{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// CreateWAFOverride creates a new WAF override. -// -// API reference: https://api.cloudflare.com/#waf-overrides-create-a-uri-controlled-waf-configuration -func (api *API) CreateWAFOverride(ctx context.Context, zoneID string, override WAFOverride) (WAFOverride, error) { - uri := fmt.Sprintf("/zones/%s/firewall/waf/overrides", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, override) - if err != nil { - return WAFOverride{}, err - } - var r WAFOverrideResponse - if err := json.Unmarshal(res, &r); err != nil { - return WAFOverride{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateWAFOverride updates an existing WAF override. -// -// API reference: https://api.cloudflare.com/#waf-overrides-update-uri-controlled-waf-configuration -func (api *API) UpdateWAFOverride(ctx context.Context, zoneID, overrideID string, override WAFOverride) (WAFOverride, error) { - uri := fmt.Sprintf("/zones/%s/firewall/waf/overrides/%s", zoneID, overrideID) - - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, override) - if err != nil { - return WAFOverride{}, err - } - - var r WAFOverrideResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WAFOverride{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// DeleteWAFOverride deletes a WAF override for a zone. -// -// API reference: https://api.cloudflare.com/#waf-overrides-delete-lockdown-rule -func (api *API) DeleteWAFOverride(ctx context.Context, zoneID, overrideID string) error { - uri := fmt.Sprintf("/zones/%s/firewall/waf/overrides/%s", zoneID, overrideID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - var r WAFOverrideResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/waiting_room.go b/vendor/github.com/cloudflare/cloudflare-go/waiting_room.go deleted file mode 100644 index 7964dbf7..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/waiting_room.go +++ /dev/null @@ -1,146 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// WaitingRoom describes a WaitingRoom object. -type WaitingRoom struct { - ID string `json:"id,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` - ModifiedOn time.Time `json:"modified_on,omitempty"` - Name string `json:"name"` - Description string `json:"description,omitempty"` - Suspended bool `json:"suspended"` - Host string `json:"host"` - Path string `json:"path"` - QueueAll bool `json:"queue_all"` - NewUsersPerMinute int `json:"new_users_per_minute"` - TotalActiveUsers int `json:"total_active_users"` - SessionDuration int `json:"session_duration"` - DisableSessionRenewal bool `json:"disable_session_renewal"` - CustomPageHTML string `json:"custom_page_html,omitempty"` - JsonResponseEnabled bool `json:"json_response_enabled"` -} - -// WaitingRoomDetailResponse is the API response, containing a single WaitingRoom. -type WaitingRoomDetailResponse struct { - Response - Result WaitingRoom `json:"result"` -} - -// WaitingRoomsResponse is the API response, containing an array of WaitingRooms. -type WaitingRoomsResponse struct { - Response - Result []WaitingRoom `json:"result"` -} - -// CreateWaitingRoom creates a new Waiting Room for a zone. -// -// API reference: https://api.cloudflare.com/#waiting-room-create-waiting-room -func (api *API) CreateWaitingRoom(ctx context.Context, zoneID string, waitingRoom WaitingRoom) (*WaitingRoom, error) { - uri := fmt.Sprintf("/zones/%s/waiting_rooms", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, waitingRoom) - if err != nil { - return nil, err - } - var r WaitingRoomDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return &r.Result, nil -} - -// ListWaitingRooms returns all Waiting Room for a zone. -// -// API reference: https://api.cloudflare.com/#waiting-room-list-waiting-rooms -func (api *API) ListWaitingRooms(ctx context.Context, zoneID string) ([]WaitingRoom, error) { - uri := fmt.Sprintf("/zones/%s/waiting_rooms", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []WaitingRoom{}, err - } - var r WaitingRoomsResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []WaitingRoom{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// WaitingRoom fetches detail about one Waiting room for a zone. -// -// API reference: https://api.cloudflare.com/#waiting-room-waiting-room-details -func (api *API) WaitingRoom(ctx context.Context, zoneID, waitingRoomID string) (WaitingRoom, error) { - uri := fmt.Sprintf("/zones/%s/waiting_rooms/%s", zoneID, waitingRoomID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return WaitingRoom{}, err - } - var r WaitingRoomDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WaitingRoom{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ChangeWaitingRoom lets you change individual settings for a Waiting room. This is -// in contrast to UpdateWaitingRoom which replaces the entire Waiting room. -// -// API reference: https://api.cloudflare.com/#waiting-room-update-waiting-room -func (api *API) ChangeWaitingRoom(ctx context.Context, zoneID, waitingRoomID string, waitingRoom WaitingRoom) (WaitingRoom, error) { - uri := fmt.Sprintf("/zones/%s/waiting_rooms/%s", zoneID, waitingRoomID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, waitingRoom) - if err != nil { - return WaitingRoom{}, err - } - var r WaitingRoomDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WaitingRoom{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateWaitingRoom lets you replace a Waiting Room. This is in contrast to -// ChangeWaitingRoom which lets you change individual settings. -// -// API reference: https://api.cloudflare.com/#waiting-room-update-waiting-room -func (api *API) UpdateWaitingRoom(ctx context.Context, zoneID string, waitingRoom WaitingRoom) (WaitingRoom, error) { - uri := fmt.Sprintf("/zones/%s/waiting_rooms/%s", zoneID, waitingRoom.ID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, waitingRoom) - if err != nil { - return WaitingRoom{}, err - } - var r WaitingRoomDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WaitingRoom{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteWaitingRoom deletes a Waiting Room for a zone. -// -// API reference: https://api.cloudflare.com/#waiting-room-delete-waiting-room -func (api *API) DeleteWaitingRoom(ctx context.Context, zoneID, waitingRoomID string) error { - uri := fmt.Sprintf("/zones/%s/waiting_rooms/%s", zoneID, waitingRoomID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return err - } - var r WaitingRoomDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/workers.go b/vendor/github.com/cloudflare/cloudflare-go/workers.go deleted file mode 100644 index 5710b345..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/workers.go +++ /dev/null @@ -1,750 +0,0 @@ -package cloudflare - -import ( - "bytes" - "context" - "encoding/hex" - "encoding/json" - "fmt" - "io" - "math/rand" - "mime/multipart" - "net/http" - "net/textproto" - "time" - - "github.com/pkg/errors" -) - -// WorkerRequestParams provides parameters for worker requests for both enterprise and standard requests -type WorkerRequestParams struct { - ZoneID string - ScriptName string -} - -// WorkerScriptParams provides a worker script and the associated bindings -type WorkerScriptParams struct { - Script string - - // Bindings should be a map where the keys are the binding name, and the - // values are the binding content - Bindings map[string]WorkerBinding -} - -// WorkerRoute is used to map traffic matching a URL pattern to a workers -// -// API reference: https://api.cloudflare.com/#worker-routes-properties -type WorkerRoute struct { - ID string `json:"id,omitempty"` - Pattern string `json:"pattern"` - Enabled bool `json:"enabled"` // this is deprecated: https://api.cloudflare.com/#worker-filters-deprecated--properties - Script string `json:"script,omitempty"` -} - -// WorkerRoutesResponse embeds Response struct and slice of WorkerRoutes -type WorkerRoutesResponse struct { - Response - Routes []WorkerRoute `json:"result"` -} - -// WorkerRouteResponse embeds Response struct and a single WorkerRoute -type WorkerRouteResponse struct { - Response - WorkerRoute `json:"result"` -} - -// WorkerScript Cloudflare Worker struct with metadata -type WorkerScript struct { - WorkerMetaData - Script string `json:"script"` -} - -// WorkerMetaData contains worker script information such as size, creation & modification dates -type WorkerMetaData struct { - ID string `json:"id,omitempty"` - ETAG string `json:"etag,omitempty"` - Size int `json:"size,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` - ModifiedOn time.Time `json:"modified_on,omitempty"` -} - -// WorkerListResponse wrapper struct for API response to worker script list API call -type WorkerListResponse struct { - Response - WorkerList []WorkerMetaData `json:"result"` -} - -// WorkerScriptResponse wrapper struct for API response to worker script calls -type WorkerScriptResponse struct { - Response - WorkerScript `json:"result"` -} - -// WorkerBindingType represents a particular type of binding -type WorkerBindingType string - -func (b WorkerBindingType) String() string { - return string(b) -} - -const ( - // WorkerInheritBindingType is the type for inherited bindings - WorkerInheritBindingType WorkerBindingType = "inherit" - // WorkerKvNamespaceBindingType is the type for KV Namespace bindings - WorkerKvNamespaceBindingType WorkerBindingType = "kv_namespace" - // WorkerWebAssemblyBindingType is the type for Web Assembly module bindings - WorkerWebAssemblyBindingType WorkerBindingType = "wasm_module" - // WorkerSecretTextBindingType is the type for secret text bindings - WorkerSecretTextBindingType WorkerBindingType = "secret_text" - // WorkerPlainTextBindingType is the type for plain text bindings - WorkerPlainTextBindingType WorkerBindingType = "plain_text" -) - -// WorkerBindingListItem a struct representing an individual binding in a list of bindings -type WorkerBindingListItem struct { - Name string `json:"name"` - Binding WorkerBinding -} - -// WorkerBindingListResponse wrapper struct for API response to worker binding list API call -type WorkerBindingListResponse struct { - Response - BindingList []WorkerBindingListItem -} - -// Workers supports multiple types of bindings, e.g. KV namespaces or WebAssembly modules, and each type -// of binding will be represented differently in the upload request body. At a high-level, every binding -// will specify metadata, which is a JSON object with the properties "name" and "type". Some types of bindings -// will also have additional metadata properties. For example, KV bindings also specify the KV namespace. -// In addition to the metadata, some binding types may need to include additional data as part of the -// multipart form. For example, WebAssembly bindings will include the contents of the WebAssembly module. - -// WorkerBinding is the generic interface implemented by all of -// the various binding types -type WorkerBinding interface { - Type() WorkerBindingType - - // serialize is responsible for returning the binding metadata as well as an optionally - // returning a function that can modify the multipart form body. For example, this is used - // by WebAssembly bindings to add a new part containing the WebAssembly module contents. - serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) -} - -// workerBindingMeta is the metadata portion of the binding -type workerBindingMeta = map[string]interface{} - -// workerBindingBodyWriter allows for a binding to add additional parts to the multipart body -type workerBindingBodyWriter func(*multipart.Writer) error - -// WorkerInheritBinding will just persist whatever binding content was previously uploaded -type WorkerInheritBinding struct { - // Optional parameter that allows for renaming a binding without changing - // its contents. If `OldName` is empty, the binding name will not be changed. - OldName string -} - -// Type returns the type of the binding -func (b WorkerInheritBinding) Type() WorkerBindingType { - return WorkerInheritBindingType -} - -func (b WorkerInheritBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) { - meta := workerBindingMeta{ - "name": bindingName, - "type": b.Type(), - } - - if b.OldName != "" { - meta["old_name"] = b.OldName - } - - return meta, nil, nil -} - -// WorkerKvNamespaceBinding is a binding to a Workers KV Namespace -// -// https://developers.cloudflare.com/workers/archive/api/resource-bindings/kv-namespaces/ -type WorkerKvNamespaceBinding struct { - NamespaceID string -} - -// Type returns the type of the binding -func (b WorkerKvNamespaceBinding) Type() WorkerBindingType { - return WorkerKvNamespaceBindingType -} - -func (b WorkerKvNamespaceBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) { - if b.NamespaceID == "" { - return nil, nil, errors.Errorf(`NamespaceID for binding "%s" cannot be empty`, bindingName) - } - - return workerBindingMeta{ - "name": bindingName, - "type": b.Type(), - "namespace_id": b.NamespaceID, - }, nil, nil -} - -// WorkerWebAssemblyBinding is a binding to a WebAssembly module -// -// https://developers.cloudflare.com/workers/archive/api/resource-bindings/webassembly-modules/ -type WorkerWebAssemblyBinding struct { - Module io.Reader -} - -// Type returns the type of the binding -func (b WorkerWebAssemblyBinding) Type() WorkerBindingType { - return WorkerWebAssemblyBindingType -} - -func (b WorkerWebAssemblyBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) { - partName := getRandomPartName() - - bodyWriter := func(mpw *multipart.Writer) error { - var hdr = textproto.MIMEHeader{} - hdr.Set("content-disposition", fmt.Sprintf(`form-data; name="%s"`, partName)) - hdr.Set("content-type", "application/wasm") - pw, err := mpw.CreatePart(hdr) - if err != nil { - return err - } - _, err = io.Copy(pw, b.Module) - return err - } - - return workerBindingMeta{ - "name": bindingName, - "type": b.Type(), - "part": partName, - }, bodyWriter, nil -} - -// WorkerPlainTextBinding is a binding to plain text -// -// https://developers.cloudflare.com/workers/tooling/api/scripts/#add-a-plain-text-binding -type WorkerPlainTextBinding struct { - Text string -} - -// Type returns the type of the binding -func (b WorkerPlainTextBinding) Type() WorkerBindingType { - return WorkerPlainTextBindingType -} - -func (b WorkerPlainTextBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) { - if b.Text == "" { - return nil, nil, errors.Errorf(`Text for binding "%s" cannot be empty`, bindingName) - } - - return workerBindingMeta{ - "name": bindingName, - "type": b.Type(), - "text": b.Text, - }, nil, nil -} - -// WorkerSecretTextBinding is a binding to secret text -// -// https://developers.cloudflare.com/workers/tooling/api/scripts/#add-a-secret-text-binding -type WorkerSecretTextBinding struct { - Text string -} - -// Type returns the type of the binding -func (b WorkerSecretTextBinding) Type() WorkerBindingType { - return WorkerSecretTextBindingType -} - -func (b WorkerSecretTextBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) { - if b.Text == "" { - return nil, nil, errors.Errorf(`Text for binding "%s" cannot be empty`, bindingName) - } - - return workerBindingMeta{ - "name": bindingName, - "type": b.Type(), - "text": b.Text, - }, nil, nil -} - -// Each binding that adds a part to the multipart form body will need -// a unique part name so we just generate a random 128bit hex string -func getRandomPartName() string { - randBytes := make([]byte, 16) - rand.Read(randBytes) - return hex.EncodeToString(randBytes) -} - -// DeleteWorker deletes worker for a zone. -// -// API reference: https://api.cloudflare.com/#worker-script-delete-worker -func (api *API) DeleteWorker(ctx context.Context, requestParams *WorkerRequestParams) (WorkerScriptResponse, error) { - // if ScriptName is provided we will treat as org request - if requestParams.ScriptName != "" { - return api.deleteWorkerWithName(ctx, requestParams.ScriptName) - } - uri := fmt.Sprintf("/zones/%s/workers/script", requestParams.ZoneID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - var r WorkerScriptResponse - if err != nil { - return r, err - } - err = json.Unmarshal(res, &r) - if err != nil { - return r, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// DeleteWorkerWithName deletes worker for a zone. -// Sccount must be specified as api option https://godoc.org/github.com/cloudflare/cloudflare-go#UsingAccount -// -// API reference: https://developers.cloudflare.com/workers/tooling/api/scripts/ -func (api *API) deleteWorkerWithName(ctx context.Context, scriptName string) (WorkerScriptResponse, error) { - if api.AccountID == "" { - return WorkerScriptResponse{}, errors.New("account ID required") - } - uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s", api.AccountID, scriptName) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - var r WorkerScriptResponse - if err != nil { - return r, err - } - err = json.Unmarshal(res, &r) - if err != nil { - return r, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// DownloadWorker fetch raw script content for your worker returns []byte containing worker code js -// -// API reference: https://api.cloudflare.com/#worker-script-download-worker -func (api *API) DownloadWorker(ctx context.Context, requestParams *WorkerRequestParams) (WorkerScriptResponse, error) { - if requestParams.ScriptName != "" { - return api.downloadWorkerWithName(ctx, requestParams.ScriptName) - } - uri := fmt.Sprintf("/zones/%s/workers/script", requestParams.ZoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - var r WorkerScriptResponse - if err != nil { - return r, err - } - r.Script = string(res) - r.Success = true - return r, nil -} - -// DownloadWorkerWithName fetch raw script content for your worker returns string containing worker code js -// -// API reference: https://developers.cloudflare.com/workers/tooling/api/scripts/ -func (api *API) downloadWorkerWithName(ctx context.Context, scriptName string) (WorkerScriptResponse, error) { - if api.AccountID == "" { - return WorkerScriptResponse{}, errors.New("account ID required") - } - uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s", api.AccountID, scriptName) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - var r WorkerScriptResponse - if err != nil { - return r, err - } - r.Script = string(res) - r.Success = true - return r, nil -} - -// ListWorkerBindings returns all the bindings for a particular worker -func (api *API) ListWorkerBindings(ctx context.Context, requestParams *WorkerRequestParams) (WorkerBindingListResponse, error) { - if requestParams.ScriptName == "" { - return WorkerBindingListResponse{}, errors.New("ScriptName is required") - } - if api.AccountID == "" { - return WorkerBindingListResponse{}, errors.New("account ID required") - } - - uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/bindings", api.AccountID, requestParams.ScriptName) - - var jsonRes struct { - Response - Bindings []workerBindingMeta `json:"result"` - } - var r WorkerBindingListResponse - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return r, err - } - err = json.Unmarshal(res, &jsonRes) - if err != nil { - return r, errors.Wrap(err, errUnmarshalError) - } - - r = WorkerBindingListResponse{ - Response: jsonRes.Response, - BindingList: make([]WorkerBindingListItem, 0, len(jsonRes.Bindings)), - } - for _, jsonBinding := range jsonRes.Bindings { - name, ok := jsonBinding["name"].(string) - if !ok { - return r, errors.Errorf("Binding missing name %v", jsonBinding) - } - bType, ok := jsonBinding["type"].(string) - if !ok { - return r, errors.Errorf("Binding missing type %v", jsonBinding) - } - bindingListItem := WorkerBindingListItem{ - Name: name, - } - - switch WorkerBindingType(bType) { - case WorkerKvNamespaceBindingType: - namespaceID := jsonBinding["namespace_id"].(string) - bindingListItem.Binding = WorkerKvNamespaceBinding{ - NamespaceID: namespaceID, - } - case WorkerWebAssemblyBindingType: - bindingListItem.Binding = WorkerWebAssemblyBinding{ - Module: &bindingContentReader{ - api: api, - requestParams: requestParams, - bindingName: name, - }, - } - case WorkerPlainTextBindingType: - text := jsonBinding["text"].(string) - bindingListItem.Binding = WorkerPlainTextBinding{ - Text: text, - } - case WorkerSecretTextBindingType: - bindingListItem.Binding = WorkerSecretTextBinding{} - default: - bindingListItem.Binding = WorkerInheritBinding{} - } - r.BindingList = append(r.BindingList, bindingListItem) - } - - return r, nil -} - -// bindingContentReader is an io.Reader that will lazily load the -// raw bytes for a binding from the API when the Read() method -// is first called. This is only useful for binding types -// that store raw bytes, like WebAssembly modules -type bindingContentReader struct { - api *API - requestParams *WorkerRequestParams - bindingName string - content []byte - position int -} - -func (b *bindingContentReader) Read(p []byte) (n int, err error) { - // Lazily load the content when Read() is first called - if b.content == nil { - uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/bindings/%s/content", b.api.AccountID, b.requestParams.ScriptName, b.bindingName) - res, err := b.api.makeRequest(http.MethodGet, uri, nil) - if err != nil { - return 0, err - } - b.content = res - } - - if b.position >= len(b.content) { - return 0, io.EOF - } - - bytesRemaining := len(b.content) - b.position - bytesToProcess := 0 - if len(p) < bytesRemaining { - bytesToProcess = len(p) - } else { - bytesToProcess = bytesRemaining - } - - for i := 0; i < bytesToProcess; i++ { - p[i] = b.content[b.position] - b.position = b.position + 1 - } - - return bytesToProcess, nil -} - -// ListWorkerScripts returns list of worker scripts for given account. -// -// API reference: https://developers.cloudflare.com/workers/tooling/api/scripts/ -func (api *API) ListWorkerScripts(ctx context.Context) (WorkerListResponse, error) { - if api.AccountID == "" { - return WorkerListResponse{}, errors.New("account ID required") - } - uri := fmt.Sprintf("/accounts/%s/workers/scripts", api.AccountID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return WorkerListResponse{}, err - } - var r WorkerListResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WorkerListResponse{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// UploadWorker push raw script content for your worker. -// -// API reference: https://api.cloudflare.com/#worker-script-upload-worker -func (api *API) UploadWorker(ctx context.Context, requestParams *WorkerRequestParams, data string) (WorkerScriptResponse, error) { - if requestParams.ScriptName != "" { - return api.uploadWorkerWithName(ctx, requestParams.ScriptName, "application/javascript", []byte(data)) - } - return api.uploadWorkerForZone(ctx, requestParams.ZoneID, "application/javascript", []byte(data)) -} - -// UploadWorkerWithBindings push raw script content and bindings for your worker -// -// API reference: https://api.cloudflare.com/#worker-script-upload-worker -func (api *API) UploadWorkerWithBindings(ctx context.Context, requestParams *WorkerRequestParams, data *WorkerScriptParams) (WorkerScriptResponse, error) { - contentType, body, err := formatMultipartBody(data) - if err != nil { - return WorkerScriptResponse{}, err - } - if requestParams.ScriptName != "" { - return api.uploadWorkerWithName(ctx, requestParams.ScriptName, contentType, body) - } - return api.uploadWorkerForZone(ctx, requestParams.ZoneID, contentType, body) -} - -func (api *API) uploadWorkerForZone(ctx context.Context, zoneID, contentType string, body []byte) (WorkerScriptResponse, error) { - uri := fmt.Sprintf("/zones/%s/workers/script", zoneID) - headers := make(http.Header) - headers.Set("Content-Type", contentType) - res, err := api.makeRequestContextWithHeaders(ctx, http.MethodPut, uri, body, headers) - var r WorkerScriptResponse - if err != nil { - return r, err - } - err = json.Unmarshal(res, &r) - if err != nil { - return r, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -func (api *API) uploadWorkerWithName(ctx context.Context, scriptName, contentType string, body []byte) (WorkerScriptResponse, error) { - if api.AccountID == "" { - return WorkerScriptResponse{}, errors.New("account ID required") - } - uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s", api.AccountID, scriptName) - headers := make(http.Header) - headers.Set("Content-Type", contentType) - res, err := api.makeRequestContextWithHeaders(ctx, http.MethodPut, uri, body, headers) - var r WorkerScriptResponse - if err != nil { - return r, err - } - err = json.Unmarshal(res, &r) - if err != nil { - return r, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// Returns content-type, body, error -func formatMultipartBody(params *WorkerScriptParams) (string, []byte, error) { - var buf = &bytes.Buffer{} - var mpw = multipart.NewWriter(buf) - defer mpw.Close() - - // Write metadata part - scriptPartName := "script" - meta := struct { - BodyPart string `json:"body_part"` - Bindings []workerBindingMeta `json:"bindings"` - }{ - BodyPart: scriptPartName, - Bindings: make([]workerBindingMeta, 0, len(params.Bindings)), - } - - bodyWriters := make([]workerBindingBodyWriter, 0, len(params.Bindings)) - for name, b := range params.Bindings { - bindingMeta, bodyWriter, err := b.serialize(name) - if err != nil { - return "", nil, err - } - - meta.Bindings = append(meta.Bindings, bindingMeta) - bodyWriters = append(bodyWriters, bodyWriter) - } - - var hdr = textproto.MIMEHeader{} - hdr.Set("content-disposition", fmt.Sprintf(`form-data; name="%s"`, "metadata")) - hdr.Set("content-type", "application/json") - pw, err := mpw.CreatePart(hdr) - if err != nil { - return "", nil, err - } - metaJSON, err := json.Marshal(meta) - if err != nil { - return "", nil, err - } - _, err = pw.Write(metaJSON) - if err != nil { - return "", nil, err - } - - // Write script part - hdr = textproto.MIMEHeader{} - hdr.Set("content-disposition", fmt.Sprintf(`form-data; name="%s"`, scriptPartName)) - hdr.Set("content-type", "application/javascript") - pw, err = mpw.CreatePart(hdr) - if err != nil { - return "", nil, err - } - _, err = pw.Write([]byte(params.Script)) - if err != nil { - return "", nil, err - } - - // Write other bindings with parts - for _, w := range bodyWriters { - if w != nil { - err = w(mpw) - if err != nil { - return "", nil, err - } - } - } - - mpw.Close() - - return mpw.FormDataContentType(), buf.Bytes(), nil -} - -// CreateWorkerRoute creates worker route for a zone -// -// API reference: https://api.cloudflare.com/#worker-filters-create-filter, https://api.cloudflare.com/#worker-routes-create-route -func (api *API) CreateWorkerRoute(ctx context.Context, zoneID string, route WorkerRoute) (WorkerRouteResponse, error) { - pathComponent, err := getRouteEndpoint(api, route) - if err != nil { - return WorkerRouteResponse{}, err - } - - uri := fmt.Sprintf("/zones/%s/workers/%s", zoneID, pathComponent) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, route) - if err != nil { - return WorkerRouteResponse{}, err - } - var r WorkerRouteResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WorkerRouteResponse{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// DeleteWorkerRoute deletes worker route for a zone -// -// API reference: https://api.cloudflare.com/#worker-routes-delete-route -func (api *API) DeleteWorkerRoute(ctx context.Context, zoneID string, routeID string) (WorkerRouteResponse, error) { - uri := fmt.Sprintf("/zones/%s/workers/routes/%s", zoneID, routeID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return WorkerRouteResponse{}, err - } - var r WorkerRouteResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WorkerRouteResponse{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// ListWorkerRoutes returns list of worker routes -// -// API reference: https://api.cloudflare.com/#worker-filters-list-filters, https://api.cloudflare.com/#worker-routes-list-routes -func (api *API) ListWorkerRoutes(ctx context.Context, zoneID string) (WorkerRoutesResponse, error) { - pathComponent := "filters" - // Unfortunately we don't have a good signal of whether the user is wanting - // to use the deprecated filters endpoint (https://api.cloudflare.com/#worker-filters-list-filters) - // or the multi-script routes endpoint (https://api.cloudflare.com/#worker-script-list-workers) - // - // The filters endpoint does not support API tokens, so if an API token is specified we need to use - // the routes endpoint. Otherwise, since the multi-script API endpoints that operate on a script - // require an AccountID, we assume that anyone specifying an AccountID is using the routes endpoint. - // This is likely too presumptuous. In the next major version, we should just remove the deprecated - // filter endpoints entirely to avoid this ambiguity. - if api.AccountID != "" || api.APIToken != "" { - pathComponent = "routes" - } - uri := fmt.Sprintf("/zones/%s/workers/%s", zoneID, pathComponent) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return WorkerRoutesResponse{}, err - } - var r WorkerRoutesResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WorkerRoutesResponse{}, errors.Wrap(err, errUnmarshalError) - } - for i := range r.Routes { - route := &r.Routes[i] - // The Enabled flag will not be set in the multi-script API response - // so we manually set it to true if the script name is not empty - // in case any multi-script customers rely on the Enabled field - if route.Script != "" { - route.Enabled = true - } - } - return r, nil -} - -// GetWorkerRoute returns a worker route. -// -// API reference: https://api.cloudflare.com/#worker-routes-get-route -func (api *API) GetWorkerRoute(ctx context.Context, zoneID string, routeID string) (WorkerRouteResponse, error) { - uri := fmt.Sprintf("/zones/%s/workers/routes/%s", zoneID, routeID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return WorkerRouteResponse{}, err - } - var r WorkerRouteResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WorkerRouteResponse{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// UpdateWorkerRoute updates worker route for a zone. -// -// API reference: https://api.cloudflare.com/#worker-filters-update-filter, https://api.cloudflare.com/#worker-routes-update-route -func (api *API) UpdateWorkerRoute(ctx context.Context, zoneID string, routeID string, route WorkerRoute) (WorkerRouteResponse, error) { - pathComponent, err := getRouteEndpoint(api, route) - if err != nil { - return WorkerRouteResponse{}, err - } - uri := fmt.Sprintf("/zones/%s/workers/%s/%s", zoneID, pathComponent, routeID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, route) - if err != nil { - return WorkerRouteResponse{}, err - } - var r WorkerRouteResponse - err = json.Unmarshal(res, &r) - if err != nil { - return WorkerRouteResponse{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -func getRouteEndpoint(api *API, route WorkerRoute) (string, error) { - if route.Script != "" && route.Enabled { - return "", errors.New("Only `Script` or `Enabled` may be specified for a WorkerRoute, not both") - } - - // For backwards-compatibility, fallback to the deprecated filter - // endpoint if Enabled == true - // https://api.cloudflare.com/#worker-filters-deprecated--properties - if route.Enabled { - return "filters", nil - } - - return "routes", nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/workers_cron_triggers.go b/vendor/github.com/cloudflare/cloudflare-go/workers_cron_triggers.go deleted file mode 100644 index 09427bb7..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/workers_cron_triggers.go +++ /dev/null @@ -1,75 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "time" - - "github.com/pkg/errors" -) - -// WorkerCronTriggerResponse represents the response from the Worker cron trigger -// API endpoint. -type WorkerCronTriggerResponse struct { - Response - Result WorkerCronTriggerSchedules `json:"result"` -} - -// WorkerCronTriggerSchedules contains the schedule of Worker cron triggers. -type WorkerCronTriggerSchedules struct { - Schedules []WorkerCronTrigger `json:"schedules"` -} - -// WorkerCronTrigger holds an individual cron schedule for a worker. -type WorkerCronTrigger struct { - Cron string `json:"cron"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` -} - -// ListWorkerCronTriggers fetches all available cron triggers for a single Worker -// script. -// -// API reference: https://api.cloudflare.com/#worker-cron-trigger-get-cron-triggers -func (api *API) ListWorkerCronTriggers(ctx context.Context, scriptName string) ([]WorkerCronTrigger, error) { - if err := api.checkAccountID(); err != nil { - return []WorkerCronTrigger{}, err - } - - uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/schedules", api.AccountID, scriptName) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []WorkerCronTrigger{}, err - } - - result := WorkerCronTriggerResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return []WorkerCronTrigger{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result.Schedules, err -} - -// UpdateWorkerCronTriggers updates a single schedule for a Worker cron trigger. -// -// API reference: https://api.cloudflare.com/#worker-cron-trigger-update-cron-triggers -func (api *API) UpdateWorkerCronTriggers(ctx context.Context, scriptName string, crons []WorkerCronTrigger) ([]WorkerCronTrigger, error) { - if err := api.checkAccountID(); err != nil { - return []WorkerCronTrigger{}, err - } - - uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/schedules", api.AccountID, scriptName) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, crons) - if err != nil { - return []WorkerCronTrigger{}, err - } - - result := WorkerCronTriggerResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return []WorkerCronTrigger{}, errors.Wrap(err, errUnmarshalError) - } - - return result.Result.Schedules, err -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/workers_kv.go b/vendor/github.com/cloudflare/cloudflare-go/workers_kv.go deleted file mode 100644 index ed5fbd0e..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/workers_kv.go +++ /dev/null @@ -1,307 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// WorkersKVNamespaceRequest provides parameters for creating and updating storage namespaces -type WorkersKVNamespaceRequest struct { - Title string `json:"title"` -} - -// WorkersKVPair is used in an array in the request to the bulk KV api -type WorkersKVPair struct { - Key string `json:"key"` - Value string `json:"value"` - Expiration int `json:"expiration,omitempty"` - ExpirationTTL int `json:"expiration_ttl,omitempty"` - Metadata interface{} `json:"metadata,omitempty"` - Base64 bool `json:"base64,omitempty"` -} - -// WorkersKVBulkWriteRequest is the request to the bulk KV api -type WorkersKVBulkWriteRequest []*WorkersKVPair - -// WorkersKVNamespaceResponse is the response received when creating storage namespaces -type WorkersKVNamespaceResponse struct { - Response - Result WorkersKVNamespace `json:"result"` -} - -// WorkersKVNamespace contains the unique identifier and title of a storage namespace -type WorkersKVNamespace struct { - ID string `json:"id"` - Title string `json:"title"` -} - -// ListWorkersKVNamespacesResponse contains a slice of storage namespaces associated with an -// account, pagination information, and an embedded response struct -type ListWorkersKVNamespacesResponse struct { - Response - Result []WorkersKVNamespace `json:"result"` - ResultInfo `json:"result_info"` -} - -// StorageKey is a key name used to identify a storage value -type StorageKey struct { - Name string `json:"name"` - Expiration int `json:"expiration"` - Metadata interface{} `json:"metadata"` -} - -// ListWorkersKVsOptions contains optional parameters for listing a namespace's keys -type ListWorkersKVsOptions struct { - Limit *int - Cursor *string - Prefix *string -} - -// ListStorageKeysResponse contains a slice of keys belonging to a storage namespace, -// pagination information, and an embedded response struct -type ListStorageKeysResponse struct { - Response - Result []StorageKey `json:"result"` - ResultInfo `json:"result_info"` -} - -// CreateWorkersKVNamespace creates a namespace under the given title. -// A 400 is returned if the account already owns a namespace with this title. -// A namespace must be explicitly deleted to be replaced. -// -// API reference: https://api.cloudflare.com/#workers-kv-namespace-create-a-namespace -func (api *API) CreateWorkersKVNamespace(ctx context.Context, req *WorkersKVNamespaceRequest) (WorkersKVNamespaceResponse, error) { - uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces", api.AccountID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, req) - if err != nil { - return WorkersKVNamespaceResponse{}, err - } - - result := WorkersKVNamespaceResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - - return result, err -} - -// ListWorkersKVNamespaces lists storage namespaces -// -// API reference: https://api.cloudflare.com/#workers-kv-namespace-list-namespaces -func (api *API) ListWorkersKVNamespaces(ctx context.Context) ([]WorkersKVNamespace, error) { - v := url.Values{} - v.Set("per_page", "100") - - var namespaces []WorkersKVNamespace - page := 1 - - for { - v.Set("page", strconv.Itoa(page)) - uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces?%s", api.AccountID, v.Encode()) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []WorkersKVNamespace{}, err - } - - var p ListWorkersKVNamespacesResponse - if err := json.Unmarshal(res, &p); err != nil { - return []WorkersKVNamespace{}, errors.Wrap(err, errUnmarshalError) - } - - if !p.Success { - return []WorkersKVNamespace{}, errors.New(errRequestNotSuccessful) - } - - namespaces = append(namespaces, p.Result...) - if p.ResultInfo.Page >= p.ResultInfo.TotalPages { - break - } - - page++ - } - - return namespaces, nil -} - -// DeleteWorkersKVNamespace deletes the namespace corresponding to the given ID -// -// API reference: https://api.cloudflare.com/#workers-kv-namespace-remove-a-namespace -func (api *API) DeleteWorkersKVNamespace(ctx context.Context, namespaceID string) (Response, error) { - uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces/%s", api.AccountID, namespaceID) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return Response{}, err - } - - result := Response{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - - return result, err -} - -// UpdateWorkersKVNamespace modifies a namespace's title -// -// API reference: https://api.cloudflare.com/#workers-kv-namespace-rename-a-namespace -func (api *API) UpdateWorkersKVNamespace(ctx context.Context, namespaceID string, req *WorkersKVNamespaceRequest) (Response, error) { - uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces/%s", api.AccountID, namespaceID) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, req) - if err != nil { - return Response{}, err - } - - result := Response{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - - return result, err -} - -// WriteWorkersKV writes a value identified by a key. -// -// API reference: https://api.cloudflare.com/#workers-kv-namespace-write-key-value-pair -func (api *API) WriteWorkersKV(ctx context.Context, namespaceID, key string, value []byte) (Response, error) { - key = url.PathEscape(key) - uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces/%s/values/%s", api.AccountID, namespaceID, key) - res, err := api.makeRequestWithHeaders( - http.MethodPut, uri, value, http.Header{"Content-Type": []string{"application/octet-stream"}}, - ) - if err != nil { - return Response{}, err - } - - result := Response{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - - return result, err -} - -// WriteWorkersKVBulk writes multiple KVs at once. -// -// API reference: https://api.cloudflare.com/#workers-kv-namespace-write-multiple-key-value-pairs -func (api *API) WriteWorkersKVBulk(ctx context.Context, namespaceID string, kvs WorkersKVBulkWriteRequest) (Response, error) { - uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces/%s/bulk", api.AccountID, namespaceID) - res, err := api.makeRequestWithHeaders( - http.MethodPut, uri, kvs, http.Header{"Content-Type": []string{"application/json"}}, - ) - if err != nil { - return Response{}, err - } - - result := Response{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - - return result, err -} - -// ReadWorkersKV returns the value associated with the given key in the given namespace -// -// API reference: https://api.cloudflare.com/#workers-kv-namespace-read-key-value-pair -func (api API) ReadWorkersKV(ctx context.Context, namespaceID, key string) ([]byte, error) { - key = url.PathEscape(key) - uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces/%s/values/%s", api.AccountID, namespaceID, key) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - return res, nil -} - -// DeleteWorkersKV deletes a key and value for a provided storage namespace -// -// API reference: https://api.cloudflare.com/#workers-kv-namespace-delete-key-value-pair -func (api API) DeleteWorkersKV(ctx context.Context, namespaceID, key string) (Response, error) { - key = url.PathEscape(key) - uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces/%s/values/%s", api.AccountID, namespaceID, key) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return Response{}, err - } - - result := Response{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - return result, err -} - -// DeleteWorkersKVBulk deletes multiple KVs at once. -// -// API reference: https://api.cloudflare.com/#workers-kv-namespace-delete-multiple-key-value-pairs -func (api *API) DeleteWorkersKVBulk(ctx context.Context, namespaceID string, keys []string) (Response, error) { - uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces/%s/bulk", api.AccountID, namespaceID) - res, err := api.makeRequestWithHeaders( - http.MethodDelete, uri, keys, http.Header{"Content-Type": []string{"application/json"}}, - ) - if err != nil { - return Response{}, err - } - - result := Response{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - - return result, err -} - -// ListWorkersKVs lists a namespace's keys -// -// API Reference: https://api.cloudflare.com/#workers-kv-namespace-list-a-namespace-s-keys -func (api API) ListWorkersKVs(ctx context.Context, namespaceID string) (ListStorageKeysResponse, error) { - uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces/%s/keys", api.AccountID, namespaceID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return ListStorageKeysResponse{}, err - } - - result := ListStorageKeysResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - return result, err -} - -// encode encodes non-nil fields into URL encoded form. -func (o ListWorkersKVsOptions) encode() string { - v := url.Values{} - if o.Limit != nil { - v.Set("limit", strconv.Itoa(*o.Limit)) - } - if o.Cursor != nil { - v.Set("cursor", *o.Cursor) - } - if o.Prefix != nil { - v.Set("prefix", *o.Prefix) - } - return v.Encode() -} - -// ListWorkersKVsWithOptions lists a namespace's keys with optional parameters -// -// API Reference: https://api.cloudflare.com/#workers-kv-namespace-list-a-namespace-s-keys -func (api API) ListWorkersKVsWithOptions(ctx context.Context, namespaceID string, o ListWorkersKVsOptions) (ListStorageKeysResponse, error) { - uri := fmt.Sprintf("/accounts/%s/storage/kv/namespaces/%s/keys?%s", api.AccountID, namespaceID, o.encode()) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return ListStorageKeysResponse{}, err - } - - result := ListStorageKeysResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - return result, err -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/workers_secrets.go b/vendor/github.com/cloudflare/cloudflare-go/workers_secrets.go deleted file mode 100644 index 973d3fc5..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/workers_secrets.go +++ /dev/null @@ -1,86 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - - "github.com/pkg/errors" -) - -// WorkersPutSecretRequest provides parameters for creating and updating secrets -type WorkersPutSecretRequest struct { - Name string `json:"name"` - Text string `json:"text"` - Type WorkerBindingType `json:"type"` -} - -// WorkersSecret contains the name and type of the secret -type WorkersSecret struct { - Name string `json:"name"` - Type string `json:"secret_text"` -} - -// WorkersPutSecretResponse is the response received when creating or updating a secret -type WorkersPutSecretResponse struct { - Response - Result WorkersSecret `json:"result"` -} - -// WorkersListSecretsResponse is the response received when listing secrets -type WorkersListSecretsResponse struct { - Response - Result []WorkersSecret `json:"result"` -} - -// SetWorkersSecret creates or updates a secret -// API reference: https://api.cloudflare.com/ -func (api *API) SetWorkersSecret(ctx context.Context, script string, req *WorkersPutSecretRequest) (WorkersPutSecretResponse, error) { - uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/secrets", api.AccountID, script) - res, err := api.makeRequestContext(ctx, http.MethodPut, uri, req) - if err != nil { - return WorkersPutSecretResponse{}, err - } - - result := WorkersPutSecretResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - - return result, err -} - -// DeleteWorkersSecret deletes a secret -// API reference: https://api.cloudflare.com/ -func (api *API) DeleteWorkersSecret(ctx context.Context, script, secretName string) (Response, error) { - uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/secrets/%s", api.AccountID, script, secretName) - res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) - if err != nil { - return Response{}, err - } - - result := Response{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - - return result, err -} - -// ListWorkersSecrets lists secrets for a given worker -// API reference: https://api.cloudflare.com/ -func (api *API) ListWorkersSecrets(ctx context.Context, script string) (WorkersListSecretsResponse, error) { - uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/secrets", api.AccountID, script) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return WorkersListSecretsResponse{}, err - } - - result := WorkersListSecretsResponse{} - if err := json.Unmarshal(res, &result); err != nil { - return result, errors.Wrap(err, errUnmarshalError) - } - - return result, err -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/zone.go b/vendor/github.com/cloudflare/cloudflare-go/zone.go deleted file mode 100644 index eafaab0f..00000000 --- a/vendor/github.com/cloudflare/cloudflare-go/zone.go +++ /dev/null @@ -1,1010 +0,0 @@ -package cloudflare - -import ( - "context" - "encoding/json" - "fmt" - "net/http" - "net/url" - "strconv" - "sync" - "time" - - "github.com/pkg/errors" - "golang.org/x/net/idna" -) - -// Owner describes the resource owner. -type Owner struct { - ID string `json:"id"` - Email string `json:"email"` - Name string `json:"name"` - OwnerType string `json:"type"` -} - -// Zone describes a Cloudflare zone. -type Zone struct { - ID string `json:"id"` - Name string `json:"name"` - // DevMode contains the time in seconds until development expires (if - // positive) or since it expired (if negative). It will be 0 if never used. - DevMode int `json:"development_mode"` - OriginalNS []string `json:"original_name_servers"` - OriginalRegistrar string `json:"original_registrar"` - OriginalDNSHost string `json:"original_dnshost"` - CreatedOn time.Time `json:"created_on"` - ModifiedOn time.Time `json:"modified_on"` - NameServers []string `json:"name_servers"` - Owner Owner `json:"owner"` - Permissions []string `json:"permissions"` - Plan ZonePlan `json:"plan"` - PlanPending ZonePlan `json:"plan_pending,omitempty"` - Status string `json:"status"` - Paused bool `json:"paused"` - Type string `json:"type"` - Host struct { - Name string - Website string - } `json:"host"` - VanityNS []string `json:"vanity_name_servers"` - Betas []string `json:"betas"` - DeactReason string `json:"deactivation_reason"` - Meta ZoneMeta `json:"meta"` - Account Account `json:"account"` - VerificationKey string `json:"verification_key"` -} - -// ZoneMeta describes metadata about a zone. -type ZoneMeta struct { - // custom_certificate_quota is broken - sometimes it's a string, sometimes a number! - // CustCertQuota int `json:"custom_certificate_quota"` - PageRuleQuota int `json:"page_rule_quota"` - WildcardProxiable bool `json:"wildcard_proxiable"` - PhishingDetected bool `json:"phishing_detected"` -} - -// ZonePlan contains the plan information for a zone. -type ZonePlan struct { - ZonePlanCommon - IsSubscribed bool `json:"is_subscribed"` - CanSubscribe bool `json:"can_subscribe"` - LegacyID string `json:"legacy_id"` - LegacyDiscount bool `json:"legacy_discount"` - ExternallyManaged bool `json:"externally_managed"` -} - -// ZoneRatePlan contains the plan information for a zone. -type ZoneRatePlan struct { - ZonePlanCommon - Components []zoneRatePlanComponents `json:"components,omitempty"` -} - -// ZonePlanCommon contains fields used by various Plan endpoints -type ZonePlanCommon struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Price int `json:"price,omitempty"` - Currency string `json:"currency,omitempty"` - Frequency string `json:"frequency,omitempty"` -} - -type zoneRatePlanComponents struct { - Name string `json:"name"` - Default int `json:"Default"` - UnitPrice int `json:"unit_price"` -} - -// ZoneID contains only the zone ID. -type ZoneID struct { - ID string `json:"id"` -} - -// ZoneResponse represents the response from the Zone endpoint containing a single zone. -type ZoneResponse struct { - Response - Result Zone `json:"result"` -} - -// ZonesResponse represents the response from the Zone endpoint containing an array of zones. -type ZonesResponse struct { - Response - Result []Zone `json:"result"` - ResultInfo `json:"result_info"` -} - -// ZoneIDResponse represents the response from the Zone endpoint, containing only a zone ID. -type ZoneIDResponse struct { - Response - Result ZoneID `json:"result"` -} - -// AvailableZoneRatePlansResponse represents the response from the Available Rate Plans endpoint. -type AvailableZoneRatePlansResponse struct { - Response - Result []ZoneRatePlan `json:"result"` - ResultInfo `json:"result_info"` -} - -// AvailableZonePlansResponse represents the response from the Available Plans endpoint. -type AvailableZonePlansResponse struct { - Response - Result []ZonePlan `json:"result"` - ResultInfo -} - -// ZoneRatePlanResponse represents the response from the Plan Details endpoint. -type ZoneRatePlanResponse struct { - Response - Result ZoneRatePlan `json:"result"` -} - -// ZoneSetting contains settings for a zone. -type ZoneSetting struct { - ID string `json:"id"` - Editable bool `json:"editable"` - ModifiedOn string `json:"modified_on,omitempty"` - Value interface{} `json:"value"` - TimeRemaining int `json:"time_remaining"` -} - -// ZoneSettingResponse represents the response from the Zone Setting endpoint. -type ZoneSettingResponse struct { - Response - Result []ZoneSetting `json:"result"` -} - -// ZoneSettingSingleResponse represents the response from the Zone Setting endpoint for the specified setting. -type ZoneSettingSingleResponse struct { - Response - Result ZoneSetting `json:"result"` -} - -// ZoneSSLSetting contains ssl setting for a zone. -type ZoneSSLSetting struct { - ID string `json:"id"` - Editable bool `json:"editable"` - ModifiedOn string `json:"modified_on"` - Value string `json:"value"` - CertificateStatus string `json:"certificate_status"` -} - -// ZoneSSLSettingResponse represents the response from the Zone SSL Setting -// endpoint. -type ZoneSSLSettingResponse struct { - Response - Result ZoneSSLSetting `json:"result"` -} - -// ZoneAnalyticsData contains totals and timeseries analytics data for a zone. -type ZoneAnalyticsData struct { - Totals ZoneAnalytics `json:"totals"` - Timeseries []ZoneAnalytics `json:"timeseries"` -} - -// zoneAnalyticsDataResponse represents the response from the Zone Analytics Dashboard endpoint. -type zoneAnalyticsDataResponse struct { - Response - Result ZoneAnalyticsData `json:"result"` -} - -// ZoneAnalyticsColocation contains analytics data by datacenter. -type ZoneAnalyticsColocation struct { - ColocationID string `json:"colo_id"` - Timeseries []ZoneAnalytics `json:"timeseries"` -} - -// zoneAnalyticsColocationResponse represents the response from the Zone Analytics By Co-location endpoint. -type zoneAnalyticsColocationResponse struct { - Response - Result []ZoneAnalyticsColocation `json:"result"` -} - -// ZoneAnalytics contains analytics data for a zone. -type ZoneAnalytics struct { - Since time.Time `json:"since"` - Until time.Time `json:"until"` - Requests struct { - All int `json:"all"` - Cached int `json:"cached"` - Uncached int `json:"uncached"` - ContentType map[string]int `json:"content_type"` - Country map[string]int `json:"country"` - SSL struct { - Encrypted int `json:"encrypted"` - Unencrypted int `json:"unencrypted"` - } `json:"ssl"` - HTTPStatus map[string]int `json:"http_status"` - } `json:"requests"` - Bandwidth struct { - All int `json:"all"` - Cached int `json:"cached"` - Uncached int `json:"uncached"` - ContentType map[string]int `json:"content_type"` - Country map[string]int `json:"country"` - SSL struct { - Encrypted int `json:"encrypted"` - Unencrypted int `json:"unencrypted"` - } `json:"ssl"` - } `json:"bandwidth"` - Threats struct { - All int `json:"all"` - Country map[string]int `json:"country"` - Type map[string]int `json:"type"` - } `json:"threats"` - Pageviews struct { - All int `json:"all"` - SearchEngines map[string]int `json:"search_engines"` - } `json:"pageviews"` - Uniques struct { - All int `json:"all"` - } -} - -// ZoneAnalyticsOptions represents the optional parameters in Zone Analytics -// endpoint requests. -type ZoneAnalyticsOptions struct { - Since *time.Time - Until *time.Time - Continuous *bool -} - -// PurgeCacheRequest represents the request format made to the purge endpoint. -type PurgeCacheRequest struct { - Everything bool `json:"purge_everything,omitempty"` - // Purge by filepath (exact match). Limit of 30 - Files []string `json:"files,omitempty"` - // Purge by Tag (Enterprise only): - // https://support.cloudflare.com/hc/en-us/articles/206596608-How-to-Purge-Cache-Using-Cache-Tags-Enterprise-only- - Tags []string `json:"tags,omitempty"` - // Purge by hostname - e.g. "assets.example.com" - Hosts []string `json:"hosts,omitempty"` - // Purge by prefix - e.g. "example.com/css" - Prefixes []string `json:"prefixes,omitempty"` -} - -// PurgeCacheResponse represents the response from the purge endpoint. -type PurgeCacheResponse struct { - Response - Result struct { - ID string `json:"id"` - } `json:"result"` -} - -// newZone describes a new zone. -type newZone struct { - Name string `json:"name"` - JumpStart bool `json:"jump_start"` - Type string `json:"type"` - // We use a pointer to get a nil type when the field is empty. - // This allows us to completely omit this with json.Marshal(). - Account *Account `json:"organization,omitempty"` -} - -// FallbackOrigin describes a fallback origin -type FallbackOrigin struct { - Value string `json:"value"` - ID string `json:"id,omitempty"` -} - -// FallbackOriginResponse represents the response from the fallback_origin endpoint -type FallbackOriginResponse struct { - Response - Result FallbackOrigin `json:"result"` -} - -// zoneSubscriptionRatePlanPayload is used to build the JSON payload for -// setting a particular rate plan on an existing zone. -type zoneSubscriptionRatePlanPayload struct { - RatePlan struct { - ID string `json:"id"` - } `json:"rate_plan"` -} - -// CreateZone creates a zone on an account. -// -// Setting jumpstart to true will attempt to automatically scan for existing -// DNS records. Setting this to false will create the zone with no DNS records. -// -// If account is non-empty, it must have at least the ID field populated. -// This will add the new zone to the specified multi-user account. -// -// API reference: https://api.cloudflare.com/#zone-create-a-zone -func (api *API) CreateZone(ctx context.Context, name string, jumpstart bool, account Account, zoneType string) (Zone, error) { - var newzone newZone - newzone.Name = name - newzone.JumpStart = jumpstart - if account.ID != "" { - newzone.Account = &account - } - - if zoneType == "partial" { - newzone.Type = "partial" - } else { - newzone.Type = "full" - } - - res, err := api.makeRequestContext(ctx, http.MethodPost, "/zones", newzone) - if err != nil { - return Zone{}, err - } - - var r ZoneResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Zone{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneActivationCheck initiates another zone activation check for newly-created zones. -// -// API reference: https://api.cloudflare.com/#zone-initiate-another-zone-activation-check -func (api *API) ZoneActivationCheck(ctx context.Context, zoneID string) (Response, error) { - res, err := api.makeRequestContext(ctx, http.MethodPut, "/zones/"+zoneID+"/activation_check", nil) - if err != nil { - return Response{}, err - } - var r Response - err = json.Unmarshal(res, &r) - if err != nil { - return Response{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// ListZones lists zones on an account. Optionally takes a list of zone names -// to filter against. -// -// API reference: https://api.cloudflare.com/#zone-list-zones -func (api *API) ListZones(ctx context.Context, z ...string) ([]Zone, error) { - var zones []Zone - if len(z) > 0 { - var ( - v = url.Values{} - r ZonesResponse - ) - for _, zone := range z { - v.Set("name", normalizeZoneName(zone)) - res, err := api.makeRequestContext(ctx, http.MethodGet, "/zones?"+v.Encode(), nil) - if err != nil { - return []Zone{}, err - } - err = json.Unmarshal(res, &r) - if err != nil { - return []Zone{}, errors.Wrap(err, errUnmarshalError) - } - if !r.Success { - // TODO: Provide an actual error message instead of always returning nil - return []Zone{}, err - } - zones = append(zones, r.Result...) - } - } else { - res, err := api.ListZonesContext(ctx) - if err != nil { - return nil, err - } - - zones = res.Result - } - - return zones, nil -} - -const listZonesPerPage = 50 - -// listZonesFetch fetches one page of zones. -// This is placed as a separate function to prevent any possibility of unintended capturing. -func (api *API) listZonesFetch(ctx context.Context, wg *sync.WaitGroup, errc chan error, - path string, pageSize int, buf []Zone) { - defer wg.Done() - - // recordError sends the error to errc in a non-blocking manner - recordError := func(err error) { - select { - case errc <- err: - default: - } - } - - res, err := api.makeRequestContext(ctx, http.MethodGet, path, nil) - if err != nil { - recordError(err) - return - } - - var r ZonesResponse - err = json.Unmarshal(res, &r) - if err != nil { - recordError(err) - return - } - - if len(r.Result) != pageSize { - recordError(errors.New(errResultInfo)) - return - } - - copy(buf, r.Result) -} - -// ListZonesContext lists all zones on an account automatically handling the -// pagination. Optionally takes a list of ReqOptions. -func (api *API) ListZonesContext(ctx context.Context, opts ...ReqOption) (r ZonesResponse, err error) { - opt := reqOption{ - params: url.Values{}, - } - for _, of := range opts { - of(&opt) - } - - if opt.params.Get("page") != "" || opt.params.Get("per_page") != "" { - return ZonesResponse{}, errors.New(errManualPagination) - } - - opt.params.Add("per_page", strconv.Itoa(listZonesPerPage)) - - res, err := api.makeRequestContext(ctx, http.MethodGet, "/zones?"+opt.params.Encode(), nil) - if err != nil { - return ZonesResponse{}, err - } - err = json.Unmarshal(res, &r) - if err != nil { - return ZonesResponse{}, errors.Wrap(err, errUnmarshalError) - } - - // avoid overhead in most common cases where the total #zones <= 50 - if r.TotalPages < 2 { - return r, nil - } - - // parameters of pagination - var ( - totalPageCount = r.TotalPages - totalCount = r.Total - - // zones is a large slice to prevent resizing during concurrent writes. - zones = make([]Zone, totalCount) - ) - - // Copy the first page into zones. - copy(zones, r.Result) - - var wg sync.WaitGroup - wg.Add(totalPageCount - 1) // all pages except the first one. - errc := make(chan error, 1) // getting the first error - - // Creating all the workers. - for pageNum := 2; pageNum <= totalPageCount; pageNum++ { - // Note: URL.Values is just a map[string], so this would override the existing 'page' - opt.params.Set("page", strconv.Itoa(pageNum)) - - // start is the first index in the zone buffer - start := listZonesPerPage * (pageNum - 1) - - pageSize := listZonesPerPage - if pageNum == totalPageCount { - // The size of the last page (which would be <= 50). - pageSize = totalCount - start - } - - go api.listZonesFetch(ctx, &wg, errc, "/zones?"+opt.params.Encode(), pageSize, zones[start:]) - } - - wg.Wait() - - select { - case err := <-errc: // if there were any errors - return ZonesResponse{}, err - default: // if there were no errors, the receive statement should block - r.Result = zones - return r, nil - } -} - -// ZoneDetails fetches information about a zone. -// -// API reference: https://api.cloudflare.com/#zone-zone-details -func (api *API) ZoneDetails(ctx context.Context, zoneID string) (Zone, error) { - res, err := api.makeRequestContext(ctx, http.MethodGet, "/zones/"+zoneID, nil) - if err != nil { - return Zone{}, err - } - var r ZoneResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Zone{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneOptions is a subset of Zone, for editable options. -type ZoneOptions struct { - Paused *bool `json:"paused,omitempty"` - VanityNS []string `json:"vanity_name_servers,omitempty"` - Plan *ZonePlan `json:"plan,omitempty"` -} - -// ZoneSetPaused pauses Cloudflare service for the entire zone, sending all -// traffic direct to the origin. -func (api *API) ZoneSetPaused(ctx context.Context, zoneID string, paused bool) (Zone, error) { - zoneopts := ZoneOptions{Paused: &paused} - zone, err := api.EditZone(ctx, zoneID, zoneopts) - if err != nil { - return Zone{}, err - } - - return zone, nil -} - -// ZoneSetVanityNS sets custom nameservers for the zone. -// These names must be within the same zone. -func (api *API) ZoneSetVanityNS(ctx context.Context, zoneID string, ns []string) (Zone, error) { - zoneopts := ZoneOptions{VanityNS: ns} - zone, err := api.EditZone(ctx, zoneID, zoneopts) - if err != nil { - return Zone{}, err - } - - return zone, nil -} - -// ZoneSetPlan sets the rate plan of an existing zone. -// -// Valid values for `planType` are "CF_FREE", "CF_PRO", "CF_BIZ" and -// "CF_ENT". -// -// API reference: https://api.cloudflare.com/#zone-subscription-create-zone-subscription -func (api *API) ZoneSetPlan(ctx context.Context, zoneID string, planType string) error { - zonePayload := zoneSubscriptionRatePlanPayload{} - zonePayload.RatePlan.ID = planType - - uri := fmt.Sprintf("/zones/%s/subscription", zoneID) - - _, err := api.makeRequestContext(ctx, http.MethodPost, uri, zonePayload) - if err != nil { - return err - } - - return nil -} - -// ZoneUpdatePlan updates the rate plan of an existing zone. -// -// Valid values for `planType` are "CF_FREE", "CF_PRO", "CF_BIZ" and -// "CF_ENT". -// -// API reference: https://api.cloudflare.com/#zone-subscription-update-zone-subscription -func (api *API) ZoneUpdatePlan(ctx context.Context, zoneID string, planType string) error { - zonePayload := zoneSubscriptionRatePlanPayload{} - zonePayload.RatePlan.ID = planType - - uri := fmt.Sprintf("/zones/%s/subscription", zoneID) - - _, err := api.makeRequestContext(ctx, http.MethodPut, uri, zonePayload) - if err != nil { - return err - } - - return nil -} - -// EditZone edits the given zone. -// -// This is usually called by ZoneSetPaused or ZoneSetVanityNS. -// -// API reference: https://api.cloudflare.com/#zone-edit-zone-properties -func (api *API) EditZone(ctx context.Context, zoneID string, zoneOpts ZoneOptions) (Zone, error) { - res, err := api.makeRequestContext(ctx, http.MethodPatch, "/zones/"+zoneID, zoneOpts) - if err != nil { - return Zone{}, err - } - var r ZoneResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Zone{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// PurgeEverything purges the cache for the given zone. -// -// Note: this will substantially increase load on the origin server for that -// zone if there is a high cached vs. uncached request ratio. -// -// API reference: https://api.cloudflare.com/#zone-purge-all-files -func (api *API) PurgeEverything(ctx context.Context, zoneID string) (PurgeCacheResponse, error) { - uri := fmt.Sprintf("/zones/%s/purge_cache", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, PurgeCacheRequest{true, nil, nil, nil, nil}) - if err != nil { - return PurgeCacheResponse{}, err - } - var r PurgeCacheResponse - err = json.Unmarshal(res, &r) - if err != nil { - return PurgeCacheResponse{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// PurgeCache purges the cache using the given PurgeCacheRequest (zone/url/tag). -// -// API reference: https://api.cloudflare.com/#zone-purge-individual-files-by-url-and-cache-tags -func (api *API) PurgeCache(ctx context.Context, zoneID string, pcr PurgeCacheRequest) (PurgeCacheResponse, error) { - return api.PurgeCacheContext(ctx, zoneID, pcr) -} - -// PurgeCacheContext purges the cache using the given PurgeCacheRequest (zone/url/tag). -// -// API reference: https://api.cloudflare.com/#zone-purge-individual-files-by-url-and-cache-tags -func (api *API) PurgeCacheContext(ctx context.Context, zoneID string, pcr PurgeCacheRequest) (PurgeCacheResponse, error) { - uri := fmt.Sprintf("/zones/%s/purge_cache", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPost, uri, pcr) - if err != nil { - return PurgeCacheResponse{}, err - } - var r PurgeCacheResponse - err = json.Unmarshal(res, &r) - if err != nil { - return PurgeCacheResponse{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// DeleteZone deletes the given zone. -// -// API reference: https://api.cloudflare.com/#zone-delete-a-zone -func (api *API) DeleteZone(ctx context.Context, zoneID string) (ZoneID, error) { - res, err := api.makeRequestContext(ctx, http.MethodDelete, "/zones/"+zoneID, nil) - if err != nil { - return ZoneID{}, err - } - var r ZoneIDResponse - err = json.Unmarshal(res, &r) - if err != nil { - return ZoneID{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// AvailableZoneRatePlans returns information about all plans available to the specified zone. -// -// API reference: https://api.cloudflare.com/#zone-plan-available-plans -func (api *API) AvailableZoneRatePlans(ctx context.Context, zoneID string) ([]ZoneRatePlan, error) { - uri := fmt.Sprintf("/zones/%s/available_rate_plans", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []ZoneRatePlan{}, err - } - var r AvailableZoneRatePlansResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []ZoneRatePlan{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// AvailableZonePlans returns information about all plans available to the specified zone. -// -// API reference: https://api.cloudflare.com/#zone-rate-plan-list-available-plans -func (api *API) AvailableZonePlans(ctx context.Context, zoneID string) ([]ZonePlan, error) { - uri := fmt.Sprintf("/zones/%s/available_plans", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return []ZonePlan{}, err - } - var r AvailableZonePlansResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []ZonePlan{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// encode encodes non-nil fields into URL encoded form. -func (o ZoneAnalyticsOptions) encode() string { - v := url.Values{} - if o.Since != nil { - v.Set("since", (*o.Since).Format(time.RFC3339)) - } - if o.Until != nil { - v.Set("until", (*o.Until).Format(time.RFC3339)) - } - if o.Continuous != nil { - v.Set("continuous", fmt.Sprintf("%t", *o.Continuous)) - } - return v.Encode() -} - -// ZoneAnalyticsDashboard returns zone analytics information. -// -// API reference: https://api.cloudflare.com/#zone-analytics-dashboard -func (api *API) ZoneAnalyticsDashboard(ctx context.Context, zoneID string, options ZoneAnalyticsOptions) (ZoneAnalyticsData, error) { - uri := fmt.Sprintf("/zones/%s/analytics/dashboard?%s", zoneID, options.encode()) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return ZoneAnalyticsData{}, err - } - var r zoneAnalyticsDataResponse - err = json.Unmarshal(res, &r) - if err != nil { - return ZoneAnalyticsData{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneAnalyticsByColocation returns zone analytics information by datacenter. -// -// API reference: https://api.cloudflare.com/#zone-analytics-analytics-by-co-locations -func (api *API) ZoneAnalyticsByColocation(ctx context.Context, zoneID string, options ZoneAnalyticsOptions) ([]ZoneAnalyticsColocation, error) { - uri := fmt.Sprintf("/zones/%s/analytics/colos?%s", zoneID, options.encode()) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - var r zoneAnalyticsColocationResponse - err = json.Unmarshal(res, &r) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneSettings returns all of the settings for a given zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-get-all-zone-settings -func (api *API) ZoneSettings(ctx context.Context, zoneID string) (*ZoneSettingResponse, error) { - uri := fmt.Sprintf("/zones/%s/settings", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - response := &ZoneSettingResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UpdateZoneSettings updates the settings for a given zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-edit-zone-settings-info -func (api *API) UpdateZoneSettings(ctx context.Context, zoneID string, settings []ZoneSetting) (*ZoneSettingResponse, error) { - uri := fmt.Sprintf("/zones/%s/settings", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, struct { - Items []ZoneSetting `json:"items"` - }{settings}) - if err != nil { - return nil, err - } - - response := &ZoneSettingResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ZoneSSLSettings returns information about SSL setting to the specified zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-get-ssl-setting -func (api *API) ZoneSSLSettings(ctx context.Context, zoneID string) (ZoneSSLSetting, error) { - uri := fmt.Sprintf("/zones/%s/settings/ssl", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return ZoneSSLSetting{}, err - } - var r ZoneSSLSettingResponse - err = json.Unmarshal(res, &r) - if err != nil { - return ZoneSSLSetting{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateZoneSSLSettings update information about SSL setting to the specified zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-change-ssl-setting -func (api *API) UpdateZoneSSLSettings(ctx context.Context, zoneID string, sslValue string) (ZoneSSLSetting, error) { - uri := fmt.Sprintf("/zones/%s/settings/ssl", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, ZoneSSLSetting{Value: sslValue}) - if err != nil { - return ZoneSSLSetting{}, err - } - var r ZoneSSLSettingResponse - err = json.Unmarshal(res, &r) - if err != nil { - return ZoneSSLSetting{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// FallbackOrigin returns information about the fallback origin for the specified zone. -// -// API reference: https://developers.cloudflare.com/ssl/ssl-for-saas/api-calls/#fallback-origin-configuration -func (api *API) FallbackOrigin(ctx context.Context, zoneID string) (FallbackOrigin, error) { - uri := fmt.Sprintf("/zones/%s/fallback_origin", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return FallbackOrigin{}, err - } - - var r FallbackOriginResponse - err = json.Unmarshal(res, &r) - if err != nil { - return FallbackOrigin{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// UpdateFallbackOrigin updates the fallback origin for a given zone. -// -// API reference: https://developers.cloudflare.com/ssl/ssl-for-saas/api-calls/#4-example-patch-to-change-fallback-origin -func (api *API) UpdateFallbackOrigin(ctx context.Context, zoneID string, fbo FallbackOrigin) (*FallbackOriginResponse, error) { - uri := fmt.Sprintf("/zones/%s/fallback_origin", zoneID) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, fbo) - if err != nil { - return nil, err - } - - response := &FallbackOriginResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// normalizeZoneName tries to convert IDNs (international domain names) -// from Punycode to Unicode form. If the given zone name is not represented -// as Punycode, or converting fails (for invalid representations), it -// is returned unchanged. -// -// Because all the zone name comparison is currently done using the API service -// (except for comparison with the empty string), theoretically, we could -// remove this function from the Go library. However, there should be no harm -// calling this function other than gelable performance penalty. -// -// Note: conversion errors are silently discarded. -func normalizeZoneName(name string) string { - if n, err := idna.ToUnicode(name); err == nil { - return n - } - return name -} - -// ZoneSingleSetting returns information about specified setting to the specified zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-get-all-zone-settings -func (api *API) ZoneSingleSetting(ctx context.Context, zoneID, settingName string) (ZoneSetting, error) { - uri := fmt.Sprintf("/zones/%s/settings/%s", zoneID, settingName) - res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) - if err != nil { - return ZoneSetting{}, err - } - var r ZoneSettingSingleResponse - err = json.Unmarshal(res, &r) - if err != nil { - return ZoneSetting{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateZoneSingleSetting updates the specified setting for a given zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-edit-zone-settings-info -func (api *API) UpdateZoneSingleSetting(ctx context.Context, zoneID, settingName string, setting ZoneSetting) (*ZoneSettingSingleResponse, error) { - uri := fmt.Sprintf("/zones/%s/settings/%s", zoneID, settingName) - res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, setting) - if err != nil { - return nil, err - } - - response := &ZoneSettingSingleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ZoneExport returns the text BIND config for the given zone -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-export-dns-records -func (api *API) ZoneExport(ctx context.Context, zoneID string) (string, error) { - res, err := api.makeRequestContext(ctx, http.MethodGet, "/zones/"+zoneID+"/dns_records/export", nil) - if err != nil { - return "", err - } - return string(res), nil -} - -// ZoneDNSSECResponse represents the response from the Zone DNSSEC Setting -type ZoneDNSSECResponse struct { - Response - Result ZoneDNSSEC `json:"result"` -} - -// ZoneDNSSEC represents the response from the Zone DNSSEC Setting result -type ZoneDNSSEC struct { - Status string `json:"status"` - Flags int `json:"flags"` - Algorithm string `json:"algorithm"` - KeyType string `json:"key_type"` - DigestType string `json:"digest_type"` - DigestAlgorithm string `json:"digest_algorithm"` - Digest string `json:"digest"` - DS string `json:"ds"` - KeyTag int `json:"key_tag"` - PublicKey string `json:"public_key"` - ModifiedOn time.Time `json:"modified_on"` -} - -// ZoneDNSSECSetting returns the DNSSEC details of a zone -// -// API reference: https://api.cloudflare.com/#dnssec-dnssec-details -func (api *API) ZoneDNSSECSetting(ctx context.Context, zoneID string) (ZoneDNSSEC, error) { - res, err := api.makeRequestContext(ctx, http.MethodGet, "/zones/"+zoneID+"/dnssec", nil) - if err != nil { - return ZoneDNSSEC{}, err - } - response := ZoneDNSSECResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return ZoneDNSSEC{}, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// ZoneDNSSECDeleteResponse represents the response from the Zone DNSSEC Delete request -type ZoneDNSSECDeleteResponse struct { - Response - Result string `json:"result"` -} - -// DeleteZoneDNSSEC deletes DNSSEC for zone -// -// API reference: https://api.cloudflare.com/#dnssec-delete-dnssec-records -func (api *API) DeleteZoneDNSSEC(ctx context.Context, zoneID string) (string, error) { - res, err := api.makeRequestContext(ctx, http.MethodDelete, "/zones/"+zoneID+"/dnssec", nil) - if err != nil { - return "", err - } - response := ZoneDNSSECDeleteResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return "", errors.Wrap(err, errUnmarshalError) - } - return response.Result, nil -} - -// ZoneDNSSECUpdateOptions represents the options for DNSSEC update -type ZoneDNSSECUpdateOptions struct { - Status string `json:"status"` -} - -// UpdateZoneDNSSEC updates DNSSEC for a zone -// -// API reference: https://api.cloudflare.com/#dnssec-edit-dnssec-status -func (api *API) UpdateZoneDNSSEC(ctx context.Context, zoneID string, options ZoneDNSSECUpdateOptions) (ZoneDNSSEC, error) { - res, err := api.makeRequestContext(ctx, http.MethodPatch, "/zones/"+zoneID+"/dnssec", options) - if err != nil { - return ZoneDNSSEC{}, err - } - response := ZoneDNSSECResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return ZoneDNSSEC{}, errors.Wrap(err, errUnmarshalError) - } - return response.Result, nil -} diff --git a/vendor/github.com/containerd/cgroups/LICENSE b/vendor/github.com/containerd/cgroups/LICENSE deleted file mode 100644 index 261eeb9e..00000000 --- a/vendor/github.com/containerd/cgroups/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/containerd/cgroups/stats/v1/doc.go b/vendor/github.com/containerd/cgroups/stats/v1/doc.go deleted file mode 100644 index 23f3cdd4..00000000 --- a/vendor/github.com/containerd/cgroups/stats/v1/doc.go +++ /dev/null @@ -1,17 +0,0 @@ -/* - Copyright The containerd 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 v1 diff --git a/vendor/github.com/containerd/cgroups/stats/v1/metrics.pb.go b/vendor/github.com/containerd/cgroups/stats/v1/metrics.pb.go deleted file mode 100644 index a530f1d8..00000000 --- a/vendor/github.com/containerd/cgroups/stats/v1/metrics.pb.go +++ /dev/null @@ -1,5985 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: github.com/containerd/cgroups/stats/v1/metrics.proto - -package v1 - -import ( - fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" - proto "github.com/gogo/protobuf/proto" - io "io" - math "math" - reflect "reflect" - strings "strings" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package - -type Metrics struct { - Hugetlb []*HugetlbStat `protobuf:"bytes,1,rep,name=hugetlb,proto3" json:"hugetlb,omitempty"` - Pids *PidsStat `protobuf:"bytes,2,opt,name=pids,proto3" json:"pids,omitempty"` - CPU *CPUStat `protobuf:"bytes,3,opt,name=cpu,proto3" json:"cpu,omitempty"` - Memory *MemoryStat `protobuf:"bytes,4,opt,name=memory,proto3" json:"memory,omitempty"` - Blkio *BlkIOStat `protobuf:"bytes,5,opt,name=blkio,proto3" json:"blkio,omitempty"` - Rdma *RdmaStat `protobuf:"bytes,6,opt,name=rdma,proto3" json:"rdma,omitempty"` - Network []*NetworkStat `protobuf:"bytes,7,rep,name=network,proto3" json:"network,omitempty"` - CgroupStats *CgroupStats `protobuf:"bytes,8,opt,name=cgroup_stats,json=cgroupStats,proto3" json:"cgroup_stats,omitempty"` - MemoryOomControl *MemoryOomControl `protobuf:"bytes,9,opt,name=memory_oom_control,json=MemoryOomControl,proto3" json:"memory_oom_control,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Metrics) Reset() { *m = Metrics{} } -func (*Metrics) ProtoMessage() {} -func (*Metrics) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{0} -} -func (m *Metrics) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Metrics) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Metrics.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Metrics) XXX_Merge(src proto.Message) { - xxx_messageInfo_Metrics.Merge(m, src) -} -func (m *Metrics) XXX_Size() int { - return m.Size() -} -func (m *Metrics) XXX_DiscardUnknown() { - xxx_messageInfo_Metrics.DiscardUnknown(m) -} - -var xxx_messageInfo_Metrics proto.InternalMessageInfo - -type HugetlbStat struct { - Usage uint64 `protobuf:"varint,1,opt,name=usage,proto3" json:"usage,omitempty"` - Max uint64 `protobuf:"varint,2,opt,name=max,proto3" json:"max,omitempty"` - Failcnt uint64 `protobuf:"varint,3,opt,name=failcnt,proto3" json:"failcnt,omitempty"` - Pagesize string `protobuf:"bytes,4,opt,name=pagesize,proto3" json:"pagesize,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *HugetlbStat) Reset() { *m = HugetlbStat{} } -func (*HugetlbStat) ProtoMessage() {} -func (*HugetlbStat) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{1} -} -func (m *HugetlbStat) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *HugetlbStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_HugetlbStat.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *HugetlbStat) XXX_Merge(src proto.Message) { - xxx_messageInfo_HugetlbStat.Merge(m, src) -} -func (m *HugetlbStat) XXX_Size() int { - return m.Size() -} -func (m *HugetlbStat) XXX_DiscardUnknown() { - xxx_messageInfo_HugetlbStat.DiscardUnknown(m) -} - -var xxx_messageInfo_HugetlbStat proto.InternalMessageInfo - -type PidsStat struct { - Current uint64 `protobuf:"varint,1,opt,name=current,proto3" json:"current,omitempty"` - Limit uint64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *PidsStat) Reset() { *m = PidsStat{} } -func (*PidsStat) ProtoMessage() {} -func (*PidsStat) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{2} -} -func (m *PidsStat) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *PidsStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_PidsStat.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *PidsStat) XXX_Merge(src proto.Message) { - xxx_messageInfo_PidsStat.Merge(m, src) -} -func (m *PidsStat) XXX_Size() int { - return m.Size() -} -func (m *PidsStat) XXX_DiscardUnknown() { - xxx_messageInfo_PidsStat.DiscardUnknown(m) -} - -var xxx_messageInfo_PidsStat proto.InternalMessageInfo - -type CPUStat struct { - Usage *CPUUsage `protobuf:"bytes,1,opt,name=usage,proto3" json:"usage,omitempty"` - Throttling *Throttle `protobuf:"bytes,2,opt,name=throttling,proto3" json:"throttling,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CPUStat) Reset() { *m = CPUStat{} } -func (*CPUStat) ProtoMessage() {} -func (*CPUStat) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{3} -} -func (m *CPUStat) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CPUStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CPUStat.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CPUStat) XXX_Merge(src proto.Message) { - xxx_messageInfo_CPUStat.Merge(m, src) -} -func (m *CPUStat) XXX_Size() int { - return m.Size() -} -func (m *CPUStat) XXX_DiscardUnknown() { - xxx_messageInfo_CPUStat.DiscardUnknown(m) -} - -var xxx_messageInfo_CPUStat proto.InternalMessageInfo - -type CPUUsage struct { - // values in nanoseconds - Total uint64 `protobuf:"varint,1,opt,name=total,proto3" json:"total,omitempty"` - Kernel uint64 `protobuf:"varint,2,opt,name=kernel,proto3" json:"kernel,omitempty"` - User uint64 `protobuf:"varint,3,opt,name=user,proto3" json:"user,omitempty"` - PerCPU []uint64 `protobuf:"varint,4,rep,packed,name=per_cpu,json=perCpu,proto3" json:"per_cpu,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CPUUsage) Reset() { *m = CPUUsage{} } -func (*CPUUsage) ProtoMessage() {} -func (*CPUUsage) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{4} -} -func (m *CPUUsage) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CPUUsage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CPUUsage.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CPUUsage) XXX_Merge(src proto.Message) { - xxx_messageInfo_CPUUsage.Merge(m, src) -} -func (m *CPUUsage) XXX_Size() int { - return m.Size() -} -func (m *CPUUsage) XXX_DiscardUnknown() { - xxx_messageInfo_CPUUsage.DiscardUnknown(m) -} - -var xxx_messageInfo_CPUUsage proto.InternalMessageInfo - -type Throttle struct { - Periods uint64 `protobuf:"varint,1,opt,name=periods,proto3" json:"periods,omitempty"` - ThrottledPeriods uint64 `protobuf:"varint,2,opt,name=throttled_periods,json=throttledPeriods,proto3" json:"throttled_periods,omitempty"` - ThrottledTime uint64 `protobuf:"varint,3,opt,name=throttled_time,json=throttledTime,proto3" json:"throttled_time,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Throttle) Reset() { *m = Throttle{} } -func (*Throttle) ProtoMessage() {} -func (*Throttle) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{5} -} -func (m *Throttle) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *Throttle) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_Throttle.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *Throttle) XXX_Merge(src proto.Message) { - xxx_messageInfo_Throttle.Merge(m, src) -} -func (m *Throttle) XXX_Size() int { - return m.Size() -} -func (m *Throttle) XXX_DiscardUnknown() { - xxx_messageInfo_Throttle.DiscardUnknown(m) -} - -var xxx_messageInfo_Throttle proto.InternalMessageInfo - -type MemoryStat struct { - Cache uint64 `protobuf:"varint,1,opt,name=cache,proto3" json:"cache,omitempty"` - RSS uint64 `protobuf:"varint,2,opt,name=rss,proto3" json:"rss,omitempty"` - RSSHuge uint64 `protobuf:"varint,3,opt,name=rss_huge,json=rssHuge,proto3" json:"rss_huge,omitempty"` - MappedFile uint64 `protobuf:"varint,4,opt,name=mapped_file,json=mappedFile,proto3" json:"mapped_file,omitempty"` - Dirty uint64 `protobuf:"varint,5,opt,name=dirty,proto3" json:"dirty,omitempty"` - Writeback uint64 `protobuf:"varint,6,opt,name=writeback,proto3" json:"writeback,omitempty"` - PgPgIn uint64 `protobuf:"varint,7,opt,name=pg_pg_in,json=pgPgIn,proto3" json:"pg_pg_in,omitempty"` - PgPgOut uint64 `protobuf:"varint,8,opt,name=pg_pg_out,json=pgPgOut,proto3" json:"pg_pg_out,omitempty"` - PgFault uint64 `protobuf:"varint,9,opt,name=pg_fault,json=pgFault,proto3" json:"pg_fault,omitempty"` - PgMajFault uint64 `protobuf:"varint,10,opt,name=pg_maj_fault,json=pgMajFault,proto3" json:"pg_maj_fault,omitempty"` - InactiveAnon uint64 `protobuf:"varint,11,opt,name=inactive_anon,json=inactiveAnon,proto3" json:"inactive_anon,omitempty"` - ActiveAnon uint64 `protobuf:"varint,12,opt,name=active_anon,json=activeAnon,proto3" json:"active_anon,omitempty"` - InactiveFile uint64 `protobuf:"varint,13,opt,name=inactive_file,json=inactiveFile,proto3" json:"inactive_file,omitempty"` - ActiveFile uint64 `protobuf:"varint,14,opt,name=active_file,json=activeFile,proto3" json:"active_file,omitempty"` - Unevictable uint64 `protobuf:"varint,15,opt,name=unevictable,proto3" json:"unevictable,omitempty"` - HierarchicalMemoryLimit uint64 `protobuf:"varint,16,opt,name=hierarchical_memory_limit,json=hierarchicalMemoryLimit,proto3" json:"hierarchical_memory_limit,omitempty"` - HierarchicalSwapLimit uint64 `protobuf:"varint,17,opt,name=hierarchical_swap_limit,json=hierarchicalSwapLimit,proto3" json:"hierarchical_swap_limit,omitempty"` - TotalCache uint64 `protobuf:"varint,18,opt,name=total_cache,json=totalCache,proto3" json:"total_cache,omitempty"` - TotalRSS uint64 `protobuf:"varint,19,opt,name=total_rss,json=totalRss,proto3" json:"total_rss,omitempty"` - TotalRSSHuge uint64 `protobuf:"varint,20,opt,name=total_rss_huge,json=totalRssHuge,proto3" json:"total_rss_huge,omitempty"` - TotalMappedFile uint64 `protobuf:"varint,21,opt,name=total_mapped_file,json=totalMappedFile,proto3" json:"total_mapped_file,omitempty"` - TotalDirty uint64 `protobuf:"varint,22,opt,name=total_dirty,json=totalDirty,proto3" json:"total_dirty,omitempty"` - TotalWriteback uint64 `protobuf:"varint,23,opt,name=total_writeback,json=totalWriteback,proto3" json:"total_writeback,omitempty"` - TotalPgPgIn uint64 `protobuf:"varint,24,opt,name=total_pg_pg_in,json=totalPgPgIn,proto3" json:"total_pg_pg_in,omitempty"` - TotalPgPgOut uint64 `protobuf:"varint,25,opt,name=total_pg_pg_out,json=totalPgPgOut,proto3" json:"total_pg_pg_out,omitempty"` - TotalPgFault uint64 `protobuf:"varint,26,opt,name=total_pg_fault,json=totalPgFault,proto3" json:"total_pg_fault,omitempty"` - TotalPgMajFault uint64 `protobuf:"varint,27,opt,name=total_pg_maj_fault,json=totalPgMajFault,proto3" json:"total_pg_maj_fault,omitempty"` - TotalInactiveAnon uint64 `protobuf:"varint,28,opt,name=total_inactive_anon,json=totalInactiveAnon,proto3" json:"total_inactive_anon,omitempty"` - TotalActiveAnon uint64 `protobuf:"varint,29,opt,name=total_active_anon,json=totalActiveAnon,proto3" json:"total_active_anon,omitempty"` - TotalInactiveFile uint64 `protobuf:"varint,30,opt,name=total_inactive_file,json=totalInactiveFile,proto3" json:"total_inactive_file,omitempty"` - TotalActiveFile uint64 `protobuf:"varint,31,opt,name=total_active_file,json=totalActiveFile,proto3" json:"total_active_file,omitempty"` - TotalUnevictable uint64 `protobuf:"varint,32,opt,name=total_unevictable,json=totalUnevictable,proto3" json:"total_unevictable,omitempty"` - Usage *MemoryEntry `protobuf:"bytes,33,opt,name=usage,proto3" json:"usage,omitempty"` - Swap *MemoryEntry `protobuf:"bytes,34,opt,name=swap,proto3" json:"swap,omitempty"` - Kernel *MemoryEntry `protobuf:"bytes,35,opt,name=kernel,proto3" json:"kernel,omitempty"` - KernelTCP *MemoryEntry `protobuf:"bytes,36,opt,name=kernel_tcp,json=kernelTcp,proto3" json:"kernel_tcp,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MemoryStat) Reset() { *m = MemoryStat{} } -func (*MemoryStat) ProtoMessage() {} -func (*MemoryStat) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{6} -} -func (m *MemoryStat) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MemoryStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MemoryStat.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MemoryStat) XXX_Merge(src proto.Message) { - xxx_messageInfo_MemoryStat.Merge(m, src) -} -func (m *MemoryStat) XXX_Size() int { - return m.Size() -} -func (m *MemoryStat) XXX_DiscardUnknown() { - xxx_messageInfo_MemoryStat.DiscardUnknown(m) -} - -var xxx_messageInfo_MemoryStat proto.InternalMessageInfo - -type MemoryEntry struct { - Limit uint64 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"` - Usage uint64 `protobuf:"varint,2,opt,name=usage,proto3" json:"usage,omitempty"` - Max uint64 `protobuf:"varint,3,opt,name=max,proto3" json:"max,omitempty"` - Failcnt uint64 `protobuf:"varint,4,opt,name=failcnt,proto3" json:"failcnt,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MemoryEntry) Reset() { *m = MemoryEntry{} } -func (*MemoryEntry) ProtoMessage() {} -func (*MemoryEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{7} -} -func (m *MemoryEntry) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MemoryEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MemoryEntry.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MemoryEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_MemoryEntry.Merge(m, src) -} -func (m *MemoryEntry) XXX_Size() int { - return m.Size() -} -func (m *MemoryEntry) XXX_DiscardUnknown() { - xxx_messageInfo_MemoryEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_MemoryEntry proto.InternalMessageInfo - -type MemoryOomControl struct { - OomKillDisable uint64 `protobuf:"varint,1,opt,name=oom_kill_disable,proto3" json:oom_kill_disable",omitempty"` - UnderOom uint64 `protobuf:"varint,2,opt,name=under_oom,proto3" json:"under_oom,omitempty"` - OomKill uint64 `protobuf:"varint,3,opt,name=oom_kill,proto3" json:"oom_kill,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *MemoryOomControl) Reset() { *m = MemoryOomControl{} } -func (*MemoryOomControl) ProtoMessage() {} -func (*MemoryOomControl) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{8} -} -func (m *MemoryOomControl) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *MemoryOomControl) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_MemoryOomControl.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *MemoryOomControl) XXX_Merge(src proto.Message) { - xxx_messageInfo_MemoryOomControl.Merge(m, src) -} -func (m *MemoryOomControl) XXX_Size() int { - return m.Size() -} -func (m *MemoryOomControl) XXX_DiscardUnknown() { - xxx_messageInfo_MemoryOomControl.DiscardUnknown(m) -} - -var xxx_messageInfo_MemoryOomControl proto.InternalMessageInfo - -type BlkIOStat struct { - IoServiceBytesRecursive []*BlkIOEntry `protobuf:"bytes,1,rep,name=io_service_bytes_recursive,json=ioServiceBytesRecursive,proto3" json:"io_service_bytes_recursive,omitempty"` - IoServicedRecursive []*BlkIOEntry `protobuf:"bytes,2,rep,name=io_serviced_recursive,json=ioServicedRecursive,proto3" json:"io_serviced_recursive,omitempty"` - IoQueuedRecursive []*BlkIOEntry `protobuf:"bytes,3,rep,name=io_queued_recursive,json=ioQueuedRecursive,proto3" json:"io_queued_recursive,omitempty"` - IoServiceTimeRecursive []*BlkIOEntry `protobuf:"bytes,4,rep,name=io_service_time_recursive,json=ioServiceTimeRecursive,proto3" json:"io_service_time_recursive,omitempty"` - IoWaitTimeRecursive []*BlkIOEntry `protobuf:"bytes,5,rep,name=io_wait_time_recursive,json=ioWaitTimeRecursive,proto3" json:"io_wait_time_recursive,omitempty"` - IoMergedRecursive []*BlkIOEntry `protobuf:"bytes,6,rep,name=io_merged_recursive,json=ioMergedRecursive,proto3" json:"io_merged_recursive,omitempty"` - IoTimeRecursive []*BlkIOEntry `protobuf:"bytes,7,rep,name=io_time_recursive,json=ioTimeRecursive,proto3" json:"io_time_recursive,omitempty"` - SectorsRecursive []*BlkIOEntry `protobuf:"bytes,8,rep,name=sectors_recursive,json=sectorsRecursive,proto3" json:"sectors_recursive,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BlkIOStat) Reset() { *m = BlkIOStat{} } -func (*BlkIOStat) ProtoMessage() {} -func (*BlkIOStat) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{9} -} -func (m *BlkIOStat) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BlkIOStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BlkIOStat.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *BlkIOStat) XXX_Merge(src proto.Message) { - xxx_messageInfo_BlkIOStat.Merge(m, src) -} -func (m *BlkIOStat) XXX_Size() int { - return m.Size() -} -func (m *BlkIOStat) XXX_DiscardUnknown() { - xxx_messageInfo_BlkIOStat.DiscardUnknown(m) -} - -var xxx_messageInfo_BlkIOStat proto.InternalMessageInfo - -type BlkIOEntry struct { - Op string `protobuf:"bytes,1,opt,name=op,proto3" json:"op,omitempty"` - Device string `protobuf:"bytes,2,opt,name=device,proto3" json:"device,omitempty"` - Major uint64 `protobuf:"varint,3,opt,name=major,proto3" json:"major,omitempty"` - Minor uint64 `protobuf:"varint,4,opt,name=minor,proto3" json:"minor,omitempty"` - Value uint64 `protobuf:"varint,5,opt,name=value,proto3" json:"value,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *BlkIOEntry) Reset() { *m = BlkIOEntry{} } -func (*BlkIOEntry) ProtoMessage() {} -func (*BlkIOEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{10} -} -func (m *BlkIOEntry) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *BlkIOEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_BlkIOEntry.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *BlkIOEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_BlkIOEntry.Merge(m, src) -} -func (m *BlkIOEntry) XXX_Size() int { - return m.Size() -} -func (m *BlkIOEntry) XXX_DiscardUnknown() { - xxx_messageInfo_BlkIOEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_BlkIOEntry proto.InternalMessageInfo - -type RdmaStat struct { - Current []*RdmaEntry `protobuf:"bytes,1,rep,name=current,proto3" json:"current,omitempty"` - Limit []*RdmaEntry `protobuf:"bytes,2,rep,name=limit,proto3" json:"limit,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RdmaStat) Reset() { *m = RdmaStat{} } -func (*RdmaStat) ProtoMessage() {} -func (*RdmaStat) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{11} -} -func (m *RdmaStat) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *RdmaStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_RdmaStat.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *RdmaStat) XXX_Merge(src proto.Message) { - xxx_messageInfo_RdmaStat.Merge(m, src) -} -func (m *RdmaStat) XXX_Size() int { - return m.Size() -} -func (m *RdmaStat) XXX_DiscardUnknown() { - xxx_messageInfo_RdmaStat.DiscardUnknown(m) -} - -var xxx_messageInfo_RdmaStat proto.InternalMessageInfo - -type RdmaEntry struct { - Device string `protobuf:"bytes,1,opt,name=device,proto3" json:"device,omitempty"` - HcaHandles uint32 `protobuf:"varint,2,opt,name=hca_handles,json=hcaHandles,proto3" json:"hca_handles,omitempty"` - HcaObjects uint32 `protobuf:"varint,3,opt,name=hca_objects,json=hcaObjects,proto3" json:"hca_objects,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *RdmaEntry) Reset() { *m = RdmaEntry{} } -func (*RdmaEntry) ProtoMessage() {} -func (*RdmaEntry) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{12} -} -func (m *RdmaEntry) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *RdmaEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_RdmaEntry.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *RdmaEntry) XXX_Merge(src proto.Message) { - xxx_messageInfo_RdmaEntry.Merge(m, src) -} -func (m *RdmaEntry) XXX_Size() int { - return m.Size() -} -func (m *RdmaEntry) XXX_DiscardUnknown() { - xxx_messageInfo_RdmaEntry.DiscardUnknown(m) -} - -var xxx_messageInfo_RdmaEntry proto.InternalMessageInfo - -type NetworkStat struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - RxBytes uint64 `protobuf:"varint,2,opt,name=rx_bytes,json=rxBytes,proto3" json:"rx_bytes,omitempty"` - RxPackets uint64 `protobuf:"varint,3,opt,name=rx_packets,json=rxPackets,proto3" json:"rx_packets,omitempty"` - RxErrors uint64 `protobuf:"varint,4,opt,name=rx_errors,json=rxErrors,proto3" json:"rx_errors,omitempty"` - RxDropped uint64 `protobuf:"varint,5,opt,name=rx_dropped,json=rxDropped,proto3" json:"rx_dropped,omitempty"` - TxBytes uint64 `protobuf:"varint,6,opt,name=tx_bytes,json=txBytes,proto3" json:"tx_bytes,omitempty"` - TxPackets uint64 `protobuf:"varint,7,opt,name=tx_packets,json=txPackets,proto3" json:"tx_packets,omitempty"` - TxErrors uint64 `protobuf:"varint,8,opt,name=tx_errors,json=txErrors,proto3" json:"tx_errors,omitempty"` - TxDropped uint64 `protobuf:"varint,9,opt,name=tx_dropped,json=txDropped,proto3" json:"tx_dropped,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *NetworkStat) Reset() { *m = NetworkStat{} } -func (*NetworkStat) ProtoMessage() {} -func (*NetworkStat) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{13} -} -func (m *NetworkStat) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *NetworkStat) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_NetworkStat.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *NetworkStat) XXX_Merge(src proto.Message) { - xxx_messageInfo_NetworkStat.Merge(m, src) -} -func (m *NetworkStat) XXX_Size() int { - return m.Size() -} -func (m *NetworkStat) XXX_DiscardUnknown() { - xxx_messageInfo_NetworkStat.DiscardUnknown(m) -} - -var xxx_messageInfo_NetworkStat proto.InternalMessageInfo - -// CgroupStats exports per-cgroup statistics. -type CgroupStats struct { - // number of tasks sleeping - NrSleeping uint64 `protobuf:"varint,1,opt,name=nr_sleeping,json=nrSleeping,proto3" json:"nr_sleeping,omitempty"` - // number of tasks running - NrRunning uint64 `protobuf:"varint,2,opt,name=nr_running,json=nrRunning,proto3" json:"nr_running,omitempty"` - // number of tasks in stopped state - NrStopped uint64 `protobuf:"varint,3,opt,name=nr_stopped,json=nrStopped,proto3" json:"nr_stopped,omitempty"` - // number of tasks in uninterruptible state - NrUninterruptible uint64 `protobuf:"varint,4,opt,name=nr_uninterruptible,json=nrUninterruptible,proto3" json:"nr_uninterruptible,omitempty"` - // number of tasks waiting on IO - NrIoWait uint64 `protobuf:"varint,5,opt,name=nr_io_wait,json=nrIoWait,proto3" json:"nr_io_wait,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *CgroupStats) Reset() { *m = CgroupStats{} } -func (*CgroupStats) ProtoMessage() {} -func (*CgroupStats) Descriptor() ([]byte, []int) { - return fileDescriptor_a17b2d87c332bfaa, []int{14} -} -func (m *CgroupStats) XXX_Unmarshal(b []byte) error { - return m.Unmarshal(b) -} -func (m *CgroupStats) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - if deterministic { - return xxx_messageInfo_CgroupStats.Marshal(b, m, deterministic) - } else { - b = b[:cap(b)] - n, err := m.MarshalTo(b) - if err != nil { - return nil, err - } - return b[:n], nil - } -} -func (m *CgroupStats) XXX_Merge(src proto.Message) { - xxx_messageInfo_CgroupStats.Merge(m, src) -} -func (m *CgroupStats) XXX_Size() int { - return m.Size() -} -func (m *CgroupStats) XXX_DiscardUnknown() { - xxx_messageInfo_CgroupStats.DiscardUnknown(m) -} - -var xxx_messageInfo_CgroupStats proto.InternalMessageInfo - -func init() { - proto.RegisterType((*Metrics)(nil), "io.containerd.cgroups.v1.Metrics") - proto.RegisterType((*HugetlbStat)(nil), "io.containerd.cgroups.v1.HugetlbStat") - proto.RegisterType((*PidsStat)(nil), "io.containerd.cgroups.v1.PidsStat") - proto.RegisterType((*CPUStat)(nil), "io.containerd.cgroups.v1.CPUStat") - proto.RegisterType((*CPUUsage)(nil), "io.containerd.cgroups.v1.CPUUsage") - proto.RegisterType((*Throttle)(nil), "io.containerd.cgroups.v1.Throttle") - proto.RegisterType((*MemoryStat)(nil), "io.containerd.cgroups.v1.MemoryStat") - proto.RegisterType((*MemoryEntry)(nil), "io.containerd.cgroups.v1.MemoryEntry") - proto.RegisterType((*MemoryOomControl)(nil), "io.containerd.cgroups.v1.MemoryOomControl") - proto.RegisterType((*BlkIOStat)(nil), "io.containerd.cgroups.v1.BlkIOStat") - proto.RegisterType((*BlkIOEntry)(nil), "io.containerd.cgroups.v1.BlkIOEntry") - proto.RegisterType((*RdmaStat)(nil), "io.containerd.cgroups.v1.RdmaStat") - proto.RegisterType((*RdmaEntry)(nil), "io.containerd.cgroups.v1.RdmaEntry") - proto.RegisterType((*NetworkStat)(nil), "io.containerd.cgroups.v1.NetworkStat") - proto.RegisterType((*CgroupStats)(nil), "io.containerd.cgroups.v1.CgroupStats") -} - -func init() { - proto.RegisterFile("github.com/containerd/cgroups/stats/v1/metrics.proto", fileDescriptor_a17b2d87c332bfaa) -} - -var fileDescriptor_a17b2d87c332bfaa = []byte{ - // 1669 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x58, 0x4f, 0x73, 0x1b, 0xb7, - 0x15, 0x0f, 0xc5, 0x95, 0xc8, 0x7d, 0x94, 0x6c, 0x09, 0xfe, 0xb7, 0x52, 0x1c, 0x51, 0xa1, 0xec, - 0xd6, 0xad, 0xa7, 0xd2, 0x24, 0xed, 0x78, 0xea, 0x34, 0x99, 0x4e, 0xa4, 0x24, 0x63, 0x4f, 0xab, - 0x9a, 0x59, 0x4a, 0x93, 0xf6, 0xb4, 0x03, 0x2e, 0xe1, 0x25, 0xac, 0xe5, 0x62, 0x83, 0xc5, 0x52, - 0x74, 0x4f, 0x3d, 0x74, 0xa6, 0xa7, 0x7e, 0xa0, 0x7e, 0x83, 0x1c, 0x7b, 0xe9, 0x4c, 0x7b, 0xd1, - 0x34, 0xfc, 0x1c, 0x3d, 0x74, 0x80, 0x87, 0xfd, 0x43, 0xc7, 0xb2, 0xc2, 0xdb, 0xe2, 0xe1, 0xf7, - 0x7e, 0xef, 0xe1, 0xe1, 0x07, 0xe0, 0x91, 0xf0, 0xab, 0x88, 0xab, 0x71, 0x3e, 0x3c, 0x08, 0xc5, - 0xe4, 0x30, 0x14, 0x89, 0xa2, 0x3c, 0x61, 0x72, 0x74, 0x18, 0x46, 0x52, 0xe4, 0x69, 0x76, 0x98, - 0x29, 0xaa, 0xb2, 0xc3, 0xe9, 0x47, 0x87, 0x13, 0xa6, 0x24, 0x0f, 0xb3, 0x83, 0x54, 0x0a, 0x25, - 0x88, 0xc7, 0xc5, 0x41, 0x85, 0x3e, 0xb0, 0xe8, 0x83, 0xe9, 0x47, 0x3b, 0xb7, 0x23, 0x11, 0x09, - 0x03, 0x3a, 0xd4, 0x5f, 0x88, 0xef, 0xfd, 0xaf, 0x09, 0xad, 0x13, 0x64, 0x20, 0xbf, 0x85, 0xd6, - 0x38, 0x8f, 0x98, 0x8a, 0x87, 0x5e, 0x63, 0xaf, 0xf9, 0xa8, 0xf3, 0xf1, 0xc3, 0x83, 0xab, 0xd8, - 0x0e, 0x9e, 0x21, 0x70, 0xa0, 0xa8, 0xf2, 0x0b, 0x2f, 0xf2, 0x04, 0x9c, 0x94, 0x8f, 0x32, 0x6f, - 0x65, 0xaf, 0xf1, 0xa8, 0xf3, 0x71, 0xef, 0x6a, 0xef, 0x3e, 0x1f, 0x65, 0xc6, 0xd5, 0xe0, 0xc9, - 0xa7, 0xd0, 0x0c, 0xd3, 0xdc, 0x6b, 0x1a, 0xb7, 0x0f, 0xaf, 0x76, 0x3b, 0xee, 0x9f, 0x69, 0xaf, - 0xa3, 0xd6, 0xfc, 0xb2, 0xdb, 0x3c, 0xee, 0x9f, 0xf9, 0xda, 0x8d, 0x7c, 0x0a, 0x6b, 0x13, 0x36, - 0x11, 0xf2, 0xb5, 0xe7, 0x18, 0x82, 0x07, 0x57, 0x13, 0x9c, 0x18, 0x9c, 0x89, 0x6c, 0x7d, 0xc8, - 0x53, 0x58, 0x1d, 0xc6, 0xe7, 0x5c, 0x78, 0xab, 0xc6, 0x79, 0xff, 0x6a, 0xe7, 0xa3, 0xf8, 0xfc, - 0xf9, 0x0b, 0xe3, 0x8b, 0x1e, 0x7a, 0xb9, 0x72, 0x34, 0xa1, 0xde, 0xda, 0x75, 0xcb, 0xf5, 0x47, - 0x13, 0x8a, 0xcb, 0xd5, 0x78, 0x5d, 0xe7, 0x84, 0xa9, 0x0b, 0x21, 0xcf, 0xbd, 0xd6, 0x75, 0x75, - 0xfe, 0x03, 0x02, 0xb1, 0xce, 0xd6, 0x8b, 0x3c, 0x83, 0x75, 0x84, 0x04, 0x46, 0x05, 0x5e, 0xdb, - 0x24, 0xf0, 0x0e, 0x96, 0x63, 0xf3, 0xa9, 0x49, 0x32, 0xbf, 0x13, 0x56, 0x83, 0xde, 0x39, 0x74, - 0x6a, 0x3b, 0x49, 0x6e, 0xc3, 0x6a, 0x9e, 0xd1, 0x88, 0x79, 0x8d, 0xbd, 0xc6, 0x23, 0xc7, 0xc7, - 0x01, 0xd9, 0x84, 0xe6, 0x84, 0xce, 0xcc, 0xae, 0x3a, 0xbe, 0xfe, 0x24, 0x1e, 0xb4, 0x5e, 0x52, - 0x1e, 0x87, 0x89, 0x32, 0x9b, 0xe6, 0xf8, 0xc5, 0x90, 0xec, 0x40, 0x3b, 0xa5, 0x11, 0xcb, 0xf8, - 0x9f, 0x99, 0xd9, 0x0e, 0xd7, 0x2f, 0xc7, 0xbd, 0x4f, 0xa0, 0x5d, 0x6c, 0xbc, 0x66, 0x08, 0x73, - 0x29, 0x59, 0xa2, 0x6c, 0xac, 0x62, 0xa8, 0x73, 0x88, 0xf9, 0x84, 0x2b, 0x1b, 0x0f, 0x07, 0xbd, - 0xbf, 0x35, 0xa0, 0x65, 0xb7, 0x9f, 0xfc, 0xba, 0x9e, 0xe5, 0x3b, 0x0b, 0x7f, 0xdc, 0x3f, 0x3b, - 0xd3, 0xc8, 0x62, 0x25, 0x47, 0x00, 0x6a, 0x2c, 0x85, 0x52, 0x31, 0x4f, 0xa2, 0xeb, 0x65, 0x7a, - 0x8a, 0x58, 0xe6, 0xd7, 0xbc, 0x7a, 0xdf, 0x42, 0xbb, 0xa0, 0xd5, 0xb9, 0x2a, 0xa1, 0x68, 0x5c, - 0xd4, 0xcb, 0x0c, 0xc8, 0x5d, 0x58, 0x3b, 0x67, 0x32, 0x61, 0xb1, 0x5d, 0x82, 0x1d, 0x11, 0x02, - 0x4e, 0x9e, 0x31, 0x69, 0x4b, 0x66, 0xbe, 0xc9, 0x3e, 0xb4, 0x52, 0x26, 0x03, 0x2d, 0x7f, 0x67, - 0xaf, 0xf9, 0xc8, 0x39, 0x82, 0xf9, 0x65, 0x77, 0xad, 0xcf, 0xa4, 0x96, 0xf7, 0x5a, 0xca, 0xe4, - 0x71, 0x9a, 0xf7, 0x66, 0xd0, 0x2e, 0x52, 0xd1, 0x85, 0x4b, 0x99, 0xe4, 0x62, 0x94, 0x15, 0x85, - 0xb3, 0x43, 0xf2, 0x18, 0xb6, 0x6c, 0x9a, 0x6c, 0x14, 0x14, 0x18, 0xcc, 0x60, 0xb3, 0x9c, 0xe8, - 0x5b, 0xf0, 0x43, 0xb8, 0x51, 0x81, 0x15, 0x9f, 0x30, 0x9b, 0xd5, 0x46, 0x69, 0x3d, 0xe5, 0x13, - 0xd6, 0xfb, 0x4f, 0x07, 0xa0, 0x3a, 0x34, 0x7a, 0xbd, 0x21, 0x0d, 0xc7, 0xa5, 0x3e, 0xcc, 0x80, - 0x6c, 0x43, 0x53, 0x66, 0x36, 0x14, 0x9e, 0x4d, 0x7f, 0x30, 0xf0, 0xb5, 0x8d, 0xfc, 0x04, 0xda, - 0x32, 0xcb, 0x02, 0x7d, 0x41, 0x60, 0x80, 0xa3, 0xce, 0xfc, 0xb2, 0xdb, 0xf2, 0x07, 0x03, 0x2d, - 0x3b, 0xbf, 0x25, 0xb3, 0x4c, 0x7f, 0x90, 0x2e, 0x74, 0x26, 0x34, 0x4d, 0xd9, 0x28, 0x78, 0xc9, - 0x63, 0x54, 0x8e, 0xe3, 0x03, 0x9a, 0xbe, 0xe2, 0xb1, 0xa9, 0xf4, 0x88, 0x4b, 0xf5, 0xda, 0x1c, - 0x53, 0xc7, 0xc7, 0x01, 0xb9, 0x0f, 0xee, 0x85, 0xe4, 0x8a, 0x0d, 0x69, 0x78, 0x6e, 0x8e, 0xa1, - 0xe3, 0x57, 0x06, 0xe2, 0x41, 0x3b, 0x8d, 0x82, 0x34, 0x0a, 0x78, 0xe2, 0xb5, 0x70, 0x27, 0xd2, - 0xa8, 0x1f, 0x3d, 0x4f, 0xc8, 0x0e, 0xb8, 0x38, 0x23, 0x72, 0x65, 0x4e, 0x8f, 0x2e, 0x63, 0xd4, - 0x8f, 0x5e, 0xe4, 0x8a, 0x6c, 0x1b, 0xaf, 0x97, 0x34, 0x8f, 0x95, 0xe7, 0x16, 0x53, 0x5f, 0xe9, - 0x21, 0xd9, 0x83, 0xf5, 0x34, 0x0a, 0x26, 0xf4, 0x95, 0x9d, 0x06, 0x4c, 0x33, 0x8d, 0x4e, 0xe8, - 0x2b, 0x44, 0xec, 0xc3, 0x06, 0x4f, 0x68, 0xa8, 0xf8, 0x94, 0x05, 0x34, 0x11, 0x89, 0xd7, 0x31, - 0x90, 0xf5, 0xc2, 0xf8, 0x79, 0x22, 0x12, 0xbd, 0xd8, 0x3a, 0x64, 0x1d, 0x59, 0x6a, 0x80, 0x3a, - 0x8b, 0xa9, 0xc7, 0xc6, 0x22, 0x8b, 0xa9, 0x48, 0xc5, 0x62, 0x20, 0x37, 0xea, 0x2c, 0x06, 0xb0, - 0x07, 0x9d, 0x3c, 0x61, 0x53, 0x1e, 0x2a, 0x3a, 0x8c, 0x99, 0x77, 0xd3, 0x00, 0xea, 0x26, 0xf2, - 0x09, 0x6c, 0x8f, 0x39, 0x93, 0x54, 0x86, 0x63, 0x1e, 0xd2, 0x38, 0xc0, 0x2b, 0x31, 0xc0, 0xe3, - 0xb7, 0x69, 0xf0, 0xf7, 0xea, 0x00, 0x54, 0xc2, 0xef, 0xf5, 0x34, 0x79, 0x02, 0x0b, 0x53, 0x41, - 0x76, 0x41, 0x53, 0xeb, 0xb9, 0x65, 0x3c, 0xef, 0xd4, 0xa7, 0x07, 0x17, 0x34, 0x45, 0xbf, 0x2e, - 0x74, 0xcc, 0x29, 0x09, 0x50, 0x48, 0x04, 0xd3, 0x36, 0xa6, 0x63, 0xa3, 0xa6, 0x9f, 0x81, 0x8b, - 0x00, 0xad, 0xa9, 0x5b, 0x46, 0x33, 0xeb, 0xf3, 0xcb, 0x6e, 0xfb, 0x54, 0x1b, 0xb5, 0xb0, 0xda, - 0x66, 0xda, 0xcf, 0x32, 0xf2, 0x04, 0x6e, 0x94, 0x50, 0xd4, 0xd8, 0x6d, 0x83, 0xdf, 0x9c, 0x5f, - 0x76, 0xd7, 0x0b, 0xbc, 0x11, 0xda, 0x7a, 0xe1, 0x63, 0xd4, 0xf6, 0x73, 0xd8, 0x42, 0xbf, 0xba, - 0xe6, 0xee, 0x98, 0x4c, 0x6e, 0x9a, 0x89, 0x93, 0x4a, 0x78, 0x65, 0xbe, 0x28, 0xbf, 0xbb, 0xb5, - 0x7c, 0xbf, 0x30, 0x1a, 0xfc, 0x29, 0xa0, 0x4f, 0x50, 0x29, 0xf1, 0x9e, 0x01, 0x61, 0x6e, 0xdf, - 0x94, 0x72, 0xdc, 0x2f, 0xb2, 0x2d, 0x45, 0xe9, 0xe1, 0x96, 0x18, 0x6b, 0x1f, 0x95, 0xf9, 0xb0, - 0x60, 0xab, 0xf4, 0xb9, 0x8d, 0x9b, 0x5f, 0xa2, 0xb4, 0x48, 0x1f, 0xd4, 0xb8, 0x50, 0x8b, 0x3b, - 0x0b, 0x28, 0x54, 0xe3, 0x63, 0x20, 0x25, 0xaa, 0x52, 0xed, 0xfb, 0xb5, 0x85, 0xf6, 0x2b, 0xe9, - 0x1e, 0xc0, 0x2d, 0x04, 0x2f, 0x0a, 0xf8, 0xbe, 0x41, 0x63, 0xbd, 0x9e, 0xd7, 0x55, 0x5c, 0x16, - 0xb1, 0x8e, 0xfe, 0xa0, 0xc6, 0xfd, 0x79, 0x85, 0xfd, 0x21, 0xb7, 0x29, 0xf9, 0xee, 0x5b, 0xb8, - 0x4d, 0xd1, 0xdf, 0xe4, 0x36, 0xe8, 0xee, 0x0f, 0xb8, 0x0d, 0xf6, 0x71, 0x81, 0xad, 0x8b, 0x7d, - 0xcf, 0x5e, 0x7b, 0x7a, 0xe2, 0xac, 0xa6, 0xf8, 0xdf, 0x14, 0x4f, 0xc7, 0x87, 0xd7, 0x3d, 0x99, - 0xa8, 0xf5, 0x2f, 0x13, 0x25, 0x5f, 0x17, 0xaf, 0xc7, 0x53, 0x70, 0xb4, 0xca, 0xbd, 0xde, 0x32, - 0xbe, 0xc6, 0x85, 0x7c, 0x56, 0x3e, 0x09, 0xfb, 0xcb, 0x38, 0x17, 0x2f, 0xc7, 0x00, 0x00, 0xbf, - 0x02, 0x15, 0xa6, 0xde, 0x83, 0x25, 0x28, 0x8e, 0x36, 0xe6, 0x97, 0x5d, 0xf7, 0x77, 0xc6, 0xf9, - 0xf4, 0xb8, 0xef, 0xbb, 0xc8, 0x73, 0x1a, 0xa6, 0x3d, 0x06, 0x9d, 0x1a, 0xb0, 0x7a, 0x77, 0x1b, - 0xb5, 0x77, 0xb7, 0xea, 0x08, 0x56, 0xde, 0xd2, 0x11, 0x34, 0xdf, 0xda, 0x11, 0x38, 0x0b, 0x1d, - 0x41, 0xef, 0x5f, 0xab, 0xe0, 0x96, 0xad, 0x13, 0xa1, 0xb0, 0xc3, 0x45, 0x90, 0x31, 0x39, 0xe5, - 0x21, 0x0b, 0x86, 0xaf, 0x15, 0xcb, 0x02, 0xc9, 0xc2, 0x5c, 0x66, 0x7c, 0xca, 0x6c, 0xdb, 0xf9, - 0xe0, 0x9a, 0x1e, 0x0c, 0x6b, 0x73, 0x8f, 0x8b, 0x01, 0xd2, 0x1c, 0x69, 0x16, 0xbf, 0x20, 0x21, - 0x7f, 0x84, 0x3b, 0x55, 0x88, 0x51, 0x8d, 0x7d, 0x65, 0x09, 0xf6, 0x5b, 0x25, 0xfb, 0xa8, 0x62, - 0x3e, 0x85, 0x5b, 0x5c, 0x04, 0xdf, 0xe6, 0x2c, 0x5f, 0xe0, 0x6d, 0x2e, 0xc1, 0xbb, 0xc5, 0xc5, - 0xd7, 0xc6, 0xbf, 0x62, 0x0d, 0x60, 0xbb, 0x56, 0x12, 0xfd, 0x16, 0xd7, 0xb8, 0x9d, 0x25, 0xb8, - 0xef, 0x96, 0x39, 0xeb, 0xb7, 0xbb, 0x0a, 0xf0, 0x27, 0xb8, 0xcb, 0x45, 0x70, 0x41, 0xb9, 0x7a, - 0x93, 0x7d, 0x75, 0xb9, 0x8a, 0x7c, 0x43, 0xb9, 0x5a, 0xa4, 0xc6, 0x8a, 0x4c, 0x98, 0x8c, 0x16, - 0x2a, 0xb2, 0xb6, 0x5c, 0x45, 0x4e, 0x8c, 0x7f, 0xc5, 0xda, 0x87, 0x2d, 0x2e, 0xde, 0xcc, 0xb5, - 0xb5, 0x04, 0xe7, 0x4d, 0x2e, 0x16, 0xf3, 0xfc, 0x1a, 0xb6, 0x32, 0x16, 0x2a, 0x21, 0xeb, 0x6a, - 0x6b, 0x2f, 0xc1, 0xb8, 0x69, 0xdd, 0x4b, 0xca, 0xde, 0x14, 0xa0, 0x9a, 0x27, 0x37, 0x60, 0x45, - 0xa4, 0xe6, 0xe8, 0xb8, 0xfe, 0x8a, 0x48, 0x75, 0x0f, 0x38, 0xd2, 0xd7, 0x0e, 0x1e, 0x1c, 0xd7, - 0xb7, 0x23, 0x7d, 0x9e, 0x26, 0xf4, 0x95, 0x28, 0x9a, 0x40, 0x1c, 0x18, 0x2b, 0x4f, 0x84, 0xb4, - 0x67, 0x07, 0x07, 0xda, 0x3a, 0xa5, 0x71, 0xce, 0x8a, 0x9e, 0xc7, 0x0c, 0x7a, 0x7f, 0x6d, 0x40, - 0xbb, 0xf8, 0x41, 0x41, 0x3e, 0xab, 0xb7, 0xd1, 0xcd, 0x77, 0xff, 0x7e, 0xd1, 0x4e, 0xb8, 0x98, - 0xb2, 0xd7, 0x7e, 0x5a, 0xf5, 0xda, 0x3f, 0xda, 0xd9, 0x36, 0xe4, 0x0c, 0xdc, 0xd2, 0x56, 0x5b, - 0x6d, 0x63, 0x61, 0xb5, 0x5d, 0xe8, 0x8c, 0x43, 0x1a, 0x8c, 0x69, 0x32, 0x8a, 0x19, 0x76, 0x88, - 0x1b, 0x3e, 0x8c, 0x43, 0xfa, 0x0c, 0x2d, 0x05, 0x40, 0x0c, 0x5f, 0xb1, 0x50, 0x65, 0xa6, 0x28, - 0x08, 0x78, 0x81, 0x96, 0xde, 0xdf, 0x57, 0xa0, 0x53, 0xfb, 0x0d, 0xa4, 0x7b, 0xe8, 0x84, 0x4e, - 0x8a, 0x38, 0xe6, 0x5b, 0x77, 0x6c, 0x72, 0x86, 0x77, 0x89, 0xbd, 0xa6, 0x5a, 0x72, 0x66, 0x2e, - 0x05, 0xf2, 0x01, 0x80, 0x9c, 0x05, 0x29, 0x0d, 0xcf, 0x99, 0xa5, 0x77, 0x7c, 0x57, 0xce, 0xfa, - 0x68, 0x20, 0xef, 0x83, 0x2b, 0x67, 0x01, 0x93, 0x52, 0xc8, 0xcc, 0xd6, 0xbe, 0x2d, 0x67, 0x5f, - 0x9a, 0xb1, 0xf5, 0x1d, 0x49, 0xa1, 0x7b, 0x01, 0xbb, 0x07, 0xae, 0x9c, 0x7d, 0x81, 0x06, 0x1d, - 0x55, 0x15, 0x51, 0xb1, 0xf5, 0x6c, 0xa9, 0x2a, 0xaa, 0xaa, 0xa2, 0x62, 0xeb, 0xe9, 0xaa, 0x7a, - 0x54, 0x55, 0x46, 0xc5, 0xee, 0xb3, 0xad, 0x6a, 0x51, 0x55, 0x15, 0xd5, 0x2d, 0x7c, 0x6d, 0xd4, - 0xde, 0x3f, 0x1a, 0xd0, 0xa9, 0xfd, 0x9a, 0xd3, 0x05, 0x4c, 0x64, 0x90, 0xc5, 0x8c, 0xa5, 0xfa, - 0x27, 0x0d, 0xde, 0xdd, 0x90, 0xc8, 0x81, 0xb5, 0x68, 0xbe, 0x44, 0x06, 0x32, 0x4f, 0x92, 0xe2, - 0x27, 0x8f, 0xe3, 0xbb, 0x89, 0xf4, 0xd1, 0x60, 0xa7, 0x33, 0x85, 0xe1, 0x9a, 0xc5, 0xf4, 0x00, - 0x0d, 0xe4, 0x17, 0x40, 0x12, 0x19, 0xe4, 0x09, 0x4f, 0x14, 0x93, 0x32, 0x4f, 0x15, 0x1f, 0x96, - 0xed, 0xf9, 0x56, 0x22, 0xcf, 0x16, 0x27, 0xc8, 0x7d, 0xc3, 0x66, 0x2f, 0x1b, 0x5b, 0xb2, 0x76, - 0x22, 0x9f, 0x9b, 0x9b, 0xe3, 0xc8, 0xfb, 0xee, 0xfb, 0xdd, 0xf7, 0xfe, 0xfd, 0xfd, 0xee, 0x7b, - 0x7f, 0x99, 0xef, 0x36, 0xbe, 0x9b, 0xef, 0x36, 0xfe, 0x39, 0xdf, 0x6d, 0xfc, 0x77, 0xbe, 0xdb, - 0x18, 0xae, 0x99, 0x3f, 0x23, 0x7e, 0xf9, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0xb9, 0x78, 0x66, - 0x06, 0xf4, 0x10, 0x00, 0x00, -} - -func (m *Metrics) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Metrics) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Hugetlb) > 0 { - for _, msg := range m.Hugetlb { - dAtA[i] = 0xa - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if m.Pids != nil { - dAtA[i] = 0x12 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Pids.Size())) - n1, err := m.Pids.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n1 - } - if m.CPU != nil { - dAtA[i] = 0x1a - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.CPU.Size())) - n2, err := m.CPU.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n2 - } - if m.Memory != nil { - dAtA[i] = 0x22 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Memory.Size())) - n3, err := m.Memory.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n3 - } - if m.Blkio != nil { - dAtA[i] = 0x2a - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Blkio.Size())) - n4, err := m.Blkio.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n4 - } - if m.Rdma != nil { - dAtA[i] = 0x32 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Rdma.Size())) - n5, err := m.Rdma.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n5 - } - if len(m.Network) > 0 { - for _, msg := range m.Network { - dAtA[i] = 0x3a - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if m.CgroupStats != nil { - dAtA[i] = 0x42 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.CgroupStats.Size())) - n6, err := m.CgroupStats.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n6 - } - if m.MemoryOomControl != nil { - dAtA[i] = 0x4a - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.MemoryOomControl.Size())) - n7, err := m.MemoryOomControl.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n7 - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *HugetlbStat) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *HugetlbStat) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Usage != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Usage)) - } - if m.Max != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Max)) - } - if m.Failcnt != 0 { - dAtA[i] = 0x18 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Failcnt)) - } - if len(m.Pagesize) > 0 { - dAtA[i] = 0x22 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(len(m.Pagesize))) - i += copy(dAtA[i:], m.Pagesize) - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *PidsStat) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PidsStat) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Current != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Current)) - } - if m.Limit != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Limit)) - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *CPUStat) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CPUStat) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Usage != nil { - dAtA[i] = 0xa - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Usage.Size())) - n7, err := m.Usage.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n7 - } - if m.Throttling != nil { - dAtA[i] = 0x12 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Throttling.Size())) - n8, err := m.Throttling.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n8 - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *CPUUsage) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CPUUsage) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Total != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Total)) - } - if m.Kernel != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Kernel)) - } - if m.User != 0 { - dAtA[i] = 0x18 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.User)) - } - if len(m.PerCPU) > 0 { - dAtA10 := make([]byte, len(m.PerCPU)*10) - var j9 int - for _, num := range m.PerCPU { - for num >= 1<<7 { - dAtA10[j9] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j9++ - } - dAtA10[j9] = uint8(num) - j9++ - } - dAtA[i] = 0x22 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(j9)) - i += copy(dAtA[i:], dAtA10[:j9]) - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *Throttle) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *Throttle) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Periods != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Periods)) - } - if m.ThrottledPeriods != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.ThrottledPeriods)) - } - if m.ThrottledTime != 0 { - dAtA[i] = 0x18 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.ThrottledTime)) - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *MemoryStat) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MemoryStat) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Cache != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Cache)) - } - if m.RSS != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.RSS)) - } - if m.RSSHuge != 0 { - dAtA[i] = 0x18 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.RSSHuge)) - } - if m.MappedFile != 0 { - dAtA[i] = 0x20 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.MappedFile)) - } - if m.Dirty != 0 { - dAtA[i] = 0x28 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Dirty)) - } - if m.Writeback != 0 { - dAtA[i] = 0x30 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Writeback)) - } - if m.PgPgIn != 0 { - dAtA[i] = 0x38 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.PgPgIn)) - } - if m.PgPgOut != 0 { - dAtA[i] = 0x40 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.PgPgOut)) - } - if m.PgFault != 0 { - dAtA[i] = 0x48 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.PgFault)) - } - if m.PgMajFault != 0 { - dAtA[i] = 0x50 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.PgMajFault)) - } - if m.InactiveAnon != 0 { - dAtA[i] = 0x58 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.InactiveAnon)) - } - if m.ActiveAnon != 0 { - dAtA[i] = 0x60 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.ActiveAnon)) - } - if m.InactiveFile != 0 { - dAtA[i] = 0x68 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.InactiveFile)) - } - if m.ActiveFile != 0 { - dAtA[i] = 0x70 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.ActiveFile)) - } - if m.Unevictable != 0 { - dAtA[i] = 0x78 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Unevictable)) - } - if m.HierarchicalMemoryLimit != 0 { - dAtA[i] = 0x80 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.HierarchicalMemoryLimit)) - } - if m.HierarchicalSwapLimit != 0 { - dAtA[i] = 0x88 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.HierarchicalSwapLimit)) - } - if m.TotalCache != 0 { - dAtA[i] = 0x90 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalCache)) - } - if m.TotalRSS != 0 { - dAtA[i] = 0x98 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalRSS)) - } - if m.TotalRSSHuge != 0 { - dAtA[i] = 0xa0 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalRSSHuge)) - } - if m.TotalMappedFile != 0 { - dAtA[i] = 0xa8 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalMappedFile)) - } - if m.TotalDirty != 0 { - dAtA[i] = 0xb0 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalDirty)) - } - if m.TotalWriteback != 0 { - dAtA[i] = 0xb8 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalWriteback)) - } - if m.TotalPgPgIn != 0 { - dAtA[i] = 0xc0 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalPgPgIn)) - } - if m.TotalPgPgOut != 0 { - dAtA[i] = 0xc8 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalPgPgOut)) - } - if m.TotalPgFault != 0 { - dAtA[i] = 0xd0 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalPgFault)) - } - if m.TotalPgMajFault != 0 { - dAtA[i] = 0xd8 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalPgMajFault)) - } - if m.TotalInactiveAnon != 0 { - dAtA[i] = 0xe0 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalInactiveAnon)) - } - if m.TotalActiveAnon != 0 { - dAtA[i] = 0xe8 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalActiveAnon)) - } - if m.TotalInactiveFile != 0 { - dAtA[i] = 0xf0 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalInactiveFile)) - } - if m.TotalActiveFile != 0 { - dAtA[i] = 0xf8 - i++ - dAtA[i] = 0x1 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalActiveFile)) - } - if m.TotalUnevictable != 0 { - dAtA[i] = 0x80 - i++ - dAtA[i] = 0x2 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TotalUnevictable)) - } - if m.Usage != nil { - dAtA[i] = 0x8a - i++ - dAtA[i] = 0x2 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Usage.Size())) - n11, err := m.Usage.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n11 - } - if m.Swap != nil { - dAtA[i] = 0x92 - i++ - dAtA[i] = 0x2 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Swap.Size())) - n12, err := m.Swap.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n12 - } - if m.Kernel != nil { - dAtA[i] = 0x9a - i++ - dAtA[i] = 0x2 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Kernel.Size())) - n13, err := m.Kernel.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n13 - } - if m.KernelTCP != nil { - dAtA[i] = 0xa2 - i++ - dAtA[i] = 0x2 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.KernelTCP.Size())) - n14, err := m.KernelTCP.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n14 - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *MemoryEntry) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MemoryEntry) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Limit != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Limit)) - } - if m.Usage != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Usage)) - } - if m.Max != 0 { - dAtA[i] = 0x18 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Max)) - } - if m.Failcnt != 0 { - dAtA[i] = 0x20 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Failcnt)) - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *MemoryOomControl) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *MemoryOomControl) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.OomKillDisable != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.OomKillDisable)) - } - if m.UnderOom != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.UnderOom)) - } - if m.OomKill != 0 { - dAtA[i] = 0x18 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.OomKill)) - } - return i, nil -} - -func (m *BlkIOStat) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *BlkIOStat) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.IoServiceBytesRecursive) > 0 { - for _, msg := range m.IoServiceBytesRecursive { - dAtA[i] = 0xa - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if len(m.IoServicedRecursive) > 0 { - for _, msg := range m.IoServicedRecursive { - dAtA[i] = 0x12 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if len(m.IoQueuedRecursive) > 0 { - for _, msg := range m.IoQueuedRecursive { - dAtA[i] = 0x1a - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if len(m.IoServiceTimeRecursive) > 0 { - for _, msg := range m.IoServiceTimeRecursive { - dAtA[i] = 0x22 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if len(m.IoWaitTimeRecursive) > 0 { - for _, msg := range m.IoWaitTimeRecursive { - dAtA[i] = 0x2a - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if len(m.IoMergedRecursive) > 0 { - for _, msg := range m.IoMergedRecursive { - dAtA[i] = 0x32 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if len(m.IoTimeRecursive) > 0 { - for _, msg := range m.IoTimeRecursive { - dAtA[i] = 0x3a - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if len(m.SectorsRecursive) > 0 { - for _, msg := range m.SectorsRecursive { - dAtA[i] = 0x42 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *BlkIOEntry) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *BlkIOEntry) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Op) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintMetrics(dAtA, i, uint64(len(m.Op))) - i += copy(dAtA[i:], m.Op) - } - if len(m.Device) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(len(m.Device))) - i += copy(dAtA[i:], m.Device) - } - if m.Major != 0 { - dAtA[i] = 0x18 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Major)) - } - if m.Minor != 0 { - dAtA[i] = 0x20 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Minor)) - } - if m.Value != 0 { - dAtA[i] = 0x28 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.Value)) - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *RdmaStat) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *RdmaStat) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Current) > 0 { - for _, msg := range m.Current { - dAtA[i] = 0xa - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if len(m.Limit) > 0 { - for _, msg := range m.Limit { - dAtA[i] = 0x12 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *RdmaEntry) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *RdmaEntry) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Device) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintMetrics(dAtA, i, uint64(len(m.Device))) - i += copy(dAtA[i:], m.Device) - } - if m.HcaHandles != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.HcaHandles)) - } - if m.HcaObjects != 0 { - dAtA[i] = 0x18 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.HcaObjects)) - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *NetworkStat) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *NetworkStat) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Name) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintMetrics(dAtA, i, uint64(len(m.Name))) - i += copy(dAtA[i:], m.Name) - } - if m.RxBytes != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.RxBytes)) - } - if m.RxPackets != 0 { - dAtA[i] = 0x18 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.RxPackets)) - } - if m.RxErrors != 0 { - dAtA[i] = 0x20 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.RxErrors)) - } - if m.RxDropped != 0 { - dAtA[i] = 0x28 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.RxDropped)) - } - if m.TxBytes != 0 { - dAtA[i] = 0x30 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TxBytes)) - } - if m.TxPackets != 0 { - dAtA[i] = 0x38 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TxPackets)) - } - if m.TxErrors != 0 { - dAtA[i] = 0x40 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TxErrors)) - } - if m.TxDropped != 0 { - dAtA[i] = 0x48 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.TxDropped)) - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func (m *CgroupStats) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *CgroupStats) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.NrSleeping != 0 { - dAtA[i] = 0x8 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.NrSleeping)) - } - if m.NrRunning != 0 { - dAtA[i] = 0x10 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.NrRunning)) - } - if m.NrStopped != 0 { - dAtA[i] = 0x18 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.NrStopped)) - } - if m.NrUninterruptible != 0 { - dAtA[i] = 0x20 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.NrUninterruptible)) - } - if m.NrIoWait != 0 { - dAtA[i] = 0x28 - i++ - i = encodeVarintMetrics(dAtA, i, uint64(m.NrIoWait)) - } - if m.XXX_unrecognized != nil { - i += copy(dAtA[i:], m.XXX_unrecognized) - } - return i, nil -} - -func encodeVarintMetrics(dAtA []byte, offset int, v uint64) int { - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return offset + 1 -} -func (m *Metrics) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Hugetlb) > 0 { - for _, e := range m.Hugetlb { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if m.Pids != nil { - l = m.Pids.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - if m.CPU != nil { - l = m.CPU.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - if m.Memory != nil { - l = m.Memory.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - if m.Blkio != nil { - l = m.Blkio.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - if m.Rdma != nil { - l = m.Rdma.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - if len(m.Network) > 0 { - for _, e := range m.Network { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if m.CgroupStats != nil { - l = m.CgroupStats.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - if m.MemoryOomControl != nil { - l = m.MemoryOomControl.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *HugetlbStat) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Usage != 0 { - n += 1 + sovMetrics(uint64(m.Usage)) - } - if m.Max != 0 { - n += 1 + sovMetrics(uint64(m.Max)) - } - if m.Failcnt != 0 { - n += 1 + sovMetrics(uint64(m.Failcnt)) - } - l = len(m.Pagesize) - if l > 0 { - n += 1 + l + sovMetrics(uint64(l)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *PidsStat) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Current != 0 { - n += 1 + sovMetrics(uint64(m.Current)) - } - if m.Limit != 0 { - n += 1 + sovMetrics(uint64(m.Limit)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *CPUStat) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Usage != nil { - l = m.Usage.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - if m.Throttling != nil { - l = m.Throttling.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *CPUUsage) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Total != 0 { - n += 1 + sovMetrics(uint64(m.Total)) - } - if m.Kernel != 0 { - n += 1 + sovMetrics(uint64(m.Kernel)) - } - if m.User != 0 { - n += 1 + sovMetrics(uint64(m.User)) - } - if len(m.PerCPU) > 0 { - l = 0 - for _, e := range m.PerCPU { - l += sovMetrics(uint64(e)) - } - n += 1 + sovMetrics(uint64(l)) + l - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *Throttle) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Periods != 0 { - n += 1 + sovMetrics(uint64(m.Periods)) - } - if m.ThrottledPeriods != 0 { - n += 1 + sovMetrics(uint64(m.ThrottledPeriods)) - } - if m.ThrottledTime != 0 { - n += 1 + sovMetrics(uint64(m.ThrottledTime)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *MemoryStat) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Cache != 0 { - n += 1 + sovMetrics(uint64(m.Cache)) - } - if m.RSS != 0 { - n += 1 + sovMetrics(uint64(m.RSS)) - } - if m.RSSHuge != 0 { - n += 1 + sovMetrics(uint64(m.RSSHuge)) - } - if m.MappedFile != 0 { - n += 1 + sovMetrics(uint64(m.MappedFile)) - } - if m.Dirty != 0 { - n += 1 + sovMetrics(uint64(m.Dirty)) - } - if m.Writeback != 0 { - n += 1 + sovMetrics(uint64(m.Writeback)) - } - if m.PgPgIn != 0 { - n += 1 + sovMetrics(uint64(m.PgPgIn)) - } - if m.PgPgOut != 0 { - n += 1 + sovMetrics(uint64(m.PgPgOut)) - } - if m.PgFault != 0 { - n += 1 + sovMetrics(uint64(m.PgFault)) - } - if m.PgMajFault != 0 { - n += 1 + sovMetrics(uint64(m.PgMajFault)) - } - if m.InactiveAnon != 0 { - n += 1 + sovMetrics(uint64(m.InactiveAnon)) - } - if m.ActiveAnon != 0 { - n += 1 + sovMetrics(uint64(m.ActiveAnon)) - } - if m.InactiveFile != 0 { - n += 1 + sovMetrics(uint64(m.InactiveFile)) - } - if m.ActiveFile != 0 { - n += 1 + sovMetrics(uint64(m.ActiveFile)) - } - if m.Unevictable != 0 { - n += 1 + sovMetrics(uint64(m.Unevictable)) - } - if m.HierarchicalMemoryLimit != 0 { - n += 2 + sovMetrics(uint64(m.HierarchicalMemoryLimit)) - } - if m.HierarchicalSwapLimit != 0 { - n += 2 + sovMetrics(uint64(m.HierarchicalSwapLimit)) - } - if m.TotalCache != 0 { - n += 2 + sovMetrics(uint64(m.TotalCache)) - } - if m.TotalRSS != 0 { - n += 2 + sovMetrics(uint64(m.TotalRSS)) - } - if m.TotalRSSHuge != 0 { - n += 2 + sovMetrics(uint64(m.TotalRSSHuge)) - } - if m.TotalMappedFile != 0 { - n += 2 + sovMetrics(uint64(m.TotalMappedFile)) - } - if m.TotalDirty != 0 { - n += 2 + sovMetrics(uint64(m.TotalDirty)) - } - if m.TotalWriteback != 0 { - n += 2 + sovMetrics(uint64(m.TotalWriteback)) - } - if m.TotalPgPgIn != 0 { - n += 2 + sovMetrics(uint64(m.TotalPgPgIn)) - } - if m.TotalPgPgOut != 0 { - n += 2 + sovMetrics(uint64(m.TotalPgPgOut)) - } - if m.TotalPgFault != 0 { - n += 2 + sovMetrics(uint64(m.TotalPgFault)) - } - if m.TotalPgMajFault != 0 { - n += 2 + sovMetrics(uint64(m.TotalPgMajFault)) - } - if m.TotalInactiveAnon != 0 { - n += 2 + sovMetrics(uint64(m.TotalInactiveAnon)) - } - if m.TotalActiveAnon != 0 { - n += 2 + sovMetrics(uint64(m.TotalActiveAnon)) - } - if m.TotalInactiveFile != 0 { - n += 2 + sovMetrics(uint64(m.TotalInactiveFile)) - } - if m.TotalActiveFile != 0 { - n += 2 + sovMetrics(uint64(m.TotalActiveFile)) - } - if m.TotalUnevictable != 0 { - n += 2 + sovMetrics(uint64(m.TotalUnevictable)) - } - if m.Usage != nil { - l = m.Usage.Size() - n += 2 + l + sovMetrics(uint64(l)) - } - if m.Swap != nil { - l = m.Swap.Size() - n += 2 + l + sovMetrics(uint64(l)) - } - if m.Kernel != nil { - l = m.Kernel.Size() - n += 2 + l + sovMetrics(uint64(l)) - } - if m.KernelTCP != nil { - l = m.KernelTCP.Size() - n += 2 + l + sovMetrics(uint64(l)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *MemoryEntry) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.Limit != 0 { - n += 1 + sovMetrics(uint64(m.Limit)) - } - if m.Usage != 0 { - n += 1 + sovMetrics(uint64(m.Usage)) - } - if m.Max != 0 { - n += 1 + sovMetrics(uint64(m.Max)) - } - if m.Failcnt != 0 { - n += 1 + sovMetrics(uint64(m.Failcnt)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *MemoryOomControl) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.OomKillDisable != 0 { - n += 1 + sovMetrics(uint64(m.OomKillDisable)) - } - if m.UnderOom != 0 { - n += 1 + sovMetrics(uint64(m.UnderOom)) - } - if m.OomKill != 0 { - n += 1 + sovMetrics(uint64(m.OomKill)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *BlkIOStat) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.IoServiceBytesRecursive) > 0 { - for _, e := range m.IoServiceBytesRecursive { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if len(m.IoServicedRecursive) > 0 { - for _, e := range m.IoServicedRecursive { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if len(m.IoQueuedRecursive) > 0 { - for _, e := range m.IoQueuedRecursive { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if len(m.IoServiceTimeRecursive) > 0 { - for _, e := range m.IoServiceTimeRecursive { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if len(m.IoWaitTimeRecursive) > 0 { - for _, e := range m.IoWaitTimeRecursive { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if len(m.IoMergedRecursive) > 0 { - for _, e := range m.IoMergedRecursive { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if len(m.IoTimeRecursive) > 0 { - for _, e := range m.IoTimeRecursive { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if len(m.SectorsRecursive) > 0 { - for _, e := range m.SectorsRecursive { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *BlkIOEntry) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Op) - if l > 0 { - n += 1 + l + sovMetrics(uint64(l)) - } - l = len(m.Device) - if l > 0 { - n += 1 + l + sovMetrics(uint64(l)) - } - if m.Major != 0 { - n += 1 + sovMetrics(uint64(m.Major)) - } - if m.Minor != 0 { - n += 1 + sovMetrics(uint64(m.Minor)) - } - if m.Value != 0 { - n += 1 + sovMetrics(uint64(m.Value)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *RdmaStat) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if len(m.Current) > 0 { - for _, e := range m.Current { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if len(m.Limit) > 0 { - for _, e := range m.Limit { - l = e.Size() - n += 1 + l + sovMetrics(uint64(l)) - } - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *RdmaEntry) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Device) - if l > 0 { - n += 1 + l + sovMetrics(uint64(l)) - } - if m.HcaHandles != 0 { - n += 1 + sovMetrics(uint64(m.HcaHandles)) - } - if m.HcaObjects != 0 { - n += 1 + sovMetrics(uint64(m.HcaObjects)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *NetworkStat) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovMetrics(uint64(l)) - } - if m.RxBytes != 0 { - n += 1 + sovMetrics(uint64(m.RxBytes)) - } - if m.RxPackets != 0 { - n += 1 + sovMetrics(uint64(m.RxPackets)) - } - if m.RxErrors != 0 { - n += 1 + sovMetrics(uint64(m.RxErrors)) - } - if m.RxDropped != 0 { - n += 1 + sovMetrics(uint64(m.RxDropped)) - } - if m.TxBytes != 0 { - n += 1 + sovMetrics(uint64(m.TxBytes)) - } - if m.TxPackets != 0 { - n += 1 + sovMetrics(uint64(m.TxPackets)) - } - if m.TxErrors != 0 { - n += 1 + sovMetrics(uint64(m.TxErrors)) - } - if m.TxDropped != 0 { - n += 1 + sovMetrics(uint64(m.TxDropped)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func (m *CgroupStats) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - if m.NrSleeping != 0 { - n += 1 + sovMetrics(uint64(m.NrSleeping)) - } - if m.NrRunning != 0 { - n += 1 + sovMetrics(uint64(m.NrRunning)) - } - if m.NrStopped != 0 { - n += 1 + sovMetrics(uint64(m.NrStopped)) - } - if m.NrUninterruptible != 0 { - n += 1 + sovMetrics(uint64(m.NrUninterruptible)) - } - if m.NrIoWait != 0 { - n += 1 + sovMetrics(uint64(m.NrIoWait)) - } - if m.XXX_unrecognized != nil { - n += len(m.XXX_unrecognized) - } - return n -} - -func sovMetrics(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} -func sozMetrics(x uint64) (n int) { - return sovMetrics(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (this *Metrics) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&Metrics{`, - `Hugetlb:` + strings.Replace(fmt.Sprintf("%v", this.Hugetlb), "HugetlbStat", "HugetlbStat", 1) + `,`, - `Pids:` + strings.Replace(fmt.Sprintf("%v", this.Pids), "PidsStat", "PidsStat", 1) + `,`, - `CPU:` + strings.Replace(fmt.Sprintf("%v", this.CPU), "CPUStat", "CPUStat", 1) + `,`, - `Memory:` + strings.Replace(fmt.Sprintf("%v", this.Memory), "MemoryStat", "MemoryStat", 1) + `,`, - `MemoryOomControl:` + strings.Replace(fmt.Sprintf("%v", this.MemoryOomControl), "MemoryOomControl", "MemoryOomControl", 1) + `,`, - `Blkio:` + strings.Replace(fmt.Sprintf("%v", this.Blkio), "BlkIOStat", "BlkIOStat", 1) + `,`, - `Rdma:` + strings.Replace(fmt.Sprintf("%v", this.Rdma), "RdmaStat", "RdmaStat", 1) + `,`, - `Network:` + strings.Replace(fmt.Sprintf("%v", this.Network), "NetworkStat", "NetworkStat", 1) + `,`, - `CgroupStats:` + strings.Replace(fmt.Sprintf("%v", this.CgroupStats), "CgroupStats", "CgroupStats", 1) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *HugetlbStat) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&HugetlbStat{`, - `Usage:` + fmt.Sprintf("%v", this.Usage) + `,`, - `Max:` + fmt.Sprintf("%v", this.Max) + `,`, - `Failcnt:` + fmt.Sprintf("%v", this.Failcnt) + `,`, - `Pagesize:` + fmt.Sprintf("%v", this.Pagesize) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *PidsStat) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&PidsStat{`, - `Current:` + fmt.Sprintf("%v", this.Current) + `,`, - `Limit:` + fmt.Sprintf("%v", this.Limit) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *CPUStat) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&CPUStat{`, - `Usage:` + strings.Replace(fmt.Sprintf("%v", this.Usage), "CPUUsage", "CPUUsage", 1) + `,`, - `Throttling:` + strings.Replace(fmt.Sprintf("%v", this.Throttling), "Throttle", "Throttle", 1) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *CPUUsage) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&CPUUsage{`, - `Total:` + fmt.Sprintf("%v", this.Total) + `,`, - `Kernel:` + fmt.Sprintf("%v", this.Kernel) + `,`, - `User:` + fmt.Sprintf("%v", this.User) + `,`, - `PerCPU:` + fmt.Sprintf("%v", this.PerCPU) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *Throttle) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&Throttle{`, - `Periods:` + fmt.Sprintf("%v", this.Periods) + `,`, - `ThrottledPeriods:` + fmt.Sprintf("%v", this.ThrottledPeriods) + `,`, - `ThrottledTime:` + fmt.Sprintf("%v", this.ThrottledTime) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *MemoryStat) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&MemoryStat{`, - `Cache:` + fmt.Sprintf("%v", this.Cache) + `,`, - `RSS:` + fmt.Sprintf("%v", this.RSS) + `,`, - `RSSHuge:` + fmt.Sprintf("%v", this.RSSHuge) + `,`, - `MappedFile:` + fmt.Sprintf("%v", this.MappedFile) + `,`, - `Dirty:` + fmt.Sprintf("%v", this.Dirty) + `,`, - `Writeback:` + fmt.Sprintf("%v", this.Writeback) + `,`, - `PgPgIn:` + fmt.Sprintf("%v", this.PgPgIn) + `,`, - `PgPgOut:` + fmt.Sprintf("%v", this.PgPgOut) + `,`, - `PgFault:` + fmt.Sprintf("%v", this.PgFault) + `,`, - `PgMajFault:` + fmt.Sprintf("%v", this.PgMajFault) + `,`, - `InactiveAnon:` + fmt.Sprintf("%v", this.InactiveAnon) + `,`, - `ActiveAnon:` + fmt.Sprintf("%v", this.ActiveAnon) + `,`, - `InactiveFile:` + fmt.Sprintf("%v", this.InactiveFile) + `,`, - `ActiveFile:` + fmt.Sprintf("%v", this.ActiveFile) + `,`, - `Unevictable:` + fmt.Sprintf("%v", this.Unevictable) + `,`, - `HierarchicalMemoryLimit:` + fmt.Sprintf("%v", this.HierarchicalMemoryLimit) + `,`, - `HierarchicalSwapLimit:` + fmt.Sprintf("%v", this.HierarchicalSwapLimit) + `,`, - `TotalCache:` + fmt.Sprintf("%v", this.TotalCache) + `,`, - `TotalRSS:` + fmt.Sprintf("%v", this.TotalRSS) + `,`, - `TotalRSSHuge:` + fmt.Sprintf("%v", this.TotalRSSHuge) + `,`, - `TotalMappedFile:` + fmt.Sprintf("%v", this.TotalMappedFile) + `,`, - `TotalDirty:` + fmt.Sprintf("%v", this.TotalDirty) + `,`, - `TotalWriteback:` + fmt.Sprintf("%v", this.TotalWriteback) + `,`, - `TotalPgPgIn:` + fmt.Sprintf("%v", this.TotalPgPgIn) + `,`, - `TotalPgPgOut:` + fmt.Sprintf("%v", this.TotalPgPgOut) + `,`, - `TotalPgFault:` + fmt.Sprintf("%v", this.TotalPgFault) + `,`, - `TotalPgMajFault:` + fmt.Sprintf("%v", this.TotalPgMajFault) + `,`, - `TotalInactiveAnon:` + fmt.Sprintf("%v", this.TotalInactiveAnon) + `,`, - `TotalActiveAnon:` + fmt.Sprintf("%v", this.TotalActiveAnon) + `,`, - `TotalInactiveFile:` + fmt.Sprintf("%v", this.TotalInactiveFile) + `,`, - `TotalActiveFile:` + fmt.Sprintf("%v", this.TotalActiveFile) + `,`, - `TotalUnevictable:` + fmt.Sprintf("%v", this.TotalUnevictable) + `,`, - `Usage:` + strings.Replace(fmt.Sprintf("%v", this.Usage), "MemoryEntry", "MemoryEntry", 1) + `,`, - `Swap:` + strings.Replace(fmt.Sprintf("%v", this.Swap), "MemoryEntry", "MemoryEntry", 1) + `,`, - `Kernel:` + strings.Replace(fmt.Sprintf("%v", this.Kernel), "MemoryEntry", "MemoryEntry", 1) + `,`, - `KernelTCP:` + strings.Replace(fmt.Sprintf("%v", this.KernelTCP), "MemoryEntry", "MemoryEntry", 1) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *MemoryEntry) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&MemoryEntry{`, - `Limit:` + fmt.Sprintf("%v", this.Limit) + `,`, - `Usage:` + fmt.Sprintf("%v", this.Usage) + `,`, - `Max:` + fmt.Sprintf("%v", this.Max) + `,`, - `Failcnt:` + fmt.Sprintf("%v", this.Failcnt) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *MemoryOomControl) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&MemoryOomControl{`, - `OomKillDisable:` + fmt.Sprintf("%v", this.OomKillDisable) + `,`, - `UnderOom:` + fmt.Sprintf("%v", this.UnderOom) + `,`, - `OomKill:` + fmt.Sprintf("%v", this.OomKill) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *BlkIOStat) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&BlkIOStat{`, - `IoServiceBytesRecursive:` + strings.Replace(fmt.Sprintf("%v", this.IoServiceBytesRecursive), "BlkIOEntry", "BlkIOEntry", 1) + `,`, - `IoServicedRecursive:` + strings.Replace(fmt.Sprintf("%v", this.IoServicedRecursive), "BlkIOEntry", "BlkIOEntry", 1) + `,`, - `IoQueuedRecursive:` + strings.Replace(fmt.Sprintf("%v", this.IoQueuedRecursive), "BlkIOEntry", "BlkIOEntry", 1) + `,`, - `IoServiceTimeRecursive:` + strings.Replace(fmt.Sprintf("%v", this.IoServiceTimeRecursive), "BlkIOEntry", "BlkIOEntry", 1) + `,`, - `IoWaitTimeRecursive:` + strings.Replace(fmt.Sprintf("%v", this.IoWaitTimeRecursive), "BlkIOEntry", "BlkIOEntry", 1) + `,`, - `IoMergedRecursive:` + strings.Replace(fmt.Sprintf("%v", this.IoMergedRecursive), "BlkIOEntry", "BlkIOEntry", 1) + `,`, - `IoTimeRecursive:` + strings.Replace(fmt.Sprintf("%v", this.IoTimeRecursive), "BlkIOEntry", "BlkIOEntry", 1) + `,`, - `SectorsRecursive:` + strings.Replace(fmt.Sprintf("%v", this.SectorsRecursive), "BlkIOEntry", "BlkIOEntry", 1) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *BlkIOEntry) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&BlkIOEntry{`, - `Op:` + fmt.Sprintf("%v", this.Op) + `,`, - `Device:` + fmt.Sprintf("%v", this.Device) + `,`, - `Major:` + fmt.Sprintf("%v", this.Major) + `,`, - `Minor:` + fmt.Sprintf("%v", this.Minor) + `,`, - `Value:` + fmt.Sprintf("%v", this.Value) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *RdmaStat) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&RdmaStat{`, - `Current:` + strings.Replace(fmt.Sprintf("%v", this.Current), "RdmaEntry", "RdmaEntry", 1) + `,`, - `Limit:` + strings.Replace(fmt.Sprintf("%v", this.Limit), "RdmaEntry", "RdmaEntry", 1) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *RdmaEntry) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&RdmaEntry{`, - `Device:` + fmt.Sprintf("%v", this.Device) + `,`, - `HcaHandles:` + fmt.Sprintf("%v", this.HcaHandles) + `,`, - `HcaObjects:` + fmt.Sprintf("%v", this.HcaObjects) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *NetworkStat) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&NetworkStat{`, - `Name:` + fmt.Sprintf("%v", this.Name) + `,`, - `RxBytes:` + fmt.Sprintf("%v", this.RxBytes) + `,`, - `RxPackets:` + fmt.Sprintf("%v", this.RxPackets) + `,`, - `RxErrors:` + fmt.Sprintf("%v", this.RxErrors) + `,`, - `RxDropped:` + fmt.Sprintf("%v", this.RxDropped) + `,`, - `TxBytes:` + fmt.Sprintf("%v", this.TxBytes) + `,`, - `TxPackets:` + fmt.Sprintf("%v", this.TxPackets) + `,`, - `TxErrors:` + fmt.Sprintf("%v", this.TxErrors) + `,`, - `TxDropped:` + fmt.Sprintf("%v", this.TxDropped) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func (this *CgroupStats) String() string { - if this == nil { - return "nil" - } - s := strings.Join([]string{`&CgroupStats{`, - `NrSleeping:` + fmt.Sprintf("%v", this.NrSleeping) + `,`, - `NrRunning:` + fmt.Sprintf("%v", this.NrRunning) + `,`, - `NrStopped:` + fmt.Sprintf("%v", this.NrStopped) + `,`, - `NrUninterruptible:` + fmt.Sprintf("%v", this.NrUninterruptible) + `,`, - `NrIoWait:` + fmt.Sprintf("%v", this.NrIoWait) + `,`, - `XXX_unrecognized:` + fmt.Sprintf("%v", this.XXX_unrecognized) + `,`, - `}`, - }, "") - return s -} -func valueToStringMetrics(v interface{}) string { - rv := reflect.ValueOf(v) - if rv.IsNil() { - return "nil" - } - pv := reflect.Indirect(rv).Interface() - return fmt.Sprintf("*%v", pv) -} -func (m *Metrics) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Metrics: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Metrics: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Hugetlb", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Hugetlb = append(m.Hugetlb, &HugetlbStat{}) - if err := m.Hugetlb[len(m.Hugetlb)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pids", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Pids == nil { - m.Pids = &PidsStat{} - } - if err := m.Pids.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CPU", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.CPU == nil { - m.CPU = &CPUStat{} - } - if err := m.CPU.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Memory", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Memory == nil { - m.Memory = &MemoryStat{} - } - if err := m.Memory.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Blkio", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Blkio == nil { - m.Blkio = &BlkIOStat{} - } - if err := m.Blkio.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Rdma", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Rdma == nil { - m.Rdma = &RdmaStat{} - } - if err := m.Rdma.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Network", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Network = append(m.Network, &NetworkStat{}) - if err := m.Network[len(m.Network)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CgroupStats", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.CgroupStats == nil { - m.CgroupStats = &CgroupStats{} - } - if err := m.CgroupStats.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 9: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field MemoryOomControl", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.MemoryOomControl == nil { - m.MemoryOomControl = &MemoryOomControl{} - } - if err := m.MemoryOomControl.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *HugetlbStat) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: HugetlbStat: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: HugetlbStat: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Usage", wireType) - } - m.Usage = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Usage |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Max", wireType) - } - m.Max = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Max |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Failcnt", wireType) - } - m.Failcnt = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Failcnt |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Pagesize", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Pagesize = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PidsStat) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PidsStat: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PidsStat: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Current", wireType) - } - m.Current = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Current |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType) - } - m.Limit = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Limit |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CPUStat) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CPUStat: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CPUStat: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Usage", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Usage == nil { - m.Usage = &CPUUsage{} - } - if err := m.Usage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Throttling", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Throttling == nil { - m.Throttling = &Throttle{} - } - if err := m.Throttling.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CPUUsage) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CPUUsage: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CPUUsage: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Total", wireType) - } - m.Total = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Total |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Kernel", wireType) - } - m.Kernel = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Kernel |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field User", wireType) - } - m.User = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.User |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType == 0 { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.PerCPU = append(m.PerCPU, v) - } else if wireType == 2 { - var packedLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - packedLen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if packedLen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + packedLen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count - if elementCount != 0 && len(m.PerCPU) == 0 { - m.PerCPU = make([]uint64, 0, elementCount) - } - for iNdEx < postIndex { - var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - m.PerCPU = append(m.PerCPU, v) - } - } else { - return fmt.Errorf("proto: wrong wireType = %d for field PerCPU", wireType) - } - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Throttle) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Throttle: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Throttle: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Periods", wireType) - } - m.Periods = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Periods |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ThrottledPeriods", wireType) - } - m.ThrottledPeriods = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ThrottledPeriods |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ThrottledTime", wireType) - } - m.ThrottledTime = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ThrottledTime |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MemoryStat) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MemoryStat: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MemoryStat: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Cache", wireType) - } - m.Cache = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Cache |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field RSS", wireType) - } - m.RSS = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.RSS |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field RSSHuge", wireType) - } - m.RSSHuge = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.RSSHuge |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MappedFile", wireType) - } - m.MappedFile = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.MappedFile |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Dirty", wireType) - } - m.Dirty = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Dirty |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Writeback", wireType) - } - m.Writeback = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Writeback |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 7: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PgPgIn", wireType) - } - m.PgPgIn = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PgPgIn |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PgPgOut", wireType) - } - m.PgPgOut = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PgPgOut |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 9: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PgFault", wireType) - } - m.PgFault = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PgFault |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 10: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field PgMajFault", wireType) - } - m.PgMajFault = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.PgMajFault |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 11: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field InactiveAnon", wireType) - } - m.InactiveAnon = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.InactiveAnon |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 12: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ActiveAnon", wireType) - } - m.ActiveAnon = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ActiveAnon |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 13: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field InactiveFile", wireType) - } - m.InactiveFile = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.InactiveFile |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 14: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ActiveFile", wireType) - } - m.ActiveFile = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.ActiveFile |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 15: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Unevictable", wireType) - } - m.Unevictable = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Unevictable |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 16: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field HierarchicalMemoryLimit", wireType) - } - m.HierarchicalMemoryLimit = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.HierarchicalMemoryLimit |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 17: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field HierarchicalSwapLimit", wireType) - } - m.HierarchicalSwapLimit = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.HierarchicalSwapLimit |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 18: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalCache", wireType) - } - m.TotalCache = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalCache |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 19: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalRSS", wireType) - } - m.TotalRSS = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalRSS |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 20: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalRSSHuge", wireType) - } - m.TotalRSSHuge = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalRSSHuge |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 21: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalMappedFile", wireType) - } - m.TotalMappedFile = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalMappedFile |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 22: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalDirty", wireType) - } - m.TotalDirty = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalDirty |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 23: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalWriteback", wireType) - } - m.TotalWriteback = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalWriteback |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 24: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalPgPgIn", wireType) - } - m.TotalPgPgIn = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalPgPgIn |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 25: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalPgPgOut", wireType) - } - m.TotalPgPgOut = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalPgPgOut |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 26: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalPgFault", wireType) - } - m.TotalPgFault = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalPgFault |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 27: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalPgMajFault", wireType) - } - m.TotalPgMajFault = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalPgMajFault |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 28: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalInactiveAnon", wireType) - } - m.TotalInactiveAnon = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalInactiveAnon |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 29: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalActiveAnon", wireType) - } - m.TotalActiveAnon = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalActiveAnon |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 30: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalInactiveFile", wireType) - } - m.TotalInactiveFile = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalInactiveFile |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 31: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalActiveFile", wireType) - } - m.TotalActiveFile = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalActiveFile |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 32: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TotalUnevictable", wireType) - } - m.TotalUnevictable = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TotalUnevictable |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 33: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Usage", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Usage == nil { - m.Usage = &MemoryEntry{} - } - if err := m.Usage.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 34: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Swap", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Swap == nil { - m.Swap = &MemoryEntry{} - } - if err := m.Swap.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 35: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Kernel", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.Kernel == nil { - m.Kernel = &MemoryEntry{} - } - if err := m.Kernel.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 36: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field KernelTCP", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if m.KernelTCP == nil { - m.KernelTCP = &MemoryEntry{} - } - if err := m.KernelTCP.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MemoryEntry) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MemoryEntry: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MemoryEntry: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType) - } - m.Limit = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Limit |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Usage", wireType) - } - m.Usage = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Usage |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Max", wireType) - } - m.Max = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Max |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Failcnt", wireType) - } - m.Failcnt = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Failcnt |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MemoryOomControl) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MemoryOomControl: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MemoryOomControl: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field OomKillDisable", wireType) - } - m.OomKillDisable = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.OomKillDisable |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field UnderOom", wireType) - } - m.UnderOom = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.UnderOom |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field OomKill", wireType) - } - m.OomKill = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.OomKill |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *BlkIOStat) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BlkIOStat: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BlkIOStat: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IoServiceBytesRecursive", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IoServiceBytesRecursive = append(m.IoServiceBytesRecursive, &BlkIOEntry{}) - if err := m.IoServiceBytesRecursive[len(m.IoServiceBytesRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IoServicedRecursive", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IoServicedRecursive = append(m.IoServicedRecursive, &BlkIOEntry{}) - if err := m.IoServicedRecursive[len(m.IoServicedRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IoQueuedRecursive", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IoQueuedRecursive = append(m.IoQueuedRecursive, &BlkIOEntry{}) - if err := m.IoQueuedRecursive[len(m.IoQueuedRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IoServiceTimeRecursive", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IoServiceTimeRecursive = append(m.IoServiceTimeRecursive, &BlkIOEntry{}) - if err := m.IoServiceTimeRecursive[len(m.IoServiceTimeRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IoWaitTimeRecursive", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IoWaitTimeRecursive = append(m.IoWaitTimeRecursive, &BlkIOEntry{}) - if err := m.IoWaitTimeRecursive[len(m.IoWaitTimeRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IoMergedRecursive", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IoMergedRecursive = append(m.IoMergedRecursive, &BlkIOEntry{}) - if err := m.IoMergedRecursive[len(m.IoMergedRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field IoTimeRecursive", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.IoTimeRecursive = append(m.IoTimeRecursive, &BlkIOEntry{}) - if err := m.IoTimeRecursive[len(m.IoTimeRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 8: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SectorsRecursive", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SectorsRecursive = append(m.SectorsRecursive, &BlkIOEntry{}) - if err := m.SectorsRecursive[len(m.SectorsRecursive)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *BlkIOEntry) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: BlkIOEntry: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: BlkIOEntry: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Op", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Op = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Device", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Device = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Major", wireType) - } - m.Major = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Major |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Minor", wireType) - } - m.Minor = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Minor |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - m.Value = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.Value |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *RdmaStat) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: RdmaStat: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: RdmaStat: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Current", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Current = append(m.Current, &RdmaEntry{}) - if err := m.Current[len(m.Current)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Limit", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= int(b&0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + msglen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Limit = append(m.Limit, &RdmaEntry{}) - if err := m.Limit[len(m.Limit)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *RdmaEntry) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: RdmaEntry: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: RdmaEntry: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Device", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Device = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field HcaHandles", wireType) - } - m.HcaHandles = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.HcaHandles |= uint32(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field HcaObjects", wireType) - } - m.HcaObjects = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.HcaObjects |= uint32(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *NetworkStat) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: NetworkStat: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: NetworkStat: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthMetrics - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthMetrics - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field RxBytes", wireType) - } - m.RxBytes = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.RxBytes |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field RxPackets", wireType) - } - m.RxPackets = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.RxPackets |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field RxErrors", wireType) - } - m.RxErrors = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.RxErrors |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field RxDropped", wireType) - } - m.RxDropped = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.RxDropped |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TxBytes", wireType) - } - m.TxBytes = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TxBytes |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 7: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TxPackets", wireType) - } - m.TxPackets = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TxPackets |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TxErrors", wireType) - } - m.TxErrors = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TxErrors |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 9: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field TxDropped", wireType) - } - m.TxDropped = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.TxDropped |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CgroupStats) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CgroupStats: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CgroupStats: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NrSleeping", wireType) - } - m.NrSleeping = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NrSleeping |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NrRunning", wireType) - } - m.NrRunning = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NrRunning |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 3: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NrStopped", wireType) - } - m.NrStopped = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NrStopped |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NrUninterruptible", wireType) - } - m.NrUninterruptible = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NrUninterruptible |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field NrIoWait", wireType) - } - m.NrIoWait = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowMetrics - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - m.NrIoWait |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipMetrics(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) < 0 { - return ErrInvalidLengthMetrics - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipMetrics(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetrics - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetrics - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - return iNdEx, nil - case 1: - iNdEx += 8 - return iNdEx, nil - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetrics - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if length < 0 { - return 0, ErrInvalidLengthMetrics - } - iNdEx += length - if iNdEx < 0 { - return 0, ErrInvalidLengthMetrics - } - return iNdEx, nil - case 3: - for { - var innerWire uint64 - var start int = iNdEx - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowMetrics - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - innerWire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - innerWireType := int(innerWire & 0x7) - if innerWireType == 4 { - break - } - next, err := skipMetrics(dAtA[start:]) - if err != nil { - return 0, err - } - iNdEx = start + next - if iNdEx < 0 { - return 0, ErrInvalidLengthMetrics - } - } - return iNdEx, nil - case 4: - return iNdEx, nil - case 5: - iNdEx += 4 - return iNdEx, nil - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - } - panic("unreachable") -} - -var ( - ErrInvalidLengthMetrics = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowMetrics = fmt.Errorf("proto: integer overflow") -) diff --git a/vendor/github.com/containerd/cgroups/stats/v1/metrics.pb.txt b/vendor/github.com/containerd/cgroups/stats/v1/metrics.pb.txt deleted file mode 100644 index 3ed0898c..00000000 --- a/vendor/github.com/containerd/cgroups/stats/v1/metrics.pb.txt +++ /dev/null @@ -1,790 +0,0 @@ -file { - name: "github.com/containerd/cgroups/stats/v1/metrics.proto" - package: "io.containerd.cgroups.v1" - dependency: "gogoproto/gogo.proto" - message_type { - name: "Metrics" - field { - name: "hugetlb" - number: 1 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.HugetlbStat" - json_name: "hugetlb" - } - field { - name: "pids" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.PidsStat" - json_name: "pids" - } - field { - name: "cpu" - number: 3 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.CPUStat" - options { - 65004: "CPU" - } - json_name: "cpu" - } - field { - name: "memory" - number: 4 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.MemoryStat" - json_name: "memory" - } - field { - name: "blkio" - number: 5 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.BlkIOStat" - json_name: "blkio" - } - field { - name: "rdma" - number: 6 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.RdmaStat" - json_name: "rdma" - } - field { - name: "network" - number: 7 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.NetworkStat" - json_name: "network" - } - field { - name: "cgroup_stats" - number: 8 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.CgroupStats" - json_name: "cgroupStats" - } - field { - name: "memory_oom_control" - number: 9 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.MemoryOomControl" - json_name: "memoryOomControl" - } - } - message_type { - name: "HugetlbStat" - field { - name: "usage" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "usage" - } - field { - name: "max" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "max" - } - field { - name: "failcnt" - number: 3 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "failcnt" - } - field { - name: "pagesize" - number: 4 - label: LABEL_OPTIONAL - type: TYPE_STRING - json_name: "pagesize" - } - } - message_type { - name: "PidsStat" - field { - name: "current" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "current" - } - field { - name: "limit" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "limit" - } - } - message_type { - name: "CPUStat" - field { - name: "usage" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.CPUUsage" - json_name: "usage" - } - field { - name: "throttling" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.Throttle" - json_name: "throttling" - } - } - message_type { - name: "CPUUsage" - field { - name: "total" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "total" - } - field { - name: "kernel" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "kernel" - } - field { - name: "user" - number: 3 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "user" - } - field { - name: "per_cpu" - number: 4 - label: LABEL_REPEATED - type: TYPE_UINT64 - options { - 65004: "PerCPU" - } - json_name: "perCpu" - } - } - message_type { - name: "Throttle" - field { - name: "periods" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "periods" - } - field { - name: "throttled_periods" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "throttledPeriods" - } - field { - name: "throttled_time" - number: 3 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "throttledTime" - } - } - message_type { - name: "MemoryStat" - field { - name: "cache" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "cache" - } - field { - name: "rss" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - options { - 65004: "RSS" - } - json_name: "rss" - } - field { - name: "rss_huge" - number: 3 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - options { - 65004: "RSSHuge" - } - json_name: "rssHuge" - } - field { - name: "mapped_file" - number: 4 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "mappedFile" - } - field { - name: "dirty" - number: 5 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "dirty" - } - field { - name: "writeback" - number: 6 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "writeback" - } - field { - name: "pg_pg_in" - number: 7 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "pgPgIn" - } - field { - name: "pg_pg_out" - number: 8 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "pgPgOut" - } - field { - name: "pg_fault" - number: 9 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "pgFault" - } - field { - name: "pg_maj_fault" - number: 10 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "pgMajFault" - } - field { - name: "inactive_anon" - number: 11 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "inactiveAnon" - } - field { - name: "active_anon" - number: 12 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "activeAnon" - } - field { - name: "inactive_file" - number: 13 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "inactiveFile" - } - field { - name: "active_file" - number: 14 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "activeFile" - } - field { - name: "unevictable" - number: 15 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "unevictable" - } - field { - name: "hierarchical_memory_limit" - number: 16 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "hierarchicalMemoryLimit" - } - field { - name: "hierarchical_swap_limit" - number: 17 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "hierarchicalSwapLimit" - } - field { - name: "total_cache" - number: 18 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalCache" - } - field { - name: "total_rss" - number: 19 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - options { - 65004: "TotalRSS" - } - json_name: "totalRss" - } - field { - name: "total_rss_huge" - number: 20 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - options { - 65004: "TotalRSSHuge" - } - json_name: "totalRssHuge" - } - field { - name: "total_mapped_file" - number: 21 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalMappedFile" - } - field { - name: "total_dirty" - number: 22 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalDirty" - } - field { - name: "total_writeback" - number: 23 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalWriteback" - } - field { - name: "total_pg_pg_in" - number: 24 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalPgPgIn" - } - field { - name: "total_pg_pg_out" - number: 25 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalPgPgOut" - } - field { - name: "total_pg_fault" - number: 26 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalPgFault" - } - field { - name: "total_pg_maj_fault" - number: 27 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalPgMajFault" - } - field { - name: "total_inactive_anon" - number: 28 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalInactiveAnon" - } - field { - name: "total_active_anon" - number: 29 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalActiveAnon" - } - field { - name: "total_inactive_file" - number: 30 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalInactiveFile" - } - field { - name: "total_active_file" - number: 31 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalActiveFile" - } - field { - name: "total_unevictable" - number: 32 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "totalUnevictable" - } - field { - name: "usage" - number: 33 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.MemoryEntry" - json_name: "usage" - } - field { - name: "swap" - number: 34 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.MemoryEntry" - json_name: "swap" - } - field { - name: "kernel" - number: 35 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.MemoryEntry" - json_name: "kernel" - } - field { - name: "kernel_tcp" - number: 36 - label: LABEL_OPTIONAL - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.MemoryEntry" - options { - 65004: "KernelTCP" - } - json_name: "kernelTcp" - } - } - message_type { - name: "MemoryEntry" - field { - name: "limit" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "limit" - } - field { - name: "usage" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "usage" - } - field { - name: "max" - number: 3 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "max" - } - field { - name: "failcnt" - number: 4 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "failcnt" - } - } - message_type { - name: "MemoryOomControl" - field { - name: "oom_kill_disable" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "oom_kill_disable" - } - field { - name: "under_oom" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "under_oom" - } - field { - name: "oom_kill" - number: 3 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "oom_kill" - } - } - message_type { - name: "BlkIOStat" - field { - name: "io_service_bytes_recursive" - number: 1 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.BlkIOEntry" - json_name: "ioServiceBytesRecursive" - } - field { - name: "io_serviced_recursive" - number: 2 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.BlkIOEntry" - json_name: "ioServicedRecursive" - } - field { - name: "io_queued_recursive" - number: 3 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.BlkIOEntry" - json_name: "ioQueuedRecursive" - } - field { - name: "io_service_time_recursive" - number: 4 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.BlkIOEntry" - json_name: "ioServiceTimeRecursive" - } - field { - name: "io_wait_time_recursive" - number: 5 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.BlkIOEntry" - json_name: "ioWaitTimeRecursive" - } - field { - name: "io_merged_recursive" - number: 6 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.BlkIOEntry" - json_name: "ioMergedRecursive" - } - field { - name: "io_time_recursive" - number: 7 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.BlkIOEntry" - json_name: "ioTimeRecursive" - } - field { - name: "sectors_recursive" - number: 8 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.BlkIOEntry" - json_name: "sectorsRecursive" - } - } - message_type { - name: "BlkIOEntry" - field { - name: "op" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - json_name: "op" - } - field { - name: "device" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_STRING - json_name: "device" - } - field { - name: "major" - number: 3 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "major" - } - field { - name: "minor" - number: 4 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "minor" - } - field { - name: "value" - number: 5 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "value" - } - } - message_type { - name: "RdmaStat" - field { - name: "current" - number: 1 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.RdmaEntry" - json_name: "current" - } - field { - name: "limit" - number: 2 - label: LABEL_REPEATED - type: TYPE_MESSAGE - type_name: ".io.containerd.cgroups.v1.RdmaEntry" - json_name: "limit" - } - } - message_type { - name: "RdmaEntry" - field { - name: "device" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - json_name: "device" - } - field { - name: "hca_handles" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_UINT32 - json_name: "hcaHandles" - } - field { - name: "hca_objects" - number: 3 - label: LABEL_OPTIONAL - type: TYPE_UINT32 - json_name: "hcaObjects" - } - } - message_type { - name: "NetworkStat" - field { - name: "name" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_STRING - json_name: "name" - } - field { - name: "rx_bytes" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "rxBytes" - } - field { - name: "rx_packets" - number: 3 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "rxPackets" - } - field { - name: "rx_errors" - number: 4 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "rxErrors" - } - field { - name: "rx_dropped" - number: 5 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "rxDropped" - } - field { - name: "tx_bytes" - number: 6 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "txBytes" - } - field { - name: "tx_packets" - number: 7 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "txPackets" - } - field { - name: "tx_errors" - number: 8 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "txErrors" - } - field { - name: "tx_dropped" - number: 9 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "txDropped" - } - } - message_type { - name: "CgroupStats" - field { - name: "nr_sleeping" - number: 1 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "nrSleeping" - } - field { - name: "nr_running" - number: 2 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "nrRunning" - } - field { - name: "nr_stopped" - number: 3 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "nrStopped" - } - field { - name: "nr_uninterruptible" - number: 4 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "nrUninterruptible" - } - field { - name: "nr_io_wait" - number: 5 - label: LABEL_OPTIONAL - type: TYPE_UINT64 - json_name: "nrIoWait" - } - } - syntax: "proto3" -} diff --git a/vendor/github.com/containerd/cgroups/stats/v1/metrics.proto b/vendor/github.com/containerd/cgroups/stats/v1/metrics.proto deleted file mode 100644 index b3f6cc37..00000000 --- a/vendor/github.com/containerd/cgroups/stats/v1/metrics.proto +++ /dev/null @@ -1,158 +0,0 @@ -syntax = "proto3"; - -package io.containerd.cgroups.v1; - -import "gogoproto/gogo.proto"; - -message Metrics { - repeated HugetlbStat hugetlb = 1; - PidsStat pids = 2; - CPUStat cpu = 3 [(gogoproto.customname) = "CPU"]; - MemoryStat memory = 4; - BlkIOStat blkio = 5; - RdmaStat rdma = 6; - repeated NetworkStat network = 7; - CgroupStats cgroup_stats = 8; - MemoryOomControl memory_oom_control = 9; -} - -message HugetlbStat { - uint64 usage = 1; - uint64 max = 2; - uint64 failcnt = 3; - string pagesize = 4; -} - -message PidsStat { - uint64 current = 1; - uint64 limit = 2; -} - -message CPUStat { - CPUUsage usage = 1; - Throttle throttling = 2; -} - -message CPUUsage { - // values in nanoseconds - uint64 total = 1; - uint64 kernel = 2; - uint64 user = 3; - repeated uint64 per_cpu = 4 [(gogoproto.customname) = "PerCPU"]; - -} - -message Throttle { - uint64 periods = 1; - uint64 throttled_periods = 2; - uint64 throttled_time = 3; -} - -message MemoryStat { - uint64 cache = 1; - uint64 rss = 2 [(gogoproto.customname) = "RSS"]; - uint64 rss_huge = 3 [(gogoproto.customname) = "RSSHuge"]; - uint64 mapped_file = 4; - uint64 dirty = 5; - uint64 writeback = 6; - uint64 pg_pg_in = 7; - uint64 pg_pg_out = 8; - uint64 pg_fault = 9; - uint64 pg_maj_fault = 10; - uint64 inactive_anon = 11; - uint64 active_anon = 12; - uint64 inactive_file = 13; - uint64 active_file = 14; - uint64 unevictable = 15; - uint64 hierarchical_memory_limit = 16; - uint64 hierarchical_swap_limit = 17; - uint64 total_cache = 18; - uint64 total_rss = 19 [(gogoproto.customname) = "TotalRSS"]; - uint64 total_rss_huge = 20 [(gogoproto.customname) = "TotalRSSHuge"]; - uint64 total_mapped_file = 21; - uint64 total_dirty = 22; - uint64 total_writeback = 23; - uint64 total_pg_pg_in = 24; - uint64 total_pg_pg_out = 25; - uint64 total_pg_fault = 26; - uint64 total_pg_maj_fault = 27; - uint64 total_inactive_anon = 28; - uint64 total_active_anon = 29; - uint64 total_inactive_file = 30; - uint64 total_active_file = 31; - uint64 total_unevictable = 32; - MemoryEntry usage = 33; - MemoryEntry swap = 34; - MemoryEntry kernel = 35; - MemoryEntry kernel_tcp = 36 [(gogoproto.customname) = "KernelTCP"]; - -} - -message MemoryEntry { - uint64 limit = 1; - uint64 usage = 2; - uint64 max = 3; - uint64 failcnt = 4; -} - -message MemoryOomControl { - uint64 oom_kill_disable = 1; - uint64 under_oom = 2; - uint64 oom_kill = 3; -} - -message BlkIOStat { - repeated BlkIOEntry io_service_bytes_recursive = 1; - repeated BlkIOEntry io_serviced_recursive = 2; - repeated BlkIOEntry io_queued_recursive = 3; - repeated BlkIOEntry io_service_time_recursive = 4; - repeated BlkIOEntry io_wait_time_recursive = 5; - repeated BlkIOEntry io_merged_recursive = 6; - repeated BlkIOEntry io_time_recursive = 7; - repeated BlkIOEntry sectors_recursive = 8; -} - -message BlkIOEntry { - string op = 1; - string device = 2; - uint64 major = 3; - uint64 minor = 4; - uint64 value = 5; -} - -message RdmaStat { - repeated RdmaEntry current = 1; - repeated RdmaEntry limit = 2; -} - -message RdmaEntry { - string device = 1; - uint32 hca_handles = 2; - uint32 hca_objects = 3; -} - -message NetworkStat { - string name = 1; - uint64 rx_bytes = 2; - uint64 rx_packets = 3; - uint64 rx_errors = 4; - uint64 rx_dropped = 5; - uint64 tx_bytes = 6; - uint64 tx_packets = 7; - uint64 tx_errors = 8; - uint64 tx_dropped = 9; -} - -// CgroupStats exports per-cgroup statistics. -message CgroupStats { - // number of tasks sleeping - uint64 nr_sleeping = 1; - // number of tasks running - uint64 nr_running = 2; - // number of tasks in stopped state - uint64 nr_stopped = 3; - // number of tasks in uninterruptible state - uint64 nr_uninterruptible = 4; - // number of tasks waiting on IO - uint64 nr_io_wait = 5; -} diff --git a/vendor/github.com/containerd/containerd/LICENSE b/vendor/github.com/containerd/containerd/LICENSE deleted file mode 100644 index 584149b6..00000000 --- a/vendor/github.com/containerd/containerd/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://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 - - Copyright The containerd 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. diff --git a/vendor/github.com/containerd/containerd/NOTICE b/vendor/github.com/containerd/containerd/NOTICE deleted file mode 100644 index 8915f027..00000000 --- a/vendor/github.com/containerd/containerd/NOTICE +++ /dev/null @@ -1,16 +0,0 @@ -Docker -Copyright 2012-2015 Docker, Inc. - -This product includes software developed at Docker, Inc. (https://www.docker.com). - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/containerd/containerd/errdefs/errors.go b/vendor/github.com/containerd/containerd/errdefs/errors.go deleted file mode 100644 index 05a35228..00000000 --- a/vendor/github.com/containerd/containerd/errdefs/errors.go +++ /dev/null @@ -1,93 +0,0 @@ -/* - Copyright The containerd 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 errdefs defines the common errors used throughout containerd -// packages. -// -// Use with errors.Wrap and error.Wrapf to add context to an error. -// -// To detect an error class, use the IsXXX functions to tell whether an error -// is of a certain type. -// -// The functions ToGRPC and FromGRPC can be used to map server-side and -// client-side errors to the correct types. -package errdefs - -import ( - "context" - - "github.com/pkg/errors" -) - -// Definitions of common error types used throughout containerd. All containerd -// errors returned by most packages will map into one of these errors classes. -// Packages should return errors of these types when they want to instruct a -// client to take a particular action. -// -// For the most part, we just try to provide local grpc errors. Most conditions -// map very well to those defined by grpc. -var ( - ErrUnknown = errors.New("unknown") // used internally to represent a missed mapping. - ErrInvalidArgument = errors.New("invalid argument") - ErrNotFound = errors.New("not found") - ErrAlreadyExists = errors.New("already exists") - ErrFailedPrecondition = errors.New("failed precondition") - ErrUnavailable = errors.New("unavailable") - ErrNotImplemented = errors.New("not implemented") // represents not supported and unimplemented -) - -// IsInvalidArgument returns true if the error is due to an invalid argument -func IsInvalidArgument(err error) bool { - return errors.Is(err, ErrInvalidArgument) -} - -// IsNotFound returns true if the error is due to a missing object -func IsNotFound(err error) bool { - return errors.Is(err, ErrNotFound) -} - -// IsAlreadyExists returns true if the error is due to an already existing -// metadata item -func IsAlreadyExists(err error) bool { - return errors.Is(err, ErrAlreadyExists) -} - -// IsFailedPrecondition returns true if an operation could not proceed to the -// lack of a particular condition -func IsFailedPrecondition(err error) bool { - return errors.Is(err, ErrFailedPrecondition) -} - -// IsUnavailable returns true if the error is due to a resource being unavailable -func IsUnavailable(err error) bool { - return errors.Is(err, ErrUnavailable) -} - -// IsNotImplemented returns true if the error is due to not being implemented -func IsNotImplemented(err error) bool { - return errors.Is(err, ErrNotImplemented) -} - -// IsCanceled returns true if the error is due to `context.Canceled`. -func IsCanceled(err error) bool { - return errors.Is(err, context.Canceled) -} - -// IsDeadlineExceeded returns true if the error is due to -// `context.DeadlineExceeded`. -func IsDeadlineExceeded(err error) bool { - return errors.Is(err, context.DeadlineExceeded) -} diff --git a/vendor/github.com/containerd/containerd/errdefs/grpc.go b/vendor/github.com/containerd/containerd/errdefs/grpc.go deleted file mode 100644 index 209f63bd..00000000 --- a/vendor/github.com/containerd/containerd/errdefs/grpc.go +++ /dev/null @@ -1,147 +0,0 @@ -/* - Copyright The containerd 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 errdefs - -import ( - "context" - "strings" - - "github.com/pkg/errors" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// ToGRPC will attempt to map the backend containerd error into a grpc error, -// using the original error message as a description. -// -// Further information may be extracted from certain errors depending on their -// type. -// -// If the error is unmapped, the original error will be returned to be handled -// by the regular grpc error handling stack. -func ToGRPC(err error) error { - if err == nil { - return nil - } - - if isGRPCError(err) { - // error has already been mapped to grpc - return err - } - - switch { - case IsInvalidArgument(err): - return status.Errorf(codes.InvalidArgument, err.Error()) - case IsNotFound(err): - return status.Errorf(codes.NotFound, err.Error()) - case IsAlreadyExists(err): - return status.Errorf(codes.AlreadyExists, err.Error()) - case IsFailedPrecondition(err): - return status.Errorf(codes.FailedPrecondition, err.Error()) - case IsUnavailable(err): - return status.Errorf(codes.Unavailable, err.Error()) - case IsNotImplemented(err): - return status.Errorf(codes.Unimplemented, err.Error()) - case IsCanceled(err): - return status.Errorf(codes.Canceled, err.Error()) - case IsDeadlineExceeded(err): - return status.Errorf(codes.DeadlineExceeded, err.Error()) - } - - return err -} - -// ToGRPCf maps the error to grpc error codes, assembling the formatting string -// and combining it with the target error string. -// -// This is equivalent to errors.ToGRPC(errors.Wrapf(err, format, args...)) -func ToGRPCf(err error, format string, args ...interface{}) error { - return ToGRPC(errors.Wrapf(err, format, args...)) -} - -// FromGRPC returns the underlying error from a grpc service based on the grpc error code -func FromGRPC(err error) error { - if err == nil { - return nil - } - - var cls error // divide these into error classes, becomes the cause - - switch code(err) { - case codes.InvalidArgument: - cls = ErrInvalidArgument - case codes.AlreadyExists: - cls = ErrAlreadyExists - case codes.NotFound: - cls = ErrNotFound - case codes.Unavailable: - cls = ErrUnavailable - case codes.FailedPrecondition: - cls = ErrFailedPrecondition - case codes.Unimplemented: - cls = ErrNotImplemented - case codes.Canceled: - cls = context.Canceled - case codes.DeadlineExceeded: - cls = context.DeadlineExceeded - default: - cls = ErrUnknown - } - - msg := rebaseMessage(cls, err) - if msg != "" { - err = errors.Wrap(cls, msg) - } else { - err = errors.WithStack(cls) - } - - return err -} - -// rebaseMessage removes the repeats for an error at the end of an error -// string. This will happen when taking an error over grpc then remapping it. -// -// Effectively, we just remove the string of cls from the end of err if it -// appears there. -func rebaseMessage(cls error, err error) string { - desc := errDesc(err) - clss := cls.Error() - if desc == clss { - return "" - } - - return strings.TrimSuffix(desc, ": "+clss) -} - -func isGRPCError(err error) bool { - _, ok := status.FromError(err) - return ok -} - -func code(err error) codes.Code { - if s, ok := status.FromError(err); ok { - return s.Code() - } - return codes.Unknown -} - -func errDesc(err error) string { - if s, ok := status.FromError(err); ok { - return s.Message() - } - return err.Error() -} diff --git a/vendor/github.com/containerd/containerd/log/context.go b/vendor/github.com/containerd/containerd/log/context.go deleted file mode 100644 index 37b6a7d1..00000000 --- a/vendor/github.com/containerd/containerd/log/context.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - Copyright The containerd 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 log - -import ( - "context" - - "github.com/sirupsen/logrus" -) - -var ( - // G is an alias for GetLogger. - // - // We may want to define this locally to a package to get package tagged log - // messages. - G = GetLogger - - // L is an alias for the standard logger. - L = logrus.NewEntry(logrus.StandardLogger()) -) - -type ( - loggerKey struct{} -) - -const ( - // RFC3339NanoFixed is time.RFC3339Nano with nanoseconds padded using zeros to - // ensure the formatted time is always the same number of characters. - RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" - - // TextFormat represents the text logging format - TextFormat = "text" - - // JSONFormat represents the JSON logging format - JSONFormat = "json" -) - -// WithLogger returns a new context with the provided logger. Use in -// combination with logger.WithField(s) for great effect. -func WithLogger(ctx context.Context, logger *logrus.Entry) context.Context { - return context.WithValue(ctx, loggerKey{}, logger) -} - -// GetLogger retrieves the current logger from the context. If no logger is -// available, the default logger is returned. -func GetLogger(ctx context.Context) *logrus.Entry { - logger := ctx.Value(loggerKey{}) - - if logger == nil { - return L - } - - return logger.(*logrus.Entry) -} diff --git a/vendor/github.com/containerd/containerd/platforms/compare.go b/vendor/github.com/containerd/containerd/platforms/compare.go deleted file mode 100644 index c7657e18..00000000 --- a/vendor/github.com/containerd/containerd/platforms/compare.go +++ /dev/null @@ -1,193 +0,0 @@ -/* - Copyright The containerd 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 platforms - -import ( - "strconv" - "strings" - - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -// MatchComparer is able to match and compare platforms to -// filter and sort platforms. -type MatchComparer interface { - Matcher - - Less(specs.Platform, specs.Platform) bool -} - -// platformVector returns an (ordered) vector of appropriate specs.Platform -// objects to try matching for the given platform object (see platforms.Only). -func platformVector(platform specs.Platform) []specs.Platform { - vector := []specs.Platform{platform} - - switch platform.Architecture { - case "amd64": - vector = append(vector, specs.Platform{ - Architecture: "386", - OS: platform.OS, - OSVersion: platform.OSVersion, - OSFeatures: platform.OSFeatures, - Variant: platform.Variant, - }) - case "arm": - if armVersion, err := strconv.Atoi(strings.TrimPrefix(platform.Variant, "v")); err == nil && armVersion > 5 { - for armVersion--; armVersion >= 5; armVersion-- { - vector = append(vector, specs.Platform{ - Architecture: platform.Architecture, - OS: platform.OS, - OSVersion: platform.OSVersion, - OSFeatures: platform.OSFeatures, - Variant: "v" + strconv.Itoa(armVersion), - }) - } - } - case "arm64": - variant := platform.Variant - if variant == "" { - variant = "v8" - } - vector = append(vector, platformVector(specs.Platform{ - Architecture: "arm", - OS: platform.OS, - OSVersion: platform.OSVersion, - OSFeatures: platform.OSFeatures, - Variant: variant, - })...) - } - - return vector -} - -// Only returns a match comparer for a single platform -// using default resolution logic for the platform. -// -// For arm/v8, will also match arm/v7, arm/v6 and arm/v5 -// For arm/v7, will also match arm/v6 and arm/v5 -// For arm/v6, will also match arm/v5 -// For amd64, will also match 386 -func Only(platform specs.Platform) MatchComparer { - return Ordered(platformVector(Normalize(platform))...) -} - -// OnlyStrict returns a match comparer for a single platform. -// -// Unlike Only, OnlyStrict does not match sub platforms. -// So, "arm/vN" will not match "arm/vM" where M < N, -// and "amd64" will not also match "386". -// -// OnlyStrict matches non-canonical forms. -// So, "arm64" matches "arm/64/v8". -func OnlyStrict(platform specs.Platform) MatchComparer { - return Ordered(Normalize(platform)) -} - -// Ordered returns a platform MatchComparer which matches any of the platforms -// but orders them in order they are provided. -func Ordered(platforms ...specs.Platform) MatchComparer { - matchers := make([]Matcher, len(platforms)) - for i := range platforms { - matchers[i] = NewMatcher(platforms[i]) - } - return orderedPlatformComparer{ - matchers: matchers, - } -} - -// Any returns a platform MatchComparer which matches any of the platforms -// with no preference for ordering. -func Any(platforms ...specs.Platform) MatchComparer { - matchers := make([]Matcher, len(platforms)) - for i := range platforms { - matchers[i] = NewMatcher(platforms[i]) - } - return anyPlatformComparer{ - matchers: matchers, - } -} - -// All is a platform MatchComparer which matches all platforms -// with preference for ordering. -var All MatchComparer = allPlatformComparer{} - -type orderedPlatformComparer struct { - matchers []Matcher -} - -func (c orderedPlatformComparer) Match(platform specs.Platform) bool { - for _, m := range c.matchers { - if m.Match(platform) { - return true - } - } - return false -} - -func (c orderedPlatformComparer) Less(p1 specs.Platform, p2 specs.Platform) bool { - for _, m := range c.matchers { - p1m := m.Match(p1) - p2m := m.Match(p2) - if p1m && !p2m { - return true - } - if p1m || p2m { - return false - } - } - return false -} - -type anyPlatformComparer struct { - matchers []Matcher -} - -func (c anyPlatformComparer) Match(platform specs.Platform) bool { - for _, m := range c.matchers { - if m.Match(platform) { - return true - } - } - return false -} - -func (c anyPlatformComparer) Less(p1, p2 specs.Platform) bool { - var p1m, p2m bool - for _, m := range c.matchers { - if !p1m && m.Match(p1) { - p1m = true - } - if !p2m && m.Match(p2) { - p2m = true - } - if p1m && p2m { - return false - } - } - // If one matches, and the other does, sort match first - return p1m && !p2m -} - -type allPlatformComparer struct{} - -func (allPlatformComparer) Match(specs.Platform) bool { - return true -} - -func (allPlatformComparer) Less(specs.Platform, specs.Platform) bool { - return false -} diff --git a/vendor/github.com/containerd/containerd/platforms/cpuinfo.go b/vendor/github.com/containerd/containerd/platforms/cpuinfo.go deleted file mode 100644 index 4a7177e3..00000000 --- a/vendor/github.com/containerd/containerd/platforms/cpuinfo.go +++ /dev/null @@ -1,131 +0,0 @@ -/* - Copyright The containerd 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 platforms - -import ( - "bufio" - "os" - "runtime" - "strings" - "sync" - - "github.com/containerd/containerd/errdefs" - "github.com/containerd/containerd/log" - "github.com/pkg/errors" -) - -// Present the ARM instruction set architecture, eg: v7, v8 -// Don't use this value directly; call cpuVariant() instead. -var cpuVariantValue string - -var cpuVariantOnce sync.Once - -func cpuVariant() string { - cpuVariantOnce.Do(func() { - if isArmArch(runtime.GOARCH) { - cpuVariantValue = getCPUVariant() - } - }) - return cpuVariantValue -} - -// For Linux, the kernel has already detected the ABI, ISA and Features. -// So we don't need to access the ARM registers to detect platform information -// by ourselves. We can just parse these information from /proc/cpuinfo -func getCPUInfo(pattern string) (info string, err error) { - if !isLinuxOS(runtime.GOOS) { - return "", errors.Wrapf(errdefs.ErrNotImplemented, "getCPUInfo for OS %s", runtime.GOOS) - } - - cpuinfo, err := os.Open("/proc/cpuinfo") - if err != nil { - return "", err - } - defer cpuinfo.Close() - - // Start to Parse the Cpuinfo line by line. For SMP SoC, we parse - // the first core is enough. - scanner := bufio.NewScanner(cpuinfo) - for scanner.Scan() { - newline := scanner.Text() - list := strings.Split(newline, ":") - - if len(list) > 1 && strings.EqualFold(strings.TrimSpace(list[0]), pattern) { - return strings.TrimSpace(list[1]), nil - } - } - - // Check whether the scanner encountered errors - err = scanner.Err() - if err != nil { - return "", err - } - - return "", errors.Wrapf(errdefs.ErrNotFound, "getCPUInfo for pattern: %s", pattern) -} - -func getCPUVariant() string { - if runtime.GOOS == "windows" || runtime.GOOS == "darwin" { - // Windows/Darwin only supports v7 for ARM32 and v8 for ARM64 and so we can use - // runtime.GOARCH to determine the variants - var variant string - switch runtime.GOARCH { - case "arm64": - variant = "v8" - case "arm": - variant = "v7" - default: - variant = "unknown" - } - - return variant - } - - variant, err := getCPUInfo("Cpu architecture") - if err != nil { - log.L.WithError(err).Error("failure getting variant") - return "" - } - - // handle edge case for Raspberry Pi ARMv6 devices (which due to a kernel quirk, report "CPU architecture: 7") - // https://www.raspberrypi.org/forums/viewtopic.php?t=12614 - if runtime.GOARCH == "arm" && variant == "7" { - model, err := getCPUInfo("model name") - if err == nil && strings.HasPrefix(strings.ToLower(model), "armv6-compatible") { - variant = "6" - } - } - - switch strings.ToLower(variant) { - case "8", "aarch64": - variant = "v8" - case "7", "7m", "?(12)", "?(13)", "?(14)", "?(15)", "?(16)", "?(17)": - variant = "v7" - case "6", "6tej": - variant = "v6" - case "5", "5t", "5te", "5tej": - variant = "v5" - case "4", "4t": - variant = "v4" - case "3": - variant = "v3" - default: - variant = "unknown" - } - - return variant -} diff --git a/vendor/github.com/containerd/containerd/platforms/database.go b/vendor/github.com/containerd/containerd/platforms/database.go deleted file mode 100644 index 6ede9406..00000000 --- a/vendor/github.com/containerd/containerd/platforms/database.go +++ /dev/null @@ -1,114 +0,0 @@ -/* - Copyright The containerd 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 platforms - -import ( - "runtime" - "strings" -) - -// isLinuxOS returns true if the operating system is Linux. -// -// The OS value should be normalized before calling this function. -func isLinuxOS(os string) bool { - return os == "linux" -} - -// These function are generated from https://golang.org/src/go/build/syslist.go. -// -// We use switch statements because they are slightly faster than map lookups -// and use a little less memory. - -// isKnownOS returns true if we know about the operating system. -// -// The OS value should be normalized before calling this function. -func isKnownOS(os string) bool { - switch os { - case "aix", "android", "darwin", "dragonfly", "freebsd", "hurd", "illumos", "js", "linux", "nacl", "netbsd", "openbsd", "plan9", "solaris", "windows", "zos": - return true - } - return false -} - -// isArmArch returns true if the architecture is ARM. -// -// The arch value should be normalized before being passed to this function. -func isArmArch(arch string) bool { - switch arch { - case "arm", "arm64": - return true - } - return false -} - -// isKnownArch returns true if we know about the architecture. -// -// The arch value should be normalized before being passed to this function. -func isKnownArch(arch string) bool { - switch arch { - case "386", "amd64", "amd64p32", "arm", "armbe", "arm64", "arm64be", "ppc64", "ppc64le", "mips", "mipsle", "mips64", "mips64le", "mips64p32", "mips64p32le", "ppc", "riscv", "riscv64", "s390", "s390x", "sparc", "sparc64", "wasm": - return true - } - return false -} - -func normalizeOS(os string) string { - if os == "" { - return runtime.GOOS - } - os = strings.ToLower(os) - - switch os { - case "macos": - os = "darwin" - } - return os -} - -// normalizeArch normalizes the architecture. -func normalizeArch(arch, variant string) (string, string) { - arch, variant = strings.ToLower(arch), strings.ToLower(variant) - switch arch { - case "i386": - arch = "386" - variant = "" - case "x86_64", "x86-64": - arch = "amd64" - variant = "" - case "aarch64", "arm64": - arch = "arm64" - switch variant { - case "8", "v8": - variant = "" - } - case "armhf": - arch = "arm" - variant = "v7" - case "armel": - arch = "arm" - variant = "v6" - case "arm": - switch variant { - case "", "7": - variant = "v7" - case "5", "6", "8": - variant = "v" + variant - } - } - - return arch, variant -} diff --git a/vendor/github.com/containerd/containerd/platforms/defaults.go b/vendor/github.com/containerd/containerd/platforms/defaults.go deleted file mode 100644 index cb77fbc9..00000000 --- a/vendor/github.com/containerd/containerd/platforms/defaults.go +++ /dev/null @@ -1,43 +0,0 @@ -/* - Copyright The containerd 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 platforms - -import ( - "runtime" - - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -// DefaultString returns the default string specifier for the platform. -func DefaultString() string { - return Format(DefaultSpec()) -} - -// DefaultSpec returns the current platform's default platform specification. -func DefaultSpec() specs.Platform { - return specs.Platform{ - OS: runtime.GOOS, - Architecture: runtime.GOARCH, - // The Variant field will be empty if arch != ARM. - Variant: cpuVariant(), - } -} - -// DefaultStrict returns strict form of Default. -func DefaultStrict() MatchComparer { - return OnlyStrict(DefaultSpec()) -} diff --git a/vendor/github.com/containerd/containerd/platforms/defaults_unix.go b/vendor/github.com/containerd/containerd/platforms/defaults_unix.go deleted file mode 100644 index e8a7d5ff..00000000 --- a/vendor/github.com/containerd/containerd/platforms/defaults_unix.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build !windows - -/* - Copyright The containerd 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 platforms - -// Default returns the default matcher for the platform. -func Default() MatchComparer { - return Only(DefaultSpec()) -} diff --git a/vendor/github.com/containerd/containerd/platforms/defaults_windows.go b/vendor/github.com/containerd/containerd/platforms/defaults_windows.go deleted file mode 100644 index 58713aa5..00000000 --- a/vendor/github.com/containerd/containerd/platforms/defaults_windows.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build windows - -/* - Copyright The containerd 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 platforms - -import ( - "runtime" - - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -// Default returns the default matcher for the platform. -func Default() MatchComparer { - return Ordered(DefaultSpec(), specs.Platform{ - OS: "linux", - Architecture: runtime.GOARCH, - }) -} diff --git a/vendor/github.com/containerd/containerd/platforms/platforms.go b/vendor/github.com/containerd/containerd/platforms/platforms.go deleted file mode 100644 index 088bdea0..00000000 --- a/vendor/github.com/containerd/containerd/platforms/platforms.go +++ /dev/null @@ -1,278 +0,0 @@ -/* - Copyright The containerd 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 platforms provides a toolkit for normalizing, matching and -// specifying container platforms. -// -// Centered around OCI platform specifications, we define a string-based -// specifier syntax that can be used for user input. With a specifier, users -// only need to specify the parts of the platform that are relevant to their -// context, providing an operating system or architecture or both. -// -// How do I use this package? -// -// The vast majority of use cases should simply use the match function with -// user input. The first step is to parse a specifier into a matcher: -// -// m, err := Parse("linux") -// if err != nil { ... } -// -// Once you have a matcher, use it to match against the platform declared by a -// component, typically from an image or runtime. Since extracting an images -// platform is a little more involved, we'll use an example against the -// platform default: -// -// if ok := m.Match(Default()); !ok { /* doesn't match */ } -// -// This can be composed in loops for resolving runtimes or used as a filter for -// fetch and select images. -// -// More details of the specifier syntax and platform spec follow. -// -// Declaring Platform Support -// -// Components that have strict platform requirements should use the OCI -// platform specification to declare their support. Typically, this will be -// images and runtimes that should make these declaring which platform they -// support specifically. This looks roughly as follows: -// -// type Platform struct { -// Architecture string -// OS string -// Variant string -// } -// -// Most images and runtimes should at least set Architecture and OS, according -// to their GOARCH and GOOS values, respectively (follow the OCI image -// specification when in doubt). ARM should set variant under certain -// discussions, which are outlined below. -// -// Platform Specifiers -// -// While the OCI platform specifications provide a tool for components to -// specify structured information, user input typically doesn't need the full -// context and much can be inferred. To solve this problem, we introduced -// "specifiers". A specifier has the format -// `||/[/]`. The user can provide either the -// operating system or the architecture or both. -// -// An example of a common specifier is `linux/amd64`. If the host has a default -// of runtime that matches this, the user can simply provide the component that -// matters. For example, if a image provides amd64 and arm64 support, the -// operating system, `linux` can be inferred, so they only have to provide -// `arm64` or `amd64`. Similar behavior is implemented for operating systems, -// where the architecture may be known but a runtime may support images from -// different operating systems. -// -// Normalization -// -// Because not all users are familiar with the way the Go runtime represents -// platforms, several normalizations have been provided to make this package -// easier to user. -// -// The following are performed for architectures: -// -// Value Normalized -// aarch64 arm64 -// armhf arm -// armel arm/v6 -// i386 386 -// x86_64 amd64 -// x86-64 amd64 -// -// We also normalize the operating system `macos` to `darwin`. -// -// ARM Support -// -// To qualify ARM architecture, the Variant field is used to qualify the arm -// version. The most common arm version, v7, is represented without the variant -// unless it is explicitly provided. This is treated as equivalent to armhf. A -// previous architecture, armel, will be normalized to arm/v6. -// -// While these normalizations are provided, their support on arm platforms has -// not yet been fully implemented and tested. -package platforms - -import ( - "regexp" - "runtime" - "strconv" - "strings" - - "github.com/containerd/containerd/errdefs" - specs "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" -) - -var ( - specifierRe = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) -) - -// Matcher matches platforms specifications, provided by an image or runtime. -type Matcher interface { - Match(platform specs.Platform) bool -} - -// NewMatcher returns a simple matcher based on the provided platform -// specification. The returned matcher only looks for equality based on os, -// architecture and variant. -// -// One may implement their own matcher if this doesn't provide the required -// functionality. -// -// Applications should opt to use `Match` over directly parsing specifiers. -func NewMatcher(platform specs.Platform) Matcher { - return &matcher{ - Platform: Normalize(platform), - } -} - -type matcher struct { - specs.Platform -} - -func (m *matcher) Match(platform specs.Platform) bool { - normalized := Normalize(platform) - return m.OS == normalized.OS && - m.Architecture == normalized.Architecture && - m.Variant == normalized.Variant -} - -func (m *matcher) String() string { - return Format(m.Platform) -} - -// Parse parses the platform specifier syntax into a platform declaration. -// -// Platform specifiers are in the format `||/[/]`. -// The minimum required information for a platform specifier is the operating -// system or architecture. If there is only a single string (no slashes), the -// value will be matched against the known set of operating systems, then fall -// back to the known set of architectures. The missing component will be -// inferred based on the local environment. -func Parse(specifier string) (specs.Platform, error) { - if strings.Contains(specifier, "*") { - // TODO(stevvooe): need to work out exact wildcard handling - return specs.Platform{}, errors.Wrapf(errdefs.ErrInvalidArgument, "%q: wildcards not yet supported", specifier) - } - - parts := strings.Split(specifier, "/") - - for _, part := range parts { - if !specifierRe.MatchString(part) { - return specs.Platform{}, errors.Wrapf(errdefs.ErrInvalidArgument, "%q is an invalid component of %q: platform specifier component must match %q", part, specifier, specifierRe.String()) - } - } - - var p specs.Platform - switch len(parts) { - case 1: - // in this case, we will test that the value might be an OS, then look - // it up. If it is not known, we'll treat it as an architecture. Since - // we have very little information about the platform here, we are - // going to be a little more strict if we don't know about the argument - // value. - p.OS = normalizeOS(parts[0]) - if isKnownOS(p.OS) { - // picks a default architecture - p.Architecture = runtime.GOARCH - if p.Architecture == "arm" && cpuVariant() != "v7" { - p.Variant = cpuVariant() - } - - return p, nil - } - - p.Architecture, p.Variant = normalizeArch(parts[0], "") - if p.Architecture == "arm" && p.Variant == "v7" { - p.Variant = "" - } - if isKnownArch(p.Architecture) { - p.OS = runtime.GOOS - return p, nil - } - - return specs.Platform{}, errors.Wrapf(errdefs.ErrInvalidArgument, "%q: unknown operating system or architecture", specifier) - case 2: - // In this case, we treat as a regular os/arch pair. We don't care - // about whether or not we know of the platform. - p.OS = normalizeOS(parts[0]) - p.Architecture, p.Variant = normalizeArch(parts[1], "") - if p.Architecture == "arm" && p.Variant == "v7" { - p.Variant = "" - } - - return p, nil - case 3: - // we have a fully specified variant, this is rare - p.OS = normalizeOS(parts[0]) - p.Architecture, p.Variant = normalizeArch(parts[1], parts[2]) - if p.Architecture == "arm64" && p.Variant == "" { - p.Variant = "v8" - } - - return p, nil - } - - return specs.Platform{}, errors.Wrapf(errdefs.ErrInvalidArgument, "%q: cannot parse platform specifier", specifier) -} - -// MustParse is like Parses but panics if the specifier cannot be parsed. -// Simplifies initialization of global variables. -func MustParse(specifier string) specs.Platform { - p, err := Parse(specifier) - if err != nil { - panic("platform: Parse(" + strconv.Quote(specifier) + "): " + err.Error()) - } - return p -} - -// Format returns a string specifier from the provided platform specification. -func Format(platform specs.Platform) string { - if platform.OS == "" { - return "unknown" - } - - return joinNotEmpty(platform.OS, platform.Architecture, platform.Variant) -} - -func joinNotEmpty(s ...string) string { - var ss []string - for _, s := range s { - if s == "" { - continue - } - - ss = append(ss, s) - } - - return strings.Join(ss, "/") -} - -// Normalize validates and translate the platform to the canonical value. -// -// For example, if "Aarch64" is encountered, we change it to "arm64" or if -// "x86_64" is encountered, it becomes "amd64". -func Normalize(platform specs.Platform) specs.Platform { - platform.OS = normalizeOS(platform.OS) - platform.Architecture, platform.Variant = normalizeArch(platform.Architecture, platform.Variant) - - // these fields are deprecated, remove them - platform.OSFeatures = nil - platform.OSVersion = "" - - return platform -} diff --git a/vendor/github.com/containerd/containerd/sys/env.go b/vendor/github.com/containerd/containerd/sys/env.go deleted file mode 100644 index 8450d627..00000000 --- a/vendor/github.com/containerd/containerd/sys/env.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build !windows - -/* - Copyright The containerd 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 sys - -import "golang.org/x/sys/unix" - -// RunningPrivileged returns true if the effective user ID of the -// calling process is 0 -func RunningPrivileged() bool { - return unix.Geteuid() == 0 -} - -// RunningUnprivileged returns true if the effective user ID of the -// calling process is not 0 -func RunningUnprivileged() bool { - return !RunningPrivileged() -} diff --git a/vendor/github.com/containerd/containerd/sys/epoll.go b/vendor/github.com/containerd/containerd/sys/epoll.go deleted file mode 100644 index 28d6c2ca..00000000 --- a/vendor/github.com/containerd/containerd/sys/epoll.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build linux - -/* - Copyright The containerd 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 sys - -import "golang.org/x/sys/unix" - -// EpollCreate1 is an alias for unix.EpollCreate1 -// Deprecated: use golang.org/x/sys/unix.EpollCreate1 -var EpollCreate1 = unix.EpollCreate1 - -// EpollCtl is an alias for unix.EpollCtl -// Deprecated: use golang.org/x/sys/unix.EpollCtl -var EpollCtl = unix.EpollCtl - -// EpollWait is an alias for unix.EpollWait -// Deprecated: use golang.org/x/sys/unix.EpollWait -var EpollWait = unix.EpollWait diff --git a/vendor/github.com/containerd/containerd/sys/fds.go b/vendor/github.com/containerd/containerd/sys/fds.go deleted file mode 100644 index db3cf702..00000000 --- a/vendor/github.com/containerd/containerd/sys/fds.go +++ /dev/null @@ -1,34 +0,0 @@ -// +build !windows,!darwin - -/* - Copyright The containerd 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 sys - -import ( - "io/ioutil" - "path/filepath" - "strconv" -) - -// GetOpenFds returns the number of open fds for the process provided by pid -func GetOpenFds(pid int) (int, error) { - dirs, err := ioutil.ReadDir(filepath.Join("/proc", strconv.Itoa(pid), "fd")) - if err != nil { - return -1, err - } - return len(dirs), nil -} diff --git a/vendor/github.com/containerd/containerd/sys/filesys.go b/vendor/github.com/containerd/containerd/sys/filesys.go deleted file mode 100644 index 825d21d1..00000000 --- a/vendor/github.com/containerd/containerd/sys/filesys.go +++ /dev/null @@ -1,35 +0,0 @@ -/* - Copyright The containerd 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 sys - -import "os" - -// IsFifo checks if a file is a (named pipe) fifo -// if the file does not exist then it returns false -func IsFifo(path string) (bool, error) { - stat, err := os.Stat(path) - if err != nil { - if os.IsNotExist(err) { - return false, nil - } - return false, err - } - if stat.Mode()&os.ModeNamedPipe == os.ModeNamedPipe { - return true, nil - } - return false, nil -} diff --git a/vendor/github.com/containerd/containerd/sys/filesys_unix.go b/vendor/github.com/containerd/containerd/sys/filesys_unix.go deleted file mode 100644 index d8329af9..00000000 --- a/vendor/github.com/containerd/containerd/sys/filesys_unix.go +++ /dev/null @@ -1,31 +0,0 @@ -// +build !windows - -/* - Copyright The containerd 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 sys - -import "os" - -// ForceRemoveAll on unix is just a wrapper for os.RemoveAll -func ForceRemoveAll(path string) error { - return os.RemoveAll(path) -} - -// MkdirAllWithACL is a wrapper for os.MkdirAll on Unix systems. -func MkdirAllWithACL(path string, perm os.FileMode) error { - return os.MkdirAll(path, perm) -} diff --git a/vendor/github.com/containerd/containerd/sys/filesys_windows.go b/vendor/github.com/containerd/containerd/sys/filesys_windows.go deleted file mode 100644 index 2eaee2ca..00000000 --- a/vendor/github.com/containerd/containerd/sys/filesys_windows.go +++ /dev/null @@ -1,268 +0,0 @@ -// +build windows - -/* - Copyright The containerd 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 sys - -import ( - "os" - "path/filepath" - "regexp" - "strings" - "syscall" - "unsafe" - - "github.com/Microsoft/hcsshim" - "golang.org/x/sys/windows" -) - -const ( - // SddlAdministratorsLocalSystem is local administrators plus NT AUTHORITY\System - SddlAdministratorsLocalSystem = "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)" -) - -// MkdirAllWithACL is a wrapper for MkdirAll that creates a directory -// ACL'd for Builtin Administrators and Local System. -func MkdirAllWithACL(path string, perm os.FileMode) error { - return mkdirall(path, true) -} - -// MkdirAll implementation that is volume path aware for Windows. It can be used -// as a drop-in replacement for os.MkdirAll() -func MkdirAll(path string, _ os.FileMode) error { - return mkdirall(path, false) -} - -// mkdirall is a custom version of os.MkdirAll modified for use on Windows -// so that it is both volume path aware, and can create a directory with -// a DACL. -func mkdirall(path string, adminAndLocalSystem bool) error { - if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) { - return nil - } - - // The rest of this method is largely copied from os.MkdirAll and should be kept - // as-is to ensure compatibility. - - // Fast path: if we can tell whether path is a directory or file, stop with success or error. - dir, err := os.Stat(path) - if err == nil { - if dir.IsDir() { - return nil - } - return &os.PathError{ - Op: "mkdir", - Path: path, - Err: syscall.ENOTDIR, - } - } - - // Slow path: make sure parent exists and then call Mkdir for path. - i := len(path) - for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. - i-- - } - - j := i - for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. - j-- - } - - if j > 1 { - // Create parent - err = mkdirall(path[0:j-1], adminAndLocalSystem) - if err != nil { - return err - } - } - - // Parent now exists; invoke os.Mkdir or mkdirWithACL and use its result. - if adminAndLocalSystem { - err = mkdirWithACL(path) - } else { - err = os.Mkdir(path, 0) - } - - if err != nil { - // Handle arguments like "foo/." by - // double-checking that directory doesn't exist. - dir, err1 := os.Lstat(path) - if err1 == nil && dir.IsDir() { - return nil - } - return err - } - return nil -} - -// mkdirWithACL creates a new directory. If there is an error, it will be of -// type *PathError. . -// -// This is a modified and combined version of os.Mkdir and windows.Mkdir -// in golang to cater for creating a directory am ACL permitting full -// access, with inheritance, to any subfolder/file for Built-in Administrators -// and Local System. -func mkdirWithACL(name string) error { - sa := windows.SecurityAttributes{Length: 0} - sd, err := windows.SecurityDescriptorFromString(SddlAdministratorsLocalSystem) - if err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - sa.SecurityDescriptor = sd - - namep, err := windows.UTF16PtrFromString(name) - if err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - - e := windows.CreateDirectory(namep, &sa) - if e != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: e} - } - return nil -} - -// IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows, -// golang filepath.IsAbs does not consider a path \windows\system32 as absolute -// as it doesn't start with a drive-letter/colon combination. However, in -// docker we need to verify things such as WORKDIR /windows/system32 in -// a Dockerfile (which gets translated to \windows\system32 when being processed -// by the daemon. This SHOULD be treated as absolute from a docker processing -// perspective. -func IsAbs(path string) bool { - if !filepath.IsAbs(path) { - if !strings.HasPrefix(path, string(os.PathSeparator)) { - return false - } - } - return true -} - -// The origin of the functions below here are the golang OS and windows packages, -// slightly modified to only cope with files, not directories due to the -// specific use case. -// -// The alteration is to allow a file on Windows to be opened with -// FILE_FLAG_SEQUENTIAL_SCAN (particular for docker load), to avoid eating -// the standby list, particularly when accessing large files such as layer.tar. - -// CreateSequential creates the named file with mode 0666 (before umask), truncating -// it if it already exists. If successful, methods on the returned -// File can be used for I/O; the associated file descriptor has mode -// O_RDWR. -// If there is an error, it will be of type *PathError. -func CreateSequential(name string) (*os.File, error) { - return OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0) -} - -// OpenSequential opens the named file for reading. If successful, methods on -// the returned file can be used for reading; the associated file -// descriptor has mode O_RDONLY. -// If there is an error, it will be of type *PathError. -func OpenSequential(name string) (*os.File, error) { - return OpenFileSequential(name, os.O_RDONLY, 0) -} - -// OpenFileSequential is the generalized open call; most users will use Open -// or Create instead. -// If there is an error, it will be of type *PathError. -func OpenFileSequential(name string, flag int, _ os.FileMode) (*os.File, error) { - if name == "" { - return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT} - } - r, errf := windowsOpenFileSequential(name, flag, 0) - if errf == nil { - return r, nil - } - return nil, &os.PathError{Op: "open", Path: name, Err: errf} -} - -func windowsOpenFileSequential(name string, flag int, _ os.FileMode) (file *os.File, err error) { - r, e := windowsOpenSequential(name, flag|windows.O_CLOEXEC, 0) - if e != nil { - return nil, e - } - return os.NewFile(uintptr(r), name), nil -} - -func makeInheritSa() *windows.SecurityAttributes { - var sa windows.SecurityAttributes - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - return &sa -} - -func windowsOpenSequential(path string, mode int, _ uint32) (fd windows.Handle, err error) { - if len(path) == 0 { - return windows.InvalidHandle, windows.ERROR_FILE_NOT_FOUND - } - pathp, err := windows.UTF16PtrFromString(path) - if err != nil { - return windows.InvalidHandle, err - } - var access uint32 - switch mode & (windows.O_RDONLY | windows.O_WRONLY | windows.O_RDWR) { - case windows.O_RDONLY: - access = windows.GENERIC_READ - case windows.O_WRONLY: - access = windows.GENERIC_WRITE - case windows.O_RDWR: - access = windows.GENERIC_READ | windows.GENERIC_WRITE - } - if mode&windows.O_CREAT != 0 { - access |= windows.GENERIC_WRITE - } - if mode&windows.O_APPEND != 0 { - access &^= windows.GENERIC_WRITE - access |= windows.FILE_APPEND_DATA - } - sharemode := uint32(windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE) - var sa *windows.SecurityAttributes - if mode&windows.O_CLOEXEC == 0 { - sa = makeInheritSa() - } - var createmode uint32 - switch { - case mode&(windows.O_CREAT|windows.O_EXCL) == (windows.O_CREAT | windows.O_EXCL): - createmode = windows.CREATE_NEW - case mode&(windows.O_CREAT|windows.O_TRUNC) == (windows.O_CREAT | windows.O_TRUNC): - createmode = windows.CREATE_ALWAYS - case mode&windows.O_CREAT == windows.O_CREAT: - createmode = windows.OPEN_ALWAYS - case mode&windows.O_TRUNC == windows.O_TRUNC: - createmode = windows.TRUNCATE_EXISTING - default: - createmode = windows.OPEN_EXISTING - } - // Use FILE_FLAG_SEQUENTIAL_SCAN rather than FILE_ATTRIBUTE_NORMAL as implemented in golang. - // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx - const fileFlagSequentialScan = 0x08000000 // FILE_FLAG_SEQUENTIAL_SCAN - h, e := windows.CreateFile(pathp, access, sharemode, sa, createmode, fileFlagSequentialScan, 0) - return h, e -} - -// ForceRemoveAll is the same as os.RemoveAll, but uses hcsshim.DestroyLayer in order -// to delete container layers. -func ForceRemoveAll(path string) error { - info := hcsshim.DriverInfo{ - HomeDir: filepath.Dir(path), - } - - return hcsshim.DestroyLayer(info, filepath.Base(path)) -} diff --git a/vendor/github.com/containerd/containerd/sys/mount_linux.go b/vendor/github.com/containerd/containerd/sys/mount_linux.go deleted file mode 100644 index a2104552..00000000 --- a/vendor/github.com/containerd/containerd/sys/mount_linux.go +++ /dev/null @@ -1,145 +0,0 @@ -/* - Copyright The containerd 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 sys - -import ( - "runtime" - "syscall" - "unsafe" - - "github.com/containerd/containerd/log" - "github.com/pkg/errors" - "golang.org/x/sys/unix" -) - -// FMountat performs mount from the provided directory. -func FMountat(dirfd uintptr, source, target, fstype string, flags uintptr, data string) error { - var ( - sourceP, targetP, fstypeP, dataP *byte - pid uintptr - err error - errno, status syscall.Errno - ) - - sourceP, err = syscall.BytePtrFromString(source) - if err != nil { - return err - } - - targetP, err = syscall.BytePtrFromString(target) - if err != nil { - return err - } - - fstypeP, err = syscall.BytePtrFromString(fstype) - if err != nil { - return err - } - - if data != "" { - dataP, err = syscall.BytePtrFromString(data) - if err != nil { - return err - } - } - - runtime.LockOSThread() - defer runtime.UnlockOSThread() - - var pipefds [2]int - if err := syscall.Pipe2(pipefds[:], syscall.O_CLOEXEC); err != nil { - return errors.Wrap(err, "failed to open pipe") - } - - defer func() { - // close both ends of the pipe in a deferred function, since open file - // descriptor table is shared with child - syscall.Close(pipefds[0]) - syscall.Close(pipefds[1]) - }() - - pid, errno = forkAndMountat(dirfd, - uintptr(unsafe.Pointer(sourceP)), - uintptr(unsafe.Pointer(targetP)), - uintptr(unsafe.Pointer(fstypeP)), - flags, - uintptr(unsafe.Pointer(dataP)), - pipefds[1], - ) - - if errno != 0 { - return errors.Wrap(errno, "failed to fork thread") - } - - defer func() { - _, err := unix.Wait4(int(pid), nil, 0, nil) - for err == syscall.EINTR { - _, err = unix.Wait4(int(pid), nil, 0, nil) - } - - if err != nil { - log.L.WithError(err).Debugf("failed to find pid=%d process", pid) - } - }() - - _, _, errno = syscall.RawSyscall(syscall.SYS_READ, - uintptr(pipefds[0]), - uintptr(unsafe.Pointer(&status)), - unsafe.Sizeof(status)) - if errno != 0 { - return errors.Wrap(errno, "failed to read pipe") - } - - if status != 0 { - return errors.Wrap(status, "failed to mount") - } - - return nil -} - -// forkAndMountat will fork thread, change working dir and mount. -// -// precondition: the runtime OS thread must be locked. -func forkAndMountat(dirfd uintptr, source, target, fstype, flags, data uintptr, pipefd int) (pid uintptr, errno syscall.Errno) { - - // block signal during clone - beforeFork() - - // the cloned thread shares the open file descriptor, but the thread - // never be reused by runtime. - pid, _, errno = syscall.RawSyscall6(syscall.SYS_CLONE, uintptr(syscall.SIGCHLD)|syscall.CLONE_FILES, 0, 0, 0, 0, 0) - if errno != 0 || pid != 0 { - // restore all signals - afterFork() - return - } - - // restore all signals - afterForkInChild() - - // change working dir - _, _, errno = syscall.RawSyscall(syscall.SYS_FCHDIR, dirfd, 0, 0) - if errno != 0 { - goto childerr - } - _, _, errno = syscall.RawSyscall6(syscall.SYS_MOUNT, source, target, fstype, flags, data, 0) - -childerr: - _, _, errno = syscall.RawSyscall(syscall.SYS_WRITE, uintptr(pipefd), uintptr(unsafe.Pointer(&errno)), unsafe.Sizeof(errno)) - syscall.RawSyscall(syscall.SYS_EXIT, uintptr(errno), 0, 0) - panic("unreachable") -} diff --git a/vendor/github.com/containerd/containerd/sys/oom_unix.go b/vendor/github.com/containerd/containerd/sys/oom_unix.go deleted file mode 100644 index c381e1a7..00000000 --- a/vendor/github.com/containerd/containerd/sys/oom_unix.go +++ /dev/null @@ -1,61 +0,0 @@ -// +build !windows - -/* - Copyright The containerd 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 sys - -import ( - "fmt" - "io/ioutil" - "os" - "strconv" - "strings" -) - -const ( - // OOMScoreMaxKillable is the maximum score keeping the process killable by the oom killer - OOMScoreMaxKillable = -999 - // OOMScoreAdjMax is from OOM_SCORE_ADJ_MAX https://github.com/torvalds/linux/blob/master/include/uapi/linux/oom.h - OOMScoreAdjMax = 1000 -) - -// SetOOMScore sets the oom score for the provided pid -func SetOOMScore(pid, score int) error { - path := fmt.Sprintf("/proc/%d/oom_score_adj", pid) - f, err := os.OpenFile(path, os.O_WRONLY, 0) - if err != nil { - return err - } - defer f.Close() - if _, err = f.WriteString(strconv.Itoa(score)); err != nil { - if os.IsPermission(err) && (RunningInUserNS() || RunningUnprivileged()) { - return nil - } - return err - } - return nil -} - -// GetOOMScoreAdj gets the oom score for a process -func GetOOMScoreAdj(pid int) (int, error) { - path := fmt.Sprintf("/proc/%d/oom_score_adj", pid) - data, err := ioutil.ReadFile(path) - if err != nil { - return 0, err - } - return strconv.Atoi(strings.TrimSpace(string(data))) -} diff --git a/vendor/github.com/containerd/containerd/sys/oom_windows.go b/vendor/github.com/containerd/containerd/sys/oom_windows.go deleted file mode 100644 index 215c171f..00000000 --- a/vendor/github.com/containerd/containerd/sys/oom_windows.go +++ /dev/null @@ -1,36 +0,0 @@ -/* - Copyright The containerd 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 sys - -const ( - // OOMScoreAdjMax is not implemented on Windows - OOMScoreAdjMax = 0 -) - -// SetOOMScore sets the oom score for the process -// -// Not implemented on Windows -func SetOOMScore(pid, score int) error { - return nil -} - -// GetOOMScoreAdj gets the oom score for a process -// -// Not implemented on Windows -func GetOOMScoreAdj(pid int) (int, error) { - return 0, nil -} diff --git a/vendor/github.com/containerd/containerd/sys/socket_unix.go b/vendor/github.com/containerd/containerd/sys/socket_unix.go deleted file mode 100644 index b67cc1fa..00000000 --- a/vendor/github.com/containerd/containerd/sys/socket_unix.go +++ /dev/null @@ -1,80 +0,0 @@ -// +build !windows - -/* - Copyright The containerd 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 sys - -import ( - "net" - "os" - "path/filepath" - - "github.com/pkg/errors" - "golang.org/x/sys/unix" -) - -// CreateUnixSocket creates a unix socket and returns the listener -func CreateUnixSocket(path string) (net.Listener, error) { - // BSDs have a 104 limit - if len(path) > 104 { - return nil, errors.Errorf("%q: unix socket path too long (> 104)", path) - } - if err := os.MkdirAll(filepath.Dir(path), 0660); err != nil { - return nil, err - } - if err := unix.Unlink(path); err != nil && !os.IsNotExist(err) { - return nil, err - } - return net.Listen("unix", path) -} - -// GetLocalListener returns a listener out of a unix socket. -func GetLocalListener(path string, uid, gid int) (net.Listener, error) { - // Ensure parent directory is created - if err := mkdirAs(filepath.Dir(path), uid, gid); err != nil { - return nil, err - } - - l, err := CreateUnixSocket(path) - if err != nil { - return l, err - } - - if err := os.Chmod(path, 0660); err != nil { - l.Close() - return nil, err - } - - if err := os.Chown(path, uid, gid); err != nil { - l.Close() - return nil, err - } - - return l, nil -} - -func mkdirAs(path string, uid, gid int) error { - if _, err := os.Stat(path); !os.IsNotExist(err) { - return err - } - - if err := os.MkdirAll(path, 0770); err != nil { - return err - } - - return os.Chown(path, uid, gid) -} diff --git a/vendor/github.com/containerd/containerd/sys/socket_windows.go b/vendor/github.com/containerd/containerd/sys/socket_windows.go deleted file mode 100644 index 3ee7679b..00000000 --- a/vendor/github.com/containerd/containerd/sys/socket_windows.go +++ /dev/null @@ -1,32 +0,0 @@ -// +build windows - -/* - Copyright The containerd 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 sys - -import ( - "net" - - "github.com/Microsoft/go-winio" -) - -// GetLocalListener returns a Listernet out of a named pipe. -// `path` must be of the form of `\\.\pipe\` -// (see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365150) -func GetLocalListener(path string, uid, gid int) (net.Listener, error) { - return winio.ListenPipe(path, nil) -} diff --git a/vendor/github.com/containerd/containerd/sys/stat_bsd.go b/vendor/github.com/containerd/containerd/sys/stat_bsd.go deleted file mode 100644 index 4f03cd6c..00000000 --- a/vendor/github.com/containerd/containerd/sys/stat_bsd.go +++ /dev/null @@ -1,44 +0,0 @@ -// +build darwin freebsd netbsd - -/* - Copyright The containerd 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 sys - -import ( - "syscall" - "time" -) - -// StatAtime returns the access time from a stat struct -func StatAtime(st *syscall.Stat_t) syscall.Timespec { - return st.Atimespec -} - -// StatCtime returns the created time from a stat struct -func StatCtime(st *syscall.Stat_t) syscall.Timespec { - return st.Ctimespec -} - -// StatMtime returns the modified time from a stat struct -func StatMtime(st *syscall.Stat_t) syscall.Timespec { - return st.Mtimespec -} - -// StatATimeAsTime returns the access time as a time.Time -func StatATimeAsTime(st *syscall.Stat_t) time.Time { - return time.Unix(int64(st.Atimespec.Sec), int64(st.Atimespec.Nsec)) // nolint: unconvert -} diff --git a/vendor/github.com/containerd/containerd/sys/stat_openbsd.go b/vendor/github.com/containerd/containerd/sys/stat_openbsd.go deleted file mode 100644 index ec3b9df6..00000000 --- a/vendor/github.com/containerd/containerd/sys/stat_openbsd.go +++ /dev/null @@ -1,45 +0,0 @@ -// +build openbsd - -/* - Copyright The containerd 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 sys - -import ( - "syscall" - "time" -) - -// StatAtime returns the Atim -func StatAtime(st *syscall.Stat_t) syscall.Timespec { - return st.Atim -} - -// StatCtime returns the Ctim -func StatCtime(st *syscall.Stat_t) syscall.Timespec { - return st.Ctim -} - -// StatMtime returns the Mtim -func StatMtime(st *syscall.Stat_t) syscall.Timespec { - return st.Mtim -} - -// StatATimeAsTime returns st.Atim as a time.Time -func StatATimeAsTime(st *syscall.Stat_t) time.Time { - // The int64 conversions ensure the line compiles for 32-bit systems as well. - return time.Unix(int64(st.Atim.Sec), int64(st.Atim.Nsec)) // nolint: unconvert -} diff --git a/vendor/github.com/containerd/containerd/sys/stat_unix.go b/vendor/github.com/containerd/containerd/sys/stat_unix.go deleted file mode 100644 index 21a666df..00000000 --- a/vendor/github.com/containerd/containerd/sys/stat_unix.go +++ /dev/null @@ -1,44 +0,0 @@ -// +build linux solaris - -/* - Copyright The containerd 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 sys - -import ( - "syscall" - "time" -) - -// StatAtime returns the Atim -func StatAtime(st *syscall.Stat_t) syscall.Timespec { - return st.Atim -} - -// StatCtime returns the Ctim -func StatCtime(st *syscall.Stat_t) syscall.Timespec { - return st.Ctim -} - -// StatMtime returns the Mtim -func StatMtime(st *syscall.Stat_t) syscall.Timespec { - return st.Mtim -} - -// StatATimeAsTime returns st.Atim as a time.Time -func StatATimeAsTime(st *syscall.Stat_t) time.Time { - return time.Unix(int64(st.Atim.Sec), int64(st.Atim.Nsec)) // nolint: unconvert -} diff --git a/vendor/github.com/containerd/containerd/sys/subprocess_unsafe_linux.go b/vendor/github.com/containerd/containerd/sys/subprocess_unsafe_linux.go deleted file mode 100644 index 6e40a9c7..00000000 --- a/vendor/github.com/containerd/containerd/sys/subprocess_unsafe_linux.go +++ /dev/null @@ -1,30 +0,0 @@ -/* - Copyright The containerd 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 sys - -import ( - _ "unsafe" // required for go:linkname. -) - -//go:linkname beforeFork syscall.runtime_BeforeFork -func beforeFork() - -//go:linkname afterFork syscall.runtime_AfterFork -func afterFork() - -//go:linkname afterForkInChild syscall.runtime_AfterForkInChild -func afterForkInChild() diff --git a/vendor/github.com/containerd/containerd/sys/subprocess_unsafe_linux.s b/vendor/github.com/containerd/containerd/sys/subprocess_unsafe_linux.s deleted file mode 100644 index c073fa4a..00000000 --- a/vendor/github.com/containerd/containerd/sys/subprocess_unsafe_linux.s +++ /dev/null @@ -1,15 +0,0 @@ -/* - Copyright The containerd 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. -*/ diff --git a/vendor/github.com/containerd/containerd/sys/userns_linux.go b/vendor/github.com/containerd/containerd/sys/userns_linux.go deleted file mode 100644 index 3cd1a222..00000000 --- a/vendor/github.com/containerd/containerd/sys/userns_linux.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - Copyright The containerd 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 sys - -import ( - "bufio" - "fmt" - "os" - "sync" -) - -var ( - inUserNS bool - nsOnce sync.Once -) - -// RunningInUserNS detects whether we are currently running in a user namespace. -// Originally copied from github.com/lxc/lxd/shared/util.go -func RunningInUserNS() bool { - nsOnce.Do(func() { - file, err := os.Open("/proc/self/uid_map") - if err != nil { - // This kernel-provided file only exists if user namespaces are supported - return - } - defer file.Close() - - buf := bufio.NewReader(file) - l, _, err := buf.ReadLine() - if err != nil { - return - } - - line := string(l) - var a, b, c int64 - fmt.Sscanf(line, "%d %d %d", &a, &b, &c) - - /* - * We assume we are in the initial user namespace if we have a full - * range - 4294967295 uids starting at uid 0. - */ - if a == 0 && b == 0 && c == 4294967295 { - return - } - inUserNS = true - }) - return inUserNS -} diff --git a/vendor/github.com/containerd/containerd/sys/userns_unsupported.go b/vendor/github.com/containerd/containerd/sys/userns_unsupported.go deleted file mode 100644 index 549b5020..00000000 --- a/vendor/github.com/containerd/containerd/sys/userns_unsupported.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build !linux - -/* - Copyright The containerd 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 sys - -// RunningInUserNS is a stub for non-Linux systems -// Always returns false -func RunningInUserNS() bool { - return false -} diff --git a/vendor/github.com/containerd/continuity/AUTHORS b/vendor/github.com/containerd/continuity/AUTHORS deleted file mode 100644 index 376ceb93..00000000 --- a/vendor/github.com/containerd/continuity/AUTHORS +++ /dev/null @@ -1,40 +0,0 @@ -Aaron Lehmann -Akash Gupta -Akihiro Suda -Akihiro Suda -Akihiro Suda -Andrew Pennebaker -Brandon Philips -Brian Goff -Christopher Jones -Daniel, Dao Quang Minh -Darren Stahl -Derek McGowan -Derek McGowan -Edward Pilatowicz -Ian Campbell -Ivan Markin -Justin Cormack -Justin Cummins -Kasper Fabæch Brandt -Kir Kolyshkin -Michael Crosby -Michael Crosby -Michael Wan -Mike Brown -Niels de Vos -Phil Estes -Phil Estes -Samuel Karp -Sam Whited -Sebastiaan van Stijn -Shengjing Zhu -Stephen J Day -Tibor Vass -Tobias Klauser -Tom Faulhaber -Tonis Tiigi -Trevor Porter -Wei Fu -Wilbert van de Ridder -Xiaodong Ye diff --git a/vendor/github.com/containerd/continuity/LICENSE b/vendor/github.com/containerd/continuity/LICENSE deleted file mode 100644 index 584149b6..00000000 --- a/vendor/github.com/containerd/continuity/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://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 - - Copyright The containerd 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. diff --git a/vendor/github.com/containerd/continuity/fs/copy.go b/vendor/github.com/containerd/continuity/fs/copy.go deleted file mode 100644 index 818bba2c..00000000 --- a/vendor/github.com/containerd/continuity/fs/copy.go +++ /dev/null @@ -1,176 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "io/ioutil" - "os" - "path/filepath" - "sync" - - "github.com/pkg/errors" -) - -var bufferPool = &sync.Pool{ - New: func() interface{} { - buffer := make([]byte, 32*1024) - return &buffer - }, -} - -// XAttrErrorHandlers transform a non-nil xattr error. -// Return nil to ignore an error. -// xattrKey can be empty for listxattr operation. -type XAttrErrorHandler func(dst, src, xattrKey string, err error) error - -type copyDirOpts struct { - xeh XAttrErrorHandler -} - -type CopyDirOpt func(*copyDirOpts) error - -// WithXAttrErrorHandler allows specifying XAttrErrorHandler -// If nil XAttrErrorHandler is specified (default), CopyDir stops -// on a non-nil xattr error. -func WithXAttrErrorHandler(xeh XAttrErrorHandler) CopyDirOpt { - return func(o *copyDirOpts) error { - o.xeh = xeh - return nil - } -} - -// WithAllowXAttrErrors allows ignoring xattr errors. -func WithAllowXAttrErrors() CopyDirOpt { - xeh := func(dst, src, xattrKey string, err error) error { - return nil - } - return WithXAttrErrorHandler(xeh) -} - -// CopyDir copies the directory from src to dst. -// Most efficient copy of files is attempted. -func CopyDir(dst, src string, opts ...CopyDirOpt) error { - var o copyDirOpts - for _, opt := range opts { - if err := opt(&o); err != nil { - return err - } - } - inodes := map[uint64]string{} - return copyDirectory(dst, src, inodes, &o) -} - -func copyDirectory(dst, src string, inodes map[uint64]string, o *copyDirOpts) error { - stat, err := os.Stat(src) - if err != nil { - return errors.Wrapf(err, "failed to stat %s", src) - } - if !stat.IsDir() { - return errors.Errorf("source %s is not directory", src) - } - - if st, err := os.Stat(dst); err != nil { - if err := os.Mkdir(dst, stat.Mode()); err != nil { - return errors.Wrapf(err, "failed to mkdir %s", dst) - } - } else if !st.IsDir() { - return errors.Errorf("cannot copy to non-directory: %s", dst) - } else { - if err := os.Chmod(dst, stat.Mode()); err != nil { - return errors.Wrapf(err, "failed to chmod on %s", dst) - } - } - - fis, err := ioutil.ReadDir(src) - if err != nil { - return errors.Wrapf(err, "failed to read %s", src) - } - - if err := copyFileInfo(stat, dst); err != nil { - return errors.Wrapf(err, "failed to copy file info for %s", dst) - } - - if err := copyXAttrs(dst, src, o.xeh); err != nil { - return errors.Wrap(err, "failed to copy xattrs") - } - - for _, fi := range fis { - source := filepath.Join(src, fi.Name()) - target := filepath.Join(dst, fi.Name()) - - switch { - case fi.IsDir(): - if err := copyDirectory(target, source, inodes, o); err != nil { - return err - } - continue - case (fi.Mode() & os.ModeType) == 0: - link, err := getLinkSource(target, fi, inodes) - if err != nil { - return errors.Wrap(err, "failed to get hardlink") - } - if link != "" { - if err := os.Link(link, target); err != nil { - return errors.Wrap(err, "failed to create hard link") - } - } else if err := CopyFile(target, source); err != nil { - return errors.Wrap(err, "failed to copy files") - } - case (fi.Mode() & os.ModeSymlink) == os.ModeSymlink: - link, err := os.Readlink(source) - if err != nil { - return errors.Wrapf(err, "failed to read link: %s", source) - } - if err := os.Symlink(link, target); err != nil { - return errors.Wrapf(err, "failed to create symlink: %s", target) - } - case (fi.Mode() & os.ModeDevice) == os.ModeDevice: - if err := copyDevice(target, fi); err != nil { - return errors.Wrapf(err, "failed to create device") - } - default: - // TODO: Support pipes and sockets - return errors.Wrapf(err, "unsupported mode %s", fi.Mode()) - } - if err := copyFileInfo(fi, target); err != nil { - return errors.Wrap(err, "failed to copy file info") - } - - if err := copyXAttrs(target, source, o.xeh); err != nil { - return errors.Wrap(err, "failed to copy xattrs") - } - } - - return nil -} - -// CopyFile copies the source file to the target. -// The most efficient means of copying is used for the platform. -func CopyFile(target, source string) error { - src, err := os.Open(source) - if err != nil { - return errors.Wrapf(err, "failed to open source %s", source) - } - defer src.Close() - tgt, err := os.Create(target) - if err != nil { - return errors.Wrapf(err, "failed to open target %s", target) - } - defer tgt.Close() - - return copyFileContent(tgt, src) -} diff --git a/vendor/github.com/containerd/continuity/fs/copy_darwinopenbsdsolaris.go b/vendor/github.com/containerd/continuity/fs/copy_darwinopenbsdsolaris.go deleted file mode 100644 index 92ccacf9..00000000 --- a/vendor/github.com/containerd/continuity/fs/copy_darwinopenbsdsolaris.go +++ /dev/null @@ -1,40 +0,0 @@ -// +build darwin openbsd solaris - -/* - Copyright The containerd 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 fs - -import ( - "os" - "syscall" - - "github.com/pkg/errors" - "golang.org/x/sys/unix" -) - -func copyDevice(dst string, fi os.FileInfo) error { - st, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - return errors.New("unsupported stat type") - } - return unix.Mknod(dst, uint32(fi.Mode()), int(st.Rdev)) -} - -func utimesNano(name string, atime, mtime syscall.Timespec) error { - timespec := []syscall.Timespec{atime, mtime} - return syscall.UtimesNano(name, timespec) -} diff --git a/vendor/github.com/containerd/continuity/fs/copy_freebsd.go b/vendor/github.com/containerd/continuity/fs/copy_freebsd.go deleted file mode 100644 index 4b116c95..00000000 --- a/vendor/github.com/containerd/continuity/fs/copy_freebsd.go +++ /dev/null @@ -1,42 +0,0 @@ -// +build freebsd - -/* - Copyright The containerd 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 fs - -import ( - "os" - "syscall" - - "github.com/pkg/errors" - "golang.org/x/sys/unix" -) - -func copyDevice(dst string, fi os.FileInfo) error { - st, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - return errors.New("unsupported stat type") - } - return unix.Mknod(dst, uint32(fi.Mode()), st.Rdev) -} - -func utimesNano(name string, atime, mtime syscall.Timespec) error { - at := unix.NsecToTimespec(atime.Nano()) - mt := unix.NsecToTimespec(mtime.Nano()) - utimes := [2]unix.Timespec{at, mt} - return unix.UtimesNanoAt(unix.AT_FDCWD, name, utimes[0:], unix.AT_SYMLINK_NOFOLLOW) -} diff --git a/vendor/github.com/containerd/continuity/fs/copy_linux.go b/vendor/github.com/containerd/continuity/fs/copy_linux.go deleted file mode 100644 index 72bae7d4..00000000 --- a/vendor/github.com/containerd/continuity/fs/copy_linux.go +++ /dev/null @@ -1,147 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "io" - "os" - "syscall" - - "github.com/containerd/continuity/sysx" - "github.com/pkg/errors" - "golang.org/x/sys/unix" -) - -func copyFileInfo(fi os.FileInfo, name string) error { - st := fi.Sys().(*syscall.Stat_t) - if err := os.Lchown(name, int(st.Uid), int(st.Gid)); err != nil { - if os.IsPermission(err) { - // Normally if uid/gid are the same this would be a no-op, but some - // filesystems may still return EPERM... for instance NFS does this. - // In such a case, this is not an error. - if dstStat, err2 := os.Lstat(name); err2 == nil { - st2 := dstStat.Sys().(*syscall.Stat_t) - if st.Uid == st2.Uid && st.Gid == st2.Gid { - err = nil - } - } - } - if err != nil { - return errors.Wrapf(err, "failed to chown %s", name) - } - } - - if (fi.Mode() & os.ModeSymlink) != os.ModeSymlink { - if err := os.Chmod(name, fi.Mode()); err != nil { - return errors.Wrapf(err, "failed to chmod %s", name) - } - } - - timespec := []unix.Timespec{ - unix.NsecToTimespec(syscall.TimespecToNsec(StatAtime(st))), - unix.NsecToTimespec(syscall.TimespecToNsec(StatMtime(st))), - } - if err := unix.UtimesNanoAt(unix.AT_FDCWD, name, timespec, unix.AT_SYMLINK_NOFOLLOW); err != nil { - return errors.Wrapf(err, "failed to utime %s", name) - } - - return nil -} - -const maxSSizeT = int64(^uint(0) >> 1) - -func copyFileContent(dst, src *os.File) error { - st, err := src.Stat() - if err != nil { - return errors.Wrap(err, "unable to stat source") - } - - size := st.Size() - first := true - srcFd := int(src.Fd()) - dstFd := int(dst.Fd()) - - for size > 0 { - // Ensure that we are never trying to copy more than SSIZE_MAX at a - // time and at the same time avoids overflows when the file is larger - // than 4GB on 32-bit systems. - var copySize int - if size > maxSSizeT { - copySize = int(maxSSizeT) - } else { - copySize = int(size) - } - n, err := unix.CopyFileRange(srcFd, nil, dstFd, nil, copySize, 0) - if err != nil { - if (err != unix.ENOSYS && err != unix.EXDEV) || !first { - return errors.Wrap(err, "copy file range failed") - } - - buf := bufferPool.Get().(*[]byte) - _, err = io.CopyBuffer(dst, src, *buf) - bufferPool.Put(buf) - return errors.Wrap(err, "userspace copy failed") - } - - first = false - size -= int64(n) - } - - return nil -} - -func copyXAttrs(dst, src string, xeh XAttrErrorHandler) error { - xattrKeys, err := sysx.LListxattr(src) - if err != nil { - e := errors.Wrapf(err, "failed to list xattrs on %s", src) - if xeh != nil { - e = xeh(dst, src, "", e) - } - return e - } - for _, xattr := range xattrKeys { - data, err := sysx.LGetxattr(src, xattr) - if err != nil { - e := errors.Wrapf(err, "failed to get xattr %q on %s", xattr, src) - if xeh != nil { - if e = xeh(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - if err := sysx.LSetxattr(dst, xattr, data, 0); err != nil { - e := errors.Wrapf(err, "failed to set xattr %q on %s", xattr, dst) - if xeh != nil { - if e = xeh(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - } - - return nil -} - -func copyDevice(dst string, fi os.FileInfo) error { - st, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - return errors.New("unsupported stat type") - } - return unix.Mknod(dst, uint32(fi.Mode()), int(st.Rdev)) -} diff --git a/vendor/github.com/containerd/continuity/fs/copy_unix.go b/vendor/github.com/containerd/continuity/fs/copy_unix.go deleted file mode 100644 index dfd857aa..00000000 --- a/vendor/github.com/containerd/continuity/fs/copy_unix.go +++ /dev/null @@ -1,102 +0,0 @@ -// +build darwin freebsd openbsd solaris - -/* - Copyright The containerd 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 fs - -import ( - "io" - "os" - "syscall" - - "github.com/containerd/continuity/sysx" - "github.com/pkg/errors" -) - -func copyFileInfo(fi os.FileInfo, name string) error { - st := fi.Sys().(*syscall.Stat_t) - if err := os.Lchown(name, int(st.Uid), int(st.Gid)); err != nil { - if os.IsPermission(err) { - // Normally if uid/gid are the same this would be a no-op, but some - // filesystems may still return EPERM... for instance NFS does this. - // In such a case, this is not an error. - if dstStat, err2 := os.Lstat(name); err2 == nil { - st2 := dstStat.Sys().(*syscall.Stat_t) - if st.Uid == st2.Uid && st.Gid == st2.Gid { - err = nil - } - } - } - if err != nil { - return errors.Wrapf(err, "failed to chown %s", name) - } - } - - if (fi.Mode() & os.ModeSymlink) != os.ModeSymlink { - if err := os.Chmod(name, fi.Mode()); err != nil { - return errors.Wrapf(err, "failed to chmod %s", name) - } - } - - if err := utimesNano(name, StatAtime(st), StatMtime(st)); err != nil { - return errors.Wrapf(err, "failed to utime %s", name) - } - - return nil -} - -func copyFileContent(dst, src *os.File) error { - buf := bufferPool.Get().(*[]byte) - _, err := io.CopyBuffer(dst, src, *buf) - bufferPool.Put(buf) - - return err -} - -func copyXAttrs(dst, src string, xeh XAttrErrorHandler) error { - xattrKeys, err := sysx.LListxattr(src) - if err != nil { - e := errors.Wrapf(err, "failed to list xattrs on %s", src) - if xeh != nil { - e = xeh(dst, src, "", e) - } - return e - } - for _, xattr := range xattrKeys { - data, err := sysx.LGetxattr(src, xattr) - if err != nil { - e := errors.Wrapf(err, "failed to get xattr %q on %s", xattr, src) - if xeh != nil { - if e = xeh(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - if err := sysx.LSetxattr(dst, xattr, data, 0); err != nil { - e := errors.Wrapf(err, "failed to set xattr %q on %s", xattr, dst) - if xeh != nil { - if e = xeh(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - } - - return nil -} diff --git a/vendor/github.com/containerd/continuity/fs/copy_windows.go b/vendor/github.com/containerd/continuity/fs/copy_windows.go deleted file mode 100644 index 27c7d7db..00000000 --- a/vendor/github.com/containerd/continuity/fs/copy_windows.go +++ /dev/null @@ -1,49 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "io" - "os" - - "github.com/pkg/errors" -) - -func copyFileInfo(fi os.FileInfo, name string) error { - if err := os.Chmod(name, fi.Mode()); err != nil { - return errors.Wrapf(err, "failed to chmod %s", name) - } - - // TODO: copy windows specific metadata - - return nil -} - -func copyFileContent(dst, src *os.File) error { - buf := bufferPool.Get().(*[]byte) - _, err := io.CopyBuffer(dst, src, *buf) - bufferPool.Put(buf) - return err -} - -func copyXAttrs(dst, src string, xeh XAttrErrorHandler) error { - return nil -} - -func copyDevice(dst string, fi os.FileInfo) error { - return errors.New("device copy not supported") -} diff --git a/vendor/github.com/containerd/continuity/fs/diff.go b/vendor/github.com/containerd/continuity/fs/diff.go deleted file mode 100644 index e64f9e73..00000000 --- a/vendor/github.com/containerd/continuity/fs/diff.go +++ /dev/null @@ -1,326 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "context" - "os" - "path/filepath" - "strings" - - "golang.org/x/sync/errgroup" - - "github.com/sirupsen/logrus" -) - -// ChangeKind is the type of modification that -// a change is making. -type ChangeKind int - -const ( - // ChangeKindUnmodified represents an unmodified - // file - ChangeKindUnmodified = iota - - // ChangeKindAdd represents an addition of - // a file - ChangeKindAdd - - // ChangeKindModify represents a change to - // an existing file - ChangeKindModify - - // ChangeKindDelete represents a delete of - // a file - ChangeKindDelete -) - -func (k ChangeKind) String() string { - switch k { - case ChangeKindUnmodified: - return "unmodified" - case ChangeKindAdd: - return "add" - case ChangeKindModify: - return "modify" - case ChangeKindDelete: - return "delete" - default: - return "" - } -} - -// Change represents single change between a diff and its parent. -type Change struct { - Kind ChangeKind - Path string -} - -// ChangeFunc is the type of function called for each change -// computed during a directory changes calculation. -type ChangeFunc func(ChangeKind, string, os.FileInfo, error) error - -// Changes computes changes between two directories calling the -// given change function for each computed change. The first -// directory is intended to the base directory and second -// directory the changed directory. -// -// The change callback is called by the order of path names and -// should be appliable in that order. -// Due to this apply ordering, the following is true -// - Removed directory trees only create a single change for the root -// directory removed. Remaining changes are implied. -// - A directory which is modified to become a file will not have -// delete entries for sub-path items, their removal is implied -// by the removal of the parent directory. -// -// Opaque directories will not be treated specially and each file -// removed from the base directory will show up as a removal. -// -// File content comparisons will be done on files which have timestamps -// which may have been truncated. If either of the files being compared -// has a zero value nanosecond value, each byte will be compared for -// differences. If 2 files have the same seconds value but different -// nanosecond values where one of those values is zero, the files will -// be considered unchanged if the content is the same. This behavior -// is to account for timestamp truncation during archiving. -func Changes(ctx context.Context, a, b string, changeFn ChangeFunc) error { - if a == "" { - logrus.Debugf("Using single walk diff for %s", b) - return addDirChanges(ctx, changeFn, b) - } else if diffOptions := detectDirDiff(b, a); diffOptions != nil { - logrus.Debugf("Using single walk diff for %s from %s", diffOptions.diffDir, a) - return diffDirChanges(ctx, changeFn, a, diffOptions) - } - - logrus.Debugf("Using double walk diff for %s from %s", b, a) - return doubleWalkDiff(ctx, changeFn, a, b) -} - -func addDirChanges(ctx context.Context, changeFn ChangeFunc, root string) error { - return filepath.Walk(root, func(path string, f os.FileInfo, err error) error { - if err != nil { - return err - } - - // Rebase path - path, err = filepath.Rel(root, path) - if err != nil { - return err - } - - path = filepath.Join(string(os.PathSeparator), path) - - // Skip root - if path == string(os.PathSeparator) { - return nil - } - - return changeFn(ChangeKindAdd, path, f, nil) - }) -} - -// diffDirOptions is used when the diff can be directly calculated from -// a diff directory to its base, without walking both trees. -type diffDirOptions struct { - diffDir string - skipChange func(string) (bool, error) - deleteChange func(string, string, os.FileInfo) (string, error) -} - -// diffDirChanges walks the diff directory and compares changes against the base. -func diffDirChanges(ctx context.Context, changeFn ChangeFunc, base string, o *diffDirOptions) error { - changedDirs := make(map[string]struct{}) - return filepath.Walk(o.diffDir, func(path string, f os.FileInfo, err error) error { - if err != nil { - return err - } - - // Rebase path - path, err = filepath.Rel(o.diffDir, path) - if err != nil { - return err - } - - path = filepath.Join(string(os.PathSeparator), path) - - // Skip root - if path == string(os.PathSeparator) { - return nil - } - - // TODO: handle opaqueness, start new double walker at this - // location to get deletes, and skip tree in single walker - - if o.skipChange != nil { - if skip, err := o.skipChange(path); skip { - return err - } - } - - var kind ChangeKind - - deletedFile, err := o.deleteChange(o.diffDir, path, f) - if err != nil { - return err - } - - // Find out what kind of modification happened - if deletedFile != "" { - path = deletedFile - kind = ChangeKindDelete - f = nil - } else { - // Otherwise, the file was added - kind = ChangeKindAdd - - // ...Unless it already existed in a base, in which case, it's a modification - stat, err := os.Stat(filepath.Join(base, path)) - if err != nil && !os.IsNotExist(err) { - return err - } - if err == nil { - // The file existed in the base, so that's a modification - - // However, if it's a directory, maybe it wasn't actually modified. - // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar - if stat.IsDir() && f.IsDir() { - if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) { - // Both directories are the same, don't record the change - return nil - } - } - kind = ChangeKindModify - } - } - - // If /foo/bar/file.txt is modified, then /foo/bar must be part of the changed files. - // This block is here to ensure the change is recorded even if the - // modify time, mode and size of the parent directory in the rw and ro layers are all equal. - // Check https://github.com/docker/docker/pull/13590 for details. - if f.IsDir() { - changedDirs[path] = struct{}{} - } - if kind == ChangeKindAdd || kind == ChangeKindDelete { - parent := filepath.Dir(path) - if _, ok := changedDirs[parent]; !ok && parent != "/" { - pi, err := os.Stat(filepath.Join(o.diffDir, parent)) - if err := changeFn(ChangeKindModify, parent, pi, err); err != nil { - return err - } - changedDirs[parent] = struct{}{} - } - } - - return changeFn(kind, path, f, nil) - }) -} - -// doubleWalkDiff walks both directories to create a diff -func doubleWalkDiff(ctx context.Context, changeFn ChangeFunc, a, b string) (err error) { - g, ctx := errgroup.WithContext(ctx) - - var ( - c1 = make(chan *currentPath) - c2 = make(chan *currentPath) - - f1, f2 *currentPath - rmdir string - ) - g.Go(func() error { - defer close(c1) - return pathWalk(ctx, a, c1) - }) - g.Go(func() error { - defer close(c2) - return pathWalk(ctx, b, c2) - }) - g.Go(func() error { - for c1 != nil || c2 != nil { - if f1 == nil && c1 != nil { - f1, err = nextPath(ctx, c1) - if err != nil { - return err - } - if f1 == nil { - c1 = nil - } - } - - if f2 == nil && c2 != nil { - f2, err = nextPath(ctx, c2) - if err != nil { - return err - } - if f2 == nil { - c2 = nil - } - } - if f1 == nil && f2 == nil { - continue - } - - var f os.FileInfo - k, p := pathChange(f1, f2) - switch k { - case ChangeKindAdd: - if rmdir != "" { - rmdir = "" - } - f = f2.f - f2 = nil - case ChangeKindDelete: - // Check if this file is already removed by being - // under of a removed directory - if rmdir != "" && strings.HasPrefix(f1.path, rmdir) { - f1 = nil - continue - } else if f1.f.IsDir() { - rmdir = f1.path + string(os.PathSeparator) - } else if rmdir != "" { - rmdir = "" - } - f1 = nil - case ChangeKindModify: - same, err := sameFile(f1, f2) - if err != nil { - return err - } - if f1.f.IsDir() && !f2.f.IsDir() { - rmdir = f1.path + string(os.PathSeparator) - } else if rmdir != "" { - rmdir = "" - } - f = f2.f - f1 = nil - f2 = nil - if same { - if !isLinked(f) { - continue - } - k = ChangeKindUnmodified - } - } - if err := changeFn(k, p, f, nil); err != nil { - return err - } - } - return nil - }) - - return g.Wait() -} diff --git a/vendor/github.com/containerd/continuity/fs/diff_unix.go b/vendor/github.com/containerd/continuity/fs/diff_unix.go deleted file mode 100644 index 7913af27..00000000 --- a/vendor/github.com/containerd/continuity/fs/diff_unix.go +++ /dev/null @@ -1,74 +0,0 @@ -// +build !windows - -/* - Copyright The containerd 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 fs - -import ( - "bytes" - "os" - "syscall" - - "github.com/containerd/continuity/sysx" - "github.com/pkg/errors" -) - -// detectDirDiff returns diff dir options if a directory could -// be found in the mount info for upper which is the direct -// diff with the provided lower directory -func detectDirDiff(upper, lower string) *diffDirOptions { - // TODO: get mount options for upper - // TODO: detect AUFS - // TODO: detect overlay - return nil -} - -// compareSysStat returns whether the stats are equivalent, -// whether the files are considered the same file, and -// an error -func compareSysStat(s1, s2 interface{}) (bool, error) { - ls1, ok := s1.(*syscall.Stat_t) - if !ok { - return false, nil - } - ls2, ok := s2.(*syscall.Stat_t) - if !ok { - return false, nil - } - - return ls1.Mode == ls2.Mode && ls1.Uid == ls2.Uid && ls1.Gid == ls2.Gid && ls1.Rdev == ls2.Rdev, nil -} - -func compareCapabilities(p1, p2 string) (bool, error) { - c1, err := sysx.LGetxattr(p1, "security.capability") - if err != nil && err != sysx.ENODATA { - return false, errors.Wrapf(err, "failed to get xattr for %s", p1) - } - c2, err := sysx.LGetxattr(p2, "security.capability") - if err != nil && err != sysx.ENODATA { - return false, errors.Wrapf(err, "failed to get xattr for %s", p2) - } - return bytes.Equal(c1, c2), nil -} - -func isLinked(f os.FileInfo) bool { - s, ok := f.Sys().(*syscall.Stat_t) - if !ok { - return false - } - return !f.IsDir() && s.Nlink > 1 -} diff --git a/vendor/github.com/containerd/continuity/fs/diff_windows.go b/vendor/github.com/containerd/continuity/fs/diff_windows.go deleted file mode 100644 index 4bfa72d3..00000000 --- a/vendor/github.com/containerd/continuity/fs/diff_windows.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "os" - - "golang.org/x/sys/windows" -) - -func detectDirDiff(upper, lower string) *diffDirOptions { - return nil -} - -func compareSysStat(s1, s2 interface{}) (bool, error) { - f1, ok := s1.(windows.Win32FileAttributeData) - if !ok { - return false, nil - } - f2, ok := s2.(windows.Win32FileAttributeData) - if !ok { - return false, nil - } - return f1.FileAttributes == f2.FileAttributes, nil -} - -func compareCapabilities(p1, p2 string) (bool, error) { - // TODO: Use windows equivalent - return true, nil -} - -func isLinked(os.FileInfo) bool { - return false -} diff --git a/vendor/github.com/containerd/continuity/fs/dtype_linux.go b/vendor/github.com/containerd/continuity/fs/dtype_linux.go deleted file mode 100644 index 10510d8d..00000000 --- a/vendor/github.com/containerd/continuity/fs/dtype_linux.go +++ /dev/null @@ -1,103 +0,0 @@ -// +build linux - -/* - Copyright The containerd 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 fs - -import ( - "fmt" - "io/ioutil" - "os" - "syscall" - "unsafe" -) - -func locateDummyIfEmpty(path string) (string, error) { - children, err := ioutil.ReadDir(path) - if err != nil { - return "", err - } - if len(children) != 0 { - return "", nil - } - dummyFile, err := ioutil.TempFile(path, "fsutils-dummy") - if err != nil { - return "", err - } - name := dummyFile.Name() - err = dummyFile.Close() - return name, err -} - -// SupportsDType returns whether the filesystem mounted on path supports d_type -func SupportsDType(path string) (bool, error) { - // locate dummy so that we have at least one dirent - dummy, err := locateDummyIfEmpty(path) - if err != nil { - return false, err - } - if dummy != "" { - defer os.Remove(dummy) - } - - visited := 0 - supportsDType := true - fn := func(ent *syscall.Dirent) bool { - visited++ - if ent.Type == syscall.DT_UNKNOWN { - supportsDType = false - // stop iteration - return true - } - // continue iteration - return false - } - if err = iterateReadDir(path, fn); err != nil { - return false, err - } - if visited == 0 { - return false, fmt.Errorf("did not hit any dirent during iteration %s", path) - } - return supportsDType, nil -} - -func iterateReadDir(path string, fn func(*syscall.Dirent) bool) error { - d, err := os.Open(path) - if err != nil { - return err - } - defer d.Close() - fd := int(d.Fd()) - buf := make([]byte, 4096) - for { - nbytes, err := syscall.ReadDirent(fd, buf) - if err != nil { - return err - } - if nbytes == 0 { - break - } - for off := 0; off < nbytes; { - ent := (*syscall.Dirent)(unsafe.Pointer(&buf[off])) - if stop := fn(ent); stop { - return nil - } - off += int(ent.Reclen) - } - } - return nil -} diff --git a/vendor/github.com/containerd/continuity/fs/du.go b/vendor/github.com/containerd/continuity/fs/du.go deleted file mode 100644 index fccc985d..00000000 --- a/vendor/github.com/containerd/continuity/fs/du.go +++ /dev/null @@ -1,38 +0,0 @@ -/* - Copyright The containerd 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 fs - -import "context" - -// Usage of disk information -type Usage struct { - Inodes int64 - Size int64 -} - -// DiskUsage counts the number of inodes and disk usage for the resources under -// path. -func DiskUsage(ctx context.Context, roots ...string) (Usage, error) { - return diskUsage(ctx, roots...) -} - -// DiffUsage counts the numbers of inodes and disk usage in the -// diff between the 2 directories. The first path is intended -// as the base directory and the second as the changed directory. -func DiffUsage(ctx context.Context, a, b string) (Usage, error) { - return diffUsage(ctx, a, b) -} diff --git a/vendor/github.com/containerd/continuity/fs/du_unix.go b/vendor/github.com/containerd/continuity/fs/du_unix.go deleted file mode 100644 index 9da43d1b..00000000 --- a/vendor/github.com/containerd/continuity/fs/du_unix.go +++ /dev/null @@ -1,120 +0,0 @@ -// +build !windows - -/* - Copyright The containerd 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 fs - -import ( - "context" - "os" - "path/filepath" - "syscall" -) - -// blocksUnitSize is the unit used by `st_blocks` in `stat` in bytes. -// See https://man7.org/linux/man-pages/man2/stat.2.html -// st_blocks -// This field indicates the number of blocks allocated to the -// file, in 512-byte units. (This may be smaller than -// st_size/512 when the file has holes.) -const blocksUnitSize = 512 - -type inode struct { - // TODO(stevvooe): Can probably reduce memory usage by not tracking - // device, but we can leave this right for now. - dev, ino uint64 -} - -func newInode(stat *syscall.Stat_t) inode { - return inode{ - // Dev is uint32 on darwin/bsd, uint64 on linux/solaris/freebsd - dev: uint64(stat.Dev), // nolint: unconvert - // Ino is uint32 on bsd, uint64 on darwin/linux/solaris/freebsd - ino: uint64(stat.Ino), // nolint: unconvert - } -} - -func diskUsage(ctx context.Context, roots ...string) (Usage, error) { - - var ( - size int64 - inodes = map[inode]struct{}{} // expensive! - ) - - for _, root := range roots { - if err := filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { - if err != nil { - return err - } - - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - stat := fi.Sys().(*syscall.Stat_t) - inoKey := newInode(stat) - if _, ok := inodes[inoKey]; !ok { - inodes[inoKey] = struct{}{} - size += stat.Blocks * blocksUnitSize - } - - return nil - }); err != nil { - return Usage{}, err - } - } - - return Usage{ - Inodes: int64(len(inodes)), - Size: size, - }, nil -} - -func diffUsage(ctx context.Context, a, b string) (Usage, error) { - var ( - size int64 - inodes = map[inode]struct{}{} // expensive! - ) - - if err := Changes(ctx, a, b, func(kind ChangeKind, _ string, fi os.FileInfo, err error) error { - if err != nil { - return err - } - - if kind == ChangeKindAdd || kind == ChangeKindModify { - stat := fi.Sys().(*syscall.Stat_t) - inoKey := newInode(stat) - if _, ok := inodes[inoKey]; !ok { - inodes[inoKey] = struct{}{} - size += stat.Blocks * blocksUnitSize - } - - return nil - - } - return nil - }); err != nil { - return Usage{}, err - } - - return Usage{ - Inodes: int64(len(inodes)), - Size: size, - }, nil -} diff --git a/vendor/github.com/containerd/continuity/fs/du_windows.go b/vendor/github.com/containerd/continuity/fs/du_windows.go deleted file mode 100644 index 8f25ec59..00000000 --- a/vendor/github.com/containerd/continuity/fs/du_windows.go +++ /dev/null @@ -1,82 +0,0 @@ -// +build windows - -/* - Copyright The containerd 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 fs - -import ( - "context" - "os" - "path/filepath" -) - -func diskUsage(ctx context.Context, roots ...string) (Usage, error) { - var ( - size int64 - ) - - // TODO(stevvooe): Support inodes (or equivalent) for windows. - - for _, root := range roots { - if err := filepath.Walk(root, func(path string, fi os.FileInfo, err error) error { - if err != nil { - return err - } - - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - size += fi.Size() - return nil - }); err != nil { - return Usage{}, err - } - } - - return Usage{ - Size: size, - }, nil -} - -func diffUsage(ctx context.Context, a, b string) (Usage, error) { - var ( - size int64 - ) - - if err := Changes(ctx, a, b, func(kind ChangeKind, _ string, fi os.FileInfo, err error) error { - if err != nil { - return err - } - - if kind == ChangeKindAdd || kind == ChangeKindModify { - size += fi.Size() - - return nil - - } - return nil - }); err != nil { - return Usage{}, err - } - - return Usage{ - Size: size, - }, nil -} diff --git a/vendor/github.com/containerd/continuity/fs/hardlink.go b/vendor/github.com/containerd/continuity/fs/hardlink.go deleted file mode 100644 index 762aa45e..00000000 --- a/vendor/github.com/containerd/continuity/fs/hardlink.go +++ /dev/null @@ -1,43 +0,0 @@ -/* - Copyright The containerd 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 fs - -import "os" - -// GetLinkInfo returns an identifier representing the node a hardlink is pointing -// to. If the file is not hard linked then 0 will be returned. -func GetLinkInfo(fi os.FileInfo) (uint64, bool) { - return getLinkInfo(fi) -} - -// getLinkSource returns a path for the given name and -// file info to its link source in the provided inode -// map. If the given file name is not in the map and -// has other links, it is added to the inode map -// to be a source for other link locations. -func getLinkSource(name string, fi os.FileInfo, inodes map[uint64]string) (string, error) { - inode, isHardlink := getLinkInfo(fi) - if !isHardlink { - return "", nil - } - - path, ok := inodes[inode] - if !ok { - inodes[inode] = name - } - return path, nil -} diff --git a/vendor/github.com/containerd/continuity/fs/hardlink_unix.go b/vendor/github.com/containerd/continuity/fs/hardlink_unix.go deleted file mode 100644 index f95f0904..00000000 --- a/vendor/github.com/containerd/continuity/fs/hardlink_unix.go +++ /dev/null @@ -1,34 +0,0 @@ -// +build !windows - -/* - Copyright The containerd 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 fs - -import ( - "os" - "syscall" -) - -func getLinkInfo(fi os.FileInfo) (uint64, bool) { - s, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - return 0, false - } - - // Ino is uint32 on bsd, uint64 on darwin/linux/solaris - return uint64(s.Ino), !fi.IsDir() && s.Nlink > 1 // nolint: unconvert -} diff --git a/vendor/github.com/containerd/continuity/fs/hardlink_windows.go b/vendor/github.com/containerd/continuity/fs/hardlink_windows.go deleted file mode 100644 index 74855471..00000000 --- a/vendor/github.com/containerd/continuity/fs/hardlink_windows.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - Copyright The containerd 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 fs - -import "os" - -func getLinkInfo(fi os.FileInfo) (uint64, bool) { - return 0, false -} diff --git a/vendor/github.com/containerd/continuity/fs/path.go b/vendor/github.com/containerd/continuity/fs/path.go deleted file mode 100644 index c26be798..00000000 --- a/vendor/github.com/containerd/continuity/fs/path.go +++ /dev/null @@ -1,311 +0,0 @@ -/* - Copyright The containerd 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 fs - -import ( - "bytes" - "context" - "io" - "os" - "path/filepath" - - "github.com/pkg/errors" -) - -var ( - errTooManyLinks = errors.New("too many links") -) - -type currentPath struct { - path string - f os.FileInfo - fullPath string -} - -func pathChange(lower, upper *currentPath) (ChangeKind, string) { - if lower == nil { - if upper == nil { - panic("cannot compare nil paths") - } - return ChangeKindAdd, upper.path - } - if upper == nil { - return ChangeKindDelete, lower.path - } - - switch i := directoryCompare(lower.path, upper.path); { - case i < 0: - // File in lower that is not in upper - return ChangeKindDelete, lower.path - case i > 0: - // File in upper that is not in lower - return ChangeKindAdd, upper.path - default: - return ChangeKindModify, upper.path - } -} - -func directoryCompare(a, b string) int { - l := len(a) - if len(b) < l { - l = len(b) - } - for i := 0; i < l; i++ { - c1, c2 := a[i], b[i] - if c1 == filepath.Separator { - c1 = byte(0) - } - if c2 == filepath.Separator { - c2 = byte(0) - } - if c1 < c2 { - return -1 - } - if c1 > c2 { - return +1 - } - } - if len(a) < len(b) { - return -1 - } - if len(a) > len(b) { - return +1 - } - return 0 -} - -func sameFile(f1, f2 *currentPath) (bool, error) { - if os.SameFile(f1.f, f2.f) { - return true, nil - } - - equalStat, err := compareSysStat(f1.f.Sys(), f2.f.Sys()) - if err != nil || !equalStat { - return equalStat, err - } - - if eq, err := compareCapabilities(f1.fullPath, f2.fullPath); err != nil || !eq { - return eq, err - } - - // If not a directory also check size, modtime, and content - if !f1.f.IsDir() { - if f1.f.Size() != f2.f.Size() { - return false, nil - } - t1 := f1.f.ModTime() - t2 := f2.f.ModTime() - - if t1.Unix() != t2.Unix() { - return false, nil - } - - // If the timestamp may have been truncated in both of the - // files, check content of file to determine difference - if t1.Nanosecond() == 0 && t2.Nanosecond() == 0 { - if (f1.f.Mode() & os.ModeSymlink) == os.ModeSymlink { - return compareSymlinkTarget(f1.fullPath, f2.fullPath) - } - if f1.f.Size() == 0 { // if file sizes are zero length, the files are the same by definition - return true, nil - } - return compareFileContent(f1.fullPath, f2.fullPath) - } else if t1.Nanosecond() != t2.Nanosecond() { - return false, nil - } - } - - return true, nil -} - -func compareSymlinkTarget(p1, p2 string) (bool, error) { - t1, err := os.Readlink(p1) - if err != nil { - return false, err - } - t2, err := os.Readlink(p2) - if err != nil { - return false, err - } - return t1 == t2, nil -} - -const compareChuckSize = 32 * 1024 - -// compareFileContent compares the content of 2 same sized files -// by comparing each byte. -func compareFileContent(p1, p2 string) (bool, error) { - f1, err := os.Open(p1) - if err != nil { - return false, err - } - defer f1.Close() - f2, err := os.Open(p2) - if err != nil { - return false, err - } - defer f2.Close() - - b1 := make([]byte, compareChuckSize) - b2 := make([]byte, compareChuckSize) - for { - n1, err1 := f1.Read(b1) - if err1 != nil && err1 != io.EOF { - return false, err1 - } - n2, err2 := f2.Read(b2) - if err2 != nil && err2 != io.EOF { - return false, err2 - } - if n1 != n2 || !bytes.Equal(b1[:n1], b2[:n2]) { - return false, nil - } - if err1 == io.EOF && err2 == io.EOF { - return true, nil - } - } -} - -func pathWalk(ctx context.Context, root string, pathC chan<- *currentPath) error { - return filepath.Walk(root, func(path string, f os.FileInfo, err error) error { - if err != nil { - return err - } - - // Rebase path - path, err = filepath.Rel(root, path) - if err != nil { - return err - } - - path = filepath.Join(string(os.PathSeparator), path) - - // Skip root - if path == string(os.PathSeparator) { - return nil - } - - p := ¤tPath{ - path: path, - f: f, - fullPath: filepath.Join(root, path), - } - - select { - case <-ctx.Done(): - return ctx.Err() - case pathC <- p: - return nil - } - }) -} - -func nextPath(ctx context.Context, pathC <-chan *currentPath) (*currentPath, error) { - select { - case <-ctx.Done(): - return nil, ctx.Err() - case p := <-pathC: - return p, nil - } -} - -// RootPath joins a path with a root, evaluating and bounding any -// symlink to the root directory. -func RootPath(root, path string) (string, error) { - if path == "" { - return root, nil - } - var linksWalked int // to protect against cycles - for { - i := linksWalked - newpath, err := walkLinks(root, path, &linksWalked) - if err != nil { - return "", err - } - path = newpath - if i == linksWalked { - newpath = filepath.Join("/", newpath) - if path == newpath { - return filepath.Join(root, newpath), nil - } - path = newpath - } - } -} - -func walkLink(root, path string, linksWalked *int) (newpath string, islink bool, err error) { - if *linksWalked > 255 { - return "", false, errTooManyLinks - } - - path = filepath.Join("/", path) - if path == "/" { - return path, false, nil - } - realPath := filepath.Join(root, path) - - fi, err := os.Lstat(realPath) - if err != nil { - // If path does not yet exist, treat as non-symlink - if os.IsNotExist(err) { - return path, false, nil - } - return "", false, err - } - if fi.Mode()&os.ModeSymlink == 0 { - return path, false, nil - } - newpath, err = os.Readlink(realPath) - if err != nil { - return "", false, err - } - *linksWalked++ - return newpath, true, nil -} - -func walkLinks(root, path string, linksWalked *int) (string, error) { - switch dir, file := filepath.Split(path); { - case dir == "": - newpath, _, err := walkLink(root, file, linksWalked) - return newpath, err - case file == "": - if os.IsPathSeparator(dir[len(dir)-1]) { - if dir == "/" { - return dir, nil - } - return walkLinks(root, dir[:len(dir)-1], linksWalked) - } - newpath, _, err := walkLink(root, dir, linksWalked) - return newpath, err - default: - newdir, err := walkLinks(root, dir, linksWalked) - if err != nil { - return "", err - } - newpath, islink, err := walkLink(root, filepath.Join(newdir, file), linksWalked) - if err != nil { - return "", err - } - if !islink { - return newpath, nil - } - if filepath.IsAbs(newpath) { - return newpath, nil - } - return filepath.Join(newdir, newpath), nil - } -} diff --git a/vendor/github.com/containerd/continuity/fs/stat_darwinfreebsd.go b/vendor/github.com/containerd/continuity/fs/stat_darwinfreebsd.go deleted file mode 100644 index cb7400a3..00000000 --- a/vendor/github.com/containerd/continuity/fs/stat_darwinfreebsd.go +++ /dev/null @@ -1,44 +0,0 @@ -// +build darwin freebsd - -/* - Copyright The containerd 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 fs - -import ( - "syscall" - "time" -) - -// StatAtime returns the access time from a stat struct -func StatAtime(st *syscall.Stat_t) syscall.Timespec { - return st.Atimespec -} - -// StatCtime returns the created time from a stat struct -func StatCtime(st *syscall.Stat_t) syscall.Timespec { - return st.Ctimespec -} - -// StatMtime returns the modified time from a stat struct -func StatMtime(st *syscall.Stat_t) syscall.Timespec { - return st.Mtimespec -} - -// StatATimeAsTime returns the access time as a time.Time -func StatATimeAsTime(st *syscall.Stat_t) time.Time { - return time.Unix(int64(st.Atimespec.Sec), int64(st.Atimespec.Nsec)) // nolint: unconvert -} diff --git a/vendor/github.com/containerd/continuity/fs/stat_linuxopenbsd.go b/vendor/github.com/containerd/continuity/fs/stat_linuxopenbsd.go deleted file mode 100644 index c68df6e5..00000000 --- a/vendor/github.com/containerd/continuity/fs/stat_linuxopenbsd.go +++ /dev/null @@ -1,45 +0,0 @@ -// +build linux openbsd - -/* - Copyright The containerd 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 fs - -import ( - "syscall" - "time" -) - -// StatAtime returns the Atim -func StatAtime(st *syscall.Stat_t) syscall.Timespec { - return st.Atim -} - -// StatCtime returns the Ctim -func StatCtime(st *syscall.Stat_t) syscall.Timespec { - return st.Ctim -} - -// StatMtime returns the Mtim -func StatMtime(st *syscall.Stat_t) syscall.Timespec { - return st.Mtim -} - -// StatATimeAsTime returns st.Atim as a time.Time -func StatATimeAsTime(st *syscall.Stat_t) time.Time { - // The int64 conversions ensure the line compiles for 32-bit systems as well. - return time.Unix(int64(st.Atim.Sec), int64(st.Atim.Nsec)) // nolint: unconvert -} diff --git a/vendor/github.com/containerd/continuity/fs/time.go b/vendor/github.com/containerd/continuity/fs/time.go deleted file mode 100644 index cde45612..00000000 --- a/vendor/github.com/containerd/continuity/fs/time.go +++ /dev/null @@ -1,29 +0,0 @@ -/* - Copyright The containerd 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 fs - -import "time" - -// Gnu tar and the go tar writer don't have sub-second mtime -// precision, which is problematic when we apply changes via tar -// files, we handle this by comparing for exact times, *or* same -// second count and either a or b having exactly 0 nanoseconds -func sameFsTime(a, b time.Time) bool { - return a == b || - (a.Unix() == b.Unix() && - (a.Nanosecond() == 0 || b.Nanosecond() == 0)) -} diff --git a/vendor/github.com/containerd/continuity/sysx/README.md b/vendor/github.com/containerd/continuity/sysx/README.md deleted file mode 100644 index ad7aee53..00000000 --- a/vendor/github.com/containerd/continuity/sysx/README.md +++ /dev/null @@ -1,3 +0,0 @@ -This package is for internal use only. It is intended to only have -temporary changes before they are upstreamed to golang.org/x/sys/ -(a.k.a. https://github.com/golang/sys). diff --git a/vendor/github.com/containerd/continuity/sysx/generate.sh b/vendor/github.com/containerd/continuity/sysx/generate.sh deleted file mode 100644 index 87d708d7..00000000 --- a/vendor/github.com/containerd/continuity/sysx/generate.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/bash - -# Copyright The containerd 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. - - -set -e - -mksyscall="$(go env GOROOT)/src/syscall/mksyscall.pl" - -fix() { - sed 's,^package syscall$,package sysx,' \ - | sed 's,^import "unsafe"$,import (\n\t"syscall"\n\t"unsafe"\n),' \ - | gofmt -r='BytePtrFromString -> syscall.BytePtrFromString' \ - | gofmt -r='Syscall6 -> syscall.Syscall6' \ - | gofmt -r='Syscall -> syscall.Syscall' \ - | gofmt -r='SYS_GETXATTR -> syscall.SYS_GETXATTR' \ - | gofmt -r='SYS_LISTXATTR -> syscall.SYS_LISTXATTR' \ - | gofmt -r='SYS_SETXATTR -> syscall.SYS_SETXATTR' \ - | gofmt -r='SYS_REMOVEXATTR -> syscall.SYS_REMOVEXATTR' \ - | gofmt -r='SYS_LGETXATTR -> syscall.SYS_LGETXATTR' \ - | gofmt -r='SYS_LLISTXATTR -> syscall.SYS_LLISTXATTR' \ - | gofmt -r='SYS_LSETXATTR -> syscall.SYS_LSETXATTR' \ - | gofmt -r='SYS_LREMOVEXATTR -> syscall.SYS_LREMOVEXATTR' -} - -if [ "$GOARCH" == "" ] || [ "$GOOS" == "" ]; then - echo "Must specify \$GOARCH and \$GOOS" - exit 1 -fi - -mkargs="" - -if [ "$GOARCH" == "386" ] || [ "$GOARCH" == "arm" ]; then - mkargs="-l32" -fi - -for f in "$@"; do - $mksyscall $mkargs "${f}_${GOOS}.go" | fix > "${f}_${GOOS}_${GOARCH}.go" -done - diff --git a/vendor/github.com/containerd/continuity/sysx/nodata_linux.go b/vendor/github.com/containerd/continuity/sysx/nodata_linux.go deleted file mode 100644 index 28ce5d8d..00000000 --- a/vendor/github.com/containerd/continuity/sysx/nodata_linux.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - Copyright The containerd 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 sysx - -import ( - "syscall" -) - -const ENODATA = syscall.ENODATA diff --git a/vendor/github.com/containerd/continuity/sysx/nodata_solaris.go b/vendor/github.com/containerd/continuity/sysx/nodata_solaris.go deleted file mode 100644 index e0575f44..00000000 --- a/vendor/github.com/containerd/continuity/sysx/nodata_solaris.go +++ /dev/null @@ -1,24 +0,0 @@ -/* - Copyright The containerd 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 sysx - -import ( - "syscall" -) - -// This should actually be a set that contains ENOENT and EPERM -const ENODATA = syscall.ENOENT diff --git a/vendor/github.com/containerd/continuity/sysx/nodata_unix.go b/vendor/github.com/containerd/continuity/sysx/nodata_unix.go deleted file mode 100644 index de4b3d50..00000000 --- a/vendor/github.com/containerd/continuity/sysx/nodata_unix.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build darwin freebsd openbsd - -/* - Copyright The containerd 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 sysx - -import ( - "syscall" -) - -const ENODATA = syscall.ENOATTR diff --git a/vendor/github.com/containerd/continuity/sysx/xattr.go b/vendor/github.com/containerd/continuity/sysx/xattr.go deleted file mode 100644 index db6fe70f..00000000 --- a/vendor/github.com/containerd/continuity/sysx/xattr.go +++ /dev/null @@ -1,117 +0,0 @@ -// +build linux darwin - -/* - Copyright The containerd 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 sysx - -import ( - "bytes" - - "golang.org/x/sys/unix" -) - -// Listxattr calls syscall listxattr and reads all content -// and returns a string array -func Listxattr(path string) ([]string, error) { - return listxattrAll(path, unix.Listxattr) -} - -// Removexattr calls syscall removexattr -func Removexattr(path string, attr string) (err error) { - return unix.Removexattr(path, attr) -} - -// Setxattr calls syscall setxattr -func Setxattr(path string, attr string, data []byte, flags int) (err error) { - return unix.Setxattr(path, attr, data, flags) -} - -// Getxattr calls syscall getxattr -func Getxattr(path, attr string) ([]byte, error) { - return getxattrAll(path, attr, unix.Getxattr) -} - -// LListxattr lists xattrs, not following symlinks -func LListxattr(path string) ([]string, error) { - return listxattrAll(path, unix.Llistxattr) -} - -// LRemovexattr removes an xattr, not following symlinks -func LRemovexattr(path string, attr string) (err error) { - return unix.Lremovexattr(path, attr) -} - -// LSetxattr sets an xattr, not following symlinks -func LSetxattr(path string, attr string, data []byte, flags int) (err error) { - return unix.Lsetxattr(path, attr, data, flags) -} - -// LGetxattr gets an xattr, not following symlinks -func LGetxattr(path, attr string) ([]byte, error) { - return getxattrAll(path, attr, unix.Lgetxattr) -} - -const defaultXattrBufferSize = 128 - -type listxattrFunc func(path string, dest []byte) (int, error) - -func listxattrAll(path string, listFunc listxattrFunc) ([]string, error) { - buf := make([]byte, defaultXattrBufferSize) - n, err := listFunc(path, buf) - for err == unix.ERANGE { - // Buffer too small, use zero-sized buffer to get the actual size - n, err = listFunc(path, []byte{}) - if err != nil { - return nil, err - } - buf = make([]byte, n) - n, err = listFunc(path, buf) - } - if err != nil { - return nil, err - } - - ps := bytes.Split(bytes.TrimSuffix(buf[:n], []byte{0}), []byte{0}) - var entries []string - for _, p := range ps { - if len(p) > 0 { - entries = append(entries, string(p)) - } - } - - return entries, nil -} - -type getxattrFunc func(string, string, []byte) (int, error) - -func getxattrAll(path, attr string, getFunc getxattrFunc) ([]byte, error) { - buf := make([]byte, defaultXattrBufferSize) - n, err := getFunc(path, attr, buf) - for err == unix.ERANGE { - // Buffer too small, use zero-sized buffer to get the actual size - n, err = getFunc(path, attr, []byte{}) - if err != nil { - return nil, err - } - buf = make([]byte, n) - n, err = getFunc(path, attr, buf) - } - if err != nil { - return nil, err - } - return buf[:n], nil -} diff --git a/vendor/github.com/containerd/continuity/sysx/xattr_unsupported.go b/vendor/github.com/containerd/continuity/sysx/xattr_unsupported.go deleted file mode 100644 index f8fa8c63..00000000 --- a/vendor/github.com/containerd/continuity/sysx/xattr_unsupported.go +++ /dev/null @@ -1,67 +0,0 @@ -// +build !linux,!darwin - -/* - Copyright The containerd 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 sysx - -import ( - "errors" - "runtime" -) - -var errUnsupported = errors.New("extended attributes unsupported on " + runtime.GOOS) - -// Listxattr calls syscall listxattr and reads all content -// and returns a string array -func Listxattr(path string) ([]string, error) { - return []string{}, nil -} - -// Removexattr calls syscall removexattr -func Removexattr(path string, attr string) (err error) { - return errUnsupported -} - -// Setxattr calls syscall setxattr -func Setxattr(path string, attr string, data []byte, flags int) (err error) { - return errUnsupported -} - -// Getxattr calls syscall getxattr -func Getxattr(path, attr string) ([]byte, error) { - return []byte{}, errUnsupported -} - -// LListxattr lists xattrs, not following symlinks -func LListxattr(path string) ([]string, error) { - return []string{}, nil -} - -// LRemovexattr removes an xattr, not following symlinks -func LRemovexattr(path string, attr string) (err error) { - return errUnsupported -} - -// LSetxattr sets an xattr, not following symlinks -func LSetxattr(path string, attr string, data []byte, flags int) (err error) { - return errUnsupported -} - -// LGetxattr gets an xattr, not following symlinks -func LGetxattr(path, attr string) ([]byte, error) { - return []byte{}, nil -} diff --git a/vendor/github.com/coreos/go-semver/LICENSE b/vendor/github.com/coreos/go-semver/LICENSE deleted file mode 100644 index d6456956..00000000 --- a/vendor/github.com/coreos/go-semver/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/coreos/go-semver/NOTICE b/vendor/github.com/coreos/go-semver/NOTICE deleted file mode 100644 index 23a0ada2..00000000 --- a/vendor/github.com/coreos/go-semver/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -CoreOS Project -Copyright 2018 CoreOS, Inc - -This product includes software developed at CoreOS, Inc. -(http://www.coreos.com/). diff --git a/vendor/github.com/coreos/go-semver/semver/semver.go b/vendor/github.com/coreos/go-semver/semver/semver.go deleted file mode 100644 index 76cf4852..00000000 --- a/vendor/github.com/coreos/go-semver/semver/semver.go +++ /dev/null @@ -1,296 +0,0 @@ -// Copyright 2013-2015 CoreOS, 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. - -// Semantic Versions http://semver.org -package semver - -import ( - "bytes" - "errors" - "fmt" - "regexp" - "strconv" - "strings" -) - -type Version struct { - Major int64 - Minor int64 - Patch int64 - PreRelease PreRelease - Metadata string -} - -type PreRelease string - -func splitOff(input *string, delim string) (val string) { - parts := strings.SplitN(*input, delim, 2) - - if len(parts) == 2 { - *input = parts[0] - val = parts[1] - } - - return val -} - -func New(version string) *Version { - return Must(NewVersion(version)) -} - -func NewVersion(version string) (*Version, error) { - v := Version{} - - if err := v.Set(version); err != nil { - return nil, err - } - - return &v, nil -} - -// Must is a helper for wrapping NewVersion and will panic if err is not nil. -func Must(v *Version, err error) *Version { - if err != nil { - panic(err) - } - return v -} - -// Set parses and updates v from the given version string. Implements flag.Value -func (v *Version) Set(version string) error { - metadata := splitOff(&version, "+") - preRelease := PreRelease(splitOff(&version, "-")) - dotParts := strings.SplitN(version, ".", 3) - - if len(dotParts) != 3 { - return fmt.Errorf("%s is not in dotted-tri format", version) - } - - if err := validateIdentifier(string(preRelease)); err != nil { - return fmt.Errorf("failed to validate pre-release: %v", err) - } - - if err := validateIdentifier(metadata); err != nil { - return fmt.Errorf("failed to validate metadata: %v", err) - } - - parsed := make([]int64, 3, 3) - - for i, v := range dotParts[:3] { - val, err := strconv.ParseInt(v, 10, 64) - parsed[i] = val - if err != nil { - return err - } - } - - v.Metadata = metadata - v.PreRelease = preRelease - v.Major = parsed[0] - v.Minor = parsed[1] - v.Patch = parsed[2] - return nil -} - -func (v Version) String() string { - var buffer bytes.Buffer - - fmt.Fprintf(&buffer, "%d.%d.%d", v.Major, v.Minor, v.Patch) - - if v.PreRelease != "" { - fmt.Fprintf(&buffer, "-%s", v.PreRelease) - } - - if v.Metadata != "" { - fmt.Fprintf(&buffer, "+%s", v.Metadata) - } - - return buffer.String() -} - -func (v *Version) UnmarshalYAML(unmarshal func(interface{}) error) error { - var data string - if err := unmarshal(&data); err != nil { - return err - } - return v.Set(data) -} - -func (v Version) MarshalJSON() ([]byte, error) { - return []byte(`"` + v.String() + `"`), nil -} - -func (v *Version) UnmarshalJSON(data []byte) error { - l := len(data) - if l == 0 || string(data) == `""` { - return nil - } - if l < 2 || data[0] != '"' || data[l-1] != '"' { - return errors.New("invalid semver string") - } - return v.Set(string(data[1 : l-1])) -} - -// Compare tests if v is less than, equal to, or greater than versionB, -// returning -1, 0, or +1 respectively. -func (v Version) Compare(versionB Version) int { - if cmp := recursiveCompare(v.Slice(), versionB.Slice()); cmp != 0 { - return cmp - } - return preReleaseCompare(v, versionB) -} - -// Equal tests if v is equal to versionB. -func (v Version) Equal(versionB Version) bool { - return v.Compare(versionB) == 0 -} - -// LessThan tests if v is less than versionB. -func (v Version) LessThan(versionB Version) bool { - return v.Compare(versionB) < 0 -} - -// Slice converts the comparable parts of the semver into a slice of integers. -func (v Version) Slice() []int64 { - return []int64{v.Major, v.Minor, v.Patch} -} - -func (p PreRelease) Slice() []string { - preRelease := string(p) - return strings.Split(preRelease, ".") -} - -func preReleaseCompare(versionA Version, versionB Version) int { - a := versionA.PreRelease - b := versionB.PreRelease - - /* Handle the case where if two versions are otherwise equal it is the - * one without a PreRelease that is greater */ - if len(a) == 0 && (len(b) > 0) { - return 1 - } else if len(b) == 0 && (len(a) > 0) { - return -1 - } - - // If there is a prerelease, check and compare each part. - return recursivePreReleaseCompare(a.Slice(), b.Slice()) -} - -func recursiveCompare(versionA []int64, versionB []int64) int { - if len(versionA) == 0 { - return 0 - } - - a := versionA[0] - b := versionB[0] - - if a > b { - return 1 - } else if a < b { - return -1 - } - - return recursiveCompare(versionA[1:], versionB[1:]) -} - -func recursivePreReleaseCompare(versionA []string, versionB []string) int { - // A larger set of pre-release fields has a higher precedence than a smaller set, - // if all of the preceding identifiers are equal. - if len(versionA) == 0 { - if len(versionB) > 0 { - return -1 - } - return 0 - } else if len(versionB) == 0 { - // We're longer than versionB so return 1. - return 1 - } - - a := versionA[0] - b := versionB[0] - - aInt := false - bInt := false - - aI, err := strconv.Atoi(versionA[0]) - if err == nil { - aInt = true - } - - bI, err := strconv.Atoi(versionB[0]) - if err == nil { - bInt = true - } - - // Numeric identifiers always have lower precedence than non-numeric identifiers. - if aInt && !bInt { - return -1 - } else if !aInt && bInt { - return 1 - } - - // Handle Integer Comparison - if aInt && bInt { - if aI > bI { - return 1 - } else if aI < bI { - return -1 - } - } - - // Handle String Comparison - if a > b { - return 1 - } else if a < b { - return -1 - } - - return recursivePreReleaseCompare(versionA[1:], versionB[1:]) -} - -// BumpMajor increments the Major field by 1 and resets all other fields to their default values -func (v *Version) BumpMajor() { - v.Major += 1 - v.Minor = 0 - v.Patch = 0 - v.PreRelease = PreRelease("") - v.Metadata = "" -} - -// BumpMinor increments the Minor field by 1 and resets all other fields to their default values -func (v *Version) BumpMinor() { - v.Minor += 1 - v.Patch = 0 - v.PreRelease = PreRelease("") - v.Metadata = "" -} - -// BumpPatch increments the Patch field by 1 and resets all other fields to their default values -func (v *Version) BumpPatch() { - v.Patch += 1 - v.PreRelease = PreRelease("") - v.Metadata = "" -} - -// validateIdentifier makes sure the provided identifier satisfies semver spec -func validateIdentifier(id string) error { - if id != "" && !reIdentifier.MatchString(id) { - return fmt.Errorf("%s is not a valid semver identifier", id) - } - return nil -} - -// reIdentifier is a regular expression used to check that pre-release and metadata -// identifiers satisfy the spec requirements -var reIdentifier = regexp.MustCompile(`^[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*$`) diff --git a/vendor/github.com/coreos/go-semver/semver/sort.go b/vendor/github.com/coreos/go-semver/semver/sort.go deleted file mode 100644 index e256b41a..00000000 --- a/vendor/github.com/coreos/go-semver/semver/sort.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2013-2015 CoreOS, 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 semver - -import ( - "sort" -) - -type Versions []*Version - -func (s Versions) Len() int { - return len(s) -} - -func (s Versions) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -func (s Versions) Less(i, j int) bool { - return s[i].LessThan(*s[j]) -} - -// Sort sorts the given slice of Version -func Sort(versions []*Version) { - sort.Sort(Versions(versions)) -} diff --git a/vendor/github.com/coreos/go-systemd/v22/LICENSE b/vendor/github.com/coreos/go-systemd/v22/LICENSE deleted file mode 100644 index 37ec93a1..00000000 --- a/vendor/github.com/coreos/go-systemd/v22/LICENSE +++ /dev/null @@ -1,191 +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: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -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 -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/coreos/go-systemd/v22/NOTICE b/vendor/github.com/coreos/go-systemd/v22/NOTICE deleted file mode 100644 index 23a0ada2..00000000 --- a/vendor/github.com/coreos/go-systemd/v22/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -CoreOS Project -Copyright 2018 CoreOS, Inc - -This product includes software developed at CoreOS, Inc. -(http://www.coreos.com/). diff --git a/vendor/github.com/coreos/go-systemd/v22/journal/journal.go b/vendor/github.com/coreos/go-systemd/v22/journal/journal.go deleted file mode 100644 index ac24c776..00000000 --- a/vendor/github.com/coreos/go-systemd/v22/journal/journal.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2015 CoreOS, 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 journal provides write bindings to the local systemd journal. -// It is implemented in pure Go and connects to the journal directly over its -// unix socket. -// -// To read from the journal, see the "sdjournal" package, which wraps the -// sd-journal a C API. -// -// http://www.freedesktop.org/software/systemd/man/systemd-journald.service.html -package journal - -import ( - "fmt" -) - -// Priority of a journal message -type Priority int - -const ( - PriEmerg Priority = iota - PriAlert - PriCrit - PriErr - PriWarning - PriNotice - PriInfo - PriDebug -) - -// Print prints a message to the local systemd journal using Send(). -func Print(priority Priority, format string, a ...interface{}) error { - return Send(fmt.Sprintf(format, a...), priority, nil) -} diff --git a/vendor/github.com/coreos/go-systemd/v22/journal/journal_unix.go b/vendor/github.com/coreos/go-systemd/v22/journal/journal_unix.go deleted file mode 100644 index 439ad287..00000000 --- a/vendor/github.com/coreos/go-systemd/v22/journal/journal_unix.go +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2015 CoreOS, 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. - -//go:build !windows -// +build !windows - -// Package journal provides write bindings to the local systemd journal. -// It is implemented in pure Go and connects to the journal directly over its -// unix socket. -// -// To read from the journal, see the "sdjournal" package, which wraps the -// sd-journal a C API. -// -// http://www.freedesktop.org/software/systemd/man/systemd-journald.service.html -package journal - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "io/ioutil" - "net" - "os" - "strconv" - "strings" - "sync" - "sync/atomic" - "syscall" - "unsafe" -) - -var ( - // This can be overridden at build-time: - // https://github.com/golang/go/wiki/GcToolchainTricks#including-build-information-in-the-executable - journalSocket = "/run/systemd/journal/socket" - - // unixConnPtr atomically holds the local unconnected Unix-domain socket. - // Concrete safe pointer type: *net.UnixConn - unixConnPtr unsafe.Pointer - // onceConn ensures that unixConnPtr is initialized exactly once. - onceConn sync.Once -) - -// Enabled checks whether the local systemd journal is available for logging. -func Enabled() bool { - if c := getOrInitConn(); c == nil { - return false - } - - conn, err := net.Dial("unixgram", journalSocket) - if err != nil { - return false - } - defer conn.Close() - - return true -} - -// Send a message to the local systemd journal. vars is a map of journald -// fields to values. Fields must be composed of uppercase letters, numbers, -// and underscores, but must not start with an underscore. Within these -// restrictions, any arbitrary field name may be used. Some names have special -// significance: see the journalctl documentation -// (http://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html) -// for more details. vars may be nil. -func Send(message string, priority Priority, vars map[string]string) error { - conn := getOrInitConn() - if conn == nil { - return errors.New("could not initialize socket to journald") - } - - socketAddr := &net.UnixAddr{ - Name: journalSocket, - Net: "unixgram", - } - - data := new(bytes.Buffer) - appendVariable(data, "PRIORITY", strconv.Itoa(int(priority))) - appendVariable(data, "MESSAGE", message) - for k, v := range vars { - appendVariable(data, k, v) - } - - _, _, err := conn.WriteMsgUnix(data.Bytes(), nil, socketAddr) - if err == nil { - return nil - } - if !isSocketSpaceError(err) { - return err - } - - // Large log entry, send it via tempfile and ancillary-fd. - file, err := tempFd() - if err != nil { - return err - } - defer file.Close() - _, err = io.Copy(file, data) - if err != nil { - return err - } - rights := syscall.UnixRights(int(file.Fd())) - _, _, err = conn.WriteMsgUnix([]byte{}, rights, socketAddr) - if err != nil { - return err - } - - return nil -} - -// getOrInitConn attempts to get the global `unixConnPtr` socket, initializing if necessary -func getOrInitConn() *net.UnixConn { - conn := (*net.UnixConn)(atomic.LoadPointer(&unixConnPtr)) - if conn != nil { - return conn - } - onceConn.Do(initConn) - return (*net.UnixConn)(atomic.LoadPointer(&unixConnPtr)) -} - -func appendVariable(w io.Writer, name, value string) { - if err := validVarName(name); err != nil { - fmt.Fprintf(os.Stderr, "variable name %s contains invalid character, ignoring\n", name) - } - if strings.ContainsRune(value, '\n') { - /* When the value contains a newline, we write: - * - the variable name, followed by a newline - * - the size (in 64bit little endian format) - * - the data, followed by a newline - */ - fmt.Fprintln(w, name) - binary.Write(w, binary.LittleEndian, uint64(len(value))) - fmt.Fprintln(w, value) - } else { - /* just write the variable and value all on one line */ - fmt.Fprintf(w, "%s=%s\n", name, value) - } -} - -// validVarName validates a variable name to make sure journald will accept it. -// The variable name must be in uppercase and consist only of characters, -// numbers and underscores, and may not begin with an underscore: -// https://www.freedesktop.org/software/systemd/man/sd_journal_print.html -func validVarName(name string) error { - if name == "" { - return errors.New("Empty variable name") - } else if name[0] == '_' { - return errors.New("Variable name begins with an underscore") - } - - for _, c := range name { - if !(('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '_') { - return errors.New("Variable name contains invalid characters") - } - } - return nil -} - -// isSocketSpaceError checks whether the error is signaling -// an "overlarge message" condition. -func isSocketSpaceError(err error) bool { - opErr, ok := err.(*net.OpError) - if !ok || opErr == nil { - return false - } - - sysErr, ok := opErr.Err.(*os.SyscallError) - if !ok || sysErr == nil { - return false - } - - return sysErr.Err == syscall.EMSGSIZE || sysErr.Err == syscall.ENOBUFS -} - -// tempFd creates a temporary, unlinked file under `/dev/shm`. -func tempFd() (*os.File, error) { - file, err := ioutil.TempFile("/dev/shm/", "journal.XXXXX") - if err != nil { - return nil, err - } - err = syscall.Unlink(file.Name()) - if err != nil { - return nil, err - } - return file, nil -} - -// initConn initializes the global `unixConnPtr` socket. -// It is automatically called when needed. -func initConn() { - autobind, err := net.ResolveUnixAddr("unixgram", "") - if err != nil { - return - } - - sock, err := net.ListenUnixgram("unixgram", autobind) - if err != nil { - return - } - - atomic.StorePointer(&unixConnPtr, unsafe.Pointer(sock)) -} diff --git a/vendor/github.com/coreos/go-systemd/v22/journal/journal_windows.go b/vendor/github.com/coreos/go-systemd/v22/journal/journal_windows.go deleted file mode 100644 index 677aca68..00000000 --- a/vendor/github.com/coreos/go-systemd/v22/journal/journal_windows.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2015 CoreOS, 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 journal provides write bindings to the local systemd journal. -// It is implemented in pure Go and connects to the journal directly over its -// unix socket. -// -// To read from the journal, see the "sdjournal" package, which wraps the -// sd-journal a C API. -// -// http://www.freedesktop.org/software/systemd/man/systemd-journald.service.html -package journal - -import ( - "errors" -) - -func Enabled() bool { - return false -} - -func Send(message string, priority Priority, vars map[string]string) error { - return errors.New("could not initialize socket to journald") -} diff --git a/vendor/github.com/cpuguy83/go-md2man/v2/LICENSE.md b/vendor/github.com/cpuguy83/go-md2man/v2/LICENSE.md deleted file mode 100644 index 1cade6ce..00000000 --- a/vendor/github.com/cpuguy83/go-md2man/v2/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Brian Goff - -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/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go b/vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go deleted file mode 100644 index b4800567..00000000 --- a/vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go +++ /dev/null @@ -1,14 +0,0 @@ -package md2man - -import ( - "github.com/russross/blackfriday/v2" -) - -// Render converts a markdown document into a roff formatted document. -func Render(doc []byte) []byte { - renderer := NewRoffRenderer() - - return blackfriday.Run(doc, - []blackfriday.Option{blackfriday.WithRenderer(renderer), - blackfriday.WithExtensions(renderer.GetExtensions())}...) -} diff --git a/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go b/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go deleted file mode 100644 index be2b3436..00000000 --- a/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go +++ /dev/null @@ -1,336 +0,0 @@ -package md2man - -import ( - "fmt" - "io" - "os" - "strings" - - "github.com/russross/blackfriday/v2" -) - -// roffRenderer implements the blackfriday.Renderer interface for creating -// roff format (manpages) from markdown text -type roffRenderer struct { - extensions blackfriday.Extensions - listCounters []int - firstHeader bool - firstDD bool - listDepth int -} - -const ( - titleHeader = ".TH " - topLevelHeader = "\n\n.SH " - secondLevelHdr = "\n.SH " - otherHeader = "\n.SS " - crTag = "\n" - emphTag = "\\fI" - emphCloseTag = "\\fP" - strongTag = "\\fB" - strongCloseTag = "\\fP" - breakTag = "\n.br\n" - paraTag = "\n.PP\n" - hruleTag = "\n.ti 0\n\\l'\\n(.lu'\n" - linkTag = "\n\\[la]" - linkCloseTag = "\\[ra]" - codespanTag = "\\fB\\fC" - codespanCloseTag = "\\fR" - codeTag = "\n.PP\n.RS\n\n.nf\n" - codeCloseTag = "\n.fi\n.RE\n" - quoteTag = "\n.PP\n.RS\n" - quoteCloseTag = "\n.RE\n" - listTag = "\n.RS\n" - listCloseTag = "\n.RE\n" - dtTag = "\n.TP\n" - dd2Tag = "\n" - tableStart = "\n.TS\nallbox;\n" - tableEnd = ".TE\n" - tableCellStart = "T{\n" - tableCellEnd = "\nT}\n" -) - -// NewRoffRenderer creates a new blackfriday Renderer for generating roff documents -// from markdown -func NewRoffRenderer() *roffRenderer { // nolint: golint - var extensions blackfriday.Extensions - - extensions |= blackfriday.NoIntraEmphasis - extensions |= blackfriday.Tables - extensions |= blackfriday.FencedCode - extensions |= blackfriday.SpaceHeadings - extensions |= blackfriday.Footnotes - extensions |= blackfriday.Titleblock - extensions |= blackfriday.DefinitionLists - return &roffRenderer{ - extensions: extensions, - } -} - -// GetExtensions returns the list of extensions used by this renderer implementation -func (r *roffRenderer) GetExtensions() blackfriday.Extensions { - return r.extensions -} - -// RenderHeader handles outputting the header at document start -func (r *roffRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) { - // disable hyphenation - out(w, ".nh\n") -} - -// RenderFooter handles outputting the footer at the document end; the roff -// renderer has no footer information -func (r *roffRenderer) RenderFooter(w io.Writer, ast *blackfriday.Node) { -} - -// RenderNode is called for each node in a markdown document; based on the node -// type the equivalent roff output is sent to the writer -func (r *roffRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus { - - var walkAction = blackfriday.GoToNext - - switch node.Type { - case blackfriday.Text: - escapeSpecialChars(w, node.Literal) - case blackfriday.Softbreak: - out(w, crTag) - case blackfriday.Hardbreak: - out(w, breakTag) - case blackfriday.Emph: - if entering { - out(w, emphTag) - } else { - out(w, emphCloseTag) - } - case blackfriday.Strong: - if entering { - out(w, strongTag) - } else { - out(w, strongCloseTag) - } - case blackfriday.Link: - if !entering { - out(w, linkTag+string(node.LinkData.Destination)+linkCloseTag) - } - case blackfriday.Image: - // ignore images - walkAction = blackfriday.SkipChildren - case blackfriday.Code: - out(w, codespanTag) - escapeSpecialChars(w, node.Literal) - out(w, codespanCloseTag) - case blackfriday.Document: - break - case blackfriday.Paragraph: - // roff .PP markers break lists - if r.listDepth > 0 { - return blackfriday.GoToNext - } - if entering { - out(w, paraTag) - } else { - out(w, crTag) - } - case blackfriday.BlockQuote: - if entering { - out(w, quoteTag) - } else { - out(w, quoteCloseTag) - } - case blackfriday.Heading: - r.handleHeading(w, node, entering) - case blackfriday.HorizontalRule: - out(w, hruleTag) - case blackfriday.List: - r.handleList(w, node, entering) - case blackfriday.Item: - r.handleItem(w, node, entering) - case blackfriday.CodeBlock: - out(w, codeTag) - escapeSpecialChars(w, node.Literal) - out(w, codeCloseTag) - case blackfriday.Table: - r.handleTable(w, node, entering) - case blackfriday.TableHead: - case blackfriday.TableBody: - case blackfriday.TableRow: - // no action as cell entries do all the nroff formatting - return blackfriday.GoToNext - case blackfriday.TableCell: - r.handleTableCell(w, node, entering) - case blackfriday.HTMLSpan: - // ignore other HTML tags - default: - fmt.Fprintln(os.Stderr, "WARNING: go-md2man does not handle node type "+node.Type.String()) - } - return walkAction -} - -func (r *roffRenderer) handleHeading(w io.Writer, node *blackfriday.Node, entering bool) { - if entering { - switch node.Level { - case 1: - if !r.firstHeader { - out(w, titleHeader) - r.firstHeader = true - break - } - out(w, topLevelHeader) - case 2: - out(w, secondLevelHdr) - default: - out(w, otherHeader) - } - } -} - -func (r *roffRenderer) handleList(w io.Writer, node *blackfriday.Node, entering bool) { - openTag := listTag - closeTag := listCloseTag - if node.ListFlags&blackfriday.ListTypeDefinition != 0 { - // tags for definition lists handled within Item node - openTag = "" - closeTag = "" - } - if entering { - r.listDepth++ - if node.ListFlags&blackfriday.ListTypeOrdered != 0 { - r.listCounters = append(r.listCounters, 1) - } - out(w, openTag) - } else { - if node.ListFlags&blackfriday.ListTypeOrdered != 0 { - r.listCounters = r.listCounters[:len(r.listCounters)-1] - } - out(w, closeTag) - r.listDepth-- - } -} - -func (r *roffRenderer) handleItem(w io.Writer, node *blackfriday.Node, entering bool) { - if entering { - if node.ListFlags&blackfriday.ListTypeOrdered != 0 { - out(w, fmt.Sprintf(".IP \"%3d.\" 5\n", r.listCounters[len(r.listCounters)-1])) - r.listCounters[len(r.listCounters)-1]++ - } else if node.ListFlags&blackfriday.ListTypeTerm != 0 { - // DT (definition term): line just before DD (see below). - out(w, dtTag) - r.firstDD = true - } else if node.ListFlags&blackfriday.ListTypeDefinition != 0 { - // DD (definition description): line that starts with ": ". - // - // We have to distinguish between the first DD and the - // subsequent ones, as there should be no vertical - // whitespace between the DT and the first DD. - if r.firstDD { - r.firstDD = false - } else { - out(w, dd2Tag) - } - } else { - out(w, ".IP \\(bu 2\n") - } - } else { - out(w, "\n") - } -} - -func (r *roffRenderer) handleTable(w io.Writer, node *blackfriday.Node, entering bool) { - if entering { - out(w, tableStart) - // call walker to count cells (and rows?) so format section can be produced - columns := countColumns(node) - out(w, strings.Repeat("l ", columns)+"\n") - out(w, strings.Repeat("l ", columns)+".\n") - } else { - out(w, tableEnd) - } -} - -func (r *roffRenderer) handleTableCell(w io.Writer, node *blackfriday.Node, entering bool) { - if entering { - var start string - if node.Prev != nil && node.Prev.Type == blackfriday.TableCell { - start = "\t" - } - if node.IsHeader { - start += codespanTag - } else if nodeLiteralSize(node) > 30 { - start += tableCellStart - } - out(w, start) - } else { - var end string - if node.IsHeader { - end = codespanCloseTag - } else if nodeLiteralSize(node) > 30 { - end = tableCellEnd - } - if node.Next == nil && end != tableCellEnd { - // Last cell: need to carriage return if we are at the end of the - // header row and content isn't wrapped in a "tablecell" - end += crTag - } - out(w, end) - } -} - -func nodeLiteralSize(node *blackfriday.Node) int { - total := 0 - for n := node.FirstChild; n != nil; n = n.FirstChild { - total += len(n.Literal) - } - return total -} - -// because roff format requires knowing the column count before outputting any table -// data we need to walk a table tree and count the columns -func countColumns(node *blackfriday.Node) int { - var columns int - - node.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus { - switch node.Type { - case blackfriday.TableRow: - if !entering { - return blackfriday.Terminate - } - case blackfriday.TableCell: - if entering { - columns++ - } - default: - } - return blackfriday.GoToNext - }) - return columns -} - -func out(w io.Writer, output string) { - io.WriteString(w, output) // nolint: errcheck -} - -func escapeSpecialChars(w io.Writer, text []byte) { - for i := 0; i < len(text); i++ { - // escape initial apostrophe or period - if len(text) >= 1 && (text[0] == '\'' || text[0] == '.') { - out(w, "\\&") - } - - // directly copy normal characters - org := i - - for i < len(text) && text[i] != '\\' { - i++ - } - if i > org { - w.Write(text[org:i]) // nolint: errcheck - } - - // escape a character - if i >= len(text) { - break - } - - w.Write([]byte{'\\', text[i]}) // nolint: errcheck - } -} diff --git a/vendor/github.com/cyberark/conjur-api-go/LICENSE b/vendor/github.com/cyberark/conjur-api-go/LICENSE deleted file mode 100644 index f8e0d1b2..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/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 (c) 2020 CyberArk Software Ltd. 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. - 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/cyberark/conjur-api-go/NOTICES.txt b/vendor/github.com/cyberark/conjur-api-go/NOTICES.txt deleted file mode 100644 index f20c8328..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/NOTICES.txt +++ /dev/null @@ -1,245 +0,0 @@ - -=============== TABLE OF CONTENTS ============================= - - -The following is a listing of the Conjur Go API open source components detailed -in this document. This list is provided for your convenience; please read -further if you wish to review the copyright notice(s) and the full text -of the license associated with each component. - -SECTION 1: Apache License 2.0 - ->>> gopkg.in/yaml.v2-v2.2.4 - https://github.com/go-yaml/yaml/blob/v2.2.4/LICENSE - - -SECTION 2: MIT License - ->>> github.com/bgentry/go-netrc-v0.0.0-20140422174119-9fd32a8b3d3d - https://github.com/bgentry/go-netrc/blob/9fd32a8b3d3d3f9d43c341bfe098430e07609480/LICENSE - ->>> github.com/sirupsen/logrus-v1.0.5 - https://github.com/sirupsen/logrus/blob/v1.0.5/LICENSE - ->>> gopkg.in/yaml.v2-v2.2.4 - https://github.com/go-yaml/yaml/blob/v2.2.4/LICENSE.libyaml - - -APPENDIX: Standard License Files and Templates - ->>> Apache License 2.0 - ->>> MIT License - - ---------------- SECTION 1: Apache License 2.0 ---------- - -Apache License 2.0 is applicable to the following component(s). - ->>> gopkg.in/yaml.v2-v2.2.4 - - 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. - - ---------------- SECTION 2: MIT License ---------- - -MIT License is applicable to the following component(s). - - ->>> github.com/bgentry/go-netrc-v0.0.0-20140422174119-9fd32a8b3d3d - -Original version Copyright © 2010 Fazlul Shahriar . Newer -portions Copyright © 2014 Blake Gentry . - -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. - - ->>> github.com/sirupsen/logrus-v1.0.5 - -Copyright (c) 2014 Simon Eskildsen - -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. - - ->>> gopkg.in/yaml.v2-v2.2.4 - -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. - - -=============== APPENDIX: License Files and Templates ============== - - - ---------------- APPENDIX 1: Apache License 2.0 (Template) ----------- - -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: - - You must give any other recipients of the Work or Derivative Works a copy of this License; and - You must cause any modified files to carry prominent notices stating that You changed the files; and - 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 - 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. - - ---------------- APPENDIX 2: MIT License (Template) ----------- - -Copyright - -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/github.com/cyberark/conjur-api-go/conjurapi/authn.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn.go deleted file mode 100644 index 73ca6e98..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn.go +++ /dev/null @@ -1,113 +0,0 @@ -package conjurapi - -import ( - "encoding/base64" - "fmt" - "io" - "net/http" - - "github.com/cyberark/conjur-api-go/conjurapi/authn" - "github.com/cyberark/conjur-api-go/conjurapi/response" -) - -func (c *Client) RefreshToken() (err error) { - var token authn.AuthnToken - - if c.NeedsTokenRefresh() { - var tokenBytes []byte - tokenBytes, err = c.authenticator.RefreshToken() - if err == nil { - token, err = authn.NewToken(tokenBytes) - if err != nil { - return - } - token.FromJSON(tokenBytes) - c.authToken = token - } - } - - return -} - -func (c *Client) NeedsTokenRefresh() bool { - return c.authToken == nil || - c.authToken.ShouldRefresh() || - c.authenticator.NeedsTokenRefresh() -} - -func (c *Client) createAuthRequest(req *http.Request) error { - if err := c.RefreshToken(); err != nil { - return err - } - - req.Header.Set( - "Authorization", - fmt.Sprintf("Token token=\"%s\"", base64.StdEncoding.EncodeToString(c.authToken.Raw())), - ) - - return nil -} - -// Authenticate obtains a new access token. -func (c *Client) Authenticate(loginPair authn.LoginPair) ([]byte, error) { - resp, err := c.authenticate(loginPair) - if err != nil { - return nil, err - } - - return response.DataResponse(resp) -} - -// AuthenticateReader obtains a new access token and returns it as a data stream. -func (c *Client) AuthenticateReader(loginPair authn.LoginPair) (io.ReadCloser, error) { - resp, err := c.authenticate(loginPair) - if err != nil { - return nil, err - } - - return response.SecretDataResponse(resp) -} - -func (c *Client) authenticate(loginPair authn.LoginPair) (*http.Response, error) { - req, err := c.router.AuthenticateRequest(loginPair) - if err != nil { - return nil, err - } - - return c.httpClient.Do(req) -} - -// RotateAPIKey replaces the API key of a role on the server with a new -// random secret. -// -// The authenticated user must have update privilege on the role. -func (c *Client) RotateAPIKey(roleID string) ([]byte, error) { - resp, err := c.rotateAPIKey(roleID) - if err != nil { - return nil, err - } - - return response.DataResponse(resp) -} - -// RotateAPIKeyReader replaces the API key of a role on the server with a new -// random secret and returns it as a data stream. -// -// The authenticated user must have update privilege on the role. -func (c *Client) RotateAPIKeyReader(roleID string) (io.ReadCloser, error) { - resp, err := c.rotateAPIKey(roleID) - if err != nil { - return nil, err - } - - return response.SecretDataResponse(resp) -} - -func (c *Client) rotateAPIKey(roleID string) (*http.Response, error) { - req, err := c.router.RotateAPIKeyRequest(roleID) - if err != nil { - return nil, err - } - - return c.SubmitRequest(req) -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/api_key_authenticator.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/api_key_authenticator.go deleted file mode 100644 index 43e18e82..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/api_key_authenticator.go +++ /dev/null @@ -1,19 +0,0 @@ -package authn - -type APIKeyAuthenticator struct { - Authenticate func(loginPair LoginPair) ([]byte, error) - LoginPair -} - -type LoginPair struct { - Login string - APIKey string -} - -func (a *APIKeyAuthenticator) RefreshToken() ([]byte, error) { - return a.Authenticate(a.LoginPair) -} - -func (a *APIKeyAuthenticator) NeedsTokenRefresh() bool { - return false -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/auth_token.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/auth_token.go deleted file mode 100644 index f4dbcd04..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/auth_token.go +++ /dev/null @@ -1,170 +0,0 @@ -package authn - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "time" -) - -const ( - TimeFormatToken4 = "2006-01-02 15:04:05 MST" -) - -type AuthnToken interface { - // Parse from JSON. Required before further usage. - FromJSON(data []byte) error - // Raw token as obtained from the authentication service. - Raw() []byte - // Whether the token will expire soon. - ShouldRefresh() bool -} - -type AuthnToken4 struct { - bytes []byte - Data string `json:"data"` - Signature string `json:"signature"` - Key string `json:"key"` - Timestamp time.Time -} - -// Sample token -// {"protected":"eyJhbGciOiJjb25qdXIub3JnL3Nsb3NpbG8vdjIiLCJraWQiOiI5M2VjNTEwODRmZTM3Zjc3M2I1ODhlNTYyYWVjZGMxMSJ9","payload":"eyJzdWIiOiJhZG1pbiIsImlhdCI6MTUxMDc1MzI1OX0=","signature":"raCufKOf7sKzciZInQTphu1mBbLhAdIJM72ChLB4m5wKWxFnNz_7LawQ9iYEI_we1-tdZtTXoopn_T1qoTplR9_Bo3KkpI5Hj3DB7SmBpR3CSRTnnEwkJ0_aJ8bql5Cbst4i4rSftyEmUqX-FDOqJdAztdi9BUJyLfbeKTW9OGg-QJQzPX1ucB7IpvTFCEjMoO8KUxZpbHj-KpwqAMZRooG4ULBkxp5nSfs-LN27JupU58oRgIfaWASaDmA98O2x6o88MFpxK_M0FeFGuDKewNGrRc8lCOtTQ9cULA080M5CSnruCqu1Qd52r72KIOAfyzNIiBCLTkblz2fZyEkdSKQmZ8J3AakxQE2jyHmMT-eXjfsEIzEt-IRPJIirI3Qm"} -// https://www.conjur.org/reference/cryptography.html -type AuthnToken5 struct { - bytes []byte - Protected string `json:"protected"` - Payload string `json:"payload"` - Signature string `json:"signature"` - iat time.Time - exp *time.Time -} - -func hasField(fields map[string]string, name string) (hasField bool) { - _, hasField = fields[name] - return -} - -func NewToken(data []byte) (token AuthnToken, err error) { - fields := make(map[string]string) - if err = json.Unmarshal(data, &fields); err != nil { - err = fmt.Errorf("Unable to unmarshal token : %s", err) - return - } - - if hasField(fields, "protected") && hasField(fields, "payload") && hasField(fields, "signature") { - t := &AuthnToken5{} - token = t - } else if hasField(fields, "data") && hasField(fields, "timestamp") && hasField(fields, "signature") && hasField(fields, "key") { - t := &AuthnToken4{} - token = t - } else { - err = fmt.Errorf("Unrecognized token format") - return - } - - err = token.FromJSON(data) - - return -} - -func (t *AuthnToken5) FromJSON(data []byte) (err error) { - t.bytes = data - - err = json.Unmarshal(data, &t) - if err != nil { - err = fmt.Errorf("Unable to unmarshal v5 access token %s", err) - return - } - - // Example: {"sub":"admin","iat":1510753259} - payloadFields := make(map[string]interface{}) - var payloadJSON []byte - payloadJSON, err = base64.StdEncoding.DecodeString(t.Payload) - if err != nil { - err = fmt.Errorf("v5 access token field 'payload' is not valid base64") - return - } - err = json.Unmarshal(payloadJSON, &payloadFields) - if err != nil { - err = fmt.Errorf("Unable to unmarshal v5 access token field 'payload' : %s", err) - return - } - - iat_v, ok := payloadFields["iat"] - if !ok { - err = fmt.Errorf("v5 access token field 'payload' does not contain 'iat'") - return - } - iat_f := iat_v.(float64) - // In the absence of exp, the token expires at iat+8 minutes - t.iat = time.Unix(int64(iat_f), 0) - - exp_v, ok := payloadFields["exp"] - if ok { - exp_f := exp_v.(float64) - exp := time.Unix(int64(exp_f), 0) - t.exp = &exp - if t.iat.After(*t.exp) { - err = fmt.Errorf("v5 access token expired before it was issued") - return - } - } - - return -} - -func (t *AuthnToken4) FromJSON(data []byte) (err error) { - err = json.Unmarshal(data, &t) - if err != nil { - err = fmt.Errorf("Unable to unmarshal v4 access token %s", err) - } - - return -} - -func (t *AuthnToken4) UnmarshalJSON(data []byte) (err error) { - type Alias AuthnToken4 - x := &struct { - Data string `json:"data"` - Timestamp string `json:"timestamp"` - Signature string `json:"signature"` - Key string `json:"key"` - *Alias - }{ - Alias: (*Alias)(t), - } - - if err = json.Unmarshal(data, &x); err != nil { - return - } - - t.Timestamp, err = time.Parse(TimeFormatToken4, x.Timestamp) - t.bytes = data - - return -} - -func (t *AuthnToken5) Raw() []byte { - return t.bytes -} - -func (t *AuthnToken5) ShouldRefresh() bool { - if t.exp != nil { - // Expire when the token is 85% expired - lifespan := t.exp.Sub(t.iat) - duration := float32(lifespan) * 0.85 - return time.Now().After(t.iat.Add(time.Duration(duration))) - } else { - // Token expires 8 minutes after issue, by default - return time.Now().After(t.iat.Add(5 * time.Minute)) - } -} - -func (t *AuthnToken4) Raw() []byte { - return t.bytes -} - -func (t *AuthnToken4) ShouldRefresh() bool { - return time.Now().After(t.Timestamp.Add(5 * time.Minute)) -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/token_authenticator.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/token_authenticator.go deleted file mode 100644 index d6dd8701..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/token_authenticator.go +++ /dev/null @@ -1,13 +0,0 @@ -package authn - -type TokenAuthenticator struct { - Token string `env:"CONJUR_AUTHN_TOKEN"` -} - -func (a *TokenAuthenticator) RefreshToken() ([]byte, error) { - return []byte(a.Token), nil -} - -func (a *TokenAuthenticator) NeedsTokenRefresh() bool { - return false -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/token_file_authenticator.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/token_file_authenticator.go deleted file mode 100644 index dbf5b8e6..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/token_file_authenticator.go +++ /dev/null @@ -1,34 +0,0 @@ -package authn - -import ( - "os" - "time" -) - -type TokenFileAuthenticator struct { - TokenFile string `env:"CONJUR_AUTHN_TOKEN_FILE"` - mTime time.Time - MaxWaitTime time.Duration -} - -func (a *TokenFileAuthenticator) RefreshToken() ([]byte, error) { - maxWaitTime := a.MaxWaitTime - var timeout <-chan time.Time - if maxWaitTime == -1 { - timeout = nil - } else { - timeout = time.After(a.MaxWaitTime) - } - - bytes, err := waitForTextFile(a.TokenFile, timeout) - if err == nil { - fi, _ := os.Stat(a.TokenFile) - a.mTime = fi.ModTime() - } - return bytes, err -} - -func (a *TokenFileAuthenticator) NeedsTokenRefresh() bool { - fi, _ := os.Stat(a.TokenFile) - return a.mTime != fi.ModTime() -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/wait_for_file.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/wait_for_file.go deleted file mode 100644 index 906c59a4..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/authn/wait_for_file.go +++ /dev/null @@ -1,33 +0,0 @@ -package authn - -import ( - "fmt" - "io/ioutil" - "os" - "time" -) - -func waitForTextFile(fileName string, timeout <-chan time.Time) ([]byte, error) { - var ( - fileBytes []byte - err error - ) - -waiting_loop: - for { - select { - case <-timeout: - err = fmt.Errorf("Operation waitForTextFile timed out.") - break waiting_loop - default: - if _, err := os.Stat(fileName); os.IsNotExist(err) { - time.Sleep(100 * time.Millisecond) - } else { - fileBytes, err = ioutil.ReadFile(fileName) - break waiting_loop - } - } - } - - return fileBytes, err -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/client.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/client.go deleted file mode 100644 index f4ebd16c..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/client.go +++ /dev/null @@ -1,228 +0,0 @@ -package conjurapi - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - "strings" - "time" - - "github.com/bgentry/go-netrc/netrc" - "github.com/cyberark/conjur-api-go/conjurapi/authn" - "github.com/cyberark/conjur-api-go/conjurapi/logging" -) - -type Authenticator interface { - RefreshToken() ([]byte, error) - NeedsTokenRefresh() bool -} - -type Client struct { - config Config - authToken authn.AuthnToken - httpClient *http.Client - authenticator Authenticator - router Router -} - -type Router interface { - AddSecretRequest(variableID, secretValue string) (*http.Request, error) - AuthenticateRequest(loginPair authn.LoginPair) (*http.Request, error) - CheckPermissionRequest(resourceID, privilege string) (*http.Request, error) - LoadPolicyRequest(mode PolicyMode, policyID string, policy io.Reader) (*http.Request, error) - ResourceRequest(resourceID string) (*http.Request, error) - ResourcesRequest(filter *ResourceFilter) (*http.Request, error) - RetrieveBatchSecretsRequest(variableIDs []string, base64Flag bool) (*http.Request, error) - RetrieveSecretRequest(variableID string) (*http.Request, error) - RotateAPIKeyRequest(roleID string) (*http.Request, error) -} - -func NewClientFromKey(config Config, loginPair authn.LoginPair) (*Client, error) { - authenticator := &authn.APIKeyAuthenticator{ - LoginPair: loginPair, - } - client, err := newClientWithAuthenticator( - config, - authenticator, - ) - authenticator.Authenticate = client.Authenticate - return client, err -} - -// ReadResponseBody fully reads a response and closes it. -func ReadResponseBody(response io.ReadCloser) ([]byte, error) { - defer response.Close() - return ioutil.ReadAll(response) -} - -func NewClientFromToken(config Config, token string) (*Client, error) { - return newClientWithAuthenticator( - config, - &authn.TokenAuthenticator{token}, - ) -} - -func NewClientFromTokenFile(config Config, tokenFile string) (*Client, error) { - return newClientWithAuthenticator( - config, - &authn.TokenFileAuthenticator{ - TokenFile: tokenFile, - MaxWaitTime: -1, - }, - ) -} - -func LoginPairFromEnv() (*authn.LoginPair, error) { - return &authn.LoginPair{ - Login: os.Getenv("CONJUR_AUTHN_LOGIN"), - APIKey: os.Getenv("CONJUR_AUTHN_API_KEY"), - }, nil -} - -func LoginPairFromNetRC(config Config) (*authn.LoginPair, error) { - if config.NetRCPath == "" { - config.NetRCPath = os.ExpandEnv("$HOME/.netrc") - } - - rc, err := netrc.ParseFile(config.NetRCPath) - if err != nil { - return nil, err - } - - m := rc.FindMachine(config.ApplianceURL + "/authn") - - if m == nil { - return nil, fmt.Errorf("No credentials found in NetRCPath") - } - - return &authn.LoginPair{Login: m.Login, APIKey: m.Password}, nil -} - -func NewClientFromEnvironment(config Config) (*Client, error) { - err := config.validate() - - if err != nil { - return nil, err - } - - authnTokenFile := os.Getenv("CONJUR_AUTHN_TOKEN_FILE") - if authnTokenFile != "" { - return NewClientFromTokenFile(config, authnTokenFile) - } - - loginPair, err := LoginPairFromEnv() - if err == nil && loginPair.Login != "" && loginPair.APIKey != "" { - return NewClientFromKey(config, *loginPair) - } - - loginPair, err = LoginPairFromNetRC(config) - if err == nil && loginPair.Login != "" && loginPair.APIKey != "" { - return NewClientFromKey(config, *loginPair) - } - - return nil, fmt.Errorf("Environment variables and machine identity files satisfying at least one authentication strategy must be present!") -} - -func (c *Client) GetHttpClient() (*http.Client) { - return c.httpClient -} - -func (c *Client) SetHttpClient(httpClient *http.Client) { - c.httpClient = httpClient -} - -func (c *Client) GetConfig() (Config) { - return c.config -} - -func (c *Client) SubmitRequest(req *http.Request) (resp *http.Response, err error) { - err = c.createAuthRequest(req) - if err != nil { - return - } - - logging.ApiLog.Debugf("req: %+v\n", req) - resp, err = c.httpClient.Do(req) - if err != nil { - return - } - - return -} - -func makeFullId(account, kind, id string) string { - tokens := strings.SplitN(id, ":", 3) - switch len(tokens) { - case 1: - tokens = []string{account, kind, tokens[0]} - case 2: - tokens = []string{account, tokens[0], tokens[1]} - } - return strings.Join(tokens, ":") -} - -func parseID(fullID string) (account, kind, id string, err error) { - tokens := strings.SplitN(fullID, ":", 3) - if len(tokens) != 3 { - err = fmt.Errorf("Id '%s' must be fully qualified", fullID) - return - } - return tokens[0], tokens[1], tokens[2], nil -} - -func newClientWithAuthenticator(config Config, authenticator Authenticator) (*Client, error) { - var ( - err error - ) - - err = config.validate() - - if err != nil { - return nil, err - } - - var httpClient *http.Client - var router Router - - if config.IsHttps() { - cert, err := config.ReadSSLCert() - if err != nil { - return nil, err - } - httpClient, err = newHTTPSClient(cert) - if err != nil { - return nil, err - } - } else { - httpClient = &http.Client{Timeout: time.Second * 10} - } - - if config.V4 { - router = RouterV4{&config} - } else { - router = RouterV5{&config} - } - - return &Client{ - config: config, - authenticator: authenticator, - httpClient: httpClient, - router: router, - }, nil -} - -func newHTTPSClient(cert []byte) (*http.Client, error) { - pool := x509.NewCertPool() - ok := pool.AppendCertsFromPEM(cert) - if !ok { - return nil, fmt.Errorf("Can't append Conjur SSL cert") - } - tr := &http.Transport{ - TLSClientConfig: &tls.Config{RootCAs: pool}, - } - return &http.Client{Transport: tr, Timeout: time.Second * 10}, nil -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/config.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/config.go deleted file mode 100644 index 6050f9f6..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/config.go +++ /dev/null @@ -1,167 +0,0 @@ -package conjurapi - -import ( - "fmt" - "io/ioutil" - "os" - "path" - "runtime" - "strings" - - "github.com/sirupsen/logrus" - "gopkg.in/yaml.v2" - - "github.com/cyberark/conjur-api-go/conjurapi/logging" -) - -type Config struct { - Account string `yaml:"account,omitempty"` - ApplianceURL string `yaml:"appliance_url,omitempty"` - NetRCPath string `yaml:"netrc_path,omitempty"` - SSLCert string `yaml:"-"` - SSLCertPath string `yaml:"cert_file,omitempty"` - V4 bool `yaml:"v4"` -} - -func (c *Config) IsHttps() bool { - return c.SSLCertPath != "" || c.SSLCert != "" -} - -func (c *Config) validate() error { - errors := []string{} - - if c.ApplianceURL == "" { - errors = append(errors, "Must specify an ApplianceURL") - } - - if c.Account == "" { - errors = append(errors, "Must specify an Account") - } - - if len(errors) == 0 { - return nil - } else if logging.ApiLog.Level == logrus.DebugLevel { - errors = append(errors, fmt.Sprintf("config: %+v", c)) - } - return fmt.Errorf("%s", strings.Join(errors, " -- ")) -} - -func (c *Config) ReadSSLCert() ([]byte, error) { - if c.SSLCert != "" { - return []byte(c.SSLCert), nil - } - return ioutil.ReadFile(c.SSLCertPath) -} - -func (c *Config) BaseURL() string { - prefix := "" - if !strings.HasPrefix(c.ApplianceURL, "http") { - if c.IsHttps() { - prefix = "https://" - } else { - prefix = "http://" - } - } - return prefix + c.ApplianceURL -} - -func mergeValue(a, b string) string { - if len(b) != 0 { - return b - } - return a -} - -func (c *Config) merge(o *Config) { - c.ApplianceURL = mergeValue(c.ApplianceURL, o.ApplianceURL) - c.Account = mergeValue(c.Account, o.Account) - c.SSLCert = mergeValue(c.SSLCert, o.SSLCert) - c.SSLCertPath = mergeValue(c.SSLCertPath, o.SSLCertPath) - c.NetRCPath = mergeValue(c.NetRCPath, o.NetRCPath) - c.V4 = c.V4 || o.V4 -} - -func (c *Config) mergeYAML(filename string) error { - buf, err := ioutil.ReadFile(filename) - - if err != nil { - logging.ApiLog.Debugf("Failed reading %s, %v\n", filename, err) - // It is not an error if this file does not exist - return nil - } - - aux := struct { - ConjurVersion string `yaml:"version"` - Config `yaml:",inline"` - }{} - - if err := yaml.Unmarshal(buf, &aux); err != nil { - logging.ApiLog.Errorf("Parsing error %s: %s\n", filename, err) - return err - } - aux.Config.V4 = aux.ConjurVersion == "4" - - logging.ApiLog.Debugf("Config from %s: %+v\n", filename, aux.Config) - c.merge(&aux.Config) - - return nil -} - -func (c *Config) mergeEnv() { - majorVersion4 := os.Getenv("CONJUR_MAJOR_VERSION") == "4" || os.Getenv("CONJUR_VERSION") == "4" - - env := Config{ - ApplianceURL: os.Getenv("CONJUR_APPLIANCE_URL"), - SSLCert: os.Getenv("CONJUR_SSL_CERTIFICATE"), - SSLCertPath: os.Getenv("CONJUR_CERT_FILE"), - Account: os.Getenv("CONJUR_ACCOUNT"), - NetRCPath: os.Getenv("CONJUR_NETRC_PATH"), - V4: majorVersion4, - } - - logging.ApiLog.Debugf("Config from environment: %+v\n", env) - c.merge(&env) -} - -func LoadConfig() (Config, error) { - config := Config{} - - home, err := os.UserHomeDir() - if err != nil { - logging.ApiLog.Warningf("Could not detect homedir.") - } - - // Default to using ~/.netrc, subsequent configuration can - // override it if the home dir is set. - if home != "" { - config = Config{NetRCPath: path.Join(home, ".netrc")} - } - - err = config.mergeYAML(path.Join(getSystemPath(), "conjur.conf")) - if err != nil { - return config, err - } - - conjurrc := os.Getenv("CONJURRC") - if conjurrc == "" && home != "" { - conjurrc = path.Join(home, ".conjurrc") - } - if conjurrc != "" { - config.mergeYAML(conjurrc) - } - - config.mergeEnv() - - logging.ApiLog.Debugf("Final config: %+v\n", config) - return config, nil -} - -func getSystemPath() string { - if runtime.GOOS == "windows" { - //No way to use SHGetKnownFolderPath() - //Hardcoding should be fine for now since CONJURRC is available - return "C:\\windows" - } else { - return "/etc" - } -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/logging/logging.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/logging/logging.go deleted file mode 100644 index c8d90d3e..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/logging/logging.go +++ /dev/null @@ -1,42 +0,0 @@ -package logging - -import ( - "io" - "os" - - "github.com/sirupsen/logrus" -) - -// ApiLog is a separate logrus logger for the API. The destination for -// its messages is controlled by the environment variable -// CONJURAPI_LOG. CONJRAPI_LOG can be "stdout", "stderr", or the path -// to a file. If it's a path, the file's contents will be overwritten -// with new messages. -var ApiLog = logrus.New() - -func init() { - dest, ok := os.LookupEnv("CONJURAPI_LOG") - if !ok { - return - } - - var ( - out io.Writer - err error - ) - switch dest { - case "stdout": - out = os.Stdout - case "stderr": - out = os.Stderr - default: - out, err = os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - logrus.Fatalf("Failed to open %s: %v", dest, err.Error()) - } - logrus.Infof("Logging to %s", dest) - } - - ApiLog.Out = out - ApiLog.Level = logrus.DebugLevel -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/policy.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/policy.go deleted file mode 100644 index 9acc5cbb..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/policy.go +++ /dev/null @@ -1,52 +0,0 @@ -package conjurapi - -import ( - "io" - - "github.com/cyberark/conjur-api-go/conjurapi/response" -) - -// PolicyMode defines the server-sized behavior when loading a policy. -type PolicyMode uint - -const ( - // PolicyModePost appends new data to the policy. - PolicyModePost PolicyMode = 1 - // PolicyModePut completely replaces the policy, implicitly deleting data which is not present in the new policy. - PolicyModePut PolicyMode = 2 - // PolicyModePatch adds policy data and explicitly deletes policy data. - PolicyModePatch PolicyMode = 3 -) - -// CreatedRole contains the full role ID and API key of a role which was created -// by the server when loading a policy. -type CreatedRole struct { - ID string `json:"id"` - APIKey string `json:"api_key"` -} - -// PolicyResponse contains information about the policy update. -type PolicyResponse struct { - // Newly created roles. - CreatedRoles map[string]CreatedRole `json:"created_roles"` - // The version number of the policy. - Version uint32 `json:"version"` -} - -// LoadPolicy submits new policy data or polciy changes to the server. -// -// The required permission depends on the mode. -func (c *Client) LoadPolicy(mode PolicyMode, policyID string, policy io.Reader) (*PolicyResponse, error) { - req, err := c.router.LoadPolicyRequest(mode, policyID, policy) - if err != nil { - return nil, err - } - - resp, err := c.SubmitRequest(req) - if err != nil { - return nil, err - } - - policyResponse := PolicyResponse{} - return &policyResponse, response.JSONResponse(resp, &policyResponse) -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/resource.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/resource.go deleted file mode 100644 index b1f96843..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/resource.go +++ /dev/null @@ -1,85 +0,0 @@ -package conjurapi - -import ( - "encoding/json" - "fmt" - - "github.com/cyberark/conjur-api-go/conjurapi/response" -) - -type ResourceFilter struct { - Kind string - Search string - Limit int - Offset int -} - -// CheckPermission determines whether the authenticated user has a specified privilege -// on a resource. -func (c *Client) CheckPermission(resourceID, privilege string) (bool, error) { - req, err := c.router.CheckPermissionRequest(resourceID, privilege) - if err != nil { - return false, err - } - - resp, err := c.SubmitRequest(req) - if err != nil { - return false, err - } - - if resp.StatusCode >= 200 && resp.StatusCode < 300 { - return true, nil - } else if resp.StatusCode == 404 || resp.StatusCode == 403 { - return false, nil - } else { - return false, fmt.Errorf("Permission check failed with HTTP status %d", resp.StatusCode) - } -} - -// Resource fetches a single user-visible resource by id. -func (c *Client) Resource(resourceID string) (resource map[string]interface{}, err error) { - req, err := c.router.ResourceRequest(resourceID) - if err != nil { - return - } - - resp, err := c.SubmitRequest(req) - if err != nil { - return - } - - data, err := response.DataResponse(resp) - if err != nil { - return - } - - resource = make(map[string]interface{}) - err = json.Unmarshal(data, &resource) - return -} - -// Resources fetches user-visible resources. The set of resources can -// be limited by the given ResourceFilter. If filter is non-nil, only -// non-zero-valued members of the filter will be applied. -func (c *Client) Resources(filter *ResourceFilter) (resources []map[string]interface{}, err error) { - req, err := c.router.ResourcesRequest(filter) - if err != nil { - return - } - - resp, err := c.SubmitRequest(req) - if err != nil { - return - } - - data, err := response.DataResponse(resp) - if err != nil { - return - } - - resources = make([]map[string]interface{}, 1) - - err = json.Unmarshal(data, &resources) - - return -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/response/error.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/response/error.go deleted file mode 100644 index 8101c55e..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/response/error.go +++ /dev/null @@ -1,61 +0,0 @@ -package response - -import ( - "encoding/json" - "io/ioutil" - "net/http" - "strings" - - "github.com/cyberark/conjur-api-go/conjurapi/logging" -) - -type ConjurError struct { - Code int - Message string - Details *ConjurErrorDetails `json:"error"` -} - -type ConjurErrorDetails struct { - Message string - Code string - Target string - Details map[string]interface{} -} - -func NewConjurError(resp *http.Response) error { - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - - cerr := ConjurError{} - cerr.Code = resp.StatusCode - err = json.Unmarshal(body, &cerr) - if err != nil { - cerr.Message = strings.TrimSpace(string(body)) - } - - // If the body's empty, use the HTTP status as the message - if cerr.Message == "" { - cerr.Message = resp.Status - } - - return &cerr -} - -func (self *ConjurError) Error() string { - logging.ApiLog.Debugf("self.Details: %+v, self.Message: %+v\n", self.Details, self.Message) - - var b strings.Builder - - if self.Message != "" { - b.WriteString(self.Message + ". ") - } - - if self.Details != nil && self.Details.Message != "" { - b.WriteString(self.Details.Message + ".") - } - - return b.String() -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/response/response.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/response/response.go deleted file mode 100644 index f348707e..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/response/response.go +++ /dev/null @@ -1,74 +0,0 @@ -package response - -import ( - "encoding/json" - "io" - "io/ioutil" - "net/http" - - "github.com/cyberark/conjur-api-go/conjurapi/logging" -) - -func readBody(resp *http.Response) ([]byte, error) { - defer resp.Body.Close() - - responseText, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - return responseText, err -} - -func logResponse(resp *http.Response) { - req := resp.Request - logging.ApiLog.Debugf("%d %s %s %+v", resp.StatusCode, req.Method, req.URL, req.Header) -} - -// DataResponse checks the HTTP status of the response. If it's less than -// 300, it returns the response body as a byte array. Otherwise it returns -// a NewConjurError. -func DataResponse(resp *http.Response) ([]byte, error) { - logResponse(resp) - if resp.StatusCode < 300 { - return readBody(resp) - } - return nil, NewConjurError(resp) -} - -// SecretDataResponse checks the HTTP status of the response. If it's less than -// 300, it returns the response body as a stream. Otherwise it returns -// a NewConjurError. -func SecretDataResponse(resp *http.Response) (io.ReadCloser, error) { - logResponse(resp) - if resp.StatusCode < 300 { - return resp.Body, nil - } - return nil, NewConjurError(resp) -} - -// JSONResponse checks the HTTP status of the response. If it's less than -// 300, it returns the response body as JSON. Otherwise it returns -// a NewConjurError. -func JSONResponse(resp *http.Response, obj interface{}) error { - logResponse(resp) - if resp.StatusCode < 300 { - body, err := readBody(resp) - if err != nil { - return err - } - return json.Unmarshal(body, obj) - } - return NewConjurError(resp) -} - -// EmptyResponse checks the HTTP status of the response. If it's less than -// 300, it returns without an error. Otherwise it returns -// a NewConjurError. -func EmptyResponse(resp *http.Response) error { - logResponse(resp) - if resp.StatusCode < 300 { - return nil - } - return NewConjurError(resp) -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/router_url.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/router_url.go deleted file mode 100644 index be54ba84..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/router_url.go +++ /dev/null @@ -1,25 +0,0 @@ -package conjurapi - -import ( - "fmt" - "strings" -) - -type routerURL string - -func makeRouterURL(components ...string) routerURL { - return routerURL(strings.Join(components, "/")) -} - -func (url routerURL) withFormattedQuery(queryFormat string, queryArgs ...interface{}) routerURL { - query := fmt.Sprintf(queryFormat, queryArgs...) - return routerURL(strings.Join([]string{string(url), query}, "?")) -} - -func (url routerURL) withQuery(query string) routerURL { - return routerURL(strings.Join([]string{string(url), query}, "?")) -} - -func (url routerURL) String() string { - return string(url) -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/router_v4.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/router_v4.go deleted file mode 100644 index 625b2a1c..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/router_v4.go +++ /dev/null @@ -1,127 +0,0 @@ -package conjurapi - -import ( - "fmt" - "io" - "net/http" - "net/url" - "strings" - - "github.com/cyberark/conjur-api-go/conjurapi/authn" - "github.com/sirupsen/logrus" -) - -type RouterV4 struct { - Config *Config -} - -func (r RouterV4) AuthenticateRequest(loginPair authn.LoginPair) (*http.Request, error) { - authenticateURL := fmt.Sprintf("%s/authn/users/%s/authenticate", r.Config.ApplianceURL, url.QueryEscape(loginPair.Login)) - - req, err := http.NewRequest("POST", authenticateURL, strings.NewReader(loginPair.APIKey)) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "text/plain") - - return req, nil -} - -func (r RouterV4) RotateAPIKeyRequest(roleID string) (*http.Request, error) { - account, kind, id, err := parseID(roleID) - if err != nil { - return nil, err - } - if account != r.Config.Account { - return nil, fmt.Errorf("Account of '%s' must match the configured account '%s'", roleID, r.Config.Account) - } - - var username string - switch kind { - case "user": - username = id - default: - username = strings.Join([]string{kind, id}, "/") - } - - rotateURL := fmt.Sprintf("%s/authn/users/api_key?id=%s", r.Config.ApplianceURL, url.QueryEscape(username)) - - return http.NewRequest( - "PUT", - rotateURL, - nil, - ) -} - -func (r RouterV4) LoadPolicyRequest(mode PolicyMode, policyID string, policy io.Reader) (*http.Request, error) { - return nil, fmt.Errorf("LoadPolicy is not supported for Conjur V4") -} - -func (r RouterV4) ResourceRequest(resourceID string) (*http.Request, error) { - logrus.Panic("ResourceRequest not implemented yet") - return nil, nil -} - -func (r RouterV4) ResourcesRequest(filter *ResourceFilter) (*http.Request, error) { - logrus.Panic("ResourcesRequest not implemented yet") - return nil, nil -} - -func (r RouterV4) CheckPermissionRequest(resourceID, privilege string) (*http.Request, error) { - account, kind, id, err := parseID(resourceID) - if err != nil { - return nil, err - } - - checkURL := fmt.Sprintf("%s/authz/%s/resources/%s/%s?check=true&privilege=%s", r.Config.ApplianceURL, account, kind, url.QueryEscape(id), url.QueryEscape(privilege)) - - return http.NewRequest( - "GET", - checkURL, - nil, - ) -} - -func (r RouterV4) AddSecretRequest(variableID, secretValue string) (*http.Request, error) { - return nil, fmt.Errorf("AddSecret is not supported for Conjur V4") -} - -func (r RouterV4) RetrieveBatchSecretsRequest(variableIDs []string, base64Flag bool) (*http.Request, error) { - if base64Flag { - return nil, fmt.Errorf("Batch retrieving Base64-encoded secrets is not supported in Conjur V4") - } - - return http.NewRequest( - "GET", - r.batchVariableURL(variableIDs), - nil, - ) -} - -func (r RouterV4) RetrieveSecretRequest(variableID string) (*http.Request, error) { - fullVariableID := makeFullId(r.Config.Account, "variable", variableID) - - variableURL, err := r.variableURL(fullVariableID) - if err != nil { - return nil, err - } - - return http.NewRequest( - "GET", - variableURL, - nil, - ) -} - -func (r RouterV4) variableURL(variableID string) (string, error) { - _, _, id, err := parseID(variableID) - if err != nil { - return "", err - } - return fmt.Sprintf("%s/variables/%s/value", r.Config.ApplianceURL, url.PathEscape(id)), nil -} - -func (r RouterV4) batchVariableURL(variableIDs []string) string { - queryString := url.QueryEscape(strings.Join(variableIDs, ",")) - return fmt.Sprintf("%s/variables/values?vars=%s", r.Config.ApplianceURL, queryString) -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/router_v5.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/router_v5.go deleted file mode 100644 index 8c80369a..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/router_v5.go +++ /dev/null @@ -1,225 +0,0 @@ -package conjurapi - -import ( - "fmt" - "io" - "net/http" - "net/url" - "strconv" - "strings" - - "github.com/cyberark/conjur-api-go/conjurapi/authn" -) - -type RouterV5 struct { - Config *Config -} - -func (r RouterV5) AuthenticateRequest(loginPair authn.LoginPair) (*http.Request, error) { - authenticateURL := makeRouterURL(r.authnURL(), url.QueryEscape(loginPair.Login), "authenticate").String() - - req, err := http.NewRequest("POST", authenticateURL, strings.NewReader(loginPair.APIKey)) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "text/plain") - - return req, nil -} - -func (r RouterV5) RotateAPIKeyRequest(roleID string) (*http.Request, error) { - account, _, _, err := parseID(roleID) - if err != nil { - return nil, err - } - if account != r.Config.Account { - return nil, fmt.Errorf("Account of '%s' must match the configured account '%s'", roleID, r.Config.Account) - } - - rotateURL := makeRouterURL(r.authnURL(), "api_key").withFormattedQuery("role=%s", roleID).String() - - return http.NewRequest( - "PUT", - rotateURL, - nil, - ) -} - -func (r RouterV5) CheckPermissionRequest(resourceID, privilege string) (*http.Request, error) { - account, kind, id, err := parseID(resourceID) - if err != nil { - return nil, err - } - checkURL := makeRouterURL(r.resourcesURL(account), kind, url.QueryEscape(id)).withFormattedQuery("check=true&privilege=%s", url.QueryEscape(privilege)).String() - - return http.NewRequest( - "GET", - checkURL, - nil, - ) -} - -func (r RouterV5) ResourceRequest(resourceID string) (*http.Request, error) { - account, kind, id, err := parseID(resourceID) - if err != nil { - return nil, err - } - - requestURL := makeRouterURL(r.resourcesURL(account), kind, url.QueryEscape(id)) - - return http.NewRequest( - "GET", - requestURL.String(), - nil, - ) -} - -func (r RouterV5) ResourcesRequest(filter *ResourceFilter) (*http.Request, error) { - query := url.Values{} - - if filter != nil { - if filter.Kind != "" { - query.Add("kind", filter.Kind) - } - if filter.Search != "" { - query.Add("search", filter.Search) - } - - if filter.Limit != 0 { - query.Add("limit", strconv.Itoa(filter.Limit)) - } - - if filter.Offset != 0 { - query.Add("offset", strconv.Itoa(filter.Offset)) - } - } - - requestURL := makeRouterURL(r.resourcesURL(r.Config.Account)).withQuery(query.Encode()) - - return http.NewRequest( - "GET", - requestURL.String(), - nil, - ) -} - -func (r RouterV5) LoadPolicyRequest(mode PolicyMode, policyID string, policy io.Reader) (*http.Request, error) { - fullPolicyID := makeFullId(r.Config.Account, "policy", policyID) - - account, kind, id, err := parseID(fullPolicyID) - if err != nil { - return nil, err - } - policyURL := makeRouterURL(r.policiesURL(account), kind, url.QueryEscape(id)).String() - - var method string - switch mode { - case PolicyModePost: - method = "POST" - case PolicyModePatch: - method = "PATCH" - case PolicyModePut: - method = "PUT" - default: - return nil, fmt.Errorf("Invalid PolicyMode : %d", mode) - } - - return http.NewRequest( - method, - policyURL, - policy, - ) -} - -func (r RouterV5) RetrieveBatchSecretsRequest(variableIDs []string, base64Flag bool) (*http.Request, error) { - fullVariableIDs := []string{} - for _, variableID := range variableIDs { - fullVariableID := makeFullId(r.Config.Account, "variable", variableID) - fullVariableIDs = append(fullVariableIDs, fullVariableID) - } - - request, err := http.NewRequest( - "GET", - r.batchVariableURL(fullVariableIDs), - nil, - ) - - if err != nil { - return nil, err - } - - if base64Flag { - request.Header.Add("Accept", "base64") - } - - return request, nil -} - -func (r RouterV5) RetrieveSecretRequest(variableID string) (*http.Request, error) { - fullVariableID := makeFullId(r.Config.Account, "variable", variableID) - - variableURL, err := r.variableURL(fullVariableID) - if err != nil { - return nil, err - } - - return http.NewRequest( - "GET", - variableURL, - nil, - ) -} - -func (r RouterV5) AddSecretRequest(variableID, secretValue string) (*http.Request, error) { - fullVariableID := makeFullId(r.Config.Account, "variable", variableID) - - variableURL, err := r.variableURL(fullVariableID) - if err != nil { - return nil, err - } - - request, err := http.NewRequest( - "POST", - variableURL, - strings.NewReader(secretValue), - ) - if err != nil { - return nil, err - } - - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - return request, nil -} - -func (r RouterV5) variableURL(variableID string) (string, error) { - account, kind, id, err := parseID(variableID) - if err != nil { - return "", err - } - return makeRouterURL(r.secretsURL(account), kind, url.PathEscape(id)).String(), nil -} - -func (r RouterV5) batchVariableURL(variableIDs []string) string { - queryString := url.QueryEscape(strings.Join(variableIDs, ",")) - return makeRouterURL(r.globalSecretsURL()).withFormattedQuery("variable_ids=%s", queryString).String() -} - -func (r RouterV5) authnURL() string { - return makeRouterURL(r.Config.ApplianceURL, "authn", r.Config.Account).String() -} - -func (r RouterV5) resourcesURL(account string) string { - return makeRouterURL(r.Config.ApplianceURL, "resources", account).String() -} - -func (r RouterV5) secretsURL(account string) string { - return makeRouterURL(r.Config.ApplianceURL, "secrets", account).String() -} - -func (r RouterV5) globalSecretsURL() string { - return makeRouterURL(r.Config.ApplianceURL, "secrets").String() -} - -func (r RouterV5) policiesURL(account string) string { - return makeRouterURL(r.Config.ApplianceURL, "policies", account).String() -} diff --git a/vendor/github.com/cyberark/conjur-api-go/conjurapi/variable.go b/vendor/github.com/cyberark/conjur-api-go/conjurapi/variable.go deleted file mode 100644 index cd22ae9a..00000000 --- a/vendor/github.com/cyberark/conjur-api-go/conjurapi/variable.go +++ /dev/null @@ -1,130 +0,0 @@ -package conjurapi - -import ( - "io" - "net/http" - - "encoding/json" - "encoding/base64" - - "github.com/cyberark/conjur-api-go/conjurapi/response" -) - -// RetrieveBatchSecrets fetches values for all variables in a slice using a -// single API call -// -// The authenticated user must have execute privilege on all variables. -func (c *Client) RetrieveBatchSecrets(variableIDs []string) (map[string][]byte, error) { - jsonResponse, err := c.retrieveBatchSecrets(variableIDs, false) - if err != nil { - return nil, err - } - - resolvedVariables := map[string][]byte{} - for id, value := range jsonResponse { - resolvedVariables[id] = []byte(value) - } - - return resolvedVariables, nil -} - -// RetrieveBatchSecretsSafe fetches values for all variables in a slice using a -// single API call. This version of the method will automatically base64-encode -// the secrets on the server side allowing the retrieval of binary values in -// batch requests. Secrets are NOT base64 encoded in the returned map. -// -// The authenticated user must have execute privilege on all variables. -func (c *Client) RetrieveBatchSecretsSafe(variableIDs []string) (map[string][]byte, error) { - jsonResponse, err := c.retrieveBatchSecrets(variableIDs, true) - if err != nil { - return nil, err - } - - resolvedVariables := map[string][]byte{} - var decodedValue []byte - for id, value := range jsonResponse { - decodedValue, err = base64.StdEncoding.DecodeString(value) - if err != nil { - return nil, err - } - resolvedVariables[id] = decodedValue - } - - return resolvedVariables, nil -} - -// RetrieveSecret fetches a secret from a variable. -// -// The authenticated user must have execute privilege on the variable. -func (c *Client) RetrieveSecret(variableID string) ([]byte, error) { - resp, err := c.retrieveSecret(variableID) - if err != nil { - return nil, err - } - - return response.DataResponse(resp) -} - -// RetrieveSecretReader fetches a secret from a variable and returns it as a -// data stream. -// -// The authenticated user must have execute privilege on the variable. -func (c *Client) RetrieveSecretReader(variableID string) (io.ReadCloser, error) { - resp, err := c.retrieveSecret(variableID) - if err != nil { - return nil, err - } - - return response.SecretDataResponse(resp) -} - -func (c *Client) retrieveBatchSecrets(variableIDs []string, base64Flag bool) (map[string]string, error) { - req, err := c.router.RetrieveBatchSecretsRequest(variableIDs, base64Flag) - if err != nil { - return nil, err - } - - resp, err := c.SubmitRequest(req) - if err != nil { - return nil, err - } - - data, err := response.DataResponse(resp) - if err != nil { - return nil, err - } - - jsonResponse := map[string]string{} - err = json.Unmarshal(data, &jsonResponse) - if err != nil { - return nil, err - } - - return jsonResponse, nil -} - -func (c *Client) retrieveSecret(variableID string) (*http.Response, error) { - req, err := c.router.RetrieveSecretRequest(variableID) - if err != nil { - return nil, err - } - - return c.SubmitRequest(req) -} - -// AddSecret adds a secret value to a variable. -// -// The authenticated user must have update privilege on the variable. -func (c *Client) AddSecret(variableID string, secretValue string) error { - req, err := c.router.AddSecretRequest(variableID, secretValue) - if err != nil { - return err - } - - resp, err := c.SubmitRequest(req) - if err != nil { - return err - } - - return response.EmptyResponse(resp) -} diff --git a/vendor/github.com/danieljoos/wincred/.gitattributes b/vendor/github.com/danieljoos/wincred/.gitattributes deleted file mode 100644 index d207b180..00000000 --- a/vendor/github.com/danieljoos/wincred/.gitattributes +++ /dev/null @@ -1 +0,0 @@ -*.go text eol=lf diff --git a/vendor/github.com/danieljoos/wincred/.gitignore b/vendor/github.com/danieljoos/wincred/.gitignore deleted file mode 100644 index 6142c069..00000000 --- a/vendor/github.com/danieljoos/wincred/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test - -coverage.txt diff --git a/vendor/github.com/danieljoos/wincred/LICENSE b/vendor/github.com/danieljoos/wincred/LICENSE deleted file mode 100644 index 2f436f1b..00000000 --- a/vendor/github.com/danieljoos/wincred/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Daniel Joos - -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. \ No newline at end of file diff --git a/vendor/github.com/danieljoos/wincred/README.md b/vendor/github.com/danieljoos/wincred/README.md deleted file mode 100644 index 14f28622..00000000 --- a/vendor/github.com/danieljoos/wincred/README.md +++ /dev/null @@ -1,145 +0,0 @@ -wincred -======= - -Go wrapper around the Windows Credential Manager API functions. - -[![GitHub release](https://img.shields.io/github/release/danieljoos/wincred.svg?style=flat-square)](https://github.com/danieljoos/wincred/releases/latest) -[![Test Status](https://img.shields.io/github/workflow/status/danieljoos/wincred/test?label=test&logo=github&style=flat-square)](https://github.com/danieljoos/wincred/actions?query=workflow%3Atest) -[![Go Report Card](https://goreportcard.com/badge/github.com/danieljoos/wincred)](https://goreportcard.com/report/github.com/danieljoos/wincred) -[![Codecov](https://img.shields.io/codecov/c/github/danieljoos/wincred?logo=codecov&style=flat-square)](https://codecov.io/gh/danieljoos/wincred) -[![PkgGoDev](https://img.shields.io/badge/go.dev-docs-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/github.com/danieljoos/wincred) - -Installation ------------- - -```Go -go get github.com/danieljoos/wincred -``` - - -Usage ------ - -See the following examples: - -### Create and store a new generic credential object -```Go -package main - -import ( - "fmt" - "github.com/danieljoos/wincred" -) - -func main() { - cred := wincred.NewGenericCredential("myGoApplication") - cred.CredentialBlob = []byte("my secret") - err := cred.Write() - - if err != nil { - fmt.Println(err) - } -} -``` - -### Retrieve a credential object -```Go -package main - -import ( - "fmt" - "github.com/danieljoos/wincred" -) - -func main() { - cred, err := wincred.GetGenericCredential("myGoApplication") - if err == nil { - fmt.Println(string(cred.CredentialBlob)) - } -} -``` - -### Remove a credential object -```Go -package main - -import ( - "fmt" - "github.com/danieljoos/wincred" -) - -func main() { - cred, err := wincred.GetGenericCredential("myGoApplication") - if err != nil { - fmt.Println(err) - return - } - cred.Delete() -} -``` - -### List all available credentials -```Go -package main - -import ( - "fmt" - "github.com/danieljoos/wincred" -) - -func main() { - creds, err := wincred.List() - if err != nil { - fmt.Println(err) - return - } - for i := range(creds) { - fmt.Println(creds[i].TargetName) - } -} -``` - -Hints ------ - -### Encoding - -The credential objects simply store byte arrays without specific meaning or encoding. -For sharing between different applications, it might make sense to apply an explicit string encoding - for example **UTF-16 LE** (used nearly everywhere in the Win32 API). - -```Go -package main - -import ( - "fmt" - "os" - - "github.com/danieljoos/wincred" - "golang.org/x/text/encoding/unicode" - "golang.org/x/text/transform" -) - -func main() { - cred := wincred.NewGenericCredential("myGoApplication") - - encoder := unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder() - blob, _, err := transform.Bytes(encoder, []byte("mysecret")) - if err != nil { - fmt.Println(err) - os.Exit(1) - } - - cred.CredentialBlob = blob - err = cred.Write() - - if err != nil { - fmt.Println(err) - os.Exit(1) - } -} - -``` - -### Limitations - -The size of a credential blob is limited to **2560 Bytes** by the Windows API. diff --git a/vendor/github.com/danieljoos/wincred/conversion.go b/vendor/github.com/danieljoos/wincred/conversion.go deleted file mode 100644 index bc04f50f..00000000 --- a/vendor/github.com/danieljoos/wincred/conversion.go +++ /dev/null @@ -1,116 +0,0 @@ -// +build windows - -package wincred - -import ( - "encoding/binary" - "reflect" - "time" - "unsafe" - - syscall "golang.org/x/sys/windows" -) - -// utf16ToByte creates a byte array from a given UTF 16 char array. -func utf16ToByte(wstr []uint16) (result []byte) { - result = make([]byte, len(wstr)*2) - for i := range wstr { - binary.LittleEndian.PutUint16(result[(i*2):(i*2)+2], wstr[i]) - } - return -} - -// utf16FromString creates a UTF16 char array from a string. -func utf16FromString(str string) []uint16 { - res, err := syscall.UTF16FromString(str) - if err != nil { - return []uint16{} - } - return res -} - -// goBytes copies the given C byte array to a Go byte array (see `C.GoBytes`). -// This function avoids having cgo as dependency. -func goBytes(src uintptr, len uint32) []byte { - if src == uintptr(0) { - return []byte{} - } - rv := make([]byte, len) - copy(rv, *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ - Data: src, - Len: int(len), - Cap: int(len), - }))) - return rv -} - -// Convert the given CREDENTIAL struct to a more usable structure -func sysToCredential(cred *sysCREDENTIAL) (result *Credential) { - if cred == nil { - return nil - } - result = new(Credential) - result.Comment = syscall.UTF16PtrToString(cred.Comment) - result.TargetName = syscall.UTF16PtrToString(cred.TargetName) - result.TargetAlias = syscall.UTF16PtrToString(cred.TargetAlias) - result.UserName = syscall.UTF16PtrToString(cred.UserName) - result.LastWritten = time.Unix(0, cred.LastWritten.Nanoseconds()) - result.Persist = CredentialPersistence(cred.Persist) - result.CredentialBlob = goBytes(cred.CredentialBlob, cred.CredentialBlobSize) - result.Attributes = make([]CredentialAttribute, cred.AttributeCount) - attrSlice := *(*[]sysCREDENTIAL_ATTRIBUTE)(unsafe.Pointer(&reflect.SliceHeader{ - Data: cred.Attributes, - Len: int(cred.AttributeCount), - Cap: int(cred.AttributeCount), - })) - for i, attr := range attrSlice { - resultAttr := &result.Attributes[i] - resultAttr.Keyword = syscall.UTF16PtrToString(attr.Keyword) - resultAttr.Value = goBytes(attr.Value, attr.ValueSize) - } - return result -} - -// Convert the given Credential object back to a CREDENTIAL struct, which can be used for calling the -// Windows APIs -func sysFromCredential(cred *Credential) (result *sysCREDENTIAL) { - if cred == nil { - return nil - } - result = new(sysCREDENTIAL) - result.Flags = 0 - result.Type = 0 - result.TargetName, _ = syscall.UTF16PtrFromString(cred.TargetName) - result.Comment, _ = syscall.UTF16PtrFromString(cred.Comment) - result.LastWritten = syscall.NsecToFiletime(cred.LastWritten.UnixNano()) - result.CredentialBlobSize = uint32(len(cred.CredentialBlob)) - if len(cred.CredentialBlob) > 0 { - result.CredentialBlob = uintptr(unsafe.Pointer(&cred.CredentialBlob[0])) - } else { - result.CredentialBlob = 0 - } - result.Persist = uint32(cred.Persist) - result.AttributeCount = uint32(len(cred.Attributes)) - attributes := make([]sysCREDENTIAL_ATTRIBUTE, len(cred.Attributes)) - if len(attributes) > 0 { - result.Attributes = uintptr(unsafe.Pointer(&attributes[0])) - } else { - result.Attributes = 0 - } - for i := range cred.Attributes { - inAttr := &cred.Attributes[i] - outAttr := &attributes[i] - outAttr.Keyword, _ = syscall.UTF16PtrFromString(inAttr.Keyword) - outAttr.Flags = 0 - outAttr.ValueSize = uint32(len(inAttr.Value)) - if len(inAttr.Value) > 0 { - outAttr.Value = uintptr(unsafe.Pointer(&inAttr.Value[0])) - } else { - outAttr.Value = 0 - } - } - result.TargetAlias, _ = syscall.UTF16PtrFromString(cred.TargetAlias) - result.UserName, _ = syscall.UTF16PtrFromString(cred.UserName) - - return -} diff --git a/vendor/github.com/danieljoos/wincred/conversion_unsupported.go b/vendor/github.com/danieljoos/wincred/conversion_unsupported.go deleted file mode 100644 index a1ea7207..00000000 --- a/vendor/github.com/danieljoos/wincred/conversion_unsupported.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !windows - -package wincred - -func utf16ToByte(...interface{}) []byte { - return nil -} - -func utf16FromString(...interface{}) []uint16 { - return nil -} diff --git a/vendor/github.com/danieljoos/wincred/sys.go b/vendor/github.com/danieljoos/wincred/sys.go deleted file mode 100644 index 033d3c4f..00000000 --- a/vendor/github.com/danieljoos/wincred/sys.go +++ /dev/null @@ -1,143 +0,0 @@ -// +build windows - -package wincred - -import ( - "reflect" - "unsafe" - - syscall "golang.org/x/sys/windows" -) - -var ( - modadvapi32 = syscall.NewLazyDLL("advapi32.dll") - procCredRead proc = modadvapi32.NewProc("CredReadW") - procCredWrite proc = modadvapi32.NewProc("CredWriteW") - procCredDelete proc = modadvapi32.NewProc("CredDeleteW") - procCredFree proc = modadvapi32.NewProc("CredFree") - procCredEnumerate proc = modadvapi32.NewProc("CredEnumerateW") -) - -// Interface for syscall.Proc: helps testing -type proc interface { - Call(a ...uintptr) (r1, r2 uintptr, lastErr error) -} - -// https://docs.microsoft.com/en-us/windows/desktop/api/wincred/ns-wincred-_credentialw -type sysCREDENTIAL struct { - Flags uint32 - Type uint32 - TargetName *uint16 - Comment *uint16 - LastWritten syscall.Filetime - CredentialBlobSize uint32 - CredentialBlob uintptr - Persist uint32 - AttributeCount uint32 - Attributes uintptr - TargetAlias *uint16 - UserName *uint16 -} - -// https://docs.microsoft.com/en-us/windows/desktop/api/wincred/ns-wincred-_credential_attributew -type sysCREDENTIAL_ATTRIBUTE struct { - Keyword *uint16 - Flags uint32 - ValueSize uint32 - Value uintptr -} - -// https://docs.microsoft.com/en-us/windows/desktop/api/wincred/ns-wincred-_credentialw -type sysCRED_TYPE uint32 - -const ( - sysCRED_TYPE_GENERIC sysCRED_TYPE = 0x1 - sysCRED_TYPE_DOMAIN_PASSWORD sysCRED_TYPE = 0x2 - sysCRED_TYPE_DOMAIN_CERTIFICATE sysCRED_TYPE = 0x3 - sysCRED_TYPE_DOMAIN_VISIBLE_PASSWORD sysCRED_TYPE = 0x4 - sysCRED_TYPE_GENERIC_CERTIFICATE sysCRED_TYPE = 0x5 - sysCRED_TYPE_DOMAIN_EXTENDED sysCRED_TYPE = 0x6 - - // https://docs.microsoft.com/en-us/windows/desktop/Debug/system-error-codes - sysERROR_NOT_FOUND = syscall.Errno(1168) - sysERROR_INVALID_PARAMETER = syscall.Errno(87) -) - -// https://docs.microsoft.com/en-us/windows/desktop/api/wincred/nf-wincred-credreadw -func sysCredRead(targetName string, typ sysCRED_TYPE) (*Credential, error) { - var pcred *sysCREDENTIAL - targetNamePtr, _ := syscall.UTF16PtrFromString(targetName) - ret, _, err := procCredRead.Call( - uintptr(unsafe.Pointer(targetNamePtr)), - uintptr(typ), - 0, - uintptr(unsafe.Pointer(&pcred)), - ) - if ret == 0 { - return nil, err - } - defer procCredFree.Call(uintptr(unsafe.Pointer(pcred))) - - return sysToCredential(pcred), nil -} - -// https://docs.microsoft.com/en-us/windows/desktop/api/wincred/nf-wincred-credwritew -func sysCredWrite(cred *Credential, typ sysCRED_TYPE) error { - ncred := sysFromCredential(cred) - ncred.Type = uint32(typ) - ret, _, err := procCredWrite.Call( - uintptr(unsafe.Pointer(ncred)), - 0, - ) - if ret == 0 { - return err - } - - return nil -} - -// https://docs.microsoft.com/en-us/windows/desktop/api/wincred/nf-wincred-creddeletew -func sysCredDelete(cred *Credential, typ sysCRED_TYPE) error { - targetNamePtr, _ := syscall.UTF16PtrFromString(cred.TargetName) - ret, _, err := procCredDelete.Call( - uintptr(unsafe.Pointer(targetNamePtr)), - uintptr(typ), - 0, - ) - if ret == 0 { - return err - } - - return nil -} - -// https://docs.microsoft.com/en-us/windows/desktop/api/wincred/nf-wincred-credenumeratew -func sysCredEnumerate(filter string, all bool) ([]*Credential, error) { - var count int - var pcreds uintptr - var filterPtr *uint16 - if !all { - filterPtr, _ = syscall.UTF16PtrFromString(filter) - } - ret, _, err := procCredEnumerate.Call( - uintptr(unsafe.Pointer(filterPtr)), - 0, - uintptr(unsafe.Pointer(&count)), - uintptr(unsafe.Pointer(&pcreds)), - ) - if ret == 0 { - return nil, err - } - defer procCredFree.Call(pcreds) - credsSlice := *(*[]*sysCREDENTIAL)(unsafe.Pointer(&reflect.SliceHeader{ - Data: pcreds, - Len: count, - Cap: count, - })) - creds := make([]*Credential, count, count) - for i, cred := range credsSlice { - creds[i] = sysToCredential(cred) - } - - return creds, nil -} diff --git a/vendor/github.com/danieljoos/wincred/sys_unsupported.go b/vendor/github.com/danieljoos/wincred/sys_unsupported.go deleted file mode 100644 index b47bccf8..00000000 --- a/vendor/github.com/danieljoos/wincred/sys_unsupported.go +++ /dev/null @@ -1,36 +0,0 @@ -// +build !windows - -package wincred - -import ( - "errors" - "syscall" -) - -const ( - sysCRED_TYPE_GENERIC = 0 - sysCRED_TYPE_DOMAIN_PASSWORD = 0 - sysCRED_TYPE_DOMAIN_CERTIFICATE = 0 - sysCRED_TYPE_DOMAIN_VISIBLE_PASSWORD = 0 - sysCRED_TYPE_GENERIC_CERTIFICATE = 0 - sysCRED_TYPE_DOMAIN_EXTENDED = 0 - - sysERROR_NOT_FOUND = syscall.Errno(1) - sysERROR_INVALID_PARAMETER = syscall.Errno(1) -) - -func sysCredRead(...interface{}) (*Credential, error) { - return nil, errors.New("Operation not supported") -} - -func sysCredWrite(...interface{}) error { - return errors.New("Operation not supported") -} - -func sysCredDelete(...interface{}) error { - return errors.New("Operation not supported") -} - -func sysCredEnumerate(...interface{}) ([]*Credential, error) { - return nil, errors.New("Operation not supported") -} diff --git a/vendor/github.com/danieljoos/wincred/types.go b/vendor/github.com/danieljoos/wincred/types.go deleted file mode 100644 index 28debc93..00000000 --- a/vendor/github.com/danieljoos/wincred/types.go +++ /dev/null @@ -1,69 +0,0 @@ -package wincred - -import ( - "time" -) - -// CredentialPersistence describes one of three persistence modes of a credential. -// A detailed description of the available modes can be found on -// Docs: https://docs.microsoft.com/en-us/windows/desktop/api/wincred/ns-wincred-_credentialw -type CredentialPersistence uint32 - -const ( - // PersistSession indicates that the credential only persists for the life - // of the current Windows login session. Such a credential is not visible in - // any other logon session, even from the same user. - PersistSession CredentialPersistence = 0x1 - - // PersistLocalMachine indicates that the credential persists for this and - // all subsequent logon sessions on this local machine/computer. It is - // however not visible for logon sessions of this user on a different - // machine. - PersistLocalMachine CredentialPersistence = 0x2 - - // PersistEnterprise indicates that the credential persists for this and all - // subsequent logon sessions for this user. It is also visible for logon - // sessions on different computers. - PersistEnterprise CredentialPersistence = 0x3 -) - -// CredentialAttribute represents an application-specific attribute of a credential. -type CredentialAttribute struct { - Keyword string - Value []byte -} - -// Credential is the basic credential structure. -// A credential is identified by its target name. -// The actual credential secret is available in the CredentialBlob field. -type Credential struct { - TargetName string - Comment string - LastWritten time.Time - CredentialBlob []byte - Attributes []CredentialAttribute - TargetAlias string - UserName string - Persist CredentialPersistence -} - -// GenericCredential holds a credential for generic usage. -// It is typically defined and used by applications that need to manage user -// secrets. -// -// More information about the available kinds of credentials of the Windows -// Credential Management API can be found on Docs: -// https://docs.microsoft.com/en-us/windows/desktop/SecAuthN/kinds-of-credentials -type GenericCredential struct { - Credential -} - -// DomainPassword holds a domain credential that is typically used by the -// operating system for user logon. -// -// More information about the available kinds of credentials of the Windows -// Credential Management API can be found on Docs: -// https://docs.microsoft.com/en-us/windows/desktop/SecAuthN/kinds-of-credentials -type DomainPassword struct { - Credential -} diff --git a/vendor/github.com/danieljoos/wincred/wincred.go b/vendor/github.com/danieljoos/wincred/wincred.go deleted file mode 100644 index 998de7b5..00000000 --- a/vendor/github.com/danieljoos/wincred/wincred.go +++ /dev/null @@ -1,111 +0,0 @@ -// Package wincred provides primitives for accessing the Windows Credentials Management API. -// This includes functions for retrieval, listing and storage of credentials as well as Go structures for convenient access to the credential data. -// -// A more detailed description of Windows Credentials Management can be found on -// Docs: https://docs.microsoft.com/en-us/windows/desktop/SecAuthN/credentials-management -package wincred - -import "errors" - -const ( - // ErrElementNotFound is the error that is returned if a requested element cannot be found. - // This error constant can be used to check if a credential could not be found. - ErrElementNotFound = sysERROR_NOT_FOUND - - // ErrInvalidParameter is the error that is returned for invalid parameters. - // This error constant can be used to check if the given function parameters were invalid. - // For example when trying to create a new generic credential with an empty target name. - ErrInvalidParameter = sysERROR_INVALID_PARAMETER -) - -// GetGenericCredential fetches the generic credential with the given name from Windows credential manager. -// It returns nil and an error if the credential could not be found or an error occurred. -func GetGenericCredential(targetName string) (*GenericCredential, error) { - cred, err := sysCredRead(targetName, sysCRED_TYPE_GENERIC) - if cred != nil { - return &GenericCredential{Credential: *cred}, err - } - return nil, err -} - -// NewGenericCredential creates a new generic credential object with the given name. -// The persist mode of the newly created object is set to a default value that indicates local-machine-wide storage. -// The credential object is NOT yet persisted to the Windows credential vault. -func NewGenericCredential(targetName string) (result *GenericCredential) { - result = new(GenericCredential) - result.TargetName = targetName - result.Persist = PersistLocalMachine - return -} - -// Write persists the generic credential object to Windows credential manager. -func (t *GenericCredential) Write() (err error) { - err = sysCredWrite(&t.Credential, sysCRED_TYPE_GENERIC) - return -} - -// Delete removes the credential object from Windows credential manager. -func (t *GenericCredential) Delete() (err error) { - err = sysCredDelete(&t.Credential, sysCRED_TYPE_GENERIC) - return -} - -// GetDomainPassword fetches the domain-password credential with the given target host name from Windows credential manager. -// It returns nil and an error if the credential could not be found or an error occurred. -func GetDomainPassword(targetName string) (*DomainPassword, error) { - cred, err := sysCredRead(targetName, sysCRED_TYPE_DOMAIN_PASSWORD) - if cred != nil { - return &DomainPassword{Credential: *cred}, err - } - return nil, err -} - -// NewDomainPassword creates a new domain-password credential used for login to the given target host name. -// The persist mode of the newly created object is set to a default value that indicates local-machine-wide storage. -// The credential object is NOT yet persisted to the Windows credential vault. -func NewDomainPassword(targetName string) (result *DomainPassword) { - result = new(DomainPassword) - result.TargetName = targetName - result.Persist = PersistLocalMachine - return -} - -// Write persists the domain-password credential to Windows credential manager. -func (t *DomainPassword) Write() (err error) { - err = sysCredWrite(&t.Credential, sysCRED_TYPE_DOMAIN_PASSWORD) - return -} - -// Delete removes the domain-password credential from Windows credential manager. -func (t *DomainPassword) Delete() (err error) { - err = sysCredDelete(&t.Credential, sysCRED_TYPE_DOMAIN_PASSWORD) - return -} - -// SetPassword sets the CredentialBlob field of a domain password credential to the given string. -func (t *DomainPassword) SetPassword(pw string) { - t.CredentialBlob = utf16ToByte(utf16FromString(pw)) -} - -// List retrieves all credentials of the Credentials store. -func List() ([]*Credential, error) { - creds, err := sysCredEnumerate("", true) - if err != nil && errors.Is(err, ErrElementNotFound) { - // Ignore ERROR_NOT_FOUND and return an empty list instead - creds = []*Credential{} - err = nil - } - return creds, err -} - -// FilteredList retrieves the list of credentials from the Credentials store that match the given filter. -// The filter string defines the prefix followed by an asterisk for the `TargetName` attribute of the credentials. -func FilteredList(filter string) ([]*Credential, error) { - creds, err := sysCredEnumerate(filter, false) - if err != nil && errors.Is(err, ErrElementNotFound) { - // Ignore ERROR_NOT_FOUND and return an empty list instead - creds = []*Credential{} - err = nil - } - return creds, err -} diff --git a/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE deleted file mode 100644 index bc52e96f..00000000 --- a/vendor/github.com/davecgh/go-spew/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -ISC License - -Copyright (c) 2012-2016 Dave Collins - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go deleted file mode 100644 index 79299478..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/bypass.go +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) 2015-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is not running on Google App Engine, compiled by GopherJS, and -// "-tags safe" is not added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// Go versions prior to 1.4 are disabled because they use a different layout -// for interfaces which make the implementation of unsafeReflectValue more complex. -// +build !js,!appengine,!safe,!disableunsafe,go1.4 - -package spew - -import ( - "reflect" - "unsafe" -) - -const ( - // UnsafeDisabled is a build-time constant which specifies whether or - // not access to the unsafe package is available. - UnsafeDisabled = false - - // ptrSize is the size of a pointer on the current arch. - ptrSize = unsafe.Sizeof((*byte)(nil)) -) - -type flag uintptr - -var ( - // flagRO indicates whether the value field of a reflect.Value - // is read-only. - flagRO flag - - // flagAddr indicates whether the address of the reflect.Value's - // value may be taken. - flagAddr flag -) - -// flagKindMask holds the bits that make up the kind -// part of the flags field. In all the supported versions, -// it is in the lower 5 bits. -const flagKindMask = flag(0x1f) - -// Different versions of Go have used different -// bit layouts for the flags type. This table -// records the known combinations. -var okFlags = []struct { - ro, addr flag -}{{ - // From Go 1.4 to 1.5 - ro: 1 << 5, - addr: 1 << 7, -}, { - // Up to Go tip. - ro: 1<<5 | 1<<6, - addr: 1 << 8, -}} - -var flagValOffset = func() uintptr { - field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") - if !ok { - panic("reflect.Value has no flag field") - } - return field.Offset -}() - -// flagField returns a pointer to the flag field of a reflect.Value. -func flagField(v *reflect.Value) *flag { - return (*flag)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagValOffset)) -} - -// unsafeReflectValue converts the passed reflect.Value into a one that bypasses -// the typical safety restrictions preventing access to unaddressable and -// unexported data. It works by digging the raw pointer to the underlying -// value out of the protected value and generating a new unprotected (unsafe) -// reflect.Value to it. -// -// This allows us to check for implementations of the Stringer and error -// interfaces to be used for pretty printing ordinarily unaddressable and -// inaccessible values such as unexported struct fields. -func unsafeReflectValue(v reflect.Value) reflect.Value { - if !v.IsValid() || (v.CanInterface() && v.CanAddr()) { - return v - } - flagFieldPtr := flagField(&v) - *flagFieldPtr &^= flagRO - *flagFieldPtr |= flagAddr - return v -} - -// Sanity checks against future reflect package changes -// to the type or semantics of the Value.flag field. -func init() { - field, ok := reflect.TypeOf(reflect.Value{}).FieldByName("flag") - if !ok { - panic("reflect.Value has no flag field") - } - if field.Type.Kind() != reflect.TypeOf(flag(0)).Kind() { - panic("reflect.Value flag field has changed kind") - } - type t0 int - var t struct { - A t0 - // t0 will have flagEmbedRO set. - t0 - // a will have flagStickyRO set - a t0 - } - vA := reflect.ValueOf(t).FieldByName("A") - va := reflect.ValueOf(t).FieldByName("a") - vt0 := reflect.ValueOf(t).FieldByName("t0") - - // Infer flagRO from the difference between the flags - // for the (otherwise identical) fields in t. - flagPublic := *flagField(&vA) - flagWithRO := *flagField(&va) | *flagField(&vt0) - flagRO = flagPublic ^ flagWithRO - - // Infer flagAddr from the difference between a value - // taken from a pointer and not. - vPtrA := reflect.ValueOf(&t).Elem().FieldByName("A") - flagNoPtr := *flagField(&vA) - flagPtr := *flagField(&vPtrA) - flagAddr = flagNoPtr ^ flagPtr - - // Check that the inferred flags tally with one of the known versions. - for _, f := range okFlags { - if flagRO == f.ro && flagAddr == f.addr { - return - } - } - panic("reflect.Value read-only flag has changed semantics") -} diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go deleted file mode 100644 index 205c28d6..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2015-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is running on Google App Engine, compiled by GopherJS, or -// "-tags safe" is added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// +build js appengine safe disableunsafe !go1.4 - -package spew - -import "reflect" - -const ( - // UnsafeDisabled is a build-time constant which specifies whether or - // not access to the unsafe package is available. - UnsafeDisabled = true -) - -// unsafeReflectValue typically converts the passed reflect.Value into a one -// that bypasses the typical safety restrictions preventing access to -// unaddressable and unexported data. However, doing this relies on access to -// the unsafe package. This is a stub version which simply returns the passed -// reflect.Value when the unsafe package is not available. -func unsafeReflectValue(v reflect.Value) reflect.Value { - return v -} diff --git a/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go deleted file mode 100644 index 1be8ce94..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/common.go +++ /dev/null @@ -1,341 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "io" - "reflect" - "sort" - "strconv" -) - -// Some constants in the form of bytes to avoid string overhead. This mirrors -// the technique used in the fmt package. -var ( - panicBytes = []byte("(PANIC=") - plusBytes = []byte("+") - iBytes = []byte("i") - trueBytes = []byte("true") - falseBytes = []byte("false") - interfaceBytes = []byte("(interface {})") - commaNewlineBytes = []byte(",\n") - newlineBytes = []byte("\n") - openBraceBytes = []byte("{") - openBraceNewlineBytes = []byte("{\n") - closeBraceBytes = []byte("}") - asteriskBytes = []byte("*") - colonBytes = []byte(":") - colonSpaceBytes = []byte(": ") - openParenBytes = []byte("(") - closeParenBytes = []byte(")") - spaceBytes = []byte(" ") - pointerChainBytes = []byte("->") - nilAngleBytes = []byte("") - maxNewlineBytes = []byte("\n") - maxShortBytes = []byte("") - circularBytes = []byte("") - circularShortBytes = []byte("") - invalidAngleBytes = []byte("") - openBracketBytes = []byte("[") - closeBracketBytes = []byte("]") - percentBytes = []byte("%") - precisionBytes = []byte(".") - openAngleBytes = []byte("<") - closeAngleBytes = []byte(">") - openMapBytes = []byte("map[") - closeMapBytes = []byte("]") - lenEqualsBytes = []byte("len=") - capEqualsBytes = []byte("cap=") -) - -// hexDigits is used to map a decimal value to a hex digit. -var hexDigits = "0123456789abcdef" - -// catchPanic handles any panics that might occur during the handleMethods -// calls. -func catchPanic(w io.Writer, v reflect.Value) { - if err := recover(); err != nil { - w.Write(panicBytes) - fmt.Fprintf(w, "%v", err) - w.Write(closeParenBytes) - } -} - -// handleMethods attempts to call the Error and String methods on the underlying -// type the passed reflect.Value represents and outputes the result to Writer w. -// -// It handles panics in any called methods by catching and displaying the error -// as the formatted value. -func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { - // We need an interface to check if the type implements the error or - // Stringer interface. However, the reflect package won't give us an - // interface on certain things like unexported struct fields in order - // to enforce visibility rules. We use unsafe, when it's available, - // to bypass these restrictions since this package does not mutate the - // values. - if !v.CanInterface() { - if UnsafeDisabled { - return false - } - - v = unsafeReflectValue(v) - } - - // Choose whether or not to do error and Stringer interface lookups against - // the base type or a pointer to the base type depending on settings. - // Technically calling one of these methods with a pointer receiver can - // mutate the value, however, types which choose to satisify an error or - // Stringer interface with a pointer receiver should not be mutating their - // state inside these interface methods. - if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { - v = unsafeReflectValue(v) - } - if v.CanAddr() { - v = v.Addr() - } - - // Is it an error or Stringer? - switch iface := v.Interface().(type) { - case error: - defer catchPanic(w, v) - if cs.ContinueOnMethod { - w.Write(openParenBytes) - w.Write([]byte(iface.Error())) - w.Write(closeParenBytes) - w.Write(spaceBytes) - return false - } - - w.Write([]byte(iface.Error())) - return true - - case fmt.Stringer: - defer catchPanic(w, v) - if cs.ContinueOnMethod { - w.Write(openParenBytes) - w.Write([]byte(iface.String())) - w.Write(closeParenBytes) - w.Write(spaceBytes) - return false - } - w.Write([]byte(iface.String())) - return true - } - return false -} - -// printBool outputs a boolean value as true or false to Writer w. -func printBool(w io.Writer, val bool) { - if val { - w.Write(trueBytes) - } else { - w.Write(falseBytes) - } -} - -// printInt outputs a signed integer value to Writer w. -func printInt(w io.Writer, val int64, base int) { - w.Write([]byte(strconv.FormatInt(val, base))) -} - -// printUint outputs an unsigned integer value to Writer w. -func printUint(w io.Writer, val uint64, base int) { - w.Write([]byte(strconv.FormatUint(val, base))) -} - -// printFloat outputs a floating point value using the specified precision, -// which is expected to be 32 or 64bit, to Writer w. -func printFloat(w io.Writer, val float64, precision int) { - w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) -} - -// printComplex outputs a complex value using the specified float precision -// for the real and imaginary parts to Writer w. -func printComplex(w io.Writer, c complex128, floatPrecision int) { - r := real(c) - w.Write(openParenBytes) - w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) - i := imag(c) - if i >= 0 { - w.Write(plusBytes) - } - w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) - w.Write(iBytes) - w.Write(closeParenBytes) -} - -// printHexPtr outputs a uintptr formatted as hexadecimal with a leading '0x' -// prefix to Writer w. -func printHexPtr(w io.Writer, p uintptr) { - // Null pointer. - num := uint64(p) - if num == 0 { - w.Write(nilAngleBytes) - return - } - - // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix - buf := make([]byte, 18) - - // It's simpler to construct the hex string right to left. - base := uint64(16) - i := len(buf) - 1 - for num >= base { - buf[i] = hexDigits[num%base] - num /= base - i-- - } - buf[i] = hexDigits[num] - - // Add '0x' prefix. - i-- - buf[i] = 'x' - i-- - buf[i] = '0' - - // Strip unused leading bytes. - buf = buf[i:] - w.Write(buf) -} - -// valuesSorter implements sort.Interface to allow a slice of reflect.Value -// elements to be sorted. -type valuesSorter struct { - values []reflect.Value - strings []string // either nil or same len and values - cs *ConfigState -} - -// newValuesSorter initializes a valuesSorter instance, which holds a set of -// surrogate keys on which the data should be sorted. It uses flags in -// ConfigState to decide if and how to populate those surrogate keys. -func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { - vs := &valuesSorter{values: values, cs: cs} - if canSortSimply(vs.values[0].Kind()) { - return vs - } - if !cs.DisableMethods { - vs.strings = make([]string, len(values)) - for i := range vs.values { - b := bytes.Buffer{} - if !handleMethods(cs, &b, vs.values[i]) { - vs.strings = nil - break - } - vs.strings[i] = b.String() - } - } - if vs.strings == nil && cs.SpewKeys { - vs.strings = make([]string, len(values)) - for i := range vs.values { - vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) - } - } - return vs -} - -// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted -// directly, or whether it should be considered for sorting by surrogate keys -// (if the ConfigState allows it). -func canSortSimply(kind reflect.Kind) bool { - // This switch parallels valueSortLess, except for the default case. - switch kind { - case reflect.Bool: - return true - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return true - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - return true - case reflect.Float32, reflect.Float64: - return true - case reflect.String: - return true - case reflect.Uintptr: - return true - case reflect.Array: - return true - } - return false -} - -// Len returns the number of values in the slice. It is part of the -// sort.Interface implementation. -func (s *valuesSorter) Len() int { - return len(s.values) -} - -// Swap swaps the values at the passed indices. It is part of the -// sort.Interface implementation. -func (s *valuesSorter) Swap(i, j int) { - s.values[i], s.values[j] = s.values[j], s.values[i] - if s.strings != nil { - s.strings[i], s.strings[j] = s.strings[j], s.strings[i] - } -} - -// valueSortLess returns whether the first value should sort before the second -// value. It is used by valueSorter.Less as part of the sort.Interface -// implementation. -func valueSortLess(a, b reflect.Value) bool { - switch a.Kind() { - case reflect.Bool: - return !a.Bool() && b.Bool() - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return a.Int() < b.Int() - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - return a.Uint() < b.Uint() - case reflect.Float32, reflect.Float64: - return a.Float() < b.Float() - case reflect.String: - return a.String() < b.String() - case reflect.Uintptr: - return a.Uint() < b.Uint() - case reflect.Array: - // Compare the contents of both arrays. - l := a.Len() - for i := 0; i < l; i++ { - av := a.Index(i) - bv := b.Index(i) - if av.Interface() == bv.Interface() { - continue - } - return valueSortLess(av, bv) - } - } - return a.String() < b.String() -} - -// Less returns whether the value at index i should sort before the -// value at index j. It is part of the sort.Interface implementation. -func (s *valuesSorter) Less(i, j int) bool { - if s.strings == nil { - return valueSortLess(s.values[i], s.values[j]) - } - return s.strings[i] < s.strings[j] -} - -// sortValues is a sort function that handles both native types and any type that -// can be converted to error or Stringer. Other inputs are sorted according to -// their Value.String() value to ensure display stability. -func sortValues(values []reflect.Value, cs *ConfigState) { - if len(values) == 0 { - return - } - sort.Sort(newValuesSorter(values, cs)) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go deleted file mode 100644 index 2e3d22f3..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/config.go +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "io" - "os" -) - -// ConfigState houses the configuration options used by spew to format and -// display values. There is a global instance, Config, that is used to control -// all top-level Formatter and Dump functionality. Each ConfigState instance -// provides methods equivalent to the top-level functions. -// -// The zero value for ConfigState provides no indentation. You would typically -// want to set it to a space or a tab. -// -// Alternatively, you can use NewDefaultConfig to get a ConfigState instance -// with default settings. See the documentation of NewDefaultConfig for default -// values. -type ConfigState struct { - // Indent specifies the string to use for each indentation level. The - // global config instance that all top-level functions use set this to a - // single space by default. If you would like more indentation, you might - // set this to a tab with "\t" or perhaps two spaces with " ". - Indent string - - // MaxDepth controls the maximum number of levels to descend into nested - // data structures. The default, 0, means there is no limit. - // - // NOTE: Circular data structures are properly detected, so it is not - // necessary to set this value unless you specifically want to limit deeply - // nested data structures. - MaxDepth int - - // DisableMethods specifies whether or not error and Stringer interfaces are - // invoked for types that implement them. - DisableMethods bool - - // DisablePointerMethods specifies whether or not to check for and invoke - // error and Stringer interfaces on types which only accept a pointer - // receiver when the current type is not a pointer. - // - // NOTE: This might be an unsafe action since calling one of these methods - // with a pointer receiver could technically mutate the value, however, - // in practice, types which choose to satisify an error or Stringer - // interface with a pointer receiver should not be mutating their state - // inside these interface methods. As a result, this option relies on - // access to the unsafe package, so it will not have any effect when - // running in environments without access to the unsafe package such as - // Google App Engine or with the "safe" build tag specified. - DisablePointerMethods bool - - // DisablePointerAddresses specifies whether to disable the printing of - // pointer addresses. This is useful when diffing data structures in tests. - DisablePointerAddresses bool - - // DisableCapacities specifies whether to disable the printing of capacities - // for arrays, slices, maps and channels. This is useful when diffing - // data structures in tests. - DisableCapacities bool - - // ContinueOnMethod specifies whether or not recursion should continue once - // a custom error or Stringer interface is invoked. The default, false, - // means it will print the results of invoking the custom error or Stringer - // interface and return immediately instead of continuing to recurse into - // the internals of the data type. - // - // NOTE: This flag does not have any effect if method invocation is disabled - // via the DisableMethods or DisablePointerMethods options. - ContinueOnMethod bool - - // SortKeys specifies map keys should be sorted before being printed. Use - // this to have a more deterministic, diffable output. Note that only - // native types (bool, int, uint, floats, uintptr and string) and types - // that support the error or Stringer interfaces (if methods are - // enabled) are supported, with other types sorted according to the - // reflect.Value.String() output which guarantees display stability. - SortKeys bool - - // SpewKeys specifies that, as a last resort attempt, map keys should - // be spewed to strings and sorted by those strings. This is only - // considered if SortKeys is true. - SpewKeys bool -} - -// Config is the active configuration of the top-level functions. -// The configuration can be changed by modifying the contents of spew.Config. -var Config = ConfigState{Indent: " "} - -// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the formatted string as a value that satisfies error. See NewFormatter -// for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { - return fmt.Errorf(format, c.convertArgs(a)...) -} - -// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprint(w, c.convertArgs(a)...) -} - -// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, format, c.convertArgs(a)...) -} - -// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it -// passed with a Formatter interface returned by c.NewFormatter. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprintln(w, c.convertArgs(a)...) -} - -// Print is a wrapper for fmt.Print that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Print(a ...interface{}) (n int, err error) { - return fmt.Print(c.convertArgs(a)...) -} - -// Printf is a wrapper for fmt.Printf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(format, c.convertArgs(a)...) -} - -// Println is a wrapper for fmt.Println that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Println(a ...interface{}) (n int, err error) { - return fmt.Println(c.convertArgs(a)...) -} - -// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprint(a ...interface{}) string { - return fmt.Sprint(c.convertArgs(a)...) -} - -// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, c.convertArgs(a)...) -} - -// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it -// were passed with a Formatter interface returned by c.NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprintln(a ...interface{}) string { - return fmt.Sprintln(c.convertArgs(a)...) -} - -/* -NewFormatter returns a custom formatter that satisfies the fmt.Formatter -interface. As a result, it integrates cleanly with standard fmt package -printing functions. The formatter is useful for inline printing of smaller data -types similar to the standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Typically this function shouldn't be called directly. It is much easier to make -use of the custom formatter by calling one of the convenience functions such as -c.Printf, c.Println, or c.Printf. -*/ -func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { - return newFormatter(c, v) -} - -// Fdump formats and displays the passed arguments to io.Writer w. It formats -// exactly the same as Dump. -func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { - fdump(c, w, a...) -} - -/* -Dump displays the passed parameters to standard out with newlines, customizable -indentation, and additional debug information such as complete types and all -pointer addresses used to indirect to the final value. It provides the -following features over the built-in printing facilities provided by the fmt -package: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output - -The configuration options are controlled by modifying the public members -of c. See ConfigState for options documentation. - -See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to -get the formatted result as a string. -*/ -func (c *ConfigState) Dump(a ...interface{}) { - fdump(c, os.Stdout, a...) -} - -// Sdump returns a string with the passed arguments formatted exactly the same -// as Dump. -func (c *ConfigState) Sdump(a ...interface{}) string { - var buf bytes.Buffer - fdump(c, &buf, a...) - return buf.String() -} - -// convertArgs accepts a slice of arguments and returns a slice of the same -// length with each argument converted to a spew Formatter interface using -// the ConfigState associated with s. -func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { - formatters = make([]interface{}, len(args)) - for index, arg := range args { - formatters[index] = newFormatter(c, arg) - } - return formatters -} - -// NewDefaultConfig returns a ConfigState with the following default settings. -// -// Indent: " " -// MaxDepth: 0 -// DisableMethods: false -// DisablePointerMethods: false -// ContinueOnMethod: false -// SortKeys: false -func NewDefaultConfig() *ConfigState { - return &ConfigState{Indent: " "} -} diff --git a/vendor/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/davecgh/go-spew/spew/doc.go deleted file mode 100644 index aacaac6f..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/doc.go +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Package spew implements a deep pretty printer for Go data structures to aid in -debugging. - -A quick overview of the additional features spew provides over the built-in -printing facilities for Go data types are as follows: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output (only when using - Dump style) - -There are two different approaches spew allows for dumping Go data structures: - - * Dump style which prints with newlines, customizable indentation, - and additional debug information such as types and all pointer addresses - used to indirect to the final value - * A custom Formatter interface that integrates cleanly with the standard fmt - package and replaces %v, %+v, %#v, and %#+v to provide inline printing - similar to the default %v while providing the additional functionality - outlined above and passing unsupported format verbs such as %x and %q - along to fmt - -Quick Start - -This section demonstrates how to quickly get started with spew. See the -sections below for further details on formatting and configuration options. - -To dump a variable with full newlines, indentation, type, and pointer -information use Dump, Fdump, or Sdump: - spew.Dump(myVar1, myVar2, ...) - spew.Fdump(someWriter, myVar1, myVar2, ...) - str := spew.Sdump(myVar1, myVar2, ...) - -Alternatively, if you would prefer to use format strings with a compacted inline -printing style, use the convenience wrappers Printf, Fprintf, etc with -%v (most compact), %+v (adds pointer addresses), %#v (adds types), or -%#+v (adds types and pointer addresses): - spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - -Configuration Options - -Configuration of spew is handled by fields in the ConfigState type. For -convenience, all of the top-level functions use a global state available -via the spew.Config global. - -It is also possible to create a ConfigState instance that provides methods -equivalent to the top-level functions. This allows concurrent configuration -options. See the ConfigState documentation for more details. - -The following configuration options are available: - * Indent - String to use for each indentation level for Dump functions. - It is a single space by default. A popular alternative is "\t". - - * MaxDepth - Maximum number of levels to descend into nested data structures. - There is no limit by default. - - * DisableMethods - Disables invocation of error and Stringer interface methods. - Method invocation is enabled by default. - - * DisablePointerMethods - Disables invocation of error and Stringer interface methods on types - which only accept pointer receivers from non-pointer variables. - Pointer method invocation is enabled by default. - - * DisablePointerAddresses - DisablePointerAddresses specifies whether to disable the printing of - pointer addresses. This is useful when diffing data structures in tests. - - * DisableCapacities - DisableCapacities specifies whether to disable the printing of - capacities for arrays, slices, maps and channels. This is useful when - diffing data structures in tests. - - * ContinueOnMethod - Enables recursion into types after invoking error and Stringer interface - methods. Recursion after method invocation is disabled by default. - - * SortKeys - Specifies map keys should be sorted before being printed. Use - this to have a more deterministic, diffable output. Note that - only native types (bool, int, uint, floats, uintptr and string) - and types which implement error or Stringer interfaces are - supported with other types sorted according to the - reflect.Value.String() output which guarantees display - stability. Natural map order is used by default. - - * SpewKeys - Specifies that, as a last resort attempt, map keys should be - spewed to strings and sorted by those strings. This is only - considered if SortKeys is true. - -Dump Usage - -Simply call spew.Dump with a list of variables you want to dump: - - spew.Dump(myVar1, myVar2, ...) - -You may also call spew.Fdump if you would prefer to output to an arbitrary -io.Writer. For example, to dump to standard error: - - spew.Fdump(os.Stderr, myVar1, myVar2, ...) - -A third option is to call spew.Sdump to get the formatted output as a string: - - str := spew.Sdump(myVar1, myVar2, ...) - -Sample Dump Output - -See the Dump example for details on the setup of the types and variables being -shown here. - - (main.Foo) { - unexportedField: (*main.Bar)(0xf84002e210)({ - flag: (main.Flag) flagTwo, - data: (uintptr) - }), - ExportedField: (map[interface {}]interface {}) (len=1) { - (string) (len=3) "one": (bool) true - } - } - -Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C -command as shown. - ([]uint8) (len=32 cap=32) { - 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - 00000020 31 32 |12| - } - -Custom Formatter - -Spew provides a custom formatter that implements the fmt.Formatter interface -so that it integrates cleanly with standard fmt package printing functions. The -formatter is useful for inline printing of smaller data types similar to the -standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Custom Formatter Usage - -The simplest way to make use of the spew custom formatter is to call one of the -convenience functions such as spew.Printf, spew.Println, or spew.Printf. The -functions have syntax you are most likely already familiar with: - - spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - spew.Println(myVar, myVar2) - spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - -See the Index for the full list convenience functions. - -Sample Formatter Output - -Double pointer to a uint8: - %v: <**>5 - %+v: <**>(0xf8400420d0->0xf8400420c8)5 - %#v: (**uint8)5 - %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 - -Pointer to circular struct with a uint8 field and a pointer to itself: - %v: <*>{1 <*>} - %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} - %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} - %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} - -See the Printf example for details on the setup of variables being shown -here. - -Errors - -Since it is possible for custom Stringer/error interfaces to panic, spew -detects them and handles them internally by printing the panic information -inline with the output. Since spew is intended to provide deep pretty printing -capabilities on structures, it intentionally does not return any errors. -*/ -package spew diff --git a/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go deleted file mode 100644 index f78d89fc..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/dump.go +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "encoding/hex" - "fmt" - "io" - "os" - "reflect" - "regexp" - "strconv" - "strings" -) - -var ( - // uint8Type is a reflect.Type representing a uint8. It is used to - // convert cgo types to uint8 slices for hexdumping. - uint8Type = reflect.TypeOf(uint8(0)) - - // cCharRE is a regular expression that matches a cgo char. - // It is used to detect character arrays to hexdump them. - cCharRE = regexp.MustCompile(`^.*\._Ctype_char$`) - - // cUnsignedCharRE is a regular expression that matches a cgo unsigned - // char. It is used to detect unsigned character arrays to hexdump - // them. - cUnsignedCharRE = regexp.MustCompile(`^.*\._Ctype_unsignedchar$`) - - // cUint8tCharRE is a regular expression that matches a cgo uint8_t. - // It is used to detect uint8_t arrays to hexdump them. - cUint8tCharRE = regexp.MustCompile(`^.*\._Ctype_uint8_t$`) -) - -// dumpState contains information about the state of a dump operation. -type dumpState struct { - w io.Writer - depth int - pointers map[uintptr]int - ignoreNextType bool - ignoreNextIndent bool - cs *ConfigState -} - -// indent performs indentation according to the depth level and cs.Indent -// option. -func (d *dumpState) indent() { - if d.ignoreNextIndent { - d.ignoreNextIndent = false - return - } - d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) -} - -// unpackValue returns values inside of non-nil interfaces when possible. -// This is useful for data types like structs, arrays, slices, and maps which -// can contain varying types packed inside an interface. -func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { - if v.Kind() == reflect.Interface && !v.IsNil() { - v = v.Elem() - } - return v -} - -// dumpPtr handles formatting of pointers by indirecting them as necessary. -func (d *dumpState) dumpPtr(v reflect.Value) { - // Remove pointers at or below the current depth from map used to detect - // circular refs. - for k, depth := range d.pointers { - if depth >= d.depth { - delete(d.pointers, k) - } - } - - // Keep list of all dereferenced pointers to show later. - pointerChain := make([]uintptr, 0) - - // Figure out how many levels of indirection there are by dereferencing - // pointers and unpacking interfaces down the chain while detecting circular - // references. - nilFound := false - cycleFound := false - indirects := 0 - ve := v - for ve.Kind() == reflect.Ptr { - if ve.IsNil() { - nilFound = true - break - } - indirects++ - addr := ve.Pointer() - pointerChain = append(pointerChain, addr) - if pd, ok := d.pointers[addr]; ok && pd < d.depth { - cycleFound = true - indirects-- - break - } - d.pointers[addr] = d.depth - - ve = ve.Elem() - if ve.Kind() == reflect.Interface { - if ve.IsNil() { - nilFound = true - break - } - ve = ve.Elem() - } - } - - // Display type information. - d.w.Write(openParenBytes) - d.w.Write(bytes.Repeat(asteriskBytes, indirects)) - d.w.Write([]byte(ve.Type().String())) - d.w.Write(closeParenBytes) - - // Display pointer information. - if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { - d.w.Write(openParenBytes) - for i, addr := range pointerChain { - if i > 0 { - d.w.Write(pointerChainBytes) - } - printHexPtr(d.w, addr) - } - d.w.Write(closeParenBytes) - } - - // Display dereferenced value. - d.w.Write(openParenBytes) - switch { - case nilFound: - d.w.Write(nilAngleBytes) - - case cycleFound: - d.w.Write(circularBytes) - - default: - d.ignoreNextType = true - d.dump(ve) - } - d.w.Write(closeParenBytes) -} - -// dumpSlice handles formatting of arrays and slices. Byte (uint8 under -// reflection) arrays and slices are dumped in hexdump -C fashion. -func (d *dumpState) dumpSlice(v reflect.Value) { - // Determine whether this type should be hex dumped or not. Also, - // for types which should be hexdumped, try to use the underlying data - // first, then fall back to trying to convert them to a uint8 slice. - var buf []uint8 - doConvert := false - doHexDump := false - numEntries := v.Len() - if numEntries > 0 { - vt := v.Index(0).Type() - vts := vt.String() - switch { - // C types that need to be converted. - case cCharRE.MatchString(vts): - fallthrough - case cUnsignedCharRE.MatchString(vts): - fallthrough - case cUint8tCharRE.MatchString(vts): - doConvert = true - - // Try to use existing uint8 slices and fall back to converting - // and copying if that fails. - case vt.Kind() == reflect.Uint8: - // We need an addressable interface to convert the type - // to a byte slice. However, the reflect package won't - // give us an interface on certain things like - // unexported struct fields in order to enforce - // visibility rules. We use unsafe, when available, to - // bypass these restrictions since this package does not - // mutate the values. - vs := v - if !vs.CanInterface() || !vs.CanAddr() { - vs = unsafeReflectValue(vs) - } - if !UnsafeDisabled { - vs = vs.Slice(0, numEntries) - - // Use the existing uint8 slice if it can be - // type asserted. - iface := vs.Interface() - if slice, ok := iface.([]uint8); ok { - buf = slice - doHexDump = true - break - } - } - - // The underlying data needs to be converted if it can't - // be type asserted to a uint8 slice. - doConvert = true - } - - // Copy and convert the underlying type if needed. - if doConvert && vt.ConvertibleTo(uint8Type) { - // Convert and copy each element into a uint8 byte - // slice. - buf = make([]uint8, numEntries) - for i := 0; i < numEntries; i++ { - vv := v.Index(i) - buf[i] = uint8(vv.Convert(uint8Type).Uint()) - } - doHexDump = true - } - } - - // Hexdump the entire slice as needed. - if doHexDump { - indent := strings.Repeat(d.cs.Indent, d.depth) - str := indent + hex.Dump(buf) - str = strings.Replace(str, "\n", "\n"+indent, -1) - str = strings.TrimRight(str, d.cs.Indent) - d.w.Write([]byte(str)) - return - } - - // Recursively call dump for each item. - for i := 0; i < numEntries; i++ { - d.dump(d.unpackValue(v.Index(i))) - if i < (numEntries - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } -} - -// dump is the main workhorse for dumping a value. It uses the passed reflect -// value to figure out what kind of object we are dealing with and formats it -// appropriately. It is a recursive function, however circular data structures -// are detected and handled properly. -func (d *dumpState) dump(v reflect.Value) { - // Handle invalid reflect values immediately. - kind := v.Kind() - if kind == reflect.Invalid { - d.w.Write(invalidAngleBytes) - return - } - - // Handle pointers specially. - if kind == reflect.Ptr { - d.indent() - d.dumpPtr(v) - return - } - - // Print type information unless already handled elsewhere. - if !d.ignoreNextType { - d.indent() - d.w.Write(openParenBytes) - d.w.Write([]byte(v.Type().String())) - d.w.Write(closeParenBytes) - d.w.Write(spaceBytes) - } - d.ignoreNextType = false - - // Display length and capacity if the built-in len and cap functions - // work with the value's kind and the len/cap itself is non-zero. - valueLen, valueCap := 0, 0 - switch v.Kind() { - case reflect.Array, reflect.Slice, reflect.Chan: - valueLen, valueCap = v.Len(), v.Cap() - case reflect.Map, reflect.String: - valueLen = v.Len() - } - if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { - d.w.Write(openParenBytes) - if valueLen != 0 { - d.w.Write(lenEqualsBytes) - printInt(d.w, int64(valueLen), 10) - } - if !d.cs.DisableCapacities && valueCap != 0 { - if valueLen != 0 { - d.w.Write(spaceBytes) - } - d.w.Write(capEqualsBytes) - printInt(d.w, int64(valueCap), 10) - } - d.w.Write(closeParenBytes) - d.w.Write(spaceBytes) - } - - // Call Stringer/error interfaces if they exist and the handle methods flag - // is enabled - if !d.cs.DisableMethods { - if (kind != reflect.Invalid) && (kind != reflect.Interface) { - if handled := handleMethods(d.cs, d.w, v); handled { - return - } - } - } - - switch kind { - case reflect.Invalid: - // Do nothing. We should never get here since invalid has already - // been handled above. - - case reflect.Bool: - printBool(d.w, v.Bool()) - - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - printInt(d.w, v.Int(), 10) - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - printUint(d.w, v.Uint(), 10) - - case reflect.Float32: - printFloat(d.w, v.Float(), 32) - - case reflect.Float64: - printFloat(d.w, v.Float(), 64) - - case reflect.Complex64: - printComplex(d.w, v.Complex(), 32) - - case reflect.Complex128: - printComplex(d.w, v.Complex(), 64) - - case reflect.Slice: - if v.IsNil() { - d.w.Write(nilAngleBytes) - break - } - fallthrough - - case reflect.Array: - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - d.dumpSlice(v) - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.String: - d.w.Write([]byte(strconv.Quote(v.String()))) - - case reflect.Interface: - // The only time we should get here is for nil interfaces due to - // unpackValue calls. - if v.IsNil() { - d.w.Write(nilAngleBytes) - } - - case reflect.Ptr: - // Do nothing. We should never get here since pointers have already - // been handled above. - - case reflect.Map: - // nil maps should be indicated as different than empty maps - if v.IsNil() { - d.w.Write(nilAngleBytes) - break - } - - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - numEntries := v.Len() - keys := v.MapKeys() - if d.cs.SortKeys { - sortValues(keys, d.cs) - } - for i, key := range keys { - d.dump(d.unpackValue(key)) - d.w.Write(colonSpaceBytes) - d.ignoreNextIndent = true - d.dump(d.unpackValue(v.MapIndex(key))) - if i < (numEntries - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.Struct: - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - vt := v.Type() - numFields := v.NumField() - for i := 0; i < numFields; i++ { - d.indent() - vtf := vt.Field(i) - d.w.Write([]byte(vtf.Name)) - d.w.Write(colonSpaceBytes) - d.ignoreNextIndent = true - d.dump(d.unpackValue(v.Field(i))) - if i < (numFields - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.Uintptr: - printHexPtr(d.w, uintptr(v.Uint())) - - case reflect.UnsafePointer, reflect.Chan, reflect.Func: - printHexPtr(d.w, v.Pointer()) - - // There were not any other types at the time this code was written, but - // fall back to letting the default fmt package handle it in case any new - // types are added. - default: - if v.CanInterface() { - fmt.Fprintf(d.w, "%v", v.Interface()) - } else { - fmt.Fprintf(d.w, "%v", v.String()) - } - } -} - -// fdump is a helper function to consolidate the logic from the various public -// methods which take varying writers and config states. -func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { - for _, arg := range a { - if arg == nil { - w.Write(interfaceBytes) - w.Write(spaceBytes) - w.Write(nilAngleBytes) - w.Write(newlineBytes) - continue - } - - d := dumpState{w: w, cs: cs} - d.pointers = make(map[uintptr]int) - d.dump(reflect.ValueOf(arg)) - d.w.Write(newlineBytes) - } -} - -// Fdump formats and displays the passed arguments to io.Writer w. It formats -// exactly the same as Dump. -func Fdump(w io.Writer, a ...interface{}) { - fdump(&Config, w, a...) -} - -// Sdump returns a string with the passed arguments formatted exactly the same -// as Dump. -func Sdump(a ...interface{}) string { - var buf bytes.Buffer - fdump(&Config, &buf, a...) - return buf.String() -} - -/* -Dump displays the passed parameters to standard out with newlines, customizable -indentation, and additional debug information such as complete types and all -pointer addresses used to indirect to the final value. It provides the -following features over the built-in printing facilities provided by the fmt -package: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output - -The configuration options are controlled by an exported package global, -spew.Config. See ConfigState for options documentation. - -See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to -get the formatted result as a string. -*/ -func Dump(a ...interface{}) { - fdump(&Config, os.Stdout, a...) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go deleted file mode 100644 index b04edb7d..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/format.go +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "reflect" - "strconv" - "strings" -) - -// supportedFlags is a list of all the character flags supported by fmt package. -const supportedFlags = "0-+# " - -// formatState implements the fmt.Formatter interface and contains information -// about the state of a formatting operation. The NewFormatter function can -// be used to get a new Formatter which can be used directly as arguments -// in standard fmt package printing calls. -type formatState struct { - value interface{} - fs fmt.State - depth int - pointers map[uintptr]int - ignoreNextType bool - cs *ConfigState -} - -// buildDefaultFormat recreates the original format string without precision -// and width information to pass in to fmt.Sprintf in the case of an -// unrecognized type. Unless new types are added to the language, this -// function won't ever be called. -func (f *formatState) buildDefaultFormat() (format string) { - buf := bytes.NewBuffer(percentBytes) - - for _, flag := range supportedFlags { - if f.fs.Flag(int(flag)) { - buf.WriteRune(flag) - } - } - - buf.WriteRune('v') - - format = buf.String() - return format -} - -// constructOrigFormat recreates the original format string including precision -// and width information to pass along to the standard fmt package. This allows -// automatic deferral of all format strings this package doesn't support. -func (f *formatState) constructOrigFormat(verb rune) (format string) { - buf := bytes.NewBuffer(percentBytes) - - for _, flag := range supportedFlags { - if f.fs.Flag(int(flag)) { - buf.WriteRune(flag) - } - } - - if width, ok := f.fs.Width(); ok { - buf.WriteString(strconv.Itoa(width)) - } - - if precision, ok := f.fs.Precision(); ok { - buf.Write(precisionBytes) - buf.WriteString(strconv.Itoa(precision)) - } - - buf.WriteRune(verb) - - format = buf.String() - return format -} - -// unpackValue returns values inside of non-nil interfaces when possible and -// ensures that types for values which have been unpacked from an interface -// are displayed when the show types flag is also set. -// This is useful for data types like structs, arrays, slices, and maps which -// can contain varying types packed inside an interface. -func (f *formatState) unpackValue(v reflect.Value) reflect.Value { - if v.Kind() == reflect.Interface { - f.ignoreNextType = false - if !v.IsNil() { - v = v.Elem() - } - } - return v -} - -// formatPtr handles formatting of pointers by indirecting them as necessary. -func (f *formatState) formatPtr(v reflect.Value) { - // Display nil if top level pointer is nil. - showTypes := f.fs.Flag('#') - if v.IsNil() && (!showTypes || f.ignoreNextType) { - f.fs.Write(nilAngleBytes) - return - } - - // Remove pointers at or below the current depth from map used to detect - // circular refs. - for k, depth := range f.pointers { - if depth >= f.depth { - delete(f.pointers, k) - } - } - - // Keep list of all dereferenced pointers to possibly show later. - pointerChain := make([]uintptr, 0) - - // Figure out how many levels of indirection there are by derferencing - // pointers and unpacking interfaces down the chain while detecting circular - // references. - nilFound := false - cycleFound := false - indirects := 0 - ve := v - for ve.Kind() == reflect.Ptr { - if ve.IsNil() { - nilFound = true - break - } - indirects++ - addr := ve.Pointer() - pointerChain = append(pointerChain, addr) - if pd, ok := f.pointers[addr]; ok && pd < f.depth { - cycleFound = true - indirects-- - break - } - f.pointers[addr] = f.depth - - ve = ve.Elem() - if ve.Kind() == reflect.Interface { - if ve.IsNil() { - nilFound = true - break - } - ve = ve.Elem() - } - } - - // Display type or indirection level depending on flags. - if showTypes && !f.ignoreNextType { - f.fs.Write(openParenBytes) - f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) - f.fs.Write([]byte(ve.Type().String())) - f.fs.Write(closeParenBytes) - } else { - if nilFound || cycleFound { - indirects += strings.Count(ve.Type().String(), "*") - } - f.fs.Write(openAngleBytes) - f.fs.Write([]byte(strings.Repeat("*", indirects))) - f.fs.Write(closeAngleBytes) - } - - // Display pointer information depending on flags. - if f.fs.Flag('+') && (len(pointerChain) > 0) { - f.fs.Write(openParenBytes) - for i, addr := range pointerChain { - if i > 0 { - f.fs.Write(pointerChainBytes) - } - printHexPtr(f.fs, addr) - } - f.fs.Write(closeParenBytes) - } - - // Display dereferenced value. - switch { - case nilFound: - f.fs.Write(nilAngleBytes) - - case cycleFound: - f.fs.Write(circularShortBytes) - - default: - f.ignoreNextType = true - f.format(ve) - } -} - -// format is the main workhorse for providing the Formatter interface. It -// uses the passed reflect value to figure out what kind of object we are -// dealing with and formats it appropriately. It is a recursive function, -// however circular data structures are detected and handled properly. -func (f *formatState) format(v reflect.Value) { - // Handle invalid reflect values immediately. - kind := v.Kind() - if kind == reflect.Invalid { - f.fs.Write(invalidAngleBytes) - return - } - - // Handle pointers specially. - if kind == reflect.Ptr { - f.formatPtr(v) - return - } - - // Print type information unless already handled elsewhere. - if !f.ignoreNextType && f.fs.Flag('#') { - f.fs.Write(openParenBytes) - f.fs.Write([]byte(v.Type().String())) - f.fs.Write(closeParenBytes) - } - f.ignoreNextType = false - - // Call Stringer/error interfaces if they exist and the handle methods - // flag is enabled. - if !f.cs.DisableMethods { - if (kind != reflect.Invalid) && (kind != reflect.Interface) { - if handled := handleMethods(f.cs, f.fs, v); handled { - return - } - } - } - - switch kind { - case reflect.Invalid: - // Do nothing. We should never get here since invalid has already - // been handled above. - - case reflect.Bool: - printBool(f.fs, v.Bool()) - - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - printInt(f.fs, v.Int(), 10) - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - printUint(f.fs, v.Uint(), 10) - - case reflect.Float32: - printFloat(f.fs, v.Float(), 32) - - case reflect.Float64: - printFloat(f.fs, v.Float(), 64) - - case reflect.Complex64: - printComplex(f.fs, v.Complex(), 32) - - case reflect.Complex128: - printComplex(f.fs, v.Complex(), 64) - - case reflect.Slice: - if v.IsNil() { - f.fs.Write(nilAngleBytes) - break - } - fallthrough - - case reflect.Array: - f.fs.Write(openBracketBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - numEntries := v.Len() - for i := 0; i < numEntries; i++ { - if i > 0 { - f.fs.Write(spaceBytes) - } - f.ignoreNextType = true - f.format(f.unpackValue(v.Index(i))) - } - } - f.depth-- - f.fs.Write(closeBracketBytes) - - case reflect.String: - f.fs.Write([]byte(v.String())) - - case reflect.Interface: - // The only time we should get here is for nil interfaces due to - // unpackValue calls. - if v.IsNil() { - f.fs.Write(nilAngleBytes) - } - - case reflect.Ptr: - // Do nothing. We should never get here since pointers have already - // been handled above. - - case reflect.Map: - // nil maps should be indicated as different than empty maps - if v.IsNil() { - f.fs.Write(nilAngleBytes) - break - } - - f.fs.Write(openMapBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - keys := v.MapKeys() - if f.cs.SortKeys { - sortValues(keys, f.cs) - } - for i, key := range keys { - if i > 0 { - f.fs.Write(spaceBytes) - } - f.ignoreNextType = true - f.format(f.unpackValue(key)) - f.fs.Write(colonBytes) - f.ignoreNextType = true - f.format(f.unpackValue(v.MapIndex(key))) - } - } - f.depth-- - f.fs.Write(closeMapBytes) - - case reflect.Struct: - numFields := v.NumField() - f.fs.Write(openBraceBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - vt := v.Type() - for i := 0; i < numFields; i++ { - if i > 0 { - f.fs.Write(spaceBytes) - } - vtf := vt.Field(i) - if f.fs.Flag('+') || f.fs.Flag('#') { - f.fs.Write([]byte(vtf.Name)) - f.fs.Write(colonBytes) - } - f.format(f.unpackValue(v.Field(i))) - } - } - f.depth-- - f.fs.Write(closeBraceBytes) - - case reflect.Uintptr: - printHexPtr(f.fs, uintptr(v.Uint())) - - case reflect.UnsafePointer, reflect.Chan, reflect.Func: - printHexPtr(f.fs, v.Pointer()) - - // There were not any other types at the time this code was written, but - // fall back to letting the default fmt package handle it if any get added. - default: - format := f.buildDefaultFormat() - if v.CanInterface() { - fmt.Fprintf(f.fs, format, v.Interface()) - } else { - fmt.Fprintf(f.fs, format, v.String()) - } - } -} - -// Format satisfies the fmt.Formatter interface. See NewFormatter for usage -// details. -func (f *formatState) Format(fs fmt.State, verb rune) { - f.fs = fs - - // Use standard formatting for verbs that are not v. - if verb != 'v' { - format := f.constructOrigFormat(verb) - fmt.Fprintf(fs, format, f.value) - return - } - - if f.value == nil { - if fs.Flag('#') { - fs.Write(interfaceBytes) - } - fs.Write(nilAngleBytes) - return - } - - f.format(reflect.ValueOf(f.value)) -} - -// newFormatter is a helper function to consolidate the logic from the various -// public methods which take varying config states. -func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { - fs := &formatState{value: v, cs: cs} - fs.pointers = make(map[uintptr]int) - return fs -} - -/* -NewFormatter returns a custom formatter that satisfies the fmt.Formatter -interface. As a result, it integrates cleanly with standard fmt package -printing functions. The formatter is useful for inline printing of smaller data -types similar to the standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Typically this function shouldn't be called directly. It is much easier to make -use of the custom formatter by calling one of the convenience functions such as -Printf, Println, or Fprintf. -*/ -func NewFormatter(v interface{}) fmt.Formatter { - return newFormatter(&Config, v) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/spew.go b/vendor/github.com/davecgh/go-spew/spew/spew.go deleted file mode 100644 index 32c0e338..00000000 --- a/vendor/github.com/davecgh/go-spew/spew/spew.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "fmt" - "io" -) - -// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the formatted string as a value that satisfies error. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Errorf(format string, a ...interface{}) (err error) { - return fmt.Errorf(format, convertArgs(a)...) -} - -// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprint(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprint(w, convertArgs(a)...) -} - -// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, format, convertArgs(a)...) -} - -// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it -// passed with a default Formatter interface returned by NewFormatter. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprintln(w, convertArgs(a)...) -} - -// Print is a wrapper for fmt.Print that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) -func Print(a ...interface{}) (n int, err error) { - return fmt.Print(convertArgs(a)...) -} - -// Printf is a wrapper for fmt.Printf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(format, convertArgs(a)...) -} - -// Println is a wrapper for fmt.Println that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) -func Println(a ...interface{}) (n int, err error) { - return fmt.Println(convertArgs(a)...) -} - -// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprint(a ...interface{}) string { - return fmt.Sprint(convertArgs(a)...) -} - -// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, convertArgs(a)...) -} - -// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it -// were passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprintln(a ...interface{}) string { - return fmt.Sprintln(convertArgs(a)...) -} - -// convertArgs accepts a slice of arguments and returns a slice of the same -// length with each argument converted to a default spew Formatter interface. -func convertArgs(args []interface{}) (formatters []interface{}) { - formatters = make([]interface{}, len(args)) - for index, arg := range args { - formatters[index] = NewFormatter(arg) - } - return formatters -} diff --git a/vendor/github.com/dghubble/sling/.travis.yml b/vendor/github.com/dghubble/sling/.travis.yml deleted file mode 100644 index a654faa1..00000000 --- a/vendor/github.com/dghubble/sling/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go -go: - - "1.10.x" - - "1.11.x" - - "1.12.x" -install: - - go get golang.org/x/lint/golint - - go get -v -t . -script: - - make -notifications: - email: change diff --git a/vendor/github.com/dghubble/sling/CHANGES.md b/vendor/github.com/dghubble/sling/CHANGES.md deleted file mode 100644 index 0abb2e51..00000000 --- a/vendor/github.com/dghubble/sling/CHANGES.md +++ /dev/null @@ -1,68 +0,0 @@ -# Sling Changelog - -Notable changes between releases. - -## Latest - -## v1.3.0 - -* Add Sling `ResponseDecoder` setter for receiving responses with a custom `ResponseDecoder` ([#49](https://github.com/dghubble/sling/pull/49)) -* Add Go module support (i.e. `go.mod`). Exclude `examples` (multi-module). ([#52](https://github.com/dghubble/sling/pull/52)) - -## v1.2.0 - -* Add `Connect`, `Options`, and `Trace` HTTP methods ([c51967](https://github.com/dghubble/sling/commit/c519674860ff275e0ceb12caf5d87b31765c4e71)) -* Skip receiving (i.e. decoding) `204 No Content` responses ([#31](https://github.com/dghubble/sling/pull/31)) - -## v1.1.0 - -* Allow JSON decoding, regardless of response Content-Type (#26) -* Add `BodyProvider` interface and setter so request Body encoding can be customized (#23) -* Add `Doer` interface and setter so request sending behavior can be customized (#21) -* Add `SetBasicAuth` setter for Authorization headers (#16) -* Add Sling `Body` setter to set an `io.Reader` on the Request (#9) - -## v1.0.0 - -* Added support for receiving and decoding error JSON structs -* Renamed Sling `JsonBody` setter to `BodyJSON` (breaking) -* Renamed Sling `BodyStruct` setter to `BodyForm` (breaking) -* Renamed Sling fields `httpClient`, `method`, `rawURL`, and `header` to be internal (breaking) -* Changed `Do` and `Receive` to skip response JSON decoding if "application/json" Content-Type is missing -* Changed `Sling.Receive(v interface{})` to `Sling.Receive(successV, failureV interface{})` (breaking) - * Previously `Receive` attempted to decode the response Body in all cases - * Updated `Receive` will decode the response Body into successV for 2XX responses or decode the Body into failureV for other status codes. Pass a nil `successV` or `failureV` to skip JSON decoding into that value. - * To upgrade, pass nil for the `failureV` argument or consider defining a JSON tagged struct appropriate for the API endpoint. (e.g. `s.Receive(&issue, nil)`, `s.Receive(&issue, &githubError)`) - * To retain the old behavior, duplicate the first argument (e.g. s.Receive(&tweet, &tweet)) -* Changed `Sling.Do(http.Request, v interface{})` to `Sling.Do(http.Request, successV, failureV interface{})` (breaking) - * See the changelog entry about `Receive`, the upgrade path is the same. -* Removed HEAD, GET, POST, PUT, PATCH, DELETE constants, no reason to export them (breaking) - -## v0.4.0 - -* Improved golint compliance -* Fixed typos and test printouts - -## v0.3.0 - -* Added BodyStruct method for setting a url encoded form body on the Request -* Added Add and Set methods for adding or setting Request Headers -* Added JsonBody method for setting JSON Request Body -* Improved examples and documentation - -## v0.2.0 - -* Added http.Client setter -* Added Sling.New() method to return a copy of a Sling -* Added Base setter and Path extension support -* Added method setters (Get, Post, Put, Patch, Delete, Head) -* Added support for encoding URL Query parameters -* Added example tiny Github API -* Changed v0.1.0 method signatures and names (breaking) -* Removed Go 1.0 support - -## v0.1.0 - -* Support decoding JSON responses. - - diff --git a/vendor/github.com/dghubble/sling/LICENSE b/vendor/github.com/dghubble/sling/LICENSE deleted file mode 100644 index 2718840d..00000000 --- a/vendor/github.com/dghubble/sling/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Dalton Hubble - -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. \ No newline at end of file diff --git a/vendor/github.com/dghubble/sling/Makefile b/vendor/github.com/dghubble/sling/Makefile deleted file mode 100644 index ca4e0698..00000000 --- a/vendor/github.com/dghubble/sling/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -.PHONY: all -all: test vet lint fmt - -.PHONY: test -test: - @go test . -cover - -.PHONY: vet -vet: - @go vet -all . - -.PHONY: lint -lint: - @golint -set_exit_status ./... - -.PHONY: fmt -fmt: - @test -z $$(go fmt ./...) - diff --git a/vendor/github.com/dghubble/sling/README.md b/vendor/github.com/dghubble/sling/README.md deleted file mode 100644 index ff793c60..00000000 --- a/vendor/github.com/dghubble/sling/README.md +++ /dev/null @@ -1,295 +0,0 @@ -# Sling [![Build Status](https://travis-ci.org/dghubble/sling.svg?branch=master)](https://travis-ci.org/dghubble/sling) [![GoDoc](https://godoc.org/github.com/dghubble/sling?status.svg)](https://godoc.org/github.com/dghubble/sling) - - -Sling is a Go HTTP client library for creating and sending API requests. - -Slings store HTTP Request properties to simplify sending requests and decoding responses. Check [usage](#usage) or the [examples](examples) to learn how to compose a Sling into your API client. - -### Features - -* Method Setters: Get/Post/Put/Patch/Delete/Head -* Add or Set Request Headers -* Base/Path: Extend a Sling for different endpoints -* Encode structs into URL query parameters -* Encode a form or JSON into the Request Body -* Receive JSON success or failure responses - -## Install - -``` -go get github.com/dghubble/sling -``` - -## Documentation - -Read [GoDoc](https://godoc.org/github.com/dghubble/sling) - -## Usage - -Use a Sling to set path, method, header, query, or body properties and create an `http.Request`. - -```go -type Params struct { - Count int `url:"count,omitempty"` -} -params := &Params{Count: 5} - -req, err := sling.New().Get("https://example.com").QueryStruct(params).Request() -client.Do(req) -``` - -### Path - -Use `Path` to set or extend the URL for created Requests. Extension means the path will be resolved relative to the existing URL. - -```go -// creates a GET request to https://example.com/foo/bar -req, err := sling.New().Base("https://example.com/").Path("foo/").Path("bar").Request() -``` - -Use `Get`, `Post`, `Put`, `Patch`, `Delete`, `Head`, `Options`, `Trace`, or `Connect` which are exactly the same as `Path` except they set the HTTP method too. - -```go -req, err := sling.New().Post("http://upload.com/gophers") -``` - -### Headers - -`Add` or `Set` headers for requests created by a Sling. - -```go -s := sling.New().Base(baseUrl).Set("User-Agent", "Gophergram API Client") -req, err := s.New().Get("gophergram/list").Request() -``` - -### Query - -#### QueryStruct - -Define [url tagged structs](https://godoc.org/github.com/google/go-querystring/query). Use `QueryStruct` to encode a struct as query parameters on requests. - -```go -// Github Issue Parameters -type IssueParams struct { - Filter string `url:"filter,omitempty"` - State string `url:"state,omitempty"` - Labels string `url:"labels,omitempty"` - Sort string `url:"sort,omitempty"` - Direction string `url:"direction,omitempty"` - Since string `url:"since,omitempty"` -} -``` - -```go -githubBase := sling.New().Base("https://api.github.com/").Client(httpClient) - -path := fmt.Sprintf("repos/%s/%s/issues", owner, repo) -params := &IssueParams{Sort: "updated", State: "open"} -req, err := githubBase.New().Get(path).QueryStruct(params).Request() -``` - -### Body - -#### JSON Body - -Define [JSON tagged structs](https://golang.org/pkg/encoding/json/). Use `BodyJSON` to JSON encode a struct as the Body on requests. - -```go -type IssueRequest struct { - Title string `json:"title,omitempty"` - Body string `json:"body,omitempty"` - Assignee string `json:"assignee,omitempty"` - Milestone int `json:"milestone,omitempty"` - Labels []string `json:"labels,omitempty"` -} -``` - -```go -githubBase := sling.New().Base("https://api.github.com/").Client(httpClient) -path := fmt.Sprintf("repos/%s/%s/issues", owner, repo) - -body := &IssueRequest{ - Title: "Test title", - Body: "Some issue", -} -req, err := githubBase.New().Post(path).BodyJSON(body).Request() -``` - -Requests will include an `application/json` Content-Type header. - -#### Form Body - -Define [url tagged structs](https://godoc.org/github.com/google/go-querystring/query). Use `BodyForm` to form url encode a struct as the Body on requests. - -```go -type StatusUpdateParams struct { - Status string `url:"status,omitempty"` - InReplyToStatusId int64 `url:"in_reply_to_status_id,omitempty"` - MediaIds []int64 `url:"media_ids,omitempty,comma"` -} -``` - -```go -tweetParams := &StatusUpdateParams{Status: "writing some Go"} -req, err := twitterBase.New().Post(path).BodyForm(tweetParams).Request() -``` - -Requests will include an `application/x-www-form-urlencoded` Content-Type header. - -#### Plain Body - -Use `Body` to set a plain `io.Reader` on requests created by a Sling. - -```go -body := strings.NewReader("raw body") -req, err := sling.New().Base("https://example.com").Body(body).Request() -``` - -Set a content type header, if desired (e.g. `Set("Content-Type", "text/plain")`). - -### Extend a Sling - -Each Sling creates a standard `http.Request` (e.g. with some path and query -params) each time `Request()` is called. You may wish to extend an existing Sling to minimize duplication (e.g. a common client or base url). - -Each Sling instance provides a `New()` method which creates an independent copy, so setting properties on the child won't mutate the parent Sling. - -```go -const twitterApi = "https://api.twitter.com/1.1/" -base := sling.New().Base(twitterApi).Client(authClient) - -// statuses/show.json Sling -tweetShowSling := base.New().Get("statuses/show.json").QueryStruct(params) -req, err := tweetShowSling.Request() - -// statuses/update.json Sling -tweetPostSling := base.New().Post("statuses/update.json").BodyForm(params) -req, err := tweetPostSling.Request() -``` - -Without the calls to `base.New()`, `tweetShowSling` and `tweetPostSling` would reference the base Sling and POST to -"https://api.twitter.com/1.1/statuses/show.json/statuses/update.json", which -is undesired. - -Recap: If you wish to *extend* a Sling, create a new child copy with `New()`. - -### Sending - -#### Receive - -Define a JSON struct to decode a type from 2XX success responses. Use `ReceiveSuccess(successV interface{})` to send a new Request and decode the response body into `successV` if it succeeds. - -```go -// Github Issue (abbreviated) -type Issue struct { - Title string `json:"title"` - Body string `json:"body"` -} -``` - -```go -issues := new([]Issue) -resp, err := githubBase.New().Get(path).QueryStruct(params).ReceiveSuccess(issues) -fmt.Println(issues, resp, err) -``` - -Most APIs return failure responses with JSON error details. To decode these, define success and failure JSON structs. Use `Receive(successV, failureV interface{})` to send a new Request that will automatically decode the response into the `successV` for 2XX responses or into `failureV` for non-2XX responses. - -```go -type GithubError struct { - Message string `json:"message"` - Errors []struct { - Resource string `json:"resource"` - Field string `json:"field"` - Code string `json:"code"` - } `json:"errors"` - DocumentationURL string `json:"documentation_url"` -} -``` - -```go -issues := new([]Issue) -githubError := new(GithubError) -resp, err := githubBase.New().Get(path).QueryStruct(params).Receive(issues, githubError) -fmt.Println(issues, githubError, resp, err) -``` - -Pass a nil `successV` or `failureV` argument to skip JSON decoding into that value. - -### Modify a Request - -Sling provides the raw http.Request so modifications can be made using standard net/http features. For example, in Go 1.7+ , add HTTP tracing to a request with a context: - -```go -req, err := sling.New().Get("https://example.com").QueryStruct(params).Request() -// handle error - -trace := &httptrace.ClientTrace{ - DNSDone: func(dnsInfo httptrace.DNSDoneInfo) { - fmt.Printf("DNS Info: %+v\n", dnsInfo) - }, - GotConn: func(connInfo httptrace.GotConnInfo) { - fmt.Printf("Got Conn: %+v\n", connInfo) - }, -} - -req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) -client.Do(req) -``` - -### Build an API - -APIs typically define an endpoint (also called a service) for each type of resource. For example, here is a tiny Github IssueService which [lists](https://developer.github.com/v3/issues/#list-issues-for-a-repository) repository issues. - -```go -const baseURL = "https://api.github.com/" - -type IssueService struct { - sling *sling.Sling -} - -func NewIssueService(httpClient *http.Client) *IssueService { - return &IssueService{ - sling: sling.New().Client(httpClient).Base(baseURL), - } -} - -func (s *IssueService) ListByRepo(owner, repo string, params *IssueListParams) ([]Issue, *http.Response, error) { - issues := new([]Issue) - githubError := new(GithubError) - path := fmt.Sprintf("repos/%s/%s/issues", owner, repo) - resp, err := s.sling.New().Get(path).QueryStruct(params).Receive(issues, githubError) - if err == nil { - err = githubError - } - return *issues, resp, err -} -``` - -## Example APIs using Sling - -* Digits [dghubble/go-digits](https://github.com/dghubble/go-digits) -* GoSquared [drinkin/go-gosquared](https://github.com/drinkin/go-gosquared) -* Kala [ajvb/kala](https://github.com/ajvb/kala) -* Parse [fergstar/go-parse](https://github.com/fergstar/go-parse) -* Rdio [apriendeau/shares](https://github.com/apriendeau/shares) -* Swagger Generator [swagger-api/swagger-codegen](https://github.com/swagger-api/swagger-codegen) -* Twitter [dghubble/go-twitter](https://github.com/dghubble/go-twitter) -* Hacker News [mirceamironenco/go-hackernews](https://github.com/mirceamironenco/go-hackernews) -* Stacksmith [jesustinoco/go-smith](https://github.com/jesustinoco/go-smith) - -Create a Pull Request to add a link to your own API. - -## Motivation - -Many client libraries follow the lead of [google/go-github](https://github.com/google/go-github) (our inspiration!), but do so by reimplementing logic common to all clients. - -This project borrows and abstracts those ideas into a Sling, an agnostic component any API client can use for creating and sending requests. - -## Contributing - -See the [Contributing Guide](https://gist.github.com/dghubble/be682c123727f70bcfe7). - -## License - -[MIT License](LICENSE) diff --git a/vendor/github.com/dghubble/sling/body.go b/vendor/github.com/dghubble/sling/body.go deleted file mode 100644 index f3bc8160..00000000 --- a/vendor/github.com/dghubble/sling/body.go +++ /dev/null @@ -1,68 +0,0 @@ -package sling - -import ( - "bytes" - "encoding/json" - "io" - "strings" - - goquery "github.com/google/go-querystring/query" -) - -// BodyProvider provides Body content for http.Request attachment. -type BodyProvider interface { - // ContentType returns the Content-Type of the body. - ContentType() string - // Body returns the io.Reader body. - Body() (io.Reader, error) -} - -// bodyProvider provides the wrapped body value as a Body for reqests. -type bodyProvider struct { - body io.Reader -} - -func (p bodyProvider) ContentType() string { - return "" -} - -func (p bodyProvider) Body() (io.Reader, error) { - return p.body, nil -} - -// jsonBodyProvider encodes a JSON tagged struct value as a Body for requests. -// See https://golang.org/pkg/encoding/json/#MarshalIndent for details. -type jsonBodyProvider struct { - payload interface{} -} - -func (p jsonBodyProvider) ContentType() string { - return jsonContentType -} - -func (p jsonBodyProvider) Body() (io.Reader, error) { - buf := &bytes.Buffer{} - err := json.NewEncoder(buf).Encode(p.payload) - if err != nil { - return nil, err - } - return buf, nil -} - -// formBodyProvider encodes a url tagged struct value as Body for requests. -// See https://godoc.org/github.com/google/go-querystring/query for details. -type formBodyProvider struct { - payload interface{} -} - -func (p formBodyProvider) ContentType() string { - return formContentType -} - -func (p formBodyProvider) Body() (io.Reader, error) { - values, err := goquery.Values(p.payload) - if err != nil { - return nil, err - } - return strings.NewReader(values.Encode()), nil -} diff --git a/vendor/github.com/dghubble/sling/doc.go b/vendor/github.com/dghubble/sling/doc.go deleted file mode 100644 index dd2efb7e..00000000 --- a/vendor/github.com/dghubble/sling/doc.go +++ /dev/null @@ -1,179 +0,0 @@ -/* -Package sling is a Go HTTP client library for creating and sending API requests. - -Slings store HTTP Request properties to simplify sending requests and decoding -responses. Check the examples to learn how to compose a Sling into your API -client. - -Usage - -Use a Sling to set path, method, header, query, or body properties and create an -http.Request. - - type Params struct { - Count int `url:"count,omitempty"` - } - params := &Params{Count: 5} - - req, err := sling.New().Get("https://example.com").QueryStruct(params).Request() - client.Do(req) - -Path - -Use Path to set or extend the URL for created Requests. Extension means the -path will be resolved relative to the existing URL. - - // creates a GET request to https://example.com/foo/bar - req, err := sling.New().Base("https://example.com/").Path("foo/").Path("bar").Request() - -Use Get, Post, Put, Patch, Delete, or Head which are exactly the same as Path -except they set the HTTP method too. - - req, err := sling.New().Post("http://upload.com/gophers") - -Headers - -Add or Set headers for requests created by a Sling. - - s := sling.New().Base(baseUrl).Set("User-Agent", "Gophergram API Client") - req, err := s.New().Get("gophergram/list").Request() - -QueryStruct - -Define url parameter structs (https://godoc.org/github.com/google/go-querystring/query). -Use QueryStruct to encode a struct as query parameters on requests. - - // Github Issue Parameters - type IssueParams struct { - Filter string `url:"filter,omitempty"` - State string `url:"state,omitempty"` - Labels string `url:"labels,omitempty"` - Sort string `url:"sort,omitempty"` - Direction string `url:"direction,omitempty"` - Since string `url:"since,omitempty"` - } - - githubBase := sling.New().Base("https://api.github.com/").Client(httpClient) - - path := fmt.Sprintf("repos/%s/%s/issues", owner, repo) - params := &IssueParams{Sort: "updated", State: "open"} - req, err := githubBase.New().Get(path).QueryStruct(params).Request() - -Json Body - -Define JSON tagged structs (https://golang.org/pkg/encoding/json/). -Use BodyJSON to JSON encode a struct as the Body on requests. - - type IssueRequest struct { - Title string `json:"title,omitempty"` - Body string `json:"body,omitempty"` - Assignee string `json:"assignee,omitempty"` - Milestone int `json:"milestone,omitempty"` - Labels []string `json:"labels,omitempty"` - } - - githubBase := sling.New().Base("https://api.github.com/").Client(httpClient) - path := fmt.Sprintf("repos/%s/%s/issues", owner, repo) - - body := &IssueRequest{ - Title: "Test title", - Body: "Some issue", - } - req, err := githubBase.New().Post(path).BodyJSON(body).Request() - -Requests will include an "application/json" Content-Type header. - -Form Body - -Define url tagged structs (https://godoc.org/github.com/google/go-querystring/query). -Use BodyForm to form url encode a struct as the Body on requests. - - type StatusUpdateParams struct { - Status string `url:"status,omitempty"` - InReplyToStatusId int64 `url:"in_reply_to_status_id,omitempty"` - MediaIds []int64 `url:"media_ids,omitempty,comma"` - } - - tweetParams := &StatusUpdateParams{Status: "writing some Go"} - req, err := twitterBase.New().Post(path).BodyForm(tweetParams).Request() - -Requests will include an "application/x-www-form-urlencoded" Content-Type -header. - -Plain Body - -Use Body to set a plain io.Reader on requests created by a Sling. - - body := strings.NewReader("raw body") - req, err := sling.New().Base("https://example.com").Body(body).Request() - -Set a content type header, if desired (e.g. Set("Content-Type", "text/plain")). - -Extend a Sling - -Each Sling generates an http.Request (say with some path and query params) -each time Request() is called, based on its state. When creating -different slings, you may wish to extend an existing Sling to minimize -duplication (e.g. a common client). - -Each Sling instance provides a New() method which creates an independent copy, -so setting properties on the child won't mutate the parent Sling. - - const twitterApi = "https://api.twitter.com/1.1/" - base := sling.New().Base(twitterApi).Client(authClient) - - // statuses/show.json Sling - tweetShowSling := base.New().Get("statuses/show.json").QueryStruct(params) - req, err := tweetShowSling.Request() - - // statuses/update.json Sling - tweetPostSling := base.New().Post("statuses/update.json").BodyForm(params) - req, err := tweetPostSling.Request() - -Without the calls to base.New(), tweetShowSling and tweetPostSling would -reference the base Sling and POST to -"https://api.twitter.com/1.1/statuses/show.json/statuses/update.json", which -is undesired. - -Recap: If you wish to extend a Sling, create a new child copy with New(). - -Receive - -Define a JSON struct to decode a type from 2XX success responses. Use -ReceiveSuccess(successV interface{}) to send a new Request and decode the -response body into successV if it succeeds. - - // Github Issue (abbreviated) - type Issue struct { - Title string `json:"title"` - Body string `json:"body"` - } - - issues := new([]Issue) - resp, err := githubBase.New().Get(path).QueryStruct(params).ReceiveSuccess(issues) - fmt.Println(issues, resp, err) - -Most APIs return failure responses with JSON error details. To decode these, -define success and failure JSON structs. Use -Receive(successV, failureV interface{}) to send a new Request that will -automatically decode the response into the successV for 2XX responses or into -failureV for non-2XX responses. - - type GithubError struct { - Message string `json:"message"` - Errors []struct { - Resource string `json:"resource"` - Field string `json:"field"` - Code string `json:"code"` - } `json:"errors"` - DocumentationURL string `json:"documentation_url"` - } - - issues := new([]Issue) - githubError := new(GithubError) - resp, err := githubBase.New().Get(path).QueryStruct(params).Receive(issues, githubError) - fmt.Println(issues, githubError, resp, err) - -Pass a nil successV or failureV argument to skip JSON decoding into that value. -*/ -package sling diff --git a/vendor/github.com/dghubble/sling/response.go b/vendor/github.com/dghubble/sling/response.go deleted file mode 100644 index c918ed13..00000000 --- a/vendor/github.com/dghubble/sling/response.go +++ /dev/null @@ -1,22 +0,0 @@ -package sling - -import ( - "encoding/json" - "net/http" -) - -// ResponseDecoder decodes http responses into struct values. -type ResponseDecoder interface { - // Decode decodes the response into the value pointed to by v. - Decode(resp *http.Response, v interface{}) error -} - -// jsonDecoder decodes http response JSON into a JSON-tagged struct value. -type jsonDecoder struct { -} - -// Decode decodes the Response Body into the value pointed to by v. -// Caller must provide a non-nil v and close the resp.Body. -func (d jsonDecoder) Decode(resp *http.Response, v interface{}) error { - return json.NewDecoder(resp.Body).Decode(v) -} diff --git a/vendor/github.com/dghubble/sling/sling.go b/vendor/github.com/dghubble/sling/sling.go deleted file mode 100644 index fe9c54ec..00000000 --- a/vendor/github.com/dghubble/sling/sling.go +++ /dev/null @@ -1,413 +0,0 @@ -package sling - -import ( - "encoding/base64" - "io" - "net/http" - "net/url" - - goquery "github.com/google/go-querystring/query" -) - -const ( - contentType = "Content-Type" - jsonContentType = "application/json" - formContentType = "application/x-www-form-urlencoded" -) - -// Doer executes http requests. It is implemented by *http.Client. You can -// wrap *http.Client with layers of Doers to form a stack of client-side -// middleware. -type Doer interface { - Do(req *http.Request) (*http.Response, error) -} - -// Sling is an HTTP Request builder and sender. -type Sling struct { - // http Client for doing requests - httpClient Doer - // HTTP method (GET, POST, etc.) - method string - // raw url string for requests - rawURL string - // stores key-values pairs to add to request's Headers - header http.Header - // url tagged query structs - queryStructs []interface{} - // body provider - bodyProvider BodyProvider - // response decoder - responseDecoder ResponseDecoder -} - -// New returns a new Sling with an http DefaultClient. -func New() *Sling { - return &Sling{ - httpClient: http.DefaultClient, - method: "GET", - header: make(http.Header), - queryStructs: make([]interface{}, 0), - responseDecoder: jsonDecoder{}, - } -} - -// New returns a copy of a Sling for creating a new Sling with properties -// from a parent Sling. For example, -// -// parentSling := sling.New().Client(client).Base("https://api.io/") -// fooSling := parentSling.New().Get("foo/") -// barSling := parentSling.New().Get("bar/") -// -// fooSling and barSling will both use the same client, but send requests to -// https://api.io/foo/ and https://api.io/bar/ respectively. -// -// Note that query and body values are copied so if pointer values are used, -// mutating the original value will mutate the value within the child Sling. -func (s *Sling) New() *Sling { - // copy Headers pairs into new Header map - headerCopy := make(http.Header) - for k, v := range s.header { - headerCopy[k] = v - } - return &Sling{ - httpClient: s.httpClient, - method: s.method, - rawURL: s.rawURL, - header: headerCopy, - queryStructs: append([]interface{}{}, s.queryStructs...), - bodyProvider: s.bodyProvider, - responseDecoder: s.responseDecoder, - } -} - -// Http Client - -// Client sets the http Client used to do requests. If a nil client is given, -// the http.DefaultClient will be used. -func (s *Sling) Client(httpClient *http.Client) *Sling { - if httpClient == nil { - return s.Doer(http.DefaultClient) - } - return s.Doer(httpClient) -} - -// Doer sets the custom Doer implementation used to do requests. -// If a nil client is given, the http.DefaultClient will be used. -func (s *Sling) Doer(doer Doer) *Sling { - if doer == nil { - s.httpClient = http.DefaultClient - } else { - s.httpClient = doer - } - return s -} - -// Method - -// Head sets the Sling method to HEAD and sets the given pathURL. -func (s *Sling) Head(pathURL string) *Sling { - s.method = "HEAD" - return s.Path(pathURL) -} - -// Get sets the Sling method to GET and sets the given pathURL. -func (s *Sling) Get(pathURL string) *Sling { - s.method = "GET" - return s.Path(pathURL) -} - -// Post sets the Sling method to POST and sets the given pathURL. -func (s *Sling) Post(pathURL string) *Sling { - s.method = "POST" - return s.Path(pathURL) -} - -// Put sets the Sling method to PUT and sets the given pathURL. -func (s *Sling) Put(pathURL string) *Sling { - s.method = "PUT" - return s.Path(pathURL) -} - -// Patch sets the Sling method to PATCH and sets the given pathURL. -func (s *Sling) Patch(pathURL string) *Sling { - s.method = "PATCH" - return s.Path(pathURL) -} - -// Delete sets the Sling method to DELETE and sets the given pathURL. -func (s *Sling) Delete(pathURL string) *Sling { - s.method = "DELETE" - return s.Path(pathURL) -} - -// Options sets the Sling method to OPTIONS and sets the given pathURL. -func (s *Sling) Options(pathURL string) *Sling { - s.method = "OPTIONS" - return s.Path(pathURL) -} - -// Trace sets the Sling method to TRACE and sets the given pathURL. -func (s *Sling) Trace(pathURL string) *Sling { - s.method = "TRACE" - return s.Path(pathURL) -} - -// Connect sets the Sling method to CONNECT and sets the given pathURL. -func (s *Sling) Connect(pathURL string) *Sling { - s.method = "CONNECT" - return s.Path(pathURL) -} - -// Header - -// Add adds the key, value pair in Headers, appending values for existing keys -// to the key's values. Header keys are canonicalized. -func (s *Sling) Add(key, value string) *Sling { - s.header.Add(key, value) - return s -} - -// Set sets the key, value pair in Headers, replacing existing values -// associated with key. Header keys are canonicalized. -func (s *Sling) Set(key, value string) *Sling { - s.header.Set(key, value) - return s -} - -// SetBasicAuth sets the Authorization header to use HTTP Basic Authentication -// with the provided username and password. With HTTP Basic Authentication -// the provided username and password are not encrypted. -func (s *Sling) SetBasicAuth(username, password string) *Sling { - return s.Set("Authorization", "Basic "+basicAuth(username, password)) -} - -// basicAuth returns the base64 encoded username:password for basic auth copied -// from net/http. -func basicAuth(username, password string) string { - auth := username + ":" + password - return base64.StdEncoding.EncodeToString([]byte(auth)) -} - -// Url - -// Base sets the rawURL. If you intend to extend the url with Path, -// baseUrl should be specified with a trailing slash. -func (s *Sling) Base(rawURL string) *Sling { - s.rawURL = rawURL - return s -} - -// Path extends the rawURL with the given path by resolving the reference to -// an absolute URL. If parsing errors occur, the rawURL is left unmodified. -func (s *Sling) Path(path string) *Sling { - baseURL, baseErr := url.Parse(s.rawURL) - pathURL, pathErr := url.Parse(path) - if baseErr == nil && pathErr == nil { - s.rawURL = baseURL.ResolveReference(pathURL).String() - return s - } - return s -} - -// QueryStruct appends the queryStruct to the Sling's queryStructs. The value -// pointed to by each queryStruct will be encoded as url query parameters on -// new requests (see Request()). -// The queryStruct argument should be a pointer to a url tagged struct. See -// https://godoc.org/github.com/google/go-querystring/query for details. -func (s *Sling) QueryStruct(queryStruct interface{}) *Sling { - if queryStruct != nil { - s.queryStructs = append(s.queryStructs, queryStruct) - } - return s -} - -// Body - -// Body sets the Sling's body. The body value will be set as the Body on new -// requests (see Request()). -// If the provided body is also an io.Closer, the request Body will be closed -// by http.Client methods. -func (s *Sling) Body(body io.Reader) *Sling { - if body == nil { - return s - } - return s.BodyProvider(bodyProvider{body: body}) -} - -// BodyProvider sets the Sling's body provider. -func (s *Sling) BodyProvider(body BodyProvider) *Sling { - if body == nil { - return s - } - s.bodyProvider = body - - ct := body.ContentType() - if ct != "" { - s.Set(contentType, ct) - } - - return s -} - -// BodyJSON sets the Sling's bodyJSON. The value pointed to by the bodyJSON -// will be JSON encoded as the Body on new requests (see Request()). -// The bodyJSON argument should be a pointer to a JSON tagged struct. See -// https://golang.org/pkg/encoding/json/#MarshalIndent for details. -func (s *Sling) BodyJSON(bodyJSON interface{}) *Sling { - if bodyJSON == nil { - return s - } - return s.BodyProvider(jsonBodyProvider{payload: bodyJSON}) -} - -// BodyForm sets the Sling's bodyForm. The value pointed to by the bodyForm -// will be url encoded as the Body on new requests (see Request()). -// The bodyForm argument should be a pointer to a url tagged struct. See -// https://godoc.org/github.com/google/go-querystring/query for details. -func (s *Sling) BodyForm(bodyForm interface{}) *Sling { - if bodyForm == nil { - return s - } - return s.BodyProvider(formBodyProvider{payload: bodyForm}) -} - -// Requests - -// Request returns a new http.Request created with the Sling properties. -// Returns any errors parsing the rawURL, encoding query structs, encoding -// the body, or creating the http.Request. -func (s *Sling) Request() (*http.Request, error) { - reqURL, err := url.Parse(s.rawURL) - if err != nil { - return nil, err - } - - err = addQueryStructs(reqURL, s.queryStructs) - if err != nil { - return nil, err - } - - var body io.Reader - if s.bodyProvider != nil { - body, err = s.bodyProvider.Body() - if err != nil { - return nil, err - } - } - req, err := http.NewRequest(s.method, reqURL.String(), body) - if err != nil { - return nil, err - } - addHeaders(req, s.header) - return req, err -} - -// addQueryStructs parses url tagged query structs using go-querystring to -// encode them to url.Values and format them onto the url.RawQuery. Any -// query parsing or encoding errors are returned. -func addQueryStructs(reqURL *url.URL, queryStructs []interface{}) error { - urlValues, err := url.ParseQuery(reqURL.RawQuery) - if err != nil { - return err - } - // encodes query structs into a url.Values map and merges maps - for _, queryStruct := range queryStructs { - queryValues, err := goquery.Values(queryStruct) - if err != nil { - return err - } - for key, values := range queryValues { - for _, value := range values { - urlValues.Add(key, value) - } - } - } - // url.Values format to a sorted "url encoded" string, e.g. "key=val&foo=bar" - reqURL.RawQuery = urlValues.Encode() - return nil -} - -// addHeaders adds the key, value pairs from the given http.Header to the -// request. Values for existing keys are appended to the keys values. -func addHeaders(req *http.Request, header http.Header) { - for key, values := range header { - for _, value := range values { - req.Header.Add(key, value) - } - } -} - -// Sending - -// ResponseDecoder sets the Sling's response decoder. -func (s *Sling) ResponseDecoder(decoder ResponseDecoder) *Sling { - if decoder == nil { - return s - } - s.responseDecoder = decoder - return s -} - -// ReceiveSuccess creates a new HTTP request and returns the response. Success -// responses (2XX) are JSON decoded into the value pointed to by successV. -// Any error creating the request, sending it, or decoding a 2XX response -// is returned. -func (s *Sling) ReceiveSuccess(successV interface{}) (*http.Response, error) { - return s.Receive(successV, nil) -} - -// Receive creates a new HTTP request and returns the response. Success -// responses (2XX) are JSON decoded into the value pointed to by successV and -// other responses are JSON decoded into the value pointed to by failureV. -// Any error creating the request, sending it, or decoding the response is -// returned. -// Receive is shorthand for calling Request and Do. -func (s *Sling) Receive(successV, failureV interface{}) (*http.Response, error) { - req, err := s.Request() - if err != nil { - return nil, err - } - return s.Do(req, successV, failureV) -} - -// Do sends an HTTP request and returns the response. Success responses (2XX) -// are JSON decoded into the value pointed to by successV and other responses -// are JSON decoded into the value pointed to by failureV. -// Any error sending the request or decoding the response is returned. -func (s *Sling) Do(req *http.Request, successV, failureV interface{}) (*http.Response, error) { - resp, err := s.httpClient.Do(req) - if err != nil { - return resp, err - } - // when err is nil, resp contains a non-nil resp.Body which must be closed - defer resp.Body.Close() - - // Don't try to decode on 204s - if resp.StatusCode == 204 { - return resp, nil - } - - // Decode from json - if successV != nil || failureV != nil { - err = decodeResponse(resp, s.responseDecoder, successV, failureV) - } - return resp, err -} - -// decodeResponse decodes response Body into the value pointed to by successV -// if the response is a success (2XX) or into the value pointed to by failureV -// otherwise. If the successV or failureV argument to decode into is nil, -// decoding is skipped. -// Caller is responsible for closing the resp.Body. -func decodeResponse(resp *http.Response, decoder ResponseDecoder, successV, failureV interface{}) error { - if code := resp.StatusCode; 200 <= code && code <= 299 { - if successV != nil { - return decoder.Decode(resp, successV) - } - } else { - if failureV != nil { - return decoder.Decode(resp, failureV) - } - } - return nil -} diff --git a/vendor/github.com/dimchansky/utfbom/.gitignore b/vendor/github.com/dimchansky/utfbom/.gitignore deleted file mode 100644 index d7ec5ceb..00000000 --- a/vendor/github.com/dimchansky/utfbom/.gitignore +++ /dev/null @@ -1,37 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.dll -*.so -*.dylib -*.o -*.a - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.prof - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out - -# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 -.glide/ - -# Gogland -.idea/ \ No newline at end of file diff --git a/vendor/github.com/dimchansky/utfbom/.travis.yml b/vendor/github.com/dimchansky/utfbom/.travis.yml deleted file mode 100644 index 19312ee3..00000000 --- a/vendor/github.com/dimchansky/utfbom/.travis.yml +++ /dev/null @@ -1,29 +0,0 @@ -language: go -sudo: false - -go: - - 1.10.x - - 1.11.x - - 1.12.x - - 1.13.x - - 1.14.x - - 1.15.x - -cache: - directories: - - $HOME/.cache/go-build - - $HOME/gopath/pkg/mod - -env: - global: - - GO111MODULE=on - -before_install: - - go get github.com/mattn/goveralls - - go get golang.org/x/tools/cmd/cover - - go get golang.org/x/tools/cmd/goimports - - go get golang.org/x/lint/golint -script: - - gofiles=$(find ./ -name '*.go') && [ -z "$gofiles" ] || unformatted=$(goimports -l $gofiles) && [ -z "$unformatted" ] || (echo >&2 "Go files must be formatted with gofmt. Following files has problem:\n $unformatted" && false) - - golint ./... # This won't break the build, just show warnings - - $HOME/gopath/bin/goveralls -service=travis-ci diff --git a/vendor/github.com/dimchansky/utfbom/LICENSE b/vendor/github.com/dimchansky/utfbom/LICENSE deleted file mode 100644 index 6279cb87..00000000 --- a/vendor/github.com/dimchansky/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/github.com/dimchansky/utfbom/README.md b/vendor/github.com/dimchansky/utfbom/README.md deleted file mode 100644 index 8ece2800..00000000 --- a/vendor/github.com/dimchansky/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/github.com/dimchansky/utfbom/utfbom.go b/vendor/github.com/dimchansky/utfbom/utfbom.go deleted file mode 100644 index 77a303e5..00000000 --- a/vendor/github.com/dimchansky/utfbom/utfbom.go +++ /dev/null @@ -1,192 +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. -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 && 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] { - if n, err = rd.Read(bom[len(buf):]); n < 0 { - panic(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/github.com/docker/distribution/LICENSE b/vendor/github.com/docker/distribution/LICENSE deleted file mode 100644 index e06d2081..00000000 --- a/vendor/github.com/docker/distribution/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/docker/distribution/digestset/set.go b/vendor/github.com/docker/distribution/digestset/set.go deleted file mode 100644 index 71327dca..00000000 --- a/vendor/github.com/docker/distribution/digestset/set.go +++ /dev/null @@ -1,247 +0,0 @@ -package digestset - -import ( - "errors" - "sort" - "strings" - "sync" - - digest "github.com/opencontainers/go-digest" -) - -var ( - // ErrDigestNotFound is used when a matching digest - // could not be found in a set. - ErrDigestNotFound = errors.New("digest not found") - - // ErrDigestAmbiguous is used when multiple digests - // are found in a set. None of the matching digests - // should be considered valid matches. - ErrDigestAmbiguous = errors.New("ambiguous digest string") -) - -// Set is used to hold a unique set of digests which -// may be easily referenced by easily referenced by a string -// representation of the digest as well as short representation. -// The uniqueness of the short representation is based on other -// digests in the set. If digests are omitted from this set, -// collisions in a larger set may not be detected, therefore it -// is important to always do short representation lookups on -// the complete set of digests. To mitigate collisions, an -// appropriately long short code should be used. -type Set struct { - mutex sync.RWMutex - entries digestEntries -} - -// NewSet creates an empty set of digests -// which may have digests added. -func NewSet() *Set { - return &Set{ - entries: digestEntries{}, - } -} - -// checkShortMatch checks whether two digests match as either whole -// values or short values. This function does not test equality, -// rather whether the second value could match against the first -// value. -func checkShortMatch(alg digest.Algorithm, hex, shortAlg, shortHex string) bool { - if len(hex) == len(shortHex) { - if hex != shortHex { - return false - } - if len(shortAlg) > 0 && string(alg) != shortAlg { - return false - } - } else if !strings.HasPrefix(hex, shortHex) { - return false - } else if len(shortAlg) > 0 && string(alg) != shortAlg { - return false - } - return true -} - -// Lookup looks for a digest matching the given string representation. -// If no digests could be found ErrDigestNotFound will be returned -// with an empty digest value. If multiple matches are found -// ErrDigestAmbiguous will be returned with an empty digest value. -func (dst *Set) Lookup(d string) (digest.Digest, error) { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - if len(dst.entries) == 0 { - return "", ErrDigestNotFound - } - var ( - searchFunc func(int) bool - alg digest.Algorithm - hex string - ) - dgst, err := digest.Parse(d) - if err == digest.ErrDigestInvalidFormat { - hex = d - searchFunc = func(i int) bool { - return dst.entries[i].val >= d - } - } else { - hex = dgst.Hex() - alg = dgst.Algorithm() - searchFunc = func(i int) bool { - if dst.entries[i].val == hex { - return dst.entries[i].alg >= alg - } - return dst.entries[i].val >= hex - } - } - idx := sort.Search(len(dst.entries), searchFunc) - if idx == len(dst.entries) || !checkShortMatch(dst.entries[idx].alg, dst.entries[idx].val, string(alg), hex) { - return "", ErrDigestNotFound - } - if dst.entries[idx].alg == alg && dst.entries[idx].val == hex { - return dst.entries[idx].digest, nil - } - if idx+1 < len(dst.entries) && checkShortMatch(dst.entries[idx+1].alg, dst.entries[idx+1].val, string(alg), hex) { - return "", ErrDigestAmbiguous - } - - return dst.entries[idx].digest, nil -} - -// Add adds the given digest to the set. An error will be returned -// if the given digest is invalid. If the digest already exists in the -// set, this operation will be a no-op. -func (dst *Set) Add(d digest.Digest) error { - if err := d.Validate(); err != nil { - return err - } - dst.mutex.Lock() - defer dst.mutex.Unlock() - entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d} - searchFunc := func(i int) bool { - if dst.entries[i].val == entry.val { - return dst.entries[i].alg >= entry.alg - } - return dst.entries[i].val >= entry.val - } - idx := sort.Search(len(dst.entries), searchFunc) - if idx == len(dst.entries) { - dst.entries = append(dst.entries, entry) - return nil - } else if dst.entries[idx].digest == d { - return nil - } - - entries := append(dst.entries, nil) - copy(entries[idx+1:], entries[idx:len(entries)-1]) - entries[idx] = entry - dst.entries = entries - return nil -} - -// Remove removes the given digest from the set. An err will be -// returned if the given digest is invalid. If the digest does -// not exist in the set, this operation will be a no-op. -func (dst *Set) Remove(d digest.Digest) error { - if err := d.Validate(); err != nil { - return err - } - dst.mutex.Lock() - defer dst.mutex.Unlock() - entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d} - searchFunc := func(i int) bool { - if dst.entries[i].val == entry.val { - return dst.entries[i].alg >= entry.alg - } - return dst.entries[i].val >= entry.val - } - idx := sort.Search(len(dst.entries), searchFunc) - // Not found if idx is after or value at idx is not digest - if idx == len(dst.entries) || dst.entries[idx].digest != d { - return nil - } - - entries := dst.entries - copy(entries[idx:], entries[idx+1:]) - entries = entries[:len(entries)-1] - dst.entries = entries - - return nil -} - -// All returns all the digests in the set -func (dst *Set) All() []digest.Digest { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - retValues := make([]digest.Digest, len(dst.entries)) - for i := range dst.entries { - retValues[i] = dst.entries[i].digest - } - - return retValues -} - -// ShortCodeTable returns a map of Digest to unique short codes. The -// length represents the minimum value, the maximum length may be the -// entire value of digest if uniqueness cannot be achieved without the -// full value. This function will attempt to make short codes as short -// as possible to be unique. -func ShortCodeTable(dst *Set, length int) map[digest.Digest]string { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - m := make(map[digest.Digest]string, len(dst.entries)) - l := length - resetIdx := 0 - for i := 0; i < len(dst.entries); i++ { - var short string - extended := true - for extended { - extended = false - if len(dst.entries[i].val) <= l { - short = dst.entries[i].digest.String() - } else { - short = dst.entries[i].val[:l] - for j := i + 1; j < len(dst.entries); j++ { - if checkShortMatch(dst.entries[j].alg, dst.entries[j].val, "", short) { - if j > resetIdx { - resetIdx = j - } - extended = true - } else { - break - } - } - if extended { - l++ - } - } - } - m[dst.entries[i].digest] = short - if i >= resetIdx { - l = length - } - } - return m -} - -type digestEntry struct { - alg digest.Algorithm - val string - digest digest.Digest -} - -type digestEntries []*digestEntry - -func (d digestEntries) Len() int { - return len(d) -} - -func (d digestEntries) Less(i, j int) bool { - if d[i].val != d[j].val { - return d[i].val < d[j].val - } - return d[i].alg < d[j].alg -} - -func (d digestEntries) Swap(i, j int) { - d[i], d[j] = d[j], d[i] -} diff --git a/vendor/github.com/docker/distribution/reference/helpers.go b/vendor/github.com/docker/distribution/reference/helpers.go deleted file mode 100644 index 978df7ea..00000000 --- a/vendor/github.com/docker/distribution/reference/helpers.go +++ /dev/null @@ -1,42 +0,0 @@ -package reference - -import "path" - -// IsNameOnly returns true if reference only contains a repo name. -func IsNameOnly(ref Named) bool { - if _, ok := ref.(NamedTagged); ok { - return false - } - if _, ok := ref.(Canonical); ok { - return false - } - return true -} - -// FamiliarName returns the familiar name string -// for the given named, familiarizing if needed. -func FamiliarName(ref Named) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().Name() - } - return ref.Name() -} - -// FamiliarString returns the familiar string representation -// for the given reference, familiarizing if needed. -func FamiliarString(ref Reference) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().String() - } - return ref.String() -} - -// FamiliarMatch reports whether ref matches the specified pattern. -// See https://godoc.org/path#Match for supported patterns. -func FamiliarMatch(pattern string, ref Reference) (bool, error) { - matched, err := path.Match(pattern, FamiliarString(ref)) - if namedRef, isNamed := ref.(Named); isNamed && !matched { - matched, _ = path.Match(pattern, FamiliarName(namedRef)) - } - return matched, err -} diff --git a/vendor/github.com/docker/distribution/reference/normalize.go b/vendor/github.com/docker/distribution/reference/normalize.go deleted file mode 100644 index 2d71fc5e..00000000 --- a/vendor/github.com/docker/distribution/reference/normalize.go +++ /dev/null @@ -1,170 +0,0 @@ -package reference - -import ( - "errors" - "fmt" - "strings" - - "github.com/docker/distribution/digestset" - "github.com/opencontainers/go-digest" -) - -var ( - legacyDefaultDomain = "index.docker.io" - defaultDomain = "docker.io" - officialRepoName = "library" - defaultTag = "latest" -) - -// normalizedNamed represents a name which has been -// normalized and has a familiar form. A familiar name -// is what is used in Docker UI. An example normalized -// name is "docker.io/library/ubuntu" and corresponding -// familiar name of "ubuntu". -type normalizedNamed interface { - Named - Familiar() Named -} - -// ParseNormalizedNamed parses a string into a named reference -// transforming a familiar name from Docker UI to a fully -// qualified reference. If the value may be an identifier -// use ParseAnyReference. -func ParseNormalizedNamed(s string) (Named, error) { - if ok := anchoredIdentifierRegexp.MatchString(s); ok { - return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) - } - domain, remainder := splitDockerDomain(s) - var remoteName string - if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { - remoteName = remainder[:tagSep] - } else { - remoteName = remainder - } - if strings.ToLower(remoteName) != remoteName { - return nil, errors.New("invalid reference format: repository name must be lowercase") - } - - ref, err := Parse(domain + "/" + remainder) - if err != nil { - return nil, err - } - named, isNamed := ref.(Named) - if !isNamed { - return nil, fmt.Errorf("reference %s has no name", ref.String()) - } - return named, nil -} - -// splitDockerDomain splits a repository name to domain and remotename string. -// If no valid domain is found, the default domain is used. Repository name -// needs to be already validated before. -func splitDockerDomain(name string) (domain, remainder string) { - i := strings.IndexRune(name, '/') - if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != "localhost") { - domain, remainder = defaultDomain, name - } else { - domain, remainder = name[:i], name[i+1:] - } - if domain == legacyDefaultDomain { - domain = defaultDomain - } - if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { - remainder = officialRepoName + "/" + remainder - } - return -} - -// familiarizeName returns a shortened version of the name familiar -// to to the Docker UI. Familiar names have the default domain -// "docker.io" and "library/" repository prefix removed. -// For example, "docker.io/library/redis" will have the familiar -// name "redis" and "docker.io/dmcgowan/myapp" will be "dmcgowan/myapp". -// Returns a familiarized named only reference. -func familiarizeName(named namedRepository) repository { - repo := repository{ - domain: named.Domain(), - path: named.Path(), - } - - if repo.domain == defaultDomain { - repo.domain = "" - // Handle official repositories which have the pattern "library/" - if split := strings.Split(repo.path, "/"); len(split) == 2 && split[0] == officialRepoName { - repo.path = split[1] - } - } - return repo -} - -func (r reference) Familiar() Named { - return reference{ - namedRepository: familiarizeName(r.namedRepository), - tag: r.tag, - digest: r.digest, - } -} - -func (r repository) Familiar() Named { - return familiarizeName(r) -} - -func (t taggedReference) Familiar() Named { - return taggedReference{ - namedRepository: familiarizeName(t.namedRepository), - tag: t.tag, - } -} - -func (c canonicalReference) Familiar() Named { - return canonicalReference{ - namedRepository: familiarizeName(c.namedRepository), - digest: c.digest, - } -} - -// TagNameOnly adds the default tag "latest" to a reference if it only has -// a repo name. -func TagNameOnly(ref Named) Named { - if IsNameOnly(ref) { - namedTagged, err := WithTag(ref, defaultTag) - if err != nil { - // Default tag must be valid, to create a NamedTagged - // type with non-validated input the WithTag function - // should be used instead - panic(err) - } - return namedTagged - } - return ref -} - -// ParseAnyReference parses a reference string as a possible identifier, -// full digest, or familiar name. -func ParseAnyReference(ref string) (Reference, error) { - if ok := anchoredIdentifierRegexp.MatchString(ref); ok { - return digestReference("sha256:" + ref), nil - } - if dgst, err := digest.Parse(ref); err == nil { - return digestReference(dgst), nil - } - - return ParseNormalizedNamed(ref) -} - -// ParseAnyReferenceWithSet parses a reference string as a possible short -// identifier to be matched in a digest set, a full digest, or familiar name. -func ParseAnyReferenceWithSet(ref string, ds *digestset.Set) (Reference, error) { - if ok := anchoredShortIdentifierRegexp.MatchString(ref); ok { - dgst, err := ds.Lookup(ref) - if err == nil { - return digestReference(dgst), nil - } - } else { - if dgst, err := digest.Parse(ref); err == nil { - return digestReference(dgst), nil - } - } - - return ParseNormalizedNamed(ref) -} diff --git a/vendor/github.com/docker/distribution/reference/reference.go b/vendor/github.com/docker/distribution/reference/reference.go deleted file mode 100644 index 2f66cca8..00000000 --- a/vendor/github.com/docker/distribution/reference/reference.go +++ /dev/null @@ -1,433 +0,0 @@ -// Package reference provides a general type to represent any way of referencing images within the registry. -// Its main purpose is to abstract tags and digests (content-addressable hash). -// -// Grammar -// -// reference := name [ ":" tag ] [ "@" digest ] -// name := [domain '/'] path-component ['/' path-component]* -// domain := domain-component ['.' domain-component]* [':' port-number] -// domain-component := /([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/ -// port-number := /[0-9]+/ -// path-component := alpha-numeric [separator alpha-numeric]* -// alpha-numeric := /[a-z0-9]+/ -// separator := /[_.]|__|[-]*/ -// -// tag := /[\w][\w.-]{0,127}/ -// -// digest := digest-algorithm ":" digest-hex -// digest-algorithm := digest-algorithm-component [ digest-algorithm-separator digest-algorithm-component ]* -// digest-algorithm-separator := /[+.-_]/ -// digest-algorithm-component := /[A-Za-z][A-Za-z0-9]*/ -// digest-hex := /[0-9a-fA-F]{32,}/ ; At least 128 bit digest value -// -// identifier := /[a-f0-9]{64}/ -// short-identifier := /[a-f0-9]{6,64}/ -package reference - -import ( - "errors" - "fmt" - "strings" - - "github.com/opencontainers/go-digest" -) - -const ( - // NameTotalLengthMax is the maximum total number of characters in a repository name. - NameTotalLengthMax = 255 -) - -var ( - // ErrReferenceInvalidFormat represents an error while trying to parse a string as a reference. - ErrReferenceInvalidFormat = errors.New("invalid reference format") - - // ErrTagInvalidFormat represents an error while trying to parse a string as a tag. - ErrTagInvalidFormat = errors.New("invalid tag format") - - // ErrDigestInvalidFormat represents an error while trying to parse a string as a tag. - ErrDigestInvalidFormat = errors.New("invalid digest format") - - // ErrNameContainsUppercase is returned for invalid repository names that contain uppercase characters. - ErrNameContainsUppercase = errors.New("repository name must be lowercase") - - // ErrNameEmpty is returned for empty, invalid repository names. - ErrNameEmpty = errors.New("repository name must have at least one component") - - // ErrNameTooLong is returned when a repository name is longer than NameTotalLengthMax. - ErrNameTooLong = fmt.Errorf("repository name must not be more than %v characters", NameTotalLengthMax) - - // ErrNameNotCanonical is returned when a name is not canonical. - ErrNameNotCanonical = errors.New("repository name must be canonical") -) - -// Reference is an opaque object reference identifier that may include -// modifiers such as a hostname, name, tag, and digest. -type Reference interface { - // String returns the full reference - String() string -} - -// Field provides a wrapper type for resolving correct reference types when -// working with encoding. -type Field struct { - reference Reference -} - -// AsField wraps a reference in a Field for encoding. -func AsField(reference Reference) Field { - return Field{reference} -} - -// Reference unwraps the reference type from the field to -// return the Reference object. This object should be -// of the appropriate type to further check for different -// reference types. -func (f Field) Reference() Reference { - return f.reference -} - -// MarshalText serializes the field to byte text which -// is the string of the reference. -func (f Field) MarshalText() (p []byte, err error) { - return []byte(f.reference.String()), nil -} - -// UnmarshalText parses text bytes by invoking the -// reference parser to ensure the appropriately -// typed reference object is wrapped by field. -func (f *Field) UnmarshalText(p []byte) error { - r, err := Parse(string(p)) - if err != nil { - return err - } - - f.reference = r - return nil -} - -// Named is an object with a full name -type Named interface { - Reference - Name() string -} - -// Tagged is an object which has a tag -type Tagged interface { - Reference - Tag() string -} - -// NamedTagged is an object including a name and tag. -type NamedTagged interface { - Named - Tag() string -} - -// Digested is an object which has a digest -// in which it can be referenced by -type Digested interface { - Reference - Digest() digest.Digest -} - -// Canonical reference is an object with a fully unique -// name including a name with domain and digest -type Canonical interface { - Named - Digest() digest.Digest -} - -// namedRepository is a reference to a repository with a name. -// A namedRepository has both domain and path components. -type namedRepository interface { - Named - Domain() string - Path() string -} - -// Domain returns the domain part of the Named reference -func Domain(named Named) string { - if r, ok := named.(namedRepository); ok { - return r.Domain() - } - domain, _ := splitDomain(named.Name()) - return domain -} - -// Path returns the name without the domain part of the Named reference -func Path(named Named) (name string) { - if r, ok := named.(namedRepository); ok { - return r.Path() - } - _, path := splitDomain(named.Name()) - return path -} - -func splitDomain(name string) (string, string) { - match := anchoredNameRegexp.FindStringSubmatch(name) - if len(match) != 3 { - return "", name - } - return match[1], match[2] -} - -// SplitHostname splits a named reference into a -// hostname and name string. If no valid hostname is -// found, the hostname is empty and the full value -// is returned as name -// DEPRECATED: Use Domain or Path -func SplitHostname(named Named) (string, string) { - if r, ok := named.(namedRepository); ok { - return r.Domain(), r.Path() - } - return splitDomain(named.Name()) -} - -// Parse parses s and returns a syntactically valid Reference. -// If an error was encountered it is returned, along with a nil Reference. -// NOTE: Parse will not handle short digests. -func Parse(s string) (Reference, error) { - matches := ReferenceRegexp.FindStringSubmatch(s) - if matches == nil { - if s == "" { - return nil, ErrNameEmpty - } - if ReferenceRegexp.FindStringSubmatch(strings.ToLower(s)) != nil { - return nil, ErrNameContainsUppercase - } - return nil, ErrReferenceInvalidFormat - } - - if len(matches[1]) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - var repo repository - - nameMatch := anchoredNameRegexp.FindStringSubmatch(matches[1]) - if nameMatch != nil && len(nameMatch) == 3 { - repo.domain = nameMatch[1] - repo.path = nameMatch[2] - } else { - repo.domain = "" - repo.path = matches[1] - } - - ref := reference{ - namedRepository: repo, - tag: matches[2], - } - if matches[3] != "" { - var err error - ref.digest, err = digest.Parse(matches[3]) - if err != nil { - return nil, err - } - } - - r := getBestReferenceType(ref) - if r == nil { - return nil, ErrNameEmpty - } - - return r, nil -} - -// ParseNamed parses s and returns a syntactically valid reference implementing -// the Named interface. The reference must have a name and be in the canonical -// form, otherwise an error is returned. -// If an error was encountered it is returned, along with a nil Reference. -// NOTE: ParseNamed will not handle short digests. -func ParseNamed(s string) (Named, error) { - named, err := ParseNormalizedNamed(s) - if err != nil { - return nil, err - } - if named.String() != s { - return nil, ErrNameNotCanonical - } - return named, nil -} - -// WithName returns a named object representing the given string. If the input -// is invalid ErrReferenceInvalidFormat will be returned. -func WithName(name string) (Named, error) { - if len(name) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - match := anchoredNameRegexp.FindStringSubmatch(name) - if match == nil || len(match) != 3 { - return nil, ErrReferenceInvalidFormat - } - return repository{ - domain: match[1], - path: match[2], - }, nil -} - -// WithTag combines the name from "name" and the tag from "tag" to form a -// reference incorporating both the name and the tag. -func WithTag(name Named, tag string) (NamedTagged, error) { - if !anchoredTagRegexp.MatchString(tag) { - return nil, ErrTagInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if canonical, ok := name.(Canonical); ok { - return reference{ - namedRepository: repo, - tag: tag, - digest: canonical.Digest(), - }, nil - } - return taggedReference{ - namedRepository: repo, - tag: tag, - }, nil -} - -// WithDigest combines the name from "name" and the digest from "digest" to form -// a reference incorporating both the name and the digest. -func WithDigest(name Named, digest digest.Digest) (Canonical, error) { - if !anchoredDigestRegexp.MatchString(digest.String()) { - return nil, ErrDigestInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if tagged, ok := name.(Tagged); ok { - return reference{ - namedRepository: repo, - tag: tagged.Tag(), - digest: digest, - }, nil - } - return canonicalReference{ - namedRepository: repo, - digest: digest, - }, nil -} - -// TrimNamed removes any tag or digest from the named reference. -func TrimNamed(ref Named) Named { - domain, path := SplitHostname(ref) - return repository{ - domain: domain, - path: path, - } -} - -func getBestReferenceType(ref reference) Reference { - if ref.Name() == "" { - // Allow digest only references - if ref.digest != "" { - return digestReference(ref.digest) - } - return nil - } - if ref.tag == "" { - if ref.digest != "" { - return canonicalReference{ - namedRepository: ref.namedRepository, - digest: ref.digest, - } - } - return ref.namedRepository - } - if ref.digest == "" { - return taggedReference{ - namedRepository: ref.namedRepository, - tag: ref.tag, - } - } - - return ref -} - -type reference struct { - namedRepository - tag string - digest digest.Digest -} - -func (r reference) String() string { - return r.Name() + ":" + r.tag + "@" + r.digest.String() -} - -func (r reference) Tag() string { - return r.tag -} - -func (r reference) Digest() digest.Digest { - return r.digest -} - -type repository struct { - domain string - path string -} - -func (r repository) String() string { - return r.Name() -} - -func (r repository) Name() string { - if r.domain == "" { - return r.path - } - return r.domain + "/" + r.path -} - -func (r repository) Domain() string { - return r.domain -} - -func (r repository) Path() string { - return r.path -} - -type digestReference digest.Digest - -func (d digestReference) String() string { - return digest.Digest(d).String() -} - -func (d digestReference) Digest() digest.Digest { - return digest.Digest(d) -} - -type taggedReference struct { - namedRepository - tag string -} - -func (t taggedReference) String() string { - return t.Name() + ":" + t.tag -} - -func (t taggedReference) Tag() string { - return t.tag -} - -type canonicalReference struct { - namedRepository - digest digest.Digest -} - -func (c canonicalReference) String() string { - return c.Name() + "@" + c.digest.String() -} - -func (c canonicalReference) Digest() digest.Digest { - return c.digest -} diff --git a/vendor/github.com/docker/distribution/reference/regexp.go b/vendor/github.com/docker/distribution/reference/regexp.go deleted file mode 100644 index 78603493..00000000 --- a/vendor/github.com/docker/distribution/reference/regexp.go +++ /dev/null @@ -1,143 +0,0 @@ -package reference - -import "regexp" - -var ( - // alphaNumericRegexp defines the alpha numeric atom, typically a - // component of names. This only allows lower case characters and digits. - alphaNumericRegexp = match(`[a-z0-9]+`) - - // separatorRegexp defines the separators allowed to be embedded in name - // components. This allow one period, one or two underscore and multiple - // dashes. - separatorRegexp = match(`(?:[._]|__|[-]*)`) - - // nameComponentRegexp restricts registry path component names to start - // with at least one letter or number, with following parts able to be - // separated by one period, one or two underscore and multiple dashes. - nameComponentRegexp = expression( - alphaNumericRegexp, - optional(repeated(separatorRegexp, alphaNumericRegexp))) - - // domainComponentRegexp restricts the registry domain component of a - // repository name to start with a component as defined by DomainRegexp - // and followed by an optional port. - domainComponentRegexp = match(`(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])`) - - // DomainRegexp defines the structure of potential domain components - // that may be part of image names. This is purposely a subset of what is - // allowed by DNS to ensure backwards compatibility with Docker image - // names. - DomainRegexp = expression( - domainComponentRegexp, - optional(repeated(literal(`.`), domainComponentRegexp)), - optional(literal(`:`), match(`[0-9]+`))) - - // TagRegexp matches valid tag names. From docker/docker:graph/tags.go. - TagRegexp = match(`[\w][\w.-]{0,127}`) - - // anchoredTagRegexp matches valid tag names, anchored at the start and - // end of the matched string. - anchoredTagRegexp = anchored(TagRegexp) - - // DigestRegexp matches valid digests. - DigestRegexp = match(`[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}`) - - // anchoredDigestRegexp matches valid digests, anchored at the start and - // end of the matched string. - anchoredDigestRegexp = anchored(DigestRegexp) - - // NameRegexp is the format for the name component of references. The - // regexp has capturing groups for the domain and name part omitting - // the separating forward slash from either. - NameRegexp = expression( - optional(DomainRegexp, literal(`/`)), - nameComponentRegexp, - optional(repeated(literal(`/`), nameComponentRegexp))) - - // anchoredNameRegexp is used to parse a name value, capturing the - // domain and trailing components. - anchoredNameRegexp = anchored( - optional(capture(DomainRegexp), literal(`/`)), - capture(nameComponentRegexp, - optional(repeated(literal(`/`), nameComponentRegexp)))) - - // ReferenceRegexp is the full supported format of a reference. The regexp - // is anchored and has capturing groups for name, tag, and digest - // components. - ReferenceRegexp = anchored(capture(NameRegexp), - optional(literal(":"), capture(TagRegexp)), - optional(literal("@"), capture(DigestRegexp))) - - // IdentifierRegexp is the format for string identifier used as a - // content addressable identifier using sha256. These identifiers - // are like digests without the algorithm, since sha256 is used. - IdentifierRegexp = match(`([a-f0-9]{64})`) - - // ShortIdentifierRegexp is the format used to represent a prefix - // of an identifier. A prefix may be used to match a sha256 identifier - // within a list of trusted identifiers. - ShortIdentifierRegexp = match(`([a-f0-9]{6,64})`) - - // anchoredIdentifierRegexp is used to check or match an - // identifier value, anchored at start and end of string. - anchoredIdentifierRegexp = anchored(IdentifierRegexp) - - // anchoredShortIdentifierRegexp is used to check if a value - // is a possible identifier prefix, anchored at start and end - // of string. - anchoredShortIdentifierRegexp = anchored(ShortIdentifierRegexp) -) - -// match compiles the string to a regular expression. -var match = regexp.MustCompile - -// literal compiles s into a literal regular expression, escaping any regexp -// reserved characters. -func literal(s string) *regexp.Regexp { - re := match(regexp.QuoteMeta(s)) - - if _, complete := re.LiteralPrefix(); !complete { - panic("must be a literal") - } - - return re -} - -// expression defines a full expression, where each regular expression must -// follow the previous. -func expression(res ...*regexp.Regexp) *regexp.Regexp { - var s string - for _, re := range res { - s += re.String() - } - - return match(s) -} - -// optional wraps the expression in a non-capturing group and makes the -// production optional. -func optional(res ...*regexp.Regexp) *regexp.Regexp { - return match(group(expression(res...)).String() + `?`) -} - -// repeated wraps the regexp in a non-capturing group to get one or more -// matches. -func repeated(res ...*regexp.Regexp) *regexp.Regexp { - return match(group(expression(res...)).String() + `+`) -} - -// group wraps the regexp in a non-capturing group. -func group(res ...*regexp.Regexp) *regexp.Regexp { - return match(`(?:` + expression(res...).String() + `)`) -} - -// capture wraps the expression in a capturing group. -func capture(res ...*regexp.Regexp) *regexp.Regexp { - return match(`(` + expression(res...).String() + `)`) -} - -// anchored anchors the regular expression by adding start and end delimiters. -func anchored(res ...*regexp.Regexp) *regexp.Regexp { - return match(`^` + expression(res...).String() + `$`) -} diff --git a/vendor/github.com/docker/distribution/registry/api/errcode/errors.go b/vendor/github.com/docker/distribution/registry/api/errcode/errors.go deleted file mode 100644 index 6d9bb4b6..00000000 --- a/vendor/github.com/docker/distribution/registry/api/errcode/errors.go +++ /dev/null @@ -1,267 +0,0 @@ -package errcode - -import ( - "encoding/json" - "fmt" - "strings" -) - -// ErrorCoder is the base interface for ErrorCode and Error allowing -// users of each to just call ErrorCode to get the real ID of each -type ErrorCoder interface { - ErrorCode() ErrorCode -} - -// ErrorCode represents the error type. The errors are serialized via strings -// and the integer format may change and should *never* be exported. -type ErrorCode int - -var _ error = ErrorCode(0) - -// ErrorCode just returns itself -func (ec ErrorCode) ErrorCode() ErrorCode { - return ec -} - -// Error returns the ID/Value -func (ec ErrorCode) Error() string { - // NOTE(stevvooe): Cannot use message here since it may have unpopulated args. - return strings.ToLower(strings.Replace(ec.String(), "_", " ", -1)) -} - -// Descriptor returns the descriptor for the error code. -func (ec ErrorCode) Descriptor() ErrorDescriptor { - d, ok := errorCodeToDescriptors[ec] - - if !ok { - return ErrorCodeUnknown.Descriptor() - } - - return d -} - -// String returns the canonical identifier for this error code. -func (ec ErrorCode) String() string { - return ec.Descriptor().Value -} - -// Message returned the human-readable error message for this error code. -func (ec ErrorCode) Message() string { - return ec.Descriptor().Message -} - -// MarshalText encodes the receiver into UTF-8-encoded text and returns the -// result. -func (ec ErrorCode) MarshalText() (text []byte, err error) { - return []byte(ec.String()), nil -} - -// UnmarshalText decodes the form generated by MarshalText. -func (ec *ErrorCode) UnmarshalText(text []byte) error { - desc, ok := idToDescriptors[string(text)] - - if !ok { - desc = ErrorCodeUnknown.Descriptor() - } - - *ec = desc.Code - - return nil -} - -// WithMessage creates a new Error struct based on the passed-in info and -// overrides the Message property. -func (ec ErrorCode) WithMessage(message string) Error { - return Error{ - Code: ec, - Message: message, - } -} - -// WithDetail creates a new Error struct based on the passed-in info and -// set the Detail property appropriately -func (ec ErrorCode) WithDetail(detail interface{}) Error { - return Error{ - Code: ec, - Message: ec.Message(), - }.WithDetail(detail) -} - -// WithArgs creates a new Error struct and sets the Args slice -func (ec ErrorCode) WithArgs(args ...interface{}) Error { - return Error{ - Code: ec, - Message: ec.Message(), - }.WithArgs(args...) -} - -// Error provides a wrapper around ErrorCode with extra Details provided. -type Error struct { - Code ErrorCode `json:"code"` - Message string `json:"message"` - Detail interface{} `json:"detail,omitempty"` - - // TODO(duglin): See if we need an "args" property so we can do the - // variable substitution right before showing the message to the user -} - -var _ error = Error{} - -// ErrorCode returns the ID/Value of this Error -func (e Error) ErrorCode() ErrorCode { - return e.Code -} - -// Error returns a human readable representation of the error. -func (e Error) Error() string { - return fmt.Sprintf("%s: %s", e.Code.Error(), e.Message) -} - -// WithDetail will return a new Error, based on the current one, but with -// some Detail info added -func (e Error) WithDetail(detail interface{}) Error { - return Error{ - Code: e.Code, - Message: e.Message, - Detail: detail, - } -} - -// WithArgs uses the passed-in list of interface{} as the substitution -// variables in the Error's Message string, but returns a new Error -func (e Error) WithArgs(args ...interface{}) Error { - return Error{ - Code: e.Code, - Message: fmt.Sprintf(e.Code.Message(), args...), - Detail: e.Detail, - } -} - -// ErrorDescriptor provides relevant information about a given error code. -type ErrorDescriptor struct { - // Code is the error code that this descriptor describes. - Code ErrorCode - - // Value provides a unique, string key, often captilized with - // underscores, to identify the error code. This value is used as the - // keyed value when serializing api errors. - Value string - - // Message is a short, human readable decription of the error condition - // included in API responses. - Message string - - // Description provides a complete account of the errors purpose, suitable - // for use in documentation. - Description string - - // HTTPStatusCode provides the http status code that is associated with - // this error condition. - HTTPStatusCode int -} - -// ParseErrorCode returns the value by the string error code. -// `ErrorCodeUnknown` will be returned if the error is not known. -func ParseErrorCode(value string) ErrorCode { - ed, ok := idToDescriptors[value] - if ok { - return ed.Code - } - - return ErrorCodeUnknown -} - -// Errors provides the envelope for multiple errors and a few sugar methods -// for use within the application. -type Errors []error - -var _ error = Errors{} - -func (errs Errors) Error() string { - switch len(errs) { - case 0: - return "" - case 1: - return errs[0].Error() - default: - msg := "errors:\n" - for _, err := range errs { - msg += err.Error() + "\n" - } - return msg - } -} - -// Len returns the current number of errors. -func (errs Errors) Len() int { - return len(errs) -} - -// MarshalJSON converts slice of error, ErrorCode or Error into a -// slice of Error - then serializes -func (errs Errors) MarshalJSON() ([]byte, error) { - var tmpErrs struct { - Errors []Error `json:"errors,omitempty"` - } - - for _, daErr := range errs { - var err Error - - switch daErr.(type) { - case ErrorCode: - err = daErr.(ErrorCode).WithDetail(nil) - case Error: - err = daErr.(Error) - default: - err = ErrorCodeUnknown.WithDetail(daErr) - - } - - // If the Error struct was setup and they forgot to set the - // Message field (meaning its "") then grab it from the ErrCode - msg := err.Message - if msg == "" { - msg = err.Code.Message() - } - - tmpErrs.Errors = append(tmpErrs.Errors, Error{ - Code: err.Code, - Message: msg, - Detail: err.Detail, - }) - } - - return json.Marshal(tmpErrs) -} - -// UnmarshalJSON deserializes []Error and then converts it into slice of -// Error or ErrorCode -func (errs *Errors) UnmarshalJSON(data []byte) error { - var tmpErrs struct { - Errors []Error - } - - if err := json.Unmarshal(data, &tmpErrs); err != nil { - return err - } - - var newErrs Errors - for _, daErr := range tmpErrs.Errors { - // If Message is empty or exactly matches the Code's message string - // then just use the Code, no need for a full Error struct - if daErr.Detail == nil && (daErr.Message == "" || daErr.Message == daErr.Code.Message()) { - // Error's w/o details get converted to ErrorCode - newErrs = append(newErrs, daErr.Code) - } else { - // Error's w/ details are untouched - newErrs = append(newErrs, Error{ - Code: daErr.Code, - Message: daErr.Message, - Detail: daErr.Detail, - }) - } - } - - *errs = newErrs - return nil -} diff --git a/vendor/github.com/docker/distribution/registry/api/errcode/handler.go b/vendor/github.com/docker/distribution/registry/api/errcode/handler.go deleted file mode 100644 index d77e7047..00000000 --- a/vendor/github.com/docker/distribution/registry/api/errcode/handler.go +++ /dev/null @@ -1,40 +0,0 @@ -package errcode - -import ( - "encoding/json" - "net/http" -) - -// ServeJSON attempts to serve the errcode in a JSON envelope. It marshals err -// and sets the content-type header to 'application/json'. It will handle -// ErrorCoder and Errors, and if necessary will create an envelope. -func ServeJSON(w http.ResponseWriter, err error) error { - w.Header().Set("Content-Type", "application/json; charset=utf-8") - var sc int - - switch errs := err.(type) { - case Errors: - if len(errs) < 1 { - break - } - - if err, ok := errs[0].(ErrorCoder); ok { - sc = err.ErrorCode().Descriptor().HTTPStatusCode - } - case ErrorCoder: - sc = errs.ErrorCode().Descriptor().HTTPStatusCode - err = Errors{err} // create an envelope. - default: - // We just have an unhandled error type, so just place in an envelope - // and move along. - err = Errors{err} - } - - if sc == 0 { - sc = http.StatusInternalServerError - } - - w.WriteHeader(sc) - - return json.NewEncoder(w).Encode(err) -} diff --git a/vendor/github.com/docker/distribution/registry/api/errcode/register.go b/vendor/github.com/docker/distribution/registry/api/errcode/register.go deleted file mode 100644 index d1e8826c..00000000 --- a/vendor/github.com/docker/distribution/registry/api/errcode/register.go +++ /dev/null @@ -1,138 +0,0 @@ -package errcode - -import ( - "fmt" - "net/http" - "sort" - "sync" -) - -var ( - errorCodeToDescriptors = map[ErrorCode]ErrorDescriptor{} - idToDescriptors = map[string]ErrorDescriptor{} - groupToDescriptors = map[string][]ErrorDescriptor{} -) - -var ( - // ErrorCodeUnknown is a generic error that can be used as a last - // resort if there is no situation-specific error message that can be used - ErrorCodeUnknown = Register("errcode", ErrorDescriptor{ - Value: "UNKNOWN", - Message: "unknown error", - Description: `Generic error returned when the error does not have an - API classification.`, - HTTPStatusCode: http.StatusInternalServerError, - }) - - // ErrorCodeUnsupported is returned when an operation is not supported. - ErrorCodeUnsupported = Register("errcode", ErrorDescriptor{ - Value: "UNSUPPORTED", - Message: "The operation is unsupported.", - Description: `The operation was unsupported due to a missing - implementation or invalid set of parameters.`, - HTTPStatusCode: http.StatusMethodNotAllowed, - }) - - // ErrorCodeUnauthorized is returned if a request requires - // authentication. - ErrorCodeUnauthorized = Register("errcode", ErrorDescriptor{ - Value: "UNAUTHORIZED", - Message: "authentication required", - Description: `The access controller was unable to authenticate - the client. Often this will be accompanied by a - Www-Authenticate HTTP response header indicating how to - authenticate.`, - HTTPStatusCode: http.StatusUnauthorized, - }) - - // ErrorCodeDenied is returned if a client does not have sufficient - // permission to perform an action. - ErrorCodeDenied = Register("errcode", ErrorDescriptor{ - Value: "DENIED", - Message: "requested access to the resource is denied", - Description: `The access controller denied access for the - operation on a resource.`, - HTTPStatusCode: http.StatusForbidden, - }) - - // ErrorCodeUnavailable provides a common error to report unavailability - // of a service or endpoint. - ErrorCodeUnavailable = Register("errcode", ErrorDescriptor{ - Value: "UNAVAILABLE", - Message: "service unavailable", - Description: "Returned when a service is not available", - HTTPStatusCode: http.StatusServiceUnavailable, - }) - - // ErrorCodeTooManyRequests is returned if a client attempts too many - // times to contact a service endpoint. - ErrorCodeTooManyRequests = Register("errcode", ErrorDescriptor{ - Value: "TOOMANYREQUESTS", - Message: "too many requests", - Description: `Returned when a client attempts to contact a - service too many times`, - HTTPStatusCode: http.StatusTooManyRequests, - }) -) - -var nextCode = 1000 -var registerLock sync.Mutex - -// Register will make the passed-in error known to the environment and -// return a new ErrorCode -func Register(group string, descriptor ErrorDescriptor) ErrorCode { - registerLock.Lock() - defer registerLock.Unlock() - - descriptor.Code = ErrorCode(nextCode) - - if _, ok := idToDescriptors[descriptor.Value]; ok { - panic(fmt.Sprintf("ErrorValue %q is already registered", descriptor.Value)) - } - if _, ok := errorCodeToDescriptors[descriptor.Code]; ok { - panic(fmt.Sprintf("ErrorCode %v is already registered", descriptor.Code)) - } - - groupToDescriptors[group] = append(groupToDescriptors[group], descriptor) - errorCodeToDescriptors[descriptor.Code] = descriptor - idToDescriptors[descriptor.Value] = descriptor - - nextCode++ - return descriptor.Code -} - -type byValue []ErrorDescriptor - -func (a byValue) Len() int { return len(a) } -func (a byValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byValue) Less(i, j int) bool { return a[i].Value < a[j].Value } - -// GetGroupNames returns the list of Error group names that are registered -func GetGroupNames() []string { - keys := []string{} - - for k := range groupToDescriptors { - keys = append(keys, k) - } - sort.Strings(keys) - return keys -} - -// GetErrorCodeGroup returns the named group of error descriptors -func GetErrorCodeGroup(name string) []ErrorDescriptor { - desc := groupToDescriptors[name] - sort.Sort(byValue(desc)) - return desc -} - -// GetErrorAllDescriptors returns a slice of all ErrorDescriptors that are -// registered, irrespective of what group they're in -func GetErrorAllDescriptors() []ErrorDescriptor { - result := []ErrorDescriptor{} - - for _, group := range GetGroupNames() { - result = append(result, GetErrorCodeGroup(group)...) - } - sort.Sort(byValue(result)) - return result -} diff --git a/vendor/github.com/docker/docker/AUTHORS b/vendor/github.com/docker/docker/AUTHORS deleted file mode 100644 index dffacff1..00000000 --- a/vendor/github.com/docker/docker/AUTHORS +++ /dev/null @@ -1,2175 +0,0 @@ -# This file lists all individuals having contributed content to the repository. -# For how it is generated, see `hack/generate-authors.sh`. - -Aanand Prasad -Aaron Davidson -Aaron Feng -Aaron Hnatiw -Aaron Huslage -Aaron L. Xu -Aaron Lehmann -Aaron Welch -Aaron.L.Xu -Abel Muiño -Abhijeet Kasurde -Abhinandan Prativadi -Abhinav Ajgaonkar -Abhishek Chanda -Abhishek Sharma -Abin Shahab -Adam Avilla -Adam Dobrawy -Adam Eijdenberg -Adam Kunk -Adam Miller -Adam Mills -Adam Pointer -Adam Singer -Adam Walz -Addam Hardy -Aditi Rajagopal -Aditya -Adnan Khan -Adolfo Ochagavía -Adria Casas -Adrian Moisey -Adrian Mouat -Adrian Oprea -Adrien Folie -Adrien Gallouët -Ahmed Kamal -Ahmet Alp Balkan -Aidan Feldman -Aidan Hobson Sayers -AJ Bowen -Ajey Charantimath -ajneu -Akash Gupta -Akhil Mohan -Akihiro Matsushima -Akihiro Suda -Akim Demaille -Akira Koyasu -Akshay Karle -Al Tobey -alambike -Alan Hoyle -Alan Scherger -Alan Thompson -Albert Callarisa -Albert Zhang -Albin Kerouanton -Alejandro González Hevia -Aleksa Sarai -Aleksandrs Fadins -Alena Prokharchyk -Alessandro Boch -Alessio Biancalana -Alex Chan -Alex Chen -Alex Coventry -Alex Crawford -Alex Ellis -Alex Gaynor -Alex Goodman -Alex Olshansky -Alex Samorukov -Alex Warhawk -Alexander Artemenko -Alexander Boyd -Alexander Larsson -Alexander Midlash -Alexander Morozov -Alexander Shopov -Alexandre Beslic -Alexandre Garnier -Alexandre González -Alexandre Jomin -Alexandru Sfirlogea -Alexei Margasov -Alexey Guskov -Alexey Kotlyarov -Alexey Shamrin -Alexis THOMAS -Alfred Landrum -Ali Dehghani -Alicia Lauerman -Alihan Demir -Allen Madsen -Allen Sun -almoehi -Alvaro Saurin -Alvin Deng -Alvin Richards -amangoel -Amen Belayneh -Amir Goldstein -Amit Bakshi -Amit Krishnan -Amit Shukla -Amr Gawish -Amy Lindburg -Anand Patil -AnandkumarPatel -Anatoly Borodin -Anca Iordache -Anchal Agrawal -Anda Xu -Anders Janmyr -Andre Dublin <81dublin@gmail.com> -Andre Granovsky -Andrea Denisse Gómez -Andrea Luzzardi -Andrea Turli -Andreas Elvers -Andreas Köhler -Andreas Savvides -Andreas Tiefenthaler -Andrei Gherzan -Andrei Vagin -Andrew C. Bodine -Andrew Clay Shafer -Andrew Duckworth -Andrew France -Andrew Gerrand -Andrew Guenther -Andrew He -Andrew Hsu -Andrew Kuklewicz -Andrew Macgregor -Andrew Macpherson -Andrew Martin -Andrew McDonnell -Andrew Munsell -Andrew Pennebaker -Andrew Po -Andrew Weiss -Andrew Williams -Andrews Medina -Andrey Kolomentsev -Andrey Petrov -Andrey Stolbovsky -André Martins -andy -Andy Chambers -andy diller -Andy Goldstein -Andy Kipp -Andy Rothfusz -Andy Smith -Andy Wilson -Anes Hasicic -Anil Belur -Anil Madhavapeddy -Ankit Jain -Ankush Agarwal -Anonmily -Anran Qiao -Anshul Pundir -Anthon van der Neut -Anthony Baire -Anthony Bishopric -Anthony Dahanne -Anthony Sottile -Anton Löfgren -Anton Nikitin -Anton Polonskiy -Anton Tiurin -Antonio Murdaca -Antonis Kalipetis -Antony Messerli -Anuj Bahuguna -Anusha Ragunathan -apocas -Arash Deshmeh -ArikaChen -Arko Dasgupta -Arnaud Lefebvre -Arnaud Porterie -Arnaud Rebillout -Arthur Barr -Arthur Gautier -Artur Meyster -Arun Gupta -Asad Saeeduddin -Asbjørn Enge -averagehuman -Avi Das -Avi Kivity -Avi Miller -Avi Vaid -ayoshitake -Azat Khuyiyakhmetov -Bardia Keyoumarsi -Barnaby Gray -Barry Allard -Bartłomiej Piotrowski -Bastiaan Bakker -bdevloed -Ben Bonnefoy -Ben Firshman -Ben Golub -Ben Gould -Ben Hall -Ben Sargent -Ben Severson -Ben Toews -Ben Wiklund -Benjamin Atkin -Benjamin Baker -Benjamin Boudreau -Benjamin Yolken -Benny Ng -Benoit Chesneau -Bernerd Schaefer -Bernhard M. Wiedemann -Bert Goethals -Bertrand Roussel -Bevisy Zhang -Bharath Thiruveedula -Bhiraj Butala -Bhumika Bayani -Bilal Amarni -Bill Wang -Bily Zhang -Bin Liu -Bingshen Wang -Blake Geno -Boaz Shuster -bobby abbott -Boqin Qin -Boris Pruessmann -Boshi Lian -Bouke Haarsma -Boyd Hemphill -boynux -Bradley Cicenas -Bradley Wright -Brandon Liu -Brandon Philips -Brandon Rhodes -Brendan Dixon -Brent Salisbury -Brett Higgins -Brett Kochendorfer -Brett Randall -Brian (bex) Exelbierd -Brian Bland -Brian DeHamer -Brian Dorsey -Brian Flad -Brian Goff -Brian McCallister -Brian Olsen -Brian Schwind -Brian Shumate -Brian Torres-Gil -Brian Trump -Brice Jaglin -Briehan Lombaard -Brielle Broder -Bruno Bigras -Bruno Binet -Bruno Gazzera -Bruno Renié -Bruno Tavares -Bryan Bess -Bryan Boreham -Bryan Matsuo -Bryan Murphy -Burke Libbey -Byung Kang -Caleb Spare -Calen Pennington -Cameron Boehmer -Cameron Spear -Campbell Allen -Candid Dauth -Cao Weiwei -Carl Henrik Lunde -Carl Loa Odin -Carl X. Su -Carlo Mion -Carlos Alexandro Becker -Carlos de Paula -Carlos Sanchez -Carol Fager-Higgins -Cary -Casey Bisson -Catalin Pirvu -Ce Gao -Cedric Davies -Cezar Sa Espinola -Chad Swenson -Chance Zibolski -Chander Govindarajan -Chanhun Jeong -Chao Wang -Charles Chan -Charles Hooper -Charles Law -Charles Lindsay -Charles Merriam -Charles Sarrazin -Charles Smith -Charlie Drage -Charlie Lewis -Chase Bolt -ChaYoung You -Chen Chao -Chen Chuanliang -Chen Hanxiao -Chen Min -Chen Mingjie -Chen Qiu -Cheng-mean Liu -Chengfei Shang -Chengguang Xu -chenyuzhu -Chetan Birajdar -Chewey -Chia-liang Kao -chli -Cholerae Hu -Chris Alfonso -Chris Armstrong -Chris Dias -Chris Dituri -Chris Fordham -Chris Gavin -Chris Gibson -Chris Khoo -Chris McKinnel -Chris McKinnel -Chris Price -Chris Seto -Chris Snow -Chris St. Pierre -Chris Stivers -Chris Swan -Chris Telfer -Chris Wahl -Chris Weyl -Chris White -Christian Berendt -Christian Brauner -Christian Böhme -Christian Muehlhaeuser -Christian Persson -Christian Rotzoll -Christian Simon -Christian Stefanescu -Christophe Mehay -Christophe Troestler -Christophe Vidal -Christopher Biscardi -Christopher Crone -Christopher Currie -Christopher Jones -Christopher Latham -Christopher Rigor -Christy Norman -Chun Chen -Ciro S. Costa -Clayton Coleman -Clinton Kitson -Cody Roseborough -Coenraad Loubser -Colin Dunklau -Colin Hebert -Colin Panisset -Colin Rice -Colin Walters -Collin Guarino -Colm Hally -companycy -Corbin Coleman -Corey Farrell -Cory Forsyth -cressie176 -CrimsonGlory -Cristian Ariza -Cristian Staretu -cristiano balducci -Cristina Yenyxe Gonzalez Garcia -Cruceru Calin-Cristian -CUI Wei -Cyprian Gracz -Cyril F -Daan van Berkel -Daehyeok Mun -Dafydd Crosby -dalanlan -Damian Smyth -Damien Nadé -Damien Nozay -Damjan Georgievski -Dan Anolik -Dan Buch -Dan Cotora -Dan Feldman -Dan Griffin -Dan Hirsch -Dan Keder -Dan Levy -Dan McPherson -Dan Stine -Dan Williams -Dani Hodovic -Dani Louca -Daniel Antlinger -Daniel Black -Daniel Dao -Daniel Exner -Daniel Farrell -Daniel Garcia -Daniel Gasienica -Daniel Grunwell -Daniel Helfand -Daniel Hiltgen -Daniel J Walsh -Daniel Menet -Daniel Mizyrycki -Daniel Nephin -Daniel Norberg -Daniel Nordberg -Daniel Robinson -Daniel S -Daniel Sweet -Daniel Von Fange -Daniel Watkins -Daniel X Moore -Daniel YC Lin -Daniel Zhang -Danny Berger -Danny Milosavljevic -Danny Yates -Danyal Khaliq -Darren Coxall -Darren Shepherd -Darren Stahl -Dattatraya Kumbhar -Davanum Srinivas -Dave Barboza -Dave Goodchild -Dave Henderson -Dave MacDonald -Dave Tucker -David Anderson -David Calavera -David Chung -David Corking -David Cramer -David Currie -David Davis -David Dooling -David Gageot -David Gebler -David Glasser -David Lawrence -David Lechner -David M. Karr -David Mackey -David Mat -David Mcanulty -David McKay -David P Hilton -David Pelaez -David R. Jenni -David Röthlisberger -David Sheets -David Sissitka -David Trott -David Wang <00107082@163.com> -David Williamson -David Xia -David Young -Davide Ceretti -Dawn Chen -dbdd -dcylabs -Debayan De -Deborah Gertrude Digges -deed02392 -Deep Debroy -Deng Guangxing -Deni Bertovic -Denis Defreyne -Denis Gladkikh -Denis Ollier -Dennis Chen -Dennis Chen -Dennis Docter -Derek -Derek -Derek Ch -Derek McGowan -Deric Crago -Deshi Xiao -devmeyster -Devon Estes -Devvyn Murphy -Dharmit Shah -Dhawal Yogesh Bhanushali -Diego Romero -Diego Siqueira -Dieter Reuter -Dillon Dixon -Dima Stopel -Dimitri John Ledkov -Dimitris Mandalidis -Dimitris Rozakis -Dimitry Andric -Dinesh Subhraveti -Ding Fei -Diogo Monica -DiuDiugirl -Djibril Koné -dkumor -Dmitri Logvinenko -Dmitri Shuralyov -Dmitry Demeshchuk -Dmitry Gusev -Dmitry Kononenko -Dmitry Sharshakov -Dmitry Shyshkin -Dmitry Smirnov -Dmitry V. Krivenok -Dmitry Vorobev -Dolph Mathews -Dominic Tubach -Dominic Yin -Dominik Dingel -Dominik Finkbeiner -Dominik Honnef -Don Kirkby -Don Kjer -Don Spaulding -Donald Huang -Dong Chen -Donghwa Kim -Donovan Jones -Doron Podoleanu -Doug Davis -Doug MacEachern -Doug Tangren -Douglas Curtis -Dr Nic Williams -dragon788 -Dražen Lučanin -Drew Erny -Drew Hubl -Dustin Sallings -Ed Costello -Edmund Wagner -Eiichi Tsukata -Eike Herzbach -Eivin Giske Skaaren -Eivind Uggedal -Elan Ruusamäe -Elango Sivanandam -Elena Morozova -Eli Uriegas -Elias Faxö -Elias Probst -Elijah Zupancic -eluck -Elvir Kuric -Emil Davtyan -Emil Hernvall -Emily Maier -Emily Rose -Emir Ozer -Enguerran -Eohyung Lee -epeterso -Eric Barch -Eric Curtin -Eric G. Noriega -Eric Hanchrow -Eric Lee -Eric Myhre -Eric Paris -Eric Rafaloff -Eric Rosenberg -Eric Sage -Eric Soderstrom -Eric Yang -Eric-Olivier Lamey -Erica Windisch -Erik Bray -Erik Dubbelboer -Erik Hollensbe -Erik Inge Bolsø -Erik Kristensen -Erik St. Martin -Erik Weathers -Erno Hopearuoho -Erwin van der Koogh -Ethan Bell -Ethan Mosbaugh -Euan Kemp -Eugen Krizo -Eugene Yakubovich -Evan Allrich -Evan Carmi -Evan Hazlett -Evan Krall -Evan Phoenix -Evan Wies -Evelyn Xu -Everett Toews -Evgeniy Makhrov -Evgeny Shmarnev -Evgeny Vereshchagin -Ewa Czechowska -Eystein Måløy Stenberg -ezbercih -Ezra Silvera -Fabian Kramm -Fabian Lauer -Fabian Raetz -Fabiano Rosas -Fabio Falci -Fabio Kung -Fabio Rapposelli -Fabio Rehm -Fabrizio Regini -Fabrizio Soppelsa -Faiz Khan -falmp -Fangming Fang -Fangyuan Gao <21551127@zju.edu.cn> -fanjiyun -Fareed Dudhia -Fathi Boudra -Federico Gimenez -Felipe Oliveira -Felipe Ruhland -Felix Abecassis -Felix Geisendörfer -Felix Hupfeld -Felix Rabe -Felix Ruess -Felix Schindler -Feng Yan -Fengtu Wang -Ferenc Szabo -Fernando -Fero Volar -Ferran Rodenas -Filipe Brandenburger -Filipe Oliveira -Flavio Castelli -Flavio Crisciani -Florian -Florian Klein -Florian Maier -Florian Noeding -Florian Schmaus -Florian Weingarten -Florin Asavoaie -Florin Patan -fonglh -Foysal Iqbal -Francesc Campoy -Francesco Mari -Francis Chuang -Francisco Carriedo -Francisco Souza -Frank Groeneveld -Frank Herrmann -Frank Macreery -Frank Rosquin -frankyang -Fred Lifton -Frederick F. Kautz IV -Frederik Loeffert -Frederik Nordahl Jul Sabroe -Freek Kalter -Frieder Bluemle -Fu JinLin -Félix Baylac-Jacqué -Félix Cantournet -Gabe Rosenhouse -Gabor Nagy -Gabriel Linder -Gabriel Monroy -Gabriel Nicolas Avellaneda -Gaetan de Villele -Galen Sampson -Gang Qiao -Gareth Rushgrove -Garrett Barboza -Gary Schaetz -Gaurav -Gaurav Singh -Gaël PORTAY -Genki Takiuchi -GennadySpb -Geoffrey Bachelet -Geon Kim -George Kontridze -George MacRorie -George Xie -Georgi Hristozov -Gereon Frey -German DZ -Gert van Valkenhoef -Gerwim Feiken -Ghislain Bourgeois -Giampaolo Mancini -Gianluca Borello -Gildas Cuisinier -Giovan Isa Musthofa -gissehel -Giuseppe Mazzotta -Gleb Fotengauer-Malinovskiy -Gleb M Borisov -Glyn Normington -GoBella -Goffert van Gool -Goldwyn Rodrigues -Gopikannan Venugopalsamy -Gosuke Miyashita -Gou Rao -Govinda Fichtner -Grant Millar -Grant Reaber -Graydon Hoare -Greg Fausak -Greg Pflaum -Greg Stephens -Greg Thornton -Grzegorz Jaśkiewicz -Guilhem Lettron -Guilherme Salgado -Guillaume Dufour -Guillaume J. Charmes -guoxiuyan -Guri -Gurjeet Singh -Guruprasad -Gustav Sinder -gwx296173 -Günter Zöchbauer -Haichao Yang -haikuoliu -Hakan Özler -Hamish Hutchings -Hannes Ljungberg -Hans Kristian Flaatten -Hans Rødtang -Hao Shu Wei -Hao Zhang <21521210@zju.edu.cn> -Harald Albers -Harald Niesche -Harley Laue -Harold Cooper -Harrison Turton -Harry Zhang -Harshal Patil -Harshal Patil -He Simei -He Xiaoxi -He Xin -heartlock <21521209@zju.edu.cn> -Hector Castro -Helen Xie -Henning Sprang -Hiroshi Hatake -Hiroyuki Sasagawa -Hobofan -Hollie Teal -Hong Xu -Hongbin Lu -Hongxu Jia -Honza Pokorny -Hsing-Hui Hsu -hsinko <21551195@zju.edu.cn> -Hu Keping -Hu Tao -HuanHuan Ye -Huanzhong Zhang -Huayi Zhang -Hugo Duncan -Hugo Marisco <0x6875676f@gmail.com> -Hunter Blanks -huqun -Huu Nguyen -hyeongkyu.lee -Hyzhou Zhy -Iago López Galeiras -Ian Babrou -Ian Bishop -Ian Bull -Ian Calvert -Ian Campbell -Ian Chen -Ian Lee -Ian Main -Ian Philpot -Ian Truslove -Iavael -Icaro Seara -Ignacio Capurro -Igor Dolzhikov -Igor Karpovich -Iliana Weller -Ilkka Laukkanen -Ilya Dmitrichenko -Ilya Gusev -Ilya Khlopotov -imre Fitos -inglesp -Ingo Gottwald -Innovimax -Isaac Dupree -Isabel Jimenez -Isaiah Grace -Isao Jonas -Iskander Sharipov -Ivan Babrou -Ivan Fraixedes -Ivan Grcic -Ivan Markin -J Bruni -J. Nunn -Jack Danger Canty -Jack Laxson -Jacob Atzen -Jacob Edelman -Jacob Tomlinson -Jacob Vallejo -Jacob Wen -Jaime Cepeda -Jaivish Kothari -Jake Champlin -Jake Moshenko -Jake Sanders -jakedt -James Allen -James Carey -James Carr -James DeFelice -James Harrison Fisher -James Kyburz -James Kyle -James Lal -James Mills -James Nesbitt -James Nugent -James Turnbull -James Watkins-Harvey -Jamie Hannaford -Jamshid Afshar -Jan Chren -Jan Keromnes -Jan Koprowski -Jan Pazdziora -Jan Toebes -Jan-Gerd Tenberge -Jan-Jaap Driessen -Jana Radhakrishnan -Jannick Fahlbusch -Januar Wayong -Jared Biel -Jared Hocutt -Jaroslaw Zabiello -jaseg -Jasmine Hegman -Jason A. Donenfeld -Jason Divock -Jason Giedymin -Jason Green -Jason Hall -Jason Heiss -Jason Livesay -Jason McVetta -Jason Plum -Jason Shepherd -Jason Smith -Jason Sommer -Jason Stangroome -jaxgeller -Jay -Jay -Jay Kamat -Jean Rouge -Jean-Baptiste Barth -Jean-Baptiste Dalido -Jean-Christophe Berthon -Jean-Paul Calderone -Jean-Pierre Huynh -Jean-Tiare Le Bigot -Jeeva S. Chelladhurai -Jeff Anderson -Jeff Hajewski -Jeff Johnston -Jeff Lindsay -Jeff Mickey -Jeff Minard -Jeff Nickoloff -Jeff Silberman -Jeff Welch -Jeffrey Bolle -Jeffrey Morgan -Jeffrey van Gogh -Jenny Gebske -Jeremy Chambers -Jeremy Grosser -Jeremy Price -Jeremy Qian -Jeremy Unruh -Jeremy Yallop -Jeroen Franse -Jeroen Jacobs -Jesse Dearing -Jesse Dubay -Jessica Frazelle -Jezeniel Zapanta -Jhon Honce -Ji.Zhilong -Jian Liao -Jian Zhang -Jiang Jinyang -Jie Luo -Jie Ma -Jihyun Hwang -Jilles Oldenbeuving -Jim Alateras -Jim Ehrismann -Jim Galasyn -Jim Minter -Jim Perrin -Jimmy Cuadra -Jimmy Puckett -Jimmy Song -Jinsoo Park -Jintao Zhang -Jiri Appl -Jiri Popelka -Jiuyue Ma -Jiří Župka -Joao Fernandes -Joao Trindade -Joe Beda -Joe Doliner -Joe Ferguson -Joe Gordon -Joe Shaw -Joe Van Dyk -Joel Friedly -Joel Handwell -Joel Hansson -Joel Wurtz -Joey Geiger -Joey Geiger -Joey Gibson -Joffrey F -Johan Euphrosine -Johan Rydberg -Johanan Lieberman -Johannes 'fish' Ziemke -John Costa -John Feminella -John Gardiner Myers -John Gossman -John Harris -John Howard -John Laswell -John Maguire -John Mulhausen -John OBrien III -John Starks -John Stephens -John Tims -John V. Martinez -John Warwick -John Willis -Jon Johnson -Jon Surrell -Jon Wedaman -Jonas Dohse -Jonas Heinrich -Jonas Pfenniger -Jonathan A. Schweder -Jonathan A. Sternberg -Jonathan Boulle -Jonathan Camp -Jonathan Choy -Jonathan Dowland -Jonathan Lebon -Jonathan Lomas -Jonathan McCrohan -Jonathan Mueller -Jonathan Pares -Jonathan Rudenberg -Jonathan Stoppani -Jonh Wendell -Joni Sar -Joost Cassee -Jordan Arentsen -Jordan Jennings -Jordan Sissel -Jorge Marin -Jorit Kleine-Möllhoff -Jose Diaz-Gonzalez -Joseph Anthony Pasquale Holsten -Joseph Hager -Joseph Kern -Joseph Rothrock -Josh -Josh Bodah -Josh Bonczkowski -Josh Chorlton -Josh Eveleth -Josh Hawn -Josh Horwitz -Josh Poimboeuf -Josh Soref -Josh Wilson -Josiah Kiehl -José Tomás Albornoz -Joyce Jang -JP -Julian Taylor -Julien Barbier -Julien Bisconti -Julien Bordellier -Julien Dubois -Julien Kassar -Julien Maitrehenry -Julien Pervillé -Julien Pivotto -Julio Guerra -Julio Montes -Jun-Ru Chang -Jussi Nummelin -Justas Brazauskas -Justen Martin -Justin Cormack -Justin Force -Justin Menga -Justin Plock -Justin Simonelis -Justin Terry -Justyn Temme -Jyrki Puttonen -Jérémy Leherpeur -Jérôme Petazzoni -Jörg Thalheim -K. Heller -Kai Blin -Kai Qiang Wu (Kennan) -Kamil Domański -Kamjar Gerami -Kanstantsin Shautsou -Kara Alexandra -Karan Lyons -Kareem Khazem -kargakis -Karl Grzeszczak -Karol Duleba -Karthik Karanth -Karthik Nayak -Kasper Fabæch Brandt -Kate Heddleston -Katie McLaughlin -Kato Kazuyoshi -Katrina Owen -Kawsar Saiyeed -Kay Yan -kayrus -Kazuhiro Sera -Ke Li -Ke Xu -Kei Ohmura -Keith Hudgins -Keli Hu -Ken Cochrane -Ken Herner -Ken ICHIKAWA -Ken Reese -Kenfe-Mickaël Laventure -Kenjiro Nakayama -Kent Johnson -Kenta Tada -Kevin "qwazerty" Houdebert -Kevin Burke -Kevin Clark -Kevin Feyrer -Kevin J. Lynagh -Kevin Jing Qiu -Kevin Kern -Kevin Menard -Kevin Meredith -Kevin P. Kucharczyk -Kevin Parsons -Kevin Richardson -Kevin Shi -Kevin Wallace -Kevin Yap -Keyvan Fatehi -kies -Kim BKC Carlbacker -Kim Eik -Kimbro Staken -Kir Kolyshkin -Kiran Gangadharan -Kirill SIbirev -knappe -Kohei Tsuruta -Koichi Shiraishi -Konrad Kleine -Konstantin Gribov -Konstantin L -Konstantin Pelykh -Krasi Georgiev -Krasimir Georgiev -Kris-Mikael Krister -Kristian Haugene -Kristina Zabunova -Krystian Wojcicki -Kun Zhang -Kunal Kushwaha -Kunal Tyagi -Kyle Conroy -Kyle Linden -Kyle Wuolle -kyu -Lachlan Coote -Lai Jiangshan -Lajos Papp -Lakshan Perera -Lalatendu Mohanty -Lance Chen -Lance Kinley -Lars Butler -Lars Kellogg-Stedman -Lars R. Damerow -Lars-Magnus Skog -Laszlo Meszaros -Laura Frank -Laurent Erignoux -Laurie Voss -Leandro Siqueira -Lee Chao <932819864@qq.com> -Lee, Meng-Han -leeplay -Lei Gong -Lei Jitang -Len Weincier -Lennie -Leo Gallucci -Leszek Kowalski -Levi Blackstone -Levi Gross -Lewis Daly -Lewis Marshall -Lewis Peckover -Li Yi -Liam Macgillavry -Liana Lo -Liang Mingqiang -Liang-Chi Hsieh -Liao Qingwei -Lifubang -Lihua Tang -Lily Guo -limsy -Lin Lu -LingFaKe -Linus Heckemann -Liran Tal -Liron Levin -Liu Bo -Liu Hua -liwenqi -lixiaobing10051267 -Liz Zhang -LIZAO LI -Lizzie Dixon <_@lizzie.io> -Lloyd Dewolf -Lokesh Mandvekar -longliqiang88 <394564827@qq.com> -Lorenz Leutgeb -Lorenzo Fontana -Lotus Fenn -Louis Delossantos -Louis Opter -Luca Favatella -Luca Marturana -Luca Orlandi -Luca-Bogdan Grigorescu -Lucas Chan -Lucas Chi -Lucas Molas -Lucas Silvestre -Luciano Mores -Luis Martínez de Bartolomé Izquierdo -Luiz Svoboda -Lukas Heeren -Lukas Waslowski -lukaspustina -Lukasz Zajaczkowski -Luke Marsden -Lyn -Lynda O'Leary -Lénaïc Huard -Ma Müller -Ma Shimiao -Mabin -Madhan Raj Mookkandy -Madhav Puri -Madhu Venugopal -Mageee -Mahesh Tiyyagura -malnick -Malte Janduda -Manfred Touron -Manfred Zabarauskas -Manjunath A Kumatagi -Mansi Nahar -Manuel Meurer -Manuel Rüger -Manuel Woelker -mapk0y -Marc Abramowitz -Marc Kuo -Marc Tamsky -Marcel Edmund Franke -Marcelo Horacio Fortino -Marcelo Salazar -Marco Hennings -Marcus Cobden -Marcus Farkas -Marcus Linke -Marcus Martins -Marcus Ramberg -Marek Goldmann -Marian Marinov -Marianna Tessel -Mario Loriedo -Marius Gundersen -Marius Sturm -Marius Voila -Mark Allen -Mark Jeromin -Mark McGranaghan -Mark McKinstry -Mark Milstein -Mark Oates -Mark Parker -Mark West -Markan Patel -Marko Mikulicic -Marko Tibold -Markus Fix -Markus Kortlang -Martijn Dwars -Martijn van Oosterhout -Martin Honermeyer -Martin Kelly -Martin Mosegaard Amdisen -Martin Muzatko -Martin Redmond -Mary Anthony -Masahito Zembutsu -Masato Ohba -Masayuki Morita -Mason Malone -Mateusz Sulima -Mathias Monnerville -Mathieu Champlon -Mathieu Le Marec - Pasquet -Mathieu Parent -Matt Apperson -Matt Bachmann -Matt Bentley -Matt Haggard -Matt Hoyle -Matt McCormick -Matt Moore -Matt Richardson -Matt Rickard -Matt Robenolt -Matt Schurenko -Matt Williams -Matthew Heon -Matthew Lapworth -Matthew Mayer -Matthew Mosesohn -Matthew Mueller -Matthew Riley -Matthias Klumpp -Matthias Kühnle -Matthias Rampke -Matthieu Hauglustaine -Mattias Jernberg -Mauricio Garavaglia -mauriyouth -Max Harmathy -Max Shytikov -Maxim Fedchyshyn -Maxim Ivanov -Maxim Kulkin -Maxim Treskin -Maxime Petazzoni -Maximiliano Maccanti -Maxwell -Meaglith Ma -meejah -Megan Kostick -Mehul Kar -Mei ChunTao -Mengdi Gao -Mert Yazıcıoğlu -mgniu -Micah Zoltu -Michael A. Smith -Michael Bridgen -Michael Brown -Michael Chiang -Michael Crosby -Michael Currie -Michael Friis -Michael Gorsuch -Michael Grauer -Michael Holzheu -Michael Hudson-Doyle -Michael Huettermann -Michael Irwin -Michael Käufl -Michael Neale -Michael Nussbaum -Michael Prokop -Michael Scharf -Michael Spetsiotis -Michael Stapelberg -Michael Steinert -Michael Thies -Michael West -Michael Zhao -Michal Fojtik -Michal Gebauer -Michal Jemala -Michal Minář -Michal Wieczorek -Michaël Pailloncy -Michał Czeraszkiewicz -Michał Gryko -Michiel de Jong -Mickaël Fortunato -Mickaël Remars -Miguel Angel Fernández -Miguel Morales -Mihai Borobocea -Mihuleacc Sergiu -Mike Brown -Mike Bush -Mike Casas -Mike Chelen -Mike Danese -Mike Dillon -Mike Dougherty -Mike Estes -Mike Gaffney -Mike Goelzer -Mike Leone -Mike Lundy -Mike MacCana -Mike Naberezny -Mike Snitzer -mikelinjie <294893458@qq.com> -Mikhail Sobolev -Miklos Szegedi -Milind Chawre -Miloslav Trmač -mingqing -Mingzhen Feng -Misty Stanley-Jones -Mitch Capper -Mizuki Urushida -mlarcher -Mohammad Banikazemi -Mohammad Nasirifar -Mohammed Aaqib Ansari -Mohit Soni -Moorthy RS -Morgan Bauer -Morgante Pell -Morgy93 -Morten Siebuhr -Morton Fox -Moysés Borges -mrfly -Mrunal Patel -Muayyad Alsadi -Mustafa Akın -Muthukumar R -Máximo Cuadros -Médi-Rémi Hashim -Nace Oroz -Nahum Shalman -Nakul Pathak -Nalin Dahyabhai -Nan Monnand Deng -Naoki Orii -Natalie Parker -Natanael Copa -Natasha Jarus -Nate Brennand -Nate Eagleson -Nate Jones -Nathan Hsieh -Nathan Kleyn -Nathan LeClaire -Nathan McCauley -Nathan Williams -Naveed Jamil -Neal McBurnett -Neil Horman -Neil Peterson -Nelson Chen -Neyazul Haque -Nghia Tran -Niall O'Higgins -Nicholas E. Rabenau -Nick Adcock -Nick DeCoursin -Nick Irvine -Nick Neisen -Nick Parker -Nick Payne -Nick Russo -Nick Stenning -Nick Stinemates -NickrenREN -Nicola Kabar -Nicolas Borboën -Nicolas De Loof -Nicolas Dudebout -Nicolas Goy -Nicolas Kaiser -Nicolas Sterchele -Nicolas V Castet -Nicolás Hock Isaza -Nigel Poulton -Nik Nyby -Nikhil Chawla -NikolaMandic -Nikolas Garofil -Nikolay Edigaryev -Nikolay Milovanov -Nirmal Mehta -Nishant Totla -NIWA Hideyuki -Noah Meyerhans -Noah Treuhaft -NobodyOnSE -noducks -Nolan Darilek -Noriki Nakamura -nponeccop -Nuutti Kotivuori -nzwsch -O.S. Tezer -objectified -Odin Ugedal -Oguz Bilgic -Oh Jinkyun -Ohad Schneider -ohmystack -Ole Reifschneider -Oliver Neal -Oliver Reason -Olivier Gambier -Olle Jonsson -Olli Janatuinen -Olly Pomeroy -Omri Shiv -Oriol Francès -Oskar Niburski -Otto Kekäläinen -Ouyang Liduo -Ovidio Mallo -Panagiotis Moustafellos -Paolo G. Giarrusso -Pascal -Pascal Bach -Pascal Borreli -Pascal Hartig -Patrick Böänziger -Patrick Devine -Patrick Hemmer -Patrick Stapleton -Patrik Cyvoct -pattichen -Paul -paul -Paul Annesley -Paul Bellamy -Paul Bowsher -Paul Furtado -Paul Hammond -Paul Jimenez -Paul Kehrer -Paul Lietar -Paul Liljenberg -Paul Morie -Paul Nasrat -Paul Weaver -Paulo Ribeiro -Pavel Lobashov -Pavel Matěja -Pavel Pletenev -Pavel Pospisil -Pavel Sutyrin -Pavel Tikhomirov -Pavlos Ratis -Pavol Vargovcik -Pawel Konczalski -Peeyush Gupta -Peggy Li -Pei Su -Peng Tao -Penghan Wang -Per Weijnitz -perhapszzy@sina.com -Peter Bourgon -Peter Braden -Peter Bücker -Peter Choi -Peter Dave Hello -Peter Edge -Peter Ericson -Peter Esbensen -Peter Jaffe -Peter Kang -Peter Malmgren -Peter Salvatore -Peter Volpe -Peter Waller -Petr Švihlík -Phil -Phil Estes -Phil Spitler -Philip Alexander Etling -Philip Monroe -Philipp Gillé -Philipp Wahala -Philipp Weissensteiner -Phillip Alexander -phineas -pidster -Piergiuliano Bossi -Pierre -Pierre Carrier -Pierre Dal-Pra -Pierre Wacrenier -Pierre-Alain RIVIERE -Piotr Bogdan -pixelistik -Porjo -Poul Kjeldager Sørensen -Pradeep Chhetri -Pradip Dhara -Prasanna Gautam -Pratik Karki -Prayag Verma -Priya Wadhwa -Projjol Banerji -Przemek Hejman -Pure White -pysqz -Qiang Huang -Qinglan Peng -qudongfang -Quentin Brossard -Quentin Perez -Quentin Tayssier -r0n22 -Radostin Stoyanov -Rafal Jeczalik -Rafe Colton -Raghavendra K T -Raghuram Devarakonda -Raja Sami -Rajat Pandit -Rajdeep Dua -Ralf Sippl -Ralle -Ralph Bean -Ramkumar Ramachandra -Ramon Brooker -Ramon van Alteren -RaviTeja Pothana -Ray Tsang -ReadmeCritic -Recursive Madman -Reficul -Regan McCooey -Remi Rampin -Remy Suen -Renato Riccieri Santos Zannon -Renaud Gaubert -Rhys Hiltner -Ri Xu -Ricardo N Feliciano -Rich Moyse -Rich Seymour -Richard -Richard Burnison -Richard Harvey -Richard Mathie -Richard Metzler -Richard Scothern -Richo Healey -Rick Bradley -Rick van de Loo -Rick Wieman -Rik Nijessen -Riku Voipio -Riley Guerin -Ritesh H Shukla -Riyaz Faizullabhoy -Rob Gulewich -Rob Vesse -Robert Bachmann -Robert Bittle -Robert Obryk -Robert Schneider -Robert Stern -Robert Terhaar -Robert Wallis -Robert Wang -Roberto G. Hashioka -Roberto Muñoz Fernández -Robin Naundorf -Robin Schneider -Robin Speekenbrink -Robin Thoni -robpc -Rodolfo Carvalho -Rodrigo Vaz -Roel Van Nyen -Roger Peppe -Rohit Jnagal -Rohit Kadam -Rohit Kapur -Rojin George -Roland Huß -Roland Kammerer -Roland Moriz -Roma Sokolov -Roman Dudin -Roman Mazur -Roman Strashkin -Ron Smits -Ron Williams -Rong Gao -Rong Zhang -Rongxiang Song -root -root -root -root -Rory Hunter -Rory McCune -Ross Boucher -Rovanion Luckey -Royce Remer -Rozhnov Alexandr -Rudolph Gottesheim -Rui Cao -Rui Lopes -Ruilin Li -Runshen Zhu -Russ Magee -Ryan Abrams -Ryan Anderson -Ryan Aslett -Ryan Belgrave -Ryan Detzel -Ryan Fowler -Ryan Liu -Ryan McLaughlin -Ryan O'Donnell -Ryan Seto -Ryan Simmen -Ryan Stelly -Ryan Thomas -Ryan Trauntvein -Ryan Wallner -Ryan Zhang -ryancooper7 -RyanDeng -Ryo Nakao -Rémy Greinhofer -s. rannou -s00318865 -Sabin Basyal -Sachin Joshi -Sagar Hani -Sainath Grandhi -Sakeven Jiang -Salahuddin Khan -Sally O'Malley -Sam Abed -Sam Alba -Sam Bailey -Sam J Sharpe -Sam Neirinck -Sam Reis -Sam Rijs -Sam Whited -Sambuddha Basu -Sami Wagiaalla -Samuel Andaya -Samuel Dion-Girardeau -Samuel Karp -Samuel PHAN -Sandeep Bansal -Sankar சங்கர் -Sanket Saurav -Santhosh Manohar -sapphiredev -Sargun Dhillon -Sascha Andres -Sascha Grunert -SataQiu -Satnam Singh -Satoshi Amemiya -Satoshi Tagomori -Scott Bessler -Scott Collier -Scott Johnston -Scott Stamp -Scott Walls -sdreyesg -Sean Christopherson -Sean Cronin -Sean Lee -Sean McIntyre -Sean OMeara -Sean P. Kane -Sean Rodman -Sebastiaan van Steenis -Sebastiaan van Stijn -Senthil Kumar Selvaraj -Senthil Kumaran -SeongJae Park -Seongyeol Lim -Serge Hallyn -Sergey Alekseev -Sergey Evstifeev -Sergii Kabashniuk -Sergio Lopez -Serhat Gülçiçek -SeungUkLee -Sevki Hasirci -Shane Canon -Shane da Silva -Shaun Kaasten -shaunol -Shawn Landden -Shawn Siefkas -shawnhe -Shayne Wang -Shekhar Gulati -Sheng Yang -Shengbo Song -Shev Yan -Shih-Yuan Lee -Shijiang Wei -Shijun Qin -Shishir Mahajan -Shoubhik Bose -Shourya Sarcar -Shu-Wai Chow -shuai-z -Shukui Yang -Shuwei Hao -Sian Lerk Lau -Sidhartha Mani -sidharthamani -Silas Sewell -Silvan Jegen -Simão Reis -Simei He -Simon Barendse -Simon Eskildsen -Simon Ferquel -Simon Leinen -Simon Menke -Simon Taranto -Simon Vikstrom -Sindhu S -Sjoerd Langkemper -skanehira -Solganik Alexander -Solomon Hykes -Song Gao -Soshi Katsuta -Soulou -Spencer Brown -Spencer Smith -Sridatta Thatipamala -Sridhar Ratnakumar -Srini Brahmaroutu -Srinivasan Srivatsan -Staf Wagemakers -Stanislav Bondarenko -Stanislav Levin -Steeve Morin -Stefan Berger -Stefan J. Wernli -Stefan Praszalowicz -Stefan S. -Stefan Scherer -Stefan Staudenmeyer -Stefan Weil -Stephan Spindler -Stephen Benjamin -Stephen Crosby -Stephen Day -Stephen Drake -Stephen Rust -Steve Desmond -Steve Dougherty -Steve Durrheimer -Steve Francia -Steve Koch -Steven Burgess -Steven Erenst -Steven Hartland -Steven Iveson -Steven Merrill -Steven Richards -Steven Taylor -Stig Larsson -Subhajit Ghosh -Sujith Haridasan -Sun Gengze <690388648@qq.com> -Sun Jianbo -Sune Keller -Sunny Gogoi -Suryakumar Sudar -Sven Dowideit -Swapnil Daingade -Sylvain Baubeau -Sylvain Bellemare -Sébastien -Sébastien HOUZÉ -Sébastien Luttringer -Sébastien Stormacq -Tabakhase -Tadej Janež -TAGOMORI Satoshi -tang0th -Tangi Colin -Tatsuki Sugiura -Tatsushi Inagaki -Taylan Isikdemir -Taylor Jones -Ted M. Young -Tehmasp Chaudhri -Tejaswini Duggaraju -Tejesh Mehta -terryding77 <550147740@qq.com> -tgic -Thatcher Peskens -theadactyl -Thell 'Bo' Fowler -Thermionix -Thijs Terlouw -Thomas Bikeev -Thomas Frössman -Thomas Gazagnaire -Thomas Grainger -Thomas Hansen -Thomas Leonard -Thomas Léveil -Thomas Orozco -Thomas Riccardi -Thomas Schroeter -Thomas Sjögren -Thomas Swift -Thomas Tanaka -Thomas Texier -Ti Zhou -Tianon Gravi -Tianyi Wang -Tibor Vass -Tiffany Jernigan -Tiffany Low -Till Wegmüller -Tim -Tim Bart -Tim Bosse -Tim Dettrick -Tim Düsterhus -Tim Hockin -Tim Potter -Tim Ruffles -Tim Smith -Tim Terhorst -Tim Wang -Tim Waugh -Tim Wraight -Tim Zju <21651152@zju.edu.cn> -timfeirg -Timothy Hobbs -tjwebb123 -tobe -Tobias Bieniek -Tobias Bradtke -Tobias Gesellchen -Tobias Klauser -Tobias Munk -Tobias Schmidt -Tobias Schwab -Todd Crane -Todd Lunter -Todd Whiteman -Toli Kuznets -Tom Barlow -Tom Booth -Tom Denham -Tom Fotherby -Tom Howe -Tom Hulihan -Tom Maaswinkel -Tom Sweeney -Tom Wilkie -Tom X. Tobin -Tomas Tomecek -Tomasz Kopczynski -Tomasz Lipinski -Tomasz Nurkiewicz -Tommaso Visconti -Tomáš Hrčka -Tonny Xu -Tony Abboud -Tony Daws -Tony Miller -toogley -Torstein Husebø -Tõnis Tiigi -Trace Andreason -tracylihui <793912329@qq.com> -Trapier Marshall -Travis Cline -Travis Thieman -Trent Ogren -Trevor -Trevor Pounds -Trevor Sullivan -Trishna Guha -Tristan Carel -Troy Denton -Tycho Andersen -Tyler Brock -Tyler Brown -Tzu-Jung Lee -uhayate -Ulysse Carion -Umesh Yadav -Utz Bacher -vagrant -Vaidas Jablonskis -vanderliang -Velko Ivanov -Veres Lajos -Victor Algaze -Victor Coisne -Victor Costan -Victor I. Wood -Victor Lyuboslavsky -Victor Marmol -Victor Palma -Victor Vieux -Victoria Bialas -Vijaya Kumar K -Vikram bir Singh -Viktor Stanchev -Viktor Vojnovski -VinayRaghavanKS -Vincent Batts -Vincent Bernat -Vincent Boulineau -Vincent Demeester -Vincent Giersch -Vincent Mayers -Vincent Woo -Vinod Kulkarni -Vishal Doshi -Vishnu Kannan -Vitaly Ostrosablin -Vitor Monteiro -Vivek Agarwal -Vivek Dasgupta -Vivek Goyal -Vladimir Bulyga -Vladimir Kirillov -Vladimir Pouzanov -Vladimir Rutsky -Vladimir Varankin -VladimirAus -Vlastimil Zeman -Vojtech Vitek (V-Teq) -waitingkuo -Walter Leibbrandt -Walter Stanish -Wang Chao -Wang Guoliang -Wang Jie -Wang Long -Wang Ping -Wang Xing -Wang Yuexiao -Wang Yumu <37442693@qq.com> -wanghuaiqing -Ward Vandewege -WarheadsSE -Wassim Dhif -Wayne Chang -Wayne Song -Weerasak Chongnguluam -Wei Fu -Wei Wu -Wei-Ting Kuo -weipeng -weiyan -Weiyang Zhu -Wen Cheng Ma -Wendel Fleming -Wenjun Tang -Wenkai Yin -wenlxie -Wentao Zhang -Wenxuan Zhao -Wenyu You <21551128@zju.edu.cn> -Wenzhi Liang -Wes Morgan -Wewang Xiaorenfine -Wiktor Kwapisiewicz -Will Dietz -Will Rouesnel -Will Weaver -willhf -William Delanoue -William Henry -William Hubbs -William Martin -William Riancho -William Thurston -Wilson Júnior -Wing-Kam Wong -WiseTrem -Wolfgang Powisch -Wonjun Kim -xamyzhao -Xian Chaobo -Xianglin Gao -Xianlu Bird -Xiao YongBiao -XiaoBing Jiang -Xiaodong Liu -Xiaodong Zhang -Xiaoxi He -Xiaoxu Chen -Xiaoyu Zhang -xichengliudui <1693291525@qq.com> -xiekeyang -Ximo Guanter Gonzálbez -Xinbo Weng -Xinfeng Liu -Xinzi Zhou -Xiuming Chen -Xuecong Liao -xuzhaokui -Yadnyawalkya Tale -Yahya -YAMADA Tsuyoshi -Yamasaki Masahide -Yan Feng -Yang Bai -Yang Pengfei -yangchenliang -Yanqiang Miao -Yao Zaiyong -Yash Murty -Yassine Tijani -Yasunori Mahata -Yazhong Liu -Yestin Sun -Yi EungJun -Yibai Zhang -Yihang Ho -Ying Li -Yohei Ueda -Yong Tang -Yongxin Li -Yongzhi Pan -Yosef Fertel -You-Sheng Yang (楊有勝) -youcai -Youcef YEKHLEF -Yu Changchun -Yu Chengxia -Yu Peng -Yu-Ju Hong -Yuan Sun -Yuanhong Peng -Yue Zhang -Yuhao Fang -Yuichiro Kaneko -Yunxiang Huang -Yurii Rashkovskii -Yusuf Tarık Günaydın -Yves Junqueira -Zac Dover -Zach Borboa -Zachary Jaffee -Zain Memon -Zaiste! -Zane DeGraffenried -Zefan Li -Zen Lin(Zhinan Lin) -Zhang Kun -Zhang Wei -Zhang Wentao -ZhangHang -zhangxianwei -Zhenan Ye <21551168@zju.edu.cn> -zhenghenghuo -Zhenhai Gao -Zhenkun Bi -zhipengzuo -Zhou Hao -Zhoulin Xie -Zhu Guihua -Zhu Kunjia -Zhuoyun Wei -Ziheng Liu -Zilin Du -zimbatm -Ziming Dong -ZJUshuaizhou <21551191@zju.edu.cn> -zmarouf -Zoltan Tombol -Zou Yu -zqh -Zuhayr Elahi -Zunayed Ali -Álex González -Álvaro Lázaro -Átila Camurça Alves -尹吉峰 -屈骏 -徐俊杰 -慕陶 -搏通 -黄艳红00139573 diff --git a/vendor/github.com/docker/docker/LICENSE b/vendor/github.com/docker/docker/LICENSE deleted file mode 100644 index 6d8d58fb..00000000 --- a/vendor/github.com/docker/docker/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://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 - - Copyright 2013-2018 Docker, 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 - - 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. diff --git a/vendor/github.com/docker/docker/NOTICE b/vendor/github.com/docker/docker/NOTICE deleted file mode 100644 index 58b19b6d..00000000 --- a/vendor/github.com/docker/docker/NOTICE +++ /dev/null @@ -1,19 +0,0 @@ -Docker -Copyright 2012-2017 Docker, Inc. - -This product includes software developed at Docker, Inc. (https://www.docker.com). - -This product contains software (https://github.com/creack/pty) developed -by Keith Rarick, licensed under the MIT License. - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/docker/api/README.md b/vendor/github.com/docker/docker/api/README.md deleted file mode 100644 index f136c343..00000000 --- a/vendor/github.com/docker/docker/api/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Working on the Engine API - -The Engine API is an HTTP API used by the command-line client to communicate with the daemon. It can also be used by third-party software to control the daemon. - -It consists of various components in this repository: - -- `api/swagger.yaml` A Swagger definition of the API. -- `api/types/` Types shared by both the client and server, representing various objects, options, responses, etc. Most are written manually, but some are automatically generated from the Swagger definition. See [#27919](https://github.com/docker/docker/issues/27919) for progress on this. -- `cli/` The command-line client. -- `client/` The Go client used by the command-line client. It can also be used by third-party Go programs. -- `daemon/` The daemon, which serves the API. - -## Swagger definition - -The API is defined by the [Swagger](http://swagger.io/specification/) definition in `api/swagger.yaml`. This definition can be used to: - -1. Automatically generate documentation. -2. Automatically generate the Go server and client. (A work-in-progress.) -3. Provide a machine readable version of the API for introspecting what it can do, automatically generating clients for other languages, etc. - -## Updating the API documentation - -The API documentation is generated entirely from `api/swagger.yaml`. If you make updates to the API, edit this file to represent the change in the documentation. - -The file is split into two main sections: - -- `definitions`, which defines re-usable objects used in requests and responses -- `paths`, which defines the API endpoints (and some inline objects which don't need to be reusable) - -To make an edit, first look for the endpoint you want to edit under `paths`, then make the required edits. Endpoints may reference reusable objects with `$ref`, which can be found in the `definitions` section. - -There is hopefully enough example material in the file for you to copy a similar pattern from elsewhere in the file (e.g. adding new fields or endpoints), but for the full reference, see the [Swagger specification](https://github.com/docker/docker/issues/27919). - -`swagger.yaml` is validated by `hack/validate/swagger` to ensure it is a valid Swagger definition. This is useful when making edits to ensure you are doing the right thing. - -## Viewing the API documentation - -When you make edits to `swagger.yaml`, you may want to check the generated API documentation to ensure it renders correctly. - -Run `make swagger-docs` and a preview will be running at `http://localhost`. Some of the styling may be incorrect, but you'll be able to ensure that it is generating the correct documentation. - -The production documentation is generated by vendoring `swagger.yaml` into [docker/docker.github.io](https://github.com/docker/docker.github.io). diff --git a/vendor/github.com/docker/docker/api/common.go b/vendor/github.com/docker/docker/api/common.go deleted file mode 100644 index 1565e2af..00000000 --- a/vendor/github.com/docker/docker/api/common.go +++ /dev/null @@ -1,11 +0,0 @@ -package api // import "github.com/docker/docker/api" - -// Common constants for daemon and client. -const ( - // DefaultVersion of Current REST API - DefaultVersion = "1.41" - - // NoBaseImageSpecifier is the symbol used by the FROM - // command to specify that no base image is to be used. - NoBaseImageSpecifier = "scratch" -) diff --git a/vendor/github.com/docker/docker/api/common_unix.go b/vendor/github.com/docker/docker/api/common_unix.go deleted file mode 100644 index 504b0c90..00000000 --- a/vendor/github.com/docker/docker/api/common_unix.go +++ /dev/null @@ -1,6 +0,0 @@ -// +build !windows - -package api // import "github.com/docker/docker/api" - -// MinVersion represents Minimum REST API version supported -const MinVersion = "1.12" diff --git a/vendor/github.com/docker/docker/api/common_windows.go b/vendor/github.com/docker/docker/api/common_windows.go deleted file mode 100644 index 590ba547..00000000 --- a/vendor/github.com/docker/docker/api/common_windows.go +++ /dev/null @@ -1,8 +0,0 @@ -package api // import "github.com/docker/docker/api" - -// MinVersion represents Minimum REST API version supported -// Technically the first daemon API version released on Windows is v1.25 in -// engine version 1.13. However, some clients are explicitly using downlevel -// APIs (e.g. docker-compose v2.1 file format) and that is just too restrictive. -// Hence also allowing 1.24 on Windows. -const MinVersion string = "1.24" diff --git a/vendor/github.com/docker/docker/api/swagger-gen.yaml b/vendor/github.com/docker/docker/api/swagger-gen.yaml deleted file mode 100644 index f07a0273..00000000 --- a/vendor/github.com/docker/docker/api/swagger-gen.yaml +++ /dev/null @@ -1,12 +0,0 @@ - -layout: - models: - - name: definition - source: asset:model - target: "{{ joinFilePath .Target .ModelPackage }}" - file_name: "{{ (snakize (pascalize .Name)) }}.go" - operations: - - name: handler - source: asset:serverOperation - target: "{{ joinFilePath .Target .APIPackage .Package }}" - file_name: "{{ (snakize (pascalize .Name)) }}.go" diff --git a/vendor/github.com/docker/docker/api/swagger.yaml b/vendor/github.com/docker/docker/api/swagger.yaml deleted file mode 100644 index 1294e5a2..00000000 --- a/vendor/github.com/docker/docker/api/swagger.yaml +++ /dev/null @@ -1,11425 +0,0 @@ -# A Swagger 2.0 (a.k.a. OpenAPI) definition of the Engine API. -# -# This is used for generating API documentation and the types used by the -# client/server. See api/README.md for more information. -# -# Some style notes: -# - This file is used by ReDoc, which allows GitHub Flavored Markdown in -# descriptions. -# - There is no maximum line length, for ease of editing and pretty diffs. -# - operationIds are in the format "NounVerb", with a singular noun. - -swagger: "2.0" -schemes: - - "http" - - "https" -produces: - - "application/json" - - "text/plain" -consumes: - - "application/json" - - "text/plain" -basePath: "/v1.41" -info: - title: "Docker Engine API" - version: "1.41" - x-logo: - url: "https://docs.docker.com/images/logo-docker-main.png" - description: | - The Engine API is an HTTP API served by Docker Engine. It is the API the - Docker client uses to communicate with the Engine, so everything the Docker - client can do can be done with the API. - - Most of the client's commands map directly to API endpoints (e.g. `docker ps` - is `GET /containers/json`). The notable exception is running containers, - which consists of several API calls. - - # Errors - - The API uses standard HTTP status codes to indicate the success or failure - of the API call. The body of the response will be JSON in the following - format: - - ``` - { - "message": "page not found" - } - ``` - - # Versioning - - The API is usually changed in each release, so API calls are versioned to - ensure that clients don't break. To lock to a specific version of the API, - you prefix the URL with its version, for example, call `/v1.30/info` to use - the v1.30 version of the `/info` endpoint. If the API version specified in - the URL is not supported by the daemon, a HTTP `400 Bad Request` error message - is returned. - - If you omit the version-prefix, the current version of the API (v1.41) is used. - For example, calling `/info` is the same as calling `/v1.41/info`. Using the - API without a version-prefix is deprecated and will be removed in a future release. - - Engine releases in the near future should support this version of the API, - so your client will continue to work even if it is talking to a newer Engine. - - The API uses an open schema model, which means server may add extra properties - to responses. Likewise, the server will ignore any extra query parameters and - request body properties. When you write clients, you need to ignore additional - properties in responses to ensure they do not break when talking to newer - daemons. - - - # Authentication - - Authentication for registries is handled client side. The client has to send - authentication details to various endpoints that need to communicate with - registries, such as `POST /images/(name)/push`. These are sent as - `X-Registry-Auth` header as a [base64url encoded](https://tools.ietf.org/html/rfc4648#section-5) - (JSON) string with the following structure: - - ``` - { - "username": "string", - "password": "string", - "email": "string", - "serveraddress": "string" - } - ``` - - The `serveraddress` is a domain/IP without a protocol. Throughout this - structure, double quotes are required. - - If you have already got an identity token from the [`/auth` endpoint](#operation/SystemAuth), - you can just pass this instead of credentials: - - ``` - { - "identitytoken": "9cbaf023786cd7..." - } - ``` - -# The tags on paths define the menu sections in the ReDoc documentation, so -# the usage of tags must make sense for that: -# - They should be singular, not plural. -# - There should not be too many tags, or the menu becomes unwieldy. For -# example, it is preferable to add a path to the "System" tag instead of -# creating a tag with a single path in it. -# - The order of tags in this list defines the order in the menu. -tags: - # Primary objects - - name: "Container" - x-displayName: "Containers" - description: | - Create and manage containers. - - name: "Image" - x-displayName: "Images" - - name: "Network" - x-displayName: "Networks" - description: | - Networks are user-defined networks that containers can be attached to. - See the [networking documentation](https://docs.docker.com/network/) - for more information. - - name: "Volume" - x-displayName: "Volumes" - description: | - Create and manage persistent storage that can be attached to containers. - - name: "Exec" - x-displayName: "Exec" - description: | - Run new commands inside running containers. Refer to the - [command-line reference](https://docs.docker.com/engine/reference/commandline/exec/) - for more information. - - To exec a command in a container, you first need to create an exec instance, - then start it. These two API endpoints are wrapped up in a single command-line - command, `docker exec`. - - # Swarm things - - name: "Swarm" - x-displayName: "Swarm" - description: | - Engines can be clustered together in a swarm. Refer to the - [swarm mode documentation](https://docs.docker.com/engine/swarm/) - for more information. - - name: "Node" - x-displayName: "Nodes" - description: | - Nodes are instances of the Engine participating in a swarm. Swarm mode - must be enabled for these endpoints to work. - - name: "Service" - x-displayName: "Services" - description: | - Services are the definitions of tasks to run on a swarm. Swarm mode must - be enabled for these endpoints to work. - - name: "Task" - x-displayName: "Tasks" - description: | - A task is a container running on a swarm. It is the atomic scheduling unit - of swarm. Swarm mode must be enabled for these endpoints to work. - - name: "Secret" - x-displayName: "Secrets" - description: | - Secrets are sensitive data that can be used by services. Swarm mode must - be enabled for these endpoints to work. - - name: "Config" - x-displayName: "Configs" - description: | - Configs are application configurations that can be used by services. Swarm - mode must be enabled for these endpoints to work. - # System things - - name: "Plugin" - x-displayName: "Plugins" - - name: "System" - x-displayName: "System" - -definitions: - Port: - type: "object" - description: "An open port on a container" - required: [PrivatePort, Type] - properties: - IP: - type: "string" - format: "ip-address" - description: "Host IP address that the container's port is mapped to" - PrivatePort: - type: "integer" - format: "uint16" - x-nullable: false - description: "Port on the container" - PublicPort: - type: "integer" - format: "uint16" - description: "Port exposed on the host" - Type: - type: "string" - x-nullable: false - enum: ["tcp", "udp", "sctp"] - example: - PrivatePort: 8080 - PublicPort: 80 - Type: "tcp" - - MountPoint: - type: "object" - description: "A mount point inside a container" - properties: - Type: - type: "string" - Name: - type: "string" - Source: - type: "string" - Destination: - type: "string" - Driver: - type: "string" - Mode: - type: "string" - RW: - type: "boolean" - Propagation: - type: "string" - - DeviceMapping: - type: "object" - description: "A device mapping between the host and container" - properties: - PathOnHost: - type: "string" - PathInContainer: - type: "string" - CgroupPermissions: - type: "string" - example: - PathOnHost: "/dev/deviceName" - PathInContainer: "/dev/deviceName" - CgroupPermissions: "mrw" - - DeviceRequest: - type: "object" - description: "A request for devices to be sent to device drivers" - properties: - Driver: - type: "string" - example: "nvidia" - Count: - type: "integer" - example: -1 - DeviceIDs: - type: "array" - items: - type: "string" - example: - - "0" - - "1" - - "GPU-fef8089b-4820-abfc-e83e-94318197576e" - Capabilities: - description: | - A list of capabilities; an OR list of AND lists of capabilities. - type: "array" - items: - type: "array" - items: - type: "string" - example: - # gpu AND nvidia AND compute - - ["gpu", "nvidia", "compute"] - Options: - description: | - Driver-specific options, specified as a key/value pairs. These options - are passed directly to the driver. - type: "object" - additionalProperties: - type: "string" - - ThrottleDevice: - type: "object" - properties: - Path: - description: "Device path" - type: "string" - Rate: - description: "Rate" - type: "integer" - format: "int64" - minimum: 0 - - Mount: - type: "object" - properties: - Target: - description: "Container path." - type: "string" - Source: - description: "Mount source (e.g. a volume name, a host path)." - type: "string" - Type: - description: | - The mount type. Available types: - - - `bind` Mounts a file or directory from the host into the container. Must exist prior to creating the container. - - `volume` Creates a volume with the given name and options (or uses a pre-existing volume with the same name and options). These are **not** removed when the container is removed. - - `tmpfs` Create a tmpfs with the given options. The mount source cannot be specified for tmpfs. - - `npipe` Mounts a named pipe from the host into the container. Must exist prior to creating the container. - type: "string" - enum: - - "bind" - - "volume" - - "tmpfs" - - "npipe" - ReadOnly: - description: "Whether the mount should be read-only." - type: "boolean" - Consistency: - description: "The consistency requirement for the mount: `default`, `consistent`, `cached`, or `delegated`." - type: "string" - BindOptions: - description: "Optional configuration for the `bind` type." - type: "object" - properties: - Propagation: - description: "A propagation mode with the value `[r]private`, `[r]shared`, or `[r]slave`." - type: "string" - enum: - - "private" - - "rprivate" - - "shared" - - "rshared" - - "slave" - - "rslave" - NonRecursive: - description: "Disable recursive bind mount." - type: "boolean" - default: false - VolumeOptions: - description: "Optional configuration for the `volume` type." - type: "object" - properties: - NoCopy: - description: "Populate volume with data from the target." - type: "boolean" - default: false - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - DriverConfig: - description: "Map of driver specific options" - type: "object" - properties: - Name: - description: "Name of the driver to use to create the volume." - type: "string" - Options: - description: "key/value map of driver specific options." - type: "object" - additionalProperties: - type: "string" - TmpfsOptions: - description: "Optional configuration for the `tmpfs` type." - type: "object" - properties: - SizeBytes: - description: "The size for the tmpfs mount in bytes." - type: "integer" - format: "int64" - Mode: - description: "The permission mode for the tmpfs mount in an integer." - type: "integer" - - RestartPolicy: - description: | - The behavior to apply when the container exits. The default is not to - restart. - - An ever increasing delay (double the previous delay, starting at 100ms) is - added before each restart to prevent flooding the server. - type: "object" - properties: - Name: - type: "string" - description: | - - Empty string means not to restart - - `always` Always restart - - `unless-stopped` Restart always except when the user has manually stopped the container - - `on-failure` Restart only when the container exit code is non-zero - enum: - - "" - - "always" - - "unless-stopped" - - "on-failure" - MaximumRetryCount: - type: "integer" - description: | - If `on-failure` is used, the number of times to retry before giving up. - - Resources: - description: "A container's resources (cgroups config, ulimits, etc)" - type: "object" - properties: - # Applicable to all platforms - CpuShares: - description: | - An integer value representing this container's relative CPU weight - versus other containers. - type: "integer" - Memory: - description: "Memory limit in bytes." - type: "integer" - format: "int64" - default: 0 - # Applicable to UNIX platforms - CgroupParent: - description: | - Path to `cgroups` under which the container's `cgroup` is created. If - the path is not absolute, the path is considered to be relative to the - `cgroups` path of the init process. Cgroups are created if they do not - already exist. - type: "string" - BlkioWeight: - description: "Block IO weight (relative weight)." - type: "integer" - minimum: 0 - maximum: 1000 - BlkioWeightDevice: - description: | - Block IO weight (relative device weight) in the form: - - ``` - [{"Path": "device_path", "Weight": weight}] - ``` - type: "array" - items: - type: "object" - properties: - Path: - type: "string" - Weight: - type: "integer" - minimum: 0 - BlkioDeviceReadBps: - description: | - Limit read rate (bytes per second) from a device, in the form: - - ``` - [{"Path": "device_path", "Rate": rate}] - ``` - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - BlkioDeviceWriteBps: - description: | - Limit write rate (bytes per second) to a device, in the form: - - ``` - [{"Path": "device_path", "Rate": rate}] - ``` - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - BlkioDeviceReadIOps: - description: | - Limit read rate (IO per second) from a device, in the form: - - ``` - [{"Path": "device_path", "Rate": rate}] - ``` - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - BlkioDeviceWriteIOps: - description: | - Limit write rate (IO per second) to a device, in the form: - - ``` - [{"Path": "device_path", "Rate": rate}] - ``` - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - CpuPeriod: - description: "The length of a CPU period in microseconds." - type: "integer" - format: "int64" - CpuQuota: - description: | - Microseconds of CPU time that the container can get in a CPU period. - type: "integer" - format: "int64" - CpuRealtimePeriod: - description: | - The length of a CPU real-time period in microseconds. Set to 0 to - allocate no time allocated to real-time tasks. - type: "integer" - format: "int64" - CpuRealtimeRuntime: - description: | - The length of a CPU real-time runtime in microseconds. Set to 0 to - allocate no time allocated to real-time tasks. - type: "integer" - format: "int64" - CpusetCpus: - description: | - CPUs in which to allow execution (e.g., `0-3`, `0,1`). - type: "string" - example: "0-3" - CpusetMems: - description: | - Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only - effective on NUMA systems. - type: "string" - Devices: - description: "A list of devices to add to the container." - type: "array" - items: - $ref: "#/definitions/DeviceMapping" - DeviceCgroupRules: - description: "a list of cgroup rules to apply to the container" - type: "array" - items: - type: "string" - example: "c 13:* rwm" - DeviceRequests: - description: | - A list of requests for devices to be sent to device drivers. - type: "array" - items: - $ref: "#/definitions/DeviceRequest" - KernelMemory: - description: | - Kernel memory limit in bytes. - -


- - > **Deprecated**: This field is deprecated as the kernel 5.4 deprecated - > `kmem.limit_in_bytes`. - type: "integer" - format: "int64" - example: 209715200 - KernelMemoryTCP: - description: "Hard limit for kernel TCP buffer memory (in bytes)." - type: "integer" - format: "int64" - MemoryReservation: - description: "Memory soft limit in bytes." - type: "integer" - format: "int64" - MemorySwap: - description: | - Total memory limit (memory + swap). Set as `-1` to enable unlimited - swap. - type: "integer" - format: "int64" - MemorySwappiness: - description: | - Tune a container's memory swappiness behavior. Accepts an integer - between 0 and 100. - type: "integer" - format: "int64" - minimum: 0 - maximum: 100 - NanoCpus: - description: "CPU quota in units of 10-9 CPUs." - type: "integer" - format: "int64" - OomKillDisable: - description: "Disable OOM Killer for the container." - type: "boolean" - Init: - description: | - Run an init inside the container that forwards signals and reaps - processes. This field is omitted if empty, and the default (as - configured on the daemon) is used. - type: "boolean" - x-nullable: true - PidsLimit: - description: | - Tune a container's PIDs limit. Set `0` or `-1` for unlimited, or `null` - to not change. - type: "integer" - format: "int64" - x-nullable: true - Ulimits: - description: | - A list of resource limits to set in the container. For example: - - ``` - {"Name": "nofile", "Soft": 1024, "Hard": 2048} - ``` - type: "array" - items: - type: "object" - properties: - Name: - description: "Name of ulimit" - type: "string" - Soft: - description: "Soft limit" - type: "integer" - Hard: - description: "Hard limit" - type: "integer" - # Applicable to Windows - CpuCount: - description: | - The number of usable CPUs (Windows only). - - On Windows Server containers, the processor resource controls are - mutually exclusive. The order of precedence is `CPUCount` first, then - `CPUShares`, and `CPUPercent` last. - type: "integer" - format: "int64" - CpuPercent: - description: | - The usable percentage of the available CPUs (Windows only). - - On Windows Server containers, the processor resource controls are - mutually exclusive. The order of precedence is `CPUCount` first, then - `CPUShares`, and `CPUPercent` last. - type: "integer" - format: "int64" - IOMaximumIOps: - description: "Maximum IOps for the container system drive (Windows only)" - type: "integer" - format: "int64" - IOMaximumBandwidth: - description: | - Maximum IO in bytes per second for the container system drive - (Windows only). - type: "integer" - format: "int64" - - Limit: - description: | - An object describing a limit on resources which can be requested by a task. - type: "object" - properties: - NanoCPUs: - type: "integer" - format: "int64" - example: 4000000000 - MemoryBytes: - type: "integer" - format: "int64" - example: 8272408576 - Pids: - description: | - Limits the maximum number of PIDs in the container. Set `0` for unlimited. - type: "integer" - format: "int64" - default: 0 - example: 100 - - ResourceObject: - description: | - An object describing the resources which can be advertised by a node and - requested by a task. - type: "object" - properties: - NanoCPUs: - type: "integer" - format: "int64" - example: 4000000000 - MemoryBytes: - type: "integer" - format: "int64" - example: 8272408576 - GenericResources: - $ref: "#/definitions/GenericResources" - - GenericResources: - description: | - User-defined resources can be either Integer resources (e.g, `SSD=3`) or - String resources (e.g, `GPU=UUID1`). - type: "array" - items: - type: "object" - properties: - NamedResourceSpec: - type: "object" - properties: - Kind: - type: "string" - Value: - type: "string" - DiscreteResourceSpec: - type: "object" - properties: - Kind: - type: "string" - Value: - type: "integer" - format: "int64" - example: - - DiscreteResourceSpec: - Kind: "SSD" - Value: 3 - - NamedResourceSpec: - Kind: "GPU" - Value: "UUID1" - - NamedResourceSpec: - Kind: "GPU" - Value: "UUID2" - - HealthConfig: - description: "A test to perform to check that the container is healthy." - type: "object" - properties: - Test: - description: | - The test to perform. Possible values are: - - - `[]` inherit healthcheck from image or parent image - - `["NONE"]` disable healthcheck - - `["CMD", args...]` exec arguments directly - - `["CMD-SHELL", command]` run command with system's default shell - type: "array" - items: - type: "string" - Interval: - description: | - The time to wait between checks in nanoseconds. It should be 0 or at - least 1000000 (1 ms). 0 means inherit. - type: "integer" - Timeout: - description: | - The time to wait before considering the check to have hung. It should - be 0 or at least 1000000 (1 ms). 0 means inherit. - type: "integer" - Retries: - description: | - The number of consecutive failures needed to consider a container as - unhealthy. 0 means inherit. - type: "integer" - StartPeriod: - description: | - Start period for the container to initialize before starting - health-retries countdown in nanoseconds. It should be 0 or at least - 1000000 (1 ms). 0 means inherit. - type: "integer" - - Health: - description: | - Health stores information about the container's healthcheck results. - type: "object" - properties: - Status: - description: | - Status is one of `none`, `starting`, `healthy` or `unhealthy` - - - "none" Indicates there is no healthcheck - - "starting" Starting indicates that the container is not yet ready - - "healthy" Healthy indicates that the container is running correctly - - "unhealthy" Unhealthy indicates that the container has a problem - type: "string" - enum: - - "none" - - "starting" - - "healthy" - - "unhealthy" - example: "healthy" - FailingStreak: - description: "FailingStreak is the number of consecutive failures" - type: "integer" - example: 0 - Log: - type: "array" - description: | - Log contains the last few results (oldest first) - items: - x-nullable: true - $ref: "#/definitions/HealthcheckResult" - - HealthcheckResult: - description: | - HealthcheckResult stores information about a single run of a healthcheck probe - type: "object" - properties: - Start: - description: | - Date and time at which this check started in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "date-time" - example: "2020-01-04T10:44:24.496525531Z" - End: - description: | - Date and time at which this check ended in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2020-01-04T10:45:21.364524523Z" - ExitCode: - description: | - ExitCode meanings: - - - `0` healthy - - `1` unhealthy - - `2` reserved (considered unhealthy) - - other values: error running probe - type: "integer" - example: 0 - Output: - description: "Output from last check" - type: "string" - - HostConfig: - description: "Container configuration that depends on the host we are running on" - allOf: - - $ref: "#/definitions/Resources" - - type: "object" - properties: - # Applicable to all platforms - Binds: - type: "array" - description: | - A list of volume bindings for this container. Each volume binding - is a string in one of these forms: - - - `host-src:container-dest[:options]` to bind-mount a host path - into the container. Both `host-src`, and `container-dest` must - be an _absolute_ path. - - `volume-name:container-dest[:options]` to bind-mount a volume - managed by a volume driver into the container. `container-dest` - must be an _absolute_ path. - - `options` is an optional, comma-delimited list of: - - - `nocopy` disables automatic copying of data from the container - path to the volume. The `nocopy` flag only applies to named volumes. - - `[ro|rw]` mounts a volume read-only or read-write, respectively. - If omitted or set to `rw`, volumes are mounted read-write. - - `[z|Z]` applies SELinux labels to allow or deny multiple containers - to read and write to the same volume. - - `z`: a _shared_ content label is applied to the content. This - label indicates that multiple containers can share the volume - content, for both reading and writing. - - `Z`: a _private unshared_ label is applied to the content. - This label indicates that only the current container can use - a private volume. Labeling systems such as SELinux require - proper labels to be placed on volume content that is mounted - into a container. Without a label, the security system can - prevent a container's processes from using the content. By - default, the labels set by the host operating system are not - modified. - - `[[r]shared|[r]slave|[r]private]` specifies mount - [propagation behavior](https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt). - This only applies to bind-mounted volumes, not internal volumes - or named volumes. Mount propagation requires the source mount - point (the location where the source directory is mounted in the - host operating system) to have the correct propagation properties. - For shared volumes, the source mount point must be set to `shared`. - For slave volumes, the mount must be set to either `shared` or - `slave`. - items: - type: "string" - ContainerIDFile: - type: "string" - description: "Path to a file where the container ID is written" - LogConfig: - type: "object" - description: "The logging configuration for this container" - properties: - Type: - type: "string" - enum: - - "json-file" - - "syslog" - - "journald" - - "gelf" - - "fluentd" - - "awslogs" - - "splunk" - - "etwlogs" - - "none" - Config: - type: "object" - additionalProperties: - type: "string" - NetworkMode: - type: "string" - description: | - Network mode to use for this container. Supported standard values - are: `bridge`, `host`, `none`, and `container:`. Any - other value is taken as a custom network's name to which this - container should connect to. - PortBindings: - $ref: "#/definitions/PortMap" - RestartPolicy: - $ref: "#/definitions/RestartPolicy" - AutoRemove: - type: "boolean" - description: | - Automatically remove the container when the container's process - exits. This has no effect if `RestartPolicy` is set. - VolumeDriver: - type: "string" - description: "Driver that this container uses to mount volumes." - VolumesFrom: - type: "array" - description: | - A list of volumes to inherit from another container, specified in - the form `[:]`. - items: - type: "string" - Mounts: - description: | - Specification for mounts to be added to the container. - type: "array" - items: - $ref: "#/definitions/Mount" - - # Applicable to UNIX platforms - CapAdd: - type: "array" - description: | - A list of kernel capabilities to add to the container. Conflicts - with option 'Capabilities'. - items: - type: "string" - CapDrop: - type: "array" - description: | - A list of kernel capabilities to drop from the container. Conflicts - with option 'Capabilities'. - items: - type: "string" - CgroupnsMode: - type: "string" - enum: - - "private" - - "host" - description: | - cgroup namespace mode for the container. Possible values are: - - - `"private"`: the container runs in its own private cgroup namespace - - `"host"`: use the host system's cgroup namespace - - If not specified, the daemon default is used, which can either be `"private"` - or `"host"`, depending on daemon version, kernel support and configuration. - Dns: - type: "array" - description: "A list of DNS servers for the container to use." - items: - type: "string" - DnsOptions: - type: "array" - description: "A list of DNS options." - items: - type: "string" - DnsSearch: - type: "array" - description: "A list of DNS search domains." - items: - type: "string" - ExtraHosts: - type: "array" - description: | - A list of hostnames/IP mappings to add to the container's `/etc/hosts` - file. Specified in the form `["hostname:IP"]`. - items: - type: "string" - GroupAdd: - type: "array" - description: | - A list of additional groups that the container process will run as. - items: - type: "string" - IpcMode: - type: "string" - description: | - IPC sharing mode for the container. Possible values are: - - - `"none"`: own private IPC namespace, with /dev/shm not mounted - - `"private"`: own private IPC namespace - - `"shareable"`: own private IPC namespace, with a possibility to share it with other containers - - `"container:"`: join another (shareable) container's IPC namespace - - `"host"`: use the host system's IPC namespace - - If not specified, daemon default is used, which can either be `"private"` - or `"shareable"`, depending on daemon version and configuration. - Cgroup: - type: "string" - description: "Cgroup to use for the container." - Links: - type: "array" - description: | - A list of links for the container in the form `container_name:alias`. - items: - type: "string" - OomScoreAdj: - type: "integer" - description: | - An integer value containing the score given to the container in - order to tune OOM killer preferences. - example: 500 - PidMode: - type: "string" - description: | - Set the PID (Process) Namespace mode for the container. It can be - either: - - - `"container:"`: joins another container's PID namespace - - `"host"`: use the host's PID namespace inside the container - Privileged: - type: "boolean" - description: "Gives the container full access to the host." - PublishAllPorts: - type: "boolean" - description: | - Allocates an ephemeral host port for all of a container's - exposed ports. - - Ports are de-allocated when the container stops and allocated when - the container starts. The allocated port might be changed when - restarting the container. - - The port is selected from the ephemeral port range that depends on - the kernel. For example, on Linux the range is defined by - `/proc/sys/net/ipv4/ip_local_port_range`. - ReadonlyRootfs: - type: "boolean" - description: "Mount the container's root filesystem as read only." - SecurityOpt: - type: "array" - description: "A list of string values to customize labels for MLS - systems, such as SELinux." - items: - type: "string" - StorageOpt: - type: "object" - description: | - Storage driver options for this container, in the form `{"size": "120G"}`. - additionalProperties: - type: "string" - Tmpfs: - type: "object" - description: | - A map of container directories which should be replaced by tmpfs - mounts, and their corresponding mount options. For example: - - ``` - { "/run": "rw,noexec,nosuid,size=65536k" } - ``` - additionalProperties: - type: "string" - UTSMode: - type: "string" - description: "UTS namespace to use for the container." - UsernsMode: - type: "string" - description: | - Sets the usernamespace mode for the container when usernamespace - remapping option is enabled. - ShmSize: - type: "integer" - description: | - Size of `/dev/shm` in bytes. If omitted, the system uses 64MB. - minimum: 0 - Sysctls: - type: "object" - description: | - A list of kernel parameters (sysctls) to set in the container. - For example: - - ``` - {"net.ipv4.ip_forward": "1"} - ``` - additionalProperties: - type: "string" - Runtime: - type: "string" - description: "Runtime to use with this container." - # Applicable to Windows - ConsoleSize: - type: "array" - description: | - Initial console size, as an `[height, width]` array. (Windows only) - minItems: 2 - maxItems: 2 - items: - type: "integer" - minimum: 0 - Isolation: - type: "string" - description: | - Isolation technology of the container. (Windows only) - enum: - - "default" - - "process" - - "hyperv" - MaskedPaths: - type: "array" - description: | - The list of paths to be masked inside the container (this overrides - the default set of paths). - items: - type: "string" - ReadonlyPaths: - type: "array" - description: | - The list of paths to be set as read-only inside the container - (this overrides the default set of paths). - items: - type: "string" - - ContainerConfig: - description: "Configuration for a container that is portable between hosts" - type: "object" - properties: - Hostname: - description: "The hostname to use for the container, as a valid RFC 1123 hostname." - type: "string" - Domainname: - description: "The domain name to use for the container." - type: "string" - User: - description: "The user that commands are run as inside the container." - type: "string" - AttachStdin: - description: "Whether to attach to `stdin`." - type: "boolean" - default: false - AttachStdout: - description: "Whether to attach to `stdout`." - type: "boolean" - default: true - AttachStderr: - description: "Whether to attach to `stderr`." - type: "boolean" - default: true - ExposedPorts: - description: | - An object mapping ports to an empty object in the form: - - `{"/": {}}` - type: "object" - additionalProperties: - type: "object" - enum: - - {} - default: {} - Tty: - description: | - Attach standard streams to a TTY, including `stdin` if it is not closed. - type: "boolean" - default: false - OpenStdin: - description: "Open `stdin`" - type: "boolean" - default: false - StdinOnce: - description: "Close `stdin` after one attached client disconnects" - type: "boolean" - default: false - Env: - description: | - A list of environment variables to set inside the container in the - form `["VAR=value", ...]`. A variable without `=` is removed from the - environment, rather than to have an empty value. - type: "array" - items: - type: "string" - Cmd: - description: | - Command to run specified as a string or an array of strings. - type: "array" - items: - type: "string" - Healthcheck: - $ref: "#/definitions/HealthConfig" - ArgsEscaped: - description: "Command is already escaped (Windows only)" - type: "boolean" - Image: - description: | - The name of the image to use when creating the container/ - type: "string" - Volumes: - description: | - An object mapping mount point paths inside the container to empty - objects. - type: "object" - additionalProperties: - type: "object" - enum: - - {} - default: {} - WorkingDir: - description: "The working directory for commands to run in." - type: "string" - Entrypoint: - description: | - The entry point for the container as a string or an array of strings. - - If the array consists of exactly one empty string (`[""]`) then the - entry point is reset to system default (i.e., the entry point used by - docker when there is no `ENTRYPOINT` instruction in the `Dockerfile`). - type: "array" - items: - type: "string" - NetworkDisabled: - description: "Disable networking for the container." - type: "boolean" - MacAddress: - description: "MAC address of the container." - type: "string" - OnBuild: - description: | - `ONBUILD` metadata that were defined in the image's `Dockerfile`. - type: "array" - items: - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - StopSignal: - description: | - Signal to stop a container as a string or unsigned integer. - type: "string" - default: "SIGTERM" - StopTimeout: - description: "Timeout to stop a container in seconds." - type: "integer" - default: 10 - Shell: - description: | - Shell for when `RUN`, `CMD`, and `ENTRYPOINT` uses a shell. - type: "array" - items: - type: "string" - - NetworkingConfig: - description: | - NetworkingConfig represents the container's networking configuration for - each of its interfaces. - It is used for the networking configs specified in the `docker create` - and `docker network connect` commands. - type: "object" - properties: - EndpointsConfig: - description: | - A mapping of network name to endpoint configuration for that network. - type: "object" - additionalProperties: - $ref: "#/definitions/EndpointSettings" - example: - # putting an example here, instead of using the example values from - # /definitions/EndpointSettings, because containers/create currently - # does not support attaching to multiple networks, so the example request - # would be confusing if it showed that multiple networks can be contained - # in the EndpointsConfig. - # TODO remove once we support multiple networks on container create (see https://github.com/moby/moby/blob/07e6b843594e061f82baa5fa23c2ff7d536c2a05/daemon/create.go#L323) - EndpointsConfig: - isolated_nw: - IPAMConfig: - IPv4Address: "172.20.30.33" - IPv6Address: "2001:db8:abcd::3033" - LinkLocalIPs: - - "169.254.34.68" - - "fe80::3468" - Links: - - "container_1" - - "container_2" - Aliases: - - "server_x" - - "server_y" - - NetworkSettings: - description: "NetworkSettings exposes the network settings in the API" - type: "object" - properties: - Bridge: - description: Name of the network'a bridge (for example, `docker0`). - type: "string" - example: "docker0" - SandboxID: - description: SandboxID uniquely represents a container's network stack. - type: "string" - example: "9d12daf2c33f5959c8bf90aa513e4f65b561738661003029ec84830cd503a0c3" - HairpinMode: - description: | - Indicates if hairpin NAT should be enabled on the virtual interface. - type: "boolean" - example: false - LinkLocalIPv6Address: - description: IPv6 unicast address using the link-local prefix. - type: "string" - example: "fe80::42:acff:fe11:1" - LinkLocalIPv6PrefixLen: - description: Prefix length of the IPv6 unicast address. - type: "integer" - example: "64" - Ports: - $ref: "#/definitions/PortMap" - SandboxKey: - description: SandboxKey identifies the sandbox - type: "string" - example: "/var/run/docker/netns/8ab54b426c38" - - # TODO is SecondaryIPAddresses actually used? - SecondaryIPAddresses: - description: "" - type: "array" - items: - $ref: "#/definitions/Address" - x-nullable: true - - # TODO is SecondaryIPv6Addresses actually used? - SecondaryIPv6Addresses: - description: "" - type: "array" - items: - $ref: "#/definitions/Address" - x-nullable: true - - # TODO properties below are part of DefaultNetworkSettings, which is - # marked as deprecated since Docker 1.9 and to be removed in Docker v17.12 - EndpointID: - description: | - EndpointID uniquely represents a service endpoint in a Sandbox. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "b88f5b905aabf2893f3cbc4ee42d1ea7980bbc0a92e2c8922b1e1795298afb0b" - Gateway: - description: | - Gateway address for the default "bridge" network. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "172.17.0.1" - GlobalIPv6Address: - description: | - Global IPv6 address for the default "bridge" network. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "2001:db8::5689" - GlobalIPv6PrefixLen: - description: | - Mask length of the global IPv6 address. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "integer" - example: 64 - IPAddress: - description: | - IPv4 address for the default "bridge" network. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "172.17.0.4" - IPPrefixLen: - description: | - Mask length of the IPv4 address. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "integer" - example: 16 - IPv6Gateway: - description: | - IPv6 gateway address for this network. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "2001:db8:2::100" - MacAddress: - description: | - MAC address for the container on the default "bridge" network. - -


- - > **Deprecated**: This field is only propagated when attached to the - > default "bridge" network. Use the information from the "bridge" - > network inside the `Networks` map instead, which contains the same - > information. This field was deprecated in Docker 1.9 and is scheduled - > to be removed in Docker 17.12.0 - type: "string" - example: "02:42:ac:11:00:04" - Networks: - description: | - Information about all networks that the container is connected to. - type: "object" - additionalProperties: - $ref: "#/definitions/EndpointSettings" - - Address: - description: Address represents an IPv4 or IPv6 IP address. - type: "object" - properties: - Addr: - description: IP address. - type: "string" - PrefixLen: - description: Mask length of the IP address. - type: "integer" - - PortMap: - description: | - PortMap describes the mapping of container ports to host ports, using the - container's port-number and protocol as key in the format `/`, - for example, `80/udp`. - - If a container's port is mapped for multiple protocols, separate entries - are added to the mapping table. - type: "object" - additionalProperties: - type: "array" - x-nullable: true - items: - $ref: "#/definitions/PortBinding" - example: - "443/tcp": - - HostIp: "127.0.0.1" - HostPort: "4443" - "80/tcp": - - HostIp: "0.0.0.0" - HostPort: "80" - - HostIp: "0.0.0.0" - HostPort: "8080" - "80/udp": - - HostIp: "0.0.0.0" - HostPort: "80" - "53/udp": - - HostIp: "0.0.0.0" - HostPort: "53" - "2377/tcp": null - - PortBinding: - description: | - PortBinding represents a binding between a host IP address and a host - port. - type: "object" - properties: - HostIp: - description: "Host IP address that the container's port is mapped to." - type: "string" - example: "127.0.0.1" - HostPort: - description: "Host port number that the container's port is mapped to." - type: "string" - example: "4443" - - GraphDriverData: - description: "Information about a container's graph driver." - type: "object" - required: [Name, Data] - properties: - Name: - type: "string" - x-nullable: false - Data: - type: "object" - x-nullable: false - additionalProperties: - type: "string" - - Image: - type: "object" - required: - - Id - - Parent - - Comment - - Created - - Container - - DockerVersion - - Author - - Architecture - - Os - - Size - - VirtualSize - - GraphDriver - - RootFS - properties: - Id: - type: "string" - x-nullable: false - RepoTags: - type: "array" - items: - type: "string" - RepoDigests: - type: "array" - items: - type: "string" - Parent: - type: "string" - x-nullable: false - Comment: - type: "string" - x-nullable: false - Created: - type: "string" - x-nullable: false - Container: - type: "string" - x-nullable: false - ContainerConfig: - $ref: "#/definitions/ContainerConfig" - DockerVersion: - type: "string" - x-nullable: false - Author: - type: "string" - x-nullable: false - Config: - $ref: "#/definitions/ContainerConfig" - Architecture: - type: "string" - x-nullable: false - Os: - type: "string" - x-nullable: false - OsVersion: - type: "string" - Size: - type: "integer" - format: "int64" - x-nullable: false - VirtualSize: - type: "integer" - format: "int64" - x-nullable: false - GraphDriver: - $ref: "#/definitions/GraphDriverData" - RootFS: - type: "object" - required: [Type] - properties: - Type: - type: "string" - x-nullable: false - Layers: - type: "array" - items: - type: "string" - BaseLayer: - type: "string" - Metadata: - type: "object" - properties: - LastTagTime: - type: "string" - format: "dateTime" - - ImageSummary: - type: "object" - required: - - Id - - ParentId - - RepoTags - - RepoDigests - - Created - - Size - - SharedSize - - VirtualSize - - Labels - - Containers - properties: - Id: - type: "string" - x-nullable: false - ParentId: - type: "string" - x-nullable: false - RepoTags: - type: "array" - x-nullable: false - items: - type: "string" - RepoDigests: - type: "array" - x-nullable: false - items: - type: "string" - Created: - type: "integer" - x-nullable: false - Size: - type: "integer" - x-nullable: false - SharedSize: - type: "integer" - x-nullable: false - VirtualSize: - type: "integer" - x-nullable: false - Labels: - type: "object" - x-nullable: false - additionalProperties: - type: "string" - Containers: - x-nullable: false - type: "integer" - - AuthConfig: - type: "object" - properties: - username: - type: "string" - password: - type: "string" - email: - type: "string" - serveraddress: - type: "string" - example: - username: "hannibal" - password: "xxxx" - serveraddress: "https://index.docker.io/v1/" - - ProcessConfig: - type: "object" - properties: - privileged: - type: "boolean" - user: - type: "string" - tty: - type: "boolean" - entrypoint: - type: "string" - arguments: - type: "array" - items: - type: "string" - - Volume: - type: "object" - required: [Name, Driver, Mountpoint, Labels, Scope, Options] - properties: - Name: - type: "string" - description: "Name of the volume." - x-nullable: false - Driver: - type: "string" - description: "Name of the volume driver used by the volume." - x-nullable: false - Mountpoint: - type: "string" - description: "Mount path of the volume on the host." - x-nullable: false - CreatedAt: - type: "string" - format: "dateTime" - description: "Date/Time the volume was created." - Status: - type: "object" - description: | - Low-level details about the volume, provided by the volume driver. - Details are returned as a map with key/value pairs: - `{"key":"value","key2":"value2"}`. - - The `Status` field is optional, and is omitted if the volume driver - does not support this feature. - additionalProperties: - type: "object" - Labels: - type: "object" - description: "User-defined key/value metadata." - x-nullable: false - additionalProperties: - type: "string" - Scope: - type: "string" - description: | - The level at which the volume exists. Either `global` for cluster-wide, - or `local` for machine level. - default: "local" - x-nullable: false - enum: ["local", "global"] - Options: - type: "object" - description: | - The driver specific options used when creating the volume. - additionalProperties: - type: "string" - UsageData: - type: "object" - x-nullable: true - required: [Size, RefCount] - description: | - Usage details about the volume. This information is used by the - `GET /system/df` endpoint, and omitted in other endpoints. - properties: - Size: - type: "integer" - default: -1 - description: | - Amount of disk space used by the volume (in bytes). This information - is only available for volumes created with the `"local"` volume - driver. For volumes created with other volume drivers, this field - is set to `-1` ("not available") - x-nullable: false - RefCount: - type: "integer" - default: -1 - description: | - The number of containers referencing this volume. This field - is set to `-1` if the reference-count is not available. - x-nullable: false - - example: - Name: "tardis" - Driver: "custom" - Mountpoint: "/var/lib/docker/volumes/tardis" - Status: - hello: "world" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - Scope: "local" - CreatedAt: "2016-06-07T20:31:11.853781916Z" - - Network: - type: "object" - properties: - Name: - type: "string" - Id: - type: "string" - Created: - type: "string" - format: "dateTime" - Scope: - type: "string" - Driver: - type: "string" - EnableIPv6: - type: "boolean" - IPAM: - $ref: "#/definitions/IPAM" - Internal: - type: "boolean" - Attachable: - type: "boolean" - Ingress: - type: "boolean" - Containers: - type: "object" - additionalProperties: - $ref: "#/definitions/NetworkContainer" - Options: - type: "object" - additionalProperties: - type: "string" - Labels: - type: "object" - additionalProperties: - type: "string" - example: - Name: "net01" - Id: "7d86d31b1478e7cca9ebed7e73aa0fdeec46c5ca29497431d3007d2d9e15ed99" - Created: "2016-10-19T04:33:30.360899459Z" - Scope: "local" - Driver: "bridge" - EnableIPv6: false - IPAM: - Driver: "default" - Config: - - Subnet: "172.19.0.0/16" - Gateway: "172.19.0.1" - Options: - foo: "bar" - Internal: false - Attachable: false - Ingress: false - Containers: - 19a4d5d687db25203351ed79d478946f861258f018fe384f229f2efa4b23513c: - Name: "test" - EndpointID: "628cadb8bcb92de107b2a1e516cbffe463e321f548feb37697cce00ad694f21a" - MacAddress: "02:42:ac:13:00:02" - IPv4Address: "172.19.0.2/16" - IPv6Address: "" - Options: - com.docker.network.bridge.default_bridge: "true" - com.docker.network.bridge.enable_icc: "true" - com.docker.network.bridge.enable_ip_masquerade: "true" - com.docker.network.bridge.host_binding_ipv4: "0.0.0.0" - com.docker.network.bridge.name: "docker0" - com.docker.network.driver.mtu: "1500" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - IPAM: - type: "object" - properties: - Driver: - description: "Name of the IPAM driver to use." - type: "string" - default: "default" - Config: - description: | - List of IPAM configuration options, specified as a map: - - ``` - {"Subnet": , "IPRange": , "Gateway": , "AuxAddress": } - ``` - type: "array" - items: - type: "object" - additionalProperties: - type: "string" - Options: - description: "Driver-specific options, specified as a map." - type: "object" - additionalProperties: - type: "string" - - NetworkContainer: - type: "object" - properties: - Name: - type: "string" - EndpointID: - type: "string" - MacAddress: - type: "string" - IPv4Address: - type: "string" - IPv6Address: - type: "string" - - BuildInfo: - type: "object" - properties: - id: - type: "string" - stream: - type: "string" - error: - type: "string" - errorDetail: - $ref: "#/definitions/ErrorDetail" - status: - type: "string" - progress: - type: "string" - progressDetail: - $ref: "#/definitions/ProgressDetail" - aux: - $ref: "#/definitions/ImageID" - - BuildCache: - type: "object" - properties: - ID: - type: "string" - Parent: - type: "string" - Type: - type: "string" - Description: - type: "string" - InUse: - type: "boolean" - Shared: - type: "boolean" - Size: - description: | - Amount of disk space used by the build cache (in bytes). - type: "integer" - CreatedAt: - description: | - Date and time at which the build cache was created in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2016-08-18T10:44:24.496525531Z" - LastUsedAt: - description: | - Date and time at which the build cache was last used in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - x-nullable: true - example: "2017-08-09T07:09:37.632105588Z" - UsageCount: - type: "integer" - - ImageID: - type: "object" - description: "Image ID or Digest" - properties: - ID: - type: "string" - example: - ID: "sha256:85f05633ddc1c50679be2b16a0479ab6f7637f8884e0cfe0f4d20e1ebb3d6e7c" - - CreateImageInfo: - type: "object" - properties: - id: - type: "string" - error: - type: "string" - status: - type: "string" - progress: - type: "string" - progressDetail: - $ref: "#/definitions/ProgressDetail" - - PushImageInfo: - type: "object" - properties: - error: - type: "string" - status: - type: "string" - progress: - type: "string" - progressDetail: - $ref: "#/definitions/ProgressDetail" - - ErrorDetail: - type: "object" - properties: - code: - type: "integer" - message: - type: "string" - - ProgressDetail: - type: "object" - properties: - current: - type: "integer" - total: - type: "integer" - - ErrorResponse: - description: "Represents an error." - type: "object" - required: ["message"] - properties: - message: - description: "The error message." - type: "string" - x-nullable: false - example: - message: "Something went wrong." - - IdResponse: - description: "Response to an API call that returns just an Id" - type: "object" - required: ["Id"] - properties: - Id: - description: "The id of the newly created object." - type: "string" - x-nullable: false - - EndpointSettings: - description: "Configuration for a network endpoint." - type: "object" - properties: - # Configurations - IPAMConfig: - $ref: "#/definitions/EndpointIPAMConfig" - Links: - type: "array" - items: - type: "string" - example: - - "container_1" - - "container_2" - Aliases: - type: "array" - items: - type: "string" - example: - - "server_x" - - "server_y" - - # Operational data - NetworkID: - description: | - Unique ID of the network. - type: "string" - example: "08754567f1f40222263eab4102e1c733ae697e8e354aa9cd6e18d7402835292a" - EndpointID: - description: | - Unique ID for the service endpoint in a Sandbox. - type: "string" - example: "b88f5b905aabf2893f3cbc4ee42d1ea7980bbc0a92e2c8922b1e1795298afb0b" - Gateway: - description: | - Gateway address for this network. - type: "string" - example: "172.17.0.1" - IPAddress: - description: | - IPv4 address. - type: "string" - example: "172.17.0.4" - IPPrefixLen: - description: | - Mask length of the IPv4 address. - type: "integer" - example: 16 - IPv6Gateway: - description: | - IPv6 gateway address. - type: "string" - example: "2001:db8:2::100" - GlobalIPv6Address: - description: | - Global IPv6 address. - type: "string" - example: "2001:db8::5689" - GlobalIPv6PrefixLen: - description: | - Mask length of the global IPv6 address. - type: "integer" - format: "int64" - example: 64 - MacAddress: - description: | - MAC address for the endpoint on this network. - type: "string" - example: "02:42:ac:11:00:04" - DriverOpts: - description: | - DriverOpts is a mapping of driver options and values. These options - are passed directly to the driver and are driver specific. - type: "object" - x-nullable: true - additionalProperties: - type: "string" - example: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - - EndpointIPAMConfig: - description: | - EndpointIPAMConfig represents an endpoint's IPAM configuration. - type: "object" - x-nullable: true - properties: - IPv4Address: - type: "string" - example: "172.20.30.33" - IPv6Address: - type: "string" - example: "2001:db8:abcd::3033" - LinkLocalIPs: - type: "array" - items: - type: "string" - example: - - "169.254.34.68" - - "fe80::3468" - - PluginMount: - type: "object" - x-nullable: false - required: [Name, Description, Settable, Source, Destination, Type, Options] - properties: - Name: - type: "string" - x-nullable: false - example: "some-mount" - Description: - type: "string" - x-nullable: false - example: "This is a mount that's used by the plugin." - Settable: - type: "array" - items: - type: "string" - Source: - type: "string" - example: "/var/lib/docker/plugins/" - Destination: - type: "string" - x-nullable: false - example: "/mnt/state" - Type: - type: "string" - x-nullable: false - example: "bind" - Options: - type: "array" - items: - type: "string" - example: - - "rbind" - - "rw" - - PluginDevice: - type: "object" - required: [Name, Description, Settable, Path] - x-nullable: false - properties: - Name: - type: "string" - x-nullable: false - Description: - type: "string" - x-nullable: false - Settable: - type: "array" - items: - type: "string" - Path: - type: "string" - example: "/dev/fuse" - - PluginEnv: - type: "object" - x-nullable: false - required: [Name, Description, Settable, Value] - properties: - Name: - x-nullable: false - type: "string" - Description: - x-nullable: false - type: "string" - Settable: - type: "array" - items: - type: "string" - Value: - type: "string" - - PluginInterfaceType: - type: "object" - x-nullable: false - required: [Prefix, Capability, Version] - properties: - Prefix: - type: "string" - x-nullable: false - Capability: - type: "string" - x-nullable: false - Version: - type: "string" - x-nullable: false - - Plugin: - description: "A plugin for the Engine API" - type: "object" - required: [Settings, Enabled, Config, Name] - properties: - Id: - type: "string" - example: "5724e2c8652da337ab2eedd19fc6fc0ec908e4bd907c7421bf6a8dfc70c4c078" - Name: - type: "string" - x-nullable: false - example: "tiborvass/sample-volume-plugin" - Enabled: - description: - True if the plugin is running. False if the plugin is not running, - only installed. - type: "boolean" - x-nullable: false - example: true - Settings: - description: "Settings that can be modified by users." - type: "object" - x-nullable: false - required: [Args, Devices, Env, Mounts] - properties: - Mounts: - type: "array" - items: - $ref: "#/definitions/PluginMount" - Env: - type: "array" - items: - type: "string" - example: - - "DEBUG=0" - Args: - type: "array" - items: - type: "string" - Devices: - type: "array" - items: - $ref: "#/definitions/PluginDevice" - PluginReference: - description: "plugin remote reference used to push/pull the plugin" - type: "string" - x-nullable: false - example: "localhost:5000/tiborvass/sample-volume-plugin:latest" - Config: - description: "The config of a plugin." - type: "object" - x-nullable: false - required: - - Description - - Documentation - - Interface - - Entrypoint - - WorkDir - - Network - - Linux - - PidHost - - PropagatedMount - - IpcHost - - Mounts - - Env - - Args - properties: - DockerVersion: - description: "Docker Version used to create the plugin" - type: "string" - x-nullable: false - example: "17.06.0-ce" - Description: - type: "string" - x-nullable: false - example: "A sample volume plugin for Docker" - Documentation: - type: "string" - x-nullable: false - example: "https://docs.docker.com/engine/extend/plugins/" - Interface: - description: "The interface between Docker and the plugin" - x-nullable: false - type: "object" - required: [Types, Socket] - properties: - Types: - type: "array" - items: - $ref: "#/definitions/PluginInterfaceType" - example: - - "docker.volumedriver/1.0" - Socket: - type: "string" - x-nullable: false - example: "plugins.sock" - ProtocolScheme: - type: "string" - example: "some.protocol/v1.0" - description: "Protocol to use for clients connecting to the plugin." - enum: - - "" - - "moby.plugins.http/v1" - Entrypoint: - type: "array" - items: - type: "string" - example: - - "/usr/bin/sample-volume-plugin" - - "/data" - WorkDir: - type: "string" - x-nullable: false - example: "/bin/" - User: - type: "object" - x-nullable: false - properties: - UID: - type: "integer" - format: "uint32" - example: 1000 - GID: - type: "integer" - format: "uint32" - example: 1000 - Network: - type: "object" - x-nullable: false - required: [Type] - properties: - Type: - x-nullable: false - type: "string" - example: "host" - Linux: - type: "object" - x-nullable: false - required: [Capabilities, AllowAllDevices, Devices] - properties: - Capabilities: - type: "array" - items: - type: "string" - example: - - "CAP_SYS_ADMIN" - - "CAP_SYSLOG" - AllowAllDevices: - type: "boolean" - x-nullable: false - example: false - Devices: - type: "array" - items: - $ref: "#/definitions/PluginDevice" - PropagatedMount: - type: "string" - x-nullable: false - example: "/mnt/volumes" - IpcHost: - type: "boolean" - x-nullable: false - example: false - PidHost: - type: "boolean" - x-nullable: false - example: false - Mounts: - type: "array" - items: - $ref: "#/definitions/PluginMount" - Env: - type: "array" - items: - $ref: "#/definitions/PluginEnv" - example: - - Name: "DEBUG" - Description: "If set, prints debug messages" - Settable: null - Value: "0" - Args: - type: "object" - x-nullable: false - required: [Name, Description, Settable, Value] - properties: - Name: - x-nullable: false - type: "string" - example: "args" - Description: - x-nullable: false - type: "string" - example: "command line arguments" - Settable: - type: "array" - items: - type: "string" - Value: - type: "array" - items: - type: "string" - rootfs: - type: "object" - properties: - type: - type: "string" - example: "layers" - diff_ids: - type: "array" - items: - type: "string" - example: - - "sha256:675532206fbf3030b8458f88d6e26d4eb1577688a25efec97154c94e8b6b4887" - - "sha256:e216a057b1cb1efc11f8a268f37ef62083e70b1b38323ba252e25ac88904a7e8" - - ObjectVersion: - description: | - The version number of the object such as node, service, etc. This is needed - to avoid conflicting writes. The client must send the version number along - with the modified specification when updating these objects. - - This approach ensures safe concurrency and determinism in that the change - on the object may not be applied if the version number has changed from the - last read. In other words, if two update requests specify the same base - version, only one of the requests can succeed. As a result, two separate - update requests that happen at the same time will not unintentionally - overwrite each other. - type: "object" - properties: - Index: - type: "integer" - format: "uint64" - example: 373531 - - NodeSpec: - type: "object" - properties: - Name: - description: "Name for the node." - type: "string" - example: "my-node" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - Role: - description: "Role of the node." - type: "string" - enum: - - "worker" - - "manager" - example: "manager" - Availability: - description: "Availability of the node." - type: "string" - enum: - - "active" - - "pause" - - "drain" - example: "active" - example: - Availability: "active" - Name: "node-name" - Role: "manager" - Labels: - foo: "bar" - - Node: - type: "object" - properties: - ID: - type: "string" - example: "24ifsmvkjbyhk" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - description: | - Date and time at which the node was added to the swarm in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2016-08-18T10:44:24.496525531Z" - UpdatedAt: - description: | - Date and time at which the node was last updated in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2017-08-09T07:09:37.632105588Z" - Spec: - $ref: "#/definitions/NodeSpec" - Description: - $ref: "#/definitions/NodeDescription" - Status: - $ref: "#/definitions/NodeStatus" - ManagerStatus: - $ref: "#/definitions/ManagerStatus" - - NodeDescription: - description: | - NodeDescription encapsulates the properties of the Node as reported by the - agent. - type: "object" - properties: - Hostname: - type: "string" - example: "bf3067039e47" - Platform: - $ref: "#/definitions/Platform" - Resources: - $ref: "#/definitions/ResourceObject" - Engine: - $ref: "#/definitions/EngineDescription" - TLSInfo: - $ref: "#/definitions/TLSInfo" - - Platform: - description: | - Platform represents the platform (Arch/OS). - type: "object" - properties: - Architecture: - description: | - Architecture represents the hardware architecture (for example, - `x86_64`). - type: "string" - example: "x86_64" - OS: - description: | - OS represents the Operating System (for example, `linux` or `windows`). - type: "string" - example: "linux" - - EngineDescription: - description: "EngineDescription provides information about an engine." - type: "object" - properties: - EngineVersion: - type: "string" - example: "17.06.0" - Labels: - type: "object" - additionalProperties: - type: "string" - example: - foo: "bar" - Plugins: - type: "array" - items: - type: "object" - properties: - Type: - type: "string" - Name: - type: "string" - example: - - Type: "Log" - Name: "awslogs" - - Type: "Log" - Name: "fluentd" - - Type: "Log" - Name: "gcplogs" - - Type: "Log" - Name: "gelf" - - Type: "Log" - Name: "journald" - - Type: "Log" - Name: "json-file" - - Type: "Log" - Name: "logentries" - - Type: "Log" - Name: "splunk" - - Type: "Log" - Name: "syslog" - - Type: "Network" - Name: "bridge" - - Type: "Network" - Name: "host" - - Type: "Network" - Name: "ipvlan" - - Type: "Network" - Name: "macvlan" - - Type: "Network" - Name: "null" - - Type: "Network" - Name: "overlay" - - Type: "Volume" - Name: "local" - - Type: "Volume" - Name: "localhost:5000/vieux/sshfs:latest" - - Type: "Volume" - Name: "vieux/sshfs:latest" - - TLSInfo: - description: | - Information about the issuer of leaf TLS certificates and the trusted root - CA certificate. - type: "object" - properties: - TrustRoot: - description: | - The root CA certificate(s) that are used to validate leaf TLS - certificates. - type: "string" - CertIssuerSubject: - description: - The base64-url-safe-encoded raw subject bytes of the issuer. - type: "string" - CertIssuerPublicKey: - description: | - The base64-url-safe-encoded raw public key bytes of the issuer. - type: "string" - example: - TrustRoot: | - -----BEGIN CERTIFICATE----- - MIIBajCCARCgAwIBAgIUbYqrLSOSQHoxD8CwG6Bi2PJi9c8wCgYIKoZIzj0EAwIw - EzERMA8GA1UEAxMIc3dhcm0tY2EwHhcNMTcwNDI0MjE0MzAwWhcNMzcwNDE5MjE0 - MzAwWjATMREwDwYDVQQDEwhzd2FybS1jYTBZMBMGByqGSM49AgEGCCqGSM49AwEH - A0IABJk/VyMPYdaqDXJb/VXh5n/1Yuv7iNrxV3Qb3l06XD46seovcDWs3IZNV1lf - 3Skyr0ofcchipoiHkXBODojJydSjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB - Af8EBTADAQH/MB0GA1UdDgQWBBRUXxuRcnFjDfR/RIAUQab8ZV/n4jAKBggqhkjO - PQQDAgNIADBFAiAy+JTe6Uc3KyLCMiqGl2GyWGQqQDEcO3/YG36x7om65AIhAJvz - pxv6zFeVEkAEEkqIYi0omA9+CjanB/6Bz4n1uw8H - -----END CERTIFICATE----- - CertIssuerSubject: "MBMxETAPBgNVBAMTCHN3YXJtLWNh" - CertIssuerPublicKey: "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEmT9XIw9h1qoNclv9VeHmf/Vi6/uI2vFXdBveXTpcPjqx6i9wNazchk1XWV/dKTKvSh9xyGKmiIeRcE4OiMnJ1A==" - - NodeStatus: - description: | - NodeStatus represents the status of a node. - - It provides the current status of the node, as seen by the manager. - type: "object" - properties: - State: - $ref: "#/definitions/NodeState" - Message: - type: "string" - example: "" - Addr: - description: "IP address of the node." - type: "string" - example: "172.17.0.2" - - NodeState: - description: "NodeState represents the state of a node." - type: "string" - enum: - - "unknown" - - "down" - - "ready" - - "disconnected" - example: "ready" - - ManagerStatus: - description: | - ManagerStatus represents the status of a manager. - - It provides the current status of a node's manager component, if the node - is a manager. - x-nullable: true - type: "object" - properties: - Leader: - type: "boolean" - default: false - example: true - Reachability: - $ref: "#/definitions/Reachability" - Addr: - description: | - The IP address and port at which the manager is reachable. - type: "string" - example: "10.0.0.46:2377" - - Reachability: - description: "Reachability represents the reachability of a node." - type: "string" - enum: - - "unknown" - - "unreachable" - - "reachable" - example: "reachable" - - SwarmSpec: - description: "User modifiable swarm configuration." - type: "object" - properties: - Name: - description: "Name of the swarm." - type: "string" - example: "default" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - example: - com.example.corp.type: "production" - com.example.corp.department: "engineering" - Orchestration: - description: "Orchestration configuration." - type: "object" - x-nullable: true - properties: - TaskHistoryRetentionLimit: - description: | - The number of historic tasks to keep per instance or node. If - negative, never remove completed or failed tasks. - type: "integer" - format: "int64" - example: 10 - Raft: - description: "Raft configuration." - type: "object" - properties: - SnapshotInterval: - description: "The number of log entries between snapshots." - type: "integer" - format: "uint64" - example: 10000 - KeepOldSnapshots: - description: | - The number of snapshots to keep beyond the current snapshot. - type: "integer" - format: "uint64" - LogEntriesForSlowFollowers: - description: | - The number of log entries to keep around to sync up slow followers - after a snapshot is created. - type: "integer" - format: "uint64" - example: 500 - ElectionTick: - description: | - The number of ticks that a follower will wait for a message from - the leader before becoming a candidate and starting an election. - `ElectionTick` must be greater than `HeartbeatTick`. - - A tick currently defaults to one second, so these translate - directly to seconds currently, but this is NOT guaranteed. - type: "integer" - example: 3 - HeartbeatTick: - description: | - The number of ticks between heartbeats. Every HeartbeatTick ticks, - the leader will send a heartbeat to the followers. - - A tick currently defaults to one second, so these translate - directly to seconds currently, but this is NOT guaranteed. - type: "integer" - example: 1 - Dispatcher: - description: "Dispatcher configuration." - type: "object" - x-nullable: true - properties: - HeartbeatPeriod: - description: | - The delay for an agent to send a heartbeat to the dispatcher. - type: "integer" - format: "int64" - example: 5000000000 - CAConfig: - description: "CA configuration." - type: "object" - x-nullable: true - properties: - NodeCertExpiry: - description: "The duration node certificates are issued for." - type: "integer" - format: "int64" - example: 7776000000000000 - ExternalCAs: - description: | - Configuration for forwarding signing requests to an external - certificate authority. - type: "array" - items: - type: "object" - properties: - Protocol: - description: | - Protocol for communication with the external CA (currently - only `cfssl` is supported). - type: "string" - enum: - - "cfssl" - default: "cfssl" - URL: - description: | - URL where certificate signing requests should be sent. - type: "string" - Options: - description: | - An object with key/value pairs that are interpreted as - protocol-specific options for the external CA driver. - type: "object" - additionalProperties: - type: "string" - CACert: - description: | - The root CA certificate (in PEM format) this external CA uses - to issue TLS certificates (assumed to be to the current swarm - root CA certificate if not provided). - type: "string" - SigningCACert: - description: | - The desired signing CA certificate for all swarm node TLS leaf - certificates, in PEM format. - type: "string" - SigningCAKey: - description: | - The desired signing CA key for all swarm node TLS leaf certificates, - in PEM format. - type: "string" - ForceRotate: - description: | - An integer whose purpose is to force swarm to generate a new - signing CA certificate and key, if none have been specified in - `SigningCACert` and `SigningCAKey` - format: "uint64" - type: "integer" - EncryptionConfig: - description: "Parameters related to encryption-at-rest." - type: "object" - properties: - AutoLockManagers: - description: | - If set, generate a key and use it to lock data stored on the - managers. - type: "boolean" - example: false - TaskDefaults: - description: "Defaults for creating tasks in this cluster." - type: "object" - properties: - LogDriver: - description: | - The log driver to use for tasks created in the orchestrator if - unspecified by a service. - - Updating this value only affects new tasks. Existing tasks continue - to use their previously configured log driver until recreated. - type: "object" - properties: - Name: - description: | - The log driver to use as a default for new tasks. - type: "string" - example: "json-file" - Options: - description: | - Driver-specific options for the selectd log driver, specified - as key/value pairs. - type: "object" - additionalProperties: - type: "string" - example: - "max-file": "10" - "max-size": "100m" - - # The Swarm information for `GET /info`. It is the same as `GET /swarm`, but - # without `JoinTokens`. - ClusterInfo: - description: | - ClusterInfo represents information about the swarm as is returned by the - "/info" endpoint. Join-tokens are not included. - x-nullable: true - type: "object" - properties: - ID: - description: "The ID of the swarm." - type: "string" - example: "abajmipo7b4xz5ip2nrla6b11" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - description: | - Date and time at which the swarm was initialised in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2016-08-18T10:44:24.496525531Z" - UpdatedAt: - description: | - Date and time at which the swarm was last updated in - [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format with nano-seconds. - type: "string" - format: "dateTime" - example: "2017-08-09T07:09:37.632105588Z" - Spec: - $ref: "#/definitions/SwarmSpec" - TLSInfo: - $ref: "#/definitions/TLSInfo" - RootRotationInProgress: - description: | - Whether there is currently a root CA rotation in progress for the swarm - type: "boolean" - example: false - DataPathPort: - description: | - DataPathPort specifies the data path port number for data traffic. - Acceptable port range is 1024 to 49151. - If no port is set or is set to 0, the default port (4789) is used. - type: "integer" - format: "uint32" - default: 4789 - example: 4789 - DefaultAddrPool: - description: | - Default Address Pool specifies default subnet pools for global scope - networks. - type: "array" - items: - type: "string" - format: "CIDR" - example: ["10.10.0.0/16", "20.20.0.0/16"] - SubnetSize: - description: | - SubnetSize specifies the subnet size of the networks created from the - default subnet pool. - type: "integer" - format: "uint32" - maximum: 29 - default: 24 - example: 24 - - JoinTokens: - description: | - JoinTokens contains the tokens workers and managers need to join the swarm. - type: "object" - properties: - Worker: - description: | - The token workers can use to join the swarm. - type: "string" - example: "SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-1awxwuwd3z9j1z3puu7rcgdbx" - Manager: - description: | - The token managers can use to join the swarm. - type: "string" - example: "SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-7p73s1dx5in4tatdymyhg9hu2" - - Swarm: - type: "object" - allOf: - - $ref: "#/definitions/ClusterInfo" - - type: "object" - properties: - JoinTokens: - $ref: "#/definitions/JoinTokens" - - TaskSpec: - description: "User modifiable task configuration." - type: "object" - properties: - PluginSpec: - type: "object" - description: | - Plugin spec for the service. *(Experimental release only.)* - -


- - > **Note**: ContainerSpec, NetworkAttachmentSpec, and PluginSpec are - > mutually exclusive. PluginSpec is only used when the Runtime field - > is set to `plugin`. NetworkAttachmentSpec is used when the Runtime - > field is set to `attachment`. - properties: - Name: - description: "The name or 'alias' to use for the plugin." - type: "string" - Remote: - description: "The plugin image reference to use." - type: "string" - Disabled: - description: "Disable the plugin once scheduled." - type: "boolean" - PluginPrivilege: - type: "array" - items: - description: | - Describes a permission accepted by the user upon installing the - plugin. - type: "object" - properties: - Name: - type: "string" - Description: - type: "string" - Value: - type: "array" - items: - type: "string" - ContainerSpec: - type: "object" - description: | - Container spec for the service. - -


- - > **Note**: ContainerSpec, NetworkAttachmentSpec, and PluginSpec are - > mutually exclusive. PluginSpec is only used when the Runtime field - > is set to `plugin`. NetworkAttachmentSpec is used when the Runtime - > field is set to `attachment`. - properties: - Image: - description: "The image name to use for the container" - type: "string" - Labels: - description: "User-defined key/value data." - type: "object" - additionalProperties: - type: "string" - Command: - description: "The command to be run in the image." - type: "array" - items: - type: "string" - Args: - description: "Arguments to the command." - type: "array" - items: - type: "string" - Hostname: - description: | - The hostname to use for the container, as a valid - [RFC 1123](https://tools.ietf.org/html/rfc1123) hostname. - type: "string" - Env: - description: | - A list of environment variables in the form `VAR=value`. - type: "array" - items: - type: "string" - Dir: - description: "The working directory for commands to run in." - type: "string" - User: - description: "The user inside the container." - type: "string" - Groups: - type: "array" - description: | - A list of additional groups that the container process will run as. - items: - type: "string" - Privileges: - type: "object" - description: "Security options for the container" - properties: - CredentialSpec: - type: "object" - description: "CredentialSpec for managed service account (Windows only)" - properties: - Config: - type: "string" - example: "0bt9dmxjvjiqermk6xrop3ekq" - description: | - Load credential spec from a Swarm Config with the given ID. - The specified config must also be present in the Configs - field with the Runtime property set. - -


- - - > **Note**: `CredentialSpec.File`, `CredentialSpec.Registry`, - > and `CredentialSpec.Config` are mutually exclusive. - File: - type: "string" - example: "spec.json" - description: | - Load credential spec from this file. The file is read by - the daemon, and must be present in the `CredentialSpecs` - subdirectory in the docker data directory, which defaults - to `C:\ProgramData\Docker\` on Windows. - - For example, specifying `spec.json` loads - `C:\ProgramData\Docker\CredentialSpecs\spec.json`. - -


- - > **Note**: `CredentialSpec.File`, `CredentialSpec.Registry`, - > and `CredentialSpec.Config` are mutually exclusive. - Registry: - type: "string" - description: | - Load credential spec from this value in the Windows - registry. The specified registry value must be located in: - - `HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\CredentialSpecs` - -


- - - > **Note**: `CredentialSpec.File`, `CredentialSpec.Registry`, - > and `CredentialSpec.Config` are mutually exclusive. - SELinuxContext: - type: "object" - description: "SELinux labels of the container" - properties: - Disable: - type: "boolean" - description: "Disable SELinux" - User: - type: "string" - description: "SELinux user label" - Role: - type: "string" - description: "SELinux role label" - Type: - type: "string" - description: "SELinux type label" - Level: - type: "string" - description: "SELinux level label" - TTY: - description: "Whether a pseudo-TTY should be allocated." - type: "boolean" - OpenStdin: - description: "Open `stdin`" - type: "boolean" - ReadOnly: - description: "Mount the container's root filesystem as read only." - type: "boolean" - Mounts: - description: | - Specification for mounts to be added to containers created as part - of the service. - type: "array" - items: - $ref: "#/definitions/Mount" - StopSignal: - description: "Signal to stop the container." - type: "string" - StopGracePeriod: - description: | - Amount of time to wait for the container to terminate before - forcefully killing it. - type: "integer" - format: "int64" - HealthCheck: - $ref: "#/definitions/HealthConfig" - Hosts: - type: "array" - description: | - A list of hostname/IP mappings to add to the container's `hosts` - file. The format of extra hosts is specified in the - [hosts(5)](http://man7.org/linux/man-pages/man5/hosts.5.html) - man page: - - IP_address canonical_hostname [aliases...] - items: - type: "string" - DNSConfig: - description: | - Specification for DNS related configurations in resolver configuration - file (`resolv.conf`). - type: "object" - properties: - Nameservers: - description: "The IP addresses of the name servers." - type: "array" - items: - type: "string" - Search: - description: "A search list for host-name lookup." - type: "array" - items: - type: "string" - Options: - description: | - A list of internal resolver variables to be modified (e.g., - `debug`, `ndots:3`, etc.). - type: "array" - items: - type: "string" - Secrets: - description: | - Secrets contains references to zero or more secrets that will be - exposed to the service. - type: "array" - items: - type: "object" - properties: - File: - description: | - File represents a specific target that is backed by a file. - type: "object" - properties: - Name: - description: | - Name represents the final filename in the filesystem. - type: "string" - UID: - description: "UID represents the file UID." - type: "string" - GID: - description: "GID represents the file GID." - type: "string" - Mode: - description: "Mode represents the FileMode of the file." - type: "integer" - format: "uint32" - SecretID: - description: | - SecretID represents the ID of the specific secret that we're - referencing. - type: "string" - SecretName: - description: | - SecretName is the name of the secret that this references, - but this is just provided for lookup/display purposes. The - secret in the reference will be identified by its ID. - type: "string" - Configs: - description: | - Configs contains references to zero or more configs that will be - exposed to the service. - type: "array" - items: - type: "object" - properties: - File: - description: | - File represents a specific target that is backed by a file. - -


- - > **Note**: `Configs.File` and `Configs.Runtime` are mutually exclusive - type: "object" - properties: - Name: - description: | - Name represents the final filename in the filesystem. - type: "string" - UID: - description: "UID represents the file UID." - type: "string" - GID: - description: "GID represents the file GID." - type: "string" - Mode: - description: "Mode represents the FileMode of the file." - type: "integer" - format: "uint32" - Runtime: - description: | - Runtime represents a target that is not mounted into the - container but is used by the task - -


- - > **Note**: `Configs.File` and `Configs.Runtime` are mutually - > exclusive - type: "object" - ConfigID: - description: | - ConfigID represents the ID of the specific config that we're - referencing. - type: "string" - ConfigName: - description: | - ConfigName is the name of the config that this references, - but this is just provided for lookup/display purposes. The - config in the reference will be identified by its ID. - type: "string" - Isolation: - type: "string" - description: | - Isolation technology of the containers running the service. - (Windows only) - enum: - - "default" - - "process" - - "hyperv" - Init: - description: | - Run an init inside the container that forwards signals and reaps - processes. This field is omitted if empty, and the default (as - configured on the daemon) is used. - type: "boolean" - x-nullable: true - Sysctls: - description: | - Set kernel namedspaced parameters (sysctls) in the container. - The Sysctls option on services accepts the same sysctls as the - are supported on containers. Note that while the same sysctls are - supported, no guarantees or checks are made about their - suitability for a clustered environment, and it's up to the user - to determine whether a given sysctl will work properly in a - Service. - type: "object" - additionalProperties: - type: "string" - # This option is not used by Windows containers - CapabilityAdd: - type: "array" - description: | - A list of kernel capabilities to add to the default set - for the container. - items: - type: "string" - example: - - "CAP_NET_RAW" - - "CAP_SYS_ADMIN" - - "CAP_SYS_CHROOT" - - "CAP_SYSLOG" - CapabilityDrop: - type: "array" - description: | - A list of kernel capabilities to drop from the default set - for the container. - items: - type: "string" - example: - - "CAP_NET_RAW" - Ulimits: - description: | - A list of resource limits to set in the container. For example: `{"Name": "nofile", "Soft": 1024, "Hard": 2048}`" - type: "array" - items: - type: "object" - properties: - Name: - description: "Name of ulimit" - type: "string" - Soft: - description: "Soft limit" - type: "integer" - Hard: - description: "Hard limit" - type: "integer" - NetworkAttachmentSpec: - description: | - Read-only spec type for non-swarm containers attached to swarm overlay - networks. - -


- - > **Note**: ContainerSpec, NetworkAttachmentSpec, and PluginSpec are - > mutually exclusive. PluginSpec is only used when the Runtime field - > is set to `plugin`. NetworkAttachmentSpec is used when the Runtime - > field is set to `attachment`. - type: "object" - properties: - ContainerID: - description: "ID of the container represented by this task" - type: "string" - Resources: - description: | - Resource requirements which apply to each individual container created - as part of the service. - type: "object" - properties: - Limits: - description: "Define resources limits." - $ref: "#/definitions/Limit" - Reservation: - description: "Define resources reservation." - $ref: "#/definitions/ResourceObject" - RestartPolicy: - description: | - Specification for the restart policy which applies to containers - created as part of this service. - type: "object" - properties: - Condition: - description: "Condition for restart." - type: "string" - enum: - - "none" - - "on-failure" - - "any" - Delay: - description: "Delay between restart attempts." - type: "integer" - format: "int64" - MaxAttempts: - description: | - Maximum attempts to restart a given container before giving up - (default value is 0, which is ignored). - type: "integer" - format: "int64" - default: 0 - Window: - description: | - Windows is the time window used to evaluate the restart policy - (default value is 0, which is unbounded). - type: "integer" - format: "int64" - default: 0 - Placement: - type: "object" - properties: - Constraints: - description: | - An array of constraint expressions to limit the set of nodes where - a task can be scheduled. Constraint expressions can either use a - _match_ (`==`) or _exclude_ (`!=`) rule. Multiple constraints find - nodes that satisfy every expression (AND match). Constraints can - match node or Docker Engine labels as follows: - - node attribute | matches | example - ---------------------|--------------------------------|----------------------------------------------- - `node.id` | Node ID | `node.id==2ivku8v2gvtg4` - `node.hostname` | Node hostname | `node.hostname!=node-2` - `node.role` | Node role (`manager`/`worker`) | `node.role==manager` - `node.platform.os` | Node operating system | `node.platform.os==windows` - `node.platform.arch` | Node architecture | `node.platform.arch==x86_64` - `node.labels` | User-defined node labels | `node.labels.security==high` - `engine.labels` | Docker Engine's labels | `engine.labels.operatingsystem==ubuntu-14.04` - - `engine.labels` apply to Docker Engine labels like operating system, - drivers, etc. Swarm administrators add `node.labels` for operational - purposes by using the [`node update endpoint`](#operation/NodeUpdate). - - type: "array" - items: - type: "string" - example: - - "node.hostname!=node3.corp.example.com" - - "node.role!=manager" - - "node.labels.type==production" - - "node.platform.os==linux" - - "node.platform.arch==x86_64" - Preferences: - description: | - Preferences provide a way to make the scheduler aware of factors - such as topology. They are provided in order from highest to - lowest precedence. - type: "array" - items: - type: "object" - properties: - Spread: - type: "object" - properties: - SpreadDescriptor: - description: | - label descriptor, such as `engine.labels.az`. - type: "string" - example: - - Spread: - SpreadDescriptor: "node.labels.datacenter" - - Spread: - SpreadDescriptor: "node.labels.rack" - MaxReplicas: - description: | - Maximum number of replicas for per node (default value is 0, which - is unlimited) - type: "integer" - format: "int64" - default: 0 - Platforms: - description: | - Platforms stores all the platforms that the service's image can - run on. This field is used in the platform filter for scheduling. - If empty, then the platform filter is off, meaning there are no - scheduling restrictions. - type: "array" - items: - $ref: "#/definitions/Platform" - ForceUpdate: - description: | - A counter that triggers an update even if no relevant parameters have - been changed. - type: "integer" - Runtime: - description: | - Runtime is the type of runtime specified for the task executor. - type: "string" - Networks: - description: "Specifies which networks the service should attach to." - type: "array" - items: - $ref: "#/definitions/NetworkAttachmentConfig" - LogDriver: - description: | - Specifies the log driver to use for tasks created from this spec. If - not present, the default one for the swarm will be used, finally - falling back to the engine default if not specified. - type: "object" - properties: - Name: - type: "string" - Options: - type: "object" - additionalProperties: - type: "string" - - TaskState: - type: "string" - enum: - - "new" - - "allocated" - - "pending" - - "assigned" - - "accepted" - - "preparing" - - "ready" - - "starting" - - "running" - - "complete" - - "shutdown" - - "failed" - - "rejected" - - "remove" - - "orphaned" - - Task: - type: "object" - properties: - ID: - description: "The ID of the task." - type: "string" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Name: - description: "Name of the task." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - Spec: - $ref: "#/definitions/TaskSpec" - ServiceID: - description: "The ID of the service this task is part of." - type: "string" - Slot: - type: "integer" - NodeID: - description: "The ID of the node that this task is on." - type: "string" - AssignedGenericResources: - $ref: "#/definitions/GenericResources" - Status: - type: "object" - properties: - Timestamp: - type: "string" - format: "dateTime" - State: - $ref: "#/definitions/TaskState" - Message: - type: "string" - Err: - type: "string" - ContainerStatus: - type: "object" - properties: - ContainerID: - type: "string" - PID: - type: "integer" - ExitCode: - type: "integer" - DesiredState: - $ref: "#/definitions/TaskState" - JobIteration: - description: | - If the Service this Task belongs to is a job-mode service, contains - the JobIteration of the Service this Task was created for. Absent if - the Task was created for a Replicated or Global Service. - $ref: "#/definitions/ObjectVersion" - example: - ID: "0kzzo1i0y4jz6027t0k7aezc7" - Version: - Index: 71 - CreatedAt: "2016-06-07T21:07:31.171892745Z" - UpdatedAt: "2016-06-07T21:07:31.376370513Z" - Spec: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ServiceID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Slot: 1 - NodeID: "60gvrl6tm78dmak4yl7srz94v" - Status: - Timestamp: "2016-06-07T21:07:31.290032978Z" - State: "running" - Message: "started" - ContainerStatus: - ContainerID: "e5d62702a1b48d01c3e02ca1e0212a250801fa8d67caca0b6f35919ebc12f035" - PID: 677 - DesiredState: "running" - NetworksAttachments: - - Network: - ID: "4qvuz4ko70xaltuqbt8956gd1" - Version: - Index: 18 - CreatedAt: "2016-06-07T20:31:11.912919752Z" - UpdatedAt: "2016-06-07T21:07:29.955277358Z" - Spec: - Name: "ingress" - Labels: - com.docker.swarm.internal: "true" - DriverConfiguration: {} - IPAMOptions: - Driver: {} - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - DriverState: - Name: "overlay" - Options: - com.docker.network.driver.overlay.vxlanid_list: "256" - IPAMOptions: - Driver: - Name: "default" - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - Addresses: - - "10.255.0.10/16" - AssignedGenericResources: - - DiscreteResourceSpec: - Kind: "SSD" - Value: 3 - - NamedResourceSpec: - Kind: "GPU" - Value: "UUID1" - - NamedResourceSpec: - Kind: "GPU" - Value: "UUID2" - - ServiceSpec: - description: "User modifiable configuration for a service." - properties: - Name: - description: "Name of the service." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - TaskTemplate: - $ref: "#/definitions/TaskSpec" - Mode: - description: "Scheduling mode for the service." - type: "object" - properties: - Replicated: - type: "object" - properties: - Replicas: - type: "integer" - format: "int64" - Global: - type: "object" - ReplicatedJob: - description: | - The mode used for services with a finite number of tasks that run - to a completed state. - type: "object" - properties: - MaxConcurrent: - description: | - The maximum number of replicas to run simultaneously. - type: "integer" - format: "int64" - default: 1 - TotalCompletions: - description: | - The total number of replicas desired to reach the Completed - state. If unset, will default to the value of `MaxConcurrent` - type: "integer" - format: "int64" - GlobalJob: - description: | - The mode used for services which run a task to the completed state - on each valid node. - type: "object" - UpdateConfig: - description: "Specification for the update strategy of the service." - type: "object" - properties: - Parallelism: - description: | - Maximum number of tasks to be updated in one iteration (0 means - unlimited parallelism). - type: "integer" - format: "int64" - Delay: - description: "Amount of time between updates, in nanoseconds." - type: "integer" - format: "int64" - FailureAction: - description: | - Action to take if an updated task fails to run, or stops running - during the update. - type: "string" - enum: - - "continue" - - "pause" - - "rollback" - Monitor: - description: | - Amount of time to monitor each updated task for failures, in - nanoseconds. - type: "integer" - format: "int64" - MaxFailureRatio: - description: | - The fraction of tasks that may fail during an update before the - failure action is invoked, specified as a floating point number - between 0 and 1. - type: "number" - default: 0 - Order: - description: | - The order of operations when rolling out an updated task. Either - the old task is shut down before the new task is started, or the - new task is started before the old task is shut down. - type: "string" - enum: - - "stop-first" - - "start-first" - RollbackConfig: - description: "Specification for the rollback strategy of the service." - type: "object" - properties: - Parallelism: - description: | - Maximum number of tasks to be rolled back in one iteration (0 means - unlimited parallelism). - type: "integer" - format: "int64" - Delay: - description: | - Amount of time between rollback iterations, in nanoseconds. - type: "integer" - format: "int64" - FailureAction: - description: | - Action to take if an rolled back task fails to run, or stops - running during the rollback. - type: "string" - enum: - - "continue" - - "pause" - Monitor: - description: | - Amount of time to monitor each rolled back task for failures, in - nanoseconds. - type: "integer" - format: "int64" - MaxFailureRatio: - description: | - The fraction of tasks that may fail during a rollback before the - failure action is invoked, specified as a floating point number - between 0 and 1. - type: "number" - default: 0 - Order: - description: | - The order of operations when rolling back a task. Either the old - task is shut down before the new task is started, or the new task - is started before the old task is shut down. - type: "string" - enum: - - "stop-first" - - "start-first" - Networks: - description: "Specifies which networks the service should attach to." - type: "array" - items: - $ref: "#/definitions/NetworkAttachmentConfig" - - EndpointSpec: - $ref: "#/definitions/EndpointSpec" - - EndpointPortConfig: - type: "object" - properties: - Name: - type: "string" - Protocol: - type: "string" - enum: - - "tcp" - - "udp" - - "sctp" - TargetPort: - description: "The port inside the container." - type: "integer" - PublishedPort: - description: "The port on the swarm hosts." - type: "integer" - PublishMode: - description: | - The mode in which port is published. - -


- - - "ingress" makes the target port accessible on every node, - regardless of whether there is a task for the service running on - that node or not. - - "host" bypasses the routing mesh and publish the port directly on - the swarm node where that service is running. - - type: "string" - enum: - - "ingress" - - "host" - default: "ingress" - example: "ingress" - - EndpointSpec: - description: "Properties that can be configured to access and load balance a service." - type: "object" - properties: - Mode: - description: | - The mode of resolution to use for internal load balancing between tasks. - type: "string" - enum: - - "vip" - - "dnsrr" - default: "vip" - Ports: - description: | - List of exposed ports that this service is accessible on from the - outside. Ports can only be provided if `vip` resolution mode is used. - type: "array" - items: - $ref: "#/definitions/EndpointPortConfig" - - Service: - type: "object" - properties: - ID: - type: "string" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Spec: - $ref: "#/definitions/ServiceSpec" - Endpoint: - type: "object" - properties: - Spec: - $ref: "#/definitions/EndpointSpec" - Ports: - type: "array" - items: - $ref: "#/definitions/EndpointPortConfig" - VirtualIPs: - type: "array" - items: - type: "object" - properties: - NetworkID: - type: "string" - Addr: - type: "string" - UpdateStatus: - description: "The status of a service update." - type: "object" - properties: - State: - type: "string" - enum: - - "updating" - - "paused" - - "completed" - StartedAt: - type: "string" - format: "dateTime" - CompletedAt: - type: "string" - format: "dateTime" - Message: - type: "string" - ServiceStatus: - description: | - The status of the service's tasks. Provided only when requested as - part of a ServiceList operation. - type: "object" - properties: - RunningTasks: - description: | - The number of tasks for the service currently in the Running state. - type: "integer" - format: "uint64" - example: 7 - DesiredTasks: - description: | - The number of tasks for the service desired to be running. - For replicated services, this is the replica count from the - service spec. For global services, this is computed by taking - count of all tasks for the service with a Desired State other - than Shutdown. - type: "integer" - format: "uint64" - example: 10 - CompletedTasks: - description: | - The number of tasks for a job that are in the Completed state. - This field must be cross-referenced with the service type, as the - value of 0 may mean the service is not in a job mode, or it may - mean the job-mode service has no tasks yet Completed. - type: "integer" - format: "uint64" - JobStatus: - description: | - The status of the service when it is in one of ReplicatedJob or - GlobalJob modes. Absent on Replicated and Global mode services. The - JobIteration is an ObjectVersion, but unlike the Service's version, - does not need to be sent with an update request. - type: "object" - properties: - JobIteration: - description: | - JobIteration is a value increased each time a Job is executed, - successfully or otherwise. "Executed", in this case, means the - job as a whole has been started, not that an individual Task has - been launched. A job is "Executed" when its ServiceSpec is - updated. JobIteration can be used to disambiguate Tasks belonging - to different executions of a job. Though JobIteration will - increase with each subsequent execution, it may not necessarily - increase by 1, and so JobIteration should not be used to - $ref: "#/definitions/ObjectVersion" - LastExecution: - description: | - The last time, as observed by the server, that this job was - started. - type: "string" - format: "dateTime" - example: - ID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Version: - Index: 19 - CreatedAt: "2016-06-07T21:05:51.880065305Z" - UpdatedAt: "2016-06-07T21:07:29.962229872Z" - Spec: - Name: "hopeful_cori" - TaskTemplate: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ForceUpdate: 0 - Mode: - Replicated: - Replicas: 1 - UpdateConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - RollbackConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - EndpointSpec: - Mode: "vip" - Ports: - - - Protocol: "tcp" - TargetPort: 6379 - PublishedPort: 30001 - Endpoint: - Spec: - Mode: "vip" - Ports: - - - Protocol: "tcp" - TargetPort: 6379 - PublishedPort: 30001 - Ports: - - - Protocol: "tcp" - TargetPort: 6379 - PublishedPort: 30001 - VirtualIPs: - - - NetworkID: "4qvuz4ko70xaltuqbt8956gd1" - Addr: "10.255.0.2/16" - - - NetworkID: "4qvuz4ko70xaltuqbt8956gd1" - Addr: "10.255.0.3/16" - - ImageDeleteResponseItem: - type: "object" - properties: - Untagged: - description: "The image ID of an image that was untagged" - type: "string" - Deleted: - description: "The image ID of an image that was deleted" - type: "string" - - ServiceUpdateResponse: - type: "object" - properties: - Warnings: - description: "Optional warning messages" - type: "array" - items: - type: "string" - example: - Warning: "unable to pin image doesnotexist:latest to digest: image library/doesnotexist:latest not found" - - ContainerSummary: - type: "array" - items: - type: "object" - properties: - Id: - description: "The ID of this container" - type: "string" - x-go-name: "ID" - Names: - description: "The names that this container has been given" - type: "array" - items: - type: "string" - Image: - description: "The name of the image used when creating this container" - type: "string" - ImageID: - description: "The ID of the image that this container was created from" - type: "string" - Command: - description: "Command to run when starting the container" - type: "string" - Created: - description: "When the container was created" - type: "integer" - format: "int64" - Ports: - description: "The ports exposed by this container" - type: "array" - items: - $ref: "#/definitions/Port" - SizeRw: - description: "The size of files that have been created or changed by this container" - type: "integer" - format: "int64" - SizeRootFs: - description: "The total size of all the files in this container" - type: "integer" - format: "int64" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - State: - description: "The state of this container (e.g. `Exited`)" - type: "string" - Status: - description: "Additional human-readable status of this container (e.g. `Exit 0`)" - type: "string" - HostConfig: - type: "object" - properties: - NetworkMode: - type: "string" - NetworkSettings: - description: "A summary of the container's network settings" - type: "object" - properties: - Networks: - type: "object" - additionalProperties: - $ref: "#/definitions/EndpointSettings" - Mounts: - type: "array" - items: - $ref: "#/definitions/Mount" - - Driver: - description: "Driver represents a driver (network, logging, secrets)." - type: "object" - required: [Name] - properties: - Name: - description: "Name of the driver." - type: "string" - x-nullable: false - example: "some-driver" - Options: - description: "Key/value map of driver-specific options." - type: "object" - x-nullable: false - additionalProperties: - type: "string" - example: - OptionA: "value for driver-specific option A" - OptionB: "value for driver-specific option B" - - SecretSpec: - type: "object" - properties: - Name: - description: "User-defined name of the secret." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - example: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - Data: - description: | - Base64-url-safe-encoded ([RFC 4648](https://tools.ietf.org/html/rfc4648#section-5)) - data to store as secret. - - This field is only used to _create_ a secret, and is not returned by - other endpoints. - type: "string" - example: "" - Driver: - description: | - Name of the secrets driver used to fetch the secret's value from an - external secret store. - $ref: "#/definitions/Driver" - Templating: - description: | - Templating driver, if applicable - - Templating controls whether and how to evaluate the config payload as - a template. If no driver is set, no templating is used. - $ref: "#/definitions/Driver" - - Secret: - type: "object" - properties: - ID: - type: "string" - example: "blt1owaxmitz71s9v5zh81zun" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - example: "2017-07-20T13:55:28.678958722Z" - UpdatedAt: - type: "string" - format: "dateTime" - example: "2017-07-20T13:55:28.678958722Z" - Spec: - $ref: "#/definitions/SecretSpec" - - ConfigSpec: - type: "object" - properties: - Name: - description: "User-defined name of the config." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - Data: - description: | - Base64-url-safe-encoded ([RFC 4648](https://tools.ietf.org/html/rfc4648#section-5)) - config data. - type: "string" - Templating: - description: | - Templating driver, if applicable - - Templating controls whether and how to evaluate the config payload as - a template. If no driver is set, no templating is used. - $ref: "#/definitions/Driver" - - Config: - type: "object" - properties: - ID: - type: "string" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Spec: - $ref: "#/definitions/ConfigSpec" - - ContainerState: - description: | - ContainerState stores container's running state. It's part of ContainerJSONBase - and will be returned by the "inspect" command. - type: "object" - properties: - Status: - description: | - String representation of the container state. Can be one of "created", - "running", "paused", "restarting", "removing", "exited", or "dead". - type: "string" - enum: ["created", "running", "paused", "restarting", "removing", "exited", "dead"] - example: "running" - Running: - description: | - Whether this container is running. - - Note that a running container can be _paused_. The `Running` and `Paused` - booleans are not mutually exclusive: - - When pausing a container (on Linux), the freezer cgroup is used to suspend - all processes in the container. Freezing the process requires the process to - be running. As a result, paused containers are both `Running` _and_ `Paused`. - - Use the `Status` field instead to determine if a container's state is "running". - type: "boolean" - example: true - Paused: - description: "Whether this container is paused." - type: "boolean" - example: false - Restarting: - description: "Whether this container is restarting." - type: "boolean" - example: false - OOMKilled: - description: | - Whether this container has been killed because it ran out of memory. - type: "boolean" - example: false - Dead: - type: "boolean" - example: false - Pid: - description: "The process ID of this container" - type: "integer" - example: 1234 - ExitCode: - description: "The last exit code of this container" - type: "integer" - example: 0 - Error: - type: "string" - StartedAt: - description: "The time when this container was last started." - type: "string" - example: "2020-01-06T09:06:59.461876391Z" - FinishedAt: - description: "The time when this container last exited." - type: "string" - example: "2020-01-06T09:07:59.461876391Z" - Health: - x-nullable: true - $ref: "#/definitions/Health" - - SystemVersion: - type: "object" - description: | - Response of Engine API: GET "/version" - properties: - Platform: - type: "object" - required: [Name] - properties: - Name: - type: "string" - Components: - type: "array" - description: | - Information about system components - items: - type: "object" - x-go-name: ComponentVersion - required: [Name, Version] - properties: - Name: - description: | - Name of the component - type: "string" - example: "Engine" - Version: - description: | - Version of the component - type: "string" - x-nullable: false - example: "19.03.12" - Details: - description: | - Key/value pairs of strings with additional information about the - component. These values are intended for informational purposes - only, and their content is not defined, and not part of the API - specification. - - These messages can be printed by the client as information to the user. - type: "object" - x-nullable: true - Version: - description: "The version of the daemon" - type: "string" - example: "19.03.12" - ApiVersion: - description: | - The default (and highest) API version that is supported by the daemon - type: "string" - example: "1.40" - MinAPIVersion: - description: | - The minimum API version that is supported by the daemon - type: "string" - example: "1.12" - GitCommit: - description: | - The Git commit of the source code that was used to build the daemon - type: "string" - example: "48a66213fe" - GoVersion: - description: | - The version Go used to compile the daemon, and the version of the Go - runtime in use. - type: "string" - example: "go1.13.14" - Os: - description: | - The operating system that the daemon is running on ("linux" or "windows") - type: "string" - example: "linux" - Arch: - description: | - The architecture that the daemon is running on - type: "string" - example: "amd64" - KernelVersion: - description: | - The kernel version (`uname -r`) that the daemon is running on. - - This field is omitted when empty. - type: "string" - example: "4.19.76-linuxkit" - Experimental: - description: | - Indicates if the daemon is started with experimental features enabled. - - This field is omitted when empty / false. - type: "boolean" - example: true - BuildTime: - description: | - The date and time that the daemon was compiled. - type: "string" - example: "2020-06-22T15:49:27.000000000+00:00" - - - SystemInfo: - type: "object" - properties: - ID: - description: | - Unique identifier of the daemon. - -


- - > **Note**: The format of the ID itself is not part of the API, and - > should not be considered stable. - type: "string" - example: "7TRN:IPZB:QYBB:VPBQ:UMPP:KARE:6ZNR:XE6T:7EWV:PKF4:ZOJD:TPYS" - Containers: - description: "Total number of containers on the host." - type: "integer" - example: 14 - ContainersRunning: - description: | - Number of containers with status `"running"`. - type: "integer" - example: 3 - ContainersPaused: - description: | - Number of containers with status `"paused"`. - type: "integer" - example: 1 - ContainersStopped: - description: | - Number of containers with status `"stopped"`. - type: "integer" - example: 10 - Images: - description: | - Total number of images on the host. - - Both _tagged_ and _untagged_ (dangling) images are counted. - type: "integer" - example: 508 - Driver: - description: "Name of the storage driver in use." - type: "string" - example: "overlay2" - DriverStatus: - description: | - Information specific to the storage driver, provided as - "label" / "value" pairs. - - This information is provided by the storage driver, and formatted - in a way consistent with the output of `docker info` on the command - line. - -


- - > **Note**: The information returned in this field, including the - > formatting of values and labels, should not be considered stable, - > and may change without notice. - type: "array" - items: - type: "array" - items: - type: "string" - example: - - ["Backing Filesystem", "extfs"] - - ["Supports d_type", "true"] - - ["Native Overlay Diff", "true"] - DockerRootDir: - description: | - Root directory of persistent Docker state. - - Defaults to `/var/lib/docker` on Linux, and `C:\ProgramData\docker` - on Windows. - type: "string" - example: "/var/lib/docker" - Plugins: - $ref: "#/definitions/PluginsInfo" - MemoryLimit: - description: "Indicates if the host has memory limit support enabled." - type: "boolean" - example: true - SwapLimit: - description: "Indicates if the host has memory swap limit support enabled." - type: "boolean" - example: true - KernelMemory: - description: | - Indicates if the host has kernel memory limit support enabled. - -


- - > **Deprecated**: This field is deprecated as the kernel 5.4 deprecated - > `kmem.limit_in_bytes`. - type: "boolean" - example: true - CpuCfsPeriod: - description: | - Indicates if CPU CFS(Completely Fair Scheduler) period is supported by - the host. - type: "boolean" - example: true - CpuCfsQuota: - description: | - Indicates if CPU CFS(Completely Fair Scheduler) quota is supported by - the host. - type: "boolean" - example: true - CPUShares: - description: | - Indicates if CPU Shares limiting is supported by the host. - type: "boolean" - example: true - CPUSet: - description: | - Indicates if CPUsets (cpuset.cpus, cpuset.mems) are supported by the host. - - See [cpuset(7)](https://www.kernel.org/doc/Documentation/cgroup-v1/cpusets.txt) - type: "boolean" - example: true - PidsLimit: - description: "Indicates if the host kernel has PID limit support enabled." - type: "boolean" - example: true - OomKillDisable: - description: "Indicates if OOM killer disable is supported on the host." - type: "boolean" - IPv4Forwarding: - description: "Indicates IPv4 forwarding is enabled." - type: "boolean" - example: true - BridgeNfIptables: - description: "Indicates if `bridge-nf-call-iptables` is available on the host." - type: "boolean" - example: true - BridgeNfIp6tables: - description: "Indicates if `bridge-nf-call-ip6tables` is available on the host." - type: "boolean" - example: true - Debug: - description: | - Indicates if the daemon is running in debug-mode / with debug-level - logging enabled. - type: "boolean" - example: true - NFd: - description: | - The total number of file Descriptors in use by the daemon process. - - This information is only returned if debug-mode is enabled. - type: "integer" - example: 64 - NGoroutines: - description: | - The number of goroutines that currently exist. - - This information is only returned if debug-mode is enabled. - type: "integer" - example: 174 - SystemTime: - description: | - Current system-time in [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) - format with nano-seconds. - type: "string" - example: "2017-08-08T20:28:29.06202363Z" - LoggingDriver: - description: | - The logging driver to use as a default for new containers. - type: "string" - CgroupDriver: - description: | - The driver to use for managing cgroups. - type: "string" - enum: ["cgroupfs", "systemd", "none"] - default: "cgroupfs" - example: "cgroupfs" - CgroupVersion: - description: | - The version of the cgroup. - type: "string" - enum: ["1", "2"] - default: "1" - example: "1" - NEventsListener: - description: "Number of event listeners subscribed." - type: "integer" - example: 30 - KernelVersion: - description: | - Kernel version of the host. - - On Linux, this information obtained from `uname`. On Windows this - information is queried from the HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ - registry value, for example _"10.0 14393 (14393.1198.amd64fre.rs1_release_sec.170427-1353)"_. - type: "string" - example: "4.9.38-moby" - OperatingSystem: - description: | - Name of the host's operating system, for example: "Ubuntu 16.04.2 LTS" - or "Windows Server 2016 Datacenter" - type: "string" - example: "Alpine Linux v3.5" - OSVersion: - description: | - Version of the host's operating system - -


- - > **Note**: The information returned in this field, including its - > very existence, and the formatting of values, should not be considered - > stable, and may change without notice. - type: "string" - example: "16.04" - OSType: - description: | - Generic type of the operating system of the host, as returned by the - Go runtime (`GOOS`). - - Currently returned values are "linux" and "windows". A full list of - possible values can be found in the [Go documentation](https://golang.org/doc/install/source#environment). - type: "string" - example: "linux" - Architecture: - description: | - Hardware architecture of the host, as returned by the Go runtime - (`GOARCH`). - - A full list of possible values can be found in the [Go documentation](https://golang.org/doc/install/source#environment). - type: "string" - example: "x86_64" - NCPU: - description: | - The number of logical CPUs usable by the daemon. - - The number of available CPUs is checked by querying the operating - system when the daemon starts. Changes to operating system CPU - allocation after the daemon is started are not reflected. - type: "integer" - example: 4 - MemTotal: - description: | - Total amount of physical memory available on the host, in bytes. - type: "integer" - format: "int64" - example: 2095882240 - - IndexServerAddress: - description: | - Address / URL of the index server that is used for image search, - and as a default for user authentication for Docker Hub and Docker Cloud. - default: "https://index.docker.io/v1/" - type: "string" - example: "https://index.docker.io/v1/" - RegistryConfig: - $ref: "#/definitions/RegistryServiceConfig" - GenericResources: - $ref: "#/definitions/GenericResources" - HttpProxy: - description: | - HTTP-proxy configured for the daemon. This value is obtained from the - [`HTTP_PROXY`](https://www.gnu.org/software/wget/manual/html_node/Proxies.html) environment variable. - Credentials ([user info component](https://tools.ietf.org/html/rfc3986#section-3.2.1)) in the proxy URL - are masked in the API response. - - Containers do not automatically inherit this configuration. - type: "string" - example: "http://xxxxx:xxxxx@proxy.corp.example.com:8080" - HttpsProxy: - description: | - HTTPS-proxy configured for the daemon. This value is obtained from the - [`HTTPS_PROXY`](https://www.gnu.org/software/wget/manual/html_node/Proxies.html) environment variable. - Credentials ([user info component](https://tools.ietf.org/html/rfc3986#section-3.2.1)) in the proxy URL - are masked in the API response. - - Containers do not automatically inherit this configuration. - type: "string" - example: "https://xxxxx:xxxxx@proxy.corp.example.com:4443" - NoProxy: - description: | - Comma-separated list of domain extensions for which no proxy should be - used. This value is obtained from the [`NO_PROXY`](https://www.gnu.org/software/wget/manual/html_node/Proxies.html) - environment variable. - - Containers do not automatically inherit this configuration. - type: "string" - example: "*.local, 169.254/16" - Name: - description: "Hostname of the host." - type: "string" - example: "node5.corp.example.com" - Labels: - description: | - User-defined labels (key/value metadata) as set on the daemon. - -


- - > **Note**: When part of a Swarm, nodes can both have _daemon_ labels, - > set through the daemon configuration, and _node_ labels, set from a - > manager node in the Swarm. Node labels are not included in this - > field. Node labels can be retrieved using the `/nodes/(id)` endpoint - > on a manager node in the Swarm. - type: "array" - items: - type: "string" - example: ["storage=ssd", "production"] - ExperimentalBuild: - description: | - Indicates if experimental features are enabled on the daemon. - type: "boolean" - example: true - ServerVersion: - description: | - Version string of the daemon. - - > **Note**: the [standalone Swarm API](https://docs.docker.com/swarm/swarm-api/) - > returns the Swarm version instead of the daemon version, for example - > `swarm/1.2.8`. - type: "string" - example: "17.06.0-ce" - ClusterStore: - description: | - URL of the distributed storage backend. - - - The storage backend is used for multihost networking (to store - network and endpoint information) and by the node discovery mechanism. - -


- - > **Deprecated**: This field is only propagated when using standalone Swarm - > mode, and overlay networking using an external k/v store. Overlay - > networks with Swarm mode enabled use the built-in raft store, and - > this field will be empty. - type: "string" - example: "consul://consul.corp.example.com:8600/some/path" - ClusterAdvertise: - description: | - The network endpoint that the Engine advertises for the purpose of - node discovery. ClusterAdvertise is a `host:port` combination on which - the daemon is reachable by other hosts. - -


- - > **Deprecated**: This field is only propagated when using standalone Swarm - > mode, and overlay networking using an external k/v store. Overlay - > networks with Swarm mode enabled use the built-in raft store, and - > this field will be empty. - type: "string" - example: "node5.corp.example.com:8000" - Runtimes: - description: | - List of [OCI compliant](https://github.com/opencontainers/runtime-spec) - runtimes configured on the daemon. Keys hold the "name" used to - reference the runtime. - - The Docker daemon relies on an OCI compliant runtime (invoked via the - `containerd` daemon) as its interface to the Linux kernel namespaces, - cgroups, and SELinux. - - The default runtime is `runc`, and automatically configured. Additional - runtimes can be configured by the user and will be listed here. - type: "object" - additionalProperties: - $ref: "#/definitions/Runtime" - default: - runc: - path: "runc" - example: - runc: - path: "runc" - runc-master: - path: "/go/bin/runc" - custom: - path: "/usr/local/bin/my-oci-runtime" - runtimeArgs: ["--debug", "--systemd-cgroup=false"] - DefaultRuntime: - description: | - Name of the default OCI runtime that is used when starting containers. - - The default can be overridden per-container at create time. - type: "string" - default: "runc" - example: "runc" - Swarm: - $ref: "#/definitions/SwarmInfo" - LiveRestoreEnabled: - description: | - Indicates if live restore is enabled. - - If enabled, containers are kept running when the daemon is shutdown - or upon daemon start if running containers are detected. - type: "boolean" - default: false - example: false - Isolation: - description: | - Represents the isolation technology to use as a default for containers. - The supported values are platform-specific. - - If no isolation value is specified on daemon start, on Windows client, - the default is `hyperv`, and on Windows server, the default is `process`. - - This option is currently not used on other platforms. - default: "default" - type: "string" - enum: - - "default" - - "hyperv" - - "process" - InitBinary: - description: | - Name and, optional, path of the `docker-init` binary. - - If the path is omitted, the daemon searches the host's `$PATH` for the - binary and uses the first result. - type: "string" - example: "docker-init" - ContainerdCommit: - $ref: "#/definitions/Commit" - RuncCommit: - $ref: "#/definitions/Commit" - InitCommit: - $ref: "#/definitions/Commit" - SecurityOptions: - description: | - List of security features that are enabled on the daemon, such as - apparmor, seccomp, SELinux, user-namespaces (userns), and rootless. - - Additional configuration options for each security feature may - be present, and are included as a comma-separated list of key/value - pairs. - type: "array" - items: - type: "string" - example: - - "name=apparmor" - - "name=seccomp,profile=default" - - "name=selinux" - - "name=userns" - - "name=rootless" - ProductLicense: - description: | - Reports a summary of the product license on the daemon. - - If a commercial license has been applied to the daemon, information - such as number of nodes, and expiration are included. - type: "string" - example: "Community Engine" - DefaultAddressPools: - description: | - List of custom default address pools for local networks, which can be - specified in the daemon.json file or dockerd option. - - Example: a Base "10.10.0.0/16" with Size 24 will define the set of 256 - 10.10.[0-255].0/24 address pools. - type: "array" - items: - type: "object" - properties: - Base: - description: "The network address in CIDR format" - type: "string" - example: "10.10.0.0/16" - Size: - description: "The network pool size" - type: "integer" - example: "24" - Warnings: - description: | - List of warnings / informational messages about missing features, or - issues related to the daemon configuration. - - These messages can be printed by the client as information to the user. - type: "array" - items: - type: "string" - example: - - "WARNING: No memory limit support" - - "WARNING: bridge-nf-call-iptables is disabled" - - "WARNING: bridge-nf-call-ip6tables is disabled" - - - # PluginsInfo is a temp struct holding Plugins name - # registered with docker daemon. It is used by Info struct - PluginsInfo: - description: | - Available plugins per type. - -


- - > **Note**: Only unmanaged (V1) plugins are included in this list. - > V1 plugins are "lazily" loaded, and are not returned in this list - > if there is no resource using the plugin. - type: "object" - properties: - Volume: - description: "Names of available volume-drivers, and network-driver plugins." - type: "array" - items: - type: "string" - example: ["local"] - Network: - description: "Names of available network-drivers, and network-driver plugins." - type: "array" - items: - type: "string" - example: ["bridge", "host", "ipvlan", "macvlan", "null", "overlay"] - Authorization: - description: "Names of available authorization plugins." - type: "array" - items: - type: "string" - example: ["img-authz-plugin", "hbm"] - Log: - description: "Names of available logging-drivers, and logging-driver plugins." - type: "array" - items: - type: "string" - example: ["awslogs", "fluentd", "gcplogs", "gelf", "journald", "json-file", "logentries", "splunk", "syslog"] - - - RegistryServiceConfig: - description: | - RegistryServiceConfig stores daemon registry services configuration. - type: "object" - x-nullable: true - properties: - AllowNondistributableArtifactsCIDRs: - description: | - List of IP ranges to which nondistributable artifacts can be pushed, - using the CIDR syntax [RFC 4632](https://tools.ietf.org/html/4632). - - Some images (for example, Windows base images) contain artifacts - whose distribution is restricted by license. When these images are - pushed to a registry, restricted artifacts are not included. - - This configuration override this behavior, and enables the daemon to - push nondistributable artifacts to all registries whose resolved IP - address is within the subnet described by the CIDR syntax. - - This option is useful when pushing images containing - nondistributable artifacts to a registry on an air-gapped network so - hosts on that network can pull the images without connecting to - another server. - - > **Warning**: Nondistributable artifacts typically have restrictions - > on how and where they can be distributed and shared. Only use this - > feature to push artifacts to private registries and ensure that you - > are in compliance with any terms that cover redistributing - > nondistributable artifacts. - - type: "array" - items: - type: "string" - example: ["::1/128", "127.0.0.0/8"] - AllowNondistributableArtifactsHostnames: - description: | - List of registry hostnames to which nondistributable artifacts can be - pushed, using the format `[:]` or `[:]`. - - Some images (for example, Windows base images) contain artifacts - whose distribution is restricted by license. When these images are - pushed to a registry, restricted artifacts are not included. - - This configuration override this behavior for the specified - registries. - - This option is useful when pushing images containing - nondistributable artifacts to a registry on an air-gapped network so - hosts on that network can pull the images without connecting to - another server. - - > **Warning**: Nondistributable artifacts typically have restrictions - > on how and where they can be distributed and shared. Only use this - > feature to push artifacts to private registries and ensure that you - > are in compliance with any terms that cover redistributing - > nondistributable artifacts. - type: "array" - items: - type: "string" - example: ["registry.internal.corp.example.com:3000", "[2001:db8:a0b:12f0::1]:443"] - InsecureRegistryCIDRs: - description: | - List of IP ranges of insecure registries, using the CIDR syntax - ([RFC 4632](https://tools.ietf.org/html/4632)). Insecure registries - accept un-encrypted (HTTP) and/or untrusted (HTTPS with certificates - from unknown CAs) communication. - - By default, local registries (`127.0.0.0/8`) are configured as - insecure. All other registries are secure. Communicating with an - insecure registry is not possible if the daemon assumes that registry - is secure. - - This configuration override this behavior, insecure communication with - registries whose resolved IP address is within the subnet described by - the CIDR syntax. - - Registries can also be marked insecure by hostname. Those registries - are listed under `IndexConfigs` and have their `Secure` field set to - `false`. - - > **Warning**: Using this option can be useful when running a local - > registry, but introduces security vulnerabilities. This option - > should therefore ONLY be used for testing purposes. For increased - > security, users should add their CA to their system's list of trusted - > CAs instead of enabling this option. - type: "array" - items: - type: "string" - example: ["::1/128", "127.0.0.0/8"] - IndexConfigs: - type: "object" - additionalProperties: - $ref: "#/definitions/IndexInfo" - example: - "127.0.0.1:5000": - "Name": "127.0.0.1:5000" - "Mirrors": [] - "Secure": false - "Official": false - "[2001:db8:a0b:12f0::1]:80": - "Name": "[2001:db8:a0b:12f0::1]:80" - "Mirrors": [] - "Secure": false - "Official": false - "docker.io": - Name: "docker.io" - Mirrors: ["https://hub-mirror.corp.example.com:5000/"] - Secure: true - Official: true - "registry.internal.corp.example.com:3000": - Name: "registry.internal.corp.example.com:3000" - Mirrors: [] - Secure: false - Official: false - Mirrors: - description: | - List of registry URLs that act as a mirror for the official - (`docker.io`) registry. - - type: "array" - items: - type: "string" - example: - - "https://hub-mirror.corp.example.com:5000/" - - "https://[2001:db8:a0b:12f0::1]/" - - IndexInfo: - description: - IndexInfo contains information about a registry. - type: "object" - x-nullable: true - properties: - Name: - description: | - Name of the registry, such as "docker.io". - type: "string" - example: "docker.io" - Mirrors: - description: | - List of mirrors, expressed as URIs. - type: "array" - items: - type: "string" - example: - - "https://hub-mirror.corp.example.com:5000/" - - "https://registry-2.docker.io/" - - "https://registry-3.docker.io/" - Secure: - description: | - Indicates if the registry is part of the list of insecure - registries. - - If `false`, the registry is insecure. Insecure registries accept - un-encrypted (HTTP) and/or untrusted (HTTPS with certificates from - unknown CAs) communication. - - > **Warning**: Insecure registries can be useful when running a local - > registry. However, because its use creates security vulnerabilities - > it should ONLY be enabled for testing purposes. For increased - > security, users should add their CA to their system's list of - > trusted CAs instead of enabling this option. - type: "boolean" - example: true - Official: - description: | - Indicates whether this is an official registry (i.e., Docker Hub / docker.io) - type: "boolean" - example: true - - Runtime: - description: | - Runtime describes an [OCI compliant](https://github.com/opencontainers/runtime-spec) - runtime. - - The runtime is invoked by the daemon via the `containerd` daemon. OCI - runtimes act as an interface to the Linux kernel namespaces, cgroups, - and SELinux. - type: "object" - properties: - path: - description: | - Name and, optional, path, of the OCI executable binary. - - If the path is omitted, the daemon searches the host's `$PATH` for the - binary and uses the first result. - type: "string" - example: "/usr/local/bin/my-oci-runtime" - runtimeArgs: - description: | - List of command-line arguments to pass to the runtime when invoked. - type: "array" - x-nullable: true - items: - type: "string" - example: ["--debug", "--systemd-cgroup=false"] - - Commit: - description: | - Commit holds the Git-commit (SHA1) that a binary was built from, as - reported in the version-string of external tools, such as `containerd`, - or `runC`. - type: "object" - properties: - ID: - description: "Actual commit ID of external tool." - type: "string" - example: "cfb82a876ecc11b5ca0977d1733adbe58599088a" - Expected: - description: | - Commit ID of external tool expected by dockerd as set at build time. - type: "string" - example: "2d41c047c83e09a6d61d464906feb2a2f3c52aa4" - - SwarmInfo: - description: | - Represents generic information about swarm. - type: "object" - properties: - NodeID: - description: "Unique identifier of for this node in the swarm." - type: "string" - default: "" - example: "k67qz4598weg5unwwffg6z1m1" - NodeAddr: - description: | - IP address at which this node can be reached by other nodes in the - swarm. - type: "string" - default: "" - example: "10.0.0.46" - LocalNodeState: - $ref: "#/definitions/LocalNodeState" - ControlAvailable: - type: "boolean" - default: false - example: true - Error: - type: "string" - default: "" - RemoteManagers: - description: | - List of ID's and addresses of other managers in the swarm. - type: "array" - default: null - x-nullable: true - items: - $ref: "#/definitions/PeerNode" - example: - - NodeID: "71izy0goik036k48jg985xnds" - Addr: "10.0.0.158:2377" - - NodeID: "79y6h1o4gv8n120drcprv5nmc" - Addr: "10.0.0.159:2377" - - NodeID: "k67qz4598weg5unwwffg6z1m1" - Addr: "10.0.0.46:2377" - Nodes: - description: "Total number of nodes in the swarm." - type: "integer" - x-nullable: true - example: 4 - Managers: - description: "Total number of managers in the swarm." - type: "integer" - x-nullable: true - example: 3 - Cluster: - $ref: "#/definitions/ClusterInfo" - - LocalNodeState: - description: "Current local status of this node." - type: "string" - default: "" - enum: - - "" - - "inactive" - - "pending" - - "active" - - "error" - - "locked" - example: "active" - - PeerNode: - description: "Represents a peer-node in the swarm" - properties: - NodeID: - description: "Unique identifier of for this node in the swarm." - type: "string" - Addr: - description: | - IP address and ports at which this node can be reached. - type: "string" - - NetworkAttachmentConfig: - description: | - Specifies how a service should be attached to a particular network. - type: "object" - properties: - Target: - description: | - The target network for attachment. Must be a network name or ID. - type: "string" - Aliases: - description: | - Discoverable alternate names for the service on this network. - type: "array" - items: - type: "string" - DriverOpts: - description: | - Driver attachment options for the network target. - type: "object" - additionalProperties: - type: "string" - -paths: - /containers/json: - get: - summary: "List containers" - description: | - Returns a list of containers. For details on the format, see the - [inspect endpoint](#operation/ContainerInspect). - - Note that it uses a different, smaller representation of a container - than inspecting a single container. For example, the list of linked - containers is not propagated . - operationId: "ContainerList" - produces: - - "application/json" - parameters: - - name: "all" - in: "query" - description: | - Return all containers. By default, only running containers are shown. - type: "boolean" - default: false - - name: "limit" - in: "query" - description: | - Return this number of most recently created containers, including - non-running ones. - type: "integer" - - name: "size" - in: "query" - description: | - Return the size of container as fields `SizeRw` and `SizeRootFs`. - type: "boolean" - default: false - - name: "filters" - in: "query" - description: | - Filters to process on the container list, encoded as JSON (a - `map[string][]string`). For example, `{"status": ["paused"]}` will - only return paused containers. - - Available filters: - - - `ancestor`=(`[:]`, ``, or ``) - - `before`=(`` or ``) - - `expose`=(`[/]`|`/[]`) - - `exited=` containers with exit code of `` - - `health`=(`starting`|`healthy`|`unhealthy`|`none`) - - `id=` a container's ID - - `isolation=`(`default`|`process`|`hyperv`) (Windows daemon only) - - `is-task=`(`true`|`false`) - - `label=key` or `label="key=value"` of a container label - - `name=` a container's name - - `network`=(`` or ``) - - `publish`=(`[/]`|`/[]`) - - `since`=(`` or ``) - - `status=`(`created`|`restarting`|`running`|`removing`|`paused`|`exited`|`dead`) - - `volume`=(`` or ``) - type: "string" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/ContainerSummary" - examples: - application/json: - - Id: "8dfafdbc3a40" - Names: - - "/boring_feynman" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 1" - Created: 1367854155 - State: "Exited" - Status: "Exit 0" - Ports: - - PrivatePort: 2222 - PublicPort: 3333 - Type: "tcp" - Labels: - com.example.vendor: "Acme" - com.example.license: "GPL" - com.example.version: "1.0" - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "2cdc4edb1ded3631c81f57966563e5c8525b81121bb3706a9a9a3ae102711f3f" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.2" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:02" - Mounts: - - Name: "fac362...80535" - Source: "/data" - Destination: "/data" - Driver: "local" - Mode: "ro,Z" - RW: false - Propagation: "" - - Id: "9cd87474be90" - Names: - - "/coolName" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 222222" - Created: 1367854155 - State: "Exited" - Status: "Exit 0" - Ports: [] - Labels: {} - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "88eaed7b37b38c2a3f0c4bc796494fdf51b270c2d22656412a2ca5d559a64d7a" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.8" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:08" - Mounts: [] - - Id: "3176a2479c92" - Names: - - "/sleepy_dog" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 3333333333333333" - Created: 1367854154 - State: "Exited" - Status: "Exit 0" - Ports: [] - Labels: {} - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "8b27c041c30326d59cd6e6f510d4f8d1d570a228466f956edf7815508f78e30d" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.6" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:06" - Mounts: [] - - Id: "4cb07b47f9fb" - Names: - - "/running_cat" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 444444444444444444444444444444444" - Created: 1367854152 - State: "Exited" - Status: "Exit 0" - Ports: [] - Labels: {} - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "d91c7b2f0644403d7ef3095985ea0e2370325cd2332ff3a3225c4247328e66e9" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.5" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:05" - Mounts: [] - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Container"] - /containers/create: - post: - summary: "Create a container" - operationId: "ContainerCreate" - consumes: - - "application/json" - - "application/octet-stream" - produces: - - "application/json" - parameters: - - name: "name" - in: "query" - description: | - Assign the specified name to the container. Must match - `/?[a-zA-Z0-9][a-zA-Z0-9_.-]+`. - type: "string" - pattern: "^/?[a-zA-Z0-9][a-zA-Z0-9_.-]+$" - - name: "body" - in: "body" - description: "Container to create" - schema: - allOf: - - $ref: "#/definitions/ContainerConfig" - - type: "object" - properties: - HostConfig: - $ref: "#/definitions/HostConfig" - NetworkingConfig: - $ref: "#/definitions/NetworkingConfig" - example: - Hostname: "" - Domainname: "" - User: "" - AttachStdin: false - AttachStdout: true - AttachStderr: true - Tty: false - OpenStdin: false - StdinOnce: false - Env: - - "FOO=bar" - - "BAZ=quux" - Cmd: - - "date" - Entrypoint: "" - Image: "ubuntu" - Labels: - com.example.vendor: "Acme" - com.example.license: "GPL" - com.example.version: "1.0" - Volumes: - /volumes/data: {} - WorkingDir: "" - NetworkDisabled: false - MacAddress: "12:34:56:78:9a:bc" - ExposedPorts: - 22/tcp: {} - StopSignal: "SIGTERM" - StopTimeout: 10 - HostConfig: - Binds: - - "/tmp:/tmp" - Links: - - "redis3:redis" - Memory: 0 - MemorySwap: 0 - MemoryReservation: 0 - KernelMemory: 0 - NanoCpus: 500000 - CpuPercent: 80 - CpuShares: 512 - CpuPeriod: 100000 - CpuRealtimePeriod: 1000000 - CpuRealtimeRuntime: 10000 - CpuQuota: 50000 - CpusetCpus: "0,1" - CpusetMems: "0,1" - MaximumIOps: 0 - MaximumIOBps: 0 - BlkioWeight: 300 - BlkioWeightDevice: - - {} - BlkioDeviceReadBps: - - {} - BlkioDeviceReadIOps: - - {} - BlkioDeviceWriteBps: - - {} - BlkioDeviceWriteIOps: - - {} - DeviceRequests: - - Driver: "nvidia" - Count: -1 - DeviceIDs": ["0", "1", "GPU-fef8089b-4820-abfc-e83e-94318197576e"] - Capabilities: [["gpu", "nvidia", "compute"]] - Options: - property1: "string" - property2: "string" - MemorySwappiness: 60 - OomKillDisable: false - OomScoreAdj: 500 - PidMode: "" - PidsLimit: 0 - PortBindings: - 22/tcp: - - HostPort: "11022" - PublishAllPorts: false - Privileged: false - ReadonlyRootfs: false - Dns: - - "8.8.8.8" - DnsOptions: - - "" - DnsSearch: - - "" - VolumesFrom: - - "parent" - - "other:ro" - CapAdd: - - "NET_ADMIN" - CapDrop: - - "MKNOD" - GroupAdd: - - "newgroup" - RestartPolicy: - Name: "" - MaximumRetryCount: 0 - AutoRemove: true - NetworkMode: "bridge" - Devices: [] - Ulimits: - - {} - LogConfig: - Type: "json-file" - Config: {} - SecurityOpt: [] - StorageOpt: {} - CgroupParent: "" - VolumeDriver: "" - ShmSize: 67108864 - NetworkingConfig: - EndpointsConfig: - isolated_nw: - IPAMConfig: - IPv4Address: "172.20.30.33" - IPv6Address: "2001:db8:abcd::3033" - LinkLocalIPs: - - "169.254.34.68" - - "fe80::3468" - Links: - - "container_1" - - "container_2" - Aliases: - - "server_x" - - "server_y" - - required: true - responses: - 201: - description: "Container created successfully" - schema: - type: "object" - title: "ContainerCreateResponse" - description: "OK response to ContainerCreate operation" - required: [Id, Warnings] - properties: - Id: - description: "The ID of the created container" - type: "string" - x-nullable: false - Warnings: - description: "Warnings encountered when creating the container" - type: "array" - x-nullable: false - items: - type: "string" - examples: - application/json: - Id: "e90e34656806" - Warnings: [] - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "conflict" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Container"] - /containers/{id}/json: - get: - summary: "Inspect a container" - description: "Return low-level information about a container." - operationId: "ContainerInspect" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "object" - title: "ContainerInspectResponse" - properties: - Id: - description: "The ID of the container" - type: "string" - Created: - description: "The time the container was created" - type: "string" - Path: - description: "The path to the command being run" - type: "string" - Args: - description: "The arguments to the command being run" - type: "array" - items: - type: "string" - State: - x-nullable: true - $ref: "#/definitions/ContainerState" - Image: - description: "The container's image ID" - type: "string" - ResolvConfPath: - type: "string" - HostnamePath: - type: "string" - HostsPath: - type: "string" - LogPath: - type: "string" - Name: - type: "string" - RestartCount: - type: "integer" - Driver: - type: "string" - Platform: - type: "string" - MountLabel: - type: "string" - ProcessLabel: - type: "string" - AppArmorProfile: - type: "string" - ExecIDs: - description: "IDs of exec instances that are running in the container." - type: "array" - items: - type: "string" - x-nullable: true - HostConfig: - $ref: "#/definitions/HostConfig" - GraphDriver: - $ref: "#/definitions/GraphDriverData" - SizeRw: - description: | - The size of files that have been created or changed by this - container. - type: "integer" - format: "int64" - SizeRootFs: - description: "The total size of all the files in this container." - type: "integer" - format: "int64" - Mounts: - type: "array" - items: - $ref: "#/definitions/MountPoint" - Config: - $ref: "#/definitions/ContainerConfig" - NetworkSettings: - $ref: "#/definitions/NetworkSettings" - examples: - application/json: - AppArmorProfile: "" - Args: - - "-c" - - "exit 9" - Config: - AttachStderr: true - AttachStdin: false - AttachStdout: true - Cmd: - - "/bin/sh" - - "-c" - - "exit 9" - Domainname: "" - Env: - - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - Healthcheck: - Test: ["CMD-SHELL", "exit 0"] - Hostname: "ba033ac44011" - Image: "ubuntu" - Labels: - com.example.vendor: "Acme" - com.example.license: "GPL" - com.example.version: "1.0" - MacAddress: "" - NetworkDisabled: false - OpenStdin: false - StdinOnce: false - Tty: false - User: "" - Volumes: - /volumes/data: {} - WorkingDir: "" - StopSignal: "SIGTERM" - StopTimeout: 10 - Created: "2015-01-06T15:47:31.485331387Z" - Driver: "devicemapper" - ExecIDs: - - "b35395de42bc8abd327f9dd65d913b9ba28c74d2f0734eeeae84fa1c616a0fca" - - "3fc1232e5cd20c8de182ed81178503dc6437f4e7ef12b52cc5e8de020652f1c4" - HostConfig: - MaximumIOps: 0 - MaximumIOBps: 0 - BlkioWeight: 0 - BlkioWeightDevice: - - {} - BlkioDeviceReadBps: - - {} - BlkioDeviceWriteBps: - - {} - BlkioDeviceReadIOps: - - {} - BlkioDeviceWriteIOps: - - {} - ContainerIDFile: "" - CpusetCpus: "" - CpusetMems: "" - CpuPercent: 80 - CpuShares: 0 - CpuPeriod: 100000 - CpuRealtimePeriod: 1000000 - CpuRealtimeRuntime: 10000 - Devices: [] - DeviceRequests: - - Driver: "nvidia" - Count: -1 - DeviceIDs": ["0", "1", "GPU-fef8089b-4820-abfc-e83e-94318197576e"] - Capabilities: [["gpu", "nvidia", "compute"]] - Options: - property1: "string" - property2: "string" - IpcMode: "" - LxcConf: [] - Memory: 0 - MemorySwap: 0 - MemoryReservation: 0 - KernelMemory: 0 - OomKillDisable: false - OomScoreAdj: 500 - NetworkMode: "bridge" - PidMode: "" - PortBindings: {} - Privileged: false - ReadonlyRootfs: false - PublishAllPorts: false - RestartPolicy: - MaximumRetryCount: 2 - Name: "on-failure" - LogConfig: - Type: "json-file" - Sysctls: - net.ipv4.ip_forward: "1" - Ulimits: - - {} - VolumeDriver: "" - ShmSize: 67108864 - HostnamePath: "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname" - HostsPath: "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts" - LogPath: "/var/lib/docker/containers/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b-json.log" - Id: "ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39" - Image: "04c5d3b7b0656168630d3ba35d8889bd0e9caafcaeb3004d2bfbc47e7c5d35d2" - MountLabel: "" - Name: "/boring_euclid" - NetworkSettings: - Bridge: "" - SandboxID: "" - HairpinMode: false - LinkLocalIPv6Address: "" - LinkLocalIPv6PrefixLen: 0 - SandboxKey: "" - EndpointID: "" - Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - IPAddress: "" - IPPrefixLen: 0 - IPv6Gateway: "" - MacAddress: "" - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "7587b82f0dada3656fda26588aee72630c6fab1536d36e394b2bfbcf898c971d" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.2" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:12:00:02" - Path: "/bin/sh" - ProcessLabel: "" - ResolvConfPath: "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/resolv.conf" - RestartCount: 1 - State: - Error: "" - ExitCode: 9 - FinishedAt: "2015-01-06T15:47:32.080254511Z" - Health: - Status: "healthy" - FailingStreak: 0 - Log: - - Start: "2019-12-22T10:59:05.6385933Z" - End: "2019-12-22T10:59:05.8078452Z" - ExitCode: 0 - Output: "" - OOMKilled: false - Dead: false - Paused: false - Pid: 0 - Restarting: false - Running: true - StartedAt: "2015-01-06T15:47:32.072697474Z" - Status: "running" - Mounts: - - Name: "fac362...80535" - Source: "/data" - Destination: "/data" - Driver: "local" - Mode: "ro,Z" - RW: false - Propagation: "" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "size" - in: "query" - type: "boolean" - default: false - description: "Return the size of container as fields `SizeRw` and `SizeRootFs`" - tags: ["Container"] - /containers/{id}/top: - get: - summary: "List processes running inside a container" - description: | - On Unix systems, this is done by running the `ps` command. This endpoint - is not supported on Windows. - operationId: "ContainerTop" - responses: - 200: - description: "no error" - schema: - type: "object" - title: "ContainerTopResponse" - description: "OK response to ContainerTop operation" - properties: - Titles: - description: "The ps column titles" - type: "array" - items: - type: "string" - Processes: - description: | - Each process running in the container, where each is process - is an array of values corresponding to the titles. - type: "array" - items: - type: "array" - items: - type: "string" - examples: - application/json: - Titles: - - "UID" - - "PID" - - "PPID" - - "C" - - "STIME" - - "TTY" - - "TIME" - - "CMD" - Processes: - - - - "root" - - "13642" - - "882" - - "0" - - "17:03" - - "pts/0" - - "00:00:00" - - "/bin/bash" - - - - "root" - - "13735" - - "13642" - - "0" - - "17:06" - - "pts/0" - - "00:00:00" - - "sleep 10" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "ps_args" - in: "query" - description: "The arguments to pass to `ps`. For example, `aux`" - type: "string" - default: "-ef" - tags: ["Container"] - /containers/{id}/logs: - get: - summary: "Get container logs" - description: | - Get `stdout` and `stderr` logs from a container. - - Note: This endpoint works only for containers with the `json-file` or - `journald` logging driver. - operationId: "ContainerLogs" - responses: - 200: - description: | - logs returned as a stream in response body. - For the stream format, [see the documentation for the attach endpoint](#operation/ContainerAttach). - Note that unlike the attach endpoint, the logs endpoint does not - upgrade the connection and does not set Content-Type. - schema: - type: "string" - format: "binary" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "follow" - in: "query" - description: "Keep connection after returning logs." - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Return logs from `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Return logs from `stderr`" - type: "boolean" - default: false - - name: "since" - in: "query" - description: "Only return logs since this time, as a UNIX timestamp" - type: "integer" - default: 0 - - name: "until" - in: "query" - description: "Only return logs before this time, as a UNIX timestamp" - type: "integer" - default: 0 - - name: "timestamps" - in: "query" - description: "Add timestamps to every log line" - type: "boolean" - default: false - - name: "tail" - in: "query" - description: | - Only return this number of log lines from the end of the logs. - Specify as an integer or `all` to output all log lines. - type: "string" - default: "all" - tags: ["Container"] - /containers/{id}/changes: - get: - summary: "Get changes on a container’s filesystem" - description: | - Returns which files in a container's filesystem have been added, deleted, - or modified. The `Kind` of modification can be one of: - - - `0`: Modified - - `1`: Added - - `2`: Deleted - operationId: "ContainerChanges" - produces: ["application/json"] - responses: - 200: - description: "The list of changes" - schema: - type: "array" - items: - type: "object" - x-go-name: "ContainerChangeResponseItem" - title: "ContainerChangeResponseItem" - description: "change item in response to ContainerChanges operation" - required: [Path, Kind] - properties: - Path: - description: "Path to file that has changed" - type: "string" - x-nullable: false - Kind: - description: "Kind of change" - type: "integer" - format: "uint8" - enum: [0, 1, 2] - x-nullable: false - examples: - application/json: - - Path: "/dev" - Kind: 0 - - Path: "/dev/kmsg" - Kind: 1 - - Path: "/test" - Kind: 1 - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/export: - get: - summary: "Export a container" - description: "Export the contents of a container as a tarball." - operationId: "ContainerExport" - produces: - - "application/octet-stream" - responses: - 200: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/stats: - get: - summary: "Get container stats based on resource usage" - description: | - This endpoint returns a live stream of a container’s resource usage - statistics. - - The `precpu_stats` is the CPU statistic of the *previous* read, and is - used to calculate the CPU usage percentage. It is not an exact copy - of the `cpu_stats` field. - - If either `precpu_stats.online_cpus` or `cpu_stats.online_cpus` is - nil then for compatibility with older daemons the length of the - corresponding `cpu_usage.percpu_usage` array should be used. - - On a cgroup v2 host, the following fields are not set - * `blkio_stats`: all fields other than `io_service_bytes_recursive` - * `cpu_stats`: `cpu_usage.percpu_usage` - * `memory_stats`: `max_usage` and `failcnt` - Also, `memory_stats.stats` fields are incompatible with cgroup v1. - - To calculate the values shown by the `stats` command of the docker cli tool - the following formulas can be used: - * used_memory = `memory_stats.usage - memory_stats.stats.cache` - * available_memory = `memory_stats.limit` - * Memory usage % = `(used_memory / available_memory) * 100.0` - * cpu_delta = `cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage` - * system_cpu_delta = `cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage` - * number_cpus = `lenght(cpu_stats.cpu_usage.percpu_usage)` or `cpu_stats.online_cpus` - * CPU usage % = `(cpu_delta / system_cpu_delta) * number_cpus * 100.0` - operationId: "ContainerStats" - produces: ["application/json"] - responses: - 200: - description: "no error" - schema: - type: "object" - examples: - application/json: - read: "2015-01-08T22:57:31.547920715Z" - pids_stats: - current: 3 - networks: - eth0: - rx_bytes: 5338 - rx_dropped: 0 - rx_errors: 0 - rx_packets: 36 - tx_bytes: 648 - tx_dropped: 0 - tx_errors: 0 - tx_packets: 8 - eth5: - rx_bytes: 4641 - rx_dropped: 0 - rx_errors: 0 - rx_packets: 26 - tx_bytes: 690 - tx_dropped: 0 - tx_errors: 0 - tx_packets: 9 - memory_stats: - stats: - total_pgmajfault: 0 - cache: 0 - mapped_file: 0 - total_inactive_file: 0 - pgpgout: 414 - rss: 6537216 - total_mapped_file: 0 - writeback: 0 - unevictable: 0 - pgpgin: 477 - total_unevictable: 0 - pgmajfault: 0 - total_rss: 6537216 - total_rss_huge: 6291456 - total_writeback: 0 - total_inactive_anon: 0 - rss_huge: 6291456 - hierarchical_memory_limit: 67108864 - total_pgfault: 964 - total_active_file: 0 - active_anon: 6537216 - total_active_anon: 6537216 - total_pgpgout: 414 - total_cache: 0 - inactive_anon: 0 - active_file: 0 - pgfault: 964 - inactive_file: 0 - total_pgpgin: 477 - max_usage: 6651904 - usage: 6537216 - failcnt: 0 - limit: 67108864 - blkio_stats: {} - cpu_stats: - cpu_usage: - percpu_usage: - - 8646879 - - 24472255 - - 36438778 - - 30657443 - usage_in_usermode: 50000000 - total_usage: 100215355 - usage_in_kernelmode: 30000000 - system_cpu_usage: 739306590000000 - online_cpus: 4 - throttling_data: - periods: 0 - throttled_periods: 0 - throttled_time: 0 - precpu_stats: - cpu_usage: - percpu_usage: - - 8646879 - - 24350896 - - 36438778 - - 30657443 - usage_in_usermode: 50000000 - total_usage: 100093996 - usage_in_kernelmode: 30000000 - system_cpu_usage: 9492140000000 - online_cpus: 4 - throttling_data: - periods: 0 - throttled_periods: 0 - throttled_time: 0 - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "stream" - in: "query" - description: | - Stream the output. If false, the stats will be output once and then - it will disconnect. - type: "boolean" - default: true - - name: "one-shot" - in: "query" - description: | - Only get a single stat instead of waiting for 2 cycles. Must be used - with `stream=false`. - type: "boolean" - default: false - tags: ["Container"] - /containers/{id}/resize: - post: - summary: "Resize a container TTY" - description: "Resize the TTY for a container." - operationId: "ContainerResize" - consumes: - - "application/octet-stream" - produces: - - "text/plain" - responses: - 200: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "cannot resize container" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "h" - in: "query" - description: "Height of the TTY session in characters" - type: "integer" - - name: "w" - in: "query" - description: "Width of the TTY session in characters" - type: "integer" - tags: ["Container"] - /containers/{id}/start: - post: - summary: "Start a container" - operationId: "ContainerStart" - responses: - 204: - description: "no error" - 304: - description: "container already started" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "detachKeys" - in: "query" - description: | - Override the key sequence for detaching a container. Format is a - single character `[a-Z]` or `ctrl-` where `` is one - of: `a-z`, `@`, `^`, `[`, `,` or `_`. - type: "string" - tags: ["Container"] - /containers/{id}/stop: - post: - summary: "Stop a container" - operationId: "ContainerStop" - responses: - 204: - description: "no error" - 304: - description: "container already stopped" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "t" - in: "query" - description: "Number of seconds to wait before killing the container" - type: "integer" - tags: ["Container"] - /containers/{id}/restart: - post: - summary: "Restart a container" - operationId: "ContainerRestart" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "t" - in: "query" - description: "Number of seconds to wait before killing the container" - type: "integer" - tags: ["Container"] - /containers/{id}/kill: - post: - summary: "Kill a container" - description: | - Send a POSIX signal to a container, defaulting to killing to the - container. - operationId: "ContainerKill" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "container is not running" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "Container d37cde0fe4ad63c3a7252023b2f9800282894247d145cb5933ddf6e52cc03a28 is not running" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "signal" - in: "query" - description: "Signal to send to the container as an integer or string (e.g. `SIGINT`)" - type: "string" - default: "SIGKILL" - tags: ["Container"] - /containers/{id}/update: - post: - summary: "Update a container" - description: | - Change various configuration options of a container without having to - recreate it. - operationId: "ContainerUpdate" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 200: - description: "The container has been updated." - schema: - type: "object" - title: "ContainerUpdateResponse" - description: "OK response to ContainerUpdate operation" - properties: - Warnings: - type: "array" - items: - type: "string" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "update" - in: "body" - required: true - schema: - allOf: - - $ref: "#/definitions/Resources" - - type: "object" - properties: - RestartPolicy: - $ref: "#/definitions/RestartPolicy" - example: - BlkioWeight: 300 - CpuShares: 512 - CpuPeriod: 100000 - CpuQuota: 50000 - CpuRealtimePeriod: 1000000 - CpuRealtimeRuntime: 10000 - CpusetCpus: "0,1" - CpusetMems: "0" - Memory: 314572800 - MemorySwap: 514288000 - MemoryReservation: 209715200 - KernelMemory: 52428800 - RestartPolicy: - MaximumRetryCount: 4 - Name: "on-failure" - tags: ["Container"] - /containers/{id}/rename: - post: - summary: "Rename a container" - operationId: "ContainerRename" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "name already in use" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "name" - in: "query" - required: true - description: "New name for the container" - type: "string" - tags: ["Container"] - /containers/{id}/pause: - post: - summary: "Pause a container" - description: | - Use the freezer cgroup to suspend all processes in a container. - - Traditionally, when suspending a process the `SIGSTOP` signal is used, - which is observable by the process being suspended. With the freezer - cgroup the process is unaware, and unable to capture, that it is being - suspended, and subsequently resumed. - operationId: "ContainerPause" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/unpause: - post: - summary: "Unpause a container" - description: "Resume a container which has been paused." - operationId: "ContainerUnpause" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/attach: - post: - summary: "Attach to a container" - description: | - Attach to a container to read its output or send it input. You can attach - to the same container multiple times and you can reattach to containers - that have been detached. - - Either the `stream` or `logs` parameter must be `true` for this endpoint - to do anything. - - See the [documentation for the `docker attach` command](https://docs.docker.com/engine/reference/commandline/attach/) - for more details. - - ### Hijacking - - This endpoint hijacks the HTTP connection to transport `stdin`, `stdout`, - and `stderr` on the same socket. - - This is the response from the daemon for an attach request: - - ``` - HTTP/1.1 200 OK - Content-Type: application/vnd.docker.raw-stream - - [STREAM] - ``` - - After the headers and two new lines, the TCP connection can now be used - for raw, bidirectional communication between the client and server. - - To hint potential proxies about connection hijacking, the Docker client - can also optionally send connection upgrade headers. - - For example, the client sends this request to upgrade the connection: - - ``` - POST /containers/16253994b7c4/attach?stream=1&stdout=1 HTTP/1.1 - Upgrade: tcp - Connection: Upgrade - ``` - - The Docker daemon will respond with a `101 UPGRADED` response, and will - similarly follow with the raw stream: - - ``` - HTTP/1.1 101 UPGRADED - Content-Type: application/vnd.docker.raw-stream - Connection: Upgrade - Upgrade: tcp - - [STREAM] - ``` - - ### Stream format - - When the TTY setting is disabled in [`POST /containers/create`](#operation/ContainerCreate), - the stream over the hijacked connected is multiplexed to separate out - `stdout` and `stderr`. The stream consists of a series of frames, each - containing a header and a payload. - - The header contains the information which the stream writes (`stdout` or - `stderr`). It also contains the size of the associated frame encoded in - the last four bytes (`uint32`). - - It is encoded on the first eight bytes like this: - - ```go - header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} - ``` - - `STREAM_TYPE` can be: - - - 0: `stdin` (is written on `stdout`) - - 1: `stdout` - - 2: `stderr` - - `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of the `uint32` size - encoded as big endian. - - Following the header is the payload, which is the specified number of - bytes of `STREAM_TYPE`. - - The simplest way to implement this protocol is the following: - - 1. Read 8 bytes. - 2. Choose `stdout` or `stderr` depending on the first byte. - 3. Extract the frame size from the last four bytes. - 4. Read the extracted size and output it on the correct output. - 5. Goto 1. - - ### Stream format when using a TTY - - When the TTY setting is enabled in [`POST /containers/create`](#operation/ContainerCreate), - the stream is not multiplexed. The data exchanged over the hijacked - connection is simply the raw data from the process PTY and client's - `stdin`. - - operationId: "ContainerAttach" - produces: - - "application/vnd.docker.raw-stream" - responses: - 101: - description: "no error, hints proxy about hijacking" - 200: - description: "no error, no upgrade header found" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "detachKeys" - in: "query" - description: | - Override the key sequence for detaching a container.Format is a single - character `[a-Z]` or `ctrl-` where `` is one of: `a-z`, - `@`, `^`, `[`, `,` or `_`. - type: "string" - - name: "logs" - in: "query" - description: | - Replay previous logs from the container. - - This is useful for attaching to a container that has started and you - want to output everything since the container started. - - If `stream` is also enabled, once all the previous output has been - returned, it will seamlessly transition into streaming current - output. - type: "boolean" - default: false - - name: "stream" - in: "query" - description: | - Stream attached streams from the time the request was made onwards. - type: "boolean" - default: false - - name: "stdin" - in: "query" - description: "Attach to `stdin`" - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Attach to `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Attach to `stderr`" - type: "boolean" - default: false - tags: ["Container"] - /containers/{id}/attach/ws: - get: - summary: "Attach to a container via a websocket" - operationId: "ContainerAttachWebsocket" - responses: - 101: - description: "no error, hints proxy about hijacking" - 200: - description: "no error, no upgrade header found" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "detachKeys" - in: "query" - description: | - Override the key sequence for detaching a container.Format is a single - character `[a-Z]` or `ctrl-` where `` is one of: `a-z`, - `@`, `^`, `[`, `,`, or `_`. - type: "string" - - name: "logs" - in: "query" - description: "Return logs" - type: "boolean" - default: false - - name: "stream" - in: "query" - description: "Return stream" - type: "boolean" - default: false - - name: "stdin" - in: "query" - description: "Attach to `stdin`" - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Attach to `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Attach to `stderr`" - type: "boolean" - default: false - tags: ["Container"] - /containers/{id}/wait: - post: - summary: "Wait for a container" - description: "Block until a container stops, then returns the exit code." - operationId: "ContainerWait" - produces: ["application/json"] - responses: - 200: - description: "The container has exit." - schema: - type: "object" - title: "ContainerWaitResponse" - description: "OK response to ContainerWait operation" - required: [StatusCode] - properties: - StatusCode: - description: "Exit code of the container" - type: "integer" - x-nullable: false - Error: - description: "container waiting error, if any" - type: "object" - properties: - Message: - description: "Details of an error" - type: "string" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "condition" - in: "query" - description: | - Wait until a container state reaches the given condition, either - 'not-running' (default), 'next-exit', or 'removed'. - type: "string" - default: "not-running" - tags: ["Container"] - /containers/{id}: - delete: - summary: "Remove a container" - operationId: "ContainerDelete" - responses: - 204: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "conflict" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: | - You cannot remove a running container: c2ada9df5af8. Stop the - container before attempting removal or force remove - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "v" - in: "query" - description: "Remove anonymous volumes associated with the container." - type: "boolean" - default: false - - name: "force" - in: "query" - description: "If the container is running, kill it before removing it." - type: "boolean" - default: false - - name: "link" - in: "query" - description: "Remove the specified link associated with the container." - type: "boolean" - default: false - tags: ["Container"] - /containers/{id}/archive: - head: - summary: "Get information about files in a container" - description: | - A response header `X-Docker-Container-Path-Stat` is returned, containing - a base64 - encoded JSON object with some filesystem header information - about the path. - operationId: "ContainerArchiveInfo" - responses: - 200: - description: "no error" - headers: - X-Docker-Container-Path-Stat: - type: "string" - description: | - A base64 - encoded JSON object with some filesystem header - information about the path - 400: - description: "Bad parameter" - schema: - allOf: - - $ref: "#/definitions/ErrorResponse" - - type: "object" - properties: - message: - description: | - The error message. Either "must specify path parameter" - (path cannot be empty) or "not a directory" (path was - asserted to be a directory but exists as a file). - type: "string" - x-nullable: false - 404: - description: "Container or path does not exist" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "path" - in: "query" - required: true - description: "Resource in the container’s filesystem to archive." - type: "string" - tags: ["Container"] - get: - summary: "Get an archive of a filesystem resource in a container" - description: "Get a tar archive of a resource in the filesystem of container id." - operationId: "ContainerArchive" - produces: ["application/x-tar"] - responses: - 200: - description: "no error" - 400: - description: "Bad parameter" - schema: - allOf: - - $ref: "#/definitions/ErrorResponse" - - type: "object" - properties: - message: - description: | - The error message. Either "must specify path parameter" - (path cannot be empty) or "not a directory" (path was - asserted to be a directory but exists as a file). - type: "string" - x-nullable: false - 404: - description: "Container or path does not exist" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "path" - in: "query" - required: true - description: "Resource in the container’s filesystem to archive." - type: "string" - tags: ["Container"] - put: - summary: "Extract an archive of files or folders to a directory in a container" - description: "Upload a tar archive to be extracted to a path in the filesystem of container id." - operationId: "PutContainerArchive" - consumes: ["application/x-tar", "application/octet-stream"] - responses: - 200: - description: "The content was extracted successfully" - 400: - description: "Bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 403: - description: "Permission denied, the volume or container rootfs is marked as read-only." - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "No such container or path does not exist inside the container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "path" - in: "query" - required: true - description: "Path to a directory in the container to extract the archive’s contents into. " - type: "string" - - name: "noOverwriteDirNonDir" - in: "query" - description: | - If `1`, `true`, or `True` then it will be an error if unpacking the - given content would cause an existing directory to be replaced with - a non-directory and vice versa. - type: "string" - - name: "copyUIDGID" - in: "query" - description: | - If `1`, `true`, then it will copy UID/GID maps to the dest file or - dir - type: "string" - - name: "inputStream" - in: "body" - required: true - description: | - The input stream must be a tar archive compressed with one of the - following algorithms: `identity` (no compression), `gzip`, `bzip2`, - or `xz`. - schema: - type: "string" - format: "binary" - tags: ["Container"] - /containers/prune: - post: - summary: "Delete stopped containers" - produces: - - "application/json" - operationId: "ContainerPrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `until=` Prune containers created before this timestamp. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon machine’s time. - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune containers with (or without, in case `label!=...` is used) the specified labels. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - title: "ContainerPruneResponse" - properties: - ContainersDeleted: - description: "Container IDs that were deleted" - type: "array" - items: - type: "string" - SpaceReclaimed: - description: "Disk space reclaimed in bytes" - type: "integer" - format: "int64" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Container"] - /images/json: - get: - summary: "List Images" - description: "Returns a list of images on the server. Note that it uses a different, smaller representation of an image than inspecting a single image." - operationId: "ImageList" - produces: - - "application/json" - responses: - 200: - description: "Summary image data for the images matching the query" - schema: - type: "array" - items: - $ref: "#/definitions/ImageSummary" - examples: - application/json: - - Id: "sha256:e216a057b1cb1efc11f8a268f37ef62083e70b1b38323ba252e25ac88904a7e8" - ParentId: "" - RepoTags: - - "ubuntu:12.04" - - "ubuntu:precise" - RepoDigests: - - "ubuntu@sha256:992069aee4016783df6345315302fa59681aae51a8eeb2f889dea59290f21787" - Created: 1474925151 - Size: 103579269 - VirtualSize: 103579269 - SharedSize: 0 - Labels: {} - Containers: 2 - - Id: "sha256:3e314f95dcace0f5e4fd37b10862fe8398e3c60ed36600bc0ca5fda78b087175" - ParentId: "" - RepoTags: - - "ubuntu:12.10" - - "ubuntu:quantal" - RepoDigests: - - "ubuntu@sha256:002fba3e3255af10be97ea26e476692a7ebed0bb074a9ab960b2e7a1526b15d7" - - "ubuntu@sha256:68ea0200f0b90df725d99d823905b04cf844f6039ef60c60bf3e019915017bd3" - Created: 1403128455 - Size: 172064416 - VirtualSize: 172064416 - SharedSize: 0 - Labels: {} - Containers: 5 - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "all" - in: "query" - description: "Show all images. Only images from a final layer (no children) are shown by default." - type: "boolean" - default: false - - name: "filters" - in: "query" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the images list. - - Available filters: - - - `before`=(`[:]`, `` or ``) - - `dangling=true` - - `label=key` or `label="key=value"` of an image label - - `reference`=(`[:]`) - - `since`=(`[:]`, `` or ``) - type: "string" - - name: "digests" - in: "query" - description: "Show digest information as a `RepoDigests` field on each image." - type: "boolean" - default: false - tags: ["Image"] - /build: - post: - summary: "Build an image" - description: | - Build an image from a tar archive with a `Dockerfile` in it. - - The `Dockerfile` specifies how the image is built from the tar archive. It is typically in the archive's root, but can be at a different path or have a different name by specifying the `dockerfile` parameter. [See the `Dockerfile` reference for more information](https://docs.docker.com/engine/reference/builder/). - - The Docker daemon performs a preliminary validation of the `Dockerfile` before starting the build, and returns an error if the syntax is incorrect. After that, each instruction is run one-by-one until the ID of the new image is output. - - The build is canceled if the client drops the connection by quitting or being killed. - operationId: "ImageBuild" - consumes: - - "application/octet-stream" - produces: - - "application/json" - parameters: - - name: "inputStream" - in: "body" - description: "A tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz." - schema: - type: "string" - format: "binary" - - name: "dockerfile" - in: "query" - description: "Path within the build context to the `Dockerfile`. This is ignored if `remote` is specified and points to an external `Dockerfile`." - type: "string" - default: "Dockerfile" - - name: "t" - in: "query" - description: "A name and optional tag to apply to the image in the `name:tag` format. If you omit the tag the default `latest` value is assumed. You can provide several `t` parameters." - type: "string" - - name: "extrahosts" - in: "query" - description: "Extra hosts to add to /etc/hosts" - type: "string" - - name: "remote" - in: "query" - description: "A Git repository URI or HTTP/HTTPS context URI. If the URI points to a single text file, the file’s contents are placed into a file called `Dockerfile` and the image is built from that file. If the URI points to a tarball, the file is downloaded by the daemon and the contents therein used as the context for the build. If the URI points to a tarball and the `dockerfile` parameter is also specified, there must be a file with the corresponding path inside the tarball." - type: "string" - - name: "q" - in: "query" - description: "Suppress verbose build output." - type: "boolean" - default: false - - name: "nocache" - in: "query" - description: "Do not use the cache when building the image." - type: "boolean" - default: false - - name: "cachefrom" - in: "query" - description: "JSON array of images used for build cache resolution." - type: "string" - - name: "pull" - in: "query" - description: "Attempt to pull the image even if an older image exists locally." - type: "string" - - name: "rm" - in: "query" - description: "Remove intermediate containers after a successful build." - type: "boolean" - default: true - - name: "forcerm" - in: "query" - description: "Always remove intermediate containers, even upon failure." - type: "boolean" - default: false - - name: "memory" - in: "query" - description: "Set memory limit for build." - type: "integer" - - name: "memswap" - in: "query" - description: "Total memory (memory + swap). Set as `-1` to disable swap." - type: "integer" - - name: "cpushares" - in: "query" - description: "CPU shares (relative weight)." - type: "integer" - - name: "cpusetcpus" - in: "query" - description: "CPUs in which to allow execution (e.g., `0-3`, `0,1`)." - type: "string" - - name: "cpuperiod" - in: "query" - description: "The length of a CPU period in microseconds." - type: "integer" - - name: "cpuquota" - in: "query" - description: "Microseconds of CPU time that the container can get in a CPU period." - type: "integer" - - name: "buildargs" - in: "query" - description: > - JSON map of string pairs for build-time variables. Users pass these values at build-time. Docker - uses the buildargs as the environment context for commands run via the `Dockerfile` RUN - instruction, or for variable expansion in other `Dockerfile` instructions. This is not meant for - passing secret values. - - - For example, the build arg `FOO=bar` would become `{"FOO":"bar"}` in JSON. This would result in the - query parameter `buildargs={"FOO":"bar"}`. Note that `{"FOO":"bar"}` should be URI component encoded. - - - [Read more about the buildargs instruction.](https://docs.docker.com/engine/reference/builder/#arg) - type: "string" - - name: "shmsize" - in: "query" - description: "Size of `/dev/shm` in bytes. The size must be greater than 0. If omitted the system uses 64MB." - type: "integer" - - name: "squash" - in: "query" - description: "Squash the resulting images layers into a single layer. *(Experimental release only.)*" - type: "boolean" - - name: "labels" - in: "query" - description: "Arbitrary key/value labels to set on the image, as a JSON map of string pairs." - type: "string" - - name: "networkmode" - in: "query" - description: | - Sets the networking mode for the run commands during build. Supported - standard values are: `bridge`, `host`, `none`, and `container:`. - Any other value is taken as a custom network's name or ID to which this - container should connect to. - type: "string" - - name: "Content-type" - in: "header" - type: "string" - enum: - - "application/x-tar" - default: "application/x-tar" - - name: "X-Registry-Config" - in: "header" - description: | - This is a base64-encoded JSON object with auth configurations for multiple registries that a build may refer to. - - The key is a registry URL, and the value is an auth configuration object, [as described in the authentication section](#section/Authentication). For example: - - ``` - { - "docker.example.com": { - "username": "janedoe", - "password": "hunter2" - }, - "https://index.docker.io/v1/": { - "username": "mobydock", - "password": "conta1n3rize14" - } - } - ``` - - Only the registry domain name (and port if not the default 443) are required. However, for legacy reasons, the Docker Hub registry must be specified with both a `https://` prefix and a `/v1/` suffix even though Docker will prefer to use the v2 registry API. - type: "string" - - name: "platform" - in: "query" - description: "Platform in the format os[/arch[/variant]]" - type: "string" - default: "" - - name: "target" - in: "query" - description: "Target build stage" - type: "string" - default: "" - - name: "outputs" - in: "query" - description: "BuildKit output configuration" - type: "string" - default: "" - responses: - 200: - description: "no error" - 400: - description: "Bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Image"] - /build/prune: - post: - summary: "Delete builder cache" - produces: - - "application/json" - operationId: "BuildPrune" - parameters: - - name: "keep-storage" - in: "query" - description: "Amount of disk space in bytes to keep for cache" - type: "integer" - format: "int64" - - name: "all" - in: "query" - type: "boolean" - description: "Remove all types of build cache" - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the list of build cache objects. - - Available filters: - - - `until=`: duration relative to daemon's time, during which build cache was not used, in Go's duration format (e.g., '24h') - - `id=` - - `parent=` - - `type=` - - `description=` - - `inuse` - - `shared` - - `private` - responses: - 200: - description: "No error" - schema: - type: "object" - title: "BuildPruneResponse" - properties: - CachesDeleted: - type: "array" - items: - description: "ID of build cache object" - type: "string" - SpaceReclaimed: - description: "Disk space reclaimed in bytes" - type: "integer" - format: "int64" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Image"] - /images/create: - post: - summary: "Create an image" - description: "Create an image by either pulling it from a registry or importing it." - operationId: "ImageCreate" - consumes: - - "text/plain" - - "application/octet-stream" - produces: - - "application/json" - responses: - 200: - description: "no error" - 404: - description: "repository does not exist or no read access" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "fromImage" - in: "query" - description: "Name of the image to pull. The name may include a tag or digest. This parameter may only be used when pulling an image. The pull is cancelled if the HTTP connection is closed." - type: "string" - - name: "fromSrc" - in: "query" - description: "Source to import. The value may be a URL from which the image can be retrieved or `-` to read the image from the request body. This parameter may only be used when importing an image." - type: "string" - - name: "repo" - in: "query" - description: "Repository name given to an image when it is imported. The repo may include a tag. This parameter may only be used when importing an image." - type: "string" - - name: "tag" - in: "query" - description: "Tag or digest. If empty when pulling an image, this causes all tags for the given image to be pulled." - type: "string" - - name: "message" - in: "query" - description: "Set commit message for imported image." - type: "string" - - name: "inputImage" - in: "body" - description: "Image content if the value `-` has been specified in fromSrc query parameter" - schema: - type: "string" - required: false - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - - name: "platform" - in: "query" - description: "Platform in the format os[/arch[/variant]]" - type: "string" - default: "" - tags: ["Image"] - /images/{name}/json: - get: - summary: "Inspect an image" - description: "Return low-level information about an image." - operationId: "ImageInspect" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - $ref: "#/definitions/Image" - examples: - application/json: - Id: "sha256:85f05633ddc1c50679be2b16a0479ab6f7637f8884e0cfe0f4d20e1ebb3d6e7c" - Container: "cb91e48a60d01f1e27028b4fc6819f4f290b3cf12496c8176ec714d0d390984a" - Comment: "" - Os: "linux" - Architecture: "amd64" - Parent: "sha256:91e54dfb11794fad694460162bf0cb0a4fa710cfa3f60979c177d920813e267c" - ContainerConfig: - Tty: false - Hostname: "e611e15f9c9d" - Domainname: "" - AttachStdout: false - PublishService: "" - AttachStdin: false - OpenStdin: false - StdinOnce: false - NetworkDisabled: false - OnBuild: [] - Image: "91e54dfb11794fad694460162bf0cb0a4fa710cfa3f60979c177d920813e267c" - User: "" - WorkingDir: "" - MacAddress: "" - AttachStderr: false - Labels: - com.example.license: "GPL" - com.example.version: "1.0" - com.example.vendor: "Acme" - Env: - - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - Cmd: - - "/bin/sh" - - "-c" - - "#(nop) LABEL com.example.vendor=Acme com.example.license=GPL com.example.version=1.0" - DockerVersion: "1.9.0-dev" - VirtualSize: 188359297 - Size: 0 - Author: "" - Created: "2015-09-10T08:30:53.26995814Z" - GraphDriver: - Name: "aufs" - Data: {} - RepoDigests: - - "localhost:5000/test/busybox/example@sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf" - RepoTags: - - "example:1.0" - - "example:latest" - - "example:stable" - Config: - Image: "91e54dfb11794fad694460162bf0cb0a4fa710cfa3f60979c177d920813e267c" - NetworkDisabled: false - OnBuild: [] - StdinOnce: false - PublishService: "" - AttachStdin: false - OpenStdin: false - Domainname: "" - AttachStdout: false - Tty: false - Hostname: "e611e15f9c9d" - Cmd: - - "/bin/bash" - Env: - - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - Labels: - com.example.vendor: "Acme" - com.example.version: "1.0" - com.example.license: "GPL" - MacAddress: "" - AttachStderr: false - WorkingDir: "" - User: "" - RootFS: - Type: "layers" - Layers: - - "sha256:1834950e52ce4d5a88a1bbd131c537f4d0e56d10ff0dd69e66be3b7dfa9df7e6" - - "sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such image: someimage (tag: latest)" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or id" - type: "string" - required: true - tags: ["Image"] - /images/{name}/history: - get: - summary: "Get the history of an image" - description: "Return parent layers of an image." - operationId: "ImageHistory" - produces: ["application/json"] - responses: - 200: - description: "List of image layers" - schema: - type: "array" - items: - type: "object" - x-go-name: HistoryResponseItem - title: "HistoryResponseItem" - description: "individual image layer information in response to ImageHistory operation" - required: [Id, Created, CreatedBy, Tags, Size, Comment] - properties: - Id: - type: "string" - x-nullable: false - Created: - type: "integer" - format: "int64" - x-nullable: false - CreatedBy: - type: "string" - x-nullable: false - Tags: - type: "array" - items: - type: "string" - Size: - type: "integer" - format: "int64" - x-nullable: false - Comment: - type: "string" - x-nullable: false - examples: - application/json: - - Id: "3db9c44f45209632d6050b35958829c3a2aa256d81b9a7be45b362ff85c54710" - Created: 1398108230 - CreatedBy: "/bin/sh -c #(nop) ADD file:eb15dbd63394e063b805a3c32ca7bf0266ef64676d5a6fab4801f2e81e2a5148 in /" - Tags: - - "ubuntu:lucid" - - "ubuntu:10.04" - Size: 182964289 - Comment: "" - - Id: "6cfa4d1f33fb861d4d114f43b25abd0ac737509268065cdfd69d544a59c85ab8" - Created: 1398108222 - CreatedBy: "/bin/sh -c #(nop) MAINTAINER Tianon Gravi - mkimage-debootstrap.sh -i iproute,iputils-ping,ubuntu-minimal -t lucid.tar.xz lucid http://archive.ubuntu.com/ubuntu/" - Tags: [] - Size: 0 - Comment: "" - - Id: "511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158" - Created: 1371157430 - CreatedBy: "" - Tags: - - "scratch12:latest" - - "scratch:latest" - Size: 0 - Comment: "Imported from -" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID" - type: "string" - required: true - tags: ["Image"] - /images/{name}/push: - post: - summary: "Push an image" - description: | - Push an image to a registry. - - If you wish to push an image on to a private registry, that image must - already have a tag which references the registry. For example, - `registry.example.com/myimage:latest`. - - The push is cancelled if the HTTP connection is closed. - operationId: "ImagePush" - consumes: - - "application/octet-stream" - responses: - 200: - description: "No error" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID." - type: "string" - required: true - - name: "tag" - in: "query" - description: "The tag to associate with the image on the registry." - type: "string" - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - required: true - tags: ["Image"] - /images/{name}/tag: - post: - summary: "Tag an image" - description: "Tag an image so that it becomes part of a repository." - operationId: "ImageTag" - responses: - 201: - description: "No error" - 400: - description: "Bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Conflict" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID to tag." - type: "string" - required: true - - name: "repo" - in: "query" - description: "The repository to tag in. For example, `someuser/someimage`." - type: "string" - - name: "tag" - in: "query" - description: "The name of the new tag." - type: "string" - tags: ["Image"] - /images/{name}: - delete: - summary: "Remove an image" - description: | - Remove an image, along with any untagged parent images that were - referenced by that image. - - Images can't be removed if they have descendant images, are being - used by a running container or are being used by a build. - operationId: "ImageDelete" - produces: ["application/json"] - responses: - 200: - description: "The image was deleted successfully" - schema: - type: "array" - items: - $ref: "#/definitions/ImageDeleteResponseItem" - examples: - application/json: - - Untagged: "3e2f21a89f" - - Deleted: "3e2f21a89f" - - Deleted: "53b4f83ac9" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Conflict" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID" - type: "string" - required: true - - name: "force" - in: "query" - description: "Remove the image even if it is being used by stopped containers or has other tags" - type: "boolean" - default: false - - name: "noprune" - in: "query" - description: "Do not delete untagged parent images" - type: "boolean" - default: false - tags: ["Image"] - /images/search: - get: - summary: "Search images" - description: "Search for an image on Docker Hub." - operationId: "ImageSearch" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - type: "array" - items: - type: "object" - title: "ImageSearchResponseItem" - properties: - description: - type: "string" - is_official: - type: "boolean" - is_automated: - type: "boolean" - name: - type: "string" - star_count: - type: "integer" - examples: - application/json: - - description: "" - is_official: false - is_automated: false - name: "wma55/u1210sshd" - star_count: 0 - - description: "" - is_official: false - is_automated: false - name: "jdswinbank/sshd" - star_count: 0 - - description: "" - is_official: false - is_automated: false - name: "vgauthier/sshd" - star_count: 0 - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "term" - in: "query" - description: "Term to search" - type: "string" - required: true - - name: "limit" - in: "query" - description: "Maximum number of results to return" - type: "integer" - - name: "filters" - in: "query" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to process on the images list. Available filters: - - - `is-automated=(true|false)` - - `is-official=(true|false)` - - `stars=` Matches images that has at least 'number' stars. - type: "string" - tags: ["Image"] - /images/prune: - post: - summary: "Delete unused images" - produces: - - "application/json" - operationId: "ImagePrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). Available filters: - - - `dangling=` When set to `true` (or `1`), prune only - unused *and* untagged images. When set to `false` - (or `0`), all unused images are pruned. - - `until=` Prune images created before this timestamp. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon machine’s time. - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune images with (or without, in case `label!=...` is used) the specified labels. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - title: "ImagePruneResponse" - properties: - ImagesDeleted: - description: "Images that were deleted" - type: "array" - items: - $ref: "#/definitions/ImageDeleteResponseItem" - SpaceReclaimed: - description: "Disk space reclaimed in bytes" - type: "integer" - format: "int64" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Image"] - /auth: - post: - summary: "Check auth configuration" - description: | - Validate credentials for a registry and, if available, get an identity - token for accessing the registry without password. - operationId: "SystemAuth" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 200: - description: "An identity token was generated successfully." - schema: - type: "object" - title: "SystemAuthResponse" - required: [Status] - properties: - Status: - description: "The status of the authentication" - type: "string" - x-nullable: false - IdentityToken: - description: "An opaque token used to authenticate a user after a successful login" - type: "string" - x-nullable: false - examples: - application/json: - Status: "Login Succeeded" - IdentityToken: "9cbaf023786cd7..." - 204: - description: "No error" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "authConfig" - in: "body" - description: "Authentication to check" - schema: - $ref: "#/definitions/AuthConfig" - tags: ["System"] - /info: - get: - summary: "Get system information" - operationId: "SystemInfo" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - $ref: "#/definitions/SystemInfo" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["System"] - /version: - get: - summary: "Get version" - description: "Returns the version of Docker that is running and various information about the system that Docker is running on." - operationId: "SystemVersion" - produces: ["application/json"] - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/SystemVersion" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["System"] - /_ping: - get: - summary: "Ping" - description: "This is a dummy endpoint you can use to test if the server is accessible." - operationId: "SystemPing" - produces: ["text/plain"] - responses: - 200: - description: "no error" - schema: - type: "string" - example: "OK" - headers: - API-Version: - type: "string" - description: "Max API Version the server supports" - Builder-Version: - type: "string" - description: "Default version of docker image builder" - Docker-Experimental: - type: "boolean" - description: "If the server is running with experimental mode enabled" - Cache-Control: - type: "string" - default: "no-cache, no-store, must-revalidate" - Pragma: - type: "string" - default: "no-cache" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - headers: - Cache-Control: - type: "string" - default: "no-cache, no-store, must-revalidate" - Pragma: - type: "string" - default: "no-cache" - tags: ["System"] - head: - summary: "Ping" - description: "This is a dummy endpoint you can use to test if the server is accessible." - operationId: "SystemPingHead" - produces: ["text/plain"] - responses: - 200: - description: "no error" - schema: - type: "string" - example: "(empty)" - headers: - API-Version: - type: "string" - description: "Max API Version the server supports" - Builder-Version: - type: "string" - description: "Default version of docker image builder" - Docker-Experimental: - type: "boolean" - description: "If the server is running with experimental mode enabled" - Cache-Control: - type: "string" - default: "no-cache, no-store, must-revalidate" - Pragma: - type: "string" - default: "no-cache" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["System"] - /commit: - post: - summary: "Create a new image from a container" - operationId: "ImageCommit" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - $ref: "#/definitions/IdResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "containerConfig" - in: "body" - description: "The container configuration" - schema: - $ref: "#/definitions/ContainerConfig" - - name: "container" - in: "query" - description: "The ID or name of the container to commit" - type: "string" - - name: "repo" - in: "query" - description: "Repository name for the created image" - type: "string" - - name: "tag" - in: "query" - description: "Tag name for the create image" - type: "string" - - name: "comment" - in: "query" - description: "Commit message" - type: "string" - - name: "author" - in: "query" - description: "Author of the image (e.g., `John Hannibal Smith `)" - type: "string" - - name: "pause" - in: "query" - description: "Whether to pause the container before committing" - type: "boolean" - default: true - - name: "changes" - in: "query" - description: "`Dockerfile` instructions to apply while committing" - type: "string" - tags: ["Image"] - /events: - get: - summary: "Monitor events" - description: | - Stream real-time events from the server. - - Various objects within Docker report events when something happens to them. - - Containers report these events: `attach`, `commit`, `copy`, `create`, `destroy`, `detach`, `die`, `exec_create`, `exec_detach`, `exec_start`, `exec_die`, `export`, `health_status`, `kill`, `oom`, `pause`, `rename`, `resize`, `restart`, `start`, `stop`, `top`, `unpause`, `update`, and `prune` - - Images report these events: `delete`, `import`, `load`, `pull`, `push`, `save`, `tag`, `untag`, and `prune` - - Volumes report these events: `create`, `mount`, `unmount`, `destroy`, and `prune` - - Networks report these events: `create`, `connect`, `disconnect`, `destroy`, `update`, `remove`, and `prune` - - The Docker daemon reports these events: `reload` - - Services report these events: `create`, `update`, and `remove` - - Nodes report these events: `create`, `update`, and `remove` - - Secrets report these events: `create`, `update`, and `remove` - - Configs report these events: `create`, `update`, and `remove` - - The Builder reports `prune` events - - operationId: "SystemEvents" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "object" - title: "SystemEventsResponse" - properties: - Type: - description: "The type of object emitting the event" - type: "string" - Action: - description: "The type of event" - type: "string" - Actor: - type: "object" - properties: - ID: - description: "The ID of the object emitting the event" - type: "string" - Attributes: - description: "Various key/value attributes of the object, depending on its type" - type: "object" - additionalProperties: - type: "string" - time: - description: "Timestamp of event" - type: "integer" - timeNano: - description: "Timestamp of event, with nanosecond accuracy" - type: "integer" - format: "int64" - examples: - application/json: - Type: "container" - Action: "create" - Actor: - ID: "ede54ee1afda366ab42f824e8a5ffd195155d853ceaec74a927f249ea270c743" - Attributes: - com.example.some-label: "some-label-value" - image: "alpine" - name: "my-container" - time: 1461943101 - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "since" - in: "query" - description: "Show events created since this timestamp then stream new events." - type: "string" - - name: "until" - in: "query" - description: "Show events created until this timestamp then stop streaming." - type: "string" - - name: "filters" - in: "query" - description: | - A JSON encoded value of filters (a `map[string][]string`) to process on the event list. Available filters: - - - `config=` config name or ID - - `container=` container name or ID - - `daemon=` daemon name or ID - - `event=` event type - - `image=` image name or ID - - `label=` image or container label - - `network=` network name or ID - - `node=` node ID - - `plugin`= plugin name or ID - - `scope`= local or swarm - - `secret=` secret name or ID - - `service=` service name or ID - - `type=` object to filter by, one of `container`, `image`, `volume`, `network`, `daemon`, `plugin`, `node`, `service`, `secret` or `config` - - `volume=` volume name - type: "string" - tags: ["System"] - /system/df: - get: - summary: "Get data usage information" - operationId: "SystemDataUsage" - responses: - 200: - description: "no error" - schema: - type: "object" - title: "SystemDataUsageResponse" - properties: - LayersSize: - type: "integer" - format: "int64" - Images: - type: "array" - items: - $ref: "#/definitions/ImageSummary" - Containers: - type: "array" - items: - $ref: "#/definitions/ContainerSummary" - Volumes: - type: "array" - items: - $ref: "#/definitions/Volume" - BuildCache: - type: "array" - items: - $ref: "#/definitions/BuildCache" - example: - LayersSize: 1092588 - Images: - - - Id: "sha256:2b8fd9751c4c0f5dd266fcae00707e67a2545ef34f9a29354585f93dac906749" - ParentId: "" - RepoTags: - - "busybox:latest" - RepoDigests: - - "busybox@sha256:a59906e33509d14c036c8678d687bd4eec81ed7c4b8ce907b888c607f6a1e0e6" - Created: 1466724217 - Size: 1092588 - SharedSize: 0 - VirtualSize: 1092588 - Labels: {} - Containers: 1 - Containers: - - - Id: "e575172ed11dc01bfce087fb27bee502db149e1a0fad7c296ad300bbff178148" - Names: - - "/top" - Image: "busybox" - ImageID: "sha256:2b8fd9751c4c0f5dd266fcae00707e67a2545ef34f9a29354585f93dac906749" - Command: "top" - Created: 1472592424 - Ports: [] - SizeRootFs: 1092588 - Labels: {} - State: "exited" - Status: "Exited (0) 56 minutes ago" - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - IPAMConfig: null - Links: null - Aliases: null - NetworkID: "d687bc59335f0e5c9ee8193e5612e8aee000c8c62ea170cfb99c098f95899d92" - EndpointID: "8ed5115aeaad9abb174f68dcf135b49f11daf597678315231a32ca28441dec6a" - Gateway: "172.18.0.1" - IPAddress: "172.18.0.2" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:12:00:02" - Mounts: [] - Volumes: - - - Name: "my-volume" - Driver: "local" - Mountpoint: "/var/lib/docker/volumes/my-volume/_data" - Labels: null - Scope: "local" - Options: null - UsageData: - Size: 10920104 - RefCount: 2 - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["System"] - /images/{name}/get: - get: - summary: "Export an image" - description: | - Get a tarball containing all images and metadata for a repository. - - If `name` is a specific name and tag (e.g. `ubuntu:latest`), then only that image (and its parents) are returned. If `name` is an image ID, similarly only that image (and its parents) are returned, but with the exclusion of the `repositories` file in the tarball, as there were no image names referenced. - - ### Image tarball format - - An image tarball contains one directory per image layer (named using its long ID), each containing these files: - - - `VERSION`: currently `1.0` - the file format version - - `json`: detailed layer information, similar to `docker inspect layer_id` - - `layer.tar`: A tarfile containing the filesystem changes in this layer - - The `layer.tar` file contains `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. - - If the tarball defines a repository, the tarball should also include a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. - - ```json - { - "hello-world": { - "latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1" - } - } - ``` - operationId: "ImageGet" - produces: - - "application/x-tar" - responses: - 200: - description: "no error" - schema: - type: "string" - format: "binary" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID" - type: "string" - required: true - tags: ["Image"] - /images/get: - get: - summary: "Export several images" - description: | - Get a tarball containing all images and metadata for several image - repositories. - - For each value of the `names` parameter: if it is a specific name and - tag (e.g. `ubuntu:latest`), then only that image (and its parents) are - returned; if it is an image ID, similarly only that image (and its parents) - are returned and there would be no names referenced in the 'repositories' - file for this image ID. - - For details on the format, see the [export image endpoint](#operation/ImageGet). - operationId: "ImageGetAll" - produces: - - "application/x-tar" - responses: - 200: - description: "no error" - schema: - type: "string" - format: "binary" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "names" - in: "query" - description: "Image names to filter by" - type: "array" - items: - type: "string" - tags: ["Image"] - /images/load: - post: - summary: "Import images" - description: | - Load a set of images and tags into a repository. - - For details on the format, see the [export image endpoint](#operation/ImageGet). - operationId: "ImageLoad" - consumes: - - "application/x-tar" - produces: - - "application/json" - responses: - 200: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "imagesTarball" - in: "body" - description: "Tar archive containing images" - schema: - type: "string" - format: "binary" - - name: "quiet" - in: "query" - description: "Suppress progress details during load." - type: "boolean" - default: false - tags: ["Image"] - /containers/{id}/exec: - post: - summary: "Create an exec instance" - description: "Run a command inside a running container." - operationId: "ContainerExec" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - $ref: "#/definitions/IdResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "container is paused" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "execConfig" - in: "body" - description: "Exec configuration" - schema: - type: "object" - properties: - AttachStdin: - type: "boolean" - description: "Attach to `stdin` of the exec command." - AttachStdout: - type: "boolean" - description: "Attach to `stdout` of the exec command." - AttachStderr: - type: "boolean" - description: "Attach to `stderr` of the exec command." - DetachKeys: - type: "string" - description: | - Override the key sequence for detaching a container. Format is - a single character `[a-Z]` or `ctrl-` where `` - is one of: `a-z`, `@`, `^`, `[`, `,` or `_`. - Tty: - type: "boolean" - description: "Allocate a pseudo-TTY." - Env: - description: | - A list of environment variables in the form `["VAR=value", ...]`. - type: "array" - items: - type: "string" - Cmd: - type: "array" - description: "Command to run, as a string or array of strings." - items: - type: "string" - Privileged: - type: "boolean" - description: "Runs the exec process with extended privileges." - default: false - User: - type: "string" - description: | - The user, and optionally, group to run the exec process inside - the container. Format is one of: `user`, `user:group`, `uid`, - or `uid:gid`. - WorkingDir: - type: "string" - description: | - The working directory for the exec process inside the container. - example: - AttachStdin: false - AttachStdout: true - AttachStderr: true - DetachKeys: "ctrl-p,ctrl-q" - Tty: false - Cmd: - - "date" - Env: - - "FOO=bar" - - "BAZ=quux" - required: true - - name: "id" - in: "path" - description: "ID or name of container" - type: "string" - required: true - tags: ["Exec"] - /exec/{id}/start: - post: - summary: "Start an exec instance" - description: | - Starts a previously set up exec instance. If detach is true, this endpoint - returns immediately after starting the command. Otherwise, it sets up an - interactive session with the command. - operationId: "ExecStart" - consumes: - - "application/json" - produces: - - "application/vnd.docker.raw-stream" - responses: - 200: - description: "No error" - 404: - description: "No such exec instance" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Container is stopped or paused" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "execStartConfig" - in: "body" - schema: - type: "object" - properties: - Detach: - type: "boolean" - description: "Detach from the command." - Tty: - type: "boolean" - description: "Allocate a pseudo-TTY." - example: - Detach: false - Tty: false - - name: "id" - in: "path" - description: "Exec instance ID" - required: true - type: "string" - tags: ["Exec"] - /exec/{id}/resize: - post: - summary: "Resize an exec instance" - description: | - Resize the TTY session used by an exec instance. This endpoint only works - if `tty` was specified as part of creating and starting the exec instance. - operationId: "ExecResize" - responses: - 201: - description: "No error" - 404: - description: "No such exec instance" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Exec instance ID" - required: true - type: "string" - - name: "h" - in: "query" - description: "Height of the TTY session in characters" - type: "integer" - - name: "w" - in: "query" - description: "Width of the TTY session in characters" - type: "integer" - tags: ["Exec"] - /exec/{id}/json: - get: - summary: "Inspect an exec instance" - description: "Return low-level information about an exec instance." - operationId: "ExecInspect" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - type: "object" - title: "ExecInspectResponse" - properties: - CanRemove: - type: "boolean" - DetachKeys: - type: "string" - ID: - type: "string" - Running: - type: "boolean" - ExitCode: - type: "integer" - ProcessConfig: - $ref: "#/definitions/ProcessConfig" - OpenStdin: - type: "boolean" - OpenStderr: - type: "boolean" - OpenStdout: - type: "boolean" - ContainerID: - type: "string" - Pid: - type: "integer" - description: "The system process ID for the exec process." - examples: - application/json: - CanRemove: false - ContainerID: "b53ee82b53a40c7dca428523e34f741f3abc51d9f297a14ff874bf761b995126" - DetachKeys: "" - ExitCode: 2 - ID: "f33bbfb39f5b142420f4759b2348913bd4a8d1a6d7fd56499cb41a1bb91d7b3b" - OpenStderr: true - OpenStdin: true - OpenStdout: true - ProcessConfig: - arguments: - - "-c" - - "exit 2" - entrypoint: "sh" - privileged: false - tty: true - user: "1000" - Running: false - Pid: 42000 - 404: - description: "No such exec instance" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Exec instance ID" - required: true - type: "string" - tags: ["Exec"] - - /volumes: - get: - summary: "List volumes" - operationId: "VolumeList" - produces: ["application/json"] - responses: - 200: - description: "Summary volume data that matches the query" - schema: - type: "object" - title: "VolumeListResponse" - description: "Volume list response" - required: [Volumes, Warnings] - properties: - Volumes: - type: "array" - x-nullable: false - description: "List of volumes" - items: - $ref: "#/definitions/Volume" - Warnings: - type: "array" - x-nullable: false - description: | - Warnings that occurred when fetching the list of volumes. - items: - type: "string" - - examples: - application/json: - Volumes: - - CreatedAt: "2017-07-19T12:00:26Z" - Name: "tardis" - Driver: "local" - Mountpoint: "/var/lib/docker/volumes/tardis" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - Scope: "local" - Options: - device: "tmpfs" - o: "size=100m,uid=1000" - type: "tmpfs" - Warnings: [] - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - description: | - JSON encoded value of the filters (a `map[string][]string`) to - process on the volumes list. Available filters: - - - `dangling=` When set to `true` (or `1`), returns all - volumes that are not in use by a container. When set to `false` - (or `0`), only volumes that are in use by one or more - containers are returned. - - `driver=` Matches volumes based on their driver. - - `label=` or `label=:` Matches volumes based on - the presence of a `label` alone or a `label` and a value. - - `name=` Matches all or part of a volume name. - type: "string" - format: "json" - tags: ["Volume"] - - /volumes/create: - post: - summary: "Create a volume" - operationId: "VolumeCreate" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 201: - description: "The volume was created successfully" - schema: - $ref: "#/definitions/Volume" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "volumeConfig" - in: "body" - required: true - description: "Volume configuration" - schema: - type: "object" - description: "Volume configuration" - title: "VolumeConfig" - properties: - Name: - description: | - The new volume's name. If not specified, Docker generates a name. - type: "string" - x-nullable: false - Driver: - description: "Name of the volume driver to use." - type: "string" - default: "local" - x-nullable: false - DriverOpts: - description: | - A mapping of driver options and values. These options are - passed directly to the driver and are driver specific. - type: "object" - additionalProperties: - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - example: - Name: "tardis" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - Driver: "custom" - tags: ["Volume"] - - /volumes/{name}: - get: - summary: "Inspect a volume" - operationId: "VolumeInspect" - produces: ["application/json"] - responses: - 200: - description: "No error" - schema: - $ref: "#/definitions/Volume" - 404: - description: "No such volume" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - required: true - description: "Volume name or ID" - type: "string" - tags: ["Volume"] - - delete: - summary: "Remove a volume" - description: "Instruct the driver to remove the volume." - operationId: "VolumeDelete" - responses: - 204: - description: "The volume was removed" - 404: - description: "No such volume or volume driver" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Volume is in use and cannot be removed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - required: true - description: "Volume name or ID" - type: "string" - - name: "force" - in: "query" - description: "Force the removal of the volume" - type: "boolean" - default: false - tags: ["Volume"] - /volumes/prune: - post: - summary: "Delete unused volumes" - produces: - - "application/json" - operationId: "VolumePrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune volumes with (or without, in case `label!=...` is used) the specified labels. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - title: "VolumePruneResponse" - properties: - VolumesDeleted: - description: "Volumes that were deleted" - type: "array" - items: - type: "string" - SpaceReclaimed: - description: "Disk space reclaimed in bytes" - type: "integer" - format: "int64" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Volume"] - /networks: - get: - summary: "List networks" - description: | - Returns a list of networks. For details on the format, see the - [network inspect endpoint](#operation/NetworkInspect). - - Note that it uses a different, smaller representation of a network than - inspecting a single network. For example, the list of containers attached - to the network is not propagated in API versions 1.28 and up. - operationId: "NetworkList" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - type: "array" - items: - $ref: "#/definitions/Network" - examples: - application/json: - - Name: "bridge" - Id: "f2de39df4171b0dc801e8002d1d999b77256983dfc63041c0f34030aa3977566" - Created: "2016-10-19T06:21:00.416543526Z" - Scope: "local" - Driver: "bridge" - EnableIPv6: false - Internal: false - Attachable: false - Ingress: false - IPAM: - Driver: "default" - Config: - - - Subnet: "172.17.0.0/16" - Options: - com.docker.network.bridge.default_bridge: "true" - com.docker.network.bridge.enable_icc: "true" - com.docker.network.bridge.enable_ip_masquerade: "true" - com.docker.network.bridge.host_binding_ipv4: "0.0.0.0" - com.docker.network.bridge.name: "docker0" - com.docker.network.driver.mtu: "1500" - - Name: "none" - Id: "e086a3893b05ab69242d3c44e49483a3bbbd3a26b46baa8f61ab797c1088d794" - Created: "0001-01-01T00:00:00Z" - Scope: "local" - Driver: "null" - EnableIPv6: false - Internal: false - Attachable: false - Ingress: false - IPAM: - Driver: "default" - Config: [] - Containers: {} - Options: {} - - Name: "host" - Id: "13e871235c677f196c4e1ecebb9dc733b9b2d2ab589e30c539efeda84a24215e" - Created: "0001-01-01T00:00:00Z" - Scope: "local" - Driver: "host" - EnableIPv6: false - Internal: false - Attachable: false - Ingress: false - IPAM: - Driver: "default" - Config: [] - Containers: {} - Options: {} - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - description: | - JSON encoded value of the filters (a `map[string][]string`) to process - on the networks list. - - Available filters: - - - `dangling=` When set to `true` (or `1`), returns all - networks that are not in use by a container. When set to `false` - (or `0`), only networks that are in use by one or more - containers are returned. - - `driver=` Matches a network's driver. - - `id=` Matches all or part of a network ID. - - `label=` or `label==` of a network label. - - `name=` Matches all or part of a network name. - - `scope=["swarm"|"global"|"local"]` Filters networks by scope (`swarm`, `global`, or `local`). - - `type=["custom"|"builtin"]` Filters networks by type. The `custom` keyword returns all user-defined networks. - type: "string" - tags: ["Network"] - - /networks/{id}: - get: - summary: "Inspect a network" - operationId: "NetworkInspect" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - $ref: "#/definitions/Network" - 404: - description: "Network not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - - name: "verbose" - in: "query" - description: "Detailed inspect output for troubleshooting" - type: "boolean" - default: false - - name: "scope" - in: "query" - description: "Filter the network by scope (swarm, global, or local)" - type: "string" - tags: ["Network"] - - delete: - summary: "Remove a network" - operationId: "NetworkDelete" - responses: - 204: - description: "No error" - 403: - description: "operation not supported for pre-defined networks" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such network" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - tags: ["Network"] - - /networks/create: - post: - summary: "Create a network" - operationId: "NetworkCreate" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "No error" - schema: - type: "object" - title: "NetworkCreateResponse" - properties: - Id: - description: "The ID of the created network." - type: "string" - Warning: - type: "string" - example: - Id: "22be93d5babb089c5aab8dbc369042fad48ff791584ca2da2100db837a1c7c30" - Warning: "" - 403: - description: "operation not supported for pre-defined networks" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "plugin not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "networkConfig" - in: "body" - description: "Network configuration" - required: true - schema: - type: "object" - required: ["Name"] - properties: - Name: - description: "The network's name." - type: "string" - CheckDuplicate: - description: | - Check for networks with duplicate names. Since Network is - primarily keyed based on a random ID and not on the name, and - network name is strictly a user-friendly alias to the network - which is uniquely identified using ID, there is no guaranteed - way to check for duplicates. CheckDuplicate is there to provide - a best effort checking of any networks which has the same name - but it is not guaranteed to catch all name collisions. - type: "boolean" - Driver: - description: "Name of the network driver plugin to use." - type: "string" - default: "bridge" - Internal: - description: "Restrict external access to the network." - type: "boolean" - Attachable: - description: | - Globally scoped network is manually attachable by regular - containers from workers in swarm mode. - type: "boolean" - Ingress: - description: | - Ingress network is the network which provides the routing-mesh - in swarm mode. - type: "boolean" - IPAM: - description: "Optional custom IP scheme for the network." - $ref: "#/definitions/IPAM" - EnableIPv6: - description: "Enable IPv6 on the network." - type: "boolean" - Options: - description: "Network specific options to be used by the drivers." - type: "object" - additionalProperties: - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - example: - Name: "isolated_nw" - CheckDuplicate: false - Driver: "bridge" - EnableIPv6: true - IPAM: - Driver: "default" - Config: - - Subnet: "172.20.0.0/16" - IPRange: "172.20.10.0/24" - Gateway: "172.20.10.11" - - Subnet: "2001:db8:abcd::/64" - Gateway: "2001:db8:abcd::1011" - Options: - foo: "bar" - Internal: true - Attachable: false - Ingress: false - Options: - com.docker.network.bridge.default_bridge: "true" - com.docker.network.bridge.enable_icc: "true" - com.docker.network.bridge.enable_ip_masquerade: "true" - com.docker.network.bridge.host_binding_ipv4: "0.0.0.0" - com.docker.network.bridge.name: "docker0" - com.docker.network.driver.mtu: "1500" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - tags: ["Network"] - - /networks/{id}/connect: - post: - summary: "Connect a container to a network" - operationId: "NetworkConnect" - consumes: - - "application/json" - responses: - 200: - description: "No error" - 403: - description: "Operation not supported for swarm scoped networks" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "Network or container not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - - name: "container" - in: "body" - required: true - schema: - type: "object" - properties: - Container: - type: "string" - description: "The ID or name of the container to connect to the network." - EndpointConfig: - $ref: "#/definitions/EndpointSettings" - example: - Container: "3613f73ba0e4" - EndpointConfig: - IPAMConfig: - IPv4Address: "172.24.56.89" - IPv6Address: "2001:db8::5689" - tags: ["Network"] - - /networks/{id}/disconnect: - post: - summary: "Disconnect a container from a network" - operationId: "NetworkDisconnect" - consumes: - - "application/json" - responses: - 200: - description: "No error" - 403: - description: "Operation not supported for swarm scoped networks" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "Network or container not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - - name: "container" - in: "body" - required: true - schema: - type: "object" - properties: - Container: - type: "string" - description: | - The ID or name of the container to disconnect from the network. - Force: - type: "boolean" - description: | - Force the container to disconnect from the network. - tags: ["Network"] - /networks/prune: - post: - summary: "Delete unused networks" - produces: - - "application/json" - operationId: "NetworkPrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `until=` Prune networks created before this timestamp. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon machine’s time. - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune networks with (or without, in case `label!=...` is used) the specified labels. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - title: "NetworkPruneResponse" - properties: - NetworksDeleted: - description: "Networks that were deleted" - type: "array" - items: - type: "string" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Network"] - /plugins: - get: - summary: "List plugins" - operationId: "PluginList" - description: "Returns information about installed plugins." - produces: ["application/json"] - responses: - 200: - description: "No error" - schema: - type: "array" - items: - $ref: "#/definitions/Plugin" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the plugin list. - - Available filters: - - - `capability=` - - `enable=|` - tags: ["Plugin"] - - /plugins/privileges: - get: - summary: "Get plugin privileges" - operationId: "GetPluginPrivileges" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - description: | - Describes a permission the user has to accept upon installing - the plugin. - type: "object" - title: "PluginPrivilegeItem" - properties: - Name: - type: "string" - Description: - type: "string" - Value: - type: "array" - items: - type: "string" - example: - - Name: "network" - Description: "" - Value: - - "host" - - Name: "mount" - Description: "" - Value: - - "/data" - - Name: "device" - Description: "" - Value: - - "/dev/cpu_dma_latency" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "remote" - in: "query" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - tags: - - "Plugin" - - /plugins/pull: - post: - summary: "Install a plugin" - operationId: "PluginPull" - description: | - Pulls and installs a plugin. After the plugin is installed, it can be - enabled using the [`POST /plugins/{name}/enable` endpoint](#operation/PostPluginsEnable). - produces: - - "application/json" - responses: - 204: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "remote" - in: "query" - description: | - Remote reference for plugin to install. - - The `:latest` tag is optional, and is used as the default if omitted. - required: true - type: "string" - - name: "name" - in: "query" - description: | - Local name for the pulled plugin. - - The `:latest` tag is optional, and is used as the default if omitted. - required: false - type: "string" - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration to use when pulling a plugin - from a registry. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - - name: "body" - in: "body" - schema: - type: "array" - items: - description: | - Describes a permission accepted by the user upon installing the - plugin. - type: "object" - properties: - Name: - type: "string" - Description: - type: "string" - Value: - type: "array" - items: - type: "string" - example: - - Name: "network" - Description: "" - Value: - - "host" - - Name: "mount" - Description: "" - Value: - - "/data" - - Name: "device" - Description: "" - Value: - - "/dev/cpu_dma_latency" - tags: ["Plugin"] - /plugins/{name}/json: - get: - summary: "Inspect a plugin" - operationId: "PluginInspect" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Plugin" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - tags: ["Plugin"] - /plugins/{name}: - delete: - summary: "Remove a plugin" - operationId: "PluginDelete" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Plugin" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - - name: "force" - in: "query" - description: | - Disable the plugin before removing. This may result in issues if the - plugin is in use by a container. - type: "boolean" - default: false - tags: ["Plugin"] - /plugins/{name}/enable: - post: - summary: "Enable a plugin" - operationId: "PluginEnable" - responses: - 200: - description: "no error" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - - name: "timeout" - in: "query" - description: "Set the HTTP client timeout (in seconds)" - type: "integer" - default: 0 - tags: ["Plugin"] - /plugins/{name}/disable: - post: - summary: "Disable a plugin" - operationId: "PluginDisable" - responses: - 200: - description: "no error" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - tags: ["Plugin"] - /plugins/{name}/upgrade: - post: - summary: "Upgrade a plugin" - operationId: "PluginUpgrade" - responses: - 204: - description: "no error" - 404: - description: "plugin not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - - name: "remote" - in: "query" - description: | - Remote reference to upgrade to. - - The `:latest` tag is optional, and is used as the default if omitted. - required: true - type: "string" - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration to use when pulling a plugin - from a registry. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - - name: "body" - in: "body" - schema: - type: "array" - items: - description: | - Describes a permission accepted by the user upon installing the - plugin. - type: "object" - properties: - Name: - type: "string" - Description: - type: "string" - Value: - type: "array" - items: - type: "string" - example: - - Name: "network" - Description: "" - Value: - - "host" - - Name: "mount" - Description: "" - Value: - - "/data" - - Name: "device" - Description: "" - Value: - - "/dev/cpu_dma_latency" - tags: ["Plugin"] - /plugins/create: - post: - summary: "Create a plugin" - operationId: "PluginCreate" - consumes: - - "application/x-tar" - responses: - 204: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "query" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - - name: "tarContext" - in: "body" - description: "Path to tar containing plugin rootfs and manifest" - schema: - type: "string" - format: "binary" - tags: ["Plugin"] - /plugins/{name}/push: - post: - summary: "Push a plugin" - operationId: "PluginPush" - description: | - Push a plugin to the registry. - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - responses: - 200: - description: "no error" - 404: - description: "plugin not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Plugin"] - /plugins/{name}/set: - post: - summary: "Configure a plugin" - operationId: "PluginSet" - consumes: - - "application/json" - parameters: - - name: "name" - in: "path" - description: | - The name of the plugin. The `:latest` tag is optional, and is the - default if omitted. - required: true - type: "string" - - name: "body" - in: "body" - schema: - type: "array" - items: - type: "string" - example: ["DEBUG=1"] - responses: - 204: - description: "No error" - 404: - description: "Plugin not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Plugin"] - /nodes: - get: - summary: "List nodes" - operationId: "NodeList" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Node" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the nodes list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `id=` - - `label=` - - `membership=`(`accepted`|`pending`)` - - `name=` - - `node.label=` - - `role=`(`manager`|`worker`)` - type: "string" - tags: ["Node"] - /nodes/{id}: - get: - summary: "Inspect a node" - operationId: "NodeInspect" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Node" - 404: - description: "no such node" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID or name of the node" - type: "string" - required: true - tags: ["Node"] - delete: - summary: "Delete a node" - operationId: "NodeDelete" - responses: - 200: - description: "no error" - 404: - description: "no such node" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID or name of the node" - type: "string" - required: true - - name: "force" - in: "query" - description: "Force remove a node from the swarm" - default: false - type: "boolean" - tags: ["Node"] - /nodes/{id}/update: - post: - summary: "Update a node" - operationId: "NodeUpdate" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such node" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID of the node" - type: "string" - required: true - - name: "body" - in: "body" - schema: - $ref: "#/definitions/NodeSpec" - - name: "version" - in: "query" - description: | - The version number of the node object being updated. This is required - to avoid conflicting writes. - type: "integer" - format: "int64" - required: true - tags: ["Node"] - /swarm: - get: - summary: "Inspect swarm" - operationId: "SwarmInspect" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Swarm" - 404: - description: "no such swarm" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Swarm"] - /swarm/init: - post: - summary: "Initialize a new swarm" - operationId: "SwarmInit" - produces: - - "application/json" - - "text/plain" - responses: - 200: - description: "no error" - schema: - description: "The node ID" - type: "string" - example: "7v2t30z9blmxuhnyo6s4cpenp" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is already part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - type: "object" - properties: - ListenAddr: - description: | - Listen address used for inter-manager communication, as well - as determining the networking interface used for the VXLAN - Tunnel Endpoint (VTEP). This can either be an address/port - combination in the form `192.168.1.1:4567`, or an interface - followed by a port number, like `eth0:4567`. If the port number - is omitted, the default swarm listening port is used. - type: "string" - AdvertiseAddr: - description: | - Externally reachable address advertised to other nodes. This - can either be an address/port combination in the form - `192.168.1.1:4567`, or an interface followed by a port number, - like `eth0:4567`. If the port number is omitted, the port - number from the listen address is used. If `AdvertiseAddr` is - not specified, it will be automatically detected when possible. - type: "string" - DataPathAddr: - description: | - Address or interface to use for data path traffic (format: - ``), for example, `192.168.1.1`, or an interface, - like `eth0`. If `DataPathAddr` is unspecified, the same address - as `AdvertiseAddr` is used. - - The `DataPathAddr` specifies the address that global scope - network drivers will publish towards other nodes in order to - reach the containers running on this node. Using this parameter - it is possible to separate the container data traffic from the - management traffic of the cluster. - type: "string" - DataPathPort: - description: | - DataPathPort specifies the data path port number for data traffic. - Acceptable port range is 1024 to 49151. - if no port is set or is set to 0, default port 4789 will be used. - type: "integer" - format: "uint32" - DefaultAddrPool: - description: | - Default Address Pool specifies default subnet pools for global - scope networks. - type: "array" - items: - type: "string" - example: ["10.10.0.0/16", "20.20.0.0/16"] - ForceNewCluster: - description: "Force creation of a new swarm." - type: "boolean" - SubnetSize: - description: | - SubnetSize specifies the subnet size of the networks created - from the default subnet pool. - type: "integer" - format: "uint32" - Spec: - $ref: "#/definitions/SwarmSpec" - example: - ListenAddr: "0.0.0.0:2377" - AdvertiseAddr: "192.168.1.1:2377" - DataPathPort: 4789 - DefaultAddrPool: ["10.10.0.0/8", "20.20.0.0/8"] - SubnetSize: 24 - ForceNewCluster: false - Spec: - Orchestration: {} - Raft: {} - Dispatcher: {} - CAConfig: {} - EncryptionConfig: - AutoLockManagers: false - tags: ["Swarm"] - /swarm/join: - post: - summary: "Join an existing swarm" - operationId: "SwarmJoin" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is already part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - type: "object" - properties: - ListenAddr: - description: | - Listen address used for inter-manager communication if the node - gets promoted to manager, as well as determining the networking - interface used for the VXLAN Tunnel Endpoint (VTEP). - type: "string" - AdvertiseAddr: - description: | - Externally reachable address advertised to other nodes. This - can either be an address/port combination in the form - `192.168.1.1:4567`, or an interface followed by a port number, - like `eth0:4567`. If the port number is omitted, the port - number from the listen address is used. If `AdvertiseAddr` is - not specified, it will be automatically detected when possible. - type: "string" - DataPathAddr: - description: | - Address or interface to use for data path traffic (format: - ``), for example, `192.168.1.1`, or an interface, - like `eth0`. If `DataPathAddr` is unspecified, the same addres - as `AdvertiseAddr` is used. - - The `DataPathAddr` specifies the address that global scope - network drivers will publish towards other nodes in order to - reach the containers running on this node. Using this parameter - it is possible to separate the container data traffic from the - management traffic of the cluster. - - type: "string" - RemoteAddrs: - description: | - Addresses of manager nodes already participating in the swarm. - type: "array" - items: - type: "string" - JoinToken: - description: "Secret token for joining this swarm." - type: "string" - example: - ListenAddr: "0.0.0.0:2377" - AdvertiseAddr: "192.168.1.1:2377" - RemoteAddrs: - - "node1:2377" - JoinToken: "SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-7p73s1dx5in4tatdymyhg9hu2" - tags: ["Swarm"] - /swarm/leave: - post: - summary: "Leave a swarm" - operationId: "SwarmLeave" - responses: - 200: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "force" - description: | - Force leave swarm, even if this is the last manager or that it will - break the cluster. - in: "query" - type: "boolean" - default: false - tags: ["Swarm"] - /swarm/update: - post: - summary: "Update a swarm" - operationId: "SwarmUpdate" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - $ref: "#/definitions/SwarmSpec" - - name: "version" - in: "query" - description: | - The version number of the swarm object being updated. This is - required to avoid conflicting writes. - type: "integer" - format: "int64" - required: true - - name: "rotateWorkerToken" - in: "query" - description: "Rotate the worker join token." - type: "boolean" - default: false - - name: "rotateManagerToken" - in: "query" - description: "Rotate the manager join token." - type: "boolean" - default: false - - name: "rotateManagerUnlockKey" - in: "query" - description: "Rotate the manager unlock key." - type: "boolean" - default: false - tags: ["Swarm"] - /swarm/unlockkey: - get: - summary: "Get the unlock key" - operationId: "SwarmUnlockkey" - consumes: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "object" - title: "UnlockKeyResponse" - properties: - UnlockKey: - description: "The swarm's unlock key." - type: "string" - example: - UnlockKey: "SWMKEY-1-7c37Cc8654o6p38HnroywCi19pllOnGtbdZEgtKxZu8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Swarm"] - /swarm/unlock: - post: - summary: "Unlock a locked manager" - operationId: "SwarmUnlock" - consumes: - - "application/json" - produces: - - "application/json" - parameters: - - name: "body" - in: "body" - required: true - schema: - type: "object" - properties: - UnlockKey: - description: "The swarm's unlock key." - type: "string" - example: - UnlockKey: "SWMKEY-1-7c37Cc8654o6p38HnroywCi19pllOnGtbdZEgtKxZu8" - responses: - 200: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Swarm"] - /services: - get: - summary: "List services" - operationId: "ServiceList" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Service" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the services list. - - Available filters: - - - `id=` - - `label=` - - `mode=["replicated"|"global"]` - - `name=` - - name: "status" - in: "query" - type: "boolean" - description: | - Include service status, with count of running and desired tasks. - tags: ["Service"] - /services/create: - post: - summary: "Create a service" - operationId: "ServiceCreate" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - type: "object" - title: "ServiceCreateResponse" - properties: - ID: - description: "The ID of the created service." - type: "string" - Warning: - description: "Optional warning message" - type: "string" - example: - ID: "ak7w3gjqoa3kuz8xcpnyy0pvl" - Warning: "unable to pin image doesnotexist:latest to digest: image library/doesnotexist:latest not found" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 403: - description: "network is not eligible for services" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "name conflicts with an existing service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - allOf: - - $ref: "#/definitions/ServiceSpec" - - type: "object" - example: - Name: "web" - TaskTemplate: - ContainerSpec: - Image: "nginx:alpine" - Mounts: - - - ReadOnly: true - Source: "web-data" - Target: "/usr/share/nginx/html" - Type: "volume" - VolumeOptions: - DriverConfig: {} - Labels: - com.example.something: "something-value" - Hosts: ["10.10.10.10 host1", "ABCD:EF01:2345:6789:ABCD:EF01:2345:6789 host2"] - User: "33" - DNSConfig: - Nameservers: ["8.8.8.8"] - Search: ["example.org"] - Options: ["timeout:3"] - Secrets: - - - File: - Name: "www.example.org.key" - UID: "33" - GID: "33" - Mode: 384 - SecretID: "fpjqlhnwb19zds35k8wn80lq9" - SecretName: "example_org_domain_key" - LogDriver: - Name: "json-file" - Options: - max-file: "3" - max-size: "10M" - Placement: {} - Resources: - Limits: - MemoryBytes: 104857600 - Reservations: {} - RestartPolicy: - Condition: "on-failure" - Delay: 10000000000 - MaxAttempts: 10 - Mode: - Replicated: - Replicas: 4 - UpdateConfig: - Parallelism: 2 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - RollbackConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - EndpointSpec: - Ports: - - - Protocol: "tcp" - PublishedPort: 8080 - TargetPort: 80 - Labels: - foo: "bar" - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration for pulling from private - registries. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - tags: ["Service"] - /services/{id}: - get: - summary: "Inspect a service" - operationId: "ServiceInspect" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Service" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID or name of service." - required: true - type: "string" - - name: "insertDefaults" - in: "query" - description: "Fill empty fields with default values." - type: "boolean" - default: false - tags: ["Service"] - delete: - summary: "Delete a service" - operationId: "ServiceDelete" - responses: - 200: - description: "no error" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID or name of service." - required: true - type: "string" - tags: ["Service"] - /services/{id}/update: - post: - summary: "Update a service" - operationId: "ServiceUpdate" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/ServiceUpdateResponse" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID or name of service." - required: true - type: "string" - - name: "body" - in: "body" - required: true - schema: - allOf: - - $ref: "#/definitions/ServiceSpec" - - type: "object" - example: - Name: "top" - TaskTemplate: - ContainerSpec: - Image: "busybox" - Args: - - "top" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ForceUpdate: 0 - Mode: - Replicated: - Replicas: 1 - UpdateConfig: - Parallelism: 2 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - RollbackConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - EndpointSpec: - Mode: "vip" - - - name: "version" - in: "query" - description: | - The version number of the service object being updated. This is - required to avoid conflicting writes. - This version number should be the value as currently set on the - service *before* the update. You can find the current version by - calling `GET /services/{id}` - required: true - type: "integer" - - name: "registryAuthFrom" - in: "query" - description: | - If the `X-Registry-Auth` header is not specified, this parameter - indicates where to find registry authorization credentials. - type: "string" - enum: ["spec", "previous-spec"] - default: "spec" - - name: "rollback" - in: "query" - description: | - Set to this parameter to `previous` to cause a server-side rollback - to the previous service spec. The supplied spec will be ignored in - this case. - type: "string" - - name: "X-Registry-Auth" - in: "header" - description: | - A base64url-encoded auth configuration for pulling from private - registries. - - Refer to the [authentication section](#section/Authentication) for - details. - type: "string" - - tags: ["Service"] - /services/{id}/logs: - get: - summary: "Get service logs" - description: | - Get `stdout` and `stderr` logs from a service. See also - [`/containers/{id}/logs`](#operation/ContainerLogs). - - **Note**: This endpoint works only for services with the `local`, - `json-file` or `journald` logging drivers. - operationId: "ServiceLogs" - responses: - 200: - description: "logs returned as a stream in response body" - schema: - type: "string" - format: "binary" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such service: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the service" - type: "string" - - name: "details" - in: "query" - description: "Show service context and extra details provided to logs." - type: "boolean" - default: false - - name: "follow" - in: "query" - description: "Keep connection after returning logs." - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Return logs from `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Return logs from `stderr`" - type: "boolean" - default: false - - name: "since" - in: "query" - description: "Only return logs since this time, as a UNIX timestamp" - type: "integer" - default: 0 - - name: "timestamps" - in: "query" - description: "Add timestamps to every log line" - type: "boolean" - default: false - - name: "tail" - in: "query" - description: | - Only return this number of log lines from the end of the logs. - Specify as an integer or `all` to output all log lines. - type: "string" - default: "all" - tags: ["Service"] - /tasks: - get: - summary: "List tasks" - operationId: "TaskList" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Task" - example: - - ID: "0kzzo1i0y4jz6027t0k7aezc7" - Version: - Index: 71 - CreatedAt: "2016-06-07T21:07:31.171892745Z" - UpdatedAt: "2016-06-07T21:07:31.376370513Z" - Spec: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ServiceID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Slot: 1 - NodeID: "60gvrl6tm78dmak4yl7srz94v" - Status: - Timestamp: "2016-06-07T21:07:31.290032978Z" - State: "running" - Message: "started" - ContainerStatus: - ContainerID: "e5d62702a1b48d01c3e02ca1e0212a250801fa8d67caca0b6f35919ebc12f035" - PID: 677 - DesiredState: "running" - NetworksAttachments: - - Network: - ID: "4qvuz4ko70xaltuqbt8956gd1" - Version: - Index: 18 - CreatedAt: "2016-06-07T20:31:11.912919752Z" - UpdatedAt: "2016-06-07T21:07:29.955277358Z" - Spec: - Name: "ingress" - Labels: - com.docker.swarm.internal: "true" - DriverConfiguration: {} - IPAMOptions: - Driver: {} - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - DriverState: - Name: "overlay" - Options: - com.docker.network.driver.overlay.vxlanid_list: "256" - IPAMOptions: - Driver: - Name: "default" - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - Addresses: - - "10.255.0.10/16" - - ID: "1yljwbmlr8er2waf8orvqpwms" - Version: - Index: 30 - CreatedAt: "2016-06-07T21:07:30.019104782Z" - UpdatedAt: "2016-06-07T21:07:30.231958098Z" - Name: "hopeful_cori" - Spec: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ServiceID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Slot: 1 - NodeID: "60gvrl6tm78dmak4yl7srz94v" - Status: - Timestamp: "2016-06-07T21:07:30.202183143Z" - State: "shutdown" - Message: "shutdown" - ContainerStatus: - ContainerID: "1cf8d63d18e79668b0004a4be4c6ee58cddfad2dae29506d8781581d0688a213" - DesiredState: "shutdown" - NetworksAttachments: - - Network: - ID: "4qvuz4ko70xaltuqbt8956gd1" - Version: - Index: 18 - CreatedAt: "2016-06-07T20:31:11.912919752Z" - UpdatedAt: "2016-06-07T21:07:29.955277358Z" - Spec: - Name: "ingress" - Labels: - com.docker.swarm.internal: "true" - DriverConfiguration: {} - IPAMOptions: - Driver: {} - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - DriverState: - Name: "overlay" - Options: - com.docker.network.driver.overlay.vxlanid_list: "256" - IPAMOptions: - Driver: - Name: "default" - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - Addresses: - - "10.255.0.5/16" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the tasks list. - - Available filters: - - - `desired-state=(running | shutdown | accepted)` - - `id=` - - `label=key` or `label="key=value"` - - `name=` - - `node=` - - `service=` - tags: ["Task"] - /tasks/{id}: - get: - summary: "Inspect a task" - operationId: "TaskInspect" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Task" - 404: - description: "no such task" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID of the task" - required: true - type: "string" - tags: ["Task"] - /tasks/{id}/logs: - get: - summary: "Get task logs" - description: | - Get `stdout` and `stderr` logs from a task. - See also [`/containers/{id}/logs`](#operation/ContainerLogs). - - **Note**: This endpoint works only for services with the `local`, - `json-file` or `journald` logging drivers. - operationId: "TaskLogs" - responses: - 200: - description: "logs returned as a stream in response body" - schema: - type: "string" - format: "binary" - 404: - description: "no such task" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such task: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID of the task" - type: "string" - - name: "details" - in: "query" - description: "Show task context and extra details provided to logs." - type: "boolean" - default: false - - name: "follow" - in: "query" - description: "Keep connection after returning logs." - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Return logs from `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Return logs from `stderr`" - type: "boolean" - default: false - - name: "since" - in: "query" - description: "Only return logs since this time, as a UNIX timestamp" - type: "integer" - default: 0 - - name: "timestamps" - in: "query" - description: "Add timestamps to every log line" - type: "boolean" - default: false - - name: "tail" - in: "query" - description: | - Only return this number of log lines from the end of the logs. - Specify as an integer or `all` to output all log lines. - type: "string" - default: "all" - tags: ["Task"] - /secrets: - get: - summary: "List secrets" - operationId: "SecretList" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Secret" - example: - - ID: "blt1owaxmitz71s9v5zh81zun" - Version: - Index: 85 - CreatedAt: "2017-07-20T13:55:28.678958722Z" - UpdatedAt: "2017-07-20T13:55:28.678958722Z" - Spec: - Name: "mysql-passwd" - Labels: - some.label: "some.value" - Driver: - Name: "secret-bucket" - Options: - OptionA: "value for driver option A" - OptionB: "value for driver option B" - - ID: "ktnbjxoalbkvbvedmg1urrz8h" - Version: - Index: 11 - CreatedAt: "2016-11-05T01:20:17.327670065Z" - UpdatedAt: "2016-11-05T01:20:17.327670065Z" - Spec: - Name: "app-dev.crt" - Labels: - foo: "bar" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the secrets list. - - Available filters: - - - `id=` - - `label= or label==value` - - `name=` - - `names=` - tags: ["Secret"] - /secrets/create: - post: - summary: "Create a secret" - operationId: "SecretCreate" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - $ref: "#/definitions/IdResponse" - 409: - description: "name conflicts with an existing object" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - schema: - allOf: - - $ref: "#/definitions/SecretSpec" - - type: "object" - example: - Name: "app-key.crt" - Labels: - foo: "bar" - Data: "VEhJUyBJUyBOT1QgQSBSRUFMIENFUlRJRklDQVRFCg==" - Driver: - Name: "secret-bucket" - Options: - OptionA: "value for driver option A" - OptionB: "value for driver option B" - tags: ["Secret"] - /secrets/{id}: - get: - summary: "Inspect a secret" - operationId: "SecretInspect" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Secret" - examples: - application/json: - ID: "ktnbjxoalbkvbvedmg1urrz8h" - Version: - Index: 11 - CreatedAt: "2016-11-05T01:20:17.327670065Z" - UpdatedAt: "2016-11-05T01:20:17.327670065Z" - Spec: - Name: "app-dev.crt" - Labels: - foo: "bar" - Driver: - Name: "secret-bucket" - Options: - OptionA: "value for driver option A" - OptionB: "value for driver option B" - - 404: - description: "secret not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - type: "string" - description: "ID of the secret" - tags: ["Secret"] - delete: - summary: "Delete a secret" - operationId: "SecretDelete" - produces: - - "application/json" - responses: - 204: - description: "no error" - 404: - description: "secret not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - type: "string" - description: "ID of the secret" - tags: ["Secret"] - /secrets/{id}/update: - post: - summary: "Update a Secret" - operationId: "SecretUpdate" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such secret" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID or name of the secret" - type: "string" - required: true - - name: "body" - in: "body" - schema: - $ref: "#/definitions/SecretSpec" - description: | - The spec of the secret to update. Currently, only the Labels field - can be updated. All other fields must remain unchanged from the - [SecretInspect endpoint](#operation/SecretInspect) response values. - - name: "version" - in: "query" - description: | - The version number of the secret object being updated. This is - required to avoid conflicting writes. - type: "integer" - format: "int64" - required: true - tags: ["Secret"] - /configs: - get: - summary: "List configs" - operationId: "ConfigList" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Config" - example: - - ID: "ktnbjxoalbkvbvedmg1urrz8h" - Version: - Index: 11 - CreatedAt: "2016-11-05T01:20:17.327670065Z" - UpdatedAt: "2016-11-05T01:20:17.327670065Z" - Spec: - Name: "server.conf" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to - process on the configs list. - - Available filters: - - - `id=` - - `label= or label==value` - - `name=` - - `names=` - tags: ["Config"] - /configs/create: - post: - summary: "Create a config" - operationId: "ConfigCreate" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - $ref: "#/definitions/IdResponse" - 409: - description: "name conflicts with an existing object" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - schema: - allOf: - - $ref: "#/definitions/ConfigSpec" - - type: "object" - example: - Name: "server.conf" - Labels: - foo: "bar" - Data: "VEhJUyBJUyBOT1QgQSBSRUFMIENFUlRJRklDQVRFCg==" - tags: ["Config"] - /configs/{id}: - get: - summary: "Inspect a config" - operationId: "ConfigInspect" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Config" - examples: - application/json: - ID: "ktnbjxoalbkvbvedmg1urrz8h" - Version: - Index: 11 - CreatedAt: "2016-11-05T01:20:17.327670065Z" - UpdatedAt: "2016-11-05T01:20:17.327670065Z" - Spec: - Name: "app-dev.crt" - 404: - description: "config not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - type: "string" - description: "ID of the config" - tags: ["Config"] - delete: - summary: "Delete a config" - operationId: "ConfigDelete" - produces: - - "application/json" - responses: - 204: - description: "no error" - 404: - description: "config not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - type: "string" - description: "ID of the config" - tags: ["Config"] - /configs/{id}/update: - post: - summary: "Update a Config" - operationId: "ConfigUpdate" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such config" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID or name of the config" - type: "string" - required: true - - name: "body" - in: "body" - schema: - $ref: "#/definitions/ConfigSpec" - description: | - The spec of the config to update. Currently, only the Labels field - can be updated. All other fields must remain unchanged from the - [ConfigInspect endpoint](#operation/ConfigInspect) response values. - - name: "version" - in: "query" - description: | - The version number of the config object being updated. This is - required to avoid conflicting writes. - type: "integer" - format: "int64" - required: true - tags: ["Config"] - /distribution/{name}/json: - get: - summary: "Get image information from the registry" - description: | - Return image digest and platform information by contacting the registry. - operationId: "DistributionInspect" - produces: - - "application/json" - responses: - 200: - description: "descriptor and platform information" - schema: - type: "object" - x-go-name: DistributionInspect - title: "DistributionInspectResponse" - required: [Descriptor, Platforms] - properties: - Descriptor: - type: "object" - description: | - A descriptor struct containing digest, media type, and size. - properties: - MediaType: - type: "string" - Size: - type: "integer" - format: "int64" - Digest: - type: "string" - URLs: - type: "array" - items: - type: "string" - Platforms: - type: "array" - description: | - An array containing all platforms supported by the image. - items: - type: "object" - properties: - Architecture: - type: "string" - OS: - type: "string" - OSVersion: - type: "string" - OSFeatures: - type: "array" - items: - type: "string" - Variant: - type: "string" - Features: - type: "array" - items: - type: "string" - examples: - application/json: - Descriptor: - MediaType: "application/vnd.docker.distribution.manifest.v2+json" - Digest: "sha256:c0537ff6a5218ef531ece93d4984efc99bbf3f7497c0a7726c88e2bb7584dc96" - Size: 3987495 - URLs: - - "" - Platforms: - - Architecture: "amd64" - OS: "linux" - OSVersion: "" - OSFeatures: - - "" - Variant: "" - Features: - - "" - 401: - description: "Failed authentication or no image found" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such image: someimage (tag: latest)" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or id" - type: "string" - required: true - tags: ["Distribution"] - /session: - post: - summary: "Initialize interactive session" - description: | - Start a new interactive session with a server. Session allows server to - call back to the client for advanced capabilities. - - ### Hijacking - - This endpoint hijacks the HTTP connection to HTTP2 transport that allows - the client to expose gPRC services on that connection. - - For example, the client sends this request to upgrade the connection: - - ``` - POST /session HTTP/1.1 - Upgrade: h2c - Connection: Upgrade - ``` - - The Docker daemon responds with a `101 UPGRADED` response follow with - the raw stream: - - ``` - HTTP/1.1 101 UPGRADED - Connection: Upgrade - Upgrade: h2c - ``` - operationId: "Session" - produces: - - "application/vnd.docker.raw-stream" - responses: - 101: - description: "no error, hijacking successful" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Session"] diff --git a/vendor/github.com/docker/docker/api/types/auth.go b/vendor/github.com/docker/docker/api/types/auth.go deleted file mode 100644 index ddf15bb1..00000000 --- a/vendor/github.com/docker/docker/api/types/auth.go +++ /dev/null @@ -1,22 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -// AuthConfig contains authorization information for connecting to a Registry -type AuthConfig struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Auth string `json:"auth,omitempty"` - - // Email is an optional value associated with the username. - // This field is deprecated and will be removed in a later - // version of docker. - Email string `json:"email,omitempty"` - - ServerAddress string `json:"serveraddress,omitempty"` - - // IdentityToken is used to authenticate the user and get - // an access token for the registry. - IdentityToken string `json:"identitytoken,omitempty"` - - // RegistryToken is a bearer token to be sent to a registry - RegistryToken string `json:"registrytoken,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go b/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go deleted file mode 100644 index bf3463b9..00000000 --- a/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go +++ /dev/null @@ -1,23 +0,0 @@ -package blkiodev // import "github.com/docker/docker/api/types/blkiodev" - -import "fmt" - -// WeightDevice is a structure that holds device:weight pair -type WeightDevice struct { - Path string - Weight uint16 -} - -func (w *WeightDevice) String() string { - return fmt.Sprintf("%s:%d", w.Path, w.Weight) -} - -// ThrottleDevice is a structure that holds device:rate_per_second pair -type ThrottleDevice struct { - Path string - Rate uint64 -} - -func (t *ThrottleDevice) String() string { - return fmt.Sprintf("%s:%d", t.Path, t.Rate) -} diff --git a/vendor/github.com/docker/docker/api/types/client.go b/vendor/github.com/docker/docker/api/types/client.go deleted file mode 100644 index 9c464b73..00000000 --- a/vendor/github.com/docker/docker/api/types/client.go +++ /dev/null @@ -1,419 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -import ( - "bufio" - "io" - "net" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/filters" - units "github.com/docker/go-units" -) - -// CheckpointCreateOptions holds parameters to create a checkpoint from a container -type CheckpointCreateOptions struct { - CheckpointID string - CheckpointDir string - Exit bool -} - -// CheckpointListOptions holds parameters to list checkpoints for a container -type CheckpointListOptions struct { - CheckpointDir string -} - -// CheckpointDeleteOptions holds parameters to delete a checkpoint from a container -type CheckpointDeleteOptions struct { - CheckpointID string - CheckpointDir string -} - -// ContainerAttachOptions holds parameters to attach to a container. -type ContainerAttachOptions struct { - Stream bool - Stdin bool - Stdout bool - Stderr bool - DetachKeys string - Logs bool -} - -// ContainerCommitOptions holds parameters to commit changes into a container. -type ContainerCommitOptions struct { - Reference string - Comment string - Author string - Changes []string - Pause bool - Config *container.Config -} - -// ContainerExecInspect holds information returned by exec inspect. -type ContainerExecInspect struct { - ExecID string `json:"ID"` - ContainerID string - Running bool - ExitCode int - Pid int -} - -// ContainerListOptions holds parameters to list containers with. -type ContainerListOptions struct { - Quiet bool - Size bool - All bool - Latest bool - Since string - Before string - Limit int - Filters filters.Args -} - -// ContainerLogsOptions holds parameters to filter logs with. -type ContainerLogsOptions struct { - ShowStdout bool - ShowStderr bool - Since string - Until string - Timestamps bool - Follow bool - Tail string - Details bool -} - -// ContainerRemoveOptions holds parameters to remove containers. -type ContainerRemoveOptions struct { - RemoveVolumes bool - RemoveLinks bool - Force bool -} - -// ContainerStartOptions holds parameters to start containers. -type ContainerStartOptions struct { - CheckpointID string - CheckpointDir string -} - -// CopyToContainerOptions holds information -// about files to copy into a container -type CopyToContainerOptions struct { - AllowOverwriteDirWithFile bool - CopyUIDGID bool -} - -// EventsOptions holds parameters to filter events with. -type EventsOptions struct { - Since string - Until string - Filters filters.Args -} - -// NetworkListOptions holds parameters to filter the list of networks with. -type NetworkListOptions struct { - Filters filters.Args -} - -// HijackedResponse holds connection information for a hijacked request. -type HijackedResponse struct { - Conn net.Conn - Reader *bufio.Reader -} - -// Close closes the hijacked connection and reader. -func (h *HijackedResponse) Close() { - h.Conn.Close() -} - -// CloseWriter is an interface that implements structs -// that close input streams to prevent from writing. -type CloseWriter interface { - CloseWrite() error -} - -// CloseWrite closes a readWriter for writing. -func (h *HijackedResponse) CloseWrite() error { - if conn, ok := h.Conn.(CloseWriter); ok { - return conn.CloseWrite() - } - return nil -} - -// ImageBuildOptions holds the information -// necessary to build images. -type ImageBuildOptions struct { - Tags []string - SuppressOutput bool - RemoteContext string - NoCache bool - Remove bool - ForceRemove bool - PullParent bool - Isolation container.Isolation - CPUSetCPUs string - CPUSetMems string - CPUShares int64 - CPUQuota int64 - CPUPeriod int64 - Memory int64 - MemorySwap int64 - CgroupParent string - NetworkMode string - ShmSize int64 - Dockerfile string - Ulimits []*units.Ulimit - // BuildArgs needs to be a *string instead of just a string so that - // we can tell the difference between "" (empty string) and no value - // at all (nil). See the parsing of buildArgs in - // api/server/router/build/build_routes.go for even more info. - BuildArgs map[string]*string - AuthConfigs map[string]AuthConfig - Context io.Reader - Labels map[string]string - // squash the resulting image's layers to the parent - // preserves the original image and creates a new one from the parent with all - // the changes applied to a single layer - Squash bool - // CacheFrom specifies images that are used for matching cache. Images - // specified here do not need to have a valid parent chain to match cache. - CacheFrom []string - SecurityOpt []string - ExtraHosts []string // List of extra hosts - Target string - SessionID string - Platform string - // Version specifies the version of the unerlying builder to use - Version BuilderVersion - // BuildID is an optional identifier that can be passed together with the - // build request. The same identifier can be used to gracefully cancel the - // build with the cancel request. - BuildID string - // Outputs defines configurations for exporting build results. Only supported - // in BuildKit mode - Outputs []ImageBuildOutput -} - -// ImageBuildOutput defines configuration for exporting a build result -type ImageBuildOutput struct { - Type string - Attrs map[string]string -} - -// BuilderVersion sets the version of underlying builder to use -type BuilderVersion string - -const ( - // BuilderV1 is the first generation builder in docker daemon - BuilderV1 BuilderVersion = "1" - // BuilderBuildKit is builder based on moby/buildkit project - BuilderBuildKit BuilderVersion = "2" -) - -// ImageBuildResponse holds information -// returned by a server after building -// an image. -type ImageBuildResponse struct { - Body io.ReadCloser - OSType string -} - -// ImageCreateOptions holds information to create images. -type ImageCreateOptions struct { - RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry. - Platform string // Platform is the target platform of the image if it needs to be pulled from the registry. -} - -// ImageImportSource holds source information for ImageImport -type ImageImportSource struct { - Source io.Reader // Source is the data to send to the server to create this image from. You must set SourceName to "-" to leverage this. - SourceName string // SourceName is the name of the image to pull. Set to "-" to leverage the Source attribute. -} - -// ImageImportOptions holds information to import images from the client host. -type ImageImportOptions struct { - Tag string // Tag is the name to tag this image with. This attribute is deprecated. - Message string // Message is the message to tag the image with - Changes []string // Changes are the raw changes to apply to this image - Platform string // Platform is the target platform of the image -} - -// ImageListOptions holds parameters to filter the list of images with. -type ImageListOptions struct { - All bool - Filters filters.Args -} - -// ImageLoadResponse returns information to the client about a load process. -type ImageLoadResponse struct { - // Body must be closed to avoid a resource leak - Body io.ReadCloser - JSON bool -} - -// ImagePullOptions holds information to pull images. -type ImagePullOptions struct { - All bool - RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry - PrivilegeFunc RequestPrivilegeFunc - Platform string -} - -// RequestPrivilegeFunc is a function interface that -// clients can supply to retry operations after -// getting an authorization error. -// This function returns the registry authentication -// header value in base 64 format, or an error -// if the privilege request fails. -type RequestPrivilegeFunc func() (string, error) - -// ImagePushOptions holds information to push images. -type ImagePushOptions ImagePullOptions - -// ImageRemoveOptions holds parameters to remove images. -type ImageRemoveOptions struct { - Force bool - PruneChildren bool -} - -// ImageSearchOptions holds parameters to search images with. -type ImageSearchOptions struct { - RegistryAuth string - PrivilegeFunc RequestPrivilegeFunc - Filters filters.Args - Limit int -} - -// ResizeOptions holds parameters to resize a tty. -// It can be used to resize container ttys and -// exec process ttys too. -type ResizeOptions struct { - Height uint - Width uint -} - -// NodeListOptions holds parameters to list nodes with. -type NodeListOptions struct { - Filters filters.Args -} - -// NodeRemoveOptions holds parameters to remove nodes with. -type NodeRemoveOptions struct { - Force bool -} - -// ServiceCreateOptions contains the options to use when creating a service. -type ServiceCreateOptions struct { - // EncodedRegistryAuth is the encoded registry authorization credentials to - // use when updating the service. - // - // This field follows the format of the X-Registry-Auth header. - EncodedRegistryAuth string - - // QueryRegistry indicates whether the service update requires - // contacting a registry. A registry may be contacted to retrieve - // the image digest and manifest, which in turn can be used to update - // platform or other information about the service. - QueryRegistry bool -} - -// ServiceCreateResponse contains the information returned to a client -// on the creation of a new service. -type ServiceCreateResponse struct { - // ID is the ID of the created service. - ID string - // Warnings is a set of non-fatal warning messages to pass on to the user. - Warnings []string `json:",omitempty"` -} - -// Values for RegistryAuthFrom in ServiceUpdateOptions -const ( - RegistryAuthFromSpec = "spec" - RegistryAuthFromPreviousSpec = "previous-spec" -) - -// ServiceUpdateOptions contains the options to be used for updating services. -type ServiceUpdateOptions struct { - // EncodedRegistryAuth is the encoded registry authorization credentials to - // use when updating the service. - // - // This field follows the format of the X-Registry-Auth header. - EncodedRegistryAuth string - - // TODO(stevvooe): Consider moving the version parameter of ServiceUpdate - // into this field. While it does open API users up to racy writes, most - // users may not need that level of consistency in practice. - - // RegistryAuthFrom specifies where to find the registry authorization - // credentials if they are not given in EncodedRegistryAuth. Valid - // values are "spec" and "previous-spec". - RegistryAuthFrom string - - // Rollback indicates whether a server-side rollback should be - // performed. When this is set, the provided spec will be ignored. - // The valid values are "previous" and "none". An empty value is the - // same as "none". - Rollback string - - // QueryRegistry indicates whether the service update requires - // contacting a registry. A registry may be contacted to retrieve - // the image digest and manifest, which in turn can be used to update - // platform or other information about the service. - QueryRegistry bool -} - -// ServiceListOptions holds parameters to list services with. -type ServiceListOptions struct { - Filters filters.Args - - // Status indicates whether the server should include the service task - // count of running and desired tasks. - Status bool -} - -// ServiceInspectOptions holds parameters related to the "service inspect" -// operation. -type ServiceInspectOptions struct { - InsertDefaults bool -} - -// TaskListOptions holds parameters to list tasks with. -type TaskListOptions struct { - Filters filters.Args -} - -// PluginRemoveOptions holds parameters to remove plugins. -type PluginRemoveOptions struct { - Force bool -} - -// PluginEnableOptions holds parameters to enable plugins. -type PluginEnableOptions struct { - Timeout int -} - -// PluginDisableOptions holds parameters to disable plugins. -type PluginDisableOptions struct { - Force bool -} - -// PluginInstallOptions holds parameters to install a plugin. -type PluginInstallOptions struct { - Disabled bool - AcceptAllPermissions bool - RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry - RemoteRef string // RemoteRef is the plugin name on the registry - PrivilegeFunc RequestPrivilegeFunc - AcceptPermissionsFunc func(PluginPrivileges) (bool, error) - Args []string -} - -// SwarmUnlockKeyResponse contains the response for Engine API: -// GET /swarm/unlockkey -type SwarmUnlockKeyResponse struct { - // UnlockKey is the unlock key in ASCII-armored format. - UnlockKey string -} - -// PluginCreateOptions hold all options to plugin create. -type PluginCreateOptions struct { - RepoName string -} diff --git a/vendor/github.com/docker/docker/api/types/configs.go b/vendor/github.com/docker/docker/api/types/configs.go deleted file mode 100644 index 3dd133a3..00000000 --- a/vendor/github.com/docker/docker/api/types/configs.go +++ /dev/null @@ -1,66 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -import ( - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/network" - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -// configs holds structs used for internal communication between the -// frontend (such as an http server) and the backend (such as the -// docker daemon). - -// ContainerCreateConfig is the parameter set to ContainerCreate() -type ContainerCreateConfig struct { - Name string - Config *container.Config - HostConfig *container.HostConfig - NetworkingConfig *network.NetworkingConfig - Platform *specs.Platform - AdjustCPUShares bool -} - -// ContainerRmConfig holds arguments for the container remove -// operation. This struct is used to tell the backend what operations -// to perform. -type ContainerRmConfig struct { - ForceRemove, RemoveVolume, RemoveLink bool -} - -// ExecConfig is a small subset of the Config struct that holds the configuration -// for the exec feature of docker. -type ExecConfig struct { - User string // User that will run the command - Privileged bool // Is the container in privileged mode - Tty bool // Attach standard streams to a tty. - AttachStdin bool // Attach the standard input, makes possible user interaction - AttachStderr bool // Attach the standard error - AttachStdout bool // Attach the standard output - Detach bool // Execute in detach mode - DetachKeys string // Escape keys for detach - Env []string // Environment variables - WorkingDir string // Working directory - Cmd []string // Execution commands and args -} - -// PluginRmConfig holds arguments for plugin remove. -type PluginRmConfig struct { - ForceRemove bool -} - -// PluginEnableConfig holds arguments for plugin enable -type PluginEnableConfig struct { - Timeout int -} - -// PluginDisableConfig holds arguments for plugin disable. -type PluginDisableConfig struct { - ForceDisable bool -} - -// NetworkListConfig stores the options available for listing networks -type NetworkListConfig struct { - // TODO(@cpuguy83): naming is hard, this is pulled from what was being used in the router before moving here - Detailed bool - Verbose bool -} diff --git a/vendor/github.com/docker/docker/api/types/container/config.go b/vendor/github.com/docker/docker/api/types/container/config.go deleted file mode 100644 index f767195b..00000000 --- a/vendor/github.com/docker/docker/api/types/container/config.go +++ /dev/null @@ -1,69 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -import ( - "time" - - "github.com/docker/docker/api/types/strslice" - "github.com/docker/go-connections/nat" -) - -// MinimumDuration puts a minimum on user configured duration. -// This is to prevent API error on time unit. For example, API may -// set 3 as healthcheck interval with intention of 3 seconds, but -// Docker interprets it as 3 nanoseconds. -const MinimumDuration = 1 * time.Millisecond - -// HealthConfig holds configuration settings for the HEALTHCHECK feature. -type HealthConfig struct { - // Test is the test to perform to check that the container is healthy. - // An empty slice means to inherit the default. - // The options are: - // {} : inherit healthcheck - // {"NONE"} : disable healthcheck - // {"CMD", args...} : exec arguments directly - // {"CMD-SHELL", command} : run command with system's default shell - Test []string `json:",omitempty"` - - // Zero means to inherit. Durations are expressed as integer nanoseconds. - Interval time.Duration `json:",omitempty"` // Interval is the time to wait between checks. - Timeout time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung. - StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down. - - // Retries is the number of consecutive failures needed to consider a container as unhealthy. - // Zero means inherit. - Retries int `json:",omitempty"` -} - -// Config contains the configuration data about a container. -// It should hold only portable information about the container. -// Here, "portable" means "independent from the host we are running on". -// Non-portable information *should* appear in HostConfig. -// All fields added to this struct must be marked `omitempty` to keep getting -// predictable hashes from the old `v1Compatibility` configuration. -type Config struct { - Hostname string // Hostname - Domainname string // Domainname - User string // User that will run the command(s) inside the container, also support user:group - AttachStdin bool // Attach the standard input, makes possible user interaction - AttachStdout bool // Attach the standard output - AttachStderr bool // Attach the standard error - ExposedPorts nat.PortSet `json:",omitempty"` // List of exposed ports - Tty bool // Attach standard streams to a tty, including stdin if it is not closed. - OpenStdin bool // Open stdin - StdinOnce bool // If true, close stdin after the 1 attached client disconnects. - Env []string // List of environment variable to set in the container - Cmd strslice.StrSlice // Command to run when starting the container - Healthcheck *HealthConfig `json:",omitempty"` // Healthcheck describes how to check the container is healthy - ArgsEscaped bool `json:",omitempty"` // True if command is already escaped (meaning treat as a command line) (Windows specific). - Image string // Name of the image as it was passed by the operator (e.g. could be symbolic) - Volumes map[string]struct{} // List of volumes (mounts) used for the container - WorkingDir string // Current directory (PWD) in the command will be launched - Entrypoint strslice.StrSlice // Entrypoint to run when starting the container - NetworkDisabled bool `json:",omitempty"` // Is network disabled - MacAddress string `json:",omitempty"` // Mac Address of the container - OnBuild []string // ONBUILD metadata that were defined on the image Dockerfile - Labels map[string]string // List of labels set to this container - StopSignal string `json:",omitempty"` // Signal to stop a container - StopTimeout *int `json:",omitempty"` // Timeout (in seconds) to stop a container - Shell strslice.StrSlice `json:",omitempty"` // Shell for shell-form of RUN, CMD, ENTRYPOINT -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_changes.go b/vendor/github.com/docker/docker/api/types/container/container_changes.go deleted file mode 100644 index 16dd5019..00000000 --- a/vendor/github.com/docker/docker/api/types/container/container_changes.go +++ /dev/null @@ -1,20 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerChangeResponseItem change item in response to ContainerChanges operation -// swagger:model ContainerChangeResponseItem -type ContainerChangeResponseItem struct { - - // Kind of change - // Required: true - Kind uint8 `json:"Kind"` - - // Path to file that has changed - // Required: true - Path string `json:"Path"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_create.go b/vendor/github.com/docker/docker/api/types/container/container_create.go deleted file mode 100644 index d0c852f8..00000000 --- a/vendor/github.com/docker/docker/api/types/container/container_create.go +++ /dev/null @@ -1,20 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerCreateCreatedBody OK response to ContainerCreate operation -// swagger:model ContainerCreateCreatedBody -type ContainerCreateCreatedBody struct { - - // The ID of the created container - // Required: true - ID string `json:"Id"` - - // Warnings encountered when creating the container - // Required: true - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_top.go b/vendor/github.com/docker/docker/api/types/container/container_top.go deleted file mode 100644 index 63381da3..00000000 --- a/vendor/github.com/docker/docker/api/types/container/container_top.go +++ /dev/null @@ -1,22 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerTopOKBody OK response to ContainerTop operation -// swagger:model ContainerTopOKBody -type ContainerTopOKBody struct { - - // Each process running in the container, where each is process - // is an array of values corresponding to the titles. - // - // Required: true - Processes [][]string `json:"Processes"` - - // The ps column titles - // Required: true - Titles []string `json:"Titles"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_update.go b/vendor/github.com/docker/docker/api/types/container/container_update.go deleted file mode 100644 index c10f175e..00000000 --- a/vendor/github.com/docker/docker/api/types/container/container_update.go +++ /dev/null @@ -1,16 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerUpdateOKBody OK response to ContainerUpdate operation -// swagger:model ContainerUpdateOKBody -type ContainerUpdateOKBody struct { - - // warnings - // Required: true - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_wait.go b/vendor/github.com/docker/docker/api/types/container/container_wait.go deleted file mode 100644 index 49e05ae6..00000000 --- a/vendor/github.com/docker/docker/api/types/container/container_wait.go +++ /dev/null @@ -1,28 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerWaitOKBodyError container waiting error, if any -// swagger:model ContainerWaitOKBodyError -type ContainerWaitOKBodyError struct { - - // Details of an error - Message string `json:"Message,omitempty"` -} - -// ContainerWaitOKBody OK response to ContainerWait operation -// swagger:model ContainerWaitOKBody -type ContainerWaitOKBody struct { - - // error - // Required: true - Error *ContainerWaitOKBodyError `json:"Error"` - - // Exit code of the container - // Required: true - StatusCode int64 `json:"StatusCode"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/host_config.go b/vendor/github.com/docker/docker/api/types/container/host_config.go deleted file mode 100644 index 2d1cbaa9..00000000 --- a/vendor/github.com/docker/docker/api/types/container/host_config.go +++ /dev/null @@ -1,447 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -import ( - "strings" - - "github.com/docker/docker/api/types/blkiodev" - "github.com/docker/docker/api/types/mount" - "github.com/docker/docker/api/types/strslice" - "github.com/docker/go-connections/nat" - units "github.com/docker/go-units" -) - -// CgroupnsMode represents the cgroup namespace mode of the container -type CgroupnsMode string - -// IsPrivate indicates whether the container uses its own private cgroup namespace -func (c CgroupnsMode) IsPrivate() bool { - return c == "private" -} - -// IsHost indicates whether the container shares the host's cgroup namespace -func (c CgroupnsMode) IsHost() bool { - return c == "host" -} - -// IsEmpty indicates whether the container cgroup namespace mode is unset -func (c CgroupnsMode) IsEmpty() bool { - return c == "" -} - -// Valid indicates whether the cgroup namespace mode is valid -func (c CgroupnsMode) Valid() bool { - return c.IsEmpty() || c.IsPrivate() || c.IsHost() -} - -// Isolation represents the isolation technology of a container. The supported -// values are platform specific -type Isolation string - -// IsDefault indicates the default isolation technology of a container. On Linux this -// is the native driver. On Windows, this is a Windows Server Container. -func (i Isolation) IsDefault() bool { - return strings.ToLower(string(i)) == "default" || string(i) == "" -} - -// IsHyperV indicates the use of a Hyper-V partition for isolation -func (i Isolation) IsHyperV() bool { - return strings.ToLower(string(i)) == "hyperv" -} - -// IsProcess indicates the use of process isolation -func (i Isolation) IsProcess() bool { - return strings.ToLower(string(i)) == "process" -} - -const ( - // IsolationEmpty is unspecified (same behavior as default) - IsolationEmpty = Isolation("") - // IsolationDefault is the default isolation mode on current daemon - IsolationDefault = Isolation("default") - // IsolationProcess is process isolation mode - IsolationProcess = Isolation("process") - // IsolationHyperV is HyperV isolation mode - IsolationHyperV = Isolation("hyperv") -) - -// IpcMode represents the container ipc stack. -type IpcMode string - -// IsPrivate indicates whether the container uses its own private ipc namespace which can not be shared. -func (n IpcMode) IsPrivate() bool { - return n == "private" -} - -// IsHost indicates whether the container shares the host's ipc namespace. -func (n IpcMode) IsHost() bool { - return n == "host" -} - -// IsShareable indicates whether the container's ipc namespace can be shared with another container. -func (n IpcMode) IsShareable() bool { - return n == "shareable" -} - -// IsContainer indicates whether the container uses another container's ipc namespace. -func (n IpcMode) IsContainer() bool { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// IsNone indicates whether container IpcMode is set to "none". -func (n IpcMode) IsNone() bool { - return n == "none" -} - -// IsEmpty indicates whether container IpcMode is empty -func (n IpcMode) IsEmpty() bool { - return n == "" -} - -// Valid indicates whether the ipc mode is valid. -func (n IpcMode) Valid() bool { - return n.IsEmpty() || n.IsNone() || n.IsPrivate() || n.IsHost() || n.IsShareable() || n.IsContainer() -} - -// Container returns the name of the container ipc stack is going to be used. -func (n IpcMode) Container() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 && parts[0] == "container" { - return parts[1] - } - return "" -} - -// NetworkMode represents the container network stack. -type NetworkMode string - -// IsNone indicates whether container isn't using a network stack. -func (n NetworkMode) IsNone() bool { - return n == "none" -} - -// IsDefault indicates whether container uses the default network stack. -func (n NetworkMode) IsDefault() bool { - return n == "default" -} - -// IsPrivate indicates whether container uses its private network stack. -func (n NetworkMode) IsPrivate() bool { - return !(n.IsHost() || n.IsContainer()) -} - -// IsContainer indicates whether container uses a container network stack. -func (n NetworkMode) IsContainer() bool { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// ConnectedContainer is the id of the container which network this container is connected to. -func (n NetworkMode) ConnectedContainer() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" -} - -// UserDefined indicates user-created network -func (n NetworkMode) UserDefined() string { - if n.IsUserDefined() { - return string(n) - } - return "" -} - -// UsernsMode represents userns mode in the container. -type UsernsMode string - -// IsHost indicates whether the container uses the host's userns. -func (n UsernsMode) IsHost() bool { - return n == "host" -} - -// IsPrivate indicates whether the container uses the a private userns. -func (n UsernsMode) IsPrivate() bool { - return !(n.IsHost()) -} - -// Valid indicates whether the userns is valid. -func (n UsernsMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - default: - return false - } - return true -} - -// CgroupSpec represents the cgroup to use for the container. -type CgroupSpec string - -// IsContainer indicates whether the container is using another container cgroup -func (c CgroupSpec) IsContainer() bool { - parts := strings.SplitN(string(c), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// Valid indicates whether the cgroup spec is valid. -func (c CgroupSpec) Valid() bool { - return c.IsContainer() || c == "" -} - -// Container returns the name of the container whose cgroup will be used. -func (c CgroupSpec) Container() string { - parts := strings.SplitN(string(c), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" -} - -// UTSMode represents the UTS namespace of the container. -type UTSMode string - -// IsPrivate indicates whether the container uses its private UTS namespace. -func (n UTSMode) IsPrivate() bool { - return !(n.IsHost()) -} - -// IsHost indicates whether the container uses the host's UTS namespace. -func (n UTSMode) IsHost() bool { - return n == "host" -} - -// Valid indicates whether the UTS namespace is valid. -func (n UTSMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - default: - return false - } - return true -} - -// PidMode represents the pid namespace of the container. -type PidMode string - -// IsPrivate indicates whether the container uses its own new pid namespace. -func (n PidMode) IsPrivate() bool { - return !(n.IsHost() || n.IsContainer()) -} - -// IsHost indicates whether the container uses the host's pid namespace. -func (n PidMode) IsHost() bool { - return n == "host" -} - -// IsContainer indicates whether the container uses a container's pid namespace. -func (n PidMode) IsContainer() bool { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// Valid indicates whether the pid namespace is valid. -func (n PidMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - case "container": - if len(parts) != 2 || parts[1] == "" { - return false - } - default: - return false - } - return true -} - -// Container returns the name of the container whose pid namespace is going to be used. -func (n PidMode) Container() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" -} - -// DeviceRequest represents a request for devices from a device driver. -// Used by GPU device drivers. -type DeviceRequest struct { - Driver string // Name of device driver - Count int // Number of devices to request (-1 = All) - DeviceIDs []string // List of device IDs as recognizable by the device driver - Capabilities [][]string // An OR list of AND lists of device capabilities (e.g. "gpu") - Options map[string]string // Options to pass onto the device driver -} - -// DeviceMapping represents the device mapping between the host and the container. -type DeviceMapping struct { - PathOnHost string - PathInContainer string - CgroupPermissions string -} - -// RestartPolicy represents the restart policies of the container. -type RestartPolicy struct { - Name string - MaximumRetryCount int -} - -// IsNone indicates whether the container has the "no" restart policy. -// This means the container will not automatically restart when exiting. -func (rp *RestartPolicy) IsNone() bool { - return rp.Name == "no" || rp.Name == "" -} - -// IsAlways indicates whether the container has the "always" restart policy. -// This means the container will automatically restart regardless of the exit status. -func (rp *RestartPolicy) IsAlways() bool { - return rp.Name == "always" -} - -// IsOnFailure indicates whether the container has the "on-failure" restart policy. -// This means the container will automatically restart of exiting with a non-zero exit status. -func (rp *RestartPolicy) IsOnFailure() bool { - return rp.Name == "on-failure" -} - -// IsUnlessStopped indicates whether the container has the -// "unless-stopped" restart policy. This means the container will -// automatically restart unless user has put it to stopped state. -func (rp *RestartPolicy) IsUnlessStopped() bool { - return rp.Name == "unless-stopped" -} - -// IsSame compares two RestartPolicy to see if they are the same -func (rp *RestartPolicy) IsSame(tp *RestartPolicy) bool { - return rp.Name == tp.Name && rp.MaximumRetryCount == tp.MaximumRetryCount -} - -// LogMode is a type to define the available modes for logging -// These modes affect how logs are handled when log messages start piling up. -type LogMode string - -// Available logging modes -const ( - LogModeUnset = "" - LogModeBlocking LogMode = "blocking" - LogModeNonBlock LogMode = "non-blocking" -) - -// LogConfig represents the logging configuration of the container. -type LogConfig struct { - Type string - Config map[string]string -} - -// Resources contains container's resources (cgroups config, ulimits...) -type Resources struct { - // Applicable to all platforms - CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers) - Memory int64 // Memory limit (in bytes) - NanoCPUs int64 `json:"NanoCpus"` // CPU quota in units of 10-9 CPUs. - - // Applicable to UNIX platforms - CgroupParent string // Parent cgroup. - BlkioWeight uint16 // Block IO weight (relative weight vs. other containers) - BlkioWeightDevice []*blkiodev.WeightDevice - BlkioDeviceReadBps []*blkiodev.ThrottleDevice - BlkioDeviceWriteBps []*blkiodev.ThrottleDevice - BlkioDeviceReadIOps []*blkiodev.ThrottleDevice - BlkioDeviceWriteIOps []*blkiodev.ThrottleDevice - CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period - CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota - CPURealtimePeriod int64 `json:"CpuRealtimePeriod"` // CPU real-time period - CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime"` // CPU real-time runtime - CpusetCpus string // CpusetCpus 0-2, 0,1 - CpusetMems string // CpusetMems 0-2, 0,1 - Devices []DeviceMapping // List of devices to map inside the container - DeviceCgroupRules []string // List of rule to be added to the device cgroup - DeviceRequests []DeviceRequest // List of device requests for device drivers - KernelMemory int64 // Kernel memory limit (in bytes), Deprecated: kernel 5.4 deprecated kmem.limit_in_bytes - KernelMemoryTCP int64 // Hard limit for kernel TCP buffer memory (in bytes) - MemoryReservation int64 // Memory soft limit (in bytes) - MemorySwap int64 // Total memory usage (memory + swap); set `-1` to enable unlimited swap - MemorySwappiness *int64 // Tuning container memory swappiness behaviour - OomKillDisable *bool // Whether to disable OOM Killer or not - PidsLimit *int64 // Setting PIDs limit for a container; Set `0` or `-1` for unlimited, or `null` to not change. - Ulimits []*units.Ulimit // List of ulimits to be set in the container - - // Applicable to Windows - CPUCount int64 `json:"CpuCount"` // CPU count - CPUPercent int64 `json:"CpuPercent"` // CPU percent - IOMaximumIOps uint64 // Maximum IOps for the container system drive - IOMaximumBandwidth uint64 // Maximum IO in bytes per second for the container system drive -} - -// UpdateConfig holds the mutable attributes of a Container. -// Those attributes can be updated at runtime. -type UpdateConfig struct { - // Contains container's resources (cgroups, ulimits) - Resources - RestartPolicy RestartPolicy -} - -// HostConfig the non-portable Config structure of a container. -// Here, "non-portable" means "dependent of the host we are running on". -// Portable information *should* appear in Config. -type HostConfig struct { - // Applicable to all platforms - Binds []string // List of volume bindings for this container - ContainerIDFile string // File (path) where the containerId is written - LogConfig LogConfig // Configuration of the logs for this container - NetworkMode NetworkMode // Network mode to use for the container - PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host - RestartPolicy RestartPolicy // Restart policy to be used for the container - AutoRemove bool // Automatically remove container when it exits - VolumeDriver string // Name of the volume driver used to mount volumes - VolumesFrom []string // List of volumes to take from other container - - // Applicable to UNIX platforms - CapAdd strslice.StrSlice // List of kernel capabilities to add to the container - CapDrop strslice.StrSlice // List of kernel capabilities to remove from the container - CgroupnsMode CgroupnsMode // Cgroup namespace mode to use for the container - DNS []string `json:"Dns"` // List of DNS server to lookup - DNSOptions []string `json:"DnsOptions"` // List of DNSOption to look for - DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for - ExtraHosts []string // List of extra hosts - GroupAdd []string // List of additional groups that the container process will run as - IpcMode IpcMode // IPC namespace to use for the container - Cgroup CgroupSpec // Cgroup to use for the container - Links []string // List of links (in the name:alias form) - OomScoreAdj int // Container preference for OOM-killing - PidMode PidMode // PID namespace to use for the container - Privileged bool // Is the container in privileged mode - PublishAllPorts bool // Should docker publish all exposed port for the container - ReadonlyRootfs bool // Is the container root filesystem in read-only - SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux. - StorageOpt map[string]string `json:",omitempty"` // Storage driver options per container. - Tmpfs map[string]string `json:",omitempty"` // List of tmpfs (mounts) used for the container - UTSMode UTSMode // UTS namespace to use for the container - UsernsMode UsernsMode // The user namespace to use for the container - ShmSize int64 // Total shm memory usage - Sysctls map[string]string `json:",omitempty"` // List of Namespaced sysctls used for the container - Runtime string `json:",omitempty"` // Runtime to use with this container - - // Applicable to Windows - ConsoleSize [2]uint // Initial console size (height,width) - Isolation Isolation // Isolation technology of the container (e.g. default, hyperv) - - // Contains container's resources (cgroups, ulimits) - Resources - - // Mounts specs used by the container - Mounts []mount.Mount `json:",omitempty"` - - // MaskedPaths is the list of paths to be masked inside the container (this overrides the default set of paths) - MaskedPaths []string - - // ReadonlyPaths is the list of paths to be set as read-only inside the container (this overrides the default set of paths) - ReadonlyPaths []string - - // Run a custom init inside the container, if null, use the daemon's configured settings - Init *bool `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go deleted file mode 100644 index cf6fdf44..00000000 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go +++ /dev/null @@ -1,41 +0,0 @@ -// +build !windows - -package container // import "github.com/docker/docker/api/types/container" - -// IsValid indicates if an isolation technology is valid -func (i Isolation) IsValid() bool { - return i.IsDefault() -} - -// NetworkName returns the name of the network stack. -func (n NetworkMode) NetworkName() string { - if n.IsBridge() { - return "bridge" - } else if n.IsHost() { - return "host" - } else if n.IsContainer() { - return "container" - } else if n.IsNone() { - return "none" - } else if n.IsDefault() { - return "default" - } else if n.IsUserDefined() { - return n.UserDefined() - } - return "" -} - -// IsBridge indicates whether container uses the bridge network stack -func (n NetworkMode) IsBridge() bool { - return n == "bridge" -} - -// IsHost indicates whether container uses the host network stack. -func (n NetworkMode) IsHost() bool { - return n == "host" -} - -// IsUserDefined indicates user-created network -func (n NetworkMode) IsUserDefined() bool { - return !n.IsDefault() && !n.IsBridge() && !n.IsHost() && !n.IsNone() && !n.IsContainer() -} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go deleted file mode 100644 index 99f803a5..00000000 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go +++ /dev/null @@ -1,40 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// IsBridge indicates whether container uses the bridge network stack -// in windows it is given the name NAT -func (n NetworkMode) IsBridge() bool { - return n == "nat" -} - -// IsHost indicates whether container uses the host network stack. -// returns false as this is not supported by windows -func (n NetworkMode) IsHost() bool { - return false -} - -// IsUserDefined indicates user-created network -func (n NetworkMode) IsUserDefined() bool { - return !n.IsDefault() && !n.IsNone() && !n.IsBridge() && !n.IsContainer() -} - -// IsValid indicates if an isolation technology is valid -func (i Isolation) IsValid() bool { - return i.IsDefault() || i.IsHyperV() || i.IsProcess() -} - -// NetworkName returns the name of the network stack. -func (n NetworkMode) NetworkName() string { - if n.IsDefault() { - return "default" - } else if n.IsBridge() { - return "nat" - } else if n.IsNone() { - return "none" - } else if n.IsContainer() { - return "container" - } else if n.IsUserDefined() { - return n.UserDefined() - } - - return "" -} diff --git a/vendor/github.com/docker/docker/api/types/container/waitcondition.go b/vendor/github.com/docker/docker/api/types/container/waitcondition.go deleted file mode 100644 index cd8311f9..00000000 --- a/vendor/github.com/docker/docker/api/types/container/waitcondition.go +++ /dev/null @@ -1,22 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// WaitCondition is a type used to specify a container state for which -// to wait. -type WaitCondition string - -// Possible WaitCondition Values. -// -// WaitConditionNotRunning (default) is used to wait for any of the non-running -// states: "created", "exited", "dead", "removing", or "removed". -// -// WaitConditionNextExit is used to wait for the next time the state changes -// to a non-running state. If the state is currently "created" or "exited", -// this would cause Wait() to block until either the container runs and exits -// or is removed. -// -// WaitConditionRemoved is used to wait for the container to be removed. -const ( - WaitConditionNotRunning WaitCondition = "not-running" - WaitConditionNextExit WaitCondition = "next-exit" - WaitConditionRemoved WaitCondition = "removed" -) diff --git a/vendor/github.com/docker/docker/api/types/error_response.go b/vendor/github.com/docker/docker/api/types/error_response.go deleted file mode 100644 index dc942d9d..00000000 --- a/vendor/github.com/docker/docker/api/types/error_response.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ErrorResponse Represents an error. -// swagger:model ErrorResponse -type ErrorResponse struct { - - // The error message. - // Required: true - Message string `json:"message"` -} diff --git a/vendor/github.com/docker/docker/api/types/error_response_ext.go b/vendor/github.com/docker/docker/api/types/error_response_ext.go deleted file mode 100644 index f84f034c..00000000 --- a/vendor/github.com/docker/docker/api/types/error_response_ext.go +++ /dev/null @@ -1,6 +0,0 @@ -package types - -// Error returns the error message -func (e ErrorResponse) Error() string { - return e.Message -} diff --git a/vendor/github.com/docker/docker/api/types/events/events.go b/vendor/github.com/docker/docker/api/types/events/events.go deleted file mode 100644 index aa8fba81..00000000 --- a/vendor/github.com/docker/docker/api/types/events/events.go +++ /dev/null @@ -1,54 +0,0 @@ -package events // import "github.com/docker/docker/api/types/events" - -const ( - // BuilderEventType is the event type that the builder generates - BuilderEventType = "builder" - // ContainerEventType is the event type that containers generate - ContainerEventType = "container" - // DaemonEventType is the event type that daemon generate - DaemonEventType = "daemon" - // ImageEventType is the event type that images generate - ImageEventType = "image" - // NetworkEventType is the event type that networks generate - NetworkEventType = "network" - // PluginEventType is the event type that plugins generate - PluginEventType = "plugin" - // VolumeEventType is the event type that volumes generate - VolumeEventType = "volume" - // ServiceEventType is the event type that services generate - ServiceEventType = "service" - // NodeEventType is the event type that nodes generate - NodeEventType = "node" - // SecretEventType is the event type that secrets generate - SecretEventType = "secret" - // ConfigEventType is the event type that configs generate - ConfigEventType = "config" -) - -// Actor describes something that generates events, -// like a container, or a network, or a volume. -// It has a defined name and a set or attributes. -// The container attributes are its labels, other actors -// can generate these attributes from other properties. -type Actor struct { - ID string - Attributes map[string]string -} - -// Message represents the information an event contains -type Message struct { - // Deprecated information from JSONMessage. - // With data only in container events. - Status string `json:"status,omitempty"` - ID string `json:"id,omitempty"` - From string `json:"from,omitempty"` - - Type string - Action string - Actor Actor - // Engine events are local scope. Cluster events are swarm scope. - Scope string `json:"scope,omitempty"` - - Time int64 `json:"time,omitempty"` - TimeNano int64 `json:"timeNano,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/filters/parse.go b/vendor/github.com/docker/docker/api/types/filters/parse.go deleted file mode 100644 index 4bc91cff..00000000 --- a/vendor/github.com/docker/docker/api/types/filters/parse.go +++ /dev/null @@ -1,324 +0,0 @@ -/*Package filters provides tools for encoding a mapping of keys to a set of -multiple values. -*/ -package filters // import "github.com/docker/docker/api/types/filters" - -import ( - "encoding/json" - "regexp" - "strings" - - "github.com/docker/docker/api/types/versions" -) - -// Args stores a mapping of keys to a set of multiple values. -type Args struct { - fields map[string]map[string]bool -} - -// KeyValuePair are used to initialize a new Args -type KeyValuePair struct { - Key string - Value string -} - -// Arg creates a new KeyValuePair for initializing Args -func Arg(key, value string) KeyValuePair { - return KeyValuePair{Key: key, Value: value} -} - -// NewArgs returns a new Args populated with the initial args -func NewArgs(initialArgs ...KeyValuePair) Args { - args := Args{fields: map[string]map[string]bool{}} - for _, arg := range initialArgs { - args.Add(arg.Key, arg.Value) - } - return args -} - -// Keys returns all the keys in list of Args -func (args Args) Keys() []string { - keys := make([]string, 0, len(args.fields)) - for k := range args.fields { - keys = append(keys, k) - } - return keys -} - -// MarshalJSON returns a JSON byte representation of the Args -func (args Args) MarshalJSON() ([]byte, error) { - if len(args.fields) == 0 { - return []byte{}, nil - } - return json.Marshal(args.fields) -} - -// ToJSON returns the Args as a JSON encoded string -func ToJSON(a Args) (string, error) { - if a.Len() == 0 { - return "", nil - } - buf, err := json.Marshal(a) - return string(buf), err -} - -// ToParamWithVersion encodes Args as a JSON string. If version is less than 1.22 -// then the encoded format will use an older legacy format where the values are a -// list of strings, instead of a set. -// -// Deprecated: do not use in any new code; use ToJSON instead -func ToParamWithVersion(version string, a Args) (string, error) { - if a.Len() == 0 { - return "", nil - } - - if version != "" && versions.LessThan(version, "1.22") { - buf, err := json.Marshal(convertArgsToSlice(a.fields)) - return string(buf), err - } - - return ToJSON(a) -} - -// FromJSON decodes a JSON encoded string into Args -func FromJSON(p string) (Args, error) { - args := NewArgs() - - if p == "" { - return args, nil - } - - raw := []byte(p) - err := json.Unmarshal(raw, &args) - if err == nil { - return args, nil - } - - // Fallback to parsing arguments in the legacy slice format - deprecated := map[string][]string{} - if legacyErr := json.Unmarshal(raw, &deprecated); legacyErr != nil { - return args, err - } - - args.fields = deprecatedArgs(deprecated) - return args, nil -} - -// UnmarshalJSON populates the Args from JSON encode bytes -func (args Args) UnmarshalJSON(raw []byte) error { - if len(raw) == 0 { - return nil - } - return json.Unmarshal(raw, &args.fields) -} - -// Get returns the list of values associated with the key -func (args Args) Get(key string) []string { - values := args.fields[key] - if values == nil { - return make([]string, 0) - } - slice := make([]string, 0, len(values)) - for key := range values { - slice = append(slice, key) - } - return slice -} - -// Add a new value to the set of values -func (args Args) Add(key, value string) { - if _, ok := args.fields[key]; ok { - args.fields[key][value] = true - } else { - args.fields[key] = map[string]bool{value: true} - } -} - -// Del removes a value from the set -func (args Args) Del(key, value string) { - if _, ok := args.fields[key]; ok { - delete(args.fields[key], value) - if len(args.fields[key]) == 0 { - delete(args.fields, key) - } - } -} - -// Len returns the number of keys in the mapping -func (args Args) Len() int { - return len(args.fields) -} - -// MatchKVList returns true if all the pairs in sources exist as key=value -// pairs in the mapping at key, or if there are no values at key. -func (args Args) MatchKVList(key string, sources map[string]string) bool { - fieldValues := args.fields[key] - - // do not filter if there is no filter set or cannot determine filter - if len(fieldValues) == 0 { - return true - } - - if len(sources) == 0 { - return false - } - - for value := range fieldValues { - testKV := strings.SplitN(value, "=", 2) - - v, ok := sources[testKV[0]] - if !ok { - return false - } - if len(testKV) == 2 && testKV[1] != v { - return false - } - } - - return true -} - -// Match returns true if any of the values at key match the source string -func (args Args) Match(field, source string) bool { - if args.ExactMatch(field, source) { - return true - } - - fieldValues := args.fields[field] - for name2match := range fieldValues { - match, err := regexp.MatchString(name2match, source) - if err != nil { - continue - } - if match { - return true - } - } - return false -} - -// ExactMatch returns true if the source matches exactly one of the values. -func (args Args) ExactMatch(key, source string) bool { - fieldValues, ok := args.fields[key] - // do not filter if there is no filter set or cannot determine filter - if !ok || len(fieldValues) == 0 { - return true - } - - // try to match full name value to avoid O(N) regular expression matching - return fieldValues[source] -} - -// UniqueExactMatch returns true if there is only one value and the source -// matches exactly the value. -func (args Args) UniqueExactMatch(key, source string) bool { - fieldValues := args.fields[key] - // do not filter if there is no filter set or cannot determine filter - if len(fieldValues) == 0 { - return true - } - if len(args.fields[key]) != 1 { - return false - } - - // try to match full name value to avoid O(N) regular expression matching - return fieldValues[source] -} - -// FuzzyMatch returns true if the source matches exactly one value, or the -// source has one of the values as a prefix. -func (args Args) FuzzyMatch(key, source string) bool { - if args.ExactMatch(key, source) { - return true - } - - fieldValues := args.fields[key] - for prefix := range fieldValues { - if strings.HasPrefix(source, prefix) { - return true - } - } - return false -} - -// Contains returns true if the key exists in the mapping -func (args Args) Contains(field string) bool { - _, ok := args.fields[field] - return ok -} - -type invalidFilter string - -func (e invalidFilter) Error() string { - return "Invalid filter '" + string(e) + "'" -} - -func (invalidFilter) InvalidParameter() {} - -// Validate compared the set of accepted keys against the keys in the mapping. -// An error is returned if any mapping keys are not in the accepted set. -func (args Args) Validate(accepted map[string]bool) error { - for name := range args.fields { - if !accepted[name] { - return invalidFilter(name) - } - } - return nil -} - -// WalkValues iterates over the list of values for a key in the mapping and calls -// op() for each value. If op returns an error the iteration stops and the -// error is returned. -func (args Args) WalkValues(field string, op func(value string) error) error { - if _, ok := args.fields[field]; !ok { - return nil - } - for v := range args.fields[field] { - if err := op(v); err != nil { - return err - } - } - return nil -} - -// Clone returns a copy of args. -func (args Args) Clone() (newArgs Args) { - newArgs.fields = make(map[string]map[string]bool, len(args.fields)) - for k, m := range args.fields { - var mm map[string]bool - if m != nil { - mm = make(map[string]bool, len(m)) - for kk, v := range m { - mm[kk] = v - } - } - newArgs.fields[k] = mm - } - return newArgs -} - -func deprecatedArgs(d map[string][]string) map[string]map[string]bool { - m := map[string]map[string]bool{} - for k, v := range d { - values := map[string]bool{} - for _, vv := range v { - values[vv] = true - } - m[k] = values - } - return m -} - -func convertArgsToSlice(f map[string]map[string]bool) map[string][]string { - m := map[string][]string{} - for k, v := range f { - values := []string{} - for kk := range v { - if v[kk] { - values = append(values, kk) - } - } - m[k] = values - } - return m -} diff --git a/vendor/github.com/docker/docker/api/types/graph_driver_data.go b/vendor/github.com/docker/docker/api/types/graph_driver_data.go deleted file mode 100644 index 4d9bf1c6..00000000 --- a/vendor/github.com/docker/docker/api/types/graph_driver_data.go +++ /dev/null @@ -1,17 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// GraphDriverData Information about a container's graph driver. -// swagger:model GraphDriverData -type GraphDriverData struct { - - // data - // Required: true - Data map[string]string `json:"Data"` - - // name - // Required: true - Name string `json:"Name"` -} diff --git a/vendor/github.com/docker/docker/api/types/id_response.go b/vendor/github.com/docker/docker/api/types/id_response.go deleted file mode 100644 index 7592d2f8..00000000 --- a/vendor/github.com/docker/docker/api/types/id_response.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// IDResponse Response to an API call that returns just an Id -// swagger:model IdResponse -type IDResponse struct { - - // The id of the newly created object. - // Required: true - ID string `json:"Id"` -} diff --git a/vendor/github.com/docker/docker/api/types/image/image_history.go b/vendor/github.com/docker/docker/api/types/image/image_history.go deleted file mode 100644 index e302bb0a..00000000 --- a/vendor/github.com/docker/docker/api/types/image/image_history.go +++ /dev/null @@ -1,36 +0,0 @@ -package image // import "github.com/docker/docker/api/types/image" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// HistoryResponseItem individual image layer information in response to ImageHistory operation -// swagger:model HistoryResponseItem -type HistoryResponseItem struct { - - // comment - // Required: true - Comment string `json:"Comment"` - - // created - // Required: true - Created int64 `json:"Created"` - - // created by - // Required: true - CreatedBy string `json:"CreatedBy"` - - // Id - // Required: true - ID string `json:"Id"` - - // size - // Required: true - Size int64 `json:"Size"` - - // tags - // Required: true - Tags []string `json:"Tags"` -} diff --git a/vendor/github.com/docker/docker/api/types/image_delete_response_item.go b/vendor/github.com/docker/docker/api/types/image_delete_response_item.go deleted file mode 100644 index b9a65a0d..00000000 --- a/vendor/github.com/docker/docker/api/types/image_delete_response_item.go +++ /dev/null @@ -1,15 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ImageDeleteResponseItem image delete response item -// swagger:model ImageDeleteResponseItem -type ImageDeleteResponseItem struct { - - // The image ID of an image that was deleted - Deleted string `json:"Deleted,omitempty"` - - // The image ID of an image that was untagged - Untagged string `json:"Untagged,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/image_summary.go b/vendor/github.com/docker/docker/api/types/image_summary.go deleted file mode 100644 index e145b3dc..00000000 --- a/vendor/github.com/docker/docker/api/types/image_summary.go +++ /dev/null @@ -1,49 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ImageSummary image summary -// swagger:model ImageSummary -type ImageSummary struct { - - // containers - // Required: true - Containers int64 `json:"Containers"` - - // created - // Required: true - Created int64 `json:"Created"` - - // Id - // Required: true - ID string `json:"Id"` - - // labels - // Required: true - Labels map[string]string `json:"Labels"` - - // parent Id - // Required: true - ParentID string `json:"ParentId"` - - // repo digests - // Required: true - RepoDigests []string `json:"RepoDigests"` - - // repo tags - // Required: true - RepoTags []string `json:"RepoTags"` - - // shared size - // Required: true - SharedSize int64 `json:"SharedSize"` - - // size - // Required: true - Size int64 `json:"Size"` - - // virtual size - // Required: true - VirtualSize int64 `json:"VirtualSize"` -} diff --git a/vendor/github.com/docker/docker/api/types/mount/mount.go b/vendor/github.com/docker/docker/api/types/mount/mount.go deleted file mode 100644 index 443b8d07..00000000 --- a/vendor/github.com/docker/docker/api/types/mount/mount.go +++ /dev/null @@ -1,131 +0,0 @@ -package mount // import "github.com/docker/docker/api/types/mount" - -import ( - "os" -) - -// Type represents the type of a mount. -type Type string - -// Type constants -const ( - // TypeBind is the type for mounting host dir - TypeBind Type = "bind" - // TypeVolume is the type for remote storage volumes - TypeVolume Type = "volume" - // TypeTmpfs is the type for mounting tmpfs - TypeTmpfs Type = "tmpfs" - // TypeNamedPipe is the type for mounting Windows named pipes - TypeNamedPipe Type = "npipe" -) - -// Mount represents a mount (volume). -type Mount struct { - Type Type `json:",omitempty"` - // Source specifies the name of the mount. Depending on mount type, this - // may be a volume name or a host path, or even ignored. - // Source is not supported for tmpfs (must be an empty value) - Source string `json:",omitempty"` - Target string `json:",omitempty"` - ReadOnly bool `json:",omitempty"` - Consistency Consistency `json:",omitempty"` - - BindOptions *BindOptions `json:",omitempty"` - VolumeOptions *VolumeOptions `json:",omitempty"` - TmpfsOptions *TmpfsOptions `json:",omitempty"` -} - -// Propagation represents the propagation of a mount. -type Propagation string - -const ( - // PropagationRPrivate RPRIVATE - PropagationRPrivate Propagation = "rprivate" - // PropagationPrivate PRIVATE - PropagationPrivate Propagation = "private" - // PropagationRShared RSHARED - PropagationRShared Propagation = "rshared" - // PropagationShared SHARED - PropagationShared Propagation = "shared" - // PropagationRSlave RSLAVE - PropagationRSlave Propagation = "rslave" - // PropagationSlave SLAVE - PropagationSlave Propagation = "slave" -) - -// Propagations is the list of all valid mount propagations -var Propagations = []Propagation{ - PropagationRPrivate, - PropagationPrivate, - PropagationRShared, - PropagationShared, - PropagationRSlave, - PropagationSlave, -} - -// Consistency represents the consistency requirements of a mount. -type Consistency string - -const ( - // ConsistencyFull guarantees bind mount-like consistency - ConsistencyFull Consistency = "consistent" - // ConsistencyCached mounts can cache read data and FS structure - ConsistencyCached Consistency = "cached" - // ConsistencyDelegated mounts can cache read and written data and structure - ConsistencyDelegated Consistency = "delegated" - // ConsistencyDefault provides "consistent" behavior unless overridden - ConsistencyDefault Consistency = "default" -) - -// BindOptions defines options specific to mounts of type "bind". -type BindOptions struct { - Propagation Propagation `json:",omitempty"` - NonRecursive bool `json:",omitempty"` -} - -// VolumeOptions represents the options for a mount of type volume. -type VolumeOptions struct { - NoCopy bool `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - DriverConfig *Driver `json:",omitempty"` -} - -// Driver represents a volume driver. -type Driver struct { - Name string `json:",omitempty"` - Options map[string]string `json:",omitempty"` -} - -// TmpfsOptions defines options specific to mounts of type "tmpfs". -type TmpfsOptions struct { - // Size sets the size of the tmpfs, in bytes. - // - // This will be converted to an operating system specific value - // depending on the host. For example, on linux, it will be converted to - // use a 'k', 'm' or 'g' syntax. BSD, though not widely supported with - // docker, uses a straight byte value. - // - // Percentages are not supported. - SizeBytes int64 `json:",omitempty"` - // Mode of the tmpfs upon creation - Mode os.FileMode `json:",omitempty"` - - // TODO(stevvooe): There are several more tmpfs flags, specified in the - // daemon, that are accepted. Only the most basic are added for now. - // - // From https://github.com/moby/sys/blob/mount/v0.1.1/mount/flags.go#L47-L56 - // - // var validFlags = map[string]bool{ - // "": true, - // "size": true, X - // "mode": true, X - // "uid": true, - // "gid": true, - // "nr_inodes": true, - // "nr_blocks": true, - // "mpol": true, - // } - // - // Some of these may be straightforward to add, but others, such as - // uid/gid have implications in a clustered system. -} diff --git a/vendor/github.com/docker/docker/api/types/network/network.go b/vendor/github.com/docker/docker/api/types/network/network.go deleted file mode 100644 index 437b184c..00000000 --- a/vendor/github.com/docker/docker/api/types/network/network.go +++ /dev/null @@ -1,126 +0,0 @@ -package network // import "github.com/docker/docker/api/types/network" -import ( - "github.com/docker/docker/api/types/filters" -) - -// Address represents an IP address -type Address struct { - Addr string - PrefixLen int -} - -// IPAM represents IP Address Management -type IPAM struct { - Driver string - Options map[string]string // Per network IPAM driver options - Config []IPAMConfig -} - -// IPAMConfig represents IPAM configurations -type IPAMConfig struct { - Subnet string `json:",omitempty"` - IPRange string `json:",omitempty"` - Gateway string `json:",omitempty"` - AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` -} - -// EndpointIPAMConfig represents IPAM configurations for the endpoint -type EndpointIPAMConfig struct { - IPv4Address string `json:",omitempty"` - IPv6Address string `json:",omitempty"` - LinkLocalIPs []string `json:",omitempty"` -} - -// Copy makes a copy of the endpoint ipam config -func (cfg *EndpointIPAMConfig) Copy() *EndpointIPAMConfig { - cfgCopy := *cfg - cfgCopy.LinkLocalIPs = make([]string, 0, len(cfg.LinkLocalIPs)) - cfgCopy.LinkLocalIPs = append(cfgCopy.LinkLocalIPs, cfg.LinkLocalIPs...) - return &cfgCopy -} - -// PeerInfo represents one peer of an overlay network -type PeerInfo struct { - Name string - IP string -} - -// EndpointSettings stores the network endpoint details -type EndpointSettings struct { - // Configurations - IPAMConfig *EndpointIPAMConfig - Links []string - Aliases []string - // Operational data - NetworkID string - EndpointID string - Gateway string - IPAddress string - IPPrefixLen int - IPv6Gateway string - GlobalIPv6Address string - GlobalIPv6PrefixLen int - MacAddress string - DriverOpts map[string]string -} - -// Task carries the information about one backend task -type Task struct { - Name string - EndpointID string - EndpointIP string - Info map[string]string -} - -// ServiceInfo represents service parameters with the list of service's tasks -type ServiceInfo struct { - VIP string - Ports []string - LocalLBIndex int - Tasks []Task -} - -// Copy makes a deep copy of `EndpointSettings` -func (es *EndpointSettings) Copy() *EndpointSettings { - epCopy := *es - if es.IPAMConfig != nil { - epCopy.IPAMConfig = es.IPAMConfig.Copy() - } - - if es.Links != nil { - links := make([]string, 0, len(es.Links)) - epCopy.Links = append(links, es.Links...) - } - - if es.Aliases != nil { - aliases := make([]string, 0, len(es.Aliases)) - epCopy.Aliases = append(aliases, es.Aliases...) - } - return &epCopy -} - -// NetworkingConfig represents the container's networking configuration for each of its interfaces -// Carries the networking configs specified in the `docker run` and `docker network connect` commands -type NetworkingConfig struct { - EndpointsConfig map[string]*EndpointSettings // Endpoint configs for each connecting network -} - -// ConfigReference specifies the source which provides a network's configuration -type ConfigReference struct { - Network string -} - -var acceptedFilters = map[string]bool{ - "dangling": true, - "driver": true, - "id": true, - "label": true, - "name": true, - "scope": true, - "type": true, -} - -// ValidateFilters validates the list of filter args with the available filters. -func ValidateFilters(filter filters.Args) error { - return filter.Validate(acceptedFilters) -} diff --git a/vendor/github.com/docker/docker/api/types/plugin.go b/vendor/github.com/docker/docker/api/types/plugin.go deleted file mode 100644 index abae48b9..00000000 --- a/vendor/github.com/docker/docker/api/types/plugin.go +++ /dev/null @@ -1,203 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// Plugin A plugin for the Engine API -// swagger:model Plugin -type Plugin struct { - - // config - // Required: true - Config PluginConfig `json:"Config"` - - // True if the plugin is running. False if the plugin is not running, only installed. - // Required: true - Enabled bool `json:"Enabled"` - - // Id - ID string `json:"Id,omitempty"` - - // name - // Required: true - Name string `json:"Name"` - - // plugin remote reference used to push/pull the plugin - PluginReference string `json:"PluginReference,omitempty"` - - // settings - // Required: true - Settings PluginSettings `json:"Settings"` -} - -// PluginConfig The config of a plugin. -// swagger:model PluginConfig -type PluginConfig struct { - - // args - // Required: true - Args PluginConfigArgs `json:"Args"` - - // description - // Required: true - Description string `json:"Description"` - - // Docker Version used to create the plugin - DockerVersion string `json:"DockerVersion,omitempty"` - - // documentation - // Required: true - Documentation string `json:"Documentation"` - - // entrypoint - // Required: true - Entrypoint []string `json:"Entrypoint"` - - // env - // Required: true - Env []PluginEnv `json:"Env"` - - // interface - // Required: true - Interface PluginConfigInterface `json:"Interface"` - - // ipc host - // Required: true - IpcHost bool `json:"IpcHost"` - - // linux - // Required: true - Linux PluginConfigLinux `json:"Linux"` - - // mounts - // Required: true - Mounts []PluginMount `json:"Mounts"` - - // network - // Required: true - Network PluginConfigNetwork `json:"Network"` - - // pid host - // Required: true - PidHost bool `json:"PidHost"` - - // propagated mount - // Required: true - PropagatedMount string `json:"PropagatedMount"` - - // user - User PluginConfigUser `json:"User,omitempty"` - - // work dir - // Required: true - WorkDir string `json:"WorkDir"` - - // rootfs - Rootfs *PluginConfigRootfs `json:"rootfs,omitempty"` -} - -// PluginConfigArgs plugin config args -// swagger:model PluginConfigArgs -type PluginConfigArgs struct { - - // description - // Required: true - Description string `json:"Description"` - - // name - // Required: true - Name string `json:"Name"` - - // settable - // Required: true - Settable []string `json:"Settable"` - - // value - // Required: true - Value []string `json:"Value"` -} - -// PluginConfigInterface The interface between Docker and the plugin -// swagger:model PluginConfigInterface -type PluginConfigInterface struct { - - // Protocol to use for clients connecting to the plugin. - ProtocolScheme string `json:"ProtocolScheme,omitempty"` - - // socket - // Required: true - Socket string `json:"Socket"` - - // types - // Required: true - Types []PluginInterfaceType `json:"Types"` -} - -// PluginConfigLinux plugin config linux -// swagger:model PluginConfigLinux -type PluginConfigLinux struct { - - // allow all devices - // Required: true - AllowAllDevices bool `json:"AllowAllDevices"` - - // capabilities - // Required: true - Capabilities []string `json:"Capabilities"` - - // devices - // Required: true - Devices []PluginDevice `json:"Devices"` -} - -// PluginConfigNetwork plugin config network -// swagger:model PluginConfigNetwork -type PluginConfigNetwork struct { - - // type - // Required: true - Type string `json:"Type"` -} - -// PluginConfigRootfs plugin config rootfs -// swagger:model PluginConfigRootfs -type PluginConfigRootfs struct { - - // diff ids - DiffIds []string `json:"diff_ids"` - - // type - Type string `json:"type,omitempty"` -} - -// PluginConfigUser plugin config user -// swagger:model PluginConfigUser -type PluginConfigUser struct { - - // g ID - GID uint32 `json:"GID,omitempty"` - - // UID - UID uint32 `json:"UID,omitempty"` -} - -// PluginSettings Settings that can be modified by users. -// swagger:model PluginSettings -type PluginSettings struct { - - // args - // Required: true - Args []string `json:"Args"` - - // devices - // Required: true - Devices []PluginDevice `json:"Devices"` - - // env - // Required: true - Env []string `json:"Env"` - - // mounts - // Required: true - Mounts []PluginMount `json:"Mounts"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_device.go b/vendor/github.com/docker/docker/api/types/plugin_device.go deleted file mode 100644 index 56990106..00000000 --- a/vendor/github.com/docker/docker/api/types/plugin_device.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginDevice plugin device -// swagger:model PluginDevice -type PluginDevice struct { - - // description - // Required: true - Description string `json:"Description"` - - // name - // Required: true - Name string `json:"Name"` - - // path - // Required: true - Path *string `json:"Path"` - - // settable - // Required: true - Settable []string `json:"Settable"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_env.go b/vendor/github.com/docker/docker/api/types/plugin_env.go deleted file mode 100644 index 32962dc2..00000000 --- a/vendor/github.com/docker/docker/api/types/plugin_env.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginEnv plugin env -// swagger:model PluginEnv -type PluginEnv struct { - - // description - // Required: true - Description string `json:"Description"` - - // name - // Required: true - Name string `json:"Name"` - - // settable - // Required: true - Settable []string `json:"Settable"` - - // value - // Required: true - Value *string `json:"Value"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_interface_type.go b/vendor/github.com/docker/docker/api/types/plugin_interface_type.go deleted file mode 100644 index c82f204e..00000000 --- a/vendor/github.com/docker/docker/api/types/plugin_interface_type.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginInterfaceType plugin interface type -// swagger:model PluginInterfaceType -type PluginInterfaceType struct { - - // capability - // Required: true - Capability string `json:"Capability"` - - // prefix - // Required: true - Prefix string `json:"Prefix"` - - // version - // Required: true - Version string `json:"Version"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_mount.go b/vendor/github.com/docker/docker/api/types/plugin_mount.go deleted file mode 100644 index 5c031cf8..00000000 --- a/vendor/github.com/docker/docker/api/types/plugin_mount.go +++ /dev/null @@ -1,37 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginMount plugin mount -// swagger:model PluginMount -type PluginMount struct { - - // description - // Required: true - Description string `json:"Description"` - - // destination - // Required: true - Destination string `json:"Destination"` - - // name - // Required: true - Name string `json:"Name"` - - // options - // Required: true - Options []string `json:"Options"` - - // settable - // Required: true - Settable []string `json:"Settable"` - - // source - // Required: true - Source *string `json:"Source"` - - // type - // Required: true - Type string `json:"Type"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_responses.go b/vendor/github.com/docker/docker/api/types/plugin_responses.go deleted file mode 100644 index 60d1fb5a..00000000 --- a/vendor/github.com/docker/docker/api/types/plugin_responses.go +++ /dev/null @@ -1,71 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -import ( - "encoding/json" - "fmt" - "sort" -) - -// PluginsListResponse contains the response for the Engine API -type PluginsListResponse []*Plugin - -// UnmarshalJSON implements json.Unmarshaler for PluginInterfaceType -func (t *PluginInterfaceType) UnmarshalJSON(p []byte) error { - versionIndex := len(p) - prefixIndex := 0 - if len(p) < 2 || p[0] != '"' || p[len(p)-1] != '"' { - return fmt.Errorf("%q is not a plugin interface type", p) - } - p = p[1 : len(p)-1] -loop: - for i, b := range p { - switch b { - case '.': - prefixIndex = i - case '/': - versionIndex = i - break loop - } - } - t.Prefix = string(p[:prefixIndex]) - t.Capability = string(p[prefixIndex+1 : versionIndex]) - if versionIndex < len(p) { - t.Version = string(p[versionIndex+1:]) - } - return nil -} - -// MarshalJSON implements json.Marshaler for PluginInterfaceType -func (t *PluginInterfaceType) MarshalJSON() ([]byte, error) { - return json.Marshal(t.String()) -} - -// String implements fmt.Stringer for PluginInterfaceType -func (t PluginInterfaceType) String() string { - return fmt.Sprintf("%s.%s/%s", t.Prefix, t.Capability, t.Version) -} - -// PluginPrivilege describes a permission the user has to accept -// upon installing a plugin. -type PluginPrivilege struct { - Name string - Description string - Value []string -} - -// PluginPrivileges is a list of PluginPrivilege -type PluginPrivileges []PluginPrivilege - -func (s PluginPrivileges) Len() int { - return len(s) -} - -func (s PluginPrivileges) Less(i, j int) bool { - return s[i].Name < s[j].Name -} - -func (s PluginPrivileges) Swap(i, j int) { - sort.Strings(s[i].Value) - sort.Strings(s[j].Value) - s[i], s[j] = s[j], s[i] -} diff --git a/vendor/github.com/docker/docker/api/types/port.go b/vendor/github.com/docker/docker/api/types/port.go deleted file mode 100644 index d9123474..00000000 --- a/vendor/github.com/docker/docker/api/types/port.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// Port An open port on a container -// swagger:model Port -type Port struct { - - // Host IP address that the container's port is mapped to - IP string `json:"IP,omitempty"` - - // Port on the container - // Required: true - PrivatePort uint16 `json:"PrivatePort"` - - // Port exposed on the host - PublicPort uint16 `json:"PublicPort,omitempty"` - - // type - // Required: true - Type string `json:"Type"` -} diff --git a/vendor/github.com/docker/docker/api/types/registry/authenticate.go b/vendor/github.com/docker/docker/api/types/registry/authenticate.go deleted file mode 100644 index f0a2113e..00000000 --- a/vendor/github.com/docker/docker/api/types/registry/authenticate.go +++ /dev/null @@ -1,21 +0,0 @@ -package registry // import "github.com/docker/docker/api/types/registry" - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// AuthenticateOKBody authenticate o k body -// swagger:model AuthenticateOKBody -type AuthenticateOKBody struct { - - // An opaque token used to authenticate a user after a successful login - // Required: true - IdentityToken string `json:"IdentityToken"` - - // The status of the authentication - // Required: true - Status string `json:"Status"` -} diff --git a/vendor/github.com/docker/docker/api/types/registry/registry.go b/vendor/github.com/docker/docker/api/types/registry/registry.go deleted file mode 100644 index 53e47084..00000000 --- a/vendor/github.com/docker/docker/api/types/registry/registry.go +++ /dev/null @@ -1,119 +0,0 @@ -package registry // import "github.com/docker/docker/api/types/registry" - -import ( - "encoding/json" - "net" - - v1 "github.com/opencontainers/image-spec/specs-go/v1" -) - -// ServiceConfig stores daemon registry services configuration. -type ServiceConfig struct { - AllowNondistributableArtifactsCIDRs []*NetIPNet - AllowNondistributableArtifactsHostnames []string - InsecureRegistryCIDRs []*NetIPNet `json:"InsecureRegistryCIDRs"` - IndexConfigs map[string]*IndexInfo `json:"IndexConfigs"` - Mirrors []string -} - -// NetIPNet is the net.IPNet type, which can be marshalled and -// unmarshalled to JSON -type NetIPNet net.IPNet - -// String returns the CIDR notation of ipnet -func (ipnet *NetIPNet) String() string { - return (*net.IPNet)(ipnet).String() -} - -// MarshalJSON returns the JSON representation of the IPNet -func (ipnet *NetIPNet) MarshalJSON() ([]byte, error) { - return json.Marshal((*net.IPNet)(ipnet).String()) -} - -// UnmarshalJSON sets the IPNet from a byte array of JSON -func (ipnet *NetIPNet) UnmarshalJSON(b []byte) (err error) { - var ipnetStr string - if err = json.Unmarshal(b, &ipnetStr); err == nil { - var cidr *net.IPNet - if _, cidr, err = net.ParseCIDR(ipnetStr); err == nil { - *ipnet = NetIPNet(*cidr) - } - } - return -} - -// IndexInfo contains information about a registry -// -// RepositoryInfo Examples: -// { -// "Index" : { -// "Name" : "docker.io", -// "Mirrors" : ["https://registry-2.docker.io/v1/", "https://registry-3.docker.io/v1/"], -// "Secure" : true, -// "Official" : true, -// }, -// "RemoteName" : "library/debian", -// "LocalName" : "debian", -// "CanonicalName" : "docker.io/debian" -// "Official" : true, -// } -// -// { -// "Index" : { -// "Name" : "127.0.0.1:5000", -// "Mirrors" : [], -// "Secure" : false, -// "Official" : false, -// }, -// "RemoteName" : "user/repo", -// "LocalName" : "127.0.0.1:5000/user/repo", -// "CanonicalName" : "127.0.0.1:5000/user/repo", -// "Official" : false, -// } -type IndexInfo struct { - // Name is the name of the registry, such as "docker.io" - Name string - // Mirrors is a list of mirrors, expressed as URIs - Mirrors []string - // Secure is set to false if the registry is part of the list of - // insecure registries. Insecure registries accept HTTP and/or accept - // HTTPS with certificates from unknown CAs. - Secure bool - // Official indicates whether this is an official registry - Official bool -} - -// SearchResult describes a search result returned from a registry -type SearchResult struct { - // StarCount indicates the number of stars this repository has - StarCount int `json:"star_count"` - // IsOfficial is true if the result is from an official repository. - IsOfficial bool `json:"is_official"` - // Name is the name of the repository - Name string `json:"name"` - // IsAutomated indicates whether the result is automated - IsAutomated bool `json:"is_automated"` - // Description is a textual description of the repository - Description string `json:"description"` -} - -// SearchResults lists a collection search results returned from a registry -type SearchResults struct { - // Query contains the query string that generated the search results - Query string `json:"query"` - // NumResults indicates the number of results the query returned - NumResults int `json:"num_results"` - // Results is a slice containing the actual results for the search - Results []SearchResult `json:"results"` -} - -// DistributionInspect describes the result obtained from contacting the -// registry to retrieve image metadata -type DistributionInspect struct { - // Descriptor contains information about the manifest, including - // the content addressable digest - Descriptor v1.Descriptor - // Platforms contains the list of platforms supported by the image, - // obtained by parsing the manifest - Platforms []v1.Platform -} diff --git a/vendor/github.com/docker/docker/api/types/service_update_response.go b/vendor/github.com/docker/docker/api/types/service_update_response.go deleted file mode 100644 index 74ea64b1..00000000 --- a/vendor/github.com/docker/docker/api/types/service_update_response.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ServiceUpdateResponse service update response -// swagger:model ServiceUpdateResponse -type ServiceUpdateResponse struct { - - // Optional warning messages - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/stats.go b/vendor/github.com/docker/docker/api/types/stats.go deleted file mode 100644 index 20daebed..00000000 --- a/vendor/github.com/docker/docker/api/types/stats.go +++ /dev/null @@ -1,181 +0,0 @@ -// Package types is used for API stability in the types and response to the -// consumers of the API stats endpoint. -package types // import "github.com/docker/docker/api/types" - -import "time" - -// ThrottlingData stores CPU throttling stats of one running container. -// Not used on Windows. -type ThrottlingData struct { - // Number of periods with throttling active - Periods uint64 `json:"periods"` - // Number of periods when the container hits its throttling limit. - ThrottledPeriods uint64 `json:"throttled_periods"` - // Aggregate time the container was throttled for in nanoseconds. - ThrottledTime uint64 `json:"throttled_time"` -} - -// CPUUsage stores All CPU stats aggregated since container inception. -type CPUUsage struct { - // Total CPU time consumed. - // Units: nanoseconds (Linux) - // Units: 100's of nanoseconds (Windows) - TotalUsage uint64 `json:"total_usage"` - - // Total CPU time consumed per core (Linux). Not used on Windows. - // Units: nanoseconds. - PercpuUsage []uint64 `json:"percpu_usage,omitempty"` - - // Time spent by tasks of the cgroup in kernel mode (Linux). - // Time spent by all container processes in kernel mode (Windows). - // Units: nanoseconds (Linux). - // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers. - UsageInKernelmode uint64 `json:"usage_in_kernelmode"` - - // Time spent by tasks of the cgroup in user mode (Linux). - // Time spent by all container processes in user mode (Windows). - // Units: nanoseconds (Linux). - // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers - UsageInUsermode uint64 `json:"usage_in_usermode"` -} - -// CPUStats aggregates and wraps all CPU related info of container -type CPUStats struct { - // CPU Usage. Linux and Windows. - CPUUsage CPUUsage `json:"cpu_usage"` - - // System Usage. Linux only. - SystemUsage uint64 `json:"system_cpu_usage,omitempty"` - - // Online CPUs. Linux only. - OnlineCPUs uint32 `json:"online_cpus,omitempty"` - - // Throttling Data. Linux only. - ThrottlingData ThrottlingData `json:"throttling_data,omitempty"` -} - -// MemoryStats aggregates all memory stats since container inception on Linux. -// Windows returns stats for commit and private working set only. -type MemoryStats struct { - // Linux Memory Stats - - // current res_counter usage for memory - Usage uint64 `json:"usage,omitempty"` - // maximum usage ever recorded. - MaxUsage uint64 `json:"max_usage,omitempty"` - // TODO(vishh): Export these as stronger types. - // all the stats exported via memory.stat. - Stats map[string]uint64 `json:"stats,omitempty"` - // number of times memory usage hits limits. - Failcnt uint64 `json:"failcnt,omitempty"` - Limit uint64 `json:"limit,omitempty"` - - // Windows Memory Stats - // See https://technet.microsoft.com/en-us/magazine/ff382715.aspx - - // committed bytes - Commit uint64 `json:"commitbytes,omitempty"` - // peak committed bytes - CommitPeak uint64 `json:"commitpeakbytes,omitempty"` - // private working set - PrivateWorkingSet uint64 `json:"privateworkingset,omitempty"` -} - -// BlkioStatEntry is one small entity to store a piece of Blkio stats -// Not used on Windows. -type BlkioStatEntry struct { - Major uint64 `json:"major"` - Minor uint64 `json:"minor"` - Op string `json:"op"` - Value uint64 `json:"value"` -} - -// BlkioStats stores All IO service stats for data read and write. -// This is a Linux specific structure as the differences between expressing -// block I/O on Windows and Linux are sufficiently significant to make -// little sense attempting to morph into a combined structure. -type BlkioStats struct { - // number of bytes transferred to and from the block device - IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"` - IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive"` - IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive"` - IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive"` - IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive"` - IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive"` - IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive"` - SectorsRecursive []BlkioStatEntry `json:"sectors_recursive"` -} - -// StorageStats is the disk I/O stats for read/write on Windows. -type StorageStats struct { - ReadCountNormalized uint64 `json:"read_count_normalized,omitempty"` - ReadSizeBytes uint64 `json:"read_size_bytes,omitempty"` - WriteCountNormalized uint64 `json:"write_count_normalized,omitempty"` - WriteSizeBytes uint64 `json:"write_size_bytes,omitempty"` -} - -// NetworkStats aggregates the network stats of one container -type NetworkStats struct { - // Bytes received. Windows and Linux. - RxBytes uint64 `json:"rx_bytes"` - // Packets received. Windows and Linux. - RxPackets uint64 `json:"rx_packets"` - // Received errors. Not used on Windows. Note that we don't `omitempty` this - // field as it is expected in the >=v1.21 API stats structure. - RxErrors uint64 `json:"rx_errors"` - // Incoming packets dropped. Windows and Linux. - RxDropped uint64 `json:"rx_dropped"` - // Bytes sent. Windows and Linux. - TxBytes uint64 `json:"tx_bytes"` - // Packets sent. Windows and Linux. - TxPackets uint64 `json:"tx_packets"` - // Sent errors. Not used on Windows. Note that we don't `omitempty` this - // field as it is expected in the >=v1.21 API stats structure. - TxErrors uint64 `json:"tx_errors"` - // Outgoing packets dropped. Windows and Linux. - TxDropped uint64 `json:"tx_dropped"` - // Endpoint ID. Not used on Linux. - EndpointID string `json:"endpoint_id,omitempty"` - // Instance ID. Not used on Linux. - InstanceID string `json:"instance_id,omitempty"` -} - -// PidsStats contains the stats of a container's pids -type PidsStats struct { - // Current is the number of pids in the cgroup - Current uint64 `json:"current,omitempty"` - // Limit is the hard limit on the number of pids in the cgroup. - // A "Limit" of 0 means that there is no limit. - Limit uint64 `json:"limit,omitempty"` -} - -// Stats is Ultimate struct aggregating all types of stats of one container -type Stats struct { - // Common stats - Read time.Time `json:"read"` - PreRead time.Time `json:"preread"` - - // Linux specific stats, not populated on Windows. - PidsStats PidsStats `json:"pids_stats,omitempty"` - BlkioStats BlkioStats `json:"blkio_stats,omitempty"` - - // Windows specific stats, not populated on Linux. - NumProcs uint32 `json:"num_procs"` - StorageStats StorageStats `json:"storage_stats,omitempty"` - - // Shared stats - CPUStats CPUStats `json:"cpu_stats,omitempty"` - PreCPUStats CPUStats `json:"precpu_stats,omitempty"` // "Pre"="Previous" - MemoryStats MemoryStats `json:"memory_stats,omitempty"` -} - -// StatsJSON is newly used Networks -type StatsJSON struct { - Stats - - Name string `json:"name,omitempty"` - ID string `json:"id,omitempty"` - - // Networks request version >=1.21 - Networks map[string]NetworkStats `json:"networks,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/strslice/strslice.go b/vendor/github.com/docker/docker/api/types/strslice/strslice.go deleted file mode 100644 index 82921ceb..00000000 --- a/vendor/github.com/docker/docker/api/types/strslice/strslice.go +++ /dev/null @@ -1,30 +0,0 @@ -package strslice // import "github.com/docker/docker/api/types/strslice" - -import "encoding/json" - -// StrSlice represents a string or an array of strings. -// We need to override the json decoder to accept both options. -type StrSlice []string - -// UnmarshalJSON decodes the byte slice whether it's a string or an array of -// strings. This method is needed to implement json.Unmarshaler. -func (e *StrSlice) UnmarshalJSON(b []byte) error { - if len(b) == 0 { - // With no input, we preserve the existing value by returning nil and - // leaving the target alone. This allows defining default values for - // the type. - return nil - } - - p := make([]string, 0, 1) - if err := json.Unmarshal(b, &p); err != nil { - var s string - if err := json.Unmarshal(b, &s); err != nil { - return err - } - p = append(p, s) - } - - *e = p - return nil -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/common.go b/vendor/github.com/docker/docker/api/types/swarm/common.go deleted file mode 100644 index ef020f45..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/common.go +++ /dev/null @@ -1,40 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import "time" - -// Version represents the internal object version. -type Version struct { - Index uint64 `json:",omitempty"` -} - -// Meta is a base object inherited by most of the other once. -type Meta struct { - Version Version `json:",omitempty"` - CreatedAt time.Time `json:",omitempty"` - UpdatedAt time.Time `json:",omitempty"` -} - -// Annotations represents how to describe an object. -type Annotations struct { - Name string `json:",omitempty"` - Labels map[string]string `json:"Labels"` -} - -// Driver represents a driver (network, logging, secrets backend). -type Driver struct { - Name string `json:",omitempty"` - Options map[string]string `json:",omitempty"` -} - -// TLSInfo represents the TLS information about what CA certificate is trusted, -// and who the issuer for a TLS certificate is -type TLSInfo struct { - // TrustRoot is the trusted CA root certificate in PEM format - TrustRoot string `json:",omitempty"` - - // CertIssuer is the raw subject bytes of the issuer - CertIssuerSubject []byte `json:",omitempty"` - - // CertIssuerPublicKey is the raw public key bytes of the issuer - CertIssuerPublicKey []byte `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/config.go b/vendor/github.com/docker/docker/api/types/swarm/config.go deleted file mode 100644 index 16202ccc..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/config.go +++ /dev/null @@ -1,40 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import "os" - -// Config represents a config. -type Config struct { - ID string - Meta - Spec ConfigSpec -} - -// ConfigSpec represents a config specification from a config in swarm -type ConfigSpec struct { - Annotations - Data []byte `json:",omitempty"` - - // Templating controls whether and how to evaluate the config payload as - // a template. If it is not set, no templating is used. - Templating *Driver `json:",omitempty"` -} - -// ConfigReferenceFileTarget is a file target in a config reference -type ConfigReferenceFileTarget struct { - Name string - UID string - GID string - Mode os.FileMode -} - -// ConfigReferenceRuntimeTarget is a target for a config specifying that it -// isn't mounted into the container but instead has some other purpose. -type ConfigReferenceRuntimeTarget struct{} - -// ConfigReference is a reference to a config in swarm -type ConfigReference struct { - File *ConfigReferenceFileTarget `json:",omitempty"` - Runtime *ConfigReferenceRuntimeTarget `json:",omitempty"` - ConfigID string - ConfigName string -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/container.go b/vendor/github.com/docker/docker/api/types/swarm/container.go deleted file mode 100644 index af5e1c0b..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/container.go +++ /dev/null @@ -1,80 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import ( - "time" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/mount" - "github.com/docker/go-units" -) - -// DNSConfig specifies DNS related configurations in resolver configuration file (resolv.conf) -// Detailed documentation is available in: -// http://man7.org/linux/man-pages/man5/resolv.conf.5.html -// `nameserver`, `search`, `options` have been supported. -// TODO: `domain` is not supported yet. -type DNSConfig struct { - // Nameservers specifies the IP addresses of the name servers - Nameservers []string `json:",omitempty"` - // Search specifies the search list for host-name lookup - Search []string `json:",omitempty"` - // Options allows certain internal resolver variables to be modified - Options []string `json:",omitempty"` -} - -// SELinuxContext contains the SELinux labels of the container. -type SELinuxContext struct { - Disable bool - - User string - Role string - Type string - Level string -} - -// CredentialSpec for managed service account (Windows only) -type CredentialSpec struct { - Config string - File string - Registry string -} - -// Privileges defines the security options for the container. -type Privileges struct { - CredentialSpec *CredentialSpec - SELinuxContext *SELinuxContext -} - -// ContainerSpec represents the spec of a container. -type ContainerSpec struct { - Image string `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - Command []string `json:",omitempty"` - Args []string `json:",omitempty"` - Hostname string `json:",omitempty"` - Env []string `json:",omitempty"` - Dir string `json:",omitempty"` - User string `json:",omitempty"` - Groups []string `json:",omitempty"` - Privileges *Privileges `json:",omitempty"` - Init *bool `json:",omitempty"` - StopSignal string `json:",omitempty"` - TTY bool `json:",omitempty"` - OpenStdin bool `json:",omitempty"` - ReadOnly bool `json:",omitempty"` - Mounts []mount.Mount `json:",omitempty"` - StopGracePeriod *time.Duration `json:",omitempty"` - Healthcheck *container.HealthConfig `json:",omitempty"` - // The format of extra hosts on swarmkit is specified in: - // http://man7.org/linux/man-pages/man5/hosts.5.html - // IP_address canonical_hostname [aliases...] - Hosts []string `json:",omitempty"` - DNSConfig *DNSConfig `json:",omitempty"` - Secrets []*SecretReference `json:",omitempty"` - Configs []*ConfigReference `json:",omitempty"` - Isolation container.Isolation `json:",omitempty"` - Sysctls map[string]string `json:",omitempty"` - CapabilityAdd []string `json:",omitempty"` - CapabilityDrop []string `json:",omitempty"` - Ulimits []*units.Ulimit `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/network.go b/vendor/github.com/docker/docker/api/types/swarm/network.go deleted file mode 100644 index 98ef3284..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/network.go +++ /dev/null @@ -1,121 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import ( - "github.com/docker/docker/api/types/network" -) - -// Endpoint represents an endpoint. -type Endpoint struct { - Spec EndpointSpec `json:",omitempty"` - Ports []PortConfig `json:",omitempty"` - VirtualIPs []EndpointVirtualIP `json:",omitempty"` -} - -// EndpointSpec represents the spec of an endpoint. -type EndpointSpec struct { - Mode ResolutionMode `json:",omitempty"` - Ports []PortConfig `json:",omitempty"` -} - -// ResolutionMode represents a resolution mode. -type ResolutionMode string - -const ( - // ResolutionModeVIP VIP - ResolutionModeVIP ResolutionMode = "vip" - // ResolutionModeDNSRR DNSRR - ResolutionModeDNSRR ResolutionMode = "dnsrr" -) - -// PortConfig represents the config of a port. -type PortConfig struct { - Name string `json:",omitempty"` - Protocol PortConfigProtocol `json:",omitempty"` - // TargetPort is the port inside the container - TargetPort uint32 `json:",omitempty"` - // PublishedPort is the port on the swarm hosts - PublishedPort uint32 `json:",omitempty"` - // PublishMode is the mode in which port is published - PublishMode PortConfigPublishMode `json:",omitempty"` -} - -// PortConfigPublishMode represents the mode in which the port is to -// be published. -type PortConfigPublishMode string - -const ( - // PortConfigPublishModeIngress is used for ports published - // for ingress load balancing using routing mesh. - PortConfigPublishModeIngress PortConfigPublishMode = "ingress" - // PortConfigPublishModeHost is used for ports published - // for direct host level access on the host where the task is running. - PortConfigPublishModeHost PortConfigPublishMode = "host" -) - -// PortConfigProtocol represents the protocol of a port. -type PortConfigProtocol string - -const ( - // TODO(stevvooe): These should be used generally, not just for PortConfig. - - // PortConfigProtocolTCP TCP - PortConfigProtocolTCP PortConfigProtocol = "tcp" - // PortConfigProtocolUDP UDP - PortConfigProtocolUDP PortConfigProtocol = "udp" - // PortConfigProtocolSCTP SCTP - PortConfigProtocolSCTP PortConfigProtocol = "sctp" -) - -// EndpointVirtualIP represents the virtual ip of a port. -type EndpointVirtualIP struct { - NetworkID string `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// Network represents a network. -type Network struct { - ID string - Meta - Spec NetworkSpec `json:",omitempty"` - DriverState Driver `json:",omitempty"` - IPAMOptions *IPAMOptions `json:",omitempty"` -} - -// NetworkSpec represents the spec of a network. -type NetworkSpec struct { - Annotations - DriverConfiguration *Driver `json:",omitempty"` - IPv6Enabled bool `json:",omitempty"` - Internal bool `json:",omitempty"` - Attachable bool `json:",omitempty"` - Ingress bool `json:",omitempty"` - IPAMOptions *IPAMOptions `json:",omitempty"` - ConfigFrom *network.ConfigReference `json:",omitempty"` - Scope string `json:",omitempty"` -} - -// NetworkAttachmentConfig represents the configuration of a network attachment. -type NetworkAttachmentConfig struct { - Target string `json:",omitempty"` - Aliases []string `json:",omitempty"` - DriverOpts map[string]string `json:",omitempty"` -} - -// NetworkAttachment represents a network attachment. -type NetworkAttachment struct { - Network Network `json:",omitempty"` - Addresses []string `json:",omitempty"` -} - -// IPAMOptions represents ipam options. -type IPAMOptions struct { - Driver Driver `json:",omitempty"` - Configs []IPAMConfig `json:",omitempty"` -} - -// IPAMConfig represents ipam configuration. -type IPAMConfig struct { - Subnet string `json:",omitempty"` - Range string `json:",omitempty"` - Gateway string `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/node.go b/vendor/github.com/docker/docker/api/types/swarm/node.go deleted file mode 100644 index 1e30f5fa..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/node.go +++ /dev/null @@ -1,115 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -// Node represents a node. -type Node struct { - ID string - Meta - // Spec defines the desired state of the node as specified by the user. - // The system will honor this and will *never* modify it. - Spec NodeSpec `json:",omitempty"` - // Description encapsulates the properties of the Node as reported by the - // agent. - Description NodeDescription `json:",omitempty"` - // Status provides the current status of the node, as seen by the manager. - Status NodeStatus `json:",omitempty"` - // ManagerStatus provides the current status of the node's manager - // component, if the node is a manager. - ManagerStatus *ManagerStatus `json:",omitempty"` -} - -// NodeSpec represents the spec of a node. -type NodeSpec struct { - Annotations - Role NodeRole `json:",omitempty"` - Availability NodeAvailability `json:",omitempty"` -} - -// NodeRole represents the role of a node. -type NodeRole string - -const ( - // NodeRoleWorker WORKER - NodeRoleWorker NodeRole = "worker" - // NodeRoleManager MANAGER - NodeRoleManager NodeRole = "manager" -) - -// NodeAvailability represents the availability of a node. -type NodeAvailability string - -const ( - // NodeAvailabilityActive ACTIVE - NodeAvailabilityActive NodeAvailability = "active" - // NodeAvailabilityPause PAUSE - NodeAvailabilityPause NodeAvailability = "pause" - // NodeAvailabilityDrain DRAIN - NodeAvailabilityDrain NodeAvailability = "drain" -) - -// NodeDescription represents the description of a node. -type NodeDescription struct { - Hostname string `json:",omitempty"` - Platform Platform `json:",omitempty"` - Resources Resources `json:",omitempty"` - Engine EngineDescription `json:",omitempty"` - TLSInfo TLSInfo `json:",omitempty"` -} - -// Platform represents the platform (Arch/OS). -type Platform struct { - Architecture string `json:",omitempty"` - OS string `json:",omitempty"` -} - -// EngineDescription represents the description of an engine. -type EngineDescription struct { - EngineVersion string `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - Plugins []PluginDescription `json:",omitempty"` -} - -// PluginDescription represents the description of an engine plugin. -type PluginDescription struct { - Type string `json:",omitempty"` - Name string `json:",omitempty"` -} - -// NodeStatus represents the status of a node. -type NodeStatus struct { - State NodeState `json:",omitempty"` - Message string `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// Reachability represents the reachability of a node. -type Reachability string - -const ( - // ReachabilityUnknown UNKNOWN - ReachabilityUnknown Reachability = "unknown" - // ReachabilityUnreachable UNREACHABLE - ReachabilityUnreachable Reachability = "unreachable" - // ReachabilityReachable REACHABLE - ReachabilityReachable Reachability = "reachable" -) - -// ManagerStatus represents the status of a manager. -type ManagerStatus struct { - Leader bool `json:",omitempty"` - Reachability Reachability `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// NodeState represents the state of a node. -type NodeState string - -const ( - // NodeStateUnknown UNKNOWN - NodeStateUnknown NodeState = "unknown" - // NodeStateDown DOWN - NodeStateDown NodeState = "down" - // NodeStateReady READY - NodeStateReady NodeState = "ready" - // NodeStateDisconnected DISCONNECTED - NodeStateDisconnected NodeState = "disconnected" -) diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime.go b/vendor/github.com/docker/docker/api/types/swarm/runtime.go deleted file mode 100644 index 0c77403c..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime.go +++ /dev/null @@ -1,27 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -// RuntimeType is the type of runtime used for the TaskSpec -type RuntimeType string - -// RuntimeURL is the proto type url -type RuntimeURL string - -const ( - // RuntimeContainer is the container based runtime - RuntimeContainer RuntimeType = "container" - // RuntimePlugin is the plugin based runtime - RuntimePlugin RuntimeType = "plugin" - // RuntimeNetworkAttachment is the network attachment runtime - RuntimeNetworkAttachment RuntimeType = "attachment" - - // RuntimeURLContainer is the proto url for the container type - RuntimeURLContainer RuntimeURL = "types.docker.com/RuntimeContainer" - // RuntimeURLPlugin is the proto url for the plugin type - RuntimeURLPlugin RuntimeURL = "types.docker.com/RuntimePlugin" -) - -// NetworkAttachmentSpec represents the runtime spec type for network -// attachment tasks -type NetworkAttachmentSpec struct { - ContainerID string -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go b/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go deleted file mode 100644 index 98c2806c..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime/gen.go +++ /dev/null @@ -1,3 +0,0 @@ -//go:generate protoc -I . --gogofast_out=import_path=github.com/docker/docker/api/types/swarm/runtime:. plugin.proto - -package runtime // import "github.com/docker/docker/api/types/swarm/runtime" diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go deleted file mode 100644 index e4504586..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go +++ /dev/null @@ -1,754 +0,0 @@ -// Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: plugin.proto - -/* - Package runtime is a generated protocol buffer package. - - It is generated from these files: - plugin.proto - - It has these top-level messages: - PluginSpec - PluginPrivilege -*/ -package runtime - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" - -import io "io" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package - -// PluginSpec defines the base payload which clients can specify for creating -// a service with the plugin runtime. -type PluginSpec struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Remote string `protobuf:"bytes,2,opt,name=remote,proto3" json:"remote,omitempty"` - Privileges []*PluginPrivilege `protobuf:"bytes,3,rep,name=privileges" json:"privileges,omitempty"` - Disabled bool `protobuf:"varint,4,opt,name=disabled,proto3" json:"disabled,omitempty"` - Env []string `protobuf:"bytes,5,rep,name=env" json:"env,omitempty"` -} - -func (m *PluginSpec) Reset() { *m = PluginSpec{} } -func (m *PluginSpec) String() string { return proto.CompactTextString(m) } -func (*PluginSpec) ProtoMessage() {} -func (*PluginSpec) Descriptor() ([]byte, []int) { return fileDescriptorPlugin, []int{0} } - -func (m *PluginSpec) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *PluginSpec) GetRemote() string { - if m != nil { - return m.Remote - } - return "" -} - -func (m *PluginSpec) GetPrivileges() []*PluginPrivilege { - if m != nil { - return m.Privileges - } - return nil -} - -func (m *PluginSpec) GetDisabled() bool { - if m != nil { - return m.Disabled - } - return false -} - -func (m *PluginSpec) GetEnv() []string { - if m != nil { - return m.Env - } - return nil -} - -// PluginPrivilege describes a permission the user has to accept -// upon installing a plugin. -type PluginPrivilege struct { - Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` - Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` - Value []string `protobuf:"bytes,3,rep,name=value" json:"value,omitempty"` -} - -func (m *PluginPrivilege) Reset() { *m = PluginPrivilege{} } -func (m *PluginPrivilege) String() string { return proto.CompactTextString(m) } -func (*PluginPrivilege) ProtoMessage() {} -func (*PluginPrivilege) Descriptor() ([]byte, []int) { return fileDescriptorPlugin, []int{1} } - -func (m *PluginPrivilege) GetName() string { - if m != nil { - return m.Name - } - return "" -} - -func (m *PluginPrivilege) GetDescription() string { - if m != nil { - return m.Description - } - return "" -} - -func (m *PluginPrivilege) GetValue() []string { - if m != nil { - return m.Value - } - return nil -} - -func init() { - proto.RegisterType((*PluginSpec)(nil), "PluginSpec") - proto.RegisterType((*PluginPrivilege)(nil), "PluginPrivilege") -} -func (m *PluginSpec) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PluginSpec) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Name) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintPlugin(dAtA, i, uint64(len(m.Name))) - i += copy(dAtA[i:], m.Name) - } - if len(m.Remote) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintPlugin(dAtA, i, uint64(len(m.Remote))) - i += copy(dAtA[i:], m.Remote) - } - if len(m.Privileges) > 0 { - for _, msg := range m.Privileges { - dAtA[i] = 0x1a - i++ - i = encodeVarintPlugin(dAtA, i, uint64(msg.Size())) - n, err := msg.MarshalTo(dAtA[i:]) - if err != nil { - return 0, err - } - i += n - } - } - if m.Disabled { - dAtA[i] = 0x20 - i++ - if m.Disabled { - dAtA[i] = 1 - } else { - dAtA[i] = 0 - } - i++ - } - if len(m.Env) > 0 { - for _, s := range m.Env { - dAtA[i] = 0x2a - i++ - l = len(s) - for l >= 1<<7 { - dAtA[i] = uint8(uint64(l)&0x7f | 0x80) - l >>= 7 - i++ - } - dAtA[i] = uint8(l) - i++ - i += copy(dAtA[i:], s) - } - } - return i, nil -} - -func (m *PluginPrivilege) Marshal() (dAtA []byte, err error) { - size := m.Size() - dAtA = make([]byte, size) - n, err := m.MarshalTo(dAtA) - if err != nil { - return nil, err - } - return dAtA[:n], nil -} - -func (m *PluginPrivilege) MarshalTo(dAtA []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Name) > 0 { - dAtA[i] = 0xa - i++ - i = encodeVarintPlugin(dAtA, i, uint64(len(m.Name))) - i += copy(dAtA[i:], m.Name) - } - if len(m.Description) > 0 { - dAtA[i] = 0x12 - i++ - i = encodeVarintPlugin(dAtA, i, uint64(len(m.Description))) - i += copy(dAtA[i:], m.Description) - } - if len(m.Value) > 0 { - for _, s := range m.Value { - dAtA[i] = 0x1a - i++ - l = len(s) - for l >= 1<<7 { - dAtA[i] = uint8(uint64(l)&0x7f | 0x80) - l >>= 7 - i++ - } - dAtA[i] = uint8(l) - i++ - i += copy(dAtA[i:], s) - } - } - return i, nil -} - -func encodeVarintPlugin(dAtA []byte, offset int, v uint64) int { - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - dAtA[offset] = uint8(v) - return offset + 1 -} -func (m *PluginSpec) Size() (n int) { - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovPlugin(uint64(l)) - } - l = len(m.Remote) - if l > 0 { - n += 1 + l + sovPlugin(uint64(l)) - } - if len(m.Privileges) > 0 { - for _, e := range m.Privileges { - l = e.Size() - n += 1 + l + sovPlugin(uint64(l)) - } - } - if m.Disabled { - n += 2 - } - if len(m.Env) > 0 { - for _, s := range m.Env { - l = len(s) - n += 1 + l + sovPlugin(uint64(l)) - } - } - return n -} - -func (m *PluginPrivilege) Size() (n int) { - var l int - _ = l - l = len(m.Name) - if l > 0 { - n += 1 + l + sovPlugin(uint64(l)) - } - l = len(m.Description) - if l > 0 { - n += 1 + l + sovPlugin(uint64(l)) - } - if len(m.Value) > 0 { - for _, s := range m.Value { - l = len(s) - n += 1 + l + sovPlugin(uint64(l)) - } - } - return n -} - -func sovPlugin(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} -func sozPlugin(x uint64) (n int) { - return sovPlugin(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *PluginSpec) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PluginSpec: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PluginSpec: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Remote", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Remote = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Privileges", wireType) - } - var msglen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - msglen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if msglen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + msglen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Privileges = append(m.Privileges, &PluginPrivilege{}) - if err := m.Privileges[len(m.Privileges)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex - case 4: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Disabled", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - m.Disabled = bool(v != 0) - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Env", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Env = append(m.Env, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipPlugin(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthPlugin - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PluginPrivilege) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PluginPrivilege: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PluginPrivilege: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Name = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Description = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowPlugin - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthPlugin - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Value = append(m.Value, string(dAtA[iNdEx:postIndex])) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipPlugin(dAtA[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthPlugin - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipPlugin(dAtA []byte) (n int, err error) { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPlugin - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPlugin - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if dAtA[iNdEx-1] < 0x80 { - break - } - } - return iNdEx, nil - case 1: - iNdEx += 8 - return iNdEx, nil - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPlugin - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - iNdEx += length - if length < 0 { - return 0, ErrInvalidLengthPlugin - } - return iNdEx, nil - case 3: - for { - var innerWire uint64 - var start int = iNdEx - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowPlugin - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - innerWire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - innerWireType := int(innerWire & 0x7) - if innerWireType == 4 { - break - } - next, err := skipPlugin(dAtA[start:]) - if err != nil { - return 0, err - } - iNdEx = start + next - } - return iNdEx, nil - case 4: - return iNdEx, nil - case 5: - iNdEx += 4 - return iNdEx, nil - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - } - panic("unreachable") -} - -var ( - ErrInvalidLengthPlugin = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowPlugin = fmt.Errorf("proto: integer overflow") -) - -func init() { proto.RegisterFile("plugin.proto", fileDescriptorPlugin) } - -var fileDescriptorPlugin = []byte{ - // 256 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0x4d, 0x4b, 0xc3, 0x30, - 0x18, 0xc7, 0x89, 0xdd, 0xc6, 0xfa, 0x4c, 0x70, 0x04, 0x91, 0xe2, 0xa1, 0x94, 0x9d, 0x7a, 0x6a, - 0x45, 0x2f, 0x82, 0x37, 0x0f, 0x9e, 0x47, 0xbc, 0x09, 0x1e, 0xd2, 0xf6, 0xa1, 0x06, 0x9b, 0x17, - 0x92, 0xb4, 0xe2, 0x37, 0xf1, 0x23, 0x79, 0xf4, 0x23, 0x48, 0x3f, 0x89, 0x98, 0x75, 0x32, 0x64, - 0xa7, 0xff, 0x4b, 0xc2, 0x9f, 0x1f, 0x0f, 0x9c, 0x9a, 0xae, 0x6f, 0x85, 0x2a, 0x8c, 0xd5, 0x5e, - 0x6f, 0x3e, 0x08, 0xc0, 0x36, 0x14, 0x8f, 0x06, 0x6b, 0x4a, 0x61, 0xa6, 0xb8, 0xc4, 0x84, 0x64, - 0x24, 0x8f, 0x59, 0xf0, 0xf4, 0x02, 0x16, 0x16, 0xa5, 0xf6, 0x98, 0x9c, 0x84, 0x76, 0x4a, 0xf4, - 0x0a, 0xc0, 0x58, 0x31, 0x88, 0x0e, 0x5b, 0x74, 0x49, 0x94, 0x45, 0xf9, 0xea, 0x7a, 0x5d, 0xec, - 0xc6, 0xb6, 0xfb, 0x07, 0x76, 0xf0, 0x87, 0x5e, 0xc2, 0xb2, 0x11, 0x8e, 0x57, 0x1d, 0x36, 0xc9, - 0x2c, 0x23, 0xf9, 0x92, 0xfd, 0x65, 0xba, 0x86, 0x08, 0xd5, 0x90, 0xcc, 0xb3, 0x28, 0x8f, 0xd9, - 0xaf, 0xdd, 0x3c, 0xc3, 0xd9, 0xbf, 0xb1, 0xa3, 0x78, 0x19, 0xac, 0x1a, 0x74, 0xb5, 0x15, 0xc6, - 0x0b, 0xad, 0x26, 0xc6, 0xc3, 0x8a, 0x9e, 0xc3, 0x7c, 0xe0, 0x5d, 0x8f, 0x81, 0x31, 0x66, 0xbb, - 0x70, 0xff, 0xf0, 0x39, 0xa6, 0xe4, 0x6b, 0x4c, 0xc9, 0xf7, 0x98, 0x92, 0xa7, 0xdb, 0x56, 0xf8, - 0x97, 0xbe, 0x2a, 0x6a, 0x2d, 0xcb, 0x46, 0xd7, 0xaf, 0x68, 0xf7, 0xc2, 0x8d, 0x28, 0xfd, 0xbb, - 0x41, 0x57, 0xba, 0x37, 0x6e, 0x65, 0x69, 0x7b, 0xe5, 0x85, 0xc4, 0xbb, 0x49, 0xab, 0x45, 0x38, - 0xe4, 0xcd, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x99, 0xa8, 0xd9, 0x9b, 0x58, 0x01, 0x00, 0x00, -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto b/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto deleted file mode 100644 index 9ef16904..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.proto +++ /dev/null @@ -1,21 +0,0 @@ -syntax = "proto3"; - -option go_package = "github.com/docker/docker/api/types/swarm/runtime;runtime"; - -// PluginSpec defines the base payload which clients can specify for creating -// a service with the plugin runtime. -message PluginSpec { - string name = 1; - string remote = 2; - repeated PluginPrivilege privileges = 3; - bool disabled = 4; - repeated string env = 5; -} - -// PluginPrivilege describes a permission the user has to accept -// upon installing a plugin. -message PluginPrivilege { - string name = 1; - string description = 2; - repeated string value = 3; -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/secret.go b/vendor/github.com/docker/docker/api/types/swarm/secret.go deleted file mode 100644 index d5213ec9..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/secret.go +++ /dev/null @@ -1,36 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import "os" - -// Secret represents a secret. -type Secret struct { - ID string - Meta - Spec SecretSpec -} - -// SecretSpec represents a secret specification from a secret in swarm -type SecretSpec struct { - Annotations - Data []byte `json:",omitempty"` - Driver *Driver `json:",omitempty"` // name of the secrets driver used to fetch the secret's value from an external secret store - - // Templating controls whether and how to evaluate the secret payload as - // a template. If it is not set, no templating is used. - Templating *Driver `json:",omitempty"` -} - -// SecretReferenceFileTarget is a file target in a secret reference -type SecretReferenceFileTarget struct { - Name string - UID string - GID string - Mode os.FileMode -} - -// SecretReference is a reference to a secret in swarm -type SecretReference struct { - File *SecretReferenceFileTarget - SecretID string - SecretName string -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/service.go b/vendor/github.com/docker/docker/api/types/swarm/service.go deleted file mode 100644 index 6eb452d2..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/service.go +++ /dev/null @@ -1,202 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import "time" - -// Service represents a service. -type Service struct { - ID string - Meta - Spec ServiceSpec `json:",omitempty"` - PreviousSpec *ServiceSpec `json:",omitempty"` - Endpoint Endpoint `json:",omitempty"` - UpdateStatus *UpdateStatus `json:",omitempty"` - - // ServiceStatus is an optional, extra field indicating the number of - // desired and running tasks. It is provided primarily as a shortcut to - // calculating these values client-side, which otherwise would require - // listing all tasks for a service, an operation that could be - // computation and network expensive. - ServiceStatus *ServiceStatus `json:",omitempty"` - - // JobStatus is the status of a Service which is in one of ReplicatedJob or - // GlobalJob modes. It is absent on Replicated and Global services. - JobStatus *JobStatus `json:",omitempty"` -} - -// ServiceSpec represents the spec of a service. -type ServiceSpec struct { - Annotations - - // TaskTemplate defines how the service should construct new tasks when - // orchestrating this service. - TaskTemplate TaskSpec `json:",omitempty"` - Mode ServiceMode `json:",omitempty"` - UpdateConfig *UpdateConfig `json:",omitempty"` - RollbackConfig *UpdateConfig `json:",omitempty"` - - // Networks field in ServiceSpec is deprecated. The - // same field in TaskSpec should be used instead. - // This field will be removed in a future release. - Networks []NetworkAttachmentConfig `json:",omitempty"` - EndpointSpec *EndpointSpec `json:",omitempty"` -} - -// ServiceMode represents the mode of a service. -type ServiceMode struct { - Replicated *ReplicatedService `json:",omitempty"` - Global *GlobalService `json:",omitempty"` - ReplicatedJob *ReplicatedJob `json:",omitempty"` - GlobalJob *GlobalJob `json:",omitempty"` -} - -// UpdateState is the state of a service update. -type UpdateState string - -const ( - // UpdateStateUpdating is the updating state. - UpdateStateUpdating UpdateState = "updating" - // UpdateStatePaused is the paused state. - UpdateStatePaused UpdateState = "paused" - // UpdateStateCompleted is the completed state. - UpdateStateCompleted UpdateState = "completed" - // UpdateStateRollbackStarted is the state with a rollback in progress. - UpdateStateRollbackStarted UpdateState = "rollback_started" - // UpdateStateRollbackPaused is the state with a rollback in progress. - UpdateStateRollbackPaused UpdateState = "rollback_paused" - // UpdateStateRollbackCompleted is the state with a rollback in progress. - UpdateStateRollbackCompleted UpdateState = "rollback_completed" -) - -// UpdateStatus reports the status of a service update. -type UpdateStatus struct { - State UpdateState `json:",omitempty"` - StartedAt *time.Time `json:",omitempty"` - CompletedAt *time.Time `json:",omitempty"` - Message string `json:",omitempty"` -} - -// ReplicatedService is a kind of ServiceMode. -type ReplicatedService struct { - Replicas *uint64 `json:",omitempty"` -} - -// GlobalService is a kind of ServiceMode. -type GlobalService struct{} - -// ReplicatedJob is the a type of Service which executes a defined Tasks -// in parallel until the specified number of Tasks have succeeded. -type ReplicatedJob struct { - // MaxConcurrent indicates the maximum number of Tasks that should be - // executing simultaneously for this job at any given time. There may be - // fewer Tasks that MaxConcurrent executing simultaneously; for example, if - // there are fewer than MaxConcurrent tasks needed to reach - // TotalCompletions. - // - // If this field is empty, it will default to a max concurrency of 1. - MaxConcurrent *uint64 `json:",omitempty"` - - // TotalCompletions is the total number of Tasks desired to run to - // completion. - // - // If this field is empty, the value of MaxConcurrent will be used. - TotalCompletions *uint64 `json:",omitempty"` -} - -// GlobalJob is the type of a Service which executes a Task on every Node -// matching the Service's placement constraints. These tasks run to completion -// and then exit. -// -// This type is deliberately empty. -type GlobalJob struct{} - -const ( - // UpdateFailureActionPause PAUSE - UpdateFailureActionPause = "pause" - // UpdateFailureActionContinue CONTINUE - UpdateFailureActionContinue = "continue" - // UpdateFailureActionRollback ROLLBACK - UpdateFailureActionRollback = "rollback" - - // UpdateOrderStopFirst STOP_FIRST - UpdateOrderStopFirst = "stop-first" - // UpdateOrderStartFirst START_FIRST - UpdateOrderStartFirst = "start-first" -) - -// UpdateConfig represents the update configuration. -type UpdateConfig struct { - // Maximum number of tasks to be updated in one iteration. - // 0 means unlimited parallelism. - Parallelism uint64 - - // Amount of time between updates. - Delay time.Duration `json:",omitempty"` - - // FailureAction is the action to take when an update failures. - FailureAction string `json:",omitempty"` - - // Monitor indicates how long to monitor a task for failure after it is - // created. If the task fails by ending up in one of the states - // REJECTED, COMPLETED, or FAILED, within Monitor from its creation, - // this counts as a failure. If it fails after Monitor, it does not - // count as a failure. If Monitor is unspecified, a default value will - // be used. - Monitor time.Duration `json:",omitempty"` - - // MaxFailureRatio is the fraction of tasks that may fail during - // an update before the failure action is invoked. Any task created by - // the current update which ends up in one of the states REJECTED, - // COMPLETED or FAILED within Monitor from its creation counts as a - // failure. The number of failures is divided by the number of tasks - // being updated, and if this fraction is greater than - // MaxFailureRatio, the failure action is invoked. - // - // If the failure action is CONTINUE, there is no effect. - // If the failure action is PAUSE, no more tasks will be updated until - // another update is started. - MaxFailureRatio float32 - - // Order indicates the order of operations when rolling out an updated - // task. Either the old task is shut down before the new task is - // started, or the new task is started before the old task is shut down. - Order string -} - -// ServiceStatus represents the number of running tasks in a service and the -// number of tasks desired to be running. -type ServiceStatus struct { - // RunningTasks is the number of tasks for the service actually in the - // Running state - RunningTasks uint64 - - // DesiredTasks is the number of tasks desired to be running by the - // service. For replicated services, this is the replica count. For global - // services, this is computed by taking the number of tasks with desired - // state of not-Shutdown. - DesiredTasks uint64 - - // CompletedTasks is the number of tasks in the state Completed, if this - // service is in ReplicatedJob or GlobalJob mode. This field must be - // cross-referenced with the service type, because the default value of 0 - // may mean that a service is not in a job mode, or it may mean that the - // job has yet to complete any tasks. - CompletedTasks uint64 -} - -// JobStatus is the status of a job-type service. -type JobStatus struct { - // JobIteration is a value increased each time a Job is executed, - // successfully or otherwise. "Executed", in this case, means the job as a - // whole has been started, not that an individual Task has been launched. A - // job is "Executed" when its ServiceSpec is updated. JobIteration can be - // used to disambiguate Tasks belonging to different executions of a job. - // - // Though JobIteration will increase with each subsequent execution, it may - // not necessarily increase by 1, and so JobIteration should not be used to - // keep track of the number of times a job has been executed. - JobIteration Version - - // LastExecution is the time that the job was last executed, as observed by - // Swarm manager. - LastExecution time.Time `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/swarm.go b/vendor/github.com/docker/docker/api/types/swarm/swarm.go deleted file mode 100644 index b25f9996..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/swarm.go +++ /dev/null @@ -1,227 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import ( - "time" -) - -// ClusterInfo represents info about the cluster for outputting in "info" -// it contains the same information as "Swarm", but without the JoinTokens -type ClusterInfo struct { - ID string - Meta - Spec Spec - TLSInfo TLSInfo - RootRotationInProgress bool - DefaultAddrPool []string - SubnetSize uint32 - DataPathPort uint32 -} - -// Swarm represents a swarm. -type Swarm struct { - ClusterInfo - JoinTokens JoinTokens -} - -// JoinTokens contains the tokens workers and managers need to join the swarm. -type JoinTokens struct { - // Worker is the join token workers may use to join the swarm. - Worker string - // Manager is the join token managers may use to join the swarm. - Manager string -} - -// Spec represents the spec of a swarm. -type Spec struct { - Annotations - - Orchestration OrchestrationConfig `json:",omitempty"` - Raft RaftConfig `json:",omitempty"` - Dispatcher DispatcherConfig `json:",omitempty"` - CAConfig CAConfig `json:",omitempty"` - TaskDefaults TaskDefaults `json:",omitempty"` - EncryptionConfig EncryptionConfig `json:",omitempty"` -} - -// OrchestrationConfig represents orchestration configuration. -type OrchestrationConfig struct { - // TaskHistoryRetentionLimit is the number of historic tasks to keep per instance or - // node. If negative, never remove completed or failed tasks. - TaskHistoryRetentionLimit *int64 `json:",omitempty"` -} - -// TaskDefaults parameterizes cluster-level task creation with default values. -type TaskDefaults struct { - // LogDriver selects the log driver to use for tasks created in the - // orchestrator if unspecified by a service. - // - // Updating this value will only have an affect on new tasks. Old tasks - // will continue use their previously configured log driver until - // recreated. - LogDriver *Driver `json:",omitempty"` -} - -// EncryptionConfig controls at-rest encryption of data and keys. -type EncryptionConfig struct { - // AutoLockManagers specifies whether or not managers TLS keys and raft data - // should be encrypted at rest in such a way that they must be unlocked - // before the manager node starts up again. - AutoLockManagers bool -} - -// RaftConfig represents raft configuration. -type RaftConfig struct { - // SnapshotInterval is the number of log entries between snapshots. - SnapshotInterval uint64 `json:",omitempty"` - - // KeepOldSnapshots is the number of snapshots to keep beyond the - // current snapshot. - KeepOldSnapshots *uint64 `json:",omitempty"` - - // LogEntriesForSlowFollowers is the number of log entries to keep - // around to sync up slow followers after a snapshot is created. - LogEntriesForSlowFollowers uint64 `json:",omitempty"` - - // ElectionTick is the number of ticks that a follower will wait for a message - // from the leader before becoming a candidate and starting an election. - // ElectionTick must be greater than HeartbeatTick. - // - // A tick currently defaults to one second, so these translate directly to - // seconds currently, but this is NOT guaranteed. - ElectionTick int - - // HeartbeatTick is the number of ticks between heartbeats. Every - // HeartbeatTick ticks, the leader will send a heartbeat to the - // followers. - // - // A tick currently defaults to one second, so these translate directly to - // seconds currently, but this is NOT guaranteed. - HeartbeatTick int -} - -// DispatcherConfig represents dispatcher configuration. -type DispatcherConfig struct { - // HeartbeatPeriod defines how often agent should send heartbeats to - // dispatcher. - HeartbeatPeriod time.Duration `json:",omitempty"` -} - -// CAConfig represents CA configuration. -type CAConfig struct { - // NodeCertExpiry is the duration certificates should be issued for - NodeCertExpiry time.Duration `json:",omitempty"` - - // ExternalCAs is a list of CAs to which a manager node will make - // certificate signing requests for node certificates. - ExternalCAs []*ExternalCA `json:",omitempty"` - - // SigningCACert and SigningCAKey specify the desired signing root CA and - // root CA key for the swarm. When inspecting the cluster, the key will - // be redacted. - SigningCACert string `json:",omitempty"` - SigningCAKey string `json:",omitempty"` - - // If this value changes, and there is no specified signing cert and key, - // then the swarm is forced to generate a new root certificate ane key. - ForceRotate uint64 `json:",omitempty"` -} - -// ExternalCAProtocol represents type of external CA. -type ExternalCAProtocol string - -// ExternalCAProtocolCFSSL CFSSL -const ExternalCAProtocolCFSSL ExternalCAProtocol = "cfssl" - -// ExternalCA defines external CA to be used by the cluster. -type ExternalCA struct { - // Protocol is the protocol used by this external CA. - Protocol ExternalCAProtocol - - // URL is the URL where the external CA can be reached. - URL string - - // Options is a set of additional key/value pairs whose interpretation - // depends on the specified CA type. - Options map[string]string `json:",omitempty"` - - // CACert specifies which root CA is used by this external CA. This certificate must - // be in PEM format. - CACert string -} - -// InitRequest is the request used to init a swarm. -type InitRequest struct { - ListenAddr string - AdvertiseAddr string - DataPathAddr string - DataPathPort uint32 - ForceNewCluster bool - Spec Spec - AutoLockManagers bool - Availability NodeAvailability - DefaultAddrPool []string - SubnetSize uint32 -} - -// JoinRequest is the request used to join a swarm. -type JoinRequest struct { - ListenAddr string - AdvertiseAddr string - DataPathAddr string - RemoteAddrs []string - JoinToken string // accept by secret - Availability NodeAvailability -} - -// UnlockRequest is the request used to unlock a swarm. -type UnlockRequest struct { - // UnlockKey is the unlock key in ASCII-armored format. - UnlockKey string -} - -// LocalNodeState represents the state of the local node. -type LocalNodeState string - -const ( - // LocalNodeStateInactive INACTIVE - LocalNodeStateInactive LocalNodeState = "inactive" - // LocalNodeStatePending PENDING - LocalNodeStatePending LocalNodeState = "pending" - // LocalNodeStateActive ACTIVE - LocalNodeStateActive LocalNodeState = "active" - // LocalNodeStateError ERROR - LocalNodeStateError LocalNodeState = "error" - // LocalNodeStateLocked LOCKED - LocalNodeStateLocked LocalNodeState = "locked" -) - -// Info represents generic information about swarm. -type Info struct { - NodeID string - NodeAddr string - - LocalNodeState LocalNodeState - ControlAvailable bool - Error string - - RemoteManagers []Peer - Nodes int `json:",omitempty"` - Managers int `json:",omitempty"` - - Cluster *ClusterInfo `json:",omitempty"` - - Warnings []string `json:",omitempty"` -} - -// Peer represents a peer. -type Peer struct { - NodeID string - Addr string -} - -// UpdateFlags contains flags for SwarmUpdate. -type UpdateFlags struct { - RotateWorkerToken bool - RotateManagerToken bool - RotateManagerUnlockKey bool -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/task.go b/vendor/github.com/docker/docker/api/types/swarm/task.go deleted file mode 100644 index a6f7ab7b..00000000 --- a/vendor/github.com/docker/docker/api/types/swarm/task.go +++ /dev/null @@ -1,206 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import ( - "time" - - "github.com/docker/docker/api/types/swarm/runtime" -) - -// TaskState represents the state of a task. -type TaskState string - -const ( - // TaskStateNew NEW - TaskStateNew TaskState = "new" - // TaskStateAllocated ALLOCATED - TaskStateAllocated TaskState = "allocated" - // TaskStatePending PENDING - TaskStatePending TaskState = "pending" - // TaskStateAssigned ASSIGNED - TaskStateAssigned TaskState = "assigned" - // TaskStateAccepted ACCEPTED - TaskStateAccepted TaskState = "accepted" - // TaskStatePreparing PREPARING - TaskStatePreparing TaskState = "preparing" - // TaskStateReady READY - TaskStateReady TaskState = "ready" - // TaskStateStarting STARTING - TaskStateStarting TaskState = "starting" - // TaskStateRunning RUNNING - TaskStateRunning TaskState = "running" - // TaskStateComplete COMPLETE - TaskStateComplete TaskState = "complete" - // TaskStateShutdown SHUTDOWN - TaskStateShutdown TaskState = "shutdown" - // TaskStateFailed FAILED - TaskStateFailed TaskState = "failed" - // TaskStateRejected REJECTED - TaskStateRejected TaskState = "rejected" - // TaskStateRemove REMOVE - TaskStateRemove TaskState = "remove" - // TaskStateOrphaned ORPHANED - TaskStateOrphaned TaskState = "orphaned" -) - -// Task represents a task. -type Task struct { - ID string - Meta - Annotations - - Spec TaskSpec `json:",omitempty"` - ServiceID string `json:",omitempty"` - Slot int `json:",omitempty"` - NodeID string `json:",omitempty"` - Status TaskStatus `json:",omitempty"` - DesiredState TaskState `json:",omitempty"` - NetworksAttachments []NetworkAttachment `json:",omitempty"` - GenericResources []GenericResource `json:",omitempty"` - - // JobIteration is the JobIteration of the Service that this Task was - // spawned from, if the Service is a ReplicatedJob or GlobalJob. This is - // used to determine which Tasks belong to which run of the job. This field - // is absent if the Service mode is Replicated or Global. - JobIteration *Version `json:",omitempty"` -} - -// TaskSpec represents the spec of a task. -type TaskSpec struct { - // ContainerSpec, NetworkAttachmentSpec, and PluginSpec are mutually exclusive. - // PluginSpec is only used when the `Runtime` field is set to `plugin` - // NetworkAttachmentSpec is used if the `Runtime` field is set to - // `attachment`. - ContainerSpec *ContainerSpec `json:",omitempty"` - PluginSpec *runtime.PluginSpec `json:",omitempty"` - NetworkAttachmentSpec *NetworkAttachmentSpec `json:",omitempty"` - - Resources *ResourceRequirements `json:",omitempty"` - RestartPolicy *RestartPolicy `json:",omitempty"` - Placement *Placement `json:",omitempty"` - Networks []NetworkAttachmentConfig `json:",omitempty"` - - // LogDriver specifies the LogDriver to use for tasks created from this - // spec. If not present, the one on cluster default on swarm.Spec will be - // used, finally falling back to the engine default if not specified. - LogDriver *Driver `json:",omitempty"` - - // ForceUpdate is a counter that triggers an update even if no relevant - // parameters have been changed. - ForceUpdate uint64 - - Runtime RuntimeType `json:",omitempty"` -} - -// Resources represents resources (CPU/Memory) which can be advertised by a -// node and requested to be reserved for a task. -type Resources struct { - NanoCPUs int64 `json:",omitempty"` - MemoryBytes int64 `json:",omitempty"` - GenericResources []GenericResource `json:",omitempty"` -} - -// Limit describes limits on resources which can be requested by a task. -type Limit struct { - NanoCPUs int64 `json:",omitempty"` - MemoryBytes int64 `json:",omitempty"` - Pids int64 `json:",omitempty"` -} - -// GenericResource represents a "user defined" resource which can -// be either an integer (e.g: SSD=3) or a string (e.g: SSD=sda1) -type GenericResource struct { - NamedResourceSpec *NamedGenericResource `json:",omitempty"` - DiscreteResourceSpec *DiscreteGenericResource `json:",omitempty"` -} - -// NamedGenericResource represents a "user defined" resource which is defined -// as a string. -// "Kind" is used to describe the Kind of a resource (e.g: "GPU", "FPGA", "SSD", ...) -// Value is used to identify the resource (GPU="UUID-1", FPGA="/dev/sdb5", ...) -type NamedGenericResource struct { - Kind string `json:",omitempty"` - Value string `json:",omitempty"` -} - -// DiscreteGenericResource represents a "user defined" resource which is defined -// as an integer -// "Kind" is used to describe the Kind of a resource (e.g: "GPU", "FPGA", "SSD", ...) -// Value is used to count the resource (SSD=5, HDD=3, ...) -type DiscreteGenericResource struct { - Kind string `json:",omitempty"` - Value int64 `json:",omitempty"` -} - -// ResourceRequirements represents resources requirements. -type ResourceRequirements struct { - Limits *Limit `json:",omitempty"` - Reservations *Resources `json:",omitempty"` -} - -// Placement represents orchestration parameters. -type Placement struct { - Constraints []string `json:",omitempty"` - Preferences []PlacementPreference `json:",omitempty"` - MaxReplicas uint64 `json:",omitempty"` - - // Platforms stores all the platforms that the image can run on. - // This field is used in the platform filter for scheduling. If empty, - // then the platform filter is off, meaning there are no scheduling restrictions. - Platforms []Platform `json:",omitempty"` -} - -// PlacementPreference provides a way to make the scheduler aware of factors -// such as topology. -type PlacementPreference struct { - Spread *SpreadOver -} - -// SpreadOver is a scheduling preference that instructs the scheduler to spread -// tasks evenly over groups of nodes identified by labels. -type SpreadOver struct { - // label descriptor, such as engine.labels.az - SpreadDescriptor string -} - -// RestartPolicy represents the restart policy. -type RestartPolicy struct { - Condition RestartPolicyCondition `json:",omitempty"` - Delay *time.Duration `json:",omitempty"` - MaxAttempts *uint64 `json:",omitempty"` - Window *time.Duration `json:",omitempty"` -} - -// RestartPolicyCondition represents when to restart. -type RestartPolicyCondition string - -const ( - // RestartPolicyConditionNone NONE - RestartPolicyConditionNone RestartPolicyCondition = "none" - // RestartPolicyConditionOnFailure ON_FAILURE - RestartPolicyConditionOnFailure RestartPolicyCondition = "on-failure" - // RestartPolicyConditionAny ANY - RestartPolicyConditionAny RestartPolicyCondition = "any" -) - -// TaskStatus represents the status of a task. -type TaskStatus struct { - Timestamp time.Time `json:",omitempty"` - State TaskState `json:",omitempty"` - Message string `json:",omitempty"` - Err string `json:",omitempty"` - ContainerStatus *ContainerStatus `json:",omitempty"` - PortStatus PortStatus `json:",omitempty"` -} - -// ContainerStatus represents the status of a container. -type ContainerStatus struct { - ContainerID string - PID int - ExitCode int -} - -// PortStatus represents the port status of a task's host ports whose -// service has published host ports -type PortStatus struct { - Ports []PortConfig `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/time/duration_convert.go b/vendor/github.com/docker/docker/api/types/time/duration_convert.go deleted file mode 100644 index 84b6f073..00000000 --- a/vendor/github.com/docker/docker/api/types/time/duration_convert.go +++ /dev/null @@ -1,12 +0,0 @@ -package time // import "github.com/docker/docker/api/types/time" - -import ( - "strconv" - "time" -) - -// DurationToSecondsString converts the specified duration to the number -// seconds it represents, formatted as a string. -func DurationToSecondsString(duration time.Duration) string { - return strconv.FormatFloat(duration.Seconds(), 'f', 0, 64) -} diff --git a/vendor/github.com/docker/docker/api/types/time/timestamp.go b/vendor/github.com/docker/docker/api/types/time/timestamp.go deleted file mode 100644 index ea3495ef..00000000 --- a/vendor/github.com/docker/docker/api/types/time/timestamp.go +++ /dev/null @@ -1,129 +0,0 @@ -package time // import "github.com/docker/docker/api/types/time" - -import ( - "fmt" - "math" - "strconv" - "strings" - "time" -) - -// These are additional predefined layouts for use in Time.Format and Time.Parse -// with --since and --until parameters for `docker logs` and `docker events` -const ( - rFC3339Local = "2006-01-02T15:04:05" // RFC3339 with local timezone - rFC3339NanoLocal = "2006-01-02T15:04:05.999999999" // RFC3339Nano with local timezone - dateWithZone = "2006-01-02Z07:00" // RFC3339 with time at 00:00:00 - dateLocal = "2006-01-02" // RFC3339 with local timezone and time at 00:00:00 -) - -// GetTimestamp tries to parse given string as golang duration, -// then RFC3339 time and finally as a Unix timestamp. If -// any of these were successful, it returns a Unix timestamp -// as string otherwise returns the given value back. -// In case of duration input, the returned timestamp is computed -// as the given reference time minus the amount of the duration. -func GetTimestamp(value string, reference time.Time) (string, error) { - if d, err := time.ParseDuration(value); value != "0" && err == nil { - return strconv.FormatInt(reference.Add(-d).Unix(), 10), nil - } - - var format string - // if the string has a Z or a + or three dashes use parse otherwise use parseinlocation - parseInLocation := !(strings.ContainsAny(value, "zZ+") || strings.Count(value, "-") == 3) - - if strings.Contains(value, ".") { - if parseInLocation { - format = rFC3339NanoLocal - } else { - format = time.RFC3339Nano - } - } else if strings.Contains(value, "T") { - // we want the number of colons in the T portion of the timestamp - tcolons := strings.Count(value, ":") - // if parseInLocation is off and we have a +/- zone offset (not Z) then - // there will be an extra colon in the input for the tz offset subtract that - // colon from the tcolons count - if !parseInLocation && !strings.ContainsAny(value, "zZ") && tcolons > 0 { - tcolons-- - } - if parseInLocation { - switch tcolons { - case 0: - format = "2006-01-02T15" - case 1: - format = "2006-01-02T15:04" - default: - format = rFC3339Local - } - } else { - switch tcolons { - case 0: - format = "2006-01-02T15Z07:00" - case 1: - format = "2006-01-02T15:04Z07:00" - default: - format = time.RFC3339 - } - } - } else if parseInLocation { - format = dateLocal - } else { - format = dateWithZone - } - - var t time.Time - var err error - - if parseInLocation { - t, err = time.ParseInLocation(format, value, time.FixedZone(reference.Zone())) - } else { - t, err = time.Parse(format, value) - } - - if err != nil { - // if there is a `-` then it's an RFC3339 like timestamp - if strings.Contains(value, "-") { - return "", err // was probably an RFC3339 like timestamp but the parser failed with an error - } - if _, _, err := parseTimestamp(value); err != nil { - return "", fmt.Errorf("failed to parse value as time or duration: %q", value) - } - return value, nil // unix timestamp in and out case (meaning: the value passed at the command line is already in the right format for passing to the server) - } - - return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond())), nil -} - -// ParseTimestamps returns seconds and nanoseconds from a timestamp that has the -// format "%d.%09d", time.Unix(), int64(time.Nanosecond())) -// if the incoming nanosecond portion is longer or shorter than 9 digits it is -// converted to nanoseconds. The expectation is that the seconds and -// seconds will be used to create a time variable. For example: -// seconds, nanoseconds, err := ParseTimestamp("1136073600.000000001",0) -// if err == nil since := time.Unix(seconds, nanoseconds) -// returns seconds as def(aultSeconds) if value == "" -func ParseTimestamps(value string, def int64) (int64, int64, error) { - if value == "" { - return def, 0, nil - } - return parseTimestamp(value) -} - -func parseTimestamp(value string) (int64, int64, error) { - sa := strings.SplitN(value, ".", 2) - s, err := strconv.ParseInt(sa[0], 10, 64) - if err != nil { - return s, 0, err - } - if len(sa) != 2 { - return s, 0, nil - } - n, err := strconv.ParseInt(sa[1], 10, 64) - if err != nil { - return s, n, err - } - // should already be in nanoseconds but just in case convert n to nanoseconds - n = int64(float64(n) * math.Pow(float64(10), float64(9-len(sa[1])))) - return s, n, nil -} diff --git a/vendor/github.com/docker/docker/api/types/types.go b/vendor/github.com/docker/docker/api/types/types.go deleted file mode 100644 index e3a15991..00000000 --- a/vendor/github.com/docker/docker/api/types/types.go +++ /dev/null @@ -1,635 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -import ( - "errors" - "fmt" - "io" - "os" - "strings" - "time" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/mount" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/api/types/swarm" - "github.com/docker/go-connections/nat" -) - -// RootFS returns Image's RootFS description including the layer IDs. -type RootFS struct { - Type string - Layers []string `json:",omitempty"` - BaseLayer string `json:",omitempty"` -} - -// ImageInspect contains response of Engine API: -// GET "/images/{name:.*}/json" -type ImageInspect struct { - ID string `json:"Id"` - RepoTags []string - RepoDigests []string - Parent string - Comment string - Created string - Container string - ContainerConfig *container.Config - DockerVersion string - Author string - Config *container.Config - Architecture string - Variant string `json:",omitempty"` - Os string - OsVersion string `json:",omitempty"` - Size int64 - VirtualSize int64 - GraphDriver GraphDriverData - RootFS RootFS - Metadata ImageMetadata -} - -// ImageMetadata contains engine-local data about the image -type ImageMetadata struct { - LastTagTime time.Time `json:",omitempty"` -} - -// Container contains response of Engine API: -// GET "/containers/json" -type Container struct { - ID string `json:"Id"` - Names []string - Image string - ImageID string - Command string - Created int64 - Ports []Port - SizeRw int64 `json:",omitempty"` - SizeRootFs int64 `json:",omitempty"` - Labels map[string]string - State string - Status string - HostConfig struct { - NetworkMode string `json:",omitempty"` - } - NetworkSettings *SummaryNetworkSettings - Mounts []MountPoint -} - -// CopyConfig contains request body of Engine API: -// POST "/containers/"+containerID+"/copy" -type CopyConfig struct { - Resource string -} - -// ContainerPathStat is used to encode the header from -// GET "/containers/{name:.*}/archive" -// "Name" is the file or directory name. -type ContainerPathStat struct { - Name string `json:"name"` - Size int64 `json:"size"` - Mode os.FileMode `json:"mode"` - Mtime time.Time `json:"mtime"` - LinkTarget string `json:"linkTarget"` -} - -// ContainerStats contains response of Engine API: -// GET "/stats" -type ContainerStats struct { - Body io.ReadCloser `json:"body"` - OSType string `json:"ostype"` -} - -// Ping contains response of Engine API: -// GET "/_ping" -type Ping struct { - APIVersion string - OSType string - Experimental bool - BuilderVersion BuilderVersion -} - -// ComponentVersion describes the version information for a specific component. -type ComponentVersion struct { - Name string - Version string - Details map[string]string `json:",omitempty"` -} - -// Version contains response of Engine API: -// GET "/version" -type Version struct { - Platform struct{ Name string } `json:",omitempty"` - Components []ComponentVersion `json:",omitempty"` - - // The following fields are deprecated, they relate to the Engine component and are kept for backwards compatibility - - Version string - APIVersion string `json:"ApiVersion"` - MinAPIVersion string `json:"MinAPIVersion,omitempty"` - GitCommit string - GoVersion string - Os string - Arch string - KernelVersion string `json:",omitempty"` - Experimental bool `json:",omitempty"` - BuildTime string `json:",omitempty"` -} - -// Commit holds the Git-commit (SHA1) that a binary was built from, as reported -// in the version-string of external tools, such as containerd, or runC. -type Commit struct { - ID string // ID is the actual commit ID of external tool. - Expected string // Expected is the commit ID of external tool expected by dockerd as set at build time. -} - -// Info contains response of Engine API: -// GET "/info" -type Info struct { - ID string - Containers int - ContainersRunning int - ContainersPaused int - ContainersStopped int - Images int - Driver string - DriverStatus [][2]string - SystemStatus [][2]string `json:",omitempty"` // SystemStatus is only propagated by the Swarm standalone API - Plugins PluginsInfo - MemoryLimit bool - SwapLimit bool - KernelMemory bool // Deprecated: kernel 5.4 deprecated kmem.limit_in_bytes - KernelMemoryTCP bool - CPUCfsPeriod bool `json:"CpuCfsPeriod"` - CPUCfsQuota bool `json:"CpuCfsQuota"` - CPUShares bool - CPUSet bool - PidsLimit bool - IPv4Forwarding bool - BridgeNfIptables bool - BridgeNfIP6tables bool `json:"BridgeNfIp6tables"` - Debug bool - NFd int - OomKillDisable bool - NGoroutines int - SystemTime string - LoggingDriver string - CgroupDriver string - CgroupVersion string `json:",omitempty"` - NEventsListener int - KernelVersion string - OperatingSystem string - OSVersion string - OSType string - Architecture string - IndexServerAddress string - RegistryConfig *registry.ServiceConfig - NCPU int - MemTotal int64 - GenericResources []swarm.GenericResource - DockerRootDir string - HTTPProxy string `json:"HttpProxy"` - HTTPSProxy string `json:"HttpsProxy"` - NoProxy string - Name string - Labels []string - ExperimentalBuild bool - ServerVersion string - ClusterStore string `json:",omitempty"` // Deprecated: host-discovery and overlay networks with external k/v stores are deprecated - ClusterAdvertise string `json:",omitempty"` // Deprecated: host-discovery and overlay networks with external k/v stores are deprecated - Runtimes map[string]Runtime - DefaultRuntime string - Swarm swarm.Info - // LiveRestoreEnabled determines whether containers should be kept - // running when the daemon is shutdown or upon daemon start if - // running containers are detected - LiveRestoreEnabled bool - Isolation container.Isolation - InitBinary string - ContainerdCommit Commit - RuncCommit Commit - InitCommit Commit - SecurityOptions []string - ProductLicense string `json:",omitempty"` - DefaultAddressPools []NetworkAddressPool `json:",omitempty"` - Warnings []string -} - -// KeyValue holds a key/value pair -type KeyValue struct { - Key, Value string -} - -// NetworkAddressPool is a temp struct used by Info struct -type NetworkAddressPool struct { - Base string - Size int -} - -// SecurityOpt contains the name and options of a security option -type SecurityOpt struct { - Name string - Options []KeyValue -} - -// DecodeSecurityOptions decodes a security options string slice to a type safe -// SecurityOpt -func DecodeSecurityOptions(opts []string) ([]SecurityOpt, error) { - so := []SecurityOpt{} - for _, opt := range opts { - // support output from a < 1.13 docker daemon - if !strings.Contains(opt, "=") { - so = append(so, SecurityOpt{Name: opt}) - continue - } - secopt := SecurityOpt{} - split := strings.Split(opt, ",") - for _, s := range split { - kv := strings.SplitN(s, "=", 2) - if len(kv) != 2 { - return nil, fmt.Errorf("invalid security option %q", s) - } - if kv[0] == "" || kv[1] == "" { - return nil, errors.New("invalid empty security option") - } - if kv[0] == "name" { - secopt.Name = kv[1] - continue - } - secopt.Options = append(secopt.Options, KeyValue{Key: kv[0], Value: kv[1]}) - } - so = append(so, secopt) - } - return so, nil -} - -// PluginsInfo is a temp struct holding Plugins name -// registered with docker daemon. It is used by Info struct -type PluginsInfo struct { - // List of Volume plugins registered - Volume []string - // List of Network plugins registered - Network []string - // List of Authorization plugins registered - Authorization []string - // List of Log plugins registered - Log []string -} - -// ExecStartCheck is a temp struct used by execStart -// Config fields is part of ExecConfig in runconfig package -type ExecStartCheck struct { - // ExecStart will first check if it's detached - Detach bool - // Check if there's a tty - Tty bool -} - -// HealthcheckResult stores information about a single run of a healthcheck probe -type HealthcheckResult struct { - Start time.Time // Start is the time this check started - End time.Time // End is the time this check ended - ExitCode int // ExitCode meanings: 0=healthy, 1=unhealthy, 2=reserved (considered unhealthy), else=error running probe - Output string // Output from last check -} - -// Health states -const ( - NoHealthcheck = "none" // Indicates there is no healthcheck - Starting = "starting" // Starting indicates that the container is not yet ready - Healthy = "healthy" // Healthy indicates that the container is running correctly - Unhealthy = "unhealthy" // Unhealthy indicates that the container has a problem -) - -// Health stores information about the container's healthcheck results -type Health struct { - Status string // Status is one of Starting, Healthy or Unhealthy - FailingStreak int // FailingStreak is the number of consecutive failures - Log []*HealthcheckResult // Log contains the last few results (oldest first) -} - -// ContainerState stores container's running state -// it's part of ContainerJSONBase and will return by "inspect" command -type ContainerState struct { - Status string // String representation of the container state. Can be one of "created", "running", "paused", "restarting", "removing", "exited", or "dead" - Running bool - Paused bool - Restarting bool - OOMKilled bool - Dead bool - Pid int - ExitCode int - Error string - StartedAt string - FinishedAt string - Health *Health `json:",omitempty"` -} - -// ContainerNode stores information about the node that a container -// is running on. It's only used by the Docker Swarm standalone API -type ContainerNode struct { - ID string - IPAddress string `json:"IP"` - Addr string - Name string - Cpus int - Memory int64 - Labels map[string]string -} - -// ContainerJSONBase contains response of Engine API: -// GET "/containers/{name:.*}/json" -type ContainerJSONBase struct { - ID string `json:"Id"` - Created string - Path string - Args []string - State *ContainerState - Image string - ResolvConfPath string - HostnamePath string - HostsPath string - LogPath string - Node *ContainerNode `json:",omitempty"` // Node is only propagated by Docker Swarm standalone API - Name string - RestartCount int - Driver string - Platform string - MountLabel string - ProcessLabel string - AppArmorProfile string - ExecIDs []string - HostConfig *container.HostConfig - GraphDriver GraphDriverData - SizeRw *int64 `json:",omitempty"` - SizeRootFs *int64 `json:",omitempty"` -} - -// ContainerJSON is newly used struct along with MountPoint -type ContainerJSON struct { - *ContainerJSONBase - Mounts []MountPoint - Config *container.Config - NetworkSettings *NetworkSettings -} - -// NetworkSettings exposes the network settings in the api -type NetworkSettings struct { - NetworkSettingsBase - DefaultNetworkSettings - Networks map[string]*network.EndpointSettings -} - -// SummaryNetworkSettings provides a summary of container's networks -// in /containers/json -type SummaryNetworkSettings struct { - Networks map[string]*network.EndpointSettings -} - -// NetworkSettingsBase holds basic information about networks -type NetworkSettingsBase struct { - Bridge string // Bridge is the Bridge name the network uses(e.g. `docker0`) - SandboxID string // SandboxID uniquely represents a container's network stack - HairpinMode bool // HairpinMode specifies if hairpin NAT should be enabled on the virtual interface - LinkLocalIPv6Address string // LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix - LinkLocalIPv6PrefixLen int // LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address - Ports nat.PortMap // Ports is a collection of PortBinding indexed by Port - SandboxKey string // SandboxKey identifies the sandbox - SecondaryIPAddresses []network.Address - SecondaryIPv6Addresses []network.Address -} - -// DefaultNetworkSettings holds network information -// during the 2 release deprecation period. -// It will be removed in Docker 1.11. -type DefaultNetworkSettings struct { - EndpointID string // EndpointID uniquely represents a service endpoint in a Sandbox - Gateway string // Gateway holds the gateway address for the network - GlobalIPv6Address string // GlobalIPv6Address holds network's global IPv6 address - GlobalIPv6PrefixLen int // GlobalIPv6PrefixLen represents mask length of network's global IPv6 address - IPAddress string // IPAddress holds the IPv4 address for the network - IPPrefixLen int // IPPrefixLen represents mask length of network's IPv4 address - IPv6Gateway string // IPv6Gateway holds gateway address specific for IPv6 - MacAddress string // MacAddress holds the MAC address for the network -} - -// MountPoint represents a mount point configuration inside the container. -// This is used for reporting the mountpoints in use by a container. -type MountPoint struct { - Type mount.Type `json:",omitempty"` - Name string `json:",omitempty"` - Source string - Destination string - Driver string `json:",omitempty"` - Mode string - RW bool - Propagation mount.Propagation -} - -// NetworkResource is the body of the "get network" http response message -type NetworkResource struct { - Name string // Name is the requested name of the network - ID string `json:"Id"` // ID uniquely identifies a network on a single machine - Created time.Time // Created is the time the network created - Scope string // Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level) - Driver string // Driver is the Driver name used to create the network (e.g. `bridge`, `overlay`) - EnableIPv6 bool // EnableIPv6 represents whether to enable IPv6 - IPAM network.IPAM // IPAM is the network's IP Address Management - Internal bool // Internal represents if the network is used internal only - Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. - Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. - ConfigFrom network.ConfigReference // ConfigFrom specifies the source which will provide the configuration for this network. - ConfigOnly bool // ConfigOnly networks are place-holder networks for network configurations to be used by other networks. ConfigOnly networks cannot be used directly to run containers or services. - Containers map[string]EndpointResource // Containers contains endpoints belonging to the network - Options map[string]string // Options holds the network specific options to use for when creating the network - Labels map[string]string // Labels holds metadata specific to the network being created - Peers []network.PeerInfo `json:",omitempty"` // List of peer nodes for an overlay network - Services map[string]network.ServiceInfo `json:",omitempty"` -} - -// EndpointResource contains network resources allocated and used for a container in a network -type EndpointResource struct { - Name string - EndpointID string - MacAddress string - IPv4Address string - IPv6Address string -} - -// NetworkCreate is the expected body of the "create network" http request message -type NetworkCreate struct { - // Check for networks with duplicate names. - // Network is primarily keyed based on a random ID and not on the name. - // Network name is strictly a user-friendly alias to the network - // which is uniquely identified using ID. - // And there is no guaranteed way to check for duplicates. - // Option CheckDuplicate is there to provide a best effort checking of any networks - // which has the same name but it is not guaranteed to catch all name collisions. - CheckDuplicate bool - Driver string - Scope string - EnableIPv6 bool - IPAM *network.IPAM - Internal bool - Attachable bool - Ingress bool - ConfigOnly bool - ConfigFrom *network.ConfigReference - Options map[string]string - Labels map[string]string -} - -// NetworkCreateRequest is the request message sent to the server for network create call. -type NetworkCreateRequest struct { - NetworkCreate - Name string -} - -// NetworkCreateResponse is the response message sent by the server for network create call -type NetworkCreateResponse struct { - ID string `json:"Id"` - Warning string -} - -// NetworkConnect represents the data to be used to connect a container to the network -type NetworkConnect struct { - Container string - EndpointConfig *network.EndpointSettings `json:",omitempty"` -} - -// NetworkDisconnect represents the data to be used to disconnect a container from the network -type NetworkDisconnect struct { - Container string - Force bool -} - -// NetworkInspectOptions holds parameters to inspect network -type NetworkInspectOptions struct { - Scope string - Verbose bool -} - -// Checkpoint represents the details of a checkpoint -type Checkpoint struct { - Name string // Name is the name of the checkpoint -} - -// Runtime describes an OCI runtime -type Runtime struct { - Path string `json:"path"` - Args []string `json:"runtimeArgs,omitempty"` - - // This is exposed here only for internal use - // It is not currently supported to specify custom shim configs - Shim *ShimConfig `json:"-"` -} - -// ShimConfig is used by runtime to configure containerd shims -type ShimConfig struct { - Binary string - Opts interface{} -} - -// DiskUsage contains response of Engine API: -// GET "/system/df" -type DiskUsage struct { - LayersSize int64 - Images []*ImageSummary - Containers []*Container - Volumes []*Volume - BuildCache []*BuildCache - BuilderSize int64 // deprecated -} - -// ContainersPruneReport contains the response for Engine API: -// POST "/containers/prune" -type ContainersPruneReport struct { - ContainersDeleted []string - SpaceReclaimed uint64 -} - -// VolumesPruneReport contains the response for Engine API: -// POST "/volumes/prune" -type VolumesPruneReport struct { - VolumesDeleted []string - SpaceReclaimed uint64 -} - -// ImagesPruneReport contains the response for Engine API: -// POST "/images/prune" -type ImagesPruneReport struct { - ImagesDeleted []ImageDeleteResponseItem - SpaceReclaimed uint64 -} - -// BuildCachePruneReport contains the response for Engine API: -// POST "/build/prune" -type BuildCachePruneReport struct { - CachesDeleted []string - SpaceReclaimed uint64 -} - -// NetworksPruneReport contains the response for Engine API: -// POST "/networks/prune" -type NetworksPruneReport struct { - NetworksDeleted []string -} - -// SecretCreateResponse contains the information returned to a client -// on the creation of a new secret. -type SecretCreateResponse struct { - // ID is the id of the created secret. - ID string -} - -// SecretListOptions holds parameters to list secrets -type SecretListOptions struct { - Filters filters.Args -} - -// ConfigCreateResponse contains the information returned to a client -// on the creation of a new config. -type ConfigCreateResponse struct { - // ID is the id of the created config. - ID string -} - -// ConfigListOptions holds parameters to list configs -type ConfigListOptions struct { - Filters filters.Args -} - -// PushResult contains the tag, manifest digest, and manifest size from the -// push. It's used to signal this information to the trust code in the client -// so it can sign the manifest if necessary. -type PushResult struct { - Tag string - Digest string - Size int -} - -// BuildResult contains the image id of a successful build -type BuildResult struct { - ID string -} - -// BuildCache contains information about a build cache record -type BuildCache struct { - ID string - Parent string - Type string - Description string - InUse bool - Shared bool - Size int64 - CreatedAt time.Time - LastUsedAt *time.Time - UsageCount int -} - -// BuildCachePruneOptions hold parameters to prune the build cache -type BuildCachePruneOptions struct { - All bool - KeepStorage int64 - Filters filters.Args -} diff --git a/vendor/github.com/docker/docker/api/types/versions/README.md b/vendor/github.com/docker/docker/api/types/versions/README.md deleted file mode 100644 index 1ef911ed..00000000 --- a/vendor/github.com/docker/docker/api/types/versions/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Legacy API type versions - -This package includes types for legacy API versions. The stable version of the API types live in `api/types/*.go`. - -Consider moving a type here when you need to keep backwards compatibility in the API. This legacy types are organized by the latest API version they appear in. For instance, types in the `v1p19` package are valid for API versions below or equal `1.19`. Types in the `v1p20` package are valid for the API version `1.20`, since the versions below that will use the legacy types in `v1p19`. - -## Package name conventions - -The package name convention is to use `v` as a prefix for the version number and `p`(patch) as a separator. We use this nomenclature due to a few restrictions in the Go package name convention: - -1. We cannot use `.` because it's interpreted by the language, think of `v1.20.CallFunction`. -2. We cannot use `_` because golint complains about it. The code is actually valid, but it looks probably more weird: `v1_20.CallFunction`. - -For instance, if you want to modify a type that was available in the version `1.21` of the API but it will have different fields in the version `1.22`, you want to create a new package under `api/types/versions/v1p21`. diff --git a/vendor/github.com/docker/docker/api/types/versions/compare.go b/vendor/github.com/docker/docker/api/types/versions/compare.go deleted file mode 100644 index 8ccb0aa9..00000000 --- a/vendor/github.com/docker/docker/api/types/versions/compare.go +++ /dev/null @@ -1,62 +0,0 @@ -package versions // import "github.com/docker/docker/api/types/versions" - -import ( - "strconv" - "strings" -) - -// compare compares two version strings -// returns -1 if v1 < v2, 1 if v1 > v2, 0 otherwise. -func compare(v1, v2 string) int { - var ( - currTab = strings.Split(v1, ".") - otherTab = strings.Split(v2, ".") - ) - - max := len(currTab) - if len(otherTab) > max { - max = len(otherTab) - } - for i := 0; i < max; i++ { - var currInt, otherInt int - - if len(currTab) > i { - currInt, _ = strconv.Atoi(currTab[i]) - } - if len(otherTab) > i { - otherInt, _ = strconv.Atoi(otherTab[i]) - } - if currInt > otherInt { - return 1 - } - if otherInt > currInt { - return -1 - } - } - return 0 -} - -// LessThan checks if a version is less than another -func LessThan(v, other string) bool { - return compare(v, other) == -1 -} - -// LessThanOrEqualTo checks if a version is less than or equal to another -func LessThanOrEqualTo(v, other string) bool { - return compare(v, other) <= 0 -} - -// GreaterThan checks if a version is greater than another -func GreaterThan(v, other string) bool { - return compare(v, other) == 1 -} - -// GreaterThanOrEqualTo checks if a version is greater than or equal to another -func GreaterThanOrEqualTo(v, other string) bool { - return compare(v, other) >= 0 -} - -// Equal checks if a version is equal to another -func Equal(v, other string) bool { - return compare(v, other) == 0 -} diff --git a/vendor/github.com/docker/docker/api/types/volume.go b/vendor/github.com/docker/docker/api/types/volume.go deleted file mode 100644 index c69b0844..00000000 --- a/vendor/github.com/docker/docker/api/types/volume.go +++ /dev/null @@ -1,72 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// Volume volume -// swagger:model Volume -type Volume struct { - - // Date/Time the volume was created. - CreatedAt string `json:"CreatedAt,omitempty"` - - // Name of the volume driver used by the volume. - // Required: true - Driver string `json:"Driver"` - - // User-defined key/value metadata. - // Required: true - Labels map[string]string `json:"Labels"` - - // Mount path of the volume on the host. - // Required: true - Mountpoint string `json:"Mountpoint"` - - // Name of the volume. - // Required: true - Name string `json:"Name"` - - // The driver specific options used when creating the volume. - // - // Required: true - Options map[string]string `json:"Options"` - - // The level at which the volume exists. Either `global` for cluster-wide, - // or `local` for machine level. - // - // Required: true - Scope string `json:"Scope"` - - // Low-level details about the volume, provided by the volume driver. - // Details are returned as a map with key/value pairs: - // `{"key":"value","key2":"value2"}`. - // - // The `Status` field is optional, and is omitted if the volume driver - // does not support this feature. - // - Status map[string]interface{} `json:"Status,omitempty"` - - // usage data - UsageData *VolumeUsageData `json:"UsageData,omitempty"` -} - -// VolumeUsageData Usage details about the volume. This information is used by the -// `GET /system/df` endpoint, and omitted in other endpoints. -// -// swagger:model VolumeUsageData -type VolumeUsageData struct { - - // The number of containers referencing this volume. This field - // is set to `-1` if the reference-count is not available. - // - // Required: true - RefCount int64 `json:"RefCount"` - - // Amount of disk space used by the volume (in bytes). This information - // is only available for volumes created with the `"local"` volume - // driver. For volumes created with other volume drivers, this field - // is set to `-1` ("not available") - // - // Required: true - Size int64 `json:"Size"` -} diff --git a/vendor/github.com/docker/docker/api/types/volume/volume_create.go b/vendor/github.com/docker/docker/api/types/volume/volume_create.go deleted file mode 100644 index 8538078d..00000000 --- a/vendor/github.com/docker/docker/api/types/volume/volume_create.go +++ /dev/null @@ -1,31 +0,0 @@ -package volume // import "github.com/docker/docker/api/types/volume" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// VolumeCreateBody Volume configuration -// swagger:model VolumeCreateBody -type VolumeCreateBody struct { - - // Name of the volume driver to use. - // Required: true - Driver string `json:"Driver"` - - // A mapping of driver options and values. These options are - // passed directly to the driver and are driver specific. - // - // Required: true - DriverOpts map[string]string `json:"DriverOpts"` - - // User-defined key/value metadata. - // Required: true - Labels map[string]string `json:"Labels"` - - // The new volume's name. If not specified, Docker generates a name. - // - // Required: true - Name string `json:"Name"` -} diff --git a/vendor/github.com/docker/docker/api/types/volume/volume_list.go b/vendor/github.com/docker/docker/api/types/volume/volume_list.go deleted file mode 100644 index be06179b..00000000 --- a/vendor/github.com/docker/docker/api/types/volume/volume_list.go +++ /dev/null @@ -1,23 +0,0 @@ -package volume // import "github.com/docker/docker/api/types/volume" - -// ---------------------------------------------------------------------------- -// Code generated by `swagger generate operation`. DO NOT EDIT. -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -import "github.com/docker/docker/api/types" - -// VolumeListOKBody Volume list response -// swagger:model VolumeListOKBody -type VolumeListOKBody struct { - - // List of volumes - // Required: true - Volumes []*types.Volume `json:"Volumes"` - - // Warnings that occurred when fetching the list of volumes. - // - // Required: true - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/client/README.md b/vendor/github.com/docker/docker/client/README.md deleted file mode 100644 index 992f1811..00000000 --- a/vendor/github.com/docker/docker/client/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Go client for the Docker Engine API - -The `docker` command uses this package to communicate with the daemon. It can also be used by your own Go applications to do anything the command-line interface does – running containers, pulling images, managing swarms, etc. - -For example, to list running containers (the equivalent of `docker ps`): - -```go -package main - -import ( - "context" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" -) - -func main() { - cli, err := client.NewClientWithOpts(client.FromEnv) - if err != nil { - panic(err) - } - - containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{}) - if err != nil { - panic(err) - } - - for _, container := range containers { - fmt.Printf("%s %s\n", container.ID[:10], container.Image) - } -} -``` - -[Full documentation is available on GoDoc.](https://godoc.org/github.com/docker/docker/client) diff --git a/vendor/github.com/docker/docker/client/build_cancel.go b/vendor/github.com/docker/docker/client/build_cancel.go deleted file mode 100644 index 3aae43e3..00000000 --- a/vendor/github.com/docker/docker/client/build_cancel.go +++ /dev/null @@ -1,16 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" -) - -// BuildCancel requests the daemon to cancel ongoing build request -func (cli *Client) BuildCancel(ctx context.Context, id string) error { - query := url.Values{} - query.Set("id", id) - - serverResp, err := cli.post(ctx, "/build/cancel", query, nil, nil) - ensureReaderClosed(serverResp) - return err -} diff --git a/vendor/github.com/docker/docker/client/build_prune.go b/vendor/github.com/docker/docker/client/build_prune.go deleted file mode 100644 index 397d67cd..00000000 --- a/vendor/github.com/docker/docker/client/build_prune.go +++ /dev/null @@ -1,45 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/pkg/errors" -) - -// BuildCachePrune requests the daemon to delete unused cache data -func (cli *Client) BuildCachePrune(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error) { - if err := cli.NewVersionError("1.31", "build prune"); err != nil { - return nil, err - } - - report := types.BuildCachePruneReport{} - - query := url.Values{} - if opts.All { - query.Set("all", "1") - } - query.Set("keep-storage", fmt.Sprintf("%d", opts.KeepStorage)) - filters, err := filters.ToJSON(opts.Filters) - if err != nil { - return nil, errors.Wrap(err, "prune could not marshal filters option") - } - query.Set("filters", filters) - - serverResp, err := cli.post(ctx, "/build/prune", query, nil, nil) - defer ensureReaderClosed(serverResp) - - if err != nil { - return nil, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return nil, fmt.Errorf("Error retrieving disk usage: %v", err) - } - - return &report, nil -} diff --git a/vendor/github.com/docker/docker/client/checkpoint_create.go b/vendor/github.com/docker/docker/client/checkpoint_create.go deleted file mode 100644 index 921024fe..00000000 --- a/vendor/github.com/docker/docker/client/checkpoint_create.go +++ /dev/null @@ -1,14 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types" -) - -// CheckpointCreate creates a checkpoint from the given container with the given name -func (cli *Client) CheckpointCreate(ctx context.Context, container string, options types.CheckpointCreateOptions) error { - resp, err := cli.post(ctx, "/containers/"+container+"/checkpoints", nil, options, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/checkpoint_delete.go b/vendor/github.com/docker/docker/client/checkpoint_delete.go deleted file mode 100644 index 54f55fa7..00000000 --- a/vendor/github.com/docker/docker/client/checkpoint_delete.go +++ /dev/null @@ -1,20 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// CheckpointDelete deletes the checkpoint with the given name from the given container -func (cli *Client) CheckpointDelete(ctx context.Context, containerID string, options types.CheckpointDeleteOptions) error { - query := url.Values{} - if options.CheckpointDir != "" { - query.Set("dir", options.CheckpointDir) - } - - resp, err := cli.delete(ctx, "/containers/"+containerID+"/checkpoints/"+options.CheckpointID, query, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/checkpoint_list.go b/vendor/github.com/docker/docker/client/checkpoint_list.go deleted file mode 100644 index 66d46dd1..00000000 --- a/vendor/github.com/docker/docker/client/checkpoint_list.go +++ /dev/null @@ -1,28 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" -) - -// CheckpointList returns the checkpoints of the given container in the docker host -func (cli *Client) CheckpointList(ctx context.Context, container string, options types.CheckpointListOptions) ([]types.Checkpoint, error) { - var checkpoints []types.Checkpoint - - query := url.Values{} - if options.CheckpointDir != "" { - query.Set("dir", options.CheckpointDir) - } - - resp, err := cli.get(ctx, "/containers/"+container+"/checkpoints", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return checkpoints, wrapResponseError(err, resp, "container", container) - } - - err = json.NewDecoder(resp.body).Decode(&checkpoints) - return checkpoints, err -} diff --git a/vendor/github.com/docker/docker/client/client.go b/vendor/github.com/docker/docker/client/client.go deleted file mode 100644 index 68064ca9..00000000 --- a/vendor/github.com/docker/docker/client/client.go +++ /dev/null @@ -1,310 +0,0 @@ -/* -Package client is a Go client for the Docker Engine API. - -For more information about the Engine API, see the documentation: -https://docs.docker.com/engine/reference/api/ - -Usage - -You use the library by creating a client object and calling methods on it. The -client can be created either from environment variables with NewClientWithOpts(client.FromEnv), -or configured manually with NewClient(). - -For example, to list running containers (the equivalent of "docker ps"): - - package main - - import ( - "context" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" - ) - - func main() { - cli, err := client.NewClientWithOpts(client.FromEnv) - if err != nil { - panic(err) - } - - containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{}) - if err != nil { - panic(err) - } - - for _, container := range containers { - fmt.Printf("%s %s\n", container.ID[:10], container.Image) - } - } - -*/ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "fmt" - "net" - "net/http" - "net/url" - "path" - "strings" - - "github.com/docker/docker/api" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/versions" - "github.com/docker/go-connections/sockets" - "github.com/pkg/errors" -) - -// ErrRedirect is the error returned by checkRedirect when the request is non-GET. -var ErrRedirect = errors.New("unexpected redirect in response") - -// Client is the API client that performs all operations -// against a docker server. -type Client struct { - // scheme sets the scheme for the client - scheme string - // host holds the server address to connect to - host string - // proto holds the client protocol i.e. unix. - proto string - // addr holds the client address. - addr string - // basePath holds the path to prepend to the requests. - basePath string - // client used to send and receive http requests. - client *http.Client - // version of the server to talk to. - version string - // custom http headers configured by users. - customHTTPHeaders map[string]string - // manualOverride is set to true when the version was set by users. - manualOverride bool - - // negotiateVersion indicates if the client should automatically negotiate - // the API version to use when making requests. API version negotiation is - // performed on the first request, after which negotiated is set to "true" - // so that subsequent requests do not re-negotiate. - negotiateVersion bool - - // negotiated indicates that API version negotiation took place - negotiated bool -} - -// CheckRedirect specifies the policy for dealing with redirect responses: -// If the request is non-GET return `ErrRedirect`. Otherwise use the last response. -// -// Go 1.8 changes behavior for HTTP redirects (specifically 301, 307, and 308) in the client . -// The Docker client (and by extension docker API client) can be made to send a request -// like POST /containers//start where what would normally be in the name section of the URL is empty. -// This triggers an HTTP 301 from the daemon. -// In go 1.8 this 301 will be converted to a GET request, and ends up getting a 404 from the daemon. -// This behavior change manifests in the client in that before the 301 was not followed and -// the client did not generate an error, but now results in a message like Error response from daemon: page not found. -func CheckRedirect(req *http.Request, via []*http.Request) error { - if via[0].Method == http.MethodGet { - return http.ErrUseLastResponse - } - return ErrRedirect -} - -// NewClientWithOpts initializes a new API client with default values. It takes functors -// to modify values when creating it, like `NewClientWithOpts(WithVersion(…))` -// It also initializes the custom http headers to add to each request. -// -// It won't send any version information if the version number is empty. It is -// highly recommended that you set a version or your client may break if the -// server is upgraded. -func NewClientWithOpts(ops ...Opt) (*Client, error) { - client, err := defaultHTTPClient(DefaultDockerHost) - if err != nil { - return nil, err - } - c := &Client{ - host: DefaultDockerHost, - version: api.DefaultVersion, - client: client, - proto: defaultProto, - addr: defaultAddr, - } - - for _, op := range ops { - if err := op(c); err != nil { - return nil, err - } - } - - if _, ok := c.client.Transport.(http.RoundTripper); !ok { - return nil, fmt.Errorf("unable to verify TLS configuration, invalid transport %v", c.client.Transport) - } - if c.scheme == "" { - c.scheme = "http" - - tlsConfig := resolveTLSConfig(c.client.Transport) - if tlsConfig != nil { - // TODO(stevvooe): This isn't really the right way to write clients in Go. - // `NewClient` should probably only take an `*http.Client` and work from there. - // Unfortunately, the model of having a host-ish/url-thingy as the connection - // string has us confusing protocol and transport layers. We continue doing - // this to avoid breaking existing clients but this should be addressed. - c.scheme = "https" - } - } - - return c, nil -} - -func defaultHTTPClient(host string) (*http.Client, error) { - url, err := ParseHostURL(host) - if err != nil { - return nil, err - } - transport := new(http.Transport) - sockets.ConfigureTransport(transport, url.Scheme, url.Host) - return &http.Client{ - Transport: transport, - CheckRedirect: CheckRedirect, - }, nil -} - -// Close the transport used by the client -func (cli *Client) Close() error { - if t, ok := cli.client.Transport.(*http.Transport); ok { - t.CloseIdleConnections() - } - return nil -} - -// getAPIPath returns the versioned request path to call the api. -// It appends the query parameters to the path if they are not empty. -func (cli *Client) getAPIPath(ctx context.Context, p string, query url.Values) string { - var apiPath string - if cli.negotiateVersion && !cli.negotiated { - cli.NegotiateAPIVersion(ctx) - } - if cli.version != "" { - v := strings.TrimPrefix(cli.version, "v") - apiPath = path.Join(cli.basePath, "/v"+v, p) - } else { - apiPath = path.Join(cli.basePath, p) - } - return (&url.URL{Path: apiPath, RawQuery: query.Encode()}).String() -} - -// ClientVersion returns the API version used by this client. -func (cli *Client) ClientVersion() string { - return cli.version -} - -// NegotiateAPIVersion queries the API and updates the version to match the -// API version. Any errors are silently ignored. If a manual override is in place, -// either through the `DOCKER_API_VERSION` environment variable, or if the client -// was initialized with a fixed version (`opts.WithVersion(xx)`), no negotiation -// will be performed. -func (cli *Client) NegotiateAPIVersion(ctx context.Context) { - if !cli.manualOverride { - ping, _ := cli.Ping(ctx) - cli.negotiateAPIVersionPing(ping) - } -} - -// NegotiateAPIVersionPing updates the client version to match the Ping.APIVersion -// if the ping version is less than the default version. If a manual override is -// in place, either through the `DOCKER_API_VERSION` environment variable, or if -// the client was initialized with a fixed version (`opts.WithVersion(xx)`), no -// negotiation is performed. -func (cli *Client) NegotiateAPIVersionPing(p types.Ping) { - if !cli.manualOverride { - cli.negotiateAPIVersionPing(p) - } -} - -// negotiateAPIVersionPing queries the API and updates the version to match the -// API version. Any errors are silently ignored. -func (cli *Client) negotiateAPIVersionPing(p types.Ping) { - // try the latest version before versioning headers existed - if p.APIVersion == "" { - p.APIVersion = "1.24" - } - - // if the client is not initialized with a version, start with the latest supported version - if cli.version == "" { - cli.version = api.DefaultVersion - } - - // if server version is lower than the client version, downgrade - if versions.LessThan(p.APIVersion, cli.version) { - cli.version = p.APIVersion - } - - // Store the results, so that automatic API version negotiation (if enabled) - // won't be performed on the next request. - if cli.negotiateVersion { - cli.negotiated = true - } -} - -// DaemonHost returns the host address used by the client -func (cli *Client) DaemonHost() string { - return cli.host -} - -// HTTPClient returns a copy of the HTTP client bound to the server -func (cli *Client) HTTPClient() *http.Client { - c := *cli.client - return &c -} - -// ParseHostURL parses a url string, validates the string is a host url, and -// returns the parsed URL -func ParseHostURL(host string) (*url.URL, error) { - protoAddrParts := strings.SplitN(host, "://", 2) - if len(protoAddrParts) == 1 { - return nil, fmt.Errorf("unable to parse docker host `%s`", host) - } - - var basePath string - proto, addr := protoAddrParts[0], protoAddrParts[1] - if proto == "tcp" { - parsed, err := url.Parse("tcp://" + addr) - if err != nil { - return nil, err - } - addr = parsed.Host - basePath = parsed.Path - } - return &url.URL{ - Scheme: proto, - Host: addr, - Path: basePath, - }, nil -} - -// CustomHTTPHeaders returns the custom http headers stored by the client. -func (cli *Client) CustomHTTPHeaders() map[string]string { - m := make(map[string]string) - for k, v := range cli.customHTTPHeaders { - m[k] = v - } - return m -} - -// SetCustomHTTPHeaders that will be set on every HTTP request made by the client. -// Deprecated: use WithHTTPHeaders when creating the client. -func (cli *Client) SetCustomHTTPHeaders(headers map[string]string) { - cli.customHTTPHeaders = headers -} - -// Dialer returns a dialer for a raw stream connection, with HTTP/1.1 header, that can be used for proxying the daemon connection. -// Used by `docker dial-stdio` (docker/cli#889). -func (cli *Client) Dialer() func(context.Context) (net.Conn, error) { - return func(ctx context.Context) (net.Conn, error) { - if transport, ok := cli.client.Transport.(*http.Transport); ok { - if transport.DialContext != nil && transport.TLSClientConfig == nil { - return transport.DialContext(ctx, cli.proto, cli.addr) - } - } - return fallbackDial(cli.proto, cli.addr, resolveTLSConfig(cli.client.Transport)) - } -} diff --git a/vendor/github.com/docker/docker/client/client_deprecated.go b/vendor/github.com/docker/docker/client/client_deprecated.go deleted file mode 100644 index 54cdfc29..00000000 --- a/vendor/github.com/docker/docker/client/client_deprecated.go +++ /dev/null @@ -1,23 +0,0 @@ -package client - -import "net/http" - -// NewClient initializes a new API client for the given host and API version. -// It uses the given http client as transport. -// It also initializes the custom http headers to add to each request. -// -// It won't send any version information if the version number is empty. It is -// highly recommended that you set a version or your client may break if the -// server is upgraded. -// Deprecated: use NewClientWithOpts -func NewClient(host string, version string, client *http.Client, httpHeaders map[string]string) (*Client, error) { - return NewClientWithOpts(WithHost(host), WithVersion(version), WithHTTPClient(client), WithHTTPHeaders(httpHeaders)) -} - -// NewEnvClient initializes a new API client based on environment variables. -// See FromEnv for a list of support environment variables. -// -// Deprecated: use NewClientWithOpts(FromEnv) -func NewEnvClient() (*Client, error) { - return NewClientWithOpts(FromEnv) -} diff --git a/vendor/github.com/docker/docker/client/client_unix.go b/vendor/github.com/docker/docker/client/client_unix.go deleted file mode 100644 index 9d0f0dcb..00000000 --- a/vendor/github.com/docker/docker/client/client_unix.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build linux freebsd openbsd netbsd darwin solaris illumos dragonfly - -package client // import "github.com/docker/docker/client" - -// DefaultDockerHost defines os specific default if DOCKER_HOST is unset -const DefaultDockerHost = "unix:///var/run/docker.sock" - -const defaultProto = "unix" -const defaultAddr = "/var/run/docker.sock" diff --git a/vendor/github.com/docker/docker/client/client_windows.go b/vendor/github.com/docker/docker/client/client_windows.go deleted file mode 100644 index c649e544..00000000 --- a/vendor/github.com/docker/docker/client/client_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -package client // import "github.com/docker/docker/client" - -// DefaultDockerHost defines os specific default if DOCKER_HOST is unset -const DefaultDockerHost = "npipe:////./pipe/docker_engine" - -const defaultProto = "npipe" -const defaultAddr = "//./pipe/docker_engine" diff --git a/vendor/github.com/docker/docker/client/config_create.go b/vendor/github.com/docker/docker/client/config_create.go deleted file mode 100644 index ee7d411d..00000000 --- a/vendor/github.com/docker/docker/client/config_create.go +++ /dev/null @@ -1,25 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" -) - -// ConfigCreate creates a new Config. -func (cli *Client) ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error) { - var response types.ConfigCreateResponse - if err := cli.NewVersionError("1.30", "config create"); err != nil { - return response, err - } - resp, err := cli.post(ctx, "/configs/create", nil, config, nil) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/config_inspect.go b/vendor/github.com/docker/docker/client/config_inspect.go deleted file mode 100644 index 7d0ce3e1..00000000 --- a/vendor/github.com/docker/docker/client/config_inspect.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - - "github.com/docker/docker/api/types/swarm" -) - -// ConfigInspectWithRaw returns the config information with raw data -func (cli *Client) ConfigInspectWithRaw(ctx context.Context, id string) (swarm.Config, []byte, error) { - if id == "" { - return swarm.Config{}, nil, objectNotFoundError{object: "config", id: id} - } - if err := cli.NewVersionError("1.30", "config inspect"); err != nil { - return swarm.Config{}, nil, err - } - resp, err := cli.get(ctx, "/configs/"+id, nil, nil) - defer ensureReaderClosed(resp) - if err != nil { - return swarm.Config{}, nil, wrapResponseError(err, resp, "config", id) - } - - body, err := ioutil.ReadAll(resp.body) - if err != nil { - return swarm.Config{}, nil, err - } - - var config swarm.Config - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&config) - - return config, body, err -} diff --git a/vendor/github.com/docker/docker/client/config_list.go b/vendor/github.com/docker/docker/client/config_list.go deleted file mode 100644 index 565acc6e..00000000 --- a/vendor/github.com/docker/docker/client/config_list.go +++ /dev/null @@ -1,38 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" -) - -// ConfigList returns the list of configs. -func (cli *Client) ConfigList(ctx context.Context, options types.ConfigListOptions) ([]swarm.Config, error) { - if err := cli.NewVersionError("1.30", "config list"); err != nil { - return nil, err - } - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/configs", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var configs []swarm.Config - err = json.NewDecoder(resp.body).Decode(&configs) - return configs, err -} diff --git a/vendor/github.com/docker/docker/client/config_remove.go b/vendor/github.com/docker/docker/client/config_remove.go deleted file mode 100644 index a708fcae..00000000 --- a/vendor/github.com/docker/docker/client/config_remove.go +++ /dev/null @@ -1,13 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// ConfigRemove removes a Config. -func (cli *Client) ConfigRemove(ctx context.Context, id string) error { - if err := cli.NewVersionError("1.30", "config remove"); err != nil { - return err - } - resp, err := cli.delete(ctx, "/configs/"+id, nil, nil) - defer ensureReaderClosed(resp) - return wrapResponseError(err, resp, "config", id) -} diff --git a/vendor/github.com/docker/docker/client/config_update.go b/vendor/github.com/docker/docker/client/config_update.go deleted file mode 100644 index 39e59cf8..00000000 --- a/vendor/github.com/docker/docker/client/config_update.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" -) - -// ConfigUpdate attempts to update a Config -func (cli *Client) ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error { - if err := cli.NewVersionError("1.30", "config update"); err != nil { - return err - } - query := url.Values{} - query.Set("version", strconv.FormatUint(version.Index, 10)) - resp, err := cli.post(ctx, "/configs/"+id+"/update", query, config, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_attach.go b/vendor/github.com/docker/docker/client/container_attach.go deleted file mode 100644 index 88ba1ef6..00000000 --- a/vendor/github.com/docker/docker/client/container_attach.go +++ /dev/null @@ -1,57 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ContainerAttach attaches a connection to a container in the server. -// It returns a types.HijackedConnection with the hijacked connection -// and the a reader to get output. It's up to the called to close -// the hijacked connection by calling types.HijackedResponse.Close. -// -// The stream format on the response will be in one of two formats: -// -// If the container is using a TTY, there is only a single stream (stdout), and -// data is copied directly from the container output stream, no extra -// multiplexing or headers. -// -// If the container is *not* using a TTY, streams for stdout and stderr are -// multiplexed. -// The format of the multiplexed stream is as follows: -// -// [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}[]byte{OUTPUT} -// -// STREAM_TYPE can be 1 for stdout and 2 for stderr -// -// SIZE1, SIZE2, SIZE3, and SIZE4 are four bytes of uint32 encoded as big endian. -// This is the size of OUTPUT. -// -// You can use github.com/docker/docker/pkg/stdcopy.StdCopy to demultiplex this -// stream. -func (cli *Client) ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) { - query := url.Values{} - if options.Stream { - query.Set("stream", "1") - } - if options.Stdin { - query.Set("stdin", "1") - } - if options.Stdout { - query.Set("stdout", "1") - } - if options.Stderr { - query.Set("stderr", "1") - } - if options.DetachKeys != "" { - query.Set("detachKeys", options.DetachKeys) - } - if options.Logs { - query.Set("logs", "1") - } - - headers := map[string][]string{"Content-Type": {"text/plain"}} - return cli.postHijacked(ctx, "/containers/"+container+"/attach", query, nil, headers) -} diff --git a/vendor/github.com/docker/docker/client/container_commit.go b/vendor/github.com/docker/docker/client/container_commit.go deleted file mode 100644 index 2966e88c..00000000 --- a/vendor/github.com/docker/docker/client/container_commit.go +++ /dev/null @@ -1,55 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "errors" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" -) - -// ContainerCommit applies changes into a container and creates a new tagged image. -func (cli *Client) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) { - var repository, tag string - if options.Reference != "" { - ref, err := reference.ParseNormalizedNamed(options.Reference) - if err != nil { - return types.IDResponse{}, err - } - - if _, isCanonical := ref.(reference.Canonical); isCanonical { - return types.IDResponse{}, errors.New("refusing to create a tag with a digest reference") - } - ref = reference.TagNameOnly(ref) - - if tagged, ok := ref.(reference.Tagged); ok { - tag = tagged.Tag() - } - repository = reference.FamiliarName(ref) - } - - query := url.Values{} - query.Set("container", container) - query.Set("repo", repository) - query.Set("tag", tag) - query.Set("comment", options.Comment) - query.Set("author", options.Author) - for _, change := range options.Changes { - query.Add("changes", change) - } - if !options.Pause { - query.Set("pause", "0") - } - - var response types.IDResponse - resp, err := cli.post(ctx, "/commit", query, options.Config, nil) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_copy.go b/vendor/github.com/docker/docker/client/container_copy.go deleted file mode 100644 index bb278bf7..00000000 --- a/vendor/github.com/docker/docker/client/container_copy.go +++ /dev/null @@ -1,103 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path/filepath" - "strings" - - "github.com/docker/docker/api/types" -) - -// ContainerStatPath returns Stat information about a path inside the container filesystem. -func (cli *Client) ContainerStatPath(ctx context.Context, containerID, path string) (types.ContainerPathStat, error) { - query := url.Values{} - query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API. - - urlStr := "/containers/" + containerID + "/archive" - response, err := cli.head(ctx, urlStr, query, nil) - defer ensureReaderClosed(response) - if err != nil { - return types.ContainerPathStat{}, wrapResponseError(err, response, "container:path", containerID+":"+path) - } - return getContainerPathStatFromHeader(response.header) -} - -// CopyToContainer copies content into the container filesystem. -// Note that `content` must be a Reader for a TAR archive -func (cli *Client) CopyToContainer(ctx context.Context, containerID, dstPath string, content io.Reader, options types.CopyToContainerOptions) error { - query := url.Values{} - query.Set("path", filepath.ToSlash(dstPath)) // Normalize the paths used in the API. - // Do not allow for an existing directory to be overwritten by a non-directory and vice versa. - if !options.AllowOverwriteDirWithFile { - query.Set("noOverwriteDirNonDir", "true") - } - - if options.CopyUIDGID { - query.Set("copyUIDGID", "true") - } - - apiPath := "/containers/" + containerID + "/archive" - - response, err := cli.putRaw(ctx, apiPath, query, content, nil) - defer ensureReaderClosed(response) - if err != nil { - return wrapResponseError(err, response, "container:path", containerID+":"+dstPath) - } - - // TODO this code converts non-error status-codes (e.g., "204 No Content") into an error; verify if this is the desired behavior - if response.statusCode != http.StatusOK { - return fmt.Errorf("unexpected status code from daemon: %d", response.statusCode) - } - - return nil -} - -// CopyFromContainer gets the content from the container and returns it as a Reader -// for a TAR archive to manipulate it in the host. It's up to the caller to close the reader. -func (cli *Client) CopyFromContainer(ctx context.Context, containerID, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) { - query := make(url.Values, 1) - query.Set("path", filepath.ToSlash(srcPath)) // Normalize the paths used in the API. - - apiPath := "/containers/" + containerID + "/archive" - response, err := cli.get(ctx, apiPath, query, nil) - if err != nil { - return nil, types.ContainerPathStat{}, wrapResponseError(err, response, "container:path", containerID+":"+srcPath) - } - - // TODO this code converts non-error status-codes (e.g., "204 No Content") into an error; verify if this is the desired behavior - if response.statusCode != http.StatusOK { - return nil, types.ContainerPathStat{}, fmt.Errorf("unexpected status code from daemon: %d", response.statusCode) - } - - // In order to get the copy behavior right, we need to know information - // about both the source and the destination. The response headers include - // stat info about the source that we can use in deciding exactly how to - // copy it locally. Along with the stat info about the local destination, - // we have everything we need to handle the multiple possibilities there - // can be when copying a file/dir from one location to another file/dir. - stat, err := getContainerPathStatFromHeader(response.header) - if err != nil { - return nil, stat, fmt.Errorf("unable to get resource stat from response: %s", err) - } - return response.body, stat, err -} - -func getContainerPathStatFromHeader(header http.Header) (types.ContainerPathStat, error) { - var stat types.ContainerPathStat - - encodedStat := header.Get("X-Docker-Container-Path-Stat") - statDecoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encodedStat)) - - err := json.NewDecoder(statDecoder).Decode(&stat) - if err != nil { - err = fmt.Errorf("unable to decode container path stat header: %s", err) - } - - return stat, err -} diff --git a/vendor/github.com/docker/docker/client/container_create.go b/vendor/github.com/docker/docker/client/container_create.go deleted file mode 100644 index b1d5fea5..00000000 --- a/vendor/github.com/docker/docker/client/container_create.go +++ /dev/null @@ -1,63 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/containerd/containerd/platforms" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/versions" - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -type configWrapper struct { - *container.Config - HostConfig *container.HostConfig - NetworkingConfig *network.NetworkingConfig - Platform *specs.Platform -} - -// ContainerCreate creates a new container based in the given configuration. -// It can be associated with a name, but it's not mandatory. -func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *specs.Platform, containerName string) (container.ContainerCreateCreatedBody, error) { - var response container.ContainerCreateCreatedBody - - if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil { - return response, err - } - - // When using API 1.24 and under, the client is responsible for removing the container - if hostConfig != nil && versions.LessThan(cli.ClientVersion(), "1.25") { - hostConfig.AutoRemove = false - } - - if err := cli.NewVersionError("1.41", "specify container image platform"); platform != nil && err != nil { - return response, err - } - - query := url.Values{} - if platform != nil { - query.Set("platform", platforms.Format(*platform)) - } - - if containerName != "" { - query.Set("name", containerName) - } - - body := configWrapper{ - Config: config, - HostConfig: hostConfig, - NetworkingConfig: networkingConfig, - } - - serverResp, err := cli.post(ctx, "/containers/create", query, body, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return response, err - } - - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_diff.go b/vendor/github.com/docker/docker/client/container_diff.go deleted file mode 100644 index 29dac849..00000000 --- a/vendor/github.com/docker/docker/client/container_diff.go +++ /dev/null @@ -1,23 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/container" -) - -// ContainerDiff shows differences in a container filesystem since it was started. -func (cli *Client) ContainerDiff(ctx context.Context, containerID string) ([]container.ContainerChangeResponseItem, error) { - var changes []container.ContainerChangeResponseItem - - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/changes", url.Values{}, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return changes, err - } - - err = json.NewDecoder(serverResp.body).Decode(&changes) - return changes, err -} diff --git a/vendor/github.com/docker/docker/client/container_exec.go b/vendor/github.com/docker/docker/client/container_exec.go deleted file mode 100644 index e3ee755b..00000000 --- a/vendor/github.com/docker/docker/client/container_exec.go +++ /dev/null @@ -1,54 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" -) - -// ContainerExecCreate creates a new exec configuration to run an exec process. -func (cli *Client) ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) { - var response types.IDResponse - - if err := cli.NewVersionError("1.25", "env"); len(config.Env) != 0 && err != nil { - return response, err - } - - resp, err := cli.post(ctx, "/containers/"+container+"/exec", nil, config, nil) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} - -// ContainerExecStart starts an exec process already created in the docker host. -func (cli *Client) ContainerExecStart(ctx context.Context, execID string, config types.ExecStartCheck) error { - resp, err := cli.post(ctx, "/exec/"+execID+"/start", nil, config, nil) - ensureReaderClosed(resp) - return err -} - -// ContainerExecAttach attaches a connection to an exec process in the server. -// It returns a types.HijackedConnection with the hijacked connection -// and the a reader to get output. It's up to the called to close -// the hijacked connection by calling types.HijackedResponse.Close. -func (cli *Client) ContainerExecAttach(ctx context.Context, execID string, config types.ExecStartCheck) (types.HijackedResponse, error) { - headers := map[string][]string{"Content-Type": {"application/json"}} - return cli.postHijacked(ctx, "/exec/"+execID+"/start", nil, config, headers) -} - -// ContainerExecInspect returns information about a specific exec process on the docker host. -func (cli *Client) ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) { - var response types.ContainerExecInspect - resp, err := cli.get(ctx, "/exec/"+execID+"/json", nil, nil) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - ensureReaderClosed(resp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_export.go b/vendor/github.com/docker/docker/client/container_export.go deleted file mode 100644 index d0c0a5cb..00000000 --- a/vendor/github.com/docker/docker/client/container_export.go +++ /dev/null @@ -1,19 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" -) - -// ContainerExport retrieves the raw contents of a container -// and returns them as an io.ReadCloser. It's up to the caller -// to close the stream. -func (cli *Client) ContainerExport(ctx context.Context, containerID string) (io.ReadCloser, error) { - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/export", url.Values{}, nil) - if err != nil { - return nil, err - } - - return serverResp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/container_inspect.go b/vendor/github.com/docker/docker/client/container_inspect.go deleted file mode 100644 index c496bcff..00000000 --- a/vendor/github.com/docker/docker/client/container_inspect.go +++ /dev/null @@ -1,53 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ContainerInspect returns the container information. -func (cli *Client) ContainerInspect(ctx context.Context, containerID string) (types.ContainerJSON, error) { - if containerID == "" { - return types.ContainerJSON{}, objectNotFoundError{object: "container", id: containerID} - } - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/json", nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return types.ContainerJSON{}, wrapResponseError(err, serverResp, "container", containerID) - } - - var response types.ContainerJSON - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} - -// ContainerInspectWithRaw returns the container information and its raw representation. -func (cli *Client) ContainerInspectWithRaw(ctx context.Context, containerID string, getSize bool) (types.ContainerJSON, []byte, error) { - if containerID == "" { - return types.ContainerJSON{}, nil, objectNotFoundError{object: "container", id: containerID} - } - query := url.Values{} - if getSize { - query.Set("size", "1") - } - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/json", query, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return types.ContainerJSON{}, nil, wrapResponseError(err, serverResp, "container", containerID) - } - - body, err := ioutil.ReadAll(serverResp.body) - if err != nil { - return types.ContainerJSON{}, nil, err - } - - var response types.ContainerJSON - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/container_kill.go b/vendor/github.com/docker/docker/client/container_kill.go deleted file mode 100644 index 4d6f1d23..00000000 --- a/vendor/github.com/docker/docker/client/container_kill.go +++ /dev/null @@ -1,16 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" -) - -// ContainerKill terminates the container process but does not remove the container from the docker host. -func (cli *Client) ContainerKill(ctx context.Context, containerID, signal string) error { - query := url.Values{} - query.Set("signal", signal) - - resp, err := cli.post(ctx, "/containers/"+containerID+"/kill", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_list.go b/vendor/github.com/docker/docker/client/container_list.go deleted file mode 100644 index a973de59..00000000 --- a/vendor/github.com/docker/docker/client/container_list.go +++ /dev/null @@ -1,57 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - "strconv" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// ContainerList returns the list of containers in the docker host. -func (cli *Client) ContainerList(ctx context.Context, options types.ContainerListOptions) ([]types.Container, error) { - query := url.Values{} - - if options.All { - query.Set("all", "1") - } - - if options.Limit != -1 { - query.Set("limit", strconv.Itoa(options.Limit)) - } - - if options.Since != "" { - query.Set("since", options.Since) - } - - if options.Before != "" { - query.Set("before", options.Before) - } - - if options.Size { - query.Set("size", "1") - } - - if options.Filters.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) - - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/containers/json", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var containers []types.Container - err = json.NewDecoder(resp.body).Decode(&containers) - return containers, err -} diff --git a/vendor/github.com/docker/docker/client/container_logs.go b/vendor/github.com/docker/docker/client/container_logs.go deleted file mode 100644 index 5b6541f0..00000000 --- a/vendor/github.com/docker/docker/client/container_logs.go +++ /dev/null @@ -1,80 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "time" - - "github.com/docker/docker/api/types" - timetypes "github.com/docker/docker/api/types/time" - "github.com/pkg/errors" -) - -// ContainerLogs returns the logs generated by a container in an io.ReadCloser. -// It's up to the caller to close the stream. -// -// The stream format on the response will be in one of two formats: -// -// If the container is using a TTY, there is only a single stream (stdout), and -// data is copied directly from the container output stream, no extra -// multiplexing or headers. -// -// If the container is *not* using a TTY, streams for stdout and stderr are -// multiplexed. -// The format of the multiplexed stream is as follows: -// -// [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4}[]byte{OUTPUT} -// -// STREAM_TYPE can be 1 for stdout and 2 for stderr -// -// SIZE1, SIZE2, SIZE3, and SIZE4 are four bytes of uint32 encoded as big endian. -// This is the size of OUTPUT. -// -// You can use github.com/docker/docker/pkg/stdcopy.StdCopy to demultiplex this -// stream. -func (cli *Client) ContainerLogs(ctx context.Context, container string, options types.ContainerLogsOptions) (io.ReadCloser, error) { - query := url.Values{} - if options.ShowStdout { - query.Set("stdout", "1") - } - - if options.ShowStderr { - query.Set("stderr", "1") - } - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, time.Now()) - if err != nil { - return nil, errors.Wrap(err, `invalid value for "since"`) - } - query.Set("since", ts) - } - - if options.Until != "" { - ts, err := timetypes.GetTimestamp(options.Until, time.Now()) - if err != nil { - return nil, errors.Wrap(err, `invalid value for "until"`) - } - query.Set("until", ts) - } - - if options.Timestamps { - query.Set("timestamps", "1") - } - - if options.Details { - query.Set("details", "1") - } - - if options.Follow { - query.Set("follow", "1") - } - query.Set("tail", options.Tail) - - resp, err := cli.get(ctx, "/containers/"+container+"/logs", query, nil) - if err != nil { - return nil, wrapResponseError(err, resp, "container", container) - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/container_pause.go b/vendor/github.com/docker/docker/client/container_pause.go deleted file mode 100644 index 5e7271a3..00000000 --- a/vendor/github.com/docker/docker/client/container_pause.go +++ /dev/null @@ -1,10 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// ContainerPause pauses the main process of a given container without terminating it. -func (cli *Client) ContainerPause(ctx context.Context, containerID string) error { - resp, err := cli.post(ctx, "/containers/"+containerID+"/pause", nil, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_prune.go b/vendor/github.com/docker/docker/client/container_prune.go deleted file mode 100644 index 04383dea..00000000 --- a/vendor/github.com/docker/docker/client/container_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// ContainersPrune requests the daemon to delete unused data -func (cli *Client) ContainersPrune(ctx context.Context, pruneFilters filters.Args) (types.ContainersPruneReport, error) { - var report types.ContainersPruneReport - - if err := cli.NewVersionError("1.25", "container prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/containers/prune", query, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return report, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving disk usage: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/container_remove.go b/vendor/github.com/docker/docker/client/container_remove.go deleted file mode 100644 index df81461b..00000000 --- a/vendor/github.com/docker/docker/client/container_remove.go +++ /dev/null @@ -1,27 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ContainerRemove kills and removes a container from the docker host. -func (cli *Client) ContainerRemove(ctx context.Context, containerID string, options types.ContainerRemoveOptions) error { - query := url.Values{} - if options.RemoveVolumes { - query.Set("v", "1") - } - if options.RemoveLinks { - query.Set("link", "1") - } - - if options.Force { - query.Set("force", "1") - } - - resp, err := cli.delete(ctx, "/containers/"+containerID, query, nil) - defer ensureReaderClosed(resp) - return wrapResponseError(err, resp, "container", containerID) -} diff --git a/vendor/github.com/docker/docker/client/container_rename.go b/vendor/github.com/docker/docker/client/container_rename.go deleted file mode 100644 index 240fdf55..00000000 --- a/vendor/github.com/docker/docker/client/container_rename.go +++ /dev/null @@ -1,15 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" -) - -// ContainerRename changes the name of a given container. -func (cli *Client) ContainerRename(ctx context.Context, containerID, newContainerName string) error { - query := url.Values{} - query.Set("name", newContainerName) - resp, err := cli.post(ctx, "/containers/"+containerID+"/rename", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_resize.go b/vendor/github.com/docker/docker/client/container_resize.go deleted file mode 100644 index a9d4c0c7..00000000 --- a/vendor/github.com/docker/docker/client/container_resize.go +++ /dev/null @@ -1,29 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "strconv" - - "github.com/docker/docker/api/types" -) - -// ContainerResize changes the size of the tty for a container. -func (cli *Client) ContainerResize(ctx context.Context, containerID string, options types.ResizeOptions) error { - return cli.resize(ctx, "/containers/"+containerID, options.Height, options.Width) -} - -// ContainerExecResize changes the size of the tty for an exec process running inside a container. -func (cli *Client) ContainerExecResize(ctx context.Context, execID string, options types.ResizeOptions) error { - return cli.resize(ctx, "/exec/"+execID, options.Height, options.Width) -} - -func (cli *Client) resize(ctx context.Context, basePath string, height, width uint) error { - query := url.Values{} - query.Set("h", strconv.Itoa(int(height))) - query.Set("w", strconv.Itoa(int(width))) - - resp, err := cli.post(ctx, basePath+"/resize", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_restart.go b/vendor/github.com/docker/docker/client/container_restart.go deleted file mode 100644 index 41e42196..00000000 --- a/vendor/github.com/docker/docker/client/container_restart.go +++ /dev/null @@ -1,22 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "time" - - timetypes "github.com/docker/docker/api/types/time" -) - -// ContainerRestart stops and starts a container again. -// It makes the daemon to wait for the container to be up again for -// a specific amount of time, given the timeout. -func (cli *Client) ContainerRestart(ctx context.Context, containerID string, timeout *time.Duration) error { - query := url.Values{} - if timeout != nil { - query.Set("t", timetypes.DurationToSecondsString(*timeout)) - } - resp, err := cli.post(ctx, "/containers/"+containerID+"/restart", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_start.go b/vendor/github.com/docker/docker/client/container_start.go deleted file mode 100644 index c2e0b15d..00000000 --- a/vendor/github.com/docker/docker/client/container_start.go +++ /dev/null @@ -1,23 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ContainerStart sends a request to the docker daemon to start a container. -func (cli *Client) ContainerStart(ctx context.Context, containerID string, options types.ContainerStartOptions) error { - query := url.Values{} - if len(options.CheckpointID) != 0 { - query.Set("checkpoint", options.CheckpointID) - } - if len(options.CheckpointDir) != 0 { - query.Set("checkpoint-dir", options.CheckpointDir) - } - - resp, err := cli.post(ctx, "/containers/"+containerID+"/start", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_stats.go b/vendor/github.com/docker/docker/client/container_stats.go deleted file mode 100644 index 0a6488dd..00000000 --- a/vendor/github.com/docker/docker/client/container_stats.go +++ /dev/null @@ -1,42 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ContainerStats returns near realtime stats for a given container. -// It's up to the caller to close the io.ReadCloser returned. -func (cli *Client) ContainerStats(ctx context.Context, containerID string, stream bool) (types.ContainerStats, error) { - query := url.Values{} - query.Set("stream", "0") - if stream { - query.Set("stream", "1") - } - - resp, err := cli.get(ctx, "/containers/"+containerID+"/stats", query, nil) - if err != nil { - return types.ContainerStats{}, err - } - - osType := getDockerOS(resp.header.Get("Server")) - return types.ContainerStats{Body: resp.body, OSType: osType}, err -} - -// ContainerStatsOneShot gets a single stat entry from a container. -// It differs from `ContainerStats` in that the API should not wait to prime the stats -func (cli *Client) ContainerStatsOneShot(ctx context.Context, containerID string) (types.ContainerStats, error) { - query := url.Values{} - query.Set("stream", "0") - query.Set("one-shot", "1") - - resp, err := cli.get(ctx, "/containers/"+containerID+"/stats", query, nil) - if err != nil { - return types.ContainerStats{}, err - } - - osType := getDockerOS(resp.header.Get("Server")) - return types.ContainerStats{Body: resp.body, OSType: osType}, err -} diff --git a/vendor/github.com/docker/docker/client/container_stop.go b/vendor/github.com/docker/docker/client/container_stop.go deleted file mode 100644 index 629d7ab6..00000000 --- a/vendor/github.com/docker/docker/client/container_stop.go +++ /dev/null @@ -1,26 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "time" - - timetypes "github.com/docker/docker/api/types/time" -) - -// ContainerStop stops a container. In case the container fails to stop -// gracefully within a time frame specified by the timeout argument, -// it is forcefully terminated (killed). -// -// If the timeout is nil, the container's StopTimeout value is used, if set, -// otherwise the engine default. A negative timeout value can be specified, -// meaning no timeout, i.e. no forceful termination is performed. -func (cli *Client) ContainerStop(ctx context.Context, containerID string, timeout *time.Duration) error { - query := url.Values{} - if timeout != nil { - query.Set("t", timetypes.DurationToSecondsString(*timeout)) - } - resp, err := cli.post(ctx, "/containers/"+containerID+"/stop", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_top.go b/vendor/github.com/docker/docker/client/container_top.go deleted file mode 100644 index a5b78999..00000000 --- a/vendor/github.com/docker/docker/client/container_top.go +++ /dev/null @@ -1,28 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - "strings" - - "github.com/docker/docker/api/types/container" -) - -// ContainerTop shows process information from within a container. -func (cli *Client) ContainerTop(ctx context.Context, containerID string, arguments []string) (container.ContainerTopOKBody, error) { - var response container.ContainerTopOKBody - query := url.Values{} - if len(arguments) > 0 { - query.Set("ps_args", strings.Join(arguments, " ")) - } - - resp, err := cli.get(ctx, "/containers/"+containerID+"/top", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_unpause.go b/vendor/github.com/docker/docker/client/container_unpause.go deleted file mode 100644 index 1d8f8731..00000000 --- a/vendor/github.com/docker/docker/client/container_unpause.go +++ /dev/null @@ -1,10 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// ContainerUnpause resumes the process execution within a container -func (cli *Client) ContainerUnpause(ctx context.Context, containerID string) error { - resp, err := cli.post(ctx, "/containers/"+containerID+"/unpause", nil, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_update.go b/vendor/github.com/docker/docker/client/container_update.go deleted file mode 100644 index 6917cf9f..00000000 --- a/vendor/github.com/docker/docker/client/container_update.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types/container" -) - -// ContainerUpdate updates resources of a container -func (cli *Client) ContainerUpdate(ctx context.Context, containerID string, updateConfig container.UpdateConfig) (container.ContainerUpdateOKBody, error) { - var response container.ContainerUpdateOKBody - serverResp, err := cli.post(ctx, "/containers/"+containerID+"/update", nil, updateConfig, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return response, err - } - - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_wait.go b/vendor/github.com/docker/docker/client/container_wait.go deleted file mode 100644 index 6ab8c1da..00000000 --- a/vendor/github.com/docker/docker/client/container_wait.go +++ /dev/null @@ -1,83 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/versions" -) - -// ContainerWait waits until the specified container is in a certain state -// indicated by the given condition, either "not-running" (default), -// "next-exit", or "removed". -// -// If this client's API version is before 1.30, condition is ignored and -// ContainerWait will return immediately with the two channels, as the server -// will wait as if the condition were "not-running". -// -// If this client's API version is at least 1.30, ContainerWait blocks until -// the request has been acknowledged by the server (with a response header), -// then returns two channels on which the caller can wait for the exit status -// of the container or an error if there was a problem either beginning the -// wait request or in getting the response. This allows the caller to -// synchronize ContainerWait with other calls, such as specifying a -// "next-exit" condition before issuing a ContainerStart request. -func (cli *Client) ContainerWait(ctx context.Context, containerID string, condition container.WaitCondition) (<-chan container.ContainerWaitOKBody, <-chan error) { - if versions.LessThan(cli.ClientVersion(), "1.30") { - return cli.legacyContainerWait(ctx, containerID) - } - - resultC := make(chan container.ContainerWaitOKBody) - errC := make(chan error, 1) - - query := url.Values{} - query.Set("condition", string(condition)) - - resp, err := cli.post(ctx, "/containers/"+containerID+"/wait", query, nil, nil) - if err != nil { - defer ensureReaderClosed(resp) - errC <- err - return resultC, errC - } - - go func() { - defer ensureReaderClosed(resp) - var res container.ContainerWaitOKBody - if err := json.NewDecoder(resp.body).Decode(&res); err != nil { - errC <- err - return - } - - resultC <- res - }() - - return resultC, errC -} - -// legacyContainerWait returns immediately and doesn't have an option to wait -// until the container is removed. -func (cli *Client) legacyContainerWait(ctx context.Context, containerID string) (<-chan container.ContainerWaitOKBody, <-chan error) { - resultC := make(chan container.ContainerWaitOKBody) - errC := make(chan error) - - go func() { - resp, err := cli.post(ctx, "/containers/"+containerID+"/wait", nil, nil, nil) - if err != nil { - errC <- err - return - } - defer ensureReaderClosed(resp) - - var res container.ContainerWaitOKBody - if err := json.NewDecoder(resp.body).Decode(&res); err != nil { - errC <- err - return - } - - resultC <- res - }() - - return resultC, errC -} diff --git a/vendor/github.com/docker/docker/client/disk_usage.go b/vendor/github.com/docker/docker/client/disk_usage.go deleted file mode 100644 index 354cd369..00000000 --- a/vendor/github.com/docker/docker/client/disk_usage.go +++ /dev/null @@ -1,26 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" -) - -// DiskUsage requests the current data usage from the daemon -func (cli *Client) DiskUsage(ctx context.Context) (types.DiskUsage, error) { - var du types.DiskUsage - - serverResp, err := cli.get(ctx, "/system/df", nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return du, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&du); err != nil { - return du, fmt.Errorf("Error retrieving disk usage: %v", err) - } - - return du, nil -} diff --git a/vendor/github.com/docker/docker/client/distribution_inspect.go b/vendor/github.com/docker/docker/client/distribution_inspect.go deleted file mode 100644 index f4e3794c..00000000 --- a/vendor/github.com/docker/docker/client/distribution_inspect.go +++ /dev/null @@ -1,38 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - registrytypes "github.com/docker/docker/api/types/registry" -) - -// DistributionInspect returns the image digest with full Manifest -func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegistryAuth string) (registrytypes.DistributionInspect, error) { - // Contact the registry to retrieve digest and platform information - var distributionInspect registrytypes.DistributionInspect - if image == "" { - return distributionInspect, objectNotFoundError{object: "distribution", id: image} - } - - if err := cli.NewVersionError("1.30", "distribution inspect"); err != nil { - return distributionInspect, err - } - var headers map[string][]string - - if encodedRegistryAuth != "" { - headers = map[string][]string{ - "X-Registry-Auth": {encodedRegistryAuth}, - } - } - - resp, err := cli.get(ctx, "/distribution/"+image+"/json", url.Values{}, headers) - defer ensureReaderClosed(resp) - if err != nil { - return distributionInspect, err - } - - err = json.NewDecoder(resp.body).Decode(&distributionInspect) - return distributionInspect, err -} diff --git a/vendor/github.com/docker/docker/client/errors.go b/vendor/github.com/docker/docker/client/errors.go deleted file mode 100644 index 041bc8d4..00000000 --- a/vendor/github.com/docker/docker/client/errors.go +++ /dev/null @@ -1,138 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "fmt" - "net/http" - - "github.com/docker/docker/api/types/versions" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" -) - -// errConnectionFailed implements an error returned when connection failed. -type errConnectionFailed struct { - host string -} - -// Error returns a string representation of an errConnectionFailed -func (err errConnectionFailed) Error() string { - if err.host == "" { - return "Cannot connect to the Docker daemon. Is the docker daemon running on this host?" - } - return fmt.Sprintf("Cannot connect to the Docker daemon at %s. Is the docker daemon running?", err.host) -} - -// IsErrConnectionFailed returns true if the error is caused by connection failed. -func IsErrConnectionFailed(err error) bool { - return errors.As(err, &errConnectionFailed{}) -} - -// ErrorConnectionFailed returns an error with host in the error message when connection to docker daemon failed. -func ErrorConnectionFailed(host string) error { - return errConnectionFailed{host: host} -} - -// Deprecated: use the errdefs.NotFound() interface instead. Kept for backward compatibility -type notFound interface { - error - NotFound() bool -} - -// IsErrNotFound returns true if the error is a NotFound error, which is returned -// by the API when some object is not found. -func IsErrNotFound(err error) bool { - var e notFound - if errors.As(err, &e) { - return true - } - return errdefs.IsNotFound(err) -} - -type objectNotFoundError struct { - object string - id string -} - -func (e objectNotFoundError) NotFound() {} - -func (e objectNotFoundError) Error() string { - return fmt.Sprintf("Error: No such %s: %s", e.object, e.id) -} - -func wrapResponseError(err error, resp serverResponse, object, id string) error { - switch { - case err == nil: - return nil - case resp.statusCode == http.StatusNotFound: - return objectNotFoundError{object: object, id: id} - case resp.statusCode == http.StatusNotImplemented: - return errdefs.NotImplemented(err) - default: - return err - } -} - -// unauthorizedError represents an authorization error in a remote registry. -type unauthorizedError struct { - cause error -} - -// Error returns a string representation of an unauthorizedError -func (u unauthorizedError) Error() string { - return u.cause.Error() -} - -// IsErrUnauthorized returns true if the error is caused -// when a remote registry authentication fails -func IsErrUnauthorized(err error) bool { - if _, ok := err.(unauthorizedError); ok { - return ok - } - return errdefs.IsUnauthorized(err) -} - -type pluginPermissionDenied struct { - name string -} - -func (e pluginPermissionDenied) Error() string { - return "Permission denied while installing plugin " + e.name -} - -// IsErrPluginPermissionDenied returns true if the error is caused -// when a user denies a plugin's permissions -func IsErrPluginPermissionDenied(err error) bool { - _, ok := err.(pluginPermissionDenied) - return ok -} - -type notImplementedError struct { - message string -} - -func (e notImplementedError) Error() string { - return e.message -} - -func (e notImplementedError) NotImplemented() bool { - return true -} - -// IsErrNotImplemented returns true if the error is a NotImplemented error. -// This is returned by the API when a requested feature has not been -// implemented. -func IsErrNotImplemented(err error) bool { - if _, ok := err.(notImplementedError); ok { - return ok - } - return errdefs.IsNotImplemented(err) -} - -// NewVersionError returns an error if the APIVersion required -// if less than the current supported version -func (cli *Client) NewVersionError(APIrequired, feature string) error { - if cli.version != "" && versions.LessThan(cli.version, APIrequired) { - return fmt.Errorf("%q requires API version %s, but the Docker daemon API version is %s", feature, APIrequired, cli.version) - } - return nil -} diff --git a/vendor/github.com/docker/docker/client/events.go b/vendor/github.com/docker/docker/client/events.go deleted file mode 100644 index f0dc9d9e..00000000 --- a/vendor/github.com/docker/docker/client/events.go +++ /dev/null @@ -1,102 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - "time" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/events" - "github.com/docker/docker/api/types/filters" - timetypes "github.com/docker/docker/api/types/time" -) - -// Events returns a stream of events in the daemon. It's up to the caller to close the stream -// by cancelling the context. Once the stream has been completely read an io.EOF error will -// be sent over the error channel. If an error is sent all processing will be stopped. It's up -// to the caller to reopen the stream in the event of an error by reinvoking this method. -func (cli *Client) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) { - - messages := make(chan events.Message) - errs := make(chan error, 1) - - started := make(chan struct{}) - go func() { - defer close(errs) - - query, err := buildEventsQueryParams(cli.version, options) - if err != nil { - close(started) - errs <- err - return - } - - resp, err := cli.get(ctx, "/events", query, nil) - if err != nil { - close(started) - errs <- err - return - } - defer resp.body.Close() - - decoder := json.NewDecoder(resp.body) - - close(started) - for { - select { - case <-ctx.Done(): - errs <- ctx.Err() - return - default: - var event events.Message - if err := decoder.Decode(&event); err != nil { - errs <- err - return - } - - select { - case messages <- event: - case <-ctx.Done(): - errs <- ctx.Err() - return - } - } - } - }() - <-started - - return messages, errs -} - -func buildEventsQueryParams(cliVersion string, options types.EventsOptions) (url.Values, error) { - query := url.Values{} - ref := time.Now() - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, ref) - if err != nil { - return nil, err - } - query.Set("since", ts) - } - - if options.Until != "" { - ts, err := timetypes.GetTimestamp(options.Until, ref) - if err != nil { - return nil, err - } - query.Set("until", ts) - } - - if options.Filters.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cliVersion, options.Filters) - if err != nil { - return nil, err - } - query.Set("filters", filterJSON) - } - - return query, nil -} diff --git a/vendor/github.com/docker/docker/client/hijack.go b/vendor/github.com/docker/docker/client/hijack.go deleted file mode 100644 index e1dc49ef..00000000 --- a/vendor/github.com/docker/docker/client/hijack.go +++ /dev/null @@ -1,145 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bufio" - "context" - "crypto/tls" - "fmt" - "net" - "net/http" - "net/http/httputil" - "net/url" - "time" - - "github.com/docker/docker/api/types" - "github.com/docker/go-connections/sockets" - "github.com/pkg/errors" -) - -// postHijacked sends a POST request and hijacks the connection. -func (cli *Client) postHijacked(ctx context.Context, path string, query url.Values, body interface{}, headers map[string][]string) (types.HijackedResponse, error) { - bodyEncoded, err := encodeData(body) - if err != nil { - return types.HijackedResponse{}, err - } - - apiPath := cli.getAPIPath(ctx, path, query) - req, err := http.NewRequest(http.MethodPost, apiPath, bodyEncoded) - if err != nil { - return types.HijackedResponse{}, err - } - req = cli.addHeaders(req, headers) - - conn, err := cli.setupHijackConn(ctx, req, "tcp") - if err != nil { - return types.HijackedResponse{}, err - } - - return types.HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn)}, err -} - -// DialHijack returns a hijacked connection with negotiated protocol proto. -func (cli *Client) DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error) { - req, err := http.NewRequest(http.MethodPost, url, nil) - if err != nil { - return nil, err - } - req = cli.addHeaders(req, meta) - - return cli.setupHijackConn(ctx, req, proto) -} - -// fallbackDial is used when WithDialer() was not called. -// See cli.Dialer(). -func fallbackDial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) { - if tlsConfig != nil && proto != "unix" && proto != "npipe" { - return tls.Dial(proto, addr, tlsConfig) - } - if proto == "npipe" { - return sockets.DialPipe(addr, 32*time.Second) - } - return net.Dial(proto, addr) -} - -func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto string) (net.Conn, error) { - req.Host = cli.addr - req.Header.Set("Connection", "Upgrade") - req.Header.Set("Upgrade", proto) - - dialer := cli.Dialer() - conn, err := dialer(ctx) - if err != nil { - return nil, errors.Wrap(err, "cannot connect to the Docker daemon. Is 'docker daemon' running on this host?") - } - - // When we set up a TCP connection for hijack, there could be long periods - // of inactivity (a long running command with no output) that in certain - // network setups may cause ECONNTIMEOUT, leaving the client in an unknown - // state. Setting TCP KeepAlive on the socket connection will prohibit - // ECONNTIMEOUT unless the socket connection truly is broken - if tcpConn, ok := conn.(*net.TCPConn); ok { - tcpConn.SetKeepAlive(true) - tcpConn.SetKeepAlivePeriod(30 * time.Second) - } - - clientconn := httputil.NewClientConn(conn, nil) - defer clientconn.Close() - - // Server hijacks the connection, error 'connection closed' expected - resp, err := clientconn.Do(req) - - //nolint:staticcheck // ignore SA1019 for connecting to old (pre go1.8) daemons - if err != httputil.ErrPersistEOF { - if err != nil { - return nil, err - } - if resp.StatusCode != http.StatusSwitchingProtocols { - resp.Body.Close() - return nil, fmt.Errorf("unable to upgrade to %s, received %d", proto, resp.StatusCode) - } - } - - c, br := clientconn.Hijack() - if br.Buffered() > 0 { - // If there is buffered content, wrap the connection. We return an - // object that implements CloseWrite iff the underlying connection - // implements it. - if _, ok := c.(types.CloseWriter); ok { - c = &hijackedConnCloseWriter{&hijackedConn{c, br}} - } else { - c = &hijackedConn{c, br} - } - } else { - br.Reset(nil) - } - - return c, nil -} - -// hijackedConn wraps a net.Conn and is returned by setupHijackConn in the case -// that a) there was already buffered data in the http layer when Hijack() was -// called, and b) the underlying net.Conn does *not* implement CloseWrite(). -// hijackedConn does not implement CloseWrite() either. -type hijackedConn struct { - net.Conn - r *bufio.Reader -} - -func (c *hijackedConn) Read(b []byte) (int, error) { - return c.r.Read(b) -} - -// hijackedConnCloseWriter is a hijackedConn which additionally implements -// CloseWrite(). It is returned by setupHijackConn in the case that a) there -// was already buffered data in the http layer when Hijack() was called, and b) -// the underlying net.Conn *does* implement CloseWrite(). -type hijackedConnCloseWriter struct { - *hijackedConn -} - -var _ types.CloseWriter = &hijackedConnCloseWriter{} - -func (c *hijackedConnCloseWriter) CloseWrite() error { - conn := c.Conn.(types.CloseWriter) - return conn.CloseWrite() -} diff --git a/vendor/github.com/docker/docker/client/image_build.go b/vendor/github.com/docker/docker/client/image_build.go deleted file mode 100644 index 8fcf9950..00000000 --- a/vendor/github.com/docker/docker/client/image_build.go +++ /dev/null @@ -1,146 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/base64" - "encoding/json" - "io" - "net/http" - "net/url" - "strconv" - "strings" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" -) - -// ImageBuild sends request to the daemon to build images. -// The Body in the response implement an io.ReadCloser and it's up to the caller to -// close it. -func (cli *Client) ImageBuild(ctx context.Context, buildContext io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) { - query, err := cli.imageBuildOptionsToQuery(options) - if err != nil { - return types.ImageBuildResponse{}, err - } - - headers := http.Header(make(map[string][]string)) - buf, err := json.Marshal(options.AuthConfigs) - if err != nil { - return types.ImageBuildResponse{}, err - } - headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf)) - - headers.Set("Content-Type", "application/x-tar") - - serverResp, err := cli.postRaw(ctx, "/build", query, buildContext, headers) - if err != nil { - return types.ImageBuildResponse{}, err - } - - osType := getDockerOS(serverResp.header.Get("Server")) - - return types.ImageBuildResponse{ - Body: serverResp.body, - OSType: osType, - }, nil -} - -func (cli *Client) imageBuildOptionsToQuery(options types.ImageBuildOptions) (url.Values, error) { - query := url.Values{ - "t": options.Tags, - "securityopt": options.SecurityOpt, - "extrahosts": options.ExtraHosts, - } - if options.SuppressOutput { - query.Set("q", "1") - } - if options.RemoteContext != "" { - query.Set("remote", options.RemoteContext) - } - if options.NoCache { - query.Set("nocache", "1") - } - if options.Remove { - query.Set("rm", "1") - } else { - query.Set("rm", "0") - } - - if options.ForceRemove { - query.Set("forcerm", "1") - } - - if options.PullParent { - query.Set("pull", "1") - } - - if options.Squash { - if err := cli.NewVersionError("1.25", "squash"); err != nil { - return query, err - } - query.Set("squash", "1") - } - - if !container.Isolation.IsDefault(options.Isolation) { - query.Set("isolation", string(options.Isolation)) - } - - query.Set("cpusetcpus", options.CPUSetCPUs) - query.Set("networkmode", options.NetworkMode) - query.Set("cpusetmems", options.CPUSetMems) - query.Set("cpushares", strconv.FormatInt(options.CPUShares, 10)) - query.Set("cpuquota", strconv.FormatInt(options.CPUQuota, 10)) - query.Set("cpuperiod", strconv.FormatInt(options.CPUPeriod, 10)) - query.Set("memory", strconv.FormatInt(options.Memory, 10)) - query.Set("memswap", strconv.FormatInt(options.MemorySwap, 10)) - query.Set("cgroupparent", options.CgroupParent) - query.Set("shmsize", strconv.FormatInt(options.ShmSize, 10)) - query.Set("dockerfile", options.Dockerfile) - query.Set("target", options.Target) - - ulimitsJSON, err := json.Marshal(options.Ulimits) - if err != nil { - return query, err - } - query.Set("ulimits", string(ulimitsJSON)) - - buildArgsJSON, err := json.Marshal(options.BuildArgs) - if err != nil { - return query, err - } - query.Set("buildargs", string(buildArgsJSON)) - - labelsJSON, err := json.Marshal(options.Labels) - if err != nil { - return query, err - } - query.Set("labels", string(labelsJSON)) - - cacheFromJSON, err := json.Marshal(options.CacheFrom) - if err != nil { - return query, err - } - query.Set("cachefrom", string(cacheFromJSON)) - if options.SessionID != "" { - query.Set("session", options.SessionID) - } - if options.Platform != "" { - if err := cli.NewVersionError("1.32", "platform"); err != nil { - return query, err - } - query.Set("platform", strings.ToLower(options.Platform)) - } - if options.BuildID != "" { - query.Set("buildid", options.BuildID) - } - query.Set("version", string(options.Version)) - - if options.Outputs != nil { - outputsJSON, err := json.Marshal(options.Outputs) - if err != nil { - return query, err - } - query.Set("outputs", string(outputsJSON)) - } - return query, nil -} diff --git a/vendor/github.com/docker/docker/client/image_create.go b/vendor/github.com/docker/docker/client/image_create.go deleted file mode 100644 index 23938047..00000000 --- a/vendor/github.com/docker/docker/client/image_create.go +++ /dev/null @@ -1,37 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "strings" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" -) - -// ImageCreate creates a new image based in the parent options. -// It returns the JSON content in the response body. -func (cli *Client) ImageCreate(ctx context.Context, parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) { - ref, err := reference.ParseNormalizedNamed(parentReference) - if err != nil { - return nil, err - } - - query := url.Values{} - query.Set("fromImage", reference.FamiliarName(ref)) - query.Set("tag", getAPITagFromNamedRef(ref)) - if options.Platform != "" { - query.Set("platform", strings.ToLower(options.Platform)) - } - resp, err := cli.tryImageCreate(ctx, query, options.RegistryAuth) - if err != nil { - return nil, err - } - return resp.body, nil -} - -func (cli *Client) tryImageCreate(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.post(ctx, "/images/create", query, nil, headers) -} diff --git a/vendor/github.com/docker/docker/client/image_history.go b/vendor/github.com/docker/docker/client/image_history.go deleted file mode 100644 index b5bea10d..00000000 --- a/vendor/github.com/docker/docker/client/image_history.go +++ /dev/null @@ -1,22 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/image" -) - -// ImageHistory returns the changes in an image in history format. -func (cli *Client) ImageHistory(ctx context.Context, imageID string) ([]image.HistoryResponseItem, error) { - var history []image.HistoryResponseItem - serverResp, err := cli.get(ctx, "/images/"+imageID+"/history", url.Values{}, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return history, err - } - - err = json.NewDecoder(serverResp.body).Decode(&history) - return history, err -} diff --git a/vendor/github.com/docker/docker/client/image_import.go b/vendor/github.com/docker/docker/client/image_import.go deleted file mode 100644 index d3336d41..00000000 --- a/vendor/github.com/docker/docker/client/image_import.go +++ /dev/null @@ -1,40 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "strings" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" -) - -// ImageImport creates a new image based in the source options. -// It returns the JSON content in the response body. -func (cli *Client) ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { - if ref != "" { - // Check if the given image name can be resolved - if _, err := reference.ParseNormalizedNamed(ref); err != nil { - return nil, err - } - } - - query := url.Values{} - query.Set("fromSrc", source.SourceName) - query.Set("repo", ref) - query.Set("tag", options.Tag) - query.Set("message", options.Message) - if options.Platform != "" { - query.Set("platform", strings.ToLower(options.Platform)) - } - for _, change := range options.Changes { - query.Add("changes", change) - } - - resp, err := cli.postRaw(ctx, "/images/create", query, source.Source, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/image_inspect.go b/vendor/github.com/docker/docker/client/image_inspect.go deleted file mode 100644 index 1eb8dce0..00000000 --- a/vendor/github.com/docker/docker/client/image_inspect.go +++ /dev/null @@ -1,32 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - - "github.com/docker/docker/api/types" -) - -// ImageInspectWithRaw returns the image information and its raw representation. -func (cli *Client) ImageInspectWithRaw(ctx context.Context, imageID string) (types.ImageInspect, []byte, error) { - if imageID == "" { - return types.ImageInspect{}, nil, objectNotFoundError{object: "image", id: imageID} - } - serverResp, err := cli.get(ctx, "/images/"+imageID+"/json", nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return types.ImageInspect{}, nil, wrapResponseError(err, serverResp, "image", imageID) - } - - body, err := ioutil.ReadAll(serverResp.body) - if err != nil { - return types.ImageInspect{}, nil, err - } - - var response types.ImageInspect - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/image_list.go b/vendor/github.com/docker/docker/client/image_list.go deleted file mode 100644 index a4d75050..00000000 --- a/vendor/github.com/docker/docker/client/image_list.go +++ /dev/null @@ -1,46 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/versions" -) - -// ImageList returns a list of images in the docker host. -func (cli *Client) ImageList(ctx context.Context, options types.ImageListOptions) ([]types.ImageSummary, error) { - var images []types.ImageSummary - query := url.Values{} - - optionFilters := options.Filters - referenceFilters := optionFilters.Get("reference") - if versions.LessThan(cli.version, "1.25") && len(referenceFilters) > 0 { - query.Set("filter", referenceFilters[0]) - for _, filterValue := range referenceFilters { - optionFilters.Del("reference", filterValue) - } - } - if optionFilters.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, optionFilters) - if err != nil { - return images, err - } - query.Set("filters", filterJSON) - } - if options.All { - query.Set("all", "1") - } - - serverResp, err := cli.get(ctx, "/images/json", query, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return images, err - } - - err = json.NewDecoder(serverResp.body).Decode(&images) - return images, err -} diff --git a/vendor/github.com/docker/docker/client/image_load.go b/vendor/github.com/docker/docker/client/image_load.go deleted file mode 100644 index 91016e49..00000000 --- a/vendor/github.com/docker/docker/client/image_load.go +++ /dev/null @@ -1,29 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ImageLoad loads an image in the docker host from the client host. -// It's up to the caller to close the io.ReadCloser in the -// ImageLoadResponse returned by this function. -func (cli *Client) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) { - v := url.Values{} - v.Set("quiet", "0") - if quiet { - v.Set("quiet", "1") - } - headers := map[string][]string{"Content-Type": {"application/x-tar"}} - resp, err := cli.postRaw(ctx, "/images/load", v, input, headers) - if err != nil { - return types.ImageLoadResponse{}, err - } - return types.ImageLoadResponse{ - Body: resp.body, - JSON: resp.header.Get("Content-Type") == "application/json", - }, nil -} diff --git a/vendor/github.com/docker/docker/client/image_prune.go b/vendor/github.com/docker/docker/client/image_prune.go deleted file mode 100644 index 56af6d7f..00000000 --- a/vendor/github.com/docker/docker/client/image_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// ImagesPrune requests the daemon to delete unused data -func (cli *Client) ImagesPrune(ctx context.Context, pruneFilters filters.Args) (types.ImagesPruneReport, error) { - var report types.ImagesPruneReport - - if err := cli.NewVersionError("1.25", "image prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/images/prune", query, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return report, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving disk usage: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/image_pull.go b/vendor/github.com/docker/docker/client/image_pull.go deleted file mode 100644 index a2397559..00000000 --- a/vendor/github.com/docker/docker/client/image_pull.go +++ /dev/null @@ -1,64 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "strings" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/errdefs" -) - -// ImagePull requests the docker host to pull an image from a remote registry. -// It executes the privileged function if the operation is unauthorized -// and it tries one more time. -// It's up to the caller to handle the io.ReadCloser and close it properly. -// -// FIXME(vdemeester): there is currently used in a few way in docker/docker -// - if not in trusted content, ref is used to pass the whole reference, and tag is empty -// - if in trusted content, ref is used to pass the reference name, and tag for the digest -func (cli *Client) ImagePull(ctx context.Context, refStr string, options types.ImagePullOptions) (io.ReadCloser, error) { - ref, err := reference.ParseNormalizedNamed(refStr) - if err != nil { - return nil, err - } - - query := url.Values{} - query.Set("fromImage", reference.FamiliarName(ref)) - if !options.All { - query.Set("tag", getAPITagFromNamedRef(ref)) - } - if options.Platform != "" { - query.Set("platform", strings.ToLower(options.Platform)) - } - - resp, err := cli.tryImageCreate(ctx, query, options.RegistryAuth) - if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - return nil, privilegeErr - } - resp, err = cli.tryImageCreate(ctx, query, newAuthHeader) - } - if err != nil { - return nil, err - } - return resp.body, nil -} - -// getAPITagFromNamedRef returns a tag from the specified reference. -// This function is necessary as long as the docker "server" api expects -// digests to be sent as tags and makes a distinction between the name -// and tag/digest part of a reference. -func getAPITagFromNamedRef(ref reference.Named) string { - if digested, ok := ref.(reference.Digested); ok { - return digested.Digest().String() - } - ref = reference.TagNameOnly(ref) - if tagged, ok := ref.(reference.Tagged); ok { - return tagged.Tag() - } - return "" -} diff --git a/vendor/github.com/docker/docker/client/image_push.go b/vendor/github.com/docker/docker/client/image_push.go deleted file mode 100644 index 845580d4..00000000 --- a/vendor/github.com/docker/docker/client/image_push.go +++ /dev/null @@ -1,54 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "errors" - "io" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/errdefs" -) - -// ImagePush requests the docker host to push an image to a remote registry. -// It executes the privileged function if the operation is unauthorized -// and it tries one more time. -// It's up to the caller to handle the io.ReadCloser and close it properly. -func (cli *Client) ImagePush(ctx context.Context, image string, options types.ImagePushOptions) (io.ReadCloser, error) { - ref, err := reference.ParseNormalizedNamed(image) - if err != nil { - return nil, err - } - - if _, isCanonical := ref.(reference.Canonical); isCanonical { - return nil, errors.New("cannot push a digest reference") - } - - name := reference.FamiliarName(ref) - query := url.Values{} - if !options.All { - ref = reference.TagNameOnly(ref) - if tagged, ok := ref.(reference.Tagged); ok { - query.Set("tag", tagged.Tag()) - } - } - - resp, err := cli.tryImagePush(ctx, name, query, options.RegistryAuth) - if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - return nil, privilegeErr - } - resp, err = cli.tryImagePush(ctx, name, query, newAuthHeader) - } - if err != nil { - return nil, err - } - return resp.body, nil -} - -func (cli *Client) tryImagePush(ctx context.Context, imageID string, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.post(ctx, "/images/"+imageID+"/push", query, nil, headers) -} diff --git a/vendor/github.com/docker/docker/client/image_remove.go b/vendor/github.com/docker/docker/client/image_remove.go deleted file mode 100644 index 84a41af0..00000000 --- a/vendor/github.com/docker/docker/client/image_remove.go +++ /dev/null @@ -1,31 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" -) - -// ImageRemove removes an image from the docker host. -func (cli *Client) ImageRemove(ctx context.Context, imageID string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) { - query := url.Values{} - - if options.Force { - query.Set("force", "1") - } - if !options.PruneChildren { - query.Set("noprune", "1") - } - - var dels []types.ImageDeleteResponseItem - resp, err := cli.delete(ctx, "/images/"+imageID, query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return dels, wrapResponseError(err, resp, "image", imageID) - } - - err = json.NewDecoder(resp.body).Decode(&dels) - return dels, err -} diff --git a/vendor/github.com/docker/docker/client/image_save.go b/vendor/github.com/docker/docker/client/image_save.go deleted file mode 100644 index d1314e4b..00000000 --- a/vendor/github.com/docker/docker/client/image_save.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" -) - -// ImageSave retrieves one or more images from the docker host as an io.ReadCloser. -// It's up to the caller to store the images and close the stream. -func (cli *Client) ImageSave(ctx context.Context, imageIDs []string) (io.ReadCloser, error) { - query := url.Values{ - "names": imageIDs, - } - - resp, err := cli.get(ctx, "/images/get", query, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/image_search.go b/vendor/github.com/docker/docker/client/image_search.go deleted file mode 100644 index 82955a74..00000000 --- a/vendor/github.com/docker/docker/client/image_search.go +++ /dev/null @@ -1,51 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/errdefs" -) - -// ImageSearch makes the docker host to search by a term in a remote registry. -// The list of results is not sorted in any fashion. -func (cli *Client) ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) { - var results []registry.SearchResult - query := url.Values{} - query.Set("term", term) - query.Set("limit", fmt.Sprintf("%d", options.Limit)) - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - if err != nil { - return results, err - } - query.Set("filters", filterJSON) - } - - resp, err := cli.tryImageSearch(ctx, query, options.RegistryAuth) - defer ensureReaderClosed(resp) - if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - return results, privilegeErr - } - resp, err = cli.tryImageSearch(ctx, query, newAuthHeader) - } - if err != nil { - return results, err - } - - err = json.NewDecoder(resp.body).Decode(&results) - return results, err -} - -func (cli *Client) tryImageSearch(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.get(ctx, "/images/search", query, headers) -} diff --git a/vendor/github.com/docker/docker/client/image_tag.go b/vendor/github.com/docker/docker/client/image_tag.go deleted file mode 100644 index 5652bfc2..00000000 --- a/vendor/github.com/docker/docker/client/image_tag.go +++ /dev/null @@ -1,37 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/pkg/errors" -) - -// ImageTag tags an image in the docker host -func (cli *Client) ImageTag(ctx context.Context, source, target string) error { - if _, err := reference.ParseAnyReference(source); err != nil { - return errors.Wrapf(err, "Error parsing reference: %q is not a valid repository/tag", source) - } - - ref, err := reference.ParseNormalizedNamed(target) - if err != nil { - return errors.Wrapf(err, "Error parsing reference: %q is not a valid repository/tag", target) - } - - if _, isCanonical := ref.(reference.Canonical); isCanonical { - return errors.New("refusing to create a tag with a digest reference") - } - - ref = reference.TagNameOnly(ref) - - query := url.Values{} - query.Set("repo", reference.FamiliarName(ref)) - if tagged, ok := ref.(reference.Tagged); ok { - query.Set("tag", tagged.Tag()) - } - - resp, err := cli.post(ctx, "/images/"+source+"/tag", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/info.go b/vendor/github.com/docker/docker/client/info.go deleted file mode 100644 index c856704e..00000000 --- a/vendor/github.com/docker/docker/client/info.go +++ /dev/null @@ -1,26 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - "net/url" - - "github.com/docker/docker/api/types" -) - -// Info returns information about the docker server. -func (cli *Client) Info(ctx context.Context) (types.Info, error) { - var info types.Info - serverResp, err := cli.get(ctx, "/info", url.Values{}, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return info, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&info); err != nil { - return info, fmt.Errorf("Error reading remote info: %v", err) - } - - return info, nil -} diff --git a/vendor/github.com/docker/docker/client/interface.go b/vendor/github.com/docker/docker/client/interface.go deleted file mode 100644 index aabad4a9..00000000 --- a/vendor/github.com/docker/docker/client/interface.go +++ /dev/null @@ -1,201 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net" - "net/http" - "time" - - "github.com/docker/docker/api/types" - containertypes "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/events" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/image" - networktypes "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/api/types/swarm" - volumetypes "github.com/docker/docker/api/types/volume" - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -// CommonAPIClient is the common methods between stable and experimental versions of APIClient. -type CommonAPIClient interface { - ConfigAPIClient - ContainerAPIClient - DistributionAPIClient - ImageAPIClient - NodeAPIClient - NetworkAPIClient - PluginAPIClient - ServiceAPIClient - SwarmAPIClient - SecretAPIClient - SystemAPIClient - VolumeAPIClient - ClientVersion() string - DaemonHost() string - HTTPClient() *http.Client - ServerVersion(ctx context.Context) (types.Version, error) - NegotiateAPIVersion(ctx context.Context) - NegotiateAPIVersionPing(types.Ping) - DialHijack(ctx context.Context, url, proto string, meta map[string][]string) (net.Conn, error) - Dialer() func(context.Context) (net.Conn, error) - Close() error -} - -// ContainerAPIClient defines API client methods for the containers -type ContainerAPIClient interface { - ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) - ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) - ContainerCreate(ctx context.Context, config *containertypes.Config, hostConfig *containertypes.HostConfig, networkingConfig *networktypes.NetworkingConfig, platform *specs.Platform, containerName string) (containertypes.ContainerCreateCreatedBody, error) - ContainerDiff(ctx context.Context, container string) ([]containertypes.ContainerChangeResponseItem, error) - ContainerExecAttach(ctx context.Context, execID string, config types.ExecStartCheck) (types.HijackedResponse, error) - ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) - ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) - ContainerExecResize(ctx context.Context, execID string, options types.ResizeOptions) error - ContainerExecStart(ctx context.Context, execID string, config types.ExecStartCheck) error - ContainerExport(ctx context.Context, container string) (io.ReadCloser, error) - ContainerInspect(ctx context.Context, container string) (types.ContainerJSON, error) - ContainerInspectWithRaw(ctx context.Context, container string, getSize bool) (types.ContainerJSON, []byte, error) - ContainerKill(ctx context.Context, container, signal string) error - ContainerList(ctx context.Context, options types.ContainerListOptions) ([]types.Container, error) - ContainerLogs(ctx context.Context, container string, options types.ContainerLogsOptions) (io.ReadCloser, error) - ContainerPause(ctx context.Context, container string) error - ContainerRemove(ctx context.Context, container string, options types.ContainerRemoveOptions) error - ContainerRename(ctx context.Context, container, newContainerName string) error - ContainerResize(ctx context.Context, container string, options types.ResizeOptions) error - ContainerRestart(ctx context.Context, container string, timeout *time.Duration) error - ContainerStatPath(ctx context.Context, container, path string) (types.ContainerPathStat, error) - ContainerStats(ctx context.Context, container string, stream bool) (types.ContainerStats, error) - ContainerStatsOneShot(ctx context.Context, container string) (types.ContainerStats, error) - ContainerStart(ctx context.Context, container string, options types.ContainerStartOptions) error - ContainerStop(ctx context.Context, container string, timeout *time.Duration) error - ContainerTop(ctx context.Context, container string, arguments []string) (containertypes.ContainerTopOKBody, error) - ContainerUnpause(ctx context.Context, container string) error - ContainerUpdate(ctx context.Context, container string, updateConfig containertypes.UpdateConfig) (containertypes.ContainerUpdateOKBody, error) - ContainerWait(ctx context.Context, container string, condition containertypes.WaitCondition) (<-chan containertypes.ContainerWaitOKBody, <-chan error) - CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) - CopyToContainer(ctx context.Context, container, path string, content io.Reader, options types.CopyToContainerOptions) error - ContainersPrune(ctx context.Context, pruneFilters filters.Args) (types.ContainersPruneReport, error) -} - -// DistributionAPIClient defines API client methods for the registry -type DistributionAPIClient interface { - DistributionInspect(ctx context.Context, image, encodedRegistryAuth string) (registry.DistributionInspect, error) -} - -// ImageAPIClient defines API client methods for the images -type ImageAPIClient interface { - ImageBuild(ctx context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) - BuildCachePrune(ctx context.Context, opts types.BuildCachePruneOptions) (*types.BuildCachePruneReport, error) - BuildCancel(ctx context.Context, id string) error - ImageCreate(ctx context.Context, parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) - ImageHistory(ctx context.Context, image string) ([]image.HistoryResponseItem, error) - ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) - ImageInspectWithRaw(ctx context.Context, image string) (types.ImageInspect, []byte, error) - ImageList(ctx context.Context, options types.ImageListOptions) ([]types.ImageSummary, error) - ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) - ImagePull(ctx context.Context, ref string, options types.ImagePullOptions) (io.ReadCloser, error) - ImagePush(ctx context.Context, ref string, options types.ImagePushOptions) (io.ReadCloser, error) - ImageRemove(ctx context.Context, image string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) - ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) - ImageSave(ctx context.Context, images []string) (io.ReadCloser, error) - ImageTag(ctx context.Context, image, ref string) error - ImagesPrune(ctx context.Context, pruneFilter filters.Args) (types.ImagesPruneReport, error) -} - -// NetworkAPIClient defines API client methods for the networks -type NetworkAPIClient interface { - NetworkConnect(ctx context.Context, network, container string, config *networktypes.EndpointSettings) error - NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) - NetworkDisconnect(ctx context.Context, network, container string, force bool) error - NetworkInspect(ctx context.Context, network string, options types.NetworkInspectOptions) (types.NetworkResource, error) - NetworkInspectWithRaw(ctx context.Context, network string, options types.NetworkInspectOptions) (types.NetworkResource, []byte, error) - NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) - NetworkRemove(ctx context.Context, network string) error - NetworksPrune(ctx context.Context, pruneFilter filters.Args) (types.NetworksPruneReport, error) -} - -// NodeAPIClient defines API client methods for the nodes -type NodeAPIClient interface { - NodeInspectWithRaw(ctx context.Context, nodeID string) (swarm.Node, []byte, error) - NodeList(ctx context.Context, options types.NodeListOptions) ([]swarm.Node, error) - NodeRemove(ctx context.Context, nodeID string, options types.NodeRemoveOptions) error - NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error -} - -// PluginAPIClient defines API client methods for the plugins -type PluginAPIClient interface { - PluginList(ctx context.Context, filter filters.Args) (types.PluginsListResponse, error) - PluginRemove(ctx context.Context, name string, options types.PluginRemoveOptions) error - PluginEnable(ctx context.Context, name string, options types.PluginEnableOptions) error - PluginDisable(ctx context.Context, name string, options types.PluginDisableOptions) error - PluginInstall(ctx context.Context, name string, options types.PluginInstallOptions) (io.ReadCloser, error) - PluginUpgrade(ctx context.Context, name string, options types.PluginInstallOptions) (io.ReadCloser, error) - PluginPush(ctx context.Context, name string, registryAuth string) (io.ReadCloser, error) - PluginSet(ctx context.Context, name string, args []string) error - PluginInspectWithRaw(ctx context.Context, name string) (*types.Plugin, []byte, error) - PluginCreate(ctx context.Context, createContext io.Reader, options types.PluginCreateOptions) error -} - -// ServiceAPIClient defines API client methods for the services -type ServiceAPIClient interface { - ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) - ServiceInspectWithRaw(ctx context.Context, serviceID string, options types.ServiceInspectOptions) (swarm.Service, []byte, error) - ServiceList(ctx context.Context, options types.ServiceListOptions) ([]swarm.Service, error) - ServiceRemove(ctx context.Context, serviceID string) error - ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (types.ServiceUpdateResponse, error) - ServiceLogs(ctx context.Context, serviceID string, options types.ContainerLogsOptions) (io.ReadCloser, error) - TaskLogs(ctx context.Context, taskID string, options types.ContainerLogsOptions) (io.ReadCloser, error) - TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) - TaskList(ctx context.Context, options types.TaskListOptions) ([]swarm.Task, error) -} - -// SwarmAPIClient defines API client methods for the swarm -type SwarmAPIClient interface { - SwarmInit(ctx context.Context, req swarm.InitRequest) (string, error) - SwarmJoin(ctx context.Context, req swarm.JoinRequest) error - SwarmGetUnlockKey(ctx context.Context) (types.SwarmUnlockKeyResponse, error) - SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error - SwarmLeave(ctx context.Context, force bool) error - SwarmInspect(ctx context.Context) (swarm.Swarm, error) - SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error -} - -// SystemAPIClient defines API client methods for the system -type SystemAPIClient interface { - Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) - Info(ctx context.Context) (types.Info, error) - RegistryLogin(ctx context.Context, auth types.AuthConfig) (registry.AuthenticateOKBody, error) - DiskUsage(ctx context.Context) (types.DiskUsage, error) - Ping(ctx context.Context) (types.Ping, error) -} - -// VolumeAPIClient defines API client methods for the volumes -type VolumeAPIClient interface { - VolumeCreate(ctx context.Context, options volumetypes.VolumeCreateBody) (types.Volume, error) - VolumeInspect(ctx context.Context, volumeID string) (types.Volume, error) - VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) - VolumeList(ctx context.Context, filter filters.Args) (volumetypes.VolumeListOKBody, error) - VolumeRemove(ctx context.Context, volumeID string, force bool) error - VolumesPrune(ctx context.Context, pruneFilter filters.Args) (types.VolumesPruneReport, error) -} - -// SecretAPIClient defines API client methods for secrets -type SecretAPIClient interface { - SecretList(ctx context.Context, options types.SecretListOptions) ([]swarm.Secret, error) - SecretCreate(ctx context.Context, secret swarm.SecretSpec) (types.SecretCreateResponse, error) - SecretRemove(ctx context.Context, id string) error - SecretInspectWithRaw(ctx context.Context, name string) (swarm.Secret, []byte, error) - SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error -} - -// ConfigAPIClient defines API client methods for configs -type ConfigAPIClient interface { - ConfigList(ctx context.Context, options types.ConfigListOptions) ([]swarm.Config, error) - ConfigCreate(ctx context.Context, config swarm.ConfigSpec) (types.ConfigCreateResponse, error) - ConfigRemove(ctx context.Context, id string) error - ConfigInspectWithRaw(ctx context.Context, name string) (swarm.Config, []byte, error) - ConfigUpdate(ctx context.Context, id string, version swarm.Version, config swarm.ConfigSpec) error -} diff --git a/vendor/github.com/docker/docker/client/interface_experimental.go b/vendor/github.com/docker/docker/client/interface_experimental.go deleted file mode 100644 index 402ffb51..00000000 --- a/vendor/github.com/docker/docker/client/interface_experimental.go +++ /dev/null @@ -1,18 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types" -) - -type apiClientExperimental interface { - CheckpointAPIClient -} - -// CheckpointAPIClient defines API client methods for the checkpoints -type CheckpointAPIClient interface { - CheckpointCreate(ctx context.Context, container string, options types.CheckpointCreateOptions) error - CheckpointDelete(ctx context.Context, container string, options types.CheckpointDeleteOptions) error - CheckpointList(ctx context.Context, container string, options types.CheckpointListOptions) ([]types.Checkpoint, error) -} diff --git a/vendor/github.com/docker/docker/client/interface_stable.go b/vendor/github.com/docker/docker/client/interface_stable.go deleted file mode 100644 index 5502cd74..00000000 --- a/vendor/github.com/docker/docker/client/interface_stable.go +++ /dev/null @@ -1,10 +0,0 @@ -package client // import "github.com/docker/docker/client" - -// APIClient is an interface that clients that talk with a docker server must implement. -type APIClient interface { - CommonAPIClient - apiClientExperimental -} - -// Ensure that Client always implements APIClient. -var _ APIClient = &Client{} diff --git a/vendor/github.com/docker/docker/client/login.go b/vendor/github.com/docker/docker/client/login.go deleted file mode 100644 index f0585206..00000000 --- a/vendor/github.com/docker/docker/client/login.go +++ /dev/null @@ -1,25 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/registry" -) - -// RegistryLogin authenticates the docker server with a given docker registry. -// It returns unauthorizedError when the authentication fails. -func (cli *Client) RegistryLogin(ctx context.Context, auth types.AuthConfig) (registry.AuthenticateOKBody, error) { - resp, err := cli.post(ctx, "/auth", url.Values{}, auth, nil) - defer ensureReaderClosed(resp) - - if err != nil { - return registry.AuthenticateOKBody{}, err - } - - var response registry.AuthenticateOKBody - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/network_connect.go b/vendor/github.com/docker/docker/client/network_connect.go deleted file mode 100644 index 57189461..00000000 --- a/vendor/github.com/docker/docker/client/network_connect.go +++ /dev/null @@ -1,19 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/network" -) - -// NetworkConnect connects a container to an existent network in the docker host. -func (cli *Client) NetworkConnect(ctx context.Context, networkID, containerID string, config *network.EndpointSettings) error { - nc := types.NetworkConnect{ - Container: containerID, - EndpointConfig: config, - } - resp, err := cli.post(ctx, "/networks/"+networkID+"/connect", nil, nc, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/network_create.go b/vendor/github.com/docker/docker/client/network_create.go deleted file mode 100644 index 278d9383..00000000 --- a/vendor/github.com/docker/docker/client/network_create.go +++ /dev/null @@ -1,25 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" -) - -// NetworkCreate creates a new network in the docker host. -func (cli *Client) NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) { - networkCreateRequest := types.NetworkCreateRequest{ - NetworkCreate: options, - Name: name, - } - var response types.NetworkCreateResponse - serverResp, err := cli.post(ctx, "/networks/create", nil, networkCreateRequest, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return response, err - } - - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/network_disconnect.go b/vendor/github.com/docker/docker/client/network_disconnect.go deleted file mode 100644 index dd156766..00000000 --- a/vendor/github.com/docker/docker/client/network_disconnect.go +++ /dev/null @@ -1,15 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types" -) - -// NetworkDisconnect disconnects a container from an existent network in the docker host. -func (cli *Client) NetworkDisconnect(ctx context.Context, networkID, containerID string, force bool) error { - nd := types.NetworkDisconnect{Container: containerID, Force: force} - resp, err := cli.post(ctx, "/networks/"+networkID+"/disconnect", nil, nd, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/network_inspect.go b/vendor/github.com/docker/docker/client/network_inspect.go deleted file mode 100644 index 89a05b30..00000000 --- a/vendor/github.com/docker/docker/client/network_inspect.go +++ /dev/null @@ -1,49 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - "net/url" - - "github.com/docker/docker/api/types" -) - -// NetworkInspect returns the information for a specific network configured in the docker host. -func (cli *Client) NetworkInspect(ctx context.Context, networkID string, options types.NetworkInspectOptions) (types.NetworkResource, error) { - networkResource, _, err := cli.NetworkInspectWithRaw(ctx, networkID, options) - return networkResource, err -} - -// NetworkInspectWithRaw returns the information for a specific network configured in the docker host and its raw representation. -func (cli *Client) NetworkInspectWithRaw(ctx context.Context, networkID string, options types.NetworkInspectOptions) (types.NetworkResource, []byte, error) { - if networkID == "" { - return types.NetworkResource{}, nil, objectNotFoundError{object: "network", id: networkID} - } - var ( - networkResource types.NetworkResource - resp serverResponse - err error - ) - query := url.Values{} - if options.Verbose { - query.Set("verbose", "true") - } - if options.Scope != "" { - query.Set("scope", options.Scope) - } - resp, err = cli.get(ctx, "/networks/"+networkID, query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return networkResource, nil, wrapResponseError(err, resp, "network", networkID) - } - - body, err := ioutil.ReadAll(resp.body) - if err != nil { - return networkResource, nil, err - } - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&networkResource) - return networkResource, body, err -} diff --git a/vendor/github.com/docker/docker/client/network_list.go b/vendor/github.com/docker/docker/client/network_list.go deleted file mode 100644 index ed2acb55..00000000 --- a/vendor/github.com/docker/docker/client/network_list.go +++ /dev/null @@ -1,32 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// NetworkList returns the list of networks configured in the docker host. -func (cli *Client) NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) { - query := url.Values{} - if options.Filters.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - var networkResources []types.NetworkResource - resp, err := cli.get(ctx, "/networks", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return networkResources, err - } - err = json.NewDecoder(resp.body).Decode(&networkResources) - return networkResources, err -} diff --git a/vendor/github.com/docker/docker/client/network_prune.go b/vendor/github.com/docker/docker/client/network_prune.go deleted file mode 100644 index cebb1882..00000000 --- a/vendor/github.com/docker/docker/client/network_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// NetworksPrune requests the daemon to delete unused networks -func (cli *Client) NetworksPrune(ctx context.Context, pruneFilters filters.Args) (types.NetworksPruneReport, error) { - var report types.NetworksPruneReport - - if err := cli.NewVersionError("1.25", "network prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/networks/prune", query, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return report, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving network prune report: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/network_remove.go b/vendor/github.com/docker/docker/client/network_remove.go deleted file mode 100644 index e71b16d8..00000000 --- a/vendor/github.com/docker/docker/client/network_remove.go +++ /dev/null @@ -1,10 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// NetworkRemove removes an existent network from the docker host. -func (cli *Client) NetworkRemove(ctx context.Context, networkID string) error { - resp, err := cli.delete(ctx, "/networks/"+networkID, nil, nil) - defer ensureReaderClosed(resp) - return wrapResponseError(err, resp, "network", networkID) -} diff --git a/vendor/github.com/docker/docker/client/node_inspect.go b/vendor/github.com/docker/docker/client/node_inspect.go deleted file mode 100644 index d296c9fd..00000000 --- a/vendor/github.com/docker/docker/client/node_inspect.go +++ /dev/null @@ -1,32 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - - "github.com/docker/docker/api/types/swarm" -) - -// NodeInspectWithRaw returns the node information. -func (cli *Client) NodeInspectWithRaw(ctx context.Context, nodeID string) (swarm.Node, []byte, error) { - if nodeID == "" { - return swarm.Node{}, nil, objectNotFoundError{object: "node", id: nodeID} - } - serverResp, err := cli.get(ctx, "/nodes/"+nodeID, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return swarm.Node{}, nil, wrapResponseError(err, serverResp, "node", nodeID) - } - - body, err := ioutil.ReadAll(serverResp.body) - if err != nil { - return swarm.Node{}, nil, err - } - - var response swarm.Node - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/node_list.go b/vendor/github.com/docker/docker/client/node_list.go deleted file mode 100644 index c212906b..00000000 --- a/vendor/github.com/docker/docker/client/node_list.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" -) - -// NodeList returns the list of nodes. -func (cli *Client) NodeList(ctx context.Context, options types.NodeListOptions) ([]swarm.Node, error) { - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/nodes", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var nodes []swarm.Node - err = json.NewDecoder(resp.body).Decode(&nodes) - return nodes, err -} diff --git a/vendor/github.com/docker/docker/client/node_remove.go b/vendor/github.com/docker/docker/client/node_remove.go deleted file mode 100644 index 03ab8780..00000000 --- a/vendor/github.com/docker/docker/client/node_remove.go +++ /dev/null @@ -1,20 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// NodeRemove removes a Node. -func (cli *Client) NodeRemove(ctx context.Context, nodeID string, options types.NodeRemoveOptions) error { - query := url.Values{} - if options.Force { - query.Set("force", "1") - } - - resp, err := cli.delete(ctx, "/nodes/"+nodeID, query, nil) - defer ensureReaderClosed(resp) - return wrapResponseError(err, resp, "node", nodeID) -} diff --git a/vendor/github.com/docker/docker/client/node_update.go b/vendor/github.com/docker/docker/client/node_update.go deleted file mode 100644 index de32a617..00000000 --- a/vendor/github.com/docker/docker/client/node_update.go +++ /dev/null @@ -1,18 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" -) - -// NodeUpdate updates a Node. -func (cli *Client) NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error { - query := url.Values{} - query.Set("version", strconv.FormatUint(version.Index, 10)) - resp, err := cli.post(ctx, "/nodes/"+nodeID+"/update", query, node, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/options.go b/vendor/github.com/docker/docker/client/options.go deleted file mode 100644 index 6f77f095..00000000 --- a/vendor/github.com/docker/docker/client/options.go +++ /dev/null @@ -1,172 +0,0 @@ -package client - -import ( - "context" - "net" - "net/http" - "os" - "path/filepath" - "time" - - "github.com/docker/go-connections/sockets" - "github.com/docker/go-connections/tlsconfig" - "github.com/pkg/errors" -) - -// Opt is a configuration option to initialize a client -type Opt func(*Client) error - -// FromEnv configures the client with values from environment variables. -// -// Supported environment variables: -// DOCKER_HOST to set the url to the docker server. -// DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest. -// DOCKER_CERT_PATH to load the TLS certificates from. -// DOCKER_TLS_VERIFY to enable or disable TLS verification, off by default. -func FromEnv(c *Client) error { - if dockerCertPath := os.Getenv("DOCKER_CERT_PATH"); dockerCertPath != "" { - options := tlsconfig.Options{ - CAFile: filepath.Join(dockerCertPath, "ca.pem"), - CertFile: filepath.Join(dockerCertPath, "cert.pem"), - KeyFile: filepath.Join(dockerCertPath, "key.pem"), - InsecureSkipVerify: os.Getenv("DOCKER_TLS_VERIFY") == "", - } - tlsc, err := tlsconfig.Client(options) - if err != nil { - return err - } - - c.client = &http.Client{ - Transport: &http.Transport{TLSClientConfig: tlsc}, - CheckRedirect: CheckRedirect, - } - } - - if host := os.Getenv("DOCKER_HOST"); host != "" { - if err := WithHost(host)(c); err != nil { - return err - } - } - - if version := os.Getenv("DOCKER_API_VERSION"); version != "" { - if err := WithVersion(version)(c); err != nil { - return err - } - } - return nil -} - -// WithDialer applies the dialer.DialContext to the client transport. This can be -// used to set the Timeout and KeepAlive settings of the client. -// Deprecated: use WithDialContext -func WithDialer(dialer *net.Dialer) Opt { - return WithDialContext(dialer.DialContext) -} - -// WithDialContext applies the dialer to the client transport. This can be -// used to set the Timeout and KeepAlive settings of the client. -func WithDialContext(dialContext func(ctx context.Context, network, addr string) (net.Conn, error)) Opt { - return func(c *Client) error { - if transport, ok := c.client.Transport.(*http.Transport); ok { - transport.DialContext = dialContext - return nil - } - return errors.Errorf("cannot apply dialer to transport: %T", c.client.Transport) - } -} - -// WithHost overrides the client host with the specified one. -func WithHost(host string) Opt { - return func(c *Client) error { - hostURL, err := ParseHostURL(host) - if err != nil { - return err - } - c.host = host - c.proto = hostURL.Scheme - c.addr = hostURL.Host - c.basePath = hostURL.Path - if transport, ok := c.client.Transport.(*http.Transport); ok { - return sockets.ConfigureTransport(transport, c.proto, c.addr) - } - return errors.Errorf("cannot apply host to transport: %T", c.client.Transport) - } -} - -// WithHTTPClient overrides the client http client with the specified one -func WithHTTPClient(client *http.Client) Opt { - return func(c *Client) error { - if client != nil { - c.client = client - } - return nil - } -} - -// WithTimeout configures the time limit for requests made by the HTTP client -func WithTimeout(timeout time.Duration) Opt { - return func(c *Client) error { - c.client.Timeout = timeout - return nil - } -} - -// WithHTTPHeaders overrides the client default http headers -func WithHTTPHeaders(headers map[string]string) Opt { - return func(c *Client) error { - c.customHTTPHeaders = headers - return nil - } -} - -// WithScheme overrides the client scheme with the specified one -func WithScheme(scheme string) Opt { - return func(c *Client) error { - c.scheme = scheme - return nil - } -} - -// WithTLSClientConfig applies a tls config to the client transport. -func WithTLSClientConfig(cacertPath, certPath, keyPath string) Opt { - return func(c *Client) error { - opts := tlsconfig.Options{ - CAFile: cacertPath, - CertFile: certPath, - KeyFile: keyPath, - ExclusiveRootPools: true, - } - config, err := tlsconfig.Client(opts) - if err != nil { - return errors.Wrap(err, "failed to create tls config") - } - if transport, ok := c.client.Transport.(*http.Transport); ok { - transport.TLSClientConfig = config - return nil - } - return errors.Errorf("cannot apply tls config to transport: %T", c.client.Transport) - } -} - -// WithVersion overrides the client version with the specified one. If an empty -// version is specified, the value will be ignored to allow version negotiation. -func WithVersion(version string) Opt { - return func(c *Client) error { - if version != "" { - c.version = version - c.manualOverride = true - } - return nil - } -} - -// WithAPIVersionNegotiation enables automatic API version negotiation for the client. -// With this option enabled, the client automatically negotiates the API version -// to use when making requests. API version negotiation is performed on the first -// request; subsequent requests will not re-negotiate. -func WithAPIVersionNegotiation() Opt { - return func(c *Client) error { - c.negotiateVersion = true - return nil - } -} diff --git a/vendor/github.com/docker/docker/client/ping.go b/vendor/github.com/docker/docker/client/ping.go deleted file mode 100644 index a9af001e..00000000 --- a/vendor/github.com/docker/docker/client/ping.go +++ /dev/null @@ -1,66 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/http" - "path" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/errdefs" -) - -// Ping pings the server and returns the value of the "Docker-Experimental", -// "Builder-Version", "OS-Type" & "API-Version" headers. It attempts to use -// a HEAD request on the endpoint, but falls back to GET if HEAD is not supported -// by the daemon. -func (cli *Client) Ping(ctx context.Context) (types.Ping, error) { - var ping types.Ping - - // Using cli.buildRequest() + cli.doRequest() instead of cli.sendRequest() - // because ping requests are used during API version negotiation, so we want - // to hit the non-versioned /_ping endpoint, not /v1.xx/_ping - req, err := cli.buildRequest(http.MethodHead, path.Join(cli.basePath, "/_ping"), nil, nil) - if err != nil { - return ping, err - } - serverResp, err := cli.doRequest(ctx, req) - if err == nil { - defer ensureReaderClosed(serverResp) - switch serverResp.statusCode { - case http.StatusOK, http.StatusInternalServerError: - // Server handled the request, so parse the response - return parsePingResponse(cli, serverResp) - } - } else if IsErrConnectionFailed(err) { - return ping, err - } - - req, err = cli.buildRequest(http.MethodGet, path.Join(cli.basePath, "/_ping"), nil, nil) - if err != nil { - return ping, err - } - serverResp, err = cli.doRequest(ctx, req) - defer ensureReaderClosed(serverResp) - if err != nil { - return ping, err - } - return parsePingResponse(cli, serverResp) -} - -func parsePingResponse(cli *Client, resp serverResponse) (types.Ping, error) { - var ping types.Ping - if resp.header == nil { - err := cli.checkResponseErr(resp) - return ping, errdefs.FromStatusCode(err, resp.statusCode) - } - ping.APIVersion = resp.header.Get("API-Version") - ping.OSType = resp.header.Get("OSType") - if resp.header.Get("Docker-Experimental") == "true" { - ping.Experimental = true - } - if bv := resp.header.Get("Builder-Version"); bv != "" { - ping.BuilderVersion = types.BuilderVersion(bv) - } - err := cli.checkResponseErr(resp) - return ping, errdefs.FromStatusCode(err, resp.statusCode) -} diff --git a/vendor/github.com/docker/docker/client/plugin_create.go b/vendor/github.com/docker/docker/client/plugin_create.go deleted file mode 100644 index b95dbaf6..00000000 --- a/vendor/github.com/docker/docker/client/plugin_create.go +++ /dev/null @@ -1,23 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/http" - "net/url" - - "github.com/docker/docker/api/types" -) - -// PluginCreate creates a plugin -func (cli *Client) PluginCreate(ctx context.Context, createContext io.Reader, createOptions types.PluginCreateOptions) error { - headers := http.Header(make(map[string][]string)) - headers.Set("Content-Type", "application/x-tar") - - query := url.Values{} - query.Set("name", createOptions.RepoName) - - resp, err := cli.postRaw(ctx, "/plugins/create", query, createContext, headers) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_disable.go b/vendor/github.com/docker/docker/client/plugin_disable.go deleted file mode 100644 index 01f6574f..00000000 --- a/vendor/github.com/docker/docker/client/plugin_disable.go +++ /dev/null @@ -1,19 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// PluginDisable disables a plugin -func (cli *Client) PluginDisable(ctx context.Context, name string, options types.PluginDisableOptions) error { - query := url.Values{} - if options.Force { - query.Set("force", "1") - } - resp, err := cli.post(ctx, "/plugins/"+name+"/disable", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_enable.go b/vendor/github.com/docker/docker/client/plugin_enable.go deleted file mode 100644 index 736da48b..00000000 --- a/vendor/github.com/docker/docker/client/plugin_enable.go +++ /dev/null @@ -1,19 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "strconv" - - "github.com/docker/docker/api/types" -) - -// PluginEnable enables a plugin -func (cli *Client) PluginEnable(ctx context.Context, name string, options types.PluginEnableOptions) error { - query := url.Values{} - query.Set("timeout", strconv.Itoa(options.Timeout)) - - resp, err := cli.post(ctx, "/plugins/"+name+"/enable", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_inspect.go b/vendor/github.com/docker/docker/client/plugin_inspect.go deleted file mode 100644 index 81b89732..00000000 --- a/vendor/github.com/docker/docker/client/plugin_inspect.go +++ /dev/null @@ -1,31 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - - "github.com/docker/docker/api/types" -) - -// PluginInspectWithRaw inspects an existing plugin -func (cli *Client) PluginInspectWithRaw(ctx context.Context, name string) (*types.Plugin, []byte, error) { - if name == "" { - return nil, nil, objectNotFoundError{object: "plugin", id: name} - } - resp, err := cli.get(ctx, "/plugins/"+name+"/json", nil, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, nil, wrapResponseError(err, resp, "plugin", name) - } - - body, err := ioutil.ReadAll(resp.body) - if err != nil { - return nil, nil, err - } - var p types.Plugin - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&p) - return &p, body, err -} diff --git a/vendor/github.com/docker/docker/client/plugin_install.go b/vendor/github.com/docker/docker/client/plugin_install.go deleted file mode 100644 index 012afe61..00000000 --- a/vendor/github.com/docker/docker/client/plugin_install.go +++ /dev/null @@ -1,113 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "io" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" -) - -// PluginInstall installs a plugin -func (cli *Client) PluginInstall(ctx context.Context, name string, options types.PluginInstallOptions) (rc io.ReadCloser, err error) { - query := url.Values{} - if _, err := reference.ParseNormalizedNamed(options.RemoteRef); err != nil { - return nil, errors.Wrap(err, "invalid remote reference") - } - query.Set("remote", options.RemoteRef) - - privileges, err := cli.checkPluginPermissions(ctx, query, options) - if err != nil { - return nil, err - } - - // set name for plugin pull, if empty should default to remote reference - query.Set("name", name) - - resp, err := cli.tryPluginPull(ctx, query, privileges, options.RegistryAuth) - if err != nil { - return nil, err - } - - name = resp.header.Get("Docker-Plugin-Name") - - pr, pw := io.Pipe() - go func() { // todo: the client should probably be designed more around the actual api - _, err := io.Copy(pw, resp.body) - if err != nil { - pw.CloseWithError(err) - return - } - defer func() { - if err != nil { - delResp, _ := cli.delete(ctx, "/plugins/"+name, nil, nil) - ensureReaderClosed(delResp) - } - }() - if len(options.Args) > 0 { - if err := cli.PluginSet(ctx, name, options.Args); err != nil { - pw.CloseWithError(err) - return - } - } - - if options.Disabled { - pw.Close() - return - } - - enableErr := cli.PluginEnable(ctx, name, types.PluginEnableOptions{Timeout: 0}) - pw.CloseWithError(enableErr) - }() - return pr, nil -} - -func (cli *Client) tryPluginPrivileges(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.get(ctx, "/plugins/privileges", query, headers) -} - -func (cli *Client) tryPluginPull(ctx context.Context, query url.Values, privileges types.PluginPrivileges, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.post(ctx, "/plugins/pull", query, privileges, headers) -} - -func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values, options types.PluginInstallOptions) (types.PluginPrivileges, error) { - resp, err := cli.tryPluginPrivileges(ctx, query, options.RegistryAuth) - if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil { - // todo: do inspect before to check existing name before checking privileges - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - ensureReaderClosed(resp) - return nil, privilegeErr - } - options.RegistryAuth = newAuthHeader - resp, err = cli.tryPluginPrivileges(ctx, query, options.RegistryAuth) - } - if err != nil { - ensureReaderClosed(resp) - return nil, err - } - - var privileges types.PluginPrivileges - if err := json.NewDecoder(resp.body).Decode(&privileges); err != nil { - ensureReaderClosed(resp) - return nil, err - } - ensureReaderClosed(resp) - - if !options.AcceptAllPermissions && options.AcceptPermissionsFunc != nil && len(privileges) > 0 { - accept, err := options.AcceptPermissionsFunc(privileges) - if err != nil { - return nil, err - } - if !accept { - return nil, pluginPermissionDenied{options.RemoteRef} - } - } - return privileges, nil -} diff --git a/vendor/github.com/docker/docker/client/plugin_list.go b/vendor/github.com/docker/docker/client/plugin_list.go deleted file mode 100644 index cf1935e2..00000000 --- a/vendor/github.com/docker/docker/client/plugin_list.go +++ /dev/null @@ -1,33 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// PluginList returns the installed plugins -func (cli *Client) PluginList(ctx context.Context, filter filters.Args) (types.PluginsListResponse, error) { - var plugins types.PluginsListResponse - query := url.Values{} - - if filter.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, filter) - if err != nil { - return plugins, err - } - query.Set("filters", filterJSON) - } - resp, err := cli.get(ctx, "/plugins", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return plugins, wrapResponseError(err, resp, "plugin", "") - } - - err = json.NewDecoder(resp.body).Decode(&plugins) - return plugins, err -} diff --git a/vendor/github.com/docker/docker/client/plugin_push.go b/vendor/github.com/docker/docker/client/plugin_push.go deleted file mode 100644 index d20bfe84..00000000 --- a/vendor/github.com/docker/docker/client/plugin_push.go +++ /dev/null @@ -1,16 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" -) - -// PluginPush pushes a plugin to a registry -func (cli *Client) PluginPush(ctx context.Context, name string, registryAuth string) (io.ReadCloser, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - resp, err := cli.post(ctx, "/plugins/"+name+"/push", nil, nil, headers) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/plugin_remove.go b/vendor/github.com/docker/docker/client/plugin_remove.go deleted file mode 100644 index 51ca1040..00000000 --- a/vendor/github.com/docker/docker/client/plugin_remove.go +++ /dev/null @@ -1,20 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types" -) - -// PluginRemove removes a plugin -func (cli *Client) PluginRemove(ctx context.Context, name string, options types.PluginRemoveOptions) error { - query := url.Values{} - if options.Force { - query.Set("force", "1") - } - - resp, err := cli.delete(ctx, "/plugins/"+name, query, nil) - defer ensureReaderClosed(resp) - return wrapResponseError(err, resp, "plugin", name) -} diff --git a/vendor/github.com/docker/docker/client/plugin_set.go b/vendor/github.com/docker/docker/client/plugin_set.go deleted file mode 100644 index dcf5752c..00000000 --- a/vendor/github.com/docker/docker/client/plugin_set.go +++ /dev/null @@ -1,12 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" -) - -// PluginSet modifies settings for an existing plugin -func (cli *Client) PluginSet(ctx context.Context, name string, args []string) error { - resp, err := cli.post(ctx, "/plugins/"+name+"/set", nil, args, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_upgrade.go b/vendor/github.com/docker/docker/client/plugin_upgrade.go deleted file mode 100644 index 115cea94..00000000 --- a/vendor/github.com/docker/docker/client/plugin_upgrade.go +++ /dev/null @@ -1,39 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/pkg/errors" -) - -// PluginUpgrade upgrades a plugin -func (cli *Client) PluginUpgrade(ctx context.Context, name string, options types.PluginInstallOptions) (rc io.ReadCloser, err error) { - if err := cli.NewVersionError("1.26", "plugin upgrade"); err != nil { - return nil, err - } - query := url.Values{} - if _, err := reference.ParseNormalizedNamed(options.RemoteRef); err != nil { - return nil, errors.Wrap(err, "invalid remote reference") - } - query.Set("remote", options.RemoteRef) - - privileges, err := cli.checkPluginPermissions(ctx, query, options) - if err != nil { - return nil, err - } - - resp, err := cli.tryPluginUpgrade(ctx, query, privileges, name, options.RegistryAuth) - if err != nil { - return nil, err - } - return resp.body, nil -} - -func (cli *Client) tryPluginUpgrade(ctx context.Context, query url.Values, privileges types.PluginPrivileges, name, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.post(ctx, "/plugins/"+name+"/upgrade", query, privileges, headers) -} diff --git a/vendor/github.com/docker/docker/client/request.go b/vendor/github.com/docker/docker/client/request.go deleted file mode 100644 index 813eac2c..00000000 --- a/vendor/github.com/docker/docker/client/request.go +++ /dev/null @@ -1,269 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "strings" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/versions" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" -) - -// serverResponse is a wrapper for http API responses. -type serverResponse struct { - body io.ReadCloser - header http.Header - statusCode int - reqURL *url.URL -} - -// head sends an http request to the docker API using the method HEAD. -func (cli *Client) head(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, http.MethodHead, path, query, nil, headers) -} - -// get sends an http request to the docker API using the method GET with a specific Go context. -func (cli *Client) get(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, http.MethodGet, path, query, nil, headers) -} - -// post sends an http request to the docker API using the method POST with a specific Go context. -func (cli *Client) post(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) { - body, headers, err := encodeBody(obj, headers) - if err != nil { - return serverResponse{}, err - } - return cli.sendRequest(ctx, http.MethodPost, path, query, body, headers) -} - -func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, http.MethodPost, path, query, body, headers) -} - -// putRaw sends an http request to the docker API using the method PUT. -func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, http.MethodPut, path, query, body, headers) -} - -// delete sends an http request to the docker API using the method DELETE. -func (cli *Client) delete(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, http.MethodDelete, path, query, nil, headers) -} - -type headers map[string][]string - -func encodeBody(obj interface{}, headers headers) (io.Reader, headers, error) { - if obj == nil { - return nil, headers, nil - } - - body, err := encodeData(obj) - if err != nil { - return nil, headers, err - } - if headers == nil { - headers = make(map[string][]string) - } - headers["Content-Type"] = []string{"application/json"} - return body, headers, nil -} - -func (cli *Client) buildRequest(method, path string, body io.Reader, headers headers) (*http.Request, error) { - expectedPayload := (method == http.MethodPost || method == http.MethodPut) - if expectedPayload && body == nil { - body = bytes.NewReader([]byte{}) - } - - req, err := http.NewRequest(method, path, body) - if err != nil { - return nil, err - } - req = cli.addHeaders(req, headers) - - if cli.proto == "unix" || cli.proto == "npipe" { - // For local communications, it doesn't matter what the host is. We just - // need a valid and meaningful host name. (See #189) - req.Host = "docker" - } - - req.URL.Host = cli.addr - req.URL.Scheme = cli.scheme - - if expectedPayload && req.Header.Get("Content-Type") == "" { - req.Header.Set("Content-Type", "text/plain") - } - return req, nil -} - -func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers headers) (serverResponse, error) { - req, err := cli.buildRequest(method, cli.getAPIPath(ctx, path, query), body, headers) - if err != nil { - return serverResponse{}, err - } - resp, err := cli.doRequest(ctx, req) - if err != nil { - return resp, errdefs.FromStatusCode(err, resp.statusCode) - } - err = cli.checkResponseErr(resp) - return resp, errdefs.FromStatusCode(err, resp.statusCode) -} - -func (cli *Client) doRequest(ctx context.Context, req *http.Request) (serverResponse, error) { - serverResp := serverResponse{statusCode: -1, reqURL: req.URL} - - req = req.WithContext(ctx) - resp, err := cli.client.Do(req) - if err != nil { - if cli.scheme != "https" && strings.Contains(err.Error(), "malformed HTTP response") { - return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err) - } - - if cli.scheme == "https" && strings.Contains(err.Error(), "bad certificate") { - return serverResp, errors.Wrap(err, "The server probably has client authentication (--tlsverify) enabled. Please check your TLS client certification settings") - } - - // Don't decorate context sentinel errors; users may be comparing to - // them directly. - if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { - return serverResp, err - } - - if nErr, ok := err.(*url.Error); ok { - if nErr, ok := nErr.Err.(*net.OpError); ok { - if os.IsPermission(nErr.Err) { - return serverResp, errors.Wrapf(err, "Got permission denied while trying to connect to the Docker daemon socket at %v", cli.host) - } - } - } - - if err, ok := err.(net.Error); ok { - if err.Timeout() { - return serverResp, ErrorConnectionFailed(cli.host) - } - if !err.Temporary() { - if strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial unix") { - return serverResp, ErrorConnectionFailed(cli.host) - } - } - } - - // Although there's not a strongly typed error for this in go-winio, - // lots of people are using the default configuration for the docker - // daemon on Windows where the daemon is listening on a named pipe - // `//./pipe/docker_engine, and the client must be running elevated. - // Give users a clue rather than the not-overly useful message - // such as `error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.26/info: - // open //./pipe/docker_engine: The system cannot find the file specified.`. - // Note we can't string compare "The system cannot find the file specified" as - // this is localised - for example in French the error would be - // `open //./pipe/docker_engine: Le fichier spécifié est introuvable.` - if strings.Contains(err.Error(), `open //./pipe/docker_engine`) { - // Checks if client is running with elevated privileges - if f, elevatedErr := os.Open("\\\\.\\PHYSICALDRIVE0"); elevatedErr == nil { - err = errors.Wrap(err, "In the default daemon configuration on Windows, the docker client must be run with elevated privileges to connect.") - } else { - f.Close() - err = errors.Wrap(err, "This error may indicate that the docker daemon is not running.") - } - } - - return serverResp, errors.Wrap(err, "error during connect") - } - - if resp != nil { - serverResp.statusCode = resp.StatusCode - serverResp.body = resp.Body - serverResp.header = resp.Header - } - return serverResp, nil -} - -func (cli *Client) checkResponseErr(serverResp serverResponse) error { - if serverResp.statusCode >= 200 && serverResp.statusCode < 400 { - return nil - } - - var body []byte - var err error - if serverResp.body != nil { - bodyMax := 1 * 1024 * 1024 // 1 MiB - bodyR := &io.LimitedReader{ - R: serverResp.body, - N: int64(bodyMax), - } - body, err = ioutil.ReadAll(bodyR) - if err != nil { - return err - } - if bodyR.N == 0 { - return fmt.Errorf("request returned %s with a message (> %d bytes) for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), bodyMax, serverResp.reqURL) - } - } - if len(body) == 0 { - return fmt.Errorf("request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), serverResp.reqURL) - } - - var ct string - if serverResp.header != nil { - ct = serverResp.header.Get("Content-Type") - } - - var errorMessage string - if (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) && ct == "application/json" { - var errorResponse types.ErrorResponse - if err := json.Unmarshal(body, &errorResponse); err != nil { - return errors.Wrap(err, "Error reading JSON") - } - errorMessage = strings.TrimSpace(errorResponse.Message) - } else { - errorMessage = strings.TrimSpace(string(body)) - } - - return errors.Wrap(errors.New(errorMessage), "Error response from daemon") -} - -func (cli *Client) addHeaders(req *http.Request, headers headers) *http.Request { - // Add CLI Config's HTTP Headers BEFORE we set the Docker headers - // then the user can't change OUR headers - for k, v := range cli.customHTTPHeaders { - if versions.LessThan(cli.version, "1.25") && k == "User-Agent" { - continue - } - req.Header.Set(k, v) - } - - if headers != nil { - for k, v := range headers { - req.Header[k] = v - } - } - return req -} - -func encodeData(data interface{}) (*bytes.Buffer, error) { - params := bytes.NewBuffer(nil) - if data != nil { - if err := json.NewEncoder(params).Encode(data); err != nil { - return nil, err - } - } - return params, nil -} - -func ensureReaderClosed(response serverResponse) { - if response.body != nil { - // Drain up to 512 bytes and close the body to let the Transport reuse the connection - io.CopyN(ioutil.Discard, response.body, 512) - response.body.Close() - } -} diff --git a/vendor/github.com/docker/docker/client/secret_create.go b/vendor/github.com/docker/docker/client/secret_create.go deleted file mode 100644 index fd5b9141..00000000 --- a/vendor/github.com/docker/docker/client/secret_create.go +++ /dev/null @@ -1,25 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" -) - -// SecretCreate creates a new Secret. -func (cli *Client) SecretCreate(ctx context.Context, secret swarm.SecretSpec) (types.SecretCreateResponse, error) { - var response types.SecretCreateResponse - if err := cli.NewVersionError("1.25", "secret create"); err != nil { - return response, err - } - resp, err := cli.post(ctx, "/secrets/create", nil, secret, nil) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/secret_inspect.go b/vendor/github.com/docker/docker/client/secret_inspect.go deleted file mode 100644 index d093916c..00000000 --- a/vendor/github.com/docker/docker/client/secret_inspect.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - - "github.com/docker/docker/api/types/swarm" -) - -// SecretInspectWithRaw returns the secret information with raw data -func (cli *Client) SecretInspectWithRaw(ctx context.Context, id string) (swarm.Secret, []byte, error) { - if err := cli.NewVersionError("1.25", "secret inspect"); err != nil { - return swarm.Secret{}, nil, err - } - if id == "" { - return swarm.Secret{}, nil, objectNotFoundError{object: "secret", id: id} - } - resp, err := cli.get(ctx, "/secrets/"+id, nil, nil) - defer ensureReaderClosed(resp) - if err != nil { - return swarm.Secret{}, nil, wrapResponseError(err, resp, "secret", id) - } - - body, err := ioutil.ReadAll(resp.body) - if err != nil { - return swarm.Secret{}, nil, err - } - - var secret swarm.Secret - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&secret) - - return secret, body, err -} diff --git a/vendor/github.com/docker/docker/client/secret_list.go b/vendor/github.com/docker/docker/client/secret_list.go deleted file mode 100644 index a0289c9f..00000000 --- a/vendor/github.com/docker/docker/client/secret_list.go +++ /dev/null @@ -1,38 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" -) - -// SecretList returns the list of secrets. -func (cli *Client) SecretList(ctx context.Context, options types.SecretListOptions) ([]swarm.Secret, error) { - if err := cli.NewVersionError("1.25", "secret list"); err != nil { - return nil, err - } - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/secrets", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var secrets []swarm.Secret - err = json.NewDecoder(resp.body).Decode(&secrets) - return secrets, err -} diff --git a/vendor/github.com/docker/docker/client/secret_remove.go b/vendor/github.com/docker/docker/client/secret_remove.go deleted file mode 100644 index c16f5558..00000000 --- a/vendor/github.com/docker/docker/client/secret_remove.go +++ /dev/null @@ -1,13 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// SecretRemove removes a Secret. -func (cli *Client) SecretRemove(ctx context.Context, id string) error { - if err := cli.NewVersionError("1.25", "secret remove"); err != nil { - return err - } - resp, err := cli.delete(ctx, "/secrets/"+id, nil, nil) - defer ensureReaderClosed(resp) - return wrapResponseError(err, resp, "secret", id) -} diff --git a/vendor/github.com/docker/docker/client/secret_update.go b/vendor/github.com/docker/docker/client/secret_update.go deleted file mode 100644 index 164256bb..00000000 --- a/vendor/github.com/docker/docker/client/secret_update.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" -) - -// SecretUpdate attempts to update a Secret -func (cli *Client) SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error { - if err := cli.NewVersionError("1.25", "secret update"); err != nil { - return err - } - query := url.Values{} - query.Set("version", strconv.FormatUint(version.Index, 10)) - resp, err := cli.post(ctx, "/secrets/"+id+"/update", query, secret, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/service_create.go b/vendor/github.com/docker/docker/client/service_create.go deleted file mode 100644 index e0428bf9..00000000 --- a/vendor/github.com/docker/docker/client/service_create.go +++ /dev/null @@ -1,178 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - "strings" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" - digest "github.com/opencontainers/go-digest" - "github.com/pkg/errors" -) - -// ServiceCreate creates a new Service. -func (cli *Client) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) { - var response types.ServiceCreateResponse - headers := map[string][]string{ - "version": {cli.version}, - } - - if options.EncodedRegistryAuth != "" { - headers["X-Registry-Auth"] = []string{options.EncodedRegistryAuth} - } - - // Make sure containerSpec is not nil when no runtime is set or the runtime is set to container - if service.TaskTemplate.ContainerSpec == nil && (service.TaskTemplate.Runtime == "" || service.TaskTemplate.Runtime == swarm.RuntimeContainer) { - service.TaskTemplate.ContainerSpec = &swarm.ContainerSpec{} - } - - if err := validateServiceSpec(service); err != nil { - return response, err - } - - // ensure that the image is tagged - var resolveWarning string - switch { - case service.TaskTemplate.ContainerSpec != nil: - if taggedImg := imageWithTagString(service.TaskTemplate.ContainerSpec.Image); taggedImg != "" { - service.TaskTemplate.ContainerSpec.Image = taggedImg - } - if options.QueryRegistry { - resolveWarning = resolveContainerSpecImage(ctx, cli, &service.TaskTemplate, options.EncodedRegistryAuth) - } - case service.TaskTemplate.PluginSpec != nil: - if taggedImg := imageWithTagString(service.TaskTemplate.PluginSpec.Remote); taggedImg != "" { - service.TaskTemplate.PluginSpec.Remote = taggedImg - } - if options.QueryRegistry { - resolveWarning = resolvePluginSpecRemote(ctx, cli, &service.TaskTemplate, options.EncodedRegistryAuth) - } - } - - resp, err := cli.post(ctx, "/services/create", nil, service, headers) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - if resolveWarning != "" { - response.Warnings = append(response.Warnings, resolveWarning) - } - - return response, err -} - -func resolveContainerSpecImage(ctx context.Context, cli DistributionAPIClient, taskSpec *swarm.TaskSpec, encodedAuth string) string { - var warning string - if img, imgPlatforms, err := imageDigestAndPlatforms(ctx, cli, taskSpec.ContainerSpec.Image, encodedAuth); err != nil { - warning = digestWarning(taskSpec.ContainerSpec.Image) - } else { - taskSpec.ContainerSpec.Image = img - if len(imgPlatforms) > 0 { - if taskSpec.Placement == nil { - taskSpec.Placement = &swarm.Placement{} - } - taskSpec.Placement.Platforms = imgPlatforms - } - } - return warning -} - -func resolvePluginSpecRemote(ctx context.Context, cli DistributionAPIClient, taskSpec *swarm.TaskSpec, encodedAuth string) string { - var warning string - if img, imgPlatforms, err := imageDigestAndPlatforms(ctx, cli, taskSpec.PluginSpec.Remote, encodedAuth); err != nil { - warning = digestWarning(taskSpec.PluginSpec.Remote) - } else { - taskSpec.PluginSpec.Remote = img - if len(imgPlatforms) > 0 { - if taskSpec.Placement == nil { - taskSpec.Placement = &swarm.Placement{} - } - taskSpec.Placement.Platforms = imgPlatforms - } - } - return warning -} - -func imageDigestAndPlatforms(ctx context.Context, cli DistributionAPIClient, image, encodedAuth string) (string, []swarm.Platform, error) { - distributionInspect, err := cli.DistributionInspect(ctx, image, encodedAuth) - var platforms []swarm.Platform - if err != nil { - return "", nil, err - } - - imageWithDigest := imageWithDigestString(image, distributionInspect.Descriptor.Digest) - - if len(distributionInspect.Platforms) > 0 { - platforms = make([]swarm.Platform, 0, len(distributionInspect.Platforms)) - for _, p := range distributionInspect.Platforms { - // clear architecture field for arm. This is a temporary patch to address - // https://github.com/docker/swarmkit/issues/2294. The issue is that while - // image manifests report "arm" as the architecture, the node reports - // something like "armv7l" (includes the variant), which causes arm images - // to stop working with swarm mode. This patch removes the architecture - // constraint for arm images to ensure tasks get scheduled. - arch := p.Architecture - if strings.ToLower(arch) == "arm" { - arch = "" - } - platforms = append(platforms, swarm.Platform{ - Architecture: arch, - OS: p.OS, - }) - } - } - return imageWithDigest, platforms, err -} - -// imageWithDigestString takes an image string and a digest, and updates -// the image string if it didn't originally contain a digest. It returns -// image unmodified in other situations. -func imageWithDigestString(image string, dgst digest.Digest) string { - namedRef, err := reference.ParseNormalizedNamed(image) - if err == nil { - if _, isCanonical := namedRef.(reference.Canonical); !isCanonical { - // ensure that image gets a default tag if none is provided - img, err := reference.WithDigest(namedRef, dgst) - if err == nil { - return reference.FamiliarString(img) - } - } - } - return image -} - -// imageWithTagString takes an image string, and returns a tagged image -// string, adding a 'latest' tag if one was not provided. It returns an -// empty string if a canonical reference was provided -func imageWithTagString(image string) string { - namedRef, err := reference.ParseNormalizedNamed(image) - if err == nil { - return reference.FamiliarString(reference.TagNameOnly(namedRef)) - } - return "" -} - -// digestWarning constructs a formatted warning string using the -// image name that could not be pinned by digest. The formatting -// is hardcoded, but could me made smarter in the future -func digestWarning(image string) string { - return fmt.Sprintf("image %s could not be accessed on a registry to record\nits digest. Each node will access %s independently,\npossibly leading to different nodes running different\nversions of the image.\n", image, image) -} - -func validateServiceSpec(s swarm.ServiceSpec) error { - if s.TaskTemplate.ContainerSpec != nil && s.TaskTemplate.PluginSpec != nil { - return errors.New("must not specify both a container spec and a plugin spec in the task template") - } - if s.TaskTemplate.PluginSpec != nil && s.TaskTemplate.Runtime != swarm.RuntimePlugin { - return errors.New("mismatched runtime with plugin spec") - } - if s.TaskTemplate.ContainerSpec != nil && (s.TaskTemplate.Runtime != "" && s.TaskTemplate.Runtime != swarm.RuntimeContainer) { - return errors.New("mismatched runtime with container spec") - } - return nil -} diff --git a/vendor/github.com/docker/docker/client/service_inspect.go b/vendor/github.com/docker/docker/client/service_inspect.go deleted file mode 100644 index 2801483b..00000000 --- a/vendor/github.com/docker/docker/client/service_inspect.go +++ /dev/null @@ -1,37 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" -) - -// ServiceInspectWithRaw returns the service information and the raw data. -func (cli *Client) ServiceInspectWithRaw(ctx context.Context, serviceID string, opts types.ServiceInspectOptions) (swarm.Service, []byte, error) { - if serviceID == "" { - return swarm.Service{}, nil, objectNotFoundError{object: "service", id: serviceID} - } - query := url.Values{} - query.Set("insertDefaults", fmt.Sprintf("%v", opts.InsertDefaults)) - serverResp, err := cli.get(ctx, "/services/"+serviceID, query, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return swarm.Service{}, nil, wrapResponseError(err, serverResp, "service", serviceID) - } - - body, err := ioutil.ReadAll(serverResp.body) - if err != nil { - return swarm.Service{}, nil, err - } - - var response swarm.Service - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/service_list.go b/vendor/github.com/docker/docker/client/service_list.go deleted file mode 100644 index f97ec75a..00000000 --- a/vendor/github.com/docker/docker/client/service_list.go +++ /dev/null @@ -1,39 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" -) - -// ServiceList returns the list of services. -func (cli *Client) ServiceList(ctx context.Context, options types.ServiceListOptions) ([]swarm.Service, error) { - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - if options.Status { - query.Set("status", "true") - } - - resp, err := cli.get(ctx, "/services", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var services []swarm.Service - err = json.NewDecoder(resp.body).Decode(&services) - return services, err -} diff --git a/vendor/github.com/docker/docker/client/service_logs.go b/vendor/github.com/docker/docker/client/service_logs.go deleted file mode 100644 index 906fd405..00000000 --- a/vendor/github.com/docker/docker/client/service_logs.go +++ /dev/null @@ -1,52 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "time" - - "github.com/docker/docker/api/types" - timetypes "github.com/docker/docker/api/types/time" - "github.com/pkg/errors" -) - -// ServiceLogs returns the logs generated by a service in an io.ReadCloser. -// It's up to the caller to close the stream. -func (cli *Client) ServiceLogs(ctx context.Context, serviceID string, options types.ContainerLogsOptions) (io.ReadCloser, error) { - query := url.Values{} - if options.ShowStdout { - query.Set("stdout", "1") - } - - if options.ShowStderr { - query.Set("stderr", "1") - } - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, time.Now()) - if err != nil { - return nil, errors.Wrap(err, `invalid value for "since"`) - } - query.Set("since", ts) - } - - if options.Timestamps { - query.Set("timestamps", "1") - } - - if options.Details { - query.Set("details", "1") - } - - if options.Follow { - query.Set("follow", "1") - } - query.Set("tail", options.Tail) - - resp, err := cli.get(ctx, "/services/"+serviceID+"/logs", query, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/service_remove.go b/vendor/github.com/docker/docker/client/service_remove.go deleted file mode 100644 index 953a2adf..00000000 --- a/vendor/github.com/docker/docker/client/service_remove.go +++ /dev/null @@ -1,10 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import "context" - -// ServiceRemove kills and removes a service. -func (cli *Client) ServiceRemove(ctx context.Context, serviceID string) error { - resp, err := cli.delete(ctx, "/services/"+serviceID, nil, nil) - defer ensureReaderClosed(resp) - return wrapResponseError(err, resp, "service", serviceID) -} diff --git a/vendor/github.com/docker/docker/client/service_update.go b/vendor/github.com/docker/docker/client/service_update.go deleted file mode 100644 index c63895f7..00000000 --- a/vendor/github.com/docker/docker/client/service_update.go +++ /dev/null @@ -1,75 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - "strconv" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" -) - -// ServiceUpdate updates a Service. The version number is required to avoid conflicting writes. -// It should be the value as set *before* the update. You can find this value in the Meta field -// of swarm.Service, which can be found using ServiceInspectWithRaw. -func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (types.ServiceUpdateResponse, error) { - var ( - query = url.Values{} - response = types.ServiceUpdateResponse{} - ) - - headers := map[string][]string{ - "version": {cli.version}, - } - - if options.EncodedRegistryAuth != "" { - headers["X-Registry-Auth"] = []string{options.EncodedRegistryAuth} - } - - if options.RegistryAuthFrom != "" { - query.Set("registryAuthFrom", options.RegistryAuthFrom) - } - - if options.Rollback != "" { - query.Set("rollback", options.Rollback) - } - - query.Set("version", strconv.FormatUint(version.Index, 10)) - - if err := validateServiceSpec(service); err != nil { - return response, err - } - - // ensure that the image is tagged - var resolveWarning string - switch { - case service.TaskTemplate.ContainerSpec != nil: - if taggedImg := imageWithTagString(service.TaskTemplate.ContainerSpec.Image); taggedImg != "" { - service.TaskTemplate.ContainerSpec.Image = taggedImg - } - if options.QueryRegistry { - resolveWarning = resolveContainerSpecImage(ctx, cli, &service.TaskTemplate, options.EncodedRegistryAuth) - } - case service.TaskTemplate.PluginSpec != nil: - if taggedImg := imageWithTagString(service.TaskTemplate.PluginSpec.Remote); taggedImg != "" { - service.TaskTemplate.PluginSpec.Remote = taggedImg - } - if options.QueryRegistry { - resolveWarning = resolvePluginSpecRemote(ctx, cli, &service.TaskTemplate, options.EncodedRegistryAuth) - } - } - - resp, err := cli.post(ctx, "/services/"+serviceID+"/update", query, service, headers) - defer ensureReaderClosed(resp) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - if resolveWarning != "" { - response.Warnings = append(response.Warnings, resolveWarning) - } - - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_get_unlock_key.go b/vendor/github.com/docker/docker/client/swarm_get_unlock_key.go deleted file mode 100644 index 19f59dd5..00000000 --- a/vendor/github.com/docker/docker/client/swarm_get_unlock_key.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" -) - -// SwarmGetUnlockKey retrieves the swarm's unlock key. -func (cli *Client) SwarmGetUnlockKey(ctx context.Context) (types.SwarmUnlockKeyResponse, error) { - serverResp, err := cli.get(ctx, "/swarm/unlockkey", nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return types.SwarmUnlockKeyResponse{}, err - } - - var response types.SwarmUnlockKeyResponse - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_init.go b/vendor/github.com/docker/docker/client/swarm_init.go deleted file mode 100644 index da3c1637..00000000 --- a/vendor/github.com/docker/docker/client/swarm_init.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types/swarm" -) - -// SwarmInit initializes the swarm. -func (cli *Client) SwarmInit(ctx context.Context, req swarm.InitRequest) (string, error) { - serverResp, err := cli.post(ctx, "/swarm/init", nil, req, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return "", err - } - - var response string - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_inspect.go b/vendor/github.com/docker/docker/client/swarm_inspect.go deleted file mode 100644 index b52b67a8..00000000 --- a/vendor/github.com/docker/docker/client/swarm_inspect.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types/swarm" -) - -// SwarmInspect inspects the swarm. -func (cli *Client) SwarmInspect(ctx context.Context) (swarm.Swarm, error) { - serverResp, err := cli.get(ctx, "/swarm", nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return swarm.Swarm{}, err - } - - var response swarm.Swarm - err = json.NewDecoder(serverResp.body).Decode(&response) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_join.go b/vendor/github.com/docker/docker/client/swarm_join.go deleted file mode 100644 index a1cf0455..00000000 --- a/vendor/github.com/docker/docker/client/swarm_join.go +++ /dev/null @@ -1,14 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types/swarm" -) - -// SwarmJoin joins the swarm. -func (cli *Client) SwarmJoin(ctx context.Context, req swarm.JoinRequest) error { - resp, err := cli.post(ctx, "/swarm/join", nil, req, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/swarm_leave.go b/vendor/github.com/docker/docker/client/swarm_leave.go deleted file mode 100644 index 90ca84b3..00000000 --- a/vendor/github.com/docker/docker/client/swarm_leave.go +++ /dev/null @@ -1,17 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" -) - -// SwarmLeave leaves the swarm. -func (cli *Client) SwarmLeave(ctx context.Context, force bool) error { - query := url.Values{} - if force { - query.Set("force", "1") - } - resp, err := cli.post(ctx, "/swarm/leave", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/swarm_unlock.go b/vendor/github.com/docker/docker/client/swarm_unlock.go deleted file mode 100644 index d2412f7d..00000000 --- a/vendor/github.com/docker/docker/client/swarm_unlock.go +++ /dev/null @@ -1,14 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - - "github.com/docker/docker/api/types/swarm" -) - -// SwarmUnlock unlocks locked swarm. -func (cli *Client) SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error { - serverResp, err := cli.post(ctx, "/swarm/unlock", nil, req, nil) - ensureReaderClosed(serverResp) - return err -} diff --git a/vendor/github.com/docker/docker/client/swarm_update.go b/vendor/github.com/docker/docker/client/swarm_update.go deleted file mode 100644 index 56a5bea7..00000000 --- a/vendor/github.com/docker/docker/client/swarm_update.go +++ /dev/null @@ -1,22 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "fmt" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" -) - -// SwarmUpdate updates the swarm. -func (cli *Client) SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error { - query := url.Values{} - query.Set("version", strconv.FormatUint(version.Index, 10)) - query.Set("rotateWorkerToken", fmt.Sprintf("%v", flags.RotateWorkerToken)) - query.Set("rotateManagerToken", fmt.Sprintf("%v", flags.RotateManagerToken)) - query.Set("rotateManagerUnlockKey", fmt.Sprintf("%v", flags.RotateManagerUnlockKey)) - resp, err := cli.post(ctx, "/swarm/update", query, swarm, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/task_inspect.go b/vendor/github.com/docker/docker/client/task_inspect.go deleted file mode 100644 index 44d40ba5..00000000 --- a/vendor/github.com/docker/docker/client/task_inspect.go +++ /dev/null @@ -1,32 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - - "github.com/docker/docker/api/types/swarm" -) - -// TaskInspectWithRaw returns the task information and its raw representation.. -func (cli *Client) TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) { - if taskID == "" { - return swarm.Task{}, nil, objectNotFoundError{object: "task", id: taskID} - } - serverResp, err := cli.get(ctx, "/tasks/"+taskID, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return swarm.Task{}, nil, wrapResponseError(err, serverResp, "task", taskID) - } - - body, err := ioutil.ReadAll(serverResp.body) - if err != nil { - return swarm.Task{}, nil, err - } - - var response swarm.Task - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/task_list.go b/vendor/github.com/docker/docker/client/task_list.go deleted file mode 100644 index 4869b444..00000000 --- a/vendor/github.com/docker/docker/client/task_list.go +++ /dev/null @@ -1,35 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" -) - -// TaskList returns the list of tasks. -func (cli *Client) TaskList(ctx context.Context, options types.TaskListOptions) ([]swarm.Task, error) { - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToJSON(options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/tasks", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return nil, err - } - - var tasks []swarm.Task - err = json.NewDecoder(resp.body).Decode(&tasks) - return tasks, err -} diff --git a/vendor/github.com/docker/docker/client/task_logs.go b/vendor/github.com/docker/docker/client/task_logs.go deleted file mode 100644 index 6222fab5..00000000 --- a/vendor/github.com/docker/docker/client/task_logs.go +++ /dev/null @@ -1,51 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net/url" - "time" - - "github.com/docker/docker/api/types" - timetypes "github.com/docker/docker/api/types/time" -) - -// TaskLogs returns the logs generated by a task in an io.ReadCloser. -// It's up to the caller to close the stream. -func (cli *Client) TaskLogs(ctx context.Context, taskID string, options types.ContainerLogsOptions) (io.ReadCloser, error) { - query := url.Values{} - if options.ShowStdout { - query.Set("stdout", "1") - } - - if options.ShowStderr { - query.Set("stderr", "1") - } - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, time.Now()) - if err != nil { - return nil, err - } - query.Set("since", ts) - } - - if options.Timestamps { - query.Set("timestamps", "1") - } - - if options.Details { - query.Set("details", "1") - } - - if options.Follow { - query.Set("follow", "1") - } - query.Set("tail", options.Tail) - - resp, err := cli.get(ctx, "/tasks/"+taskID+"/logs", query, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/transport.go b/vendor/github.com/docker/docker/client/transport.go deleted file mode 100644 index 55413443..00000000 --- a/vendor/github.com/docker/docker/client/transport.go +++ /dev/null @@ -1,17 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "crypto/tls" - "net/http" -) - -// resolveTLSConfig attempts to resolve the TLS configuration from the -// RoundTripper. -func resolveTLSConfig(transport http.RoundTripper) *tls.Config { - switch tr := transport.(type) { - case *http.Transport: - return tr.TLSClientConfig - default: - return nil - } -} diff --git a/vendor/github.com/docker/docker/client/utils.go b/vendor/github.com/docker/docker/client/utils.go deleted file mode 100644 index 7f3ff44e..00000000 --- a/vendor/github.com/docker/docker/client/utils.go +++ /dev/null @@ -1,34 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "net/url" - "regexp" - - "github.com/docker/docker/api/types/filters" -) - -var headerRegexp = regexp.MustCompile(`\ADocker/.+\s\((.+)\)\z`) - -// getDockerOS returns the operating system based on the server header from the daemon. -func getDockerOS(serverHeader string) string { - var osType string - matches := headerRegexp.FindStringSubmatch(serverHeader) - if len(matches) > 0 { - osType = matches[1] - } - return osType -} - -// getFiltersQuery returns a url query with "filters" query term, based on the -// filters provided. -func getFiltersQuery(f filters.Args) (url.Values, error) { - query := url.Values{} - if f.Len() > 0 { - filterJSON, err := filters.ToJSON(f) - if err != nil { - return query, err - } - query.Set("filters", filterJSON) - } - return query, nil -} diff --git a/vendor/github.com/docker/docker/client/version.go b/vendor/github.com/docker/docker/client/version.go deleted file mode 100644 index 8f17ff4e..00000000 --- a/vendor/github.com/docker/docker/client/version.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" -) - -// ServerVersion returns information of the docker client and server host. -func (cli *Client) ServerVersion(ctx context.Context) (types.Version, error) { - resp, err := cli.get(ctx, "/version", nil, nil) - defer ensureReaderClosed(resp) - if err != nil { - return types.Version{}, err - } - - var server types.Version - err = json.NewDecoder(resp.body).Decode(&server) - return server, err -} diff --git a/vendor/github.com/docker/docker/client/volume_create.go b/vendor/github.com/docker/docker/client/volume_create.go deleted file mode 100644 index 92761b3c..00000000 --- a/vendor/github.com/docker/docker/client/volume_create.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" - volumetypes "github.com/docker/docker/api/types/volume" -) - -// VolumeCreate creates a volume in the docker host. -func (cli *Client) VolumeCreate(ctx context.Context, options volumetypes.VolumeCreateBody) (types.Volume, error) { - var volume types.Volume - resp, err := cli.post(ctx, "/volumes/create", nil, options, nil) - defer ensureReaderClosed(resp) - if err != nil { - return volume, err - } - err = json.NewDecoder(resp.body).Decode(&volume) - return volume, err -} diff --git a/vendor/github.com/docker/docker/client/volume_inspect.go b/vendor/github.com/docker/docker/client/volume_inspect.go deleted file mode 100644 index e20b2c67..00000000 --- a/vendor/github.com/docker/docker/client/volume_inspect.go +++ /dev/null @@ -1,38 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "io/ioutil" - - "github.com/docker/docker/api/types" -) - -// VolumeInspect returns the information about a specific volume in the docker host. -func (cli *Client) VolumeInspect(ctx context.Context, volumeID string) (types.Volume, error) { - volume, _, err := cli.VolumeInspectWithRaw(ctx, volumeID) - return volume, err -} - -// VolumeInspectWithRaw returns the information about a specific volume in the docker host and its raw representation -func (cli *Client) VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) { - if volumeID == "" { - return types.Volume{}, nil, objectNotFoundError{object: "volume", id: volumeID} - } - - var volume types.Volume - resp, err := cli.get(ctx, "/volumes/"+volumeID, nil, nil) - defer ensureReaderClosed(resp) - if err != nil { - return volume, nil, wrapResponseError(err, resp, "volume", volumeID) - } - - body, err := ioutil.ReadAll(resp.body) - if err != nil { - return volume, nil, err - } - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&volume) - return volume, body, err -} diff --git a/vendor/github.com/docker/docker/client/volume_list.go b/vendor/github.com/docker/docker/client/volume_list.go deleted file mode 100644 index 942498dd..00000000 --- a/vendor/github.com/docker/docker/client/volume_list.go +++ /dev/null @@ -1,33 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/filters" - volumetypes "github.com/docker/docker/api/types/volume" -) - -// VolumeList returns the volumes configured in the docker host. -func (cli *Client) VolumeList(ctx context.Context, filter filters.Args) (volumetypes.VolumeListOKBody, error) { - var volumes volumetypes.VolumeListOKBody - query := url.Values{} - - if filter.Len() > 0 { - //nolint:staticcheck // ignore SA1019 for old code - filterJSON, err := filters.ToParamWithVersion(cli.version, filter) - if err != nil { - return volumes, err - } - query.Set("filters", filterJSON) - } - resp, err := cli.get(ctx, "/volumes", query, nil) - defer ensureReaderClosed(resp) - if err != nil { - return volumes, err - } - - err = json.NewDecoder(resp.body).Decode(&volumes) - return volumes, err -} diff --git a/vendor/github.com/docker/docker/client/volume_prune.go b/vendor/github.com/docker/docker/client/volume_prune.go deleted file mode 100644 index 6e324708..00000000 --- a/vendor/github.com/docker/docker/client/volume_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" -) - -// VolumesPrune requests the daemon to delete unused data -func (cli *Client) VolumesPrune(ctx context.Context, pruneFilters filters.Args) (types.VolumesPruneReport, error) { - var report types.VolumesPruneReport - - if err := cli.NewVersionError("1.25", "volume prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/volumes/prune", query, nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return report, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving volume prune report: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/volume_remove.go b/vendor/github.com/docker/docker/client/volume_remove.go deleted file mode 100644 index 79decdaf..00000000 --- a/vendor/github.com/docker/docker/client/volume_remove.go +++ /dev/null @@ -1,21 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - - "github.com/docker/docker/api/types/versions" -) - -// VolumeRemove removes a volume from the docker host. -func (cli *Client) VolumeRemove(ctx context.Context, volumeID string, force bool) error { - query := url.Values{} - if versions.GreaterThanOrEqualTo(cli.version, "1.25") { - if force { - query.Set("force", "1") - } - } - resp, err := cli.delete(ctx, "/volumes/"+volumeID, query, nil) - defer ensureReaderClosed(resp) - return wrapResponseError(err, resp, "volume", volumeID) -} diff --git a/vendor/github.com/docker/docker/errdefs/defs.go b/vendor/github.com/docker/docker/errdefs/defs.go deleted file mode 100644 index 61e7456b..00000000 --- a/vendor/github.com/docker/docker/errdefs/defs.go +++ /dev/null @@ -1,69 +0,0 @@ -package errdefs // import "github.com/docker/docker/errdefs" - -// ErrNotFound signals that the requested object doesn't exist -type ErrNotFound interface { - NotFound() -} - -// ErrInvalidParameter signals that the user input is invalid -type ErrInvalidParameter interface { - InvalidParameter() -} - -// ErrConflict signals that some internal state conflicts with the requested action and can't be performed. -// A change in state should be able to clear this error. -type ErrConflict interface { - Conflict() -} - -// ErrUnauthorized is used to signify that the user is not authorized to perform a specific action -type ErrUnauthorized interface { - Unauthorized() -} - -// ErrUnavailable signals that the requested action/subsystem is not available. -type ErrUnavailable interface { - Unavailable() -} - -// ErrForbidden signals that the requested action cannot be performed under any circumstances. -// When a ErrForbidden is returned, the caller should never retry the action. -type ErrForbidden interface { - Forbidden() -} - -// ErrSystem signals that some internal error occurred. -// An example of this would be a failed mount request. -type ErrSystem interface { - System() -} - -// ErrNotModified signals that an action can't be performed because it's already in the desired state -type ErrNotModified interface { - NotModified() -} - -// ErrNotImplemented signals that the requested action/feature is not implemented on the system as configured. -type ErrNotImplemented interface { - NotImplemented() -} - -// ErrUnknown signals that the kind of error that occurred is not known. -type ErrUnknown interface { - Unknown() -} - -// ErrCancelled signals that the action was cancelled. -type ErrCancelled interface { - Cancelled() -} - -// ErrDeadline signals that the deadline was reached before the action completed. -type ErrDeadline interface { - DeadlineExceeded() -} - -// ErrDataLoss indicates that data was lost or there is data corruption. -type ErrDataLoss interface { - DataLoss() -} diff --git a/vendor/github.com/docker/docker/errdefs/doc.go b/vendor/github.com/docker/docker/errdefs/doc.go deleted file mode 100644 index c211f174..00000000 --- a/vendor/github.com/docker/docker/errdefs/doc.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package errdefs defines a set of error interfaces that packages should use for communicating classes of errors. -// Errors that cross the package boundary should implement one (and only one) of these interfaces. -// -// Packages should not reference these interfaces directly, only implement them. -// To check if a particular error implements one of these interfaces, there are helper -// functions provided (e.g. `Is`) which can be used rather than asserting the interfaces directly. -// If you must assert on these interfaces, be sure to check the causal chain (`err.Cause()`). -package errdefs // import "github.com/docker/docker/errdefs" diff --git a/vendor/github.com/docker/docker/errdefs/helpers.go b/vendor/github.com/docker/docker/errdefs/helpers.go deleted file mode 100644 index fe06fb6f..00000000 --- a/vendor/github.com/docker/docker/errdefs/helpers.go +++ /dev/null @@ -1,279 +0,0 @@ -package errdefs // import "github.com/docker/docker/errdefs" - -import "context" - -type errNotFound struct{ error } - -func (errNotFound) NotFound() {} - -func (e errNotFound) Cause() error { - return e.error -} - -func (e errNotFound) Unwrap() error { - return e.error -} - -// NotFound is a helper to create an error of the class with the same name from any error type -func NotFound(err error) error { - if err == nil || IsNotFound(err) { - return err - } - return errNotFound{err} -} - -type errInvalidParameter struct{ error } - -func (errInvalidParameter) InvalidParameter() {} - -func (e errInvalidParameter) Cause() error { - return e.error -} - -func (e errInvalidParameter) Unwrap() error { - return e.error -} - -// InvalidParameter is a helper to create an error of the class with the same name from any error type -func InvalidParameter(err error) error { - if err == nil || IsInvalidParameter(err) { - return err - } - return errInvalidParameter{err} -} - -type errConflict struct{ error } - -func (errConflict) Conflict() {} - -func (e errConflict) Cause() error { - return e.error -} - -func (e errConflict) Unwrap() error { - return e.error -} - -// Conflict is a helper to create an error of the class with the same name from any error type -func Conflict(err error) error { - if err == nil || IsConflict(err) { - return err - } - return errConflict{err} -} - -type errUnauthorized struct{ error } - -func (errUnauthorized) Unauthorized() {} - -func (e errUnauthorized) Cause() error { - return e.error -} - -func (e errUnauthorized) Unwrap() error { - return e.error -} - -// Unauthorized is a helper to create an error of the class with the same name from any error type -func Unauthorized(err error) error { - if err == nil || IsUnauthorized(err) { - return err - } - return errUnauthorized{err} -} - -type errUnavailable struct{ error } - -func (errUnavailable) Unavailable() {} - -func (e errUnavailable) Cause() error { - return e.error -} - -func (e errUnavailable) Unwrap() error { - return e.error -} - -// Unavailable is a helper to create an error of the class with the same name from any error type -func Unavailable(err error) error { - if err == nil || IsUnavailable(err) { - return err - } - return errUnavailable{err} -} - -type errForbidden struct{ error } - -func (errForbidden) Forbidden() {} - -func (e errForbidden) Cause() error { - return e.error -} - -func (e errForbidden) Unwrap() error { - return e.error -} - -// Forbidden is a helper to create an error of the class with the same name from any error type -func Forbidden(err error) error { - if err == nil || IsForbidden(err) { - return err - } - return errForbidden{err} -} - -type errSystem struct{ error } - -func (errSystem) System() {} - -func (e errSystem) Cause() error { - return e.error -} - -func (e errSystem) Unwrap() error { - return e.error -} - -// System is a helper to create an error of the class with the same name from any error type -func System(err error) error { - if err == nil || IsSystem(err) { - return err - } - return errSystem{err} -} - -type errNotModified struct{ error } - -func (errNotModified) NotModified() {} - -func (e errNotModified) Cause() error { - return e.error -} - -func (e errNotModified) Unwrap() error { - return e.error -} - -// NotModified is a helper to create an error of the class with the same name from any error type -func NotModified(err error) error { - if err == nil || IsNotModified(err) { - return err - } - return errNotModified{err} -} - -type errNotImplemented struct{ error } - -func (errNotImplemented) NotImplemented() {} - -func (e errNotImplemented) Cause() error { - return e.error -} - -func (e errNotImplemented) Unwrap() error { - return e.error -} - -// NotImplemented is a helper to create an error of the class with the same name from any error type -func NotImplemented(err error) error { - if err == nil || IsNotImplemented(err) { - return err - } - return errNotImplemented{err} -} - -type errUnknown struct{ error } - -func (errUnknown) Unknown() {} - -func (e errUnknown) Cause() error { - return e.error -} - -func (e errUnknown) Unwrap() error { - return e.error -} - -// Unknown is a helper to create an error of the class with the same name from any error type -func Unknown(err error) error { - if err == nil || IsUnknown(err) { - return err - } - return errUnknown{err} -} - -type errCancelled struct{ error } - -func (errCancelled) Cancelled() {} - -func (e errCancelled) Cause() error { - return e.error -} - -func (e errCancelled) Unwrap() error { - return e.error -} - -// Cancelled is a helper to create an error of the class with the same name from any error type -func Cancelled(err error) error { - if err == nil || IsCancelled(err) { - return err - } - return errCancelled{err} -} - -type errDeadline struct{ error } - -func (errDeadline) DeadlineExceeded() {} - -func (e errDeadline) Cause() error { - return e.error -} - -func (e errDeadline) Unwrap() error { - return e.error -} - -// Deadline is a helper to create an error of the class with the same name from any error type -func Deadline(err error) error { - if err == nil || IsDeadline(err) { - return err - } - return errDeadline{err} -} - -type errDataLoss struct{ error } - -func (errDataLoss) DataLoss() {} - -func (e errDataLoss) Cause() error { - return e.error -} - -func (e errDataLoss) Unwrap() error { - return e.error -} - -// DataLoss is a helper to create an error of the class with the same name from any error type -func DataLoss(err error) error { - if err == nil || IsDataLoss(err) { - return err - } - return errDataLoss{err} -} - -// FromContext returns the error class from the passed in context -func FromContext(ctx context.Context) error { - e := ctx.Err() - if e == nil { - return nil - } - - if e == context.Canceled { - return Cancelled(e) - } - if e == context.DeadlineExceeded { - return Deadline(e) - } - return Unknown(e) -} diff --git a/vendor/github.com/docker/docker/errdefs/http_helpers.go b/vendor/github.com/docker/docker/errdefs/http_helpers.go deleted file mode 100644 index 07552f1c..00000000 --- a/vendor/github.com/docker/docker/errdefs/http_helpers.go +++ /dev/null @@ -1,191 +0,0 @@ -package errdefs // import "github.com/docker/docker/errdefs" - -import ( - "fmt" - "net/http" - - containerderrors "github.com/containerd/containerd/errdefs" - "github.com/docker/distribution/registry/api/errcode" - "github.com/sirupsen/logrus" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// GetHTTPErrorStatusCode retrieves status code from error message. -func GetHTTPErrorStatusCode(err error) int { - if err == nil { - logrus.WithFields(logrus.Fields{"error": err}).Error("unexpected HTTP error handling") - return http.StatusInternalServerError - } - - var statusCode int - - // Stop right there - // Are you sure you should be adding a new error class here? Do one of the existing ones work? - - // Note that the below functions are already checking the error causal chain for matches. - switch { - case IsNotFound(err): - statusCode = http.StatusNotFound - case IsInvalidParameter(err): - statusCode = http.StatusBadRequest - case IsConflict(err): - statusCode = http.StatusConflict - case IsUnauthorized(err): - statusCode = http.StatusUnauthorized - case IsUnavailable(err): - statusCode = http.StatusServiceUnavailable - case IsForbidden(err): - statusCode = http.StatusForbidden - case IsNotModified(err): - statusCode = http.StatusNotModified - case IsNotImplemented(err): - statusCode = http.StatusNotImplemented - case IsSystem(err) || IsUnknown(err) || IsDataLoss(err) || IsDeadline(err) || IsCancelled(err): - statusCode = http.StatusInternalServerError - default: - statusCode = statusCodeFromGRPCError(err) - if statusCode != http.StatusInternalServerError { - return statusCode - } - statusCode = statusCodeFromContainerdError(err) - if statusCode != http.StatusInternalServerError { - return statusCode - } - statusCode = statusCodeFromDistributionError(err) - if statusCode != http.StatusInternalServerError { - return statusCode - } - if e, ok := err.(causer); ok { - return GetHTTPErrorStatusCode(e.Cause()) - } - - logrus.WithFields(logrus.Fields{ - "module": "api", - "error_type": fmt.Sprintf("%T", err), - }).Debugf("FIXME: Got an API for which error does not match any expected type!!!: %+v", err) - } - - if statusCode == 0 { - statusCode = http.StatusInternalServerError - } - - return statusCode -} - -// FromStatusCode creates an errdef error, based on the provided HTTP status-code -func FromStatusCode(err error, statusCode int) error { - if err == nil { - return err - } - switch statusCode { - case http.StatusNotFound: - err = NotFound(err) - case http.StatusBadRequest: - err = InvalidParameter(err) - case http.StatusConflict: - err = Conflict(err) - case http.StatusUnauthorized: - err = Unauthorized(err) - case http.StatusServiceUnavailable: - err = Unavailable(err) - case http.StatusForbidden: - err = Forbidden(err) - case http.StatusNotModified: - err = NotModified(err) - case http.StatusNotImplemented: - err = NotImplemented(err) - case http.StatusInternalServerError: - if !IsSystem(err) && !IsUnknown(err) && !IsDataLoss(err) && !IsDeadline(err) && !IsCancelled(err) { - err = System(err) - } - default: - logrus.WithFields(logrus.Fields{ - "module": "api", - "status_code": fmt.Sprintf("%d", statusCode), - }).Debugf("FIXME: Got an status-code for which error does not match any expected type!!!: %d", statusCode) - - switch { - case statusCode >= 200 && statusCode < 400: - // it's a client error - case statusCode >= 400 && statusCode < 500: - err = InvalidParameter(err) - case statusCode >= 500 && statusCode < 600: - err = System(err) - default: - err = Unknown(err) - } - } - return err -} - -// statusCodeFromGRPCError returns status code according to gRPC error -func statusCodeFromGRPCError(err error) int { - switch status.Code(err) { - case codes.InvalidArgument: // code 3 - return http.StatusBadRequest - case codes.NotFound: // code 5 - return http.StatusNotFound - case codes.AlreadyExists: // code 6 - return http.StatusConflict - case codes.PermissionDenied: // code 7 - return http.StatusForbidden - case codes.FailedPrecondition: // code 9 - return http.StatusBadRequest - case codes.Unauthenticated: // code 16 - return http.StatusUnauthorized - case codes.OutOfRange: // code 11 - return http.StatusBadRequest - case codes.Unimplemented: // code 12 - return http.StatusNotImplemented - case codes.Unavailable: // code 14 - return http.StatusServiceUnavailable - default: - // codes.Canceled(1) - // codes.Unknown(2) - // codes.DeadlineExceeded(4) - // codes.ResourceExhausted(8) - // codes.Aborted(10) - // codes.Internal(13) - // codes.DataLoss(15) - return http.StatusInternalServerError - } -} - -// statusCodeFromDistributionError returns status code according to registry errcode -// code is loosely based on errcode.ServeJSON() in docker/distribution -func statusCodeFromDistributionError(err error) int { - switch errs := err.(type) { - case errcode.Errors: - if len(errs) < 1 { - return http.StatusInternalServerError - } - if _, ok := errs[0].(errcode.ErrorCoder); ok { - return statusCodeFromDistributionError(errs[0]) - } - case errcode.ErrorCoder: - return errs.ErrorCode().Descriptor().HTTPStatusCode - } - return http.StatusInternalServerError -} - -// statusCodeFromContainerdError returns status code for containerd errors when -// consumed directly (not through gRPC) -func statusCodeFromContainerdError(err error) int { - switch { - case containerderrors.IsInvalidArgument(err): - return http.StatusBadRequest - case containerderrors.IsNotFound(err): - return http.StatusNotFound - case containerderrors.IsAlreadyExists(err): - return http.StatusConflict - case containerderrors.IsFailedPrecondition(err): - return http.StatusPreconditionFailed - case containerderrors.IsUnavailable(err): - return http.StatusServiceUnavailable - case containerderrors.IsNotImplemented(err): - return http.StatusNotImplemented - default: - return http.StatusInternalServerError - } -} diff --git a/vendor/github.com/docker/docker/errdefs/is.go b/vendor/github.com/docker/docker/errdefs/is.go deleted file mode 100644 index 3abf07d0..00000000 --- a/vendor/github.com/docker/docker/errdefs/is.go +++ /dev/null @@ -1,107 +0,0 @@ -package errdefs // import "github.com/docker/docker/errdefs" - -type causer interface { - Cause() error -} - -func getImplementer(err error) error { - switch e := err.(type) { - case - ErrNotFound, - ErrInvalidParameter, - ErrConflict, - ErrUnauthorized, - ErrUnavailable, - ErrForbidden, - ErrSystem, - ErrNotModified, - ErrNotImplemented, - ErrCancelled, - ErrDeadline, - ErrDataLoss, - ErrUnknown: - return err - case causer: - return getImplementer(e.Cause()) - default: - return err - } -} - -// IsNotFound returns if the passed in error is an ErrNotFound -func IsNotFound(err error) bool { - _, ok := getImplementer(err).(ErrNotFound) - return ok -} - -// IsInvalidParameter returns if the passed in error is an ErrInvalidParameter -func IsInvalidParameter(err error) bool { - _, ok := getImplementer(err).(ErrInvalidParameter) - return ok -} - -// IsConflict returns if the passed in error is an ErrConflict -func IsConflict(err error) bool { - _, ok := getImplementer(err).(ErrConflict) - return ok -} - -// IsUnauthorized returns if the passed in error is an ErrUnauthorized -func IsUnauthorized(err error) bool { - _, ok := getImplementer(err).(ErrUnauthorized) - return ok -} - -// IsUnavailable returns if the passed in error is an ErrUnavailable -func IsUnavailable(err error) bool { - _, ok := getImplementer(err).(ErrUnavailable) - return ok -} - -// IsForbidden returns if the passed in error is an ErrForbidden -func IsForbidden(err error) bool { - _, ok := getImplementer(err).(ErrForbidden) - return ok -} - -// IsSystem returns if the passed in error is an ErrSystem -func IsSystem(err error) bool { - _, ok := getImplementer(err).(ErrSystem) - return ok -} - -// IsNotModified returns if the passed in error is a NotModified error -func IsNotModified(err error) bool { - _, ok := getImplementer(err).(ErrNotModified) - return ok -} - -// IsNotImplemented returns if the passed in error is an ErrNotImplemented -func IsNotImplemented(err error) bool { - _, ok := getImplementer(err).(ErrNotImplemented) - return ok -} - -// IsUnknown returns if the passed in error is an ErrUnknown -func IsUnknown(err error) bool { - _, ok := getImplementer(err).(ErrUnknown) - return ok -} - -// IsCancelled returns if the passed in error is an ErrCancelled -func IsCancelled(err error) bool { - _, ok := getImplementer(err).(ErrCancelled) - return ok -} - -// IsDeadline returns if the passed in error is an ErrDeadline -func IsDeadline(err error) bool { - _, ok := getImplementer(err).(ErrDeadline) - return ok -} - -// IsDataLoss returns if the passed in error is an ErrDataLoss -func IsDataLoss(err error) bool { - _, ok := getImplementer(err).(ErrDataLoss) - return ok -} diff --git a/vendor/github.com/docker/docker/pkg/archive/README.md b/vendor/github.com/docker/docker/pkg/archive/README.md deleted file mode 100644 index 7307d969..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/README.md +++ /dev/null @@ -1 +0,0 @@ -This code provides helper functions for dealing with archive files. diff --git a/vendor/github.com/docker/docker/pkg/archive/archive.go b/vendor/github.com/docker/docker/pkg/archive/archive.go deleted file mode 100644 index 084a4fa0..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive.go +++ /dev/null @@ -1,1300 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "bufio" - "bytes" - "compress/bzip2" - "compress/gzip" - "context" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "runtime" - "strconv" - "strings" - "syscall" - "time" - - "github.com/docker/docker/pkg/fileutils" - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/ioutils" - "github.com/docker/docker/pkg/pools" - "github.com/docker/docker/pkg/system" - "github.com/sirupsen/logrus" - exec "golang.org/x/sys/execabs" -) - -type ( - // Compression is the state represents if compressed or not. - Compression int - // WhiteoutFormat is the format of whiteouts unpacked - WhiteoutFormat int - - // TarOptions wraps the tar options. - TarOptions struct { - IncludeFiles []string - ExcludePatterns []string - Compression Compression - NoLchown bool - UIDMaps []idtools.IDMap - GIDMaps []idtools.IDMap - ChownOpts *idtools.Identity - IncludeSourceDir bool - // WhiteoutFormat is the expected on disk format for whiteout files. - // This format will be converted to the standard format on pack - // and from the standard format on unpack. - WhiteoutFormat WhiteoutFormat - // When unpacking, specifies whether overwriting a directory with a - // non-directory is allowed and vice versa. - NoOverwriteDirNonDir bool - // For each include when creating an archive, the included name will be - // replaced with the matching name from this map. - RebaseNames map[string]string - InUserNS bool - } -) - -// Archiver implements the Archiver interface and allows the reuse of most utility functions of -// this package with a pluggable Untar function. Also, to facilitate the passing of specific id -// mappings for untar, an Archiver can be created with maps which will then be passed to Untar operations. -type Archiver struct { - Untar func(io.Reader, string, *TarOptions) error - IDMapping *idtools.IdentityMapping -} - -// NewDefaultArchiver returns a new Archiver without any IdentityMapping -func NewDefaultArchiver() *Archiver { - return &Archiver{Untar: Untar, IDMapping: &idtools.IdentityMapping{}} -} - -// breakoutError is used to differentiate errors related to breaking out -// When testing archive breakout in the unit tests, this error is expected -// in order for the test to pass. -type breakoutError error - -const ( - // Uncompressed represents the uncompressed. - Uncompressed Compression = iota - // Bzip2 is bzip2 compression algorithm. - Bzip2 - // Gzip is gzip compression algorithm. - Gzip - // Xz is xz compression algorithm. - Xz -) - -const ( - // AUFSWhiteoutFormat is the default format for whiteouts - AUFSWhiteoutFormat WhiteoutFormat = iota - // OverlayWhiteoutFormat formats whiteout according to the overlay - // standard. - OverlayWhiteoutFormat -) - -const ( - modeISDIR = 040000 // Directory - modeISFIFO = 010000 // FIFO - modeISREG = 0100000 // Regular file - modeISLNK = 0120000 // Symbolic link - modeISBLK = 060000 // Block special file - modeISCHR = 020000 // Character special file - modeISSOCK = 0140000 // Socket -) - -// IsArchivePath checks if the (possibly compressed) file at the given path -// starts with a tar file header. -func IsArchivePath(path string) bool { - file, err := os.Open(path) - if err != nil { - return false - } - defer file.Close() - rdr, err := DecompressStream(file) - if err != nil { - return false - } - defer rdr.Close() - r := tar.NewReader(rdr) - _, err = r.Next() - return err == nil -} - -// DetectCompression detects the compression algorithm of the source. -func DetectCompression(source []byte) Compression { - for compression, m := range map[Compression][]byte{ - Bzip2: {0x42, 0x5A, 0x68}, - Gzip: {0x1F, 0x8B, 0x08}, - Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}, - } { - if len(source) < len(m) { - logrus.Debug("Len too short") - continue - } - if bytes.Equal(m, source[:len(m)]) { - return compression - } - } - return Uncompressed -} - -func xzDecompress(ctx context.Context, archive io.Reader) (io.ReadCloser, error) { - args := []string{"xz", "-d", "-c", "-q"} - - return cmdStream(exec.CommandContext(ctx, args[0], args[1:]...), archive) -} - -func gzDecompress(ctx context.Context, buf io.Reader) (io.ReadCloser, error) { - noPigzEnv := os.Getenv("MOBY_DISABLE_PIGZ") - var noPigz bool - - if noPigzEnv != "" { - var err error - noPigz, err = strconv.ParseBool(noPigzEnv) - if err != nil { - logrus.WithError(err).Warn("invalid value in MOBY_DISABLE_PIGZ env var") - } - } - - if noPigz { - logrus.Debugf("Use of pigz is disabled due to MOBY_DISABLE_PIGZ=%s", noPigzEnv) - return gzip.NewReader(buf) - } - - unpigzPath, err := exec.LookPath("unpigz") - if err != nil { - logrus.Debugf("unpigz binary not found, falling back to go gzip library") - return gzip.NewReader(buf) - } - - logrus.Debugf("Using %s to decompress", unpigzPath) - - return cmdStream(exec.CommandContext(ctx, unpigzPath, "-d", "-c"), buf) -} - -func wrapReadCloser(readBuf io.ReadCloser, cancel context.CancelFunc) io.ReadCloser { - return ioutils.NewReadCloserWrapper(readBuf, func() error { - cancel() - return readBuf.Close() - }) -} - -// DecompressStream decompresses the archive and returns a ReaderCloser with the decompressed archive. -func DecompressStream(archive io.Reader) (io.ReadCloser, error) { - p := pools.BufioReader32KPool - buf := p.Get(archive) - bs, err := buf.Peek(10) - if err != nil && err != io.EOF { - // Note: we'll ignore any io.EOF error because there are some odd - // cases where the layer.tar file will be empty (zero bytes) and - // that results in an io.EOF from the Peek() call. So, in those - // cases we'll just treat it as a non-compressed stream and - // that means just create an empty layer. - // See Issue 18170 - return nil, err - } - - compression := DetectCompression(bs) - switch compression { - case Uncompressed: - readBufWrapper := p.NewReadCloserWrapper(buf, buf) - return readBufWrapper, nil - case Gzip: - ctx, cancel := context.WithCancel(context.Background()) - - gzReader, err := gzDecompress(ctx, buf) - if err != nil { - cancel() - return nil, err - } - readBufWrapper := p.NewReadCloserWrapper(buf, gzReader) - return wrapReadCloser(readBufWrapper, cancel), nil - case Bzip2: - bz2Reader := bzip2.NewReader(buf) - readBufWrapper := p.NewReadCloserWrapper(buf, bz2Reader) - return readBufWrapper, nil - case Xz: - ctx, cancel := context.WithCancel(context.Background()) - - xzReader, err := xzDecompress(ctx, buf) - if err != nil { - cancel() - return nil, err - } - readBufWrapper := p.NewReadCloserWrapper(buf, xzReader) - return wrapReadCloser(readBufWrapper, cancel), nil - default: - return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) - } -} - -// CompressStream compresses the dest with specified compression algorithm. -func CompressStream(dest io.Writer, compression Compression) (io.WriteCloser, error) { - p := pools.BufioWriter32KPool - buf := p.Get(dest) - switch compression { - case Uncompressed: - writeBufWrapper := p.NewWriteCloserWrapper(buf, buf) - return writeBufWrapper, nil - case Gzip: - gzWriter := gzip.NewWriter(dest) - writeBufWrapper := p.NewWriteCloserWrapper(buf, gzWriter) - return writeBufWrapper, nil - case Bzip2, Xz: - // archive/bzip2 does not support writing, and there is no xz support at all - // However, this is not a problem as docker only currently generates gzipped tars - return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) - default: - return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) - } -} - -// TarModifierFunc is a function that can be passed to ReplaceFileTarWrapper to -// modify the contents or header of an entry in the archive. If the file already -// exists in the archive the TarModifierFunc will be called with the Header and -// a reader which will return the files content. If the file does not exist both -// header and content will be nil. -type TarModifierFunc func(path string, header *tar.Header, content io.Reader) (*tar.Header, []byte, error) - -// ReplaceFileTarWrapper converts inputTarStream to a new tar stream. Files in the -// tar stream are modified if they match any of the keys in mods. -func ReplaceFileTarWrapper(inputTarStream io.ReadCloser, mods map[string]TarModifierFunc) io.ReadCloser { - pipeReader, pipeWriter := io.Pipe() - - go func() { - tarReader := tar.NewReader(inputTarStream) - tarWriter := tar.NewWriter(pipeWriter) - defer inputTarStream.Close() - defer tarWriter.Close() - - modify := func(name string, original *tar.Header, modifier TarModifierFunc, tarReader io.Reader) error { - header, data, err := modifier(name, original, tarReader) - switch { - case err != nil: - return err - case header == nil: - return nil - } - - header.Name = name - header.Size = int64(len(data)) - if err := tarWriter.WriteHeader(header); err != nil { - return err - } - if len(data) != 0 { - if _, err := tarWriter.Write(data); err != nil { - return err - } - } - return nil - } - - var err error - var originalHeader *tar.Header - for { - originalHeader, err = tarReader.Next() - if err == io.EOF { - break - } - if err != nil { - pipeWriter.CloseWithError(err) - return - } - - modifier, ok := mods[originalHeader.Name] - if !ok { - // No modifiers for this file, copy the header and data - if err := tarWriter.WriteHeader(originalHeader); err != nil { - pipeWriter.CloseWithError(err) - return - } - if _, err := pools.Copy(tarWriter, tarReader); err != nil { - pipeWriter.CloseWithError(err) - return - } - continue - } - delete(mods, originalHeader.Name) - - if err := modify(originalHeader.Name, originalHeader, modifier, tarReader); err != nil { - pipeWriter.CloseWithError(err) - return - } - } - - // Apply the modifiers that haven't matched any files in the archive - for name, modifier := range mods { - if err := modify(name, nil, modifier, nil); err != nil { - pipeWriter.CloseWithError(err) - return - } - } - - pipeWriter.Close() - - }() - return pipeReader -} - -// Extension returns the extension of a file that uses the specified compression algorithm. -func (compression *Compression) Extension() string { - switch *compression { - case Uncompressed: - return "tar" - case Bzip2: - return "tar.bz2" - case Gzip: - return "tar.gz" - case Xz: - return "tar.xz" - } - return "" -} - -// FileInfoHeader creates a populated Header from fi. -// Compared to archive pkg this function fills in more information. -// Also, regardless of Go version, this function fills file type bits (e.g. hdr.Mode |= modeISDIR), -// which have been deleted since Go 1.9 archive/tar. -func FileInfoHeader(name string, fi os.FileInfo, link string) (*tar.Header, error) { - hdr, err := tar.FileInfoHeader(fi, link) - if err != nil { - return nil, err - } - hdr.Format = tar.FormatPAX - hdr.ModTime = hdr.ModTime.Truncate(time.Second) - hdr.AccessTime = time.Time{} - hdr.ChangeTime = time.Time{} - hdr.Mode = fillGo18FileTypeBits(int64(chmodTarEntry(os.FileMode(hdr.Mode))), fi) - hdr.Name = canonicalTarName(name, fi.IsDir()) - if err := setHeaderForSpecialDevice(hdr, name, fi.Sys()); err != nil { - return nil, err - } - return hdr, nil -} - -// fillGo18FileTypeBits fills type bits which have been removed on Go 1.9 archive/tar -// https://github.com/golang/go/commit/66b5a2f -func fillGo18FileTypeBits(mode int64, fi os.FileInfo) int64 { - fm := fi.Mode() - switch { - case fm.IsRegular(): - mode |= modeISREG - case fi.IsDir(): - mode |= modeISDIR - case fm&os.ModeSymlink != 0: - mode |= modeISLNK - case fm&os.ModeDevice != 0: - if fm&os.ModeCharDevice != 0 { - mode |= modeISCHR - } else { - mode |= modeISBLK - } - case fm&os.ModeNamedPipe != 0: - mode |= modeISFIFO - case fm&os.ModeSocket != 0: - mode |= modeISSOCK - } - return mode -} - -// ReadSecurityXattrToTarHeader reads security.capability xattr from filesystem -// to a tar header -func ReadSecurityXattrToTarHeader(path string, hdr *tar.Header) error { - capability, _ := system.Lgetxattr(path, "security.capability") - if capability != nil { - hdr.Xattrs = make(map[string]string) - hdr.Xattrs["security.capability"] = string(capability) - } - return nil -} - -type tarWhiteoutConverter interface { - ConvertWrite(*tar.Header, string, os.FileInfo) (*tar.Header, error) - ConvertRead(*tar.Header, string) (bool, error) -} - -type tarAppender struct { - TarWriter *tar.Writer - Buffer *bufio.Writer - - // for hardlink mapping - SeenFiles map[uint64]string - IdentityMapping *idtools.IdentityMapping - ChownOpts *idtools.Identity - - // For packing and unpacking whiteout files in the - // non standard format. The whiteout files defined - // by the AUFS standard are used as the tar whiteout - // standard. - WhiteoutConverter tarWhiteoutConverter -} - -func newTarAppender(idMapping *idtools.IdentityMapping, writer io.Writer, chownOpts *idtools.Identity) *tarAppender { - return &tarAppender{ - SeenFiles: make(map[uint64]string), - TarWriter: tar.NewWriter(writer), - Buffer: pools.BufioWriter32KPool.Get(nil), - IdentityMapping: idMapping, - ChownOpts: chownOpts, - } -} - -// canonicalTarName provides a platform-independent and consistent posix-style -// path for files and directories to be archived regardless of the platform. -func canonicalTarName(name string, isDir bool) string { - name = CanonicalTarNameForPath(name) - - // suffix with '/' for directories - if isDir && !strings.HasSuffix(name, "/") { - name += "/" - } - return name -} - -// addTarFile adds to the tar archive a file from `path` as `name` -func (ta *tarAppender) addTarFile(path, name string) error { - fi, err := os.Lstat(path) - if err != nil { - return err - } - - var link string - if fi.Mode()&os.ModeSymlink != 0 { - var err error - link, err = os.Readlink(path) - if err != nil { - return err - } - } - - hdr, err := FileInfoHeader(name, fi, link) - if err != nil { - return err - } - if err := ReadSecurityXattrToTarHeader(path, hdr); err != nil { - return err - } - - // if it's not a directory and has more than 1 link, - // it's hard linked, so set the type flag accordingly - if !fi.IsDir() && hasHardlinks(fi) { - inode, err := getInodeFromStat(fi.Sys()) - if err != nil { - return err - } - // a link should have a name that it links too - // and that linked name should be first in the tar archive - if oldpath, ok := ta.SeenFiles[inode]; ok { - hdr.Typeflag = tar.TypeLink - hdr.Linkname = oldpath - hdr.Size = 0 // This Must be here for the writer math to add up! - } else { - ta.SeenFiles[inode] = name - } - } - - // check whether the file is overlayfs whiteout - // if yes, skip re-mapping container ID mappings. - isOverlayWhiteout := fi.Mode()&os.ModeCharDevice != 0 && hdr.Devmajor == 0 && hdr.Devminor == 0 - - // handle re-mapping container ID mappings back to host ID mappings before - // writing tar headers/files. We skip whiteout files because they were written - // by the kernel and already have proper ownership relative to the host - if !isOverlayWhiteout && !strings.HasPrefix(filepath.Base(hdr.Name), WhiteoutPrefix) && !ta.IdentityMapping.Empty() { - fileIDPair, err := getFileUIDGID(fi.Sys()) - if err != nil { - return err - } - hdr.Uid, hdr.Gid, err = ta.IdentityMapping.ToContainer(fileIDPair) - if err != nil { - return err - } - } - - // explicitly override with ChownOpts - if ta.ChownOpts != nil { - hdr.Uid = ta.ChownOpts.UID - hdr.Gid = ta.ChownOpts.GID - } - - if ta.WhiteoutConverter != nil { - wo, err := ta.WhiteoutConverter.ConvertWrite(hdr, path, fi) - if err != nil { - return err - } - - // If a new whiteout file exists, write original hdr, then - // replace hdr with wo to be written after. Whiteouts should - // always be written after the original. Note the original - // hdr may have been updated to be a whiteout with returning - // a whiteout header - if wo != nil { - if err := ta.TarWriter.WriteHeader(hdr); err != nil { - return err - } - if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 { - return fmt.Errorf("tar: cannot use whiteout for non-empty file") - } - hdr = wo - } - } - - if err := ta.TarWriter.WriteHeader(hdr); err != nil { - return err - } - - if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 { - // We use system.OpenSequential to ensure we use sequential file - // access on Windows to avoid depleting the standby list. - // On Linux, this equates to a regular os.Open. - file, err := system.OpenSequential(path) - if err != nil { - return err - } - - ta.Buffer.Reset(ta.TarWriter) - defer ta.Buffer.Reset(nil) - _, err = io.Copy(ta.Buffer, file) - file.Close() - if err != nil { - return err - } - err = ta.Buffer.Flush() - if err != nil { - return err - } - } - - return nil -} - -func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool, chownOpts *idtools.Identity, inUserns bool) error { - // hdr.Mode is in linux format, which we can use for sycalls, - // but for os.Foo() calls we need the mode converted to os.FileMode, - // so use hdrInfo.Mode() (they differ for e.g. setuid bits) - hdrInfo := hdr.FileInfo() - - switch hdr.Typeflag { - case tar.TypeDir: - // Create directory unless it exists as a directory already. - // In that case we just want to merge the two - if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) { - if err := os.Mkdir(path, hdrInfo.Mode()); err != nil { - return err - } - } - - case tar.TypeReg, tar.TypeRegA: - // Source is regular file. We use system.OpenFileSequential to use sequential - // file access to avoid depleting the standby list on Windows. - // On Linux, this equates to a regular os.OpenFile - file, err := system.OpenFileSequential(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode()) - if err != nil { - return err - } - if _, err := io.Copy(file, reader); err != nil { - file.Close() - return err - } - file.Close() - - case tar.TypeBlock, tar.TypeChar: - if inUserns { // cannot create devices in a userns - return nil - } - // Handle this is an OS-specific way - if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { - return err - } - - case tar.TypeFifo: - // Handle this is an OS-specific way - if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { - return err - } - - case tar.TypeLink: - targetPath := filepath.Join(extractDir, hdr.Linkname) - // check for hardlink breakout - if !strings.HasPrefix(targetPath, extractDir) { - return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname)) - } - if err := os.Link(targetPath, path); err != nil { - return err - } - - case tar.TypeSymlink: - // path -> hdr.Linkname = targetPath - // e.g. /extractDir/path/to/symlink -> ../2/file = /extractDir/path/2/file - targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname) - - // the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because - // that symlink would first have to be created, which would be caught earlier, at this very check: - if !strings.HasPrefix(targetPath, extractDir) { - return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname)) - } - if err := os.Symlink(hdr.Linkname, path); err != nil { - return err - } - - case tar.TypeXGlobalHeader: - logrus.Debug("PAX Global Extended Headers found and ignored") - return nil - - default: - return fmt.Errorf("unhandled tar header type %d", hdr.Typeflag) - } - - // Lchown is not supported on Windows. - if Lchown && runtime.GOOS != "windows" { - if chownOpts == nil { - chownOpts = &idtools.Identity{UID: hdr.Uid, GID: hdr.Gid} - } - if err := os.Lchown(path, chownOpts.UID, chownOpts.GID); err != nil { - return err - } - } - - var errors []string - for key, value := range hdr.Xattrs { - if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil { - if err == syscall.ENOTSUP || err == syscall.EPERM { - // We ignore errors here because not all graphdrivers support - // xattrs *cough* old versions of AUFS *cough*. However only - // ENOTSUP should be emitted in that case, otherwise we still - // bail. - // EPERM occurs if modifying xattrs is not allowed. This can - // happen when running in userns with restrictions (ChromeOS). - errors = append(errors, err.Error()) - continue - } - return err - } - - } - - if len(errors) > 0 { - logrus.WithFields(logrus.Fields{ - "errors": errors, - }).Warn("ignored xattrs in archive: underlying filesystem doesn't support them") - } - - // There is no LChmod, so ignore mode for symlink. Also, this - // must happen after chown, as that can modify the file mode - if err := handleLChmod(hdr, path, hdrInfo); err != nil { - return err - } - - aTime := hdr.AccessTime - if aTime.Before(hdr.ModTime) { - // Last access time should never be before last modified time. - aTime = hdr.ModTime - } - - // system.Chtimes doesn't support a NOFOLLOW flag atm - if hdr.Typeflag == tar.TypeLink { - if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { - if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil { - return err - } - } - } else if hdr.Typeflag != tar.TypeSymlink { - if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil { - return err - } - } else { - ts := []syscall.Timespec{timeToTimespec(aTime), timeToTimespec(hdr.ModTime)} - if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform { - return err - } - } - return nil -} - -// Tar creates an archive from the directory at `path`, and returns it as a -// stream of bytes. -func Tar(path string, compression Compression) (io.ReadCloser, error) { - return TarWithOptions(path, &TarOptions{Compression: compression}) -} - -// TarWithOptions creates an archive from the directory at `path`, only including files whose relative -// paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. -func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { - - // Fix the source path to work with long path names. This is a no-op - // on platforms other than Windows. - srcPath = fixVolumePathPrefix(srcPath) - - pm, err := fileutils.NewPatternMatcher(options.ExcludePatterns) - if err != nil { - return nil, err - } - - pipeReader, pipeWriter := io.Pipe() - - compressWriter, err := CompressStream(pipeWriter, options.Compression) - if err != nil { - return nil, err - } - - go func() { - ta := newTarAppender( - idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps), - compressWriter, - options.ChownOpts, - ) - ta.WhiteoutConverter = getWhiteoutConverter(options.WhiteoutFormat, options.InUserNS) - - defer func() { - // Make sure to check the error on Close. - if err := ta.TarWriter.Close(); err != nil { - logrus.Errorf("Can't close tar writer: %s", err) - } - if err := compressWriter.Close(); err != nil { - logrus.Errorf("Can't close compress writer: %s", err) - } - if err := pipeWriter.Close(); err != nil { - logrus.Errorf("Can't close pipe writer: %s", err) - } - }() - - // this buffer is needed for the duration of this piped stream - defer pools.BufioWriter32KPool.Put(ta.Buffer) - - // In general we log errors here but ignore them because - // during e.g. a diff operation the container can continue - // mutating the filesystem and we can see transient errors - // from this - - stat, err := os.Lstat(srcPath) - if err != nil { - return - } - - if !stat.IsDir() { - // We can't later join a non-dir with any includes because the - // 'walk' will error if "file/." is stat-ed and "file" is not a - // directory. So, we must split the source path and use the - // basename as the include. - if len(options.IncludeFiles) > 0 { - logrus.Warn("Tar: Can't archive a file with includes") - } - - dir, base := SplitPathDirEntry(srcPath) - srcPath = dir - options.IncludeFiles = []string{base} - } - - if len(options.IncludeFiles) == 0 { - options.IncludeFiles = []string{"."} - } - - seen := make(map[string]bool) - - for _, include := range options.IncludeFiles { - rebaseName := options.RebaseNames[include] - - walkRoot := getWalkRoot(srcPath, include) - filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error { - if err != nil { - logrus.Errorf("Tar: Can't stat file %s to tar: %s", srcPath, err) - return nil - } - - relFilePath, err := filepath.Rel(srcPath, filePath) - if err != nil || (!options.IncludeSourceDir && relFilePath == "." && f.IsDir()) { - // Error getting relative path OR we are looking - // at the source directory path. Skip in both situations. - return nil - } - - if options.IncludeSourceDir && include == "." && relFilePath != "." { - relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator)) - } - - skip := false - - // If "include" is an exact match for the current file - // then even if there's an "excludePatterns" pattern that - // matches it, don't skip it. IOW, assume an explicit 'include' - // is asking for that file no matter what - which is true - // for some files, like .dockerignore and Dockerfile (sometimes) - if include != relFilePath { - skip, err = pm.Matches(relFilePath) - if err != nil { - logrus.Errorf("Error matching %s: %v", relFilePath, err) - return err - } - } - - if skip { - // If we want to skip this file and its a directory - // then we should first check to see if there's an - // excludes pattern (e.g. !dir/file) that starts with this - // dir. If so then we can't skip this dir. - - // Its not a dir then so we can just return/skip. - if !f.IsDir() { - return nil - } - - // No exceptions (!...) in patterns so just skip dir - if !pm.Exclusions() { - return filepath.SkipDir - } - - dirSlash := relFilePath + string(filepath.Separator) - - for _, pat := range pm.Patterns() { - if !pat.Exclusion() { - continue - } - if strings.HasPrefix(pat.String()+string(filepath.Separator), dirSlash) { - // found a match - so can't skip this dir - return nil - } - } - - // No matching exclusion dir so just skip dir - return filepath.SkipDir - } - - if seen[relFilePath] { - return nil - } - seen[relFilePath] = true - - // Rename the base resource. - if rebaseName != "" { - var replacement string - if rebaseName != string(filepath.Separator) { - // Special case the root directory to replace with an - // empty string instead so that we don't end up with - // double slashes in the paths. - replacement = rebaseName - } - - relFilePath = strings.Replace(relFilePath, include, replacement, 1) - } - - if err := ta.addTarFile(filePath, relFilePath); err != nil { - logrus.Errorf("Can't add file %s to tar: %s", filePath, err) - // if pipe is broken, stop writing tar stream to it - if err == io.ErrClosedPipe { - return err - } - } - return nil - }) - } - }() - - return pipeReader, nil -} - -// Unpack unpacks the decompressedArchive to dest with options. -func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error { - tr := tar.NewReader(decompressedArchive) - trBuf := pools.BufioReader32KPool.Get(nil) - defer pools.BufioReader32KPool.Put(trBuf) - - var dirs []*tar.Header - idMapping := idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps) - rootIDs := idMapping.RootPair() - whiteoutConverter := getWhiteoutConverter(options.WhiteoutFormat, options.InUserNS) - - // Iterate through the files in the archive. -loop: - for { - hdr, err := tr.Next() - if err == io.EOF { - // end of tar archive - break - } - if err != nil { - return err - } - - // ignore XGlobalHeader early to avoid creating parent directories for them - if hdr.Typeflag == tar.TypeXGlobalHeader { - logrus.Debugf("PAX Global Extended Headers found for %s and ignored", hdr.Name) - continue - } - - // Normalize name, for safety and for a simple is-root check - // This keeps "../" as-is, but normalizes "/../" to "/". Or Windows: - // This keeps "..\" as-is, but normalizes "\..\" to "\". - hdr.Name = filepath.Clean(hdr.Name) - - for _, exclude := range options.ExcludePatterns { - if strings.HasPrefix(hdr.Name, exclude) { - continue loop - } - } - - // After calling filepath.Clean(hdr.Name) above, hdr.Name will now be in - // the filepath format for the OS on which the daemon is running. Hence - // the check for a slash-suffix MUST be done in an OS-agnostic way. - if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { - // Not the root directory, ensure that the parent directory exists - parent := filepath.Dir(hdr.Name) - parentPath := filepath.Join(dest, parent) - if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { - err = idtools.MkdirAllAndChownNew(parentPath, 0755, rootIDs) - if err != nil { - return err - } - } - } - - path := filepath.Join(dest, hdr.Name) - rel, err := filepath.Rel(dest, path) - if err != nil { - return err - } - if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { - return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) - } - - // If path exits we almost always just want to remove and replace it - // The only exception is when it is a directory *and* the file from - // the layer is also a directory. Then we want to merge them (i.e. - // just apply the metadata from the layer). - if fi, err := os.Lstat(path); err == nil { - if options.NoOverwriteDirNonDir && fi.IsDir() && hdr.Typeflag != tar.TypeDir { - // If NoOverwriteDirNonDir is true then we cannot replace - // an existing directory with a non-directory from the archive. - return fmt.Errorf("cannot overwrite directory %q with non-directory %q", path, dest) - } - - if options.NoOverwriteDirNonDir && !fi.IsDir() && hdr.Typeflag == tar.TypeDir { - // If NoOverwriteDirNonDir is true then we cannot replace - // an existing non-directory with a directory from the archive. - return fmt.Errorf("cannot overwrite non-directory %q with directory %q", path, dest) - } - - if fi.IsDir() && hdr.Name == "." { - continue - } - - if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { - if err := os.RemoveAll(path); err != nil { - return err - } - } - } - trBuf.Reset(tr) - - if err := remapIDs(idMapping, hdr); err != nil { - return err - } - - if whiteoutConverter != nil { - writeFile, err := whiteoutConverter.ConvertRead(hdr, path) - if err != nil { - return err - } - if !writeFile { - continue - } - } - - if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown, options.ChownOpts, options.InUserNS); err != nil { - return err - } - - // Directory mtimes must be handled at the end to avoid further - // file creation in them to modify the directory mtime - if hdr.Typeflag == tar.TypeDir { - dirs = append(dirs, hdr) - } - } - - for _, hdr := range dirs { - path := filepath.Join(dest, hdr.Name) - - if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { - return err - } - } - return nil -} - -// Untar reads a stream of bytes from `archive`, parses it as a tar archive, -// and unpacks it into the directory at `dest`. -// The archive may be compressed with one of the following algorithms: -// identity (uncompressed), gzip, bzip2, xz. -// FIXME: specify behavior when target path exists vs. doesn't exist. -func Untar(tarArchive io.Reader, dest string, options *TarOptions) error { - return untarHandler(tarArchive, dest, options, true) -} - -// UntarUncompressed reads a stream of bytes from `archive`, parses it as a tar archive, -// and unpacks it into the directory at `dest`. -// The archive must be an uncompressed stream. -func UntarUncompressed(tarArchive io.Reader, dest string, options *TarOptions) error { - return untarHandler(tarArchive, dest, options, false) -} - -// Handler for teasing out the automatic decompression -func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decompress bool) error { - if tarArchive == nil { - return fmt.Errorf("Empty archive") - } - dest = filepath.Clean(dest) - if options == nil { - options = &TarOptions{} - } - if options.ExcludePatterns == nil { - options.ExcludePatterns = []string{} - } - - r := tarArchive - if decompress { - decompressedArchive, err := DecompressStream(tarArchive) - if err != nil { - return err - } - defer decompressedArchive.Close() - r = decompressedArchive - } - - return Unpack(r, dest, options) -} - -// TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. -// If either Tar or Untar fails, TarUntar aborts and returns the error. -func (archiver *Archiver) TarUntar(src, dst string) error { - logrus.Debugf("TarUntar(%s %s)", src, dst) - archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed}) - if err != nil { - return err - } - defer archive.Close() - options := &TarOptions{ - UIDMaps: archiver.IDMapping.UIDs(), - GIDMaps: archiver.IDMapping.GIDs(), - } - return archiver.Untar(archive, dst, options) -} - -// UntarPath untar a file from path to a destination, src is the source tar file path. -func (archiver *Archiver) UntarPath(src, dst string) error { - archive, err := os.Open(src) - if err != nil { - return err - } - defer archive.Close() - options := &TarOptions{ - UIDMaps: archiver.IDMapping.UIDs(), - GIDMaps: archiver.IDMapping.GIDs(), - } - return archiver.Untar(archive, dst, options) -} - -// CopyWithTar creates a tar archive of filesystem path `src`, and -// unpacks it at filesystem path `dst`. -// The archive is streamed directly with fixed buffering and no -// intermediary disk IO. -func (archiver *Archiver) CopyWithTar(src, dst string) error { - srcSt, err := os.Stat(src) - if err != nil { - return err - } - if !srcSt.IsDir() { - return archiver.CopyFileWithTar(src, dst) - } - - // if this Archiver is set up with ID mapping we need to create - // the new destination directory with the remapped root UID/GID pair - // as owner - rootIDs := archiver.IDMapping.RootPair() - // Create dst, copy src's content into it - logrus.Debugf("Creating dest directory: %s", dst) - if err := idtools.MkdirAllAndChownNew(dst, 0755, rootIDs); err != nil { - return err - } - logrus.Debugf("Calling TarUntar(%s, %s)", src, dst) - return archiver.TarUntar(src, dst) -} - -// CopyFileWithTar emulates the behavior of the 'cp' command-line -// for a single file. It copies a regular file from path `src` to -// path `dst`, and preserves all its metadata. -func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { - logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst) - srcSt, err := os.Stat(src) - if err != nil { - return err - } - - if srcSt.IsDir() { - return fmt.Errorf("Can't copy a directory") - } - - // Clean up the trailing slash. This must be done in an operating - // system specific manner. - if dst[len(dst)-1] == os.PathSeparator { - dst = filepath.Join(dst, filepath.Base(src)) - } - // Create the holding directory if necessary - if err := system.MkdirAll(filepath.Dir(dst), 0700); err != nil { - return err - } - - r, w := io.Pipe() - errC := make(chan error, 1) - - go func() { - defer close(errC) - - errC <- func() error { - defer w.Close() - - srcF, err := os.Open(src) - if err != nil { - return err - } - defer srcF.Close() - - hdr, err := tar.FileInfoHeader(srcSt, "") - if err != nil { - return err - } - hdr.Format = tar.FormatPAX - hdr.ModTime = hdr.ModTime.Truncate(time.Second) - hdr.AccessTime = time.Time{} - hdr.ChangeTime = time.Time{} - hdr.Name = filepath.Base(dst) - hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) - - if err := remapIDs(archiver.IDMapping, hdr); err != nil { - return err - } - - tw := tar.NewWriter(w) - defer tw.Close() - if err := tw.WriteHeader(hdr); err != nil { - return err - } - if _, err := io.Copy(tw, srcF); err != nil { - return err - } - return nil - }() - }() - defer func() { - if er := <-errC; err == nil && er != nil { - err = er - } - }() - - err = archiver.Untar(r, filepath.Dir(dst), nil) - if err != nil { - r.CloseWithError(err) - } - return err -} - -// IdentityMapping returns the IdentityMapping of the archiver. -func (archiver *Archiver) IdentityMapping() *idtools.IdentityMapping { - return archiver.IDMapping -} - -func remapIDs(idMapping *idtools.IdentityMapping, hdr *tar.Header) error { - ids, err := idMapping.ToHost(idtools.Identity{UID: hdr.Uid, GID: hdr.Gid}) - hdr.Uid, hdr.Gid = ids.UID, ids.GID - return err -} - -// cmdStream executes a command, and returns its stdout as a stream. -// If the command fails to run or doesn't complete successfully, an error -// will be returned, including anything written on stderr. -func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) { - cmd.Stdin = input - pipeR, pipeW := io.Pipe() - cmd.Stdout = pipeW - var errBuf bytes.Buffer - cmd.Stderr = &errBuf - - // Run the command and return the pipe - if err := cmd.Start(); err != nil { - return nil, err - } - - // Ensure the command has exited before we clean anything up - done := make(chan struct{}) - - // Copy stdout to the returned pipe - go func() { - if err := cmd.Wait(); err != nil { - pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errBuf.String())) - } else { - pipeW.Close() - } - close(done) - }() - - return ioutils.NewReadCloserWrapper(pipeR, func() error { - // Close pipeR, and then wait for the command to complete before returning. We have to close pipeR first, as - // cmd.Wait waits for any non-file stdout/stderr/stdin to close. - err := pipeR.Close() - <-done - return err - }), nil -} - -// NewTempArchive reads the content of src into a temporary file, and returns the contents -// of that file as an archive. The archive can only be read once - as soon as reading completes, -// the file will be deleted. -func NewTempArchive(src io.Reader, dir string) (*TempArchive, error) { - f, err := ioutil.TempFile(dir, "") - if err != nil { - return nil, err - } - if _, err := io.Copy(f, src); err != nil { - return nil, err - } - if _, err := f.Seek(0, 0); err != nil { - return nil, err - } - st, err := f.Stat() - if err != nil { - return nil, err - } - size := st.Size() - return &TempArchive{File: f, Size: size}, nil -} - -// TempArchive is a temporary archive. The archive can only be read once - as soon as reading completes, -// the file will be deleted. -type TempArchive struct { - *os.File - Size int64 // Pre-computed from Stat().Size() as a convenience - read int64 - closed bool -} - -// Close closes the underlying file if it's still open, or does a no-op -// to allow callers to try to close the TempArchive multiple times safely. -func (archive *TempArchive) Close() error { - if archive.closed { - return nil - } - - archive.closed = true - - return archive.File.Close() -} - -func (archive *TempArchive) Read(data []byte) (int, error) { - n, err := archive.File.Read(data) - archive.read += int64(n) - if err != nil || archive.read == archive.Size { - archive.Close() - os.Remove(archive.File.Name()) - } - return n, err -} diff --git a/vendor/github.com/docker/docker/pkg/archive/archive_linux.go b/vendor/github.com/docker/docker/pkg/archive/archive_linux.go deleted file mode 100644 index f7888e65..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_linux.go +++ /dev/null @@ -1,264 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strings" - "syscall" - - "github.com/containerd/continuity/fs" - "github.com/docker/docker/pkg/system" - "github.com/moby/sys/mount" - "github.com/pkg/errors" - "golang.org/x/sys/unix" -) - -func getWhiteoutConverter(format WhiteoutFormat, inUserNS bool) tarWhiteoutConverter { - if format == OverlayWhiteoutFormat { - return overlayWhiteoutConverter{inUserNS: inUserNS} - } - return nil -} - -type overlayWhiteoutConverter struct { - inUserNS bool -} - -func (overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi os.FileInfo) (wo *tar.Header, err error) { - // convert whiteouts to AUFS format - if fi.Mode()&os.ModeCharDevice != 0 && hdr.Devmajor == 0 && hdr.Devminor == 0 { - // we just rename the file and make it normal - dir, filename := filepath.Split(hdr.Name) - hdr.Name = filepath.Join(dir, WhiteoutPrefix+filename) - hdr.Mode = 0600 - hdr.Typeflag = tar.TypeReg - hdr.Size = 0 - } - - if fi.Mode()&os.ModeDir != 0 { - // convert opaque dirs to AUFS format by writing an empty file with the prefix - opaque, err := system.Lgetxattr(path, "trusted.overlay.opaque") - if err != nil { - return nil, err - } - if len(opaque) == 1 && opaque[0] == 'y' { - if hdr.Xattrs != nil { - delete(hdr.Xattrs, "trusted.overlay.opaque") - } - - // create a header for the whiteout file - // it should inherit some properties from the parent, but be a regular file - wo = &tar.Header{ - Typeflag: tar.TypeReg, - Mode: hdr.Mode & int64(os.ModePerm), - Name: filepath.Join(hdr.Name, WhiteoutOpaqueDir), - Size: 0, - Uid: hdr.Uid, - Uname: hdr.Uname, - Gid: hdr.Gid, - Gname: hdr.Gname, - AccessTime: hdr.AccessTime, - ChangeTime: hdr.ChangeTime, - } - } - } - - return -} - -func (c overlayWhiteoutConverter) ConvertRead(hdr *tar.Header, path string) (bool, error) { - base := filepath.Base(path) - dir := filepath.Dir(path) - - // if a directory is marked as opaque by the AUFS special file, we need to translate that to overlay - if base == WhiteoutOpaqueDir { - err := unix.Setxattr(dir, "trusted.overlay.opaque", []byte{'y'}, 0) - if err != nil { - if c.inUserNS { - if err = replaceDirWithOverlayOpaque(dir); err != nil { - return false, errors.Wrapf(err, "replaceDirWithOverlayOpaque(%q) failed", dir) - } - } else { - return false, errors.Wrapf(err, "setxattr(%q, trusted.overlay.opaque=y)", dir) - } - } - // don't write the file itself - return false, err - } - - // if a file was deleted and we are using overlay, we need to create a character device - if strings.HasPrefix(base, WhiteoutPrefix) { - originalBase := base[len(WhiteoutPrefix):] - originalPath := filepath.Join(dir, originalBase) - - if err := unix.Mknod(originalPath, unix.S_IFCHR, 0); err != nil { - if c.inUserNS { - // Ubuntu and a few distros support overlayfs in userns. - // - // Although we can't call mknod directly in userns (at least on bionic kernel 4.15), - // we can still create 0,0 char device using mknodChar0Overlay(). - // - // NOTE: we don't need this hack for the containerd snapshotter+unpack model. - if err := mknodChar0Overlay(originalPath); err != nil { - return false, errors.Wrapf(err, "failed to mknodChar0UserNS(%q)", originalPath) - } - } else { - return false, errors.Wrapf(err, "failed to mknod(%q, S_IFCHR, 0)", originalPath) - } - } - if err := os.Chown(originalPath, hdr.Uid, hdr.Gid); err != nil { - return false, err - } - - // don't write the file itself - return false, nil - } - - return true, nil -} - -// mknodChar0Overlay creates 0,0 char device by mounting overlayfs and unlinking. -// This function can be used for creating 0,0 char device in userns on Ubuntu. -// -// Steps: -// * Mkdir lower,upper,merged,work -// * Create lower/dummy -// * Mount overlayfs -// * Unlink merged/dummy -// * Unmount overlayfs -// * Make sure a 0,0 char device is created as upper/dummy -// * Rename upper/dummy to cleansedOriginalPath -func mknodChar0Overlay(cleansedOriginalPath string) error { - dir := filepath.Dir(cleansedOriginalPath) - tmp, err := ioutil.TempDir(dir, "mc0o") - if err != nil { - return errors.Wrapf(err, "failed to create a tmp directory under %s", dir) - } - defer os.RemoveAll(tmp) - lower := filepath.Join(tmp, "l") - upper := filepath.Join(tmp, "u") - work := filepath.Join(tmp, "w") - merged := filepath.Join(tmp, "m") - for _, s := range []string{lower, upper, work, merged} { - if err := os.MkdirAll(s, 0700); err != nil { - return errors.Wrapf(err, "failed to mkdir %s", s) - } - } - dummyBase := "d" - lowerDummy := filepath.Join(lower, dummyBase) - if err := ioutil.WriteFile(lowerDummy, []byte{}, 0600); err != nil { - return errors.Wrapf(err, "failed to create a dummy lower file %s", lowerDummy) - } - // lowerdir needs ":" to be escaped: https://github.com/moby/moby/issues/40939#issuecomment-627098286 - lowerEscaped := strings.ReplaceAll(lower, ":", "\\:") - mOpts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerEscaped, upper, work) - if err := mount.Mount("overlay", merged, "overlay", mOpts); err != nil { - return err - } - mergedDummy := filepath.Join(merged, dummyBase) - if err := os.Remove(mergedDummy); err != nil { - syscall.Unmount(merged, 0) - return errors.Wrapf(err, "failed to unlink %s", mergedDummy) - } - if err := syscall.Unmount(merged, 0); err != nil { - return errors.Wrapf(err, "failed to unmount %s", merged) - } - upperDummy := filepath.Join(upper, dummyBase) - if err := isChar0(upperDummy); err != nil { - return err - } - if err := os.Rename(upperDummy, cleansedOriginalPath); err != nil { - return errors.Wrapf(err, "failed to rename %s to %s", upperDummy, cleansedOriginalPath) - } - return nil -} - -func isChar0(path string) error { - osStat, err := os.Stat(path) - if err != nil { - return errors.Wrapf(err, "failed to stat %s", path) - } - st, ok := osStat.Sys().(*syscall.Stat_t) - if !ok { - return errors.Errorf("got unsupported stat for %s", path) - } - if os.FileMode(st.Mode)&syscall.S_IFMT != syscall.S_IFCHR { - return errors.Errorf("%s is not a character device, got mode=%d", path, st.Mode) - } - if st.Rdev != 0 { - return errors.Errorf("%s is not a 0,0 character device, got Rdev=%d", path, st.Rdev) - } - return nil -} - -// replaceDirWithOverlayOpaque replaces path with a new directory with trusted.overlay.opaque -// xattr. The contents of the directory are preserved. -func replaceDirWithOverlayOpaque(path string) error { - if path == "/" { - return errors.New("replaceDirWithOverlayOpaque: path must not be \"/\"") - } - dir := filepath.Dir(path) - tmp, err := ioutil.TempDir(dir, "rdwoo") - if err != nil { - return errors.Wrapf(err, "failed to create a tmp directory under %s", dir) - } - defer os.RemoveAll(tmp) - // newPath is a new empty directory crafted with trusted.overlay.opaque xattr. - // we copy the content of path into newPath, remove path, and rename newPath to path. - newPath, err := createDirWithOverlayOpaque(tmp) - if err != nil { - return errors.Wrapf(err, "createDirWithOverlayOpaque(%q) failed", tmp) - } - if err := fs.CopyDir(newPath, path); err != nil { - return errors.Wrapf(err, "CopyDir(%q, %q) failed", newPath, path) - } - if err := os.RemoveAll(path); err != nil { - return err - } - return os.Rename(newPath, path) -} - -// createDirWithOverlayOpaque creates a directory with trusted.overlay.opaque xattr, -// without calling setxattr, so as to allow creating opaque dir in userns on Ubuntu. -func createDirWithOverlayOpaque(tmp string) (string, error) { - lower := filepath.Join(tmp, "l") - upper := filepath.Join(tmp, "u") - work := filepath.Join(tmp, "w") - merged := filepath.Join(tmp, "m") - for _, s := range []string{lower, upper, work, merged} { - if err := os.MkdirAll(s, 0700); err != nil { - return "", errors.Wrapf(err, "failed to mkdir %s", s) - } - } - dummyBase := "d" - lowerDummy := filepath.Join(lower, dummyBase) - if err := os.MkdirAll(lowerDummy, 0700); err != nil { - return "", errors.Wrapf(err, "failed to create a dummy lower directory %s", lowerDummy) - } - // lowerdir needs ":" to be escaped: https://github.com/moby/moby/issues/40939#issuecomment-627098286 - lowerEscaped := strings.ReplaceAll(lower, ":", "\\:") - mOpts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerEscaped, upper, work) - if err := mount.Mount("overlay", merged, "overlay", mOpts); err != nil { - return "", err - } - mergedDummy := filepath.Join(merged, dummyBase) - if err := os.Remove(mergedDummy); err != nil { - syscall.Unmount(merged, 0) - return "", errors.Wrapf(err, "failed to rmdir %s", mergedDummy) - } - // upperDummy becomes a 0,0-char device file here - if err := os.Mkdir(mergedDummy, 0700); err != nil { - syscall.Unmount(merged, 0) - return "", errors.Wrapf(err, "failed to mkdir %s", mergedDummy) - } - // upperDummy becomes a directory with trusted.overlay.opaque xattr - // (but can't be verified in userns) - if err := syscall.Unmount(merged, 0); err != nil { - return "", errors.Wrapf(err, "failed to unmount %s", merged) - } - upperDummy := filepath.Join(upper, dummyBase) - return upperDummy, nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/archive_other.go b/vendor/github.com/docker/docker/pkg/archive/archive_other.go deleted file mode 100644 index 65a73354..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_other.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !linux - -package archive // import "github.com/docker/docker/pkg/archive" - -func getWhiteoutConverter(format WhiteoutFormat, inUserNS bool) tarWhiteoutConverter { - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/archive_unix.go b/vendor/github.com/docker/docker/pkg/archive/archive_unix.go deleted file mode 100644 index 0b92bb0f..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_unix.go +++ /dev/null @@ -1,115 +0,0 @@ -// +build !windows - -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "errors" - "os" - "path/filepath" - "strings" - "syscall" - - "github.com/containerd/containerd/sys" - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/system" - "golang.org/x/sys/unix" -) - -// fixVolumePathPrefix does platform specific processing to ensure that if -// the path being passed in is not in a volume path format, convert it to one. -func fixVolumePathPrefix(srcPath string) string { - return srcPath -} - -// getWalkRoot calculates the root path when performing a TarWithOptions. -// We use a separate function as this is platform specific. On Linux, we -// can't use filepath.Join(srcPath,include) because this will clean away -// a trailing "." or "/" which may be important. -func getWalkRoot(srcPath string, include string) string { - return strings.TrimSuffix(srcPath, string(filepath.Separator)) + string(filepath.Separator) + include -} - -// CanonicalTarNameForPath returns platform-specific filepath -// to canonical posix-style path for tar archival. p is relative -// path. -func CanonicalTarNameForPath(p string) string { - return p // already unix-style -} - -// chmodTarEntry is used to adjust the file permissions used in tar header based -// on the platform the archival is done. - -func chmodTarEntry(perm os.FileMode) os.FileMode { - return perm // noop for unix as golang APIs provide perm bits correctly -} - -func setHeaderForSpecialDevice(hdr *tar.Header, name string, stat interface{}) (err error) { - s, ok := stat.(*syscall.Stat_t) - - if ok { - // Currently go does not fill in the major/minors - if s.Mode&unix.S_IFBLK != 0 || - s.Mode&unix.S_IFCHR != 0 { - hdr.Devmajor = int64(unix.Major(uint64(s.Rdev))) // nolint: unconvert - hdr.Devminor = int64(unix.Minor(uint64(s.Rdev))) // nolint: unconvert - } - } - - return -} - -func getInodeFromStat(stat interface{}) (inode uint64, err error) { - s, ok := stat.(*syscall.Stat_t) - - if ok { - inode = s.Ino - } - - return -} - -func getFileUIDGID(stat interface{}) (idtools.Identity, error) { - s, ok := stat.(*syscall.Stat_t) - - if !ok { - return idtools.Identity{}, errors.New("cannot convert stat value to syscall.Stat_t") - } - return idtools.Identity{UID: int(s.Uid), GID: int(s.Gid)}, nil -} - -// handleTarTypeBlockCharFifo is an OS-specific helper function used by -// createTarFile to handle the following types of header: Block; Char; Fifo -func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { - mode := uint32(hdr.Mode & 07777) - switch hdr.Typeflag { - case tar.TypeBlock: - mode |= unix.S_IFBLK - case tar.TypeChar: - mode |= unix.S_IFCHR - case tar.TypeFifo: - mode |= unix.S_IFIFO - } - - err := system.Mknod(path, mode, int(system.Mkdev(hdr.Devmajor, hdr.Devminor))) - if errors.Is(err, syscall.EPERM) && sys.RunningInUserNS() { - // In most cases, cannot create a device if running in user namespace - err = nil - } - return err -} - -func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { - if hdr.Typeflag == tar.TypeLink { - if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { - if err := os.Chmod(path, hdrInfo.Mode()); err != nil { - return err - } - } - } else if hdr.Typeflag != tar.TypeSymlink { - if err := os.Chmod(path, hdrInfo.Mode()); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/archive_windows.go b/vendor/github.com/docker/docker/pkg/archive/archive_windows.go deleted file mode 100644 index 7260174b..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_windows.go +++ /dev/null @@ -1,67 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "os" - "path/filepath" - - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/longpath" -) - -// fixVolumePathPrefix does platform specific processing to ensure that if -// the path being passed in is not in a volume path format, convert it to one. -func fixVolumePathPrefix(srcPath string) string { - return longpath.AddPrefix(srcPath) -} - -// getWalkRoot calculates the root path when performing a TarWithOptions. -// We use a separate function as this is platform specific. -func getWalkRoot(srcPath string, include string) string { - return filepath.Join(srcPath, include) -} - -// CanonicalTarNameForPath returns platform-specific filepath -// to canonical posix-style path for tar archival. p is relative -// path. -func CanonicalTarNameForPath(p string) string { - return filepath.ToSlash(p) -} - -// chmodTarEntry is used to adjust the file permissions used in tar header based -// on the platform the archival is done. -func chmodTarEntry(perm os.FileMode) os.FileMode { - // perm &= 0755 // this 0-ed out tar flags (like link, regular file, directory marker etc.) - permPart := perm & os.ModePerm - noPermPart := perm &^ os.ModePerm - // Add the x bit: make everything +x from windows - permPart |= 0111 - permPart &= 0755 - - return noPermPart | permPart -} - -func setHeaderForSpecialDevice(hdr *tar.Header, name string, stat interface{}) (err error) { - // do nothing. no notion of Rdev, Nlink in stat on Windows - return -} - -func getInodeFromStat(stat interface{}) (inode uint64, err error) { - // do nothing. no notion of Inode in stat on Windows - return -} - -// handleTarTypeBlockCharFifo is an OS-specific helper function used by -// createTarFile to handle the following types of header: Block; Char; Fifo -func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { - return nil -} - -func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { - return nil -} - -func getFileUIDGID(stat interface{}) (idtools.Identity, error) { - // no notion of file ownership mapping yet on Windows - return idtools.Identity{UID: 0, GID: 0}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/changes.go b/vendor/github.com/docker/docker/pkg/archive/changes.go deleted file mode 100644 index aedb91b0..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes.go +++ /dev/null @@ -1,445 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "sort" - "strings" - "syscall" - "time" - - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/pools" - "github.com/docker/docker/pkg/system" - "github.com/sirupsen/logrus" -) - -// ChangeType represents the change type. -type ChangeType int - -const ( - // ChangeModify represents the modify operation. - ChangeModify = iota - // ChangeAdd represents the add operation. - ChangeAdd - // ChangeDelete represents the delete operation. - ChangeDelete -) - -func (c ChangeType) String() string { - switch c { - case ChangeModify: - return "C" - case ChangeAdd: - return "A" - case ChangeDelete: - return "D" - } - return "" -} - -// Change represents a change, it wraps the change type and path. -// It describes changes of the files in the path respect to the -// parent layers. The change could be modify, add, delete. -// This is used for layer diff. -type Change struct { - Path string - Kind ChangeType -} - -func (change *Change) String() string { - return fmt.Sprintf("%s %s", change.Kind, change.Path) -} - -// for sort.Sort -type changesByPath []Change - -func (c changesByPath) Less(i, j int) bool { return c[i].Path < c[j].Path } -func (c changesByPath) Len() int { return len(c) } -func (c changesByPath) Swap(i, j int) { c[j], c[i] = c[i], c[j] } - -// Gnu tar doesn't have sub-second mtime precision. The go tar -// writer (1.10+) does when using PAX format, but we round times to seconds -// to ensure archives have the same hashes for backwards compatibility. -// See https://github.com/moby/moby/pull/35739/commits/fb170206ba12752214630b269a40ac7be6115ed4. -// -// Non-sub-second is problematic when we apply changes via tar -// files. We handle this by comparing for exact times, *or* same -// second count and either a or b having exactly 0 nanoseconds -func sameFsTime(a, b time.Time) bool { - return a.Equal(b) || - (a.Unix() == b.Unix() && - (a.Nanosecond() == 0 || b.Nanosecond() == 0)) -} - -func sameFsTimeSpec(a, b syscall.Timespec) bool { - return a.Sec == b.Sec && - (a.Nsec == b.Nsec || a.Nsec == 0 || b.Nsec == 0) -} - -// Changes walks the path rw and determines changes for the files in the path, -// with respect to the parent layers -func Changes(layers []string, rw string) ([]Change, error) { - return changes(layers, rw, aufsDeletedFile, aufsMetadataSkip) -} - -func aufsMetadataSkip(path string) (skip bool, err error) { - skip, err = filepath.Match(string(os.PathSeparator)+WhiteoutMetaPrefix+"*", path) - if err != nil { - skip = true - } - return -} - -func aufsDeletedFile(root, path string, fi os.FileInfo) (string, error) { - f := filepath.Base(path) - - // If there is a whiteout, then the file was removed - if strings.HasPrefix(f, WhiteoutPrefix) { - originalFile := f[len(WhiteoutPrefix):] - return filepath.Join(filepath.Dir(path), originalFile), nil - } - - return "", nil -} - -type skipChange func(string) (bool, error) -type deleteChange func(string, string, os.FileInfo) (string, error) - -func changes(layers []string, rw string, dc deleteChange, sc skipChange) ([]Change, error) { - var ( - changes []Change - changedDirs = make(map[string]struct{}) - ) - - err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error { - if err != nil { - return err - } - - // Rebase path - path, err = filepath.Rel(rw, path) - if err != nil { - return err - } - - // As this runs on the daemon side, file paths are OS specific. - path = filepath.Join(string(os.PathSeparator), path) - - // Skip root - if path == string(os.PathSeparator) { - return nil - } - - if sc != nil { - if skip, err := sc(path); skip { - return err - } - } - - change := Change{ - Path: path, - } - - deletedFile, err := dc(rw, path, f) - if err != nil { - return err - } - - // Find out what kind of modification happened - if deletedFile != "" { - change.Path = deletedFile - change.Kind = ChangeDelete - } else { - // Otherwise, the file was added - change.Kind = ChangeAdd - - // ...Unless it already existed in a top layer, in which case, it's a modification - for _, layer := range layers { - stat, err := os.Stat(filepath.Join(layer, path)) - if err != nil && !os.IsNotExist(err) { - return err - } - if err == nil { - // The file existed in the top layer, so that's a modification - - // However, if it's a directory, maybe it wasn't actually modified. - // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar - if stat.IsDir() && f.IsDir() { - if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) { - // Both directories are the same, don't record the change - return nil - } - } - change.Kind = ChangeModify - break - } - } - } - - // If /foo/bar/file.txt is modified, then /foo/bar must be part of the changed files. - // This block is here to ensure the change is recorded even if the - // modify time, mode and size of the parent directory in the rw and ro layers are all equal. - // Check https://github.com/docker/docker/pull/13590 for details. - if f.IsDir() { - changedDirs[path] = struct{}{} - } - if change.Kind == ChangeAdd || change.Kind == ChangeDelete { - parent := filepath.Dir(path) - if _, ok := changedDirs[parent]; !ok && parent != "/" { - changes = append(changes, Change{Path: parent, Kind: ChangeModify}) - changedDirs[parent] = struct{}{} - } - } - - // Record change - changes = append(changes, change) - return nil - }) - if err != nil && !os.IsNotExist(err) { - return nil, err - } - return changes, nil -} - -// FileInfo describes the information of a file. -type FileInfo struct { - parent *FileInfo - name string - stat *system.StatT - children map[string]*FileInfo - capability []byte - added bool -} - -// LookUp looks up the file information of a file. -func (info *FileInfo) LookUp(path string) *FileInfo { - // As this runs on the daemon side, file paths are OS specific. - parent := info - if path == string(os.PathSeparator) { - return info - } - - pathElements := strings.Split(path, string(os.PathSeparator)) - for _, elem := range pathElements { - if elem != "" { - child := parent.children[elem] - if child == nil { - return nil - } - parent = child - } - } - return parent -} - -func (info *FileInfo) path() string { - if info.parent == nil { - // As this runs on the daemon side, file paths are OS specific. - return string(os.PathSeparator) - } - return filepath.Join(info.parent.path(), info.name) -} - -func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) { - - sizeAtEntry := len(*changes) - - if oldInfo == nil { - // add - change := Change{ - Path: info.path(), - Kind: ChangeAdd, - } - *changes = append(*changes, change) - info.added = true - } - - // We make a copy so we can modify it to detect additions - // also, we only recurse on the old dir if the new info is a directory - // otherwise any previous delete/change is considered recursive - oldChildren := make(map[string]*FileInfo) - if oldInfo != nil && info.isDir() { - for k, v := range oldInfo.children { - oldChildren[k] = v - } - } - - for name, newChild := range info.children { - oldChild := oldChildren[name] - if oldChild != nil { - // change? - oldStat := oldChild.stat - newStat := newChild.stat - // Note: We can't compare inode or ctime or blocksize here, because these change - // when copying a file into a container. However, that is not generally a problem - // because any content change will change mtime, and any status change should - // be visible when actually comparing the stat fields. The only time this - // breaks down is if some code intentionally hides a change by setting - // back mtime - if statDifferent(oldStat, newStat) || - !bytes.Equal(oldChild.capability, newChild.capability) { - change := Change{ - Path: newChild.path(), - Kind: ChangeModify, - } - *changes = append(*changes, change) - newChild.added = true - } - - // Remove from copy so we can detect deletions - delete(oldChildren, name) - } - - newChild.addChanges(oldChild, changes) - } - for _, oldChild := range oldChildren { - // delete - change := Change{ - Path: oldChild.path(), - Kind: ChangeDelete, - } - *changes = append(*changes, change) - } - - // If there were changes inside this directory, we need to add it, even if the directory - // itself wasn't changed. This is needed to properly save and restore filesystem permissions. - // As this runs on the daemon side, file paths are OS specific. - if len(*changes) > sizeAtEntry && info.isDir() && !info.added && info.path() != string(os.PathSeparator) { - change := Change{ - Path: info.path(), - Kind: ChangeModify, - } - // Let's insert the directory entry before the recently added entries located inside this dir - *changes = append(*changes, change) // just to resize the slice, will be overwritten - copy((*changes)[sizeAtEntry+1:], (*changes)[sizeAtEntry:]) - (*changes)[sizeAtEntry] = change - } - -} - -// Changes add changes to file information. -func (info *FileInfo) Changes(oldInfo *FileInfo) []Change { - var changes []Change - - info.addChanges(oldInfo, &changes) - - return changes -} - -func newRootFileInfo() *FileInfo { - // As this runs on the daemon side, file paths are OS specific. - root := &FileInfo{ - name: string(os.PathSeparator), - children: make(map[string]*FileInfo), - } - return root -} - -// ChangesDirs compares two directories and generates an array of Change objects describing the changes. -// If oldDir is "", then all files in newDir will be Add-Changes. -func ChangesDirs(newDir, oldDir string) ([]Change, error) { - var ( - oldRoot, newRoot *FileInfo - ) - if oldDir == "" { - emptyDir, err := ioutil.TempDir("", "empty") - if err != nil { - return nil, err - } - defer os.Remove(emptyDir) - oldDir = emptyDir - } - oldRoot, newRoot, err := collectFileInfoForChanges(oldDir, newDir) - if err != nil { - return nil, err - } - - return newRoot.Changes(oldRoot), nil -} - -// ChangesSize calculates the size in bytes of the provided changes, based on newDir. -func ChangesSize(newDir string, changes []Change) int64 { - var ( - size int64 - sf = make(map[uint64]struct{}) - ) - for _, change := range changes { - if change.Kind == ChangeModify || change.Kind == ChangeAdd { - file := filepath.Join(newDir, change.Path) - fileInfo, err := os.Lstat(file) - if err != nil { - logrus.Errorf("Can not stat %q: %s", file, err) - continue - } - - if fileInfo != nil && !fileInfo.IsDir() { - if hasHardlinks(fileInfo) { - inode := getIno(fileInfo) - if _, ok := sf[inode]; !ok { - size += fileInfo.Size() - sf[inode] = struct{}{} - } - } else { - size += fileInfo.Size() - } - } - } - } - return size -} - -// ExportChanges produces an Archive from the provided changes, relative to dir. -func ExportChanges(dir string, changes []Change, uidMaps, gidMaps []idtools.IDMap) (io.ReadCloser, error) { - reader, writer := io.Pipe() - go func() { - ta := newTarAppender(idtools.NewIDMappingsFromMaps(uidMaps, gidMaps), writer, nil) - - // this buffer is needed for the duration of this piped stream - defer pools.BufioWriter32KPool.Put(ta.Buffer) - - sort.Sort(changesByPath(changes)) - - // In general we log errors here but ignore them because - // during e.g. a diff operation the container can continue - // mutating the filesystem and we can see transient errors - // from this - for _, change := range changes { - if change.Kind == ChangeDelete { - whiteOutDir := filepath.Dir(change.Path) - whiteOutBase := filepath.Base(change.Path) - whiteOut := filepath.Join(whiteOutDir, WhiteoutPrefix+whiteOutBase) - timestamp := time.Now() - hdr := &tar.Header{ - Name: whiteOut[1:], - Size: 0, - ModTime: timestamp, - AccessTime: timestamp, - ChangeTime: timestamp, - } - if err := ta.TarWriter.WriteHeader(hdr); err != nil { - logrus.Debugf("Can't write whiteout header: %s", err) - } - } else { - path := filepath.Join(dir, change.Path) - if err := ta.addTarFile(path, change.Path[1:]); err != nil { - logrus.Debugf("Can't add file %s to tar: %s", path, err) - } - } - } - - // Make sure to check the error on Close. - if err := ta.TarWriter.Close(); err != nil { - logrus.Debugf("Can't close layer: %s", err) - } - if err := writer.Close(); err != nil { - logrus.Debugf("failed close Changes writer: %s", err) - } - }() - return reader, nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/changes_linux.go b/vendor/github.com/docker/docker/pkg/archive/changes_linux.go deleted file mode 100644 index f8792b3d..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes_linux.go +++ /dev/null @@ -1,286 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "bytes" - "fmt" - "os" - "path/filepath" - "sort" - "syscall" - "unsafe" - - "github.com/docker/docker/pkg/system" - "golang.org/x/sys/unix" -) - -// walker is used to implement collectFileInfoForChanges on linux. Where this -// method in general returns the entire contents of two directory trees, we -// optimize some FS calls out on linux. In particular, we take advantage of the -// fact that getdents(2) returns the inode of each file in the directory being -// walked, which, when walking two trees in parallel to generate a list of -// changes, can be used to prune subtrees without ever having to lstat(2) them -// directly. Eliminating stat calls in this way can save up to seconds on large -// images. -type walker struct { - dir1 string - dir2 string - root1 *FileInfo - root2 *FileInfo -} - -// collectFileInfoForChanges returns a complete representation of the trees -// rooted at dir1 and dir2, with one important exception: any subtree or -// leaf where the inode and device numbers are an exact match between dir1 -// and dir2 will be pruned from the results. This method is *only* to be used -// to generating a list of changes between the two directories, as it does not -// reflect the full contents. -func collectFileInfoForChanges(dir1, dir2 string) (*FileInfo, *FileInfo, error) { - w := &walker{ - dir1: dir1, - dir2: dir2, - root1: newRootFileInfo(), - root2: newRootFileInfo(), - } - - i1, err := os.Lstat(w.dir1) - if err != nil { - return nil, nil, err - } - i2, err := os.Lstat(w.dir2) - if err != nil { - return nil, nil, err - } - - if err := w.walk("/", i1, i2); err != nil { - return nil, nil, err - } - - return w.root1, w.root2, nil -} - -// Given a FileInfo, its path info, and a reference to the root of the tree -// being constructed, register this file with the tree. -func walkchunk(path string, fi os.FileInfo, dir string, root *FileInfo) error { - if fi == nil { - return nil - } - parent := root.LookUp(filepath.Dir(path)) - if parent == nil { - return fmt.Errorf("walkchunk: Unexpectedly no parent for %s", path) - } - info := &FileInfo{ - name: filepath.Base(path), - children: make(map[string]*FileInfo), - parent: parent, - } - cpath := filepath.Join(dir, path) - stat, err := system.FromStatT(fi.Sys().(*syscall.Stat_t)) - if err != nil { - return err - } - info.stat = stat - info.capability, _ = system.Lgetxattr(cpath, "security.capability") // lgetxattr(2): fs access - parent.children[info.name] = info - return nil -} - -// Walk a subtree rooted at the same path in both trees being iterated. For -// example, /docker/overlay/1234/a/b/c/d and /docker/overlay/8888/a/b/c/d -func (w *walker) walk(path string, i1, i2 os.FileInfo) (err error) { - // Register these nodes with the return trees, unless we're still at the - // (already-created) roots: - if path != "/" { - if err := walkchunk(path, i1, w.dir1, w.root1); err != nil { - return err - } - if err := walkchunk(path, i2, w.dir2, w.root2); err != nil { - return err - } - } - - is1Dir := i1 != nil && i1.IsDir() - is2Dir := i2 != nil && i2.IsDir() - - sameDevice := false - if i1 != nil && i2 != nil { - si1 := i1.Sys().(*syscall.Stat_t) - si2 := i2.Sys().(*syscall.Stat_t) - if si1.Dev == si2.Dev { - sameDevice = true - } - } - - // If these files are both non-existent, or leaves (non-dirs), we are done. - if !is1Dir && !is2Dir { - return nil - } - - // Fetch the names of all the files contained in both directories being walked: - var names1, names2 []nameIno - if is1Dir { - names1, err = readdirnames(filepath.Join(w.dir1, path)) // getdents(2): fs access - if err != nil { - return err - } - } - if is2Dir { - names2, err = readdirnames(filepath.Join(w.dir2, path)) // getdents(2): fs access - if err != nil { - return err - } - } - - // We have lists of the files contained in both parallel directories, sorted - // in the same order. Walk them in parallel, generating a unique merged list - // of all items present in either or both directories. - var names []string - ix1 := 0 - ix2 := 0 - - for { - if ix1 >= len(names1) { - break - } - if ix2 >= len(names2) { - break - } - - ni1 := names1[ix1] - ni2 := names2[ix2] - - switch bytes.Compare([]byte(ni1.name), []byte(ni2.name)) { - case -1: // ni1 < ni2 -- advance ni1 - // we will not encounter ni1 in names2 - names = append(names, ni1.name) - ix1++ - case 0: // ni1 == ni2 - if ni1.ino != ni2.ino || !sameDevice { - names = append(names, ni1.name) - } - ix1++ - ix2++ - case 1: // ni1 > ni2 -- advance ni2 - // we will not encounter ni2 in names1 - names = append(names, ni2.name) - ix2++ - } - } - for ix1 < len(names1) { - names = append(names, names1[ix1].name) - ix1++ - } - for ix2 < len(names2) { - names = append(names, names2[ix2].name) - ix2++ - } - - // For each of the names present in either or both of the directories being - // iterated, stat the name under each root, and recurse the pair of them: - for _, name := range names { - fname := filepath.Join(path, name) - var cInfo1, cInfo2 os.FileInfo - if is1Dir { - cInfo1, err = os.Lstat(filepath.Join(w.dir1, fname)) // lstat(2): fs access - if err != nil && !os.IsNotExist(err) { - return err - } - } - if is2Dir { - cInfo2, err = os.Lstat(filepath.Join(w.dir2, fname)) // lstat(2): fs access - if err != nil && !os.IsNotExist(err) { - return err - } - } - if err = w.walk(fname, cInfo1, cInfo2); err != nil { - return err - } - } - return nil -} - -// {name,inode} pairs used to support the early-pruning logic of the walker type -type nameIno struct { - name string - ino uint64 -} - -type nameInoSlice []nameIno - -func (s nameInoSlice) Len() int { return len(s) } -func (s nameInoSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s nameInoSlice) Less(i, j int) bool { return s[i].name < s[j].name } - -// readdirnames is a hacked-apart version of the Go stdlib code, exposing inode -// numbers further up the stack when reading directory contents. Unlike -// os.Readdirnames, which returns a list of filenames, this function returns a -// list of {filename,inode} pairs. -func readdirnames(dirname string) (names []nameIno, err error) { - var ( - size = 100 - buf = make([]byte, 4096) - nbuf int - bufp int - nb int - ) - - f, err := os.Open(dirname) - if err != nil { - return nil, err - } - defer f.Close() - - names = make([]nameIno, 0, size) // Empty with room to grow. - for { - // Refill the buffer if necessary - if bufp >= nbuf { - bufp = 0 - nbuf, err = unix.ReadDirent(int(f.Fd()), buf) // getdents on linux - if nbuf < 0 { - nbuf = 0 - } - if err != nil { - return nil, os.NewSyscallError("readdirent", err) - } - if nbuf <= 0 { - break // EOF - } - } - - // Drain the buffer - nb, names = parseDirent(buf[bufp:nbuf], names) - bufp += nb - } - - sl := nameInoSlice(names) - sort.Sort(sl) - return sl, nil -} - -// parseDirent is a minor modification of unix.ParseDirent (linux version) -// which returns {name,inode} pairs instead of just names. -func parseDirent(buf []byte, names []nameIno) (consumed int, newnames []nameIno) { - origlen := len(buf) - for len(buf) > 0 { - dirent := (*unix.Dirent)(unsafe.Pointer(&buf[0])) - buf = buf[dirent.Reclen:] - if dirent.Ino == 0 { // File absent in directory. - continue - } - bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) - var name = string(bytes[0:clen(bytes[:])]) - if name == "." || name == ".." { // Useless names - continue - } - names = append(names, nameIno{name, dirent.Ino}) - } - return origlen - len(buf), names -} - -func clen(n []byte) int { - for i := 0; i < len(n); i++ { - if n[i] == 0 { - return i - } - } - return len(n) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/changes_other.go b/vendor/github.com/docker/docker/pkg/archive/changes_other.go deleted file mode 100644 index ba744741..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes_other.go +++ /dev/null @@ -1,97 +0,0 @@ -// +build !linux - -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "fmt" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/docker/docker/pkg/system" -) - -func collectFileInfoForChanges(oldDir, newDir string) (*FileInfo, *FileInfo, error) { - var ( - oldRoot, newRoot *FileInfo - err1, err2 error - errs = make(chan error, 2) - ) - go func() { - oldRoot, err1 = collectFileInfo(oldDir) - errs <- err1 - }() - go func() { - newRoot, err2 = collectFileInfo(newDir) - errs <- err2 - }() - - // block until both routines have returned - for i := 0; i < 2; i++ { - if err := <-errs; err != nil { - return nil, nil, err - } - } - - return oldRoot, newRoot, nil -} - -func collectFileInfo(sourceDir string) (*FileInfo, error) { - root := newRootFileInfo() - - err := filepath.Walk(sourceDir, func(path string, f os.FileInfo, err error) error { - if err != nil { - return err - } - - // Rebase path - relPath, err := filepath.Rel(sourceDir, path) - if err != nil { - return err - } - - // As this runs on the daemon side, file paths are OS specific. - relPath = filepath.Join(string(os.PathSeparator), relPath) - - // See https://github.com/golang/go/issues/9168 - bug in filepath.Join. - // Temporary workaround. If the returned path starts with two backslashes, - // trim it down to a single backslash. Only relevant on Windows. - if runtime.GOOS == "windows" { - if strings.HasPrefix(relPath, `\\`) { - relPath = relPath[1:] - } - } - - if relPath == string(os.PathSeparator) { - return nil - } - - parent := root.LookUp(filepath.Dir(relPath)) - if parent == nil { - return fmt.Errorf("collectFileInfo: Unexpectedly no parent for %s", relPath) - } - - info := &FileInfo{ - name: filepath.Base(relPath), - children: make(map[string]*FileInfo), - parent: parent, - } - - s, err := system.Lstat(path) - if err != nil { - return err - } - info.stat = s - - info.capability, _ = system.Lgetxattr(path, "security.capability") - - parent.children[info.name] = info - - return nil - }) - if err != nil { - return nil, err - } - return root, nil -} diff --git a/vendor/github.com/docker/docker/pkg/archive/changes_unix.go b/vendor/github.com/docker/docker/pkg/archive/changes_unix.go deleted file mode 100644 index 06217b71..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes_unix.go +++ /dev/null @@ -1,43 +0,0 @@ -// +build !windows - -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "os" - "syscall" - - "github.com/docker/docker/pkg/system" - "golang.org/x/sys/unix" -) - -func statDifferent(oldStat *system.StatT, newStat *system.StatT) bool { - // Don't look at size for dirs, its not a good measure of change - if oldStat.Mode() != newStat.Mode() || - oldStat.UID() != newStat.UID() || - oldStat.GID() != newStat.GID() || - oldStat.Rdev() != newStat.Rdev() || - // Don't look at size or modification time for dirs, its not a good - // measure of change. See https://github.com/moby/moby/issues/9874 - // for a description of the issue with modification time, and - // https://github.com/moby/moby/pull/11422 for the change. - // (Note that in the Windows implementation of this function, - // modification time IS taken as a change). See - // https://github.com/moby/moby/pull/37982 for more information. - (oldStat.Mode()&unix.S_IFDIR != unix.S_IFDIR && - (!sameFsTimeSpec(oldStat.Mtim(), newStat.Mtim()) || (oldStat.Size() != newStat.Size()))) { - return true - } - return false -} - -func (info *FileInfo) isDir() bool { - return info.parent == nil || info.stat.Mode()&unix.S_IFDIR != 0 -} - -func getIno(fi os.FileInfo) uint64 { - return fi.Sys().(*syscall.Stat_t).Ino -} - -func hasHardlinks(fi os.FileInfo) bool { - return fi.Sys().(*syscall.Stat_t).Nlink > 1 -} diff --git a/vendor/github.com/docker/docker/pkg/archive/changes_windows.go b/vendor/github.com/docker/docker/pkg/archive/changes_windows.go deleted file mode 100644 index 9906685e..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes_windows.go +++ /dev/null @@ -1,34 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "os" - - "github.com/docker/docker/pkg/system" -) - -func statDifferent(oldStat *system.StatT, newStat *system.StatT) bool { - // Note there is slight difference between the Linux and Windows - // implementations here. Due to https://github.com/moby/moby/issues/9874, - // and the fix at https://github.com/moby/moby/pull/11422, Linux does not - // consider a change to the directory time as a change. Windows on NTFS - // does. See https://github.com/moby/moby/pull/37982 for more information. - - if !sameFsTime(oldStat.Mtim(), newStat.Mtim()) || - oldStat.Mode() != newStat.Mode() || - oldStat.Size() != newStat.Size() && !oldStat.Mode().IsDir() { - return true - } - return false -} - -func (info *FileInfo) isDir() bool { - return info.parent == nil || info.stat.Mode().IsDir() -} - -func getIno(fi os.FileInfo) (inode uint64) { - return -} - -func hasHardlinks(fi os.FileInfo) bool { - return false -} diff --git a/vendor/github.com/docker/docker/pkg/archive/copy.go b/vendor/github.com/docker/docker/pkg/archive/copy.go deleted file mode 100644 index 57fddac0..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/copy.go +++ /dev/null @@ -1,480 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "errors" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - - "github.com/docker/docker/pkg/system" - "github.com/sirupsen/logrus" -) - -// Errors used or returned by this file. -var ( - ErrNotDirectory = errors.New("not a directory") - ErrDirNotExists = errors.New("no such directory") - ErrCannotCopyDir = errors.New("cannot copy directory") - ErrInvalidCopySource = errors.New("invalid copy source content") -) - -// PreserveTrailingDotOrSeparator returns the given cleaned path (after -// processing using any utility functions from the path or filepath stdlib -// packages) and appends a trailing `/.` or `/` if its corresponding original -// path (from before being processed by utility functions from the path or -// filepath stdlib packages) ends with a trailing `/.` or `/`. If the cleaned -// path already ends in a `.` path segment, then another is not added. If the -// clean path already ends in the separator, then another is not added. -func PreserveTrailingDotOrSeparator(cleanedPath string, originalPath string, sep byte) string { - // Ensure paths are in platform semantics - cleanedPath = strings.Replace(cleanedPath, "/", string(sep), -1) - originalPath = strings.Replace(originalPath, "/", string(sep), -1) - - if !specifiesCurrentDir(cleanedPath) && specifiesCurrentDir(originalPath) { - if !hasTrailingPathSeparator(cleanedPath, sep) { - // Add a separator if it doesn't already end with one (a cleaned - // path would only end in a separator if it is the root). - cleanedPath += string(sep) - } - cleanedPath += "." - } - - if !hasTrailingPathSeparator(cleanedPath, sep) && hasTrailingPathSeparator(originalPath, sep) { - cleanedPath += string(sep) - } - - return cleanedPath -} - -// assertsDirectory returns whether the given path is -// asserted to be a directory, i.e., the path ends with -// a trailing '/' or `/.`, assuming a path separator of `/`. -func assertsDirectory(path string, sep byte) bool { - return hasTrailingPathSeparator(path, sep) || specifiesCurrentDir(path) -} - -// hasTrailingPathSeparator returns whether the given -// path ends with the system's path separator character. -func hasTrailingPathSeparator(path string, sep byte) bool { - return len(path) > 0 && path[len(path)-1] == sep -} - -// specifiesCurrentDir returns whether the given path specifies -// a "current directory", i.e., the last path segment is `.`. -func specifiesCurrentDir(path string) bool { - return filepath.Base(path) == "." -} - -// SplitPathDirEntry splits the given path between its directory name and its -// basename by first cleaning the path but preserves a trailing "." if the -// original path specified the current directory. -func SplitPathDirEntry(path string) (dir, base string) { - cleanedPath := filepath.Clean(filepath.FromSlash(path)) - - if specifiesCurrentDir(path) { - cleanedPath += string(os.PathSeparator) + "." - } - - return filepath.Dir(cleanedPath), filepath.Base(cleanedPath) -} - -// TarResource archives the resource described by the given CopyInfo to a Tar -// archive. A non-nil error is returned if sourcePath does not exist or is -// asserted to be a directory but exists as another type of file. -// -// This function acts as a convenient wrapper around TarWithOptions, which -// requires a directory as the source path. TarResource accepts either a -// directory or a file path and correctly sets the Tar options. -func TarResource(sourceInfo CopyInfo) (content io.ReadCloser, err error) { - return TarResourceRebase(sourceInfo.Path, sourceInfo.RebaseName) -} - -// TarResourceRebase is like TarResource but renames the first path element of -// items in the resulting tar archive to match the given rebaseName if not "". -func TarResourceRebase(sourcePath, rebaseName string) (content io.ReadCloser, err error) { - sourcePath = normalizePath(sourcePath) - if _, err = os.Lstat(sourcePath); err != nil { - // Catches the case where the source does not exist or is not a - // directory if asserted to be a directory, as this also causes an - // error. - return - } - - // Separate the source path between its directory and - // the entry in that directory which we are archiving. - sourceDir, sourceBase := SplitPathDirEntry(sourcePath) - opts := TarResourceRebaseOpts(sourceBase, rebaseName) - - logrus.Debugf("copying %q from %q", sourceBase, sourceDir) - return TarWithOptions(sourceDir, opts) -} - -// TarResourceRebaseOpts does not preform the Tar, but instead just creates the rebase -// parameters to be sent to TarWithOptions (the TarOptions struct) -func TarResourceRebaseOpts(sourceBase string, rebaseName string) *TarOptions { - filter := []string{sourceBase} - return &TarOptions{ - Compression: Uncompressed, - IncludeFiles: filter, - IncludeSourceDir: true, - RebaseNames: map[string]string{ - sourceBase: rebaseName, - }, - } -} - -// CopyInfo holds basic info about the source -// or destination path of a copy operation. -type CopyInfo struct { - Path string - Exists bool - IsDir bool - RebaseName string -} - -// CopyInfoSourcePath stats the given path to create a CopyInfo -// struct representing that resource for the source of an archive copy -// operation. The given path should be an absolute local path. A source path -// has all symlinks evaluated that appear before the last path separator ("/" -// on Unix). As it is to be a copy source, the path must exist. -func CopyInfoSourcePath(path string, followLink bool) (CopyInfo, error) { - // normalize the file path and then evaluate the symbol link - // we will use the target file instead of the symbol link if - // followLink is set - path = normalizePath(path) - - resolvedPath, rebaseName, err := ResolveHostSourcePath(path, followLink) - if err != nil { - return CopyInfo{}, err - } - - stat, err := os.Lstat(resolvedPath) - if err != nil { - return CopyInfo{}, err - } - - return CopyInfo{ - Path: resolvedPath, - Exists: true, - IsDir: stat.IsDir(), - RebaseName: rebaseName, - }, nil -} - -// CopyInfoDestinationPath stats the given path to create a CopyInfo -// struct representing that resource for the destination of an archive copy -// operation. The given path should be an absolute local path. -func CopyInfoDestinationPath(path string) (info CopyInfo, err error) { - maxSymlinkIter := 10 // filepath.EvalSymlinks uses 255, but 10 already seems like a lot. - path = normalizePath(path) - originalPath := path - - stat, err := os.Lstat(path) - - if err == nil && stat.Mode()&os.ModeSymlink == 0 { - // The path exists and is not a symlink. - return CopyInfo{ - Path: path, - Exists: true, - IsDir: stat.IsDir(), - }, nil - } - - // While the path is a symlink. - for n := 0; err == nil && stat.Mode()&os.ModeSymlink != 0; n++ { - if n > maxSymlinkIter { - // Don't follow symlinks more than this arbitrary number of times. - return CopyInfo{}, errors.New("too many symlinks in " + originalPath) - } - - // The path is a symbolic link. We need to evaluate it so that the - // destination of the copy operation is the link target and not the - // link itself. This is notably different than CopyInfoSourcePath which - // only evaluates symlinks before the last appearing path separator. - // Also note that it is okay if the last path element is a broken - // symlink as the copy operation should create the target. - var linkTarget string - - linkTarget, err = os.Readlink(path) - if err != nil { - return CopyInfo{}, err - } - - if !system.IsAbs(linkTarget) { - // Join with the parent directory. - dstParent, _ := SplitPathDirEntry(path) - linkTarget = filepath.Join(dstParent, linkTarget) - } - - path = linkTarget - stat, err = os.Lstat(path) - } - - if err != nil { - // It's okay if the destination path doesn't exist. We can still - // continue the copy operation if the parent directory exists. - if !os.IsNotExist(err) { - return CopyInfo{}, err - } - - // Ensure destination parent dir exists. - dstParent, _ := SplitPathDirEntry(path) - - parentDirStat, err := os.Stat(dstParent) - if err != nil { - return CopyInfo{}, err - } - if !parentDirStat.IsDir() { - return CopyInfo{}, ErrNotDirectory - } - - return CopyInfo{Path: path}, nil - } - - // The path exists after resolving symlinks. - return CopyInfo{ - Path: path, - Exists: true, - IsDir: stat.IsDir(), - }, nil -} - -// PrepareArchiveCopy prepares the given srcContent archive, which should -// contain the archived resource described by srcInfo, to the destination -// described by dstInfo. Returns the possibly modified content archive along -// with the path to the destination directory which it should be extracted to. -func PrepareArchiveCopy(srcContent io.Reader, srcInfo, dstInfo CopyInfo) (dstDir string, content io.ReadCloser, err error) { - // Ensure in platform semantics - srcInfo.Path = normalizePath(srcInfo.Path) - dstInfo.Path = normalizePath(dstInfo.Path) - - // Separate the destination path between its directory and base - // components in case the source archive contents need to be rebased. - dstDir, dstBase := SplitPathDirEntry(dstInfo.Path) - _, srcBase := SplitPathDirEntry(srcInfo.Path) - - switch { - case dstInfo.Exists && dstInfo.IsDir: - // The destination exists as a directory. No alteration - // to srcContent is needed as its contents can be - // simply extracted to the destination directory. - return dstInfo.Path, ioutil.NopCloser(srcContent), nil - case dstInfo.Exists && srcInfo.IsDir: - // The destination exists as some type of file and the source - // content is a directory. This is an error condition since - // you cannot copy a directory to an existing file location. - return "", nil, ErrCannotCopyDir - case dstInfo.Exists: - // The destination exists as some type of file and the source content - // is also a file. The source content entry will have to be renamed to - // have a basename which matches the destination path's basename. - if len(srcInfo.RebaseName) != 0 { - srcBase = srcInfo.RebaseName - } - return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil - case srcInfo.IsDir: - // The destination does not exist and the source content is an archive - // of a directory. The archive should be extracted to the parent of - // the destination path instead, and when it is, the directory that is - // created as a result should take the name of the destination path. - // The source content entries will have to be renamed to have a - // basename which matches the destination path's basename. - if len(srcInfo.RebaseName) != 0 { - srcBase = srcInfo.RebaseName - } - return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil - case assertsDirectory(dstInfo.Path, os.PathSeparator): - // The destination does not exist and is asserted to be created as a - // directory, but the source content is not a directory. This is an - // error condition since you cannot create a directory from a file - // source. - return "", nil, ErrDirNotExists - default: - // The last remaining case is when the destination does not exist, is - // not asserted to be a directory, and the source content is not an - // archive of a directory. It this case, the destination file will need - // to be created when the archive is extracted and the source content - // entry will have to be renamed to have a basename which matches the - // destination path's basename. - if len(srcInfo.RebaseName) != 0 { - srcBase = srcInfo.RebaseName - } - return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil - } - -} - -// RebaseArchiveEntries rewrites the given srcContent archive replacing -// an occurrence of oldBase with newBase at the beginning of entry names. -func RebaseArchiveEntries(srcContent io.Reader, oldBase, newBase string) io.ReadCloser { - if oldBase == string(os.PathSeparator) { - // If oldBase specifies the root directory, use an empty string as - // oldBase instead so that newBase doesn't replace the path separator - // that all paths will start with. - oldBase = "" - } - - rebased, w := io.Pipe() - - go func() { - srcTar := tar.NewReader(srcContent) - rebasedTar := tar.NewWriter(w) - - for { - hdr, err := srcTar.Next() - if err == io.EOF { - // Signals end of archive. - rebasedTar.Close() - w.Close() - return - } - if err != nil { - w.CloseWithError(err) - return - } - - // srcContent tar stream, as served by TarWithOptions(), is - // definitely in PAX format, but tar.Next() mistakenly guesses it - // as USTAR, which creates a problem: if the newBase is >100 - // characters long, WriteHeader() returns an error like - // "archive/tar: cannot encode header: Format specifies USTAR; and USTAR cannot encode Name=...". - // - // To fix, set the format to PAX here. See docker/for-linux issue #484. - hdr.Format = tar.FormatPAX - hdr.Name = strings.Replace(hdr.Name, oldBase, newBase, 1) - if hdr.Typeflag == tar.TypeLink { - hdr.Linkname = strings.Replace(hdr.Linkname, oldBase, newBase, 1) - } - - if err = rebasedTar.WriteHeader(hdr); err != nil { - w.CloseWithError(err) - return - } - - if _, err = io.Copy(rebasedTar, srcTar); err != nil { - w.CloseWithError(err) - return - } - } - }() - - return rebased -} - -// TODO @gupta-ak. These might have to be changed in the future to be -// continuity driver aware as well to support LCOW. - -// CopyResource performs an archive copy from the given source path to the -// given destination path. The source path MUST exist and the destination -// path's parent directory must exist. -func CopyResource(srcPath, dstPath string, followLink bool) error { - var ( - srcInfo CopyInfo - err error - ) - - // Ensure in platform semantics - srcPath = normalizePath(srcPath) - dstPath = normalizePath(dstPath) - - // Clean the source and destination paths. - srcPath = PreserveTrailingDotOrSeparator(filepath.Clean(srcPath), srcPath, os.PathSeparator) - dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath, os.PathSeparator) - - if srcInfo, err = CopyInfoSourcePath(srcPath, followLink); err != nil { - return err - } - - content, err := TarResource(srcInfo) - if err != nil { - return err - } - defer content.Close() - - return CopyTo(content, srcInfo, dstPath) -} - -// CopyTo handles extracting the given content whose -// entries should be sourced from srcInfo to dstPath. -func CopyTo(content io.Reader, srcInfo CopyInfo, dstPath string) error { - // The destination path need not exist, but CopyInfoDestinationPath will - // ensure that at least the parent directory exists. - dstInfo, err := CopyInfoDestinationPath(normalizePath(dstPath)) - if err != nil { - return err - } - - dstDir, copyArchive, err := PrepareArchiveCopy(content, srcInfo, dstInfo) - if err != nil { - return err - } - defer copyArchive.Close() - - options := &TarOptions{ - NoLchown: true, - NoOverwriteDirNonDir: true, - } - - return Untar(copyArchive, dstDir, options) -} - -// ResolveHostSourcePath decides real path need to be copied with parameters such as -// whether to follow symbol link or not, if followLink is true, resolvedPath will return -// link target of any symbol link file, else it will only resolve symlink of directory -// but return symbol link file itself without resolving. -func ResolveHostSourcePath(path string, followLink bool) (resolvedPath, rebaseName string, err error) { - if followLink { - resolvedPath, err = filepath.EvalSymlinks(path) - if err != nil { - return - } - - resolvedPath, rebaseName = GetRebaseName(path, resolvedPath) - } else { - dirPath, basePath := filepath.Split(path) - - // if not follow symbol link, then resolve symbol link of parent dir - var resolvedDirPath string - resolvedDirPath, err = filepath.EvalSymlinks(dirPath) - if err != nil { - return - } - // resolvedDirPath will have been cleaned (no trailing path separators) so - // we can manually join it with the base path element. - resolvedPath = resolvedDirPath + string(filepath.Separator) + basePath - if hasTrailingPathSeparator(path, os.PathSeparator) && - filepath.Base(path) != filepath.Base(resolvedPath) { - rebaseName = filepath.Base(path) - } - } - return resolvedPath, rebaseName, nil -} - -// GetRebaseName normalizes and compares path and resolvedPath, -// return completed resolved path and rebased file name -func GetRebaseName(path, resolvedPath string) (string, string) { - // linkTarget will have been cleaned (no trailing path separators and dot) so - // we can manually join it with them - var rebaseName string - if specifiesCurrentDir(path) && - !specifiesCurrentDir(resolvedPath) { - resolvedPath += string(filepath.Separator) + "." - } - - if hasTrailingPathSeparator(path, os.PathSeparator) && - !hasTrailingPathSeparator(resolvedPath, os.PathSeparator) { - resolvedPath += string(filepath.Separator) - } - - if filepath.Base(path) != filepath.Base(resolvedPath) { - // In the case where the path had a trailing separator and a symlink - // evaluation has changed the last path component, we will need to - // rebase the name in the archive that is being copied to match the - // originally requested name. - rebaseName = filepath.Base(path) - } - return resolvedPath, rebaseName -} diff --git a/vendor/github.com/docker/docker/pkg/archive/copy_unix.go b/vendor/github.com/docker/docker/pkg/archive/copy_unix.go deleted file mode 100644 index 3958364f..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/copy_unix.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !windows - -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "path/filepath" -) - -func normalizePath(path string) string { - return filepath.ToSlash(path) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/copy_windows.go b/vendor/github.com/docker/docker/pkg/archive/copy_windows.go deleted file mode 100644 index a878d1ba..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/copy_windows.go +++ /dev/null @@ -1,9 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "path/filepath" -) - -func normalizePath(path string) string { - return filepath.FromSlash(path) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/diff.go b/vendor/github.com/docker/docker/pkg/archive/diff.go deleted file mode 100644 index 27897e6a..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/diff.go +++ /dev/null @@ -1,260 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/pools" - "github.com/docker/docker/pkg/system" - "github.com/sirupsen/logrus" -) - -// UnpackLayer unpack `layer` to a `dest`. The stream `layer` can be -// compressed or uncompressed. -// Returns the size in bytes of the contents of the layer. -func UnpackLayer(dest string, layer io.Reader, options *TarOptions) (size int64, err error) { - tr := tar.NewReader(layer) - trBuf := pools.BufioReader32KPool.Get(tr) - defer pools.BufioReader32KPool.Put(trBuf) - - var dirs []*tar.Header - unpackedPaths := make(map[string]struct{}) - - if options == nil { - options = &TarOptions{} - } - if options.ExcludePatterns == nil { - options.ExcludePatterns = []string{} - } - idMapping := idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps) - - aufsTempdir := "" - aufsHardlinks := make(map[string]*tar.Header) - - // Iterate through the files in the archive. - for { - hdr, err := tr.Next() - if err == io.EOF { - // end of tar archive - break - } - if err != nil { - return 0, err - } - - size += hdr.Size - - // Normalize name, for safety and for a simple is-root check - hdr.Name = filepath.Clean(hdr.Name) - - // Windows does not support filenames with colons in them. Ignore - // these files. This is not a problem though (although it might - // appear that it is). Let's suppose a client is running docker pull. - // The daemon it points to is Windows. Would it make sense for the - // client to be doing a docker pull Ubuntu for example (which has files - // with colons in the name under /usr/share/man/man3)? No, absolutely - // not as it would really only make sense that they were pulling a - // Windows image. However, for development, it is necessary to be able - // to pull Linux images which are in the repository. - // - // TODO Windows. Once the registry is aware of what images are Windows- - // specific or Linux-specific, this warning should be changed to an error - // to cater for the situation where someone does manage to upload a Linux - // image but have it tagged as Windows inadvertently. - if runtime.GOOS == "windows" { - if strings.Contains(hdr.Name, ":") { - logrus.Warnf("Windows: Ignoring %s (is this a Linux image?)", hdr.Name) - continue - } - } - - // Note as these operations are platform specific, so must the slash be. - if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { - // Not the root directory, ensure that the parent directory exists. - // This happened in some tests where an image had a tarfile without any - // parent directories. - parent := filepath.Dir(hdr.Name) - parentPath := filepath.Join(dest, parent) - - if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { - err = system.MkdirAll(parentPath, 0600) - if err != nil { - return 0, err - } - } - } - - // Skip AUFS metadata dirs - if strings.HasPrefix(hdr.Name, WhiteoutMetaPrefix) { - // Regular files inside /.wh..wh.plnk can be used as hardlink targets - // We don't want this directory, but we need the files in them so that - // such hardlinks can be resolved. - if strings.HasPrefix(hdr.Name, WhiteoutLinkDir) && hdr.Typeflag == tar.TypeReg { - basename := filepath.Base(hdr.Name) - aufsHardlinks[basename] = hdr - if aufsTempdir == "" { - if aufsTempdir, err = ioutil.TempDir("", "dockerplnk"); err != nil { - return 0, err - } - defer os.RemoveAll(aufsTempdir) - } - if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, true, nil, options.InUserNS); err != nil { - return 0, err - } - } - - if hdr.Name != WhiteoutOpaqueDir { - continue - } - } - path := filepath.Join(dest, hdr.Name) - rel, err := filepath.Rel(dest, path) - if err != nil { - return 0, err - } - - // Note as these operations are platform specific, so must the slash be. - if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { - return 0, breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) - } - base := filepath.Base(path) - - if strings.HasPrefix(base, WhiteoutPrefix) { - dir := filepath.Dir(path) - if base == WhiteoutOpaqueDir { - _, err := os.Lstat(dir) - if err != nil { - return 0, err - } - err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { - if err != nil { - if os.IsNotExist(err) { - err = nil // parent was deleted - } - return err - } - if path == dir { - return nil - } - if _, exists := unpackedPaths[path]; !exists { - err := os.RemoveAll(path) - return err - } - return nil - }) - if err != nil { - return 0, err - } - } else { - originalBase := base[len(WhiteoutPrefix):] - originalPath := filepath.Join(dir, originalBase) - if err := os.RemoveAll(originalPath); err != nil { - return 0, err - } - } - } else { - // If path exits we almost always just want to remove and replace it. - // The only exception is when it is a directory *and* the file from - // the layer is also a directory. Then we want to merge them (i.e. - // just apply the metadata from the layer). - if fi, err := os.Lstat(path); err == nil { - if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { - if err := os.RemoveAll(path); err != nil { - return 0, err - } - } - } - - trBuf.Reset(tr) - srcData := io.Reader(trBuf) - srcHdr := hdr - - // Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so - // we manually retarget these into the temporary files we extracted them into - if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), WhiteoutLinkDir) { - linkBasename := filepath.Base(hdr.Linkname) - srcHdr = aufsHardlinks[linkBasename] - if srcHdr == nil { - return 0, fmt.Errorf("Invalid aufs hardlink") - } - tmpFile, err := os.Open(filepath.Join(aufsTempdir, linkBasename)) - if err != nil { - return 0, err - } - defer tmpFile.Close() - srcData = tmpFile - } - - if err := remapIDs(idMapping, srcHdr); err != nil { - return 0, err - } - - if err := createTarFile(path, dest, srcHdr, srcData, !options.NoLchown, nil, options.InUserNS); err != nil { - return 0, err - } - - // Directory mtimes must be handled at the end to avoid further - // file creation in them to modify the directory mtime - if hdr.Typeflag == tar.TypeDir { - dirs = append(dirs, hdr) - } - unpackedPaths[path] = struct{}{} - } - } - - for _, hdr := range dirs { - path := filepath.Join(dest, hdr.Name) - if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { - return 0, err - } - } - - return size, nil -} - -// ApplyLayer parses a diff in the standard layer format from `layer`, -// and applies it to the directory `dest`. The stream `layer` can be -// compressed or uncompressed. -// Returns the size in bytes of the contents of the layer. -func ApplyLayer(dest string, layer io.Reader) (int64, error) { - return applyLayerHandler(dest, layer, &TarOptions{}, true) -} - -// ApplyUncompressedLayer parses a diff in the standard layer format from -// `layer`, and applies it to the directory `dest`. The stream `layer` -// can only be uncompressed. -// Returns the size in bytes of the contents of the layer. -func ApplyUncompressedLayer(dest string, layer io.Reader, options *TarOptions) (int64, error) { - return applyLayerHandler(dest, layer, options, false) -} - -// do the bulk load of ApplyLayer, but allow for not calling DecompressStream -func applyLayerHandler(dest string, layer io.Reader, options *TarOptions, decompress bool) (int64, error) { - dest = filepath.Clean(dest) - - // We need to be able to set any perms - if runtime.GOOS != "windows" { - oldmask, err := system.Umask(0) - if err != nil { - return 0, err - } - defer system.Umask(oldmask) - } - - if decompress { - decompLayer, err := DecompressStream(layer) - if err != nil { - return 0, err - } - defer decompLayer.Close() - layer = decompLayer - } - return UnpackLayer(dest, layer, options) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/time_linux.go b/vendor/github.com/docker/docker/pkg/archive/time_linux.go deleted file mode 100644 index 797143ee..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/time_linux.go +++ /dev/null @@ -1,16 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "syscall" - "time" -) - -func timeToTimespec(time time.Time) (ts syscall.Timespec) { - if time.IsZero() { - // Return UTIME_OMIT special value - ts.Sec = 0 - ts.Nsec = (1 << 30) - 2 - return - } - return syscall.NsecToTimespec(time.UnixNano()) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/time_unsupported.go b/vendor/github.com/docker/docker/pkg/archive/time_unsupported.go deleted file mode 100644 index f58bf227..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/time_unsupported.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build !linux - -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "syscall" - "time" -) - -func timeToTimespec(time time.Time) (ts syscall.Timespec) { - nsec := int64(0) - if !time.IsZero() { - nsec = time.UnixNano() - } - return syscall.NsecToTimespec(nsec) -} diff --git a/vendor/github.com/docker/docker/pkg/archive/whiteouts.go b/vendor/github.com/docker/docker/pkg/archive/whiteouts.go deleted file mode 100644 index 4c072a87..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/whiteouts.go +++ /dev/null @@ -1,23 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -// Whiteouts are files with a special meaning for the layered filesystem. -// Docker uses AUFS whiteout files inside exported archives. In other -// filesystems these files are generated/handled on tar creation/extraction. - -// WhiteoutPrefix prefix means file is a whiteout. If this is followed by a -// filename this means that file has been removed from the base layer. -const WhiteoutPrefix = ".wh." - -// WhiteoutMetaPrefix prefix means whiteout has a special meaning and is not -// for removing an actual file. Normally these files are excluded from exported -// archives. -const WhiteoutMetaPrefix = WhiteoutPrefix + WhiteoutPrefix - -// WhiteoutLinkDir is a directory AUFS uses for storing hardlink links to other -// layers. Normally these should not go into exported archives and all changed -// hardlinks should be copied to the top layer. -const WhiteoutLinkDir = WhiteoutMetaPrefix + "plnk" - -// WhiteoutOpaqueDir file means directory has been made opaque - meaning -// readdir calls to this directory do not follow to lower layers. -const WhiteoutOpaqueDir = WhiteoutMetaPrefix + ".opq" diff --git a/vendor/github.com/docker/docker/pkg/archive/wrap.go b/vendor/github.com/docker/docker/pkg/archive/wrap.go deleted file mode 100644 index 85435694..00000000 --- a/vendor/github.com/docker/docker/pkg/archive/wrap.go +++ /dev/null @@ -1,59 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "bytes" - "io" -) - -// Generate generates a new archive from the content provided -// as input. -// -// `files` is a sequence of path/content pairs. A new file is -// added to the archive for each pair. -// If the last pair is incomplete, the file is created with an -// empty content. For example: -// -// Generate("foo.txt", "hello world", "emptyfile") -// -// The above call will return an archive with 2 files: -// * ./foo.txt with content "hello world" -// * ./empty with empty content -// -// FIXME: stream content instead of buffering -// FIXME: specify permissions and other archive metadata -func Generate(input ...string) (io.Reader, error) { - files := parseStringPairs(input...) - buf := new(bytes.Buffer) - tw := tar.NewWriter(buf) - for _, file := range files { - name, content := file[0], file[1] - hdr := &tar.Header{ - Name: name, - Size: int64(len(content)), - } - if err := tw.WriteHeader(hdr); err != nil { - return nil, err - } - if _, err := tw.Write([]byte(content)); err != nil { - return nil, err - } - } - if err := tw.Close(); err != nil { - return nil, err - } - return buf, nil -} - -func parseStringPairs(input ...string) (output [][2]string) { - output = make([][2]string, 0, len(input)/2+1) - for i := 0; i < len(input); i += 2 { - var pair [2]string - pair[0] = input[i] - if i+1 < len(input) { - pair[1] = input[i+1] - } - output = append(output, pair) - } - return -} diff --git a/vendor/github.com/docker/docker/pkg/fileutils/fileutils.go b/vendor/github.com/docker/docker/pkg/fileutils/fileutils.go deleted file mode 100644 index 34f1c726..00000000 --- a/vendor/github.com/docker/docker/pkg/fileutils/fileutils.go +++ /dev/null @@ -1,298 +0,0 @@ -package fileutils // import "github.com/docker/docker/pkg/fileutils" - -import ( - "errors" - "fmt" - "io" - "os" - "path/filepath" - "regexp" - "strings" - "text/scanner" - - "github.com/sirupsen/logrus" -) - -// PatternMatcher allows checking paths against a list of patterns -type PatternMatcher struct { - patterns []*Pattern - exclusions bool -} - -// NewPatternMatcher creates a new matcher object for specific patterns that can -// be used later to match against patterns against paths -func NewPatternMatcher(patterns []string) (*PatternMatcher, error) { - pm := &PatternMatcher{ - patterns: make([]*Pattern, 0, len(patterns)), - } - for _, p := range patterns { - // Eliminate leading and trailing whitespace. - p = strings.TrimSpace(p) - if p == "" { - continue - } - p = filepath.Clean(p) - newp := &Pattern{} - if p[0] == '!' { - if len(p) == 1 { - return nil, errors.New("illegal exclusion pattern: \"!\"") - } - newp.exclusion = true - p = p[1:] - pm.exclusions = true - } - // Do some syntax checking on the pattern. - // filepath's Match() has some really weird rules that are inconsistent - // so instead of trying to dup their logic, just call Match() for its - // error state and if there is an error in the pattern return it. - // If this becomes an issue we can remove this since its really only - // needed in the error (syntax) case - which isn't really critical. - if _, err := filepath.Match(p, "."); err != nil { - return nil, err - } - newp.cleanedPattern = p - newp.dirs = strings.Split(p, string(os.PathSeparator)) - pm.patterns = append(pm.patterns, newp) - } - return pm, nil -} - -// Matches matches path against all the patterns. Matches is not safe to be -// called concurrently -func (pm *PatternMatcher) Matches(file string) (bool, error) { - matched := false - file = filepath.FromSlash(file) - parentPath := filepath.Dir(file) - parentPathDirs := strings.Split(parentPath, string(os.PathSeparator)) - - for _, pattern := range pm.patterns { - negative := false - - if pattern.exclusion { - negative = true - } - - match, err := pattern.match(file) - if err != nil { - return false, err - } - - if !match && parentPath != "." { - // Check to see if the pattern matches one of our parent dirs. - if len(pattern.dirs) <= len(parentPathDirs) { - match, _ = pattern.match(strings.Join(parentPathDirs[:len(pattern.dirs)], string(os.PathSeparator))) - } - } - - if match { - matched = !negative - } - } - - if matched { - logrus.Debugf("Skipping excluded path: %s", file) - } - - return matched, nil -} - -// Exclusions returns true if any of the patterns define exclusions -func (pm *PatternMatcher) Exclusions() bool { - return pm.exclusions -} - -// Patterns returns array of active patterns -func (pm *PatternMatcher) Patterns() []*Pattern { - return pm.patterns -} - -// Pattern defines a single regexp used to filter file paths. -type Pattern struct { - cleanedPattern string - dirs []string - regexp *regexp.Regexp - exclusion bool -} - -func (p *Pattern) String() string { - return p.cleanedPattern -} - -// Exclusion returns true if this pattern defines exclusion -func (p *Pattern) Exclusion() bool { - return p.exclusion -} - -func (p *Pattern) match(path string) (bool, error) { - - if p.regexp == nil { - if err := p.compile(); err != nil { - return false, filepath.ErrBadPattern - } - } - - b := p.regexp.MatchString(path) - - return b, nil -} - -func (p *Pattern) compile() error { - regStr := "^" - pattern := p.cleanedPattern - // Go through the pattern and convert it to a regexp. - // We use a scanner so we can support utf-8 chars. - var scan scanner.Scanner - scan.Init(strings.NewReader(pattern)) - - sl := string(os.PathSeparator) - escSL := sl - if sl == `\` { - escSL += `\` - } - - for scan.Peek() != scanner.EOF { - ch := scan.Next() - - if ch == '*' { - if scan.Peek() == '*' { - // is some flavor of "**" - scan.Next() - - // Treat **/ as ** so eat the "/" - if string(scan.Peek()) == sl { - scan.Next() - } - - if scan.Peek() == scanner.EOF { - // is "**EOF" - to align with .gitignore just accept all - regStr += ".*" - } else { - // is "**" - // Note that this allows for any # of /'s (even 0) because - // the .* will eat everything, even /'s - regStr += "(.*" + escSL + ")?" - } - } else { - // is "*" so map it to anything but "/" - regStr += "[^" + escSL + "]*" - } - } else if ch == '?' { - // "?" is any char except "/" - regStr += "[^" + escSL + "]" - } else if ch == '.' || ch == '$' { - // Escape some regexp special chars that have no meaning - // in golang's filepath.Match - regStr += `\` + string(ch) - } else if ch == '\\' { - // escape next char. Note that a trailing \ in the pattern - // will be left alone (but need to escape it) - if sl == `\` { - // On windows map "\" to "\\", meaning an escaped backslash, - // and then just continue because filepath.Match on - // Windows doesn't allow escaping at all - regStr += escSL - continue - } - if scan.Peek() != scanner.EOF { - regStr += `\` + string(scan.Next()) - } else { - regStr += `\` - } - } else { - regStr += string(ch) - } - } - - regStr += "$" - - re, err := regexp.Compile(regStr) - if err != nil { - return err - } - - p.regexp = re - return nil -} - -// Matches returns true if file matches any of the patterns -// and isn't excluded by any of the subsequent patterns. -func Matches(file string, patterns []string) (bool, error) { - pm, err := NewPatternMatcher(patterns) - if err != nil { - return false, err - } - file = filepath.Clean(file) - - if file == "." { - // Don't let them exclude everything, kind of silly. - return false, nil - } - - return pm.Matches(file) -} - -// CopyFile copies from src to dst until either EOF is reached -// on src or an error occurs. It verifies src exists and removes -// the dst if it exists. -func CopyFile(src, dst string) (int64, error) { - cleanSrc := filepath.Clean(src) - cleanDst := filepath.Clean(dst) - if cleanSrc == cleanDst { - return 0, nil - } - sf, err := os.Open(cleanSrc) - if err != nil { - return 0, err - } - defer sf.Close() - if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) { - return 0, err - } - df, err := os.Create(cleanDst) - if err != nil { - return 0, err - } - defer df.Close() - return io.Copy(df, sf) -} - -// ReadSymlinkedDirectory returns the target directory of a symlink. -// The target of the symbolic link may not be a file. -func ReadSymlinkedDirectory(path string) (string, error) { - var realPath string - var err error - if realPath, err = filepath.Abs(path); err != nil { - return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err) - } - if realPath, err = filepath.EvalSymlinks(realPath); err != nil { - return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err) - } - realPathInfo, err := os.Stat(realPath) - if err != nil { - return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err) - } - if !realPathInfo.Mode().IsDir() { - return "", fmt.Errorf("canonical path points to a file '%s'", realPath) - } - return realPath, nil -} - -// CreateIfNotExists creates a file or a directory only if it does not already exist. -func CreateIfNotExists(path string, isDir bool) error { - if _, err := os.Stat(path); err != nil { - if os.IsNotExist(err) { - if isDir { - return os.MkdirAll(path, 0755) - } - if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { - return err - } - f, err := os.OpenFile(path, os.O_CREATE, 0755) - if err != nil { - return err - } - f.Close() - } - } - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_darwin.go b/vendor/github.com/docker/docker/pkg/fileutils/fileutils_darwin.go deleted file mode 100644 index e40cc271..00000000 --- a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_darwin.go +++ /dev/null @@ -1,27 +0,0 @@ -package fileutils // import "github.com/docker/docker/pkg/fileutils" - -import ( - "os" - "os/exec" - "strconv" - "strings" -) - -// GetTotalUsedFds returns the number of used File Descriptors by -// executing `lsof -p PID` -func GetTotalUsedFds() int { - pid := os.Getpid() - - cmd := exec.Command("lsof", "-p", strconv.Itoa(pid)) - - output, err := cmd.CombinedOutput() - if err != nil { - return -1 - } - - outputStr := strings.TrimSpace(string(output)) - - fds := strings.Split(outputStr, "\n") - - return len(fds) - 1 -} diff --git a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_unix.go b/vendor/github.com/docker/docker/pkg/fileutils/fileutils_unix.go deleted file mode 100644 index 565396f1..00000000 --- a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_unix.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build linux freebsd - -package fileutils // import "github.com/docker/docker/pkg/fileutils" - -import ( - "fmt" - "io/ioutil" - "os" - - "github.com/sirupsen/logrus" -) - -// GetTotalUsedFds Returns the number of used File Descriptors by -// reading it via /proc filesystem. -func GetTotalUsedFds() int { - if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil { - logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err) - } else { - return len(fds) - } - return -1 -} diff --git a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_windows.go b/vendor/github.com/docker/docker/pkg/fileutils/fileutils_windows.go deleted file mode 100644 index 3f1ebb65..00000000 --- a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -package fileutils // import "github.com/docker/docker/pkg/fileutils" - -// GetTotalUsedFds Returns the number of used File Descriptors. Not supported -// on Windows. -func GetTotalUsedFds() int { - return -1 -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/idtools.go b/vendor/github.com/docker/docker/pkg/idtools/idtools.go deleted file mode 100644 index 25a57b23..00000000 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools.go +++ /dev/null @@ -1,241 +0,0 @@ -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "bufio" - "fmt" - "os" - "strconv" - "strings" -) - -// IDMap contains a single entry for user namespace range remapping. An array -// of IDMap entries represents the structure that will be provided to the Linux -// kernel for creating a user namespace. -type IDMap struct { - ContainerID int `json:"container_id"` - HostID int `json:"host_id"` - Size int `json:"size"` -} - -type subIDRange struct { - Start int - Length int -} - -type ranges []subIDRange - -func (e ranges) Len() int { return len(e) } -func (e ranges) Swap(i, j int) { e[i], e[j] = e[j], e[i] } -func (e ranges) Less(i, j int) bool { return e[i].Start < e[j].Start } - -const ( - subuidFileName = "/etc/subuid" - subgidFileName = "/etc/subgid" -) - -// MkdirAllAndChown creates a directory (include any along the path) and then modifies -// ownership to the requested uid/gid. If the directory already exists, this -// function will still change ownership and permissions. -func MkdirAllAndChown(path string, mode os.FileMode, owner Identity) error { - return mkdirAs(path, mode, owner, true, true) -} - -// MkdirAndChown creates a directory and then modifies ownership to the requested uid/gid. -// If the directory already exists, this function still changes ownership and permissions. -// Note that unlike os.Mkdir(), this function does not return IsExist error -// in case path already exists. -func MkdirAndChown(path string, mode os.FileMode, owner Identity) error { - return mkdirAs(path, mode, owner, false, true) -} - -// MkdirAllAndChownNew creates a directory (include any along the path) and then modifies -// ownership ONLY of newly created directories to the requested uid/gid. If the -// directories along the path exist, no change of ownership or permissions will be performed -func MkdirAllAndChownNew(path string, mode os.FileMode, owner Identity) error { - return mkdirAs(path, mode, owner, true, false) -} - -// GetRootUIDGID retrieves the remapped root uid/gid pair from the set of maps. -// If the maps are empty, then the root uid/gid will default to "real" 0/0 -func GetRootUIDGID(uidMap, gidMap []IDMap) (int, int, error) { - uid, err := toHost(0, uidMap) - if err != nil { - return -1, -1, err - } - gid, err := toHost(0, gidMap) - if err != nil { - return -1, -1, err - } - return uid, gid, nil -} - -// toContainer takes an id mapping, and uses it to translate a -// host ID to the remapped ID. If no map is provided, then the translation -// assumes a 1-to-1 mapping and returns the passed in id -func toContainer(hostID int, idMap []IDMap) (int, error) { - if idMap == nil { - return hostID, nil - } - for _, m := range idMap { - if (hostID >= m.HostID) && (hostID <= (m.HostID + m.Size - 1)) { - contID := m.ContainerID + (hostID - m.HostID) - return contID, nil - } - } - return -1, fmt.Errorf("Host ID %d cannot be mapped to a container ID", hostID) -} - -// toHost takes an id mapping and a remapped ID, and translates the -// ID to the mapped host ID. If no map is provided, then the translation -// assumes a 1-to-1 mapping and returns the passed in id # -func toHost(contID int, idMap []IDMap) (int, error) { - if idMap == nil { - return contID, nil - } - for _, m := range idMap { - if (contID >= m.ContainerID) && (contID <= (m.ContainerID + m.Size - 1)) { - hostID := m.HostID + (contID - m.ContainerID) - return hostID, nil - } - } - return -1, fmt.Errorf("Container ID %d cannot be mapped to a host ID", contID) -} - -// Identity is either a UID and GID pair or a SID (but not both) -type Identity struct { - UID int - GID int - SID string -} - -// IdentityMapping contains a mappings of UIDs and GIDs -type IdentityMapping struct { - uids []IDMap - gids []IDMap -} - -// NewIDMappingsFromMaps creates a new mapping from two slices -// Deprecated: this is a temporary shim while transitioning to IDMapping -func NewIDMappingsFromMaps(uids []IDMap, gids []IDMap) *IdentityMapping { - return &IdentityMapping{uids: uids, gids: gids} -} - -// RootPair returns a uid and gid pair for the root user. The error is ignored -// because a root user always exists, and the defaults are correct when the uid -// and gid maps are empty. -func (i *IdentityMapping) RootPair() Identity { - uid, gid, _ := GetRootUIDGID(i.uids, i.gids) - return Identity{UID: uid, GID: gid} -} - -// ToHost returns the host UID and GID for the container uid, gid. -// Remapping is only performed if the ids aren't already the remapped root ids -func (i *IdentityMapping) ToHost(pair Identity) (Identity, error) { - var err error - target := i.RootPair() - - if pair.UID != target.UID { - target.UID, err = toHost(pair.UID, i.uids) - if err != nil { - return target, err - } - } - - if pair.GID != target.GID { - target.GID, err = toHost(pair.GID, i.gids) - } - return target, err -} - -// ToContainer returns the container UID and GID for the host uid and gid -func (i *IdentityMapping) ToContainer(pair Identity) (int, int, error) { - uid, err := toContainer(pair.UID, i.uids) - if err != nil { - return -1, -1, err - } - gid, err := toContainer(pair.GID, i.gids) - return uid, gid, err -} - -// Empty returns true if there are no id mappings -func (i *IdentityMapping) Empty() bool { - return len(i.uids) == 0 && len(i.gids) == 0 -} - -// UIDs return the UID mapping -// TODO: remove this once everything has been refactored to use pairs -func (i *IdentityMapping) UIDs() []IDMap { - return i.uids -} - -// GIDs return the UID mapping -// TODO: remove this once everything has been refactored to use pairs -func (i *IdentityMapping) GIDs() []IDMap { - return i.gids -} - -func createIDMap(subidRanges ranges) []IDMap { - idMap := []IDMap{} - - containerID := 0 - for _, idrange := range subidRanges { - idMap = append(idMap, IDMap{ - ContainerID: containerID, - HostID: idrange.Start, - Size: idrange.Length, - }) - containerID = containerID + idrange.Length - } - return idMap -} - -func parseSubuid(username string) (ranges, error) { - return parseSubidFile(subuidFileName, username) -} - -func parseSubgid(username string) (ranges, error) { - return parseSubidFile(subgidFileName, username) -} - -// parseSubidFile will read the appropriate file (/etc/subuid or /etc/subgid) -// and return all found ranges for a specified username. If the special value -// "ALL" is supplied for username, then all ranges in the file will be returned -func parseSubidFile(path, username string) (ranges, error) { - var rangeList ranges - - subidFile, err := os.Open(path) - if err != nil { - return rangeList, err - } - defer subidFile.Close() - - s := bufio.NewScanner(subidFile) - for s.Scan() { - text := strings.TrimSpace(s.Text()) - if text == "" || strings.HasPrefix(text, "#") { - continue - } - parts := strings.Split(text, ":") - if len(parts) != 3 { - return rangeList, fmt.Errorf("Cannot parse subuid/gid information: Format not correct for %s file", path) - } - if parts[0] == username || username == "ALL" { - startid, err := strconv.Atoi(parts[1]) - if err != nil { - return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) - } - length, err := strconv.Atoi(parts[2]) - if err != nil { - return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) - } - rangeList = append(rangeList, subIDRange{startid, length}) - } - } - - return rangeList, s.Err() -} - -// CurrentIdentity returns the identity of the current process -func CurrentIdentity() Identity { - return Identity{UID: os.Getuid(), GID: os.Getegid()} -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/idtools_unix.go b/vendor/github.com/docker/docker/pkg/idtools/idtools_unix.go deleted file mode 100644 index e7d25ee4..00000000 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools_unix.go +++ /dev/null @@ -1,295 +0,0 @@ -// +build !windows - -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "strconv" - "sync" - "syscall" - - "github.com/docker/docker/pkg/system" - "github.com/opencontainers/runc/libcontainer/user" - "github.com/pkg/errors" -) - -var ( - entOnce sync.Once - getentCmd string -) - -func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting bool) error { - // make an array containing the original path asked for, plus (for mkAll == true) - // all path components leading up to the complete path that don't exist before we MkdirAll - // so that we can chown all of them properly at the end. If chownExisting is false, we won't - // chown the full directory path if it exists - - var paths []string - - stat, err := system.Stat(path) - if err == nil { - if !stat.IsDir() { - return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} - } - if !chownExisting { - return nil - } - - // short-circuit--we were called with an existing directory and chown was requested - return setPermissions(path, mode, owner.UID, owner.GID, stat) - } - - if os.IsNotExist(err) { - paths = []string{path} - } - - if mkAll { - // walk back to "/" looking for directories which do not exist - // and add them to the paths array for chown after creation - dirPath := path - for { - dirPath = filepath.Dir(dirPath) - if dirPath == "/" { - break - } - if _, err := os.Stat(dirPath); err != nil && os.IsNotExist(err) { - paths = append(paths, dirPath) - } - } - if err := system.MkdirAll(path, mode); err != nil { - return err - } - } else { - if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) { - return err - } - } - // even if it existed, we will chown the requested path + any subpaths that - // didn't exist when we called MkdirAll - for _, pathComponent := range paths { - if err := setPermissions(pathComponent, mode, owner.UID, owner.GID, nil); err != nil { - return err - } - } - return nil -} - -// CanAccess takes a valid (existing) directory and a uid, gid pair and determines -// if that uid, gid pair has access (execute bit) to the directory -func CanAccess(path string, pair Identity) bool { - statInfo, err := system.Stat(path) - if err != nil { - return false - } - fileMode := os.FileMode(statInfo.Mode()) - permBits := fileMode.Perm() - return accessible(statInfo.UID() == uint32(pair.UID), - statInfo.GID() == uint32(pair.GID), permBits) -} - -func accessible(isOwner, isGroup bool, perms os.FileMode) bool { - if isOwner && (perms&0100 == 0100) { - return true - } - if isGroup && (perms&0010 == 0010) { - return true - } - if perms&0001 == 0001 { - return true - } - return false -} - -// LookupUser uses traditional local system files lookup (from libcontainer/user) on a username, -// followed by a call to `getent` for supporting host configured non-files passwd and group dbs -func LookupUser(name string) (user.User, error) { - // first try a local system files lookup using existing capabilities - usr, err := user.LookupUser(name) - if err == nil { - return usr, nil - } - // local files lookup failed; attempt to call `getent` to query configured passwd dbs - usr, err = getentUser(name) - if err != nil { - return user.User{}, err - } - return usr, nil -} - -// LookupUID uses traditional local system files lookup (from libcontainer/user) on a uid, -// followed by a call to `getent` for supporting host configured non-files passwd and group dbs -func LookupUID(uid int) (user.User, error) { - // first try a local system files lookup using existing capabilities - usr, err := user.LookupUid(uid) - if err == nil { - return usr, nil - } - // local files lookup failed; attempt to call `getent` to query configured passwd dbs - return getentUser(strconv.Itoa(uid)) -} - -func getentUser(name string) (user.User, error) { - reader, err := callGetent("passwd", name) - if err != nil { - return user.User{}, err - } - users, err := user.ParsePasswd(reader) - if err != nil { - return user.User{}, err - } - if len(users) == 0 { - return user.User{}, fmt.Errorf("getent failed to find passwd entry for %q", name) - } - return users[0], nil -} - -// LookupGroup uses traditional local system files lookup (from libcontainer/user) on a group name, -// followed by a call to `getent` for supporting host configured non-files passwd and group dbs -func LookupGroup(name string) (user.Group, error) { - // first try a local system files lookup using existing capabilities - group, err := user.LookupGroup(name) - if err == nil { - return group, nil - } - // local files lookup failed; attempt to call `getent` to query configured group dbs - return getentGroup(name) -} - -// LookupGID uses traditional local system files lookup (from libcontainer/user) on a group ID, -// followed by a call to `getent` for supporting host configured non-files passwd and group dbs -func LookupGID(gid int) (user.Group, error) { - // first try a local system files lookup using existing capabilities - group, err := user.LookupGid(gid) - if err == nil { - return group, nil - } - // local files lookup failed; attempt to call `getent` to query configured group dbs - return getentGroup(strconv.Itoa(gid)) -} - -func getentGroup(name string) (user.Group, error) { - reader, err := callGetent("group", name) - if err != nil { - return user.Group{}, err - } - groups, err := user.ParseGroup(reader) - if err != nil { - return user.Group{}, err - } - if len(groups) == 0 { - return user.Group{}, fmt.Errorf("getent failed to find groups entry for %q", name) - } - return groups[0], nil -} - -func callGetent(database, key string) (io.Reader, error) { - entOnce.Do(func() { getentCmd, _ = resolveBinary("getent") }) - // if no `getent` command on host, can't do anything else - if getentCmd == "" { - return nil, fmt.Errorf("unable to find getent command") - } - out, err := execCmd(getentCmd, database, key) - if err != nil { - exitCode, errC := system.GetExitCode(err) - if errC != nil { - return nil, err - } - switch exitCode { - case 1: - return nil, fmt.Errorf("getent reported invalid parameters/database unknown") - case 2: - return nil, fmt.Errorf("getent unable to find entry %q in %s database", key, database) - case 3: - return nil, fmt.Errorf("getent database doesn't support enumeration") - default: - return nil, err - } - - } - return bytes.NewReader(out), nil -} - -// setPermissions performs a chown/chmod only if the uid/gid don't match what's requested -// Normally a Chown is a no-op if uid/gid match, but in some cases this can still cause an error, e.g. if the -// dir is on an NFS share, so don't call chown unless we absolutely must. -// Likewise for setting permissions. -func setPermissions(p string, mode os.FileMode, uid, gid int, stat *system.StatT) error { - if stat == nil { - var err error - stat, err = system.Stat(p) - if err != nil { - return err - } - } - if os.FileMode(stat.Mode()).Perm() != mode.Perm() { - if err := os.Chmod(p, mode.Perm()); err != nil { - return err - } - } - if stat.UID() == uint32(uid) && stat.GID() == uint32(gid) { - return nil - } - return os.Chown(p, uid, gid) -} - -// NewIdentityMapping takes a requested username and -// using the data from /etc/sub{uid,gid} ranges, creates the -// proper uid and gid remapping ranges for that user/group pair -func NewIdentityMapping(name string) (*IdentityMapping, error) { - usr, err := LookupUser(name) - if err != nil { - return nil, fmt.Errorf("Could not get user for username %s: %v", name, err) - } - - subuidRanges, err := lookupSubUIDRanges(usr) - if err != nil { - return nil, err - } - subgidRanges, err := lookupSubGIDRanges(usr) - if err != nil { - return nil, err - } - - return &IdentityMapping{ - uids: subuidRanges, - gids: subgidRanges, - }, nil -} - -func lookupSubUIDRanges(usr user.User) ([]IDMap, error) { - rangeList, err := parseSubuid(strconv.Itoa(usr.Uid)) - if err != nil { - return nil, err - } - if len(rangeList) == 0 { - rangeList, err = parseSubuid(usr.Name) - if err != nil { - return nil, err - } - } - if len(rangeList) == 0 { - return nil, errors.Errorf("no subuid ranges found for user %q", usr.Name) - } - return createIDMap(rangeList), nil -} - -func lookupSubGIDRanges(usr user.User) ([]IDMap, error) { - rangeList, err := parseSubgid(strconv.Itoa(usr.Uid)) - if err != nil { - return nil, err - } - if len(rangeList) == 0 { - rangeList, err = parseSubgid(usr.Name) - if err != nil { - return nil, err - } - } - if len(rangeList) == 0 { - return nil, errors.Errorf("no subgid ranges found for user %q", usr.Name) - } - return createIDMap(rangeList), nil -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/idtools_windows.go b/vendor/github.com/docker/docker/pkg/idtools/idtools_windows.go deleted file mode 100644 index 35ede0ff..00000000 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools_windows.go +++ /dev/null @@ -1,25 +0,0 @@ -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "os" - - "github.com/docker/docker/pkg/system" -) - -// This is currently a wrapper around MkdirAll, however, since currently -// permissions aren't set through this path, the identity isn't utilized. -// Ownership is handled elsewhere, but in the future could be support here -// too. -func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting bool) error { - if err := system.MkdirAll(path, mode); err != nil { - return err - } - return nil -} - -// CanAccess takes a valid (existing) directory and a uid, gid pair and determines -// if that uid, gid pair has access (execute bit) to the directory -// Windows does not require/support this function, so always return true -func CanAccess(path string, identity Identity) bool { - return true -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go b/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go deleted file mode 100644 index bf7ae056..00000000 --- a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go +++ /dev/null @@ -1,164 +0,0 @@ -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "fmt" - "regexp" - "sort" - "strconv" - "strings" - "sync" -) - -// add a user and/or group to Linux /etc/passwd, /etc/group using standard -// Linux distribution commands: -// adduser --system --shell /bin/false --disabled-login --disabled-password --no-create-home --group -// useradd -r -s /bin/false - -var ( - once sync.Once - userCommand string - idOutRegexp = regexp.MustCompile(`uid=([0-9]+).*gid=([0-9]+)`) -) - -const ( - // default length for a UID/GID subordinate range - defaultRangeLen = 65536 - defaultRangeStart = 100000 -) - -// AddNamespaceRangesUser takes a username and uses the standard system -// utility to create a system user/group pair used to hold the -// /etc/sub{uid,gid} ranges which will be used for user namespace -// mapping ranges in containers. -func AddNamespaceRangesUser(name string) (int, int, error) { - if err := addUser(name); err != nil { - return -1, -1, fmt.Errorf("Error adding user %q: %v", name, err) - } - - // Query the system for the created uid and gid pair - out, err := execCmd("id", name) - if err != nil { - return -1, -1, fmt.Errorf("Error trying to find uid/gid for new user %q: %v", name, err) - } - matches := idOutRegexp.FindStringSubmatch(strings.TrimSpace(string(out))) - if len(matches) != 3 { - return -1, -1, fmt.Errorf("Can't find uid, gid from `id` output: %q", string(out)) - } - uid, err := strconv.Atoi(matches[1]) - if err != nil { - return -1, -1, fmt.Errorf("Can't convert found uid (%s) to int: %v", matches[1], err) - } - gid, err := strconv.Atoi(matches[2]) - if err != nil { - return -1, -1, fmt.Errorf("Can't convert found gid (%s) to int: %v", matches[2], err) - } - - // Now we need to create the subuid/subgid ranges for our new user/group (system users - // do not get auto-created ranges in subuid/subgid) - - if err := createSubordinateRanges(name); err != nil { - return -1, -1, fmt.Errorf("Couldn't create subordinate ID ranges: %v", err) - } - return uid, gid, nil -} - -func addUser(name string) error { - once.Do(func() { - // set up which commands are used for adding users/groups dependent on distro - if _, err := resolveBinary("adduser"); err == nil { - userCommand = "adduser" - } else if _, err := resolveBinary("useradd"); err == nil { - userCommand = "useradd" - } - }) - var args []string - switch userCommand { - case "adduser": - args = []string{"--system", "--shell", "/bin/false", "--no-create-home", "--disabled-login", "--disabled-password", "--group", name} - case "useradd": - args = []string{"-r", "-s", "/bin/false", name} - default: - return fmt.Errorf("cannot add user; no useradd/adduser binary found") - } - - if out, err := execCmd(userCommand, args...); err != nil { - return fmt.Errorf("failed to add user with error: %v; output: %q", err, string(out)) - } - return nil -} - -func createSubordinateRanges(name string) error { - - // first, we should verify that ranges weren't automatically created - // by the distro tooling - ranges, err := parseSubuid(name) - if err != nil { - return fmt.Errorf("Error while looking for subuid ranges for user %q: %v", name, err) - } - if len(ranges) == 0 { - // no UID ranges; let's create one - startID, err := findNextUIDRange() - if err != nil { - return fmt.Errorf("Can't find available subuid range: %v", err) - } - out, err := execCmd("usermod", "-v", fmt.Sprintf("%d-%d", startID, startID+defaultRangeLen-1), name) - if err != nil { - return fmt.Errorf("Unable to add subuid range to user: %q; output: %s, err: %v", name, out, err) - } - } - - ranges, err = parseSubgid(name) - if err != nil { - return fmt.Errorf("Error while looking for subgid ranges for user %q: %v", name, err) - } - if len(ranges) == 0 { - // no GID ranges; let's create one - startID, err := findNextGIDRange() - if err != nil { - return fmt.Errorf("Can't find available subgid range: %v", err) - } - out, err := execCmd("usermod", "-w", fmt.Sprintf("%d-%d", startID, startID+defaultRangeLen-1), name) - if err != nil { - return fmt.Errorf("Unable to add subgid range to user: %q; output: %s, err: %v", name, out, err) - } - } - return nil -} - -func findNextUIDRange() (int, error) { - ranges, err := parseSubuid("ALL") - if err != nil { - return -1, fmt.Errorf("Couldn't parse all ranges in /etc/subuid file: %v", err) - } - sort.Sort(ranges) - return findNextRangeStart(ranges) -} - -func findNextGIDRange() (int, error) { - ranges, err := parseSubgid("ALL") - if err != nil { - return -1, fmt.Errorf("Couldn't parse all ranges in /etc/subgid file: %v", err) - } - sort.Sort(ranges) - return findNextRangeStart(ranges) -} - -func findNextRangeStart(rangeList ranges) (int, error) { - startID := defaultRangeStart - for _, arange := range rangeList { - if wouldOverlap(arange, startID) { - startID = arange.Start + arange.Length - } - } - return startID, nil -} - -func wouldOverlap(arange subIDRange, ID int) bool { - low := ID - high := ID + defaultRangeLen - if (low >= arange.Start && low <= arange.Start+arange.Length) || - (high <= arange.Start+arange.Length && high >= arange.Start) { - return true - } - return false -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go b/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go deleted file mode 100644 index e7c4d631..00000000 --- a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !linux - -package idtools // import "github.com/docker/docker/pkg/idtools" - -import "fmt" - -// AddNamespaceRangesUser takes a name and finds an unused uid, gid pair -// and calls the appropriate helper function to add the group and then -// the user to the group in /etc/group and /etc/passwd respectively. -func AddNamespaceRangesUser(name string) (int, int, error) { - return -1, -1, fmt.Errorf("No support for adding users or groups on this OS") -} diff --git a/vendor/github.com/docker/docker/pkg/idtools/utils_unix.go b/vendor/github.com/docker/docker/pkg/idtools/utils_unix.go deleted file mode 100644 index 1e2d4a7a..00000000 --- a/vendor/github.com/docker/docker/pkg/idtools/utils_unix.go +++ /dev/null @@ -1,31 +0,0 @@ -// +build !windows - -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "fmt" - "os/exec" - "path/filepath" -) - -func resolveBinary(binname string) (string, error) { - binaryPath, err := exec.LookPath(binname) - if err != nil { - return "", err - } - resolvedPath, err := filepath.EvalSymlinks(binaryPath) - if err != nil { - return "", err - } - // only return no error if the final resolved binary basename - // matches what was searched for - if filepath.Base(resolvedPath) == binname { - return resolvedPath, nil - } - return "", fmt.Errorf("Binary %q does not resolve to a binary of that name in $PATH (%q)", binname, resolvedPath) -} - -func execCmd(cmd string, arg ...string) ([]byte, error) { - execCmd := exec.Command(cmd, arg...) - return execCmd.CombinedOutput() -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/buffer.go b/vendor/github.com/docker/docker/pkg/ioutils/buffer.go deleted file mode 100644 index 466f7929..00000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/buffer.go +++ /dev/null @@ -1,51 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "errors" - "io" -) - -var errBufferFull = errors.New("buffer is full") - -type fixedBuffer struct { - buf []byte - pos int - lastRead int -} - -func (b *fixedBuffer) Write(p []byte) (int, error) { - n := copy(b.buf[b.pos:cap(b.buf)], p) - b.pos += n - - if n < len(p) { - if b.pos == cap(b.buf) { - return n, errBufferFull - } - return n, io.ErrShortWrite - } - return n, nil -} - -func (b *fixedBuffer) Read(p []byte) (int, error) { - n := copy(p, b.buf[b.lastRead:b.pos]) - b.lastRead += n - return n, nil -} - -func (b *fixedBuffer) Len() int { - return b.pos - b.lastRead -} - -func (b *fixedBuffer) Cap() int { - return cap(b.buf) -} - -func (b *fixedBuffer) Reset() { - b.pos = 0 - b.lastRead = 0 - b.buf = b.buf[:0] -} - -func (b *fixedBuffer) String() string { - return string(b.buf[b.lastRead:b.pos]) -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go b/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go deleted file mode 100644 index 87514b64..00000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go +++ /dev/null @@ -1,187 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "errors" - "io" - "sync" -) - -// maxCap is the highest capacity to use in byte slices that buffer data. -const maxCap = 1e6 - -// minCap is the lowest capacity to use in byte slices that buffer data -const minCap = 64 - -// blockThreshold is the minimum number of bytes in the buffer which will cause -// a write to BytesPipe to block when allocating a new slice. -const blockThreshold = 1e6 - -var ( - // ErrClosed is returned when Write is called on a closed BytesPipe. - ErrClosed = errors.New("write to closed BytesPipe") - - bufPools = make(map[int]*sync.Pool) - bufPoolsLock sync.Mutex -) - -// BytesPipe is io.ReadWriteCloser which works similarly to pipe(queue). -// All written data may be read at most once. Also, BytesPipe allocates -// and releases new byte slices to adjust to current needs, so the buffer -// won't be overgrown after peak loads. -type BytesPipe struct { - mu sync.Mutex - wait *sync.Cond - buf []*fixedBuffer - bufLen int - closeErr error // error to return from next Read. set to nil if not closed. -} - -// NewBytesPipe creates new BytesPipe, initialized by specified slice. -// If buf is nil, then it will be initialized with slice which cap is 64. -// buf will be adjusted in a way that len(buf) == 0, cap(buf) == cap(buf). -func NewBytesPipe() *BytesPipe { - bp := &BytesPipe{} - bp.buf = append(bp.buf, getBuffer(minCap)) - bp.wait = sync.NewCond(&bp.mu) - return bp -} - -// Write writes p to BytesPipe. -// It can allocate new []byte slices in a process of writing. -func (bp *BytesPipe) Write(p []byte) (int, error) { - bp.mu.Lock() - - written := 0 -loop0: - for { - if bp.closeErr != nil { - bp.mu.Unlock() - return written, ErrClosed - } - - if len(bp.buf) == 0 { - bp.buf = append(bp.buf, getBuffer(64)) - } - // get the last buffer - b := bp.buf[len(bp.buf)-1] - - n, err := b.Write(p) - written += n - bp.bufLen += n - - // errBufferFull is an error we expect to get if the buffer is full - if err != nil && err != errBufferFull { - bp.wait.Broadcast() - bp.mu.Unlock() - return written, err - } - - // if there was enough room to write all then break - if len(p) == n { - break - } - - // more data: write to the next slice - p = p[n:] - - // make sure the buffer doesn't grow too big from this write - for bp.bufLen >= blockThreshold { - bp.wait.Wait() - if bp.closeErr != nil { - continue loop0 - } - } - - // add new byte slice to the buffers slice and continue writing - nextCap := b.Cap() * 2 - if nextCap > maxCap { - nextCap = maxCap - } - bp.buf = append(bp.buf, getBuffer(nextCap)) - } - bp.wait.Broadcast() - bp.mu.Unlock() - return written, nil -} - -// CloseWithError causes further reads from a BytesPipe to return immediately. -func (bp *BytesPipe) CloseWithError(err error) error { - bp.mu.Lock() - if err != nil { - bp.closeErr = err - } else { - bp.closeErr = io.EOF - } - bp.wait.Broadcast() - bp.mu.Unlock() - return nil -} - -// Close causes further reads from a BytesPipe to return immediately. -func (bp *BytesPipe) Close() error { - return bp.CloseWithError(nil) -} - -// Read reads bytes from BytesPipe. -// Data could be read only once. -func (bp *BytesPipe) Read(p []byte) (n int, err error) { - bp.mu.Lock() - if bp.bufLen == 0 { - if bp.closeErr != nil { - err := bp.closeErr - bp.mu.Unlock() - return 0, err - } - bp.wait.Wait() - if bp.bufLen == 0 && bp.closeErr != nil { - err := bp.closeErr - bp.mu.Unlock() - return 0, err - } - } - - for bp.bufLen > 0 { - b := bp.buf[0] - read, _ := b.Read(p) // ignore error since fixedBuffer doesn't really return an error - n += read - bp.bufLen -= read - - if b.Len() == 0 { - // it's empty so return it to the pool and move to the next one - returnBuffer(b) - bp.buf[0] = nil - bp.buf = bp.buf[1:] - } - - if len(p) == read { - break - } - - p = p[read:] - } - - bp.wait.Broadcast() - bp.mu.Unlock() - return -} - -func returnBuffer(b *fixedBuffer) { - b.Reset() - bufPoolsLock.Lock() - pool := bufPools[b.Cap()] - bufPoolsLock.Unlock() - if pool != nil { - pool.Put(b) - } -} - -func getBuffer(size int) *fixedBuffer { - bufPoolsLock.Lock() - pool, ok := bufPools[size] - if !ok { - pool = &sync.Pool{New: func() interface{} { return &fixedBuffer{buf: make([]byte, 0, size)} }} - bufPools[size] = pool - } - bufPoolsLock.Unlock() - return pool.Get().(*fixedBuffer) -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go b/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go deleted file mode 100644 index 534d66ac..00000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go +++ /dev/null @@ -1,162 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "io" - "io/ioutil" - "os" - "path/filepath" -) - -// NewAtomicFileWriter returns WriteCloser so that writing to it writes to a -// temporary file and closing it atomically changes the temporary file to -// destination path. Writing and closing concurrently is not allowed. -func NewAtomicFileWriter(filename string, perm os.FileMode) (io.WriteCloser, error) { - f, err := ioutil.TempFile(filepath.Dir(filename), ".tmp-"+filepath.Base(filename)) - if err != nil { - return nil, err - } - - abspath, err := filepath.Abs(filename) - if err != nil { - return nil, err - } - return &atomicFileWriter{ - f: f, - fn: abspath, - perm: perm, - }, nil -} - -// AtomicWriteFile atomically writes data to a file named by filename. -func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error { - f, err := NewAtomicFileWriter(filename, perm) - if err != nil { - return err - } - n, err := f.Write(data) - if err == nil && n < len(data) { - err = io.ErrShortWrite - f.(*atomicFileWriter).writeErr = err - } - if err1 := f.Close(); err == nil { - err = err1 - } - return err -} - -type atomicFileWriter struct { - f *os.File - fn string - writeErr error - perm os.FileMode -} - -func (w *atomicFileWriter) Write(dt []byte) (int, error) { - n, err := w.f.Write(dt) - if err != nil { - w.writeErr = err - } - return n, err -} - -func (w *atomicFileWriter) Close() (retErr error) { - defer func() { - if retErr != nil || w.writeErr != nil { - os.Remove(w.f.Name()) - } - }() - if err := w.f.Sync(); err != nil { - w.f.Close() - return err - } - if err := w.f.Close(); err != nil { - return err - } - if err := os.Chmod(w.f.Name(), w.perm); err != nil { - return err - } - if w.writeErr == nil { - return os.Rename(w.f.Name(), w.fn) - } - return nil -} - -// AtomicWriteSet is used to atomically write a set -// of files and ensure they are visible at the same time. -// Must be committed to a new directory. -type AtomicWriteSet struct { - root string -} - -// NewAtomicWriteSet creates a new atomic write set to -// atomically create a set of files. The given directory -// is used as the base directory for storing files before -// commit. If no temporary directory is given the system -// default is used. -func NewAtomicWriteSet(tmpDir string) (*AtomicWriteSet, error) { - td, err := ioutil.TempDir(tmpDir, "write-set-") - if err != nil { - return nil, err - } - - return &AtomicWriteSet{ - root: td, - }, nil -} - -// WriteFile writes a file to the set, guaranteeing the file -// has been synced. -func (ws *AtomicWriteSet) WriteFile(filename string, data []byte, perm os.FileMode) error { - f, err := ws.FileWriter(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) - if err != nil { - return err - } - n, err := f.Write(data) - if err == nil && n < len(data) { - err = io.ErrShortWrite - } - if err1 := f.Close(); err == nil { - err = err1 - } - return err -} - -type syncFileCloser struct { - *os.File -} - -func (w syncFileCloser) Close() error { - err := w.File.Sync() - if err1 := w.File.Close(); err == nil { - err = err1 - } - return err -} - -// FileWriter opens a file writer inside the set. The file -// should be synced and closed before calling commit. -func (ws *AtomicWriteSet) FileWriter(name string, flag int, perm os.FileMode) (io.WriteCloser, error) { - f, err := os.OpenFile(filepath.Join(ws.root, name), flag, perm) - if err != nil { - return nil, err - } - return syncFileCloser{f}, nil -} - -// Cancel cancels the set and removes all temporary data -// created in the set. -func (ws *AtomicWriteSet) Cancel() error { - return os.RemoveAll(ws.root) -} - -// Commit moves all created files to the target directory. The -// target directory must not exist and the parent of the target -// directory must exist. -func (ws *AtomicWriteSet) Commit(target string) error { - return os.Rename(ws.root, target) -} - -// String returns the location the set is writing to. -func (ws *AtomicWriteSet) String() string { - return ws.root -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/readers.go b/vendor/github.com/docker/docker/pkg/ioutils/readers.go deleted file mode 100644 index 1f657bd3..00000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/readers.go +++ /dev/null @@ -1,157 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "io" -) - -// ReadCloserWrapper wraps an io.Reader, and implements an io.ReadCloser -// It calls the given callback function when closed. It should be constructed -// with NewReadCloserWrapper -type ReadCloserWrapper struct { - io.Reader - closer func() error -} - -// Close calls back the passed closer function -func (r *ReadCloserWrapper) Close() error { - return r.closer() -} - -// NewReadCloserWrapper returns a new io.ReadCloser. -func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser { - return &ReadCloserWrapper{ - Reader: r, - closer: closer, - } -} - -type readerErrWrapper struct { - reader io.Reader - closer func() -} - -func (r *readerErrWrapper) Read(p []byte) (int, error) { - n, err := r.reader.Read(p) - if err != nil { - r.closer() - } - return n, err -} - -// NewReaderErrWrapper returns a new io.Reader. -func NewReaderErrWrapper(r io.Reader, closer func()) io.Reader { - return &readerErrWrapper{ - reader: r, - closer: closer, - } -} - -// HashData returns the sha256 sum of src. -func HashData(src io.Reader) (string, error) { - h := sha256.New() - if _, err := io.Copy(h, src); err != nil { - return "", err - } - return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil -} - -// OnEOFReader wraps an io.ReadCloser and a function -// the function will run at the end of file or close the file. -type OnEOFReader struct { - Rc io.ReadCloser - Fn func() -} - -func (r *OnEOFReader) Read(p []byte) (n int, err error) { - n, err = r.Rc.Read(p) - if err == io.EOF { - r.runFunc() - } - return -} - -// Close closes the file and run the function. -func (r *OnEOFReader) Close() error { - err := r.Rc.Close() - r.runFunc() - return err -} - -func (r *OnEOFReader) runFunc() { - if fn := r.Fn; fn != nil { - fn() - r.Fn = nil - } -} - -// cancelReadCloser wraps an io.ReadCloser with a context for cancelling read -// operations. -type cancelReadCloser struct { - cancel func() - pR *io.PipeReader // Stream to read from - pW *io.PipeWriter -} - -// NewCancelReadCloser creates a wrapper that closes the ReadCloser when the -// context is cancelled. The returned io.ReadCloser must be closed when it is -// no longer needed. -func NewCancelReadCloser(ctx context.Context, in io.ReadCloser) io.ReadCloser { - pR, pW := io.Pipe() - - // Create a context used to signal when the pipe is closed - doneCtx, cancel := context.WithCancel(context.Background()) - - p := &cancelReadCloser{ - cancel: cancel, - pR: pR, - pW: pW, - } - - go func() { - _, err := io.Copy(pW, in) - select { - case <-ctx.Done(): - // If the context was closed, p.closeWithError - // was already called. Calling it again would - // change the error that Read returns. - default: - p.closeWithError(err) - } - in.Close() - }() - go func() { - for { - select { - case <-ctx.Done(): - p.closeWithError(ctx.Err()) - case <-doneCtx.Done(): - return - } - } - }() - - return p -} - -// Read wraps the Read method of the pipe that provides data from the wrapped -// ReadCloser. -func (p *cancelReadCloser) Read(buf []byte) (n int, err error) { - return p.pR.Read(buf) -} - -// closeWithError closes the wrapper and its underlying reader. It will -// cause future calls to Read to return err. -func (p *cancelReadCloser) closeWithError(err error) { - p.pW.CloseWithError(err) - p.cancel() -} - -// Close closes the wrapper its underlying reader. It will cause -// future calls to Read to return io.EOF. -func (p *cancelReadCloser) Close() error { - p.closeWithError(io.EOF) - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go b/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go deleted file mode 100644 index dc894f91..00000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !windows - -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import "io/ioutil" - -// TempDir on Unix systems is equivalent to ioutil.TempDir. -func TempDir(dir, prefix string) (string, error) { - return ioutil.TempDir(dir, prefix) -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go b/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go deleted file mode 100644 index ecaba2e3..00000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go +++ /dev/null @@ -1,16 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "io/ioutil" - - "github.com/docker/docker/pkg/longpath" -) - -// TempDir is the equivalent of ioutil.TempDir, except that the result is in Windows longpath format. -func TempDir(dir, prefix string) (string, error) { - tempDir, err := ioutil.TempDir(dir, prefix) - if err != nil { - return "", err - } - return longpath.AddPrefix(tempDir), nil -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/writeflusher.go b/vendor/github.com/docker/docker/pkg/ioutils/writeflusher.go deleted file mode 100644 index 91b8d182..00000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/writeflusher.go +++ /dev/null @@ -1,92 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "io" - "sync" -) - -// WriteFlusher wraps the Write and Flush operation ensuring that every write -// is a flush. In addition, the Close method can be called to intercept -// Read/Write calls if the targets lifecycle has already ended. -type WriteFlusher struct { - w io.Writer - flusher flusher - flushed chan struct{} - flushedOnce sync.Once - closed chan struct{} - closeLock sync.Mutex -} - -type flusher interface { - Flush() -} - -var errWriteFlusherClosed = io.EOF - -func (wf *WriteFlusher) Write(b []byte) (n int, err error) { - select { - case <-wf.closed: - return 0, errWriteFlusherClosed - default: - } - - n, err = wf.w.Write(b) - wf.Flush() // every write is a flush. - return n, err -} - -// Flush the stream immediately. -func (wf *WriteFlusher) Flush() { - select { - case <-wf.closed: - return - default: - } - - wf.flushedOnce.Do(func() { - close(wf.flushed) - }) - wf.flusher.Flush() -} - -// Flushed returns the state of flushed. -// If it's flushed, return true, or else it return false. -func (wf *WriteFlusher) Flushed() bool { - // BUG(stevvooe): Remove this method. Its use is inherently racy. Seems to - // be used to detect whether or a response code has been issued or not. - // Another hook should be used instead. - var flushed bool - select { - case <-wf.flushed: - flushed = true - default: - } - return flushed -} - -// Close closes the write flusher, disallowing any further writes to the -// target. After the flusher is closed, all calls to write or flush will -// result in an error. -func (wf *WriteFlusher) Close() error { - wf.closeLock.Lock() - defer wf.closeLock.Unlock() - - select { - case <-wf.closed: - return errWriteFlusherClosed - default: - close(wf.closed) - } - return nil -} - -// NewWriteFlusher returns a new WriteFlusher. -func NewWriteFlusher(w io.Writer) *WriteFlusher { - var fl flusher - if f, ok := w.(flusher); ok { - fl = f - } else { - fl = &NopFlusher{} - } - return &WriteFlusher{w: w, flusher: fl, closed: make(chan struct{}), flushed: make(chan struct{})} -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/writers.go b/vendor/github.com/docker/docker/pkg/ioutils/writers.go deleted file mode 100644 index 61c67949..00000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/writers.go +++ /dev/null @@ -1,66 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import "io" - -// NopWriter represents a type which write operation is nop. -type NopWriter struct{} - -func (*NopWriter) Write(buf []byte) (int, error) { - return len(buf), nil -} - -type nopWriteCloser struct { - io.Writer -} - -func (w *nopWriteCloser) Close() error { return nil } - -// NopWriteCloser returns a nopWriteCloser. -func NopWriteCloser(w io.Writer) io.WriteCloser { - return &nopWriteCloser{w} -} - -// NopFlusher represents a type which flush operation is nop. -type NopFlusher struct{} - -// Flush is a nop operation. -func (f *NopFlusher) Flush() {} - -type writeCloserWrapper struct { - io.Writer - closer func() error -} - -func (r *writeCloserWrapper) Close() error { - return r.closer() -} - -// NewWriteCloserWrapper returns a new io.WriteCloser. -func NewWriteCloserWrapper(r io.Writer, closer func() error) io.WriteCloser { - return &writeCloserWrapper{ - Writer: r, - closer: closer, - } -} - -// WriteCounter wraps a concrete io.Writer and hold a count of the number -// of bytes written to the writer during a "session". -// This can be convenient when write return is masked -// (e.g., json.Encoder.Encode()) -type WriteCounter struct { - Count int64 - Writer io.Writer -} - -// NewWriteCounter returns a new WriteCounter. -func NewWriteCounter(w io.Writer) *WriteCounter { - return &WriteCounter{ - Writer: w, - } -} - -func (wc *WriteCounter) Write(p []byte) (count int, err error) { - count, err = wc.Writer.Write(p) - wc.Count += int64(count) - return -} diff --git a/vendor/github.com/docker/docker/pkg/longpath/longpath.go b/vendor/github.com/docker/docker/pkg/longpath/longpath.go deleted file mode 100644 index 4177affb..00000000 --- a/vendor/github.com/docker/docker/pkg/longpath/longpath.go +++ /dev/null @@ -1,26 +0,0 @@ -// longpath introduces some constants and helper functions for handling long paths -// in Windows, which are expected to be prepended with `\\?\` and followed by either -// a drive letter, a UNC server\share, or a volume identifier. - -package longpath // import "github.com/docker/docker/pkg/longpath" - -import ( - "strings" -) - -// Prefix is the longpath prefix for Windows file paths. -const Prefix = `\\?\` - -// AddPrefix will add the Windows long path prefix to the path provided if -// it does not already have it. -func AddPrefix(path string) string { - if !strings.HasPrefix(path, Prefix) { - if strings.HasPrefix(path, `\\`) { - // This is a UNC path, so we need to add 'UNC' to the path as well. - path = Prefix + `UNC` + path[1:] - } else { - path = Prefix + path - } - } - return path -} diff --git a/vendor/github.com/docker/docker/pkg/pools/pools.go b/vendor/github.com/docker/docker/pkg/pools/pools.go deleted file mode 100644 index 3792c67a..00000000 --- a/vendor/github.com/docker/docker/pkg/pools/pools.go +++ /dev/null @@ -1,137 +0,0 @@ -// Package pools provides a collection of pools which provide various -// data types with buffers. These can be used to lower the number of -// memory allocations and reuse buffers. -// -// New pools should be added to this package to allow them to be -// shared across packages. -// -// Utility functions which operate on pools should be added to this -// package to allow them to be reused. -package pools // import "github.com/docker/docker/pkg/pools" - -import ( - "bufio" - "io" - "sync" - - "github.com/docker/docker/pkg/ioutils" -) - -const buffer32K = 32 * 1024 - -var ( - // BufioReader32KPool is a pool which returns bufio.Reader with a 32K buffer. - BufioReader32KPool = newBufioReaderPoolWithSize(buffer32K) - // BufioWriter32KPool is a pool which returns bufio.Writer with a 32K buffer. - BufioWriter32KPool = newBufioWriterPoolWithSize(buffer32K) - buffer32KPool = newBufferPoolWithSize(buffer32K) -) - -// BufioReaderPool is a bufio reader that uses sync.Pool. -type BufioReaderPool struct { - pool sync.Pool -} - -// newBufioReaderPoolWithSize is unexported because new pools should be -// added here to be shared where required. -func newBufioReaderPoolWithSize(size int) *BufioReaderPool { - return &BufioReaderPool{ - pool: sync.Pool{ - New: func() interface{} { return bufio.NewReaderSize(nil, size) }, - }, - } -} - -// Get returns a bufio.Reader which reads from r. The buffer size is that of the pool. -func (bufPool *BufioReaderPool) Get(r io.Reader) *bufio.Reader { - buf := bufPool.pool.Get().(*bufio.Reader) - buf.Reset(r) - return buf -} - -// Put puts the bufio.Reader back into the pool. -func (bufPool *BufioReaderPool) Put(b *bufio.Reader) { - b.Reset(nil) - bufPool.pool.Put(b) -} - -type bufferPool struct { - pool sync.Pool -} - -func newBufferPoolWithSize(size int) *bufferPool { - return &bufferPool{ - pool: sync.Pool{ - New: func() interface{} { s := make([]byte, size); return &s }, - }, - } -} - -func (bp *bufferPool) Get() *[]byte { - return bp.pool.Get().(*[]byte) -} - -func (bp *bufferPool) Put(b *[]byte) { - bp.pool.Put(b) -} - -// Copy is a convenience wrapper which uses a buffer to avoid allocation in io.Copy. -func Copy(dst io.Writer, src io.Reader) (written int64, err error) { - buf := buffer32KPool.Get() - written, err = io.CopyBuffer(dst, src, *buf) - buffer32KPool.Put(buf) - return -} - -// NewReadCloserWrapper returns a wrapper which puts the bufio.Reader back -// into the pool and closes the reader if it's an io.ReadCloser. -func (bufPool *BufioReaderPool) NewReadCloserWrapper(buf *bufio.Reader, r io.Reader) io.ReadCloser { - return ioutils.NewReadCloserWrapper(r, func() error { - if readCloser, ok := r.(io.ReadCloser); ok { - readCloser.Close() - } - bufPool.Put(buf) - return nil - }) -} - -// BufioWriterPool is a bufio writer that uses sync.Pool. -type BufioWriterPool struct { - pool sync.Pool -} - -// newBufioWriterPoolWithSize is unexported because new pools should be -// added here to be shared where required. -func newBufioWriterPoolWithSize(size int) *BufioWriterPool { - return &BufioWriterPool{ - pool: sync.Pool{ - New: func() interface{} { return bufio.NewWriterSize(nil, size) }, - }, - } -} - -// Get returns a bufio.Writer which writes to w. The buffer size is that of the pool. -func (bufPool *BufioWriterPool) Get(w io.Writer) *bufio.Writer { - buf := bufPool.pool.Get().(*bufio.Writer) - buf.Reset(w) - return buf -} - -// Put puts the bufio.Writer back into the pool. -func (bufPool *BufioWriterPool) Put(b *bufio.Writer) { - b.Reset(nil) - bufPool.pool.Put(b) -} - -// NewWriteCloserWrapper returns a wrapper which puts the bufio.Writer back -// into the pool and closes the writer if it's an io.Writecloser. -func (bufPool *BufioWriterPool) NewWriteCloserWrapper(buf *bufio.Writer, w io.Writer) io.WriteCloser { - return ioutils.NewWriteCloserWrapper(w, func() error { - buf.Flush() - if writeCloser, ok := w.(io.WriteCloser); ok { - writeCloser.Close() - } - bufPool.Put(buf) - return nil - }) -} diff --git a/vendor/github.com/docker/docker/pkg/system/args_windows.go b/vendor/github.com/docker/docker/pkg/system/args_windows.go deleted file mode 100644 index b7c9487a..00000000 --- a/vendor/github.com/docker/docker/pkg/system/args_windows.go +++ /dev/null @@ -1,16 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "strings" - - "golang.org/x/sys/windows" -) - -// EscapeArgs makes a Windows-style escaped command line from a set of arguments -func EscapeArgs(args []string) string { - escapedArgs := make([]string, len(args)) - for i, a := range args { - escapedArgs[i] = windows.EscapeArg(a) - } - return strings.Join(escapedArgs, " ") -} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes.go b/vendor/github.com/docker/docker/pkg/system/chtimes.go deleted file mode 100644 index c26a4e24..00000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes.go +++ /dev/null @@ -1,31 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "time" -) - -// Chtimes changes the access time and modified time of a file at the given path -func Chtimes(name string, atime time.Time, mtime time.Time) error { - unixMinTime := time.Unix(0, 0) - unixMaxTime := maxTime - - // If the modified time is prior to the Unix Epoch, or after the - // end of Unix Time, os.Chtimes has undefined behavior - // default to Unix Epoch in this case, just in case - - if atime.Before(unixMinTime) || atime.After(unixMaxTime) { - atime = unixMinTime - } - - if mtime.Before(unixMinTime) || mtime.After(unixMaxTime) { - mtime = unixMinTime - } - - if err := os.Chtimes(name, atime, mtime); err != nil { - return err - } - - // Take platform specific action for setting create time. - return setCTime(name, mtime) -} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes_nowindows.go b/vendor/github.com/docker/docker/pkg/system/chtimes_nowindows.go deleted file mode 100644 index d5fab96f..00000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes_nowindows.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "time" -) - -// setCTime will set the create time on a file. On Unix, the create -// time is updated as a side effect of setting the modified time, so -// no action is required. -func setCTime(path string, ctime time.Time) error { - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go b/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go deleted file mode 100644 index 6664b8bc..00000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go +++ /dev/null @@ -1,26 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "time" - - "golang.org/x/sys/windows" -) - -// setCTime will set the create time on a file. On Windows, this requires -// calling SetFileTime and explicitly including the create time. -func setCTime(path string, ctime time.Time) error { - ctimespec := windows.NsecToTimespec(ctime.UnixNano()) - pathp, e := windows.UTF16PtrFromString(path) - if e != nil { - return e - } - h, e := windows.CreateFile(pathp, - windows.FILE_WRITE_ATTRIBUTES, windows.FILE_SHARE_WRITE, nil, - windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0) - if e != nil { - return e - } - defer windows.Close(h) - c := windows.NsecToFiletime(windows.TimespecToNsec(ctimespec)) - return windows.SetFileTime(h, &c, nil, nil) -} diff --git a/vendor/github.com/docker/docker/pkg/system/errors.go b/vendor/github.com/docker/docker/pkg/system/errors.go deleted file mode 100644 index 2573d716..00000000 --- a/vendor/github.com/docker/docker/pkg/system/errors.go +++ /dev/null @@ -1,13 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "errors" -) - -var ( - // ErrNotSupportedPlatform means the platform is not supported. - ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") - - // ErrNotSupportedOperatingSystem means the operating system is not supported. - ErrNotSupportedOperatingSystem = errors.New("operating system is not supported") -) diff --git a/vendor/github.com/docker/docker/pkg/system/exitcode.go b/vendor/github.com/docker/docker/pkg/system/exitcode.go deleted file mode 100644 index 4ba8fe35..00000000 --- a/vendor/github.com/docker/docker/pkg/system/exitcode.go +++ /dev/null @@ -1,19 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "fmt" - "os/exec" - "syscall" -) - -// GetExitCode returns the ExitStatus of the specified error if its type is -// exec.ExitError, returns 0 and an error otherwise. -func GetExitCode(err error) (int, error) { - exitCode := 0 - if exiterr, ok := err.(*exec.ExitError); ok { - if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok { - return procExit.ExitStatus(), nil - } - } - return exitCode, fmt.Errorf("failed to get exit code") -} diff --git a/vendor/github.com/docker/docker/pkg/system/filesys_unix.go b/vendor/github.com/docker/docker/pkg/system/filesys_unix.go deleted file mode 100644 index dcee3e9f..00000000 --- a/vendor/github.com/docker/docker/pkg/system/filesys_unix.go +++ /dev/null @@ -1,67 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "io/ioutil" - "os" - "path/filepath" -) - -// MkdirAllWithACL is a wrapper for os.MkdirAll on unix systems. -func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error { - return os.MkdirAll(path, perm) -} - -// MkdirAll creates a directory named path along with any necessary parents, -// with permission specified by attribute perm for all dir created. -func MkdirAll(path string, perm os.FileMode) error { - return os.MkdirAll(path, perm) -} - -// IsAbs is a platform-specific wrapper for filepath.IsAbs. -func IsAbs(path string) bool { - return filepath.IsAbs(path) -} - -// The functions below here are wrappers for the equivalents in the os and ioutils packages. -// They are passthrough on Unix platforms, and only relevant on Windows. - -// CreateSequential creates the named file with mode 0666 (before umask), truncating -// it if it already exists. If successful, methods on the returned -// File can be used for I/O; the associated file descriptor has mode -// O_RDWR. -// If there is an error, it will be of type *PathError. -func CreateSequential(name string) (*os.File, error) { - return os.Create(name) -} - -// OpenSequential opens the named file for reading. If successful, methods on -// the returned file can be used for reading; the associated file -// descriptor has mode O_RDONLY. -// If there is an error, it will be of type *PathError. -func OpenSequential(name string) (*os.File, error) { - return os.Open(name) -} - -// OpenFileSequential is the generalized open call; most users will use Open -// or Create instead. It opens the named file with specified flag -// (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, -// methods on the returned File can be used for I/O. -// If there is an error, it will be of type *PathError. -func OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) { - return os.OpenFile(name, flag, perm) -} - -// TempFileSequential creates a new temporary file in the directory dir -// with a name beginning with prefix, opens the file for reading -// and writing, and returns the resulting *os.File. -// If dir is the empty string, TempFile uses the default directory -// for temporary files (see os.TempDir). -// Multiple programs calling TempFile simultaneously -// will not choose the same file. The caller can use f.Name() -// to find the pathname of the file. It is the caller's responsibility -// to remove the file when no longer needed. -func TempFileSequential(dir, prefix string) (f *os.File, err error) { - return ioutil.TempFile(dir, prefix) -} diff --git a/vendor/github.com/docker/docker/pkg/system/filesys_windows.go b/vendor/github.com/docker/docker/pkg/system/filesys_windows.go deleted file mode 100644 index b4646277..00000000 --- a/vendor/github.com/docker/docker/pkg/system/filesys_windows.go +++ /dev/null @@ -1,292 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "path/filepath" - "regexp" - "strconv" - "strings" - "sync" - "syscall" - "time" - "unsafe" - - "golang.org/x/sys/windows" -) - -const ( - // SddlAdministratorsLocalSystem is local administrators plus NT AUTHORITY\System - SddlAdministratorsLocalSystem = "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)" -) - -// MkdirAllWithACL is a wrapper for MkdirAll that creates a directory -// with an appropriate SDDL defined ACL. -func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error { - return mkdirall(path, true, sddl) -} - -// MkdirAll implementation that is volume path aware for Windows. It can be used -// as a drop-in replacement for os.MkdirAll() -func MkdirAll(path string, _ os.FileMode) error { - return mkdirall(path, false, "") -} - -// mkdirall is a custom version of os.MkdirAll modified for use on Windows -// so that it is both volume path aware, and can create a directory with -// a DACL. -func mkdirall(path string, applyACL bool, sddl string) error { - if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) { - return nil - } - - // The rest of this method is largely copied from os.MkdirAll and should be kept - // as-is to ensure compatibility. - - // Fast path: if we can tell whether path is a directory or file, stop with success or error. - dir, err := os.Stat(path) - if err == nil { - if dir.IsDir() { - return nil - } - return &os.PathError{ - Op: "mkdir", - Path: path, - Err: syscall.ENOTDIR, - } - } - - // Slow path: make sure parent exists and then call Mkdir for path. - i := len(path) - for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. - i-- - } - - j := i - for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. - j-- - } - - if j > 1 { - // Create parent - err = mkdirall(path[0:j-1], false, sddl) - if err != nil { - return err - } - } - - // Parent now exists; invoke os.Mkdir or mkdirWithACL and use its result. - if applyACL { - err = mkdirWithACL(path, sddl) - } else { - err = os.Mkdir(path, 0) - } - - if err != nil { - // Handle arguments like "foo/." by - // double-checking that directory doesn't exist. - dir, err1 := os.Lstat(path) - if err1 == nil && dir.IsDir() { - return nil - } - return err - } - return nil -} - -// mkdirWithACL creates a new directory. If there is an error, it will be of -// type *PathError. . -// -// This is a modified and combined version of os.Mkdir and windows.Mkdir -// in golang to cater for creating a directory am ACL permitting full -// access, with inheritance, to any subfolder/file for Built-in Administrators -// and Local System. -func mkdirWithACL(name string, sddl string) error { - sa := windows.SecurityAttributes{Length: 0} - sd, err := windows.SecurityDescriptorFromString(sddl) - if err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - sa.SecurityDescriptor = sd - - namep, err := windows.UTF16PtrFromString(name) - if err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - - e := windows.CreateDirectory(namep, &sa) - if e != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: e} - } - return nil -} - -// IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows, -// golang filepath.IsAbs does not consider a path \windows\system32 as absolute -// as it doesn't start with a drive-letter/colon combination. However, in -// docker we need to verify things such as WORKDIR /windows/system32 in -// a Dockerfile (which gets translated to \windows\system32 when being processed -// by the daemon. This SHOULD be treated as absolute from a docker processing -// perspective. -func IsAbs(path string) bool { - if filepath.IsAbs(path) || strings.HasPrefix(path, string(os.PathSeparator)) { - return true - } - return false -} - -// The origin of the functions below here are the golang OS and windows packages, -// slightly modified to only cope with files, not directories due to the -// specific use case. -// -// The alteration is to allow a file on Windows to be opened with -// FILE_FLAG_SEQUENTIAL_SCAN (particular for docker load), to avoid eating -// the standby list, particularly when accessing large files such as layer.tar. - -// CreateSequential creates the named file with mode 0666 (before umask), truncating -// it if it already exists. If successful, methods on the returned -// File can be used for I/O; the associated file descriptor has mode -// O_RDWR. -// If there is an error, it will be of type *PathError. -func CreateSequential(name string) (*os.File, error) { - return OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0) -} - -// OpenSequential opens the named file for reading. If successful, methods on -// the returned file can be used for reading; the associated file -// descriptor has mode O_RDONLY. -// If there is an error, it will be of type *PathError. -func OpenSequential(name string) (*os.File, error) { - return OpenFileSequential(name, os.O_RDONLY, 0) -} - -// OpenFileSequential is the generalized open call; most users will use Open -// or Create instead. -// If there is an error, it will be of type *PathError. -func OpenFileSequential(name string, flag int, _ os.FileMode) (*os.File, error) { - if name == "" { - return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT} - } - r, errf := windowsOpenFileSequential(name, flag, 0) - if errf == nil { - return r, nil - } - return nil, &os.PathError{Op: "open", Path: name, Err: errf} -} - -func windowsOpenFileSequential(name string, flag int, _ os.FileMode) (file *os.File, err error) { - r, e := windowsOpenSequential(name, flag|windows.O_CLOEXEC, 0) - if e != nil { - return nil, e - } - return os.NewFile(uintptr(r), name), nil -} - -func makeInheritSa() *windows.SecurityAttributes { - var sa windows.SecurityAttributes - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - return &sa -} - -func windowsOpenSequential(path string, mode int, _ uint32) (fd windows.Handle, err error) { - if len(path) == 0 { - return windows.InvalidHandle, windows.ERROR_FILE_NOT_FOUND - } - pathp, err := windows.UTF16PtrFromString(path) - if err != nil { - return windows.InvalidHandle, err - } - var access uint32 - switch mode & (windows.O_RDONLY | windows.O_WRONLY | windows.O_RDWR) { - case windows.O_RDONLY: - access = windows.GENERIC_READ - case windows.O_WRONLY: - access = windows.GENERIC_WRITE - case windows.O_RDWR: - access = windows.GENERIC_READ | windows.GENERIC_WRITE - } - if mode&windows.O_CREAT != 0 { - access |= windows.GENERIC_WRITE - } - if mode&windows.O_APPEND != 0 { - access &^= windows.GENERIC_WRITE - access |= windows.FILE_APPEND_DATA - } - sharemode := uint32(windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE) - var sa *windows.SecurityAttributes - if mode&windows.O_CLOEXEC == 0 { - sa = makeInheritSa() - } - var createmode uint32 - switch { - case mode&(windows.O_CREAT|windows.O_EXCL) == (windows.O_CREAT | windows.O_EXCL): - createmode = windows.CREATE_NEW - case mode&(windows.O_CREAT|windows.O_TRUNC) == (windows.O_CREAT | windows.O_TRUNC): - createmode = windows.CREATE_ALWAYS - case mode&windows.O_CREAT == windows.O_CREAT: - createmode = windows.OPEN_ALWAYS - case mode&windows.O_TRUNC == windows.O_TRUNC: - createmode = windows.TRUNCATE_EXISTING - default: - createmode = windows.OPEN_EXISTING - } - // Use FILE_FLAG_SEQUENTIAL_SCAN rather than FILE_ATTRIBUTE_NORMAL as implemented in golang. - // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx - const fileFlagSequentialScan = 0x08000000 // FILE_FLAG_SEQUENTIAL_SCAN - h, e := windows.CreateFile(pathp, access, sharemode, sa, createmode, fileFlagSequentialScan, 0) - return h, e -} - -// Helpers for TempFileSequential -var rand uint32 -var randmu sync.Mutex - -func reseed() uint32 { - return uint32(time.Now().UnixNano() + int64(os.Getpid())) -} -func nextSuffix() string { - randmu.Lock() - r := rand - if r == 0 { - r = reseed() - } - r = r*1664525 + 1013904223 // constants from Numerical Recipes - rand = r - randmu.Unlock() - return strconv.Itoa(int(1e9 + r%1e9))[1:] -} - -// TempFileSequential is a copy of ioutil.TempFile, modified to use sequential -// file access. Below is the original comment from golang: -// TempFile creates a new temporary file in the directory dir -// with a name beginning with prefix, opens the file for reading -// and writing, and returns the resulting *os.File. -// If dir is the empty string, TempFile uses the default directory -// for temporary files (see os.TempDir). -// Multiple programs calling TempFile simultaneously -// will not choose the same file. The caller can use f.Name() -// to find the pathname of the file. It is the caller's responsibility -// to remove the file when no longer needed. -func TempFileSequential(dir, prefix string) (f *os.File, err error) { - if dir == "" { - dir = os.TempDir() - } - - nconflict := 0 - for i := 0; i < 10000; i++ { - name := filepath.Join(dir, prefix+nextSuffix()) - f, err = OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) - if os.IsExist(err) { - if nconflict++; nconflict > 10 { - randmu.Lock() - rand = reseed() - randmu.Unlock() - } - continue - } - break - } - return -} diff --git a/vendor/github.com/docker/docker/pkg/system/init.go b/vendor/github.com/docker/docker/pkg/system/init.go deleted file mode 100644 index a17597aa..00000000 --- a/vendor/github.com/docker/docker/pkg/system/init.go +++ /dev/null @@ -1,22 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "syscall" - "time" - "unsafe" -) - -// Used by chtimes -var maxTime time.Time - -func init() { - // chtimes initialization - if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 { - // This is a 64 bit timespec - // os.Chtimes limits time to the following - maxTime = time.Unix(0, 1<<63-1) - } else { - // This is a 32 bit timespec - maxTime = time.Unix(1<<31-1, 0) - } -} diff --git a/vendor/github.com/docker/docker/pkg/system/init_windows.go b/vendor/github.com/docker/docker/pkg/system/init_windows.go deleted file mode 100644 index a91288c6..00000000 --- a/vendor/github.com/docker/docker/pkg/system/init_windows.go +++ /dev/null @@ -1,29 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - - "github.com/sirupsen/logrus" -) - -var ( - // containerdRuntimeSupported determines if ContainerD should be the runtime. - // As of March 2019, this is an experimental feature. - containerdRuntimeSupported = false -) - -// InitContainerdRuntime sets whether to use ContainerD for runtime -// on Windows. This is an experimental feature still in development, and -// also requires an environment variable to be set (so as not to turn the -// feature on from simply experimental which would also mean LCOW. -func InitContainerdRuntime(experimental bool, cdPath string) { - if experimental && len(cdPath) > 0 && len(os.Getenv("DOCKER_WINDOWS_CONTAINERD_RUNTIME")) > 0 { - logrus.Warnf("Using ContainerD runtime. This feature is experimental") - containerdRuntimeSupported = true - } -} - -// ContainerdRuntimeSupported returns true if the use of ContainerD runtime is supported. -func ContainerdRuntimeSupported() bool { - return containerdRuntimeSupported -} diff --git a/vendor/github.com/docker/docker/pkg/system/lcow.go b/vendor/github.com/docker/docker/pkg/system/lcow.go deleted file mode 100644 index 0f00028f..00000000 --- a/vendor/github.com/docker/docker/pkg/system/lcow.go +++ /dev/null @@ -1,48 +0,0 @@ -// +build windows,!no_lcow - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "strings" - - "github.com/Microsoft/hcsshim/osversion" - specs "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" -) - -var ( - // lcowSupported determines if Linux Containers on Windows are supported. - lcowSupported = false -) - -// InitLCOW sets whether LCOW is supported or not. Requires RS5+ -func InitLCOW(experimental bool) { - if experimental && osversion.Build() >= osversion.RS5 { - lcowSupported = true - } -} - -func LCOWSupported() bool { - return lcowSupported -} - -// ValidatePlatform determines if a platform structure is valid. -// TODO This is a temporary windows-only function, should be replaced by -// comparison of worker capabilities -func ValidatePlatform(platform specs.Platform) error { - if !IsOSSupported(platform.OS) { - return errors.Errorf("unsupported os %s", platform.OS) - } - return nil -} - -// IsOSSupported determines if an operating system is supported by the host -func IsOSSupported(os string) bool { - if strings.EqualFold("windows", os) { - return true - } - if LCOWSupported() && strings.EqualFold(os, "linux") { - return true - } - return false -} diff --git a/vendor/github.com/docker/docker/pkg/system/lcow_unsupported.go b/vendor/github.com/docker/docker/pkg/system/lcow_unsupported.go deleted file mode 100644 index 3d3cf775..00000000 --- a/vendor/github.com/docker/docker/pkg/system/lcow_unsupported.go +++ /dev/null @@ -1,28 +0,0 @@ -// +build !windows windows,no_lcow - -package system // import "github.com/docker/docker/pkg/system" -import ( - "runtime" - "strings" - - specs "github.com/opencontainers/image-spec/specs-go/v1" -) - -// InitLCOW does nothing since LCOW is a windows only feature -func InitLCOW(_ bool) {} - -// LCOWSupported returns true if Linux containers on Windows are supported. -func LCOWSupported() bool { - return false -} - -// ValidatePlatform determines if a platform structure is valid. This function -// is used for LCOW, and is a no-op on non-windows platforms. -func ValidatePlatform(_ specs.Platform) error { - return nil -} - -// IsOSSupported determines if an operating system is supported by the host. -func IsOSSupported(os string) bool { - return strings.EqualFold(runtime.GOOS, os) -} diff --git a/vendor/github.com/docker/docker/pkg/system/lstat_unix.go b/vendor/github.com/docker/docker/pkg/system/lstat_unix.go deleted file mode 100644 index de5a1c0f..00000000 --- a/vendor/github.com/docker/docker/pkg/system/lstat_unix.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "syscall" -) - -// Lstat takes a path to a file and returns -// a system.StatT type pertaining to that file. -// -// Throws an error if the file does not exist -func Lstat(path string) (*StatT, error) { - s := &syscall.Stat_t{} - if err := syscall.Lstat(path, s); err != nil { - return nil, &os.PathError{Op: "Lstat", Path: path, Err: err} - } - return fromStatT(s) -} diff --git a/vendor/github.com/docker/docker/pkg/system/lstat_windows.go b/vendor/github.com/docker/docker/pkg/system/lstat_windows.go deleted file mode 100644 index 359c791d..00000000 --- a/vendor/github.com/docker/docker/pkg/system/lstat_windows.go +++ /dev/null @@ -1,14 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "os" - -// Lstat calls os.Lstat to get a fileinfo interface back. -// This is then copied into our own locally defined structure. -func Lstat(path string) (*StatT, error) { - fi, err := os.Lstat(path) - if err != nil { - return nil, err - } - - return fromStatT(&fi) -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo.go b/vendor/github.com/docker/docker/pkg/system/meminfo.go deleted file mode 100644 index 6667eb84..00000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo.go +++ /dev/null @@ -1,17 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -// MemInfo contains memory statistics of the host system. -type MemInfo struct { - // Total usable RAM (i.e. physical RAM minus a few reserved bits and the - // kernel binary code). - MemTotal int64 - - // Amount of free memory. - MemFree int64 - - // Total amount of swap space available. - SwapTotal int64 - - // Amount of swap space that is currently unused. - SwapFree int64 -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go b/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go deleted file mode 100644 index cd060eff..00000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go +++ /dev/null @@ -1,71 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "bufio" - "io" - "os" - "strconv" - "strings" - - units "github.com/docker/go-units" -) - -// ReadMemInfo retrieves memory statistics of the host system and returns a -// MemInfo type. -func ReadMemInfo() (*MemInfo, error) { - file, err := os.Open("/proc/meminfo") - if err != nil { - return nil, err - } - defer file.Close() - return parseMemInfo(file) -} - -// parseMemInfo parses the /proc/meminfo file into -// a MemInfo object given an io.Reader to the file. -// Throws error if there are problems reading from the file -func parseMemInfo(reader io.Reader) (*MemInfo, error) { - meminfo := &MemInfo{} - scanner := bufio.NewScanner(reader) - memAvailable := int64(-1) - for scanner.Scan() { - // Expected format: ["MemTotal:", "1234", "kB"] - parts := strings.Fields(scanner.Text()) - - // Sanity checks: Skip malformed entries. - if len(parts) < 3 || parts[2] != "kB" { - continue - } - - // Convert to bytes. - size, err := strconv.Atoi(parts[1]) - if err != nil { - continue - } - bytes := int64(size) * units.KiB - - switch parts[0] { - case "MemTotal:": - meminfo.MemTotal = bytes - case "MemFree:": - meminfo.MemFree = bytes - case "MemAvailable:": - memAvailable = bytes - case "SwapTotal:": - meminfo.SwapTotal = bytes - case "SwapFree:": - meminfo.SwapFree = bytes - } - - } - if memAvailable != -1 { - meminfo.MemFree = memAvailable - } - - // Handle errors that may have occurred during the reading of the file. - if err := scanner.Err(); err != nil { - return nil, err - } - - return meminfo, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go b/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go deleted file mode 100644 index 56f44942..00000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !linux,!windows - -package system // import "github.com/docker/docker/pkg/system" - -// ReadMemInfo is not supported on platforms other than linux and windows. -func ReadMemInfo() (*MemInfo, error) { - return nil, ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go b/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go deleted file mode 100644 index 6ed93f2f..00000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go +++ /dev/null @@ -1,45 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "unsafe" - - "golang.org/x/sys/windows" -) - -var ( - modkernel32 = windows.NewLazySystemDLL("kernel32.dll") - - procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx") -) - -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx -type memorystatusex struct { - dwLength uint32 - dwMemoryLoad uint32 - ullTotalPhys uint64 - ullAvailPhys uint64 - ullTotalPageFile uint64 - ullAvailPageFile uint64 - ullTotalVirtual uint64 - ullAvailVirtual uint64 - ullAvailExtendedVirtual uint64 -} - -// ReadMemInfo retrieves memory statistics of the host system and returns a -// MemInfo type. -func ReadMemInfo() (*MemInfo, error) { - msi := &memorystatusex{ - dwLength: 64, - } - r1, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msi))) - if r1 == 0 { - return &MemInfo{}, nil - } - return &MemInfo{ - MemTotal: int64(msi.ullTotalPhys), - MemFree: int64(msi.ullAvailPhys), - SwapTotal: int64(msi.ullTotalPageFile), - SwapFree: int64(msi.ullAvailPageFile), - }, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/mknod.go b/vendor/github.com/docker/docker/pkg/system/mknod.go deleted file mode 100644 index b132482e..00000000 --- a/vendor/github.com/docker/docker/pkg/system/mknod.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "golang.org/x/sys/unix" -) - -// Mknod creates a filesystem node (file, device special file or named pipe) named path -// with attributes specified by mode and dev. -func Mknod(path string, mode uint32, dev int) error { - return unix.Mknod(path, mode, dev) -} - -// Mkdev is used to build the value of linux devices (in /dev/) which specifies major -// and minor number of the newly created device special file. -// Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes. -// They are, from low to high: the lower 8 bits of the minor, then 12 bits of the major, -// then the top 12 bits of the minor. -func Mkdev(major int64, minor int64) uint32 { - return uint32(unix.Mkdev(uint32(major), uint32(minor))) -} diff --git a/vendor/github.com/docker/docker/pkg/system/mknod_windows.go b/vendor/github.com/docker/docker/pkg/system/mknod_windows.go deleted file mode 100644 index ec89d7a1..00000000 --- a/vendor/github.com/docker/docker/pkg/system/mknod_windows.go +++ /dev/null @@ -1,11 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -// Mknod is not implemented on Windows. -func Mknod(path string, mode uint32, dev int) error { - return ErrNotSupportedPlatform -} - -// Mkdev is not implemented on Windows. -func Mkdev(major int64, minor int64) uint32 { - panic("Mkdev not implemented on Windows.") -} diff --git a/vendor/github.com/docker/docker/pkg/system/path.go b/vendor/github.com/docker/docker/pkg/system/path.go deleted file mode 100644 index 64e89228..00000000 --- a/vendor/github.com/docker/docker/pkg/system/path.go +++ /dev/null @@ -1,64 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "fmt" - "path/filepath" - "runtime" - "strings" -) - -const defaultUnixPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - -// DefaultPathEnv is unix style list of directories to search for -// executables. Each directory is separated from the next by a colon -// ':' character . -func DefaultPathEnv(os string) string { - if runtime.GOOS == "windows" { - if os != runtime.GOOS { - return defaultUnixPathEnv - } - // Deliberately empty on Windows containers on Windows as the default path will be set by - // the container. Docker has no context of what the default path should be. - return "" - } - return defaultUnixPathEnv - -} - -// PathVerifier defines the subset of a PathDriver that CheckSystemDriveAndRemoveDriveLetter -// actually uses in order to avoid system depending on containerd/continuity. -type PathVerifier interface { - IsAbs(string) bool -} - -// CheckSystemDriveAndRemoveDriveLetter verifies that a path, if it includes a drive letter, -// is the system drive. -// On Linux: this is a no-op. -// On Windows: this does the following> -// CheckSystemDriveAndRemoveDriveLetter verifies and manipulates a Windows path. -// This is used, for example, when validating a user provided path in docker cp. -// If a drive letter is supplied, it must be the system drive. The drive letter -// is always removed. Also, it translates it to OS semantics (IOW / to \). We -// need the path in this syntax so that it can ultimately be concatenated with -// a Windows long-path which doesn't support drive-letters. Examples: -// C: --> Fail -// C:\ --> \ -// a --> a -// /a --> \a -// d:\ --> Fail -func CheckSystemDriveAndRemoveDriveLetter(path string, driver PathVerifier) (string, error) { - if runtime.GOOS != "windows" || LCOWSupported() { - return path, nil - } - - if len(path) == 2 && string(path[1]) == ":" { - return "", fmt.Errorf("No relative path specified in %q", path) - } - if !driver.IsAbs(path) || len(path) < 2 { - return filepath.FromSlash(path), nil - } - if string(path[1]) == ":" && !strings.EqualFold(string(path[0]), "c") { - return "", fmt.Errorf("The specified path is not on the system drive (C:)") - } - return filepath.FromSlash(path[2:]), nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/path_unix.go b/vendor/github.com/docker/docker/pkg/system/path_unix.go deleted file mode 100644 index b0b93196..00000000 --- a/vendor/github.com/docker/docker/pkg/system/path_unix.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -// GetLongPathName converts Windows short pathnames to full pathnames. -// For example C:\Users\ADMIN~1 --> C:\Users\Administrator. -// It is a no-op on non-Windows platforms -func GetLongPathName(path string) (string, error) { - return path, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/path_windows.go b/vendor/github.com/docker/docker/pkg/system/path_windows.go deleted file mode 100644 index 22a56136..00000000 --- a/vendor/github.com/docker/docker/pkg/system/path_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "golang.org/x/sys/windows" - -// GetLongPathName converts Windows short pathnames to full pathnames. -// For example C:\Users\ADMIN~1 --> C:\Users\Administrator. -// It is a no-op on non-Windows platforms -func GetLongPathName(path string) (string, error) { - // See https://groups.google.com/forum/#!topic/golang-dev/1tufzkruoTg - p, err := windows.UTF16FromString(path) - if err != nil { - return "", err - } - b := p // GetLongPathName says we can reuse buffer - n, err := windows.GetLongPathName(&p[0], &b[0], uint32(len(b))) - if err != nil { - return "", err - } - if n > uint32(len(b)) { - b = make([]uint16, n) - _, err = windows.GetLongPathName(&p[0], &b[0], uint32(len(b))) - if err != nil { - return "", err - } - } - return windows.UTF16ToString(b), nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/process_unix.go b/vendor/github.com/docker/docker/pkg/system/process_unix.go deleted file mode 100644 index 79aebb52..00000000 --- a/vendor/github.com/docker/docker/pkg/system/process_unix.go +++ /dev/null @@ -1,44 +0,0 @@ -// +build linux freebsd darwin - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "fmt" - "io/ioutil" - "strings" - "syscall" - - "golang.org/x/sys/unix" -) - -// IsProcessAlive returns true if process with a given pid is running. -func IsProcessAlive(pid int) bool { - err := unix.Kill(pid, syscall.Signal(0)) - if err == nil || err == unix.EPERM { - return true - } - - return false -} - -// KillProcess force-stops a process. -func KillProcess(pid int) { - unix.Kill(pid, unix.SIGKILL) -} - -// IsProcessZombie return true if process has a state with "Z" -// http://man7.org/linux/man-pages/man5/proc.5.html -func IsProcessZombie(pid int) (bool, error) { - statPath := fmt.Sprintf("/proc/%d/stat", pid) - dataBytes, err := ioutil.ReadFile(statPath) - if err != nil { - return false, err - } - data := string(dataBytes) - sdata := strings.SplitN(data, " ", 4) - if len(sdata) >= 3 && sdata[2] == "Z" { - return true, nil - } - - return false, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/process_windows.go b/vendor/github.com/docker/docker/pkg/system/process_windows.go deleted file mode 100644 index 09bdfa0c..00000000 --- a/vendor/github.com/docker/docker/pkg/system/process_windows.go +++ /dev/null @@ -1,18 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "os" - -// IsProcessAlive returns true if process with a given pid is running. -func IsProcessAlive(pid int) bool { - _, err := os.FindProcess(pid) - - return err == nil -} - -// KillProcess force-stops a process. -func KillProcess(pid int) { - p, err := os.FindProcess(pid) - if err == nil { - _ = p.Kill() - } -} diff --git a/vendor/github.com/docker/docker/pkg/system/rm.go b/vendor/github.com/docker/docker/pkg/system/rm.go deleted file mode 100644 index c5d80ebd..00000000 --- a/vendor/github.com/docker/docker/pkg/system/rm.go +++ /dev/null @@ -1,78 +0,0 @@ -// +build !darwin,!windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "syscall" - "time" - - "github.com/moby/sys/mount" - "github.com/pkg/errors" -) - -// EnsureRemoveAll wraps `os.RemoveAll` to check for specific errors that can -// often be remedied. -// Only use `EnsureRemoveAll` if you really want to make every effort to remove -// a directory. -// -// Because of the way `os.Remove` (and by extension `os.RemoveAll`) works, there -// can be a race between reading directory entries and then actually attempting -// to remove everything in the directory. -// These types of errors do not need to be returned since it's ok for the dir to -// be gone we can just retry the remove operation. -// -// This should not return a `os.ErrNotExist` kind of error under any circumstances -func EnsureRemoveAll(dir string) error { - notExistErr := make(map[string]bool) - - // track retries - exitOnErr := make(map[string]int) - maxRetry := 50 - - // Attempt to unmount anything beneath this dir first - mount.RecursiveUnmount(dir) - - for { - err := os.RemoveAll(dir) - if err == nil { - return nil - } - - pe, ok := err.(*os.PathError) - if !ok { - return err - } - - if os.IsNotExist(err) { - if notExistErr[pe.Path] { - return err - } - notExistErr[pe.Path] = true - - // There is a race where some subdir can be removed but after the parent - // dir entries have been read. - // So the path could be from `os.Remove(subdir)` - // If the reported non-existent path is not the passed in `dir` we - // should just retry, but otherwise return with no error. - if pe.Path == dir { - return nil - } - continue - } - - if pe.Err != syscall.EBUSY { - return err - } - - if e := mount.Unmount(pe.Path); e != nil { - return errors.Wrapf(e, "error while removing %s", dir) - } - - if exitOnErr[pe.Path] == maxRetry { - return err - } - exitOnErr[pe.Path]++ - time.Sleep(100 * time.Millisecond) - } -} diff --git a/vendor/github.com/docker/docker/pkg/system/rm_windows.go b/vendor/github.com/docker/docker/pkg/system/rm_windows.go deleted file mode 100644 index ed9c5dcb..00000000 --- a/vendor/github.com/docker/docker/pkg/system/rm_windows.go +++ /dev/null @@ -1,6 +0,0 @@ -package system - -import "os" - -// EnsureRemoveAll is an alias to os.RemoveAll on Windows -var EnsureRemoveAll = os.RemoveAll diff --git a/vendor/github.com/docker/docker/pkg/system/stat_bsd.go b/vendor/github.com/docker/docker/pkg/system/stat_bsd.go deleted file mode 100644 index ea55c3db..00000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_bsd.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build freebsd netbsd - -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtimespec}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_darwin.go b/vendor/github.com/docker/docker/pkg/system/stat_darwin.go deleted file mode 100644 index c1c0ee9f..00000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_darwin.go +++ /dev/null @@ -1,13 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtimespec}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_linux.go b/vendor/github.com/docker/docker/pkg/system/stat_linux.go deleted file mode 100644 index 17d5d131..00000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_linux.go +++ /dev/null @@ -1,20 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: s.Mode, - uid: s.Uid, - gid: s.Gid, - // the type is 32bit on mips - rdev: uint64(s.Rdev), // nolint: unconvert - mtim: s.Mtim}, nil -} - -// FromStatT converts a syscall.Stat_t type to a system.Stat_t type -// This is exposed on Linux as pkg/archive/changes uses it. -func FromStatT(s *syscall.Stat_t) (*StatT, error) { - return fromStatT(s) -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go b/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go deleted file mode 100644 index 756b92d1..00000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go +++ /dev/null @@ -1,13 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtim}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_solaris.go b/vendor/github.com/docker/docker/pkg/system/stat_solaris.go deleted file mode 100644 index 6a51ccd6..00000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_solaris.go +++ /dev/null @@ -1,13 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: s.Mode, - uid: s.Uid, - gid: s.Gid, - rdev: s.Rdev, - mtim: s.Mtim}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_unix.go b/vendor/github.com/docker/docker/pkg/system/stat_unix.go deleted file mode 100644 index 86bb6dd5..00000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_unix.go +++ /dev/null @@ -1,66 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "syscall" -) - -// StatT type contains status of a file. It contains metadata -// like permission, owner, group, size, etc about a file. -type StatT struct { - mode uint32 - uid uint32 - gid uint32 - rdev uint64 - size int64 - mtim syscall.Timespec -} - -// Mode returns file's permission mode. -func (s StatT) Mode() uint32 { - return s.mode -} - -// UID returns file's user id of owner. -func (s StatT) UID() uint32 { - return s.uid -} - -// GID returns file's group id of owner. -func (s StatT) GID() uint32 { - return s.gid -} - -// Rdev returns file's device ID (if it's special file). -func (s StatT) Rdev() uint64 { - return s.rdev -} - -// Size returns file's size. -func (s StatT) Size() int64 { - return s.size -} - -// Mtim returns file's last modification time. -func (s StatT) Mtim() syscall.Timespec { - return s.mtim -} - -// IsDir reports whether s describes a directory. -func (s StatT) IsDir() bool { - return s.mode&syscall.S_IFDIR != 0 -} - -// Stat takes a path to a file and returns -// a system.StatT type pertaining to that file. -// -// Throws an error if the file does not exist -func Stat(path string) (*StatT, error) { - s := &syscall.Stat_t{} - if err := syscall.Stat(path, s); err != nil { - return nil, &os.PathError{Op: "Stat", Path: path, Err: err} - } - return fromStatT(s) -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_windows.go b/vendor/github.com/docker/docker/pkg/system/stat_windows.go deleted file mode 100644 index b2456cb8..00000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_windows.go +++ /dev/null @@ -1,49 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "time" -) - -// StatT type contains status of a file. It contains metadata -// like permission, size, etc about a file. -type StatT struct { - mode os.FileMode - size int64 - mtim time.Time -} - -// Size returns file's size. -func (s StatT) Size() int64 { - return s.size -} - -// Mode returns file's permission mode. -func (s StatT) Mode() os.FileMode { - return os.FileMode(s.mode) -} - -// Mtim returns file's last modification time. -func (s StatT) Mtim() time.Time { - return time.Time(s.mtim) -} - -// Stat takes a path to a file and returns -// a system.StatT type pertaining to that file. -// -// Throws an error if the file does not exist -func Stat(path string) (*StatT, error) { - fi, err := os.Stat(path) - if err != nil { - return nil, err - } - return fromStatT(&fi) -} - -// fromStatT converts a os.FileInfo type to a system.StatT type -func fromStatT(fi *os.FileInfo) (*StatT, error) { - return &StatT{ - size: (*fi).Size(), - mode: (*fi).Mode(), - mtim: (*fi).ModTime()}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/syscall_unix.go b/vendor/github.com/docker/docker/pkg/system/syscall_unix.go deleted file mode 100644 index 905d10f1..00000000 --- a/vendor/github.com/docker/docker/pkg/system/syscall_unix.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build linux freebsd - -package system // import "github.com/docker/docker/pkg/system" - -import "golang.org/x/sys/unix" - -// Unmount is a platform-specific helper function to call -// the unmount syscall. -func Unmount(dest string) error { - return unix.Unmount(dest, 0) -} diff --git a/vendor/github.com/docker/docker/pkg/system/syscall_windows.go b/vendor/github.com/docker/docker/pkg/system/syscall_windows.go deleted file mode 100644 index 1588aa3e..00000000 --- a/vendor/github.com/docker/docker/pkg/system/syscall_windows.go +++ /dev/null @@ -1,136 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "syscall" - "unsafe" - - "github.com/Microsoft/hcsshim/osversion" - "github.com/sirupsen/logrus" - "golang.org/x/sys/windows" -) - -const ( - OWNER_SECURITY_INFORMATION = windows.OWNER_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.OWNER_SECURITY_INFORMATION - GROUP_SECURITY_INFORMATION = windows.GROUP_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.GROUP_SECURITY_INFORMATION - DACL_SECURITY_INFORMATION = windows.DACL_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.DACL_SECURITY_INFORMATION - SACL_SECURITY_INFORMATION = windows.SACL_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.SACL_SECURITY_INFORMATION - LABEL_SECURITY_INFORMATION = windows.LABEL_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.LABEL_SECURITY_INFORMATION - ATTRIBUTE_SECURITY_INFORMATION = windows.ATTRIBUTE_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.ATTRIBUTE_SECURITY_INFORMATION - SCOPE_SECURITY_INFORMATION = windows.SCOPE_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.SCOPE_SECURITY_INFORMATION - PROCESS_TRUST_LABEL_SECURITY_INFORMATION = 0x00000080 - ACCESS_FILTER_SECURITY_INFORMATION = 0x00000100 - BACKUP_SECURITY_INFORMATION = windows.BACKUP_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.BACKUP_SECURITY_INFORMATION - PROTECTED_DACL_SECURITY_INFORMATION = windows.PROTECTED_DACL_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.PROTECTED_DACL_SECURITY_INFORMATION - PROTECTED_SACL_SECURITY_INFORMATION = windows.PROTECTED_SACL_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.PROTECTED_SACL_SECURITY_INFORMATION - UNPROTECTED_DACL_SECURITY_INFORMATION = windows.UNPROTECTED_DACL_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.UNPROTECTED_DACL_SECURITY_INFORMATION - UNPROTECTED_SACL_SECURITY_INFORMATION = windows.UNPROTECTED_SACL_SECURITY_INFORMATION // Deprecated: use golang.org/x/sys/windows.UNPROTECTED_SACL_SECURITY_INFORMATION -) - -const ( - SE_UNKNOWN_OBJECT_TYPE = windows.SE_UNKNOWN_OBJECT_TYPE // Deprecated: use golang.org/x/sys/windows.SE_UNKNOWN_OBJECT_TYPE - SE_FILE_OBJECT = windows.SE_FILE_OBJECT // Deprecated: use golang.org/x/sys/windows.SE_FILE_OBJECT - SE_SERVICE = windows.SE_SERVICE // Deprecated: use golang.org/x/sys/windows.SE_SERVICE - SE_PRINTER = windows.SE_PRINTER // Deprecated: use golang.org/x/sys/windows.SE_PRINTER - SE_REGISTRY_KEY = windows.SE_REGISTRY_KEY // Deprecated: use golang.org/x/sys/windows.SE_REGISTRY_KEY - SE_LMSHARE = windows.SE_LMSHARE // Deprecated: use golang.org/x/sys/windows.SE_LMSHARE - SE_KERNEL_OBJECT = windows.SE_KERNEL_OBJECT // Deprecated: use golang.org/x/sys/windows.SE_KERNEL_OBJECT - SE_WINDOW_OBJECT = windows.SE_WINDOW_OBJECT // Deprecated: use golang.org/x/sys/windows.SE_WINDOW_OBJECT - SE_DS_OBJECT = windows.SE_DS_OBJECT // Deprecated: use golang.org/x/sys/windows.SE_DS_OBJECT - SE_DS_OBJECT_ALL = windows.SE_DS_OBJECT_ALL // Deprecated: use golang.org/x/sys/windows.SE_DS_OBJECT_ALL - SE_PROVIDER_DEFINED_OBJECT = windows.SE_PROVIDER_DEFINED_OBJECT // Deprecated: use golang.org/x/sys/windows.SE_PROVIDER_DEFINED_OBJECT - SE_WMIGUID_OBJECT = windows.SE_WMIGUID_OBJECT // Deprecated: use golang.org/x/sys/windows.SE_WMIGUID_OBJECT - SE_REGISTRY_WOW64_32KEY = windows.SE_REGISTRY_WOW64_32KEY // Deprecated: use golang.org/x/sys/windows.SE_REGISTRY_WOW64_32KEY -) - -const ( - SeTakeOwnershipPrivilege = "SeTakeOwnershipPrivilege" -) - -const ( - ContainerAdministratorSidString = "S-1-5-93-2-1" - ContainerUserSidString = "S-1-5-93-2-2" -) - -var ( - ntuserApiset = windows.NewLazyDLL("ext-ms-win-ntuser-window-l1-1-0") - modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") - procGetVersionExW = modkernel32.NewProc("GetVersionExW") - procSetNamedSecurityInfo = modadvapi32.NewProc("SetNamedSecurityInfoW") - procGetSecurityDescriptorDacl = modadvapi32.NewProc("GetSecurityDescriptorDacl") -) - -// OSVersion is a wrapper for Windows version information -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx -type OSVersion = osversion.OSVersion - -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx -// TODO: use golang.org/x/sys/windows.OsVersionInfoEx (needs OSVersionInfoSize to be exported) -type osVersionInfoEx struct { - OSVersionInfoSize uint32 - MajorVersion uint32 - MinorVersion uint32 - BuildNumber uint32 - PlatformID uint32 - CSDVersion [128]uint16 - ServicePackMajor uint16 - ServicePackMinor uint16 - SuiteMask uint16 - ProductType byte - Reserve byte -} - -// GetOSVersion gets the operating system version on Windows. Note that -// dockerd.exe must be manifested to get the correct version information. -// Deprecated: use github.com/Microsoft/hcsshim/osversion.Get() instead -func GetOSVersion() OSVersion { - return osversion.Get() -} - -// IsWindowsClient returns true if the SKU is client -func IsWindowsClient() bool { - osviex := &osVersionInfoEx{OSVersionInfoSize: 284} - r1, _, err := procGetVersionExW.Call(uintptr(unsafe.Pointer(osviex))) - if r1 == 0 { - logrus.Warnf("GetVersionExW failed - assuming server SKU: %v", err) - return false - } - const verNTWorkstation = 0x00000001 - return osviex.ProductType == verNTWorkstation -} - -// Unmount is a platform-specific helper function to call -// the unmount syscall. Not supported on Windows -func Unmount(_ string) error { - return nil -} - -// HasWin32KSupport determines whether containers that depend on win32k can -// run on this machine. Win32k is the driver used to implement windowing. -func HasWin32KSupport() bool { - // For now, check for ntuser API support on the host. In the future, a host - // may support win32k in containers even if the host does not support ntuser - // APIs. - return ntuserApiset.Load() == nil -} - -// Deprecated: use golang.org/x/sys/windows.SetNamedSecurityInfo() -func SetNamedSecurityInfo(objectName *uint16, objectType uint32, securityInformation uint32, sidOwner *windows.SID, sidGroup *windows.SID, dacl *byte, sacl *byte) (result error) { - r0, _, _ := syscall.Syscall9(procSetNamedSecurityInfo.Addr(), 7, uintptr(unsafe.Pointer(objectName)), uintptr(objectType), uintptr(securityInformation), uintptr(unsafe.Pointer(sidOwner)), uintptr(unsafe.Pointer(sidGroup)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(sacl)), 0, 0) - if r0 != 0 { - result = syscall.Errno(r0) - } - return -} - -// Deprecated: uses golang.org/x/sys/windows.SecurityDescriptorFromString() and golang.org/x/sys/windows.SECURITY_DESCRIPTOR.DACL() -func GetSecurityDescriptorDacl(securityDescriptor *byte, daclPresent *uint32, dacl **byte, daclDefaulted *uint32) (result error) { - r1, _, e1 := syscall.Syscall6(procGetSecurityDescriptorDacl.Addr(), 4, uintptr(unsafe.Pointer(securityDescriptor)), uintptr(unsafe.Pointer(daclPresent)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(daclDefaulted)), 0, 0) - if r1 == 0 { - if e1 != 0 { - result = e1 - } else { - result = syscall.EINVAL - } - } - return -} diff --git a/vendor/github.com/docker/docker/pkg/system/umask.go b/vendor/github.com/docker/docker/pkg/system/umask.go deleted file mode 100644 index 9912a2ba..00000000 --- a/vendor/github.com/docker/docker/pkg/system/umask.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "golang.org/x/sys/unix" -) - -// Umask sets current process's file mode creation mask to newmask -// and returns oldmask. -func Umask(newmask int) (oldmask int, err error) { - return unix.Umask(newmask), nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/umask_windows.go b/vendor/github.com/docker/docker/pkg/system/umask_windows.go deleted file mode 100644 index fc62388c..00000000 --- a/vendor/github.com/docker/docker/pkg/system/umask_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -// Umask is not supported on the windows platform. -func Umask(newmask int) (oldmask int, err error) { - // should not be called on cli code path - return 0, ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_unix.go b/vendor/github.com/docker/docker/pkg/system/utimes_unix.go deleted file mode 100644 index 61ba8c47..00000000 --- a/vendor/github.com/docker/docker/pkg/system/utimes_unix.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build linux freebsd - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "syscall" - - "golang.org/x/sys/unix" -) - -// LUtimesNano is used to change access and modification time of the specified path. -// It's used for symbol link file because unix.UtimesNano doesn't support a NOFOLLOW flag atm. -func LUtimesNano(path string, ts []syscall.Timespec) error { - uts := []unix.Timespec{ - unix.NsecToTimespec(syscall.TimespecToNsec(ts[0])), - unix.NsecToTimespec(syscall.TimespecToNsec(ts[1])), - } - err := unix.UtimesNanoAt(unix.AT_FDCWD, path, uts, unix.AT_SYMLINK_NOFOLLOW) - if err != nil && err != unix.ENOSYS { - return err - } - - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go b/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go deleted file mode 100644 index 095e072e..00000000 --- a/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !linux,!freebsd - -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// LUtimesNano is only supported on linux and freebsd. -func LUtimesNano(path string, ts []syscall.Timespec) error { - return ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go b/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go deleted file mode 100644 index 95b609fe..00000000 --- a/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go +++ /dev/null @@ -1,37 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "golang.org/x/sys/unix" - -// Lgetxattr retrieves the value of the extended attribute identified by attr -// and associated with the given path in the file system. -// It will returns a nil slice and nil error if the xattr is not set. -func Lgetxattr(path string, attr string) ([]byte, error) { - // Start with a 128 length byte array - dest := make([]byte, 128) - sz, errno := unix.Lgetxattr(path, attr, dest) - - for errno == unix.ERANGE { - // Buffer too small, use zero-sized buffer to get the actual size - sz, errno = unix.Lgetxattr(path, attr, []byte{}) - if errno != nil { - return nil, errno - } - dest = make([]byte, sz) - sz, errno = unix.Lgetxattr(path, attr, dest) - } - - switch { - case errno == unix.ENODATA: - return nil, nil - case errno != nil: - return nil, errno - } - - return dest[:sz], nil -} - -// Lsetxattr sets the value of the extended attribute identified by attr -// and associated with the given path in the file system. -func Lsetxattr(path string, attr string, data []byte, flags int) error { - return unix.Lsetxattr(path, attr, data, flags) -} diff --git a/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go b/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go deleted file mode 100644 index d780a90c..00000000 --- a/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !linux - -package system // import "github.com/docker/docker/pkg/system" - -// Lgetxattr is not supported on platforms other than linux. -func Lgetxattr(path string, attr string) ([]byte, error) { - return nil, ErrNotSupportedPlatform -} - -// Lsetxattr is not supported on platforms other than linux. -func Lsetxattr(path string, attr string, data []byte, flags int) error { - return ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/go-connections/LICENSE b/vendor/github.com/docker/go-connections/LICENSE deleted file mode 100644 index b55b37bc..00000000 --- a/vendor/github.com/docker/go-connections/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://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 - - Copyright 2015 Docker, 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 - - 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. diff --git a/vendor/github.com/docker/go-connections/nat/nat.go b/vendor/github.com/docker/go-connections/nat/nat.go deleted file mode 100644 index bb7e4e33..00000000 --- a/vendor/github.com/docker/go-connections/nat/nat.go +++ /dev/null @@ -1,242 +0,0 @@ -// Package nat is a convenience package for manipulation of strings describing network ports. -package nat - -import ( - "fmt" - "net" - "strconv" - "strings" -) - -const ( - // portSpecTemplate is the expected format for port specifications - portSpecTemplate = "ip:hostPort:containerPort" -) - -// PortBinding represents a binding between a Host IP address and a Host Port -type PortBinding struct { - // HostIP is the host IP Address - HostIP string `json:"HostIp"` - // HostPort is the host port number - HostPort string -} - -// PortMap is a collection of PortBinding indexed by Port -type PortMap map[Port][]PortBinding - -// PortSet is a collection of structs indexed by Port -type PortSet map[Port]struct{} - -// Port is a string containing port number and protocol in the format "80/tcp" -type Port string - -// NewPort creates a new instance of a Port given a protocol and port number or port range -func NewPort(proto, port string) (Port, error) { - // Check for parsing issues on "port" now so we can avoid having - // to check it later on. - - portStartInt, portEndInt, err := ParsePortRangeToInt(port) - if err != nil { - return "", err - } - - if portStartInt == portEndInt { - return Port(fmt.Sprintf("%d/%s", portStartInt, proto)), nil - } - return Port(fmt.Sprintf("%d-%d/%s", portStartInt, portEndInt, proto)), nil -} - -// ParsePort parses the port number string and returns an int -func ParsePort(rawPort string) (int, error) { - if len(rawPort) == 0 { - return 0, nil - } - port, err := strconv.ParseUint(rawPort, 10, 16) - if err != nil { - return 0, err - } - return int(port), nil -} - -// ParsePortRangeToInt parses the port range string and returns start/end ints -func ParsePortRangeToInt(rawPort string) (int, int, error) { - if len(rawPort) == 0 { - return 0, 0, nil - } - start, end, err := ParsePortRange(rawPort) - if err != nil { - return 0, 0, err - } - return int(start), int(end), nil -} - -// Proto returns the protocol of a Port -func (p Port) Proto() string { - proto, _ := SplitProtoPort(string(p)) - return proto -} - -// Port returns the port number of a Port -func (p Port) Port() string { - _, port := SplitProtoPort(string(p)) - return port -} - -// Int returns the port number of a Port as an int -func (p Port) Int() int { - portStr := p.Port() - // We don't need to check for an error because we're going to - // assume that any error would have been found, and reported, in NewPort() - port, _ := ParsePort(portStr) - return port -} - -// Range returns the start/end port numbers of a Port range as ints -func (p Port) Range() (int, int, error) { - return ParsePortRangeToInt(p.Port()) -} - -// SplitProtoPort splits a port in the format of proto/port -func SplitProtoPort(rawPort string) (string, string) { - parts := strings.Split(rawPort, "/") - l := len(parts) - if len(rawPort) == 0 || l == 0 || len(parts[0]) == 0 { - return "", "" - } - if l == 1 { - return "tcp", rawPort - } - if len(parts[1]) == 0 { - return "tcp", parts[0] - } - return parts[1], parts[0] -} - -func validateProto(proto string) bool { - for _, availableProto := range []string{"tcp", "udp", "sctp"} { - if availableProto == proto { - return true - } - } - return false -} - -// ParsePortSpecs receives port specs in the format of ip:public:private/proto and parses -// these in to the internal types -func ParsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding, error) { - var ( - exposedPorts = make(map[Port]struct{}, len(ports)) - bindings = make(map[Port][]PortBinding) - ) - for _, rawPort := range ports { - portMappings, err := ParsePortSpec(rawPort) - if err != nil { - return nil, nil, err - } - - for _, portMapping := range portMappings { - port := portMapping.Port - if _, exists := exposedPorts[port]; !exists { - exposedPorts[port] = struct{}{} - } - bslice, exists := bindings[port] - if !exists { - bslice = []PortBinding{} - } - bindings[port] = append(bslice, portMapping.Binding) - } - } - return exposedPorts, bindings, nil -} - -// PortMapping is a data object mapping a Port to a PortBinding -type PortMapping struct { - Port Port - Binding PortBinding -} - -func splitParts(rawport string) (string, string, string) { - parts := strings.Split(rawport, ":") - n := len(parts) - containerport := parts[n-1] - - switch n { - case 1: - return "", "", containerport - case 2: - return "", parts[0], containerport - case 3: - return parts[0], parts[1], containerport - default: - return strings.Join(parts[:n-2], ":"), parts[n-2], containerport - } -} - -// ParsePortSpec parses a port specification string into a slice of PortMappings -func ParsePortSpec(rawPort string) ([]PortMapping, error) { - var proto string - rawIP, hostPort, containerPort := splitParts(rawPort) - proto, containerPort = SplitProtoPort(containerPort) - - // Strip [] from IPV6 addresses - ip, _, err := net.SplitHostPort(rawIP + ":") - if err != nil { - return nil, fmt.Errorf("Invalid ip address %v: %s", rawIP, err) - } - if ip != "" && net.ParseIP(ip) == nil { - return nil, fmt.Errorf("Invalid ip address: %s", ip) - } - if containerPort == "" { - return nil, fmt.Errorf("No port specified: %s", rawPort) - } - - startPort, endPort, err := ParsePortRange(containerPort) - if err != nil { - return nil, fmt.Errorf("Invalid containerPort: %s", containerPort) - } - - var startHostPort, endHostPort uint64 = 0, 0 - if len(hostPort) > 0 { - startHostPort, endHostPort, err = ParsePortRange(hostPort) - if err != nil { - return nil, fmt.Errorf("Invalid hostPort: %s", hostPort) - } - } - - if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) { - // Allow host port range iff containerPort is not a range. - // In this case, use the host port range as the dynamic - // host port range to allocate into. - if endPort != startPort { - return nil, fmt.Errorf("Invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort) - } - } - - if !validateProto(strings.ToLower(proto)) { - return nil, fmt.Errorf("Invalid proto: %s", proto) - } - - ports := []PortMapping{} - for i := uint64(0); i <= (endPort - startPort); i++ { - containerPort = strconv.FormatUint(startPort+i, 10) - if len(hostPort) > 0 { - hostPort = strconv.FormatUint(startHostPort+i, 10) - } - // Set hostPort to a range only if there is a single container port - // and a dynamic host port. - if startPort == endPort && startHostPort != endHostPort { - hostPort = fmt.Sprintf("%s-%s", hostPort, strconv.FormatUint(endHostPort, 10)) - } - port, err := NewPort(strings.ToLower(proto), containerPort) - if err != nil { - return nil, err - } - - binding := PortBinding{ - HostIP: ip, - HostPort: hostPort, - } - ports = append(ports, PortMapping{Port: port, Binding: binding}) - } - return ports, nil -} diff --git a/vendor/github.com/docker/go-connections/nat/parse.go b/vendor/github.com/docker/go-connections/nat/parse.go deleted file mode 100644 index 892adf8c..00000000 --- a/vendor/github.com/docker/go-connections/nat/parse.go +++ /dev/null @@ -1,57 +0,0 @@ -package nat - -import ( - "fmt" - "strconv" - "strings" -) - -// PartParser parses and validates the specified string (data) using the specified template -// e.g. ip:public:private -> 192.168.0.1:80:8000 -// DEPRECATED: do not use, this function may be removed in a future version -func PartParser(template, data string) (map[string]string, error) { - // ip:public:private - var ( - templateParts = strings.Split(template, ":") - parts = strings.Split(data, ":") - out = make(map[string]string, len(templateParts)) - ) - if len(parts) != len(templateParts) { - return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template) - } - - for i, t := range templateParts { - value := "" - if len(parts) > i { - value = parts[i] - } - out[t] = value - } - return out, nil -} - -// ParsePortRange parses and validates the specified string as a port-range (8000-9000) -func ParsePortRange(ports string) (uint64, uint64, error) { - if ports == "" { - return 0, 0, fmt.Errorf("Empty string specified for ports.") - } - if !strings.Contains(ports, "-") { - start, err := strconv.ParseUint(ports, 10, 16) - end := start - return start, end, err - } - - parts := strings.Split(ports, "-") - start, err := strconv.ParseUint(parts[0], 10, 16) - if err != nil { - return 0, 0, err - } - end, err := strconv.ParseUint(parts[1], 10, 16) - if err != nil { - return 0, 0, err - } - if end < start { - return 0, 0, fmt.Errorf("Invalid range specified for the Port: %s", ports) - } - return start, end, nil -} diff --git a/vendor/github.com/docker/go-connections/nat/sort.go b/vendor/github.com/docker/go-connections/nat/sort.go deleted file mode 100644 index ce950171..00000000 --- a/vendor/github.com/docker/go-connections/nat/sort.go +++ /dev/null @@ -1,96 +0,0 @@ -package nat - -import ( - "sort" - "strings" -) - -type portSorter struct { - ports []Port - by func(i, j Port) bool -} - -func (s *portSorter) Len() int { - return len(s.ports) -} - -func (s *portSorter) Swap(i, j int) { - s.ports[i], s.ports[j] = s.ports[j], s.ports[i] -} - -func (s *portSorter) Less(i, j int) bool { - ip := s.ports[i] - jp := s.ports[j] - - return s.by(ip, jp) -} - -// Sort sorts a list of ports using the provided predicate -// This function should compare `i` and `j`, returning true if `i` is -// considered to be less than `j` -func Sort(ports []Port, predicate func(i, j Port) bool) { - s := &portSorter{ports, predicate} - sort.Sort(s) -} - -type portMapEntry struct { - port Port - binding PortBinding -} - -type portMapSorter []portMapEntry - -func (s portMapSorter) Len() int { return len(s) } -func (s portMapSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// sort the port so that the order is: -// 1. port with larger specified bindings -// 2. larger port -// 3. port with tcp protocol -func (s portMapSorter) Less(i, j int) bool { - pi, pj := s[i].port, s[j].port - hpi, hpj := toInt(s[i].binding.HostPort), toInt(s[j].binding.HostPort) - return hpi > hpj || pi.Int() > pj.Int() || (pi.Int() == pj.Int() && strings.ToLower(pi.Proto()) == "tcp") -} - -// SortPortMap sorts the list of ports and their respected mapping. The ports -// will explicit HostPort will be placed first. -func SortPortMap(ports []Port, bindings PortMap) { - s := portMapSorter{} - for _, p := range ports { - if binding, ok := bindings[p]; ok { - for _, b := range binding { - s = append(s, portMapEntry{port: p, binding: b}) - } - bindings[p] = []PortBinding{} - } else { - s = append(s, portMapEntry{port: p}) - } - } - - sort.Sort(s) - var ( - i int - pm = make(map[Port]struct{}) - ) - // reorder ports - for _, entry := range s { - if _, ok := pm[entry.port]; !ok { - ports[i] = entry.port - pm[entry.port] = struct{}{} - i++ - } - // reorder bindings for this port - if _, ok := bindings[entry.port]; ok { - bindings[entry.port] = append(bindings[entry.port], entry.binding) - } - } -} - -func toInt(s string) uint64 { - i, _, err := ParsePortRange(s) - if err != nil { - i = 0 - } - return i -} diff --git a/vendor/github.com/docker/go-connections/sockets/README.md b/vendor/github.com/docker/go-connections/sockets/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/vendor/github.com/docker/go-connections/sockets/inmem_socket.go b/vendor/github.com/docker/go-connections/sockets/inmem_socket.go deleted file mode 100644 index 99846ffd..00000000 --- a/vendor/github.com/docker/go-connections/sockets/inmem_socket.go +++ /dev/null @@ -1,81 +0,0 @@ -package sockets - -import ( - "errors" - "net" - "sync" -) - -var errClosed = errors.New("use of closed network connection") - -// InmemSocket implements net.Listener using in-memory only connections. -type InmemSocket struct { - chConn chan net.Conn - chClose chan struct{} - addr string - mu sync.Mutex -} - -// dummyAddr is used to satisfy net.Addr for the in-mem socket -// it is just stored as a string and returns the string for all calls -type dummyAddr string - -// NewInmemSocket creates an in-memory only net.Listener -// The addr argument can be any string, but is used to satisfy the `Addr()` part -// of the net.Listener interface -func NewInmemSocket(addr string, bufSize int) *InmemSocket { - return &InmemSocket{ - chConn: make(chan net.Conn, bufSize), - chClose: make(chan struct{}), - addr: addr, - } -} - -// Addr returns the socket's addr string to satisfy net.Listener -func (s *InmemSocket) Addr() net.Addr { - return dummyAddr(s.addr) -} - -// Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn. -func (s *InmemSocket) Accept() (net.Conn, error) { - select { - case conn := <-s.chConn: - return conn, nil - case <-s.chClose: - return nil, errClosed - } -} - -// Close closes the listener. It will be unavailable for use once closed. -func (s *InmemSocket) Close() error { - s.mu.Lock() - defer s.mu.Unlock() - select { - case <-s.chClose: - default: - close(s.chClose) - } - return nil -} - -// Dial is used to establish a connection with the in-mem server -func (s *InmemSocket) Dial(network, addr string) (net.Conn, error) { - srvConn, clientConn := net.Pipe() - select { - case s.chConn <- srvConn: - case <-s.chClose: - return nil, errClosed - } - - return clientConn, nil -} - -// Network returns the addr string, satisfies net.Addr -func (a dummyAddr) Network() string { - return string(a) -} - -// String returns the string form -func (a dummyAddr) String() string { - return string(a) -} diff --git a/vendor/github.com/docker/go-connections/sockets/proxy.go b/vendor/github.com/docker/go-connections/sockets/proxy.go deleted file mode 100644 index 98e9a1dc..00000000 --- a/vendor/github.com/docker/go-connections/sockets/proxy.go +++ /dev/null @@ -1,51 +0,0 @@ -package sockets - -import ( - "net" - "net/url" - "os" - "strings" - - "golang.org/x/net/proxy" -) - -// GetProxyEnv allows access to the uppercase and the lowercase forms of -// proxy-related variables. See the Go specification for details on these -// variables. https://golang.org/pkg/net/http/ -func GetProxyEnv(key string) string { - proxyValue := os.Getenv(strings.ToUpper(key)) - if proxyValue == "" { - return os.Getenv(strings.ToLower(key)) - } - return proxyValue -} - -// DialerFromEnvironment takes in a "direct" *net.Dialer and returns a -// proxy.Dialer which will route the connections through the proxy using the -// given dialer. -func DialerFromEnvironment(direct *net.Dialer) (proxy.Dialer, error) { - allProxy := GetProxyEnv("all_proxy") - if len(allProxy) == 0 { - return direct, nil - } - - proxyURL, err := url.Parse(allProxy) - if err != nil { - return direct, err - } - - proxyFromURL, err := proxy.FromURL(proxyURL, direct) - if err != nil { - return direct, err - } - - noProxy := GetProxyEnv("no_proxy") - if len(noProxy) == 0 { - return proxyFromURL, nil - } - - perHost := proxy.NewPerHost(proxyFromURL, direct) - perHost.AddFromString(noProxy) - - return perHost, nil -} diff --git a/vendor/github.com/docker/go-connections/sockets/sockets.go b/vendor/github.com/docker/go-connections/sockets/sockets.go deleted file mode 100644 index a1d7beb4..00000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets.go +++ /dev/null @@ -1,38 +0,0 @@ -// Package sockets provides helper functions to create and configure Unix or TCP sockets. -package sockets - -import ( - "errors" - "net" - "net/http" - "time" -) - -// Why 32? See https://github.com/docker/docker/pull/8035. -const defaultTimeout = 32 * time.Second - -// ErrProtocolNotAvailable is returned when a given transport protocol is not provided by the operating system. -var ErrProtocolNotAvailable = errors.New("protocol not available") - -// ConfigureTransport configures the specified Transport according to the -// specified proto and addr. -// If the proto is unix (using a unix socket to communicate) or npipe the -// compression is disabled. -func ConfigureTransport(tr *http.Transport, proto, addr string) error { - switch proto { - case "unix": - return configureUnixTransport(tr, proto, addr) - case "npipe": - return configureNpipeTransport(tr, proto, addr) - default: - tr.Proxy = http.ProxyFromEnvironment - dialer, err := DialerFromEnvironment(&net.Dialer{ - Timeout: defaultTimeout, - }) - if err != nil { - return err - } - tr.Dial = dialer.Dial - } - return nil -} diff --git a/vendor/github.com/docker/go-connections/sockets/sockets_unix.go b/vendor/github.com/docker/go-connections/sockets/sockets_unix.go deleted file mode 100644 index 386cf0db..00000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets_unix.go +++ /dev/null @@ -1,35 +0,0 @@ -// +build !windows - -package sockets - -import ( - "fmt" - "net" - "net/http" - "syscall" - "time" -) - -const maxUnixSocketPathSize = len(syscall.RawSockaddrUnix{}.Path) - -func configureUnixTransport(tr *http.Transport, proto, addr string) error { - if len(addr) > maxUnixSocketPathSize { - return fmt.Errorf("Unix socket path %q is too long", addr) - } - // No need for compression in local communications. - tr.DisableCompression = true - tr.Dial = func(_, _ string) (net.Conn, error) { - return net.DialTimeout(proto, addr, defaultTimeout) - } - return nil -} - -func configureNpipeTransport(tr *http.Transport, proto, addr string) error { - return ErrProtocolNotAvailable -} - -// DialPipe connects to a Windows named pipe. -// This is not supported on other OSes. -func DialPipe(_ string, _ time.Duration) (net.Conn, error) { - return nil, syscall.EAFNOSUPPORT -} diff --git a/vendor/github.com/docker/go-connections/sockets/sockets_windows.go b/vendor/github.com/docker/go-connections/sockets/sockets_windows.go deleted file mode 100644 index 5c21644e..00000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -package sockets - -import ( - "net" - "net/http" - "time" - - "github.com/Microsoft/go-winio" -) - -func configureUnixTransport(tr *http.Transport, proto, addr string) error { - return ErrProtocolNotAvailable -} - -func configureNpipeTransport(tr *http.Transport, proto, addr string) error { - // No need for compression in local communications. - tr.DisableCompression = true - tr.Dial = func(_, _ string) (net.Conn, error) { - return DialPipe(addr, defaultTimeout) - } - return nil -} - -// DialPipe connects to a Windows named pipe. -func DialPipe(addr string, timeout time.Duration) (net.Conn, error) { - return winio.DialPipe(addr, &timeout) -} diff --git a/vendor/github.com/docker/go-connections/sockets/tcp_socket.go b/vendor/github.com/docker/go-connections/sockets/tcp_socket.go deleted file mode 100644 index 53cbb6c7..00000000 --- a/vendor/github.com/docker/go-connections/sockets/tcp_socket.go +++ /dev/null @@ -1,22 +0,0 @@ -// Package sockets provides helper functions to create and configure Unix or TCP sockets. -package sockets - -import ( - "crypto/tls" - "net" -) - -// NewTCPSocket creates a TCP socket listener with the specified address and -// the specified tls configuration. If TLSConfig is set, will encapsulate the -// TCP listener inside a TLS one. -func NewTCPSocket(addr string, tlsConfig *tls.Config) (net.Listener, error) { - l, err := net.Listen("tcp", addr) - if err != nil { - return nil, err - } - if tlsConfig != nil { - tlsConfig.NextProtos = []string{"http/1.1"} - l = tls.NewListener(l, tlsConfig) - } - return l, nil -} diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket.go b/vendor/github.com/docker/go-connections/sockets/unix_socket.go deleted file mode 100644 index a8b5dbb6..00000000 --- a/vendor/github.com/docker/go-connections/sockets/unix_socket.go +++ /dev/null @@ -1,32 +0,0 @@ -// +build !windows - -package sockets - -import ( - "net" - "os" - "syscall" -) - -// NewUnixSocket creates a unix socket with the specified path and group. -func NewUnixSocket(path string, gid int) (net.Listener, error) { - if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { - return nil, err - } - mask := syscall.Umask(0777) - defer syscall.Umask(mask) - - l, err := net.Listen("unix", path) - if err != nil { - return nil, err - } - if err := os.Chown(path, 0, gid); err != nil { - l.Close() - return nil, err - } - if err := os.Chmod(path, 0660); err != nil { - l.Close() - return nil, err - } - return l, nil -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go b/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go deleted file mode 100644 index 1ca0965e..00000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build go1.7 - -package tlsconfig - -import ( - "crypto/x509" - "runtime" -) - -// SystemCertPool returns a copy of the system cert pool, -// returns an error if failed to load or empty pool on windows. -func SystemCertPool() (*x509.CertPool, error) { - certpool, err := x509.SystemCertPool() - if err != nil && runtime.GOOS == "windows" { - return x509.NewCertPool(), nil - } - return certpool, err -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go b/vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go deleted file mode 100644 index 1ff81c33..00000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !go1.7 - -package tlsconfig - -import ( - "crypto/x509" -) - -// SystemCertPool returns an new empty cert pool, -// accessing system cert pool is supported in go 1.7 -func SystemCertPool() (*x509.CertPool, error) { - return x509.NewCertPool(), nil -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/config.go b/vendor/github.com/docker/go-connections/tlsconfig/config.go deleted file mode 100644 index 0ef3fdcb..00000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/config.go +++ /dev/null @@ -1,254 +0,0 @@ -// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers. -// -// As a reminder from https://golang.org/pkg/crypto/tls/#Config: -// A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified. -// A Config may be reused; the tls package will also not modify it. -package tlsconfig - -import ( - "crypto/tls" - "crypto/x509" - "encoding/pem" - "fmt" - "io/ioutil" - "os" - - "github.com/pkg/errors" -) - -// Options represents the information needed to create client and server TLS configurations. -type Options struct { - CAFile string - - // If either CertFile or KeyFile is empty, Client() will not load them - // preventing the client from authenticating to the server. - // However, Server() requires them and will error out if they are empty. - CertFile string - KeyFile string - - // client-only option - InsecureSkipVerify bool - // server-only option - ClientAuth tls.ClientAuthType - // If ExclusiveRootPools is set, then if a CA file is provided, the root pool used for TLS - // creds will include exclusively the roots in that CA file. If no CA file is provided, - // the system pool will be used. - ExclusiveRootPools bool - MinVersion uint16 - // If Passphrase is set, it will be used to decrypt a TLS private key - // if the key is encrypted - Passphrase string -} - -// Extra (server-side) accepted CBC cipher suites - will phase out in the future -var acceptedCBCCiphers = []uint16{ - tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, -} - -// DefaultServerAcceptedCiphers should be uses by code which already has a crypto/tls -// options struct but wants to use a commonly accepted set of TLS cipher suites, with -// known weak algorithms removed. -var DefaultServerAcceptedCiphers = append(clientCipherSuites, acceptedCBCCiphers...) - -// allTLSVersions lists all the TLS versions and is used by the code that validates -// a uint16 value as a TLS version. -var allTLSVersions = map[uint16]struct{}{ - tls.VersionSSL30: {}, - tls.VersionTLS10: {}, - tls.VersionTLS11: {}, - tls.VersionTLS12: {}, -} - -// ServerDefault returns a secure-enough TLS configuration for the server TLS configuration. -func ServerDefault(ops ...func(*tls.Config)) *tls.Config { - tlsconfig := &tls.Config{ - // Avoid fallback by default to SSL protocols < TLS1.2 - MinVersion: tls.VersionTLS12, - PreferServerCipherSuites: true, - CipherSuites: DefaultServerAcceptedCiphers, - } - - for _, op := range ops { - op(tlsconfig) - } - - return tlsconfig -} - -// ClientDefault returns a secure-enough TLS configuration for the client TLS configuration. -func ClientDefault(ops ...func(*tls.Config)) *tls.Config { - tlsconfig := &tls.Config{ - // Prefer TLS1.2 as the client minimum - MinVersion: tls.VersionTLS12, - CipherSuites: clientCipherSuites, - } - - for _, op := range ops { - op(tlsconfig) - } - - return tlsconfig -} - -// certPool returns an X.509 certificate pool from `caFile`, the certificate file. -func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) { - // If we should verify the server, we need to load a trusted ca - var ( - certPool *x509.CertPool - err error - ) - if exclusivePool { - certPool = x509.NewCertPool() - } else { - certPool, err = SystemCertPool() - if err != nil { - return nil, fmt.Errorf("failed to read system certificates: %v", err) - } - } - pem, err := ioutil.ReadFile(caFile) - if err != nil { - return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err) - } - if !certPool.AppendCertsFromPEM(pem) { - return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile) - } - return certPool, nil -} - -// isValidMinVersion checks that the input value is a valid tls minimum version -func isValidMinVersion(version uint16) bool { - _, ok := allTLSVersions[version] - return ok -} - -// adjustMinVersion sets the MinVersion on `config`, the input configuration. -// It assumes the current MinVersion on the `config` is the lowest allowed. -func adjustMinVersion(options Options, config *tls.Config) error { - if options.MinVersion > 0 { - if !isValidMinVersion(options.MinVersion) { - return fmt.Errorf("Invalid minimum TLS version: %x", options.MinVersion) - } - if options.MinVersion < config.MinVersion { - return fmt.Errorf("Requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion) - } - config.MinVersion = options.MinVersion - } - - return nil -} - -// IsErrEncryptedKey returns true if the 'err' is an error of incorrect -// password when tryin to decrypt a TLS private key -func IsErrEncryptedKey(err error) bool { - return errors.Cause(err) == x509.IncorrectPasswordError -} - -// getPrivateKey returns the private key in 'keyBytes', in PEM-encoded format. -// If the private key is encrypted, 'passphrase' is used to decrypted the -// private key. -func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) { - // this section makes some small changes to code from notary/tuf/utils/x509.go - pemBlock, _ := pem.Decode(keyBytes) - if pemBlock == nil { - return nil, fmt.Errorf("no valid private key found") - } - - var err error - if x509.IsEncryptedPEMBlock(pemBlock) { - keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase)) - if err != nil { - return nil, errors.Wrap(err, "private key is encrypted, but could not decrypt it") - } - keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes}) - } - - return keyBytes, nil -} - -// getCert returns a Certificate from the CertFile and KeyFile in 'options', -// if the key is encrypted, the Passphrase in 'options' will be used to -// decrypt it. -func getCert(options Options) ([]tls.Certificate, error) { - if options.CertFile == "" && options.KeyFile == "" { - return nil, nil - } - - errMessage := "Could not load X509 key pair" - - cert, err := ioutil.ReadFile(options.CertFile) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - prKeyBytes, err := ioutil.ReadFile(options.KeyFile) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - tlsCert, err := tls.X509KeyPair(cert, prKeyBytes) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - return []tls.Certificate{tlsCert}, nil -} - -// Client returns a TLS configuration meant to be used by a client. -func Client(options Options) (*tls.Config, error) { - tlsConfig := ClientDefault() - tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify - if !options.InsecureSkipVerify && options.CAFile != "" { - CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) - if err != nil { - return nil, err - } - tlsConfig.RootCAs = CAs - } - - tlsCerts, err := getCert(options) - if err != nil { - return nil, err - } - tlsConfig.Certificates = tlsCerts - - if err := adjustMinVersion(options, tlsConfig); err != nil { - return nil, err - } - - return tlsConfig, nil -} - -// Server returns a TLS configuration meant to be used by a server. -func Server(options Options) (*tls.Config, error) { - tlsConfig := ServerDefault() - tlsConfig.ClientAuth = options.ClientAuth - tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile) - if err != nil { - if os.IsNotExist(err) { - return nil, fmt.Errorf("Could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err) - } - return nil, fmt.Errorf("Error reading X509 key pair (cert: %q, key: %q): %v. Make sure the key is not encrypted.", options.CertFile, options.KeyFile, err) - } - tlsConfig.Certificates = []tls.Certificate{tlsCert} - if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" { - CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) - if err != nil { - return nil, err - } - tlsConfig.ClientCAs = CAs - } - - if err := adjustMinVersion(options, tlsConfig); err != nil { - return nil, err - } - - return tlsConfig, nil -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go b/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go deleted file mode 100644 index 6b4c6a7c..00000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build go1.5 - -// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers. -// -package tlsconfig - -import ( - "crypto/tls" -) - -// Client TLS cipher suites (dropping CBC ciphers for client preferred suite set) -var clientCipherSuites = []uint16{ - tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go b/vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go deleted file mode 100644 index ee22df47..00000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !go1.5 - -// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers. -// -package tlsconfig - -import ( - "crypto/tls" -) - -// Client TLS cipher suites (dropping CBC ciphers for client preferred suite set) -var clientCipherSuites = []uint16{ - tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, -} diff --git a/vendor/github.com/docker/go-units/CONTRIBUTING.md b/vendor/github.com/docker/go-units/CONTRIBUTING.md deleted file mode 100644 index 9ea86d78..00000000 --- a/vendor/github.com/docker/go-units/CONTRIBUTING.md +++ /dev/null @@ -1,67 +0,0 @@ -# Contributing to go-units - -Want to hack on go-units? Awesome! Here are instructions to get you started. - -go-units is a part of the [Docker](https://www.docker.com) project, and follows -the same rules and principles. If you're already familiar with the way -Docker does things, you'll feel right at home. - -Otherwise, go read Docker's -[contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md), -[issue triaging](https://github.com/docker/docker/blob/master/project/ISSUE-TRIAGE.md), -[review process](https://github.com/docker/docker/blob/master/project/REVIEWING.md) and -[branches and tags](https://github.com/docker/docker/blob/master/project/BRANCHES-AND-TAGS.md). - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the patch. Your -signature certifies that you wrote the patch or otherwise have the right to pass -it on as an open-source patch. The rules are pretty simple: if you can certify -the below (from [developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -Then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -Use your real name (sorry, no pseudonyms or anonymous contributions.) - -If you set your `user.name` and `user.email` git configs, you can sign your -commit automatically with `git commit -s`. diff --git a/vendor/github.com/docker/go-units/LICENSE b/vendor/github.com/docker/go-units/LICENSE deleted file mode 100644 index b55b37bc..00000000 --- a/vendor/github.com/docker/go-units/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://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 - - Copyright 2015 Docker, 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 - - 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. diff --git a/vendor/github.com/docker/go-units/MAINTAINERS b/vendor/github.com/docker/go-units/MAINTAINERS deleted file mode 100644 index 4aac7c74..00000000 --- a/vendor/github.com/docker/go-units/MAINTAINERS +++ /dev/null @@ -1,46 +0,0 @@ -# go-units maintainers file -# -# This file describes who runs the docker/go-units project and how. -# This is a living document - if you see something out of date or missing, speak up! -# -# It is structured to be consumable by both humans and programs. -# To extract its contents programmatically, use any TOML-compliant parser. -# -# This file is compiled into the MAINTAINERS file in docker/opensource. -# -[Org] - [Org."Core maintainers"] - people = [ - "akihirosuda", - "dnephin", - "thajeztah", - "vdemeester", - ] - -[people] - -# A reference list of all people associated with the project. -# All other sections should refer to people by their canonical key -# in the people section. - - # ADD YOURSELF HERE IN ALPHABETICAL ORDER - - [people.akihirosuda] - Name = "Akihiro Suda" - Email = "akihiro.suda.cz@hco.ntt.co.jp" - GitHub = "AkihiroSuda" - - [people.dnephin] - Name = "Daniel Nephin" - Email = "dnephin@gmail.com" - GitHub = "dnephin" - - [people.thajeztah] - Name = "Sebastiaan van Stijn" - Email = "github@gone.nl" - GitHub = "thaJeztah" - - [people.vdemeester] - Name = "Vincent Demeester" - Email = "vincent@sbr.pm" - GitHub = "vdemeester" \ No newline at end of file diff --git a/vendor/github.com/docker/go-units/README.md b/vendor/github.com/docker/go-units/README.md deleted file mode 100644 index 4f70a4e1..00000000 --- a/vendor/github.com/docker/go-units/README.md +++ /dev/null @@ -1,16 +0,0 @@ -[![GoDoc](https://godoc.org/github.com/docker/go-units?status.svg)](https://godoc.org/github.com/docker/go-units) - -# Introduction - -go-units is a library to transform human friendly measurements into machine friendly values. - -## Usage - -See the [docs in godoc](https://godoc.org/github.com/docker/go-units) for examples and documentation. - -## Copyright and license - -Copyright © 2015 Docker, Inc. - -go-units is licensed under the Apache License, Version 2.0. -See [LICENSE](LICENSE) for the full text of the license. diff --git a/vendor/github.com/docker/go-units/circle.yml b/vendor/github.com/docker/go-units/circle.yml deleted file mode 100644 index af9d6055..00000000 --- a/vendor/github.com/docker/go-units/circle.yml +++ /dev/null @@ -1,11 +0,0 @@ -dependencies: - post: - # install golint - - go get golang.org/x/lint/golint - -test: - pre: - # run analysis before tests - - go vet ./... - - test -z "$(golint ./... | tee /dev/stderr)" - - test -z "$(gofmt -s -l . | tee /dev/stderr)" diff --git a/vendor/github.com/docker/go-units/duration.go b/vendor/github.com/docker/go-units/duration.go deleted file mode 100644 index 48dd8744..00000000 --- a/vendor/github.com/docker/go-units/duration.go +++ /dev/null @@ -1,35 +0,0 @@ -// Package units provides helper function to parse and print size and time units -// in human-readable format. -package units - -import ( - "fmt" - "time" -) - -// HumanDuration returns a human-readable approximation of a duration -// (eg. "About a minute", "4 hours ago", etc.). -func HumanDuration(d time.Duration) string { - if seconds := int(d.Seconds()); seconds < 1 { - return "Less than a second" - } else if seconds == 1 { - return "1 second" - } else if seconds < 60 { - return fmt.Sprintf("%d seconds", seconds) - } else if minutes := int(d.Minutes()); minutes == 1 { - return "About a minute" - } else if minutes < 60 { - return fmt.Sprintf("%d minutes", minutes) - } else if hours := int(d.Hours() + 0.5); hours == 1 { - return "About an hour" - } else if hours < 48 { - return fmt.Sprintf("%d hours", hours) - } else if hours < 24*7*2 { - return fmt.Sprintf("%d days", hours/24) - } else if hours < 24*30*2 { - return fmt.Sprintf("%d weeks", hours/24/7) - } else if hours < 24*365*2 { - return fmt.Sprintf("%d months", hours/24/30) - } - return fmt.Sprintf("%d years", int(d.Hours())/24/365) -} diff --git a/vendor/github.com/docker/go-units/size.go b/vendor/github.com/docker/go-units/size.go deleted file mode 100644 index 85f6ab07..00000000 --- a/vendor/github.com/docker/go-units/size.go +++ /dev/null @@ -1,108 +0,0 @@ -package units - -import ( - "fmt" - "regexp" - "strconv" - "strings" -) - -// See: http://en.wikipedia.org/wiki/Binary_prefix -const ( - // Decimal - - KB = 1000 - MB = 1000 * KB - GB = 1000 * MB - TB = 1000 * GB - PB = 1000 * TB - - // Binary - - KiB = 1024 - MiB = 1024 * KiB - GiB = 1024 * MiB - TiB = 1024 * GiB - PiB = 1024 * TiB -) - -type unitMap map[string]int64 - -var ( - decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB} - binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB} - sizeRegex = regexp.MustCompile(`^(\d+(\.\d+)*) ?([kKmMgGtTpP])?[iI]?[bB]?$`) -) - -var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} -var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} - -func getSizeAndUnit(size float64, base float64, _map []string) (float64, string) { - i := 0 - unitsLimit := len(_map) - 1 - for size >= base && i < unitsLimit { - size = size / base - i++ - } - return size, _map[i] -} - -// CustomSize returns a human-readable approximation of a size -// using custom format. -func CustomSize(format string, size float64, base float64, _map []string) string { - size, unit := getSizeAndUnit(size, base, _map) - return fmt.Sprintf(format, size, unit) -} - -// HumanSizeWithPrecision allows the size to be in any precision, -// instead of 4 digit precision used in units.HumanSize. -func HumanSizeWithPrecision(size float64, precision int) string { - size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs) - return fmt.Sprintf("%.*g%s", precision, size, unit) -} - -// HumanSize returns a human-readable approximation of a size -// capped at 4 valid numbers (eg. "2.746 MB", "796 KB"). -func HumanSize(size float64) string { - return HumanSizeWithPrecision(size, 4) -} - -// BytesSize returns a human-readable size in bytes, kibibytes, -// mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB"). -func BytesSize(size float64) string { - return CustomSize("%.4g%s", size, 1024.0, binaryAbbrs) -} - -// FromHumanSize returns an integer from a human-readable specification of a -// size using SI standard (eg. "44kB", "17MB"). -func FromHumanSize(size string) (int64, error) { - return parseSize(size, decimalMap) -} - -// RAMInBytes parses a human-readable string representing an amount of RAM -// in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and -// returns the number of bytes, or -1 if the string is unparseable. -// Units are case-insensitive, and the 'b' suffix is optional. -func RAMInBytes(size string) (int64, error) { - return parseSize(size, binaryMap) -} - -// Parses the human-readable size string into the amount it represents. -func parseSize(sizeStr string, uMap unitMap) (int64, error) { - matches := sizeRegex.FindStringSubmatch(sizeStr) - if len(matches) != 4 { - return -1, fmt.Errorf("invalid size: '%s'", sizeStr) - } - - size, err := strconv.ParseFloat(matches[1], 64) - if err != nil { - return -1, err - } - - unitPrefix := strings.ToLower(matches[3]) - if mul, ok := uMap[unitPrefix]; ok { - size *= float64(mul) - } - - return int64(size), nil -} diff --git a/vendor/github.com/docker/go-units/ulimit.go b/vendor/github.com/docker/go-units/ulimit.go deleted file mode 100644 index fca0400c..00000000 --- a/vendor/github.com/docker/go-units/ulimit.go +++ /dev/null @@ -1,123 +0,0 @@ -package units - -import ( - "fmt" - "strconv" - "strings" -) - -// Ulimit is a human friendly version of Rlimit. -type Ulimit struct { - Name string - Hard int64 - Soft int64 -} - -// Rlimit specifies the resource limits, such as max open files. -type Rlimit struct { - Type int `json:"type,omitempty"` - Hard uint64 `json:"hard,omitempty"` - Soft uint64 `json:"soft,omitempty"` -} - -const ( - // magic numbers for making the syscall - // some of these are defined in the syscall package, but not all. - // Also since Windows client doesn't get access to the syscall package, need to - // define these here - rlimitAs = 9 - rlimitCore = 4 - rlimitCPU = 0 - rlimitData = 2 - rlimitFsize = 1 - rlimitLocks = 10 - rlimitMemlock = 8 - rlimitMsgqueue = 12 - rlimitNice = 13 - rlimitNofile = 7 - rlimitNproc = 6 - rlimitRss = 5 - rlimitRtprio = 14 - rlimitRttime = 15 - rlimitSigpending = 11 - rlimitStack = 3 -) - -var ulimitNameMapping = map[string]int{ - //"as": rlimitAs, // Disabled since this doesn't seem usable with the way Docker inits a container. - "core": rlimitCore, - "cpu": rlimitCPU, - "data": rlimitData, - "fsize": rlimitFsize, - "locks": rlimitLocks, - "memlock": rlimitMemlock, - "msgqueue": rlimitMsgqueue, - "nice": rlimitNice, - "nofile": rlimitNofile, - "nproc": rlimitNproc, - "rss": rlimitRss, - "rtprio": rlimitRtprio, - "rttime": rlimitRttime, - "sigpending": rlimitSigpending, - "stack": rlimitStack, -} - -// ParseUlimit parses and returns a Ulimit from the specified string. -func ParseUlimit(val string) (*Ulimit, error) { - parts := strings.SplitN(val, "=", 2) - if len(parts) != 2 { - return nil, fmt.Errorf("invalid ulimit argument: %s", val) - } - - if _, exists := ulimitNameMapping[parts[0]]; !exists { - return nil, fmt.Errorf("invalid ulimit type: %s", parts[0]) - } - - var ( - soft int64 - hard = &soft // default to soft in case no hard was set - temp int64 - err error - ) - switch limitVals := strings.Split(parts[1], ":"); len(limitVals) { - case 2: - temp, err = strconv.ParseInt(limitVals[1], 10, 64) - if err != nil { - return nil, err - } - hard = &temp - fallthrough - case 1: - soft, err = strconv.ParseInt(limitVals[0], 10, 64) - if err != nil { - return nil, err - } - default: - return nil, fmt.Errorf("too many limit value arguments - %s, can only have up to two, `soft[:hard]`", parts[1]) - } - - if *hard != -1 { - if soft == -1 { - return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: soft: -1 (unlimited), hard: %d", *hard) - } - if soft > *hard { - return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: %d > %d", soft, *hard) - } - } - - return &Ulimit{Name: parts[0], Soft: soft, Hard: *hard}, nil -} - -// GetRlimit returns the RLimit corresponding to Ulimit. -func (u *Ulimit) GetRlimit() (*Rlimit, error) { - t, exists := ulimitNameMapping[u.Name] - if !exists { - return nil, fmt.Errorf("invalid ulimit name %s", u.Name) - } - - return &Rlimit{Type: t, Soft: uint64(u.Soft), Hard: uint64(u.Hard)}, nil -} - -func (u *Ulimit) String() string { - return fmt.Sprintf("%s=%d:%d", u.Name, u.Soft, u.Hard) -} diff --git a/vendor/github.com/dustin/go-humanize/.travis.yml b/vendor/github.com/dustin/go-humanize/.travis.yml deleted file mode 100644 index ac12e485..00000000 --- a/vendor/github.com/dustin/go-humanize/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -sudo: false -language: go -go_import_path: github.com/dustin/go-humanize -go: - - 1.13.x - - 1.14.x - - 1.15.x - - 1.16.x - - stable - - master -matrix: - allow_failures: - - go: master - fast_finish: true -install: - - # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step). -script: - - diff -u <(echo -n) <(gofmt -d -s .) - - go vet . - - go install -v -race ./... - - go test -v -race ./... diff --git a/vendor/github.com/dustin/go-humanize/LICENSE b/vendor/github.com/dustin/go-humanize/LICENSE deleted file mode 100644 index 8d9a94a9..00000000 --- a/vendor/github.com/dustin/go-humanize/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2005-2008 Dustin Sallings - -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/github.com/dustin/go-humanize/README.markdown b/vendor/github.com/dustin/go-humanize/README.markdown deleted file mode 100644 index 7d0b16b3..00000000 --- a/vendor/github.com/dustin/go-humanize/README.markdown +++ /dev/null @@ -1,124 +0,0 @@ -# Humane Units [![Build Status](https://travis-ci.org/dustin/go-humanize.svg?branch=master)](https://travis-ci.org/dustin/go-humanize) [![GoDoc](https://godoc.org/github.com/dustin/go-humanize?status.svg)](https://godoc.org/github.com/dustin/go-humanize) - -Just a few functions for helping humanize times and sizes. - -`go get` it as `github.com/dustin/go-humanize`, import it as -`"github.com/dustin/go-humanize"`, use it as `humanize`. - -See [godoc](https://pkg.go.dev/github.com/dustin/go-humanize) for -complete documentation. - -## Sizes - -This lets you take numbers like `82854982` and convert them to useful -strings like, `83 MB` or `79 MiB` (whichever you prefer). - -Example: - -```go -fmt.Printf("That file is %s.", humanize.Bytes(82854982)) // That file is 83 MB. -``` - -## Times - -This lets you take a `time.Time` and spit it out in relative terms. -For example, `12 seconds ago` or `3 days from now`. - -Example: - -```go -fmt.Printf("This was touched %s.", humanize.Time(someTimeInstance)) // This was touched 7 hours ago. -``` - -Thanks to Kyle Lemons for the time implementation from an IRC -conversation one day. It's pretty neat. - -## Ordinals - -From a [mailing list discussion][odisc] where a user wanted to be able -to label ordinals. - - 0 -> 0th - 1 -> 1st - 2 -> 2nd - 3 -> 3rd - 4 -> 4th - [...] - -Example: - -```go -fmt.Printf("You're my %s best friend.", humanize.Ordinal(193)) // You are my 193rd best friend. -``` - -## Commas - -Want to shove commas into numbers? Be my guest. - - 0 -> 0 - 100 -> 100 - 1000 -> 1,000 - 1000000000 -> 1,000,000,000 - -100000 -> -100,000 - -Example: - -```go -fmt.Printf("You owe $%s.\n", humanize.Comma(6582491)) // You owe $6,582,491. -``` - -## Ftoa - -Nicer float64 formatter that removes trailing zeros. - -```go -fmt.Printf("%f", 2.24) // 2.240000 -fmt.Printf("%s", humanize.Ftoa(2.24)) // 2.24 -fmt.Printf("%f", 2.0) // 2.000000 -fmt.Printf("%s", humanize.Ftoa(2.0)) // 2 -``` - -## SI notation - -Format numbers with [SI notation][sinotation]. - -Example: - -```go -humanize.SI(0.00000000223, "M") // 2.23 nM -``` - -## English-specific functions - -The following functions are in the `humanize/english` subpackage. - -### Plurals - -Simple English pluralization - -```go -english.PluralWord(1, "object", "") // object -english.PluralWord(42, "object", "") // objects -english.PluralWord(2, "bus", "") // buses -english.PluralWord(99, "locus", "loci") // loci - -english.Plural(1, "object", "") // 1 object -english.Plural(42, "object", "") // 42 objects -english.Plural(2, "bus", "") // 2 buses -english.Plural(99, "locus", "loci") // 99 loci -``` - -### Word series - -Format comma-separated words lists with conjuctions: - -```go -english.WordSeries([]string{"foo"}, "and") // foo -english.WordSeries([]string{"foo", "bar"}, "and") // foo and bar -english.WordSeries([]string{"foo", "bar", "baz"}, "and") // foo, bar and baz - -english.OxfordWordSeries([]string{"foo", "bar", "baz"}, "and") // foo, bar, and baz -``` - -[odisc]: https://groups.google.com/d/topic/golang-nuts/l8NhI74jl-4/discussion -[sinotation]: http://en.wikipedia.org/wiki/Metric_prefix diff --git a/vendor/github.com/dustin/go-humanize/big.go b/vendor/github.com/dustin/go-humanize/big.go deleted file mode 100644 index f49dc337..00000000 --- a/vendor/github.com/dustin/go-humanize/big.go +++ /dev/null @@ -1,31 +0,0 @@ -package humanize - -import ( - "math/big" -) - -// order of magnitude (to a max order) -func oomm(n, b *big.Int, maxmag int) (float64, int) { - mag := 0 - m := &big.Int{} - for n.Cmp(b) >= 0 { - n.DivMod(n, b, m) - mag++ - if mag == maxmag && maxmag >= 0 { - break - } - } - return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag -} - -// total order of magnitude -// (same as above, but with no upper limit) -func oom(n, b *big.Int) (float64, int) { - mag := 0 - m := &big.Int{} - for n.Cmp(b) >= 0 { - n.DivMod(n, b, m) - mag++ - } - return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag -} diff --git a/vendor/github.com/dustin/go-humanize/bigbytes.go b/vendor/github.com/dustin/go-humanize/bigbytes.go deleted file mode 100644 index 3b015fd5..00000000 --- a/vendor/github.com/dustin/go-humanize/bigbytes.go +++ /dev/null @@ -1,189 +0,0 @@ -package humanize - -import ( - "fmt" - "math/big" - "strings" - "unicode" -) - -var ( - bigIECExp = big.NewInt(1024) - - // BigByte is one byte in bit.Ints - BigByte = big.NewInt(1) - // BigKiByte is 1,024 bytes in bit.Ints - BigKiByte = (&big.Int{}).Mul(BigByte, bigIECExp) - // BigMiByte is 1,024 k bytes in bit.Ints - BigMiByte = (&big.Int{}).Mul(BigKiByte, bigIECExp) - // BigGiByte is 1,024 m bytes in bit.Ints - BigGiByte = (&big.Int{}).Mul(BigMiByte, bigIECExp) - // BigTiByte is 1,024 g bytes in bit.Ints - BigTiByte = (&big.Int{}).Mul(BigGiByte, bigIECExp) - // BigPiByte is 1,024 t bytes in bit.Ints - BigPiByte = (&big.Int{}).Mul(BigTiByte, bigIECExp) - // BigEiByte is 1,024 p bytes in bit.Ints - BigEiByte = (&big.Int{}).Mul(BigPiByte, bigIECExp) - // BigZiByte is 1,024 e bytes in bit.Ints - BigZiByte = (&big.Int{}).Mul(BigEiByte, bigIECExp) - // BigYiByte is 1,024 z bytes in bit.Ints - BigYiByte = (&big.Int{}).Mul(BigZiByte, bigIECExp) - // BigRiByte is 1,024 y bytes in bit.Ints - BigRiByte = (&big.Int{}).Mul(BigYiByte, bigIECExp) - // BigQiByte is 1,024 r bytes in bit.Ints - BigQiByte = (&big.Int{}).Mul(BigRiByte, bigIECExp) -) - -var ( - bigSIExp = big.NewInt(1000) - - // BigSIByte is one SI byte in big.Ints - BigSIByte = big.NewInt(1) - // BigKByte is 1,000 SI bytes in big.Ints - BigKByte = (&big.Int{}).Mul(BigSIByte, bigSIExp) - // BigMByte is 1,000 SI k bytes in big.Ints - BigMByte = (&big.Int{}).Mul(BigKByte, bigSIExp) - // BigGByte is 1,000 SI m bytes in big.Ints - BigGByte = (&big.Int{}).Mul(BigMByte, bigSIExp) - // BigTByte is 1,000 SI g bytes in big.Ints - BigTByte = (&big.Int{}).Mul(BigGByte, bigSIExp) - // BigPByte is 1,000 SI t bytes in big.Ints - BigPByte = (&big.Int{}).Mul(BigTByte, bigSIExp) - // BigEByte is 1,000 SI p bytes in big.Ints - BigEByte = (&big.Int{}).Mul(BigPByte, bigSIExp) - // BigZByte is 1,000 SI e bytes in big.Ints - BigZByte = (&big.Int{}).Mul(BigEByte, bigSIExp) - // BigYByte is 1,000 SI z bytes in big.Ints - BigYByte = (&big.Int{}).Mul(BigZByte, bigSIExp) - // BigRByte is 1,000 SI y bytes in big.Ints - BigRByte = (&big.Int{}).Mul(BigYByte, bigSIExp) - // BigQByte is 1,000 SI r bytes in big.Ints - BigQByte = (&big.Int{}).Mul(BigRByte, bigSIExp) -) - -var bigBytesSizeTable = map[string]*big.Int{ - "b": BigByte, - "kib": BigKiByte, - "kb": BigKByte, - "mib": BigMiByte, - "mb": BigMByte, - "gib": BigGiByte, - "gb": BigGByte, - "tib": BigTiByte, - "tb": BigTByte, - "pib": BigPiByte, - "pb": BigPByte, - "eib": BigEiByte, - "eb": BigEByte, - "zib": BigZiByte, - "zb": BigZByte, - "yib": BigYiByte, - "yb": BigYByte, - "rib": BigRiByte, - "rb": BigRByte, - "qib": BigQiByte, - "qb": BigQByte, - // Without suffix - "": BigByte, - "ki": BigKiByte, - "k": BigKByte, - "mi": BigMiByte, - "m": BigMByte, - "gi": BigGiByte, - "g": BigGByte, - "ti": BigTiByte, - "t": BigTByte, - "pi": BigPiByte, - "p": BigPByte, - "ei": BigEiByte, - "e": BigEByte, - "z": BigZByte, - "zi": BigZiByte, - "y": BigYByte, - "yi": BigYiByte, - "r": BigRByte, - "ri": BigRiByte, - "q": BigQByte, - "qi": BigQiByte, -} - -var ten = big.NewInt(10) - -func humanateBigBytes(s, base *big.Int, sizes []string) string { - if s.Cmp(ten) < 0 { - return fmt.Sprintf("%d B", s) - } - c := (&big.Int{}).Set(s) - val, mag := oomm(c, base, len(sizes)-1) - suffix := sizes[mag] - f := "%.0f %s" - if val < 10 { - f = "%.1f %s" - } - - return fmt.Sprintf(f, val, suffix) - -} - -// BigBytes produces a human readable representation of an SI size. -// -// See also: ParseBigBytes. -// -// BigBytes(82854982) -> 83 MB -func BigBytes(s *big.Int) string { - sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "RB", "QB"} - return humanateBigBytes(s, bigSIExp, sizes) -} - -// BigIBytes produces a human readable representation of an IEC size. -// -// See also: ParseBigBytes. -// -// BigIBytes(82854982) -> 79 MiB -func BigIBytes(s *big.Int) string { - sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB"} - return humanateBigBytes(s, bigIECExp, sizes) -} - -// ParseBigBytes parses a string representation of bytes into the number -// of bytes it represents. -// -// See also: BigBytes, BigIBytes. -// -// ParseBigBytes("42 MB") -> 42000000, nil -// ParseBigBytes("42 mib") -> 44040192, nil -func ParseBigBytes(s string) (*big.Int, error) { - lastDigit := 0 - hasComma := false - for _, r := range s { - if !(unicode.IsDigit(r) || r == '.' || r == ',') { - break - } - if r == ',' { - hasComma = true - } - lastDigit++ - } - - num := s[:lastDigit] - if hasComma { - num = strings.Replace(num, ",", "", -1) - } - - val := &big.Rat{} - _, err := fmt.Sscanf(num, "%f", val) - if err != nil { - return nil, err - } - - extra := strings.ToLower(strings.TrimSpace(s[lastDigit:])) - if m, ok := bigBytesSizeTable[extra]; ok { - mv := (&big.Rat{}).SetInt(m) - val.Mul(val, mv) - rv := &big.Int{} - rv.Div(val.Num(), val.Denom()) - return rv, nil - } - - return nil, fmt.Errorf("unhandled size name: %v", extra) -} diff --git a/vendor/github.com/dustin/go-humanize/bytes.go b/vendor/github.com/dustin/go-humanize/bytes.go deleted file mode 100644 index 0b498f48..00000000 --- a/vendor/github.com/dustin/go-humanize/bytes.go +++ /dev/null @@ -1,143 +0,0 @@ -package humanize - -import ( - "fmt" - "math" - "strconv" - "strings" - "unicode" -) - -// IEC Sizes. -// kibis of bits -const ( - Byte = 1 << (iota * 10) - KiByte - MiByte - GiByte - TiByte - PiByte - EiByte -) - -// SI Sizes. -const ( - IByte = 1 - KByte = IByte * 1000 - MByte = KByte * 1000 - GByte = MByte * 1000 - TByte = GByte * 1000 - PByte = TByte * 1000 - EByte = PByte * 1000 -) - -var bytesSizeTable = map[string]uint64{ - "b": Byte, - "kib": KiByte, - "kb": KByte, - "mib": MiByte, - "mb": MByte, - "gib": GiByte, - "gb": GByte, - "tib": TiByte, - "tb": TByte, - "pib": PiByte, - "pb": PByte, - "eib": EiByte, - "eb": EByte, - // Without suffix - "": Byte, - "ki": KiByte, - "k": KByte, - "mi": MiByte, - "m": MByte, - "gi": GiByte, - "g": GByte, - "ti": TiByte, - "t": TByte, - "pi": PiByte, - "p": PByte, - "ei": EiByte, - "e": EByte, -} - -func logn(n, b float64) float64 { - return math.Log(n) / math.Log(b) -} - -func humanateBytes(s uint64, base float64, sizes []string) string { - if s < 10 { - return fmt.Sprintf("%d B", s) - } - e := math.Floor(logn(float64(s), base)) - suffix := sizes[int(e)] - val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10 - f := "%.0f %s" - if val < 10 { - f = "%.1f %s" - } - - return fmt.Sprintf(f, val, suffix) -} - -// Bytes produces a human readable representation of an SI size. -// -// See also: ParseBytes. -// -// Bytes(82854982) -> 83 MB -func Bytes(s uint64) string { - sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB"} - return humanateBytes(s, 1000, sizes) -} - -// IBytes produces a human readable representation of an IEC size. -// -// See also: ParseBytes. -// -// IBytes(82854982) -> 79 MiB -func IBytes(s uint64) string { - sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"} - return humanateBytes(s, 1024, sizes) -} - -// ParseBytes parses a string representation of bytes into the number -// of bytes it represents. -// -// See Also: Bytes, IBytes. -// -// ParseBytes("42 MB") -> 42000000, nil -// ParseBytes("42 mib") -> 44040192, nil -func ParseBytes(s string) (uint64, error) { - lastDigit := 0 - hasComma := false - for _, r := range s { - if !(unicode.IsDigit(r) || r == '.' || r == ',') { - break - } - if r == ',' { - hasComma = true - } - lastDigit++ - } - - num := s[:lastDigit] - if hasComma { - num = strings.Replace(num, ",", "", -1) - } - - f, err := strconv.ParseFloat(num, 64) - if err != nil { - return 0, err - } - - extra := strings.ToLower(strings.TrimSpace(s[lastDigit:])) - if m, ok := bytesSizeTable[extra]; ok { - f *= float64(m) - if f >= math.MaxUint64 { - return 0, fmt.Errorf("too large: %v", s) - } - return uint64(f), nil - } - - return 0, fmt.Errorf("unhandled size name: %v", extra) -} diff --git a/vendor/github.com/dustin/go-humanize/comma.go b/vendor/github.com/dustin/go-humanize/comma.go deleted file mode 100644 index 520ae3e5..00000000 --- a/vendor/github.com/dustin/go-humanize/comma.go +++ /dev/null @@ -1,116 +0,0 @@ -package humanize - -import ( - "bytes" - "math" - "math/big" - "strconv" - "strings" -) - -// Comma produces a string form of the given number in base 10 with -// commas after every three orders of magnitude. -// -// e.g. Comma(834142) -> 834,142 -func Comma(v int64) string { - sign := "" - - // Min int64 can't be negated to a usable value, so it has to be special cased. - if v == math.MinInt64 { - return "-9,223,372,036,854,775,808" - } - - if v < 0 { - sign = "-" - v = 0 - v - } - - parts := []string{"", "", "", "", "", "", ""} - j := len(parts) - 1 - - for v > 999 { - parts[j] = strconv.FormatInt(v%1000, 10) - switch len(parts[j]) { - case 2: - parts[j] = "0" + parts[j] - case 1: - parts[j] = "00" + parts[j] - } - v = v / 1000 - j-- - } - parts[j] = strconv.Itoa(int(v)) - return sign + strings.Join(parts[j:], ",") -} - -// Commaf produces a string form of the given number in base 10 with -// commas after every three orders of magnitude. -// -// e.g. Commaf(834142.32) -> 834,142.32 -func Commaf(v float64) string { - buf := &bytes.Buffer{} - if v < 0 { - buf.Write([]byte{'-'}) - v = 0 - v - } - - comma := []byte{','} - - parts := strings.Split(strconv.FormatFloat(v, 'f', -1, 64), ".") - pos := 0 - if len(parts[0])%3 != 0 { - pos += len(parts[0]) % 3 - buf.WriteString(parts[0][:pos]) - buf.Write(comma) - } - for ; pos < len(parts[0]); pos += 3 { - buf.WriteString(parts[0][pos : pos+3]) - buf.Write(comma) - } - buf.Truncate(buf.Len() - 1) - - if len(parts) > 1 { - buf.Write([]byte{'.'}) - buf.WriteString(parts[1]) - } - return buf.String() -} - -// CommafWithDigits works like the Commaf but limits the resulting -// string to the given number of decimal places. -// -// e.g. CommafWithDigits(834142.32, 1) -> 834,142.3 -func CommafWithDigits(f float64, decimals int) string { - return stripTrailingDigits(Commaf(f), decimals) -} - -// BigComma produces a string form of the given big.Int in base 10 -// with commas after every three orders of magnitude. -func BigComma(b *big.Int) string { - sign := "" - if b.Sign() < 0 { - sign = "-" - b.Abs(b) - } - - athousand := big.NewInt(1000) - c := (&big.Int{}).Set(b) - _, m := oom(c, athousand) - parts := make([]string, m+1) - j := len(parts) - 1 - - mod := &big.Int{} - for b.Cmp(athousand) >= 0 { - b.DivMod(b, athousand, mod) - parts[j] = strconv.FormatInt(mod.Int64(), 10) - switch len(parts[j]) { - case 2: - parts[j] = "0" + parts[j] - case 1: - parts[j] = "00" + parts[j] - } - j-- - } - parts[j] = strconv.Itoa(int(b.Int64())) - return sign + strings.Join(parts[j:], ",") -} diff --git a/vendor/github.com/dustin/go-humanize/commaf.go b/vendor/github.com/dustin/go-humanize/commaf.go deleted file mode 100644 index 2bc83a03..00000000 --- a/vendor/github.com/dustin/go-humanize/commaf.go +++ /dev/null @@ -1,41 +0,0 @@ -//go:build go1.6 -// +build go1.6 - -package humanize - -import ( - "bytes" - "math/big" - "strings" -) - -// BigCommaf produces a string form of the given big.Float in base 10 -// with commas after every three orders of magnitude. -func BigCommaf(v *big.Float) string { - buf := &bytes.Buffer{} - if v.Sign() < 0 { - buf.Write([]byte{'-'}) - v.Abs(v) - } - - comma := []byte{','} - - parts := strings.Split(v.Text('f', -1), ".") - pos := 0 - if len(parts[0])%3 != 0 { - pos += len(parts[0]) % 3 - buf.WriteString(parts[0][:pos]) - buf.Write(comma) - } - for ; pos < len(parts[0]); pos += 3 { - buf.WriteString(parts[0][pos : pos+3]) - buf.Write(comma) - } - buf.Truncate(buf.Len() - 1) - - if len(parts) > 1 { - buf.Write([]byte{'.'}) - buf.WriteString(parts[1]) - } - return buf.String() -} diff --git a/vendor/github.com/dustin/go-humanize/ftoa.go b/vendor/github.com/dustin/go-humanize/ftoa.go deleted file mode 100644 index bce923f3..00000000 --- a/vendor/github.com/dustin/go-humanize/ftoa.go +++ /dev/null @@ -1,49 +0,0 @@ -package humanize - -import ( - "strconv" - "strings" -) - -func stripTrailingZeros(s string) string { - if !strings.ContainsRune(s, '.') { - return s - } - offset := len(s) - 1 - for offset > 0 { - if s[offset] == '.' { - offset-- - break - } - if s[offset] != '0' { - break - } - offset-- - } - return s[:offset+1] -} - -func stripTrailingDigits(s string, digits int) string { - if i := strings.Index(s, "."); i >= 0 { - if digits <= 0 { - return s[:i] - } - i++ - if i+digits >= len(s) { - return s - } - return s[:i+digits] - } - return s -} - -// Ftoa converts a float to a string with no trailing zeros. -func Ftoa(num float64) string { - return stripTrailingZeros(strconv.FormatFloat(num, 'f', 6, 64)) -} - -// FtoaWithDigits converts a float to a string but limits the resulting string -// to the given number of decimal places, and no trailing zeros. -func FtoaWithDigits(num float64, digits int) string { - return stripTrailingZeros(stripTrailingDigits(strconv.FormatFloat(num, 'f', 6, 64), digits)) -} diff --git a/vendor/github.com/dustin/go-humanize/humanize.go b/vendor/github.com/dustin/go-humanize/humanize.go deleted file mode 100644 index a2c2da31..00000000 --- a/vendor/github.com/dustin/go-humanize/humanize.go +++ /dev/null @@ -1,8 +0,0 @@ -/* -Package humanize converts boring ugly numbers to human-friendly strings and back. - -Durations can be turned into strings such as "3 days ago", numbers -representing sizes like 82854982 into useful strings like, "83 MB" or -"79 MiB" (whichever you prefer). -*/ -package humanize diff --git a/vendor/github.com/dustin/go-humanize/number.go b/vendor/github.com/dustin/go-humanize/number.go deleted file mode 100644 index 6470d0d4..00000000 --- a/vendor/github.com/dustin/go-humanize/number.go +++ /dev/null @@ -1,192 +0,0 @@ -package humanize - -/* -Slightly adapted from the source to fit go-humanize. - -Author: https://github.com/gorhill -Source: https://gist.github.com/gorhill/5285193 - -*/ - -import ( - "math" - "strconv" -) - -var ( - renderFloatPrecisionMultipliers = [...]float64{ - 1, - 10, - 100, - 1000, - 10000, - 100000, - 1000000, - 10000000, - 100000000, - 1000000000, - } - - renderFloatPrecisionRounders = [...]float64{ - 0.5, - 0.05, - 0.005, - 0.0005, - 0.00005, - 0.000005, - 0.0000005, - 0.00000005, - 0.000000005, - 0.0000000005, - } -) - -// FormatFloat produces a formatted number as string based on the following user-specified criteria: -// * thousands separator -// * decimal separator -// * decimal precision -// -// Usage: s := RenderFloat(format, n) -// The format parameter tells how to render the number n. -// -// See examples: http://play.golang.org/p/LXc1Ddm1lJ -// -// Examples of format strings, given n = 12345.6789: -// "#,###.##" => "12,345.67" -// "#,###." => "12,345" -// "#,###" => "12345,678" -// "#\u202F###,##" => "12 345,68" -// "#.###,###### => 12.345,678900 -// "" (aka default format) => 12,345.67 -// -// The highest precision allowed is 9 digits after the decimal symbol. -// There is also a version for integer number, FormatInteger(), -// which is convenient for calls within template. -func FormatFloat(format string, n float64) string { - // Special cases: - // NaN = "NaN" - // +Inf = "+Infinity" - // -Inf = "-Infinity" - if math.IsNaN(n) { - return "NaN" - } - if n > math.MaxFloat64 { - return "Infinity" - } - if n < (0.0 - math.MaxFloat64) { - return "-Infinity" - } - - // default format - precision := 2 - decimalStr := "." - thousandStr := "," - positiveStr := "" - negativeStr := "-" - - if len(format) > 0 { - format := []rune(format) - - // If there is an explicit format directive, - // then default values are these: - precision = 9 - thousandStr = "" - - // collect indices of meaningful formatting directives - formatIndx := []int{} - for i, char := range format { - if char != '#' && char != '0' { - formatIndx = append(formatIndx, i) - } - } - - if len(formatIndx) > 0 { - // Directive at index 0: - // Must be a '+' - // Raise an error if not the case - // index: 0123456789 - // +0.000,000 - // +000,000.0 - // +0000.00 - // +0000 - if formatIndx[0] == 0 { - if format[formatIndx[0]] != '+' { - panic("RenderFloat(): invalid positive sign directive") - } - positiveStr = "+" - formatIndx = formatIndx[1:] - } - - // Two directives: - // First is thousands separator - // Raise an error if not followed by 3-digit - // 0123456789 - // 0.000,000 - // 000,000.00 - if len(formatIndx) == 2 { - if (formatIndx[1] - formatIndx[0]) != 4 { - panic("RenderFloat(): thousands separator directive must be followed by 3 digit-specifiers") - } - thousandStr = string(format[formatIndx[0]]) - formatIndx = formatIndx[1:] - } - - // One directive: - // Directive is decimal separator - // The number of digit-specifier following the separator indicates wanted precision - // 0123456789 - // 0.00 - // 000,0000 - if len(formatIndx) == 1 { - decimalStr = string(format[formatIndx[0]]) - precision = len(format) - formatIndx[0] - 1 - } - } - } - - // generate sign part - var signStr string - if n >= 0.000000001 { - signStr = positiveStr - } else if n <= -0.000000001 { - signStr = negativeStr - n = -n - } else { - signStr = "" - n = 0.0 - } - - // split number into integer and fractional parts - intf, fracf := math.Modf(n + renderFloatPrecisionRounders[precision]) - - // generate integer part string - intStr := strconv.FormatInt(int64(intf), 10) - - // add thousand separator if required - if len(thousandStr) > 0 { - for i := len(intStr); i > 3; { - i -= 3 - intStr = intStr[:i] + thousandStr + intStr[i:] - } - } - - // no fractional part, we can leave now - if precision == 0 { - return signStr + intStr - } - - // generate fractional part - fracStr := strconv.Itoa(int(fracf * renderFloatPrecisionMultipliers[precision])) - // may need padding - if len(fracStr) < precision { - fracStr = "000000000000000"[:precision-len(fracStr)] + fracStr - } - - return signStr + intStr + decimalStr + fracStr -} - -// FormatInteger produces a formatted number as string. -// See FormatFloat. -func FormatInteger(format string, n int) string { - return FormatFloat(format, float64(n)) -} diff --git a/vendor/github.com/dustin/go-humanize/ordinals.go b/vendor/github.com/dustin/go-humanize/ordinals.go deleted file mode 100644 index 43d88a86..00000000 --- a/vendor/github.com/dustin/go-humanize/ordinals.go +++ /dev/null @@ -1,25 +0,0 @@ -package humanize - -import "strconv" - -// Ordinal gives you the input number in a rank/ordinal format. -// -// Ordinal(3) -> 3rd -func Ordinal(x int) string { - suffix := "th" - switch x % 10 { - case 1: - if x%100 != 11 { - suffix = "st" - } - case 2: - if x%100 != 12 { - suffix = "nd" - } - case 3: - if x%100 != 13 { - suffix = "rd" - } - } - return strconv.Itoa(x) + suffix -} diff --git a/vendor/github.com/dustin/go-humanize/si.go b/vendor/github.com/dustin/go-humanize/si.go deleted file mode 100644 index 8b850198..00000000 --- a/vendor/github.com/dustin/go-humanize/si.go +++ /dev/null @@ -1,127 +0,0 @@ -package humanize - -import ( - "errors" - "math" - "regexp" - "strconv" -) - -var siPrefixTable = map[float64]string{ - -30: "q", // quecto - -27: "r", // ronto - -24: "y", // yocto - -21: "z", // zepto - -18: "a", // atto - -15: "f", // femto - -12: "p", // pico - -9: "n", // nano - -6: "µ", // micro - -3: "m", // milli - 0: "", - 3: "k", // kilo - 6: "M", // mega - 9: "G", // giga - 12: "T", // tera - 15: "P", // peta - 18: "E", // exa - 21: "Z", // zetta - 24: "Y", // yotta - 27: "R", // ronna - 30: "Q", // quetta -} - -var revSIPrefixTable = revfmap(siPrefixTable) - -// revfmap reverses the map and precomputes the power multiplier -func revfmap(in map[float64]string) map[string]float64 { - rv := map[string]float64{} - for k, v := range in { - rv[v] = math.Pow(10, k) - } - return rv -} - -var riParseRegex *regexp.Regexp - -func init() { - ri := `^([\-0-9.]+)\s?([` - for _, v := range siPrefixTable { - ri += v - } - ri += `]?)(.*)` - - riParseRegex = regexp.MustCompile(ri) -} - -// ComputeSI finds the most appropriate SI prefix for the given number -// and returns the prefix along with the value adjusted to be within -// that prefix. -// -// See also: SI, ParseSI. -// -// e.g. ComputeSI(2.2345e-12) -> (2.2345, "p") -func ComputeSI(input float64) (float64, string) { - if input == 0 { - return 0, "" - } - mag := math.Abs(input) - exponent := math.Floor(logn(mag, 10)) - exponent = math.Floor(exponent/3) * 3 - - value := mag / math.Pow(10, exponent) - - // Handle special case where value is exactly 1000.0 - // Should return 1 M instead of 1000 k - if value == 1000.0 { - exponent += 3 - value = mag / math.Pow(10, exponent) - } - - value = math.Copysign(value, input) - - prefix := siPrefixTable[exponent] - return value, prefix -} - -// SI returns a string with default formatting. -// -// SI uses Ftoa to format float value, removing trailing zeros. -// -// See also: ComputeSI, ParseSI. -// -// e.g. SI(1000000, "B") -> 1 MB -// e.g. SI(2.2345e-12, "F") -> 2.2345 pF -func SI(input float64, unit string) string { - value, prefix := ComputeSI(input) - return Ftoa(value) + " " + prefix + unit -} - -// SIWithDigits works like SI but limits the resulting string to the -// given number of decimal places. -// -// e.g. SIWithDigits(1000000, 0, "B") -> 1 MB -// e.g. SIWithDigits(2.2345e-12, 2, "F") -> 2.23 pF -func SIWithDigits(input float64, decimals int, unit string) string { - value, prefix := ComputeSI(input) - return FtoaWithDigits(value, decimals) + " " + prefix + unit -} - -var errInvalid = errors.New("invalid input") - -// ParseSI parses an SI string back into the number and unit. -// -// See also: SI, ComputeSI. -// -// e.g. ParseSI("2.2345 pF") -> (2.2345e-12, "F", nil) -func ParseSI(input string) (float64, string, error) { - found := riParseRegex.FindStringSubmatch(input) - if len(found) != 4 { - return 0, "", errInvalid - } - mag := revSIPrefixTable[found[2]] - unit := found[3] - - base, err := strconv.ParseFloat(found[1], 64) - return base * mag, unit, err -} diff --git a/vendor/github.com/dustin/go-humanize/times.go b/vendor/github.com/dustin/go-humanize/times.go deleted file mode 100644 index dd3fbf5e..00000000 --- a/vendor/github.com/dustin/go-humanize/times.go +++ /dev/null @@ -1,117 +0,0 @@ -package humanize - -import ( - "fmt" - "math" - "sort" - "time" -) - -// Seconds-based time units -const ( - Day = 24 * time.Hour - Week = 7 * Day - Month = 30 * Day - Year = 12 * Month - LongTime = 37 * Year -) - -// Time formats a time into a relative string. -// -// Time(someT) -> "3 weeks ago" -func Time(then time.Time) string { - return RelTime(then, time.Now(), "ago", "from now") -} - -// A RelTimeMagnitude struct contains a relative time point at which -// the relative format of time will switch to a new format string. A -// slice of these in ascending order by their "D" field is passed to -// CustomRelTime to format durations. -// -// The Format field is a string that may contain a "%s" which will be -// replaced with the appropriate signed label (e.g. "ago" or "from -// now") and a "%d" that will be replaced by the quantity. -// -// The DivBy field is the amount of time the time difference must be -// divided by in order to display correctly. -// -// e.g. if D is 2*time.Minute and you want to display "%d minutes %s" -// DivBy should be time.Minute so whatever the duration is will be -// expressed in minutes. -type RelTimeMagnitude struct { - D time.Duration - Format string - DivBy time.Duration -} - -var defaultMagnitudes = []RelTimeMagnitude{ - {time.Second, "now", time.Second}, - {2 * time.Second, "1 second %s", 1}, - {time.Minute, "%d seconds %s", time.Second}, - {2 * time.Minute, "1 minute %s", 1}, - {time.Hour, "%d minutes %s", time.Minute}, - {2 * time.Hour, "1 hour %s", 1}, - {Day, "%d hours %s", time.Hour}, - {2 * Day, "1 day %s", 1}, - {Week, "%d days %s", Day}, - {2 * Week, "1 week %s", 1}, - {Month, "%d weeks %s", Week}, - {2 * Month, "1 month %s", 1}, - {Year, "%d months %s", Month}, - {18 * Month, "1 year %s", 1}, - {2 * Year, "2 years %s", 1}, - {LongTime, "%d years %s", Year}, - {math.MaxInt64, "a long while %s", 1}, -} - -// RelTime formats a time into a relative string. -// -// It takes two times and two labels. In addition to the generic time -// delta string (e.g. 5 minutes), the labels are used applied so that -// the label corresponding to the smaller time is applied. -// -// RelTime(timeInPast, timeInFuture, "earlier", "later") -> "3 weeks earlier" -func RelTime(a, b time.Time, albl, blbl string) string { - return CustomRelTime(a, b, albl, blbl, defaultMagnitudes) -} - -// CustomRelTime formats a time into a relative string. -// -// It takes two times two labels and a table of relative time formats. -// In addition to the generic time delta string (e.g. 5 minutes), the -// labels are used applied so that the label corresponding to the -// smaller time is applied. -func CustomRelTime(a, b time.Time, albl, blbl string, magnitudes []RelTimeMagnitude) string { - lbl := albl - diff := b.Sub(a) - - if a.After(b) { - lbl = blbl - diff = a.Sub(b) - } - - n := sort.Search(len(magnitudes), func(i int) bool { - return magnitudes[i].D > diff - }) - - if n >= len(magnitudes) { - n = len(magnitudes) - 1 - } - mag := magnitudes[n] - args := []interface{}{} - escaped := false - for _, ch := range mag.Format { - if escaped { - switch ch { - case 's': - args = append(args, lbl) - case 'd': - args = append(args, diff/mag.DivBy) - } - escaped = false - } else { - escaped = ch == '%' - } - } - return fmt.Sprintf(mag.Format, args...) -} diff --git a/vendor/github.com/fatih/color/LICENSE.md b/vendor/github.com/fatih/color/LICENSE.md deleted file mode 100644 index 25fdaf63..00000000 --- a/vendor/github.com/fatih/color/LICENSE.md +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Fatih Arslan - -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/github.com/fatih/color/README.md b/vendor/github.com/fatih/color/README.md deleted file mode 100644 index be82827c..00000000 --- a/vendor/github.com/fatih/color/README.md +++ /dev/null @@ -1,176 +0,0 @@ -# color [![](https://github.com/fatih/color/workflows/build/badge.svg)](https://github.com/fatih/color/actions) [![PkgGoDev](https://pkg.go.dev/badge/github.com/fatih/color)](https://pkg.go.dev/github.com/fatih/color) - -Color lets you use colorized outputs in terms of [ANSI Escape -Codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) in Go (Golang). It -has support for Windows too! The API can be used in several ways, pick one that -suits you. - -![Color](https://user-images.githubusercontent.com/438920/96832689-03b3e000-13f4-11eb-9803-46f4c4de3406.jpg) - -## Install - -```bash -go get github.com/fatih/color -``` - -## Examples - -### Standard colors - -```go -// Print with default helper functions -color.Cyan("Prints text in cyan.") - -// A newline will be appended automatically -color.Blue("Prints %s in blue.", "text") - -// These are using the default foreground colors -color.Red("We have red") -color.Magenta("And many others ..") - -``` - -### Mix and reuse colors - -```go -// Create a new color object -c := color.New(color.FgCyan).Add(color.Underline) -c.Println("Prints cyan text with an underline.") - -// Or just add them to New() -d := color.New(color.FgCyan, color.Bold) -d.Printf("This prints bold cyan %s\n", "too!.") - -// Mix up foreground and background colors, create new mixes! -red := color.New(color.FgRed) - -boldRed := red.Add(color.Bold) -boldRed.Println("This will print text in bold red.") - -whiteBackground := red.Add(color.BgWhite) -whiteBackground.Println("Red text with white background.") -``` - -### Use your own output (io.Writer) - -```go -// Use your own io.Writer output -color.New(color.FgBlue).Fprintln(myWriter, "blue color!") - -blue := color.New(color.FgBlue) -blue.Fprint(writer, "This will print text in blue.") -``` - -### Custom print functions (PrintFunc) - -```go -// Create a custom print function for convenience -red := color.New(color.FgRed).PrintfFunc() -red("Warning") -red("Error: %s", err) - -// Mix up multiple attributes -notice := color.New(color.Bold, color.FgGreen).PrintlnFunc() -notice("Don't forget this...") -``` - -### Custom fprint functions (FprintFunc) - -```go -blue := color.New(color.FgBlue).FprintfFunc() -blue(myWriter, "important notice: %s", stars) - -// Mix up with multiple attributes -success := color.New(color.Bold, color.FgGreen).FprintlnFunc() -success(myWriter, "Don't forget this...") -``` - -### Insert into noncolor strings (SprintFunc) - -```go -// Create SprintXxx functions to mix strings with other non-colorized strings: -yellow := color.New(color.FgYellow).SprintFunc() -red := color.New(color.FgRed).SprintFunc() -fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error")) - -info := color.New(color.FgWhite, color.BgGreen).SprintFunc() -fmt.Printf("This %s rocks!\n", info("package")) - -// Use helper functions -fmt.Println("This", color.RedString("warning"), "should be not neglected.") -fmt.Printf("%v %v\n", color.GreenString("Info:"), "an important message.") - -// Windows supported too! Just don't forget to change the output to color.Output -fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS")) -``` - -### Plug into existing code - -```go -// Use handy standard colors -color.Set(color.FgYellow) - -fmt.Println("Existing text will now be in yellow") -fmt.Printf("This one %s\n", "too") - -color.Unset() // Don't forget to unset - -// You can mix up parameters -color.Set(color.FgMagenta, color.Bold) -defer color.Unset() // Use it in your function - -fmt.Println("All text will now be bold magenta.") -``` - -### Disable/Enable color - -There might be a case where you want to explicitly disable/enable color output. the -`go-isatty` package will automatically disable color output for non-tty output streams -(for example if the output were piped directly to `less`). - -The `color` package also disables color output if the [`NO_COLOR`](https://no-color.org) environment -variable is set to a non-empty string. - -`Color` has support to disable/enable colors programmatically both globally and -for single color definitions. For example suppose you have a CLI app and a -`-no-color` bool flag. You can easily disable the color output with: - -```go -var flagNoColor = flag.Bool("no-color", false, "Disable color output") - -if *flagNoColor { - color.NoColor = true // disables colorized output -} -``` - -It also has support for single color definitions (local). You can -disable/enable color output on the fly: - -```go -c := color.New(color.FgCyan) -c.Println("Prints cyan text") - -c.DisableColor() -c.Println("This is printed without any color") - -c.EnableColor() -c.Println("This prints again cyan...") -``` - -## GitHub Actions - -To output color in GitHub Actions (or other CI systems that support ANSI colors), make sure to set `color.NoColor = false` so that it bypasses the check for non-tty output streams. - -## Todo - -* Save/Return previous values -* Evaluate fmt.Formatter interface - -## Credits - -* [Fatih Arslan](https://github.com/fatih) -* Windows support via @mattn: [colorable](https://github.com/mattn/go-colorable) - -## License - -The MIT License (MIT) - see [`LICENSE.md`](https://github.com/fatih/color/blob/master/LICENSE.md) for more details diff --git a/vendor/github.com/fatih/color/color.go b/vendor/github.com/fatih/color/color.go deleted file mode 100644 index 889f9e77..00000000 --- a/vendor/github.com/fatih/color/color.go +++ /dev/null @@ -1,616 +0,0 @@ -package color - -import ( - "fmt" - "io" - "os" - "strconv" - "strings" - "sync" - - "github.com/mattn/go-colorable" - "github.com/mattn/go-isatty" -) - -var ( - // NoColor defines if the output is colorized or not. It's dynamically set to - // false or true based on the stdout's file descriptor referring to a terminal - // or not. It's also set to true if the NO_COLOR environment variable is - // set (regardless of its value). This is a global option and affects all - // colors. For more control over each color block use the methods - // DisableColor() individually. - NoColor = noColorIsSet() || os.Getenv("TERM") == "dumb" || - (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) - - // Output defines the standard output of the print functions. By default, - // os.Stdout is used. - Output = colorable.NewColorableStdout() - - // Error defines a color supporting writer for os.Stderr. - Error = colorable.NewColorableStderr() - - // colorsCache is used to reduce the count of created Color objects and - // allows to reuse already created objects with required Attribute. - colorsCache = make(map[Attribute]*Color) - colorsCacheMu sync.Mutex // protects colorsCache -) - -// noColorIsSet returns true if the environment variable NO_COLOR is set to a non-empty string. -func noColorIsSet() bool { - return os.Getenv("NO_COLOR") != "" -} - -// Color defines a custom color object which is defined by SGR parameters. -type Color struct { - params []Attribute - noColor *bool -} - -// Attribute defines a single SGR Code -type Attribute int - -const escape = "\x1b" - -// Base attributes -const ( - Reset Attribute = iota - Bold - Faint - Italic - Underline - BlinkSlow - BlinkRapid - ReverseVideo - Concealed - CrossedOut -) - -// Foreground text colors -const ( - FgBlack Attribute = iota + 30 - FgRed - FgGreen - FgYellow - FgBlue - FgMagenta - FgCyan - FgWhite -) - -// Foreground Hi-Intensity text colors -const ( - FgHiBlack Attribute = iota + 90 - FgHiRed - FgHiGreen - FgHiYellow - FgHiBlue - FgHiMagenta - FgHiCyan - FgHiWhite -) - -// Background text colors -const ( - BgBlack Attribute = iota + 40 - BgRed - BgGreen - BgYellow - BgBlue - BgMagenta - BgCyan - BgWhite -) - -// Background Hi-Intensity text colors -const ( - BgHiBlack Attribute = iota + 100 - BgHiRed - BgHiGreen - BgHiYellow - BgHiBlue - BgHiMagenta - BgHiCyan - BgHiWhite -) - -// New returns a newly created color object. -func New(value ...Attribute) *Color { - c := &Color{ - params: make([]Attribute, 0), - } - - if noColorIsSet() { - c.noColor = boolPtr(true) - } - - c.Add(value...) - return c -} - -// Set sets the given parameters immediately. It will change the color of -// output with the given SGR parameters until color.Unset() is called. -func Set(p ...Attribute) *Color { - c := New(p...) - c.Set() - return c -} - -// Unset resets all escape attributes and clears the output. Usually should -// be called after Set(). -func Unset() { - if NoColor { - return - } - - fmt.Fprintf(Output, "%s[%dm", escape, Reset) -} - -// Set sets the SGR sequence. -func (c *Color) Set() *Color { - if c.isNoColorSet() { - return c - } - - fmt.Fprint(Output, c.format()) - return c -} - -func (c *Color) unset() { - if c.isNoColorSet() { - return - } - - Unset() -} - -// SetWriter is used to set the SGR sequence with the given io.Writer. This is -// a low-level function, and users should use the higher-level functions, such -// as color.Fprint, color.Print, etc. -func (c *Color) SetWriter(w io.Writer) *Color { - if c.isNoColorSet() { - return c - } - - fmt.Fprint(w, c.format()) - return c -} - -// UnsetWriter resets all escape attributes and clears the output with the give -// io.Writer. Usually should be called after SetWriter(). -func (c *Color) UnsetWriter(w io.Writer) { - if c.isNoColorSet() { - return - } - - if NoColor { - return - } - - fmt.Fprintf(w, "%s[%dm", escape, Reset) -} - -// Add is used to chain SGR parameters. Use as many as parameters to combine -// and create custom color objects. Example: Add(color.FgRed, color.Underline). -func (c *Color) Add(value ...Attribute) *Color { - c.params = append(c.params, value...) - return c -} - -// Fprint formats using the default formats for its operands and writes to w. -// Spaces are added between operands when neither is a string. -// It returns the number of bytes written and any write error encountered. -// On Windows, users should wrap w with colorable.NewColorable() if w is of -// type *os.File. -func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) { - c.SetWriter(w) - defer c.UnsetWriter(w) - - return fmt.Fprint(w, a...) -} - -// Print formats using the default formats for its operands and writes to -// standard output. Spaces are added between operands when neither is a -// string. It returns the number of bytes written and any write error -// encountered. This is the standard fmt.Print() method wrapped with the given -// color. -func (c *Color) Print(a ...interface{}) (n int, err error) { - c.Set() - defer c.unset() - - return fmt.Fprint(Output, a...) -} - -// Fprintf formats according to a format specifier and writes to w. -// It returns the number of bytes written and any write error encountered. -// On Windows, users should wrap w with colorable.NewColorable() if w is of -// type *os.File. -func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - c.SetWriter(w) - defer c.UnsetWriter(w) - - return fmt.Fprintf(w, format, a...) -} - -// Printf formats according to a format specifier and writes to standard output. -// It returns the number of bytes written and any write error encountered. -// This is the standard fmt.Printf() method wrapped with the given color. -func (c *Color) Printf(format string, a ...interface{}) (n int, err error) { - c.Set() - defer c.unset() - - return fmt.Fprintf(Output, format, a...) -} - -// Fprintln formats using the default formats for its operands and writes to w. -// Spaces are always added between operands and a newline is appended. -// On Windows, users should wrap w with colorable.NewColorable() if w is of -// type *os.File. -func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - c.SetWriter(w) - defer c.UnsetWriter(w) - - return fmt.Fprintln(w, a...) -} - -// Println formats using the default formats for its operands and writes to -// standard output. Spaces are always added between operands and a newline is -// appended. It returns the number of bytes written and any write error -// encountered. This is the standard fmt.Print() method wrapped with the given -// color. -func (c *Color) Println(a ...interface{}) (n int, err error) { - c.Set() - defer c.unset() - - return fmt.Fprintln(Output, a...) -} - -// Sprint is just like Print, but returns a string instead of printing it. -func (c *Color) Sprint(a ...interface{}) string { - return c.wrap(fmt.Sprint(a...)) -} - -// Sprintln is just like Println, but returns a string instead of printing it. -func (c *Color) Sprintln(a ...interface{}) string { - return c.wrap(fmt.Sprintln(a...)) -} - -// Sprintf is just like Printf, but returns a string instead of printing it. -func (c *Color) Sprintf(format string, a ...interface{}) string { - return c.wrap(fmt.Sprintf(format, a...)) -} - -// FprintFunc returns a new function that prints the passed arguments as -// colorized with color.Fprint(). -func (c *Color) FprintFunc() func(w io.Writer, a ...interface{}) { - return func(w io.Writer, a ...interface{}) { - c.Fprint(w, a...) - } -} - -// PrintFunc returns a new function that prints the passed arguments as -// colorized with color.Print(). -func (c *Color) PrintFunc() func(a ...interface{}) { - return func(a ...interface{}) { - c.Print(a...) - } -} - -// FprintfFunc returns a new function that prints the passed arguments as -// colorized with color.Fprintf(). -func (c *Color) FprintfFunc() func(w io.Writer, format string, a ...interface{}) { - return func(w io.Writer, format string, a ...interface{}) { - c.Fprintf(w, format, a...) - } -} - -// PrintfFunc returns a new function that prints the passed arguments as -// colorized with color.Printf(). -func (c *Color) PrintfFunc() func(format string, a ...interface{}) { - return func(format string, a ...interface{}) { - c.Printf(format, a...) - } -} - -// FprintlnFunc returns a new function that prints the passed arguments as -// colorized with color.Fprintln(). -func (c *Color) FprintlnFunc() func(w io.Writer, a ...interface{}) { - return func(w io.Writer, a ...interface{}) { - c.Fprintln(w, a...) - } -} - -// PrintlnFunc returns a new function that prints the passed arguments as -// colorized with color.Println(). -func (c *Color) PrintlnFunc() func(a ...interface{}) { - return func(a ...interface{}) { - c.Println(a...) - } -} - -// SprintFunc returns a new function that returns colorized strings for the -// given arguments with fmt.Sprint(). Useful to put into or mix into other -// string. Windows users should use this in conjunction with color.Output, example: -// -// put := New(FgYellow).SprintFunc() -// fmt.Fprintf(color.Output, "This is a %s", put("warning")) -func (c *Color) SprintFunc() func(a ...interface{}) string { - return func(a ...interface{}) string { - return c.wrap(fmt.Sprint(a...)) - } -} - -// SprintfFunc returns a new function that returns colorized strings for the -// given arguments with fmt.Sprintf(). Useful to put into or mix into other -// string. Windows users should use this in conjunction with color.Output. -func (c *Color) SprintfFunc() func(format string, a ...interface{}) string { - return func(format string, a ...interface{}) string { - return c.wrap(fmt.Sprintf(format, a...)) - } -} - -// SprintlnFunc returns a new function that returns colorized strings for the -// given arguments with fmt.Sprintln(). Useful to put into or mix into other -// string. Windows users should use this in conjunction with color.Output. -func (c *Color) SprintlnFunc() func(a ...interface{}) string { - return func(a ...interface{}) string { - return c.wrap(fmt.Sprintln(a...)) - } -} - -// sequence returns a formatted SGR sequence to be plugged into a "\x1b[...m" -// an example output might be: "1;36" -> bold cyan -func (c *Color) sequence() string { - format := make([]string, len(c.params)) - for i, v := range c.params { - format[i] = strconv.Itoa(int(v)) - } - - return strings.Join(format, ";") -} - -// wrap wraps the s string with the colors attributes. The string is ready to -// be printed. -func (c *Color) wrap(s string) string { - if c.isNoColorSet() { - return s - } - - return c.format() + s + c.unformat() -} - -func (c *Color) format() string { - return fmt.Sprintf("%s[%sm", escape, c.sequence()) -} - -func (c *Color) unformat() string { - return fmt.Sprintf("%s[%dm", escape, Reset) -} - -// DisableColor disables the color output. Useful to not change any existing -// code and still being able to output. Can be used for flags like -// "--no-color". To enable back use EnableColor() method. -func (c *Color) DisableColor() { - c.noColor = boolPtr(true) -} - -// EnableColor enables the color output. Use it in conjunction with -// DisableColor(). Otherwise, this method has no side effects. -func (c *Color) EnableColor() { - c.noColor = boolPtr(false) -} - -func (c *Color) isNoColorSet() bool { - // check first if we have user set action - if c.noColor != nil { - return *c.noColor - } - - // if not return the global option, which is disabled by default - return NoColor -} - -// Equals returns a boolean value indicating whether two colors are equal. -func (c *Color) Equals(c2 *Color) bool { - if len(c.params) != len(c2.params) { - return false - } - - for _, attr := range c.params { - if !c2.attrExists(attr) { - return false - } - } - - return true -} - -func (c *Color) attrExists(a Attribute) bool { - for _, attr := range c.params { - if attr == a { - return true - } - } - - return false -} - -func boolPtr(v bool) *bool { - return &v -} - -func getCachedColor(p Attribute) *Color { - colorsCacheMu.Lock() - defer colorsCacheMu.Unlock() - - c, ok := colorsCache[p] - if !ok { - c = New(p) - colorsCache[p] = c - } - - return c -} - -func colorPrint(format string, p Attribute, a ...interface{}) { - c := getCachedColor(p) - - if !strings.HasSuffix(format, "\n") { - format += "\n" - } - - if len(a) == 0 { - c.Print(format) - } else { - c.Printf(format, a...) - } -} - -func colorString(format string, p Attribute, a ...interface{}) string { - c := getCachedColor(p) - - if len(a) == 0 { - return c.SprintFunc()(format) - } - - return c.SprintfFunc()(format, a...) -} - -// Black is a convenient helper function to print with black foreground. A -// newline is appended to format by default. -func Black(format string, a ...interface{}) { colorPrint(format, FgBlack, a...) } - -// Red is a convenient helper function to print with red foreground. A -// newline is appended to format by default. -func Red(format string, a ...interface{}) { colorPrint(format, FgRed, a...) } - -// Green is a convenient helper function to print with green foreground. A -// newline is appended to format by default. -func Green(format string, a ...interface{}) { colorPrint(format, FgGreen, a...) } - -// Yellow is a convenient helper function to print with yellow foreground. -// A newline is appended to format by default. -func Yellow(format string, a ...interface{}) { colorPrint(format, FgYellow, a...) } - -// Blue is a convenient helper function to print with blue foreground. A -// newline is appended to format by default. -func Blue(format string, a ...interface{}) { colorPrint(format, FgBlue, a...) } - -// Magenta is a convenient helper function to print with magenta foreground. -// A newline is appended to format by default. -func Magenta(format string, a ...interface{}) { colorPrint(format, FgMagenta, a...) } - -// Cyan is a convenient helper function to print with cyan foreground. A -// newline is appended to format by default. -func Cyan(format string, a ...interface{}) { colorPrint(format, FgCyan, a...) } - -// White is a convenient helper function to print with white foreground. A -// newline is appended to format by default. -func White(format string, a ...interface{}) { colorPrint(format, FgWhite, a...) } - -// BlackString is a convenient helper function to return a string with black -// foreground. -func BlackString(format string, a ...interface{}) string { return colorString(format, FgBlack, a...) } - -// RedString is a convenient helper function to return a string with red -// foreground. -func RedString(format string, a ...interface{}) string { return colorString(format, FgRed, a...) } - -// GreenString is a convenient helper function to return a string with green -// foreground. -func GreenString(format string, a ...interface{}) string { return colorString(format, FgGreen, a...) } - -// YellowString is a convenient helper function to return a string with yellow -// foreground. -func YellowString(format string, a ...interface{}) string { return colorString(format, FgYellow, a...) } - -// BlueString is a convenient helper function to return a string with blue -// foreground. -func BlueString(format string, a ...interface{}) string { return colorString(format, FgBlue, a...) } - -// MagentaString is a convenient helper function to return a string with magenta -// foreground. -func MagentaString(format string, a ...interface{}) string { - return colorString(format, FgMagenta, a...) -} - -// CyanString is a convenient helper function to return a string with cyan -// foreground. -func CyanString(format string, a ...interface{}) string { return colorString(format, FgCyan, a...) } - -// WhiteString is a convenient helper function to return a string with white -// foreground. -func WhiteString(format string, a ...interface{}) string { return colorString(format, FgWhite, a...) } - -// HiBlack is a convenient helper function to print with hi-intensity black foreground. A -// newline is appended to format by default. -func HiBlack(format string, a ...interface{}) { colorPrint(format, FgHiBlack, a...) } - -// HiRed is a convenient helper function to print with hi-intensity red foreground. A -// newline is appended to format by default. -func HiRed(format string, a ...interface{}) { colorPrint(format, FgHiRed, a...) } - -// HiGreen is a convenient helper function to print with hi-intensity green foreground. A -// newline is appended to format by default. -func HiGreen(format string, a ...interface{}) { colorPrint(format, FgHiGreen, a...) } - -// HiYellow is a convenient helper function to print with hi-intensity yellow foreground. -// A newline is appended to format by default. -func HiYellow(format string, a ...interface{}) { colorPrint(format, FgHiYellow, a...) } - -// HiBlue is a convenient helper function to print with hi-intensity blue foreground. A -// newline is appended to format by default. -func HiBlue(format string, a ...interface{}) { colorPrint(format, FgHiBlue, a...) } - -// HiMagenta is a convenient helper function to print with hi-intensity magenta foreground. -// A newline is appended to format by default. -func HiMagenta(format string, a ...interface{}) { colorPrint(format, FgHiMagenta, a...) } - -// HiCyan is a convenient helper function to print with hi-intensity cyan foreground. A -// newline is appended to format by default. -func HiCyan(format string, a ...interface{}) { colorPrint(format, FgHiCyan, a...) } - -// HiWhite is a convenient helper function to print with hi-intensity white foreground. A -// newline is appended to format by default. -func HiWhite(format string, a ...interface{}) { colorPrint(format, FgHiWhite, a...) } - -// HiBlackString is a convenient helper function to return a string with hi-intensity black -// foreground. -func HiBlackString(format string, a ...interface{}) string { - return colorString(format, FgHiBlack, a...) -} - -// HiRedString is a convenient helper function to return a string with hi-intensity red -// foreground. -func HiRedString(format string, a ...interface{}) string { return colorString(format, FgHiRed, a...) } - -// HiGreenString is a convenient helper function to return a string with hi-intensity green -// foreground. -func HiGreenString(format string, a ...interface{}) string { - return colorString(format, FgHiGreen, a...) -} - -// HiYellowString is a convenient helper function to return a string with hi-intensity yellow -// foreground. -func HiYellowString(format string, a ...interface{}) string { - return colorString(format, FgHiYellow, a...) -} - -// HiBlueString is a convenient helper function to return a string with hi-intensity blue -// foreground. -func HiBlueString(format string, a ...interface{}) string { return colorString(format, FgHiBlue, a...) } - -// HiMagentaString is a convenient helper function to return a string with hi-intensity magenta -// foreground. -func HiMagentaString(format string, a ...interface{}) string { - return colorString(format, FgHiMagenta, a...) -} - -// HiCyanString is a convenient helper function to return a string with hi-intensity cyan -// foreground. -func HiCyanString(format string, a ...interface{}) string { return colorString(format, FgHiCyan, a...) } - -// HiWhiteString is a convenient helper function to return a string with hi-intensity white -// foreground. -func HiWhiteString(format string, a ...interface{}) string { - return colorString(format, FgHiWhite, a...) -} diff --git a/vendor/github.com/fatih/color/doc.go b/vendor/github.com/fatih/color/doc.go deleted file mode 100644 index 9491ad54..00000000 --- a/vendor/github.com/fatih/color/doc.go +++ /dev/null @@ -1,134 +0,0 @@ -/* -Package color is an ANSI color package to output colorized or SGR defined -output to the standard output. The API can be used in several way, pick one -that suits you. - -Use simple and default helper functions with predefined foreground colors: - - color.Cyan("Prints text in cyan.") - - // a newline will be appended automatically - color.Blue("Prints %s in blue.", "text") - - // More default foreground colors.. - color.Red("We have red") - color.Yellow("Yellow color too!") - color.Magenta("And many others ..") - - // Hi-intensity colors - color.HiGreen("Bright green color.") - color.HiBlack("Bright black means gray..") - color.HiWhite("Shiny white color!") - -However, there are times when custom color mixes are required. Below are some -examples to create custom color objects and use the print functions of each -separate color object. - - // Create a new color object - c := color.New(color.FgCyan).Add(color.Underline) - c.Println("Prints cyan text with an underline.") - - // Or just add them to New() - d := color.New(color.FgCyan, color.Bold) - d.Printf("This prints bold cyan %s\n", "too!.") - - - // Mix up foreground and background colors, create new mixes! - red := color.New(color.FgRed) - - boldRed := red.Add(color.Bold) - boldRed.Println("This will print text in bold red.") - - whiteBackground := red.Add(color.BgWhite) - whiteBackground.Println("Red text with White background.") - - // Use your own io.Writer output - color.New(color.FgBlue).Fprintln(myWriter, "blue color!") - - blue := color.New(color.FgBlue) - blue.Fprint(myWriter, "This will print text in blue.") - -You can create PrintXxx functions to simplify even more: - - // Create a custom print function for convenient - red := color.New(color.FgRed).PrintfFunc() - red("warning") - red("error: %s", err) - - // Mix up multiple attributes - notice := color.New(color.Bold, color.FgGreen).PrintlnFunc() - notice("don't forget this...") - -You can also FprintXxx functions to pass your own io.Writer: - - blue := color.New(FgBlue).FprintfFunc() - blue(myWriter, "important notice: %s", stars) - - // Mix up with multiple attributes - success := color.New(color.Bold, color.FgGreen).FprintlnFunc() - success(myWriter, don't forget this...") - -Or create SprintXxx functions to mix strings with other non-colorized strings: - - yellow := New(FgYellow).SprintFunc() - red := New(FgRed).SprintFunc() - - fmt.Printf("this is a %s and this is %s.\n", yellow("warning"), red("error")) - - info := New(FgWhite, BgGreen).SprintFunc() - fmt.Printf("this %s rocks!\n", info("package")) - -Windows support is enabled by default. All Print functions work as intended. -However, only for color.SprintXXX functions, user should use fmt.FprintXXX and -set the output to color.Output: - - fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS")) - - info := New(FgWhite, BgGreen).SprintFunc() - fmt.Fprintf(color.Output, "this %s rocks!\n", info("package")) - -Using with existing code is possible. Just use the Set() method to set the -standard output to the given parameters. That way a rewrite of an existing -code is not required. - - // Use handy standard colors. - color.Set(color.FgYellow) - - fmt.Println("Existing text will be now in Yellow") - fmt.Printf("This one %s\n", "too") - - color.Unset() // don't forget to unset - - // You can mix up parameters - color.Set(color.FgMagenta, color.Bold) - defer color.Unset() // use it in your function - - fmt.Println("All text will be now bold magenta.") - -There might be a case where you want to disable color output (for example to -pipe the standard output of your app to somewhere else). `Color` has support to -disable colors both globally and for single color definition. For example -suppose you have a CLI app and a `--no-color` bool flag. You can easily disable -the color output with: - - var flagNoColor = flag.Bool("no-color", false, "Disable color output") - - if *flagNoColor { - color.NoColor = true // disables colorized output - } - -You can also disable the color by setting the NO_COLOR environment variable to any value. - -It also has support for single color definitions (local). You can -disable/enable color output on the fly: - - c := color.New(color.FgCyan) - c.Println("Prints cyan text") - - c.DisableColor() - c.Println("This is printed without any color") - - c.EnableColor() - c.Println("This prints again cyan...") -*/ -package color diff --git a/vendor/github.com/form3tech-oss/jwt-go/.gitignore b/vendor/github.com/form3tech-oss/jwt-go/.gitignore deleted file mode 100644 index c0e81a8d..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -.DS_Store -bin -.idea/ - - diff --git a/vendor/github.com/form3tech-oss/jwt-go/.travis.yml b/vendor/github.com/form3tech-oss/jwt-go/.travis.yml deleted file mode 100644 index 3c7fb7e1..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go - -script: - - go vet ./... - - go test -v ./... - -go: - - 1.12 - - 1.13 - - 1.14 - - 1.15 - - tip diff --git a/vendor/github.com/form3tech-oss/jwt-go/LICENSE b/vendor/github.com/form3tech-oss/jwt-go/LICENSE deleted file mode 100644 index df83a9c2..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/LICENSE +++ /dev/null @@ -1,8 +0,0 @@ -Copyright (c) 2012 Dave Grijalva - -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/github.com/form3tech-oss/jwt-go/MIGRATION_GUIDE.md b/vendor/github.com/form3tech-oss/jwt-go/MIGRATION_GUIDE.md deleted file mode 100644 index 7fc1f793..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/MIGRATION_GUIDE.md +++ /dev/null @@ -1,97 +0,0 @@ -## Migration Guide from v2 -> v3 - -Version 3 adds several new, frequently requested features. To do so, it introduces a few breaking changes. We've worked to keep these as minimal as possible. This guide explains the breaking changes and how you can quickly update your code. - -### `Token.Claims` is now an interface type - -The most requested feature from the 2.0 verison of this library was the ability to provide a custom type to the JSON parser for claims. This was implemented by introducing a new interface, `Claims`, to replace `map[string]interface{}`. We also included two concrete implementations of `Claims`: `MapClaims` and `StandardClaims`. - -`MapClaims` is an alias for `map[string]interface{}` with built in validation behavior. It is the default claims type when using `Parse`. The usage is unchanged except you must type cast the claims property. - -The old example for parsing a token looked like this.. - -```go - if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { - fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) - } -``` - -is now directly mapped to... - -```go - if token, err := jwt.Parse(tokenString, keyLookupFunc); err == nil { - claims := token.Claims.(jwt.MapClaims) - fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) - } -``` - -`StandardClaims` is designed to be embedded in your custom type. You can supply a custom claims type with the new `ParseWithClaims` function. Here's an example of using a custom claims type. - -```go - type MyCustomClaims struct { - User string - *StandardClaims - } - - if token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, keyLookupFunc); err == nil { - claims := token.Claims.(*MyCustomClaims) - fmt.Printf("Token for user %v expires %v", claims.User, claims.StandardClaims.ExpiresAt) - } -``` - -### `ParseFromRequest` has been moved - -To keep this library focused on the tokens without becoming overburdened with complex request processing logic, `ParseFromRequest` and its new companion `ParseFromRequestWithClaims` have been moved to a subpackage, `request`. The method signatues have also been augmented to receive a new argument: `Extractor`. - -`Extractors` do the work of picking the token string out of a request. The interface is simple and composable. - -This simple parsing example: - -```go - if token, err := jwt.ParseFromRequest(tokenString, req, keyLookupFunc); err == nil { - fmt.Printf("Token for user %v expires %v", token.Claims["user"], token.Claims["exp"]) - } -``` - -is directly mapped to: - -```go - if token, err := request.ParseFromRequest(req, request.OAuth2Extractor, keyLookupFunc); err == nil { - claims := token.Claims.(jwt.MapClaims) - fmt.Printf("Token for user %v expires %v", claims["user"], claims["exp"]) - } -``` - -There are several concrete `Extractor` types provided for your convenience: - -* `HeaderExtractor` will search a list of headers until one contains content. -* `ArgumentExtractor` will search a list of keys in request query and form arguments until one contains content. -* `MultiExtractor` will try a list of `Extractors` in order until one returns content. -* `AuthorizationHeaderExtractor` will look in the `Authorization` header for a `Bearer` token. -* `OAuth2Extractor` searches the places an OAuth2 token would be specified (per the spec): `Authorization` header and `access_token` argument -* `PostExtractionFilter` wraps an `Extractor`, allowing you to process the content before it's parsed. A simple example is stripping the `Bearer ` text from a header - - -### RSA signing methods no longer accept `[]byte` keys - -Due to a [critical vulnerability](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/), we've decided the convenience of accepting `[]byte` instead of `rsa.PublicKey` or `rsa.PrivateKey` isn't worth the risk of misuse. - -To replace this behavior, we've added two helper methods: `ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error)` and `ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error)`. These are just simple helpers for unpacking PEM encoded PKCS1 and PKCS8 keys. If your keys are encoded any other way, all you need to do is convert them to the `crypto/rsa` package's types. - -```go - func keyLookupFunc(*Token) (interface{}, error) { - // Don't forget to validate the alg is what you expect: - if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) - } - - // Look up key - key, err := lookupPublicKey(token.Header["kid"]) - if err != nil { - return nil, err - } - - // Unpack key from PEM encoded PKCS8 - return jwt.ParseRSAPublicKeyFromPEM(key) - } -``` diff --git a/vendor/github.com/form3tech-oss/jwt-go/README.md b/vendor/github.com/form3tech-oss/jwt-go/README.md deleted file mode 100644 index d7749077..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/README.md +++ /dev/null @@ -1,104 +0,0 @@ -# jwt-go - -[![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go) -[![GoDoc](https://godoc.org/github.com/dgrijalva/jwt-go?status.svg)](https://godoc.org/github.com/dgrijalva/jwt-go) - -A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) - -**NEW VERSION COMING:** There have been a lot of improvements suggested since the version 3.0.0 released in 2016. I'm working now on cutting two different releases: 3.2.0 will contain any non-breaking changes or enhancements. 4.0.0 will follow shortly which will include breaking changes. See the 4.0.0 milestone to get an idea of what's coming. If you have other ideas, or would like to participate in 4.0.0, now's the time. If you depend on this library and don't want to be interrupted, I recommend you use your dependency mangement tool to pin to version 3. - -**SECURITY NOTICE:** Some older versions of Go have a security issue in the cryotp/elliptic. Recommendation is to upgrade to at least 1.8.3. See issue #216 for more detail. - -**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided. - -## What the heck is a JWT? - -JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens. - -In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](http://tools.ietf.org/html/rfc4648) encoded. The last part is the signature, encoded the same way. - -The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used. - -The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [the RFC](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) for information about reserved keys and the proper way to add your own. - -## What's in the box? - -This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own. - -## Examples - -See [the project documentation](https://godoc.org/github.com/dgrijalva/jwt-go) for examples of usage: - -* [Simple example of parsing and validating a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac) -* [Simple example of building and signing a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac) -* [Directory of Examples](https://godoc.org/github.com/dgrijalva/jwt-go#pkg-examples) - -## Extensions - -This library publishes all the necessary components for adding your own signing methods. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod`. - -Here's an example of an extension that integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS): https://github.com/someone1/gcp-jwt-go - -## Compliance - -This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences: - -* In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key. - -## Project Status & Versioning - -This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason). - -This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases). - -While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v3`. It will do the right thing WRT semantic versioning. - -**BREAKING CHANGES:*** -* Version 3.0.0 includes _a lot_ of changes from the 2.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. - -## Usage Tips - -### Signing vs Encryption - -A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data: - -* The author of the token was in the possession of the signing secret -* The data has not been modified since it was signed - -It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library. - -### Choosing a Signing Method - -There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric. - -Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation. - -Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification. - -### Signing Methods and Key Types - -Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: - -* The [HMAC signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation -* The [RSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation -* The [ECDSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation - -### JWT and OAuth - -It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication. - -Without going too far down the rabbit hole, here's a description of the interaction of these technologies: - -* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth. -* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token. -* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL. - -### Troubleshooting - -This library uses descriptive error messages whenever possible. If you are not getting the expected result, have a look at the errors. The most common place people get stuck is providing the correct type of key to the parser. See the above section on signing methods and key types. - -## More - -Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go). - -The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation. diff --git a/vendor/github.com/form3tech-oss/jwt-go/VERSION_HISTORY.md b/vendor/github.com/form3tech-oss/jwt-go/VERSION_HISTORY.md deleted file mode 100644 index 63702983..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/VERSION_HISTORY.md +++ /dev/null @@ -1,118 +0,0 @@ -## `jwt-go` Version History - -#### 3.2.0 - -* Added method `ParseUnverified` to allow users to split up the tasks of parsing and validation -* HMAC signing method returns `ErrInvalidKeyType` instead of `ErrInvalidKey` where appropriate -* Added options to `request.ParseFromRequest`, which allows for an arbitrary list of modifiers to parsing behavior. Initial set include `WithClaims` and `WithParser`. Existing usage of this function will continue to work as before. -* Deprecated `ParseFromRequestWithClaims` to simplify API in the future. - -#### 3.1.0 - -* Improvements to `jwt` command line tool -* Added `SkipClaimsValidation` option to `Parser` -* Documentation updates - -#### 3.0.0 - -* **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code - * Dropped support for `[]byte` keys when using RSA signing methods. This convenience feature could contribute to security vulnerabilities involving mismatched key types with signing methods. - * `ParseFromRequest` has been moved to `request` subpackage and usage has changed - * The `Claims` property on `Token` is now type `Claims` instead of `map[string]interface{}`. The default value is type `MapClaims`, which is an alias to `map[string]interface{}`. This makes it possible to use a custom type when decoding claims. -* Other Additions and Changes - * Added `Claims` interface type to allow users to decode the claims into a custom type - * Added `ParseWithClaims`, which takes a third argument of type `Claims`. Use this function instead of `Parse` if you have a custom type you'd like to decode into. - * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage - * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims` - * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`. - * Added several new, more specific, validation errors to error type bitmask - * Moved examples from README to executable example files - * Signing method registry is now thread safe - * Added new property to `ValidationError`, which contains the raw error returned by calls made by parse/verify (such as those returned by keyfunc or json parser) - -#### 2.7.0 - -This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes. - -* Added new option `-show` to the `jwt` command that will just output the decoded token without verifying -* Error text for expired tokens includes how long it's been expired -* Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM` -* Documentation updates - -#### 2.6.0 - -* Exposed inner error within ValidationError -* Fixed validation errors when using UseJSONNumber flag -* Added several unit tests - -#### 2.5.0 - -* Added support for signing method none. You shouldn't use this. The API tries to make this clear. -* Updated/fixed some documentation -* Added more helpful error message when trying to parse tokens that begin with `BEARER ` - -#### 2.4.0 - -* Added new type, Parser, to allow for configuration of various parsing parameters - * You can now specify a list of valid signing methods. Anything outside this set will be rejected. - * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON -* Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go) -* Fixed some bugs with ECDSA parsing - -#### 2.3.0 - -* Added support for ECDSA signing methods -* Added support for RSA PSS signing methods (requires go v1.4) - -#### 2.2.0 - -* Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic. - -#### 2.1.0 - -Backwards compatible API change that was missed in 2.0.0. - -* The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte` - -#### 2.0.0 - -There were two major reasons for breaking backwards compatibility with this update. The first was a refactor required to expand the width of the RSA and HMAC-SHA signing implementations. There will likely be no required code changes to support this change. - -The second update, while unfortunately requiring a small change in integration, is required to open up this library to other signing methods. Not all keys used for all signing methods have a single standard on-disk representation. Requiring `[]byte` as the type for all keys proved too limiting. Additionally, this implementation allows for pre-parsed tokens to be reused, which might matter in an application that parses a high volume of tokens with a small set of keys. Backwards compatibilty has been maintained for passing `[]byte` to the RSA signing methods, but they will also accept `*rsa.PublicKey` and `*rsa.PrivateKey`. - -It is likely the only integration change required here will be to change `func(t *jwt.Token) ([]byte, error)` to `func(t *jwt.Token) (interface{}, error)` when calling `Parse`. - -* **Compatibility Breaking Changes** - * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct` - * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct` - * `KeyFunc` now returns `interface{}` instead of `[]byte` - * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key - * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key -* Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type. - * Added public package global `SigningMethodHS256` - * Added public package global `SigningMethodHS384` - * Added public package global `SigningMethodHS512` -* Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type. - * Added public package global `SigningMethodRS256` - * Added public package global `SigningMethodRS384` - * Added public package global `SigningMethodRS512` -* Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged. -* Refactored the RSA implementation to be easier to read -* Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` - -#### 1.0.2 - -* Fixed bug in parsing public keys from certificates -* Added more tests around the parsing of keys for RS256 -* Code refactoring in RS256 implementation. No functional changes - -#### 1.0.1 - -* Fixed panic if RS256 signing method was passed an invalid key - -#### 1.0.0 - -* First versioned release -* API stabilized -* Supports creating, signing, parsing, and validating JWT tokens -* Supports RS256 and HS256 signing methods \ No newline at end of file diff --git a/vendor/github.com/form3tech-oss/jwt-go/claims.go b/vendor/github.com/form3tech-oss/jwt-go/claims.go deleted file mode 100644 index 62489066..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/claims.go +++ /dev/null @@ -1,136 +0,0 @@ -package jwt - -import ( - "crypto/subtle" - "fmt" - "time" -) - -// For a type to be a Claims object, it must just have a Valid method that determines -// if the token is invalid for any supported reason -type Claims interface { - Valid() error -} - -// Structured version of Claims Section, as referenced at -// https://tools.ietf.org/html/rfc7519#section-4.1 -// See examples for how to use this with your own claim types -type StandardClaims struct { - Audience []string `json:"aud,omitempty"` - ExpiresAt int64 `json:"exp,omitempty"` - Id string `json:"jti,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - Issuer string `json:"iss,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Subject string `json:"sub,omitempty"` -} - -// Validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (c StandardClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - // The claims below are optional, by default, so if they are set to the - // default value in Go, let's not fail the verification for them. - if c.VerifyExpiresAt(now, false) == false { - delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) - vErr.Inner = fmt.Errorf("token is expired by %v", delta) - vErr.Errors |= ValidationErrorExpired - } - - if c.VerifyIssuedAt(now, false) == false { - vErr.Inner = fmt.Errorf("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if c.VerifyNotBefore(now, false) == false { - vErr.Inner = fmt.Errorf("token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} - -// Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { - return verifyAud(c.Audience, cmp, req) -} - -// Compares the exp claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { - return verifyExp(c.ExpiresAt, cmp, req) -} - -// Compares the iat claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { - return verifyIat(c.IssuedAt, cmp, req) -} - -// Compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { - return verifyIss(c.Issuer, cmp, req) -} - -// Compares the nbf claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { - return verifyNbf(c.NotBefore, cmp, req) -} - -// ----- helpers - -func verifyAud(aud []string, cmp string, required bool) bool { - if len(aud) == 0 { - return !required - } - - for _, a := range aud { - if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { - return true - } - } - return false -} - -func verifyExp(exp int64, now int64, required bool) bool { - if exp == 0 { - return !required - } - return now <= exp -} - -func verifyIat(iat int64, now int64, required bool) bool { - if iat == 0 { - return !required - } - return now >= iat -} - -func verifyIss(iss string, cmp string, required bool) bool { - if iss == "" { - return !required - } - if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { - return true - } else { - return false - } -} - -func verifyNbf(nbf int64, now int64, required bool) bool { - if nbf == 0 { - return !required - } - return now >= nbf -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/doc.go b/vendor/github.com/form3tech-oss/jwt-go/doc.go deleted file mode 100644 index a86dc1a3..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html -// -// See README.md for more info. -package jwt diff --git a/vendor/github.com/form3tech-oss/jwt-go/ecdsa.go b/vendor/github.com/form3tech-oss/jwt-go/ecdsa.go deleted file mode 100644 index f9773812..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/ecdsa.go +++ /dev/null @@ -1,148 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rand" - "errors" - "math/big" -) - -var ( - // Sadly this is missing from crypto/ecdsa compared to crypto/rsa - ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") -) - -// Implements the ECDSA family of signing methods signing methods -// Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification -type SigningMethodECDSA struct { - Name string - Hash crypto.Hash - KeySize int - CurveBits int -} - -// Specific instances for EC256 and company -var ( - SigningMethodES256 *SigningMethodECDSA - SigningMethodES384 *SigningMethodECDSA - SigningMethodES512 *SigningMethodECDSA -) - -func init() { - // ES256 - SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} - RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { - return SigningMethodES256 - }) - - // ES384 - SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} - RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { - return SigningMethodES384 - }) - - // ES512 - SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} - RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { - return SigningMethodES512 - }) -} - -func (m *SigningMethodECDSA) Alg() string { - return m.Name -} - -// Implements the Verify method from SigningMethod -// For this verify method, key must be an ecdsa.PublicKey struct -func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - // Get the key - var ecdsaKey *ecdsa.PublicKey - switch k := key.(type) { - case *ecdsa.PublicKey: - ecdsaKey = k - default: - return ErrInvalidKeyType - } - - if len(sig) != 2*m.KeySize { - return ErrECDSAVerification - } - - r := big.NewInt(0).SetBytes(sig[:m.KeySize]) - s := big.NewInt(0).SetBytes(sig[m.KeySize:]) - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Verify the signature - if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true { - return nil - } else { - return ErrECDSAVerification - } -} - -// Implements the Sign method from SigningMethod -// For this signing method, key must be an ecdsa.PrivateKey struct -func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { - // Get the key - var ecdsaKey *ecdsa.PrivateKey - switch k := key.(type) { - case *ecdsa.PrivateKey: - ecdsaKey = k - default: - return "", ErrInvalidKeyType - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return r, s - if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { - curveBits := ecdsaKey.Curve.Params().BitSize - - if m.CurveBits != curveBits { - return "", ErrInvalidKey - } - - keyBytes := curveBits / 8 - if curveBits%8 > 0 { - keyBytes += 1 - } - - // We serialize the outpus (r and s) into big-endian byte arrays and pad - // them with zeros on the left to make sure the sizes work out. Both arrays - // must be keyBytes long, and the output must be 2*keyBytes long. - rBytes := r.Bytes() - rBytesPadded := make([]byte, keyBytes) - copy(rBytesPadded[keyBytes-len(rBytes):], rBytes) - - sBytes := s.Bytes() - sBytesPadded := make([]byte, keyBytes) - copy(sBytesPadded[keyBytes-len(sBytes):], sBytes) - - out := append(rBytesPadded, sBytesPadded...) - - return EncodeSegment(out), nil - } else { - return "", err - } -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/ecdsa_utils.go b/vendor/github.com/form3tech-oss/jwt-go/ecdsa_utils.go deleted file mode 100644 index db9f4be7..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/ecdsa_utils.go +++ /dev/null @@ -1,69 +0,0 @@ -package jwt - -import ( - "crypto/ecdsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -var ( - ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") - ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") -) - -// Parse PEM encoded Elliptic Curve Private Key Structure -func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { - return nil, err - } - } - - var pkey *ecdsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { - return nil, ErrNotECPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 public key -func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *ecdsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { - return nil, ErrNotECPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/errors.go b/vendor/github.com/form3tech-oss/jwt-go/errors.go deleted file mode 100644 index 1c93024a..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/errors.go +++ /dev/null @@ -1,59 +0,0 @@ -package jwt - -import ( - "errors" -) - -// Error constants -var ( - ErrInvalidKey = errors.New("key is invalid") - ErrInvalidKeyType = errors.New("key is of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") -) - -// The errors that might occur when parsing and validating a token -const ( - ValidationErrorMalformed uint32 = 1 << iota // Token is malformed - ValidationErrorUnverifiable // Token could not be verified because of signing problems - ValidationErrorSignatureInvalid // Signature validation failed - - // Standard Claim validation errors - ValidationErrorAudience // AUD validation failed - ValidationErrorExpired // EXP validation failed - ValidationErrorIssuedAt // IAT validation failed - ValidationErrorIssuer // ISS validation failed - ValidationErrorNotValidYet // NBF validation failed - ValidationErrorId // JTI validation failed - ValidationErrorClaimsInvalid // Generic claims validation error -) - -// Helper for constructing a ValidationError with a string error message -func NewValidationError(errorText string, errorFlags uint32) *ValidationError { - return &ValidationError{ - text: errorText, - Errors: errorFlags, - } -} - -// The error from Parse if token is not valid -type ValidationError struct { - Inner error // stores the error returned by external dependencies, i.e.: KeyFunc - Errors uint32 // bitfield. see ValidationError... constants - text string // errors that do not have a valid error just have text -} - -// Validation error is an error type -func (e ValidationError) Error() string { - if e.Inner != nil { - return e.Inner.Error() - } else if e.text != "" { - return e.text - } else { - return "token is invalid" - } -} - -// No errors -func (e *ValidationError) valid() bool { - return e.Errors == 0 -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/hmac.go b/vendor/github.com/form3tech-oss/jwt-go/hmac.go deleted file mode 100644 index addbe5d4..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/hmac.go +++ /dev/null @@ -1,95 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/hmac" - "errors" -) - -// Implements the HMAC-SHA family of signing methods signing methods -// Expects key type of []byte for both signing and validation -type SigningMethodHMAC struct { - Name string - Hash crypto.Hash -} - -// Specific instances for HS256 and company -var ( - SigningMethodHS256 *SigningMethodHMAC - SigningMethodHS384 *SigningMethodHMAC - SigningMethodHS512 *SigningMethodHMAC - ErrSignatureInvalid = errors.New("signature is invalid") -) - -func init() { - // HS256 - SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} - RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { - return SigningMethodHS256 - }) - - // HS384 - SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} - RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { - return SigningMethodHS384 - }) - - // HS512 - SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} - RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { - return SigningMethodHS512 - }) -} - -func (m *SigningMethodHMAC) Alg() string { - return m.Name -} - -// Verify the signature of HSXXX tokens. Returns nil if the signature is valid. -func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { - // Verify the key is the right type - keyBytes, ok := key.([]byte) - if !ok { - return ErrInvalidKeyType - } - - // Decode signature, for comparison - sig, err := DecodeSegment(signature) - if err != nil { - return err - } - - // Can we use the specified hashing method? - if !m.Hash.Available() { - return ErrHashUnavailable - } - - // This signing method is symmetric, so we validate the signature - // by reproducing the signature from the signing string and key, then - // comparing that against the provided signature. - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - if !hmac.Equal(sig, hasher.Sum(nil)) { - return ErrSignatureInvalid - } - - // No validation errors. Signature is good. - return nil -} - -// Implements the Sign method from SigningMethod for this signing method. -// Key must be []byte -func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { - if keyBytes, ok := key.([]byte); ok { - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - - return EncodeSegment(hasher.Sum(nil)), nil - } - - return "", ErrInvalidKeyType -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/map_claims.go b/vendor/github.com/form3tech-oss/jwt-go/map_claims.go deleted file mode 100644 index 90ab6bea..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/map_claims.go +++ /dev/null @@ -1,102 +0,0 @@ -package jwt - -import ( - "encoding/json" - "errors" - // "fmt" -) - -// Claims type that uses the map[string]interface{} for JSON decoding -// This is the default claims type if you don't supply one -type MapClaims map[string]interface{} - -// Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyAudience(cmp string, req bool) bool { - aud, ok := m["aud"].([]string) - if !ok { - strAud, ok := m["aud"].(string) - if !ok { - return false - } - aud = append(aud, strAud) - } - - return verifyAud(aud, cmp, req) -} - -// Compares the exp claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { - switch exp := m["exp"].(type) { - case float64: - return verifyExp(int64(exp), cmp, req) - case json.Number: - v, _ := exp.Int64() - return verifyExp(v, cmp, req) - } - return req == false -} - -// Compares the iat claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { - switch iat := m["iat"].(type) { - case float64: - return verifyIat(int64(iat), cmp, req) - case json.Number: - v, _ := iat.Int64() - return verifyIat(v, cmp, req) - } - return req == false -} - -// Compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { - iss, _ := m["iss"].(string) - return verifyIss(iss, cmp, req) -} - -// Compares the nbf claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { - switch nbf := m["nbf"].(type) { - case float64: - return verifyNbf(int64(nbf), cmp, req) - case json.Number: - v, _ := nbf.Int64() - return verifyNbf(v, cmp, req) - } - return req == false -} - -// Validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (m MapClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - if m.VerifyExpiresAt(now, false) == false { - vErr.Inner = errors.New("Token is expired") - vErr.Errors |= ValidationErrorExpired - } - - if m.VerifyIssuedAt(now, false) == false { - vErr.Inner = errors.New("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if m.VerifyNotBefore(now, false) == false { - vErr.Inner = errors.New("Token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/none.go b/vendor/github.com/form3tech-oss/jwt-go/none.go deleted file mode 100644 index f04d189d..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/none.go +++ /dev/null @@ -1,52 +0,0 @@ -package jwt - -// Implements the none signing method. This is required by the spec -// but you probably should never use it. -var SigningMethodNone *signingMethodNone - -const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" - -var NoneSignatureTypeDisallowedError error - -type signingMethodNone struct{} -type unsafeNoneMagicConstant string - -func init() { - SigningMethodNone = &signingMethodNone{} - NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) - - RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { - return SigningMethodNone - }) -} - -func (m *signingMethodNone) Alg() string { - return "none" -} - -// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { - // Key must be UnsafeAllowNoneSignatureType to prevent accidentally - // accepting 'none' signing method - if _, ok := key.(unsafeNoneMagicConstant); !ok { - return NoneSignatureTypeDisallowedError - } - // If signing method is none, signature must be an empty string - if signature != "" { - return NewValidationError( - "'none' signing method with non-empty signature", - ValidationErrorSignatureInvalid, - ) - } - - // Accept 'none' signing method. - return nil -} - -// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { - if _, ok := key.(unsafeNoneMagicConstant); ok { - return "", nil - } - return "", NoneSignatureTypeDisallowedError -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/parser.go b/vendor/github.com/form3tech-oss/jwt-go/parser.go deleted file mode 100644 index d6901d9a..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/parser.go +++ /dev/null @@ -1,148 +0,0 @@ -package jwt - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" -) - -type Parser struct { - ValidMethods []string // If populated, only these methods will be considered valid - UseJSONNumber bool // Use JSON Number format in JSON decoder - SkipClaimsValidation bool // Skip claims validation during token parsing -} - -// Parse, validate, and return a token. -// keyFunc will receive the parsed token and should return the key for validating. -// If everything is kosher, err will be nil -func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) -} - -func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - token, parts, err := p.ParseUnverified(tokenString, claims) - if err != nil { - return token, err - } - - // Verify signing method is in the required set - if p.ValidMethods != nil { - var signingMethodValid = false - var alg = token.Method.Alg() - for _, m := range p.ValidMethods { - if m == alg { - signingMethodValid = true - break - } - } - if !signingMethodValid { - // signing method is not in the listed set - return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) - } - } - - // Lookup key - var key interface{} - if keyFunc == nil { - // keyFunc was not provided. short circuiting validation - return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) - } - if key, err = keyFunc(token); err != nil { - // keyFunc returned an error - if ve, ok := err.(*ValidationError); ok { - return token, ve - } - return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} - } - - vErr := &ValidationError{} - - // Validate Claims - if !p.SkipClaimsValidation { - if err := token.Claims.Valid(); err != nil { - - // If the Claims Valid returned an error, check if it is a validation error, - // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set - if e, ok := err.(*ValidationError); !ok { - vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} - } else { - vErr = e - } - } - } - - // Perform validation - token.Signature = parts[2] - if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { - vErr.Inner = err - vErr.Errors |= ValidationErrorSignatureInvalid - } - - if vErr.valid() { - token.Valid = true - return token, nil - } - - return token, vErr -} - -// WARNING: Don't use this method unless you know what you're doing -// -// This method parses the token but doesn't validate the signature. It's only -// ever useful in cases where you know the signature is valid (because it has -// been checked previously in the stack) and you want to extract values from -// it. -func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { - parts = strings.Split(tokenString, ".") - if len(parts) != 3 { - return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) - } - - token = &Token{Raw: tokenString} - - // parse Header - var headerBytes []byte - if headerBytes, err = DecodeSegment(parts[0]); err != nil { - if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { - return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) - } - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // parse Claims - var claimBytes []byte - token.Claims = claims - - if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - if p.UseJSONNumber { - dec.UseNumber() - } - // JSON Decode. Special case for map type to avoid weird pointer behavior - if c, ok := token.Claims.(MapClaims); ok { - err = dec.Decode(&c) - } else { - err = dec.Decode(&claims) - } - // Handle decode error - if err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // Lookup signature method - if method, ok := token.Header["alg"].(string); ok { - if token.Method = GetSigningMethod(method); token.Method == nil { - return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) - } - } else { - return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) - } - - return token, parts, nil -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/rsa.go b/vendor/github.com/form3tech-oss/jwt-go/rsa.go deleted file mode 100644 index e4caf1ca..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/rsa.go +++ /dev/null @@ -1,101 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" -) - -// Implements the RSA family of signing methods signing methods -// Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation -type SigningMethodRSA struct { - Name string - Hash crypto.Hash -} - -// Specific instances for RS256 and company -var ( - SigningMethodRS256 *SigningMethodRSA - SigningMethodRS384 *SigningMethodRSA - SigningMethodRS512 *SigningMethodRSA -) - -func init() { - // RS256 - SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} - RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { - return SigningMethodRS256 - }) - - // RS384 - SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} - RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { - return SigningMethodRS384 - }) - - // RS512 - SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} - RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { - return SigningMethodRS512 - }) -} - -func (m *SigningMethodRSA) Alg() string { - return m.Name -} - -// Implements the Verify method from SigningMethod -// For this signing method, must be an *rsa.PublicKey structure. -func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - var rsaKey *rsa.PublicKey - var ok bool - - if rsaKey, ok = key.(*rsa.PublicKey); !ok { - return ErrInvalidKeyType - } - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Verify the signature - return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) -} - -// Implements the Sign method from SigningMethod -// For this signing method, must be an *rsa.PrivateKey structure. -func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { - var rsaKey *rsa.PrivateKey - var ok bool - - // Validate type of key - if rsaKey, ok = key.(*rsa.PrivateKey); !ok { - return "", ErrInvalidKey - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return the encoded bytes - if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { - return EncodeSegment(sigBytes), nil - } else { - return "", err - } -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/rsa_pss.go b/vendor/github.com/form3tech-oss/jwt-go/rsa_pss.go deleted file mode 100644 index c0147086..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/rsa_pss.go +++ /dev/null @@ -1,142 +0,0 @@ -// +build go1.4 - -package jwt - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" -) - -// Implements the RSAPSS family of signing methods signing methods -type SigningMethodRSAPSS struct { - *SigningMethodRSA - Options *rsa.PSSOptions - // VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS. - // Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow - // https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously. - // See https://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details. - VerifyOptions *rsa.PSSOptions -} - -// Specific instances for RS/PS and company. -var ( - SigningMethodPS256 *SigningMethodRSAPSS - SigningMethodPS384 *SigningMethodRSAPSS - SigningMethodPS512 *SigningMethodRSAPSS -) - -func init() { - // PS256 - SigningMethodPS256 = &SigningMethodRSAPSS{ - SigningMethodRSA: &SigningMethodRSA{ - Name: "PS256", - Hash: crypto.SHA256, - }, - Options: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthEqualsHash, - }, - VerifyOptions: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - }, - } - RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { - return SigningMethodPS256 - }) - - // PS384 - SigningMethodPS384 = &SigningMethodRSAPSS{ - SigningMethodRSA: &SigningMethodRSA{ - Name: "PS384", - Hash: crypto.SHA384, - }, - Options: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthEqualsHash, - }, - VerifyOptions: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - }, - } - RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { - return SigningMethodPS384 - }) - - // PS512 - SigningMethodPS512 = &SigningMethodRSAPSS{ - SigningMethodRSA: &SigningMethodRSA{ - Name: "PS512", - Hash: crypto.SHA512, - }, - Options: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthEqualsHash, - }, - VerifyOptions: &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - }, - } - RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { - return SigningMethodPS512 - }) -} - -// Implements the Verify method from SigningMethod -// For this verify method, key must be an rsa.PublicKey struct -func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - var rsaKey *rsa.PublicKey - switch k := key.(type) { - case *rsa.PublicKey: - rsaKey = k - default: - return ErrInvalidKey - } - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - opts := m.Options - if m.VerifyOptions != nil { - opts = m.VerifyOptions - } - - return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts) -} - -// Implements the Sign method from SigningMethod -// For this signing method, key must be an rsa.PrivateKey struct -func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { - var rsaKey *rsa.PrivateKey - - switch k := key.(type) { - case *rsa.PrivateKey: - rsaKey = k - default: - return "", ErrInvalidKeyType - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return the encoded bytes - if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { - return EncodeSegment(sigBytes), nil - } else { - return "", err - } -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/rsa_utils.go b/vendor/github.com/form3tech-oss/jwt-go/rsa_utils.go deleted file mode 100644 index 14c78c29..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/rsa_utils.go +++ /dev/null @@ -1,101 +0,0 @@ -package jwt - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -var ( - ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be a PEM encoded PKCS1 or PKCS8 key") - ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") -) - -// Parse PEM encoded PKCS1 or PKCS8 private key -func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 private key protected with password -func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - - var blockDecrypted []byte - if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { - return nil, err - } - - if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 public key -func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *rsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { - return nil, ErrNotRSAPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/signing_method.go b/vendor/github.com/form3tech-oss/jwt-go/signing_method.go deleted file mode 100644 index ed1f212b..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/signing_method.go +++ /dev/null @@ -1,35 +0,0 @@ -package jwt - -import ( - "sync" -) - -var signingMethods = map[string]func() SigningMethod{} -var signingMethodLock = new(sync.RWMutex) - -// Implement SigningMethod to add new methods for signing or verifying tokens. -type SigningMethod interface { - Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid - Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error - Alg() string // returns the alg identifier for this method (example: 'HS256') -} - -// Register the "alg" name and a factory function for signing method. -// This is typically done during init() in the method's implementation -func RegisterSigningMethod(alg string, f func() SigningMethod) { - signingMethodLock.Lock() - defer signingMethodLock.Unlock() - - signingMethods[alg] = f -} - -// Get a signing method from an "alg" string -func GetSigningMethod(alg string) (method SigningMethod) { - signingMethodLock.RLock() - defer signingMethodLock.RUnlock() - - if methodF, ok := signingMethods[alg]; ok { - method = methodF() - } - return -} diff --git a/vendor/github.com/form3tech-oss/jwt-go/token.go b/vendor/github.com/form3tech-oss/jwt-go/token.go deleted file mode 100644 index d637e086..00000000 --- a/vendor/github.com/form3tech-oss/jwt-go/token.go +++ /dev/null @@ -1,108 +0,0 @@ -package jwt - -import ( - "encoding/base64" - "encoding/json" - "strings" - "time" -) - -// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). -// You can override it to use another time value. This is useful for testing or if your -// server uses a different time zone than your tokens. -var TimeFunc = time.Now - -// Parse methods use this callback function to supply -// the key for verification. The function receives the parsed, -// but unverified Token. This allows you to use properties in the -// Header of the token (such as `kid`) to identify which key to use. -type Keyfunc func(*Token) (interface{}, error) - -// A JWT Token. Different fields will be used depending on whether you're -// creating or parsing/verifying a token. -type Token struct { - Raw string // The raw token. Populated when you Parse a token - Method SigningMethod // The signing method used or to be used - Header map[string]interface{} // The first segment of the token - Claims Claims // The second segment of the token - Signature string // The third segment of the token. Populated when you Parse a token - Valid bool // Is the token valid? Populated when you Parse/Verify a token -} - -// Create a new Token. Takes a signing method -func New(method SigningMethod) *Token { - return NewWithClaims(method, MapClaims{}) -} - -func NewWithClaims(method SigningMethod, claims Claims) *Token { - return &Token{ - Header: map[string]interface{}{ - "typ": "JWT", - "alg": method.Alg(), - }, - Claims: claims, - Method: method, - } -} - -// Get the complete, signed token -func (t *Token) SignedString(key interface{}) (string, error) { - var sig, sstr string - var err error - if sstr, err = t.SigningString(); err != nil { - return "", err - } - if sig, err = t.Method.Sign(sstr, key); err != nil { - return "", err - } - return strings.Join([]string{sstr, sig}, "."), nil -} - -// Generate the signing string. This is the -// most expensive part of the whole deal. Unless you -// need this for something special, just go straight for -// the SignedString. -func (t *Token) SigningString() (string, error) { - var err error - parts := make([]string, 2) - for i, _ := range parts { - var jsonValue []byte - if i == 0 { - if jsonValue, err = json.Marshal(t.Header); err != nil { - return "", err - } - } else { - if jsonValue, err = json.Marshal(t.Claims); err != nil { - return "", err - } - } - - parts[i] = EncodeSegment(jsonValue) - } - return strings.Join(parts, "."), nil -} - -// Parse, validate, and return a token. -// keyFunc will receive the parsed token and should return the key for validating. -// If everything is kosher, err will be nil -func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return new(Parser).Parse(tokenString, keyFunc) -} - -func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) -} - -// Encode JWT specific base64url encoding with padding stripped -func EncodeSegment(seg []byte) string { - return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") -} - -// Decode JWT specific base64url encoding with padding stripped -func DecodeSegment(seg string) ([]byte, error) { - if l := len(seg) % 4; l > 0 { - seg += strings.Repeat("=", 4-l) - } - - return base64.URLEncoding.DecodeString(seg) -} diff --git a/vendor/github.com/godbus/dbus/v5/CONTRIBUTING.md b/vendor/github.com/godbus/dbus/v5/CONTRIBUTING.md deleted file mode 100644 index c88f9b2b..00000000 --- a/vendor/github.com/godbus/dbus/v5/CONTRIBUTING.md +++ /dev/null @@ -1,50 +0,0 @@ -# How to Contribute - -## Getting Started - -- Fork the repository on GitHub -- Read the [README](README.markdown) for build and test instructions -- Play with the project, submit bugs, submit patches! - -## Contribution Flow - -This is a rough outline of what a contributor's workflow looks like: - -- Create a topic branch from where you want to base your work (usually master). -- Make commits of logical units. -- Make sure your commit messages are in the proper format (see below). -- Push your changes to a topic branch in your fork of the repository. -- Make sure the tests pass, and add any new tests as appropriate. -- Submit a pull request to the original repository. - -Thanks for your contributions! - -### Format of the Commit Message - -We follow a rough convention for commit messages that is designed to answer two -questions: what changed and why. The subject line should feature the what and -the body of the commit should describe the why. - -``` -scripts: add the test-cluster command - -this uses tmux to setup a test cluster that you can easily kill and -start for debugging. - -Fixes #38 -``` - -The format can be described more formally as follows: - -``` -: - - - -